query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
TokenFromHeader returns the token from the request
func TokenFromHeader(r *http.Request) (string, error) { authHeader := r.Header.Get("Authorization") if authHeader == "" { return "", nil } authSplit := strings.Split(authHeader, " ") if len(authSplit) != 2 || strings.ToLower(authSplit[0]) != "bearer" { return "", errors.New("Authorization header format should be Bearer {token}") } return authSplit[1], nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetTokenFromHeader(c *gin.Context) (*authentication.AuthenticationToken, error) {\n\tauthorizationHeader := strings.SplitN(c.Request.Header.Get(\"Authorization\"), \" \", 2)\n\tif len(authorizationHeader) != 2 || strings.ToLower(authorizationHeader[0]) != \"bearer\" {\n\t\treturn nil, errors.New(\"No authorization header\")\n\t}\n\ttoken := &authentication.AuthenticationToken{}\n\tif err := token.Decode(authorizationHeader[1]); err != nil {\n\t\treturn nil, err\n\t}\n\treturn token, nil\n}", "func TokenFromAuthHeader(r *http.Request) (string, error) {\n\t// Look for an Authorization header\n\tif ah := r.Header.Get(\"Authorization\"); ah != \"\" {\n\t\t// Should be a bearer token\n\t\tif len(ah) > 6 && strings.ToUpper(ah[0:6]) == \"BEARER\" {\n\t\t\treturn ah[7:], nil\n\t\t}\n\t}\n\treturn \"\", errors.New(\"No token in the HTTP request\")\n}", "func GetTokenFromHeader(ctx context.Context) (string, error) {\n\tauthHeader := rpc.GetIncomingHeader(ctx, authenticationHeader)\n\tif authHeader == \"\" {\n\t\treturn \"\", errors.New(\"no auth header provided\")\n\t}\n\treturn getTokenFromString(authHeader)\n}", "func TokenFromRequest(r *http.Request) string {\n\tauth := r.Header.Get(\"Authorization\")\n\tmatches := bearerPattern.FindStringSubmatch(auth)\n\tif len(matches) == 0 {\n\t\treturn \"\"\n\t}\n\treturn matches[1]\n}", "func csrfTokenFromHeader(header string) csrfTokenExtractor {\n\treturn func(c echo.Context) (string, error) {\n\t\treturn c.Request().Header.Get(header), nil\n\t}\n}", "func getTokenHeader(c *gin.Context) (string, error) {\n\ttokenString := c.GetHeader(\"Authorization\")\n\tif strings.Index(tokenString, \"Bearer \") != 0 {\n\t\treturn \"\", errors.Unauthorized\n\t}\n\treturn tokenString[7:], nil\n}", "func extractToken(header http.Header) (string, error) {\n\tconst authHeaderName = \"Authorization\"\n\tauthHeader := header.Get(authHeaderName)\n\tif authHeader == \"\" {\n\t\treturn \"\", ErrNoAuthHeader\n\t}\n\ttokenStr := strings.Replace(authHeader, \"Bearer\", \"\", 1)\n\ttokenStr = strings.Replace(tokenStr, \"bearer\", \"\", 1)\n\treturn strings.TrimSpace(tokenStr), nil\n}", "func getTokenFromReq(r *http.Request) string {\n\theader := r.Header.Get(\"Authorization\")\n\ttoken := strings.Split(header, \" \")\n\tif len(token) > 1 {\n\t\treturn token[1]\n\t}\n\treturn \"\"\n}", "func FromHeader(r *http.Request) (*jwt.JSONWebToken, error) {\n\n\traw, err := fromHeader(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jwt.ParseSigned(string(raw))\n}", "func getAuthTokenFromHeader(ctx echo.Context) (string, error) {\n\theaderContent := ctx.Request().Header.Get(echo.HeaderAuthorization)\n\theaderContent = strings.TrimSpace(headerContent)\n\tprefix := \"Bearer:\"\n\tif strings.HasPrefix(headerContent, prefix) {\n\t\trunes := []rune(headerContent)\n\t\treturn strings.TrimSpace(string(runes[len(prefix):])), nil\n\t}\n\treturn \"\", fmt.Errorf(\"auth header not found\")\n}", "func GetJwtFromHeader(c *gin.Context) {\n\tauthHeader := c.Request.Header.Get(\"Authorization\")\n\tif authHeader == \"\" {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"success\": false,\n\t\t\t\"message\": \"请求头中auth为空\",\n\t\t})\n\t\tc.Abort()\n\t\treturn\n\t}\n\t// 按空格分割\n\tparts := strings.SplitN(authHeader, \" \", 2)\n\tif !(len(parts) == 2 && parts[0] == \"Bearer\") {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"success\": false,\n\t\t\t\"message\": \"请求头中auth格式有误\",\n\t\t})\n\t\tc.Abort()\n\t\treturn\n\t}\n\tmc, err := ParseToken(parts[1])\n\tif !mc {\n\t\tlog.Println(err)\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"success\": false,\n\t\t\t\"message\": \"无效的Token\",\n\t\t})\n\t\tc.Abort()\n\t\treturn\n\t}\n\t// 将当前请求的username信息保存到请求的上下文c上\n\t//c.Set(\"username\", mc.Username)\n\tc.Next() // 后续的处理函数可以用过c.Get(\"username\")来获取当前请求的用户信息\n}", "func getTokenFromAuthHeader(header string) string {\n\tretval := \"\"\n\n\t//\tIf we don't have at least x number characters,\n\t//\tit must not include the prefix text 'Bearer '\n\tif len(header) < len(\"Bearer \") {\n\t\treturn \"\"\n\t}\n\n\t//\tIf the first part of the string isn't 'Bearer ' then it's not a bearer token...\n\tif strings.EqualFold(header[:len(\"Bearer \")], \"Bearer \") != true {\n\t\treturn \"\"\n\t}\n\n\t//\tGet the token and decode it\n\tencodedToken := header[len(\"Bearer \"):]\n\ttokenBytes, err := base64.StdEncoding.DecodeString(encodedToken)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\t//\tChange the type to string\n\tretval = string(tokenBytes)\n\n\treturn retval\n}", "func FromAuthHeader(r *http.Request) (string, error) {\n\tauthHeader := r.Header.Get(\"Authorization\")\n\tif authHeader == \"\" {\n\t\treturn \"\", nil // No error, just no token\n\t}\n\n\t// TODO: Make this a bit more robust, parsing-wise\n\tauthHeaderParts := strings.Split(authHeader, \" \")\n\tif len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != \"bearer\" {\n\t\treturn \"\", errors.New(\"Authorization header format must be Bearer {token}\")\n\t}\n\n\treturn authHeaderParts[1], nil\n}", "func FromHeader(r *http.Request) (string, error) {\n\tauth := r.Header.Get(HeaderAuthorization)\n\tif auth == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tauthHeaderParts := strings.Split(auth, \" \")\n\tif len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != Bearer {\n\t\treturn \"\", ErrorAuthHeaderFormat\n\t}\n\n\treturn authHeaderParts[1], nil\n}", "func GetJwtTokenFromAuthHeader(authorizationHeader string) (token *SignedToken, err error) {\n\tconst PREFIX = \"Bearer \"\n\n\tif !strings.HasPrefix(authorizationHeader, PREFIX) {\n\t\terr = errors.New(\"Invalid token format\")\n\t\treturn\n\t}\n\n\ttoken = &SignedToken{\n\t\tToken: strings.TrimPrefix(authorizationHeader, PREFIX),\n\t}\n\n\treturn\n}", "func FromAuthHeader(r *http.Request) (string, error) {\n\tauthHeader := r.Header.Get(\"Authorization\")\n\tif authHeader == \"\" {\n\t\treturn \"\", nil // No error, just no token\n\t}\n\n\t// TODO: Make this a bit more robust, parsing-wise\n\tauthHeaderParts := strings.Fields(authHeader)\n\tif len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != \"bearer\" {\n\t\treturn \"\", errors.New(\"Authorization header format must be Bearer {token}\")\n\t}\n\n\treturn authHeaderParts[1], nil\n}", "func ExtracToken(request * http.Request) (string) {\n keys := request.URL.Query()\n token := keys.Get(\"token\")\n \n if token != \"\" {\n\t return token\n }\n\n bearToken := request.Header.Get(\"Authorization\")\n //Authorization the token\n\n strArr := strings.Split(bearToken,\" \")\n if len(strArr) == 2 {\n\t return strArr[1]\n }\n return \"\"\n}", "func GetTokenFromRequest(r *http.Request) (string, error) {\n\t// Token might come either as a Cookie or as a Header\n\t// if not set in cookie, check if it is set on Header.\n\ttokenCookie, err := r.Cookie(\"token\")\n\tif err != nil {\n\t\treturn \"\", ErrNoAuthToken\n\t}\n\tcurrentTime := time.Now()\n\tif tokenCookie.Expires.After(currentTime) {\n\t\treturn \"\", errTokenExpired\n\t}\n\treturn strings.TrimSpace(tokenCookie.Value), nil\n}", "func getToken(r *http.Request) string {\n\treturn r.Header.Get(\"Authorization\")\n}", "func (c *Cache) requestToken(req *http.Request) (string, error) {\n\tauthorization := req.Header.Get(\"Authorization\")\n\tif authorization == \"\" {\n\t\treturn \"\", failure.New(\"request contains no authorization header\")\n\t}\n\tfields := strings.Fields(authorization)\n\tif len(fields) != 2 || fields[0] != \"Bearer\" {\n\t\treturn \"\", failure.New(\"invalid authorization header: %q\", authorization)\n\t}\n\treturn fields[1], nil\n}", "func extractToken(r *http.Request) (string, error) {\n\treqToken := r.Header.Get(\"Authorization\")\n\tsplitToken := strings.Split(reqToken, \"Bearer \")\n\n\tif len(splitToken) < 2 {\n\t\treturn \"\", errors.New(\"No token\")\n\t}\n\n\treturn splitToken[1], nil\n}", "func token(r *http.Request) (token string) {\n\ttoken = r.Header.Get(\"X-Access-Token\")\n\tif len(token) > 0 {\n\t\treturn\n\t}\n\n\ttoken = r.FormValue(\"token\")\n\tif len(token) > 0 {\n\t\treturn\n\t}\n\n\ttoken = r.FormValue(\"access_token\")\n\tif len(token) > 0 {\n\t\treturn\n\t}\n\n\treturn \"\"\n}", "func getTokenInRequest(req *http.Request, name string) (string, bool, error) {\n\tbearer := true\n\t// step: check for a token in the authorization header\n\ttoken, err := getTokenInBearer(req)\n\tif err != nil {\n\t\tif err != ErrSessionNotFound {\n\t\t\treturn \"\", false, err\n\t\t}\n\t\tif token, err = getTokenInCookie(req, name); err != nil {\n\t\t\treturn token, false, err\n\t\t}\n\t\tbearer = false\n\t}\n\n\treturn token, bearer, nil\n}", "func GetBearerTokenFromReq(ctx types.Context, req *http.Request) string {\n\tm := rxBearer.FindStringSubmatch(\n\t\treq.Header.Get(types.AuthorizationHeader))\n\tif len(m) == 0 {\n\t\treturn \"\"\n\t}\n\treturn m[1]\n}", "func GetToken(r *http.Request) (string, error) {\n\theader := r.Header.Get(\"Authorization\")\n\tif len(header) == 0 {\n\t\treturn \"\", ErrNoAuthHeader\n\t}\n\n\theaderStr := strings.TrimSpace(header)\n\tif !strings.HasPrefix(header, \"Bearer\") {\n\t\treturn \"\", ErrInvalidAuthHeader\n\t}\n\n\treturn strings.TrimSpace(strings.TrimPrefix(headerStr, \"Bearer\")), nil\n}", "func GetJWTFromGinHeader(c *gin.Context) (token string, err error) {\n\treturn GetJWTFromHeader(c.GetHeader(\"Authorization\"))\n}", "func ParseToken(req *http.Request) string {\n\treqToken := req.Header.Get(\"Authorization\")\n\tfmt.Printf(\"helper debug: [%#v]\\n\", reqToken) //debug\n\tsplitToken := strings.Split(reqToken, \"Bearer\")\n\tfmt.Println(splitToken) //debug\n\treqToken = splitToken[1]\n\treqToken = strings.Trim(reqToken, \" \")\n\tfmt.Println(reqToken) //debug\n\n\treturn reqToken\n}", "func FromAuthHeader(ctx context.Context) (string, error) {\n\tauthHeader := ctx.GetHeader(\"Authorization\")\n\tif authHeader == \"\" {\n\t\treturn \"\", nil // No error, just no token\n\t}\n\n\t// TODO: Make this a bit more robust, parsing-wise\n\tauthHeaderParts := strings.Split(authHeader, \" \")\n\tif len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != \"bearer\" {\n\t\treturn \"\", fmt.Errorf(\"Authorization header format must be Bearer {token}\")\n\t}\n\n\treturn authHeaderParts[1], nil\n}", "func GetTokenFromHTTPHeaders(headers http.Header) (string, error) {\n\tauthHeader := headers.Get(authenticationHeader)\n\tif authHeader == \"\" {\n\t\treturn \"\", errors.New(\"no auth header provided\")\n\t}\n\treturn getTokenFromString(authHeader)\n}", "func ExtractToken(r *http.Request) string {\n\tkeys := r.URL.Query()\n\ttoken := keys.Get(\"token\")\n\tif token != \"\" {\n\t\treturn token\n\t}\n\tbearToken := r.Header.Get(\"Authorization\")\n\t//normally Authorization the_token_xxx\n\tstrArr := strings.Split(bearToken, \" \")\n\tif len(strArr) == 2 {\n\t\treturn strArr[1]\n\t}\n\treturn \"\"\n}", "func ExtractToken(r *http.Request) string {\n\n\tbearToken := r.Header.Get(\"Authorization\")\n\n\t//normally Authorization the_token_xxx\n\tstrArr := strings.Split(bearToken, \" \")\n\tif len(strArr) == 2 {\n\t\treturn strArr[1]\n\t}\n\treturn \"\"\n}", "func getTokenInBearer(req *http.Request) (string, error) {\n\ttoken := req.Header.Get(authorizationHeader)\n\tif token == \"\" {\n\t\treturn \"\", ErrSessionNotFound\n\t}\n\n\titems := strings.Split(token, \" \")\n\tif len(items) != 2 {\n\t\treturn \"\", ErrInvalidSession\n\t}\n\n\tif items[0] != authorizationType { // only accept bearer authorization type\n\t\treturn \"\", ErrSessionNotFound\n\t}\n\treturn items[1], nil\n}", "func ExtractToken(r *http.Request) string {\n\tbearToken := r.Header.Get(\"Authorization\")\n\t//normally Authorization the_token_xxx\n\tstrArr := strings.Split(bearToken, \" \")\n\tif len(strArr) == 2 {\n\t\treturn strArr[1]\n\t}\n\treturn \"\"\n}", "func extractToken(r *http.Request) string {\n\tbearToken := r.Header.Get(\"Authorization\")\n\n\ttoken := strings.Split(bearToken, \" \")\n\n\tif len(token) == 2 {\n\t\treturn token[1]\n\t}\n\n\treturn \"\"\n}", "func ExtractToken(r *http.Request) string {\r\n\tauthorization := r.Header.Get(\"Authorization\")\r\n\tregex := regexp.MustCompile(\"(Bearer\\\\s)(.*)\")\r\n\tmatch := regex.FindStringSubmatch(authorization)\r\n\r\n\tif len(match) > 0 {\r\n\t\treturn match[2]\r\n\t}\r\n\r\n\treturn \"\"\r\n}", "func CsrfFromHeader(param string) func(c *fiber.Ctx) (string, error) {\n\treturn func(c *fiber.Ctx) (string, error) {\n\t\ttoken := c.Get(param)\n\t\tif token == \"\" {\n\t\t\treturn \"\", errMissingHeader\n\t\t}\n\t\treturn token, nil\n\t}\n}", "func jwtFromHeader(header string, authScheme string) func(c *fiber.Ctx) (string, error) {\n\treturn func(c *fiber.Ctx) (string, error) {\n\t\tauth := c.Get(header)\n\t\tl := len(authScheme)\n\t\tif len(auth) > l+1 && strings.EqualFold(auth[:l], authScheme) {\n\t\t\treturn strings.TrimSpace(auth[l:]), nil\n\t\t}\n\t\treturn \"\", ErrJWTMissingOrMalformed\n\t}\n}", "func ParseTokenFromRequest(ctx *fasthttp.RequestCtx) string {\n\ttoken := string(ctx.Request.Header.Cookie(\"GoLog-Token\")) // GoLog-Token is the hardcoded name of the cookie\n\tlog.Info(\"ParseTokenFromRequest | Checking if token is in the cookie ...\")\n\tif strings.Compare(token, \"\") == 0 { // No cookie provided :/ Checking in the request\n\t\tlog.Warn(\"ParseTokenFromRequest | Token is not in the cookie, retrieving from the request ...\")\n\t\ttoken = string(ctx.FormValue(\"token\")) // Extracting the token from the request (ARGS,GET,POST)\n\t\tif strings.Compare(token, \"\") == 0 { // No token provided in the request\n\t\t\tlog.Warn(\"ParseTokenFromRequest | Can not find the token! ...\")\n\t\t\treturn \"\" // \"COOKIE_NOT_PRESENT\"\n\t\t}\n\t\tlog.Info(\"ParseTokenFromRequest | Token found in request! ... | \", token)\n\t} else {\n\t\tlog.Info(\"ParseTokenFromRequest | Token found in cookie! ... | \", token)\n\t}\n\treturn token\n}", "func extractXApiTokenHeader(key, value string) string {\n\treturn value\n}", "func (c *Conn) Token() string {\n\ta := c.headers.Get(\"Authorization\")\n\tif len(a) < 7 {\n\t\treturn \"\"\n\t}\n\treturn a[7:]\n}", "func getTokenFromResponse(r *http.Request) string {\n\tconst prefix = \"Bearer \"\n\n\tauth, ok := r.Header[\"Authorization\"]\n\tif !ok {\n\t\treturn \"\"\n\t}\n\n\tfor _, v := range auth {\n\t\tif strings.HasPrefix(v, prefix) {\n\t\t\treturn strings.TrimPrefix(v, prefix)\n\t\t}\n\t}\n\n\treturn \"\"\n}", "func (jwtAuth *JWTAuth) ExtractToken(r *http.Request) string {\n\tkeys := r.URL.Query()\n\ttoken := keys.Get(\"token\")\n\tif token != \"\" {\n\t\treturn token\n\t}\n\tbearToken := r.Header.Get(\"Authorization\")\n\n\tstrArr := strings.Split(bearToken, \" \")\n\tif len(strArr) == 2 {\n\t\treturn strArr[1]\n\t}\n\treturn \"\"\n}", "func getBearerToken(r *http.Request) string {\n\tauthHeader := r.Header.Get(\"Authorization\")\n\tif len(authHeader) < 1 {\n\t\treturn \"\"\n\t}\n\twords := strings.Split(authHeader, \" \")\n\tif len(words) != 2 {\n\t\treturn \"\"\n\t}\n\tif words[0] != \"Bearer\" {\n\t\treturn \"\"\n\t}\n\treturn words[1]\n}", "func getToken(md metadata.MD) (string, error) {\n\tif tokens := md.Get(\"authorization\"); len(tokens) > 0 {\n\t\tsplitToken := strings.Split(tokens[0], \"Token\")\n\t\tif len(splitToken) != 2 {\n\t\t\treturn \"\", errors.New(\"bad token format, expected Authorization: Token <token>\")\n\t\t}\n\t\treturn strings.TrimSpace(splitToken[1]), nil\n\t}\n\n\tv := md.Get(\"grpcgateway-cookie\")\n\tif len(v) == 0 {\n\t\treturn \"\", errors.New(\"token not present in authorization header or cookies\")\n\t}\n\n\treturn mux.GetCookieValue(v, \"token\")\n}", "func getAuthHeaderFromToken(path string) (string, error) {\n\tvar token string\n\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"reading bearer token file\")\n\t}\n\n\tif len(b) != 0 {\n\t\tif b[len(b)-1] == '\\n' {\n\t\t\tb = b[0 : len(b)-1]\n\t\t}\n\t\ttoken = fmt.Sprintf(\"Bearer %s\", string(b))\n\t}\n\n\treturn token, nil\n}", "func (j *JWTUtil) ExtractToken(c *gin.Context) (token string, err error) {\n\tsentTokenSlice := c.Request.Header[\"Authorization\"]\n\tif len(sentTokenSlice) == 0 {\n\t\treturn \"\", errors.New(\"Missing authorization token\")\n\t}\n\tsentTokenSlice = strings.Split(sentTokenSlice[0], \" \")\n\tif len(sentTokenSlice) != 2 {\n\t\treturn \"\", errors.New(\"Something wrong with the token\")\n\t}\n\n\treturn sentTokenSlice[1], nil\n}", "func (a *authSvc) ValidateToken(authHeader interface{}) (interface{}, error) {\n\t// validate an Authorization header token is present in the request\n\tif authHeader == nil {\n\t\treturn nil, errors.New(\"no valid Authorization token in request\")\n\t}\n\theader := authHeader.(string)\n\tif header == \"\" {\n\t\treturn nil, errors.New(\"no valid Authorization token in request\")\n\t}\n\t// validate that it is a Bearer token\n\tif !strings.HasPrefix(header, bearerTokenKey) {\n\t\treturn nil, errors.New(\"authorization token is not valid Bearer token\")\n\t}\n\tt := strings.Replace(header, bearerTokenKey, \"\", -1)\n\t// parse the header token\n\ttoken, err := jwt.Parse(t, func(token *jwt.Token) (interface{}, error) {\n\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"there was an parsing the given token. please validate the token is for this service\")\n\t\t}\n\t\treturn a.authSecret, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// validate token and get claims\n\tif claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {\n\t\tvar decodedToken map[string]string\n\t\terr = mapstructure.Decode(claims, &decodedToken)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn decodedToken[\"email\"], nil\n\t}\n\treturn nil, errors.New(\"invalid authorization token\") // token is not valid, return error\n}", "func getToken(r *http.Request) (token string) {\n\ttoken, _, _ = r.BasicAuth()\n\treturn token\n}", "func Token(token string) 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\tif token == \"\" {\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\theader := r.Header.Get(\"Authorization\")\n\n\t\t\tif header == \"\" {\n\t\t\t\thttp.Error(w, ErrInvalidToken.Error(), http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif header != \"Bearer \"+token {\n\t\t\t\thttp.Error(w, ErrInvalidToken.Error(), http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func extractBearerToken(ctx *gin.Context) (string, error) {\n\tauthHeader := strings.Split(ctx.GetHeader(\"Authorization\"), \"bearer\")\n\t// Check that the authorization header exists\n\tif len(authHeader) <= 1 {\n\t\treturn \"\", errors.New(\"no authorization header\")\n\t}\n\t// Remove all spaces from the parsed auth header\n\treturn strings.ReplaceAll(authHeader[1], \" \", \"\"), nil\n}", "func GetBearerToken(r *http.Request) (string, error) {\n\n\t// FIXME optimize this !!\n\n\tauth := r.Header.Get(\"Authorization\")\n\tif len(auth) == 0 {\n\t\treturn \"\", ErrNoToken\n\t}\n\n\tparts := strings.Split(auth, \" \")\n\tif len(parts) != 2 {\n\t\treturn \"\", ErrNoToken\n\t}\n\tif parts[0] == \"Bearer\" {\n\t\treturn parts[1], nil\n\t}\n\n\treturn \"\", ErrNoToken\n}", "func parseToken(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tevent := ssas.Event{Op: \"ParseToken\"}\n\t\tauthHeader := r.Header.Get(\"Authorization\")\n\t\tif authHeader == \"\" {\n\t\t\tevent.Help = \"no authorization header found\"\n\t\t\tssas.AuthorizationFailure(event)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tauthRegexp := regexp.MustCompile(`^Bearer (\\S+)$`)\n\t\tauthSubmatches := authRegexp.FindStringSubmatch(authHeader)\n\t\tif len(authSubmatches) < 2 {\n\t\t\tevent.Help = \"invalid Authorization header value\"\n\t\t\tssas.AuthorizationFailure(event)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\ttokenString := authSubmatches[1]\n\t\ttoken, err := server.VerifyToken(tokenString)\n\t\tif err != nil {\n\t\t\tevent.Help = fmt.Sprintf(\"unable to decode authorization header value; %s\", err)\n\t\t\tssas.AuthorizationFailure(event)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tvar rd ssas.AuthRegData\n\t\tif rd, err = readRegData(r); err != nil {\n\t\t\trd = ssas.AuthRegData{}\n\t\t}\n\n\t\tif claims, ok := token.Claims.(*service.CommonClaims); ok && token.Valid {\n\t\t\trd.AllowedGroupIDs = claims.GroupIDs\n\t\t\trd.OktaID = claims.OktaID\n\t\t}\n\t\tctx := context.WithValue(r.Context(), \"ts\", tokenString)\n\t\tctx = context.WithValue(ctx, \"rd\", rd)\n\t\tservice.LogEntrySetField(r, \"rd\", rd)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}", "func GetJWTFromEchoHeader(c echo.Context) (token string, err error) {\n\treturn GetJWTFromHeader(c.Request().Header.Get(\"Authorization\"))\n}", "func ExtractToken(bearer string) (token string, err error) {\n\tstrArr := strings.Split(bearer, \" \")\n\tif len(strArr) == 2 {\n\t\treturn strArr[1], nil\n\t}\n\treturn token, errors.New(\"wrong token format\")\n}", "func ValidateToken(bearerHeader string) (User, error) {\n\n\t// format the token string\n\ttokenString := strings.Split(bearerHeader, \" \")[1]\n\n\tvar user User\n\n\ttoken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {\n\t\t// Don't forget to validate the alg is what you expect:\n\n\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\n\t\treturn []byte(\"secretkey\"), nil\n\t})\n\n\tif err != nil {\n\n\t\tfmt.Println(err)\n\t\treturn user, err\n\t}\n\n\tif claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {\n\t\t// convert the interface to the map[string]interface{}\n\t\ts := claims[\"user\"].(map[string]interface{})\n\n\t\t// create a user of User type\n\t\t// convert the s[\"userID\"] interface to string\n\t\tuser := User{s[\"userID\"].(string), s[\"name\"].(string)}\n\n\t\treturn user, nil\n\n\t}\n\n\treturn user, errors.New(\"Something went wrong\")\n\n}", "func DecodeToken() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\n\t\ttokenStr := c.Request.Header.Get(\"Authorization\")\n\n\t\tuid, b := token.DecodeToken(tokenStr)\n\n\t\tif b {\n\t\t\tc.Set(common.TokenUid, uid)\n\t\t}\n\t\tc.Next()\n\t}\n}", "func GetUIDFromToken(ctx *fiber.Ctx) string {\n\ttokenHeader := string(ctx.Request().Header.Peek(\"Authorization\"))\n\ttk := &Token{}\n\t_, err := jwt.ParseWithClaims(tokenHeader, tk, func(t *jwt.Token) (interface{}, error) {\n\t\treturn []byte(os.Getenv(\"jwtsecret\")), nil\n\t})\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn tk.Username\n}", "func Token(token string) (interface{}, error) {\n\tif token == \"\" {\n\t\treturn nil, nil // unauthorized\n\t}\n\n\t// In a real authentication, here we should actually validate that the token is valid\n\tvar user User\n\terr := json.Unmarshal([]byte(token), &user)\n\treturn &user, err\n}", "func (k *Client) fetchToken(ctx context.Context, authRequest interface{}) (string, error) {\n\td, err := json.Marshal(authRequest)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trequest, err := http.NewRequest(\"POST\", k.URL+\"/auth/tokens\", bytes.NewReader(d))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trequest = request.WithContext(ctx) // TODO(mblotniak): use http.NewRequestWithContext after go 1.13 upgrade\n\thttputil.SetContextHeaders(request)\n\trequest.Header.Set(contentTypeHeader, applicationJSONValue)\n\n\tresp, err := k.HTTPDoer.Do(request)\n\tif err != nil {\n\t\treturn \"\", httputil.ErrorFromResponse(err, resp)\n\t}\n\tdefer resp.Body.Close() // nolint: errcheck\n\n\tif err = httputil.CheckStatusCode([]int{200, 201}, resp.StatusCode); err != nil {\n\t\treturn \"\", httputil.ErrorFromResponse(err, resp)\n\t}\n\n\treturn resp.Header.Get(xSubjectTokenHeader), nil\n}", "func Token(t string) *Conn {\n\treturn &Conn{\n\t\theaders: http.Header{\n\t\t\t\"Authorization\": []string{\n\t\t\t\t\"Bearer \" + t,\n\t\t\t},\n\t\t\t\"Content-Type\": contentType,\n\t\t},\n\t}\n}", "func Token(req *http.Request) string {\n\tctx, ok := req.Context().Value(nosurfKey).(*csrfContext)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\n\treturn ctx.token\n}", "func TokenAuth() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\ttokenString, _ := c.GetQuery(\"token\")\n\t\tif len(tokenString) == 0 {\n\t\t\ttokenString = c.GetHeader(\"Authorization\")\n\t\t}\n\t\tif len(tokenString) == 0 {\n\t\t\tc.AbortWithStatusJSON(400, gin.H{\"msg\": \"empty token.\"})\n\t\t\treturn\n\t\t}\n\n\t\ttoken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {\n\t\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\t\treturn nil, errors.New(\"validation error\")\n\t\t\t}\n\t\t\treturn []byte(\"abc\"), nil\n\t\t})\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(400, gin.H{\"msg\": \"auth failed.\"})\n\t\t\treturn\n\t\t}\n\t\tif _, ok := token.Claims.(jwt.MapClaims); !ok || !token.Valid {\n\t\t\tc.AbortWithStatusJSON(400, gin.H{\"msg\": \"auth failed.\"})\n\t\t\treturn\n\t\t}\n\n\t}\n}", "func getRequestWithToken(t *testing.T, url, bearer string) *http.Request {\n\treq := getRequest(t, url)\n\treq.Header.Add(\"Authorization\", bearer)\n\treturn req\n}", "func (middleware *Middleware) ParseToken(c controller.MContext) (*jwt.Token, error) {\n\ttoken, err := middleware.jwtFromHeader(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn middleware.ParseWithClaims(token)\n}", "func BuildWithHeader(signer Signer, header *Header, claims encoding.BinaryMarshaler) (*Token, error) {\n\tb := &TokenBuilder{\n\t\tsigner: signer,\n\t\theader: *header,\n\t}\n\treturn b.Build(claims)\n}", "func (t *Token) Header() Header {\n\treturn t.header\n}", "func NewToken(header *Header, body *Body, secret *pbauth.Secret) (string, error) {\n\tif err := ValidateHeader(header); err != nil {\n\t\treturn \"\", err\n\t}\n\tif err := ValidateBody(body); err != nil {\n\t\treturn \"\", err\n\t}\n\tif err := ValidateSecret(secret); err != nil {\n\t\treturn \"\", err\n\t}\n\tif body.Permission == Admin && header.Alg != Hs512 {\n\t\treturn \"\", consts.ErrInvalidPermission\n\t}\n\t// Currently supports JWT, JET\n\tif header.TokenTyp != Jwt && header.TokenTyp != Jet {\n\t\treturn \"\", consts.ErrUnknownTokenType\n\t}\n\ttokenString, err := getTokenSignature(header, body, secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn tokenString, nil\n}", "func GetBearerToken(request *http.Request) (string, error) {\n\tauthorization := request.Header.Get(\"Authorization\")\n\tdump := strings.Split(authorization, \"Bearer\")\n\tif len(dump) != 2 {\n\t\treturn \"\", errorext.NewAuthorizeError(\"invalid authorization bearer token\")\n\t}\n\treturn strings.TrimSpace(dump[1]), nil\n}", "func VerifyToken(headerString string) (*jwt.Token, error) {\n\ttokenString := ExtractToken(headerString)\n\ttoken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {\n\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\t\treturn []byte(os.Getenv(\"ACCESS_SECRET\")), nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn token, nil\n}", "func requestAuthHeaderClaims(r *http.Request) AuthClaims {\n\tauthHdr, prs := r.Header[\"Authorization\"]\n\tif prs {\n\t\tif claims := parseAuthHeader(authHdr); claims != nil {\n\t\t\treturn claims\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Server) getToken(ctx context.Context) (string, bool) {\n\tmd, ok := metadata.FromIncomingContext(ctx)\n\tif !ok || len(md[constants.TokenHeader]) == 0 {\n\t\treturn \"\", false\n\t}\n\n\treturn md[constants.TokenHeader][0], true\n}", "func (s *HTTPServer) parseTokenInternal(req *http.Request, token *string, resolveProxyToken bool) {\n\ttok := \"\"\n\tif other := req.URL.Query().Get(\"token\"); other != \"\" {\n\t\ttok = other\n\t} else if other := req.Header.Get(\"X-Consul-Token\"); other != \"\" {\n\t\ttok = other\n\t} else if other := req.Header.Get(\"Authorization\"); other != \"\" {\n\t\t// HTTP Authorization headers are in the format: <Scheme>[SPACE]<Value>\n\t\t// Ref. https://tools.ietf.org/html/rfc7236#section-3\n\t\tparts := strings.Split(other, \" \")\n\n\t\t// Authorization Header is invalid if containing 1 or 0 parts, e.g.:\n\t\t// \"\" || \"<Scheme><Value>\" || \"<Scheme>\" || \"<Value>\"\n\t\tif len(parts) > 1 {\n\t\t\tscheme := parts[0]\n\t\t\t// Everything after \"<Scheme>\" is \"<Value>\", trimmed\n\t\t\tvalue := strings.TrimSpace(strings.Join(parts[1:], \" \"))\n\n\t\t\t// <Scheme> must be \"Bearer\"\n\t\t\tif scheme == \"Bearer\" {\n\t\t\t\t// Since Bearer tokens shouldnt contain spaces (rfc6750#section-2.1)\n\t\t\t\t// \"value\" is tokenized, only the first item is used\n\t\t\t\ttok = strings.TrimSpace(strings.Split(value, \" \")[0])\n\t\t\t}\n\t\t}\n\t}\n\n\tif tok != \"\" {\n\t\tif resolveProxyToken {\n\t\t\tif p := s.agent.resolveProxyToken(tok); p != nil {\n\t\t\t\t*token = s.agent.State.ServiceToken(p.Proxy.TargetServiceID)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t*token = tok\n\t\treturn\n\t}\n\n\t*token = s.agent.tokens.UserToken()\n}", "func ExtractToken(bearerToken string) string {\n\tstrArr := strings.Split(bearerToken, \" \")\n\tif len(strArr) == 2 {\n\t\treturn strArr[1]\n\t}\n\treturn \"\"\n}", "func (s *ExtendedJWT) retrieveToken(httpRequest *http.Request) string {\n\tjwtToken := httpRequest.Header.Get(\"Authorization\")\n\n\t// Strip the 'Bearer' prefix if it exists.\n\treturn strings.TrimPrefix(jwtToken, \"Bearer \")\n}", "func GetToken(c *gin.Context) {\n\tcode = c.Query(\"code\")\n\t//fmt.Println(\"code: \" + code)\n\tTokenRequest(code, c)\n}", "func authRequest(req *http.Request) (JWTClaims, error) {\n\n\t// init tokenStr\n\ttokenStr := \"\"\n\n\t// attempt to retrieve from cookie, if not assign the value of the authorization header\n\tcookie, err := req.Cookie(\"token\")\n\tif err != nil {\n\t\ttokenStr = strings.TrimPrefix(req.Header.Get(\"Authorization\"), \"Bearer \")\n\t} else {\n\t\ttokenStr = cookie.Value\n\t}\n\n\tclaims := &JWTClaims{}\n\n\ttoken, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {\n\t\treturn getSigningKey(), nil\n\t})\n\tif err != nil || !token.Valid {\n\t\treturn JWTClaims{}, fmt.Errorf(\"failed to parse jwt/invalid token, unauthorized\")\n\t}\n\n\treturn *claims, nil\n}", "func getToken(body string) string {\n\tvar f interface{}\n\tif err := json.Unmarshal([]byte(body), &f); err != nil {\n\t\tlog.Panicf(\"Receieved malformed JSON body, %v\\n\", body)\n\t}\n\tm := f.(map[string]interface{})\n\treturn m[\"token\"].(string)\n}", "func Token(app *container.Container) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\n\t\tvar (\n\t\t\tbearer *authorizationHeader = &authorizationHeader{}\n\t\t\tclaims *tokenModels.JWTClaims = &tokenModels.JWTClaims{}\n\t\t\tjwtToken *jwt.Token = &jwt.Token{}\n\t\t\ttoken *tokenModels.Token = &tokenModels.Token{}\n\t\t\tuser *userModels.User = &userModels.User{}\n\t\t)\n\n\t\t// validate authorization header\n\t\terr := c.ShouldBindWith(bearer, binding.Header)\n\t\tok, httpResponse := app.Facades.Error.ShouldContinue(err, &response.ErrValidation)\n\t\tif !ok {\n\t\t\tc.AbortWithStatusJSON(httpResponse.Status, httpResponse)\n\t\t\treturn\n\t\t}\n\n\t\t// split authorization header value, i.e. from Bearer xxx to [\"Bearer\", \"xxx\"]\n\t\tbearerHeader := strings.Split(bearer.Authorization, \" \")\n\t\tif len(bearerHeader) != 2 || bearerHeader[0] != \"Bearer\" {\n\t\t\thttpResponse := response.ErrTokenInvalid\n\t\t\tc.AbortWithStatusJSON(httpResponse.Status, httpResponse)\n\t\t\treturn\n\t\t}\n\n\t\t// validate the token\n\t\tjwtToken, err = app.Facades.Token.ParseWithClaims(bearerHeader[1], claims)\n\t\tok, httpResponse = app.Facades.Error.ShouldContinue(err, &response.ErrTokenInvalid)\n\t\tif !ok {\n\t\t\tc.AbortWithStatusJSON(httpResponse.Status, httpResponse)\n\t\t\treturn\n\t\t}\n\n\t\t// find the user\n\t\terr = app.Facades.User.BindByID(user, claims.Subject)\n\t\tok, httpResponse = app.Facades.Error.ShouldContinue(err, &response.ErrUserNotFound)\n\t\tif !ok {\n\t\t\tc.AbortWithStatusJSON(httpResponse.Status, httpResponse)\n\t\t\treturn\n\t\t}\n\n\t\t// explicitly check for expiry for both refresh and access types\n\t\t// remove if expired\n\t\tnow := time.Now()\n\t\ttokenExpiry := time.Unix(claims.ExpiresAt, 0)\n\n\t\t// if expiry is before now\n\t\tif tokenExpiry.Before(now) {\n\t\t\t// revoke the token\n\t\t\tapp.Facades.User.RevokeTokenByID(claims.ID.String())\n\n\t\t\t// respond\n\t\t\thttpResponse := response.ErrTokenExpired\n\t\t\t// serverErr := logging.NewServerError(err).BindClientErr(httpResponse)\n\t\t\t// c.Error(serverErr)\n\t\t\tc.AbortWithStatusJSON(httpResponse.Status, httpResponse)\n\t\t\treturn\n\t\t}\n\n\t\t// We'll only allow the access token flow in this middleware. If the user has\n\t\t// a refresh token, they should go through a different flow. For example, exchanging\n\t\t// their refresh token for a new access token.\n\t\tif claims.TokenType != enums.JWTTokenTypeAccess {\n\t\t\thttpResponse := response.ErrTokenTypeInvalid\n\t\t\t// serverErr := logging.NewServerError(nil).BindClientErr(httpResponse)\n\t\t\t// c.Error(serverErr)\n\t\t\tc.AbortWithStatusJSON(httpResponse.Status, httpResponse)\n\t\t\treturn\n\t\t}\n\n\t\t// We'll disallow invalid tokens, too.\n\t\tif !jwtToken.Valid {\n\t\t\tfmt.Println(\"here it is\")\n\t\t\thttpResponse := response.ErrTokenInvalid\n\t\t\tc.AbortWithStatusJSON(httpResponse.Status, httpResponse)\n\t\t\treturn\n\t\t}\n\n\t\t// lastly we'll check to see if the token is in the whitelist\n\t\terr = app.Facades.Token.BindByID(token, claims.ID)\n\t\tif err != nil {\n\t\t\thttpResponse := response.ErrTokenNotFound\n\t\t\t// serverErr := logging.NewServerError(err).BindClientErr(httpResponse)\n\t\t\t// c.Error(serverErr)\n\t\t\tc.AbortWithStatusJSON(httpResponse.Status, httpResponse)\n\t\t\treturn\n\t\t}\n\n\t\t// store user in the handler dependencies\n\t\tapp.Current.User = user\n\n\t\t// store the token so we can revoke tokens related to the session\n\t\tapp.Current.Token = token\n\n\t\tc.Next()\n\t}\n}", "func (t *targetrunner) userFromRequest(r *http.Request) (*authRec, error) {\n\tif r == nil {\n\t\treturn nil, nil\n\t}\n\n\ttoken := \"\"\n\ttokenParts := strings.SplitN(r.Header.Get(\"Authorization\"), \" \", 2)\n\tif len(tokenParts) == 2 && tokenParts[0] == tokenStart {\n\t\ttoken = tokenParts[1]\n\t}\n\n\tif token == \"\" {\n\t\t// no token in header = use default credentials\n\t\treturn nil, nil\n\t}\n\n\tauthrec, err := t.authn.validateToken(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to decrypt token [%s]: %v\", token, err)\n\t}\n\n\treturn authrec, nil\n}", "func CheckTheValidityOfTheTokenFromHTTPHeader(w http.ResponseWriter, r *http.Request) (writer http.ResponseWriter, newToken string, err error) {\n err = createError(011)\n for _, cookie := range r.Cookies() {\n if cookie.Name == \"Token\" {\n var token string\n token, err = CheckTheValidityOfTheToken(cookie.Value)\n //fmt.Println(\"T\", token, err)\n writer = SetCookieToken(w, token)\n newToken = token\n }\n }\n //fmt.Println(err)\n return\n}", "func ParseBearerToken(authHeader string) (string, error) {\n\tparts := strings.Split(authHeader, \" \")\n\tif len(parts) == 2 && parts[0] == \"Bearer\" {\n\t\treturn parts[1], nil\n\t}\n\n\treturn \"\", errors.New(\"unable to parse authorization header\")\n}", "func GetTokenFromPinRequest(p *PinRequest) (string, error) {\n\thttpClient := &http.Client{Timeout: time.Second * 10}\n\t_, body, err := sendRequest(\"GET\", fmt.Sprintf(\"https://plex.tv/pins/%d\", p.Id), headers, httpClient)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpinRequest := PinRequest{}\n\n\terr = json.Unmarshal(body, &pinRequest)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif pinRequest.AuthToken == \"\" {\n\t\treturn \"\", fmt.Errorf(ErrorPinNotAuthorized)\n\t}\n\n\treturn pinRequest.AuthToken, nil\n}", "func GetToken(w http.ResponseWriter, r *http.Request) (string, error) {\n\n\tcookie, err := r.Cookie(\"token\")\n\tif err != nil {\n\t\tif err == http.ErrNoCookie {\n\t\t\t// If there is no cookie in the request the client is not authorized to proceed\n\t\t\tMakeErrorResponse(w, http.StatusUnauthorized, \"No token provided\")\n\t\t\tlog.Println(\"No token provided\")\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// Any other error occurring during the cookie read results in a Bad request error\n\t\tMakeErrorResponse(w, http.StatusBadRequest, \"Bad request\")\n\t\tlog.Println(\"Bad request\")\n\t\treturn \"\", err\n\t}\n\n\treturn cookie.Value, nil\n}", "func (a *Api) token(res http.ResponseWriter, req *http.Request) *token.TokenData {\n\ttd := a.auth.Authenticate(req)\n\n\tif td == nil {\n\t\tstatusErr := &status.StatusError{Status: status.NewStatus(http.StatusUnauthorized, STATUS_NO_TOKEN)}\n\t\ta.sendModelAsResWithStatus(res, statusErr, http.StatusUnauthorized)\n\t\treturn nil\n\t}\n\t//all good!\n\treturn td\n}", "func (r commonResult) ExtractToken() (*Token, error) {\n\tvar s Token\n\terr := r.ExtractInto(&s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Parse the token itself from the stored headers.\n\ts.ID = r.Header.Get(\"X-Subject-Token\")\n\n\treturn &s, err\n}", "func (rs Routes) TokenExtractionMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttoken := r.Header.Get(\"Authorization\")\n\t\tif !strings.HasPrefix(token, \"Bearer \") {\n\t\t\thttp.Error(w, \"Invalid Authorization Header\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\ttoken = strings.TrimPrefix(token, \"Bearer \")\n\n\t\tctx := r.Context()\n\t\tctx = context.WithValue(ctx, contextKeyToken, token)\n\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}", "func BuildHeader(tokenType string, token string) string {\n\treturn fmt.Sprintf(\"Authorization: %s %s\", tokenType, token)\n}", "func (certIdentityRequest *CertificateIdentityRequest) GetToken() string {\n\treturn certIdentityRequest.Token\n}", "func AddTokenHeader(h map[string]string, t string) map[string]string {\n\th[\"X-Plex-Token\"] = t\n\treturn h\n}", "func extractAuthorizationHeader(key, value string) string {\n\n\t// Authorization token is space separated\n\tparts := strings.Split(value, \" \")\n\n\t// Invalid if we don't have at least two parts\n\tif len(parts) < 2 {\n\t\treturn \"\"\n\t}\n\n\t// Check our authorization scheme is supported\n\tif parts[0] != authorizationScheme {\n\t\treturn \"\"\n\t}\n\n\treturn parts[1]\n}", "func GetTokenFrom(ctx context.Context) (*Token, error) {\n\ttoken := ctx.Value(contextKeyAuthToken)\n\tif token == nil {\n\t\terr := errors.New(\"Error: context doesn't contain a token\")\n\t\treturn nil, err\n\t}\n\tt := token.(*Token)\n\treturn t, nil\n}", "func parseAuthHeaderItem(headerItem string) AuthClaims {\n\tparts := strings.SplitN(headerItem, \" \", 2)\n\tif parts[0] == \"Bearer\" {\n\t\tif claims, err := parseJWToken(parts[1]); err == nil && claims != nil {\n\t\t\treturn claims\n\t\t}\n\t}\n\treturn nil\n}", "func ParseJWTFromRequest(req *http.Request) (jwt.JWT, error) {\n\tif b, ok := fromHeader(req); ok {\n\t\treturn ParseJWT(b)\n\t}\n\tif b, ok := fromForm(req); ok {\n\t\treturn ParseJWT(b)\n\t}\n\treturn nil, ErrNoTokenInRequest\n}", "func parseJWTToken(token string) (*jwt.StandardClaims, error) {\n\t// Remove \"bearer \" in front if there is any\n\t// to lowercase as the cli sends in Bearer\n\tif strings.HasPrefix(token, \"bearer \") {\n\t\tsegments := strings.SplitAfterN(token, \"bearer \", 2)\n\t\ttoken = segments[len(segments)-1]\n\t} else if strings.HasPrefix(token, \"Bearer \") {\n\t\tsegments := strings.SplitAfterN(token, \"Bearer \", 2)\n\t\ttoken = segments[len(segments)-1]\n\t}\n\n\t// Parse the token\n\tparsedToken, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, nil)\n\tif parsedToken != nil {\n\t\tif claims, ok := parsedToken.Claims.(*jwt.StandardClaims); ok {\n\t\t\treturn claims, nil\n\t\t} else if ve, ok := err.(*jwt.ValidationError); ok {\n\t\t\tif ve.Errors&jwt.ValidationErrorMalformed != 0 {\n\t\t\t\treturn nil, errors.New(\"token malformed\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, errors.New(\"cannot parse token\")\n}", "func GetToken() string {\n\tif !viper.IsSet(\"cookie\") {\n\t\tlog.Fatalln(\"Cookie not found, run nm5 sc [cookie] to set cookie\")\n\t}\n\tvar token string\n\tcookie := fmt.Sprintf(\"%v=%v\", cookieName, viper.GetString(\"cookie\"))\n\n\treq, err := http.NewRequest(http.MethodGet, homePage, nil)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\treq.Header.Add(\"cookie\", cookie)\n\n\tresponse, err := http.DefaultClient.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error making get-token request, %v\\n\", err)\n\t}\n\n\tdefer response.Body.Close()\n\n\tdoc, err := goquery.NewDocumentFromReader(response.Body)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\thtml, err := doc.Html()\n\n\tif !strings.Contains(html, \"ACCESS_TOKEN\") {\n\t\tlog.Fatalln(\"Error getting token: Invalid or Expired cookie\")\n\t}\n\n\tdoc.Find(\"script\").Each(func(i int, s *goquery.Selection) {\n\t\ttagText := s.Text()\n\n\t\tif strings.Contains(tagText, \"ACCESS_TOKEN\") {\n\t\t\ttagTextArr := strings.Split(tagText, \"\\n\")\n\t\t\tfor _, line := range tagTextArr {\n\t\t\t\tif strings.Contains(line, \"ACCESS_TOKEN\") {\n\t\t\t\t\tre := regexp.MustCompile(`\\'(.*)\\'`)\n\t\t\t\t\tmatches := re.FindStringSubmatch(line)\n\t\t\t\t\ttoken = matches[1]\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\treturn token\n}", "func ExtractUsernameFromAuthorizationHeader(authorizationHeader string) (string, error) {\n\tauthorizationHeaderValue := strings.TrimPrefix(authorizationHeader, \"Basic \")\n\tif authorizationHeader == authorizationHeaderValue {\n\t\treturn \"\", errors.New(\"unsupported authorization header type\")\n\t}\n\n\tcredentials, err := base64.StdEncoding.DecodeString(authorizationHeaderValue)\n\tif err != nil {\n\t\treturn \"\", errors.New(\"invalid authorization header\")\n\t}\n\n\tsplit := strings.Split(string(credentials), \":\")\n\tusername := split[0]\n\n\treturn username, nil\n}", "func ParseRequestorToken(input string) (RequestorToken, error) {\n\tif match := regexp.MustCompile(common.SessionTokenRegex).MatchString(input); match {\n\t\treturn RequestorToken(input), nil\n\t} else {\n\t\treturn \"\", errors.New(\"string did not pass input validation for requestorToken\")\n\t}\n}", "func csrfTokenFromQuery(param string) csrfTokenExtractor {\n\treturn func(c echo.Context) (string, error) {\n\t\ttoken := c.QueryParam(param)\n\t\tif token == \"\" {\n\t\t\treturn \"\", errors.New(\"missing csrf token in the query string\")\n\t\t}\n\t\treturn token, nil\n\t}\n}", "func getBearerToken(t *testing.T) string {\n\ttokenProvider, err := framework.GetConfig()\n\tif err != nil {\n\t\tt.Fatalf(\"error, can't get config: %s\", err)\n\t}\n\n\t// use this for\n\t// tokenProvider.TLSClientConfig\n\n\t// build the request header with a token from the kubeconfig\n\treturn fmt.Sprintf(\"Bearer %s\", tokenProvider.BearerToken)\n}", "func (s Server) GetRequestToken(w http.ResponseWriter, r *http.Request) (string, error) {\n\t// Check for session cookie\n\tcookie, err := r.Cookie(token.CookieName)\n\tif err != nil || cookie.Value == \"\" {\n\t\treturn \"\", err\n\t}\n\treturn cookie.Value, nil\n}" ]
[ "0.8343575", "0.81691396", "0.80145687", "0.7758329", "0.76594764", "0.75980914", "0.75453174", "0.7509722", "0.7469492", "0.7373232", "0.73404735", "0.7257794", "0.7158246", "0.7156253", "0.7118528", "0.71183777", "0.70597965", "0.7051635", "0.70363194", "0.69934404", "0.69782805", "0.69409674", "0.6937576", "0.69223803", "0.69037414", "0.6851772", "0.6848083", "0.6844491", "0.6839344", "0.6766216", "0.6753512", "0.6753121", "0.67443013", "0.6723753", "0.6709287", "0.665817", "0.665219", "0.6518831", "0.6513734", "0.6495724", "0.6480501", "0.64492065", "0.63728696", "0.63566166", "0.6346812", "0.63413215", "0.63363564", "0.63120574", "0.6309609", "0.6252045", "0.6241579", "0.6189048", "0.61807007", "0.61625344", "0.61533386", "0.60997045", "0.6075444", "0.604836", "0.60454476", "0.6030555", "0.6010679", "0.6010589", "0.5986076", "0.5974223", "0.5963665", "0.5955512", "0.59530497", "0.59220845", "0.5906775", "0.58914256", "0.5878338", "0.58545387", "0.584586", "0.5844095", "0.5842761", "0.5823452", "0.5784529", "0.57840383", "0.5781856", "0.5777596", "0.5748539", "0.57453203", "0.5736299", "0.573515", "0.5726044", "0.57136947", "0.5701686", "0.56985456", "0.5695862", "0.5683189", "0.5675786", "0.5666663", "0.56350046", "0.56318456", "0.56167245", "0.5603277", "0.5599207", "0.55955714", "0.55904794", "0.5578435" ]
0.85811514
0
ReadResponse reads a server response into the received o.
func (o *UploadWorkstationJposEntriesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewUploadWorkstationJposEntriesOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewUploadWorkstationJposEntriesBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 404: result := NewUploadWorkstationJposEntriesNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *ResourceHandler) ReadResponse(dataOut unsafe.Pointer, bytesToRead int32, bytesRead *int32, callback *Callback) int32 {\n\treturn lookupResourceHandlerProxy(d.Base()).ReadResponse(d, dataOut, bytesToRead, bytesRead, callback)\n}", "func (o *GetServerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetServerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *InteractionBindReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewInteractionBindOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewInteractionBindNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 500:\n\t\tresult := NewInteractionBindInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *InteractionUnbindReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewInteractionUnbindOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewInteractionUnbindNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 500:\n\t\tresult := NewInteractionUnbindInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (r *ResponseReader) ReadResponse(req *Request) (res *Response, err error) {\n\tres = CreateEmptyResponse(req)\n\t_, err = readFirstLine(r, res)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = readHeaders(r, res)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t_, err = readBodyContent(r, res)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn res, nil\n}", "func (c *Conn) ReadResponse(rmsg *Response) error {\n\tdata, err := c.ReadDataUnit()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcolor.Printf(\"@{c}<!-- RESPONSE -->\\n%s\\n\\n\", string(data))\n\terr = xml.Unmarshal(data, rmsg)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// color.Fprintf(os.Stderr, \"@{y}%s\\n\", spew.Sprintf(\"%+v\", msg))\n\tif len(rmsg.Results) != 0 {\n\t\tr := rmsg.Results[0]\n\t\tif r.IsError() {\n\t\t\treturn r\n\t\t}\n\t}\n\treturn nil\n}", "func (o *VerifyConnectionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewVerifyConnectionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetAvailableReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetAvailableOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *ClosePositionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewClosePositionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewClosePositionBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 401:\n\t\tresult := NewClosePositionUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewClosePositionNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 405:\n\t\tresult := NewClosePositionMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *DescribeServerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDescribeServerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewDescribeServerBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewDescribeServerNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 409:\n\t\tresult := NewDescribeServerConflict()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewDescribeServerInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetServerSessionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetServerSessionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetServerSessionBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewGetServerSessionUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetServerSessionNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewGetServerSessionInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested GET /dsmcontroller/namespaces/{namespace}/servers/{podName}/session returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (o *StartReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewStartOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (resp *PharosResponse) readResponse() {\n\tif !resp.hasBeenRead && resp.Response != nil && resp.Response.Body != nil {\n\t\tresp.data, resp.Error = ioutil.ReadAll(resp.Response.Body)\n\t\tresp.Response.Body.Close()\n\t\tresp.hasBeenRead = true\n\t}\n}", "func (o *HelloWorldReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewHelloWorldOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewHelloWorldBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewHelloWorldInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (reader *BasicRpcReader) ReadResponse(r io.Reader, method string, requestID int32, resp proto.Message) error {\n\trrh := &hadoop.RpcResponseHeaderProto{}\n\terr := readRPCPacket(r, rrh, resp)\n\tif err != nil {\n\t\treturn err\n\t} else if int32(rrh.GetCallId()) != requestID {\n\t\treturn errors.New(\"unexpected sequence number\")\n\t} else if rrh.GetStatus() != hadoop.RpcResponseHeaderProto_SUCCESS {\n\t\treturn &NamenodeError{\n\t\t\tmethod: method,\n\t\t\tmessage: rrh.GetErrorMsg(),\n\t\t\tcode: int(rrh.GetErrorDetail()),\n\t\t\texception: rrh.GetExceptionClassName(),\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *UpdateAntivirusServerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewUpdateAntivirusServerNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tresult := NewUpdateAntivirusServerDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *HasEventsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewHasEventsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewHasEventsUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewHasEventsForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetV2Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetV2OK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewGetV2InternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SaveReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewSaveNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 500:\n\t\tresult := NewSaveInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *TestWriteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewTestWriteOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewTestWriteUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *AllConnectionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewAllConnectionsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewAllConnectionsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewAllConnectionsNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SendDataToDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewSendDataToDeviceOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewSendDataToDeviceBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewSendDataToDeviceInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *HealthNoopReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewHealthNoopOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PutOutOfRotationReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewPutOutOfRotationNoContent()\n\t\tresult.HttpResponse = response\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\terrorResult := kbcommon.NewKillbillError(response.Code())\n\t\tif err := consumer.Consume(response.Body(), &errorResult); err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, errorResult\n\t}\n}", "func (o *GetReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *ReplaceServerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewReplaceServerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 202:\n\t\tresult := NewReplaceServerAccepted()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewReplaceServerBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewReplaceServerNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\tresult := NewReplaceServerDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *StatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewStatusOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewStatusUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewStatusForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func ReadResponse(r *bfe_bufio.Reader, req *Request) (*Response, error) {\n\ttp := textproto.NewReader(r)\n\tresp := &Response{\n\t\tRequest: req,\n\t}\n\n\t// Parse the first line of the response.\n\tline, err := tp.ReadLine()\n\tif err != nil {\n\t\tif err == io.EOF {\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\treturn nil, err\n\t}\n\tf := strings.SplitN(line, \" \", 3)\n\tif len(f) < 2 {\n\t\treturn nil, &badStringError{\"malformed HTTP response\", line}\n\t}\n\treasonPhrase := \"\"\n\tif len(f) > 2 {\n\t\treasonPhrase = f[2]\n\t}\n\tresp.Status = f[1] + \" \" + reasonPhrase\n\tresp.StatusCode, err = strconv.Atoi(f[1])\n\tif err != nil {\n\t\treturn nil, &badStringError{\"malformed HTTP status code\", f[1]}\n\t}\n\n\tresp.Proto = f[0]\n\tvar ok bool\n\tif resp.ProtoMajor, resp.ProtoMinor, ok = ParseHTTPVersion(resp.Proto); !ok {\n\t\treturn nil, &badStringError{\"malformed HTTP version\", resp.Proto}\n\t}\n\n\t// Parse the response headers.\n\tmimeHeader, err := tp.ReadMIMEHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Header = Header(mimeHeader)\n\n\tfixPragmaCacheControl(resp.Header)\n\n\terr = readTransfer(resp, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (o *PostChatroomsChannelHashReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostChatroomsChannelHashReadOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 403:\n\t\tresult := NewPostChatroomsChannelHashReadForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *TogglePacketGeneratorsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewTogglePacketGeneratorsCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *FrontPutBinaryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewFrontPutBinaryOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SystemPingReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewSystemPingOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 500:\n\t\tresult := NewSystemPingInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SendDummyAlertReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewSendDummyAlertOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewSendDummyAlertBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewSendDummyAlertNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetViewsConnectionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetViewsConnectionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetViewsConnectionBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *SyncCopyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewSyncCopyOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewSyncCopyDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (c *Conn) readResponse(res *response_) error {\n\terr := c.readDataUnit()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = IgnoreEOF(scanResponse.Scan(c.decoder, res))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif res.Result.IsError() {\n\t\treturn res.Result\n\t}\n\treturn nil\n}", "func (o *PostPatientsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostPatientsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewPostPatientsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 405:\n\t\tresult := NewPostPatientsMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *AllConnectionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n switch response.Code() {\n \n case 200:\n result := NewAllConnectionsOK()\n if err := result.readResponse(response, consumer, o.formats); err != nil {\n return nil, err\n }\n return result, nil\n \n case 400:\n result := NewAllConnectionsBadRequest()\n if err := result.readResponse(response, consumer, o.formats); err != nil {\n return nil, err\n }\n return nil, result\n \n case 404:\n result := NewAllConnectionsNotFound()\n if err := result.readResponse(response, consumer, o.formats); err != nil {\n return nil, err\n }\n return nil, result\n \n default:\n return nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n }\n}", "func (o *GetMsgVpnReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetMsgVpnOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tresult := NewGetMsgVpnDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (r *Response) Read(p []byte) (n int, err error) {\n\n\tif r.Error != nil {\n\t\treturn -1, r.Error\n\t}\n\n\treturn r.RawResponse.Body.Read(p)\n}", "func (o *PostPciLinksMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPostPciLinksMoidCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostPciLinksMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *PostGatewayConnectNetaddressReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewPostGatewayConnectNetaddressNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostGatewayConnectNetaddressDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *THSRAPIODFare2121Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewTHSRAPIODFare2121OK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 299:\n\t\tresult := NewTHSRAPIODFare2121Status299()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 304:\n\t\tresult := NewTHSRAPIODFare2121NotModified()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *DNSGetReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDNSGetOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewDNSGetDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetGreetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetGreetStatusOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PostAPIV2EventsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPostAPIV2EventsNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPostAPIV2EventsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewPostAPIV2EventsForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *CreateAntivirusServerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewCreateAntivirusServerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tresult := NewCreateAntivirusServerDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *PostCarsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostCarsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 405:\n\t\tresult := NewPostCarsMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *LogReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewLogOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewLogNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *ChatGetConnectedReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewChatGetConnectedOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewChatGetConnectedBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 401:\n\t\tresult := NewChatGetConnectedUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewChatGetConnectedNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *WebModifyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewWebModifyOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 202:\n\t\tresult := NewWebModifyAccepted()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewWebModifyDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetHyperflexServerModelsMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetHyperflexServerModelsMoidOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetHyperflexServerModelsMoidNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\tresult := NewGetHyperflexServerModelsMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *KillQueryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewKillQueryNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewKillQueryBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewKillQueryNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 422:\n\t\tresult := NewKillQueryUnprocessableEntity()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetProgressionViewReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetProgressionViewOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetProgressionViewBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *UpdateRackTopoReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUpdateRackTopoOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewUpdateRackTopoBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetByUIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetByUIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetByUIDNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *UtilTestReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUtilTestOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetMeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetMeOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewGetMeDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *Delete1Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewDelete1NoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewDelete1NotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *PostGatewayDisconnectNetaddressReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewPostGatewayDisconnectNetaddressNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostGatewayDisconnectNetaddressDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *RevokeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewRevokeOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewRevokeUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewRevokeNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetProtocolsUsingGETReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetProtocolsUsingGETOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *CompleteTransactionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewCompleteTransactionNoContent()\n\t\tresult.HttpResponse = response\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\terrorResult := kbcommon.NewKillbillError(response.Code())\n\t\tif err := consumer.Consume(response.Body(), &errorResult); err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, errorResult\n\t}\n}", "func (o *DestroySessionUsingPOSTReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDestroySessionUsingPOSTOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetMapNameEventsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetMapNameEventsOK(o.writer)\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetMapNameEventsNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *RecoveryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewRecoveryOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewRecoveryInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetPeersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetPeersOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 403:\n\t\tresult := NewGetPeersForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *InstallEventsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewInstallEventsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *UpdateRackTopoReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUpdateRackTopoOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewUpdateRackTopoBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewUpdateRackTopoNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewUpdateRackTopoInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetVoicesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetVoicesOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SetMemoRequiredReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewSetMemoRequiredOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewSetMemoRequiredBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewSetMemoRequiredInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PatchHyperflexServerModelsMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPatchHyperflexServerModelsMoidCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPatchHyperflexServerModelsMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *BounceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tresult := NewBounceDefault(response.Code())\n\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\treturn nil, err\n\t}\n\tif response.Code()/100 == 2 {\n\t\treturn result, nil\n\t}\n\treturn nil, result\n}", "func (o *PostHyperflexHxdpVersionsMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPostHyperflexHxdpVersionsMoidCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostHyperflexHxdpVersionsMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetObmsLibraryIdentifierReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetObmsLibraryIdentifierOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewGetObmsLibraryIdentifierNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\tresult := NewGetObmsLibraryIdentifierDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *DeleteApplianceRestoresMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDeleteApplianceRestoresMoidOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewDeleteApplianceRestoresMoidNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\tresult := NewDeleteApplianceRestoresMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *UserQuerySessionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUserQuerySessionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewUserQuerySessionBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewUserQuerySessionInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested GET /sessionbrowser/namespaces/{namespace}/gamesession returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (o *GetDiscoverReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetDiscoverOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *UnclaimTrafficFilterLinkIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUnclaimTrafficFilterLinkIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewUnclaimTrafficFilterLinkIDBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewUnclaimTrafficFilterLinkIDInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (r *overwriteConsumerReader) ReadResponse(resp runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tif r.forStatusCode == ForAllStatusCodes || resp.Code() == r.forStatusCode {\n\t\treturn r.requestReader.ReadResponse(resp, r.consumer)\n\t}\n\n\treturn r.requestReader.ReadResponse(resp, consumer)\n}", "func (o *ChangeaspecificSpeedDialReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewChangeaspecificSpeedDialNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetDebugRequestReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetDebugRequestOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewGetDebugRequestNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PostMemoryArraysMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPostMemoryArraysMoidCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostMemoryArraysMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (c *Client) readResponse(conn net.Conn) ([]byte, error) {\n\tif c.Timeout > 0 {\n\t\t_ = conn.SetReadDeadline(time.Now().Add(c.Timeout))\n\t}\n\n\tproto := \"udp\"\n\tif _, ok := conn.(*net.TCPConn); ok {\n\t\tproto = \"tcp\"\n\t}\n\n\tif proto == \"udp\" {\n\t\tbufSize := c.UDPSize\n\t\tif bufSize == 0 {\n\t\t\tbufSize = dns.MinMsgSize\n\t\t}\n\t\tresponse := make([]byte, bufSize)\n\t\tn, err := conn.Read(response)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn response[:n], nil\n\t}\n\n\t// If we got here, this is a TCP connection\n\t// so we should read a 2-byte prefix first\n\treturn readPrefixed(conn)\n}", "func (o *PayReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPayOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPayBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewPayNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 409:\n\t\tresult := NewPayConflict()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested POST /platform/public/namespaces/{namespace}/payment/orders/{paymentOrderNo}/pay returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (o *CountReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewCountOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewCountBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PostNodesIdentifierObmIdentifyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 201:\n\t\tresult := NewPostNodesIdentifierObmIdentifyCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewPostNodesIdentifierObmIdentifyNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\tresult := NewPostNodesIdentifierObmIdentifyDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *DeleteEventsEventIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewDeleteEventsEventIDNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 401:\n\t\tresult := NewDeleteEventsEventIDUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewDeleteEventsEventIDNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetInterpreterReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetInterpreterOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetInterpreterNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *UtilityServiceReadyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUtilityServiceReadyOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewUtilityServiceReadyDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *SubscriptionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewSubscriptionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *HTTPGetPersistenceItemDataReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewHTTPGetPersistenceItemDataOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewHTTPGetPersistenceItemDataNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *FrontSessionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewFrontSessionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (pr *PushedRequest) ReadResponse(ctx context.Context) (*http.Response, error) {\n\tselect {\n\tcase <-ctx.Done():\n\t\tpr.Cancel()\n\t\tpr.pushedStream.bufPipe.CloseWithError(ctx.Err())\n\t\treturn nil, ctx.Err()\n\tcase <-pr.pushedStream.peerReset:\n\t\treturn nil, pr.pushedStream.resetErr\n\tcase resErr := <-pr.pushedStream.resc:\n\t\tif resErr.err != nil {\n\t\t\tfmt.Println(resErr.err.Error())\n\t\t\tpr.Cancel()\n\t\t\tpr.pushedStream.bufPipe.CloseWithError(resErr.err)\n\t\t\treturn nil, resErr.err\n\t\t}\n\t\tresErr.res.Request = pr.Promise\n\t\tresErr.res.TLS = pr.pushedStream.cc.tlsState\n\t\treturn resErr.res, resErr.err\n\t}\n}", "func (o *PostEquipmentIoExpandersMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPostEquipmentIoExpandersMoidCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostEquipmentIoExpandersMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *DeleteFirmwareUpgradesMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDeleteFirmwareUpgradesMoidOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewDeleteFirmwareUpgradesMoidNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\tresult := NewDeleteFirmwareUpgradesMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetZippedReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tresult := NewGetZippedDefault(response.Code())\n\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\treturn nil, err\n\t}\n\tif response.Code()/100 == 2 {\n\t\treturn result, nil\n\t}\n\treturn nil, result\n}", "func (o *GetEtherPhysicalPortsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetEtherPhysicalPortsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewGetEtherPhysicalPortsDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *ZoneStreamReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewZoneStreamOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *ByNamespaceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewByNamespaceOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewByNamespaceNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SystemDataUsageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewSystemDataUsageOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 500:\n\t\tresult := NewSystemDataUsageInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}" ]
[ "0.76401496", "0.7606844", "0.75207657", "0.7508911", "0.74786514", "0.74720436", "0.743376", "0.74238384", "0.7374945", "0.73664176", "0.7357928", "0.7354524", "0.734958", "0.73463714", "0.7345592", "0.73392683", "0.733557", "0.7321857", "0.7315043", "0.7313861", "0.7309584", "0.7307115", "0.72902143", "0.7285779", "0.72808784", "0.7273853", "0.7273292", "0.7265671", "0.7263609", "0.7261635", "0.7254307", "0.7249632", "0.7249049", "0.7247858", "0.724058", "0.72237885", "0.7223532", "0.7219069", "0.7215034", "0.72117007", "0.7209753", "0.7208508", "0.72079265", "0.71992487", "0.7197488", "0.7196517", "0.71923745", "0.7176729", "0.7173791", "0.717366", "0.71649307", "0.71543473", "0.7149373", "0.71486646", "0.7147398", "0.71429765", "0.7142514", "0.7139922", "0.7138658", "0.7136166", "0.7135955", "0.71357924", "0.7134905", "0.71348715", "0.71330374", "0.71302736", "0.7123791", "0.7123586", "0.71190846", "0.7118953", "0.71186715", "0.7113356", "0.71046627", "0.7100332", "0.7098135", "0.70979005", "0.7097729", "0.7096977", "0.7096106", "0.70955265", "0.7093761", "0.7093045", "0.70870584", "0.70863247", "0.7082525", "0.7080518", "0.7077727", "0.70766544", "0.7076579", "0.70752037", "0.7069205", "0.70680195", "0.7067238", "0.70668125", "0.70663476", "0.7061179", "0.70608747", "0.705933", "0.7056612", "0.70528394", "0.70501614" ]
0.0
-1
NewUploadWorkstationJposEntriesOK creates a UploadWorkstationJposEntriesOK with default headers values
func NewUploadWorkstationJposEntriesOK() *UploadWorkstationJposEntriesOK { return &UploadWorkstationJposEntriesOK{} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewUploadWorkstationJposEntriesNotFound() *UploadWorkstationJposEntriesNotFound {\n\treturn &UploadWorkstationJposEntriesNotFound{}\n}", "func NewUploadWorkstationJposEntriesBadRequest() *UploadWorkstationJposEntriesBadRequest {\n\treturn &UploadWorkstationJposEntriesBadRequest{}\n}", "func newAppendEntriesRequest(term uint64, prevLogIndex uint64, prevLogTerm uint64, commitIndex uint64, leaderName string, entries []*LogEntry) *AppendEntriesRequest {\n\treturn &AppendEntriesRequest{\n\t\tTerm: term,\n\t\tPrevLogIndex: prevLogIndex,\n\t\tPrevLogTerm: prevLogTerm,\n\t\tCommitIndex: commitIndex,\n\t\tLeaderName: leaderName,\n\t\tEntries: entries,\n\t}\n}", "func NewAddEntriesOK() *AddEntriesOK {\n\treturn &AddEntriesOK{}\n}", "func PostEntryNew(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tif isLoggedIn(w, req) {\n\t\tq := req.URL.Query()\n\t\tbox, _ := strconv.Atoi(q[\"box\"][0])\n\t\tpacket, _ := strconv.Atoi(q[\"packet\"][0])\n\t\tid, _ := strconv.Atoi(q[\"product\"][0])\n\t\tje := opdatabase.JournalEntry{\n\t\t\tID: 0,\n\t\t\tLabour: q[\"labour\"][0],\n\t\t\tDate: q[\"date\"][0],\n\t\t\tBox: box,\n\t\t\tPacket: packet,\n\t\t\tProductID: id,\n\t\t}\n\t\tgo model.UpdateLabourNames(je.Labour, je.Date, labours)\n\t\tmodel.CreateJournalEntry(je)\n\t\tres := Response{\n\t\t\t301,\n\t\t\tResponse{20, \", \"},\n\t\t}\n\t\tp, err := json.Marshal(res)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tio.WriteString(w, string(p))\n\n\t}\n}", "func (s SegTypeHopReply) NewEntries(n int32) (SegTypeHopReplyEntry_List, error) {\n\tl, err := NewSegTypeHopReplyEntry_List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn SegTypeHopReplyEntry_List{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func newfileUploadRequest(uri string, resource string, params map[string]string, path string) (*http.Request, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfileContents, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfile.Close()\n\n\trequest, err := http.NewRequest(\"POST\", uri+resource, bytes.NewBuffer([]byte(fileContents)))\n\n\tif err != nil {\n\t\tlog.Println(\"Could not allocate new request object: \", err)\n\t\treturn nil, err\n\t}\n\n\tvalues := request.URL.Query()\n\tfor key, val := range params {\n\t\tvalues.Add(key, val)\n\t}\n\n\trequest.URL.RawQuery = values.Encode()\n\n\trequest.Header.Add(\"Accept\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", authorizationKey)\n\trequest.Header.Add(\"Content-Type\", \"text/csv\")\n\n\treturn request, err\n}", "func NewListSelLogServiceEntriesOK() *ListSelLogServiceEntriesOK {\n\treturn &ListSelLogServiceEntriesOK{}\n}", "func NewUploadSession()(*UploadSession) {\n m := &UploadSession{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func NewGetEntriesOK() *GetEntriesOK {\n\treturn &GetEntriesOK{}\n}", "func NewSpareListOK() *SpareListOK {\n\treturn &SpareListOK{}\n}", "func NewCopyToDefaultContentLocationPostRequestBody()(*CopyToDefaultContentLocationPostRequestBody) {\n m := &CopyToDefaultContentLocationPostRequestBody{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func newKubeListRequest(values url.Values, site, resourceKind string) (*kubeproto.ListKubernetesResourcesRequest, error) {\n\tlimit, err := queryLimitAsInt32(values, \"limit\", defaults.MaxIterationLimit)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tsortBy := types.GetSortByFromString(values.Get(\"sort\"))\n\n\tstartKey := values.Get(\"startKey\")\n\treq := &kubeproto.ListKubernetesResourcesRequest{\n\t\tResourceType: resourceKind,\n\t\tLimit: limit,\n\t\tStartKey: startKey,\n\t\tSortBy: &sortBy,\n\t\tPredicateExpression: values.Get(\"query\"),\n\t\tSearchKeywords: client.ParseSearchKeywords(values.Get(\"search\"), ' '),\n\t\tUseSearchAsRoles: values.Get(\"searchAsRoles\") == \"yes\",\n\t\tTeleportCluster: site,\n\t\tKubernetesCluster: values.Get(\"kubeCluster\"),\n\t\tKubernetesNamespace: values.Get(\"kubeNamespace\"),\n\t}\n\treturn req, nil\n}", "func generateListMultipartUploadsResponse(bucket string, multipartsInfo ListMultipartsInfo, encodingType string) ListMultipartUploadsResponse {\n\tlistMultipartUploadsResponse := ListMultipartUploadsResponse{}\n\tlistMultipartUploadsResponse.Bucket = bucket\n\tlistMultipartUploadsResponse.Delimiter = s3EncodeName(multipartsInfo.Delimiter, encodingType)\n\tlistMultipartUploadsResponse.IsTruncated = multipartsInfo.IsTruncated\n\tlistMultipartUploadsResponse.EncodingType = encodingType\n\tlistMultipartUploadsResponse.Prefix = s3EncodeName(multipartsInfo.Prefix, encodingType)\n\tlistMultipartUploadsResponse.KeyMarker = s3EncodeName(multipartsInfo.KeyMarker, encodingType)\n\tlistMultipartUploadsResponse.NextKeyMarker = s3EncodeName(multipartsInfo.NextKeyMarker, encodingType)\n\tlistMultipartUploadsResponse.MaxUploads = multipartsInfo.MaxUploads\n\tlistMultipartUploadsResponse.NextUploadIDMarker = multipartsInfo.NextUploadIDMarker\n\tlistMultipartUploadsResponse.UploadIDMarker = multipartsInfo.UploadIDMarker\n\tlistMultipartUploadsResponse.CommonPrefixes = make([]CommonPrefix, len(multipartsInfo.CommonPrefixes))\n\tfor index, commonPrefix := range multipartsInfo.CommonPrefixes {\n\t\tlistMultipartUploadsResponse.CommonPrefixes[index] = CommonPrefix{\n\t\t\tPrefix: s3EncodeName(commonPrefix, encodingType),\n\t\t}\n\t}\n\tlistMultipartUploadsResponse.Uploads = make([]Upload, len(multipartsInfo.Uploads))\n\tfor index, upload := range multipartsInfo.Uploads {\n\t\tnewUpload := Upload{}\n\t\tnewUpload.UploadID = upload.UploadID\n\t\tnewUpload.Key = s3EncodeName(upload.Object, encodingType)\n\t\tnewUpload.Initiated = upload.Initiated.UTC().Format(timeFormatAMZLong)\n\t\tlistMultipartUploadsResponse.Uploads[index] = newUpload\n\t}\n\treturn listMultipartUploadsResponse\n}", "func (s ServiceInfoReply) NewEntries(n int32) (ServiceInfoReplyEntry_List, error) {\n\tl, err := NewServiceInfoReplyEntry_List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn ServiceInfoReplyEntry_List{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n decoder := json.NewDecoder(r.Body)\n var ecsBucket ECSBucket\n err := decoder.Decode(&ecsBucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n headers := make(map[string][]string)\n if ecsBucket.ReplicationGroup != \"\" {\n headers[\"x-emc-vpool\"] = []string{ecsBucket.ReplicationGroup}\n }\n if ecsBucket.MetadataSearch != \"\" {\n headers[\"x-emc-metadata-search\"] = []string{ecsBucket.MetadataSearch}\n }\n if ecsBucket.EnableADO {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"false\"}\n }\n if ecsBucket.EnableFS {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableCompliance {\n headers[\"x-emc-compliance-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-compliance-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableEncryption {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"false\"}\n }\n retentionEnabled := false\n headers[\"x-emc-retention-period\"] = []string{\"0\"}\n if ecsBucket.Retention != \"\" {\n days, err := strconv.ParseInt(ecsBucket.Retention, 10, 64)\n if err == nil {\n if days > 0 {\n seconds := days * 24 * 3600\n headers[\"x-emc-retention-period\"] = []string{int64toString(seconds)}\n retentionEnabled = true\n }\n }\n }\n var expirationCurrentVersions int64\n expirationCurrentVersions = 0\n if ecsBucket.ExpirationCurrentVersions != \"\" {\n days, err := strconv.ParseInt(ecsBucket.ExpirationCurrentVersions, 10, 64)\n if err == nil {\n expirationCurrentVersions = days\n }\n }\n var expirationNonCurrentVersions int64\n expirationNonCurrentVersions = 0\n if ecsBucket.ExpirationNonCurrentVersions != \"\" {\n days, err := strconv.ParseInt(ecsBucket.ExpirationNonCurrentVersions, 10, 64)\n if err == nil && ecsBucket.EnableVersioning {\n expirationNonCurrentVersions = days\n }\n }\n var bucketCreateResponse Response\n if ecsBucket.Api == \"s3\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = s3Request(s3, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n versioningStatusOK := true\n lifecyclePolicyStatusOK := true\n // If the bucket has been created\n if bucketCreateResponse.Code == 200 {\n if !retentionEnabled && ecsBucket.EnableVersioning {\n // Enable versioning\n enableVersioningHeaders := map[string][]string{}\n enableVersioningHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n versioningConfiguration := `\n <VersioningConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n <Status>Enabled</Status>\n <MfaDelete>Disabled</MfaDelete>\n </VersioningConfiguration>\n `\n enableVersioningResponse, _ := s3Request(s3, ecsBucket.Name, \"PUT\", \"/?versioning\", enableVersioningHeaders, versioningConfiguration)\n if enableVersioningResponse.Code != 200 {\n versioningStatusOK = false\n }\n }\n if expirationCurrentVersions > 0 || expirationNonCurrentVersions > 0 {\n lifecyclePolicyHeaders := map[string][]string{}\n lifecyclePolicyHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n lifecyclePolicyConfiguration := `\n <LifecycleConfiguration>\n <Rule>\n <ID>expiration</ID>\n <Prefix></Prefix>\n <Status>Enabled</Status>\n `\n if expirationCurrentVersions > 0 && expirationNonCurrentVersions > 0 {\n // Enable expiration for both current and non current versions\n lifecyclePolicyConfiguration += \"<Expiration><Days>\" + ecsBucket.ExpirationCurrentVersions + \"</Days></Expiration>\"\n lifecyclePolicyConfiguration += \"<NoncurrentVersionExpiration><NoncurrentDays>\" + ecsBucket.ExpirationNonCurrentVersions + \"</NoncurrentDays></NoncurrentVersionExpiration>\"\n } else {\n if expirationCurrentVersions > 0 {\n // Enable expiration for current versions only\n lifecyclePolicyConfiguration += \"<Expiration><Days>\" + ecsBucket.ExpirationCurrentVersions + \"</Days></Expiration>\"\n }\n if expirationNonCurrentVersions > 0 {\n // Enable expiration for non current versions only\n // To fix a bug in ECS 3.0 where an expiration for non current version can't be set if there's no expiration set for current versions\n lifecyclePolicyConfiguration += \"<Expiration><Days>1000000</Days></Expiration>\"\n lifecyclePolicyConfiguration += \"<NoncurrentVersionExpiration><NoncurrentDays>\" + ecsBucket.ExpirationNonCurrentVersions + \"</NoncurrentDays></NoncurrentVersionExpiration>\"\n }\n }\n lifecyclePolicyConfiguration += `\n </Rule>\n </LifecycleConfiguration>\n `\n lifecyclePolicyResponse, _ := s3Request(s3, ecsBucket.Name, \"PUT\", \"/?lifecycle\", lifecyclePolicyHeaders, lifecyclePolicyConfiguration)\n if lifecyclePolicyResponse.Code != 200 {\n lifecyclePolicyStatusOK = false\n }\n }\n if versioningStatusOK && lifecyclePolicyStatusOK {\n rendering.JSON(w, http.StatusOK, \"\")\n } else {\n message := \"\"\n if !versioningStatusOK {\n message += \" Versioning can't be enabled.\"\n }\n if !lifecyclePolicyStatusOK {\n message += \" Expiration can't be set.\"\n }\n rendering.JSON(w, http.StatusOK, message)\n }\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"swift\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = swiftRequest(ecsBucket.Endpoint, s3.AccessKey, ecsBucket.Password, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, ecsBucket.Name)\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"atmos\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = atmosRequest(ecsBucket.Endpoint, s3.AccessKey, s3.SecretKey, \"\", \"PUT\", \"/rest/subtenant\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, bucketCreateResponse.ResponseHeaders[\"Subtenantid\"][0])\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n }\n\n return nil\n}", "func WrapUploadInfos(h Handler, w http.ResponseWriter, r *http.Request) {\n\th.UploadInfos(w, r)\n}", "func NewListSyncJobsOK() *ListSyncJobsOK {\n\treturn &ListSyncJobsOK{}\n}", "func CreateListDisks00Request() (request *ListDisks00Request) {\n\trequest = &ListDisks00Request{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"EcsDemo\", \"2019-06-20\", \"ListDisks00\", \"\", \"\")\n\treturn\n}", "func (s IFInfoReply) NewEntries(n int32) (IFInfoReplyEntry_List, error) {\n\tl, err := NewIFInfoReplyEntry_List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn IFInfoReplyEntry_List{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func NewNewThreadOK() *NewThreadOK {\n\treturn &NewThreadOK{}\n}", "func (mgr *MiningMgr) newWork() {\n\tgo func() {\n\t\t// instantSubmit means 15 mins have passed so\n\t\t// the difficulty now is zero and any solution/nonce will work so\n\t\t// can just submit without sending to the miner.\n\t\twork, instantSubmit := mgr.tasker.GetWork()\n\t\tif instantSubmit {\n\t\t\tmgr.solutionOutput <- &pow.Result{Work: work, Nonce: \"anything will work\"}\n\t\t} else {\n\t\t\t// It sends even nil work to indicate that no new challenge is available.\n\t\t\tif work == nil {\n\t\t\t\tmgr.solutionOutput <- nil\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar ids []int64\n\t\t\tfor _, id := range work.Challenge.RequestIDs {\n\t\t\t\tids = append(ids, id.Int64())\n\t\t\t}\n\t\t\tlevel.Debug(mgr.logger).Log(\"msg\", \"sending new chalenge for mining\", \"reqIDs\", fmt.Sprintf(\"%+v\", ids))\n\t\t\tmgr.toMineInput <- work\n\t\t}\n\t}()\n}", "func (s ASInfoReply) NewEntries(n int32) (ASInfoReplyEntry_List, error) {\n\tl, err := NewASInfoReplyEntry_List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn ASInfoReplyEntry_List{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func NewThingsListOK() *ThingsListOK {\n\treturn &ThingsListOK{}\n}", "func NewThreadUpdateOK() *ThreadUpdateOK {\n\n\treturn &ThreadUpdateOK{}\n}", "func NewTeamworkSoftwareUpdateHealth()(*TeamworkSoftwareUpdateHealth) {\n m := &TeamworkSoftwareUpdateHealth{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewJWTCredentials(\n\tclient accounts_proto.AccountsClient,\n\ttokens *accounts_proto.AuthTokens,\n\ttokensSaver TokensSaver,\n) *JWTCredentials {\n\treturn &JWTCredentials{\n\t\tclient: client,\n\t\tsave: tokensSaver,\n\t\ttokens: tokens,\n\t}\n}", "func newfileUploadRequest(uri string, headers map[string]string, paramName, path string) (*http.Request, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer file.Close()\n\n\tbody := &bytes.Buffer{}\n\twriter := multipart.NewWriter(body)\n\tpart, err := writer.CreateFormFile(paramName, filepath.Base(path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = io.Copy(part, file)\n\n\terr = writer.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Does the request with the headers\n\treq, err := http.NewRequest(\"POST\", uri+\"/api/v2/upload\", body)\n\tfor key, val := range headers {\n\t\treq.Header.Set(key, val)\n\t}\n\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\treq.Header.Set(\"User-Agent\", \"Share-CLI/1.0\")\n\treturn req, err\n}", "func NewListUpcomingMeetingsOK() *ListUpcomingMeetingsOK {\n\n\treturn &ListUpcomingMeetingsOK{}\n}", "func (rf *Raft) createAppendEntriesRequest(start int, stop int, term int) *AppendEntriesArgs {\n\tDPrintf(\"Peer-%d create AppendEntriesRequest with start=%d, stop=%d, term=%d.\", rf.me, start, stop, term)\n\tcurrentLen := len(rf.log)\n\tif start < 0 || stop <= start {\n\t\treturn nil\n\t}\n\tif stop > currentLen {\n\t\tstop = currentLen\n\t}\n\trequest := new(AppendEntriesArgs)\n\trequest.Term = term\n\trequest.LeaderId = rf.me\n\trequest.LeaderCommit = rf.commitIndex\n\tprevLogIndex := start - 1\n\tif prevLogIndex >= 0 && prevLogIndex < currentLen {\n\t\trequest.PrevLogIndex = prevLogIndex\n\t\trequest.PrevLogTerm = rf.log[prevLogIndex].Term\n\t} else {\n\t\trequest.PrevLogIndex = 0\n\t\trequest.PrevLogTerm = 0\n\t}\n\tif start < currentLen && stop >= start {\n\t\tif start == 0 {\n\t\t\tstart = 1\n\t\t}\n\t\trequest.Entries = rf.log[start:stop]\n\t}\n\tDPrintf(\"Peer-%d create an appendRequest: %v\", rf.me, *request)\n\treturn request\n}", "func (service *S3Service) newS3Request() *S3Request {\n return NewS3Request(service.accessKey, service.secretKey)\n}", "func (c *OutputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func CreateListAvailableFileSystemTypesRequest() (request *ListAvailableFileSystemTypesRequest) {\n\trequest = &ListAvailableFileSystemTypesRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"EHPC\", \"2018-04-12\", \"ListAvailableFileSystemTypes\", \"ehs\", \"openAPI\")\n\treturn\n}", "func NewTemplateListOK() *TemplateListOK {\n\treturn &TemplateListOK{}\n}", "func CreateOemSitingSelctionRequest() (request *OemSitingSelctionRequest) {\n\trequest = &OemSitingSelctionRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"cloudwf\", \"2017-03-28\", \"OemSitingSelction\", \"cloudwf\", \"openAPI\")\n\treturn\n}", "func NewListUserContributionsOK() *ListUserContributionsOK {\n\treturn &ListUserContributionsOK{}\n}", "func (req *AppendEntriesRequest) Encode(w io.Writer) (int, error) {\n\n\tprotoEntries := make([]*protobuf.ProtoAppendEntriesRequest_ProtoLogEntry, len(req.Entries))\n\n\tfor i, entry := range req.Entries {\n\t\tprotoEntries[i] = &protobuf.ProtoAppendEntriesRequest_ProtoLogEntry{\n\t\t\tIndex: proto.Uint64(entry.Index),\n\t\t\tTerm: proto.Uint64(entry.Term),\n\t\t\tCommandName: proto.String(entry.CommandName),\n\t\t\tCommand: entry.Command,\n\t\t}\n\t}\n\n\tpb := &protobuf.ProtoAppendEntriesRequest{\n\t\tTerm: proto.Uint64(req.Term),\n\t\tPrevLogIndex: proto.Uint64(req.PrevLogIndex),\n\t\tPrevLogTerm: proto.Uint64(req.PrevLogTerm),\n\t\tCommitIndex: proto.Uint64(req.CommitIndex),\n\t\tLeaderName: proto.String(req.LeaderName),\n\t\tEntries: protoEntries,\n\t}\n\n\tp, err := proto.Marshal(pb)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn w.Write(p)\n}", "func (u *uploader) uploadEntries(done <-chan struct{}, entries <-chan files.TreeEntry, result chan<- string) {\n\tfor entry := range entries {\n\t\tselect {\n\t\tcase result <- u.uploadEntry(entry):\n\t\tcase <-done:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (o *UpdateZoneProjectsUsingPUTParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (c *OutputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewDeployRequestWithoutParam() *DeployRequest {\n\n return &DeployRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/scenes/{sceneId}/deployments\",\n Method: \"POST\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}", "func NewLoginOK() *LoginOK {\n\treturn &LoginOK{}\n}", "func (c *InputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewUpdateMTOPostCounselingInformationOK() *UpdateMTOPostCounselingInformationOK {\n\treturn &UpdateMTOPostCounselingInformationOK{}\n}", "func (o *SearchWorkspacesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\tif o.Body != nil {\n\t\tif err := r.SetBodyParam(o.Body); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (c *Client) newRequest(method, path string, v interface{}, ctype string) (req *http.Request, err error) {\n\t// Build request JSON.\n\tbody, err := writeJson(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err = http.NewRequest(method, c.pathToEndPoint(path), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"X-Kii-AppID\", c.AppId)\n\treq.Header.Add(\"X-Kii-AppKey\", c.AppKey)\n\tif ctype != \"\" {\n\t\treq.Header.Add(\"Content-Type\", ctype)\n\t}\n\tif c.Authorization != \"\" {\n\t\treq.Header.Add(\"Authorization\", c.Authorization)\n\t}\n\treturn\n}", "func NewSearchBucket()(*SearchBucket) {\n m := &SearchBucket{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s PathReply) NewEntries(n int32) (PathReplyEntry_List, error) {\n\tl, err := NewPathReplyEntry_List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn PathReplyEntry_List{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func CreateQueryWorksRequest() (request *QueryWorksRequest) {\n\trequest = &QueryWorksRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"quickbi-public\", \"2022-01-01\", \"QueryWorks\", \"2.2.0\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func lsifUploadOptions(out *output.Output) upload.UploadOptions {\n\tvar associatedIndexID *int\n\tif lsifUploadFlags.associatedIndexID != -1 {\n\t\tassociatedIndexID = &lsifUploadFlags.associatedIndexID\n\t}\n\n\tlogger := upload.NewRequestLogger(\n\t\tos.Stdout,\n\t\t// Don't need to check upper bounds as we only compare verbosity ranges\n\t\t// It's fine if someone supplies -trace=42, but it will just behave the\n\t\t// same as if they supplied the highest verbosity level we define\n\t\t// internally.\n\t\tupload.RequestLoggerVerbosity(lsifUploadFlags.verbosity),\n\t)\n\n\treturn upload.UploadOptions{\n\t\tUploadRecordOptions: upload.UploadRecordOptions{\n\t\t\tRepo: lsifUploadFlags.repo,\n\t\t\tCommit: lsifUploadFlags.commit,\n\t\t\tRoot: lsifUploadFlags.root,\n\t\t\tIndexer: lsifUploadFlags.indexer,\n\t\t\tAssociatedIndexID: associatedIndexID,\n\t\t},\n\t\tSourcegraphInstanceOptions: upload.SourcegraphInstanceOptions{\n\t\t\tSourcegraphURL: cfg.Endpoint,\n\t\t\tAccessToken: cfg.AccessToken,\n\t\t\tAdditionalHeaders: cfg.AdditionalHeaders,\n\t\t\tMaxRetries: 5,\n\t\t\tRetryInterval: time.Second,\n\t\t\tPath: lsifUploadFlags.uploadRoute,\n\t\t\tGitHubToken: lsifUploadFlags.gitHubToken,\n\t\t\tMaxPayloadSizeBytes: lsifUploadFlags.maxPayloadSizeMb * 1000 * 1000,\n\t\t},\n\t\tOutputOptions: upload.OutputOptions{\n\t\t\tOutput: out,\n\t\t\tLogger: logger,\n\t\t},\n\t}\n}", "func NewCreateanewPreferencesMetaEntryRequest(server string, body CreateanewPreferencesMetaEntryJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewPreferencesMetaEntryRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (c *InputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewWatchStorageV1CSINodeListOK() *WatchStorageV1CSINodeListOK {\n\treturn &WatchStorageV1CSINodeListOK{}\n}", "func TestUpload(t *testing.T) {\n\toss := NewService(\"<<api key>>\", \"<<secret key>>\")\n\toss.SetEndPoint(\"oss-cn-shanghai.aliyuncs.com\")\n\toss.SetBucket(\"dong-feng\")\n\n\topts1 := &UploadOptions{\n\t\tObjectName: \"test\",\n\t\tPublic: true,\n\t\tIsFolder: true,\n\t}\n\n\tresp := oss.Upload(opts1)\n\tif resp.Error != nil {\n\t\tt.Error(resp.Error)\n\t}\n\n\topts2 := &UploadOptions{\n\t\tObjectName: \"../test/index.html\",\n\t\tPublic: true,\n\t\tParentFolder: \"test\",\n\t}\n\n\tresp = oss.Upload(opts2)\n\tif resp.Error != nil {\n\t\tt.Error(resp.Error)\n\t}\n}", "func (c *InputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (client *ReplicationvCentersClient) listCreateRequest(ctx context.Context, options *ReplicationvCentersClientListOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationvCenters\"\n\tif client.resourceName == \"\" {\n\t\treturn nil, errors.New(\"parameter client.resourceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceName}\", url.PathEscape(client.resourceName))\n\tif client.resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter client.resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(client.resourceGroupName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewJobsListOK() *JobsListOK {\n\treturn &JobsListOK{}\n}", "func NewSharePostRequestBody()(*SharePostRequestBody) {\n m := &SharePostRequestBody{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func NewCreateClusterRequestWithoutParam() *CreateClusterRequest {\n\n return &CreateClusterRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/regions/{regionId}/clusters\",\n Method: \"POST\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}", "func NewSolutionsRoot()(*SolutionsRoot) {\n m := &SolutionsRoot{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (s *HsmProvidersService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (client OpenShiftManagedClustersClient) CreateOrUpdateAndWait(ctx context.Context, resourceGroupName, resourceName string, parameters v20180930preview.OpenShiftManagedCluster) (osmc v20180930preview.OpenShiftManagedCluster, err error) {\n\tvar future OpenShiftManagedClustersCreateOrUpdateFuture\n\tfuture, err = client.CreateOrUpdate(ctx, resourceGroupName, resourceName, parameters)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = future.WaitForCompletionRef(ctx, client.Client); err != nil {\n\t\treturn\n\t}\n\treturn future.Result(client)\n}", "func (c *OutputService9ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewGetTopupLogitemsRequest(server string, params *GetTopupLogitemsParams) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/topuplogs\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryValues := queryUrl.Query()\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"reseller_id\", params.ResellerId); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"request_token\", params.RequestToken); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"timestamp_from\", params.TimestampFrom); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"timestamp_to\", params.TimestampTo); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"contract_id\", params.ContractId); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"subscriber_id\", params.SubscriberId); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"voucher_id\", params.VoucherId); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"outcome\", params.Outcome); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"amount_above\", params.AmountAbove); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"amount_below\", params.AmountBelow); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"order_by\", params.OrderBy); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"order_by_direction\", params.OrderByDirection); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"page\", params.Page); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"rows\", params.Rows); err != nil {\n\t\treturn nil, err\n\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tfor k, v := range parsed {\n\t\t\tfor _, v2 := range v {\n\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t}\n\t\t}\n\t}\n\n\tqueryUrl.RawQuery = queryValues.Encode()\n\n\treq, err := http.NewRequest(\"GET\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func NewHeaders()(*Headers) {\n m := &Headers{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n decoder := json.NewDecoder(r.Body)\n var ecsBucket ECSBucket\n err := decoder.Decode(&ecsBucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n headers := make(map[string][]string)\n if ecsBucket.ReplicationGroup != \"\" {\n headers[\"x-emc-vpool\"] = []string{ecsBucket.ReplicationGroup}\n }\n if ecsBucket.MetadataSearch != \"\" {\n headers[\"x-emc-metadata-search\"] = []string{ecsBucket.MetadataSearch}\n }\n if ecsBucket.EnableADO {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"false\"}\n }\n if ecsBucket.EnableFS {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableCompliance {\n headers[\"x-emc-compliance-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-compliance-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableEncryption {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"false\"}\n }\n var bucketCreateResponse Response\n if ecsBucket.Api == \"s3\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = s3Request(s3, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n if bucketCreateResponse.Code == 200 {\n rendering.JSON(w, http.StatusOK, ecsBucket.Name)\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"swift\" {\n bucketCreateResponse, err = swiftRequest(ecsBucket.Endpoint, ecsBucket.User, ecsBucket.Password, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n log.Print(bucketCreateResponse)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, ecsBucket.Name)\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"atmos\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = atmosRequest(ecsBucket.Endpoint, s3.AccessKey, s3.SecretKey, \"\", \"PUT\", \"/rest/subtenant\", headers, \"\")\n if err != nil {\n log.Print(err)\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, bucketCreateResponse.ResponseHeaders[\"Subtenantid\"][0])\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n }\n\n return nil\n}", "func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (p *Newest) CreateEntries(entries ...upstream.Entry) ([]upstream.Entry, error) {\n\tif len(entries) == 0 {\n\t\treturn nil, fs.ErrorObjectNotFound\n\t}\n\tentries = filterNCEntries(entries)\n\tif len(entries) == 0 {\n\t\treturn nil, fs.ErrorPermissionDenied\n\t}\n\te, err := p.newestEntries(entries)\n\treturn []upstream.Entry{e}, err\n}", "func NewSendMessagesByPinUsingPOSTRequestWithoutParam() *SendMessagesByPinUsingPOSTRequest {\n\n return &SendMessagesByPinUsingPOSTRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/sendMessagesByPin\",\n Method: \"POST\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceFdbMacTableEntries(ctx context.Context, name string, frinxOpenconfigNetworkInstanceL2nimactabletopMactableEntriesBodyParam FrinxOpenconfigNetworkInstanceL2nimactabletopMactableEntriesRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:fdb/frinx-openconfig-network-instance:mac-table/frinx-openconfig-network-instance:entries/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\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/xml\"}\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 = &frinxOpenconfigNetworkInstanceL2nimactabletopMactableEntriesBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, 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\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (s *AuthnReqListsService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewListSiteFilesOK() *ListSiteFilesOK {\n\treturn &ListSiteFilesOK{}\n}", "func CreateInstallLogstashSystemPluginRequest() (request *InstallLogstashSystemPluginRequest) {\n\trequest = &InstallLogstashSystemPluginRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"elasticsearch\", \"2017-06-13\", \"InstallLogstashSystemPlugin\", \"/openapi/logstashes/[InstanceId]/plugins/system/actions/install\", \"elasticsearch\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceFdbMacTableEntriesEntryInterface(ctx context.Context, name string, macAddress string, frinxOpenconfigNetworkInstanceL2nimactabletopMactableEntriesEntryInterfaceBodyParam FrinxOpenconfigNetworkInstanceL2nimactabletopMactableEntriesEntryInterfaceRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:fdb/frinx-openconfig-network-instance:mac-table/frinx-openconfig-network-instance:entries/frinx-openconfig-network-instance:entry/{mac-address}/frinx-openconfig-network-instance:interface/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"mac-address\"+\"}\", fmt.Sprintf(\"%v\", macAddress), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\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/xml\"}\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 = &frinxOpenconfigNetworkInstanceL2nimactabletopMactableEntriesEntryInterfaceBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, 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\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func NewCreateanewPreferencesMetaEntryRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/preferencesmetaentries\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", queryUrl.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\treturn req, nil\n}", "func newfileUploadRequest(uri string, headers map[string]string, paramName, path string) (*http.Request, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tbody := &bytes.Buffer{}\n\twriter := multipart.NewWriter(body)\n\n\tpart, err := writer.CreateFormFile(paramName, filepath.Base(path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = io.Copy(part, file)\n\n\terr = writer.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest, err := http.NewRequest(\"POST\", uri, body)\n\n\trequest.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\n\tif headers != nil {\n\t\tfor key, val := range headers {\n\t\t\trequest.Header.Add(key, val)\n\t\t}\n\t}\n\n\treturn request, err\n}", "func (c *InputService9ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func InitAWSMpUpload(filehash string, filename string) string {\n\t// sess := GetSession()\n\t// svc := s3.New(sess)\n\tinput := &s3.CreateMultipartUploadInput{\n\t\tBucket: aws.String(AWSS3Bucket),\n\t\tKey: aws.String(filehash),\n\t\tContentDisposition: aws.String(\"attachment;filename=\\\"\" + filename + \"\\\"\"),\n\t}\n\n\tresult, err := svc.CreateMultipartUpload(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t\tpanic(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\n\treturn aws.StringValue(result.UploadId)\n}", "func NewPutMenuItemOK() *PutMenuItemOK {\n\treturn &PutMenuItemOK{}\n}", "func newfileUploadRequest(uri string, params map[string]string, paramName, filePath string) (*http.Request, error) {\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\tfmt.Println(\"filepath.Base(filePath)=\", filepath.Base(filePath))\n\n\tbody := &bytes.Buffer{}\n\twriter := multipart.NewWriter(body)\n\t// part, err := writer.CreateFormFile(paramName, filepath.Base(filePath))\n\t// if err != nil {\n\t// \tfmt.Println(\"create form file failed, err=\", err)\n\t// \treturn nil, err\n\t// }\n\t// _, err = io.Copy(part, file)\n\n\tfor key, val := range params {\n\t\t_ = writer.WriteField(key, val)\n\t}\n\n\tpart, err := writer.CreateFormFile(paramName, filepath.Base(filePath))\n\tif err != nil {\n\t\tfmt.Println(\"create form file failed, err=\", err)\n\t\treturn nil, err\n\t}\n\t_, err = io.Copy(part, file)\n\n\terr = writer.Close()\n\tif err != nil {\n\t\tfmt.Println(\"writer close failed, err=\", err)\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", uri, body)\n\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\tfmt.Println(\"writer.FormDataContentType()=\", writer.FormDataContentType())\n\treturn req, err\n}", "func (m *Miner) createWork() {\n\t//Register a function to clear the generated work if a job gets deprecated.\n\t// It does not matter if we clear too many, it is worse to work on a stale job.\n\tm.Client.SetDeprecatedJobCall(func() {\n\t\tnumberOfWorkItemsToRemove := len(m.miningWorkChannel)\n\t\tfor i := 0; i <= numberOfWorkItemsToRemove; i++ {\n\t\t\t<-m.miningWorkChannel\n\t\t}\n\t})\n\n\tm.Client.Start()\n\n\tfor {\n\t\ttarget, header, deprecationChannel, job, err := m.Client.GetHeaderForWork()\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROR fetching work -\", err)\n\t\t\ttime.Sleep(1000 * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\n\t\t//copy target to header\n\t\tfor i := 0; i < 8; i++ {\n\t\t\t// Re: why not 32 bytes for target? Only the first 6 bytes of the target\n\t\t\t// matter. The other 2 are a buffer. We won't need more than that unless\n\t\t\t// the hashrate increases by about 100,000x the current hashrate.\n\t\t\t// https://git.io/fx7bN\n\t\t\theader[i+32] = target[7-i]\n\t\t}\n\n\t\t//Fill the workchannel with work\n\t\t// Only generate nonces for a 32 bit space (since gpu's are mostly 32 bit)\n\tnonce32loop:\n\t\tfor i := int64(0); i * int64(m.GlobalItemSize) < (maxUint32 - int64(m.GlobalItemSize)); i++ {\n\t\t\t//Do not continue mining the 32 bit nonce space if the current job is deprecated\n\t\t\tselect {\n\t\t\tcase <-deprecationChannel:\n\t\t\t\tbreak nonce32loop\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tm.miningWorkChannel <- &miningWork{header, int(i) * m.GlobalItemSize, job}\n\t\t}\n\t}\n}", "func NewJWK(jwk map[string]interface{}) JWK {\n\treturn jwk\n}", "func (o *ListMachineDeploymentNodesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\t// path param cluster_id\n\tif err := r.SetPathParam(\"cluster_id\", o.ClusterID); err != nil {\n\t\treturn err\n\t}\n\n\tif o.HideInitialConditions != nil {\n\n\t\t// query param hideInitialConditions\n\t\tvar qrHideInitialConditions bool\n\n\t\tif o.HideInitialConditions != nil {\n\t\t\tqrHideInitialConditions = *o.HideInitialConditions\n\t\t}\n\t\tqHideInitialConditions := swag.FormatBool(qrHideInitialConditions)\n\t\tif qHideInitialConditions != \"\" {\n\n\t\t\tif err := r.SetQueryParam(\"hideInitialConditions\", qHideInitialConditions); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// path param machinedeployment_id\n\tif err := r.SetPathParam(\"machinedeployment_id\", o.MachineDeploymentID); err != nil {\n\t\treturn err\n\t}\n\n\t// path param project_id\n\tif err := r.SetPathParam(\"project_id\", o.ProjectID); 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 newfileUploadRequest(uri string, params map[string]string, paramName, xmlString string) (*http.Request, error) {\n\n\tbXml:=strings.NewReader(xmlString)\n\n\tbody := &bytes.Buffer{}\n\twriter := multipart.NewWriter(body)\n hs,_:=hash_string_md5(xmlString)\n finename := \"DFEServicioConsulta_\"+ strings.ToUpper(hs) +\".XML\"\n\txmlFile, _ := CreateXML(writer, finename)\n\n\t_, err := io.Copy(xmlFile, bXml)\n\n\tfor key, val := range params {\n\t\t_ = writer.WriteField(key, val)\n\t}\n\terr = writer.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\n\n\treq, err := http.NewRequest(\"POST\", uri, body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\n\treturn req, err\n}", "func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *Service) JWKS(w http.ResponseWriter, r *http.Request) {\n\tkeys := s.signer.PublicKeys()\n\tb, err := json.Marshal(keys)\n\tif err != nil {\n\t\thttputils.WriteError(w, status.Errorf(codes.Unavailable, \"writing jwks to json: %v\", err))\n\t\treturn\n\t}\n\tw.Write(b)\n}", "func NewAddItemOK() *AddItemOK {\n\n\treturn &AddItemOK{}\n}", "func (client OpenShiftManagedClustersClient) CreateOrUpdateSender(req *http.Request) (future OpenShiftManagedClustersCreateOrUpdateFuture, err error) {\n\tvar resp *http.Response\n\tresp, err = autorest.SendWithSender(client, req,\n\t\tazure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\terr = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))\n\tif err != nil {\n\t\treturn\n\t}\n\tfuture.Future, err = azure.NewFutureFromResponse(resp)\n\treturn\n}", "func NewPutRecordingsOK() *PutRecordingsOK {\n\n\treturn &PutRecordingsOK{}\n}", "func (p *FileInf) initResumableUpload(metadata map[string]interface{}) string {\r\n\ttokenparams := url.Values{}\r\n\ttokenparams.Set(\"fields\", \"id,mimeType,name,parents\")\r\n\tmeta, _ := json.Marshal(metadata)\r\n\tr := &RequestParams{\r\n\t\tMethod: \"POST\",\r\n\t\tAPIURL: resumableUrl + \"&\" + tokenparams.Encode(),\r\n\t\tData: bytes.NewBuffer(meta),\r\n\t\tContenttype: \"application/json; charset=UTF-8\",\r\n\t\tAccesstoken: p.Accesstoken,\r\n\t\tDtime: 10,\r\n\t}\r\n\tres, err := r.FetchAPIres()\r\n\tif res.StatusCode != 200 || err != nil {\r\n\t\tfmt.Fprintf(os.Stderr, \"Error: %v\\n%v\\n\", err, res)\r\n\t\tos.Exit(1)\r\n\t}\r\n\treturn res.Header[\"Location\"][0]\r\n}" ]
[ "0.58120656", "0.56020886", "0.48270583", "0.47020715", "0.45160374", "0.44535", "0.4308796", "0.42836794", "0.4243138", "0.42217743", "0.42198837", "0.42106935", "0.4207686", "0.41678897", "0.4166974", "0.41594934", "0.4156131", "0.4155134", "0.4147959", "0.41451487", "0.41359693", "0.41283166", "0.41195405", "0.4107208", "0.40889344", "0.4087922", "0.40706316", "0.40639865", "0.40569788", "0.40342027", "0.40326947", "0.40312344", "0.40312344", "0.40205455", "0.40178823", "0.40092483", "0.3991735", "0.3986811", "0.3983936", "0.39802516", "0.39768866", "0.39768866", "0.39721856", "0.39720717", "0.39717177", "0.39685223", "0.39587077", "0.3957139", "0.3955098", "0.3951181", "0.3951181", "0.39502513", "0.3947993", "0.39449844", "0.39419064", "0.39335912", "0.39281818", "0.3927381", "0.39130554", "0.39127743", "0.3909195", "0.3909195", "0.3900963", "0.3900963", "0.38995573", "0.3890442", "0.38882864", "0.3886104", "0.3880264", "0.38771862", "0.387656", "0.38720545", "0.38709238", "0.38693205", "0.38665953", "0.38665953", "0.38615236", "0.38597783", "0.38594362", "0.38585147", "0.3853683", "0.38529134", "0.3850922", "0.38490292", "0.38488308", "0.3845154", "0.3840638", "0.38371524", "0.3836516", "0.38354826", "0.38324845", "0.3829433", "0.38276702", "0.38266373", "0.38266373", "0.38132116", "0.3812189", "0.38105103", "0.38091084", "0.38063264" ]
0.72544926
0
NewUploadWorkstationJposEntriesBadRequest creates a UploadWorkstationJposEntriesBadRequest with default headers values
func NewUploadWorkstationJposEntriesBadRequest() *UploadWorkstationJposEntriesBadRequest { return &UploadWorkstationJposEntriesBadRequest{} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewDeleteHardwareProfileJposEntriesBadRequest() *DeleteHardwareProfileJposEntriesBadRequest {\n\treturn &DeleteHardwareProfileJposEntriesBadRequest{}\n}", "func NewUploadWorkstationJposEntriesNotFound() *UploadWorkstationJposEntriesNotFound {\n\treturn &UploadWorkstationJposEntriesNotFound{}\n}", "func NewAddEntriesBadRequest() *AddEntriesBadRequest {\n\treturn &AddEntriesBadRequest{}\n}", "func NewNewThreadBadRequest() *NewThreadBadRequest {\n\treturn &NewThreadBadRequest{}\n}", "func NewListSelLogServiceEntriesBadRequest() *ListSelLogServiceEntriesBadRequest {\n\treturn &ListSelLogServiceEntriesBadRequest{}\n}", "func NewThingsListBadRequest() *ThingsListBadRequest {\n\treturn &ThingsListBadRequest{}\n}", "func NewUploadWorkstationJposEntriesOK() *UploadWorkstationJposEntriesOK {\n\treturn &UploadWorkstationJposEntriesOK{}\n}", "func NewWeaviateThingsPatchBadRequest() *WeaviateThingsPatchBadRequest {\n\treturn &WeaviateThingsPatchBadRequest{}\n}", "func NewMoveClustersBadRequest() *MoveClustersBadRequest {\n\treturn &MoveClustersBadRequest{}\n}", "func SetNewBadRequestByFormat(ef *ErrorFormat) *ErrorMessage {\n\treturn &ErrorMessage{\n\t\tCode: http.StatusBadRequest,\n\t\tErrorList: []*ErrorFormat{\n\t\t\tef,\n\t\t},\n\t}\n}", "func NewCreateInternationalStandingOrdersBadRequest() *CreateInternationalStandingOrdersBadRequest {\n\treturn &CreateInternationalStandingOrdersBadRequest{}\n}", "func NewAllDashboardsBadRequest() *AllDashboardsBadRequest {\n return &AllDashboardsBadRequest{\n }\n}", "func NewIndexMachinePolicyWorkersBadRequest() *IndexMachinePolicyWorkersBadRequest {\n\treturn &IndexMachinePolicyWorkersBadRequest{}\n}", "func NewCreateWaitlistEntryBadRequest(body *CreateWaitlistEntryBadRequestResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func (client *LROSADsClient) putNonRetry201Creating400InvalidJSONCreateRequest(ctx context.Context, product Product, options *LROSADsClientBeginPutNonRetry201Creating400InvalidJSONOptions) (*policy.Request, error) {\n\turlPath := \"/lro/nonretryerror/put/201/creating/400/invalidjson\"\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\tif err := runtime.MarshalAsJSON(req, product); err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func NewGetEntriesBadRequest() *GetEntriesBadRequest {\n\treturn &GetEntriesBadRequest{}\n}", "func NewCreateOrUpdateAWSSettingsBadRequest() *CreateOrUpdateAWSSettingsBadRequest {\n\treturn &CreateOrUpdateAWSSettingsBadRequest{}\n}", "func NewFolderLooksBadRequest() *FolderLooksBadRequest {\n\treturn &FolderLooksBadRequest{}\n}", "func NewWeaviateActionsPatchBadRequest() *WeaviateActionsPatchBadRequest {\n\n\treturn &WeaviateActionsPatchBadRequest{}\n}", "func NewArtifactListerBadRequest() *ArtifactListerBadRequest {\n\n\treturn &ArtifactListerBadRequest{}\n}", "func NewAddItemBadRequest() *AddItemBadRequest {\n\n\treturn &AddItemBadRequest{}\n}", "func NewUpdateHostIgnitionBadRequest() *UpdateHostIgnitionBadRequest {\n\n\treturn &UpdateHostIgnitionBadRequest{}\n}", "func NewIntegrationBadRequest() *IntegrationBadRequest {\n\treturn &IntegrationBadRequest{}\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n decoder := json.NewDecoder(r.Body)\n var ecsBucket ECSBucket\n err := decoder.Decode(&ecsBucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n headers := make(map[string][]string)\n if ecsBucket.ReplicationGroup != \"\" {\n headers[\"x-emc-vpool\"] = []string{ecsBucket.ReplicationGroup}\n }\n if ecsBucket.MetadataSearch != \"\" {\n headers[\"x-emc-metadata-search\"] = []string{ecsBucket.MetadataSearch}\n }\n if ecsBucket.EnableADO {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"false\"}\n }\n if ecsBucket.EnableFS {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableCompliance {\n headers[\"x-emc-compliance-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-compliance-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableEncryption {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"false\"}\n }\n retentionEnabled := false\n headers[\"x-emc-retention-period\"] = []string{\"0\"}\n if ecsBucket.Retention != \"\" {\n days, err := strconv.ParseInt(ecsBucket.Retention, 10, 64)\n if err == nil {\n if days > 0 {\n seconds := days * 24 * 3600\n headers[\"x-emc-retention-period\"] = []string{int64toString(seconds)}\n retentionEnabled = true\n }\n }\n }\n var expirationCurrentVersions int64\n expirationCurrentVersions = 0\n if ecsBucket.ExpirationCurrentVersions != \"\" {\n days, err := strconv.ParseInt(ecsBucket.ExpirationCurrentVersions, 10, 64)\n if err == nil {\n expirationCurrentVersions = days\n }\n }\n var expirationNonCurrentVersions int64\n expirationNonCurrentVersions = 0\n if ecsBucket.ExpirationNonCurrentVersions != \"\" {\n days, err := strconv.ParseInt(ecsBucket.ExpirationNonCurrentVersions, 10, 64)\n if err == nil && ecsBucket.EnableVersioning {\n expirationNonCurrentVersions = days\n }\n }\n var bucketCreateResponse Response\n if ecsBucket.Api == \"s3\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = s3Request(s3, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n versioningStatusOK := true\n lifecyclePolicyStatusOK := true\n // If the bucket has been created\n if bucketCreateResponse.Code == 200 {\n if !retentionEnabled && ecsBucket.EnableVersioning {\n // Enable versioning\n enableVersioningHeaders := map[string][]string{}\n enableVersioningHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n versioningConfiguration := `\n <VersioningConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n <Status>Enabled</Status>\n <MfaDelete>Disabled</MfaDelete>\n </VersioningConfiguration>\n `\n enableVersioningResponse, _ := s3Request(s3, ecsBucket.Name, \"PUT\", \"/?versioning\", enableVersioningHeaders, versioningConfiguration)\n if enableVersioningResponse.Code != 200 {\n versioningStatusOK = false\n }\n }\n if expirationCurrentVersions > 0 || expirationNonCurrentVersions > 0 {\n lifecyclePolicyHeaders := map[string][]string{}\n lifecyclePolicyHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n lifecyclePolicyConfiguration := `\n <LifecycleConfiguration>\n <Rule>\n <ID>expiration</ID>\n <Prefix></Prefix>\n <Status>Enabled</Status>\n `\n if expirationCurrentVersions > 0 && expirationNonCurrentVersions > 0 {\n // Enable expiration for both current and non current versions\n lifecyclePolicyConfiguration += \"<Expiration><Days>\" + ecsBucket.ExpirationCurrentVersions + \"</Days></Expiration>\"\n lifecyclePolicyConfiguration += \"<NoncurrentVersionExpiration><NoncurrentDays>\" + ecsBucket.ExpirationNonCurrentVersions + \"</NoncurrentDays></NoncurrentVersionExpiration>\"\n } else {\n if expirationCurrentVersions > 0 {\n // Enable expiration for current versions only\n lifecyclePolicyConfiguration += \"<Expiration><Days>\" + ecsBucket.ExpirationCurrentVersions + \"</Days></Expiration>\"\n }\n if expirationNonCurrentVersions > 0 {\n // Enable expiration for non current versions only\n // To fix a bug in ECS 3.0 where an expiration for non current version can't be set if there's no expiration set for current versions\n lifecyclePolicyConfiguration += \"<Expiration><Days>1000000</Days></Expiration>\"\n lifecyclePolicyConfiguration += \"<NoncurrentVersionExpiration><NoncurrentDays>\" + ecsBucket.ExpirationNonCurrentVersions + \"</NoncurrentDays></NoncurrentVersionExpiration>\"\n }\n }\n lifecyclePolicyConfiguration += `\n </Rule>\n </LifecycleConfiguration>\n `\n lifecyclePolicyResponse, _ := s3Request(s3, ecsBucket.Name, \"PUT\", \"/?lifecycle\", lifecyclePolicyHeaders, lifecyclePolicyConfiguration)\n if lifecyclePolicyResponse.Code != 200 {\n lifecyclePolicyStatusOK = false\n }\n }\n if versioningStatusOK && lifecyclePolicyStatusOK {\n rendering.JSON(w, http.StatusOK, \"\")\n } else {\n message := \"\"\n if !versioningStatusOK {\n message += \" Versioning can't be enabled.\"\n }\n if !lifecyclePolicyStatusOK {\n message += \" Expiration can't be set.\"\n }\n rendering.JSON(w, http.StatusOK, message)\n }\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"swift\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = swiftRequest(ecsBucket.Endpoint, s3.AccessKey, ecsBucket.Password, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, ecsBucket.Name)\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"atmos\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = atmosRequest(ecsBucket.Endpoint, s3.AccessKey, s3.SecretKey, \"\", \"PUT\", \"/rest/subtenant\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, bucketCreateResponse.ResponseHeaders[\"Subtenantid\"][0])\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n }\n\n return nil\n}", "func NewListBadRequest(body *ListBadRequestResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NewGetSovereigntyStructuresBadRequest() *GetSovereigntyStructuresBadRequest {\n\treturn &GetSovereigntyStructuresBadRequest{}\n}", "func NewSyncSteamInventoryBadRequest() *SyncSteamInventoryBadRequest {\n\treturn &SyncSteamInventoryBadRequest{}\n}", "func (ctx *CreateItemContext) BadRequest(r error) error {\n\tif ctx.ResponseData.Header().Get(\"Content-Type\") == \"\" {\n\t\tctx.ResponseData.Header().Set(\"Content-Type\", \"application/vnd.goa.error\")\n\t}\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 400, r)\n}", "func TestEmployeeManagerMapCreate_BadRequest(t *testing.T) {\n\tdb, _, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\templyManagerMap := NewEmployeeManagerMapHandler(db)\n\n\tw := httptest.NewRecorder()\n\tvar jsonStr = []byte(`{\"invalidjson\":}`)\n\tr := httptest.NewRequest(\"POST\", \"http://localhost:9090/api/v1/emplymgrmap\", bytes.NewBuffer(jsonStr))\n\tr = r.WithContext(context.Background())\n\templyManagerMap.Create(w, r)\n\n\texpectedResponse := `{\"error_message\":\"Error:: Invalid Request\"}`\n\tassert.Equal(t, gohttp.StatusBadRequest, w.Code)\n\tassert.Equal(t, expectedResponse, w.Body.String())\n}", "func NewPutMenuItemBadRequest() *PutMenuItemBadRequest {\n\treturn &PutMenuItemBadRequest{}\n}", "func NewBadRequest(err error, msg ...string) *Errs {\n\tif err == nil {\n\t\terr = ErrBadRequest\n\t}\n\n\treturn &Errs{\n\t\tcodeHTTP: http.StatusBadRequest,\n\t\terr: err,\n\t\tkind: trace(2),\n\t\tmessage: msg,\n\t}\n}", "func NewListPrioritiesBadRequest() *ListPrioritiesBadRequest {\n\treturn &ListPrioritiesBadRequest{}\n}", "func ErrRequestHeaderFieldsTooLargef(format string, arguments ...interface{}) *Status {\n\treturn &Status{Code: http.StatusRequestHeaderFieldsTooLarge, Text: fmt.Sprintf(format, arguments...)}\n}", "func NewUploadMediaBadRequest(body *UploadMediaBadRequestResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func (ctx *CreateHostContext) BadRequest() error {\n\tctx.ResponseData.WriteHeader(400)\n\treturn nil\n}", "func BadRequest(format string, args ...interface{}) error {\n\treturn New(http.StatusBadRequest, format, args...)\n}", "func NewListDisksBadRequest() *ListDisksBadRequest {\n\treturn &ListDisksBadRequest{}\n}", "func NewDistributeContentLibraryVmtemplateClustersBadRequest() *DistributeContentLibraryVmtemplateClustersBadRequest {\n\treturn &DistributeContentLibraryVmtemplateClustersBadRequest{}\n}", "func NewAllTimezonesBadRequest() *AllTimezonesBadRequest {\n return &AllTimezonesBadRequest{\n }\n}", "func (ctx *UploadOpmlContext) BadRequest(r error) error {\n\tif ctx.ResponseData.Header().Get(\"Content-Type\") == \"\" {\n\t\tctx.ResponseData.Header().Set(\"Content-Type\", \"application/vnd.goa.error\")\n\t}\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 400, r)\n}", "func (client *LROSADsClient) putNonRetry201Creating400CreateRequest(ctx context.Context, product Product, options *LROSADsClientBeginPutNonRetry201Creating400Options) (*policy.Request, error) {\n\turlPath := \"/lro/nonretryerror/put/201/creating/400\"\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\tif err := runtime.MarshalAsJSON(req, product); err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func WrapWithRequestEntityTooLarge(cause error, parameters ...wparams.ParamStorer) Error {\n\treturn newGenericError(cause, DefaultRequestEntityTooLarge, wparams.NewParamStorer(parameters...))\n}", "func NewGetPresignedForClusterFilesBadRequest() *GetPresignedForClusterFilesBadRequest {\n\n\treturn &GetPresignedForClusterFilesBadRequest{}\n}", "func (client *LROSADsClient) post202NoLocationCreateRequest(ctx context.Context, options *LROSADsClientBeginPost202NoLocationOptions) (*policy.Request, error) {\n\turlPath := \"/lro/error/post/202/nolocation\"\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\tif options != nil && options.Product != nil {\n\t\tif err := runtime.MarshalAsJSON(req, *options.Product); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn req, nil\n\t}\n\treturn req, nil\n}", "func NewBadRequest(field string, message string, args ...interface{}) *AppError {\n\treturn NewError(InvalidArgument, field, message, args...)\n}", "func NewObjectsListBadRequest() *ObjectsListBadRequest {\n\n\treturn &ObjectsListBadRequest{}\n}", "func (client *LROSADsClient) post202RetryInvalidHeaderCreateRequest(ctx context.Context, options *LROSADsClientBeginPost202RetryInvalidHeaderOptions) (*policy.Request, error) {\n\turlPath := \"/lro/error/post/202/retry/invalidheader\"\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\tif options != nil && options.Product != nil {\n\t\tif err := runtime.MarshalAsJSON(req, *options.Product); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn req, nil\n\t}\n\treturn req, nil\n}", "func BadRequest(message ...interface{}) Err {\n\treturn Boomify(http.StatusBadRequest, message...)\n}", "func NewObjectsPatchBadRequest() *ObjectsPatchBadRequest {\n\n\treturn &ObjectsPatchBadRequest{}\n}", "func (client *LROSADsClient) put200InvalidJSONCreateRequest(ctx context.Context, product Product, options *LROSADsClientBeginPut200InvalidJSONOptions) (*policy.Request, error) {\n\turlPath := \"/lro/error/put/200/invalidjson\"\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\tif err := runtime.MarshalAsJSON(req, product); err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func NewIntegrationGetAllIntegrationsBadRequest() *IntegrationGetAllIntegrationsBadRequest {\n\treturn &IntegrationGetAllIntegrationsBadRequest{}\n}", "func NewRemoveContentLibraryImageClustersBadRequest() *RemoveContentLibraryImageClustersBadRequest {\n\treturn &RemoveContentLibraryImageClustersBadRequest{}\n}", "func (o *CreateOrUpdateAWSSettingsBadRequest) Code() int {\n\treturn 400\n}", "func ErrRequestEntityTooLargef(format string, arguments ...interface{}) *Status {\n\treturn &Status{Code: http.StatusRequestEntityTooLarge, Text: fmt.Sprintf(format, arguments...)}\n}", "func NewDeployRequestWithoutParam() *DeployRequest {\n\n return &DeployRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/scenes/{sceneId}/deployments\",\n Method: \"POST\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}", "func CreateBadRequest(errorMessage string) BadRequest {\n\treturn BadRequest{Error: errorMessage}\n}", "func (ctx *CreateSecretsContext) BadRequest() error {\n\tctx.ResponseData.WriteHeader(400)\n\treturn nil\n}", "func NewCountBadRequest() *CountBadRequest {\n\treturn &CountBadRequest{}\n}", "func NewSearchInventoryBadRequest() *SearchInventoryBadRequest {\n\treturn &SearchInventoryBadRequest{}\n}", "func invalid_request(w http.ResponseWriter, statCode int, message string){\n w.Header().Set(\"Content-Type\", \"application/json\")\n switch statCode {\n case 400: w.WriteHeader(http.StatusBadRequest)\n case 403: w.WriteHeader(http.StatusForbidden)\n case 404: w.WriteHeader(http.StatusNotFound)\n default: w.WriteHeader(http.StatusNotFound)\n }\n err := Error {\n StatusCode: statCode,\n ErrorMessage: message}\n json.NewEncoder(w).Encode(err)\n}", "func ErrBadRequestf(format string, arguments ...interface{}) *Status {\n\treturn &Status{Code: http.StatusBadRequest, Text: fmt.Sprintf(format, arguments...)}\n}", "func NewGetRecentFoodsBadRequest() *GetRecentFoodsBadRequest {\n\treturn &GetRecentFoodsBadRequest{}\n}", "func NewGetInstancesObjectsDefinitionsBadRequest() *GetInstancesObjectsDefinitionsBadRequest {\n\treturn &GetInstancesObjectsDefinitionsBadRequest{}\n}", "func (ctx *CreateOutputContext) BadRequest(r error) error {\n\tif ctx.ResponseData.Header().Get(\"Content-Type\") == \"\" {\n\t\tctx.ResponseData.Header().Set(\"Content-Type\", \"application/vnd.goa.error\")\n\t}\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 400, r)\n}", "func NewListLocalUserBadRequest() *ListLocalUserBadRequest {\n\treturn &ListLocalUserBadRequest{}\n}", "func NewPutWorkpaceByIDBadRequest() *PutWorkpaceByIDBadRequest {\n\n\treturn &PutWorkpaceByIDBadRequest{}\n}", "func NewListUserContributionsBadRequest() *ListUserContributionsBadRequest {\n\treturn &ListUserContributionsBadRequest{}\n}", "func NewSearchLooksBadRequest() *SearchLooksBadRequest {\n\treturn &SearchLooksBadRequest{}\n}", "func NewSearchMyRecipeGroupForRecipeBadRequest() *SearchMyRecipeGroupForRecipeBadRequest {\n\treturn &SearchMyRecipeGroupForRecipeBadRequest{}\n}", "func NewPatchApi24DirectoriesBadRequest() *PatchApi24DirectoriesBadRequest {\n\treturn &PatchApi24DirectoriesBadRequest{}\n}", "func NewReplicateBadRequest() *ReplicateBadRequest {\n\n\treturn &ReplicateBadRequest{}\n}", "func (ctx *CreateFeedContext) BadRequest(r error) error {\n\tif ctx.ResponseData.Header().Get(\"Content-Type\") == \"\" {\n\t\tctx.ResponseData.Header().Set(\"Content-Type\", \"application/vnd.goa.error\")\n\t}\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 400, r)\n}", "func (ctx *CreateMessageContext) BadRequest(r error) error {\n\tif ctx.ResponseData.Header().Get(\"Content-Type\") == \"\" {\n\t\tctx.ResponseData.Header().Set(\"Content-Type\", \"application/vnd.goa.error\")\n\t}\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 400, r)\n}", "func (ctx *ListMessageContext) BadRequest(r error) error {\n\tif ctx.ResponseData.Header().Get(\"Content-Type\") == \"\" {\n\t\tctx.ResponseData.Header().Set(\"Content-Type\", \"application/vnd.goa.error\")\n\t}\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 400, r)\n}", "func NewRequestEntityTooLarge(parameters ...wparams.ParamStorer) Error {\n\treturn newGenericError(nil, DefaultRequestEntityTooLarge, wparams.NewParamStorer(parameters...))\n}", "func ErrUnprocessableEntityf(format string, arguments ...interface{}) *Status {\n\treturn &Status{Code: http.StatusUnprocessableEntity, Text: fmt.Sprintf(format, arguments...)}\n}", "func NewListTransactionFilesBadRequest() *ListTransactionFilesBadRequest {\n\treturn &ListTransactionFilesBadRequest{}\n}", "func NewAddBodyFatLogBadRequest() *AddBodyFatLogBadRequest {\n\treturn &AddBodyFatLogBadRequest{}\n}", "func NewHelloWorldBadRequest() *HelloWorldBadRequest {\n\treturn &HelloWorldBadRequest{}\n}", "func ValidateCreateWaitlistEntryBadRequestResponseBody(body *CreateWaitlistEntryBadRequestResponseBody) (err error) {\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Message == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"message\", \"body\"))\n\t}\n\tif body.Temporary == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"temporary\", \"body\"))\n\t}\n\tif body.Timeout == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"timeout\", \"body\"))\n\t}\n\tif body.Fault == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"fault\", \"body\"))\n\t}\n\treturn\n}", "func HS400(w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.Header().Set(\"Cache-Control\", \"no-cache,no-store\")\n\tw.WriteHeader(http.StatusBadRequest)\n\tw.Write([]byte(\"400 Bad Request\"))\n}", "func NewCancelLaunchBadRequest() *CancelLaunchBadRequest {\n\n\treturn &CancelLaunchBadRequest{}\n}", "func NewCreateWaitlistEntryNotImplemented(body *CreateWaitlistEntryNotImplementedResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NewCreateIntegrationBadRequest() *CreateIntegrationBadRequest {\n\treturn &CreateIntegrationBadRequest{}\n}", "func (e ErrUnsupportedAllocation) BadRequest() {}", "func (ij ErrInvalidJoin) BadRequest() {}", "func NewPatchMachineConfigurationBadRequest() *PatchMachineConfigurationBadRequest {\n\treturn &PatchMachineConfigurationBadRequest{}\n}", "func (o *MoveClustersBadRequest) Code() int {\n\treturn 400\n}", "func NewListEdgeClustersBadRequest() *ListEdgeClustersBadRequest {\n\treturn &ListEdgeClustersBadRequest{}\n}", "func NewListSystemProcessorsBadRequest() *ListSystemProcessorsBadRequest {\n\treturn &ListSystemProcessorsBadRequest{}\n}", "func (ctx *ListFeedContext) BadRequest(r error) error {\n\tif ctx.ResponseData.Header().Get(\"Content-Type\") == \"\" {\n\t\tctx.ResponseData.Header().Set(\"Content-Type\", \"application/vnd.goa.error\")\n\t}\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 400, r)\n}", "func NewAddBadRequest() *AddBadRequest {\n\treturn &AddBadRequest{}\n}", "func NewCreateLocationBadRequest() *CreateLocationBadRequest {\n\treturn &CreateLocationBadRequest{}\n}", "func (client *LROSADsClient) putAsyncRelativeRetryInvalidHeaderCreateRequest(ctx context.Context, product Product, options *LROSADsClientBeginPutAsyncRelativeRetryInvalidHeaderOptions) (*policy.Request, error) {\n\turlPath := \"/lro/error/putasync/retry/invalidheader\"\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\tif err := runtime.MarshalAsJSON(req, product); err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func NewCreateWaitlistEntryForbidden(body *CreateWaitlistEntryForbiddenResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func newAppendEntriesRequest(term uint64, prevLogIndex uint64, prevLogTerm uint64, commitIndex uint64, leaderName string, entries []*LogEntry) *AppendEntriesRequest {\n\treturn &AppendEntriesRequest{\n\t\tTerm: term,\n\t\tPrevLogIndex: prevLogIndex,\n\t\tPrevLogTerm: prevLogTerm,\n\t\tCommitIndex: commitIndex,\n\t\tLeaderName: leaderName,\n\t\tEntries: entries,\n\t}\n}", "func NewCreateWaitlistEntryTooManyRequests(body *CreateWaitlistEntryTooManyRequestsResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func HS400t(w http.ResponseWriter, errmsg string) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.Header().Set(\"Cache-Control\", \"no-cache,no-store\")\n\tw.WriteHeader(http.StatusBadRequest)\n\tw.Write([]byte(\"400 Bad Request: \" + errmsg))\n}", "func (ctx *PubPshbContext) BadRequest(r error) error {\n\tif ctx.ResponseData.Header().Get(\"Content-Type\") == \"\" {\n\t\tctx.ResponseData.Header().Set(\"Content-Type\", \"application/vnd.goa.error\")\n\t}\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 400, r)\n}", "func NewUserGroupListBadRequest() *UserGroupListBadRequest {\n\treturn &UserGroupListBadRequest{}\n}" ]
[ "0.5698449", "0.55090106", "0.5479071", "0.5344149", "0.52392775", "0.51587063", "0.5107721", "0.50884795", "0.50567716", "0.50399405", "0.50129634", "0.5005355", "0.4915207", "0.4905453", "0.4884739", "0.48438808", "0.48361212", "0.48330328", "0.4818166", "0.48128146", "0.4807197", "0.48040166", "0.4790071", "0.47825646", "0.4774135", "0.47644764", "0.476195", "0.47601968", "0.47296813", "0.47285074", "0.47164774", "0.46932608", "0.46841887", "0.46825346", "0.46668664", "0.46555346", "0.46500307", "0.46433622", "0.46271554", "0.46108824", "0.46043068", "0.46013767", "0.45930514", "0.45925146", "0.4586596", "0.4585197", "0.4581289", "0.4574716", "0.4568886", "0.45640403", "0.45602486", "0.45580536", "0.45556462", "0.4548528", "0.45479754", "0.45377332", "0.45359406", "0.45301086", "0.4528359", "0.45234272", "0.45135906", "0.4497835", "0.4490884", "0.44896185", "0.44864753", "0.44863933", "0.44760776", "0.44732776", "0.44700766", "0.44690308", "0.4465778", "0.4462914", "0.44617882", "0.4461595", "0.44567797", "0.44552302", "0.44513157", "0.44501728", "0.44410467", "0.4428289", "0.44244382", "0.4423361", "0.44149694", "0.44103974", "0.44097087", "0.44076502", "0.44074723", "0.4407403", "0.44073707", "0.44063598", "0.4406164", "0.44045606", "0.44004843", "0.43988553", "0.43937483", "0.4391631", "0.43841776", "0.43774885", "0.43758082", "0.43734002" ]
0.7274397
0
NewUploadWorkstationJposEntriesNotFound creates a UploadWorkstationJposEntriesNotFound with default headers values
func NewUploadWorkstationJposEntriesNotFound() *UploadWorkstationJposEntriesNotFound { return &UploadWorkstationJposEntriesNotFound{} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewUploadWorkstationJposEntriesOK() *UploadWorkstationJposEntriesOK {\n\treturn &UploadWorkstationJposEntriesOK{}\n}", "func NewAddEntriesNotFound() *AddEntriesNotFound {\n\treturn &AddEntriesNotFound{}\n}", "func NewUploadWorkstationJposEntriesBadRequest() *UploadWorkstationJposEntriesBadRequest {\n\treturn &UploadWorkstationJposEntriesBadRequest{}\n}", "func NewNotFound() error {\n\treturn requestError{\n\t\tClientError: ClientError{\n\t\t\tErrors: []clientErrorSubError{{Message: \"status code 404\"}},\n\t\t},\n\t}\n}", "func NewGetEntriesNotFound() *GetEntriesNotFound {\n\treturn &GetEntriesNotFound{}\n}", "func NewNotFound(parameters ...wparams.ParamStorer) Error {\n\treturn newGenericError(nil, DefaultNotFound, wparams.NewParamStorer(parameters...))\n}", "func NewNotFound(s string, v ...interface{}) error {\n\treturn asNotFound(fmt.Errorf(s, v...))\n}", "func WrapWithNotFound(cause error, parameters ...wparams.ParamStorer) Error {\n\treturn newGenericError(cause, DefaultNotFound, wparams.NewParamStorer(parameters...))\n}", "func NewThingsListNotFound() *ThingsListNotFound {\n\treturn &ThingsListNotFound{}\n}", "func NewNotFound(err error, msg ...string) *Errs {\n\tif err == nil {\n\t\terr = ErrNotFound\n\t}\n\treturn &Errs{\n\t\tcodeHTTP: http.StatusNotFound,\n\t\terr: err,\n\t\tkind: trace(2),\n\t\tmessage: msg,\n\t}\n}", "func NewWeaviateActionsPatchNotFound() *WeaviateActionsPatchNotFound {\n\n\treturn &WeaviateActionsPatchNotFound{}\n}", "func NewWeaviateThingsPatchNotFound() *WeaviateThingsPatchNotFound {\n\treturn &WeaviateThingsPatchNotFound{}\n}", "func NewObjectsPatchNotFound() *ObjectsPatchNotFound {\n\n\treturn &ObjectsPatchNotFound{}\n}", "func NewListSelLogServiceEntriesNotFound() *ListSelLogServiceEntriesNotFound {\n\treturn &ListSelLogServiceEntriesNotFound{}\n}", "func NotFound(w ResponseWriter, r *Request) {\n\tw.SetHeader(CodeNotFound, \"not found\")\n}", "func NewCreateInternationalStandingOrdersNotFound() *CreateInternationalStandingOrdersNotFound {\n\treturn &CreateInternationalStandingOrdersNotFound{}\n}", "func NotFound(w http.ResponseWriter, r *http.Request, h *render.Renderer) {\n\taccept := strings.Split(r.Header.Get(\"Accept\"), \",\")\n\taccept = append(accept, strings.Split(r.Header.Get(\"Content-Type\"), \",\")...)\n\n\tswitch {\n\tcase prefixInList(accept, ContentTypeHTML):\n\t\tm := TemplateMapFromContext(r.Context())\n\t\tm.Title(http.StatusText(http.StatusNotFound))\n\t\th.RenderHTMLStatus(w, http.StatusNotFound, \"404\", m)\n\tcase prefixInList(accept, ContentTypeJSON):\n\t\th.RenderJSON(w, http.StatusNotFound, http.StatusText(http.StatusNotFound))\n\tdefault:\n\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t}\n}", "func NewGetPresignedForClusterFilesNotFound() *GetPresignedForClusterFilesNotFound {\n\n\treturn &GetPresignedForClusterFilesNotFound{}\n}", "func notfound(out http.ResponseWriter, format string, args ...interface{}) {\n\tsend(http.StatusNotFound, out, format, args...)\n}", "func (r *Macross) NotFound(handlers ...Handler) {\n\tr.notFound = handlers\n\tr.notFoundHandlers = combineHandlers(r.handlers, r.notFound)\n}", "func NewNotFound(a Attributes) error {\n\tname, resource, err := extractResourceName(a)\n\tif err != nil {\n\t\treturn apierrors.NewInternalError(err)\n\t}\n\treturn apierrors.NewNotFound(resource, name)\n}", "func writeInsightNotFound(w http.ResponseWriter, str string) {\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tw.WriteHeader(http.StatusNotFound)\n\tio.WriteString(w, str)\n}", "func NewObjectsListNotFound() *ObjectsListNotFound {\n\n\treturn &ObjectsListNotFound{}\n}", "func notFound(w http.ResponseWriter, req *http.Request) {\n\t// w.Header().Set(\"Content-Type\", \"text/plain; charset=utf-8\")\n\tapiError := apirouter.ErrorFromRequest(req, fmt.Sprintf(\"404 occurred: %s\", req.RequestURI), \"Whoops - this request is not recognized\", http.StatusNotFound, http.StatusNotFound, \"\")\n\tapirouter.ReturnResponse(w, req, apiError.Code, apiError)\n}", "func NewThreadUpdateNotFound() *ThreadUpdateNotFound {\n\n\treturn &ThreadUpdateNotFound{}\n}", "func notFound(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\thttp.NotFound(w, req)\n}", "func NewCreateWaitlistEntryNotFound(body *CreateWaitlistEntryNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NotFound(format string, args ...interface{}) error {\n\targs = append(args, withDefaultMessage(NotFoundDefaultMsg))\n\treturn Errorf(http.StatusNotFound, format, args...)\n}", "func notFound(resp *ApiResponse, msg string) error {\n resp.StatusCode = http.StatusNotFound\n resp.Message = []byte(msg)\n resp.ErrorMessage = http.StatusText(http.StatusNotFound)\n\n return nil\n}", "func noFound(msg string) error {\n\treturn status.Error(codes.NotFound, msg)\n}", "func (ctx *GetLocationsContext) NotFound(r *Error) error {\n\tctx.ResponseData.Header().Set(\"Content-Type\", \"error\")\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 404, r)\n}", "func NewListTemplatesNotFound() *ListTemplatesNotFound {\n\treturn &ListTemplatesNotFound{}\n}", "func NotFound(w ResponseWriter, r *Request) { Error(w, \"404 page not found\", StatusNotFound) }", "func NewByNamespaceNotFound() *ByNamespaceNotFound {\n\treturn &ByNamespaceNotFound{}\n}", "func NewNotFound(name, group, resource string) error {\n\treturn errors.NewNotFound(schema.GroupResource{Group: group, Resource: resource}, name)\n}", "func NewGetRacksNotFound() *GetRacksNotFound {\n\treturn &GetRacksNotFound{}\n}", "func (c ApiWrapper) NotFound(msg string, objs ...interface{}) revel.Result {\n\treturn c.renderErrorString(404, fmt.Sprintf(msg, objs))\n}", "func notFound(w http.ResponseWriter) {\n\tt, err := template.ParseFiles(notFoundTemplatePath)\n\tif err != nil {\n\t\trlog.Errorf(\"could not load notfound template [%s]\", err.Error())\n\t\treturn\n\t}\n\tt.ExecuteTemplate(w, notFoundTemplate, nil)\n\treturn\n}", "func (ctx *PlayLocationsContext) NotFound(r *Error) error {\n\tctx.ResponseData.Header().Set(\"Content-Type\", \"error\")\n\treturn ctx.ResponseData.Service.Send(ctx.Context, 404, r)\n}", "func NewListByPathNotFound(body *ListByPathNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NewListByPathNotFound(body *ListByPathNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NewAddItemNotFound() *AddItemNotFound {\n\n\treturn &AddItemNotFound{}\n}", "func NewWeaviateThingsActionsListNotFound() *WeaviateThingsActionsListNotFound {\n\treturn &WeaviateThingsActionsListNotFound{}\n}", "func NewGetNicsNotFound() *GetNicsNotFound {\n\treturn &GetNicsNotFound{}\n}", "func NewUploadMediaNotFound(body *UploadMediaNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NewAllDashboardsNotFound() *AllDashboardsNotFound {\n return &AllDashboardsNotFound{\n }\n}", "func NewUpdateHostIgnitionNotFound() *UpdateHostIgnitionNotFound {\n\n\treturn &UpdateHostIgnitionNotFound{}\n}", "func NewNotFoundError(message string)*RestErr{\n\treturn &RestErr{\n\t\tMessage: message,\n\t\tStatus: http.StatusNotFound,\n\t\tError: \"Not Found\",\n\t}\n}", "func NotFound(w http.ResponseWriter, r *http.Request) {\n\tresponse := response.CreateResponse()\n\tresponse.SendDataWithStatusCode(w, \"not found\", http.StatusOK)\n}", "func AsNotFound(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn &notFoundError{err}\n}", "func NewIntegrationNotFound() *IntegrationNotFound {\n\treturn &IntegrationNotFound{}\n}", "func NewNotFound(msg string) error {\n\treturn &ELBError{\n\t\tmsg: msg,\n\t\tCode: http.StatusNotFound,\n\t}\n}", "func NewObjectsClassPutNotFound() *ObjectsClassPutNotFound {\n\n\treturn &ObjectsClassPutNotFound{}\n}", "func NotFound(w http.ResponseWriter, message ...interface{}) {\n\tboom(w, 404, message...)\n}", "func (ctx *StartFeedContext) NotFound() error {\n\tctx.ResponseData.WriteHeader(404)\n\treturn nil\n}", "func NewJudgeNotFound() *JudgeNotFound {\n\treturn &JudgeNotFound{}\n}", "func NewSchemaObjectsUpdateNotFound() *SchemaObjectsUpdateNotFound {\n\treturn &SchemaObjectsUpdateNotFound{}\n}", "func NotFound(message ...interface{}) Err {\n\treturn Boomify(http.StatusNotFound, message...)\n}", "func ERROR_TRX_NOT_FOUND(w http.ResponseWriter) {\n\tbuildForeignError(w, http.StatusNotFound, \"ERROR_TRX_NOT_FOUND\", \"\")\n}", "func NotFound(w http.ResponseWriter, r *http.Request) { Error(w, \"404 page not found\", http.StatusNotFound) }", "func NotFound(fn http.HandlerFunc) {\n\tinfoMutex.Lock()\n\tvestigo.CustomNotFoundHandlerFunc(fn)\n\tinfoMutex.Unlock()\n}", "func notFoundHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusNotFound)\n\n\twritten, err := json.Marshal(struct{ Message string }{Message: \"Bulamadık :(\"})\n\tif err != nil {\n\t\tbadImplementationHandler(w, r, err)\n\t}\n\t_, err = w.Write(written)\n\tif err != nil {\n\n\t\tbadImplementationHandler(w, r, err)\n\t}\n}", "func sitePageNotFound(s *data.Site, path string) *contentBuffers {\n\tvar cb contentBuffers\n\tcb.body.WriteString(\"Page not found at \" + path)\n\t// TODO: build the appropriate page for the site\n\treturn &cb\n}", "func (ctx *UpdateFeedContext) NotFound() error {\n\tctx.ResponseData.WriteHeader(404)\n\treturn nil\n}", "func NewNotFound() *AppError {\n\treturn NewNotFoundR(StatusText(NotFound))\n}", "func NewUpdateNotFound(body *UpdateNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NewUpdateNotFound(body *UpdateNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func (a *API) getNotFound(ctx context.Context, res *common.HttpResponseWriter) error {\n\tres.WriteHeader(http.StatusNotFound)\n\treturn nil\n}", "func ERROR_ASSET_NOT_FOUND(w http.ResponseWriter, payload string) {\n\tbuildForeignError(w, http.StatusNotFound, \"ERROR_ASSET_NOT_FOUND\", payload)\n}", "func (ctx *AddLinkWorkflowContext) NotFound() error {\n\tctx.ResponseData.WriteHeader(404)\n\treturn nil\n}", "func NewUpdateLocalizationTemplateNotFound() *UpdateLocalizationTemplateNotFound {\n\treturn &UpdateLocalizationTemplateNotFound{}\n}", "func SendKeyNotFoundError(key string, w httppkg.ResponseWriter) {\n\tw.Header().Add(CACHE_HEADER_KEY, \"miss\")\n\tw.WriteHeader(httppkg.StatusNotFound)\n\tio.WriteString(w, \"\")\n\n\tlog.Printf(\"404 - unexisting key %s\", key)\n}", "func NotFound(msg string) Error {\n\te := err{msg: msg, code: notFoundCode, group: generic, kind: notFound}\n\treturn &e\n}", "func NewShowNotFound(body *ShowNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NewShowNotFound(body *ShowNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func (Http) getNotFound(name string) *Http {\n\treturn &Http{\n\t\tCode: http.StatusNotFound,\n\t\tStatus: http.StatusText(http.StatusNotFound),\n\t\tMessage: fmt.Sprintf(\"%s not found\", toUpperFirstChar(name)),\n\t}\n}", "func NewListByReferenceNotFound(body *ListByReferenceNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NewGetWaitlistEntryNotFound(body *GetWaitlistEntryNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NotFound(w http.ResponseWriter) {\n\trenderError(w, http.StatusNotFound, nil)\n}", "func NewGetNiaapiDcnmHweolsMoidNotFound() *GetNiaapiDcnmHweolsMoidNotFound {\n\treturn &GetNiaapiDcnmHweolsMoidNotFound{}\n}", "func ErrNotFoundf(format string, arguments ...interface{}) *Status {\n\treturn &Status{Code: http.StatusNotFound, Text: fmt.Sprintf(format, arguments...)}\n}", "func NotFoundf(format string, args ...interface{}) error {\n\treturn &notFoundError{fmt.Errorf(format, args...)}\n}", "func NotFound(ctx context.Context, w http.ResponseWriter, message string) {\n\tfhirError(ctx, w, http.StatusNotFound, fhir.IssueSeverityWarning, fhir.IssueTypeNotFound, message)\n}", "func (ctx *ListMessageContext) NotFound() error {\n\tctx.ResponseData.WriteHeader(404)\n\treturn nil\n}", "func TestTrunkENI_InitTrunk_ErrWhen_EmptyNWInterfaceResponse(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\n\ttrunkENI, mockEC2APIHelper, mockInstance := getMockHelperInstanceAndTrunkObject(ctrl)\n\n\tmockInstance.EXPECT().InstanceID().Return(InstanceId)\n\tmockEC2APIHelper.EXPECT().GetInstanceNetworkInterface(&InstanceId).Return(\n\t\t[]*awsEc2.InstanceNetworkInterface{{InterfaceType: nil}}, nil)\n\n\terr := trunkENI.InitTrunk(mockInstance, []v1.Pod{*MockPod2})\n\n\tassert.NotNil(t, err)\n}", "func NewListVsphereResourceNotFound() *ListVsphereResourceNotFound {\n\n\treturn &ListVsphereResourceNotFound{}\n}", "func NotFoundHandler() ServiceHttpHandler { return ServiceHttpHandler{Handler: NotFound} }", "func NewListServicesNotFound() *ListServicesNotFound {\n\treturn &ListServicesNotFound{}\n}", "func NewListServicesNotFound() *ListServicesNotFound {\n\treturn &ListServicesNotFound{}\n}", "func NewCompanyListNotFound(body *CompanyListNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}", "func NewGetKeysNotFound() *GetKeysNotFound {\n\treturn &GetKeysNotFound{}\n}", "func NewUpdateMTOPostCounselingInformationNotFound() *UpdateMTOPostCounselingInformationNotFound {\n\treturn &UpdateMTOPostCounselingInformationNotFound{}\n}", "func NotFound(w http.ResponseWriter, _ error) {\n\t(Response{Error: \"resource not found\"}).json(w, http.StatusNotFound)\n}", "func TestPutNotificationNotFound(t *testing.T) {\n\treq, err := http.NewRequest(\"PUT\", fmt.Sprintf(\"%s/api/v1/notification/not-found\", server.URL), nil)\n\n\tif err != nil {\n\t\tt.Fatal(\"Request failed [PUT] /api/v1/notification\")\n\t}\n\n\tresp, _ := http.DefaultClient.Do(req)\n\n\tassert.Equal(t, 404, resp.StatusCode)\n}", "func (response BasicJSONResponse) NotFound(writer http.ResponseWriter) {\n\tNotFound(writer, response)\n}", "func NewGetStockNotFound() *GetStockNotFound {\n\treturn &GetStockNotFound{}\n}", "func NewThingsDeleteNotFound() *ThingsDeleteNotFound {\n\n\treturn &ThingsDeleteNotFound{}\n}", "func NewGetMempoolOperationsNotFound() *GetMempoolOperationsNotFound {\n\n\treturn &GetMempoolOperationsNotFound{}\n}", "func (ctx *ListFeedContext) NotFound() error {\n\tctx.ResponseData.WriteHeader(404)\n\treturn nil\n}", "func NewListDashboardsNotFound() *ListDashboardsNotFound {\n\treturn &ListDashboardsNotFound{}\n}" ]
[ "0.5836788", "0.5688912", "0.5615028", "0.5315221", "0.52917695", "0.52688783", "0.52228385", "0.5204381", "0.50217444", "0.5009253", "0.49161574", "0.49049112", "0.4901144", "0.48926064", "0.48387036", "0.48291805", "0.48241967", "0.4805554", "0.47989002", "0.4798526", "0.47750336", "0.47642124", "0.4762271", "0.47562325", "0.47246647", "0.47171387", "0.46959192", "0.46913335", "0.4656404", "0.46296862", "0.4602397", "0.4599044", "0.45671", "0.45395058", "0.45379916", "0.45299855", "0.45291382", "0.45252633", "0.45244813", "0.45230317", "0.45230317", "0.45200187", "0.4518477", "0.45158863", "0.45078915", "0.45021665", "0.44994983", "0.449901", "0.44974113", "0.44965145", "0.44952735", "0.44828892", "0.44536304", "0.44515294", "0.4450314", "0.4449277", "0.4441215", "0.44405252", "0.44307896", "0.44223943", "0.44178972", "0.44130823", "0.44090575", "0.44027174", "0.43880242", "0.43773535", "0.43773535", "0.4375043", "0.4367945", "0.43642846", "0.4359858", "0.4353592", "0.43516797", "0.43494225", "0.43494225", "0.43489724", "0.43468693", "0.43452638", "0.434249", "0.43414986", "0.43381178", "0.43321514", "0.43267545", "0.43231037", "0.4322829", "0.43204227", "0.43112683", "0.43045035", "0.43045035", "0.43013486", "0.42991182", "0.42981815", "0.4295319", "0.4289613", "0.42895463", "0.4288766", "0.4285265", "0.4282972", "0.4282095", "0.42802942" ]
0.70803344
0
Parent return the node's parent
func Parent(i int) int { return int(math.Ceil(float64(i) / 2)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Parent(n Node) Node { return n.n().parent }", "func (n *node) Parent() *node {\n\treturn n.parent\n}", "func (n *Node) Parent() *Node {\n\treturn n.parent\n}", "func (n *Node) Parent(ctx context.Context) (p *Node, err error) {\n\treturn n.ParentWithReader(ctx, nil)\n}", "func (s *baseNode) Parent() Node {\n\treturn s.parent\n}", "func (e *Tree) Parent() *Tree { return e.parent }", "func (t *TableNode) Parent() Node {\n\treturn t.PN\n}", "func (node *Node) GetParent() helpers.GraphNode {\n\treturn node.parent\n}", "func (r *Root) Parent() Parent { return nil }", "func (p *PN) Parent() parlex.ParseNode {\n\treturn p.P\n}", "func (w *W3CNode) ParentNode() w3cdom.Node {\n\tif w == nil {\n\t\treturn nil\n\t}\n\ttn, ok := NodeAsTreeNode(w)\n\tif ok {\n\t\tp := tn.Parent()\n\t\tif p != nil {\n\t\t\treturn domify(p)\n\t\t}\n\t}\n\treturn nil\n}", "func (node *GoValueNode) Parent() ValueNode {\n\n\treturn node.parentNode\n}", "func (id NodeID) Parent() NodeID {\n\treturn NewNodeID(id.Level+1, id.Index>>1)\n}", "func (n *Node) Parent() (p *Node, err error) {\n\tif n.ParentID == \"\" {\n\t\treturn nil, fmt.Errorf(\"decomposedfs: root has no parent\")\n\t}\n\tp = &Node{\n\t\tlu: n.lu,\n\t\tID: n.ParentID,\n\t\tSpaceRoot: n.SpaceRoot,\n\t}\n\n\tparentPath := n.lu.InternalPath(n.ParentID)\n\n\t// lookup parent id in extended attributes\n\tvar attrBytes []byte\n\tif attrBytes, err = xattr.Get(parentPath, xattrs.ParentidAttr); err == nil {\n\t\tp.ParentID = string(attrBytes)\n\t} else {\n\t\treturn\n\t}\n\t// lookup name in extended attributes\n\tif attrBytes, err = xattr.Get(parentPath, xattrs.NameAttr); err == nil {\n\t\tp.Name = string(attrBytes)\n\t} else {\n\t\treturn\n\t}\n\n\t// check node exists\n\tif _, err := os.Stat(parentPath); err == nil {\n\t\tp.Exists = true\n\t}\n\treturn\n}", "func (j *Jail) Parent() int {\n\treturn j.parent\n}", "func (MatchedNode) Parent() Node { return Node{} }", "func (s *S) Parent() Surfer {\n\treturn s.parent\n}", "func (t *treeNode) parent(node *treeNode) *treeNode {\n\tif t == nil {\n\t\tfmt.Println(\"Tree does not exist\")\n\t\treturn nil\n\t}\n\tif t == node {\n\t\tfmt.Println(\"Node is root node, that has no parent\")\n\t\treturn nil\n\t}\n\tif node.Value < t.Value {\n\t\tif t.Left == node {\n\t\t\treturn t\n\t\t}\n\t\treturn t.Left.parent(node)\n\t}\n\tif t.Right == node {\n\t\treturn t\n\t}\n\treturn t.Right.parent(node)\n}", "func (g *Group) GetParent() Shape {\n\treturn g.parent\n}", "func (m *Descriptor) GetParent() *Descriptor { return m.Parent }", "func (p Pos) Parent() Pos {\n\tp.assertValid()\n\n\tif p.r == MaxLayer {\n\t\tpanic(\"historytree: parent layer out of range\")\n\t}\n\n\tr := p.r + 1\n\treturn Pos{\n\t\ti: p.i &^ r.MaxIndex(), // clear all the descendant bits\n\t\tr: r,\n\t}\n}", "func (p *Page) Parent() (*Page, error) {\n\trow := Db.QueryRow(\"SELECT p.* FROM pages c JOIN pages p ON (p.id = c.parent) WHERE c.id = $1\", p.id)\n\treturn fromRow(row)\n}", "func (f *Folder) Parent() Parent { return f.DotDot }", "func (nsf NamespaceFile) Parent() (*NamespaceFile, error) {\n\treturn namespaceFileFromFd(ioctl(int(nsf.Fd()), _NS_GET_PARENT))\n}", "func (jn jobNode) ParentNodePath() string {\n\treturn jn.parentNodePath\n}", "func (d *Dentry) Parent() *Dentry {\n\treturn d.parent\n}", "func (ref *UIElement) Parent() *UIElement {\n\tret, _ := ref.UIElementAttr(ParentAttribute)\n\treturn ret\n}", "func (d *Directory) Parent() walk.TreeItem {\n\tif d.parent == nil {\n\t\t// We can't simply return d.parent in this case, because the interface\n\t\t// value then would not be nil.\n\t\treturn nil\n\t}\n\n\treturn d.parent\n}", "func (d *Document) Parent() Parent { return d.Folder }", "func (a *_Atom) Parent() *Molecule {\n\treturn a.mol\n}", "func (c *Channel) Parent() *Channel {\n\treturn c.parent\n}", "func (t *Tree) GetParent() *Tree {\n\treturn t.parent\n}", "func (jm JSONMeta) Parent() JSONMetaNode {\n\tif len(jm.provenance.Sources) != 1 || jm.provenance.Function != \"\" {\n\t\treturn nil\n\t}\n\treturn jm.provenance.Sources[0]\n}", "func (nsfd NamespaceFd) Parent() (*NamespaceFile, error) {\n\treturn namespaceFileFromFd(ioctl(int(nsfd), _NS_GET_PARENT))\n}", "func (c *Cursor) Parent() AST { return c.parent }", "func (w *Worker) Parent() *Client {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\n\treturn w.wr.parent\n}", "func (l *Library) Parent() Parent { return l.Root }", "func (o LienOutput) Parent() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Lien) pulumi.StringOutput { return v.Parent }).(pulumi.StringOutput)\n}", "func (n *Node) GrandParent() *Node {\n\tif n != nil && n.parent != nil {\n\t\treturn n.parent.parent\n\t}\n\n\treturn nil\n}", "func (n *Node) ParentPath() string {\n\treturn n.lu.InternalPath(n.SpaceID, n.ParentID)\n}", "func (ns Nodes) Parent(a ...string) Nodes {\n\tsl := Nodes{}\n\tsel := []selector{}\n\tif len(a) != 0 {\n\t\tsel = parseSelector(a[0])\n\t\tif len(sel) != 1 {\n\t\t\treturn sl\n\t\t}\n\t}\n\tfor _, v := range ns {\n\t\tif len(sel) == 0 {\n\t\t\tsl = append(sl, v)\n\t\t} else if satisfiesSel(&Node{v.Parent}, sel[0]) {\n\t\t\tsl = append(sl, v)\n\t\t}\n\t}\n\treturn sl\n}", "func (e *Episode) Parent() string {\n\treturn e.Metadata.Labels[LabelParentGUID]\n}", "func (p *Path) Parent() (*Path, error) {\n\tpth, err := p.Absolute()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"get parent failed\")\n\t}\n\tdir := filepath.Dir(pth.Path)\n\tnewP := New(dir)\n\treturn newP, nil\n}", "func (g *Group) Parent() *Group {\n\tif g == g.db.root {\n\t\treturn nil\n\t}\n\tif indexGroup(g.db.root.groups, g) != -1 {\n\t\treturn g.db.root\n\t}\n\tfor _, gg := range g.db.groups {\n\t\tif indexGroup(gg.groups, g) != -1 {\n\t\t\treturn gg\n\t\t}\n\t}\n\tpanic(\"group without parent\")\n}", "func ParentNode(node []byte) *uint32 {\n\treturn (*uint32)(unsafe.Pointer(&node[ParentNodePointerOffset]))\n}", "func (b *BaseElement) GetParent() (e ElementI) {\n\treturn b.Parent\n}", "func (t *Team) GetParent() *Team {\n\tif t == nil {\n\t\treturn nil\n\t}\n\treturn t.Parent\n}", "func (m *UsageRecord) GetParent() string {\n\tif m != nil {\n\t\treturn m.Parent\n\t}\n\treturn \"\"\n}", "func (s *Stream) Parent() *Stream {\n\treturn s.parent\n}", "func (m *Resource) Parent() string {\n\treturn m.parentresource\n}", "func (w *Walker) Parent() *Walker {\n\tif w == nil {\n\t\treturn nil\n\t}\n\tif err := w.appendFilterForTask(parent, nil, 0); err != nil {\n\t\tT().Errorf(err.Error())\n\t\tpanic(err)\n\t}\n\treturn w\n}", "func parent(node *Node, isBuffered bool, udata userdata, push func(*Node, uint32),\n\tpushBuf func(*Node, interface{}, uint32)) error {\n\t//\n\tp := node.Parent()\n\tserial := udata.serial\n\tif p != nil {\n\t\tpush(p, serial) // forward parent node to next pipeline stage\n\t}\n\treturn nil\n}", "func (m *InMemoryRepository) Parent(u fyne.URI) (fyne.URI, error) {\n\treturn repository.GenericParent(u)\n}", "func (e *FakeElement) Parent() Element {\n\treturn e.parent\n}", "func (t *Commit) GetParent() string {\n\tif t.Parent == nil {\n\t\treturn \"\"\n\t}\n\treturn *t.Parent\n}", "func (d *Die) Parent() Roller {\n\treturn d.parent\n}", "func (c Command) Parent() *Command {\n\treturn c.parent\n}", "func (path PathImpl) Parent() Path {\n\t// path.String() can't be empty\n\tparent, _ := New(path, \"..\")\n\treturn parent\n}", "func (o ProjectOutput) Parent() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Project) pulumi.StringOutput { return v.Parent }).(pulumi.StringOutput)\n}", "func (t *Transform) Parent() Transformable {\n\tt.access.RLock()\n\tp := t.parent\n\tt.access.RUnlock()\n\treturn p\n}", "func (r *Repository) GetParent() *Repository {\n\tif r == nil {\n\t\treturn nil\n\t}\n\treturn r.Parent\n}", "func (n *resPool) Parent() ResPool {\n\tn.RLock()\n\tdefer n.RUnlock()\n\treturn n.parent\n}", "func (item *Item) Parent() IItem {\n return item.parent\n}", "func (m *SectionGroup) GetParentNotebook()(Notebookable) {\n return m.parentNotebook\n}", "func (d *Dentry) ParentOrSelf() *Dentry {\n\tif d.parent == nil {\n\t\treturn d\n\t}\n\treturn d.parent\n}", "func (c *GitCommit) Parent(n uint) *GitCommit {\n\treturn &GitCommit{\n\t\tRepo: c.Repo,\n\t\tCommit: c.Commit.Parent(n),\n\t}\n}", "func Parent(w io.Writer) io.Writer {\n\tswitch x := w.(type) {\n\tcase node:\n\t\treturn coalesceWriters(x.Parent(), w)\n\tcase decorator:\n\t\treturn coalesceWriters(Parent(x.Base()), w)\n\tdefault:\n\t\treturn x\n\t}\n}", "func (d *device) getParent() Device {\n\treturn d.parent\n}", "func (tk Tokens) Parent() Tokens {\n\tif tk.IsSubCat() {\n\t\treturn tk.Cat()\n\t}\n\treturn tk.SubCat()\n}", "func (v *IADs) Parent() (path string, err error) {\n\tvar bstr *int16\n\thr, _, _ := syscall.Syscall(\n\t\tuintptr(v.VTable().Parent),\n\t\t2,\n\t\tuintptr(unsafe.Pointer(v)),\n\t\tuintptr(unsafe.Pointer(&bstr)),\n\t\t0)\n\tif bstr != nil {\n\t\tdefer ole.SysFreeString(bstr)\n\t}\n\tif hr == 0 {\n\t\tpath = ole.BstrToString((*uint16)(unsafe.Pointer(bstr)))\n\t} else {\n\t\treturn \"\", convertHresultToError(hr)\n\t}\n\treturn\n}", "func (sc *BaseSmartContract) GetParent() object.Parent {\n\treturn sc.Parent\n}", "func (c *Category) GetParent() Category {\r\n\tparent := Category{}\r\n\tif c.ParentID != nil {\r\n\t\tdb.First(&parent, *c.ParentID)\r\n\t}\r\n\treturn parent\r\n}", "func Parent(tileid TileID) TileID {\n\tcenter := Center(tileid)\n\treturn Tile(center[0], center[1], int(tileid.Z)-1)\n}", "func (w *WidgetImplement) Parent() Widget {\n\treturn w.parent\n}", "func (selfPtr *ActorRef) Parent() *ActorRef {\n\treturn &ActorRef{\n\t\tcoreActor:selfPtr.coreActor.Parent,\n\t}\n}", "func (i *Resource) Parent() (*Version, error) {\n\tversions, err := i.conn.middleware.FindVersions(\n\t\t1,\n\t\t0,\n\t\t[]*wyc.QueryDesc{\n\t\t\t{Id: i.data.Parent},\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(versions) < 1 {\n\t\treturn nil, fmt.Errorf(\"version with Id %s not found\", i.data.Parent)\n\t}\n\n\treturn &Version{\n\t\tconn: i.conn,\n\t\tdata: versions[0],\n\t}, nil\n}", "func (cmd *CLI) Parent() Command {\n\treturn cmd.parent\n}", "func (e *Entry) Parent() *Group {\n\tfor _, g := range e.db.groups {\n\t\tfor _, ee := range g.entries {\n\t\t\tif ee == e {\n\t\t\t\treturn g\n\t\t\t}\n\t\t}\n\t}\n\tpanic(\"entry without parent\")\n}", "func (a *evalActivation) Parent() interpreter.Activation {\n\treturn nil\n}", "func (m *ParentLabelDetails) GetParent()(ParentLabelDetailsable) {\n val, err := m.GetBackingStore().Get(\"parent\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(ParentLabelDetailsable)\n }\n return nil\n}", "func (c FieldsCollection) Parent() *models.Field {\n\treturn c.MustGet(\"Parent\")\n}", "func (thread *Thread) GetParentID() string {\n\treturn \"\"\n}", "func Parent(index, depth uint) uint {\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\toffset := Offset(index, depth)\n\n\treturn Index(depth+1, rightShift(offset))\n}", "func (jdcb jobDirectoryContentsBatch) ParentNodePath() string {\n\treturn jdcb.parentPath\n}", "func (o TagBindingOutput) Parent() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *TagBinding) pulumi.StringOutput { return v.Parent }).(pulumi.StringOutput)\n}", "func parent(index int) int {\n\treturn (index - 1) / 2\n}", "func (sc *TraceScope) Parent() *TraceScope {\n\treturn sc.parent\n}", "func (ds *dagSession) getParentFor(id cid.Cid) Node {\n\tds.pl.Lock()\n\tdefer ds.pl.Unlock()\n\n\tfor _, n := range ds.prnts {\n\t\tfor _, l := range n.Links() {\n\t\t\tif l.Cid.Equals(id) {\n\t\t\t\t// restoration reconstructs all linked nodes at fo hence parent can't be reused, so uncache it.\n\t\t\t//\tdelete(ds.prnts, p)\n\t\t\t\treturn n\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s UserSet) Parent() m.PartnerSet {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"Parent\", \"parent_id\")).(models.RecordSet).Collection().Wrap(\"Partner\").(m.PartnerSet)\n\treturn res\n}", "func (blk *Block) Parent() (*Block, error) {\n\t// get the parent block by hash\n\tparent, err := blk.repo.BlockByHash(&blk.ParentHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewBlock(parent, blk.repo), nil\n}", "func (i *Resource) ParentId() string {\n\treturn i.data.Parent\n}", "func getCgroupParent() (string, error) {\n\treturn \"\", nil\n}", "func (e *ExtensionDescriptor) GetParent() *Descriptor { return e.Parent }", "func (ctx *Context) Parent() (parent reflect.Value) {\n\tif len(ctx.values) > 1 {\n\t\tparent = ctx.values[len(ctx.values)-2]\n\t}\n\treturn\n}", "func parent(k int) int {\n\treturn int(math.Ceil(float64(k)/2.0) - 1)\n}", "func (self *Events) Parent() *Sprite{\n return &Sprite{self.Object.Get(\"parent\")}\n}", "func (sc *SwayConnection) FindParent(id int64) Node {\n\ttree, _ := sc.GetTree()\n\tvar result []Node\n\n\tparent := finder(result, tree.Nodes, tree.Nodes[0], id)\n\n\treturn parent[0]\n}", "func (e *Entry) parentPath() string {\n\tif len(e.path) == 0 {\n\t\tpanic(\"trying to get the parentPath of the root\")\n\t}\n\tparts := make([]string, 1, len(e.path))\n\tparts[0] = e.root.path\n\tparts = append(parts, e.path[:len(e.path)-1]...)\n\treturn filepath.Join(parts...)\n}", "func (t *Task) ParentID() uint64 {\n\tt.mutex.RLock()\n\tdefer t.mutex.RUnlock()\n\tif t.parent != nil {\n\t\treturn t.parent.ID()\n\t}\n\treturn 0\n}", "func (k *Key) Parent() *Key {\n\tif len(k.toks) <= 1 {\n\t\treturn nil\n\t}\n\treturn k.kc.NewKeyToks(k.toks[:len(k.toks)-1])\n}", "func parent(i int) int {\n\treturn (i - 1) / 2\n}" ]
[ "0.8816087", "0.8577594", "0.84672266", "0.8187701", "0.81343466", "0.8095857", "0.80675375", "0.7883262", "0.76794785", "0.7658783", "0.7632359", "0.761028", "0.7596659", "0.74704593", "0.74425", "0.74424994", "0.73512036", "0.73434335", "0.7332849", "0.73273283", "0.7278904", "0.7271242", "0.7266321", "0.72399163", "0.7223315", "0.7222821", "0.72151685", "0.7164777", "0.7150391", "0.71191835", "0.7119004", "0.7094365", "0.7072985", "0.7055035", "0.70438707", "0.7001064", "0.69876826", "0.6986637", "0.69771594", "0.6965219", "0.69583535", "0.69502676", "0.69204783", "0.69160855", "0.6911613", "0.6903163", "0.6895942", "0.68847054", "0.6884204", "0.6843479", "0.6839889", "0.6819472", "0.68174285", "0.6816951", "0.6807813", "0.6802447", "0.67850816", "0.6757408", "0.67445", "0.67133945", "0.67048967", "0.66935915", "0.669249", "0.6673876", "0.6671595", "0.66630965", "0.6661805", "0.6650644", "0.6635928", "0.6633651", "0.66274184", "0.6616875", "0.6606014", "0.6596511", "0.6584559", "0.6578229", "0.65678203", "0.6565457", "0.6546839", "0.65393734", "0.6519768", "0.6513482", "0.64974034", "0.64968723", "0.64862317", "0.6477673", "0.64739007", "0.6449824", "0.6439994", "0.642837", "0.6416524", "0.6409463", "0.640473", "0.6401705", "0.63961095", "0.63915366", "0.637556", "0.63681614", "0.6360751", "0.63607115", "0.63603884" ]
0.0
-1
Left return the node's lchild
func Left(i int) int { return 2 * i }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (eln *EmptyLeafNode) GetLeftChild() Node {\n\treturn nil\n}", "func (s SGTree) leftChild(treeIndex int) int {\n\treturn 2*treeIndex + 1\n}", "func (tree *Tree) Left() *Node {\n\tvar parent *Node\n\tcurrent := tree.Root\n\tfor current != nil {\n\t\tparent = current\n\t\tcurrent = current.Left\n\t}\n\treturn parent\n}", "func (e *Tree) Left() *Tree { return e.left }", "func (tree *UTree) Left() *Node {\r\n\tvar parent *Node\r\n\tcurrent := tree.root\r\n\tfor current != nil {\r\n\t\tparent = current\r\n\t\tcurrent = current.left\r\n\t}\r\n\treturn parent\r\n}", "func LeftChild(index, depth uint) (uint, error) {\n\tif index&1 == 0 {\n\t\treturn 0, errors.New(\"No left child\")\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Index(depth-1, Offset(index, depth)*2), nil\n}", "func (n *BinaryTreeNode) leftmostChild() *BinaryTreeNode {\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\tvar cur *BinaryTreeNode\n\tfor cur = n; cur.left != nil; cur = cur.left {\n\t}\n\n\treturn cur\n}", "func (l *Label) leftmostNode(g *Graph) *Label {\n left, _ := l.left(g) // TODO do not ignore error\n if left == nil {\n return l\n }\n return left.leftmostNode(g)\n}", "func LeftRotate(x *Node) *Node {\n\tif x.IsNil {\n\t\treturn x\n\t}\n\n\txRight := x.RightChild\n\t// Get right Child\n\t//\n\tif xRight.IsNil {\n\t\treturn xRight\n\t}\n\n\t// Assign parent of x as parent of right child\n\t//\n\txParent := x.Parent\n\txRight.Parent = xParent\n\tif !xParent.IsNil {\n\t\tif xParent.LeftChild == x {\n\t\t\txParent.LeftChild = xRight\n\t\t} else if xParent.RightChild == x {\n\t\t\txParent.RightChild = xRight\n\t\t}\n\t}\n\n\txRightLeft := xRight.LeftChild\n\n\t// Set xright as the parent of x\n\t//\n\tx.Parent = xRight\n\txRight.LeftChild = x\n\n\t// Set right child of x to the left child of xright\n\t//\n\tx.RightChild = xRightLeft\n\tif !xRightLeft.IsNil {\n\t\txRightLeft.Parent = x\n\t}\n\n\treturn xRight\n}", "func leftChild(i int) int {\n\treturn (i * 2) + 1\n}", "func (l *Label) left(g *Graph) (*Label, *DataError) {\n Assert(nilLabel, l != nil)\n Assert(nilGraph, g != nil)\n Assert(nilLabelStore, g.labelStore != nil)\n \n return g.labelStore.findAllowZero(l.l)\n}", "func (ubt *ubtTree) Left() UnboundBinaryTree {\n\tif ubt.left == nil {\n\t\tubt.left = &ubtTree{}\n\t}\n\treturn ubt.left\n}", "func (tree *DNFTree) CreateLeftChild(nodeID int, phi br.ClauseSet, isFinal bool) int {\n\tif debug {\n\t\tif nodeID < 0 {\n\t\t\tpanic(\"Expected nodeID >= 0 in CreateLeftChild\")\n\t\t}\n\t\tif nodeID >= len(tree.Content) {\n\t\t\tpanic(\"Expected nodeID < len(content) in CreateLeftChild\")\n\t\t}\n\t}\n\tn := tree.Content[nodeID]\n\tid := tree.CreateNodeEntry(phi, n.depth+1, isFinal)\n\tn.leftChild = id\n\treturn id\n}", "func mostLeftChild(root *treeNode) *treeNode {\n\tif root == nil {\n\t\treturn root\n\t}\n\tp := root\n\tfor p.left != nil {\n\t\tp = p.left\n\t}\n\treturn p\n}", "func (rbnode *RBNode) getMostLeftNode() *RBNode {\n\tif rbnode.left == nil {\n\t\treturn rbnode\n\t}\n\treturn rbnode.left.getMostLeftNode()\n}", "func (t *treeNode) ShowLeft() *BTree {\n\treturn t.left\n}", "func rotateLeft(n *rbnode) *rbnode {\n\tif n.right == nil {\n\t\treturn n\n\t}\n\tr := n.right\n\tconnectRight(n, r.left)\n\treplaceChild(n, r)\n\tconnectLeft(r, n)\n\tn.c, r.c = r.c, n.c\n\treturn r\n}", "func (node *node) leftRotate() *node {\n\tvar x = node.RightNode\n\tvar t2 = x.LeftNode\n\n\tx.LeftNode = node\n\tnode.RightNode = t2\n\n\tnode.height = max(getHeight(node.LeftNode), getHeight(node.RightNode)) + 1\n\tx.height = max(getHeight(x.LeftNode), getHeight(x.RightNode)) + 1\n\n\treturn x\n}", "func (n *Node) rotateLeft(c *Node) {\n\t// Save `c`'s right child.\n\tr := c.Right\n\t// `r`'s left subtree gets reassigned to `c`.\n\tc.Right = r.Left\n\t// `c` becomes the left child of `r`.\n\tr.Left = c\n\t// Make the parent node (that is, the current one) point to the new root node.\n\tif c == n.Left {\n\t\tn.Left = r\n\t} else {\n\t\tn.Right = r\n\t}\n\t// Finally, adjust the balances. After a single rotation, the subtrees are always of the same height.\n\tc.bal = 0\n\tr.bal = 0\n}", "func getLeftmost(start *node) *node {\n\tp := start\n\tleftmost := start\n\tfor {\n\t\tif p.x < leftmost.x {\n\t\t\tleftmost = p\n\t\t}\n\t\tp = p.next\n\t\tif p == start {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn leftmost\n}", "func (n *Node) PrintLeft(level int, maxLevel *int) {\n\t// No more nodes to iterate\n\tif n == nil {\n\t\treturn\n\t}\n\t// Check if the current iteration corresponds to the\n\t// first node of the BST level\n\tif *maxLevel < level {\n\t\tfmt.Println(n.Value)\n\t\t*maxLevel = level\n\t}\n\t// Do the recursion for the left side of the current node\n\tn.Left.PrintLeft(level+1, maxLevel)\n\t// Same for the right side\n\tn.Right.PrintLeft(level+1, maxLevel)\n}", "func LeftRotate(n *Node) *Node {\n\tr := n.Right\n\tif r == nil {\n\t\treturn n\n\t}\n\n\tn.Right = r.Left\n\tr.Left = n\n\n\treturn r\n}", "func (e *Tree) SetLeft(replacement *Tree) { e.left = replacement }", "func llrbLeftMost(root *llrbNode) *llrbNode {\n for root.left != nil {\n root = root.left\n }\n return root\n}", "func (rbTree *RBTree)rotateLeft(X *treeNode) {\n\tvar Y = X.right\n\t// move W to X's right child\n\tX.right = Y.left\n\tif Y.left != nil {\n\t\tY.left.father = X\n\t}\n\t// move Y to X's father's child\n\tY.father = X.father\n\tif X == rbTree.root {\n\t\t// X is root\n\t\trbTree.root = Y\n\t} else if X == X.father.left {\n\t\t// X is father's left child\n\t\tX.father.left = Y\n\t} else {\n\t\t// X is father's right child\n\t\tX.father.right = Y\n\t}\n\t// move X to Y's left child\n\tY.left = X\n\tX.father = Y\n}", "func (mt MerkleTree) LeftTree() *MerkleTree {\n\treturn mt.leftTree\n}", "func (tree *RBTree) rotateLeft(node *RBTreeNode) {\n\tif node == nil {\n\t\treturn\n\t}\n\tr := node.right\n\tnode.right = r.left\n\tif r.left != nil {\n\t\tr.left.parent = node\n\t}\n\n\tr.parent = node.parent\n\tif node.parent == nil {\n\t\ttree.root = r\n\t} else {\n\t\tif node.parent.left == node {\n\t\t\tnode.parent.left = r\n\t\t} else {\n\t\t\tnode.parent.right = r\n\t\t}\n\t}\n\tnode.parent = r\n\tr.left = node\n}", "func (rbst *RBSTAbelGroup) RotateLeft(root *Node, start, stop, k int) *Node {\r\n\tstart++\r\n\tk %= (stop - start + 1)\r\n\r\n\tx, y := rbst.SplitByRank(root, start-1)\r\n\ty, z := rbst.SplitByRank(y, k)\r\n\tz, p := rbst.SplitByRank(z, stop-start+1-k)\r\n\treturn rbst.Merge(rbst.Merge(rbst.Merge(x, z), y), p)\r\n}", "func (eln *EmptyLeafNode) SetLeftChild(child Node) {\n\tpanic(\"Cannot set children of an empty leaf node\")\n}", "func llrbRotateLeft(root *llrbNode) *llrbNode {\n right := root.right\n root.right = right.left\n right.left = root\n right.color = root.color\n root.color = true // the left subtree is now red\n return right // the right child becomes the new root\n}", "func leftRotate(node *Node) *Node {\n\ttempNode := node.right\n\tnode.right = tempNode.left\n\ttempNode.left = node\n\treturn tempNode\n}", "func (root *TreeNode) leftRotate() *TreeNode {\n\tnode := root.right\n\troot.right = node.left\n\tnode.left = root\n\n\troot.height = max(root.left.getHeight(), root.right.getHeight()) + 1\n\tnode.height = max(node.right.getHeight(), node.left.getHeight()) + 1\n\treturn node\n}", "func (t *RedBlackTree) rotateLeft(node *Node) {\n\tright := node.right\n\tt.swapNodes(node, right)\n\tnode.right = right.left\n\tif right.left != nil {\n\t\tright.left.parent = node\n\t}\n\tright.left = node\n\tnode.parent = right\n}", "func leftRecursive(expr ast.Node) ast.Node {\n\tswitch node := expr.(type) {\n\tcase *ast.Apply:\n\t\treturn node.Target\n\tcase *ast.ApplyBrace:\n\t\treturn node.Left\n\tcase *ast.Binary:\n\t\treturn node.Left\n\tcase *ast.Index:\n\t\treturn node.Target\n\tcase *ast.InSuper:\n\t\treturn node.Index\n\tcase *ast.Slice:\n\t\treturn node.Target\n\tdefault:\n\t\treturn nil\n\t}\n}", "func leftMost(node *Node) *Node {\n\tif node == nil {\n\t\treturn nil\n\t}\n\n\tcurrent := node\n\n\tfor {\n\t\tif current.left == nil {\n\t\t\treturn current\n\t\t}\n\t\tcurrent = current.left\n\t}\n}", "func (self SimpleInterval) Left() float64 {\n\treturn self.LR[0]\n}", "func (o DashboardSpacingPtrOutput) Left() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardSpacing) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Left\n\t}).(pulumi.StringPtrOutput)\n}", "func rotateLeft(root, pivot *Node) *Node {\n\tchild := pivot.Left\n\n\tpivot.Left = root\n\troot.Parent = pivot\n\n\tif child != nil {\n\t\tchild.Parent = root\n\t}\n\troot.Right = child\n\n\treturn pivot\n}", "func (h *heap) leftChildIndex(i int64) int64 {\n\treturn i*2 + 1\n}", "func (llrb *LLRB) moveredleft(nd *Llrbnode) *Llrbnode {\n\tllrb.flip(nd)\n\tif nd.right.left.isred() {\n\t\tnd.right = llrb.rotateright(nd.right)\n\t\tnd = llrb.rotateleft(nd)\n\t\tllrb.flip(nd)\n\t}\n\treturn nd\n}", "func (e *Tree) PushLeft(value interface{}) *Tree {\n\treturn e.pushTree(\"left\", value)\n}", "func rotate_left_callback(n, parent *Node) {\n\t// parent inherit max m value\n\tparent.m = n.m\n\t// update node 'm' value by it's children.\n\tn.m = Max(n.high, Max(M(n.left), M(n.right)))\n}", "func (b *Bound) Left() float64 {\n\treturn b.sw[0]\n}", "func (t *Tree) leftRotate(x *Node) {\n\ty := x.right\n\tx.right = y.left\n\tif y.left != nil {\n\t\ty.left.p = x\n\t}\n\tt.transplant(x, y)\n\ty.left = x\n\tx.p = y\n}", "func (o *WorkbookChart) GetLeft() AnyOfnumberstringstring {\n\tif o == nil || o.Left == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Left\n}", "func (pb *PhilosopherBase) LeftFork() Fork {\n\treturn Forks[pb.leftForkID()]\n}", "func (n *Node) rotateRightLeft(c *Node) {\n\t// `rotateRight` assumes that the left child has a left child, but as part of the rotate-right-left process,\n\t// the left child of `c.Right` is a leaf. We therefore have to tweak the balance factors before and after\n\t// calling `rotateRight`.\n\t// If we did not do that, we would not be able to reuse `rotateRight` and `rotateLeft`.\n\tc.Right.Left.bal = 1\n\tc.rotateRight(c.Right)\n\tc.Right.bal = 1\n\tn.rotateLeft(c)\n}", "func (tree *BinaryTree) SetLeft(value int) *BinaryTree {\n\ttree.left = &BinaryTree{value: value, left: nil, right: nil}\n\treturn tree\n}", "func (ll *LinkedList) PopLeft() (int, bool) {\n\tif ll.IsEmpty() {\n\t\treturn -1, false\n\t}\n\n\telement := ll.start.value\n\n\t// single element\n\tif ll.start == ll.end {\n\t\tll.Clear()\n\t} else {\n\t\tll.start = ll.start.next\n\t\tll.start.previous = nil\n\t\tll.length--\n\t}\n\n\treturn element, true\n}", "func (t *treeNode) printLeftView(root *treeNode) {\n\tif t == nil {\n\t\treturn\n\t}\n\tfmt.Println(t.Value)\n\tleft(root)\n}", "func (l Left) Children() []sql.Expression {\n\treturn []sql.Expression{l.str, l.len}\n}", "func (node *Node) AllocLeft() (*Node, uint32) {\n\tvar (\n\t\tinto = NewNode(node.Shift + BITS)\n\t\thalf = uint32((1 << (into.Shift + BITS)) / 2)\n\t)\n\tinto.Elements[(half>>into.Shift)&MASK] = node\n\treturn into, half\n}", "func (bst BinaryTree) InsertLeft(n, at *BSTreeNode) *BSTreeNode {\n\tif at.Left == nil {\n\t\tat.Left = n\n\t\treturn at.Left\n\t}\n\tif at.Left.Value >= n.Value {\n\t\treturn bst.InsertLeft(n, at.Left)\n\t}\n\treturn bst.InsertRight(n, at.Left)\n}", "func llrbMoveRedLeft(root *llrbNode) *llrbNode {\n llrbFlipColor(root)\n if llrbIsRed(root.right.left) {\n root.right = llrbRotateRight(root.right)\n root = llrbRotateLeft(root)\n llrbFlipColor(root)\n }\n return root\n}", "func (v *TypePair) GetLeft() (o *Type) {\n\tif v != nil {\n\t\to = v.Left\n\t}\n\treturn\n}", "func (e Equation) Left() Type {\n\treturn e.left\n}", "func (o DashboardSpacingOutput) Left() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DashboardSpacing) *string { return v.Left }).(pulumi.StringPtrOutput)\n}", "func rotate_left_callback(n, parent *Node) {\n\tparent.size = _nodesize(n)\n\tn.size = _nodesize(n.left) + _nodesize(n.right) + len(n.ids)\n}", "func left(x uint) uint {\n\tif level(x) == 0 {\n\t\treturn x\n\t}\n\n\treturn x ^ (0x01 << (level(x) - 1))\n}", "func (board *Board) Left() *Board {\n\tblankPosition := board.PositionOfBlank()\n\tif blankPosition%board.Dimension == 0 {\n\t\treturn nil\n\t}\n\n\tclone := board.Clone()\n\tclone.move = LEFT\n\ttile := clone.GetTileAt(blankPosition - 1)\n\tclone.SetTileAt(blankPosition-1, BLANK)\n\tclone.SetTileAt(blankPosition, tile)\n\tclone.cost = clone.g + clone.Cost()\n\treturn clone\n}", "func (root *mTreap) rotateLeft(x *treapNode) {\n\t// p -> (x a (y b c))\n\tp := x.parent\n\ta, y := x.left, x.right\n\tb, c := y.left, y.right\n\n\ty.left = x\n\tx.parent = y\n\ty.right = c\n\tif c != nil {\n\t\tc.parent = y\n\t}\n\tx.left = a\n\tif a != nil {\n\t\ta.parent = x\n\t}\n\tx.right = b\n\tif b != nil {\n\t\tb.parent = x\n\t}\n\n\ty.parent = p\n\tif p == nil {\n\t\troot.treap = y\n\t} else if p.left == x {\n\t\tp.left = y\n\t} else {\n\t\tif p.right != x {\n\t\t\tthrow(\"large span treap rotateLeft\")\n\t\t}\n\t\tp.right = y\n\t}\n\n\tx.updateInvariants()\n\ty.updateInvariants()\n}", "func (n *Node) LeftRed() bool {\n\treturn n.Left != nil && n.Left.Color == Red\n}", "func (root *TreeNode) leftRightRotate() *TreeNode {\n\troot.left = root.left.leftRotate()\n\troot = root.rightRotate()\n\treturn root\n}", "func (o *TileBounds) GetLeft() int32 {\n\tif o == nil || o.Left == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Left\n}", "func (root *TreeNode) rightLeftRotate() *TreeNode {\n\troot.right = root.right.rightRotate()\n\troot = root.leftRotate()\n\treturn root\n}", "func (n *Node) findLargestLeft() (parent, largest *Node) {\n\tparent = n\n\ttrav := n.left\n\tfor trav != nil {\n\t\tif trav.right == nil {\n\t\t\treturn parent, trav\n\t\t}\n\t\tparent = trav\n\t\ttrav = trav.right\n\t}\n\treturn nil, nil\n}", "func (l *Label) rotateLeft(g *Graph) uint16 {\n Assert(nilLabel, l != nil)\n Assert(nilGraph, g != nil)\n Assert(nilLabelStore, g.labelStore != nil)\n Assert(nilLabelWriteMap, g.labelStore.writes != nil)\n \n // perform the rotation\n right, _ := l.right(g) // TODO do not ignore error\n l.r = right.l\n right.l = l.Id\n \n l.setHeight(g)\n right.setHeight(g)\n \n // make sure the changes are written\n g.labelStore.writes[l.Id] = l\n g.labelStore.writes[right.Id] = right\n \n return right.Id\n}", "func (l Left) WithChildren(children ...sql.Expression) (sql.Expression, error) {\n\tif len(children) != 2 {\n\t\treturn nil, sql.ErrInvalidChildrenNumber.New(l, len(children), 2)\n\t}\n\treturn NewLeft(children[0], children[1]), nil\n}", "func (d *Deque) Left() interface{} {\n\treturn d.left[d.leftOff]\n}", "func (t *treeNode) printLeftView1(root *treeNode) {\n\tif t == nil {\n\t\treturn\n\t}\n\tvar queue []*treeNode\n\tqueue = append(queue, t)\n\tfmt.Println(t.Value)\n\tprintLeft(queue)\n}", "func (l *Label) rightmostNode(g *Graph) *Label {\n right, _ := l.right(g) // TODO do not ignore error\n if right == nil {\n return l\n }\n return right.rightmostNode(g)\n}", "func (ll *LinkedList) PushLeft(element int) {\n\tnewNode := &node{\n\t\tvalue: element,\n\t\tprevious: nil,\n\t\tnext: ll.start,\n\t}\n\n\tif ll.IsEmpty() {\n\t\tll.end = newNode\n\t} else {\n\t\t// when not empty the current start node should point\n\t\t// to the new one before it is updated, so we don't get\n\t\t// a broken link\n\t\tll.start.previous = newNode\n\t}\n\n\tll.start = newNode\n\tll.length++\n}", "func leftRecursiveDeep(expr ast.Node) ast.Node {\n\tlast := expr\n\tleft := leftRecursive(expr)\n\tfor left != nil {\n\t\tlast = left\n\t\tleft = leftRecursive(last)\n\t}\n\treturn last\n}", "func (fn *formulaFuncs) LEFT(argsList *list.List) formulaArg {\n\treturn fn.leftRight(\"LEFT\", argsList)\n}", "func (n *Node) MoveLeft(p []int, i int) {\n\tif i%NumberColumns > 0 {\n\t\tc := n.ClonePuzzle()\n\t\ttemp := c[i-1]\n\t\tc[i-1] = c[i]\n\t\tc[i] = temp\n\n\t\tchild := NewPuzzle(c)\n\t\tchild.Move = boardPositions[i-1]\n\t\tchild.Parent = n\n\t\tchild.G = n.G + 1\n\t\tn.Children = append(n.Children, child)\n\t}\n}", "func (r *RedirectNode) LeftFD() int { return r.rmap.lfd }", "func (o *SceneTreeTimer) GetTimeLeft() gdnative.Real {\n\t//log.Println(\"Calling SceneTreeTimer.GetTimeLeft()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"SceneTreeTimer\", \"get_time_left\")\n\n\t// Call the parent method.\n\t// float\n\tretPtr := gdnative.NewEmptyReal()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewRealFromPointer(retPtr)\n\treturn ret\n}", "func rotateRightLeft(root, pivot *Node) *Node {\n\trotateRight(root.Right, pivot)\n\tpivot.Parent = root\n\troot.Right = pivot\n\trotateLeft(root, pivot)\n\treturn pivot\n}", "func (n *Node) MoveDownLeft(p []int, i int) {\n\tif i%NumberColumns > 0 && i < 8 {\n\t\tc := n.ClonePuzzle()\n\t\ttemp := c[i+3]\n\t\tc[i+3] = c[i]\n\t\tc[i] = temp\n\n\t\tchild := NewPuzzle(c)\n\t\tchild.Move = boardPositions[i+3]\n\t\tchild.Parent = n\n\t\tchild.G = n.G + 1\n\t\tn.Children = append(n.Children, child)\n\t}\n}", "func (e *Tree) Right() *Tree { return e.right }", "func RightRotate(x *Node) *Node {\n\tif x.IsNil {\n\t\treturn x\n\t}\n\n\t// Get left Child\n\t//\n\txLeft := x.LeftChild\n\tif xLeft.IsNil {\n\t\treturn xLeft\n\t}\n\n\t// Assign parent of x as parent of left child\n\t//\n\txParent := x.Parent\n\txLeft.Parent = xParent\n\tif !xParent.IsNil {\n\t\tif xParent.LeftChild == x {\n\t\t\txParent.LeftChild = xLeft\n\t\t} else if xParent.RightChild == x {\n\t\t\txParent.RightChild = xLeft\n\t\t}\n\t}\n\n\txLeftRight := xLeft.RightChild\n\n\t// Set xleft as the parent of x\n\t//\n\tx.Parent = xLeft\n\txLeft.RightChild = x\n\n\t// Set left child of x to right child of xleft\n\t//\n\tx.LeftChild = xLeftRight\n\tif !xLeftRight.IsNil {\n\t\txLeftRight.Parent = x\n\t}\n\n\treturn xLeft\n}", "func ColumnLeft(name string) {\n\tidx := colIndex(name)\n\tif idx > 0 {\n\t\tswapCols(idx, idx-1)\n\t}\n}", "func (this *Tuple) Left(n int) *Tuple {\n\treturn this.Slice(0, n)\n}", "func rotateLeft(root, pivot *node) *node {\n\troot.right = pivot.left\n\tpivot.left = root\n\treturn pivot\n}", "func GetLeftIndex(n int) int {\n\treturn 2*n + 1\n}", "func (p Permutator) left() int {\n\treturn (p.amount - p.index) + 1\n}", "func (d *Deque) PopLeft() (res interface{}) {\n\tres, d.left[d.leftOff] = d.left[d.leftOff], nil\n\td.leftOff++\n\tif d.leftOff == blockSize {\n\t\td.leftOff = 0\n\t\td.leftIdx = (d.leftIdx + 1) % len(d.blocks)\n\t\td.left = d.blocks[d.leftIdx]\n\t}\n\treturn\n}", "func (this *Tuple) PopLeft() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tret := this.data[0]\n\tthis.data = this.data[1:]\n\treturn ret\n}", "func (m *Machine) Left() {\n\tfmt.Printf(\">> LEFT\\n\")\n\t// If we're at the 0th position, then we need to expand our tape array:\n\tif m.position == 0 {\n\t\tsize := len(m.Tape)\n\t\tm.Tape = append(make([]Cell, size), m.Tape...)\n\t\tm.position += size\n\t}\n\n\tm.position -= 1\n}", "func (tree *Tree) Right() *Node {\n\tvar parent *Node\n\tcurrent := tree.Root\n\tfor current != nil {\n\t\tparent = current\n\t\tcurrent = current.Right\n\t}\n\treturn parent\n}", "func (o *WorkbookChart) SetLeft(v AnyOfnumberstringstring) {\n\to.Left = &v\n}", "func (n *nodeHeader) leftTrimPrefix(l uint16) {\n\tif l < 1 {\n\t\treturn\n\t}\n\tpLen, pBytes := n.prefixFields()\n\tif l > *pLen {\n\t\tl = *pLen\n\t}\n\tnewLen := *pLen - uint16(l)\n\tcopy(pBytes[0:newLen], pBytes[l:*pLen])\n\t*pLen = newLen\n}", "func (n *Node) LeftBlack() bool {\n\treturn n.Left == nil || n.Left.Color == Black\n}", "func (b *BaseElement) GetMarginLeft() int32 {\n\treturn b.ml\n}", "func (root *TreeNode) minValueNode() *TreeNode {\n\tif root.left == nil {\n\t\t// If no left element is available, we are at the smallest key\n\t\t// so we return ourself\n\t\treturn root\n\t}\n\n\treturn root.left.minValueNode()\n}", "func (p Permutator) Left() int {\n\t<- p.idle\n\tremaining := p.left()\n\tp.idle <- true\n\treturn remaining\n}", "func (builder *Builder) Left(n uint) *Builder {\n\treturn builder.With(Left(n))\n}", "func (unpacker *BitUnpacker) Left() uint32 {\n\treturn unpacker.size - (unpacker.pbyte*8 + unpacker.pbit)\n}", "func (sopsTxtJustify TextJustify) Left() TextJustify {\n\n\tlockStrOpsTextJustify.Lock()\n\n\tdefer lockStrOpsTextJustify.Unlock()\n\n\treturn TextJustify(1)\n}", "func LeftSpan(index, depth uint) uint {\n\tif index&1 == 0 {\n\t\treturn index\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Offset(index, depth) * twoPow(depth+1)\n}", "func (tree *UTree) Right() *Node {\r\n\tvar parent *Node\r\n\tcurrent := tree.root\r\n\tfor current != nil {\r\n\t\tparent = current\r\n\t\tcurrent = current.right\r\n\t}\r\n\treturn parent\r\n}" ]
[ "0.7842684", "0.78384054", "0.77299625", "0.76749134", "0.7537389", "0.7500175", "0.73262113", "0.73135996", "0.70279986", "0.695127", "0.6936538", "0.6888183", "0.6833107", "0.6756451", "0.66923714", "0.66854984", "0.664722", "0.6646739", "0.66022724", "0.6602229", "0.6589755", "0.65746534", "0.6540362", "0.6531427", "0.652906", "0.6524639", "0.6521721", "0.65177566", "0.65059084", "0.6488049", "0.64825845", "0.64540493", "0.6441141", "0.6436071", "0.6435153", "0.63893384", "0.63644224", "0.63513446", "0.63373417", "0.63100225", "0.6302706", "0.629306", "0.62717813", "0.6241924", "0.6228862", "0.62113595", "0.6182728", "0.6177602", "0.61752695", "0.61629826", "0.6159427", "0.6151453", "0.6129593", "0.6080513", "0.60774225", "0.60766923", "0.6074811", "0.60713863", "0.60503525", "0.60464", "0.6003573", "0.5971488", "0.59528446", "0.59467953", "0.5929035", "0.59288603", "0.59217054", "0.59139687", "0.59011", "0.5894036", "0.5888664", "0.58533627", "0.5841787", "0.58346945", "0.58160734", "0.5812398", "0.5807978", "0.5786609", "0.57611465", "0.5743322", "0.573475", "0.57193", "0.57079", "0.57015735", "0.569787", "0.56902754", "0.564958", "0.56477404", "0.56426585", "0.56159586", "0.5612668", "0.5602948", "0.5594771", "0.55906224", "0.5585625", "0.55843157", "0.55712223", "0.5561294", "0.55377924", "0.5526892", "0.5505849" ]
0.0
-1
Right ret urn the node's rchild
func Right(i int) int { return 2*i + 1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s SGTree) rightChild(treeIndex int) int {\n\treturn 2*treeIndex + 2\n}", "func RightChild(index, depth uint) (uint, error) {\n\tif index&1 == 0 {\n\t\treturn 0, errors.New(\"No right child\")\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Index(depth-1, 1+(Offset(index, depth)*2)), nil\n}", "func (tree *UTree) Right() *Node {\r\n\tvar parent *Node\r\n\tcurrent := tree.root\r\n\tfor current != nil {\r\n\t\tparent = current\r\n\t\tcurrent = current.right\r\n\t}\r\n\treturn parent\r\n}", "func (tree *Tree) Right() *Node {\n\tvar parent *Node\n\tcurrent := tree.Root\n\tfor current != nil {\n\t\tparent = current\n\t\tcurrent = current.Right\n\t}\n\treturn parent\n}", "func (e *Tree) Right() *Tree { return e.right }", "func (ubt *ubtTree) Right() UnboundBinaryTree {\n\tif ubt.right == nil {\n\t\tubt.right = &ubtTree{}\n\t}\n\treturn ubt.right\n}", "func (eln *EmptyLeafNode) GetRightChild() Node {\n\treturn nil\n}", "func rotateRight(n *rbnode) *rbnode {\n\tif n.left == nil {\n\t\treturn n\n\t}\n\tl := n.left\n\tconnectLeft(n, l.right)\n\treplaceChild(n, l)\n\tconnectRight(l, n)\n\tn.c, l.c = l.c, n.c\n\treturn l\n}", "func rightChild(i int) int {\n\treturn (i * 2) + 2\n}", "func (rbTree *RBTree)rotateRight(X *treeNode) {\n\tvar Y = X.left\n\t// move W to X's left child\n\tX.left = Y.right\n\tif Y.right != nil {\n\t\tY.right.father = X\n\t}\n\t// move Y to X's father's child\n\tY.father = X.father\n\tif X == rbTree.root {\n\t\t// X is root\n\t \trbTree.root = Y\n\t} else if X == X.father.right {\n\t\t// X is father's left child\n\t\tX.father.right = Y\n\t} else {\n\t\t// X is father's right child\n\t\tX.father.left = Y\n\t}\n\t// move X to Y's right child\n\tY.right = X\n\tX.father = Y\n}", "func llrbRotateRight(root *llrbNode) *llrbNode {\n left := root.left\n root.left = left.right\n left.right = root\n left.color = root.color\n root.color = true // the right subtree is now red\n return left // the left child becomes the new root\n}", "func (b *Impl) rotateParentRight(n *node) {\n\tuncle := n.parent.parent.left\n\n\tif uncle.red {\n\t\tn.parent.red = false\n\t\tuncle.red = false\n\t\tn.parent.parent.red = true\n\n\t\tn = n.parent.parent\n\t} else {\n\t\tif n.IsLeftChild() {\n\t\t\tn = n.parent\n\n\t\t\tb.rotateRight(n)\n\t\t}\n\n\t\tn.parent.red = false\n\t\tn.parent.parent.red = true\n\n\t\tb.rotateLeft(n.parent.parent)\n\t}\n}", "func mostRightChild(root *treeNode) *treeNode {\n\tif root == nil {\n\t\treturn root\n\t}\n\tp := root\n\tfor p.right != nil {\n\t\tp = p.right\n\t}\n\treturn p\n}", "func RightRotate(x *Node) *Node {\n\tif x.IsNil {\n\t\treturn x\n\t}\n\n\t// Get left Child\n\t//\n\txLeft := x.LeftChild\n\tif xLeft.IsNil {\n\t\treturn xLeft\n\t}\n\n\t// Assign parent of x as parent of left child\n\t//\n\txParent := x.Parent\n\txLeft.Parent = xParent\n\tif !xParent.IsNil {\n\t\tif xParent.LeftChild == x {\n\t\t\txParent.LeftChild = xLeft\n\t\t} else if xParent.RightChild == x {\n\t\t\txParent.RightChild = xLeft\n\t\t}\n\t}\n\n\txLeftRight := xLeft.RightChild\n\n\t// Set xleft as the parent of x\n\t//\n\tx.Parent = xLeft\n\txLeft.RightChild = x\n\n\t// Set left child of x to right child of xleft\n\t//\n\tx.LeftChild = xLeftRight\n\tif !xLeftRight.IsNil {\n\t\txLeftRight.Parent = x\n\t}\n\n\treturn xLeft\n}", "func (l *Label) rightmostNode(g *Graph) *Label {\n right, _ := l.right(g) // TODO do not ignore error\n if right == nil {\n return l\n }\n return right.rightmostNode(g)\n}", "func (r *Thing) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (h *heap) rightChildIndex(i int64) int64 {\n\treturn i*2 + 2\n}", "func internalNodeRightChildPtr(node []byte) *uint32 {\n\treturn (*uint32)(unsafe.Pointer(&node[InternalNodeRightChildOffset]))\n}", "func (node *node) rightRotate() *node {\n\tvar x = node.LeftNode\n\tvar t3 = x.RightNode\n\n\tx.RightNode = node\n\tnode.LeftNode = t3\n\n\t// update height\n\tnode.height = max(getHeight(node.LeftNode), getHeight(node.RightNode)) + 1\n\tx.height = max(getHeight(x.LeftNode), getHeight(x.RightNode)) + 1\n\n\treturn x\n}", "func RightRotate(n *Node) *Node {\n\tl := n.Left\n\tif l == nil {\n\t\treturn n\n\t}\n\n\tn.Left = l.Right\n\tl.Right = n\n\n\treturn l\n}", "func (r *Folder) URN() *pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (tree *RBTree) rotateRight(node *RBTreeNode) {\n\tif node == nil {\n\t\treturn\n\t}\n\tl := node.left\n\tnode.left = l.right\n\tif l.right != nil {\n\t\tl.right.parent = node\n\t}\n\n\tl.parent = node.parent\n\tif node.parent == nil {\n\t\ttree.root = l\n\t} else {\n\t\tif node.parent.left == node {\n\t\t\tnode.parent.left = l\n\t\t} else {\n\t\t\tnode.parent.right = l\n\t\t}\n\t}\n\tnode.parent = l\n\tl.right = node\n}", "func (n Name) RName() Name { return n }", "func (r *Bucket) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (r *Rule) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func llrbMoveRedRight(root *llrbNode) *llrbNode {\n llrbFlipColor(root)\n if llrbIsRed(root.left.left) {\n root = llrbRotateRight(root)\n llrbFlipColor(root)\n }\n return root\n}", "func (r *ServiceLinkedRole) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (b *Bound) Right() float64 {\n\treturn b.ne[0]\n}", "func (llrb *LLRB) moveredright(nd *Llrbnode) *Llrbnode {\n\tllrb.flip(nd)\n\tif nd.left.left.isred() {\n\t\tnd = llrb.rotateright(nd)\n\t\tllrb.flip(nd)\n\t}\n\treturn nd\n}", "func (r *RouteTable) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (c *Chapter) URN() string {\n\treturn fmt.Sprintf(\"urn:spfg:v1:chapter:%s:%s\", c.ID, slug.Make(c.Name))\n}", "func (r *Distribution) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (tree *DNFTree) CreateRightChild(nodeID int, phi br.ClauseSet, isFinal bool) int {\n\tif debug {\n\t\tif nodeID < 0 {\n\t\t\tpanic(\"Expected nodeID >= 0 in CreateRightChild\")\n\t\t}\n\t\tif nodeID >= len(tree.Content) {\n\t\t\tpanic(\"Expected nodeID < len(content) in CreateRightChild\")\n\t\t}\n\t}\n\tn := tree.Content[nodeID]\n\tid := tree.CreateNodeEntry(phi, n.depth+1, isFinal)\n\tn.rightChild = id\n\treturn id\n}", "func (r *Trail) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (rbnode *RBNode) getMostLeftNode() *RBNode {\n\tif rbnode.left == nil {\n\t\treturn rbnode\n\t}\n\treturn rbnode.left.getMostLeftNode()\n}", "func (r *Document) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (t *RedBlackTree) rotateRight(node *Node) {\n\tleft := node.left\n\tt.swapNodes(node, left)\n\tnode.left = left.right\n\tif left.right != nil {\n\t\tleft.right.parent = node\n\t}\n\tleft.right = node\n\tnode.parent = left\n}", "func (r *Network) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (rbst *RBSTAbelGroup) RotateRight(root *Node, start, stop, k int) *Node {\r\n\tstart++\r\n\tn := stop - start + 1 - k%(stop-start+1)\r\n\r\n\tx, y := rbst.SplitByRank(root, start-1)\r\n\ty, z := rbst.SplitByRank(y, n)\r\n\tz, p := rbst.SplitByRank(z, stop-start+1-n)\r\n\treturn rbst.Merge(rbst.Merge(rbst.Merge(x, z), y), p)\r\n}", "func (r *ResourceGroup) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (mt MerkleTree) RightTree() *MerkleTree {\n\treturn mt.rightTree\n}", "func (root *TreeNode) rightRotate() *TreeNode {\n\tnode := root.left\n\troot.left = node.right\n\tnode.right = root\n\troot.height = max(root.left.getHeight(), root.right.getHeight()) + 1\n\tnode.height = max(node.left.getHeight(), node.right.getHeight()) + 1\n\treturn node\n}", "func (r *PrivateVirtualInterface) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (r *Template) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (r *Policy) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (mySelf SQLJoin) Right() SQLJoin {\n\tmySelf.right = true\n\treturn mySelf\n}", "func (r *SshKey) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (r *LogGroup) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func decendRight(root *SnailfishNumber) *SnailfishNumber {\n\tfor root.rhs != nil {\n\t\troot = root.rhs\n\t}\n\treturn root\n}", "func (r *DomainIdentity) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (n *Node) rotateRight(c *Node) {\n\tl := c.Left\n\tc.Left = l.Right\n\tl.Right = c\n\tif c == n.Left {\n\t\tn.Left = l\n\t} else {\n\t\tn.Right = l\n\t}\n\tc.bal = 0\n\tl.bal = 0\n}", "func (n *node) IRI() string {\n\treturn n.iri\n}", "func rotateRight(root, pivot *Node) *Node {\n\tchild := pivot.Right\n\n\tpivot.Right = root\n\troot.Parent = pivot\n\n\tif child != nil {\n\t\tchild.Parent = root\n\t}\n\troot.Left = child\n\n\treturn pivot\n}", "func (r *Authorizer) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (l *FuncNode) Rvalue() string {\n\treturn \"Variable Node Rvalue()\"\n}", "func (r *DomainName) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func rightMost(node *Node) *Node {\n\tif node == nil {\n\t\treturn nil\n\t}\n\n\tcurrent := node\n\n\tfor {\n\t\tif current.right == nil {\n\t\t\treturn current\n\t\t}\n\t\tcurrent = current.right\n\t}\n}", "func (r *Organization) URN() *pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (n *node) RdfType() string {\n\treturn n.rdfType\n}", "func (h *heap) rightSiblingIndex(i int64) int64 {\n\treturn i + 1\n}", "func (rbt *RBTree) RRange() *RBTreeReverseRange {\n\trbt.init()\n\n\treturn &RBTreeReverseRange{\n\t\tBegin: rbt.RBegin(),\n\t\tEnd: rbt.REnd(),\n\t}\n}", "func (r *Cluster) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (r *Cluster) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (rbnode *RBNode) rotate(isRotateLeft bool) (*RBNode, error) {\n\tvar root *RBNode\n\n\tif rbnode == nil {\n\t\treturn root, nil\n\t}\n\tif !isRotateLeft && rbnode.left == nil {\n\t\treturn root, errors.New(\"The Right Rotate Left Node can't be nil\")\n\t} else if isRotateLeft && rbnode.right == nil {\n\t\treturn root, errors.New(\"The Left Rotate Right Node can't be nil\")\n\t}\n\n\tparent := rbnode.parent\n\t//判断是否左边\n\tvar isleft bool\n\tif parent != nil {\n\t\tisleft = parent.left == rbnode\n\t}\n\n\t//左旋\n\tif isRotateLeft {\n\t\tgrandsonleft := rbnode.right.left\n\t\t//magic operation\n\t\trbnode.right.left = rbnode\n\t\trbnode.parent = rbnode.right\n\t\trbnode.right = grandsonleft\n\t} else {\n\t\t//右旋\n\t\t//记录孙节点\n\t\tgrandsonright := rbnode.left.right\n\t\t//magic operation\n\t\t//要移动的孙节点 将其赋值为节点\n\t\t//节点的父节点设置为节点的左节点\n\t\t//节点的左节点设置为之前保存的孙节点\n\t\trbnode.left.right = rbnode\n\t\trbnode.parent = rbnode.left\n\t\trbnode.left = grandsonright\n\t}\n\n\t//\n\tif parent == nil {\n\t\trbnode.parent.parent = nil\n\t\troot = rbnode.parent\n\t} else {\n\t\tif isleft {\n\t\t\tparent.left = rbnode.parent\n\t\t} else {\n\t\t\tparent.right = rbnode.parent\n\t\t}\n\t\trbnode.parent.parent = parent\n\t}\n\treturn root, nil\n}", "func (tree *Tree) rightRotate(oldRoot *Node) {\n\n\tif oldRoot.left == nil {\n\t\tpanic(\"Attempt to right rotate with nil left node\")\n\t}\n\n\tleftChild := oldRoot.left\n\tleftChild.parent = oldRoot.parent\n\ttmp := leftChild.right\n\tleftChild.right = oldRoot\n\n\toldRoot.left = tmp\n\n\tif oldRoot.parent == nil {\n\t\ttree.root = leftChild\n\t} else if oldRoot.parent.left == oldRoot {\n\t\toldRoot.parent.left = leftChild\n\t} else {\n\t\toldRoot.parent.right = leftChild\n\t}\n\toldRoot.parent = leftChild\n}", "func (r *VpnConnectionRoute) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (self SimpleInterval) Right() float64 {\n\treturn self.LR[1]\n}", "func (o DashboardSpacingPtrOutput) Right() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardSpacing) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Right\n\t}).(pulumi.StringPtrOutput)\n}", "func (r *RedirectNode) RightFD() int { return r.rmap.rfd }", "func right(x uint, n uint) uint {\n\tif level(x) == 0 {\n\t\treturn x\n\t}\n\n\tr := x ^ (0x03 << (level(x) - 1))\n\tfor r > 2*(n-1) {\n\t\tr = left(r)\n\t}\n\treturn r\n}", "func (r *ScheduledAction) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (rbt *RBTree) REnd() RBTreeReverseIterator {\n\trbt.init()\n\treturn RBTreeReverseIterator(rbtreeEndIterator(reverse(rbt)))\n}", "func (t *Tree) rightRotate(x *Node) {\n\ty := x.left\n\tx.left = y.right\n\tif y.right != nil {\n\t\ty.right.p = x\n\t}\n\tt.transplant(x, y)\n\ty.right = x\n\tx.p = y\n}", "func rob(root *TreeNode) int {\n\tif root == nil {\n\t\treturn 0\n\t}\n\tval1 := root.Val\n\tif root.Left != nil {\n\t\tval1 += rob(root.Left.Left) + rob(root.Left.Right)\n\t}\n\tif root.Right != nil {\n\t\tval1 += rob(root.Right.Left) + rob(root.Right.Right)\n\t}\n\tval2 := rob(root.Left) + rob(root.Right)\n\treturn Max(val1, val2)\n}", "func (r *LoadBalancerBackendServerPolicy) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (rbt *RBTree) RUpperBound(d interface{}) RBTreeReverseIterator {\n\trbt.init()\n\treturn RBTreeReverseIterator{\n\t\ttree: rbt,\n\t\tnode: rbtreeUpperBound(d, reverse(rbt)),\n\t}\n}", "func (r *TopicRule) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (c *expression) extendRight(n *expression) *expression {\n\n\tc.right = n\n\tn.parent = c\n\n\tfmt.Printf(\"++++++++++++++++++++++++++ extendRight FROM %s -> [%s] \\n\", c.opr, n.opr)\n\treturn n\n}", "func (r *VpcLink) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (s *Scope) GetRight() raytracing.Vector {\n\treturn *s.Right\n}", "func (n *IfNode) Rvalue() Expr {\n\treturn n.rvalue\n}", "func llrbRotateLeft(root *llrbNode) *llrbNode {\n right := root.right\n root.right = right.left\n right.left = root\n right.color = root.color\n root.color = true // the left subtree is now red\n return right // the right child becomes the new root\n}", "func (o FioSpecVolumeVolumeSourcePtrOutput) Rbd() FioSpecVolumeVolumeSourceRbdPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSource) *FioSpecVolumeVolumeSourceRbd {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Rbd\n\t}).(FioSpecVolumeVolumeSourceRbdPtrOutput)\n}", "func (r *CachesIscsiVolume) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (n *Node) RightRed() bool {\n\treturn n.Right != nil && n.Right.Color == Red\n}", "func (r *LoadBalancerCookieStickinessPolicy) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (o IopingSpecVolumeVolumeSourcePtrOutput) Rbd() IopingSpecVolumeVolumeSourceRbdPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceRbd {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Rbd\n\t}).(IopingSpecVolumeVolumeSourceRbdPtrOutput)\n}", "func (r *Portfolio) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (q Quat) Right() Vec3f {\n\treturn q.RotateVec(Vec3f{1, 0, 0})\n}", "func (pb *PhilosopherBase) RightFork() Fork {\n\treturn Forks[pb.rightForkID()]\n}", "func URN(x string) (string, error) {\n\tu, err := uuid.Parse(string(x))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn u.URN(), nil\n}", "func (o IopingSpecVolumeVolumeSourceOutput) Rbd() IopingSpecVolumeVolumeSourceRbdPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceRbd { return v.Rbd }).(IopingSpecVolumeVolumeSourceRbdPtrOutput)\n}", "func (root *mTreap) rotateRight(y *treapNode) {\n\t// p -> (y (x a b) c)\n\tp := y.parent\n\tx, c := y.left, y.right\n\ta, b := x.left, x.right\n\n\tx.left = a\n\tif a != nil {\n\t\ta.parent = x\n\t}\n\tx.right = y\n\ty.parent = x\n\ty.left = b\n\tif b != nil {\n\t\tb.parent = y\n\t}\n\ty.right = c\n\tif c != nil {\n\t\tc.parent = y\n\t}\n\n\tx.parent = p\n\tif p == nil {\n\t\troot.treap = x\n\t} else if p.left == y {\n\t\tp.left = x\n\t} else {\n\t\tif p.right != y {\n\t\t\tthrow(\"large span treap rotateRight\")\n\t\t}\n\t\tp.right = x\n\t}\n\n\ty.updateInvariants()\n\tx.updateInvariants()\n}", "func (o FioSpecVolumeVolumeSourceOutput) Rbd() FioSpecVolumeVolumeSourceRbdPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSource) *FioSpecVolumeVolumeSourceRbd { return v.Rbd }).(FioSpecVolumeVolumeSourceRbdPtrOutput)\n}", "func (o DashboardSpacingOutput) Right() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DashboardSpacing) *string { return v.Right }).(pulumi.StringPtrOutput)\n}", "func (e *Tree) SetRight(replacement *Tree) { e.right = replacement }", "func (t *treeNode) ShowRight() *BTree {\n\treturn t.right\n}", "func (r *UserProfile) URN() pulumi.URNOutput {\n\treturn r.s.URN()\n}", "func (e Equation) Right() Type {\n\treturn e.right\n}", "func (o Orbit) RNorm() float64 {\n\treturn Norm(o.rVec)\n}", "func (builder *Builder) Right(n uint) *Builder {\n\treturn builder.With(Right(n))\n}" ]
[ "0.69422585", "0.66609776", "0.656084", "0.64772874", "0.64333636", "0.6422469", "0.62607646", "0.6249417", "0.6149255", "0.60102046", "0.5993862", "0.596532", "0.59599054", "0.59236705", "0.5865749", "0.58195287", "0.57743317", "0.57664484", "0.5763913", "0.5758138", "0.57144916", "0.5714443", "0.5689479", "0.5660341", "0.564967", "0.56253606", "0.5624637", "0.5618768", "0.56176543", "0.56135213", "0.5607701", "0.5592727", "0.55792487", "0.5569934", "0.55521774", "0.55411947", "0.55395323", "0.5534745", "0.5525946", "0.5520694", "0.5507621", "0.5500632", "0.54864126", "0.5476674", "0.54760647", "0.5465543", "0.54634666", "0.54505825", "0.5443078", "0.54263794", "0.54142827", "0.5402113", "0.5400439", "0.5385423", "0.53772616", "0.53731805", "0.5373123", "0.5372747", "0.5371995", "0.536502", "0.53508455", "0.53354627", "0.53354627", "0.5331602", "0.5327743", "0.529567", "0.52893937", "0.5286527", "0.5280381", "0.5271179", "0.52688617", "0.5266545", "0.5246953", "0.5225327", "0.5217985", "0.52131903", "0.51873165", "0.51830757", "0.5168103", "0.51648486", "0.5164692", "0.5151465", "0.5149417", "0.5149248", "0.5141094", "0.5132176", "0.5121166", "0.5113243", "0.5110868", "0.51023555", "0.50899476", "0.5085702", "0.5075493", "0.50353605", "0.50216126", "0.50215805", "0.5004457", "0.49886924", "0.4983425", "0.49757692", "0.4967922" ]
0.0
-1
MaxHeapIFY keep the quality of max heap
func MaxHeapIFY(A []int, i int) { var largest int l := Left(i) r := Right(i) // fmt.Println(l, r) if l <= HeapSize && A[l] > A[i] { largest = l } else { largest = i } if r <= HeapSize && A[r] > A[largest] { largest = r } if largest != i { swap(&A[i], &A[largest]) MaxHeapIFY(A, largest) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *Heap) MaxHeap() {\n for i := h.num_nodes; i >= 0; i-- {\n if h.data[i] < h.data[i * 2 + 1] {\n swap(h.data, i, i * 2 + 1)\n }else if len(h.data) > i * 2 + 2 && h.data[i] < h.data[i * 2 + 2] {\n swap(h.data, i, i * 2 + 2)\n }\n }\n\n if !h.MaxHeapTest() {\n h.MaxHeap()\n }\n}", "func (h *heap) buildMaxHeap() {\n\tfor i := parent(h.size - 1); i >= 0; i-- {\n\t\th.maxHeapify(i)\n\t}\n}", "func MaxHeapify(heap []int, index int) {\n\tval := heap[index]\n\tlv, li, lok := LeftChild(heap, index)\n\trv, ri, rok := RightChild(heap, index)\n\n\tif !lok {\n\t\treturn\n\t} else if !rok {\n\t\tif val < lv {\n\t\t\theap[index], heap[li] = heap[li], heap[index]\n\t\t\tMaxHeapify(heap, li)\n\t\t}\n\t} else {\n\t\tif val > lv && val > rv {\n\t\t\treturn\n\t\t} else if lv > rv {\n\t\t\theap[index], heap[li] = heap[li], heap[index]\n\t\t\tMaxHeapify(heap, li)\n\t\t} else {\n\t\t\theap[index], heap[ri] = heap[ri], heap[index]\n\t\t\tMaxHeapify(heap, ri)\n\t\t}\n\t}\n\treturn\n}", "func MaxHeapify(list []Comparable) {\n\tfirstNonLeafNode := int(math.Floor(float64(len(list) / 2)))\n\tfor i := firstNonLeafNode; i >= 0; i-- {\n\n\t\tmaxHeapifyDown(list, i, len(list)-1)\n\t}\n}", "func (b *BHeap) BuildMaxHeap() {\n\tb.HeapSize = b.Keys.Len()\n\tmid := b.Keys.Len()/2 - 1\n\tfor i := mid; i >= 0; i-- {\n\t\tb.MaxHeapify(i)\n\t}\n}", "func (b *BHeap) MaxHeapify(i int) {\n\tlargest := i\n\tl, r := b.left(i), b.right(i)\n\tif l < b.HeapSize && b.Keys.Less(i, l) {\n\t\tlargest = l\n\t}\n\tif r < b.HeapSize && b.Keys.Less(largest, r) {\n\t\tlargest = r\n\t}\n\tif largest != i {\n\t\tb.Keys.Swap(largest, i)\n\t\tb.MaxHeapify(largest)\n\t}\n}", "func MaxHeapify(a []int, used, i int) {\n\tfor {\n\t\tmax := i // record the max position\n\t\tif i*2 <= used && a[i] < a[i*2] {\n\t\t\tmax = i * 2\n\t\t}\n\n\t\tif i*2+1 <= used && a[max] < a[i*2+1] {\n\t\t\tmax = i*2 + 1\n\t\t}\n\n\t\tif max == i {\n\t\t\tbreak\n\t\t}\n\n\t\ta[i], a[max] = a[max], a[i]\n\n\t\ti = max\n\t}\n}", "func MaxHeapify(a []int, i, heapSize int) {\n\tleft := i << 1\n\tright := i<<1 + 1\n\tvar largest int\n\n\tif left <= heapSize && a[left] > a[i] {\n\t\tlargest = left\n\t} else {\n\t\tlargest = i\n\t}\n\n\tif right <= heapSize && a[right] > a[largest] {\n\t\tlargest = right\n\t}\n\n\tif largest != i {\n\t\ta[i], a[largest] = a[largest], a[i]\n\t\tMaxHeapify(a, largest, heapSize)\n\t}\n}", "func BuildMaxHeap(A []int) {\n\tHeapSize = len(A) - 1\n\tfor i := int(math.Ceil(float64(len(A)) / 2)); i >= 1; i-- {\n\t\tMaxHeapIFY(A, i)\n\t}\n}", "func MaxHeapify(arr []int, root int) {\n\tleft := 2 * root\n\tright := 2*root + 1\n\tlargest := root\n\n\t// Find the largest number among root and its left, right child node\n\tif left < len(arr) && arr[left] > arr[largest] {\n\t\tlargest = left\n\t}\n\n\tif right < len(arr) && arr[right] > arr[largest] {\n\t\tlargest = right\n\t}\n\n\tif largest != root {\n\t\t// Swap root with largest child node and rebuild\n\t\t// the max heap for the swapped child node subtree\n\t\tswap(arr, largest, root)\n\t\tMaxHeapify(arr, largest)\n\t}\n}", "func MakeMaxHeap() *MaxHeap {\n maxheap := new(MaxHeap)\n heap.Init(maxheap)\n return maxheap\n}", "func MaxIntHeapify(h []int) {\n\tsliceLen := len(h)\n\tif sliceLen < 2 {\n\t\t// Either empty or a single element, this is a valid \"heap\"\n\t\treturn\n\t}\n\tif sliceLen == 2 {\n\t\tif h[0] < h[1] {\n\t\t\th[0], h[1] = h[1], h[0]\n\t\t}\n\t\treturn\n\t}\n\n\tlastIndex := sliceLen - 1\n\tfor idx := getParentIndex(lastIndex); -1 < idx; idx-- {\n\t\tsiftDown(h, idx)\n\t}\n}", "func BuildMaxHeap(arr []int) {\n\tfor i := len(arr) / 2; i >= 1; i-- {\n\t\tMaxHeapify(arr, i)\n\t}\n}", "func BuildMaxHeap(a []int) {\n\tfor i := ((len(a)) / 2) - 1; i >= 0; i-- {\n\t\tMaxHeapify(a, i, len(a)-1)\n\t}\n}", "func maxHeapify(array []int, i int) {\n\tlargestIdx := i\n\n\tl := left(i)\n\tr := right(i)\n\n\tif l < len(array) && array[l] > array[i] {\n\t\tlargestIdx = l\n\t}\n\n\tif r < len(array) && array[r] > array[largestIdx] {\n\t\tlargestIdx = r\n\t}\n\n\tif i != largestIdx {\n\t\tarray[i], array[largestIdx] = array[largestIdx], array[i]\n\t\tmaxHeapify(array, largestIdx)\n\t}\n}", "func BuildMaxHeap(a []int) {\n\tmaxIdx := len(a) - 1\n\tfor i := maxIdx / 2; 1 <= i; i-- {\n\t\tMaxHeapify(a, maxIdx, i)\n\t}\n}", "func (b *BinaryHeap) MaxHeapWith(element int) (bool, error) {\n\tif b.isEmpty() {\n\t\tb.initialize()\n\t} else if b.isFull() {\n\t\treturn false, errors.New(\"NOT ENOUGH SPACE LEFT IN HEAP\")\n\t}\n\tb.add(element)\n\tb.reAdjustElementsOnAdding(element)\n\tb.CurrentIndex = b.CurrentIndex + 1\n\treturn true, nil\n}", "func (sv *sorterValues) InitMaxHeap() {\n\tsv.invertSorting = true\n\theap.Init(sv)\n}", "func PushMaxHeap(h *MaxHeap, x int) {\n heap.Push(h, x)\n}", "func (h *MaxHeap) Delete() (string, error) {\n\tif h.size == 0 {\n\t\treturn \"\", errors.New(\"Heap empty\")\n\t}\n\tmax := h.data[1]\n\t// Take the last item in the heap and make it the\n\t// new root, even though this is almost certainly\n\t// not the largest element...\n\th.data[1] = h.data[h.size]\n\th.size--\n\n\tparent := 1\n\t// ...and \"sink\" it down to its correct level in the heap.\n\tsink(h.data, parent, h.size)\n\n\treturn max, nil\n}", "func (h *binaryHeap) GetMax() int {\n\tmax := h.items[0]\n\th.items[0], h.items[h.size-1] = h.items[h.size-1], 0\n\th.size--\n\th.siftdown(0)\n\treturn max\n}", "func (m *metricFlinkJvmMemoryHeapMax) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (b *BHeap) MaxHeapInsert(key interface{}) {\n\tb.HeapSize++\n\tb.Keys.Push(key)\n\tb.HeapIncreaseKey(b.HeapSize-1, key)\n}", "func (h Heap) MaxHeapifyDown(pos int) {\n\tleft := pos*2 + 1\n\tright := left + 1\n\n\tmaxPos := pos\n\tif len(h) > left && h[left] > h[maxPos] {\n\t\tmaxPos = left\n\t}\n\tif len(h) > right && h[right] > h[maxPos] {\n\t\tmaxPos = right\n\t}\n\n\tif maxPos == pos {\n\t\treturn\n\t}\n\n\ttmp := h[pos]\n\th[pos] = h[maxPos]\n\th[maxPos] = tmp\n\n\th.MaxHeapifyDown(maxPos)\n}", "func heapify(data []int, root, length int) {\n\tmax := root\n\tl, r := 2*root+1, 2*root+2\n\n\tif l < length && data[l] > data[max] {\n\t\tmax = l\n\t}\n\n\tif r < length && data[r] > data[max] {\n\t\tmax = r\n\t}\n\n\tif max != root {\n\t\tdata[root], data[max] = data[max], data[root]\n\t\theapify(data, max, length)\n\t}\n}", "func PopMaxHeap(h *MaxHeap) interface{}{\n return heap.Pop(h)\n}", "func (h *Heap) RemoveMax() bool {\n\tif h.count == 0 {\n\t\treturn false\n\t}\n\n\th.items[1] = h.count\n\th.count--\n\n\theapify(h.items, h.count, 1)\n\treturn true\n}", "func BuildMax(in []int) Heap {\n\th := Heap(in)\n\n\tpos := len(in) / 2\n\tfor pos > 0 {\n\t\th.MaxHeapifyDown(pos)\n\t}\n\n\treturn nil\n}", "func NewWithCapacity(requested int) (h *MaxHeap) {\n\tpower := 1\n\tfor power < requested {\n\t\tpower *= 2\n\t\tif power < 0 {\n\t\t\t// looks like we wrapped\n\t\t\tpower = mmmdatastructures.MaxInt\n\t\t\tbreak\n\t\t}\n\t}\n\th = new(MaxHeap)\n\th.data = make([]string, power, power)\n\th.capacity = power\n\th.size = 0\n\treturn h\n}", "func New() (h *MaxHeap) {\n\treturn NewWithCapacity(DefaultCapacity)\n}", "func CreateMaxHeap(capacity int) *MaxHeap {\n\tnewHeap := new(MaxHeap)\n\tnewHeap.heap = make([]Comparable, 0, capacity)\n\n\treturn newHeap\n}", "func (h *MaxHeap) RemoveMaxOrMin() {\n\t// return if the heap is empty\n\tif h.used <= 0 {\n\t\treturn\n\t}\n\n\t// move the last data to h.data[1] which is the first data\n\th.data[1] = h.data[h.used]\n\th.data[h.used] = 0\n\th.used--\n\n\tMaxHeapify(h.data, h.used, 1)\n}", "func MaxIntHeapPush(s []int, v int) []int {\n\th := append(s, v)\n\tMaxIntHeapify(h)\n\treturn h\n}", "func (h *MaxHeap) maxHeapifyUp(index int) {\r\n\tfor h.elements[index] > h.elements[parent(index)] {\r\n\t\th.swap(parent(index), index)\r\n\t\tindex = parent(index)\r\n\t}\r\n}", "func heap() []byte {\n\treturn make([]byte, 1024*10)\n}", "func main(){\n\t maxQueue := Constructor()\n\t maxQueue.Push_back(94)\n\t maxQueue.Push_back(16)\n\t maxQueue.Push_back(89)\n\t fmt.Println(maxQueue.Pop_front())\n\t maxQueue.Push_back(22)\n\t maxQueue.Push_back(33)\n\t maxQueue.Push_back(44)\n\t maxQueue.Push_back(111)\n\t maxQueue.Pop_front()\n\t maxQueue.Pop_front()\n\t maxQueue.Pop_front()\n\t fmt.Println(maxQueue.Max_value())\n }", "func (h *Heap) MaxHeapTest() bool {\n ok := true\n for i := h.num_nodes; i >= 0; i-- {\n node := h.data[i]\n if node < h.data[i * 2 + 1] || (len(h.data) > i * 2 + 2 && node < h.data[i * 2 + 2]) {\n ok = false\n break\n }\n }\n return ok\n}", "func NewHeap() Heap {\n\treturn &maxHeightVertexHeap{}\n}", "func main() {\n\th := &IntHeap{2, 1, 5}\n\theap.Init(h)\n\theap.Push(h, 3)\n\tfmt.Printf(\"minimum: %d\\n\", (*h)[0])\n\tfor h.Len() > 0 {\n\t\tfmt.Printf(\"%d \", heap.Pop(h))\n\t}\n\n\tfmt.Println()\n\ttempKthLargest := Constructor(3, []int{1000, 4,5,8,2,9, 10, 100})\n\t//for tempKthLargest.MyHeap.Len() > 0 {\n\t//\tfmt.Printf(\"%d \", heap.Pop(tempKthLargest.MyHeap))\n\t//}\n\tfmt.Println()\n\tfmt.Println(tempKthLargest.Add(10000))\n\n\tConstructor(1, []int{})\n\t//fmt.Println(heap.Pop(temp2.MyHeap))\n}", "func maxHeapAdjust(values []int, index, heapSize int) {\n\n\tleft := getLeftChildIndex(index)\n\tright := getRightChildIndex(index)\n\n\tvar adjustIndex = index\n\tif left < heapSize && values[left] > values[adjustIndex] {\n\t\t//\t\tvalues[index], values[left] = values[left], values[index]\n\t\tadjustIndex = left\n\t}\n\tif right < heapSize && values[right] > values[adjustIndex] {\n\t\t//\t\tvalues[index], values[right] = values[right], values[index]\n\t\tadjustIndex = right\n\t}\n\n\t//\tfmt.Printf(\"%d - %d\\n\", index, adjustIndex)\n\tif adjustIndex != index {\n\t\tvalues[adjustIndex], values[index] = values[index], values[adjustIndex]\n\t\tmaxHeapAdjust(values, adjustIndex, heapSize)\n\t}\n\n}", "func (b *BHeap) HeapMaximum() interface{} {\n\treturn b.Keys.Get(0)\n}", "func (h *MaxHeap) maxHeapifyDown(index int) {\n\n\tlastIndex := len(h.array)-1\n\tl,r := left(index), right(index)\n\tchildToCompare := 0\n\t// loop while index has at least one child\n\tfor l <= lastIndex {\n\t\t// Define child to compare\n\t\t// When there is only one child or the \n\t\tif l == lastIndex {\n\t\t\tchildToCompare = l\n\t\t} else if h.array[l] > h.array[r] { // left child is larger\n\t\t\tchildToCompare = l\n\t\t} else { // When right child is larger\n\t\t\tchildToCompare = r\n\t\t}\n\t\t// Compare array value of current idx to larger child and swap if smaller\n\t\tif h.array[index] < h.array[childToCompare] {\n\t\t\th.swap(index, childToCompare)\n\t\t\tindex = childToCompare\n\t\t\tl,r = left(index), right(index)\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (h *MaxHeap) Max() int {\n\tif h.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn h.data[1]\n}", "func (h *MinHeap) RemoveMaxOrMin() {\n\t// return if the heap is empty\n\tif h.used <= 0 {\n\t\treturn\n\t}\n\n\t// move the last data to h.data[1] which is the first data\n\th.data[1] = h.data[h.used]\n\th.data[h.used] = 0\n\th.used--\n\n\tMinHeapify(h.data, h.used, 1)\n}", "func (h *Heap) Max() (int, bool) {\n\tif len(h.heap) == 0 {\n\t\treturn 0, false\n\t}\n\treturn h.heap[0], true\n}", "func (h *MaxHeap) maxHeapifyDown(index int) {\r\n\tlastIndex := len(h.elements) - 1\r\n\tl, r := left(index), right(index)\r\n\tchildToCompare := 0\r\n\r\n\tfor l <= lastIndex {\r\n\r\n\t\tif l == lastIndex { // if left child is the last child\r\n\t\t\tchildToCompare = l\r\n\t\t} else if h.elements[l] > h.elements[r] { // if left child is larger\r\n\t\t\tchildToCompare = l\r\n\t\t} else { // if right child is larger\r\n\t\t\tchildToCompare = r\r\n\t\t}\r\n\r\n\r\n\t\t// compare element value of current index to the larger child and swap if lower\r\n\t\tif h.elements[index] < h.elements[childToCompare] {\r\n\t\t\th.swap(index, childToCompare)\r\n\t\t\tindex = childToCompare\r\n\t\t\tl, r = left(index), right(index)\r\n\t\t} else {\r\n\t\t\treturn\r\n\t\t}\r\n\t\t\r\n\t}\r\n}", "func TestIHMaxAddOrder1(t *testing.T) {\n\th := NewImplicitHeapMax(false)\n\n\th.Push(1, 1)\n\th.Push(3, 3)\n\th.Push(4, 4)\n\n\ttestIMPriorityOrder(h.a, []int{4, 1, 3}, \"push 1\", t)\n\n\th.Push(2, 2)\n\ttestIMPriorityOrder(h.a, []int{4, 2, 3, 1}, \"push 2\", t)\n\n\th.Push(5, 5)\n\ttestIMPriorityOrder(h.a, []int{5, 4, 3, 1, 2}, \"push 3\", t)\n}", "func (m *metricFlinkJvmMemoryNonheapMax) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func NewMax(capacity int) *MaxHeap {\n\t// set default capacity\n\tif 0 == capacity {\n\t\tcapacity = 16\n\t}\n\n\treturn &MaxHeap{\n\t\tdata: make([]int, capacity),\n\t\tcapacity: capacity,\n\t\tused: 0,\n\t}\n}", "func (h *MaxHeap) maxHeapifyUp(index int) {\n\t// When parent is smaller than current index\n\tfor h.array[parent(index)] < h.array[index] {\n\t\th.swap(parent(index), index)\n\t\tindex = parent(index)\n\t}\n}", "func (h MaxHeap) Len() int { return len(h) }", "func (h *MaxHeap) maxHeapifyDown(index int) {\n\n\tlastIndex := len(h.array) - 1\n\tl, r := leftChild(index), rightChild(index)\n\tchildToCompare := 0\n\n\t//loop while index has at least one child\n\tfor l <= lastIndex {\n\t\t//when left child is the only child\n\t\tif l == lastIndex {\n\t\t\tchildToCompare = l\n\t\t} else if h.array[l] > h.array[r] { //when left child is larger than right\n\t\t\tchildToCompare = l\n\t\t} else { //when right child is larger than left\n\t\t\tchildToCompare = r\n\t\t}\n\n\t\t//compare array value of current index to larger child and swap if smaller\n\t\tif h.array[index] < h.array[childToCompare] {\n\t\t\th.swap(index, childToCompare)\n\t\t\tindex = childToCompare\n\t\t\tl, r = leftChild(index), rightChild(index)\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func main() {\n\tmichael := CreatePerson(\"Michael\", 23)\n\tleah := CreatePerson(\"Leah\", 22)\n\tjake := CreatePerson(\"jake\", 19)\n\ttim := CreatePerson(\"tim\", 12)\n\tlarry := CreatePerson(\"larry\", 20)\n\tlenny := CreatePerson(\"lenny\", 21)\n\tjunior := CreatePerson(\"junior\", 10)\n\n\tpersonList := []Comparable{michael, leah, jake, tim, larry, lenny, junior}\n\n\t// HEAPSORT\n\tfmt.Println(\"### Testing HeapSort Implementation ###\")\n\tfmt.Println(\"Before Sorting:\")\n\tfor _, value := range personList {\n\t\tfmt.Println(value)\n\t}\n\n\tHeapSort(personList)\n\n\tfmt.Println(\"\\nAfter Sorting:\")\n\tfor _, value := range personList {\n\t\tfmt.Println(value)\n\t}\n\n\tfmt.Printf(\"\\n### Constructing Max Heap ###\\n\")\n\tpersonHeap := CreateMaxHeap(10)\n\tpersonHeap.Add(michael)\n\tpersonHeap.Add(leah)\n\tpersonHeap.Add(jake)\n\tpersonHeap.Add(tim)\n\tpersonHeap.Add(larry)\n\tpersonHeap.Add(lenny)\n\tpersonHeap.Add(junior)\n\n\tfmt.Println(\"Popping values from top of Max Heap\")\n\tvalue, ok := personHeap.Pop()\n\tfor ok {\n\t\tfmt.Printf(\"Top Value: %v\\n\", value)\n\t\tvalue, ok = personHeap.Pop()\n\t}\n}", "func initHeap()", "func (h *MaxHeap) maxHeapifyUp(index int) {\n\n\t//if the parent index key is smaller than the currentIndex key\n\tfor h.array[parent(index)] < h.array[index] {\n\t\tfmt.Println(\"===>\\nthis is the current index : \", index, \"\\n======>\")\n\t\th.swap(parent(index), index)\n\t\tindex = parent(index)\n\t\tfmt.Println(\"===>\\nthis is the swap index : \", index, \"\\n======>\")\n\t}\n\n}", "func (a *Graph) PrimHeap() {\n\tthis := a.copy()\n\t// change to undirected graph\n\t// 0 convert to infinity\n\tfor i, _ := range this.edge {\n\t\tif this.edge[i] != 0 {\n\t\t\tthis.edge[i%this.n*this.n+i/this.n] = this.edge[i]\n\t\t}\n\t\tif this.edge[i] == 0 {\n\t\t\tthis.edge[i] = infinity\n\t\t}\n\t}\n\n\th := &priorityQueue{}\n\theap.Init(h)\n\n\tvar vis []bool\n\tvis = make([]bool, this.n)\n\tvis[0] = true\n\n\tvar pre int // record the begin node\n\n\tfor i := 0; i < this.n; i++ {\n\t\tif this.edge[i] != infinity {\n\t\t\theap.Push(h, &space{i, this.edge[i], -1})\n\t\t}\n\t}\n\tpre = 0\n\tfor i := 1; i < this.n; i++ {\n\t\te := heap.Pop(h).(*space)\n\t\tv := e.end\n\t\tvis[v] = true\n\t\tfmt.Println(\"(\", pre, \",\", v, \",\", e.cost, \")\")\n\t\tpre = v\n\t\tfor i := 0; i < this.n; i++ {\n\t\t\tif this.edge[v*this.n+i] != infinity && !vis[i] {\n\t\t\t\theap.Push(h, &space{i, this.edge[v*this.n+i], -1})\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *Heap) MinHeap() {\n for i := h.num_nodes; i >= 0; i-- {\n if h.data[i] > h.data[i * 2 + 1] {\n swap(h.data, i, i * 2 + 1)\n }else if len(h.data) > i * 2 + 2 && h.data[i] > h.data[i * 2 + 2] {\n swap(h.data, i, i * 2 + 2)\n }\n }\n\n if !h.MinHeapTest() {\n h.MinHeap()\n }\n}", "func MakeFixedSizeHeap(mode PriorityQueueMode, limit int,\n\trefCoord Coord) *FixedSizeHeap {\n\n\treturn &FixedSizeHeap{\n\t\tdata: make([]Coord, 0, limit+1),\n\t\tCenterCoord: refCoord,\n\t\tLimit: limit,\n\t\tmode: mode,\n\t}\n}", "func heapify(v Interface, root, size int) {\n\tfor size > 1 {\n\t\tright := root - 1\n\t\tleft := right - leo[size-2]\n\t\tif v.Less(left, right) {\n\t\t\tif v.Less(root, right) {\n\t\t\t\tv.Swap(root, right)\n\t\t\t\troot = right\n\t\t\t\tsize -= 2\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\tif v.Less(root, left) {\n\t\t\t\tv.Swap(root, left)\n\t\t\t\troot = left\n\t\t\t\tsize -= 1\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func MaxIntHeapPop(s []int) (int, []int) {\n\tcpy := make([]int, len(s), cap(s))\n\tcopy(cpy, s)\n\tmaxVal := cpy[0]\n\tlastIndex := len(cpy) - 1\n\tcpy[0] = cpy[lastIndex]\n\tcpy = cpy[:lastIndex]\n\tMaxIntHeapify(cpy)\n\treturn maxVal, cpy\n}", "func (h *MaxHeap) resize(newCapacity int) error {\n\tif newCapacity <= h.capacity {\n\t\treturn errors.Errorf(\"New capacity %d is not larger than current capacity %d\", newCapacity, h.capacity)\n\t}\n\tnewData := make([]string, newCapacity, newCapacity)\n\tfor i := 0; i < len(h.data); i++ {\n\t\tnewData[i] = h.data[i]\n\t}\n\th.capacity = newCapacity\n\th.data = newData\n\treturn nil\n}", "func (heap SkewHeap) Size() int { return heap.size }", "func (m *PriorityQueue) HeapSize() int {\r\n\treturn m.size\r\n}", "func IsMaxHeap(heap []int) bool {\n\tl := len(heap)\n\tfor i := 0; i < l; i++ {\n\t\tleftChild := 2*i + 1\n\t\trightChild := 2*i + 2\n\t\tif leftChild < l && heap[i] < heap[leftChild] {\n\t\t\treturn false\n\t\t}\n\t\tif rightChild < l && heap[i] < heap[rightChild] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (m *metricFlinkJvmMemoryMetaspaceMax) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricFlinkJvmMemoryHeapMax) init() {\n\tm.data.SetName(\"flink.jvm.memory.heap.max\")\n\tm.data.SetDescription(\"The maximum amount of heap memory that can be used for memory management.\")\n\tm.data.SetUnit(\"By\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(false)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n}", "func (b *BHeap) ExtractMax() (interface{}, bool) {\n\tif b.Empty() {\n\t\treturn nil, false\n\t}\n\tmax := b.Keys.Pop()\n\tb.HeapSize--\n\tb.MaxHeapify(0)\n\treturn max, true\n}", "func heapify(arr []int, count, i int) {\n\tfor {\n\t\tmaxPos := i\n\n\t\tif (i*2 <= count) && (arr[i] < arr[i*2]) {\n\t\t\tmaxPos = i * 2\n\t\t}\n\t\tif (i*2+1 <= count) && (arr[maxPos] < arr[i*2+1]) {\n\t\t\tmaxPos = i*2 + 1\n\t\t}\n\t\tif maxPos == i {\n\t\t\tbreak\n\t\t}\n\n\t\tarr[i], arr[maxPos] = arr[maxPos], arr[i]\n\t\ti = maxPos\n\t}\n}", "func (h *Heap) heapify(idx int) {\n\tfor {\n\t\t// find biggest among element with index idx and his children\n\t\tbiggest := idx\n\t\tleft := 2*idx + 1\n\t\tright := 2 * (idx + 1)\n\t\tif left < len(h.heap) && h.heap[idx] < h.heap[left] {\n\t\t\tbiggest = left\n\t\t}\n\n\t\tif right < len(h.heap) && h.heap[biggest] < h.heap[right] {\n\t\t\tbiggest = right\n\t\t}\n\n\t\tif biggest == idx {\n\t\t\tbreak // there is nothing more to normalize\n\t\t}\n\n\t\t// swap biggest element with element idx\n\t\t// and perfome the same procedure for new index\n\t\th.heap[biggest], h.heap[idx] = h.heap[idx], h.heap[biggest]\n\t\tidx = biggest\n\t}\n}", "func (h *binaryHeap) Heapify() {\n\tnonLeafNode := h.len / 2\n\tfor i := nonLeafNode; i > 0; i-- {\n\t\th.bubbleDown(i)\n\t}\n}", "func newWorker(max int) *worker {\n\tworker := &worker{cutoff: max}\n\tworker.Grow(max) // allocating memory here seemed to help performance\n\treturn worker\n}", "func MaxHeapSort(array []int) {\r\n\tvar n int = len(array)\r\n\tMakeMaxHeap(array)\r\n\r\n\tfor i := n - 1; i >= 1; i-- {\r\n\t\tarray[0], array[i] = array[i], array[0]\r\n\t\tMaxHeapFixdown(array, 0, i)\r\n\t}\r\n\r\n}", "func (pq *PQueue) removeMax() int {\n\tif pq.pos >= 1 {\n\t\tmaxI := pq.queue[1]\n\t\tpq.queue[1] = pq.queue[pq.pos]\n\t\tpq.queue[pq.pos] = -1\n\t\tpq.pos--\n\n\t\tfor i := 1 ; i*2 < pq.pos ; i*=2 {\n\t\t\tif pq.queue[2*i] > pq.queue[2*i+1] {\n\t\t\t\tif pq.queue[i] < pq.queue[2*i] {\n\t\t\t\t\tpq.queue[i], pq.queue[2*i] = pq.queue[2*i], pq.queue[i]\n\t\t\t\t}\t\n\t\t\t} else {\n\t\t\t\tif pq.queue[i] < pq.queue[2*i+1] {\n\t\t\t\t\tpq.queue[i], pq.queue[2*i+1] = pq.queue[2*i+1], pq.queue[i]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn maxI\n\t} else {\n\t\treturn -1\n\t}\n}", "func main() {\n\tmedianFinder := Constructor()\n\tmedianFinder.AddNum(40)\n\tmedianFinder.AddNum(12)\n\tmedianFinder.AddNum(16)\n\tmedianFinder.AddNum(14)\n\tmedianFinder.AddNum(35)\n\tmedianFinder.AddNum(19)\n\tmedianFinder.AddNum(34)\n\tmedianFinder.AddNum(35)\n\tmedianFinder.AddNum(28)\n\tmedianFinder.AddNum(35)\n\tmedianFinder.AddNum(26)\n\tmedianFinder.AddNum(6)\n\tmedianFinder.AddNum(8)\n\tmedianFinder.AddNum(2)\n\tmedianFinder.AddNum(14)\n\tmedianFinder.AddNum(25)\n\tmedianFinder.AddNum(25)\n\tmedianFinder.AddNum(4)\n\tmedianFinder.AddNum(33)\n\tmedianFinder.AddNum(18)\n\tmedianFinder.AddNum(10)\n\tmedianFinder.AddNum(14)\n\tfmt.Println(medianFinder.FindMedian())\n\n\tfmt.Println(bigHeapifyFromUp([]int{6, 19, 26, 12, 16, 14}, 0, 5))\n}", "func (h *MaxHeap) Capacity() int {\n\treturn h.capacity\n}", "func (p *PackingEfficiency) Max() float64 {\n\treturn math.Max(p.GPU, math.Max(p.CPU, p.Memory))\n}", "func main() {\n\t// 1, 7, 2, 3, 8, 1, 1 : collide two max stones : 7, 8 here remaining 1 . 1 will added\n\t// 1, 2, 3, 1, 1, 1 : collide 3 and 2 and remaining 1 will be added\n\t// 1, 1, 1, 1, 1 : collide 1, 1 nothing will be added\n\t// 1 1 1 : collide 1 and 1 nothing will be added\n\t// 1 will be answer\n\ta := []int{1, 7, 2, 3, 8, 1, 1}\n\n\t/*\n\t\t// this works too\n\t\th := &IntHeap{}\n\t\theap.Init(h)\n\t\tfor _, item := range a {\n\t\t\theap.Push(h, item)\n\t\t}\n\t*/\n\n\thh := IntHeap(a)\n\th := &hh\n\theap.Init(h)\n\tfor h.Len() >= 2 {\n\t\telement1 := heap.Pop(h)\n\t\telement2 := heap.Pop(h)\n\t\titem1 := element1.(int)\n\t\titem2 := element2.(int)\n\n\t\tfmt.Println(\"item1 popped=\", item1)\n\t\tfmt.Println(\"item2 popped=\", item2)\n\n\t\tif item1 > item2 {\n\t\t\theap.Push(h, item1-item2)\n\t\t}\n\t}\n\tif h.Len() > 0 {\n\t\tfmt.Println(\"answer=\", heap.Pop(h))\n\t} else {\n\t\tfmt.Println(\"answer is empty\")\n\t}\n\n}", "func Example_intHeap() {\n\th := &IntHeap{2, 1, 5}\n\theap.Init(h)\n\theap.Push(h, 3)\n\tfmt.Printf(\"minimum: %d\\n\", (*h)[0])\n\tfor h.Len() > 0 {\n\t\tfmt.Printf(\"%d \", heap.Pop(h))\n\t}\n\t// Output:\n\t// minimum: 1\n\t// 1 2 3 5\n}", "func Example_intHeap() {\n\th := &IntHeap{2, 1, 5}\n\theap.Init(h)\n\theap.Push(h, 3)\n\tfmt.Printf(\"minimum: %d\\n\", (*h)[0])\n\tfor h.Len() > 0 {\n\t\tfmt.Printf(\"%d \", heap.Pop(h))\n\t}\n\t// Output:\n\t// minimum: 1\n\t// 1 2 3 5\n}", "func (h *MaxHeap) Size() int {\n\treturn h.size\n}", "func Example_int64Heap() {\n\th := &Int64Heap{2, 1, 5}\n\theap.Init(h)\n\theap.Push(h, int64(3))\n\tfmt.Printf(\"minimum: %d\\n\", (*h)[0])\n\tfor h.Len() > 0 {\n\t\tfmt.Printf(\"%d \", heap.Pop(h))\n\t}\n\t// Output:\n\t// minimum: 1\n\t// 1 2 3 5\n}", "func NewMax(elements ...*PQElement) *PriorityQueue {\n\treturn New(true, elements...)\n}", "func (this *FeedableBuffer) Maximize() {\n\tthis.ExpandTo(this.maxByteCount)\n}", "func (m *metricFlinkJvmMemoryHeapCommitted) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (o ElasticPoolPerDatabaseSettingsOutput) MaxCapacity() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v ElasticPoolPerDatabaseSettings) *float64 { return v.MaxCapacity }).(pulumi.Float64PtrOutput)\n}", "func TestHeap(t *testing.T) {\n\tt.Run(\"Remove\", func(t *testing.T) {\n\n\t})\n}", "func (h *Heap) ExtractMax() (int, bool) {\n\tif len(h.heap) == 0 {\n\t\treturn 0, false\n\t}\n\n\tmax := h.heap[0]\n\tlast := len(h.heap) - 1\n\th.heap[0] = h.heap[last]\n\th.heap = h.heap[:last]\n\n\th.heapify(0)\n\treturn max, true\n}", "func (mb *MetricsBuilder) RecordFlinkJvmMemoryHeapMaxDataPoint(ts pcommon.Timestamp, inputVal string) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for FlinkJvmMemoryHeapMax, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricFlinkJvmMemoryHeapMax.recordDataPoint(mb.startTime, ts, val)\n\treturn nil\n}", "func (m *metricFlinkJvmMemoryNonheapMax) init() {\n\tm.data.SetName(\"flink.jvm.memory.nonheap.max\")\n\tm.data.SetDescription(\"The maximum amount of non-heap memory that can be used for memory management.\")\n\tm.data.SetUnit(\"By\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(false)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n}", "func FetchHeap(r *bufio.Reader) (*PeepHeap, int) {\n\tn, t := ReadConstraints(r)\n\tpeeps := &PeepHeap{}\n\tfor i := 0; i < n; i++ {\n\t\tline, err := r.ReadBytes('\\n')\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlineString := strings.TrimSuffix(string(line), \"\\n\")\n\t\tnums := strings.Split(lineString, \" \")\n\t\tvalue, err := strconv.Atoi(nums[0])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlimit, err := strconv.Atoi(nums[1])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\theap.Push(peeps, Peep{Limit: limit, Value: value})\n\t}\n\treturn peeps, t\n}", "func MaxIntHeapSort(s []int) {\n\tMaxIntHeapify(s) // just in case it's not a heap when we get it.\n\tfor idx := len(s) - 1; idx > 0; idx-- {\n\t\ts[0], s[idx] = s[idx], s[0]\n\t\tMaxIntHeapify(s[:idx])\n\t}\n}", "func (h *Heap) InitHeap(values []interface{}) {\n\t// Assign the values first.\n\th.values = append([]interface{}{nil}, values...)\n\th.size = len(values)\n\n\t// Start from the parent of the last node.\n\t// Loop back to the root, which is index 1.\n\tlastParent := h.size / 2\n\tfor i := lastParent; i >= 1; i-- {\n\t\t// Cache the value of node to data[0]\n\t\th.values[0] = h.values[i]\n\t\t// Loop through the subtrees to maintain.\n\t\tnode := i\n\t\t// keep iterating as long as the node still has left child.\n\t\tfor node*2 <= h.size {\n\t\t\t// get left child\n\t\t\tnode = node * 2\n\n\t\t\t// if has left child and right child and right child is larger\n\t\t\t// get the right child.\n\t\t\tif node < h.size {\n\t\t\t\tif (h.HeapType == HeapTypeMax && h.Comparator(h.values[node], h.values[node+1]) <= 0) ||\n\t\t\t\t\t(h.HeapType == HeapTypeMin && h.Comparator(h.values[node], h.values[node+1]) >= 0) {\n\t\t\t\t\tnode++\n\t\t\t\t}\n\t\t\t}\n\t\t\t// if current value is larger than the current biggest value in its children.\n\t\t\tif (h.HeapType == HeapTypeMax && h.Comparator(h.values[0], h.values[node]) >= 0) ||\n\t\t\t\t(h.HeapType == HeapTypeMin && h.Comparator(h.values[0], h.values[node]) <= 0) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Otherwise, we switch the value of the parent of current child.\n\t\t\th.values[node/2] = h.values[node]\n\t\t\th.values[node] = h.values[0]\n\t\t}\n\t}\n}", "func (bh* BinomialHeap) Size() int {\n return bh.size\n}", "func (b *BHeap) BuildMinHeap() {\n\tmid := b.Keys.Len()/2 - 1\n\tfor i := mid; i >= 0; i-- {\n\t\tb.MinHeapify(i)\n\t}\n}", "func (m *metricFlinkJvmMemoryNonheapCommitted) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (h minHeap) Len() int { return len(h) }", "func TestTxFeePrioHeap(t *testing.T) {\n\t// Create some fake priority items that exercise the expected sort\n\t// edge conditions.\n\ttestItems := []*txPrioItem{\n\t\t{feePerKB: 5678, priority: 1},\n\t\t{feePerKB: 5678, priority: 1}, // Duplicate fee and prio\n\t\t{feePerKB: 5678, priority: 5},\n\t\t{feePerKB: 5678, priority: 2},\n\t\t{feePerKB: 1234, priority: 3},\n\t\t{feePerKB: 1234, priority: 1},\n\t\t{feePerKB: 1234, priority: 5},\n\t\t{feePerKB: 1234, priority: 5}, // Duplicate fee and prio\n\t\t{feePerKB: 1234, priority: 2},\n\t\t{feePerKB: 10000, priority: 0}, // Higher fee, smaller prio\n\t\t{feePerKB: 0, priority: 10000}, // Higher prio, lower fee\n\t}\n\tnumItems := len(testItems)\n\n\t// Add random data in addition to the edge conditions already manually\n\t// specified.\n\trandSeed := rand.Int63()\n\tdefer func() {\n\t\tif t.Failed() {\n\t\t\tt.Logf(\"Random numbers using seed: %v\", randSeed)\n\t\t}\n\t}()\n\tprng := rand.New(rand.NewSource(randSeed))\n\tfor i := 0; i < 1000; i++ {\n\t\ttestItems = append(testItems, &txPrioItem{\n\t\t\tfeePerKB: prng.Float64() * dcrutil.AtomsPerCoin,\n\t\t\tpriority: prng.Float64() * 100,\n\t\t})\n\t}\n\n\t// Test sorting by fee per KB then priority.\n\tvar highest *txPrioItem\n\tpriorityQueue := newTxPriorityQueue(len(testItems), txPQByFee)\n\tfor i := 0; i < len(testItems); i++ {\n\t\tprioItem := testItems[i]\n\t\tif highest == nil {\n\t\t\thighest = prioItem\n\t\t}\n\t\tif prioItem.feePerKB >= highest.feePerKB {\n\t\t\thighest = prioItem\n\n\t\t\tif prioItem.feePerKB == highest.feePerKB {\n\t\t\t\tif prioItem.priority >= highest.priority {\n\t\t\t\t\thighest = prioItem\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\theap.Push(priorityQueue, prioItem)\n\t}\n\n\tfor i := 0; i < len(testItems); i++ {\n\t\tprioItem := heap.Pop(priorityQueue).(*txPrioItem)\n\t\tfeesEqual := false\n\t\tswitch {\n\t\tcase prioItem.feePerKB > highest.feePerKB:\n\t\t\tt.Fatalf(\"priority sort: item (fee per KB: %v, \"+\n\t\t\t\t\"priority: %v) higher than than prev \"+\n\t\t\t\t\"(fee per KB: %v, priority %v)\",\n\t\t\t\tprioItem.feePerKB, prioItem.priority,\n\t\t\t\thighest.feePerKB, highest.priority)\n\t\tcase prioItem.feePerKB == highest.feePerKB:\n\t\t\tfeesEqual = true\n\t\tdefault:\n\t\t}\n\t\tif feesEqual {\n\t\t\tswitch {\n\t\t\tcase prioItem.priority > highest.priority:\n\t\t\t\tt.Fatalf(\"priority sort: item (fee per KB: %v, \"+\n\t\t\t\t\t\"priority: %v) higher than than prev \"+\n\t\t\t\t\t\"(fee per KB: %v, priority %v)\",\n\t\t\t\t\tprioItem.feePerKB, prioItem.priority,\n\t\t\t\t\thighest.feePerKB, highest.priority)\n\t\t\tcase prioItem.priority == highest.priority:\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\n\t\thighest = prioItem\n\t}\n\n\t// Test sorting by priority then fee per KB.\n\thighest = nil\n\tpriorityQueue = newTxPriorityQueue(numItems, txPQByPriority)\n\tfor i := 0; i < len(testItems); i++ {\n\t\tprioItem := testItems[i]\n\t\tif highest == nil {\n\t\t\thighest = prioItem\n\t\t}\n\t\tif prioItem.priority >= highest.priority {\n\t\t\thighest = prioItem\n\n\t\t\tif prioItem.priority == highest.priority {\n\t\t\t\tif prioItem.feePerKB >= highest.feePerKB {\n\t\t\t\t\thighest = prioItem\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\theap.Push(priorityQueue, prioItem)\n\t}\n\n\tfor i := 0; i < len(testItems); i++ {\n\t\tprioItem := heap.Pop(priorityQueue).(*txPrioItem)\n\t\tprioEqual := false\n\t\tswitch {\n\t\tcase prioItem.priority > highest.priority:\n\t\t\tt.Fatalf(\"priority sort: item (fee per KB: %v, \"+\n\t\t\t\t\"priority: %v) higher than than prev \"+\n\t\t\t\t\"(fee per KB: %v, priority %v)\",\n\t\t\t\tprioItem.feePerKB, prioItem.priority,\n\t\t\t\thighest.feePerKB, highest.priority)\n\t\tcase prioItem.priority == highest.priority:\n\t\t\tprioEqual = true\n\t\tdefault:\n\t\t}\n\t\tif prioEqual {\n\t\t\tswitch {\n\t\t\tcase prioItem.feePerKB > highest.feePerKB:\n\t\t\t\tt.Fatalf(\"priority sort: item (fee per KB: %v, \"+\n\t\t\t\t\t\"priority: %v) higher than than prev \"+\n\t\t\t\t\t\"(fee per KB: %v, priority %v)\",\n\t\t\t\t\tprioItem.feePerKB, prioItem.priority,\n\t\t\t\t\thighest.feePerKB, highest.priority)\n\t\t\tcase prioItem.priority == highest.priority:\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\n\t\thighest = prioItem\n\t}\n}", "func (h *MaxHeap) Insert(str string) error {\n\tif h.size+1 > h.capacity {\n\t\tnewCapacity := h.capacity * 2\n\t\t// if newCapacity became negative, we have exceeded\n\t\t// our capacity by doing one bit-shift too far\n\t\tif newCapacity < 0 {\n\t\t\treturn errors.New(\"Capacity exceeded\")\n\t\t}\n\t\t// NOTE: Purposefully not concerning ourselves\n\t\t// with the error returned from Resize here, because\n\t\t// we know our newCapacity is larger than q.capacity.\n\t\th.resize(newCapacity)\n\t}\n\t// Increase the size of the max heap. Usefully, the size\n\t// is also the new last index into the backing slice.\n\t// Put our new value there. Then, bubble the new value\n\t// up, swapping it with its parent, until it is in the\n\t// correct position in the max heap.\n\th.size++\n\th.data[h.size] = str\n\tchild := h.size\n\tfor parent := child / 2; parent > 0; parent = child / 2 {\n\t\tif h.data[child] > h.data[parent] {\n\t\t\th.data[child], h.data[parent] = h.data[parent], h.data[child]\n\t\t}\n\t\tchild = parent\n\t}\n\treturn nil\n}", "func (o ApplicationMetricDescriptionOutput) MaximumCapacity() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v ApplicationMetricDescription) *float64 { return v.MaximumCapacity }).(pulumi.Float64PtrOutput)\n}", "func maximize() int64 {\n\tmax := 0\n\tmaxItem := int64(0)\n\t// var cache Cache\n\n\t// The larger the cache, the faster it is. Even without a\n\t// cache, it's only around a second on a modern machine, so\n\t// not that big of a deal.\n\t// cache.init(10000)\n\n\tfor x := int64(1); x < 1000000; x++ {\n\t\tcount := collatz2(x)\n\t\t// count := cache.chainLen(x)\n\t\tif count > max {\n\t\t\tmax = count\n\t\t\tmaxItem = x\n\t\t}\n\t}\n\tfmt.Printf(\"%d, %d\\n\", maxItem, max)\n\treturn maxItem\n}" ]
[ "0.7564299", "0.72031695", "0.7078273", "0.70533323", "0.7027819", "0.68514633", "0.67852706", "0.6690617", "0.6680223", "0.6646162", "0.6530533", "0.6525325", "0.6512418", "0.65064913", "0.6497302", "0.6484673", "0.6451575", "0.6400144", "0.63021207", "0.6280715", "0.62640846", "0.6256402", "0.6232105", "0.6229807", "0.62200063", "0.6201473", "0.6187763", "0.61591154", "0.6150876", "0.6144529", "0.61419463", "0.6137136", "0.6133644", "0.6131801", "0.61179125", "0.6106696", "0.610383", "0.6093282", "0.60737306", "0.60654676", "0.60400534", "0.6033334", "0.6030809", "0.602987", "0.60200846", "0.59937066", "0.5991647", "0.59526634", "0.5947152", "0.5945595", "0.5940426", "0.59317", "0.5915795", "0.5885449", "0.5839903", "0.5772904", "0.57580894", "0.575128", "0.57407117", "0.573578", "0.5735213", "0.57255316", "0.57197523", "0.5671765", "0.564929", "0.5647974", "0.5646828", "0.56458074", "0.56445676", "0.5643416", "0.56267875", "0.5625007", "0.5611412", "0.56100065", "0.5602597", "0.55695873", "0.5563231", "0.55593455", "0.55593455", "0.5555377", "0.5542502", "0.5524181", "0.5511245", "0.5480201", "0.5457773", "0.54507214", "0.54417866", "0.5428595", "0.542465", "0.540991", "0.5408775", "0.5401278", "0.5397626", "0.53920186", "0.5375404", "0.5367524", "0.53611165", "0.535754", "0.53512096", "0.53453964" ]
0.68308735
6
BuildMaxHeap build max heap
func BuildMaxHeap(A []int) { HeapSize = len(A) - 1 for i := int(math.Ceil(float64(len(A)) / 2)); i >= 1; i-- { MaxHeapIFY(A, i) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *heap) buildMaxHeap() {\n\tfor i := parent(h.size - 1); i >= 0; i-- {\n\t\th.maxHeapify(i)\n\t}\n}", "func (b *BHeap) BuildMaxHeap() {\n\tb.HeapSize = b.Keys.Len()\n\tmid := b.Keys.Len()/2 - 1\n\tfor i := mid; i >= 0; i-- {\n\t\tb.MaxHeapify(i)\n\t}\n}", "func BuildMax(in []int) Heap {\n\th := Heap(in)\n\n\tpos := len(in) / 2\n\tfor pos > 0 {\n\t\th.MaxHeapifyDown(pos)\n\t}\n\n\treturn nil\n}", "func BuildMaxHeap(a []int) {\n\tmaxIdx := len(a) - 1\n\tfor i := maxIdx / 2; 1 <= i; i-- {\n\t\tMaxHeapify(a, maxIdx, i)\n\t}\n}", "func BuildMaxHeap(a []int) {\n\tfor i := ((len(a)) / 2) - 1; i >= 0; i-- {\n\t\tMaxHeapify(a, i, len(a)-1)\n\t}\n}", "func BuildMaxHeap(arr []int) {\n\tfor i := len(arr) / 2; i >= 1; i-- {\n\t\tMaxHeapify(arr, i)\n\t}\n}", "func (h *Heap) MaxHeap() {\n for i := h.num_nodes; i >= 0; i-- {\n if h.data[i] < h.data[i * 2 + 1] {\n swap(h.data, i, i * 2 + 1)\n }else if len(h.data) > i * 2 + 2 && h.data[i] < h.data[i * 2 + 2] {\n swap(h.data, i, i * 2 + 2)\n }\n }\n\n if !h.MaxHeapTest() {\n h.MaxHeap()\n }\n}", "func MakeMaxHeap() *MaxHeap {\n maxheap := new(MaxHeap)\n heap.Init(maxheap)\n return maxheap\n}", "func CreateMaxHeap(capacity int) *MaxHeap {\n\tnewHeap := new(MaxHeap)\n\tnewHeap.heap = make([]Comparable, 0, capacity)\n\n\treturn newHeap\n}", "func MaxHeapify(list []Comparable) {\n\tfirstNonLeafNode := int(math.Floor(float64(len(list) / 2)))\n\tfor i := firstNonLeafNode; i >= 0; i-- {\n\n\t\tmaxHeapifyDown(list, i, len(list)-1)\n\t}\n}", "func NewMax(capacity int) *MaxHeap {\n\t// set default capacity\n\tif 0 == capacity {\n\t\tcapacity = 16\n\t}\n\n\treturn &MaxHeap{\n\t\tdata: make([]int, capacity),\n\t\tcapacity: capacity,\n\t\tused: 0,\n\t}\n}", "func (sv *sorterValues) InitMaxHeap() {\n\tsv.invertSorting = true\n\theap.Init(sv)\n}", "func MaxHeapify(heap []int, index int) {\n\tval := heap[index]\n\tlv, li, lok := LeftChild(heap, index)\n\trv, ri, rok := RightChild(heap, index)\n\n\tif !lok {\n\t\treturn\n\t} else if !rok {\n\t\tif val < lv {\n\t\t\theap[index], heap[li] = heap[li], heap[index]\n\t\t\tMaxHeapify(heap, li)\n\t\t}\n\t} else {\n\t\tif val > lv && val > rv {\n\t\t\treturn\n\t\t} else if lv > rv {\n\t\t\theap[index], heap[li] = heap[li], heap[index]\n\t\t\tMaxHeapify(heap, li)\n\t\t} else {\n\t\t\theap[index], heap[ri] = heap[ri], heap[index]\n\t\t\tMaxHeapify(heap, ri)\n\t\t}\n\t}\n\treturn\n}", "func PushMaxHeap(h *MaxHeap, x int) {\n heap.Push(h, x)\n}", "func MaxHeapify(arr []int, root int) {\n\tleft := 2 * root\n\tright := 2*root + 1\n\tlargest := root\n\n\t// Find the largest number among root and its left, right child node\n\tif left < len(arr) && arr[left] > arr[largest] {\n\t\tlargest = left\n\t}\n\n\tif right < len(arr) && arr[right] > arr[largest] {\n\t\tlargest = right\n\t}\n\n\tif largest != root {\n\t\t// Swap root with largest child node and rebuild\n\t\t// the max heap for the swapped child node subtree\n\t\tswap(arr, largest, root)\n\t\tMaxHeapify(arr, largest)\n\t}\n}", "func New() (h *MaxHeap) {\n\treturn NewWithCapacity(DefaultCapacity)\n}", "func BuildHeap(arr []int) {\n\tif len(arr) == 0 {\n\t\treturn\n\t}\n\tfor i := len(arr) / 2; i >= 0; i-- {\n\t\tDownAdjust(arr, i, len(arr))\n\t}\n}", "func NewWithCapacity(requested int) (h *MaxHeap) {\n\tpower := 1\n\tfor power < requested {\n\t\tpower *= 2\n\t\tif power < 0 {\n\t\t\t// looks like we wrapped\n\t\t\tpower = mmmdatastructures.MaxInt\n\t\t\tbreak\n\t\t}\n\t}\n\th = new(MaxHeap)\n\th.data = make([]string, power, power)\n\th.capacity = power\n\th.size = 0\n\treturn h\n}", "func (h *binaryHeap) GetMax() int {\n\tmax := h.items[0]\n\th.items[0], h.items[h.size-1] = h.items[h.size-1], 0\n\th.size--\n\th.siftdown(0)\n\treturn max\n}", "func MaxHeapify(a []int, i, heapSize int) {\n\tleft := i << 1\n\tright := i<<1 + 1\n\tvar largest int\n\n\tif left <= heapSize && a[left] > a[i] {\n\t\tlargest = left\n\t} else {\n\t\tlargest = i\n\t}\n\n\tif right <= heapSize && a[right] > a[largest] {\n\t\tlargest = right\n\t}\n\n\tif largest != i {\n\t\ta[i], a[largest] = a[largest], a[i]\n\t\tMaxHeapify(a, largest, heapSize)\n\t}\n}", "func main() {\n\th := &IntHeap{2, 1, 5}\n\theap.Init(h)\n\theap.Push(h, 3)\n\tfmt.Printf(\"minimum: %d\\n\", (*h)[0])\n\tfor h.Len() > 0 {\n\t\tfmt.Printf(\"%d \", heap.Pop(h))\n\t}\n\n\tfmt.Println()\n\ttempKthLargest := Constructor(3, []int{1000, 4,5,8,2,9, 10, 100})\n\t//for tempKthLargest.MyHeap.Len() > 0 {\n\t//\tfmt.Printf(\"%d \", heap.Pop(tempKthLargest.MyHeap))\n\t//}\n\tfmt.Println()\n\tfmt.Println(tempKthLargest.Add(10000))\n\n\tConstructor(1, []int{})\n\t//fmt.Println(heap.Pop(temp2.MyHeap))\n}", "func (h *MaxHeap) Max() int {\n\tif h.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn h.data[1]\n}", "func MaxIntHeapPush(s []int, v int) []int {\n\th := append(s, v)\n\tMaxIntHeapify(h)\n\treturn h\n}", "func MaxHeapify(a []int, used, i int) {\n\tfor {\n\t\tmax := i // record the max position\n\t\tif i*2 <= used && a[i] < a[i*2] {\n\t\t\tmax = i * 2\n\t\t}\n\n\t\tif i*2+1 <= used && a[max] < a[i*2+1] {\n\t\t\tmax = i*2 + 1\n\t\t}\n\n\t\tif max == i {\n\t\t\tbreak\n\t\t}\n\n\t\ta[i], a[max] = a[max], a[i]\n\n\t\ti = max\n\t}\n}", "func (h *Heap) MaxHeapTest() bool {\n ok := true\n for i := h.num_nodes; i >= 0; i-- {\n node := h.data[i]\n if node < h.data[i * 2 + 1] || (len(h.data) > i * 2 + 2 && node < h.data[i * 2 + 2]) {\n ok = false\n break\n }\n }\n return ok\n}", "func (b *BHeap) BuildMinHeap() {\n\tmid := b.Keys.Len()/2 - 1\n\tfor i := mid; i >= 0; i-- {\n\t\tb.MinHeapify(i)\n\t}\n}", "func (b *BinaryHeap) MaxHeapWith(element int) (bool, error) {\n\tif b.isEmpty() {\n\t\tb.initialize()\n\t} else if b.isFull() {\n\t\treturn false, errors.New(\"NOT ENOUGH SPACE LEFT IN HEAP\")\n\t}\n\tb.add(element)\n\tb.reAdjustElementsOnAdding(element)\n\tb.CurrentIndex = b.CurrentIndex + 1\n\treturn true, nil\n}", "func MaxIntHeapify(h []int) {\n\tsliceLen := len(h)\n\tif sliceLen < 2 {\n\t\t// Either empty or a single element, this is a valid \"heap\"\n\t\treturn\n\t}\n\tif sliceLen == 2 {\n\t\tif h[0] < h[1] {\n\t\t\th[0], h[1] = h[1], h[0]\n\t\t}\n\t\treturn\n\t}\n\n\tlastIndex := sliceLen - 1\n\tfor idx := getParentIndex(lastIndex); -1 < idx; idx-- {\n\t\tsiftDown(h, idx)\n\t}\n}", "func main(){\n\t maxQueue := Constructor()\n\t maxQueue.Push_back(94)\n\t maxQueue.Push_back(16)\n\t maxQueue.Push_back(89)\n\t fmt.Println(maxQueue.Pop_front())\n\t maxQueue.Push_back(22)\n\t maxQueue.Push_back(33)\n\t maxQueue.Push_back(44)\n\t maxQueue.Push_back(111)\n\t maxQueue.Pop_front()\n\t maxQueue.Pop_front()\n\t maxQueue.Pop_front()\n\t fmt.Println(maxQueue.Max_value())\n }", "func (h MaxHeap) Len() int { return len(h) }", "func NewHeap() Heap {\n\treturn &maxHeightVertexHeap{}\n}", "func (b *BHeap) MaxHeapify(i int) {\n\tlargest := i\n\tl, r := b.left(i), b.right(i)\n\tif l < b.HeapSize && b.Keys.Less(i, l) {\n\t\tlargest = l\n\t}\n\tif r < b.HeapSize && b.Keys.Less(largest, r) {\n\t\tlargest = r\n\t}\n\tif largest != i {\n\t\tb.Keys.Swap(largest, i)\n\t\tb.MaxHeapify(largest)\n\t}\n}", "func initHeap()", "func PopMaxHeap(h *MaxHeap) interface{}{\n return heap.Pop(h)\n}", "func MaxHeapSort(array []int) {\r\n\tvar n int = len(array)\r\n\tMakeMaxHeap(array)\r\n\r\n\tfor i := n - 1; i >= 1; i-- {\r\n\t\tarray[0], array[i] = array[i], array[0]\r\n\t\tMaxHeapFixdown(array, 0, i)\r\n\t}\r\n\r\n}", "func (h *MaxHeap) Delete() (string, error) {\n\tif h.size == 0 {\n\t\treturn \"\", errors.New(\"Heap empty\")\n\t}\n\tmax := h.data[1]\n\t// Take the last item in the heap and make it the\n\t// new root, even though this is almost certainly\n\t// not the largest element...\n\th.data[1] = h.data[h.size]\n\th.size--\n\n\tparent := 1\n\t// ...and \"sink\" it down to its correct level in the heap.\n\tsink(h.data, parent, h.size)\n\n\treturn max, nil\n}", "func BuildMinHeap(a []int) {\n\tmaxIdx := len(a) - 1\n\tfor i := maxIdx / 2; 1 <= i; i-- {\n\t\tMinHeapify(a, maxIdx, i)\n\t}\n}", "func heap() []byte {\n\treturn make([]byte, 1024*10)\n}", "func maxHeapify(array []int, i int) {\n\tlargestIdx := i\n\n\tl := left(i)\n\tr := right(i)\n\n\tif l < len(array) && array[l] > array[i] {\n\t\tlargestIdx = l\n\t}\n\n\tif r < len(array) && array[r] > array[largestIdx] {\n\t\tlargestIdx = r\n\t}\n\n\tif i != largestIdx {\n\t\tarray[i], array[largestIdx] = array[largestIdx], array[i]\n\t\tmaxHeapify(array, largestIdx)\n\t}\n}", "func maxHeapAdjust(values []int, index, heapSize int) {\n\n\tleft := getLeftChildIndex(index)\n\tright := getRightChildIndex(index)\n\n\tvar adjustIndex = index\n\tif left < heapSize && values[left] > values[adjustIndex] {\n\t\t//\t\tvalues[index], values[left] = values[left], values[index]\n\t\tadjustIndex = left\n\t}\n\tif right < heapSize && values[right] > values[adjustIndex] {\n\t\t//\t\tvalues[index], values[right] = values[right], values[index]\n\t\tadjustIndex = right\n\t}\n\n\t//\tfmt.Printf(\"%d - %d\\n\", index, adjustIndex)\n\tif adjustIndex != index {\n\t\tvalues[adjustIndex], values[index] = values[index], values[adjustIndex]\n\t\tmaxHeapAdjust(values, adjustIndex, heapSize)\n\t}\n\n}", "func heapify(data []int, root, length int) {\n\tmax := root\n\tl, r := 2*root+1, 2*root+2\n\n\tif l < length && data[l] > data[max] {\n\t\tmax = l\n\t}\n\n\tif r < length && data[r] > data[max] {\n\t\tmax = r\n\t}\n\n\tif max != root {\n\t\tdata[root], data[max] = data[max], data[root]\n\t\theapify(data, max, length)\n\t}\n}", "func main() {\n\tmichael := CreatePerson(\"Michael\", 23)\n\tleah := CreatePerson(\"Leah\", 22)\n\tjake := CreatePerson(\"jake\", 19)\n\ttim := CreatePerson(\"tim\", 12)\n\tlarry := CreatePerson(\"larry\", 20)\n\tlenny := CreatePerson(\"lenny\", 21)\n\tjunior := CreatePerson(\"junior\", 10)\n\n\tpersonList := []Comparable{michael, leah, jake, tim, larry, lenny, junior}\n\n\t// HEAPSORT\n\tfmt.Println(\"### Testing HeapSort Implementation ###\")\n\tfmt.Println(\"Before Sorting:\")\n\tfor _, value := range personList {\n\t\tfmt.Println(value)\n\t}\n\n\tHeapSort(personList)\n\n\tfmt.Println(\"\\nAfter Sorting:\")\n\tfor _, value := range personList {\n\t\tfmt.Println(value)\n\t}\n\n\tfmt.Printf(\"\\n### Constructing Max Heap ###\\n\")\n\tpersonHeap := CreateMaxHeap(10)\n\tpersonHeap.Add(michael)\n\tpersonHeap.Add(leah)\n\tpersonHeap.Add(jake)\n\tpersonHeap.Add(tim)\n\tpersonHeap.Add(larry)\n\tpersonHeap.Add(lenny)\n\tpersonHeap.Add(junior)\n\n\tfmt.Println(\"Popping values from top of Max Heap\")\n\tvalue, ok := personHeap.Pop()\n\tfor ok {\n\t\tfmt.Printf(\"Top Value: %v\\n\", value)\n\t\tvalue, ok = personHeap.Pop()\n\t}\n}", "func (h *Heap) Max() (int, bool) {\n\tif len(h.heap) == 0 {\n\t\treturn 0, false\n\t}\n\treturn h.heap[0], true\n}", "func (h Heap) MaxHeapifyDown(pos int) {\n\tleft := pos*2 + 1\n\tright := left + 1\n\n\tmaxPos := pos\n\tif len(h) > left && h[left] > h[maxPos] {\n\t\tmaxPos = left\n\t}\n\tif len(h) > right && h[right] > h[maxPos] {\n\t\tmaxPos = right\n\t}\n\n\tif maxPos == pos {\n\t\treturn\n\t}\n\n\ttmp := h[pos]\n\th[pos] = h[maxPos]\n\th[maxPos] = tmp\n\n\th.MaxHeapifyDown(maxPos)\n}", "func MakeFixedSizeHeap(mode PriorityQueueMode, limit int,\n\trefCoord Coord) *FixedSizeHeap {\n\n\treturn &FixedSizeHeap{\n\t\tdata: make([]Coord, 0, limit+1),\n\t\tCenterCoord: refCoord,\n\t\tLimit: limit,\n\t\tmode: mode,\n\t}\n}", "func MaxIntHeapPop(s []int) (int, []int) {\n\tcpy := make([]int, len(s), cap(s))\n\tcopy(cpy, s)\n\tmaxVal := cpy[0]\n\tlastIndex := len(cpy) - 1\n\tcpy[0] = cpy[lastIndex]\n\tcpy = cpy[:lastIndex]\n\tMaxIntHeapify(cpy)\n\treturn maxVal, cpy\n}", "func (h *Heap) InitHeap(values []interface{}) {\n\t// Assign the values first.\n\th.values = append([]interface{}{nil}, values...)\n\th.size = len(values)\n\n\t// Start from the parent of the last node.\n\t// Loop back to the root, which is index 1.\n\tlastParent := h.size / 2\n\tfor i := lastParent; i >= 1; i-- {\n\t\t// Cache the value of node to data[0]\n\t\th.values[0] = h.values[i]\n\t\t// Loop through the subtrees to maintain.\n\t\tnode := i\n\t\t// keep iterating as long as the node still has left child.\n\t\tfor node*2 <= h.size {\n\t\t\t// get left child\n\t\t\tnode = node * 2\n\n\t\t\t// if has left child and right child and right child is larger\n\t\t\t// get the right child.\n\t\t\tif node < h.size {\n\t\t\t\tif (h.HeapType == HeapTypeMax && h.Comparator(h.values[node], h.values[node+1]) <= 0) ||\n\t\t\t\t\t(h.HeapType == HeapTypeMin && h.Comparator(h.values[node], h.values[node+1]) >= 0) {\n\t\t\t\t\tnode++\n\t\t\t\t}\n\t\t\t}\n\t\t\t// if current value is larger than the current biggest value in its children.\n\t\t\tif (h.HeapType == HeapTypeMax && h.Comparator(h.values[0], h.values[node]) >= 0) ||\n\t\t\t\t(h.HeapType == HeapTypeMin && h.Comparator(h.values[0], h.values[node]) <= 0) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Otherwise, we switch the value of the parent of current child.\n\t\t\th.values[node/2] = h.values[node]\n\t\t\th.values[node] = h.values[0]\n\t\t}\n\t}\n}", "func (b *BHeap) MaxHeapInsert(key interface{}) {\n\tb.HeapSize++\n\tb.Keys.Push(key)\n\tb.HeapIncreaseKey(b.HeapSize-1, key)\n}", "func MaxHeapIFY(A []int, i int) {\n\tvar largest int\n\tl := Left(i)\n\tr := Right(i)\n\t// fmt.Println(l, r)\n\tif l <= HeapSize && A[l] > A[i] {\n\t\tlargest = l\n\t} else {\n\t\tlargest = i\n\t}\n\tif r <= HeapSize && A[r] > A[largest] {\n\t\tlargest = r\n\t}\n\tif largest != i {\n\t\tswap(&A[i], &A[largest])\n\t\tMaxHeapIFY(A, largest)\n\t}\n}", "func NewMax(elements ...*PQElement) *PriorityQueue {\n\treturn New(true, elements...)\n}", "func (b *BHeap) HeapMaximum() interface{} {\n\treturn b.Keys.Get(0)\n}", "func newWorker(max int) *worker {\n\tworker := &worker{cutoff: max}\n\tworker.Grow(max) // allocating memory here seemed to help performance\n\treturn worker\n}", "func IsMaxHeap(heap []int) bool {\n\tl := len(heap)\n\tfor i := 0; i < l; i++ {\n\t\tleftChild := 2*i + 1\n\t\trightChild := 2*i + 2\n\t\tif leftChild < l && heap[i] < heap[leftChild] {\n\t\t\treturn false\n\t\t}\n\t\tif rightChild < l && heap[i] < heap[rightChild] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (m *metricFlinkJvmMemoryHeapMax) init() {\n\tm.data.SetName(\"flink.jvm.memory.heap.max\")\n\tm.data.SetDescription(\"The maximum amount of heap memory that can be used for memory management.\")\n\tm.data.SetUnit(\"By\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(false)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n}", "func MaxValSize(max int) Option {\n\treturn func(lc *memoryCache) error {\n\t\tlc.maxValueSize = max\n\t\treturn nil\n\t}\n}", "func (h *MaxHeap) maxHeapifyDown(index int) {\n\n\tlastIndex := len(h.array)-1\n\tl,r := left(index), right(index)\n\tchildToCompare := 0\n\t// loop while index has at least one child\n\tfor l <= lastIndex {\n\t\t// Define child to compare\n\t\t// When there is only one child or the \n\t\tif l == lastIndex {\n\t\t\tchildToCompare = l\n\t\t} else if h.array[l] > h.array[r] { // left child is larger\n\t\t\tchildToCompare = l\n\t\t} else { // When right child is larger\n\t\t\tchildToCompare = r\n\t\t}\n\t\t// Compare array value of current idx to larger child and swap if smaller\n\t\tif h.array[index] < h.array[childToCompare] {\n\t\t\th.swap(index, childToCompare)\n\t\t\tindex = childToCompare\n\t\t\tl,r = left(index), right(index)\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (h *MaxHeap) Size() int {\n\treturn h.size\n}", "func (h *MaxHeap) maxHeapifyDown(index int) {\r\n\tlastIndex := len(h.elements) - 1\r\n\tl, r := left(index), right(index)\r\n\tchildToCompare := 0\r\n\r\n\tfor l <= lastIndex {\r\n\r\n\t\tif l == lastIndex { // if left child is the last child\r\n\t\t\tchildToCompare = l\r\n\t\t} else if h.elements[l] > h.elements[r] { // if left child is larger\r\n\t\t\tchildToCompare = l\r\n\t\t} else { // if right child is larger\r\n\t\t\tchildToCompare = r\r\n\t\t}\r\n\r\n\r\n\t\t// compare element value of current index to the larger child and swap if lower\r\n\t\tif h.elements[index] < h.elements[childToCompare] {\r\n\t\t\th.swap(index, childToCompare)\r\n\t\t\tindex = childToCompare\r\n\t\t\tl, r = left(index), right(index)\r\n\t\t} else {\r\n\t\t\treturn\r\n\t\t}\r\n\t\t\r\n\t}\r\n}", "func (h *MaxHeap) maxHeapifyDown(index int) {\n\n\tlastIndex := len(h.array) - 1\n\tl, r := leftChild(index), rightChild(index)\n\tchildToCompare := 0\n\n\t//loop while index has at least one child\n\tfor l <= lastIndex {\n\t\t//when left child is the only child\n\t\tif l == lastIndex {\n\t\t\tchildToCompare = l\n\t\t} else if h.array[l] > h.array[r] { //when left child is larger than right\n\t\t\tchildToCompare = l\n\t\t} else { //when right child is larger than left\n\t\t\tchildToCompare = r\n\t\t}\n\n\t\t//compare array value of current index to larger child and swap if smaller\n\t\tif h.array[index] < h.array[childToCompare] {\n\t\t\th.swap(index, childToCompare)\n\t\t\tindex = childToCompare\n\t\t\tl, r = leftChild(index), rightChild(index)\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func MaxValSize(max int) Option {\n\treturn func(lc *loadingCache) error {\n\t\tlc.maxValueSize = max\n\t\treturn nil\n\t}\n}", "func NewMax(max int64) *Max {\n\tm := &Max{sema: semaphore.NewWeighted(max)}\n\treturn m\n}", "func (m *PriorityQueue) HeapSize() int {\r\n\treturn m.size\r\n}", "func main() {\n\tmedianFinder := Constructor()\n\tmedianFinder.AddNum(40)\n\tmedianFinder.AddNum(12)\n\tmedianFinder.AddNum(16)\n\tmedianFinder.AddNum(14)\n\tmedianFinder.AddNum(35)\n\tmedianFinder.AddNum(19)\n\tmedianFinder.AddNum(34)\n\tmedianFinder.AddNum(35)\n\tmedianFinder.AddNum(28)\n\tmedianFinder.AddNum(35)\n\tmedianFinder.AddNum(26)\n\tmedianFinder.AddNum(6)\n\tmedianFinder.AddNum(8)\n\tmedianFinder.AddNum(2)\n\tmedianFinder.AddNum(14)\n\tmedianFinder.AddNum(25)\n\tmedianFinder.AddNum(25)\n\tmedianFinder.AddNum(4)\n\tmedianFinder.AddNum(33)\n\tmedianFinder.AddNum(18)\n\tmedianFinder.AddNum(10)\n\tmedianFinder.AddNum(14)\n\tfmt.Println(medianFinder.FindMedian())\n\n\tfmt.Println(bigHeapifyFromUp([]int{6, 19, 26, 12, 16, 14}, 0, 5))\n}", "func (bh* BinomialHeap) Size() int {\n return bh.size\n}", "func (p *PackingEfficiency) Max() float64 {\n\treturn math.Max(p.GPU, math.Max(p.CPU, p.Memory))\n}", "func MaxIntHeapSort(s []int) {\n\tMaxIntHeapify(s) // just in case it's not a heap when we get it.\n\tfor idx := len(s) - 1; idx > 0; idx-- {\n\t\ts[0], s[idx] = s[idx], s[0]\n\t\tMaxIntHeapify(s[:idx])\n\t}\n}", "func FetchHeap(r *bufio.Reader) (*PeepHeap, int) {\n\tn, t := ReadConstraints(r)\n\tpeeps := &PeepHeap{}\n\tfor i := 0; i < n; i++ {\n\t\tline, err := r.ReadBytes('\\n')\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlineString := strings.TrimSuffix(string(line), \"\\n\")\n\t\tnums := strings.Split(lineString, \" \")\n\t\tvalue, err := strconv.Atoi(nums[0])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlimit, err := strconv.Atoi(nums[1])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\theap.Push(peeps, Peep{Limit: limit, Value: value})\n\t}\n\treturn peeps, t\n}", "func maximize() int64 {\n\tmax := 0\n\tmaxItem := int64(0)\n\t// var cache Cache\n\n\t// The larger the cache, the faster it is. Even without a\n\t// cache, it's only around a second on a modern machine, so\n\t// not that big of a deal.\n\t// cache.init(10000)\n\n\tfor x := int64(1); x < 1000000; x++ {\n\t\tcount := collatz2(x)\n\t\t// count := cache.chainLen(x)\n\t\tif count > max {\n\t\t\tmax = count\n\t\t\tmaxItem = x\n\t\t}\n\t}\n\tfmt.Printf(\"%d, %d\\n\", maxItem, max)\n\treturn maxItem\n}", "func (mb *MetricsBuilder) RecordFlinkJvmMemoryHeapMaxDataPoint(ts pcommon.Timestamp, inputVal string) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for FlinkJvmMemoryHeapMax, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricFlinkJvmMemoryHeapMax.recordDataPoint(mb.startTime, ts, val)\n\treturn nil\n}", "func (h *MaxHeap) Capacity() int {\n\treturn h.capacity\n}", "func (o ElasticPoolPerDatabaseSettingsOutput) MaxCapacity() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v ElasticPoolPerDatabaseSettings) *float64 { return v.MaxCapacity }).(pulumi.Float64PtrOutput)\n}", "func Max(key []byte, nodes []*memberlist.Node) (max *memberlist.Node) {\n\tmaxValue := big.NewInt(0)\n\n\tCompute(key, nodes, func(node *memberlist.Node, bi *big.Int) {\n\t\tif bi.Cmp(maxValue) == 1 {\n\t\t\tmaxValue = bi\n\t\t\tmax = node\n\t\t}\n\t})\n\n\treturn max\n}", "func (m *metricFlinkJvmMemoryHeapMax) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (h *Heap) RemoveMax() bool {\n\tif h.count == 0 {\n\t\treturn false\n\t}\n\n\th.items[1] = h.count\n\th.count--\n\n\theapify(h.items, h.count, 1)\n\treturn true\n}", "func TestIHMaxAddOrder1(t *testing.T) {\n\th := NewImplicitHeapMax(false)\n\n\th.Push(1, 1)\n\th.Push(3, 3)\n\th.Push(4, 4)\n\n\ttestIMPriorityOrder(h.a, []int{4, 1, 3}, \"push 1\", t)\n\n\th.Push(2, 2)\n\ttestIMPriorityOrder(h.a, []int{4, 2, 3, 1}, \"push 2\", t)\n\n\th.Push(5, 5)\n\ttestIMPriorityOrder(h.a, []int{5, 4, 3, 1, 2}, \"push 3\", t)\n}", "func (m *metricFlinkJvmMemoryNonheapMax) init() {\n\tm.data.SetName(\"flink.jvm.memory.nonheap.max\")\n\tm.data.SetDescription(\"The maximum amount of non-heap memory that can be used for memory management.\")\n\tm.data.SetUnit(\"By\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(false)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n}", "func (a *Graph) PrimHeap() {\n\tthis := a.copy()\n\t// change to undirected graph\n\t// 0 convert to infinity\n\tfor i, _ := range this.edge {\n\t\tif this.edge[i] != 0 {\n\t\t\tthis.edge[i%this.n*this.n+i/this.n] = this.edge[i]\n\t\t}\n\t\tif this.edge[i] == 0 {\n\t\t\tthis.edge[i] = infinity\n\t\t}\n\t}\n\n\th := &priorityQueue{}\n\theap.Init(h)\n\n\tvar vis []bool\n\tvis = make([]bool, this.n)\n\tvis[0] = true\n\n\tvar pre int // record the begin node\n\n\tfor i := 0; i < this.n; i++ {\n\t\tif this.edge[i] != infinity {\n\t\t\theap.Push(h, &space{i, this.edge[i], -1})\n\t\t}\n\t}\n\tpre = 0\n\tfor i := 1; i < this.n; i++ {\n\t\te := heap.Pop(h).(*space)\n\t\tv := e.end\n\t\tvis[v] = true\n\t\tfmt.Println(\"(\", pre, \",\", v, \",\", e.cost, \")\")\n\t\tpre = v\n\t\tfor i := 0; i < this.n; i++ {\n\t\t\tif this.edge[v*this.n+i] != infinity && !vis[i] {\n\t\t\t\theap.Push(h, &space{i, this.edge[v*this.n+i], -1})\n\t\t\t}\n\t\t}\n\t}\n}", "func main() {\n\t// 1, 7, 2, 3, 8, 1, 1 : collide two max stones : 7, 8 here remaining 1 . 1 will added\n\t// 1, 2, 3, 1, 1, 1 : collide 3 and 2 and remaining 1 will be added\n\t// 1, 1, 1, 1, 1 : collide 1, 1 nothing will be added\n\t// 1 1 1 : collide 1 and 1 nothing will be added\n\t// 1 will be answer\n\ta := []int{1, 7, 2, 3, 8, 1, 1}\n\n\t/*\n\t\t// this works too\n\t\th := &IntHeap{}\n\t\theap.Init(h)\n\t\tfor _, item := range a {\n\t\t\theap.Push(h, item)\n\t\t}\n\t*/\n\n\thh := IntHeap(a)\n\th := &hh\n\theap.Init(h)\n\tfor h.Len() >= 2 {\n\t\telement1 := heap.Pop(h)\n\t\telement2 := heap.Pop(h)\n\t\titem1 := element1.(int)\n\t\titem2 := element2.(int)\n\n\t\tfmt.Println(\"item1 popped=\", item1)\n\t\tfmt.Println(\"item2 popped=\", item2)\n\n\t\tif item1 > item2 {\n\t\t\theap.Push(h, item1-item2)\n\t\t}\n\t}\n\tif h.Len() > 0 {\n\t\tfmt.Println(\"answer=\", heap.Pop(h))\n\t} else {\n\t\tfmt.Println(\"answer is empty\")\n\t}\n\n}", "func (o BeanstalkScheduledTaskOutput) MaxCapacity() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BeanstalkScheduledTask) *string { return v.MaxCapacity }).(pulumi.StringPtrOutput)\n}", "func (b *BHeap) ExtractMax() (interface{}, bool) {\n\tif b.Empty() {\n\t\treturn nil, false\n\t}\n\tmax := b.Keys.Pop()\n\tb.HeapSize--\n\tb.MaxHeapify(0)\n\treturn max, true\n}", "func (h *MaxHeap) maxHeapifyUp(index int) {\r\n\tfor h.elements[index] > h.elements[parent(index)] {\r\n\t\th.swap(parent(index), index)\r\n\t\tindex = parent(index)\r\n\t}\r\n}", "func (n *hetznerNodeGroup) MaxSize() int {\n\treturn n.maxSize\n}", "func New(max bool, elements ...*PQElement) *PriorityQueue {\n\tpriorityQueue := PriorityQueue{pq: &heapArray{max: max}}\n\theap.Init(priorityQueue.pq)\n\tpriorityQueue.Push(elements...)\n\treturn &priorityQueue\n}", "func MaxValSize(max int) Option {\n\treturn func(lc cacheWithOpts) error {\n\t\treturn lc.setMaxValSize(max)\n\t}\n}", "func (c *Cache) MaxSize() (maxSize int64) {\n\tfor _, shard := range c.shards {\n\t\tmaxSize += shard.maxSize\n\t}\n\treturn int64(bytesToMB(int(maxSize)))\n}", "func NewHeap() *Heap {\n\treturn &Heap{data: []int{}, mutex: &sync.Mutex{}}\n}", "func (o ElastigroupScheduledTaskOutput) MaxCapacity() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScheduledTask) *string { return v.MaxCapacity }).(pulumi.StringPtrOutput)\n}", "func (heap SkewHeap) Size() int { return heap.size }", "func (h *Heap) ExtractMax() (int, bool) {\n\tif len(h.heap) == 0 {\n\t\treturn 0, false\n\t}\n\n\tmax := h.heap[0]\n\tlast := len(h.heap) - 1\n\th.heap[0] = h.heap[last]\n\th.heap = h.heap[:last]\n\n\th.heapify(0)\n\treturn max, true\n}", "func (o ElasticPoolPerDatabaseSettingsPtrOutput) MaxCapacity() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *ElasticPoolPerDatabaseSettings) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MaxCapacity\n\t}).(pulumi.Float64PtrOutput)\n}", "func NewHeap(arr []int) *Heap {\n\th := Heap{\n\t\theap: make([]int, len(arr)),\n\t}\n\n\tif len(arr) == 0 {\n\t\treturn &h\n\t}\n\n\tcopy(h.heap, arr)\n\tfor i := len(h.heap) / 2; i >= 0; i-- {\n\t\th.heapify(i)\n\t}\n\treturn &h\n}", "func NewHeap() *Heap {\n return &Heap{}\n}", "func maximumClique(g graph.Undirected) (k int, maxClique []graph.Node, cliques [][]graph.Node) {\n\tcliques = topo.BronKerbosch(g)\n\tfor _, c := range topo.BronKerbosch(g) {\n\t\tif len(c) > len(maxClique) {\n\t\t\tmaxClique = c\n\t\t}\n\t}\n\treturn len(maxClique), maxClique, cliques\n}", "func newHeap() *heapTree {\n\treturn &heapTree{Values: &path{}}\n}", "func (o MrScalarScheduledTaskOutput) MaxCapacity() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MrScalarScheduledTask) *string { return v.MaxCapacity }).(pulumi.StringPtrOutput)\n}", "func (h *MaxHeap) resize(newCapacity int) error {\n\tif newCapacity <= h.capacity {\n\t\treturn errors.Errorf(\"New capacity %d is not larger than current capacity %d\", newCapacity, h.capacity)\n\t}\n\tnewData := make([]string, newCapacity, newCapacity)\n\tfor i := 0; i < len(h.data); i++ {\n\t\tnewData[i] = h.data[i]\n\t}\n\th.capacity = newCapacity\n\th.data = newData\n\treturn nil\n}", "func findKthLargestHeap(nums []int, k int) int {\n\th := heap(nums)\n\th.build()\n\tfor i := 1; i < k; i++ {\n\t\th.pop()\n\t}\n\treturn h.pop()\n}", "func MaxKeys(max int) Option {\n\treturn func(lc *memoryCache) error {\n\t\tlc.maxKeys = max\n\t\treturn nil\n\t}\n}", "func (o *MemoryArrayAllOf) GetMaxCapacity() string {\n\tif o == nil || o.MaxCapacity == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.MaxCapacity\n}", "func (s *Sim) CreateMax() int {\n\tid := len(s.aggs)\n\ts.aggs = append(s.aggs, newMax())\n\tfor i, _ := range s.runners {\n\t\ts.runners[i].aggs = append(s.runners[i].aggs, newMax())\n\t}\n\treturn id\n}" ]
[ "0.8362464", "0.8227338", "0.8057785", "0.79148865", "0.7886661", "0.78837705", "0.7368793", "0.7287856", "0.6896935", "0.68310094", "0.66480005", "0.6635684", "0.66338724", "0.6497776", "0.64796835", "0.6453171", "0.64160424", "0.6295048", "0.6288548", "0.6245706", "0.6211794", "0.6163679", "0.61579996", "0.61274505", "0.6079645", "0.607295", "0.6072492", "0.6061139", "0.6050949", "0.6028701", "0.6022985", "0.60176307", "0.6000787", "0.5964391", "0.5959899", "0.5957583", "0.5951458", "0.59510714", "0.5938179", "0.58898735", "0.5877539", "0.58769625", "0.5873448", "0.58588666", "0.5833592", "0.58245254", "0.58056855", "0.58038837", "0.5795037", "0.578037", "0.57744664", "0.5764363", "0.57562536", "0.57360905", "0.57145053", "0.5629033", "0.5618955", "0.556885", "0.55541897", "0.5509808", "0.549173", "0.54889387", "0.5473133", "0.54675585", "0.5459961", "0.5458335", "0.54353154", "0.5434595", "0.5431065", "0.5430845", "0.5398759", "0.53728026", "0.5371035", "0.53632915", "0.5359277", "0.53557783", "0.5341935", "0.5338892", "0.5320413", "0.5316744", "0.53153545", "0.53153354", "0.529804", "0.52664876", "0.5263277", "0.52395725", "0.5229908", "0.52242243", "0.5224038", "0.5198628", "0.5192233", "0.5186766", "0.5185741", "0.51824635", "0.51797473", "0.5161826", "0.5159277", "0.51373553", "0.5127566", "0.5115543" ]
0.7953508
3
Get tag(s) for the nginx plugin
func getTags(addr *url.URL) map[string]string { h := addr.Host host, port, err := net.SplitHostPort(h) if err != nil { host = addr.Host if addr.Scheme == "http" { port = "80" } else if addr.Scheme == "https" { port = "443" } else { port = "" } } return map[string]string{"server": host, "port": port} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getHostTags(c *config.Config) []string {\n\ttags := c.HostMetadata.Tags\n\n\tif len(tags) == 0 {\n\t\t//lint:ignore SA1019 Will be removed when environment variable detection is removed\n\t\ttags = strings.Split(c.EnvVarTags, \" \") //nolint\n\t}\n\n\tif c.Env != \"none\" {\n\t\ttags = append(tags, fmt.Sprintf(\"env:%s\", c.Env))\n\t}\n\treturn tags\n}", "func (rfs *RootFileSystem) GetTags(fileName string) ([]string, error) {\n\tfn, err := rfs.retrieveFn(fileName, false)\n\n\tif err == nil {\n\t\tret := make([]string, len(fn.AlternateRoutes), len(fn.AlternateRoutes))\n\t\tfor k, _ := range fn.AlternateRoutes {\n\t\t\tret = append(ret, k)\n\t\t}\n\t\treturn ret, nil\n\t}\n\treturn nil, err\n}", "func (c *repoCacheManager) getTags(ctx context.Context) ([]string, error) {\n\tctx, cancel := context.WithTimeout(ctx, c.clientTimeout)\n\tdefer cancel()\n\ttags, err := c.client.Tags(ctx)\n\tif ctx.Err() == context.DeadlineExceeded {\n\t\treturn nil, c.clientTimeoutError()\n\t}\n\treturn tags, err\n}", "func GetTags() []string {\n\ttags := []string{\n\t\t\"script\",\n\t\t\"iframe\",\n\t\t\"svg\",\n\t\t\"img\",\n\t\t\"video\",\n\t\t\"audio\",\n\t\t\"meta\",\n\t\t\"object\",\n\t\t\"embed\",\n\t\t\"style\",\n\t\t\"frame\",\n\t\t\"frameset\",\n\t\t\"applet\",\n\t}\n\treturn tags\n}", "func (aiService *AppinsightsMonitorService) getTags(tagType string, name string) map[string]*string {\n\n\ttags := make(map[string]*string)\n\n\tcomponentHiddenlink := fmt.Sprintf(\"hidden-link:/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s\", aiService.subscriptionID, aiService.resourceGroup, aiService.name)\n\twebtestHiddenlink := fmt.Sprintf(\"hidden-link:/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/webtests/%s\", aiService.subscriptionID, aiService.resourceGroup, name)\n\tvalue := \"Resource\"\n\n\tif tagType == \"webtest\" {\n\t\ttags[componentHiddenlink] = &value\n\t}\n\n\tif tagType == \"alert\" {\n\n\t\ttags[componentHiddenlink] = &value\n\t\ttags[webtestHiddenlink] = &value\n\t}\n\n\treturn tags\n}", "func (h *Hub) Tags() []string {\n\treturn h.tags\n}", "func (hdr RPMHeader) Tag(tagname string) []string {\n\tfor _, tag := range hdr.Tags {\n\t\tif tag.Name == tagname {\n\t\t\treturn tag.Values\n\t\t}\n\t}\n\treturn []string{\"\"}\n}", "func (m *Application) GetTags()([]string) {\n return m.tags\n}", "func (c *UserId) GetIpTags(ip, tag, vsys string) (map[string][]string, error) {\n\tif vsys == \"\" {\n\t\tvsys = \"vsys1\"\n\t}\n\tc.con.LogOp(\"(op) getting registered ip addresses - ip:%q tag:%q vsys:%q\", ip, tag, vsys)\n\treq := c.versioning()\n\n\tans := make(map[string][]string)\n\tfor {\n\t\treq.FilterOn(ip, tag, len(ans))\n\t\tresp := regResp{}\n\n\t\t_, err := c.con.Op(req, vsys, nil, &resp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if resp.Msg != nil && resp.Msg.Outfile != \"\" {\n\t\t\treturn nil, fmt.Errorf(\"PAN-OS returned %q instead of IP/tag mappings, please upgrade to 8.0+\", resp.Msg.Outfile)\n\t\t}\n\n\t\tfor i := range resp.Entry {\n\t\t\tans[resp.Entry[i].Ip] = resp.Entry[i].Tags\n\t\t}\n\n\t\tif req.ShouldStop(len(resp.Entry)) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn ans, nil\n}", "func (v *vcsCmd) tags(dir string) ([]string, error) {\n\tvar tags []string\n\tfor _, tc := range v.tagCmd {\n\t\tout, err := v.runOutput(dir, tc.cmd)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tre := regexp.MustCompile(`(?m-s)` + tc.pattern)\n\t\tfor _, m := range re.FindAllStringSubmatch(string(out), -1) {\n\t\t\ttags = append(tags, m[1])\n\t\t}\n\t}\n\treturn tags, nil\n}", "func (p *Pod) GetTags(n string) []string {\n\tif tagStr, ok := p.Pod.ObjectMeta.Annotations[ConsulServiceTagsOverride+n]; ok {\n\t\treturn strings.Split(tagStr, \",\")\n\t}\n\n\tif tagStr, ok := p.Pod.ObjectMeta.Annotations[ConsulServiceTags]; ok {\n\t\treturn strings.Split(tagStr, \",\")\n\t}\n\n\treturn nil\n}", "func GetTags() [10]string {\n\treturn tags\n}", "func (o LookupServerResultOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupServerResult) []string { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func (o NodeBalancerOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *NodeBalancer) pulumi.StringArrayOutput { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func (o *FiltersVirtualGateway) GetTags() []string {\n\tif o == nil || o.Tags == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.Tags\n}", "func getTags(operation *openapi3.Operation) string {\n\treturn strings.Replace(operation.Tags[0], \" \", \"-\", -1)\n}", "func (c *NodeCpu) GetTags() []string {\n\tvar tags []string\n\tvalueMap := structs.Map(c)\n\tfor k := range valueMap {\n\t\ttags = append(tags, k)\n\t}\n\n\treturn tags\n}", "func (c Client) ListTags(repo string) ([]string, error) {\n\tif c.isHub {\n\t\ttags, err := c.HubClient.QueryImageTags(repo)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar res []string\n\t\tfor _, t := range tags {\n\t\t\tres = append(res, t.Name)\n\t\t}\n\t\treturn res, nil\n\t}\n\n\tif c.version == \"v1\" {\n\t\tauth, err := c.RegClient.Hub.GetReadToken(repo)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"GetReadToken failed:%s\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttagMap, err := c.RegClient.Repository.ListTags(repo, auth)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"ListTags failed, error info:%s\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tglog.V(6).Infof(\"ListTags v1 succeeds, repo:%s, results: %v\\n\", repo, tagMap)\n\t\ttags := make([]string, 0, 64)\n\t\tfor key := range tagMap {\n\t\t\ttags = append(tags, key)\n\t\t}\n\t\treturn tags, nil\n\t}\n\n\t// use v2 version api\n\ttags, err := c.RegClientV2.Tags(repo)\n\tif err != nil {\n\t\tglog.Errorf(\"ListTags failed, error info: %s\\n\", err)\n\t\treturn nil, err\n\t}\n\tglog.V(6).Infof(\"ListTags v2 succeeds, repo: %s, results: %v\\n\", repo, tags)\n\treturn tags, nil\n}", "func (p *NodeProcess) GetTags() []string {\n\tvar tags []string\n\tvalueMap := structs.Map(p)\n\tfor k := range valueMap {\n\t\ttags = append(tags, k)\n\t}\n\n\treturn tags\n}", "func (f Fess) GetTags() []string {\n\ttags := []string{\n\t\t\"full size\",\n\t\t\"ordinary\",\n\t}\n\treturn tags\n}", "func (r Roundel) GetTags() []string {\n\ttags := []string{\n\t\t\"ordinary\",\n\t}\n\treturn tags\n}", "func (o LookupGatewayResultOutput) Tags() GatewayTagArrayOutput {\n\treturn o.ApplyT(func(v LookupGatewayResult) []GatewayTag { return v.Tags }).(GatewayTagArrayOutput)\n}", "func (r *RepositoryDockerHub) Tags() (out []struct {\n\tName string\n\tImage string\n}, err error) {\n\turl := fmt.Sprintf(\"https://registry.hub.docker.com/v2/repositories/%s/%s/tags/\", r.User, r.Image)\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar apiResp struct {\n\t\tCount int `json:\"count\"`\n\t\tNext *string `json:\"next\"`\n\t\tResults []struct {\n\t\t\tName string `json:\"name\"`\n\t\t} `json:\"results\"`\n\t}\n\terr = json.NewDecoder(resp.Body).Decode(&apiResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor {\n\t\tfor _, result := range apiResp.Results {\n\t\t\ttagName := result.Name\n\t\t\tout = append(out, struct {\n\t\t\t\tName string\n\t\t\t\tImage string\n\t\t\t}{\n\t\t\t\tName: tagName,\n\t\t\t\tImage: fmt.Sprintf(\"%s/%s:%s\", r.User, r.Image, tagName),\n\t\t\t})\n\t\t}\n\t\tif apiResp.Next == nil {\n\t\t\tbreak\n\t\t}\n\t\turl = *apiResp.Next\n\t\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tapiResp.Count = 0\n\t\tapiResp.Next = nil\n\t\tapiResp.Results = nil\n\t\terr = json.NewDecoder(resp.Body).Decode(&apiResp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn out, nil\n}", "func (l *NodeLoad) GetTags() []string {\n\tvar tags []string\n\tvalueMap := structs.Map(l)\n\tfor k := range valueMap {\n\t\ttags = append(tags, k)\n\t}\n\n\treturn tags\n}", "func (c *StatsClient) Tags() []string {\n\treturn c.tags\n}", "func GetTags(registry string, github GitHub) ([]string, error) {\n\trepo := dockerRepo(github)\n\tvar tags []string\n\tfor _, t := range staticTags() {\n\t\ttags = append(tags, toFullTag(registry, repo, t))\n\t}\n\tif withRef, err := tagWithRef(); err != nil {\n\t\treturn nil, err\n\t} else if withRef {\n\t\tswitch github.Reference.Type {\n\t\tcase GitRefHead:\n\t\t\tif github.Reference.Name == \"master\" || github.Reference.Name == \"main\" {\n\t\t\t\ttags = append(tags, toFullTag(registry, repo, \"latest\"))\n\t\t\t} else {\n\t\t\t\ttags = appendGitRefTag(tags, registry, repo, github.Reference.Name)\n\t\t\t}\n\t\tcase GitRefPullRequest:\n\t\t\ttags = appendGitRefTag(tags, registry, repo, fmt.Sprintf(\"pr-%s\", github.Reference.Name))\n\n\t\tcase GitRefTag:\n\t\t\ttags = appendGitRefTag(tags, registry, repo, github.Reference.Name)\n\t\t}\n\t}\n\tif withSha, err := tagWithSha(); err != nil {\n\t\treturn nil, err\n\t} else if withSha {\n\t\ttags = appendShortGitShaTag(tags, github, registry, repo)\n\t}\n\treturn tags, nil\n}", "func (o NetworkOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Network) pulumi.StringArrayOutput { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func GetTags(c *gin.Context) {\n\ts := services.NewTagService(daos.NewTagDAO())\n\tid, _ := strconv.ParseUint(c.Param(\"post_id\"), 10, 32)\n\tif tags, err := s.FindAll(uint(id)); err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\tlog.Println(err)\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"tags\": tags,\n\t\t})\n\t}\n}", "func GetStartupTagList(ctx *router.Context) {\n\tresponse, err := service.GetStartupTagList()\n\tif err != nil {\n\t\tctx.ERROR(\n\t\t\trouter.ErrBuisnessError,\n\t\t\terr.Error(),\n\t\t)\n\t\treturn\n\t}\n\n\tctx.OK(response)\n}", "func (sp *Space) GetTags() []string {\n\tif len(*sp) > 0 {\n\t\treturn (*sp)[0].GetTags()\n\t}\n\treturn []string{}\n}", "func (o VirtualGatewayOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *VirtualGateway) pulumi.StringMapOutput { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (r *RepositoryV2) Tags() (out []struct {\n\tName string\n\tImage string\n}, err error) {\n\turl := fmt.Sprintf(\"https://%s/v2/%s/tags/list\", r.Registry, r.Image)\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar apiResp struct {\n\t\tTags []string `json:\"tags\"`\n\t}\n\terr = json.NewDecoder(resp.Body).Decode(&apiResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, tagName := range apiResp.Tags {\n\t\tout = append(out, struct {\n\t\t\tName string\n\t\t\tImage string\n\t\t}{\n\t\t\tName: tagName,\n\t\t\tImage: fmt.Sprintf(\"%s/%s:%s\", r.Registry, r.Image, tagName),\n\t\t})\n\t}\n\treturn out, nil\n}", "func (r *Repository) Tags() (out []struct {\n\tName string\n\tImage string\n}, err error) {\n\terr = r.Parse()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch {\n\tcase r.V2 != nil:\n\t\treturn r.V2.Tags()\n\tcase r.DockerHub != nil:\n\t\treturn r.DockerHub.Tags()\n\tdefault:\n\t\treturn nil, errors.New(\"no docker Repository defined\")\n\t}\n}", "func (o *VirtualGateway) GetTags() []ResourceTag {\n\tif o == nil || o.Tags == nil {\n\t\tvar ret []ResourceTag\n\t\treturn ret\n\t}\n\treturn *o.Tags\n}", "func (d *common) Etag() []any {\n\treturn []any{d.info.Name, d.info.Description, d.info.Ingress, d.info.Egress, d.info.Config}\n}", "func (o LinuxWebAppOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *LinuxWebApp) pulumi.StringMapOutput { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (self *Client) Tags(t MetricType, id string, o ...Modifier) (map[string]string, error) {\n\to = prepend(o, self.Url(\"GET\", TypeEndpoint(t), SingleMetricEndpoint(id), TagEndpoint()))\n\n\tr, err := self.Send(o...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer r.Body.Close()\n\n\tif r.StatusCode == http.StatusOK {\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttags := make(map[string]string)\n\t\tif b != nil {\n\t\t\tif err = json.Unmarshal(b, &tags); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn tags, nil\n\t} else if r.StatusCode > 399 {\n\t\treturn nil, self.parseErrorResponse(r)\n\t}\n\n\treturn nil, nil\n}", "func (r *Registry) Tags(ctx context.Context, repository string) ([]Tag, error) {\n tagNames, err := r.TagNames(ctx, repository)\n if err != nil {\n\t\treturn nil, err\n\t}\n\n\ttags := make([]Tag, len(tagNames))\n\tfor i := range tags {\n\t\ttags[i] = Tag {\n\t\t\tName: tagNames[i],\n\t\t\tRepository: repository,\n\t\t\tRegistry: r,\n\t\t}\n\t}\n\treturn tags, nil\n}", "func (h *handler) ListTags(ctx context.Context) ([]string, error) {\n\treturn h.setting.TagsList(ctx)\n}", "func (is *IfaceStat) GetTags() []string {\n\tvar tags []string\n\tvalueMap := structs.Map(is)\n\tfor k := range valueMap {\n\t\ttags = append(tags, k)\n\t}\n\n\treturn tags\n}", "func (l *LocalService) GetTags() map[string]string {\n\treturn map[string]string{}\n}", "func (r serverResult) ExtractTags() ([]string, error) {\n\tvar s struct {\n\t\tTags []string `json:\"tags\"`\n\t}\n\terr := r.ExtractInto(&s)\n\treturn s.Tags, err\n}", "func (o InstanceFromTemplateOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *InstanceFromTemplate) pulumi.StringArrayOutput { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func makeTags() []string {\n\ttags := make([]string, 2)\n\thostname := GetHostname()\n\thostTag := fmt.Sprintf(\"host:%s\", hostname)\n\texecString := strings.Replace(Exec, \" \", \"_\", -1)\n\texecTag := fmt.Sprintf(\"exec:%s\", execString)\n\ttags = append(tags, hostTag)\n\ttags = append(tags, execTag)\n\treturn tags\n}", "func (c *Client) GetTags() string {\n\turl := fmt.Sprintf(c.baseURL + \"tags\")\n\tres, err := http.Get(url)\n\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\treturn string(body)\n}", "func (m *MyMetric) TagList() []*protocol.Tag {\n\treturn m.Tags\n}", "func (n *node) Tags() []string {\n\treturn n.tags\n}", "func (p *localProvider) GetTags() []string {\n\tp.RLock()\n\tdefer p.RUnlock()\n\n\tif p.expectedTags != nil {\n\t\treturn p.expectedTags\n\t}\n\treturn p.tags\n}", "func (o *PublicIp) GetTags() []ResourceTag {\n\tif o == nil || o.Tags == nil {\n\t\tvar ret []ResourceTag\n\t\treturn ret\n\t}\n\treturn *o.Tags\n}", "func (o *PublicIp) GetTags() []ResourceTag {\n\tif o == nil || o.Tags == nil {\n\t\tvar ret []ResourceTag\n\t\treturn ret\n\t}\n\treturn *o.Tags\n}", "func (p Pale) GetTags() []string {\n\ttags := []string{\n\t\t\"full size\",\n\t\t\"ordinary\",\n\t}\n\treturn tags\n}", "func GetUntaggedNodes(appSettings appsettings.AppSettings) (nodes2tag []string, err error) {\n\t// creates the in-cluster config\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nodes2tag, err\n\t}\n\t// creates the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Debugf(\"Getting the in cluster configuration for Kubernetes\")\n\t\treturn nodes2tag, err\n\t}\n\tfor {\n\t\tnodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"Connecting to Kubernetes...\")\n\t\t\treturn nodes2tag, err\n\t\t}\n\t\tlog.Debugf(\"There are %d nodes in the cluster\\n\", len(nodes.Items))\n\n\t\tfor _, node := range nodes.Items {\n\t\t\tlog.Debugf(\"NodeName: %s\", node.Name)\n\t\t\tlog.Debugf(\"Annotations: %v\", node.Annotations)\n\n\t\t\t// not very pretty, this will itirate over annotations of all nodes for all annotations\n\t\t\tfor i := range appSettings.InfrastructureTags {\n\t\t\t\tif node.Annotations[K8sAnnotationDomain+\"/\"+appSettings.InfrastructureTags[i].Key] == \"\" {\n\t\t\t\t\tlog.Debugf(\"Annotation: %v, does not exist on node %s\", appSettings.InfrastructureTags[i].Key, node.Name)\n\t\t\t\t\tlog.Debugf(\"Adding Node %s, to list of nodes to tag\", node.Name)\n\t\t\t\t\tnodes2tag = append(nodes2tag, node.Name)\n\t\t\t\t\tbreak\n\t\t\t\t} else if node.Annotations[K8sAnnotationDomain+\"/\"+appSettings.InfrastructureTags[i].Key] != appSettings.InfrastructureTags[i].Value {\n\t\t\t\t\tlog.Debugf(\"Annotation: %v, value is %s however we expected %s\",\n\t\t\t\t\t\tappSettings.InfrastructureTags[i].Key,\n\t\t\t\t\t\tnode.Annotations[appSettings.InfrastructureTags[i].Key],\n\t\t\t\t\t\tappSettings.InfrastructureTags[i].Value,\n\t\t\t\t\t)\n\t\t\t\t\tlog.Debugf(\"Adding Node %s, to list of nodes to tag\", node.Name)\n\t\t\t\t\tnodes2tag = append(nodes2tag, node.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nodes2tag, nil\n\t}\n}", "func (mgr *Manager) Tags() []string {\n\treturn mgr.tags\n}", "func (self Channel) GetTags(tag int) string {\n\treturn C.GoString(C.BASS_ChannelGetTags(self.cint(), C.DWORD(tag)))\n}", "func (s *Store) GetTags(string) ([]newstorage.Tag, error) {\n\treturn nil, nil\n}", "func (o *SyntheticMonitorUpdate) GetTags() []TagWithSourceInfo {\n\tif o == nil {\n\t\tvar ret []TagWithSourceInfo\n\t\treturn ret\n\t}\n\n\treturn o.Tags\n}", "func lbTags(app string, process string) map[string]string {\n\treturn map[string]string{\n\t\t\"AppID\": app,\n\t\t\"ProcessType\": process,\n\t}\n}", "func getTagLabels() ([]string, []string) {\n\tdefer trace()()\n\tvar ntags []string\n\tvar vtags []string\n\tif conf.UCMConfig.AwsTagsToLabels.Enabled {\n\t\ttags := processTagLabelMap(labels, conf.UCMConfig.MetadataReporting.Attributes)\n\t\tfor k, v := range tags {\n\t\t\tntags = append(ntags, strings.ToLower(k))\n\t\t\tvtags = append(vtags, v)\n\t\t}\n\t}\n\treturn ntags, vtags\n}", "func (c Cross) GetTags() []string {\n\ttags := []string{\n\t\t\"full size\",\n\t\t\"ordinary\",\n\t}\n\treturn tags\n}", "func (o LookupLoggingConfigurationResultOutput) Tags() LoggingConfigurationTagArrayOutput {\n\treturn o.ApplyT(func(v LookupLoggingConfigurationResult) []LoggingConfigurationTag { return v.Tags }).(LoggingConfigurationTagArrayOutput)\n}", "func (m *NodeMemory) GetTags() []string {\n\tvar tags []string\n\tvalueMap := structs.Map(m)\n\tfor k := range valueMap {\n\t\ttags = append(tags, k)\n\t}\n\n\treturn tags\n}", "func ListTags() []string {\n\treturn _tags\n}", "func (c *Client) Tags(t MetricType, id string, o ...Modifier) (map[string]string, error) {\n\to = prepend(o, c.Url(\"GET\", TypeEndpoint(t), SingleMetricEndpoint(id), TagEndpoint()))\n\n\tr, err := c.Send(o...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer r.Body.Close()\n\n\tif r.StatusCode == http.StatusOK {\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttags := make(map[string]string)\n\t\tif b != nil {\n\t\t\tif err = json.Unmarshal(b, &tags); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn tags, nil\n\t} else if r.StatusCode > 399 {\n\t\treturn nil, c.parseErrorResponse(r)\n\t}\n\n\treturn nil, nil\n}", "func (o *ServiceCheck) GetTags() []string {\n\tif o == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.Tags\n}", "func (o LookupConfigurationAggregatorResultOutput) Tags() ConfigurationAggregatorTagArrayOutput {\n\treturn o.ApplyT(func(v LookupConfigurationAggregatorResult) []ConfigurationAggregatorTag { return v.Tags }).(ConfigurationAggregatorTagArrayOutput)\n}", "func (o RegistryGeoreplicationOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v RegistryGeoreplication) map[string]string { return v.Tags }).(pulumi.StringMapOutput)\n}", "func buildTags() string {\n\treturn *tags\n}", "func (is *ObjectStorage) GetImageTags(repo string) ([]string, error) {\n\tvar lockLatency time.Time\n\n\tdir := path.Join(is.rootDir, repo)\n\tif fi, err := is.store.Stat(context.Background(), dir); err != nil || !fi.IsDir() {\n\t\treturn nil, zerr.ErrRepoNotFound\n\t}\n\n\tis.RLock(&lockLatency)\n\tdefer is.RUnlock(&lockLatency)\n\n\tindex, err := common.GetIndex(is, repo, is.log)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn common.GetTagsByIndex(index), nil\n}", "func (r *Distribution) Tags() pulumi.MapOutput {\n\treturn (pulumi.MapOutput)(r.s.State[\"tags\"])\n}", "func (o LookupListenerResultOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v LookupListenerResult) map[string]string { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (r *PrivateVirtualInterface) Tags() pulumi.MapOutput {\n\treturn (pulumi.MapOutput)(r.s.State[\"tags\"])\n}", "func extractTags(txt string) []string {\n\ttags := []string{}\n\tfor _, match := range TagsRx.FindAllStringSubmatch(txt, -1) {\n\t\ttags = append(tags, strings.TrimLeft(match[1], \"#\"))\n\t}\n\treturn tags\n}", "func (iface tagsInterface) getTaggedApiGateway() (*apigateway.GetRestApisOutput, error) {\n\tctx := context.Background()\n\tapiGatewayAPICounter.Inc()\n\tvar limit int64 = 500 // max number of results per page. default=25, max=500\n\tconst maxPages = 10\n\tinput := apigateway.GetRestApisInput{Limit: &limit}\n\toutput := apigateway.GetRestApisOutput{}\n\tvar pageNum int\n\terr := iface.apiGatewayClient.GetRestApisPagesWithContext(ctx, &input, func(page *apigateway.GetRestApisOutput, lastPage bool) bool {\n\t\tpageNum++\n\t\toutput.Items = append(output.Items, page.Items...)\n\t\treturn pageNum <= maxPages\n\t})\n\treturn &output, err\n}", "func (o LookupDedicatedIpPoolResultOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v LookupDedicatedIpPoolResult) map[string]string { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (o KubernetesNodePoolOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *KubernetesNodePool) pulumi.StringArrayOutput { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func (nrs *NodeResourceState) GetTags() []string {\n\tvar tags []string\n\tif nrs.CPU != nil {\n\t\ttags = append(tags, nrs.CPU.GetTags()...)\n\t}\n\tif nrs.Load != nil {\n\t\ttags = append(tags, nrs.Load.GetTags()...)\n\t}\n\tif nrs.Memory != nil {\n\t\ttags = append(tags, nrs.Memory.GetTags()...)\n\t}\n\tif nrs.DiskIO != nil {\n\t\tfor _, v := range nrs.DiskIO.IOState {\n\t\t\ttags = append(tags, v.GetTags()...)\n\t\t\tbreak\n\t\t}\n\t}\n\tif nrs.NetIO != nil {\n\t\tfor _, v := range nrs.NetIO.IfaceStats {\n\t\t\ttags = append(tags, v.GetTags()...)\n\t\t\tbreak\n\t\t}\n\t}\n\tif nrs.Process != nil {\n\t\ttags = append(tags, nrs.Process.GetTags()...)\n\t}\n\n\treturn tags\n}", "func (o DatabaseReplicaOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *DatabaseReplica) pulumi.StringArrayOutput { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func (is *ImageStoreLocal) GetImageTags(repo string) ([]string, error) {\n\tvar lockLatency time.Time\n\n\tdir := path.Join(is.rootDir, repo)\n\tif !is.DirExists(dir) {\n\t\treturn nil, zerr.ErrRepoNotFound\n\t}\n\n\tis.RLock(&lockLatency)\n\tdefer is.RUnlock(&lockLatency)\n\n\tindex, err := common.GetIndex(is, repo, is.log)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn common.GetTagsByIndex(index), nil\n}", "func (o IotHubDeviceUpdateInstanceOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *IotHubDeviceUpdateInstance) pulumi.StringMapOutput { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (r *DefaultVpcDhcpOptions) Tags() pulumi.MapOutput {\n\treturn (pulumi.MapOutput)(r.s.State[\"tags\"])\n}", "func (vg *VolumeGroup) Tags() ([]string, error) {\n\tresult := new(vgsOutput)\n\tif err := run(\"vgs\", result, \"--options=vg_tags\", vg.name); err != nil {\n\t\tif IsVolumeGroupNotFound(err) {\n\t\t\treturn nil, ErrVolumeGroupNotFound\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tfor _, report := range result.Report {\n\t\tfor _, vg := range report.Vg {\n\t\t\tvar tags []string\n\t\t\tfor _, tag := range strings.Split(vg.VgTags, \",\") {\n\t\t\t\ttag = strings.TrimSpace(tag)\n\t\t\t\tif tag != \"\" {\n\t\t\t\t\ttags = append(tags, tag)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn tags, nil //nolint: staticcheck\n\t\t}\n\t}\n\treturn nil, ErrVolumeGroupNotFound\n}", "func (s *KSession) GetTags() (tags Tags, err error) {\n\ttags = Tags{}\n\tres, err := s.request(\"GET\", EndpointMemeTags, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(res, &tags)\n\treturn\n}", "func (o NetworkInterfaceOutput) Tags() NetworkInterfaceTagArrayOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) NetworkInterfaceTagArrayOutput { return v.Tags }).(NetworkInterfaceTagArrayOutput)\n}", "func fetchTags(c *gin.Context) {\n\tbody, err := ioutil.ReadAll(c.Request.Body)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error--read file: %s\", err)\n\t}\n\tvar request struct {\n\t\tImage string `json:\"image\"`\n\t}\n\terr = json.Unmarshal(body, &request)\n\tif err != nil {\n\t\tfmt.Printf(\"Error--parse json: %s\", err)\n\t}\n\n\t// TODO: somehow refresh token before it expires, without waiting for a request on an expired token\n\tif !CLFclient.isAccessible() {\n\t\tCLFclient.refreshToken()\n\t}\n\tclarifaiTags, err := CLFclient.getImageTags(request.Image)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\ttags, err := getPxTags(clarifaiTags)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, tags)\n}", "func (o BucketReplicationConfigurationRuleFilterPtrOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *BucketReplicationConfigurationRuleFilter) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Tags\n\t}).(pulumi.StringMapOutput)\n}", "func apiTags(res http.ResponseWriter, req *http.Request) {\n\tjsonRes(res, finder.FindTags())\n}", "func (o OceanLaunchSpecOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *OceanLaunchSpec) pulumi.StringArrayOutput { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func (o TrackerOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *Tracker) pulumi.StringMapOutput { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (o BucketIntelligentTieringConfigurationFilterPtrOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *BucketIntelligentTieringConfigurationFilter) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Tags\n\t}).(pulumi.StringMapOutput)\n}", "func (m *Store) GetLanguageTags()([]string) {\n return m.languageTags\n}", "func (o CrawlerOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *Crawler) pulumi.StringMapOutput { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (o *SyntheticsBrowserTest) GetTags() []string {\n\tif o == nil || o.Tags == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.Tags\n}", "func (r RegistryPath) Tag() string {\n\tif strings.Contains(string(r), \"@\") || !strings.Contains(string(r), \":\") {\n\t\treturn \"\"\n\t}\n\n\ttagTokens := strings.Split(string(r), \":\")\n\treturn tagTokens[1]\n}", "func (o LookupManagedPrefixListResultOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v LookupManagedPrefixListResult) map[string]string { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (drc *DummyRegistryClient) AllTags(rn string) (tags []string, err error) {\n\tres := drc.Called(rn)\n\treturn res.Get(0).([]string), res.Error(1)\n}", "func (o ListenerOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v Listener) map[string]string { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (o LookupSharedImageResultOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v LookupSharedImageResult) map[string]string { return v.Tags }).(pulumi.StringMapOutput)\n}", "func processJaegerTags(s *model.Span) (*string, *trace.Endpoint, map[string]string) {\n\tvar kind *string\n\tvar remote *trace.Endpoint\n\ttags := make(map[string]string, len(s.Tags))\n\n\tensureRemote := func() {\n\t\tif remote == nil {\n\t\t\tremote = &trace.Endpoint{}\n\t\t}\n\t}\n\n\tfor i := range s.Tags {\n\t\tswitch s.Tags[i].Key {\n\t\tcase string(ext.PeerHostIPv4):\n\t\t\tip := convertPeerIPv4(&s.Tags[i])\n\t\t\tif ip == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tensureRemote()\n\t\t\tremote.Ipv4 = pointer.String(ip)\n\t\t// ipv6 host is always string\n\t\tcase string(ext.PeerHostIPv6):\n\t\t\tif s.Tags[i].VStr != \"\" {\n\t\t\t\tensureRemote()\n\t\t\t\tremote.Ipv6 = pointer.String(s.Tags[i].VStr)\n\t\t\t}\n\t\tcase string(ext.PeerPort):\n\t\t\tport := convertPeerPort(&s.Tags[i])\n\t\t\tif port == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tensureRemote()\n\t\t\tremote.Port = &port\n\t\tcase string(ext.PeerService):\n\t\t\tensureRemote()\n\t\t\tremote.ServiceName = pointer.String(s.Tags[i].VStr)\n\t\tcase string(ext.SpanKind):\n\t\t\tkind = convertKind(&s.Tags[i])\n\t\tdefault:\n\t\t\tval := tagValueToString(&s.Tags[i])\n\t\t\tif val != \"\" {\n\t\t\t\ttags[s.Tags[i].Key] = val\n\t\t\t}\n\t\t}\n\t}\n\treturn kind, remote, tags\n}", "func (ce *CustomEvent) GetTags() []string {\n\treturn append(ce.tags, \"type:\"+ce.GetType())\n}", "func (pm *PostMetadata) Tags() []string {\n\ttags := make([]string, 0)\n\tsplitTags := strings.Split(pm.TagsRaw, \",\")\n\tfor i := range splitTags {\n\t\ttags = append(tags, strings.TrimSpace(splitTags[i]))\n\t}\n\treturn tags\n}" ]
[ "0.6039615", "0.59908503", "0.5986334", "0.5895096", "0.58939666", "0.5863573", "0.58431673", "0.58150065", "0.57897615", "0.5771257", "0.5767361", "0.57522726", "0.5681852", "0.56656694", "0.5660905", "0.5658994", "0.5647578", "0.56391597", "0.5625925", "0.5622773", "0.56189895", "0.56056786", "0.55770326", "0.55515116", "0.55446637", "0.5538854", "0.5500516", "0.5498226", "0.54980046", "0.5491285", "0.5487815", "0.548336", "0.54821444", "0.5462468", "0.5451085", "0.5449372", "0.5447953", "0.54458034", "0.5440758", "0.5438443", "0.54286474", "0.5426998", "0.5425505", "0.54249513", "0.5422568", "0.5420947", "0.54187524", "0.5410771", "0.54087526", "0.54087526", "0.5408641", "0.54057896", "0.5393456", "0.5392222", "0.5392119", "0.5391747", "0.5380041", "0.5368984", "0.53668183", "0.5366397", "0.5364075", "0.53608793", "0.5357377", "0.5349962", "0.53481966", "0.5347274", "0.53396547", "0.53267884", "0.5322069", "0.53219086", "0.5317962", "0.53146976", "0.53097624", "0.5293381", "0.52926946", "0.5285851", "0.52808744", "0.52723736", "0.52702343", "0.5257845", "0.52561176", "0.5252002", "0.52493715", "0.5245427", "0.5245126", "0.52440685", "0.5243752", "0.52419806", "0.5240182", "0.5237813", "0.5233696", "0.52252734", "0.5221386", "0.5219649", "0.5218349", "0.52059543", "0.5199845", "0.51925623", "0.51892996", "0.51806414" ]
0.58468735
6
SubarraySum calculates the number of continuous subarrays that sum to a certain number
func SubarraySum() { t := []int{-1, -1, 1} fmt.Printf("%d == 1 \n", goodSolution(t, 0)) t = []int{-1, -1, 1} fmt.Printf("%d == 1 \n", goodSolution(t, 1)) t = []int{1, -1, 1, -1, 1, 1, 2} fmt.Printf("%d == 4 \n", goodSolution(t, 2)) t = []int{1, 1, 1} fmt.Printf("%d == 2 \n", goodSolution(t, 2)) t = []int{1} fmt.Printf("%d == 0 \n", goodSolution(t, 0)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func sumSubarrayMins(arr []int) int {\n\tmodBase := 1000000007\n\tsum := 0\n\tsz := len(arr)\n\tstack := util.Stack[int]{}\n\tfor i := 0; i <= sz; i++ {\n\t\tfor evaluateCondition(stack, i, arr) {\n\t\t\tmid, _ := stack.Pop()\n\t\t\tleftBoundry := -1\n\t\t\tif !stack.Empty() {\n\t\t\t\tleftBoundry, _ = stack.Peek()\n\t\t\t}\n\t\t\trightBoundry := i\n\n\t\t\tcount := (mid - leftBoundry) * (rightBoundry - mid) % modBase\n\t\t\tsum += (count * arr[mid]) % modBase\n\t\t\tsum = sum % modBase\n\t\t}\n\t\tstack.Push(i)\n\t}\n\treturn sum\n}", "func sSubarraySum(nums []int, sum int) int {\n\tresult := 0\n\tsumMap := make(map[int]int)\n\n\tcum := 0\n\n\tfor i, v := range nums {\n\t\tcum += v\n\t\tnums[i] = cum\n\t\tsumMap[cum-sum]++\n\t}\n\n\tif c, ok := sumMap[0]; ok {\n\t\tresult += c\n\t}\n\tfor _, v := range nums {\n\t\tif c, ok := sumMap[v]; ok {\n\t\t\tif sum == 0 {\n\t\t\t\tresult += c / 2\n\t\t\t\tdelete(sumMap, v)\n\t\t\t} else {\n\t\t\t\tresult += c\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}", "func SumSubarray(A []int, low, high int) (sum int) {\n\tsum = 0\n\tfor i := low; i < high; i++ {\n\t\tsum += A[i]\n\t}\n\treturn sum\n}", "func minSizeSubArraySum(input []int, targetSum int) int {\n\n\t// check for entry conditions\n\tif len(input) == 0 {\n\t\treturn 0\n\t}\n\n\n\t// Return value should be MIN, so by default set to Max\n\tresult := len(input)\n\n\t// start two pointers starts and end \n\tleftIndex := 0\n\tvalueSum := 0\n\t\n\t// loop on the input array\n\tfor i:=0; i< len(input); i++{\n\n\t\tvalueSum += input[i]\n\n\t\tfor valueSum >= targetSum{\n\t\n\t\t\tresult = min(result, i + 1 - leftIndex )\n\t\t\t\n\t\t\tvalueSum -= input[leftIndex]\n\t\t\tleftIndex++\n\t\t}\t\n\t}\n\n\tif result != len(input){\n\t\treturn result\n\t}\n\treturn 0\n}", "func MaxLengthSumSubArray(arr []int , sum int)[]int {\n\n\tm := make(map[int]int)\n\n\tlength := 0\n\tendIndex := -1\n\n\n\tsumSoFar := 0\n\n\tfor i:=0;i<len(arr);i++{\n\t\tsumSoFar += arr[i]\n\n\t\tif sumSoFar == sum {\n\t\t\treturn arr[0:i+1]\n\t\t}\n\n\t\t// bcoz we need the max length so if sum repeats we need the whole length thats why !ok\n\t\tif _,ok := m[sumSoFar];!ok {\n\t\t\tm[sumSoFar] = i\n\t\t}\n\n\t\tif val,ok := m[sumSoFar-sum];ok && length < i-val {\n\t\t\tlength = i - val\n\t\t\tendIndex = i\n\n\t\t}\n\t}\n\tif endIndex > 0 {\n\t\treturn arr[endIndex - length + 1 : endIndex+1]\n\t} \n\treturn make([]int, 0)\n\t\n\n}", "func subarraySum(nums []int, k int) int {\n\tdic := make(map[int]int)\n\tdic[0] = 1\n\tcurr, res := 0, 0\n\n\tfor _, el := range nums {\n\t\tcurr += el\n\t\tif val, ok := dic[curr-k]; ok == true {\n\t\t\tres += val\n\t\t}\n\t\tif val, ok := dic[curr]; ok == true {\n\t\t\tdic[curr] = val + 1\n\t\t} else {\n\t\t\tdic[curr] = 1\n\t\t}\n\t}\n\treturn res\n}", "func MaximumSubarraySum(numbers []int) int {\n\tmax := 0\n\tfor i := 0; i < len(numbers); i++ {\n\t\tsum := 0\n\t\tfor y := i; y < len(numbers); y++ {\n\t\t\tsum = sum + numbers[y]\n\t\t\tif sum > max {\n\t\t\t\tmax = sum\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}", "func maxSubArraySum(data []int) int {\n\tsum := 0\n\tmax := 0\n\tfor _, v := range data {\n\t\tsum = sum + v\n\t\tif sum < 0 {\n\t\t\tsum = 0\n\t\t}\n\t\tif max < sum {\n\t\t\tmax = sum\n\t\t}\n\t}\n\treturn max\n}", "func main() {\n\tnums := []int{1,1,1}\n\tfmt.Println(subarraySum(nums, 2))\n\n\tnums2 := []int{1,2,3}\n\tfmt.Println(subarraySum(nums2, 3))\n}", "func sumSubarrayMinsBasic(arr []int) int {\n\tmodBase := 1000000007\n\tsum := 0\n\tsz := len(arr)\n\tfor start := 0; start < sz; start++ {\n\t\tmin := arr[start]\n\t\tfor j := start; j < sz; j++ {\n\t\t\tif arr[j] < min {\n\t\t\t\tmin = arr[j]\n\t\t\t}\n\t\t\tsum = sum + min\n\t\t\tsum = sum % modBase\n\t\t}\n\t}\n\treturn sum\n}", "func SumOddLengthSubarrays(arr []int) int {\n result, length := 0, len(arr)\n\n for step := 1; step <= length; step += 2 {\n if step <= length {\n for i := 0; i < length; i++ {\n if i + step <= length {\n for p := i; p < i + step; p++ {\n result = result + arr[p]\n }\n }\n }\n }\n }\n\n return result\n}", "func checkSubarraySum(nums []int, k int) bool {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn false\n\t}\n\n\tfor i := range nums[1:] {\n\t\tif nums[i] == 0 && nums[i+1] == 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tm := make(map[int]int)\n\n\ts := 0\n\tfor i := 0; i < n; i++ {\n\t\ts += nums[i]\n\t\tif _, ok := m[s]; !ok {\n\t\t\tm[s] = i\n\t\t}\n\t}\n\n\tif k == s || s == 0 || k == 1 {\n\t\treturn true\n\t}\n\n\tif k > s {\n\t\treturn false\n\t}\n\n\tm[0] = -1\n\n\tmul := s / k\n\tfor v, i := range m {\n\t\tfor x := 1; x <= mul; x++ {\n\t\t\tif k*x > v {\n\t\t\t\tj, ok := m[k*x+v]\n\t\t\t\tif ok && j-i >= 2 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tj, ok := m[v-k*x]\n\t\t\t\tif ok && i-j >= 2 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func FindMaxSumOfSubArray(arr []int) (int, bool) {\n\tif arr == nil || len(arr) < 1 {\n\t\treturn 0, false\n\t}\n\n\tmaxSum, curSum := ^int(^uint(0)>>1), 0\n\tfor _, e := range arr {\n\t\tif curSum <= 0 {\n\t\t\tcurSum = e\n\t\t} else {\n\t\t\tcurSum += e\n\t\t}\n\t\tif maxSum < curSum {\n\t\t\tmaxSum = curSum\n\t\t}\n\t}\n\treturn maxSum, true\n}", "func NumSubmatrixSumTarget(matrix [][]int, target int) int {\n\tvar rows int = len(matrix)\n\tvar columns int = len(matrix[0])\n\tvar prefix [][]int = make([][]int,rows + 1)//prefix[i][j] = sum from 0,0 to i - 1,j - 1\n\tfor i := 0;i <= rows;i++{\n\t\tprefix[i] = make([]int,columns + 1)\n\t}\n\tfor i := 1;i <= rows;i++{\n\t\tfor j := 1;j <= columns;j++{\n\t\t\tprefix[i][j] = matrix[i - 1][j - 1] + prefix[i - 1][j] + prefix[i][j - 1] - prefix[i - 1][j - 1]\n\t\t}\n\t}\n\tvar res int = 0\n\tfor i := 0;i <= rows;i++{\n\t\tfor j := 0;j <= columns;j++{\n\t\t\tfor r := i + 1;r <= rows;r++{\n\t\t\t\tfor c := j + 1;c <= columns;c++{\n\t\t\t\t\tarea := prefix[r][c] - prefix[r][j] - prefix[i][c] + prefix[i][j]\n\t\t\t\t\tif area == target{\n\t\t\t\t\t\tres++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func maxSubsetSum(arr []int32) int32 {\n\tk := make([]int32, len(arr))\n\n\tfor i := range arr {\n\t\tif i == 0 {\n\t\t\tk[i] = arr[i]\n\t\t} else if i == 1 {\n\t\t\tk[i] = max(arr[i], arr[i-1])\n\t\t} else {\n\t\t\tk[i] = max(k[i-2]+arr[i], k[i-1])\n\t\t}\n\t}\n\n\tif k[len(arr)-1] <= 0 {\n\t\treturn 0\n\t}\n\n\treturn k[len(arr)-1]\n}", "func SumOfSlice(array []int) int {\n\tsum := 0\n\tfor _, num := range array {\n\t\tsum += num\n\t}\n\treturn sum\n}", "func maxSubArray(nums []int) int {\n if len(nums) == 0 {\n return 0\n }\n result := nums[0]\n preSum := nums[0]\n for i:=1; i<len(nums); i++ {\n if preSum < 0 {\n preSum = nums[i]\n } else {\n preSum += nums[i]\n }\n result = max(result, preSum)\n }\n return result\n}", "func checkSubarraySum(nums []int, k int) bool {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn false\n\t}\n\tindex := make(map[int]int)\n\tindex[0] = -1\n\n\tsum := 0\n\tfor i := 0; i < n; i++ {\n\t\tsum += nums[i]\n\t\tif k != 0 {\n\t\t\tsum %= k\n\t\t}\n\n\t\tidx, ok := index[sum]\n\t\tif ok {\n\t\t\tif i-idx > 1 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else {\n\t\t\tindex[sum] = i\n\t\t}\n\t}\n\treturn false\n}", "func SumContinousArray(arr []int, k int) {\n\tfor start := 0; start < len(arr); start++ {\n\t\tsum = 0\n\t\tfor end := start + 1; end < len(arr); end++ {\n\t\t\tsum += arr[end]\n\t\t\tif sum == k {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n}", "func sliceSum(a []float64) float64", "func FindSubArrayWithMaxSum(arr []int) []int {\n\tif arr == nil || len(arr) < 1 {\n\t\treturn nil\n\t}\n\tsub := []int{}\n\tbegin := 0\n\tmaxSum, curSum := ^int(^uint(0)>>1), 0\n\tfor i, e := range arr {\n\t\tif curSum <= 0 {\n\t\t\tbegin = i\n\t\t\tcurSum = e\n\t\t\tsub = []int{e}\n\t\t} else {\n\t\t\tcurSum += e\n\t\t}\n\t\tif maxSum < curSum {\n\t\t\tmaxSum = curSum\n\t\t\tsub = arr[begin : i+1]\n\t\t}\n\t}\n\treturn sub\n}", "func maxSubsetSum(arr []int32) int32 {\n\t// Check if the array contains any element\n\t// The sum of 0 subset is 0\n\tif len(arr) == 0 {\n\t\treturn int32(0)\n\t}\n\n\t// Check if the array contains only 1 element\n\t// If yes, return the first element\n\tarr[0] = int32(math.Max(float64(0), float64(arr[0])))\n\tif len(arr) == 1 {\n\t\treturn arr[0]\n\t}\n\n\t// At index 1, the max value could be at index 0 or\n\t// at index 1 itself\n\tarr[1] = int32(math.Max(float64(arr[0]), float64(arr[1])))\n\n\t// Loop for the length of the array but start at index 2\n\tfor index := 2; index < len(arr); index++ {\n\n\t\t// At index 2, calculate which is greater\n\t\t// Previous value at current index - 1 or current value plus previous value at current index - 2\n\t\t// That way, at each iteration we keep track of current max value that are stored at current index - 1\n\t\tarr[index] = int32(math.Max(float64(arr[index-1]), float64(arr[index-2]+arr[index])))\n\t}\n\n\t// After the sum, we keep the max value at last index\n\t// Return it\n\treturn arr[len(arr)-1]\n}", "func subsetSum(nums []int, target int) int {\n\t dp := make([]int, target+1)\n\t dp[0] = 1\n\t for _, n := range nums {\n\t\t for i := target; i >= n; i-- {\n\t\t\t dp[i] += dp[i - n]\n\t\t }\n\t }\n\t return dp[target]\n}", "func minSubArrayLen(s int, nums []int) int {\n\tleft := 0\n\tflen := 0\n\tlength := 0\n\tvar sum int\n\tfor j := 0; j < len(nums); j++ {\n\t\tsum += nums[j]\n\t\tif sum >= s {\n\t\t\tlength = j + 1\n\t\t}\n\t}\n\n\tfor left <= len(nums) {\n\t\ttmp := 0\n\t\tfor i := left; i < min(left+length, len(nums)); i++ {\n\t\t\ttmp += nums[i]\n\t\t}\n\t\tif tmp >= s {\n\t\t\tflen = length\n\t\t\tlength--\n\t\t\tcontinue\n\t\t}\n\t\tleft++\n\t}\n\n\treturn flen\n}", "func sumOfNumbers(slice []int) int {\n\tnumber := 0\n\n\tfor _, value := range slice {\n\t\tnumber += value\n\t}\n\treturn number\n}", "func maxSubArray(nums []int) int {\n\tvar sum int\n\tvar max int\n\tmax = nums[0]\n\tfor i := 0; i < len(nums); i++ {\n\t\tsum = sum + nums[i]\n\t\tif sum > max {\n\t\t\tmax = sum\n\t\t}\n\t\tif sum < 0 {\n\t\t\tsum = 0\n\t\t}\n\t}\n\treturn max\n}", "func maxSubArray(nums []int) int {\n\tstMax := -1\n\tvar max int\n\t// var endMax int\n\tfor st := 0; st < len(nums); st++ {\n\t\tsum := 0\n\t\tfor end := st; end < len(nums); end++ {\n\t\t\tsum += nums[end]\n\t\t\tif (stMax < 0) || (sum > max) {\n\t\t\t\tmax = sum\n\t\t\t\tstMax = st\n\t\t\t\t// end_max = end\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}", "func SumArray(arr []int, k int) {\n\tvar count int\n\tfor start := 0; start < len(arr); start++ {\n\t\tsum := 0\n\t\tfor end := start + 1; end < len(arr); end++ {\n\t\t\tsum += arr[end]\n\t\t\tif sum == k {\n\t\t\t\tcount++\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}", "func maxSubArray(nums []int) int {\n\tnumsLen := len(nums)\n\tif numsLen < 1 {\n\t\treturn 0\n\t}\n\tpreviouse, max := nums[0], nums[0]\n\tfor i := 1; i < numsLen; i++ {\n\t\tif previouse > 0 {\n\t\t\tpreviouse += nums[i]\n\t\t} else {\n\t\t\tpreviouse = nums[i]\n\t\t}\n\t\tif previouse > max {\n\t\t\tmax = previouse\n\t\t}\n\t}\n\treturn max\n}", "func MaximumUniqueSubarray(nums []int) int{\n\tvar l int = len(nums)\n\tvar left int = 0\n\tvar right int = 0\n\tvar record map[int]bool = make(map[int]bool)\n\tvar cur_sum int = 0\n\tvar res int = 0\n\tfor left < l{\n\t\tfor right < l{\n\t\t\tif _,ok := record[nums[right]];ok{\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcur_sum += nums[right]\n\t\t\trecord[nums[right]] = true\n\t\t\tright++\n\t\t\tres = max_int(res,cur_sum)\n\t\t}\n\t\tcur_sum -= nums[left]\n\t\tdelete(record,nums[left])\n\t\tleft++\n\t}\n\treturn res\n}", "func SubArrayWithZeroSum(input []int) {\n\t// O(n) multi-dimensional map\n\tset := map[int][]int{0: []int{-1}}\n\tsum := 0\n\tfor key, val := range input {\n\t\tsum += val\n\t\tif indexes, ok := set[sum]; ok {\n\t\t\tfor _, idx := range indexes {\n\t\t\t\tfmt.Println(idx+1, \" ... \", key)\n\t\t\t}\n\t\t}\n\t\tset[sum] = append(set[sum], key)\n\t}\n}", "func MaxSumSubmatrix(matrix [][]int, k int) int {\n type point struct {\n i, j int\n }\n // re map right bottom point to left top point for all sub matrix\n re := make(map[point]map[point]int)\n var maxSum int\n var hasSum bool\n for i := range matrix {\n for j := range matrix[i] {\n re[point{i,j}] = map[point]int{point{i,j}: matrix[i][j]}\n if (!hasSum || matrix[i][j] > maxSum) && matrix[i][j] <= k {\n maxSum = matrix[i][j]\n hasSum = true\n }\n if hasSum && maxSum == k {\n return maxSum\n }\n\n if i > 0 {\n s := 0\n for jLeftTop := j; jLeftTop >= 0; jLeftTop-- {\n s += matrix[i][jLeftTop]\n m, exist := re[point{i-1, j}]\n if !exist {\n break\n }\n for p := range m {\n if p.j != jLeftTop {\n continue\n }\n re[point{i, j}][p] = m[p] + s\n if (!hasSum || re[point{i, j}][p] > maxSum) && re[point{i, j}][p] <= k {\n maxSum = re[point{i, j}][p]\n hasSum = true\n }\n if hasSum && maxSum == k {\n return maxSum\n }\n }\n }\n }\n\n if j > 0 {\n s := 0\n for iLeftTop := i; iLeftTop >= 0; iLeftTop-- {\n s += matrix[iLeftTop][j]\n m, exist := re[point{i, j-1}]\n if !exist {\n continue\n }\n for p := range m {\n if p.i != iLeftTop {\n continue\n }\n re[point{i, j}][p] = m[p] + s\n if (!hasSum || re[point{i, j}][p] > maxSum) && re[point{i, j}][p] <= k {\n maxSum = re[point{i, j}][p]\n hasSum = true\n }\n if hasSum && maxSum == k {\n return maxSum\n }\n }\n }\n }\n }\n }\n\n return maxSum\n}", "func TotalSum(array []int) (ts int) {\n\tfor _, v := range array {\n\t\tts += v\n\t}\n\treturn\n}", "func maxSubArray(nums []int) int {\n dp := make([]int, len(nums))\n if len(nums) == 0 {\n return 0\n }\n if len(nums) == 1 {\n return nums[0]\n }\n result := nums[0]\n for i:=0; i<len(nums); i++ {\n if i == 0 {\n dp[0] = nums[0]\n continue\n }\n if dp[i-1] > 0 {\n dp[i] = dp[i-1] + nums[i]\n } else {\n dp[i] = nums[i]\n }\n if dp[i] > result {\n result = dp[i]\n }\n }\n return result\n}", "func maxSumOfThreeSubarrays(nums []int, k int) []int {\n // to find 3 non-overlapping subarrays in nums[:i], \n // if we use nums[i-k: i], we need to find 2 subarrays in nums[:i-k];\n // if we don't use, we need to find 3 subrarrys in nums[:i-1]\n sum := make([]int, len(nums)+1)\n for i:=1; i<=len(nums); i++ {\n \tsum[i] = sum[i-1]+nums[i-1]\n }\n\n one := make([][2]int, len(nums))\n one[k-1] = [2]int{sum[k], 0} // (sum, start) pair\n for i:=k; i<len(nums); i++ { // from [0...i], select one k-length subarray with max sum\n \tone[i] = one[i-1]\n \tif sum[i+1]-sum[i-k+1] > one[i][0] {\n \t\tone[i][0] = sum[i+1]-sum[i-k+1]\n \t\tone[i][1] = i-k+1\n \t}\n } \n // fmt.Println(one)\n\n two := make([][3]int, len(nums)) \n two[2*k-1] = [3]int{sum[2*k], 0, k} // (sum, start1, starrt2) pair \n for i:=2*k; i<len(nums); i++ { // from [0...i], select two k-length subarrays with max sum\n \ttwo[i] = two[i-1]\n \tif one[i-k][0]+sum[i+1]-sum[i-k+1] > two[i][0] {\n \t\ttwo[i][0] = one[i-k][0]+sum[i+1]-sum[i-k+1]\n \t\ttwo[i][1] = one[i-k][1]\n \t\ttwo[i][2] = i-k+1\n \t}\n }\n // fmt.Println(two)\n\n three := make([][4]int, len(nums))\n three[3*k-1] = [4]int{sum[3*k], 0, k, 2*k} // (sum, start1, starrt2, start3) pair \n for i:=3*k; i<len(nums); i++ { // from [0...i], select three k-length subarrays with max sum\n \t// select 3 subarrays from [0...i-k], or,\n \t// select 2 from [0...i-k], plus [i-k+1...i]\n \tthree[i] = three[i-1]\n \tif two[i-k][0]+sum[i+1]-sum[i-k+1] > three[i][0] {\n \t\tthree[i][0] = two[i-k][0]+sum[i+1]-sum[i-k+1]\n \t\tthree[i][1] = two[i-k][1]\n \t\tthree[i][2] = two[i-k][2]\n \t\tthree[i][3] = i-k+1\n \t}\n }\n // fmt.Println(three)\n\n return three[len(nums)-1][1:]\n}", "func MaxSumSubArrayOfSizeK(nums []int, k int) int {\n\tif len(nums) < k {\n\t\treturn 0\n\t}\n\n\tvar start, windowSum int\n\tmax := math.MinInt64\n\n\tfor end, num := range nums {\n\t\twindowSum += num\n\t\tif end >= k-1 {\n\t\t\tif windowSum > max {\n\t\t\t\tmax = windowSum\n\t\t\t}\n\t\t\twindowSum -= nums[start]\n\t\t\tstart++\n\t\t}\n\t}\n\n\treturn max\n}", "func arrayPairSum(nums []int) int {\n\tcounts := make([]int, 20001)\n\tfor _, n := range nums {\n\t\tcounts[n+10000]++\n\t}\n\tvar sum int\n\tadd := true\n\tfor i, _ := range counts {\n\t\tfor 0 < counts[i] {\n\t\t\tif add {\n\t\t\t\tsum += i - 10000\n\t\t\t}\n\t\t\tcounts[i]--\n\t\t\tadd = !add\n\t\t}\n\t}\n\treturn sum\n}", "func maxSubArray(nums []int) int {\n\tn := len(nums)\n\tif n == 0 {\n\t\treturn 0\n\t}\n\tif n == 1 {\n\t\treturn nums[0]\n\t}\n\tdp := make([]int, n)\n\tdp[0] = nums[0] // 注意dp是连续到最后一个index的最大subarray\n\tmax := nums[0]\n\tfor i := 1; i < n; i++ {\n\t\tif nums[i] >= 0 {\n\t\t\tif dp[i-1] <= 0 {\n\t\t\t\tdp[i] = nums[i]\n\t\t\t} else {\n\t\t\t\tdp[i] = dp[i-1] + nums[i]\n\t\t\t}\n\t\t} else {\n\t\t\tif dp[i-1] + nums[i] >= 0 {\n\t\t\t\tdp[i] = dp[i-1] + nums[i]\n\t\t\t} else {\n\t\t\t\tdp[i] = nums[i]\n\t\t\t}\n\t\t}\n\t\tif dp[i] > max {\n\t\t\tmax = dp[i]\n\t\t}\n\t}\n\t//fmt.Println(dp)\n\treturn max\n}", "func SumArray(n [5]int) int {\n\tsum := 0\n\tfor _, n := range n {\n\t\tsum += n\n\n\t}\n\treturn sum\n}", "func countTotal(P []int, x int, y int) int {\n return P[y+1] - P[x]\n}", "func Sum(arrays ...[]int) []int {\n\tresult := []int{}\n\tfor _, arr := range arrays {\n\t\tcount := 0\n\t\tfor _, elem := range arr {\n\t\t\tcount += elem\n\t\t}\n\t\tresult = append(result, count)\n\t}\n\treturn result\n}", "func maxSubArray2(nums []int) int {\n\tvar sum = math.MinInt64\n\tvar suffixSum int\n\tfor _, num := range nums {\n\t\tif suffixSum < 0 {\n\t\t\tsuffixSum = 0\n\t\t}\n\t\tsuffixSum += num\n\t\tsum = max(sum, suffixSum)\n\t}\n\treturn sum\n}", "func (na *NArray) Sum() float32 {\n\treturn sliceSum(na.Data)\n}", "func SumSlice(s []int) int {\n\tsum := 0\n\tfor _, s := range s {\n\t\tsum += s\n\t}\n\treturn sum\n}", "func countRangeSum1(nums []int, lower int, upper int) int {\n\trst := 0\n\tfor i := 0; i < len(nums); i++ {\n\t\tfor j := i; j < len(nums); j++ {\n\t\t\ttmp := 0\n\t\t\tfor k := i; k <= j; k++ { // s(i,j)\n\t\t\t\ttmp += nums[k]\n\t\t\t}\n\t\t\tif tmp <= upper && tmp >= lower {\n\t\t\t\trst++\n\t\t\t}\n\t\t}\n\t}\n\treturn rst\n}", "func arrayPairSum(nums []int) int {\n\tmin, max := nums[0], nums[0]\n\tfor _, num := range nums {\n\t\tif num < min {\n\t\t\tmin = num\n\t\t}\n\t\tif num > max {\n\t\t\tmax = num\n\t\t}\n\t}\n\n\tbuckets := make([]int, max-min+1)\n\tfor _, num := range nums {\n\t\tbuckets[num-min]++\n\t}\n\n\tvar isLeft bool\n\tvar sum int\n\tvar num, quotient, modulo int\n\tfor idx, item := range buckets {\n\t\tif item <= 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tnum = idx + min\n\t\tif isLeft {\n\t\t\tisLeft = false\n\t\t\titem--\n\n\t\t\tif item <= 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tquotient = item / 2\n\t\tmodulo = item % 2\n\n\t\tsum += num * quotient\n\t\tif modulo > 0 {\n\t\t\tisLeft = true\n\t\t\tsum += num\n\t\t}\n\t}\n\n\treturn sum\n}", "func sumArray(arr []int) int {\n\tvar sum int\n\tfor _, elem := range arr {\n\t\tsum += elem\n\t}\n\treturn sum\n}", "func subsetSumRecursive(data []int, n int, sum int, acc []int) (bool, []int) {\n\n\tfmt.Printf(\"n:%d\\n\", n)\n\n\tif sum == 0 {\n\t\treturn true, acc\n\t}\n\n\tif n < 0 || sum < 0 {\n\t\treturn false, nil\n\t}\n\n\t// Case 1. include current item in the subset (A[n]) and recur\n\t// for remaining items (n - 1) with remaining sum (sum - A[n])\n\tinclude, acc1 := subsetSumRecursive(data, n-1, sum-data[n], append(acc, data[n]))\n\n\t// Case 2. exclude current item n from subset and recur for\n\t// remaining items (n - 1)\n\texclude, acc2 := subsetSumRecursive(data, n-1, sum, acc)\n\n\t// return true if we can get subset by including or excluding the\n\t// current item\n\tif include {\n\t\treturn include, acc1\n\t}\n\n\tif exclude {\n\t\treturn exclude, acc2\n\t}\n\n\treturn false, nil\n}", "func sum(array1 []int) (sum int) {\n\n\t\ti := len( array1 );\n\n\t\tfor\t i > 0 {\n\n\t\t\tsum += array1[i-1]\n\t\t\ti--\n\t\t}\n\n\t\treturn\n\t}", "func (f *fragment) sum(filter *Row, bitDepth uint) (sum int64, count uint64, err error) {\n\t// Compute count based on the existence row.\n\tconsider := f.row(bsiExistsBit)\n\tif filter != nil {\n\t\tconsider = consider.Intersect(filter)\n\t}\n\tcount = consider.Count()\n\n\t// Determine positive & negative sets.\n\tnrow := f.row(bsiSignBit)\n\tprow := consider.Difference(nrow)\n\n\t// Compute the sum based on the bit count of each row multiplied by the\n\t// place value of each row. For example, 10 bits in the 1's place plus\n\t// 4 bits in the 2's place plus 3 bits in the 4's place equals a total\n\t// sum of 30:\n\t//\n\t// 10*(2^0) + 4*(2^1) + 3*(2^2) = 30\n\t//\n\t// Execute once for positive numbers and once for negative. Subtract the\n\t// negative sum from the positive sum.\n\tfor i := uint(0); i < bitDepth; i++ {\n\t\trow := f.row(uint64(bsiOffsetBit + i))\n\n\t\tpsum := int64((1 << i) * row.intersectionCount(prow))\n\t\tnsum := int64((1 << i) * row.intersectionCount(nrow))\n\n\t\t// Squash to reduce the possibility of overflow.\n\t\tsum += psum - nsum\n\t}\n\n\treturn sum, count, nil\n}", "func (ls *LevelSlice) SizeSum() uint64 {\n\tvar sum uint64\n\titer := ls.Iter()\n\tfor f := iter.First(); f != nil; f = iter.Next() {\n\t\tsum += f.Size\n\t}\n\treturn sum\n}", "func TestNumArray(t *testing.T) {\n\t// Example:\n\tast := assert.New(t)\n\tnums := []int{-2, 0, 3, -5, 2, -1}\n\t// Given nums = [-2, 0, 3, -5, 2, -1]\n\tobj := Constructor(nums)\n\tast.Equal(-2, obj.SumRange(0, 0))\n\tast.Equal(1, obj.SumRange(0, 2))\n\t// sumRange(0, 2) -> 1\n\tast.Equal(-1, obj.SumRange(2, 5))\n\t// sumRange(2, 5) -> -1\n\tast.Equal(-3, obj.SumRange(0, 5))\n\t// sumRange(0, 5) -> -3\n}", "func findUnsortedSubarray(nums []int) int {\n l := len(nums)\n lv, rv := false,false\n var lMin, rMax = nums[l-1], nums[0]\n for i := 0; i< l-1; i++ {\n if lv {\n lMin = min(lMin, nums[i])\n } else {\n lv = nums[i] > nums[i+1]\n }\n\n if rv {\n rMax = max(rMax, nums[l-1-i])\n } else {\n rv = nums[l-1-i] < nums[l-2-i]\n }\n }\n\n if !lv || !rv {\n return 0\n }\n\n li,ri := 0, l\n for i := 0; i < l-1; i++ {\n if lMin < nums[i]{\n li = i\n break\n }\n }\n for i := 0; i < l-1; i++ {\n if rMax > nums[l-1-i] {\n ri = l-i\n break\n }\n }\n return ri - li\n}", "func sum(arr []int) int {\n\tvar res int\n\tfor _, v := range arr {\n\t\tres += v\n\t}\n\treturn res\n}", "func Sum(in []int) (total int) {\n\ttotal = 0\n\tfor _, v := range in {\n\t\ttotal += v\n\t}\n\treturn\n}", "func totals(arr []int) []int {\n\tvar diffs []int\n\tcount := 0\n\tfor i := range arr {\n\t\tif i < len(arr)-1 && arr[i+1]-arr[i] == 1 {\n\t\t\tcount++\n\t\t} else {\n\t\t\tif count > 0 {\n\t\t\t\tdiffs = append(diffs, count)\n\t\t\t}\n\t\t\tcount = 0\n\t\t}\n\t}\n\n\tvar totals []int\n\tfor i := range diffs {\n\t\tn := diffs[i]\n\t\ttotals = append(totals, 1+(n*(n-1)/2))\n\t}\n\treturn totals\n}", "func maxSubarray(arr []int32) []int32 {\n\tmaxSub := int32(0)\n\tmaxSeq := int32(0)\n\tsubs := make([]int32, len(arr))\n\thasPos := false\n\tmaxNeg := int32(0)\n\tfor i, n := range arr {\n\t\tif n >= 0 {\n\t\t\thasPos = true\n\t\t\tmaxSeq = maxSeq + n\n\t\t} else if n > maxNeg || maxNeg == 0 {\n\t\t\tmaxNeg = n\n\t\t}\n\t\tif i > 0 {\n\t\t\tsub := subs[i-1] + n\n\t\t\tif sub > 0 {\n\t\t\t\tsubs[i] = sub\n\t\t\t} else {\n\t\t\t\tsubs[i] = 0\n\t\t\t}\n\t\t} else {\n\t\t\tsubs[i] = n\n\t\t}\n\t\tif subs[i] > maxSub {\n\t\t\tmaxSub = subs[i]\n\t\t}\n\t}\n\tif !hasPos {\n\t\tmaxSeq = maxNeg\n\t\tmaxSub = maxNeg\n\t}\n\treturn []int32{maxSub, maxSeq}\n}", "func SumAll(arrays ...[]int) (sums []int) {\n\t// sums = make([]int, len(arrays))\n\n\t// for i, array := range arrays {\n\t// \tsums[i] = SumOfSlice(array)\n\t// }\n\tfor _, array := range arrays {\n\t\tsums = append(sums, SumOfSlice(array))\n\t}\n\treturn sums\n}", "func subarraysDivByK(A []int, K int) int {\n cursum := 0\n mapp := make(map[int]int)\n mapp[0] = 1 // no numbers sums to 0, 1 way\n count := 0\n for i:=0; i<len(A); i++ {\n \tcursum += A[i]\n \tkey := (cursum%K+K)%K // avoid negative \n \tprev := mapp[key] // how many previous sums that mod K = cursum mod K\n \tcount += prev\n \tmapp[key] = mapp[key]+1\n }\n return count\n}", "func Recursion(arr []int, sum int) (bool, subset) {\n\tarrLen := len(arr)\n\n\tif sum == 0 {\n\t\treturn true, subset{}\n\t}\n\tif sum < 0 || (sum > 0 && arrLen == 0) {\n\t\treturn false, nil\n\t}\n\n\t// check if the last element of arr is part of the sum\n\twithoutBool, withoutSet := Recursion(arr[:arrLen-1], sum)\n\tif withoutBool {\n\t\t// the 'sum' can be calculated without the last element of arr\n\t\treturn withoutBool, withoutSet\n\t}\n\n\t// the 'sum' cannot be calculated without the last element of arr\n\tarrLast := arr[arrLen-1]\n\twithBool, withSet := Recursion(arr[:arrLen-1], sum-arrLast)\n\tif withBool {\n\t\t// the 'sum' can be calculated with the last element of arr\n\t\twithSet[arrLast]++\n\t\treturn withBool, withSet\n\t}\n\treturn false, nil\n}", "func MaxSumIncreasingSub(arr []int) int {\n\tans := []int{}\n\tvar res int\n\tans = append(ans, arr[0])\n\tfor i := 1; i < len(arr); i++ {\n\t\tcurrent := arr[i]\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif arr[j] < arr[i] {\n\t\t\t\tcurrent += arr[j]\n\t\t\t}\n\t\t}\n\t\tans = append(ans, current)\n\t}\n\n\tprintln(\"The valur of the ans is \")\n\tfor i := 0; i < len(ans); i++ {\n\n\t\tfmt.Printf(\"%v \", ans[i])\n\t}\n\tprintln(\"\")\n\n\tfor i := 0; i < len(ans); i++ {\n\t\tif res < ans[i] {\n\t\t\tres = ans[i]\n\t\t}\n\t}\n\n\treturn res\n}", "func sum(arr []int) int {\n\ts := 0\n\tfor i := 0; i < len(arr); i++ {\n\t\ts += arr[i]\n\t}\n\treturn s\n}", "func main() {\n\tnumArray := Constructor([]int{-2, 0, 3, -5, 2, -1})\n\tfmt.Println(numArray.SumRange(0, 2))\n\tfmt.Println(numArray.SumRange(2, 5))\n\tfmt.Println(numArray.SumRange(0, 5))\n}", "func sum(arr []int) (result int) {\n\tfor _, each := range arr {\n\t\tresult += each\n\t}\n\treturn\n}", "func calcTotalSpin (spin [][]int) int {\n\ttotalSpin := 0\n\n\tfor ix:=0; ix<nx; ix++ {\n\t\tfor iy:=0; iy<ny; iy++ {\n\t\t\ttotalSpin += spin[ix][iy]\n\t\t}\n\t}\n\treturn totalSpin\n}", "func arrayManipulation(n int32, queries [][]int32) int64 {\n\tmax, arr, sum := int64(0), make([]int64, n), int64(0)\n\n\t// Instead of observing increases on each individual value...\n\t// We observe each beginning of range increase, and where it ends.\n\t//\n\t// For example:\n\t// n = 5, m = 3\n\t// a b k\n\t// 1 2 100 -> this will add 100 to n[1 - 1] and -100 to n[2]\n\t// 2 5 100 -> this will add 100 to n[2 - 1] and should add -100 to n[5] or none at all since it is beyond index range\n\t// 3 4 100\n\t// Expected output: 200\n\t//\n\t// Begin with: [5]int64 {0, 0, 0, 0, 0}\n\t// Then we iterate through the queries\n\t// m[0]: {100, 0, -100, 0, 0}\n\t// m[1]: {100, 100, -100, 0, 0}\n\t// m[2]: {100, 100, 0, 0, -100}\n\t//\n\t// Then we'll get sum of the whole array\n\t// while observing the peak sum as max value\n\t// (0)+100 100(+100) 200(+0) 200(+0) 100(-100)\n\n\tfor i := 0; i < len(queries); i++ {\n\t\tquery := queries[i]\n\t\ta := query[0] - 1\n\t\tb := query[1] - 1\n\t\tk := int64(query[2])\n\t\tarr[a] += k\n\t\tif b+1 < n {\n\t\t\tarr[b+1] -= k\n\t\t}\n\t}\n\tfor i := int32(0); i < n; i++ {\n\t\tif arr[i] != 0 {\n\t\t\tsum += arr[i]\n\t\t\tif sum > max {\n\t\t\t\tmax = sum\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}", "func FindMaxSubarrayBrute(A []int, low, high int) (i, j, sum int) {\n\tmaxLeft, maxRight := low, low+1 // initialize to valid values\n\tmaxSum := MinInt\n\tfor i := low; i < high; i++ {\n\t\tfor j := i + 1; j <= high; j++ {\n\t\t\tsum = SumSubarray(A, i, j)\n\t\t\tif sum > maxSum {\n\t\t\t\tmaxSum = sum\n\t\t\t\tmaxLeft, maxRight = i, j\n\t\t\t}\n\t\t}\n\t}\n\treturn maxLeft, maxRight, maxSum\n}", "func SumAll(slices ...[]int) []int {\n\tsums := make([]int, len(slices))\n\tfor i, numbers := range slices {\n\t\tsums[i] = Sum(numbers)\n\t}\n\treturn sums\n}", "func (n *NumArray) SumRange(i int, j int) int {\n\treturn n.sums[j+1] - n.sums[i]\n}", "func findElementsWithSum(arr [5]int, combinations [10]int, size int, k int, addValue int, l int, m int) int {\r\n\tvar num int = 0\r\n\tif addValue > k {\r\n\t\treturn -1\r\n\t}\r\n\tif addValue == k {\r\n\t\tnum = num + 1\r\n\t\tvar p int = 0\r\n\t\tfor p = 0; p < m; p++ {\r\n\t\t\tfmt.Printf(\"%d,\", arr[combinations[p]])\r\n\t\t}\r\n\t\tfmt.Println(\" \")\r\n\t}\r\n\tvar i int\r\n\tfor i = l; i < size; i++ {\r\n\t\t//fmt.Println(\" m\", m)\r\n\t\tcombinations[m] = l\r\n\t\tfindElementsWithSum(arr, combinations, size, k, addValue+arr[i], l, m+1)\r\n\t\tl = l + 1\r\n\t}\r\n\treturn num\r\n}", "func findUnsortedSubarray_Solution_1(nums []int) int {\n\tvar s Stack\n\tvar hasFirst bool\n\tvar res int\n\tvar max int\n\n\tfor i, num := range nums {\n\t\tif i == 0 || num >= max {\n\t\t\tif !hasFirst {\n\t\t\t\ts.push(i)\n\t\t\t}\n\t\t\tmax = num\n\t\t} else {\n\t\t\tfor !s.isEmpty() && num < nums[s.top()] {\n\t\t\t\ts.pop()\n\t\t\t}\n\t\t\tif s.isEmpty() {\n\t\t\t\tres = i - (-1)\n\t\t\t} else {\n\t\t\t\tres = i - s.top()\n\t\t\t}\n\t\t\thasFirst = true\n\t\t}\n\t}\n\treturn res\n}", "func SumAllTails(arrays ...[]int) (sums []int) {\n\tfor _, array := range arrays {\n\t\tif len(array) == 0 {\n\t\t\tsums = append(sums, 0)\n\t\t} else {\n\t\t\ttails := array[1:]\n\t\t\tsums = append(sums, SumOfSlice(tails))\n\t\t}\n\t}\n\treturn\n}", "func getSumsOfComb(index int, k int, ar []int) int {\n\tvar res []int\n\tres = append(res, 0)\n\tvar n = len(ar)\n\tvar s = 0\n\tfor t := 1; t <= k; t++ {\n\t\tvar j = res[t-1] + 1\n\t\tfor {\n\t\t\tif !((j < (n - k + t)) && ((s + countCombinations(n-j, k-t)) <= index)) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ts += countCombinations(n-j, k-t)\n\t\t\tj++\n\t\t}\n\t\tres = append(res, j)\n\t}\n\n\tsum := 0\n\tfor i := 1; i < len(res); i++ {\n\t\tsum += ar[res[i]-1]\n\t}\n\treturn sum\n}", "func maxSumCircularArray(input []int) int {\n\tif len(input) == 0 {\n\t\treturn 0\n\t}\n\n\tif len(input) == 1 {\n\t\treturn input[0]\n\t}\n\n\t// maxsum excluding 1st element from left to right\n\tmaxSum1 := maxSum(input[1:])\n\n\t// maxsum excluding nth element from right to left\n\tmaxSum2 := maxSum(input[:len(input)-1])\n\n\treturn max(maxSum1, maxSum2)\n}", "func TestSumSlice(t *testing.T){\n\tassertCorrectMessage := func(t *testing.T, got, want int) {\n t.Helper()\n if got != want {\n t.Errorf(\"got %d want %d\", got, want)\n }\n\t}\n\t\n\tt.Run(\"Adding numbers inside array and returning sum\", func(t *testing.T){\n\t\tslicenumbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\t\tgot := SumSlice(slicenumbers)\n want := 55\n\n\t\tassertCorrectMessage(t, got, want)\n\t})\n}", "func sumIntArray(a []int) int {\n\tsum := 0\n\tintSize := unsafe.Sizeof(int(0))\n\tarrLen := len(a)\n\tap := (uintptr((*(*int)(unsafe.Pointer(uintptr(unsafe.Pointer(&a)))))))\n\tfor i := 0; i < arrLen; i++ {\n\t\tsum += *(*int)(unsafe.Pointer(ap + uintptr(i)*intSize))\n\t}\n\treturn sum\n}", "func Sum(xs []int) int {\n\tsum := 0\n\tfor _, x := range xs {\n\t\tsum += x\n\t}\n\treturn sum\n}", "func sum(ar []int) int {\n\tsum := 0\n\tfor i := range ar {\n\t\tsum += ar[i]\n\t}\n\treturn sum\n}", "func isSum(n int, ab []int) bool {\n i := 0\n j := len(ab) - 1\n for i <= j {\n diff := ab[i] + ab[j]\n if diff == n {\n return true\n } else if diff > n {\n j--\n } else { // diff < n\n i++\n }\n }\n return false\n}", "func maxSubArray(nums []int) int {\n\tl := len(nums)\n\tif l == 0 {\n\t\treturn 0\n\t} else if l == 1 {\n\t\treturn nums[0]\n\t}\n\tm := l / 2\n\tleft := nums[:m]\n\tright := nums[m:]\n\treturn max(maxSubArray(left), max(\n\t\tmaxSubArray(right),\n\t\tmaxSuffix(left)+maxPrefix(right),\n\t))\n}", "func calc_total_spin (spin [][]int) (total_spin int) {\n\ttotal_spin = 0\n\tfor ix:=0; ix<nx; ix++ {\n\t\tfor iy:=0; iy<ny; iy++ {\n\t\t\ttotal_spin += spin[ix][iy]\n\t\t}\n\t}\n\treturn\n}", "func sum(size int) int {\n\tnumbers := make([]int, size) // never scape sum()\n\tfor i := range numbers {\n\t\tnumbers[i] = i + 1\n\t}\n\tvar sum int\n\tfor i := range numbers {\n\t\tsum += i\n\t}\n\n\treturn sum\n}", "func findShortestSubArray(nums []int) int {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn n\n\t}\n\tfirst := make(map[int]int, n) //第一次出现当前元素的位置\n\tcount := make(map[int]int, n) //记录当前元素出现的个数\n\tmaxCount := 1\n\tminLen := n\n\tfor i, v := range nums {\n\t\tcount[v]++\n\t\tif count[v] == 1 {\n\t\t\tfirst[v] = i\n\t\t} else {\n\t\t\tl := i - first[v] + 1 //度\n\t\t\tif maxCount < count[v] || (maxCount == count[v] && minLen > l) {\n\t\t\t\tmaxCount = count[v]\n\t\t\t\tminLen = l\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(count) == n {\n\t\treturn 1\n\t}\n\treturn minLen\n}", "func SumSlices(a []int, b []int) []int {\n\tvalues := []int{}\n\n\tfor idx := 0; idx < len(a) && idx < len(b); idx++ {\n\t\tvalues = append(values, a[idx]+b[idx])\n\t}\n\n\tif len(a) > len(b) {\n\t\tvalues = append(values, a[len(b):]...)\n\t} else if len(b) > len(a) {\n\t\tvalues = append(values, b[len(a):]...)\n\t}\n\n\treturn values\n}", "func rec(nums []int, total, i int) int {\n\tct++\n\t// fmt.Printf(\"%d total %d i %d nums %v\\n\", ct, total, i, nums)\n\tif total == 0 {\n\t\tfmt.Printf(\"total 0, i %d nums %v\\n\", i, nums)\n\t\treturn 1\n\t} else if total < 0 {\n\t\t// fmt.Printf(\"%d total %d\\n\", ct, total)\n\t\treturn 0\n\t} else if i < 0 {\n\t\treturn 0\n\t} else if total < nums[i] {\n\t\t// if total < nums[i]\n\t\t// we cant find any subset add up to total, remove nums[i]\n\n\t\t// fmt.Printf(\"%d total %d nums[i] %d i %d\\n\", ct, total, nums[i], i)\n\t\treturn rec(nums, total, i-1)\n\t} else {\n\t\t//\n\t\t// fmt.Printf(\"%d total %d -nums[i] %d i %d \\n\", ct, total, nums[i], i)\n\t\treturn rec(nums, total-nums[i], i-1) + rec(nums, total, i-1)\n\t}\n}", "func sum(in []int) int {\n\tvar result int\n\tfor i := 0; i < len(in); i++ {\n\t\tresult += in[i]\n\t}\n\treturn result\n}", "func sumOfNumbers(arrayOfNumbers []int) int {\n\t// this function adds up all of the numbers in the array, using a For Each loop\n\ttotal := 0\n\n\tfor _, aSingleNumber := range arrayOfNumbers {\n\t\ttotal += aSingleNumber\n\t}\n\n\treturn total\n}", "func findUnsortedSubarray(nums []int) int {\n\tstart, end, min, max := 0, -1, math.MaxInt32, math.MinInt32\n\tfor i, j := 0, len(nums)-1; i < len(nums); i, j = i+1, j-1 {\n\t\tif nums[i] >= max {\n\t\t\tmax = nums[i]\n\t\t} else {\n\t\t\tend = i\n\t\t}\n\t\tif nums[j] <= min {\n\t\t\tmin = nums[j]\n\t\t} else {\n\t\t\tstart = j\n\t\t}\n\t}\n\treturn end - start + 1\n}", "func sumInRange(nums []int, queries [][]int) int {\n\tvar totalSum int\n\tvar prefixSums = map[int]int{}\n\tmodulo := 1000000000 + 7\n\n\t// calculates the prefix-sums\n\tfor index, num := range nums {\n\t\tif index == 0 {\n\t\t\tprefixSums[index] = num % modulo\n\t\t} else {\n\t\t\tprefixSums[index] = (prefixSums[index-1] + num) % modulo\n\t\t}\n\t}\n\n\t// Now adds up each separate range\n\tfor _, query := range queries {\n\t\tfromIndex := query[0]\n\t\ttoIndex := query[1]\n\t\ttotalSum += prefixSums[toIndex]\n\n\t\tif fromIndex != 0 {\n\t\t\ttotalSum -= prefixSums[fromIndex-1]\n\t\t}\n\t\ttotalSum %= modulo\n\t}\n\t// if totalSum is negative we just add the modulo\n\tif totalSum < 0 {\n\t\ttotalSum += modulo\n\t}\n\treturn totalSum\n}", "func calculateSum(preVal, curVal int) int {\n\tsum := 0\n\tfor i := 1; i <= rangeOfCells; i++ {\n\t\tif i == preVal {\n\t\t\tsum += curVal\n\t\t} else {\n\t\t\tsum += i\n\t\t}\n\t}\n\treturn sum\n}", "func isSumInSlice(slice []int, num int) bool {\n\tif len(slice) == 0 {\n\t\treturn false\n\t}\n\tdev := make(map[int]struct{})\n\tfor _, s := range slice {\n\t\tif _, ok := dev[s]; ok {\n\t\t\treturn true\n\t\t} else {\n\t\t\tdev[num-s] = struct{}{}\n\t\t}\n\t}\n\n\treturn false\n}", "func Sum(nums []int) int {\n\tvar total int = 0\n\tfor _, n := range nums {\n\t\ttotal += n\n\t}\n\treturn total\n}", "func findShortestSubArray(nums []int) int {\n \n}", "func popcountSliceGeneric(s []uint64) (n uint64) {\n\tcnt := uint64(0)\n\tfor _, x := range s {\n\t\tx -= (x >> 1) & 0x5555555555555555\n\t\tx = (x>>2)&0x3333333333333333 + x&0x3333333333333333\n\t\tx += x >> 4\n\t\tx &= 0x0f0f0f0f0f0f0f0f\n\t\tx *= 0x0101010101010101\n\t\tcnt += x >> 56\n\t}\n\treturn cnt\n}", "func Solution(A []int) int {\n\n\tN := len(A)\n\n\tsum := make([]int, N)\n\tsum[0] = A[0]\n\tfor i := 1; i < N; i++ {\n\t\tsum[i] = sum[i-1] + A[i]\n\t}\n\n\tif sum[N-1] >= 0 {\n\t\treturn N\n\t}\n\n\t// Now lets look for repitions in sum, basically the next position where a sum repeats\n\t// is indicative of non zero (especially for negative values)\n\tlower := make(map[int]int)\n\tupper := make(map[int]int)\n\tfor i := 0; i < N; i++ {\n\t\ts := sum[i]\n\t\t_, ok := lower[s]\n\t\tif !ok {\n\t\t\tlower[s] = i\n\t\t\tupper[s] = -1 // dummy\n\t\t} else {\n\t\t\tupper[s] = i\n\t\t}\n\t}\n\n\t// fmt.Printf(\"lower: %v\\n\", lower)\n\t// fmt.Printf(\"upper: %v\\n\", upper)\n\n\tvar sum_arr []int\n\tfor s, _ := range lower {\n\t\tsum_arr = append(sum_arr, s)\n\t}\n\n\tsort.Ints(sum_arr)\n\n\tmax_gap := 0\n\tfirst_lower := N\n\tfor i := 0; i < len(sum_arr); i++ {\n\t\ts := sum_arr[i]\n\t\tl := lower[s]\n\t\tif l < first_lower {\n\t\t\tfirst_lower = l\n\t\t\t//fmt.Printf(\"first_lower: %v\\n\", first_lower)\n\t\t}\n\n\t\tu := upper[s]\n\t\t// fmt.Printf(\"u: %v\\n\", u)\n\t\tgap := u - first_lower\n\t\tif s >= 0 {\n\t\t\t// or 0 or more the values are inclusive by 1\n\t\t\tgap++\n\t\t}\n\t\tif gap > max_gap {\n\t\t\tmax_gap = gap\n\t\t}\n\t}\n\n\treturn max_gap\n}", "func check_sum(base int, nums []int, level int) int {\n\tfor _, num := range nums {\n\t\tif level == 1 {\n\t\t\tlevel2 := level + 1\n\t\t\tbase3 := check_sum(num+base, nums, level2)\n\t\t\tif base3 != 0 {\n\t\t\t\tfmt.Printf(\"%d %d %d == 2020\\n\", base, num, base3)\n\t\t\t\tsum := base * num * base3\n\t\t\t\tfmt.Printf(\"%d == sum\\n\", sum)\n\t\t\t}\n\t\t}\n\t\tif num+base == 2020 {\n\t\t\treturn num\n\t\t}\n\t}\n\treturn 0\n}", "func sumSubvectorCloseToNumber(vector []float64, number float64) []float64 {\n\tvar size int\n\n\tif size = sv.ValidateAndReturnSize(vector); size == 0 {\n\t\treturn []float64{}\n\t}\n\n\tcumArray := u.CalculateCummulativeArray(vector)\n\tcurrentCloseNumber := sv.NewSubvector(0, 0, u.GetDistance(cumArray[0].Value, number))\n\n\tfor i := 0; i < size-1; i++ {\n\t\tcurrentNumber := cumArray[i].Value\n\n\t\t// Check i element of the cummulative array\n\t\tfromZeroToCurrent := u.GetDistance(cumArray[i].Value, number)\n\t\tif fromZeroToCurrent < currentCloseNumber.DistanceToNumber {\n\t\t\tcurrentCloseNumber = sv.NewSubvector(0, i, fromZeroToCurrent)\n\t\t}\n\n\t\tfor j := i + 1; j < size; j++ {\n\t\t\tcurrentDiff := u.GetDistance(cumArray[j].Value-currentNumber, number)\n\t\t\tif currentDiff < currentCloseNumber.DistanceToNumber {\n\t\t\t\tcurrentCloseNumber = sv.NewSubvector(i+1, j, currentDiff)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check last element of the cummulative array\n\tfromZeroToCurrent := u.GetDistance(cumArray[size-1].Value, number)\n\tif fromZeroToCurrent < currentCloseNumber.DistanceToNumber {\n\t\tcurrentCloseNumber = sv.NewSubvector(0, size-1, fromZeroToCurrent)\n\t}\n\n\treturn vector[currentCloseNumber.From : currentCloseNumber.To+1]\n}", "func maxArrayN(nums []int, sumA []int, n int) []int {\n\tnLen := len(sumA) - 1\n\tnewSum := make([]int, nLen)\n\tfor i := 0; i < nLen; i++ {\n\t\tnewSum[i] = sumA[i] + nums[i+n]\n\t}\n\tfmt.Println(newSum)\n\treturn newSum\n}", "func SumAll(numbersToSum ...[]int) (sums []int) {\n\tfor _, slice := range numbersToSum {\n\t\tsliceSum := SumSlice(slice)\n\t\tsums = append(sums, sliceSum)\n\t}\n\treturn\n}", "func sumOfDistancesInTree(N int, edges [][]int) []int {\n \n}" ]
[ "0.77158356", "0.7639435", "0.74943244", "0.73906565", "0.72541004", "0.7244827", "0.717466", "0.7166157", "0.7151122", "0.7147069", "0.6765837", "0.6695406", "0.6649781", "0.661678", "0.65642065", "0.65581495", "0.65577483", "0.653032", "0.6522212", "0.6502528", "0.64851654", "0.639998", "0.6398069", "0.6373649", "0.6372735", "0.6339627", "0.6266609", "0.62389755", "0.61697674", "0.6119356", "0.61126465", "0.6097688", "0.6096864", "0.6093372", "0.6086291", "0.6085274", "0.6044986", "0.5973993", "0.59641385", "0.5949946", "0.59474814", "0.591081", "0.5903093", "0.58911127", "0.5847268", "0.5845455", "0.58436483", "0.58357835", "0.5833212", "0.5795642", "0.5780991", "0.57467574", "0.573151", "0.57305974", "0.57236534", "0.5718353", "0.5710134", "0.57054204", "0.5678882", "0.5674749", "0.5669589", "0.56536484", "0.5641607", "0.5635175", "0.5605984", "0.5571194", "0.55393696", "0.55371517", "0.55306756", "0.55205923", "0.5511299", "0.55107045", "0.54986364", "0.5494032", "0.5492646", "0.54842174", "0.54796183", "0.54702115", "0.54617834", "0.5460907", "0.54592615", "0.54508185", "0.54433876", "0.5421412", "0.54069656", "0.5406661", "0.54031163", "0.53961015", "0.53791815", "0.5378591", "0.53408384", "0.532014", "0.5319871", "0.53139454", "0.530437", "0.5291256", "0.5280708", "0.5279448", "0.5271951", "0.5269861" ]
0.7607504
2
solution from avoid duplicated keys in case of 0 and also doubling because of jumps (no continous arrays as in my solution)
func goodSolution(nums []int, sum int) int { result := 0 sumMap := make(map[int]int) cum := 0 sumMap[0] = 1 for _, v := range nums { cum += v result += sumMap[cum-sum] sumMap[cum]++ } return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *AllOne) Inc(key string) {\n adr := this.m[key]\n if adr == nil{\n adr = &dll{k: key, v: 1}\n this.m[key] = adr\n if this.min == 0{\n this.min = 1\n this.max = 1\n this.g[1] = []*dll{adr, adr}\n return\n }\n adr.v = 0\n adr.nxt = this.g[this.min][0]\n this.g[this.min][0].prv = adr\n this.min = 1\n }else if this.g[adr.v][0] == this.g[adr.v][1]{\n if this.min == adr.v{\n this.min = adr.v + 1\n }\n delete(this.g, adr.v)\n }else if this.g[adr.v][1] == adr{\n this.g[adr.v][1] = adr.prv\n }else {\n adr.nxt.prv = adr.prv\n if this.g[adr.v][0] == adr{\n this.g[adr.v][0] = adr.nxt\n }\n if adr.prv != nil{\n adr.prv.nxt = adr.nxt\n }\n\n adr.nxt = this.g[adr.v][1].nxt\n adr.prv = this.g[adr.v][1]\n this.g[adr.v][1].nxt = adr\n if adr.nxt != nil{\n adr.nxt.prv = adr\n }\n }\n\n adr.v += 1\n if adr.v == this.max + 1{\n this.max += 1\n this.g[adr.v] = []*dll{adr, adr}\n }else if len(this.g[adr.v]) != 0{\n this.g[adr.v][0] = adr\n }else{\n this.g[adr.v] = []*dll{adr, adr}\n }\n return\n}", "func duplicateZeros1(arr []int) {\n\tvar count int\n\tn := len(arr)\n\tfor _, v := range arr {\n\t\tif v == 0 {\n\t\t\tcount++\n\t\t}\n\t}\n\n\tfor i := n - 1; i >= 0; i-- {\n\t\tif i+count >= n {\n\t\t\tif arr[i] == 0 {\n\t\t\t\tif i+count-1 < n {\n\t\t\t\t\tarr[i+count-1] = 0\n\t\t\t\t}\n\t\t\t\tcount--\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif count != 0 {\n\t\t\tarr[i+count] = arr[i]\n\t\t\tif arr[i] == 0 {\n\t\t\t\tarr[i+count-1] = 0\n\t\t\t\tcount--\n\t\t\t}\n\t\t}\n\t}\n}", "func (this *AllOne) Dec(key string) {\n if this.m[key] == nil{\n return\n }\n adr := this.m[key]\n if adr.v == 1{\n delete(this.m, key)\n if this.g[1][0] == this.g[1][1]{\n delete(this.g, 1)\n if this.max == 1{\n this.max = 0\n this.min = 0\n }else{\n this.min = adr.nxt.v\n adr.nxt.prv = nil\n }\n }else{\n if this.g[1][0] == adr{\n this.g[1][0] = adr.nxt\n }\n if this.g[1][1] == adr{\n this.g[1][1] = adr.prv\n }\n if adr.nxt != nil{\n adr.nxt.prv = adr.prv\n }\n if adr.prv != nil{\n adr.prv.nxt = adr.nxt\n }\n }\n return\n }\n\n\n if this.g[adr.v][0] == this.g[adr.v][1]{\n if this.max == adr.v{\n this.max = adr.v - 1\n }\n delete(this.g, adr.v)\n }else if this.g[adr.v][0] == adr{\n this.g[adr.v][0] = adr.nxt\n }else {\n adr.prv.nxt = adr.nxt\n if this.g[adr.v][1] == adr{\n this.g[adr.v][1] = adr.prv\n }\n if adr.nxt != nil{\n adr.nxt.prv = adr.prv\n }\n\n adr.nxt = this.g[adr.v][0]\n adr.prv = this.g[adr.v][0].prv\n this.g[adr.v][0].prv = adr\n if adr.prv != nil{\n adr.prv.nxt = adr\n }\n }\n\n adr.v -= 1\n if adr.v == this.min - 1{\n this.min -= 1\n this.g[adr.v] = []*dll{adr, adr}\n }else if len(this.g[adr.v]) != 0{\n this.g[adr.v][1] = adr\n }else{\n this.g[adr.v] = []*dll{adr, adr}\n }\n return\n}", "func Solution(A []int, K int) []int {\n lengthA := len(A)\n result := make([]int, lengthA)\n \n if K < 1 || len(A) == 0{\n return A\n }else{\n result[0] = A[lengthA-1] \n counter := 1\n //Iterate throught the original array, append to result array\n for x := 0; x < lengthA -1; x++{\n result[counter] = A[x]\n counter ++\n }\n result = Solution(result, K -1)\n \n }\n \n return result\n}", "func duplicateZerosV1(arr []int) {\n\tvar buf []int\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] == 0 && i < len(arr)-1 {\n\t\t\tbuf = make([]int, len(arr)-i-1)\n\t\t\tcopy(buf, arr[i+1:i+len(buf)])\n\t\t\tarr[i+1] = 0\n\t\t\tfor j := 0; j < len(buf)-1; j++ {\n\t\t\t\tarr[i+2+j] = buf[j]\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n}", "func Solution(X int, A []int) int {\n // write your code in Go 1.4\n bucket := make([]bool, X + 1)\n count := 0\n \n for i, n := range A {\n if (bucket[n] == false) {\n bucket[n] = true\n count++\n }\n \n if (count == X) {\n return i\n }\n\t}\n\t\n\treturn -1\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tn := len(A)\n\tsum := n * (n + 1) / 2\n\n\tisSeen := make(map[int]bool)\n\n\tfor _, el := range A {\n\t\tdup := isSeen[el]\n\t\tif dup {\n\t\t\treturn 0\n\t\t}\n\t\tisSeen[el] = true\n\t\tsum -= el\n\t}\n\tif sum != 0 {\n\t\treturn 0\n\t}\n\treturn 1\n}", "func (s *solution) SmallestUnreachable() int {\n\t// Write your code here\n\tpowerSetHelper := func (original []int) [][]int {\n\t\tpowerSetSize := int(math.Pow(2, float64(len(original))))\n\t\tresult := make([][]int, 0, powerSetSize)\n\n\t\tvar index int\n\t\tfor index < powerSetSize {\n\t\tvar subSet []int\n\n\t\tfor j, elem := range original {\n\t\tif index& (1 << uint(j)) > 0 {\n\t\tsubSet = append(subSet, elem)\n\t}\n\t}\n\t\tresult = append(result, subSet)\n\t\tindex++\n\t}\n\t\treturn result\n\t}\n\n\n\tnbills := s.GetNumBills()\n\tfmt.Println(\"number of bills\", nbills)\n\tbills := make([]int, nbills)\n\tfor i := 0; i < nbills ; i++ {\n\t\tbills[i] = s.GetBill(i)\n\t}\n\tfmt.Println(\"Bills\", bills)\n\tprice := s.GetPrice()\n\tfmt.Println(\"Price\", price)\n\tpayment := s.GetPayment()\n\tfmt.Println(\"payment\", payment)\n\tdiff := payment - price\n\tfmt.Println(\"diff\", diff)\n\n\tp := powerSetHelper(bills)\n\tmax := 0\n\tmaxIndex := -1\n\tfor i,v := range p {\n\t\tsum := 0\n\t\tfor _,b := range v {\n\t\t\tsum += b\n\t\t}\n\t\tif sum > max {\n\t\t\tmax = sum\n\t\t\tmaxIndex = i\n\t\t}\n\t}\n\tfmt.Println(p[maxIndex])\n\n\treturn diff - max\n}", "func duplicateZeros(arr []int) {\n\tif len(arr) <= 1 {\n\t\treturn\n\t}\n\t//j:=len(arr)-1\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] == 0 {\n\t\t\tfor j := len(arr) - 1; j != i; j-- {\n\t\t\t\tarr[j] = arr[j-1]\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n}", "func SubArrayWithZeroSum(input []int) {\n\t// O(n) multi-dimensional map\n\tset := map[int][]int{0: []int{-1}}\n\tsum := 0\n\tfor key, val := range input {\n\t\tsum += val\n\t\tif indexes, ok := set[sum]; ok {\n\t\t\tfor _, idx := range indexes {\n\t\t\t\tfmt.Println(idx+1, \" ... \", key)\n\t\t\t}\n\t\t}\n\t\tset[sum] = append(set[sum], key)\n\t}\n}", "func singleNumberB(nums []int) int {\n \n mp := make(map[int]int)\n result:= 0\n for _,data := range nums{\n if _,exist := mp[data]; exist{ //if element exist we remove the elemtn\n delete(mp, data)\n \n }else{\n mp[data] = data\n }\n\t}\n\t//really O(1) since there's always one element left\n for _, data := range mp{ \n result = data\n }\n return result \n}", "func coverZeros(input [][]float64) int {\n\n\treturn 0\n}", "func Solution(A []int) int {\n\n\tN := len(A)\n\n\tsum := make([]int, N)\n\tsum[0] = A[0]\n\tfor i := 1; i < N; i++ {\n\t\tsum[i] = sum[i-1] + A[i]\n\t}\n\n\tif sum[N-1] >= 0 {\n\t\treturn N\n\t}\n\n\t// Now lets look for repitions in sum, basically the next position where a sum repeats\n\t// is indicative of non zero (especially for negative values)\n\tlower := make(map[int]int)\n\tupper := make(map[int]int)\n\tfor i := 0; i < N; i++ {\n\t\ts := sum[i]\n\t\t_, ok := lower[s]\n\t\tif !ok {\n\t\t\tlower[s] = i\n\t\t\tupper[s] = -1 // dummy\n\t\t} else {\n\t\t\tupper[s] = i\n\t\t}\n\t}\n\n\t// fmt.Printf(\"lower: %v\\n\", lower)\n\t// fmt.Printf(\"upper: %v\\n\", upper)\n\n\tvar sum_arr []int\n\tfor s, _ := range lower {\n\t\tsum_arr = append(sum_arr, s)\n\t}\n\n\tsort.Ints(sum_arr)\n\n\tmax_gap := 0\n\tfirst_lower := N\n\tfor i := 0; i < len(sum_arr); i++ {\n\t\ts := sum_arr[i]\n\t\tl := lower[s]\n\t\tif l < first_lower {\n\t\t\tfirst_lower = l\n\t\t\t//fmt.Printf(\"first_lower: %v\\n\", first_lower)\n\t\t}\n\n\t\tu := upper[s]\n\t\t// fmt.Printf(\"u: %v\\n\", u)\n\t\tgap := u - first_lower\n\t\tif s >= 0 {\n\t\t\t// or 0 or more the values are inclusive by 1\n\t\t\tgap++\n\t\t}\n\t\tif gap > max_gap {\n\t\t\tmax_gap = gap\n\t\t}\n\t}\n\n\treturn max_gap\n}", "func duplicateZeros(arr []int) {\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] == 0 && i < len(arr)-1 {\n\t\t\tfor j := len(arr) - 1; j > i+1; j-- {\n\t\t\t\tarr[j] = arr[j-1]\n\t\t\t}\n\t\t\tarr[i+1] = 0\n\t\t\ti++\n\t\t}\n\t}\n}", "func duplicateZeros(arr []int) {\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] == 0 {\n\t\t\tfor j := len(arr) - 1; j > i; j-- {\n\t\t\t\tarr[j] = arr[j-1]\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n}", "func findKey(s []int) int{\n\tn := len(s)\n\tm := make(map[int]int)\n\tvar ans,temp int\n\tans = 0\n\tfor i := 0; i < n; i++ {\n\t\tfor j := i+1; j < n; j++ {\n\t\t\tif true==checkValid(s[i]^s[j]){\n\t\t\t\tm[s[i]]++\n\t\t\t\tm[s[j]]++\n\t\t\t}\n\t\t}\n\t}\n\tfor a,b := range m{\n\t\tif b>temp {\n\t\t\ttemp = b\n\t\t\tans = a\n\t\t}\n\t}\n\tif ans != 0{\n\t\treturn ans^32 \t\n\t}\n\treturn 0\n}", "func naive(mappings map[int]map[int][]mapping, data *util.QueryDocumentSet, iterations int) []float64 {\n\tN := data.Size()\n\n\titerations = gomath.MinInt(iterations, N-1)\n\n\ts := &sortable{}\n\n\ts.n = N\n\ts.nodeInfo = make([]wrapper, N)\n\n\tdead := make([]bool, N)\n\tres := make([]float64, N)\n\n\tfor iterations > 0 {\n\n\t\tfor i := 0; i < N; i++ {\n\t\t\ts.nodeInfo[i].outDegree = 0\n\t\t\ts.nodeInfo[i].inDegree = 0\n\t\t}\n\n\t\tcountDegrees(s, dead, mappings)\n\t\tbestIndex, bestRatio := findBestRatio(s)\n\n\t\tdead[bestIndex] = true\n\n\t\tres[bestIndex] = bestRatio\n\n\t\titerations--\n\t}\n\treturn res\n}", "func FourSum(seq []int, target int) [][]int {\n res := [][]int{}\n seqPairMap := map[int][]int{} // { sum1: [i1, j1, i2, j2, ...], sum2: [i3, j3, i4, j4, ...], ... }\n for i := 0; i < len(seq) - 1; i++ {\n for j := i + 1; j < len(seq); j++ {\n sum := seq[i] + seq[j]\n if _, ok := seqPairMap[sum]; !ok { seqPairMap[sum] = []int{}; }\n seqPairMap[sum] = append(seqPairMap[sum], i)\n seqPairMap[sum] = append(seqPairMap[sum], j)\n }\n }\n // example: target = 14, sums are 5 + 9, 3 + 11 (map on smaller of the two i.e. 5, 3; other is implicit)\n sumMap := map[int][][]int{} // { 5: [[i1, j1, ...],[i5, j5, ...]], ...} 5 <-- [i1, j1, ...], 9 <-- [i5, j5, ...]\n for k, _ := range seqPairMap {\n if _, ok := seqPairMap[target-k]; ok {\n if k < target - k {\n sumMap[k] = [][]int{[]int{}, []int{}}\n sumMap[k][0] = seqPairMap[k]; sumMap[k][1] = seqPairMap[target-k];\n } else {\n sumMap[target-k] = [][]int{[]int{}, []int{}}\n sumMap[target-k][0] = seqPairMap[target-k]; sumMap[target-k][1] = seqPairMap[k];\n }\n }\n }\n \n for _, indexArr := range sumMap {\n arr0 := indexArr[0]; arr1 := indexArr[1]\n for m := 0; m < len(arr0); m += 2 {\n for n := 0; n < len(arr1); n += 2 {\n // check for distinctness of arr0[m], arr0[m+1], arr1[n], arr1[n+1]\n if arr0[m] != arr1[n] && arr0[m] != arr1[n+1] &&\n arr0[m+1] != arr1[n] && arr0[m+1] != arr1[n+1] {\n // still allows some dups to go through e.g. indexes [2 5 7 10], [2 7 5 10]\n res = append(res, []int{arr0[m], arr0[m+1], arr1[n], arr1[n+1]})\n }\n }\n }\n }\n // returns arrays of indices, convert to actual values as seq[i] for each i \n return res\n}", "func FindDuplicates(input []int) int {\n\t// using XOR\n\tresult := 0\n\t//for _, val := range input {\n\t//result ^= val\n\t//}\n\t//for key, _ := range input {\n\t//result ^= key\n\t//}\n\n\t// using constant space\n\tfor _, val := range input {\n\t\tif input[val] < 0 {\n\t\t\treturn input[val]\n\t\t}\n\t\tinput[val] = input[val] * -1\n\t}\n\treturn result\n}", "func asymptotic(k int, x float64) float64 {\n\ts := 1 + 2*k\n\ta := math.Log(float64(s) * x)\n\tb := math.Log(float64(s) * a)\n\n\tba := b / a\n\tb2 := b * b\n\tb3 := b2 * b\n\tb4 := b2 * b2\n\n\tq0 := b - 2\n\tq1 := 2*b2 - 9*b + 6\n\tq2 := 3*b3 - 22*b2 + 36*b - 12\n\tq3 := 12*b4 - 125*b3 + 350*b2 - 300*b + 60\n\treturn a - b + ba*(1+1/(2*a)*(q0+1/(3*a)*(q1+1/(2*a)*(q2+1/(5*a)*q3))))\n}", "func main() {\n\tnums := []int{1, 0, -1, 0, -2, 2}\n\ttarget := 0\n\tsum := map[string]int{}\n\n\t//1st loop\n\tfor i, val1 := range nums {\n\t\t//2nd loop\n\t\tfor j, val2 := range nums {\n\t\t\tif i == j {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//3rd loop\n\t\t\tfor k, val3 := range nums {\n\t\t\t\tif i == k || j == k {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor l, val4 := range nums {\n\t\t\t\t\tif k == l || l == j || l == i {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tkeyArr := []int{val1, val2, val3, val4}\n\t\t\t\t\tsort.Ints(keyArr)\n\t\t\t\t\tkey := strconv.Itoa(keyArr[0]) + \".\" + strconv.Itoa(keyArr[1]) + \".\" + strconv.Itoa(keyArr[2]) + \".\" + strconv.Itoa(keyArr[3])\n\t\t\t\t\tsum[key] = val1 + val2 + val3 + val4\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tresult := [][]int{}\n\n\tfor k, val := range sum {\n\t\tif val == target {\n\t\t\tarr4 := strings.Split(k, \".\")\n\t\t\tsum4 := make([]int, 0, 4)\n\t\t\tfor _, v := range arr4 {\n\t\t\t\tval, _ := strconv.Atoi(v)\n\t\t\t\tsum4 = append(sum4, val)\n\t\t\t}\n\t\t\tresult = append(result, sum4)\n\t\t}\n\t}\n\n}", "func dsvdct(n int, s, e *mat.Vector, shift float64) (num int) {\n\tvar m1, m2, mx, one, ovfl, sov, sshift, ssun, sun, tmp, tom, u, unfl, zero float64\n\tvar i int\n\n\tone = 1.0\n\tzero = 0.0\n\n\t// Get machine constants\n\tunfl = 2 * golapack.Dlamch(SafeMinimum)\n\tovfl = one / unfl\n\n\t// Find largest entry\n\tmx = s.GetMag(0)\n\tfor i = 1; i <= n-1; i++ {\n\t\tmx = math.Max(mx, math.Max(s.GetMag(i), e.GetMag(i-1)))\n\t}\n\n\tif mx == zero {\n\t\tif shift < zero {\n\t\t\tnum = 0\n\t\t} else {\n\t\t\tnum = 2 * n\n\t\t}\n\t\treturn\n\t}\n\n\t// Compute scale factors as in Kahan's report\n\tsun = math.Sqrt(unfl)\n\tssun = math.Sqrt(sun)\n\tsov = math.Sqrt(ovfl)\n\ttom = ssun * sov\n\tif mx <= one {\n\t\tm1 = one / mx\n\t\tm2 = tom\n\t} else {\n\t\tm1 = one\n\t\tm2 = tom / mx\n\t}\n\n\t// Begin counting\n\tu = one\n\tnum = 0\n\tsshift = (shift * m1) * m2\n\tu = -sshift\n\tif u <= sun {\n\t\tif u <= zero {\n\t\t\tnum = num + 1\n\t\t\tif u > -sun {\n\t\t\t\tu = -sun\n\t\t\t}\n\t\t} else {\n\t\t\tu = sun\n\t\t}\n\t}\n\ttmp = (s.Get(0) * m1) * m2\n\tu = -tmp*(tmp/u) - sshift\n\tif u <= sun {\n\t\tif u <= zero {\n\t\t\tnum = num + 1\n\t\t\tif u > -sun {\n\t\t\t\tu = -sun\n\t\t\t}\n\t\t} else {\n\t\t\tu = sun\n\t\t}\n\t}\n\tfor i = 1; i <= n-1; i++ {\n\t\ttmp = (e.Get(i-1) * m1) * m2\n\t\tu = -tmp*(tmp/u) - sshift\n\t\tif u <= sun {\n\t\t\tif u <= zero {\n\t\t\t\tnum = num + 1\n\t\t\t\tif u > -sun {\n\t\t\t\t\tu = -sun\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tu = sun\n\t\t\t}\n\t\t}\n\t\ttmp = (s.Get(i) * m1) * m2\n\t\tu = -tmp*(tmp/u) - sshift\n\t\tif u <= sun {\n\t\t\tif u <= zero {\n\t\t\t\tnum = num + 1\n\t\t\t\tif u > -sun {\n\t\t\t\t\tu = -sun\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tu = sun\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func jumpHash(key uint64, numBuckets int) int32 {\n\tvar b int64 = -1\n\tvar j int64\n\n\tfor j < int64(numBuckets) {\n\t\tb = j\n\t\tkey = key*2862933555777941757 + 1\n\t\tj = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))\n\t}\n\n\treturn int32(b)\n}", "func (s *Dense) grow(w int) {\n\tswitch {\n\tcase w >= cap(s.v):\n\t\t// The current backing won't hold the new key. Reallocate.\n\t\tv := make([]uint, w)\n\t\tcopy(v, s.v)\n\t\ts.v = v\n\tcase w >= len(s.v):\n\t\t// The backing is large enough, but it's been reset. The previously\n\t\t// unused words might contain garbage from a previous use, so we need\n\t\t// to zero them.\n\t\ta := len(s.v)\n\t\ts.v = s.v[:w]\n\t\tfor a < w {\n\t\t\ts.v[a] = 0\n\t\t\ta++\n\t\t}\n\tdefault:\n\t\t// Already large enough. Do nothing.\n\t}\n}", "func subarraysDivByK(A []int, K int) int {\n cursum := 0\n mapp := make(map[int]int)\n mapp[0] = 1 // no numbers sums to 0, 1 way\n count := 0\n for i:=0; i<len(A); i++ {\n \tcursum += A[i]\n \tkey := (cursum%K+K)%K // avoid negative \n \tprev := mapp[key] // how many previous sums that mod K = cursum mod K\n \tcount += prev\n \tmapp[key] = mapp[key]+1\n }\n return count\n}", "func main() {\n\tvalues := []string{\"ABC\", \"ACB\", \"BAC\", \"BCA\", \"CAB\", \"CBA\"}\n\t// values := []string{\"to\", \"to\", \"top\", \"ton\", \"tom\"}\n\tfactor := []int{100, 10, 1}\n\n\t// 65x100 + 66x10 + 67x1 = 7227\n\thashKey := 0\n\tfor v := range values {\n\t\tbytes := []byte(values[v])\n\t\tf := 0\n\t\thashKey = 0\n\t\tfor i := range bytes {\n\t\t\tfmt.Print(bytes[i], \" \")\n\t\t\thashKey += int(bytes[i]) * factor[f]\n\t\t\tf++\n\t\t}\n\t\tfmt.Printf(\" (hashKey: %d) \\n\", hashKey)\n\t}\n}", "func Cubed() {\n\t// fmt.Println(\"# Find all possible (a, b, c, d) combination \")\n\t// fmt.Println(\" where a^3 + b^3 = c^3 + d ^ 3 | 0 < a, b, c, d < 1000\")\n\tLEN := 1000\n\n\t// Build a hashmap that have such format:\n\t// a^3 + b^3 : (a, b)\n\tbuildMap := func() map[int]Pairs {\n\t\tresult := make(map[int]Pairs)\n\n\t\tfor i := 1; i <= LEN; i++ {\n\t\t\tfor j := 1; j <= LEN; j++ {\n\n\t\t\t\tp := MyPair{i, j}\n\n\t\t\t\tkey := cube(i) + cube(j)\n\t\t\t\tnotExisted := !includesPair(result[key], &p)\n\n\t\t\t\tif notExisted {\n\t\t\t\t\tif result[key] != nil {\n\t\t\t\t\t\tresult[key] = append(result[key], &p)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult[key] = Pairs{&p}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Delete the field only have one items\n\t\tfor key, pairs := range result {\n\t\t\tif len(pairs) == 1 {\n\t\t\t\tdelete(result, key)\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\tdict := buildMap()\n\tfailed := false\n\n\t// if pairs, ok := dict[1729]; ok {\n\t// \tfmt.Println(\"1729:\")\n\t// \tfor _, p := range pairs {\n\t// \t\tfmt.Println(p.toString())\n\t// \t}\n\t// }\n\n\tfor key, pairs := range dict {\n\t\tspecial := \"\"\n\t\tif len(pairs) > 2 {\n\t\t\tspecial = \"(special case)\"\n\t\t}\n\t\tfmt.Printf(\"%d %v: \", key, special)\n\t\tfor _, p := range pairs {\n\t\t\tif p.cubify() != key {\n\t\t\t\tfailed = true\n\t\t\t}\n\t\t\tfmt.Printf(\"%v, \", p.toString())\n\t\t}\n\t\tfmt.Println(\"\")\n\t}\n\n\tif !failed {\n\t\tfmt.Println(\"Pass !!\")\n\t}\n\tfmt.Println(\"end of process\")\n}", "func find3Sum(nums []int){\n lenS := len(nums)\n fmt.Println(lenS)\n fmt.Println(nums[0: lenS-2])\n sort.Ints(nums)\n fmt.Println(nums)\n numsMap := make(map[int]int)\n var res [] int\n for i,v := range nums[0: lenS-2] {\n if i >= 1 && nums[i] == nums[i-1] {\n continue\n }\n for _,x := range nums[i: lenS] {\n _, ok := numsMap[x]\n if ok {\n res = append(res, v)\n res = append(res, x)\n res = append(res, -v-x)\n } else {\n numsMap[-x-v] = 1\n }\n }\n }\n\n}", "func Compute_n_glength(kmer int, pr float64, gsm map[string]int, length map[string]int) (map[string]int){\n n := make(map[string]int)\n \n for k := range gsm {\n temp := int(Round((pr*float64(length[k]))/float64(kmer), 0.5, 0))\n //temp := int(Round((pr*gsm[k]), 0.5, 0))\n if (temp == 0){\n n[k] = 1\n }else{\n n[k] = int(math.Min(float64(temp), float64(gsm[k])))/2\n }\n //fmt.Println(k, n[k])\n }\n \n\n return n\n}", "func updateMatrix(matrix [][]int) [][]int {\n if len(matrix) == 0 {\n return matrix\n }\n\n q := [][]int{}\n\n push := func(x,y int) {\n q = append(q,[]int{x,y})\n }\n\n pull := func() (int,int) {\n if len(q) == 0 {\n return -1,-1\n }\n\n out := q[0]\n q = q[1:]\n return out[0],out[1]\n }\n\n out := make([][]int,len(matrix))\n for i := range matrix {\n out[i] = make([]int,len(matrix[i]))\n for j := range matrix[i] {\n if matrix[i][j] == 0 {\n out[i][j] = 0\n push(i,j)\n } else {\n out[i][j] = -1\n }\n }\n }\n\n for len(q) > 0 {\n i,j := pull()\n if i + 1 < len(out) && out[i+1][j] == -1 {\n out[i+1][j] = out[i][j] + 1\n push(i+1,j)\n }\n if i > 0 && out[i-1][j] == -1 {\n out[i-1][j] = out[i][j] + 1\n push(i-1,j)\n }\n if j + 1 < len(out[i]) && out[i][j+1] == -1 {\n out[i][j+1] = out[i][j] + 1\n push(i,j+1)\n }\n if j > 0 && out[i][j-1] == -1 {\n out[i][j-1] = out[i][j] + 1\n push(i,j-1)\n }\n }\n\n return out\n}", "func siftDown(kvs []_MapPair, lo, hi, first int) {\n root := lo\n for {\n child := 2*root + 1\n if child >= hi {\n break\n }\n if child+1 < hi && kvs[first+child].k < kvs[first+child+1].k {\n child++\n }\n if kvs[first+root].k >= kvs[first+child].k {\n return\n }\n swap(kvs, first+root, first+child)\n root = child\n }\n}", "func cutTheSticks(arr []int32) []int32 {\n s := make(map[int32]int32)\n var max int32 = 0\n n := int32(len(arr))\n for _, v := range arr {\n if v > max { max = v }\n s[v]++\n }\n arr = nil\n for max > 0 {\n var min int32 = 0\n arr = append(arr,n)\n for i := int32(0); min == 0 && i <= max; i++ {\n if s[i] > 0 {\n min = i\n n -= s[min]\n s[min] = 0\n }\n }\n for j := min + 1; j <= max; j++ {\n s[j-min] = s[j]\n }\n max -= min\n }\n return arr\n}", "func setZeroes(matrix [][]int) {\n\t// 20200819\n\t// 1、全部复制\n\t// O(M*N)\n\t// 不需要用visitor数组,直接在原数组设置\n\t/*if len(matrix) == 0 || len(matrix[0]) == 0 {\n\t\treturn\n\t}\n\tm := len(matrix)\n\tn := len(matrix[0])\n\tvisited := make([][]bool, m)\n\tfor i := range visited {\n\t\tvisited[i] = make([]bool, n)\n\t}\n\tfor i:=0;i<m;i++{\n\t\tfor j:=0;j<n;j++{\n\t\t\tif !visited[i][j] && matrix[i][j] == 0 {\n\t\t\t\tfor p := 0; p<n;p++ {\n\t\t\t\t\tif !visited[i][p] {\n\t\t\t\t\t\tmatrix[i][p] = 0\n\t\t\t\t\t\tvisited[i][p] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor p := 0; p<m;p++ {\n\t\t\t\t\tif !visited[p][j] {\n\t\t\t\t\t\tmatrix[p][j] = 0\n\t\t\t\t\t\tvisited[p][j] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//visited[i][j] = true\n\t\t}\n\t}\n\tfmt.Println(matrix)*/\n\t// https://leetcode-cn.com/problems/set-matrix-zeroes/solution/ju-zhen-zhi-ling-by-leetcode/\n\t// 1、两次扫描,额外空间,用set\n\t// O(M*N)/O(M+N)\n\t// 执行耗时:16 ms,击败了70.23% 的Go用户\n\t// 内存消耗:6 MB,击败了42.53% 的Go用户\n\t// 本题算法不需要,工程化最好加上\n\t//if len(matrix) == 0 || len(matrix[0]) == 0 {\n\t//\treturn\n\t//}\n\t/*m := len(matrix)\n\tn := len(matrix[0])\n\trows := map[int]bool{}\n\tcols := map[int]bool{}\n\tfor i:=0;i<m;i++{\n\t\tfor j:=0;j<n;j++{\n\t\t\tif matrix[i][j] == 0 {\n\t\t\t\trows[i] = true\n\t\t\t\tcols[j] = true\n\t\t\t}\n\t\t}\n\t}\n\tfor i:=0;i<m;i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tif rows[i] || cols[j] {\n\t\t\t\tmatrix[i][j] = 0\n\t\t\t}\n\t\t}\n\t}*/\n\t// 3、O(1)空间复杂度+暴力\n\t// O((MxN)x(M+N))/O(1)\n\t// 执行耗时:24 ms,击败了7.36% 的Go用户\n\t// 内存消耗:6 MB,击败了13.79% 的Go用户\n\t/*FLAG := math.MinInt64\n\tm := len(matrix)\n\tn := len(matrix[0])\n\tfor i:=0;i<m;i++{\n\t\tfor j:=0;j<n;j++{\n\t\t\tif matrix[i][j] == 0{\n\t\t\t\tfor k :=0;k<m;k++{\n\t\t\t\t\tif matrix[k][j] != 0{\n\t\t\t\t\t\tmatrix[k][j] = FLAG\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor k :=0;k<n;k++{\n\t\t\t\t\tif matrix[i][k] != 0 {\n\t\t\t\t\t\tmatrix[i][k] = FLAG\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i:=0;i<m;i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tif matrix[i][j] == FLAG {\n\t\t\t\tmatrix[i][j] = 0\n\t\t\t}\n\t\t}\n\t}*/\n\t// 3、只将每行和每列的第一个元素赋值为0\n\t// O(MxN)/O(1)\n\t// 执行耗时:20 ms,击败了15.72% 的Go用户\n\t// 内存消耗:6.1 MB,击败了5.75% 的Go用户\n\tm := len(matrix)\n\tn := len(matrix[0])\n\tisCol := false\n\tfor i := 0; i < m; i++ {\n\t\tif matrix[i][0] == 0 {\n\t\t\tisCol = true\n\t\t}\n\t\tfor j := 1; j < n; j++ {\n\t\t\tif matrix[i][j] == 0 {\n\t\t\t\tmatrix[0][j] = 0\n\t\t\t\tmatrix[i][0] = 0\n\t\t\t}\n\t\t}\n\t}\n\tfor i := 1; i < m; i++ {\n\t\tfor j := 1; j < n; j++ {\n\t\t\tif matrix[i][0] == 0 || matrix[0][j] == 0 {\n\t\t\t\tmatrix[i][j] = 0\n\t\t\t}\n\t\t}\n\t}\n\tif matrix[0][0] == 0 {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tmatrix[0][j] = 0\n\t\t}\n\t}\n\tif isCol {\n\t\tfor i := 0; i < m; i++ {\n\t\t\tmatrix[i][0] = 0\n\t\t}\n\t}\n\tfmt.Println(matrix)\n}", "func Same(arr1, arr2 []int) bool {\n\tif len(arr1) != len(arr2) {\n\t\treturn false\n\t}\n\tm1 := map[int]int{}\n\tm2 := map[int]int{}\n\tfor _, v := range arr1 {\n\t\tif _, ok := m1[v]; !ok {\n\t\t\tm1[v] = 1\n\t\t} else {\n\t\t\tm1[v] = m1[v] + 1\n\t\t}\n\t}\n\tfor _, v := range arr2 {\n\t\tif _, ok := m2[v]; !ok {\n\t\t\tm2[v] = 1\n\t\t} else {\n\t\t\tm2[v] = m2[v] + 1\n\t\t}\n\t}\n\n\t// fmt.Printf(\"a1:%#v\", m1)\n\t// fmt.Printf(\"a2:%#v\", m2)\n\n\tfor elem, elemFreq := range m1 {\n\t\t// sqrElemt, okt := m2[int(math.Pow(float64(elem), 2.0))]\n\t\t// fmt.Println(sqrElemt, okt)\n\t\t// fmt.Println(m2[int(math.Pow(float64(elem), 2.0))])\n\t\tif sqrElemFreq, ok := m2[int(math.Pow(float64(elem), 2.0))]; ok {\n\t\t\t// fmt.Println(\"\\n\", sqrElem, ok)\n\t\t\t// fmt.Println(\"\\n\", elem, elemFreq, sqrElem, m2[sqrElem], int(math.Pow(float64(elem), 2.0)))\n\t\t\tif sqrElemFreq != elemFreq {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Array_find_element_occur_more_nby2_unsorted_01(arr []int) string {\n\n\tdic := make(map[int]int)\n\n\tfor _, e := range arr {\n\t\tdic[e]++\n\t}\n\n\tfor k, v := range dic {\n\t\tif v >= len(arr)/2 {\n\t\t\treturn strconv.Itoa(k)\n\t\t}\n\t}\n\treturn \"NaN\"\n}", "func Solution(C []int, k int) int {\n\tn := len(C) + 1\n\tdp := make([][]int, n)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, k+1)\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tdp[i][0] = 0\n\t}\n\n\tfor i := 1; i <= k; i++ {\n\t\tdp[0][i] = math.MaxInt64\n\t}\n\n\tfor i := 1; i < n; i++ {\n\t\tfor j := 1; j <= k; j++ {\n\t\t\tCmax := C[0]\n\t\t\tfor idx := 0; idx < i; idx++ {\n\t\t\t\tif C[idx] > j {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tCmax = C[idx]\n\t\t\t}\n\n\t\t\tdpij1 := dp[i][j-Cmax] + 1\n\t\t\tdpij2 := dp[i-1][j]\n\t\t\tif dpij1 <= dpij2 {\n\t\t\t\tdp[i][j] = dpij1\n\t\t\t} else {\n\t\t\t\tdp[i][j] = dpij2\n\t\t\t}\n\t\t}\n\t}\n\n\t//printDp(dp)\n\n\treturn dp[n-1][k]\n}", "func findJudge(N int, trust [][]int) int {\n if N == 1 && len(trust) == 0 {\n return 1\n }\n if len(trust) == 0 {\n return -1\n }\n m := make(map[int]int)\n for _, row := range trust {\n m[row[1]]++\n m[row[0]]--\n }\n for key, value := range m {\n if value == N-1 {\n return key\n }\n }\n return -1\n}", "func Dchkbl(t *testing.T) {\n\tvar rmax, sfmin, temp, vmax, zero float64\n\tvar _i, i, ihi, ihiin, ilo, iloin, info, j, knt, n, ninfo int\n\tvar err error\n\n\t// dummy := vf(1)\n\tscale := vf(20)\n\tscalin := vf(20)\n\tlmax := make([]int, 3)\n\ta := mf(20, 20, opts)\n\tain := mf(20, 20, opts)\n\n\tzero = 0.0\n\n\talenlist := []int{5, 5, 5, 4, 6, 5, 4, 4, 5, 6, 7, 5, 6}\n\talist := [][]float64{\n\t\t{\n\t\t\t0.1000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.2000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.3000e+01, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.4000e+01, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.5000e+01,\n\t\t},\n\t\t{\n\t\t\t0.1000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.1000e+01, 0.2000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.1000e+01, 0.2000e+01, 0.3000e+01, 0.0000e+00, 0.0000e+00,\n\t\t\t0.1000e+01, 0.2000e+01, 0.3000e+01, 0.4000e+01, 0.0000e+00,\n\t\t\t0.1000e+01, 0.2000e+01, 0.3000e+01, 0.4000e+01, 0.5000e+01,\n\t\t},\n\t\t{\n\t\t\t0.1000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.1000e+01, 0.1000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.1000e+01, 0.1000e+01, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.1000e+01, 0.1000e+01, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.1000e+01, 0.1000e+01,\n\t\t},\n\t\t{\n\t\t\t0.0000e+00, 0.2000e+01, 0.1000e+00, 0.0000e+00,\n\t\t\t0.2000e+01, 0.0000e+00, 0.0000e+00, 0.1000e+00,\n\t\t\t0.1000e+03, 0.0000e+00, 0.0000e+00, 0.2000e+01,\n\t\t\t0.0000e+00, 0.1000e+03, 0.2000e+01, 0.0000e+00,\n\t\t},\n\t\t{\n\t\t\t0.2000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.1024e+04,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.1280e+03,\n\t\t\t0.0000e+00, 0.2000e+01, 0.3000e+04, 0.0000e+00, 0.0000e+00, 0.2000e+01,\n\t\t\t0.1280e+03, 0.4000e+01, 0.4000e-02, 0.5000e+01, 0.6000e+03, 0.8000e+01,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.2000e-02, 0.2000e+01,\n\t\t\t0.8000e+01, 0.8192e+04, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.2000e+01,\n\t\t},\n\t\t{\n\t\t\t0.1000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.8000e+01,\n\t\t\t0.0000e+00, 0.2000e+01, 0.8192e+04, 0.2000e+01, 0.4000e+01,\n\t\t\t0.2500e-03, 0.1250e-03, 0.4000e+01, 0.0000e+00, 0.6400e+02,\n\t\t\t0.0000e+00, 0.2000e+01, 0.1024e+04, 0.4000e+01, 0.8000e+01,\n\t\t\t0.0000e+00, 0.8192e+04, 0.0000e+00, 0.0000e+00, 0.8000e+01,\n\t\t},\n\t\t{\n\t\t\t0.1000e+01, 0.1000e+07, 0.1000e+07, 0.1000e+07,\n\t\t\t-0.2000e+07, 0.3000e+01, 0.2000e-05, 0.3000e-05,\n\t\t\t-0.3000e+07, 0.0000e+00, 0.1000e-05, 0.2000e+01,\n\t\t\t0.1000e+07, 0.0000e+00, 0.3000e-05, 0.4000e+07,\n\t\t},\n\t\t{\n\t\t\t0.1000e+01, 0.1000e+05, 0.1000e+05, 0.1000e+05,\n\t\t\t-0.2000e+05, 0.3000e+01, 0.2000e-02, 0.3000e-02,\n\t\t\t0.0000e+00, 0.2000e+01, 0.0000e+00, -0.3000e+05,\n\t\t\t0.0000e+00, 0.0000e+00, 0.1000e+05, 0.0000e+00,\n\t\t},\n\t\t{\n\t\t\t0.1000e+01, 0.5120e+03, 0.4096e+04, 3.2768e+04, 2.62144e+05,\n\t\t\t0.8000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.8000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.8000e+01, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.8000e+01, 0.0000e+00,\n\t\t},\n\t\t{\n\t\t\t0.1000e+01, 0.1000e+01, 0.0000e+00, 0.1000e+01, 0.1000e+01, 0.1000e+01,\n\t\t\t0.1000e+01, 0.1000e+01, 0.0000e+00, 0.1000e+01, 0.1000e+01, 0.1000e+01,\n\t\t\t0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.1000e+01, 0.0000e+00, 0.0000e+00,\n\t\t\t0.1000e+01, 0.1000e+01, 0.0000e+00, 0.1000e+01, 0.1000e+01, 0.1000e+01,\n\t\t\t0.1000e+01, 0.1000e+01, 0.0000e+00, 0.1000e+01, 0.1000e+01, 0.1000e+01,\n\t\t},\n\t\t{\n\t\t\t0.6000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.1000e+01, 0.0000e+00,\n\t\t\t0.0000e+00, 0.4000e+01, 0.0000e+00, 0.2500e-03, 0.1250e-01, 0.2000e-01, 0.1250e+00,\n\t\t\t0.1000e+01, 0.1280e+03, 0.6400e+02, 0.0000e+00, 0.0000e+00, -0.2000e+01, 0.1600e+02,\n\t\t\t0.0000e+00, 1.6384e+04, 0.0000e+00, 0.1000e+01, -0.4000e+03, 0.2560e+03, -0.4000e+04,\n\t\t\t-0.2000e+01, -0.2560e+03, 0.0000e+00, 0.1250e-01, 0.2000e+01, 0.2000e+01, 0.3200e+02,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.8000e+01, 0.0000e+00, 0.4000e-02, 0.1250e+00, -0.2000e+00, 0.3000e+01,\n\t\t},\n\t\t{\n\t\t\t0.1000e+04, 0.2000e+01, 0.3000e+01, 0.4000e+01, 0.5000e+06,\n\t\t\t0.9000e+01, 0.0000e+00, 0.2000e-03, 0.1000e+01, 0.3000e+01,\n\t\t\t0.0000e+00, -0.3000e+03, 0.2000e+01, 0.1000e+01, 0.1000e+01,\n\t\t\t0.9000e+01, 0.2000e-02, 0.1000e+01, 0.1000e+01, -0.1000e+04,\n\t\t\t0.6000e+01, 0.2000e+03, 0.1000e+01, 0.6000e+03, 0.3000e+01,\n\t\t},\n\t\t{\n\t\t\t1.0000e+00, 1.0000e+120, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t1.0000e-120, 1.0000e+00, 1.0000e+120, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 1.0000e-120, 1.0000e+00, 1.0000e+120, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 1.0000e-120, 1.0000e+00, 1.0000e+120, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 1.0000e-120, 1.0000e+00, 1.0000e+120,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 1.0000e-120, 1.0000e+00,\n\t\t},\n\t}\n\tilolist := []int{1, 1, 1, 1, 4, 1, 1, 1, 1, 2, 2, 1, 1}\n\tihilist := []int{1, 1, 1, 4, 6, 5, 4, 4, 5, 5, 5, 5, 6}\n\tainlist := [][]float64{\n\t\t{\n\t\t\t0.1000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.2000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.3000e+01, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.4000e+01, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.5000e+01,\n\t\t},\n\t\t{\n\t\t\t0.5000e+01, 0.4000e+01, 0.3000e+01, 0.2000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.4000e+01, 0.3000e+01, 0.2000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.0000e+00, 0.3000e+01, 0.2000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.2000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.1000e+01,\n\t\t},\n\t\t{\n\t\t\t0.1000e+01, 0.1000e+01, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.1000e+01, 0.1000e+01, 0.0000e+00, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.1000e+01, 0.1000e+01, 0.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.1000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.1000e+01,\n\t\t},\n\t\t{\n\t\t\t0.0000e-03, 2.0000e+00, 3.2000e+00, 0.0000e-03,\n\t\t\t2.0000e+00, 0.0000e-03, 0.0000e-03, 3.2000e+00,\n\t\t\t3.1250e+00, 0.0000e-03, 0.0000e-03, 2.0000e+00,\n\t\t\t0.0000e-03, 3.1250e+00, 2.0000e+00, 0.0000e-03,\n\t\t},\n\t\t{\n\t\t\t0.5000e+01, 0.4000e-02, 0.6000e+03, 0.1024e+04, 0.5000e+00, 0.8000e+01,\n\t\t\t0.0000e+00, 0.3000e+04, 0.0000e+00, 0.0000e+00, 0.2500e+00, 0.2000e+01,\n\t\t\t0.0000e+00, 0.0000e+00, 0.2000e-02, 0.0000e+00, 0.0000e+00, 0.2000e+01,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.2000e+01, 0.0000e+00, 0.1280e+03,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.1024e+04,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.6400e+02, 0.1024e+04, 0.2000e+01,\n\t\t},\n\t\t{\n\t\t\t1.0000e+00, 0.0000e-03, 0.0000e-03, 0.0000e-03, 2.0000e+00,\n\t\t\t0.0000e-03, 2.0000e+00, 1.0240e+03, 16.0000e+00, 16.0000e+00,\n\t\t\t3.2000e-02, 1.0000e-03, 4.0000e+00, 0.0000e-03, 2.0480e+03,\n\t\t\t0.0000e-03, 250.0000e-03, 16.0000e+00, 4.0000e+00, 4.0000e+00,\n\t\t\t0.0000e-03, 2.0480e+03, 0.0000e-03, 0.0000e-03, 8.0000e+00,\n\t\t},\n\t\t{\n\t\t\t1.0000e+00, 1.0000e+06, 2.0000e+06, 1.0000e+06,\n\t\t\t-2.0000e+06, 3.0000e+00, 4.0000e-06, 3.0000e-06,\n\t\t\t-1.5000e+06, 0.0000e-03, 1.0000e-06, 1.0000e+00,\n\t\t\t1.0000e+06, 0.0000e-03, 6.0000e-06, 4.0000e+06,\n\t\t},\n\t\t{\n\t\t\t1.0000e+00, 10.0000e+03, 10.0000e+03, 5.0000e+03,\n\t\t\t-20.0000e+03, 3.0000e+00, 2.0000e-03, 1.5000e-03,\n\t\t\t0.0000e-03, 2.0000e+00, 0.0000e-03, -15.0000e+03,\n\t\t\t0.0000e-03, 0.0000e-03, 20.0000e+03, 0.0000e-03,\n\t\t},\n\t\t{\n\t\t\t1.0000e+00, 32.0000e+00, 32.0000e+00, 32.0000e+000, 32.0000e+00,\n\t\t\t128.0000e+00, 0.0000e-03, 0.0000e-03, 0.0000e-003, 0.0000e-03,\n\t\t\t0.0000e-03, 64.0000e+00, 0.0000e-03, 0.0000e-003, 0.0000e-03,\n\t\t\t0.0000e-03, 0.0000e-03, 64.0000e+00, 0.0000e-003, 0.0000e-03,\n\t\t\t0.0000e-03, 0.0000e-03, 0.0000e-03, 64.0000e+000, 0.0000e-03,\n\t\t},\n\t\t{\n\t\t\t0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01,\n\t\t\t0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.1000e+01,\n\t\t},\n\t\t{\n\t\t\t6.4000e+01, 1.0000e+00, 5.00000e-01, 0.0000e+00, 0.0000e+00, 1.0000e+00, -2.0000e+00,\n\t\t\t0.0000e+00, 4.0000e+00, 5.00000e-01, 1.0240e+00, 8.0000e-01, 0.0000e+00, 2.5600e+00,\n\t\t\t0.0000e+00, 2.0000e+00, 3.00000e+00, 4.0960e+00, 2.0000e+00, 0.0000e+00, -6.4000e+00,\n\t\t\t0.0000e+00, 4.0000e+00, -3.90625e+00, 1.0000e+00, -6.2500e+00, 0.0000e+00, 8.0000e+00,\n\t\t\t0.0000e+00, -4.0000e+00, 2.00000e+00, 8.0000e-01, 2.0000e+00, -4.0000e+00, 4.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.00000e+00, 0.0000e+00, 0.0000e+00, 6.0000e+00, 1.0000e+00,\n\t\t\t0.0000e+00, 0.0000e+00, 0.00000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00,\n\t\t},\n\t\t{\n\t\t\t1.0000e+03, 3.1250e-02, 3.7500e-01, 3.1250e-02, 1.95312500e+03,\n\t\t\t5.7600e+02, 0.0000e+00, 1.6000e-03, 5.0000e-01, 7.50000000e-01,\n\t\t\t0.0000e+00, -3.7500e+01, 2.0000e+00, 6.2500e-02, 3.12500000e-02,\n\t\t\t1.1520e+03, 4.0000e-03, 1.6000e+01, 1.0000e+00, -5.00000000e+02,\n\t\t\t1.5360e+03, 8.0000e+02, 3.2000e+01, 1.2000e+03, 3.00000000e+00,\n\t\t},\n\t\t{\n\t\t\t0.10000000000000000000e+01, 0.63448545932891229313e+04, 0.00000000000000000000e+00, 0.00000000000000000000e+00, 0.00000000000000000000e+00, 0.00000000000000000000e+00,\n\t\t\t0.15760802478557791348e-03, 0.10000000000000000000e+01, 0.63448545932891229313e+04, 0.00000000000000000000e+00, 0.00000000000000000000e+00, 0.00000000000000000000e+00,\n\t\t\t0.00000000000000000000e+00, 0.15760802478557791348e-03, 0.10000000000000000000e+01, 0.31724272966445614657e+04, 0.00000000000000000000e+00, 0.00000000000000000000e+00,\n\t\t\t0.00000000000000000000e+00, 0.00000000000000000000e+00, 0.31521604957115582695e-03, 0.10000000000000000000e+01, 0.15862136483222807328e+04, 0.00000000000000000000e+00,\n\t\t\t0.00000000000000000000e+00, 0.00000000000000000000e+00, 0.00000000000000000000e+00, 0.63043209914231165391e-03, 0.10000000000000000000e+01, 0.79310682416114036641e+03,\n\t\t\t0.00000000000000000000e+00, 0.00000000000000000000e+00, 0.00000000000000000000e+00, 0.00000000000000000000e+00, 0.12608641982846233078e-02, 0.10000000000000000000e+01,\n\t\t},\n\t}\n\tscalelist := [][]float64{\n\t\t{0.1000e+01, 0.2000e+01, 0.3000e+01, 0.4000e+01, 0.5000e+01},\n\t\t{0.1000e+01, 0.2000e+01, 0.3000e+01, 0.2000e+01, 0.1000e+01},\n\t\t{0.1000e+01, 0.2000e+01, 0.3000e+01, 0.2000e+01, 0.1000e+01},\n\t\t{62.5000e-03, 62.5000e-03, 2.0000e+00, 2.0000e+00},\n\t\t{0.4000e+01, 0.3000e+01, 0.5000e+01, 0.8000e+01, 0.1250e+00, 0.1000e+01},\n\t\t{8.0000e+00, 500.0000e-03, 62.5000e-03, 4.0000e+00, 2.0000e+00},\n\t\t{1.0000e+00, 1.0000e+00, 2.0000e+00, 1.0000e+00},\n\t\t{1.0000e+00, 1.0000e+00, 1.0000e+00, 500.0000e-03},\n\t\t{256.0000e+00, 16.0000e+00, 2.0000e+00, 250.0000e-03, 31.2500e-03},\n\t\t{0.3000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.1000e+01, 0.4000e+01},\n\t\t{3.0000e+00, 7.812500e-03, 3.1250e-02, 3.2000e+01, 5.0000e-01, 1.0000e+00, 6.0000e+00},\n\t\t{3.2000e+01, 5.0000e-01, 4.0000e+00, 2.5000e-01, 1.2500e-01},\n\t\t{2.494800386918399765e+291, 1.582914569427869018e+175, 1.004336277661868922e+59, 3.186183822264904554e-58, 5.053968264940243633e-175, 0.40083367200179455560e-291},\n\t}\n\n\tlmax[0] = 0\n\tlmax[1] = 0\n\tlmax[2] = 0\n\tninfo = 0\n\tknt = 0\n\trmax = zero\n\tvmax = zero\n\tsfmin = golapack.Dlamch(SafeMinimum)\n\t// meps = golapack.Dlamch(Epsilon)\n\n\tfor _i, n = range alenlist {\n\t\tfor i = 1; i <= n; i++ {\n\t\t\tfor j = 1; j <= n; j++ {\n\t\t\t\ta.Set(i-1, j-1, alist[_i][(i-1)*(n)+j-1])\n\t\t\t}\n\t\t}\n\n\t\tiloin = ilolist[_i]\n\t\tihiin = ihilist[_i]\n\t\tfor i = 1; i <= n; i++ {\n\t\t\tfor j = 1; j <= n; j++ {\n\t\t\t\tain.Set(i-1, j-1, ainlist[_i][(i-1)*(n)+j-1])\n\t\t\t}\n\t\t}\n\t\tfor i = 1; i <= n; i++ {\n\t\t\tscalin.Set(i-1, scalelist[_i][i-1])\n\t\t}\n\n\t\t// anorm = Dlange('M', &n, &n, a, &lda, dummy)\n\t\tknt = knt + 1\n\n\t\tif ilo, ihi, err = golapack.Dgebal('B', n, a, scale); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif info != 0 {\n\t\t\tt.Fail()\n\t\t\tninfo = ninfo + 1\n\t\t\tlmax[0] = knt\n\t\t}\n\n\t\tif ilo != iloin || ihi != ihiin {\n\t\t\tt.Fail()\n\t\t\tninfo = ninfo + 1\n\t\t\tlmax[1] = knt\n\t\t}\n\n\t\tfor i = 1; i <= n; i++ {\n\t\t\tfor j = 1; j <= n; j++ {\n\t\t\t\ttemp = math.Max(a.Get(i-1, j-1), ain.Get(i-1, j-1))\n\t\t\t\ttemp = math.Max(temp, sfmin)\n\t\t\t\tvmax = math.Max(vmax, math.Abs(a.Get(i-1, j-1)-ain.Get(i-1, j-1))/temp)\n\t\t\t}\n\t\t}\n\n\t\tfor i = 1; i <= n; i++ {\n\t\t\ttemp = math.Max(scale.Get(i-1), scalin.Get(i-1))\n\t\t\ttemp = math.Max(temp, sfmin)\n\t\t\tvmax = math.Max(vmax, math.Abs(scale.Get(i-1)-scalin.Get(i-1))/temp)\n\t\t}\n\n\t\tif vmax > rmax {\n\t\t\tlmax[2] = knt\n\t\t\trmax = vmax\n\t\t}\n\n\t}\n\n\tfmt.Printf(\" .. test output of dgebal .. \\n\")\n\n\tfmt.Printf(\"\\tvalue of largest test error = %12.3E\\n\", rmax)\n\tfmt.Printf(\"\\texample number where info is not zero = %4d\\n\", lmax[0])\n\tfmt.Printf(\"\\texample number where ilo or ihi wrong = %4d\\n\", lmax[1])\n\tfmt.Printf(\"\\texample number having largest error = %4d\\n\", lmax[2])\n\tfmt.Printf(\"\\tnumber of examples where info is not 0 = %4d\\n\", ninfo)\n\tfmt.Printf(\"\\ttotal number of examples tested = %4d\\n\", knt)\n}", "func solveB(input []int) int {\n\t// We found a loop if we found the first occurrence of this first pattern.\n\tfirst := fmt.Sprintf(\"%v\", input)\n\tfor n := 0; ; n++ {\n\t\tredistribute(input)\n\t\tkey := fmt.Sprintf(\"%v\", input)\n\t\tif key == first {\n\t\t\treturn n + 1\n\t\t}\n\t}\n}", "func Solution(K int, A []int) int {\n\t// write your code in Go 1.4\n\tresult := 0\n\ttie := 0\n\tfor _, a := range A {\n\t\ttie = tie + a\n\t\tif tie >= K {\n\t\t\tresult++\n\t\t\ttie = 0\n\t\t}\n\t}\n\treturn result\n}", "func getLongestIncrease(arr []int) (int, []int) {\n\tvar size = len(arr)\n\tvar current, saved []int\n\tvar noIncrease = true\n\n\t// fmt.Printf(\"\\narr(%v)=%+v\\n\", len(arr), arr)\n\tu.Debug(\"\\narr(%v)=%+v\\n\", len(arr), arr)\n\tfor m := 0; m < size-1; m++ {\n\t\tfor i := m; i < size-1; i++ {\n\t\t\tfor j := i + 1; j < size && (size-j) >= len(saved); j++ {\n\t\t\t\tvar opt = arr[i]\n\t\t\t\tvar previous = opt\n\t\t\t\tcurrent = []int{previous}\n\t\t\t\tfor k := j; k < size; k++ {\n\t\t\t\t\tif arr[k] > previous {\n\t\t\t\t\t\topt = previous\n\t\t\t\t\t\tprevious = arr[k]\n\t\t\t\t\t\tcurrent = append(current, previous)\n\t\t\t\t\t\tnoIncrease = false\n\t\t\t\t\t} else if arr[k] > opt {\n\t\t\t\t\t\tprevious = arr[k]\n\t\t\t\t\t\tcurrent[len(current)-1] = previous\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// fmt.Printf(\"m=%v, i=%v, j=%v, current(%v)=%+v, saved(%v)=%+v\\n\", m, i, j, len(current), current, len(saved), saved)\n\t\t\t\tu.Debug(\"m=%v, i=%v, j=%v, current(%v)=%+v, saved(%v)=%+v\\n\", m, i, j, len(current), current, len(saved), saved)\n\t\t\t\tif len(current) > len(saved) {\n\t\t\t\t\tsaved = current\n\t\t\t\t}\n\t\t\t\t// never true but proves how condition should work in `for j` loop\n\t\t\t\tif len(saved) > (size - j) {\n\t\t\t\t\t// fmt.Println(\"break\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif noIncrease {\n\t\treturn 0, []int{}\n\t} else if len(current) > len(saved) {\n\t\treturn len(current), current\n\t}\n\n\treturn len(saved), saved\n}", "func subarraySum(nums []int, k int) int {\n\tdic := make(map[int]int)\n\tdic[0] = 1\n\tcurr, res := 0, 0\n\n\tfor _, el := range nums {\n\t\tcurr += el\n\t\tif val, ok := dic[curr-k]; ok == true {\n\t\t\tres += val\n\t\t}\n\t\tif val, ok := dic[curr]; ok == true {\n\t\t\tdic[curr] = val + 1\n\t\t} else {\n\t\t\tdic[curr] = 1\n\t\t}\n\t}\n\treturn res\n}", "func sink(data []pq.Key, i, l int) {\n\tfor 2*i+1 < l {\n\t\tj := 2*i + 1\n\t\tif j+1 < l && data[j].Less(data[j+1]) {\n\t\t\tj++\n\t\t}\n\t\tif data[j].Less(data[i]) {\n\t\t\treturn\n\t\t}\n\t\tswap(data, i, j)\n\t\ti = j\n\t}\n}", "func (da *DoubleArray) PrefixLookup(key string) ([]string, []int) {\n\tkeys := make([]string, 0)\n\tvalues := make([]int, 0)\n\n\tnpos := 0\n\tdepth := 0\n\n\tfor ; depth < len(key); depth++ {\n\t\tif da.array[npos].base < 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tbase := da.array[npos].base\n\n\t\tif da.array[base].check == npos {\n\t\t\tkeys = append(keys, key[:depth])\n\t\t\tvalues = append(values, da.array[base].base)\n\t\t}\n\n\t\tcpos := base ^ int(key[depth])\n\t\tif da.array[cpos].check != npos {\n\t\t\treturn keys, values\n\t\t}\n\t\tnpos = cpos\n\t}\n\n\tbase := da.array[npos].base\n\n\tif base >= 0 {\n\t\tif da.array[base].check == npos {\n\t\t\tkeys = append(keys, key[:depth])\n\t\t\tvalues = append(values, da.array[base].base)\n\t\t}\n\t\treturn keys, values\n\t}\n\n\ttpos := -base\n\tfor ; depth < len(key); depth++ {\n\t\tif da.tail[tpos] != key[depth] {\n\t\t\treturn keys, values\n\t\t}\n\t\ttpos++\n\t}\n\n\tif da.tail[tpos] == terminator {\n\t\tkeys = append(keys, key[:depth])\n\t\tvalues = append(values, da.getValue(tpos+1))\n\t}\n\n\treturn keys, values\n}", "func BreakRepeatingXorArrays(arr [][]byte, numKeySizes int) ([]byte, [][]byte) {\n\tvar bestXorKey []byte\n\tvar maxScore float64\n\txorKeyList, xorKeyScores := GetRepeatingXorCandidates(arr, numKeySizes)\n\tisFirst := true\n\tfor i, score := range xorKeyScores {\n\t\tif isFirst || score > maxScore {\n\t\t\tmaxScore = score\n\t\t\tbestXorKey = xorKeyList[i]\n\t\t\tisFirst = false\n\t\t}\n\t}\n\txordResult := [][]byte{}\n\tfor _, subArr := range arr {\n\t\txordResult = append(xordResult, RepeatingKeyXor(subArr, bestXorKey))\n\t}\n\treturn bestXorKey, xordResult\n}", "func Solution01(N int, K int) int {\n\tif K > (N * (N + 1) / 2) {\n\t\treturn -1\n\t}\n\tcount := 0\n\tfor K > 0 {\n\t\tif K > N {\n\t\t\tK -= N\n\t\t\tN--\n\t\t} else {\n\t\t\tK = 0\n\t\t}\n\t\tcount++\n\t}\n\n\treturn count\n}", "func Solution(A []int) []int {\n\t// write your code in Go 1.4\n\n\tN := len(A)\n\n\tmymap := make(map[int]int)\n\tfor i := 0; i < N; i++ {\n\t\t_, ok := mymap[A[i]]\n\t\tif !ok {\n\t\t\tmymap[A[i]] = 1\n\t\t} else {\n\t\t\tmymap[A[i]] += 1\n\t\t}\n\t}\n\n\t// construct a custom Eratosthenes sieve\n\t// of factors\n\t// Note we create a custom sieve based on numbers we have\n\t// in the map created above\n\tsieve := make([]int, 2*N+1)\n\tfor i := 1; i <= 2*N; i++ {\n\t\tv, ok := mymap[i]\n\t\tif ok {\n\t\t\tfor k := i; k <= 2*N; k += i {\n\t\t\t\tsieve[k] += v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now we have every thing computed in the sieve,\n\t// with the help of the sieve.\n\t// We just loop again,\n\t// and return the values from the sive\n\n\tret := make([]int, N)\n\tfor i := 0; i < N; i++ {\n\t\tret[i] = N - sieve[A[i]]\n\t}\n\n\treturn ret\n\n}", "func zeroKey(b []byte) {\n\tfor i := range b {\n\t\tb[i] = 0\n\t}\n}", "func symMerge(nums []int, a, m, b int) {\n\t// Avoid unnecessary recursions of symMerge\n\t// by direct insertion of data[a] into data[m:b]\n\t// if data[a:m] only contains one element.\n\tif m-a == 1 {\n\t\t// Use binary search to find the lowest index i\n\t\t// such that data[i] >= data[a] for m <= i < b.\n\t\t// Exit the search loop with i == b in case no such index exists.\n\t\ti := m\n\t\tj := b\n\t\tfor i < j {\n\t\t\th := int(uint(i+j) >> 1)\n\t\t\tif nums[h] < nums[a] {\n\t\t\t\ti = h + 1\n\t\t\t} else {\n\t\t\t\tj = h\n\t\t\t}\n\t\t}\n\t\t// Swap values until data[a] reaches the position before i.\n\t\tfor k := a; k < i-1; k++ {\n\t\t\tnums[k], nums[k+1] = nums[k+1], nums[k]\n\t\t}\n\t\treturn\n\t}\n\n\t// Avoid unnecessary recursions of symMerge\n\t// by direct insertion of data[m] into data[a:m]\n\t// if data[m:b] only contains one element.\n\tif b-m == 1 {\n\t\t// Use binary search to find the lowest index i\n\t\t// such that data[i] > data[m] for a <= i < m.\n\t\t// Exit the search loop with i == m in case no such index exists.\n\t\ti := a\n\t\tj := m\n\t\tfor i < j {\n\t\t\th := int(uint(i+j) >> 1)\n\t\t\tif !(nums[m] < nums[h]) {\n\t\t\t\ti = h + 1\n\t\t\t} else {\n\t\t\t\tj = h\n\t\t\t}\n\t\t}\n\t\t// Swap values until data[m] reaches the position i.\n\t\tfor k := m; k > i; k-- {\n\t\t\tnums[k], nums[k-1] = nums[k-1], nums[k]\n\t\t}\n\t\treturn\n\t}\n\n\tmid := int(uint(a+b) >> 1)\n\tn := mid + m\n\tvar start, r int\n\tif m > mid {\n\t\tstart = n - b\n\t\tr = mid\n\t} else {\n\t\tstart = a\n\t\tr = m\n\t}\n\tp := n - 1\n\n\tfor start < r {\n\t\tc := int(uint(start+r) >> 1)\n\t\tif !(nums[p-c] < nums[c]) {\n\t\t\tstart = c + 1\n\t\t} else {\n\t\t\tr = c\n\t\t}\n\t}\n\n\tend := n - start\n\tif start < m && m < end {\n\t\trotate(nums, start, m, end)\n\t}\n\tif a < start && start < mid {\n\t\tsymMerge(nums, a, start, mid)\n\t}\n\tif mid < end && end < b {\n\t\tsymMerge(nums, mid, end, b)\n\t}\n}", "func sol2(nums1 []int, nums2 []int, k int) [][]int {\n if len(nums1) == 0 || len(nums2) == 0 {\n return nil\n }\n\n cursors := make([]int, len(nums1))\n var res [][]int\n for len(res) < k && len(res) < len(nums1) * len(nums2) {\n min := nums1[len(nums1)-1] + nums2[len(nums2)-1] + 1\n next := -1\n for i, j := range cursors {\n if j >= len(nums2) {\n continue\n }\n t := nums1[i] + nums2[j]\n if min > t {\n min = t\n next = i\n }\n // todo: skip condition\n }\n res = append(res, []int{nums1[next], nums2[cursors[next]]})\n cursors[next]++\n }\n\n return res\n}", "func checkSubarraySum(nums []int, k int) bool {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn false\n\t}\n\tindex := make(map[int]int)\n\tindex[0] = -1\n\n\tsum := 0\n\tfor i := 0; i < n; i++ {\n\t\tsum += nums[i]\n\t\tif k != 0 {\n\t\t\tsum %= k\n\t\t}\n\n\t\tidx, ok := index[sum]\n\t\tif ok {\n\t\t\tif i-idx > 1 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else {\n\t\t\tindex[sum] = i\n\t\t}\n\t}\n\treturn false\n}", "func naive(a []int) []int {\n\n\t/* if the array has 0 or zero elements, return an empty array */ \n\tif (len(a) < 2) {\n\t\treturn make([]int, 0)\n\t}\n\n\tp := make([]int, len(a))\n\tfor i := 0; i < len(a); i++ {\n\t\n\t\tproduct := 1; \n\t\tfor j := 0; j < len(a); j++ {\n\t\t\tif i != j {\n\t\t\t\tproduct = product * a[j]\n\t\t\t}\n \t\t}\n\t\tp[i] = product;\n\t}\n\n\treturn p\n}", "func Compute_n_gsm(kmer int, pr float64, gsm map[string]int, length map[string]int) (map[string]int){\n n := make(map[string]int)\n \n for k := range gsm {\n temp := int(Round((pr*float64(gsm[k])), 0.5, 0))\n if (temp == 0){\n n[k] = 1\n }else{\n n[k] = int(math.Min(float64(temp), float64(gsm[k])))/2\n }\n //fmt.Println(k, n[k])\n }\n \n\n return n\n}", "func solution(knows func(a int, b int) bool) func(n int) int {\n\treturn func(n int) int {\n\t\ti := 0\n\t\tj := 0\n\n\t\tindeg := make([]int, n)\n\n\t\tfor i = 0; i < n; i++ {\n\t\t\tfor j = 0; j< n; j++ {\n\t\t\t\tif knows(i, j) && i != j{\n\t\t\t\t\tindeg[i]--\n\t\t\t\t\tindeg[j]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor index, val := range indeg {\n\t\t\tif val == n-1 {\n\t\t\t\treturn index\n\t\t\t}\n\t\t}\n\n\t\treturn -1\n\t}\n}", "func createOrdering(mappings map[int]map[int][]mapping, data *util.QueryDocumentSet, iterations int) []float64 {\n\tN := data.Size()\n\titerations = gomath.MinInt(iterations, N-1)\n\n\tres := make([]float64, N)\n\n\tactive := make([]int, N)\n\tinDegree := make([]int, N)\n\toutDegree := make([][]int, N)\n\n\tfor i := range active {\n\t\tactive[i] = i\n\t}\n\n\t// O(N^3)\n\tfor _, v1 := range mappings {\n\t\tfor _, v2 := range v1 {\n\t\t\tfor _, d := range v2 {\n\t\t\t\tif d.weight > 0 {\n\t\t\t\t\toutDegree[d.from] = append(outDegree[d.from], d.to)\n\t\t\t\t\tinDegree[d.to]++\n\t\t\t\t} else {\n\t\t\t\t\toutDegree[d.to] = append(outDegree[d.to], d.from)\n\t\t\t\t\tinDegree[d.from]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// O(N^2)\n\tfor len(active) > 0 {\n\n\t\taIndex := -1\n\t\tbest := -1.0\n\t\tbestIdx := -1\n\t\tfor aI, i := range active {\n\t\t\ttest := float64(len(outDegree[i])) / (float64(inDegree[i]) + 1.0)\n\t\t\tif test > best {\n\t\t\t\tbest = test\n\t\t\t\tbestIdx = i\n\t\t\t\taIndex = aI\n\t\t\t}\n\t\t}\n\n\t\tres[bestIdx] = best\n\n\t\tfor _, v := range outDegree[bestIdx] {\n\t\t\tinDegree[v]--\n\t\t}\n\n\t\tactive[aIndex] = active[len(active)-1]\n\t\tactive = active[:len(active)-1]\n\t}\n\n\treturn res\n}", "func rising(arr []float64, len int) bool {\n\n\t// Add deffajult value as 3\n\tflag := false\n\tcurrVal := arr[0]\n\n\tfor _, val := range arr[1:] {\n\t\tlen--\n\t\tif len != 0 {\n\t\t\tif currVal > val {\n\t\t\t\tflag = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\tbreak\n\t}\n\treturn flag\n\n}", "func finalPrices(prices []int) []int {\n for i:=0; i<len(prices)-1; i++ {\n for j:=i+1; j<len(prices); j++ {\n if prices[j] <= prices[i] {\n prices[i] -= prices[j]\n // First eval of this is the lowest idx\n // so we break\n break\n }\n }\n }\n return prices\n}", "func BSearchFirstKey(k int64, l int64, h int64, s []int64) {\n\tfmt.Println()\n\tintervalLength := h - l\n\tswitch {\n\tcase intervalLength == 0:\n\t\tswitch {\n\t\tcase s[l] == k:\n\t\t\tfmt.Println(\"a\")\n\t\t\tfmt.Println(l)\n\t\tcase s[l+1] == k:\n\t\t\tfmt.Println(\"b\")\n\t\t\tfmt.Println(l + 1)\n\t\t}\n\tcase intervalLength == 1:\n\t\tswitch {\n\t\tcase s[l] == k:\n\t\t\tfmt.Println(\"c\")\n\t\t\tfmt.Println(l)\n\t\tcase s[h] == k:\n\t\t\tfmt.Println(\"d\")\n\t\t\tfmt.Println(h)\n\t\tcase s[h+1] == k:\n\t\t\tfmt.Println(\"e\")\n\t\t\tfmt.Println(h + 1)\n\t\t}\n\tdefault:\n\t\tmidIntervalIndex := (h + l) / 2\n\t\tmid := s[midIntervalIndex]\n\t\tswitch {\n\t\tcase mid >= k:\n\t\t\th = midIntervalIndex - 1\n\t\tcase mid < k:\n\t\t\tl = midIntervalIndex + 1\n\t\t}\n\t\tBSearchFirstKey(k, l, h, s)\n\t}\n}", "func twoSum1(nums []int, target int) []int {\n\thashTable := make(map[int]int)\n\tfor i, x := range nums {\n\t\tif j, ok := hashTable[target-x]; ok {\n\t\t\treturn []int{j, i}\n\t\t}\n\t\thashTable[x] = i\n\t}\n\treturn nil\n}", "func solve(n string, k int) int {\n\t//var dp [102][4][2]int\n\tl := len(n)\n\tdp := make([][][]int, l+1)\n\tfor i := range dp {\n\t\tdp[i] = make([][]int, 4)\n\t\tfor j := range dp[i] {\n\t\t\tdp[i][j] = make([]int, 2)\n\t\t}\n\t}\n\tdp[0][0][0] = 1\n\tfor i := 0; i < l; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\tfor p := 0; p < 2; p++ {\n\t\t\t\tf := int(n[i] - '0')\n\t\t\t\tfor d := 0; d < 10; d++ {\n\t\t\t\t\tni, nj, np := i+1, j, p\n\t\t\t\t\tif d > 0 {\n\t\t\t\t\t\tnj++\n\t\t\t\t\t}\n\t\t\t\t\tif nj > k {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif p == 0 {\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase d < f:\n\t\t\t\t\t\t\tnp = 1\n\t\t\t\t\t\tcase d > f:\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\tdp[ni][nj][np] += dp[i][j][p]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdebugf(\"%v\\n\", dp)\n\n\treturn dp[l][k][0] + dp[l][k][1]\n}", "func (g Graph) FullEdgesTo0ForVertex(v int) {\n count := 0;\n for count < len(*g.full) {\n v1temp := (*g.full)[count].v1_index\n v2temp := (*g.full)[count].v2_index\n if (v == v1temp || v == v2temp){\n //fmt.Printf(\"%d ---- %d\\n\", v1temp, v2temp)\n (*g.full)[count].weight = 0.0\n }\n \n count = count + 1\n }\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tsorted := MergeSort(A)\n\tcounter := 0\n\tvar initial int\n\tfor k := 0; k < len(sorted); k++ {\n\t\tif k == 0 {\n\t\t\tinitial = sorted[k]\n\t\t\tcounter++\n\t\t} else {\n\t\t\tif sorted[k] != initial {\n\t\t\t\tinitial = sorted[k]\n\t\t\t\tcounter++\n\t\t\t}\n\t\t}\n\t}\n\treturn counter\n}", "func checkSubarraySum(nums []int, k int) bool {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn false\n\t}\n\n\tfor i := range nums[1:] {\n\t\tif nums[i] == 0 && nums[i+1] == 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tm := make(map[int]int)\n\n\ts := 0\n\tfor i := 0; i < n; i++ {\n\t\ts += nums[i]\n\t\tif _, ok := m[s]; !ok {\n\t\t\tm[s] = i\n\t\t}\n\t}\n\n\tif k == s || s == 0 || k == 1 {\n\t\treturn true\n\t}\n\n\tif k > s {\n\t\treturn false\n\t}\n\n\tm[0] = -1\n\n\tmul := s / k\n\tfor v, i := range m {\n\t\tfor x := 1; x <= mul; x++ {\n\t\t\tif k*x > v {\n\t\t\t\tj, ok := m[k*x+v]\n\t\t\t\tif ok && j-i >= 2 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tj, ok := m[v-k*x]\n\t\t\t\tif ok && i-j >= 2 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func main() {\n\tvar n int\n\tfmt.Scanf(\"%d\", &n)\n\tvar emp []int\n\tempNum := make(map[int]int, 0)\n\tfor i := 0; i < n; i++ {\n\t\tvar num, value int\n\t\tfmt.Scanf(\"%d %d\", &num, &value)\n\t\temp = append(emp, value)\n\t\tempNum[value] = num\n\t}\n\tsort.Ints(emp)\n\t//fmt.Println(emp)\n\t//fmt.Println(empNum)\n\t//fmt.Println(empNum[2])\n\ti := 0\n\tj := len(emp) - 1\n\tmax := 0\n\tfor {\n\t\tif i == j && empNum[emp[i]] == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif empNum[emp[i]] != 0 {\n\t\t\tif empNum[emp[j]] != 0 {\n\t\t\t\ttemp := emp[i] + emp[j]\n\t\t\t\tif temp > max {\n\t\t\t\t\tmax = temp\n\t\t\t\t}\n\t\t\t\tempNum[emp[i]] -= 1\n\t\t\t\tempNum[emp[j]] -= 1\n\t\t\t} else {\n\t\t\t\tj -= 1\n\t\t\t}\n\t\t} else {\n\t\t\ti += 1\n\t\t}\n\t}\n\tfmt.Println(max)\n}", "func minIncrementForUnique(A []int) int {\n\tarr := [80000]int{}\n\tfor _, v := range A {\n\t\tarr[v]++\n\t}\n\n\tvar (\n\t\tans int\n\t\ttoken int\n\t)\n\tfor i := 0; i < 80000; i++ {\n\t\tif arr[i] > 1 {\n\t\t\ttoken += arr[i] - 1\n\t\t\tans -= i * (arr[i] - 1)\n\t\t} else if token > 0 && arr[i] == 0 {\n\t\t\ttoken--\n\t\t\tans += i\n\t\t}\n\t}\n\n\treturn ans\n}", "func bgmlogsdist(a, b bgmcommon.Hash) int {\n\tlz := 0\n\tfor i := range a {\n\t\tx := a[i] ^ b[i]\n\t\tif x == 0 {\n\t\t\tlz += 8\n\t\t} else {\n\t\t\tlz += lzcount[x]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn len(a)*8 - lz\n}", "func (arr *FloatArray) Uniq() {\n\tif len(*arr) == 0 {\n\t\treturn\n\t}\n\n\tstrMap := make(map[float64]int)\n\n\tfor _, el := range *arr {\n\t\t// value doesn't matter here cause we collect just keys\n\t\tstrMap[el] = 1\n\t}\n\n\tresArr := make([]float64, 0, 0)\n\tfor k := range strMap {\n\t\tresArr = append(resArr, k)\n\t}\n\n\t*arr = resArr\n}", "func lookup8(k []byte, level uint64) uint64 {\n\t// uint8_t *k; /* the key */\n\t// uint64_t length; /* the length of the key */\n\t// uint64_t level; /* the previous hash, or an arbitrary value */\n\tvar a, b, c uint64\n\tvar length int\n\n\t/* Set up the internal state */\n\tlength = len(k)\n\ta = level\n\tb = level /* the previous hash value */\n\tc = 0x9e3779b97f4a7c13 /* the golden ratio; an arbitrary value */\n\tp := 0\n\t/*---------------------------------------- handle most of the key */\n\tfor length >= 24 {\n\t\ta += uint64(k[p+0]) + (uint64(k[p+1]) << 8) + (uint64(k[p+2]) << 16) + (uint64(k[p+3]) << 24) + (uint64(k[p+4]) << 32) + (uint64(k[p+5]) << 40) + (uint64(k[p+6]) << 48) + (uint64(k[p+7]) << 56)\n\t\tb += uint64(k[p+8]) + (uint64(k[p+9]) << 8) + (uint64(k[p+10]) << 16) + (uint64(k[p+11]) << 24) + (uint64(k[p+12]) << 32) + (uint64(k[p+13]) << 40) + (uint64(k[p+14]) << 48) + (uint64(k[p+15]) << 56)\n\t\tc += uint64(k[p+16]) + (uint64(k[p+17]) << 8) + (uint64(k[p+18]) << 16) + (uint64(k[p+19]) << 24) + (uint64(k[p+20]) << 32) + (uint64(k[p+21]) << 40) + (uint64(k[p+22]) << 48) + (uint64(k[p+23]) << 56)\n\t\tmix64(&a, &b, &c)\n\t\tp += 24\n\t\tlength -= 24\n\t}\n\n\t/*------------------------------------- handle the last 23 bytes */\n\tc += uint64(len(k))\n\tswitch length { /* all the case statements fall through */\n\tcase 23:\n\t\tc += (uint64(k[p+22]) << 56)\n\t\tfallthrough\n\tcase 22:\n\t\tc += (uint64(k[p+21]) << 48)\n\t\tfallthrough\n\tcase 21:\n\t\tc += (uint64(k[p+20]) << 40)\n\t\tfallthrough\n\tcase 20:\n\t\tc += (uint64(k[p+19]) << 32)\n\t\tfallthrough\n\tcase 19:\n\t\tc += (uint64(k[p+18]) << 24)\n\t\tfallthrough\n\tcase 18:\n\t\tc += (uint64(k[p+17]) << 16)\n\t\tfallthrough\n\tcase 17:\n\t\tc += (uint64(k[p+16]) << 8)\n\t\tfallthrough\n\t/* the first byte of c is reserved for the length */\n\tcase 16:\n\t\tb += (uint64(k[p+15]) << 56)\n\t\tfallthrough\n\tcase 15:\n\t\tb += (uint64(k[p+14]) << 48)\n\t\tfallthrough\n\tcase 14:\n\t\tb += (uint64(k[p+13]) << 40)\n\t\tfallthrough\n\tcase 13:\n\t\tb += (uint64(k[p+12]) << 32)\n\t\tfallthrough\n\tcase 12:\n\t\tb += (uint64(k[p+11]) << 24)\n\t\tfallthrough\n\tcase 11:\n\t\tb += (uint64(k[p+10]) << 16)\n\t\tfallthrough\n\tcase 10:\n\t\tb += (uint64(k[p+9]) << 8)\n\t\tfallthrough\n\tcase 9:\n\t\tb += (uint64(k[p+8]))\n\t\tfallthrough\n\tcase 8:\n\t\ta += (uint64(k[p+7]) << 56)\n\t\tfallthrough\n\tcase 7:\n\t\ta += (uint64(k[p+6]) << 48)\n\t\tfallthrough\n\tcase 6:\n\t\ta += (uint64(k[p+5]) << 40)\n\t\tfallthrough\n\tcase 5:\n\t\ta += (uint64(k[p+4]) << 32)\n\t\tfallthrough\n\tcase 4:\n\t\ta += (uint64(k[p+3]) << 24)\n\t\tfallthrough\n\tcase 3:\n\t\ta += (uint64(k[p+2]) << 16)\n\t\tfallthrough\n\tcase 2:\n\t\ta += (uint64(k[p+1]) << 8)\n\t\tfallthrough\n\tcase 1:\n\t\ta += uint64(k[p+0])\n\t\t/* case 0: nothing left to add */\n\t}\n\tmix64(&a, &b, &c)\n\t/*-------------------------------------------- report the result */\n\treturn c\n}", "func keepDistance264(k int) []int {\n\tres, used := new([]int), new([]bool)\n\t*res, *used = make([]int, 2*k), make([]bool, k+1)\n\tfor i := 0; i < k; i++ {\n\t\t(*res)[i] = i + 1\n\t\t(*res)[i+k] = i + 1\n\t}\n\tif dfs264(0, res, used, k) {\n\t\treturn *res\n\t} else {\n\t\treturn nil\n\t}\n}", "func TestDuplicateZeros(t *testing.T) {\n\tduplicateZeros1([]int{1, 0, 2, 3, 0, 4, 5, 0})\n\tduplicateZeros1([]int{1, 2, 3})\n}", "func arrayManipulation(n int32, queries [][]int32) int64 {\n\n\tvar ret int64\n\n\t// create a slice with n amount of zeros\n\tmainSlice := []int32{}\n\tvar i int32\n\tfor i = 0; i <= n; i++ {\n\t\t// append 'n' number of 0's to slice to begin\n\t\tmainSlice = append(mainSlice, 0)\n\t}\n\n\tmainSlice = addKValsToArr(mainSlice, queries)\n\n\ttemp := mainSlice[0]\n\tfor i = 0; i <= n; i++ {\n\t\tif mainSlice[i] > temp {\n\t\t\ttemp = mainSlice[i]\n\t\t}\n\t}\n\n\tret = int64(temp)\n\n\treturn ret\n}", "func mockReduction(hash []byte, round uint64, step uint8, keys []key.ConsensusKeys, iterativeIdx ...int) consensus.Event {\n\tidx := 0\n\tif len(iterativeIdx) != 0 {\n\t\tidx = iterativeIdx[0]\n\t}\n\n\tif idx > len(keys) {\n\t\tpanic(\"wrong iterative index: cannot iterate more than there are keys\")\n\t}\n\n\thdr := header.Header{Round: round, Step: step, BlockHash: hash, PubKeyBLS: keys[idx].BLSPubKeyBytes}\n\n\tr := new(bytes.Buffer)\n\t_ = header.MarshalSignableVote(r, hdr)\n\tsigma, _ := bls.Sign(keys[idx].BLSSecretKey, keys[idx].BLSPubKey, r.Bytes())\n\tsignedHash := sigma.Compress()\n\treturn consensus.Event{hdr, *bytes.NewBuffer(signedHash)}\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 arrayManipulation(n int32, queries [][]int32) int64 {\n // slice is initialized with zeroes\n // 1-based indices + another element for the decrease\n // if upper bound == n\n arr := make([]int64, n+2)\n\n for _, row := range queries {\n var lhs, rhs, k = row[0], row[1], row[2]\n\n arr[lhs] += int64(k)\n arr[rhs+1] -= int64(k)\n }\n\n // Find maximum by adding up the changes into an accumulator.\n // all k are positive => invariant: acc >= 0.\n var acc, max int64 = 0, 0\n\n for _, val := range arr {\n acc += val\n if acc > max {\n max = acc\n }\n }\n\n return max\n}", "func deduplicate(data []float64) []float64 {\n\tkeys := make(map[float64]bool)\n\tuniq := []float64{}\n\tfor _, entry := range data {\n\t\tif _, value := keys[entry]; !value {\n\t\t\tkeys[entry] = true\n\t\t\tuniq = append(uniq, entry)\n\t\t}\n\t}\n\treturn uniq\n}", "func (p *G1Jac) mulGLV(a *G1Jac, s *big.Int) *G1Jac {\n\n\tvar table [15]G1Jac\n\tvar res G1Jac\n\tvar k1, k2 fr.Element\n\n\tres.Set(&g1Infinity)\n\n\t// table[b3b2b1b0-1] = b3b2*phi(a) + b1b0*a\n\ttable[0].Set(a)\n\ttable[3].phi(a)\n\n\t// split the scalar, modifies +-a, phi(a) accordingly\n\tk := ecc.SplitScalar(s, &glvBasis)\n\n\tif k[0].Sign() == -1 {\n\t\tk[0].Neg(&k[0])\n\t\ttable[0].Neg(&table[0])\n\t}\n\tif k[1].Sign() == -1 {\n\t\tk[1].Neg(&k[1])\n\t\ttable[3].Neg(&table[3])\n\t}\n\n\t// precompute table (2 bits sliding window)\n\t// table[b3b2b1b0-1] = b3b2*phi(a) + b1b0*a if b3b2b1b0 != 0\n\ttable[1].Double(&table[0])\n\ttable[2].Set(&table[1]).AddAssign(&table[0])\n\ttable[4].Set(&table[3]).AddAssign(&table[0])\n\ttable[5].Set(&table[3]).AddAssign(&table[1])\n\ttable[6].Set(&table[3]).AddAssign(&table[2])\n\ttable[7].Double(&table[3])\n\ttable[8].Set(&table[7]).AddAssign(&table[0])\n\ttable[9].Set(&table[7]).AddAssign(&table[1])\n\ttable[10].Set(&table[7]).AddAssign(&table[2])\n\ttable[11].Set(&table[7]).AddAssign(&table[3])\n\ttable[12].Set(&table[11]).AddAssign(&table[0])\n\ttable[13].Set(&table[11]).AddAssign(&table[1])\n\ttable[14].Set(&table[11]).AddAssign(&table[2])\n\n\t// bounds on the lattice base vectors guarantee that k1, k2 are len(r)/2 bits long max\n\tk1.SetBigInt(&k[0]).FromMont()\n\tk2.SetBigInt(&k[1]).FromMont()\n\n\t// loop starts from len(k1)/2 due to the bounds\n\tfor i := int(math.Ceil(fr.Limbs/2. - 1)); i >= 0; i-- {\n\t\tmask := uint64(3) << 62\n\t\tfor j := 0; j < 32; j++ {\n\t\t\tres.Double(&res).Double(&res)\n\t\t\tb1 := (k1[i] & mask) >> (62 - 2*j)\n\t\t\tb2 := (k2[i] & mask) >> (62 - 2*j)\n\t\t\tif b1|b2 != 0 {\n\t\t\t\ts := (b2<<2 | b1)\n\t\t\t\tres.AddAssign(&table[s-1])\n\t\t\t}\n\t\t\tmask = mask >> 2\n\t\t}\n\t}\n\n\tp.Set(&res)\n\treturn p\n}", "func P011() int {\n\tvec := newVector()\n\tmax, sum := 0, 0\n\n\tfor j := 0; j < 20; j++ {\n\t\tfor i := 0; i < 20; i++ {\n\t\t\t//fmt.Println(vec[i][j])\n\t\t\tsum = 0\n\t\t\t/*\n\t\t\t * UP\n\t\t\t */\n\t\t\tif j > 2 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i][j-k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * Down\n\t\t\t */\n\t\t\tif j < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i][j+k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * LEFT\n\t\t\t */\n\t\t\tif i > 2 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i-k][j]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * RIGHT\n\t\t\t */\n\t\t\tif i < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i+k][j]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * UP LEFT\n\t\t\t */\n\t\t\tif j > 2 && i > 2 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i-k][j-k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * UP RIGHT\n\t\t\t */\n\t\t\tif j > 2 && i < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i+k][j-k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * DOWN LEFT\n\t\t\t */\n\t\t\tif i > 2 && j < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i-k][j+k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * DOWN RIGHT\n\t\t\t */\n\t\t\tif i < 17 && j < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i+k][j+k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif sum > max {\n\t\t\t\tmax = sum\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}", "func KnapSack(value, weight []int, capacity, length int) int {\n\tif capacity == 0 {\n\t\treturn 0\n\t}\n\tif length < 0 {\n\t\treturn 0\n\t}\n\tif weight[length] <= capacity {\n\t\treturn int(math.Max(float64(value[length]+KnapSack(value, weight, capacity-weight[length], length-1)), float64(KnapSack(value, weight, capacity, length-1))))\n\t}\n\treturn KnapSack(value, weight, capacity, length-1)\n\n}", "func lookUpIdx(scaledValue int) int {\n\tscaledValue32 := int32(scaledValue)\n\tif scaledValue32 < maxArrayValue { //constant\n\t\treturn val2Bucket[scaledValue]\n\t}\n\tfor i := maxArrayValueIndex; i < numValues; i++ {\n\t\tif histogramBucketValues[i] > scaledValue32 {\n\t\t\treturn i\n\t\t}\n\t}\n\tlog.Fatalf(\"never reached/bug\")\n\treturn 0\n}", "func logdist(a, b common.Hash) int {\n\tlz := 0\n\tfor i := range a {\n\t\tx := a[i] ^ b[i]\n\t\tif x == 0 {\n\t\t\tlz += 8\n\t\t} else {\n\t\t\tlz += lzcount[x]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn len(a)*8 - lz\n}", "func sol2(nums []int, target int) []int {\n\tmemo := make(map[int]int)\n\tfor i, n := range nums {\n\t\tmemo[n] = i\n\t}\n\tfor i, n := range nums {\n\t\tif _, ok := memo[target-n]; ok && i != memo[target-n] {\n\t\t\treturn []int{i, memo[target-n]}\n\t\t}\n\t}\n\treturn nil\n}", "func containsNearbyDuplicate(nums []int, k int) bool {\n m := make(map[int]int)\n for i := 0; i < len(nums); i++ {\n index, exists := m[nums[i]]\n if exists {\n if math.Abs(float64(index - i)) <= float64(k) {\n return true\n }\n }\n m[nums[i]] = i \n }\n return false\n}", "func Solution(S string, K int) int {\n\t// write your code in Go 1.4\n\n\tN := len(S)\n\n\t// boundary case 1\n\tif K == 0 {\n\t\tret := 0\n\t\tfor i := 0; i < N; i++ {\n\t\t\tch := S[i]\n\t\t\tif ch == 'M' {\n\t\t\t\tret++\n\t\t\t}\n\t\t}\n\t\treturn ret\n\t}\n\n\tarr1 := make([]int, N)\n\n\tmaxl := 0\n\ttc := -1\n\tprevm := false\n\tfor i := 0; i < N; i++ {\n\t\tif S[i] == 'M' {\n\t\t\tif prevm {\n\t\t\t\ttc++\n\t\t\t} else {\n\t\t\t\ttc = 1\n\t\t\t}\n\t\t\tif tc > maxl {\n\t\t\t\tmaxl = tc\n\t\t\t}\n\t\t\tarr1[i] = tc\n\t\t\tprevm = true\n\n\t\t} else {\n\t\t\tarr1[i] = 0\n\t\t\tprevm = false\n\t\t}\n\n\t}\n\n\t// calculate M count, for K sliding window\n\tarr2 := make([]int, N)\n\tinit_sum := 0\n\tfor i := 0; i < K; i++ {\n\t\tif S[i] == 'M' {\n\t\t\tinit_sum++\n\t\t}\n\t\tarr2[i] = init_sum\n\t}\n\n\tfor i := K; i < N; i++ {\n\t\tarr2[i] = arr2[i-1]\n\t\tif S[i-K] == 'M' {\n\t\t\tarr2[i]--\n\t\t}\n\n\t\tif S[i] == 'M' {\n\t\t\tarr2[i]++\n\t\t}\n\t}\n\n\tfmt.Println(\"arr2: %v\\n\", arr2)\n\n\tif K == maxl {\n\t\treturn 0\n\t} else if K < maxl {\n\t\tret := 0\n\t\tfor i := 1; i < N; i++ {\n\t\t\tif arr1[i] == 0 && arr1[i-1] > 0 {\n\t\t\t\tif arr1[i-1] > K {\n\t\t\t\t\tret += arr1[i-1] / (K + 1)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif arr1[N-1] > K {\n\t\t\tret += arr1[N-1] / (K + 1)\n\t\t}\n\t\treturn ret\n\t} else {\n\n\t\tminret := N\n\n\t\tfor i := K - 1; i < N; i++ {\n\t\t\ttmpret := K - arr2[i]\n\t\t\tif i < N-1 && S[i+1] == 'M' {\n\t\t\t\ttmpret++\n\t\t\t}\n\n\t\t\tif i-K >= 0 && S[i-K] == 'M' {\n\t\t\t\ttmpret++\n\t\t\t}\n\n\t\t\tif tmpret < minret {\n\t\t\t\tminret = tmpret\n\t\t\t}\n\n\t\t}\n\t\treturn minret\n\t}\n\n\treturn N\n}", "func emptyBucket(input []int, value int) (int, int) {\n\tfor i, v := range input {\n\t\tif v == value {\n\t\t\tblocks := input[i]\n\t\t\tinput[i] = 0\n\t\t\treturn i, blocks\n\t\t}\n\t}\n\tlog.Fatalf(\"Cannot find memory bank with value %d\", value)\n\treturn -1, -1\n}", "func arrayManipulation(n int32, queries [][]int32) int64 {\n\tmax, arr, sum := int64(0), make([]int64, n), int64(0)\n\n\t// Instead of observing increases on each individual value...\n\t// We observe each beginning of range increase, and where it ends.\n\t//\n\t// For example:\n\t// n = 5, m = 3\n\t// a b k\n\t// 1 2 100 -> this will add 100 to n[1 - 1] and -100 to n[2]\n\t// 2 5 100 -> this will add 100 to n[2 - 1] and should add -100 to n[5] or none at all since it is beyond index range\n\t// 3 4 100\n\t// Expected output: 200\n\t//\n\t// Begin with: [5]int64 {0, 0, 0, 0, 0}\n\t// Then we iterate through the queries\n\t// m[0]: {100, 0, -100, 0, 0}\n\t// m[1]: {100, 100, -100, 0, 0}\n\t// m[2]: {100, 100, 0, 0, -100}\n\t//\n\t// Then we'll get sum of the whole array\n\t// while observing the peak sum as max value\n\t// (0)+100 100(+100) 200(+0) 200(+0) 100(-100)\n\n\tfor i := 0; i < len(queries); i++ {\n\t\tquery := queries[i]\n\t\ta := query[0] - 1\n\t\tb := query[1] - 1\n\t\tk := int64(query[2])\n\t\tarr[a] += k\n\t\tif b+1 < n {\n\t\t\tarr[b+1] -= k\n\t\t}\n\t}\n\tfor i := int32(0); i < n; i++ {\n\t\tif arr[i] != 0 {\n\t\t\tsum += arr[i]\n\t\t\tif sum > max {\n\t\t\t\tmax = sum\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}", "func (iter *Iterator) tick(i, min int, delta []*vcache) (ok bool, err error) {\n\tnext := make([]*vcache, i)\n\n\t// The biggest outer loop is walking backwards over iter.In[i]\n\tx := len(iter.in[i])\n\tfor x > 0 {\n\t\tj := iter.in[i][x-1]\n\n\t\tif j <= min {\n\t\t\treturn false, iter.restore(next, i)\n\t\t} else if iter.blacklist[j] {\n\t\t\tx--\n\t\t\tcontinue\n\t\t}\n\n\t\tv := iter.variables[j]\n\n\t\tself := v.save()\n\n\t\tif v.value = v.Next(); v.value == NIL {\n\t\t\t// That sucks. Now we need to restore the value\n\t\t\t// that was changed and decrement x.\n\t\t\tv.value = v.Seek(self.ID)\n\t\t\tx--\n\t\t} else {\n\t\t\t// We got a non-nil value for v, so now we\n\t\t\t// propagate between j and i, then crawl forward\n\t\t\t// over the indices in iter.Out[q] that are less than i\n\t\t\t// and seek to their new values.\n\n\t\t\t// Propagate up to but not including i\n\t\t\tif err = iter.push(v, j, i); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Fantastic. Now that we've propagated the value we found for v,\n\t\t\t// we start \"the crawl\" from j to i, seeking to the new satisfying root\n\t\t\t// and recursing on tick when necessary.\n\t\t\tcursor := j\n\t\t\titer.blacklist[j] = true\n\t\t\tfor _, k := range iter.out[j] {\n\t\t\t\tif k >= i {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw := iter.variables[k]\n\n\t\t\t\tif next[k] == nil {\n\t\t\t\t\tnext[k] = w.save()\n\t\t\t\t}\n\n\t\t\t\td := make([]*vcache, k)\n\n\t\t\t\t// Here we keep seeking and ticking until we have a real value.\n\t\t\t\tfor w.value = w.Seek(w.root); w.value == NIL; w.value = w.Seek(w.root) {\n\t\t\t\t\tif ok, err = iter.tick(k, min, d); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else if ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err = iter.restore(d, i); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif w.value == NIL {\n\t\t\t\t\t// We were unable to complete the crawl.\n\t\t\t\t\t// We've already reset our state.\n\t\t\t\t\t// This is how far we got:\n\t\t\t\t\tcursor = k + 1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// We got a real value for w! Now we propagate the affected values\n\t\t\t\t// through i and stash them into next if they're not there already,\n\t\t\t\t// and then continue with the tick-crawl.\n\t\t\t\terr = iter.push(w, k, i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfor l, saved := range d {\n\t\t\t\t\tif saved != nil {\n\t\t\t\t\t\terr = iter.push(iter.variables[l], l, i)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif next[l] == nil {\n\t\t\t\t\t\t\tnext[l] = saved\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\t// We need to *unset* the blacklist after recursing.\n\t\t\t// Variables are only blacklisted when they appear as\n\t\t\t// a parent in the call stack - they might be visited\n\t\t\t// twice as siblings in the call tree, etc.\n\t\t\titer.blacklist[j] = false\n\n\t\t\tif cursor == j {\n\t\t\t\t// Hooray!\n\t\t\t\t// Now here we need to push every affected value\n\t\t\t\t// through to the rest of the domain\n\t\t\t\t// delta[j] = self\n\t\t\t\tnext[j] = self\n\t\t\t\tfor l, saved := range next {\n\t\t\t\t\tif saved != nil {\n\t\t\t\t\t\tif delta[l] == nil {\n\t\t\t\t\t\t\tdelta[l] = saved\n\t\t\t\t\t\t}\n\t\t\t\t\t\terr = iter.push(iter.variables[l], i, iter.Len())\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true, nil\n\t\t\t}\n\n\t\t\t// This means we reset (all) those affected to their previous state\n\t\t\terr = iter.restore(next, i)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func duplicateZeros(arr []int) {\n\thelpFunc2(arr)\n}", "func DutchFlagAlgo(arr []int) {\n\tlow := 0\n\tmid := 0\n\thigh := len(arr) - 1\n\tfor mid <= high {\n\t\tif arr[mid] == 0 {\n\t\t\tarr[low], arr[mid] = arr[mid], arr[low]\n\t\t\tmid++\n\t\t\tlow++\n\t\t} else if arr[mid] == 1 {\n\t\t\tmid++\n\t\t} else if arr[mid] == 2 {\n\t\t\tarr[high], arr[mid] = arr[mid], arr[high]\n\t\t\thigh--\n\t\t}\n\t}\n\tfmt.Println(arr)\n}", "func minimumSwaps(arr []int32) int32 {\n\n\tvar trackArray []visit\n\tfor _, v := range arr {\n\t\ttrackArray = append(trackArray, visit{int(v), false})\n\t}\n\t// traversing through array finding cycles\n\tvar swapCount int\n\tfor i, v := range trackArray {\n\t\tif v.seen {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Mark this number as seen (note that we have to access the original array rather than v)\n\t\ttrackArray[i].seen = true\n\n\t\tif i == v.val {\n\t\t\t// Number already in correct place\n\t\t\tcontinue\n\t\t}\n\t\t// Start tracking a cycle\n\t\t// Check the number sitting in v's \"home\"\n\t\tcurrent := v\n\t\tfor {\n\t\t\tnext := trackArray[current.val-1]\n\n\t\t\t// Mark next as seen (have to update original array)\n\t\t\ttrackArray[current.val-1].seen = true\n\n\t\t\tif next.val == v.val {\n\t\t\t\t// End of the cycle\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Necessary swaps is (length of cycle) - 1\n\t\t\tswapCount++\n\t\t\tcurrent = next\n\t\t}\n\t}\n\n\treturn int32(swapCount)\n\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tsort.Ints(A)\n\tfor i, a := range A {\n\t\tif i+1 != a {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn 1\n}", "func D1b(input string) string {\n\tnums, err := parseSlice(input)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Can not load input: %v\", err)\n\t}\n\n\tsort.Ints(nums)\n\n\tfor i := len(nums) - 1; i >= 0; i-- {\n\t\tfor j := i - 1; j >= 0; j-- {\n\t\t\tif nums[i]+nums[j] > 2020 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t//\n\t\t\tfor k := 0; k < j; k++ {\n\t\t\t\tif nums[i]+nums[j]+nums[k] > 2020 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif nums[i]+nums[j]+nums[k] != 2020 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn strconv.Itoa(nums[i] * nums[j] * nums[k])\n\t\t\t}\n\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"No correct values :(\")\n}", "func (this *AllOne) Inc(key string) {\n\tnode, _ := this.mapping[key]\n\tif node == nil { // key doesn't exist\n\t\tif this.head.next == this.tail { // first element\n\t\t\tnewNode := &Node{\n\t\t\t\tval: 1,\n\t\t\t\tkeys: map[string]bool{key:true},\n\t\t\t}\n\t\t\tthis.head.next = newNode\n\t\t\tnewNode.pre = this.head\n\t\t\tthis.tail.pre = newNode\n\t\t\tnewNode.next = this.tail\n\t\t\tthis.mapping[key] = newNode\n\t\t} else if this.head.next.val != 1 { // 1 doesn't exist\n\t\t\tnewNode := &Node{\n\t\t\t\tval: 1,\n\t\t\t\tkeys: map[string]bool{key:true},\n\t\t\t}\n\t\t\tjumpNode := this.head.next\n\t\t\tthis.head.next = newNode\n\t\t\tnewNode.pre = this.head\n\t\t\tjumpNode.pre = newNode\n\t\t\tnewNode.next = jumpNode\n\t\t\tthis.mapping[key] = newNode\n\t\t} else { // 1 exits\n\t\t\tthis.head.next.keys[key] = true\n\t\t\tthis.mapping[key] = this.head.next\n\t\t}\n\t} else { // key exists there\n\t\tif len(node.keys) == 1 { // node has itself only\n\t\t\tif node.next == this.tail || node.next.val != node.val + 1 { // node is max or node next is not adjacent node\n\t\t\t\tnode.val++\n\t\t\t} else { // node has a next node which need to merge\n\t\t\t\tmergeNode := node.next\n\t\t\t\tmergeNode.keys[key] = true\n\t\t\t\tmergeNode.pre = node.pre\n\t\t\t\tnode.pre.next = mergeNode\n\t\t\t\tthis.mapping[key] = mergeNode\n\t\t\t}\n\t\t} else { // node has other key\n\t\t\tif node.next == this.tail || node.next.val != node.val + 1 { // node is max or node next is not adjacent node\n\t\t\t\tnewNode := &Node{\n\t\t\t\t\tval: node.val + 1,\n\t\t\t\t\tkeys: map[string]bool{key:true},\n\t\t\t\t}\n\t\t\t\tnextNode := node.next\n\t\t\t\tnode.next = newNode\n\t\t\t\tnewNode.pre = node\n\t\t\t\tnextNode.pre = newNode\n\t\t\t\tnewNode.next = nextNode\n\t\t\t\tdelete(node.keys, key)\n\t\t\t\tthis.mapping[key] = newNode\n\t\t\t} else { // node has a next node so just move the key\n\t\t\t\tmergeNode := node.next\n\t\t\t\tmergeNode.keys[key] = true\n\t\t\t\tdelete(node.keys, key)\n\t\t\t\tthis.mapping[key] = mergeNode\n\t\t\t}\n\t\t}\n\t}\n\t// next := this.head.next\n\t// for next != this.tail {\n\t// fmt.Print(next.val, next.keys)\n\t// next = next.next\n\t// }\n\t// fmt.Println()\n}", "func Jagged(x float64) float64 {\n\tx = x - math.Floor(x)\n\tmult := 1.0\n\tresult := 0.0\n\toldResult := 0.0\n\tfor {\n\t\tif x > 0.5 {\n\t\t\tresult += (1.0 - x) * mult\n\t\t} else {\n\t\t\tresult += x * mult\n\t\t}\n\t\tif result == oldResult {\n\t\t\treturn result\n\t\t}\n\t\toldResult = result\n\t\tmult /= 2.0\n\t\tx *= 2.0\n\t\tif x >= 1.0 {\n\t\t\tx -= 1.0\n\t\t}\n\t}\n\treturn 0.0\n}", "func repeatedNTimes(A []int) int {\n m := make(map[int]int)\n for _, v := range A {\n m[v]++\n if m[v] > 1 {\n return v\n }\n }\n return 0\n}", "func (da *DoubleArray) Lookup(key string) (int, bool) {\n\tnpos := 0\n\tdepth := 0\n\n\tfor ; depth < len(key); depth++ {\n\t\tif da.array[npos].base < 0 {\n\t\t\tbreak\n\t\t}\n\t\tcpos := da.array[npos].base ^ int(key[depth])\n\t\tif da.array[cpos].check != npos {\n\t\t\treturn 0, false\n\t\t}\n\t\tnpos = cpos\n\t}\n\n\tif da.array[npos].base >= 0 {\n\t\tcpos := da.array[npos].base // ^ int(terminator)\n\t\tif da.array[cpos].check != npos {\n\t\t\treturn 0, false\n\t\t}\n\t\treturn da.array[cpos].base, true\n\t}\n\n\ttpos := -da.array[npos].base\n\tfor ; depth < len(key); depth++ {\n\t\tif da.tail[tpos] != key[depth] {\n\t\t\treturn 0, false\n\t\t}\n\t\ttpos++\n\t}\n\n\tif da.tail[tpos] != terminator {\n\t\treturn 0, false\n\t}\n\treturn da.getValue(tpos + 1), true\n}", "func NaiveShift(arr []int) []int {\n\twork := make([]int, len(arr))\n\tcopy(work, arr)\n\n\tfor i := 0; i < len(work); i++ {\n\t\tfmt.Println(work)\n\t\tif work[i] == 0 {\n\t\t\tfor j := i; j < len(work); j++ {\n\t\t\t\tif work[j] != 0 {\n\t\t\t\t\twork[i], work[j] = work[j], work[i]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn work\n}", "func repeatedNTimes(A []int) int {\n cache := map[int]bool {}\n for _,a := range A {\n if cache[a] {\n return a\n }\n cache[a] = true\n }\n return -1\n}", "func recInversionCount(v *array) (*array, int){\r\n\tif len(v.a) == 1{\r\n\t\treturn v, 0\r\n\t}\r\n\tmid := (len(v.a))/2\r\n\tleftHalf, leftInv := recInversionCount(&array{v.a[:mid]})\r\n\trightHalf, rightInv := recInversionCount(&array{v.a[mid:]})\r\n\tsortedArr := []int{}\r\n\tsplitInv := 0\r\n\ti, j := 0, 0\r\n\tfor i < len(leftHalf.a) && j < len(rightHalf.a){\r\n\t\tif leftHalf.a[i] <= rightHalf.a[j]{\r\n\t\t\tsortedArr = append(sortedArr, leftHalf.a[i])\r\n\t\t\ti++\r\n\t\t} else{\r\n\t\t\tsortedArr = append(sortedArr, rightHalf.a[j])\r\n\t\t\tsplitInv += len(leftHalf.a)-i\r\n\t\t\tj++\r\n\t\t}\r\n\t}\r\n\tif i<len(leftHalf.a) {\r\n\t\tsortedArr = append(sortedArr, leftHalf.a[i:]...)\r\n\t} \r\n\tfor j < len(rightHalf.a) {\r\n\t\tsortedArr = append(sortedArr, rightHalf.a[j])\r\n\t\tj++\r\n\t}\r\n\treturn &array{sortedArr}, leftInv+rightInv+splitInv\r\n}", "func menageatrois(arr []int) {\n sort.Ints( arr )\n\n for outer := 0; outer < len(arr); outer++ {\n var a = arr[outer]\n var start = outer+1\n var end = len(arr)-1\n\n for ; start < end ; {\n var b = arr[start]\n var c = arr[end]\n\n switch {\n case a+b+c == 0:\n fmt.Println(a, b, c)\n end -=1\n case a+b+c > 0:\n end -=1\n default:\n start += 1\n }\n }\n }\n}", "func solveEqn(s string, n int)map[byte]float64{\n rhs := make([]float64, n)\n //res := make([]int, n)\n co_eff := make([][]float64, n)\n m := make(map[byte]int)\n var k, e bool\n var i, j, t, c int\n p := true\n co_eff[0] = make([]float64,n)\n for ;i < len(s); i++{\n if s[i] == 10{ //new line; new equation signal\n if c != 0{\n if p{\n rhs[j] += float64(c)\n }else{\n rhs[j] -= float64(c)\n }\n }\n e = false\n p = true\n c = 0\n j += 1\n if j < n{\n co_eff[j] = make([]float64, n)\n }\n }else if s[i] > 47 && s[i] < 58{ //number\n c = c*10 + int(s[i]-48)\n }else if s[i] == 43{ //\"+\"\n if (e && !p) || (!e && p){\n rhs[j] -= float64(c)\n }else{\n rhs[j] += float64(c)\n }\n p = true\n c = 0\n }else if s[i] == 45{ //\"-\"\n if (e && !p) || (!e && p){\n rhs[j] -= float64(c)\n }else{\n rhs[j] += float64(c)\n }\n p = false\n c = 0\n }else if s[i] == 61{ //\"=\"\n if (e && !p) || (!e && p){\n rhs[j] -= float64(c)\n }else{\n rhs[j] += float64(c)\n }\n e = true\n p = true\n c = 0\n }else{ //char_variable\n _, k = m[s[i]]\n if !k{\n m[s[i]] = len(m)\n }\n if c == 0{ //x + y = 1; coefficient of x == 1\n c = 1\n }\n //fmt.Println(j, s[i],m[s[i]])\n if (e && !p) || (!e && p){\n co_eff[j][m[s[i]]] += float64(c)\n }else{\n co_eff[j][m[s[i]]] -= float64(c)\n }\n c = 0\n }\n }\n// printmatrix(co_eff)\n// fmt.Println(rhs)\n /*\n Gauss elimination method, turn co_eff into an upper triangular matirx using\n row operations (also perform the same operations on rhs) and than solve for each\n variable starting from the end row(i == n-1)\n */\n\n for i = 0; i < n-1; i++{\n j = i+1\n c = i\n if co_eff[i][c] == 0{\n k = false\n //find row with non zero value at col == c if it doesnt exist than return\n for ;j < n; j++{\n if co_eff[j][c] != 0{\n k = true\n break\n }\n }\n if k{\n //swap i and j rows\n rhs[j], rhs[i] = rhs[i], rhs[j]\n for t = c; t < n; t++{ //row operation\n co_eff[i][t], co_eff[j][t] = co_eff[j][t], co_eff[i][t]\n }\n j = j+1\n }else{\n return map[byte]float64{} //infinite or no solution case\n }\n }\n\n for ;j < n; j++{\n if co_eff[j][c] == 0{\n continue\n }\n co_eff[j][c] /= co_eff[i][c]\n rhs[j] -= co_eff[j][c]*rhs[i]\n for t = n-1; t > c; t--{//row operation\n co_eff[j][t] -= co_eff[j][c]*co_eff[i][t]\n }\n co_eff[j][c] = 0\n }\n }\n fmt.Println(\"row echleon form\")\n printmatrix(co_eff)\n fmt.Println(\"rhs\", rhs)\n for i = n-1; i >= 0; i--{\n for j = i+1; j < n; j++{\n rhs[i] -= co_eff[i][j]*rhs[j]\n }\n rhs[i] /= co_eff[i][i]\n }\n res := make(map[byte]float64)\n for b, i := range m{\n res[b] = rhs[i]\n }\n return res\n}" ]
[ "0.5987535", "0.5879524", "0.58719933", "0.56984395", "0.567414", "0.5672431", "0.5597899", "0.5594946", "0.55765355", "0.5502879", "0.5439185", "0.54181236", "0.539837", "0.5391178", "0.53850394", "0.52594733", "0.5241006", "0.5219284", "0.52050865", "0.52036333", "0.5172266", "0.51597375", "0.51514775", "0.5145688", "0.51404005", "0.51371306", "0.5134215", "0.5100763", "0.50987", "0.50923645", "0.5085705", "0.508142", "0.5066852", "0.50588775", "0.505354", "0.5034078", "0.50319666", "0.5019589", "0.501662", "0.5011165", "0.5007225", "0.5003609", "0.50021833", "0.49993366", "0.49942166", "0.49931115", "0.49894086", "0.49839467", "0.4970046", "0.49579415", "0.49521607", "0.4948318", "0.494458", "0.49319175", "0.49282473", "0.49187526", "0.4918174", "0.4917649", "0.49076477", "0.49070084", "0.48975196", "0.48922017", "0.48783094", "0.4875103", "0.48680413", "0.48629645", "0.4858477", "0.48563826", "0.48552808", "0.485392", "0.48535362", "0.48499638", "0.48470855", "0.4846926", "0.48446858", "0.48366588", "0.48346588", "0.4829638", "0.4828531", "0.48189113", "0.4817649", "0.48124114", "0.48072174", "0.48058555", "0.4805063", "0.48036438", "0.48024538", "0.4802298", "0.48021284", "0.4796464", "0.47961873", "0.47864354", "0.4778101", "0.47772187", "0.47651497", "0.476287", "0.47628596", "0.47595417", "0.47594893", "0.47594446" ]
0.511641
27
Not working . Is a bad ideea to put them in a map cause they might get duplicated for certain inputs.
func sSubarraySum(nums []int, sum int) int { result := 0 sumMap := make(map[int]int) cum := 0 for i, v := range nums { cum += v nums[i] = cum sumMap[cum-sum]++ } if c, ok := sumMap[0]; ok { result += c } for _, v := range nums { if c, ok := sumMap[v]; ok { if sum == 0 { result += c / 2 delete(sumMap, v) } else { result += c } } } return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func main() {\n unique := \"abcde\"\n dup := \"aabcde\"\n\n uniqueRes := UniqueUsingMap(unique)\n dupRes := UniqueUsingMap(dup)\n\n fmt.Println(uniqueRes) // => true\n fmt.Println(dupRes) // => false\n\n uniqueRes = UniqueUsingString(unique)\n dupRes = UniqueUsingString(dup)\n\n fmt.Println(uniqueRes) // => true\n fmt.Println(dupRes) // => false\n}", "func mapKeysAndVals() {\r\n\tages := map[string]float64{}\r\n\r\n\tages[\"Alice\"] = 12\r\n\tages[\"Bob\"] = 9\r\n\tfmt.Println(ages[\"Alice\"], ages[\"Bob\"])\r\n}", "func uniqueTokenMap(list []Token) map[Token]bool {\n\tm := map[Token]bool{}\n\tfor _, t := range list {\n\t\tm[t] = true\n\t}\n\treturn m\n}", "func linkedConstructInputsMap(ctx *pulumi.Context, inputs map[string]interface{}) (pulumi.Map, error)", "func MakeMap(ints []int) map[string]int {\n\t// Your code goes here\n}", "func toMap(params []interface{}) map[string]interface{} {\n\tpar := make(map[string]interface{})\n\tif len(params) == 0 {\n\t\treturn par\n\t}\n\tif len(params)%2 != 0 {\n\t\tpanic(\"WithParams: len(params) % 2 != 0\")\n\t}\n\tfor i := 0; i < len(params)/2; i++ {\n\t\tkey, ok := params[2*i].(string)\n\t\tif !ok {\n\t\t\tpanic(\"WithParams: string expected\")\n\t\t}\n\t\tpar[key] = params[2*i+1]\n\t}\n\treturn par\n}", "func main() {\n\ta := [...]string {Enone: \"no error\", Eio: \"Eio\", Einval: \"invalid argument\"}\n\ts := []string {Enone: \"no error\", Eio: \"Eio\", Einval: \"invalid argument\"}\n\tm := map[int]string{Enone: \"no error\", Eio: \"Eio\", Einval: \"invalid argument\"}\n\n\tfmt.Println(a)\n\tfmt.Println(s)\n\tfmt.Println(m)\n\n\tfmt.Println(NewPersonV3(\"\",1,\"\"))\n\tfmt.Println(NewPersonV3(\"\", 1, \"\"))\n}", "func makeInput() Map {\n\treturn Map{\n\t\t\"a\": 25,\n\t\t\"b\": float32(2.5),\n\t\t\"c\": float64(2.5),\n\t\t\"d\": true,\n\t\t\"e\": false,\n\t\t\"f\": \"25\",\n\t\t\"g\": nil,\n\t}\n}", "func Map[M map[K]V, K ~int, V string | int](s []V) M {\n// func Map[M map[int]V, V string | int](s []V) M {\n\tvar m = make(M)\n\tfor i, one := range s {\n\t\tm[i] = one\n\t}\n\treturn m\n}", "func constructInputsMap(ctx *Context, inputs map[string]interface{}) (Map, error) {\n\tresult := make(Map, len(inputs))\n\tfor k, v := range inputs {\n\t\tci := v.(*constructInput)\n\n\t\tknown := !ci.value.ContainsUnknowns()\n\t\tvalue, secret, err := unmarshalPropertyValue(ctx, ci.value)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"unmarshaling input %s\", k)\n\t\t}\n\n\t\tresultType := anyOutputType\n\t\tif ot, ok := concreteTypeToOutputType.Load(reflect.TypeOf(value)); ok {\n\t\t\tresultType = ot.(reflect.Type)\n\t\t}\n\n\t\toutput := ctx.newOutput(resultType, ci.deps...)\n\t\toutput.getState().resolve(value, known, secret, nil)\n\t\tresult[k] = output\n\t}\n\treturn result, nil\n}", "func validityMap(rules []rule) map[int][]int {\n\tvalid := make(map[int][]int)\n\tfor i:=0; i<1000; i++ { \n\t\tvalid[i] = []int{}\n\t\tfor rIx, rl := range rules {\n\t\t\tif rl.rng.contains(i) {\n\t\t\t\tvalid[i] = append(valid[i], rIx)\n\t\t\t}\n\t\t}\n\t}\n\treturn valid\n}", "func extractSNARNMap(typ string, results map[string]arn, input []*string) error {\n\tfor _, sptr := range input {\n\t\tif sptr == nil {\n\t\t\treturn fmt.Errorf(\"Unexpectd nil walking ECS %s\", typ)\n\t\t}\n\n\t\ts := arnValue(sptr)\n\t\tcname := extractSN(s)\n\t\tif _, dupe := results[cname]; dupe {\n\t\t\treturn fmt.Errorf(\"Duplicate ECS %s found: %s\", typ, s)\n\t\t}\n\t\tresults[cname] = s\n\t}\n\n\treturn nil\n}", "func (qq Qualifiers) Map() map[string]string {\n\tm := make(map[string]string)\n\n\tfor i := 0; i < len(qq); i++ {\n\t\tk := qq[i].Key\n\t\tv := qq[i].Value\n\t\tm[k] = v\n\t}\n\n\treturn m\n}", "func main() {\n\ts := make(set)\n\ts[\"item1\"] = struct{}{}\n\ts[\"item2\"] = struct{}{}\n\ts[\"item1\"] = struct{}{} //Won't be added. Matches already added key.\n\tfmt.Println(getSetValues(s))\n}", "func MerkMake(mapfile []string) map[string]string {\n mermap := map[string]string{}\n\n for lx := 0; lx < len(mapfile); lx++ {\n hashthis := himitsu.Hashit(mapfile[lx])\n mermap[hashthis] = mapfile[lx]\n } // end for mapfile.\n\n return mermap\n\n}", "func mapCreator2() {\n\n\tvar bootstrap2 = make(map[string]float64)\n\n\tbootstrap2[\"this is fun\"] = 123e9\n\n\tfmt.Println(bootstrap2)\n}", "func getPermutation(inputs ledgerstate.Inputs) map[ledgerstate.OutputID]int {\n\tret := make(map[ledgerstate.OutputID]int)\n\tfor i := range inputs {\n\t\tret[inputs[i].(*ledgerstate.UTXOInput).ReferencedOutputID()] = i\n\t}\n\treturn ret\n}", "func toMap(sl []string) map[string]bool {\n\tm := make(map[string]bool, len(sl))\n\tfor _, s := range sl {\n\t\tm[s] = true\n\t}\n\treturn m\n}", "func createMapSubStringAndIndex(input string) map[string] []int{\n\tmSubStringIndex := make(map[string] []int)\n\t//loop in to find Tandem repeat from size 3 to 10\n\tfor size := 3; size <= 10; size++ {\n\t\ti := 0\n\t\tfor i + size < len(input) + 1 {\n\t\t\tframeValue := input[i:i+size]\n\t\t\tif val, ok := mSubStringIndex[frameValue]; ok {\n\t\t\t\tif val[0] != -1 {\n\t\t\t\t\tmSubStringIndex[frameValue] = append(mSubStringIndex[frameValue],i)\n\t\t\t\t\tsetIgnoreValue(frameValue,&mSubStringIndex)\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tmSubStringIndex[frameValue] = []int{i}\n\t\t\t\tsetIgnoreValue(frameValue,&mSubStringIndex)\n\t\t\t}\n\t\t\ti += 1\n\t\t}\n\t}\n\treturn mSubStringIndex\n}", "func defs() []string {\n\t// MUST be called AFTER init()\n\trv := make([]string, 0)\n\tfor k, v := range sensorMap {\n\t\tif k != v { // then it's an _input sensor\n\t\t\trv = append(rv, v)\n\t\t}\n\t}\n\treturn rv\n}", "func registersUnique(regs ...asm.Register) error {\n\tseen := make(map[asm.Register]struct{}, len(regs))\n\n\tfor _, reg := range regs {\n\t\tif err := registerValid(reg); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, ok := seen[reg]; ok {\n\t\t\treturn errors.Errorf(\"register %v used twice\", reg)\n\t\t}\n\t\tseen[reg] = struct{}{}\n\t}\n\n\treturn nil\n}", "func same(sMap, cMap map[rune]int) bool {\n\tfor sr, sCount := range sMap {\n\t\tif cCount, ok := cMap[sr]; !ok {\n\t\t\treturn false\n\t\t} else if cCount != sCount {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func mapfn(kvs ...interface{}) (map[string]interface{}, error) {\n\tif len(kvs)%2 != 0 {\n\t\treturn nil, errors.New(\"map requires even number of arguments.\")\n\t}\n\tm := make(map[string]interface{})\n\tfor i := 0; i < len(kvs); i += 2 {\n\t\ts, ok := kvs[i].(string)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"even args to map must be strings.\")\n\t\t}\n\t\tm[s] = kvs[i+1]\n\t}\n\treturn m, nil\n}", "func (b *Builder) internSet(s []string) map[string]struct{} {\n\tout := make(map[string]struct{}, len(s))\n\tfor _, val := range s {\n\t\tout[b.internStr(val)] = struct{}{}\n\t}\n\treturn out\n}", "func mapExecutorNames(ge *agent.Response_GetExecutors) map[string]string {\n\tresults := map[string]string{}\n\tif ge != nil {\n\t\tfor _, e := range ge.GetExecutors() {\n\t\t\tei := e.GetExecutorInfo()\n\t\t\tid := ei.GetExecutorID().Value\n\t\t\tresults[id] = ei.GetName()\n\t\t}\n\t}\n\treturn results\n}", "func mapCreateList(name, rollNo, height, weight, averageMarks, extraCurricularGrade string) map[string][]string {\n\tvar mapRet = map[string][]string{\n\t\t\"name\": createList(name),\n\t\t\"roll_no\": createList(rollNo),\n\t\t\"weight\": createList(weight),\n\t\t\"height\": createList(height),\n\t\t\"avg_marks\": createList(averageMarks),\n\t\t\"extra_curr_grades\": createList(extraCurricularGrade),\n\t}\n\treturn mapRet\n}", "func (mr MrImpl) Map(key, value string) (result []mapreduce.KeyValue) {\n\tvals := strings.Split(value, \" \")\n\tif len(vals) != 3 {\n\t\treturn\n\t}\n\n\tnumbers := strings.Split(vals[2], \",\")\n\tif len(numbers) != 6 {\n\t\tfmt.Printf(\"wrong lotto results format: %s\\n\", vals[2])\n\t\treturn\n\t}\n\n\tresult = make([]mapreduce.KeyValue, 0, 6)\n\tfor _, w := range numbers {\n\t\tresult = append(result, mapreduce.KeyValue{Key: w, Value: strconv.Itoa(1)})\n\t}\n\treturn\n}", "func same(x, y []string) bool {\n\txMap := make(map[string]int)\n\tyMap := make(map[string]int)\n\n\tfor _, xElem := range x {\n\t\txMap[xElem]++\n\t}\n\tfor _, yElem := range y {\n\t\tyMap[yElem]++\n\t}\n\n\tfor xMapKey, xMapVal := range xMap {\n\t\tif yMap[xMapKey] != xMapVal {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func processMap(name string, arr map[string]interface{}, value proto.Message) (reflect.Value, *adapter.ConfigErrors) {\n\tvar ce *adapter.ConfigErrors\n\tptrType := reflect.TypeOf(value)\n\tvalueType := reflect.Indirect(reflect.ValueOf(value)).Type()\n\toutmap := reflect.MakeMap(reflect.MapOf(reflect.ValueOf(\"\").Type(), ptrType))\n\tfor vname, val := range arr {\n\t\tdm := reflect.New(valueType).Interface().(proto.Message)\n\t\tif cerr := updateMsg(fmt.Sprintf(\"%s[%s]\", name, vname), val, dm, value, false); cerr != nil {\n\t\t\tce = ce.Extend(cerr)\n\t\t\tcontinue\n\t\t}\n\t\toutmap.SetMapIndex(reflect.ValueOf(vname), reflect.ValueOf(dm))\n\t}\n\treturn outmap, ce\n}", "func set(a []string) map[string]bool {\n\tr := map[string]bool{}\n\tfor _, k := range a {\n\t\tr[k] = true\n\t}\n\treturn r\n}", "func copyParams(r *http.Request) map[string]string {\n\tparamMap := make(map[string]string)\n\n\tfor k, v := range r.Form {\n\t\tparamMap[k] = v[0]\n\t}\n\n\treturn paramMap\n}", "func PopulateTools() (tls map[string] tool.Tool){\n\n tls = make(map[string]tool.Tool,1)\n\n t := &tool.RemoveDuplicates{}\n tls[t.Name()] = t\n\n // Add another\n //t = tools.<Name of tool>{}\n //tls.put[t.Name()] = t\n return tls\n}", "func generateMinerIDs() map[string]*minerIDPair {\n\tids := make(map[string]*minerIDPair)\n\tcpu := newMinerIDPair(cpuID, CPU)\n\tobelisk := newMinerIDPair(dcr1ID, ObeliskDCR1)\n\tinnosilicon := newMinerIDPair(d9ID, InnosiliconD9)\n\tantminer := newMinerIDPair(dr3ID, AntminerDR3, AntminerDR5)\n\twhatsminer := newMinerIDPair(d1ID, WhatsminerD1)\n\tnicehash := newMinerIDPair(nhID, NiceHashValidator)\n\n\tids[cpu.id] = cpu\n\tids[obelisk.id] = obelisk\n\tids[innosilicon.id] = innosilicon\n\tids[antminer.id] = antminer\n\tids[whatsminer.id] = whatsminer\n\tids[nicehash.id] = nicehash\n\treturn ids\n}", "func (sl *Slice) UniqueNameToIndexMap() map[string]int {\n\tif len(*sl) == 0 {\n\t\treturn nil\n\t}\n\tnim := make(map[string]int, len(*sl))\n\tfor i, kid := range *sl {\n\t\tnim[kid.UniqueName()] = i\n\t}\n\treturn nim\n}", "func mapTags(tags []*elb.Tag) map[string]string {\n\ttagMap := make(map[string]string)\n\tfor _, t := range tags {\n\t\ttagMap[*t.Key] = *t.Value\n\t}\n\n\treturn tagMap\n}", "func createParamsMap(params []TrafficOpsParameter) map[string]map[string]string {\n\tm := make(map[string]map[string]string)\n\tfor _, param := range params {\n\t\tif m[param.ConfigFile] == nil {\n\t\t\tm[param.ConfigFile] = make(map[string]string)\n\t\t}\n\t\tm[param.ConfigFile][param.Name] = param.Value\n\t}\n\treturn m\n}", "func runemap(rs []rune) map[rune]struct{} {\n\tm := make(map[rune]struct{})\n\tfor _, r := range rs {\n\t\tm[r] = struct{}{}\n\t}\n\treturn m\n}", "func hasDup(m map[string]string) bool {\n\tvals := make(map[string]bool, len(m))\n\tfor _, v := range m {\n\t\tif vals[v] {\n\t\t\treturn true\n\t\t}\n\t\tvals[v] = true\n\t}\n\treturn false\n}", "func runStringToIntMap() {\n\tvar string2IntMap = make(String2IntMap, 5)\n\tstring2IntMap[\"USA\"] = 100\n\tstring2IntMap[\"China\"] = 200\n\tfmt.Printf(\"Map says %d \\r\\n\", len(string2IntMap))\n\tdelete(string2IntMap, \"USA\")\n\tfmt.Printf(\"Map says %d \\r\\n\", len(string2IntMap))\n\tfmt.Printf(\"Map says %d \\r\\n\", string2IntMap[\"USA\"])\n\tfmt.Printf(\"Map says %d \\r\\n\", len(string2IntMap))\n}", "func getSelectorMap(s string) map[string]string {\n\tselector := map[string]string{}\n\tif name := nameRegex.FindString(s); name != \"\" {\n\t\tselector[\"elementName\"] = name\n\t}\n\tif id := idRegex.FindString(s); id != \"\" {\n\t\tselector[\"id\"] = id[1:]\n\t}\n\tif class := classRegex.FindString(s); class != \"\" {\n\t\tselector[\"class\"] = class[1:]\n\t}\n\treturn selector\n}", "func checkMap(treasureMap TreasureMap, startAxis int, staticAxis int, addValue int, typeAxis int) ([2]int, [][2]int) {\n\tvar (\n\t\tcheck = true\n\t\ttreasurePosition [2]int\n\t\tpathPosition [][2]int\n\t\tcurrentPosition [2]int\n\t)\n\tfor check {\n\t\tif typeAxis == axis_x {\n\t\t\tcurrentPosition = [2]int{startAxis, staticAxis}\n\t\t} else {\n\t\t\tcurrentPosition = [2]int{staticAxis, startAxis}\n\t\t}\n\n\t\tif check {\n\t\t\tswitch treasureMap.OriginalMapping[currentPosition] {\n\t\t\tcase entity_path:\n\t\t\t\tpathPosition = append(pathPosition, currentPosition)\n\t\t\tcase entity_treasure:\n\t\t\t\ttreasurePosition = currentPosition\n\t\t\tcase entity_obstacle:\n\t\t\t\tcheck = false\n\t\t\tdefault:\n\t\t\t\tcheck = false\n\t\t\t}\n\t\t}\n\t\tstartAxis += addValue\n\t}\n\n\treturn treasurePosition, pathPosition\n}", "func mapsTest() {\n\tm1 := make(map[string]string) //using var m1 map[string]string will not initialise the hash - cannot assign!\n\tm2 := map[string]int{\"test\": 0} //map literal\n\tm1[\"hello\"] = \"world\" //assignment\n\tdelete(m1, \"hello\") //deletion\n\tv, p := m2[\"none\"] //double assignment - v is value, p is a boolean indicating presence of key\n\tfmt.Println(v, p) //v is null and p is false\n\tfor key, value := range m1 {\n\t\t_, _ = key, value //dosomething\n\t}\n}", "func Map(vars ...Variable) map[string]interface{} {\n\tresult := map[string]interface{}{}\n\tfor _, v := range vars {\n\t\tresult[(string)(v)] = v.Value()\n\t}\n\treturn result\n}", "func pointyMap() interface{} {\n\treturn map[string]interface{}{\n\t\t\"bar\": map[string]interface{}{\n\t\t\t\"baz\": &b{0, []int{1, 2, 3}},\n\t\t\t\"buzz\": []int{4, 5, 6}},\n\t\t\"baz\": []int{7, 8, 9},\n\t\t\"bazzle\": []string{\"10\", \"11\", \"12\"}}\n}", "func toMap(s *DefaultIDSetMap) map[int]*IDSet {\n\tif s.key != 0 {\n\t\treturn map[int]*IDSet{\n\t\t\ts.key: s.value,\n\t\t}\n\t}\n\n\tif s.m != nil {\n\t\tm := map[int]*IDSet{}\n\t\tfor k, v := range s.m {\n\t\t\tm[k] = v\n\t\t}\n\t\treturn m\n\t}\n\n\treturn nil\n}", "func createVoteMapForConflicts(conflictIDs, timestampIDs []string) map[string]opinion.Opinions {\n\tvoteMap := map[string]opinion.Opinions{}\n\n\tfor _, id := range conflictIDs {\n\t\tvoteMap[id] = opinion.Opinions{}\n\t}\n\tfor _, id := range timestampIDs {\n\t\tvoteMap[id] = opinion.Opinions{}\n\t}\n\n\treturn voteMap\n}", "func compare(t *testing.T, have, want []string) {\n\twantMap := make(map[string]bool)\n\tfor _, w := range want {\n\t\twantMap[w] = true\n\t}\n\n\tfor _, h := range have {\n\t\tif !wantMap[h] {\n\t\t\tt.Errorf(\"Extracted extra value: have: %v, want: %v\", h, nil)\n\t\t}\n\n\t\tdelete(wantMap, h)\n\t}\n\n\tfor w := range wantMap {\n\t\tt.Errorf(\"Failed to extract a value: have: %v, want: %v\", nil, w)\n\t}\n}", "func init() {\n\t//hashMap = make(map[crypto.Hash]FuncHash)\n\t//hashMap[crypto.MD5] = _md5\n\t//hashMap[crypto.Sha1] = _sha1\n\t//hashMap[crypto.SHA224] = _sha224\n\t//hashMap[crypto.SHA256] = _sha256\n\t//hashMap[crypto.SHA384] = _sha384\n\t//hashMap[crypto.SHA512] = _sha512\n\t//hashMap[crypto.SHA512_224] = _sha512_224\n\t//hashMap[crypto.SHA512_256] = _sha512_256\n\t//hashMap[crypto.RIPEMD160] = _ripemd160\n\t//hashMap[crypto.SHA3_224] = _sha3_224\n\t//hashMap[crypto.SHA3_256] = _sha3_256\n\t//hashMap[crypto.SHA3_384] = _sha3_384\n\t//hashMap[crypto.SHA3_512] = _sha3_512\n\t//hashMap[crypto.BLAKE2s_256] = _blake2s_256\n\t//hashMap[crypto.BLAKE2b_256] = _blake2b_256\n\t//hashMap[crypto.BLAKE2b_384] = _blake2b_384\n\t//hashMap[crypto.BLAKE2b_512] = _blake2b_512\n}", "func init() {\n\tSliceOfString = make([]string, 0, 10)\n\tMapOfString = make(map[string]string)\n\tMapOfBool = make(map[string]bool)\n}", "func createParamsMap(params []string) *map[string]string {\n\n\tparamsMap := map[string]string{}\n\n\tfor _, param := range params {\n\t\tkeyval := strings.Split(param, \"=\")\n\t\tif len(keyval) == 0 || len(keyval) > 2 {\n\t\t\tcontinue // weird but skip\n\t\t}\n\t\tif len(keyval) == 1 {\n\t\t\tparamsMap[strings.TrimSpace(keyval[0])] = \"\" // no value\n\t\t\tcontinue\n\t\t}\n\t\tparamsMap[strings.TrimSpace(keyval[0])] = strings.TrimSpace(keyval[1])\n\t}\n\tif len(paramsMap) < 1 {\n\t\treturn nil\n\t}\n\treturn &paramsMap\n\n}", "func (inputs *input) validateInputs() error {\n\n\tif _, ok := howMap[inputs.how]; !ok {\n\t\treturn fmt.Errorf(\"how option is invalid\")\n\t}\n\n\tlog.Printf(\"Got Inputs : %+v\", inputs)\n\n\treturn nil\n}", "func NASSCropMap() map[string]Crop {\r\n\tm := make(map[string]Crop)\r\n\r\n\tm[\"1\"] = BuildCrop(1, \"Corn\")\r\n\tm[\"2\"] = BuildCrop(2, \"Cotton\")\r\n\tm[\"3\"] = BuildCrop(3, \"Rice\")\r\n\tm[\"4\"] = BuildCrop(4, \"Sorghum\")\r\n\tm[\"5\"] = BuildCrop(5, \"Soybeans\")\r\n\tm[\"6\"] = BuildCrop(6, \"Sunflower\")\r\n\tm[\"10\"] = BuildCrop(10, \"Peanuts\")\r\n\tm[\"11\"] = BuildCrop(11, \"Tobacco\")\r\n\tm[\"12\"] = BuildCrop(12, \"Sweet Corn\")\r\n\tm[\"13\"] = BuildCrop(13, \"Pop or Orn Corn\")\r\n\tm[\"14\"] = BuildCrop(14, \"Mint\")\r\n\tm[\"21\"] = BuildCrop(21, \"Barley\")\r\n\tm[\"22\"] = BuildCrop(22, \"Durum Wheat\")\r\n\tm[\"23\"] = BuildCrop(23, \"Spring Wheat\")\r\n\tm[\"24\"] = BuildCrop(24, \"Winter Wheat\")\r\n\tm[\"25\"] = BuildCrop(25, \"Other Small Grains\")\r\n\tm[\"26\"] = BuildCrop(26, \"Dbl Crop WinWht/Soybeans\")\r\n\tm[\"27\"] = BuildCrop(27, \"Rye\")\r\n\tm[\"28\"] = BuildCrop(28, \"Oats\")\r\n\tm[\"29\"] = BuildCrop(29, \"Millet\")\r\n\tm[\"30\"] = BuildCrop(30, \"Speltz\")\r\n\tm[\"31\"] = BuildCrop(31, \"Canola\")\r\n\tm[\"32\"] = BuildCrop(32, \"Flaxseed\")\r\n\tm[\"33\"] = BuildCrop(33, \"Safflower\")\r\n\tm[\"34\"] = BuildCrop(34, \"Rape Seed\")\r\n\tm[\"35\"] = BuildCrop(35, \"Mustard\")\r\n\tm[\"36\"] = BuildCrop(36, \"Alfalfa\")\r\n\tm[\"37\"] = BuildCrop(37, \"Other Hay/Non Alfalfa\")\r\n\tm[\"38\"] = BuildCrop(38, \"Camelina\")\r\n\tm[\"39\"] = BuildCrop(39, \"Buckwheat\")\r\n\tm[\"41\"] = BuildCrop(41, \"Sugarbeets\")\r\n\tm[\"42\"] = BuildCrop(42, \"Dry Beans\")\r\n\tm[\"43\"] = BuildCrop(43, \"Potatoes\")\r\n\tm[\"44\"] = BuildCrop(44, \"Other Crops\")\r\n\tm[\"45\"] = BuildCrop(45, \"Sugarcane\")\r\n\tm[\"46\"] = BuildCrop(46, \"Sweet Potatoes\")\r\n\tm[\"47\"] = BuildCrop(47, \"Misc Vegs & Fruits\")\r\n\tm[\"48\"] = BuildCrop(48, \"Watermelons\")\r\n\tm[\"49\"] = BuildCrop(49, \"Onions\")\r\n\tm[\"50\"] = BuildCrop(50, \"Cucumbers\")\r\n\tm[\"51\"] = BuildCrop(51, \"Chick Peas\")\r\n\tm[\"52\"] = BuildCrop(52, \"Lentils\")\r\n\tm[\"53\"] = BuildCrop(53, \"Peas\")\r\n\tm[\"54\"] = BuildCrop(54, \"Tomatoes\")\r\n\tm[\"55\"] = BuildCrop(55, \"Caneberries\")\r\n\tm[\"56\"] = BuildCrop(56, \"Hops\")\r\n\tm[\"57\"] = BuildCrop(57, \"Herbs\")\r\n\tm[\"58\"] = BuildCrop(58, \"Clover/Wildflowers\")\r\n\tm[\"59\"] = BuildCrop(59, \"Sod/Grass Seed\")\r\n\tm[\"60\"] = BuildCrop(60, \"Switchgrass\")\r\n\tm[\"61\"] = BuildCrop(61, \"Fallow/Idle Cropland\")\r\n\tm[\"63\"] = BuildCrop(63, \"Forest\")\r\n\tm[\"64\"] = BuildCrop(64, \"Shrubland\")\r\n\tm[\"65\"] = BuildCrop(65, \"Barren\")\r\n\tm[\"66\"] = BuildCrop(66, \"Cherries\")\r\n\tm[\"67\"] = BuildCrop(67, \"Peaches\")\r\n\tm[\"68\"] = BuildCrop(68, \"Apples\")\r\n\tm[\"69\"] = BuildCrop(69, \"Grapes\")\r\n\tm[\"70\"] = BuildCrop(70, \"Christmas Trees\")\r\n\tm[\"71\"] = BuildCrop(71, \"Other Tree Crops\")\r\n\tm[\"72\"] = BuildCrop(72, \"Citrus\")\r\n\tm[\"74\"] = BuildCrop(74, \"Pecans\")\r\n\tm[\"75\"] = BuildCrop(75, \"Almonds\")\r\n\tm[\"76\"] = BuildCrop(76, \"Walnuts\")\r\n\tm[\"77\"] = BuildCrop(77, \"Pears\")\r\n\tm[\"92\"] = BuildCrop(92, \"Aquaculture\")\r\n\tm[\"152\"] = BuildCrop(152, \"Shrubland\")\r\n\tm[\"204\"] = BuildCrop(204, \"Pistachios\")\r\n\tm[\"205\"] = BuildCrop(205, \"Triticale\")\r\n\tm[\"206\"] = BuildCrop(206, \"Carrots\")\r\n\tm[\"207\"] = BuildCrop(207, \"Asparagus\")\r\n\tm[\"208\"] = BuildCrop(208, \"Garlic\")\r\n\tm[\"209\"] = BuildCrop(209, \"Cantaloupes\")\r\n\tm[\"210\"] = BuildCrop(210, \"Prunes\")\r\n\tm[\"211\"] = BuildCrop(211, \"Olives\")\r\n\tm[\"212\"] = BuildCrop(212, \"Oranges\")\r\n\tm[\"213\"] = BuildCrop(213, \"Honeydew Melons\")\r\n\tm[\"214\"] = BuildCrop(214, \"Broccoli\")\r\n\tm[\"215\"] = BuildCrop(215, \"Avocados\")\r\n\tm[\"216\"] = BuildCrop(216, \"Peppers\")\r\n\tm[\"217\"] = BuildCrop(217, \"Pomegranates\")\r\n\tm[\"218\"] = BuildCrop(218, \"Nectarines\")\r\n\tm[\"219\"] = BuildCrop(219, \"Greens\")\r\n\tm[\"220\"] = BuildCrop(220, \"Plums\")\r\n\tm[\"221\"] = BuildCrop(221, \"Strawberries\")\r\n\tm[\"222\"] = BuildCrop(222, \"Squash\")\r\n\tm[\"223\"] = BuildCrop(223, \"Apricots\")\r\n\tm[\"224\"] = BuildCrop(224, \"Vetch\")\r\n\tm[\"225\"] = BuildCrop(225, \"Dbl Crop WinWht/Corn\")\r\n\tm[\"226\"] = BuildCrop(226, \"Dbl Crop Oats/Corn\")\r\n\tm[\"227\"] = BuildCrop(227, \"Lettuce\")\r\n\tm[\"228\"] = BuildCrop(228, \"Dbl Crop Triticale/Corn\")\r\n\tm[\"229\"] = BuildCrop(229, \"Pumpkins\")\r\n\tm[\"230\"] = BuildCrop(230, \"Dbl Crop Lettuce/Durum Wheat\")\r\n\tm[\"231\"] = BuildCrop(231, \"Dbl Crop Lettuce/Cantaloupe\")\r\n\tm[\"232\"] = BuildCrop(232, \"Dbl Crop Lettuce/Cotton\")\r\n\tm[\"233\"] = BuildCrop(233, \"Dbl Crop Lettuce/Barley\")\r\n\tm[\"234\"] = BuildCrop(234, \"Dbl Crop Durum Wht/Sorghum\")\r\n\tm[\"235\"] = BuildCrop(235, \"Dbl Crop Barley/Sorghum\")\r\n\tm[\"236\"] = BuildCrop(236, \"Dbl Crop WinWht/Sorghum\")\r\n\tm[\"237\"] = BuildCrop(237, \"Dbl Crop Barley/Corn\")\r\n\tm[\"238\"] = BuildCrop(238, \"Dbl Crop WinWht/Cotton\")\r\n\tm[\"239\"] = BuildCrop(239, \"Dbl Crop Soybeans/Cotton\")\r\n\tm[\"240\"] = BuildCrop(240, \"Dbl Crop Soybeans/Oats\")\r\n\tm[\"241\"] = BuildCrop(241, \"Dbl Crop Corn/Soybeans\")\r\n\tm[\"242\"] = BuildCrop(242, \"Blueberries\")\r\n\tm[\"243\"] = BuildCrop(243, \"Cabbage\")\r\n\tm[\"244\"] = BuildCrop(244, \"Cauliflower\")\r\n\tm[\"245\"] = BuildCrop(245, \"Celery\")\r\n\tm[\"246\"] = BuildCrop(246, \"Radishes\")\r\n\tm[\"247\"] = BuildCrop(247, \"Turnips\")\r\n\tm[\"248\"] = BuildCrop(248, \"Eggplants\")\r\n\tm[\"249\"] = BuildCrop(249, \"Gourds\")\r\n\tm[\"250\"] = BuildCrop(250, \"Cranberries\")\r\n\tm[\"254\"] = BuildCrop(254, \"Dbl Crop Barley/Soybeans\")\r\n\treturn m\r\n}", "func (elems *Elements) add(toAdd Elements) {\n\temap := make(map[string]int)\n\tfor i, elem := range *elems {\n\t\temap[elem.Pos.MapKey()] = i\n\t}\n\tfor _, elem := range toAdd {\n\t\ti, found := emap[elem.Pos.MapKey()]\n\t\tif !found {\n\t\t\t*elems = append(*elems, elem)\n\t\t} else {\n\t\t\t(*elems)[i] = elem\n\t\t}\n\t}\n}", "func newMapCache(dss map[string]rrd.DataSourcer) *mapCache {\n\tmc := &mapCache{make(map[string]int64), make(map[int64]rrd.DataSourcer)}\n\tvar n int64\n\tfor name, ds := range dss {\n\t\tmc.byName[name] = n\n\t\tmc.byId[n] = ds\n\t\tn++\n\t}\n\treturn mc\n}", "func addMap(a, b map[string]interface{}) map[string]interface{} {\n\tc := map[string]interface{}{}\n\tfor k, v := range a {\n\t\tc[k] = v\n\t}\n\tfor k, v := range b {\n\t\tc[k] = v\n\t}\n\treturn c\n}", "func main () {\n\t/*name := utilidades.GetName()\n\tLasName := \"Boso\"\n\tvar miNumero = utilidades.Suma(40, 60)\n\tx, y, z := utilidades.GetMultiplesVariables()\n\tdecimal32, decimal64 := utilidades.GetDecimal()\n\n\thola := \"Hola\"\n\n\t\n\tfmt.Println(\"hola \", name)\n\tfmt.Printf(holaMundo, name, LasName)\n\tfmt.Println(\"\")\n\tfmt.Println(miNumero, x, y ,z)\n\t\n\tfmt.Println(decimal32, decimal64)\n\n\tfmt.Println(utilidades.GetUnicode())\n\tfmt.Println(string(hola[0]))\n\tfmt.Println(len(hola))\n\tarrays.ImprimeArray()\n\n\tarrays.ImprimirSlice()\n\n\n\tutilidades.Multiplo5()\n\tutilidades.Multiplo5switch()\n\tutilidades.Bucles()\n\toperacionesstrings.OperacionesConStrings()\n\t*/\n\t/*\n\tfmt.Println(maps.GetMap())\n\tfmt.Println(maps.GetKeyMap(\"Casa\"))\n\t*/\n\t/*\n\tvar miVariable structs.Boso = \"Mi propio tipo de dato\"\n\tfmt.Println(miVariable)\n\n\tantonio := structs.Persona {\n\t\tNombre : \"Antonio Jose\",\n\t\tApellido : \"Galisteo Cantero\",\n\t\tDocumentoIdentidad : \"6699\",\n\t\tTelefono : []string {\"111\", \"123\"},\n\t\tDireccion : \"YYYY\",\n\t\tEdad : 30,\n\t}\n\n\tfmt.Println(antonio)\n\n\t\n\tmaria := structs.Persona {\n\t\tNombre : \"Maria\",\n\t\tApellido : \"Alvarado\",\n\t\tDocumentoIdentidad : \"YYY\",\n\t\tTelefono : []string {\"222\", \"345\"},\n\t\tDireccion : \"ZZZZ\",\n\t\tEdad : 31,\n\t}\n\n\tfmt.Println(maria)\n\n\tjorge := new (structs.Persona)\n\tjorge.Nombre = \"Jorge\"\n\tjorge.Apellido = \"Apellidos\"\n\tjorge.DocumentoIdentidad = \"ZZZ\"\n\tjorge.Telefono = []string {\"333\", \"678\"}\n\tjorge.Direccion = \"AAAA\"\n\tjorge.Edad = 31\n\n\tfmt.Println(jorge)\n\tcasa := structs.Casa{\n\t\tNumeroCasa : 1,\n\t\tPersonas : []structs.Persona{antonio, maria, *jorge},\n\n\t}\n\tfmt.Println(casa)\n\n\tcasa.GetNumeroCasa()\n\tcasa.GetPersonasCasa()\n\n\n\n*/\n/*\n\tmiNumero, error := utilidades.Suma(\"60\",40)\n\tif error !=nil {\n\t\tpanic(error)\n\t}\n\n\tfmt.Println(miNumero)\n*/\n\t//punteros()\n\tcanal := make( chan string)\n\tlanzaHilos(300, canal)\n\n\tfor valor := range canal{\n\t\tfmt.Println(valor)\n\t}\n}", "func makeMap(yamlStruct T) map[string]string {\n\turlMap := make(map[string]string)\n\tfor _, s := range yamlStruct {\n\t\turlMap[s.P] = s.U\n\t}\n\treturn urlMap\n}", "func mutatingMaps() {\n\tm := make(map[string]int)\n\tm[\"Answer\"] = 42\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\n\tm[\"Answer\"] = 48\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\n\t// Deleting an element.\n\tdelete(m, \"Answer\")\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\n\t// if key is in m, ok is true. If not, ok is false.\n\tv, ok := m[\"Answer\"]\n\tfmt.Println(\"The value:\", v, \"Present?\", ok)\n}", "func mapBottles(bottles []Bottle) map[uint32]int {\n\tbottleMap := make(map[uint32]int, len(bottles))\n\tfor _, bottle := range bottles {\n\t\t_, ok := bottleMap[bottle.VolumeML]\n\t\tif !ok {\n\t\t\tbottleMap[bottle.VolumeML] = 1\n\t\t\tcontinue\n\t\t}\n\t\tbottleMap[bottle.VolumeML]++\n\t}\n\treturn bottleMap\n}", "func mapDedupe(s []int) []int {\n\tnewS := []int{}\n\tm := make(map[int]bool)\n\tfor _, v := range s {\n\t\tif ok := m[v]; !ok {\n\t\t\tm[v] = true\n\t\t\tnewS = append(newS, v)\n\t\t}\n\t}\n\treturn newS\n}", "func newMap(src *map[string]interface{}) map[string]interface{} {\n\tdst := make(map[string]interface{})\n\tif src == nil {\n\t\treturn dst\n\t}\n\tfor k, v := range *src {\n\t\tif strings.HasPrefix(k, \"_\") {\n\t\t\tcontinue\n\t\t}\n\t\tdst[k] = v\n\t}\n\treturn dst\n}", "func mapCreate(name, rollNo, height, weight, averageMarks, extraCurricularGrade string) map[string]string {\n\tvar mapRet = map[string]string{\n\t\t\"name\": name,\n\t\t\"roll_no\": rollNo,\n\t\t\"weight\": weight,\n\t\t\"height\": height,\n\t\t\"avg_marks\": averageMarks,\n\t\t\"extra_curr_grades\": extraCurricularGrade,\n\t}\n\treturn mapRet\n}", "func Map(args ...interface{}) (map[string]interface{}, error) {\n\tif len(args)%2 != 0 {\n\t\treturn nil, fmt.Errorf(\"expecting even number of arguments, got %d\", len(args))\n\t}\n\n\tm := make(map[string]interface{})\n\tfn := \"\"\n\tfor _, v := range args {\n\t\tif len(fn) == 0 {\n\t\t\tif s, ok := v.(string); ok {\n\t\t\t\tfn = s\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn m, fmt.Errorf(\"expecting string for odd numbered arguments, got %+v\", v)\n\t\t}\n\t\tm[fn] = v\n\t\tfn = \"\"\n\t}\n\n\treturn m, nil\n}", "func (lId *LangId) buildTmpMap() map[string]string {\n\ttmpMap := make(map[string]string)\n\tfor _, name := range lId.varNames {\n\t\ttmpMap[strings.TrimSuffix(name, \":\")] = NA_STR\n\t}\n\treturn tmpMap\n}", "func mapexp() {\n\n\tvar ayam map[string]int\n\tayam = map[string]int{}\n\n\tayam[\"dada\"] = 10\n\tayam[\"paha\"] = 8\n\n\tfmt.Println(\"dada\", ayam[\"dada\"])\n\tfmt.Println(\"paha\", ayam[\"paha\"])\n}", "func keyValOrder(form url.Values, dataFields interface{}) *orderedmap.OrderedMap {\n\n\t//uMap := make(map[string]interface{}, 0)\n\toMap := orderedmap.NewOrderedMap()\n\tiVal := reflect.ValueOf(dataFields).Elem()\n\ttyp := iVal.Type()\n\n\tfor i := 0; i < iVal.NumField(); i++ {\n\n\t\ttag := typ.Field(i).Tag.Get(\"json\")\n\n\t\tvar omitFound bool\n\t\tif strings.Contains(tag, \",\") == true {\n\t\t\tomitFound = true\n\t\t\tcommaFoundAt := strings.Index(tag, \",\")\n\t\t\t//fmt.Println(\"commaFoundAt-->\", commaFoundAt, tag)\n\t\t\ttag = tag[0:commaFoundAt]\n\t\t}\n\n\t\t//ignored omitemty field which has 0 length\n\t\tif omitFound == true && len(form.Get(tag)) == 0 {\n\t\t\toMap.Set(tag, \"\")\n\t\t\t//fmt.Println(\">>\", tag, \"=\", form.Get(tag), omitFound, len(form.Get(tag)))\n\t\t} else {\n\t\t\toMap.Set(tag, form.Get(tag))\n\t\t}\n\t\t//fmt.Println(\">>\", tag, \"=\", form.Get(tag), omitFound, len(form.Get(tag)))\n\t}\n\n\treturn oMap\n}", "func keyGen(items []interface{}, keyable Keyable) map[string]interface{} {\n\tkeyMap := make(map[string]interface{}, len(items))\n\tfor _, item := range items {\n\t\tkey := keyable.Key(item)\n\t\tkeyMap[key] = item\n\t}\n\n\treturn keyMap\n}", "func testMapSetN(n int, m map[Key]interface{}) {\n\tfor i := 0; i < n; i++ {\n\t\tm[Key(i)] = i\n\t}\n}", "func inputAssignMap(ac *app.Config, triggerRef, name string) {\n\t// add the name to all flow resources\n\tprop := map[string]interface{}{\"name\": name, \"type\": \"any\"}\n\tfor _, rc := range ac.Resources {\n\t\tvar jsonobj map[string]interface{}\n\t\tif err := json.Unmarshal(rc.Data, &jsonobj); err != nil {\n\t\t\tlogger.Errorf(\"failed to parse resource data %s: %+v\", rc.ID, err)\n\t\t\tcontinue\n\t\t}\n\t\tif metadata, ok := jsonobj[\"metadata\"]; ok {\n\t\t\tmetaMap := metadata.(map[string]interface{})\n\t\t\tif input, ok := metaMap[\"input\"]; ok {\n\t\t\t\tinputArray := input.([]interface{})\n\t\t\t\tdone := false\n\t\t\t\tfor _, ip := range inputArray {\n\t\t\t\t\tipMap := ip.(map[string]interface{})\n\t\t\t\t\tif ipMap[\"name\"].(string) == name {\n\t\t\t\t\t\tdone = true\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !done {\n\t\t\t\t\tlogger.Debugf(\"add new property %s to resource input of %s\", name, rc.ID)\n\t\t\t\t\tmetaMap[\"input\"] = append(inputArray, prop)\n\t\t\t\t\tif jsonbytes, err := json.Marshal(jsonobj); err == nil {\n\t\t\t\t\t\tlogger.Debugf(\"resource data is updated for %s: %s\", rc.ID, string(jsonbytes))\n\t\t\t\t\t\trc.Data = jsonbytes\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.Debugf(\"failed to serialize resource %s: %+v\", rc.ID, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// add input mapper\n\tfor _, tc := range ac.Triggers {\n\t\tif tc.Ref == triggerRef {\n\t\t\tfor _, hc := range tc.Handlers {\n\t\t\t\tfor _, acc := range hc.Actions {\n\t\t\t\t\tif acc.Ref == \"github.com/project-flogo/flow\" {\n\t\t\t\t\t\t_, done := acc.Input[name]\n\t\t\t\t\t\tif !done {\n\t\t\t\t\t\t\tacc.Input[name] = \"=$.\" + 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 addParamsList(params map[string]string, label string, ids []string) {\n\tfor i, id := range ids {\n\t\tparams[label+\".\"+strconv.Itoa(i+1)] = id\n\t}\n}", "func getDuplication(fiA, fiB *FileInfo) (paths []string) {\n\tallPaths := append(fiA.pathList(), fiB.pathList()...)\n\tcheckMap := make(map[string]bool, len(allPaths))\n\tfor _, p := range allPaths {\n\t\tif _, ok := checkMap[p]; ok {\n\t\t\tpaths = append(paths, p)\n\t\t}\n\t\tcheckMap[p] = true\n\t}\n\treturn paths\n}", "func main() {\n\t/*\n\tmaps are the go variant of dictionaries\n\t\t\t\t\t\tkey val\n\t*/\n\tdict := make(map[string]int)\n\tinput := bufio.NewScanner(os.Stdin)\n\n\tfor input.Scan() {\n\t\tdict[input.Text()]++\n\t\tif dict[input.Text()] > 1{\n\t\t\tfmt.Print(\"\\t\",input.Text(),\" : \",dict[input.Text()],\"\\n\")\n\t\t}\n\t}\n\n\t// LOOPING THROUGH DICTIONARY\n\t//for key,val := range dict {\n\t//\tif val > 1{\n\t//\tfmt.Println(key,\"\\t: \",val)\n\t//\t}\n\t//}\n\n}", "func (ph *processHashtable) getMapping() map[string]*model.Process {\n\tout := make(map[string]*model.Process)\n\tfor _, keys := range ph.processes {\n\t\tfor _, key := range keys {\n\t\t\tout[key.key] = key.process\n\t\t}\n\t}\n\treturn out\n}", "func Map() {\n\t// How to create a map and use it. Map is like dict in python\n\tfmt.Println(\" ***************** STARTING MAPS DEMO NOW *****************\")\n\n\t//M1\n\tvar map1 = make(map[string]int)\n\tmap1[\"Hello\"] = 1\n\tmap1[\"Hi\"] = 2\n\n\t//M2\n\tm2 := map[string]int{\"foo\": 1, \"bar\": 2}\n\n\tfmt.Println(map1) // map[Hello:1 Hi:2]\n\tfmt.Println(m2)\n\n\tfor k, v := range map1 {\n\t\tprintln(k, v)\n\t}\n\n\tdelete(map1, \"Hello\")\n\n\tid, p := map1[\"Hello\"]\n\tprint(id, p) // 0, false because we deleted hello from the map\n\n\tfmt.Println(\"\\n ***************** ENDING MAPS DEMO NOW *****************\")\n\n}", "func (elems *ElementsNR) add(toAdd ElementsNR) {\n\temap := make(map[string]int)\n\tfor i, elem := range *elems {\n\t\temap[elem.Pos.MapKey()] = i\n\t}\n\tfor _, elem := range toAdd {\n\t\ti, found := emap[elem.Pos.MapKey()]\n\t\tif !found {\n\t\t\t*elems = append(*elems, elem)\n\t\t} else {\n\t\t\t(*elems)[i] = elem\n\t\t}\n\t}\n}", "func getMapKeys(res map[string]bool) []string {\n\tkeys := make([]string, len(res))\n\ti := 0\n\tfor key, _ := range res {\n\t\tkeys[i] = key\n\t\ti++\n\t}\n\treturn keys\n}", "func Maps() {\n\t// maps use the builtin function make to instanciate it.\n\t// you give it a index type or key type\n\t// and you give it a value type.\n\tvar m = make(map[string]int)\n\n\t// you use the index type to set the values of the map\n\tm[\"a\"] = 43\n\tm[\"b\"] = 56\n\n\t// you can use the builtin len function to get the length of a map\n\tfmt.Println(m, len(m))\n\n\t// use the builtin delete function to delete an entry on a map\n\tdelete(m, \"b\")\n\n\tfmt.Println(m)\n\n\t// if you address a key that doesnt exist the value will be the zero value of the value type.\n\tn := m[\"nothing\"]\n\n\tfmt.Println(m, n)\n\n\t// if you want to see if an index didnt exist you can use the multi return value\n\t// where 'value' is the value of the element and 'ok' is if it exists or not (boolean eg true or false)\n\tvalue, ok := m[\"a\"]\n\n\tfmt.Println(value, \"and\", ok)\n\n\tnothing, test := m[\"hello\"]\n\n\tfmt.Println(nothing, \"and\", test)\n}", "func (p Doc) Map() map[string]string {\n\tm := make(map[string]string)\n\n\tp.Foreach(func(v, k string) bool { m[k] = v; return true })\n\n\treturn m\n}", "func (r *resolver) calculateUniqueParameterNames() []string {\n\tset := map[string]struct{}{\"\": {}}\n\tnames := []string{}\n\tfor _, intrinsics := range [][]*sem.Intrinsic{\n\t\tr.s.Builtins,\n\t\tr.s.UnaryOperators,\n\t\tr.s.BinaryOperators,\n\t\tr.s.ConstructorsAndConverters,\n\t} {\n\t\tfor _, i := range intrinsics {\n\t\t\tfor _, o := range i.Overloads {\n\t\t\t\tfor _, p := range o.Parameters {\n\t\t\t\t\tif _, dup := set[p.Name]; !dup {\n\t\t\t\t\t\tset[p.Name] = struct{}{}\n\t\t\t\t\t\tnames = append(names, p.Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tsort.Strings(names)\n\treturn names\n}", "func TestDecompositionMultiMapSameValue(t *testing.T) {\n\tfoo := \"foo\"\n\tbar := \"bar\"\n\tm1 := make(map[string]*string)\n\tm1[foo] = &bar\n\tm2 := make(map[string]*string)\n\tm2[foo] = &bar\n\ts := NewScanner(nil).WithParallism(6)\n\n\t// add \"foo\", ptr to \"bar\", \"bar\" and the map\n\ts.decompose(context.Background(), nil, reflect.ValueOf(m1), nil)\n\tassert.Len(t, s.nodes, 4)\n\t// add new map m2 and another instance of \"foo\"\n\t// pointer and bar are shared\n\ts.decompose(context.Background(), nil, reflect.ValueOf(m2), nil)\n\tassert.Len(t, s.nodes, 4+2)\n\n\t// if just shallow copy the map, should not add anything as the map\n\t// itself is also a reference\n\tm3 := m1\n\ts.decompose(context.Background(), nil, reflect.ValueOf(m3), nil)\n\tassert.Len(t, s.nodes, 4+2+0)\n}", "func f1() {\n\tvar lmap map[string]bool\n\tfmt.Printf(\"%d\\n\", len(gmap)+1) // 1\n\tfmt.Printf(\"%d\\n\", len(lmap)+2) // 2\n}", "func validateNominees(i interface{}) error {\n\tconst paramName = \"nominees\"\n\n\tv, ok := i.([]string)\n\tif !ok {\n\t\treturn fmt.Errorf(\"%s param: invalid type: %T\", paramName, i)\n\t}\n\n\tnomineeSet := make(map[string]struct{})\n\tfor _, nominee := range v {\n\t\tif _, found := nomineeSet[nominee]; found {\n\t\t\treturn fmt.Errorf(\"%s param: nominee (%s): duplicated\", paramName, nominee)\n\t\t}\n\t\tnomineeSet[nominee] = struct{}{}\n\n\t\tif _, err := sdk.AccAddressFromBech32(nominee); err != nil {\n\t\t\treturn fmt.Errorf(\"%s param: nominee (%s): invalid Bech32 accAddress: %w\", paramName, nominee, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func buildPathsMap(pTUrl []PathURL) map[string]string {\n\tpTUrls := make(map[string]string)\n\tfor _, pu := range pTUrl {\n\t\tpTUrls[pu.Path] = pu.URL\n\t}\n\treturn pTUrls\n}", "func toSet(list []string) map[string]struct{} {\n\tset := make(map[string]struct{})\n\tfor _, item := range list {\n\t\tset[item] = struct{}{}\n\t}\n\treturn set\n}", "func getMetricDataToShow(metricsData map[string][]metricSource.MetricData, metricsWhitelist []string) map[string][]metricSource.MetricData {\n\tresult := make(map[string][]metricSource.MetricData)\n\tif len(metricsWhitelist) == 0 {\n\t\treturn metricsData\n\t}\n\tmetricsWhitelistHash := make(map[string]bool, len(metricsWhitelist))\n\tfor _, whiteListed := range metricsWhitelist {\n\t\tmetricsWhitelistHash[whiteListed] = true\n\t}\n\n\tfor targetName, metrics := range metricsData {\n\t\tnewMetricsData := make([]metricSource.MetricData, 0, len(metricsWhitelist))\n\t\tif len(metrics) == 1 {\n\t\t\tresult[targetName] = metrics\n\t\t\tcontinue\n\t\t}\n\t\tfor _, metricData := range metrics {\n\t\t\tif _, ok := metricsWhitelistHash[metricData.Name]; ok {\n\t\t\t\tnewMetricsData = append(newMetricsData, metricData)\n\t\t\t}\n\t\t}\n\t\tresult[targetName] = newMetricsData\n\t}\n\treturn result\n}", "func NamesMap() map[string]uint32 {\n\treturn map[string]uint32{\n\t\t\"int\": 0xa8509bda,\n\t\t\"long\": 0x22076cba,\n\t\t\"double\": 0x2210c154,\n\t\t\"string\": 0xb5286e24,\n\t\t\"bytes\": 0xe937bb82,\n\t\t\"boolFalse\": 0xbc799737,\n\t\t\"boolTrue\": 0x997275b5,\n\t\t\"true\": 0x3fedd339,\n\t\t\"decryptedMessage8\": 0x1f814f1f,\n\t\t\"decryptedMessageService8\": 0xaa48327d,\n\t\t\"decryptedMessageMediaEmpty\": 0x89f5c4a,\n\t\t\"decryptedMessageMediaPhoto23\": 0x32798a8c,\n\t\t\"decryptedMessageMediaVideo8\": 0x4cee6ef3,\n\t\t\"decryptedMessageMediaGeoPoint\": 0x35480a59,\n\t\t\"decryptedMessageMediaContact\": 0x588a0a97,\n\t\t\"decryptedMessageActionSetMessageTTL\": 0xa1733aec,\n\t\t\"decryptedMessageMediaDocument23\": 0xb095434b,\n\t\t\"decryptedMessageMediaAudio8\": 0x6080758f,\n\t\t\"decryptedMessageActionReadMessages\": 0xc4f40be,\n\t\t\"decryptedMessageActionDeleteMessages\": 0x65614304,\n\t\t\"decryptedMessageActionScreenshotMessages\": 0x8ac1f475,\n\t\t\"decryptedMessageActionFlushHistory\": 0x6719e45c,\n\t\t\"decryptedMessage23\": 0x204d3878,\n\t\t\"decryptedMessageService\": 0x73164160,\n\t\t\"decryptedMessageMediaVideo23\": 0x524a415d,\n\t\t\"decryptedMessageMediaAudio\": 0x57e0a9cb,\n\t\t\"decryptedMessageLayer\": 0x1be31789,\n\t\t\"sendMessageTypingAction\": 0x16bf744e,\n\t\t\"sendMessageCancelAction\": 0xfd5ec8f5,\n\t\t\"sendMessageRecordVideoAction\": 0xa187d66f,\n\t\t\"sendMessageUploadVideoAction\": 0x92042ff7,\n\t\t\"sendMessageRecordAudioAction\": 0xd52f73f7,\n\t\t\"sendMessageUploadAudioAction\": 0xe6ac8a6f,\n\t\t\"sendMessageUploadPhotoAction\": 0x990a3c1a,\n\t\t\"sendMessageUploadDocumentAction\": 0x8faee98e,\n\t\t\"sendMessageGeoLocationAction\": 0x176f8ba1,\n\t\t\"sendMessageChooseContactAction\": 0x628cbc6f,\n\t\t\"decryptedMessageActionResend\": 0x511110b0,\n\t\t\"decryptedMessageActionNotifyLayer\": 0xf3048883,\n\t\t\"decryptedMessageActionTyping\": 0xccb27641,\n\t\t\"decryptedMessageActionRequestKey\": 0xf3c9611b,\n\t\t\"decryptedMessageActionAcceptKey\": 0x6fe1735b,\n\t\t\"decryptedMessageActionAbortKey\": 0xdd05ec6b,\n\t\t\"decryptedMessageActionCommitKey\": 0xec2e0b9b,\n\t\t\"decryptedMessageActionNoop\": 0xa82fdd63,\n\t\t\"documentAttributeImageSize\": 0x6c37c15c,\n\t\t\"documentAttributeAnimated\": 0x11b58939,\n\t\t\"documentAttributeSticker23\": 0xfb0a5727,\n\t\t\"documentAttributeVideo\": 0x5910cccb,\n\t\t\"documentAttributeAudio23\": 0x51448e5,\n\t\t\"documentAttributeFilename\": 0x15590068,\n\t\t\"photoSizeEmpty\": 0xe17e23c,\n\t\t\"photoSize\": 0x77bfb61b,\n\t\t\"photoCachedSize\": 0xe9a734fa,\n\t\t\"fileLocationUnavailable\": 0x7c596b46,\n\t\t\"fileLocation\": 0x53d69076,\n\t\t\"decryptedMessageMediaExternalDocument\": 0xfa95b0dd,\n\t\t\"documentAttributeAudio45\": 0xded218e0,\n\t\t\"decryptedMessage46\": 0x36b091de,\n\t\t\"decryptedMessageMediaPhoto\": 0xf1fa8d78,\n\t\t\"decryptedMessageMediaVideo\": 0x970c8c0e,\n\t\t\"decryptedMessageMediaDocument\": 0x7afe8ae2,\n\t\t\"documentAttributeSticker\": 0x3a556302,\n\t\t\"documentAttributeAudio\": 0x9852f9c6,\n\t\t\"messageEntityUnknown\": 0xbb92ba95,\n\t\t\"messageEntityMention\": 0xfa04579d,\n\t\t\"messageEntityHashtag\": 0x6f635b0d,\n\t\t\"messageEntityBotCommand\": 0x6cef8ac7,\n\t\t\"messageEntityUrl\": 0x6ed02538,\n\t\t\"messageEntityEmail\": 0x64e475c2,\n\t\t\"messageEntityBold\": 0xbd610bc9,\n\t\t\"messageEntityItalic\": 0x826f8b60,\n\t\t\"messageEntityCode\": 0x28a20571,\n\t\t\"messageEntityPre\": 0x73924be0,\n\t\t\"messageEntityTextUrl\": 0x76a6d327,\n\t\t\"messageEntityMentionName\": 0x352dca58,\n\t\t\"messageEntityPhone\": 0x9b69e34b,\n\t\t\"messageEntityCashtag\": 0x4c4e743f,\n\t\t\"messageEntityBankCard\": 0x761e6af4,\n\t\t\"inputStickerSetShortName\": 0x861cc8a0,\n\t\t\"inputStickerSetEmpty\": 0xffb62b95,\n\t\t\"decryptedMessageMediaVenue\": 0x8a0df56f,\n\t\t\"decryptedMessageMediaWebPage\": 0xe50511d8,\n\t\t\"sendMessageRecordRoundAction\": 0x88f27fbc,\n\t\t\"sendMessageUploadRoundAction\": 0xbb718624,\n\t\t\"documentAttributeVideo66\": 0xef02ce6,\n\t\t\"decryptedMessage\": 0x91cc4674,\n\t\t\"messageEntityUnderline\": 0x9c4e7e8b,\n\t\t\"messageEntityStrike\": 0xbf0693d4,\n\t\t\"messageEntityBlockquote\": 0x20df5d0,\n\t\t\"test.dummyFunction\": 0xc8357709,\n\t}\n}", "func buildSynonyms(a *Parser) map[string]string {\n\tsynonyms := make(map[string]string)\n\tfor _, n := range a.seq {\n\t\tp := a.params[n]\n\t\tif n == p.name {\n\t\t\tif len(n) == 0 {\n\t\t\t\tsynonyms[n] = \"(nameless)\"\n\t\t\t} else {\n\t\t\t\tsynonyms[n] = n\n\t\t\t}\n\t\t} else {\n\t\t\tsynonyms[p.name] += \", \" + n\n\t\t}\n\t}\n\treturn synonyms\n}", "func parseToMap(input string) map[string]string {\n\n\tflagMap := make(map[string]string)\n\tdoParse(input, func(flag, key, canonicalKey, value, trimmedValue string) {\n\t\t// We store the value twice, once with dash, once with underscores\n\t\t// Just in case people check with the wrong method\n\t\tflagMap[canonicalKey] = trimmedValue\n\t\tflagMap[key] = trimmedValue\n\t})\n\n\treturn flagMap\n}", "func fillMessageMaps(whichMap string) {\n\tswitch whichMap {\n\tcase \"hotdog\":\n\t\tfor x := 0; x < len(theMessageBoardHDog.AllOriginalMessages); x++ {\n\t\t\tloadedMessagesMapHDog[x+1] = theMessageBoardHDog.AllOriginalMessages[x]\n\t\t}\n\t\tbreak\n\tcase \"hamburger\":\n\t\tfor x := 0; x < len(theMessageBoardHam.AllOriginalMessages); x++ {\n\t\t\tloadedMessagesMapHam[x+1] = theMessageBoardHam.AllOriginalMessages[x]\n\t\t}\n\t\tbreak\n\tdefault:\n\t\terr := \"Wrong 'whichMap' entered in fillMessageMaps: \" + whichMap\n\t\tfmt.Println(err)\n\t\tlogWriter(err)\n\t\tbreak\n\t}\n}", "func imageNamesMapping() map[string]string {\n\n\tswitch getTestArch() {\n\tcase \"s390x\":\n\t\treturn map[string]string{\n\t\t\t\"registry\": getTestImage(registryImage),\n\t\t\t\"node\": \"node:alpine3.11\",\n\t\t\t\"gcr.io/cloud-builders/git\": \"alpine/git:latest\",\n\t\t\t\"docker:dind\": \"ibmcom/docker-s390x:dind\",\n\t\t\t\"docker\": \"docker:18.06.3\",\n\t\t\t\"mikefarah/yq:3\": \"danielxlee/yq:2.4.0\",\n\t\t\t\"stedolan/jq\": \"ibmcom/jq-s390x:latest\",\n\t\t\t\"gcr.io/kaniko-project/executor:v1.3.0\": getTestImage(kanikoImage),\n\t\t}\n\tcase \"ppc64le\":\n\t\treturn map[string]string{\n\t\t\t\"registry\": getTestImage(registryImage),\n\t\t\t\"node\": \"node:alpine3.11\",\n\t\t\t\"gcr.io/cloud-builders/git\": \"alpine/git:latest\",\n\t\t\t\"docker:dind\": \"ibmcom/docker-ppc64le:19.03-dind\",\n\t\t\t\"docker\": \"docker:18.06.3\",\n\t\t\t\"mikefarah/yq:3\": \"danielxlee/yq:2.4.0\",\n\t\t\t\"stedolan/jq\": \"ibmcom/jq-ppc64le:latest\",\n\t\t\t\"gcr.io/kaniko-project/executor:v1.3.0\": getTestImage(kanikoImage),\n\t\t}\n\n\t}\n\n\treturn make(map[string]string)\n}", "func getEntriesMap(a string) (map[string]int, error) {\n\tresult := make(map[string]int)\n\tfile, err := afs.Open(a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\tfor s, header, i := bufio.NewScanner(file), true, -1; s.Scan(); header = false {\n\t\t// Find correct row if len() > 1 and check for ambiguities\n\t\tif header {\n\t\t\tfor k, v := range strings.Split(s.Text(), \",\") {\n\t\t\t\tif v == headerName {\n\t\t\t\t\tif i < 0 {\n\t\t\t\t\t\ti = k\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfile.Close()\n\t\t\t\t\t\treturn nil,\n\t\t\t\t\t\t\tfmt.Errorf(multipleHeaderErr,\n\t\t\t\t\t\t\t\ta, headerName)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif i < 0 {\n\t\t\t\treturn nil, fmt.Errorf(headerNotFoundErr, headerName, a)\n\t\t\t}\n\t\t\tcontinue // don't want to add header to result\n\t\t}\n\t\tif v := strings.Split(s.Text(), \",\"); len(v) > i {\n\t\t\t// Ignoring what are presumably null values (discuss?)\n\t\t\tif v[i] != \"\\\"\\\"\" {\n\t\t\t\tresult[v[i]]++\n\t\t\t}\n\t\t}\n\t}\n\treturn result, nil\n}", "func UseInterface() {\n\ti1 := map[string]interface{}{\n\t\t\"id\": 1111,\n\t\t\"name\": \"Toran\",\n\t\t\"interests\": []interface{}{\n\t\t\t\"technology\",\n\t\t\t\"trekking\",\n\t\t\t\"biking\",\n\t\t},\n\t\t\"extra\": map[string]interface{}{\n\t\t\t\"edu\": \"graduation\",\n\t\t},\n\t}\n\tfmt.Println(i1)\n\n\ti2 := []interface{}{\n\t\tmap[string]interface{}{\n\t\t\t\"id\": 1111,\n\t\t\t\"name\": \"Toran\",\n\t\t},\n\t\tmap[string]interface{}{\n\t\t\t\"id\": 1112,\n\t\t\t\"name\": \"Abhishek\",\n\t\t},\n\t}\n\tfmt.Println(i2)\n}", "func getImagesMappingRE() map[*regexp.Regexp][]byte {\n\timageNamesMapping := imageNamesMapping()\n\timageMappingRE := make(map[*regexp.Regexp][]byte, len(imageNamesMapping))\n\n\tfor existingImage, archSpecificImage := range imageNamesMapping {\n\t\timageMappingRE[regexp.MustCompile(\"(?im)image: \"+existingImage+\"$\")] = []byte(\"image: \" + archSpecificImage)\n\t\timageMappingRE[regexp.MustCompile(\"(?im)default: \"+existingImage+\"$\")] = []byte(\"default: \" + archSpecificImage)\n\t}\n\n\treturn imageMappingRE\n}", "func containsDuplicate(nums []int) bool {\n\tnumMap := make(map[int]bool)\n\tfor _, num := range nums {\n\t\tif _, ok := numMap[num]; ok {\n\t\t\treturn true\n\t\t} else {\n\t\t\tnumMap[num] = true\n\t\t}\n\t}\n\treturn false\n}", "func mapArgs(rawArgs string) (map[string]string, error) {\n\targMap := make(map[string]string)\n\n\t// split params: param0:<param-val0> paramN:<param-valN> badparam\n\tparams, err := commandSplit(rawArgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// for each, split pram:<pram-value> into {param, <param-val>}\n\tfor _, param := range params {\n\t\tcmdName, cmdStr, err := namedParamSplit(param)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"map args: %s\", err)\n\t\t}\n\t\targMap[cmdName] = cmdStr\n\t}\n\n\treturn argMap, nil\n}", "func (vectorizer *Vectorizer) indexMap(src Map) {\n\tfor _, key := range src.orderedKeys() {\n\t\telem := src[key]\n\t\tif vectorizer.indexes[key] == nil {\n\t\t\tvectorizer.indexes[key] = index{}\n\t\t}\n\t\tif vectorizer.indexes[key][elem] == 0 {\n\t\t\tvectorizer.indexes[key][elem] = vectorizer.nextID(key)\n\t\t}\n\t}\n}", "func map_again() {\n\tnigeria_population := make(map[string]int)\n\tnigeria_population = map[string] int {\n\t\t\"Lagos\": 23421,\n\t\t\"Ondo\": 23450,\n\t}\n\tnigeria_population[\"Enugu\"] = 2345\n\tLagos_population, ok := nigeria_population[\"Lagos\"]\n\tfmt.Println(nigeria_population)\n\tdelete(nigeria_population, \"Lagos\")\n\tfmt.Println(nigeria_population)\n\tfmt.Println(Lagos_population, ok)\n}", "func (winMap tWinMap) createMap (hwnd W.HWND) {\n\t_, ok := winMap[hwnd]\n\tif !ok {\n\t\twinMap[hwnd] = make(map[uint32]TWinProc)\n\t}\n}", "func nomatch(arr []int16, ints []int16) []string {\n\n\tdmap := make(map[int16]bool)\n\tfor _, v := range arr {\n\t\tif _, ok := dmap[v]; !ok {\n\t\t\tdmap[v] = true\n\t\t}\n\t}\n\n\tfor _, v := range ints {\n\t\tdelete(dmap, v)\n\t}\n\n\tretval := []string{}\n\n\tfor k := range dmap {\n\t\tretval = append(retval, fmt.Sprintf(\"%d\", k))\n\t}\n\n\treturn retval\n}", "func TestMapSet(t *testing.T) {\n\tm := map[Key]interface{}{}\n\ttestMapSetN(testN, m)\n}", "func (i GinJwtSignAlgorithm) NameMap() map[string]GinJwtSignAlgorithm {\n\treturn _GinJwtSignAlgorithmNameToValueMap\n}" ]
[ "0.58030295", "0.57346433", "0.5727044", "0.56617534", "0.5628022", "0.56051046", "0.55091906", "0.54440206", "0.54367346", "0.542426", "0.5421174", "0.5410108", "0.5404929", "0.5377638", "0.537033", "0.53634435", "0.53602934", "0.53554034", "0.53473467", "0.5329108", "0.53019255", "0.52712667", "0.52574795", "0.52453387", "0.524449", "0.52391016", "0.5238626", "0.5233917", "0.52071667", "0.520335", "0.5200276", "0.5194655", "0.5182355", "0.518114", "0.5175009", "0.51679045", "0.51629615", "0.51580524", "0.51361686", "0.5134704", "0.51286113", "0.5122118", "0.5114286", "0.51140666", "0.51022875", "0.5063836", "0.50601864", "0.50597984", "0.50565135", "0.50487596", "0.50487053", "0.5044579", "0.50404733", "0.50394046", "0.5039106", "0.5034426", "0.5028791", "0.50246966", "0.50232315", "0.5009925", "0.50028175", "0.5001908", "0.50017416", "0.4996594", "0.49951303", "0.49837008", "0.4983438", "0.49760285", "0.49755174", "0.49754778", "0.49705017", "0.49703634", "0.49700016", "0.49640864", "0.4963816", "0.49600926", "0.49511522", "0.49478886", "0.49429238", "0.49427393", "0.4939167", "0.49388784", "0.49376294", "0.4929911", "0.49295238", "0.49223703", "0.4919664", "0.49194705", "0.4916677", "0.4912214", "0.4907531", "0.49042603", "0.49033898", "0.49015814", "0.48941818", "0.48906827", "0.4887296", "0.48762575", "0.4874051", "0.48701644", "0.48694682" ]
0.0
-1
Trace will output the execution time for a given function.
func Trace(funcName string, msg ...string) func() { start := time.Now() s := funcName for _, i := range msg { s = fmt.Sprintf("%s [%s]", s, i) } LOGGER.Infof("enter %s ...", s) return func() { LOGGER.Infof("exit %s (%s)", s, time.Since(start)) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Trace() {\n\tpc := make([]uintptr, 10) // at least 1 entry needed\n\truntime.Callers(2, pc)\n\tf := runtime.FuncForPC(pc[0])\n\tfile, line := f.FileLine(pc[0])\n\tfmt.Printf(\"%s:%d %s\\n\", file, line, shortFuncname(f.Name()))\n}", "func Trace(msg string) func() {\n\tstart := time.Now()\n\tlog.Printf(\"enter %s\", msg)\n\treturn func() { log.Printf(\"exit %s (%s)\", msg, time.Since(start)) }\n}", "func Trace() (string) {\n // At least one entry needed\n pc := make([]uintptr, 10)\n runtime.Callers(3, pc)\n f := runtime.FuncForPC(pc[0])\n file, line := f.FileLine(pc[0])\n return filepath.Base(file) + \":\" + strconv.Itoa(line) + \" \" + f.Name()\n}", "func Trace() {\n\tfn, _, _, _ := runtime.Caller(1)\n\tname := runtime.FuncForPC(fn).Name()\n\tname = filepath.Base(name)\n\tlog(traceType, name+\"()\")\n}", "func (l *Logger) Trace(name, file string, line int) {\r\n\tl.timeReset()\r\n\tdefer l.timeLog(name)\r\n}", "func (c Context) Trace(msg string) {\n\tc.Log(50, msg, GetCallingFunction())\n}", "func trace(msg string) func() {\n\tstart := time.Now()\n\tlog.Printf(\"enter %s\", msg)\n\treturn func() {\n\t\tlog.Printf(\"exit %s (%s)\", msg, time.Since(start))\n\t}\n}", "func Trace() (line string) {\n\tpc := make([]uintptr, 15)\n\tn := runtime.Callers(2, pc)\n\tframes := runtime.CallersFrames(pc[:n])\n\tframe, _ := frames.Next()\n\n\treturn fmt.Sprintf(\"%s,:%d %s\\n\", frame.File, frame.Line, frame.Function)\n}", "func Trace(f interface{}, v ...interface{}) {\n\tlogs.Trace(f, v...)\n}", "func (l Mylog) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {\n\telapsed := time.Now().Sub(begin)\n\ts, _ := json.Marshal(&ctx)\n\tl.Info(ctx, string(s))\n\tif err != nil {\n\t\tsql, rows := fc()\n\t\tl.ServiceLog.Error(ctx, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)\n\t} else {\n\t\tsql, rows := fc()\n\t\tl.ServiceLog.Info(utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)\n\t}\n}", "func trace() string {\n var buf bytes.Buffer\n traceWalk(16, func(fn function) {\n fmt.Fprintf(&buf, \"%s\\n\\t%s:%d\\n\", fn.name, fn.file, fn.line)\n })\n return buf.String()\n}", "func Timetracker(start time.Time, fname string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"Function %s ran for %s\\n\", fname, elapsed)\n}", "func Trace(info string) {\n\tpc := make([]uintptr, 1)\n\n\t// get call stack, ommitting 2 elements on stack, which is runtime.Callers and Trace2, respectively\n\truntime.Callers(2 , pc)\n\tf := runtime.FuncForPC(pc[0])\n\t// get the file and line number of the instruction immediately following the call\n\tfile, line := f.FileLine(pc[0])\n\n\tif len(info) == 0 {\n\t\tlogrus.Debugf(\"Lele: %s:%d; funcName: '%s'\", file, line, f.Name())\n\t}else{\n\t\tlogrus.Debugf(\"Lele: %s, %s:%d; funcName: '%s'\", info, file, line, f.Name())\n\t}\n\n}", "func TraceTime(logid int64, desc string, startTime time.Time, timeThreshold int64) {\n\ttimeSpent := time.Since(startTime)\n\tTraceTimeD(logid, desc, timeSpent, timeThreshold)\n}", "func Track(start time.Time, fnname string) {\n\telapsed := time.Since(start)\n\tlog.Printf(\"[timetrack] %s took %s\\n\", fnname, elapsed)\n}", "func TimeTrack(startTime time.Time, funcName string) {\n\tduration := time.Since(startTime)\n\tInfoLogger.Printf(\"%s Duration: %s\", funcName, duration)\n}", "func TimeTrack(start time.Time) {\n\telapsed := time.Since(start)\n\n\t// Skip this function, and fetch the PC and file for its parent.\n\tpc, _, _, _ := runtime.Caller(1)\n\n\t// Retrieve a function object this functions parent.\n\tfuncObj := runtime.FuncForPC(pc)\n\n\t// Regex to extract just the function name (and not the module path).\n\truntimeFunc := regexp.MustCompile(`^.*\\.(.*)$`)\n\tname := runtimeFunc.ReplaceAllString(funcObj.Name(), \"$1\")\n\n\tlog.Println(fmt.Sprintf(\"DEBUG %s() took %s\", name, elapsed))\n}", "func Trace(msg string, ctx ...interface{}) {\n\tmetrics.GetOrRegisterCounter(\"trace\", nil).Inc(1)\n\tl.Output(msg, l.LvlTrace, CallDepth, ctx...)\n}", "func TimeTrack(start time.Time) {\n\telapsed := time.Since(start)\n\n\t// Skip this function, and fetch the PC and file for its parent\n\tpc, _, _, _ := runtime.Caller(1)\n\n\t// Retrieve a Function object this functions parent\n\tfunctionObject := runtime.FuncForPC(pc)\n\n\t// Regex to extract just the function name (and not the module path)\n\n\tname := _extractFnName.ReplaceAllString(functionObject.Name(), \"$1\")\n\n\tlog.Printf(\"[timetrack] %s took %s\\n\", name, elapsed)\n}", "func LogAndMeasureExecutionTime(log *Logger, functionName string) (onEnd func()) {\n\tstart := time.Now()\n\tlog.Debugf(\"%s start\", functionName)\n\treturn func() {\n\t\tlog.Debugf(\"%s end. Took: %s\", functionName, time.Since(start))\n\t}\n}", "func Trace(v ...interface{}) { std.lprint(TRACE, v...) }", "func (CryptoMachineLogger) Trace(message string, args ...interface{}) {\n\tlog.Tracef(message, args...)\n}", "func printTime(fn func(int) ([]int)) (func(int) ([]int)) {\n return func(arg int) ([]int){\n start := time.Now()\n res := fn(arg)\n end := time.Now()\n elapsed := end.Sub(start)\n fmt.Println(\"elapsed time = \", elapsed)\n return res\n }\n}", "func (dl *DummyTracer) Trace(ctx context.Context, format string, args ...interface{}) {\n\tfmt.Printf(format+\"\\n\", args...)\n}", "func Trace(ctx context.Context, format string, args ...interface{}) {\n\ttracer.Trace(ctx, format, args...)\n}", "func (log *Logger) Trace(arg0 interface{}, args ...interface{}) {\n\tconst (\n\t\tlvl = TRACE\n\t)\n\tswitch first := arg0.(type) {\n\tcase string:\n\t\t// Use the string as a format string\n\t\tlog.intLogf(lvl, first, args...)\n\tcase func() string:\n\t\t// Log the closure (no other arguments used)\n\t\tlog.intLogc(lvl, first)\n\tdefault:\n\t\t// Build a format string so that it will be similar to Sprint\n\t\tlog.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(\" %v\", len(args)), args...)\n\t}\n}", "func (l *Logger) Trace(message string, args ...interface{}) { l.Log(Trace, message, args...) }", "func Trace(v ...interface{}) {\n\tWithLevel(LevelTrace, v...)\n}", "func Tracef(format string, v ...interface{}) { std.lprintf(TRACE, format, v...) }", "func FnTracker(start time.Time, name string) {\r\n\telapsed := time.Since(start)\r\n\tlog.Printf(\"%s took %v Min, %v Sec\", name, int64(elapsed/time.Minute), int64(elapsed/time.Second))\r\n}", "func (c Context) Tracef(format string, args ...interface{}) {\n\tc.Log(50, fmt.Sprintf(format, args...), GetCallingFunction())\n}", "func Trace(args ...interface{}) {\n\tif glog.V(trace) {\n\t\tglog.InfoDepth(1, \"TRACE: \"+fmt.Sprint(args...)) // 1 == depth in the stack of the caller\n\t}\n}", "func (t *tracer) Trace(a ...interface{}) {\n\tfmt.Fprint(t.out, a...)\n\tfmt.Fprintln(t.out)\n}", "func Trace(format string, v ...interface{}) {\n\tLog(1, TRACE, format, v...)\n}", "func Trace(args ...interface{}) {\n\tLog(logrus.TraceLevel, args...)\n}", "func TraceTimeDetail(logid int64, desc string, detail string, startTime time.Time, timeThreshold int64) {\n\ttimeSpent := time.Since(startTime).Nanoseconds() / int64(time.Millisecond)\n\tif timeSpent > timeThreshold {\n\t\tif timeThreshold > 0 {\n\t\t\tlog.Warningf(\"%d, time spent: %d, for %s\", logid, timeSpent, desc+detail)\n\t\t} else {\n\t\t\tlog.Debugf(\"%d, time spent: %d, for %s\", logid, timeSpent, desc+detail)\n\t\t}\n\t} else {\n\t\tlog.Debugf(\"%d, time spent: %d, for %s\", logid, timeSpent, desc)\n\t}\n}", "func Trace(ctx context.Context, funcName string) api.Decorator {\n\treturn func(ef api.FuncType) api.FuncType {\n\t\treturn func() error {\n\t\t\tspan := opentracing.SpanFromContext(ctx)\n\t\t\tif span != nil {\n\t\t\t\tchild := opentracing.StartSpan(funcName, opentracing.ChildOf(span.Context()))\n\t\t\t\tdefer child.Finish()\n\t\t\t}\n\t\t\treturn ef()\n\t\t}\n\t}\n}", "func Trace(msg ...interface{}) {\n\tCurrent.Trace(msg...)\n}", "func Trace(msg string, args ...interface{}) {\n\tDefaultLog.Trace(msg, args...)\n}", "func Trace(args ...interface{}) {\n\tLogger.Trace(args...)\n}", "func ExampleTrace() {\n\tsetup()\n\tlog.Trace().Msg(\"hello world\")\n\n\t// Output: {\"level\":\"trace\",\"time\":1199811905,\"message\":\"hello world\"}\n}", "func Trace_(trace interface{}) {}", "func TraceCall_(trace interface{}) {}", "func Timed(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s took %s\\n\", name, elapsed)\n\t// use like this\n\t// defer timed(time.Now(), \"functionName\")\n}", "func (r *Record) Trace(args ...interface{}) {\n\tr.Log(TraceLevel, args...)\n}", "func (z *ZapLogger) Trace(args ...interface{}) {\n\tz.Debug(args)\n}", "func Tracef(template string, args ...interface{}) {\n\tCurrent.Tracef(template, args...)\n}", "func Trace(v ...interface{}) {\n\tjasonLog.output(2, levelTrace, \"\", v...)\n}", "func Trace(data []byte) {\n\tlog.Print(\"TRACE: \", string(data))\n}", "func Trace(v ...interface{}) {\n\tif level <= LevelTrace {\n\t\tTorbitLogger.Printf(\"[T] %v\\n\", v)\n\t}\n}", "func Trace(fn func(string, ...interface{})) Option {\n\treturn func(o *options) {\n\t\to.trace = fn\n\t}\n}", "func Trace(info interface{}) {\n\tif trace {\n\t\tfmt.Println(info)\n\t}\n}", "func (o TraceObject) TimeTrack(start time.Time) {\n\telapsed := time.Since(start)\n\tlogger.WriteLog(logger.INFO, fmt.Sprintf(\"(%s) %s took %s\", o.HandlerName, o.Parameter, elapsed))\n}", "func (l gormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {\n\tif l.LogLevel > logger.Silent {\n\t\tlog := l.getLogger(ctx)\n\t\telapsed := time.Since(begin)\n\t\tswitch {\n\t\tcase err != nil && l.LogLevel >= logger.Error:\n\t\t\tsql, rows := fc()\n\t\t\tif rows == -1 {\n\t\t\t\t//l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, \"-\", sql)\n\t\t\t\tlog.Logf(loggerCore.TraceLevel, l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, \"-\", sql)\n\t\t\t} else {\n\t\t\t\t//l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)\n\t\t\t\tlog.Logf(loggerCore.TraceLevel, l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)\n\t\t\t}\n\t\tcase elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= logger.Warn:\n\t\t\tsql, rows := fc()\n\t\t\tslowLog := fmt.Sprintf(\"SLOW SQL >= %v\", l.SlowThreshold)\n\t\t\tif rows == -1 {\n\t\t\t\t//l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, \"-\", sql)\n\t\t\t\tlog.Logf(loggerCore.TraceLevel, l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, \"-\", sql)\n\t\t\t} else {\n\t\t\t\t//l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)\n\t\t\t\tlog.Logf(loggerCore.TraceLevel, l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)\n\t\t\t}\n\t\tcase l.LogLevel == logger.Info:\n\t\t\tsql, rows := fc()\n\t\t\tif rows == -1 {\n\t\t\t\t//l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, \"-\", sql)\n\t\t\t\tlog.Logf(loggerCore.TraceLevel, l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, \"-\", sql)\n\t\t\t} else {\n\t\t\t\t//l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)\n\t\t\t\tlog.Logf(loggerCore.TraceLevel, l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)\n\t\t\t}\n\t\t}\n\t}\n}", "func (l *Log) Trace(args ...interface{}) {\n\tl.logger.Trace(args...)\n}", "func timeMeasure() func() {\n\tstartTime := time.Now()\n\n\treturn func() {\n\t\tfmt.Print(toFixed(time.Since(startTime).Seconds(), 5))\n\t\tfmt.Println(\" seconds\")\n\t}\n}", "func Trace(ctx context.Context, msg string) {\n\tsp := opentracing.SpanFromContext(ctx)\n\tif sp != nil {\n\t\tsp.LogEvent(msg)\n\t}\n}", "func Timing(f func()) int64 {\n\tnow := time.Now().UnixNano()\n\tf()\n\n\treturn time.Now().UnixNano() - now\n}", "func (tr *Transport) Trace(url string, fn HandlerFunc, options ...HandlerOption) {\n\ttr.mux.Handler(net_http.MethodTrace, url, encapsulate(fn, tr.options, options))\n}", "func (l *Logger) Trace(messageFormat string, messageArgs ...interface{}) {\n\tl.Log(Trace, messageFormat, messageArgs...)\n}", "func Trace(message interface{}) {\n\tlogging.Debug(message)\n}", "func (l *Logger) Trace(v ...interface{}) {\n\tl.Log(fmt.Sprintln(v...), Ltrace, Trace)\n}", "func (l *thundraLogger) Trace(v ...interface{}) {\n\tif logLevelId > traceLogLevelId {\n\t\treturn\n\t}\n\tlogManager.recentLogLevel = traceLogLevel\n\tlogManager.recentLogLevelId = traceLogLevelId\n\tl.Output(2, fmt.Sprint(v...))\n}", "func Trace(ctx *context.Context) func(*error) {\n\treturn DefaultManager.TraceWithSpanNamed(ctx, CallerName())\n}", "func Trace(format string, a ...interface{}) {\n\tprefix := yellow(trac)\n\tlog.Println(prefix, fmt.Sprintf(format, a...))\n}", "func timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s took %s \\n\", name, elapsed)\n}", "func timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s took %s \\n\", name, elapsed)\n}", "func timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s took %s \\n\", name, elapsed)\n}", "func timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s took %s \\n\", name, elapsed)\n}", "func timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s took %s \\n\", name, elapsed)\n}", "func timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s took %s \\n\", name, elapsed)\n}", "func timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s took %s \\n\", name, elapsed)\n}", "func timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s took %s \\n\", name, elapsed)\n}", "func (l *zapLog) Trace(args ...interface{}) {\n\tif l.logger.Core().Enabled(zapcore.DebugLevel) {\n\t\tl.logger.Debug(fmt.Sprint(args...))\n\t}\n}", "func (log *Log) Trace(message string) {\n\tlog.Log(NewMessage(MessageTrace, message))\n}", "func (this *Logger) Trace(message string) {\n\tthis.Tracef(\"%s\", message)\n}", "func timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s took %s\\n\", name, elapsed)\n}", "func timeTrack(start time.Time, name string) {\n\tif ShellConfig.Bench {\n\t\tfmt.Fprintf(term, \"%s Method %s took %s %s\\n\", au.Bold(au.Blue(string(\"Δ\"))), au.Bold(au.Blue(name)), time.Since(start), au.Bold(au.Blue(string(\"Δ\"))))\n\t}\n}", "func printTrace(msg string) {\n\tif Trace {\n\t\tfmt.Println(fmt.Sprintf(\"TRACE %s: %s\", getFormattedTime(), msg))\n\t}\n}", "func printTrace(msg string) {\n\tif Trace {\n\t\tfmt.Println(fmt.Sprintf(\"TRACE %s: %s\", getFormattedTime(), msg))\n\t}\n}", "func timeTrack(start time.Time, action string) {\n\telapsed := time.Since(start)\n\tfmt.Printf(\"%s done in %v\\n\", action, elapsed)\n}", "func TimeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tlog.Printf(\"%s took %s\", name, elapsed)\n}", "func (logger *Logger) Trace(msg string, extras ...map[string]string) error {\n\tif TraceLevel >= logger.LogLevel {\n\t\treturn logger.Log(msg, TraceLevel, extras...)\n\t}\n\treturn nil\n}", "func (z *ZapLogWrapper) Trace(args ...interface{}) {\n\tz.l.Trace(args...)\n}", "func (logger *Logger) Trace(a ...any) {\n\tlogger.echo(nil, level.Trace, formatPrint, a...)\n}", "func Trace(msg string) {\r\n\tif (currentLogLevel > trace_level.value) {\r\n\t\treturn;\r\n\t}\r\n\r\n\tfmt.Fprintf(os.Stdout, adjustLog(trace_level.name, msg))\r\n}", "func Tracef(format string, args ...interface{}) {\n\tif glog.V(trace) {\n\t\tglog.InfoDepth(1, fmt.Sprintf(\"TRACE: \"+format, args...)) // 1 == depth in the stack of the caller\n\t}\n}", "func Tracef(logKey LogKey, format string, args ...interface{}) {\n\tlogTo(context.TODO(), LevelTrace, logKey, format, args...)\n}", "func trace(c echo.Context) error {\n\tpprof.Trace(c.Response().Writer, c.Request())\n\treturn nil\n}", "func (o TraceObject) TimeTrack(start time.Time) {\n\telapsed := time.Since(start)\n\tmsg := fmt.Sprintf(\"(%s) %s took %s\", o.HandlerName, o.Parameter, elapsed)\n\tlogger.InitWithRequest(o.Rq).Info(msg)\n}", "func Tracef(format string, v ...interface{}) {\n\tWithLevelf(LevelTrace, format, v...)\n}", "func Tracef(format string, params ...interface{}){\n log.Tracef(format, params)\n}", "func (l *Logger) Trace(v ...interface{}) { l.lprint(TRACE, v...) }", "func trackTime(start time.Time, result float64, name string) {\n\telapsed := time.Since(start)\n\tlog.Printf(\"---> %s solution | result: %v | took %s\", name, result, elapsed)\n}", "func TraceF(format string, v ...interface{}) {\n\tif variable.EnableTraceLog {\n\t\tlog.Printf(\"[TRACE] \"+format, v...)\n\t}\n}", "func TraceCall(log logr.Logger) {\n\tcallerInfo := GetCaller(MyCaller, true)\n\tlog.V(TraceLevel).Info(\"Entering function\", \"function\", callerInfo.FunctionName, \"source\", callerInfo.SourceFile, \"line\", callerInfo.SourceLine)\n}", "func Trace(format string, v ...interface{}) {\n\tLeveledLogger(level.Trace, format, v...)\n}", "func (c *context) Trace(tag, msg string, fields ...log.Field) {\n\tc.l.Trace(tag, msg, c.logFields(fields)...)\n\tc.incLogLevelCount(log.LevelTrace, tag)\n}", "func Trace(\n\tparent context.Context,\n\tdesc string) (ctx context.Context, report ReportFunc) {\n\t// If tracing is disabled, this is a no-op.\n\tif !*fEnabled {\n\t\tctx = parent\n\t\treport = func(err error) {}\n\t\treturn\n\t}\n\n\t// Is this context already being traced? If so, simply add a span.\n\tif parent.Value(traceStateKey) != nil {\n\t\tctx, report = StartSpan(parent, desc)\n\t\treturn\n\t}\n\n\t// Set up a new trace state.\n\tts := new(traceState)\n\tbaseReport := ts.CreateSpan(desc)\n\n\t// Log when finished.\n\treport = func(err error) {\n\t\tbaseReport(err)\n\t\tts.Log()\n\t}\n\n\t// Set up the context.\n\tctx = context.WithValue(parent, traceStateKey, ts)\n\n\treturn\n}", "func TimeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tfmt.Println(name, \"took\", elapsed, \", result: \")\n\tfmt.Println()\n}" ]
[ "0.6916347", "0.6909088", "0.6636149", "0.65993786", "0.658818", "0.65189373", "0.65169257", "0.65053225", "0.650356", "0.6475821", "0.64708906", "0.64122266", "0.6346052", "0.6315753", "0.6270708", "0.62663174", "0.6260435", "0.6254812", "0.61569095", "0.6138131", "0.6130659", "0.61094475", "0.6084655", "0.5993707", "0.5974457", "0.59630203", "0.59307885", "0.59301126", "0.589358", "0.58868366", "0.5882604", "0.58454114", "0.5834518", "0.5824449", "0.5823069", "0.58206177", "0.581974", "0.58193624", "0.581695", "0.58065677", "0.57899255", "0.5783596", "0.5777819", "0.5770973", "0.57688576", "0.575297", "0.57500535", "0.57426965", "0.57377744", "0.5722979", "0.5721855", "0.5720013", "0.5719485", "0.5711575", "0.5706994", "0.57008296", "0.5698033", "0.5680883", "0.56779397", "0.56767166", "0.5659695", "0.56584054", "0.56564933", "0.5640573", "0.5639014", "0.5635124", "0.5635124", "0.5635124", "0.5635124", "0.5635124", "0.5635124", "0.5635124", "0.5635124", "0.5632555", "0.5621945", "0.56217283", "0.56196076", "0.56156117", "0.5613387", "0.5613387", "0.5580943", "0.55733126", "0.5566859", "0.5559173", "0.5558498", "0.55525994", "0.5544866", "0.5539905", "0.5538471", "0.5538015", "0.55293727", "0.5522433", "0.55130506", "0.5511541", "0.5492406", "0.548669", "0.54839", "0.54663944", "0.54646945", "0.54538316" ]
0.6981734
0
check whether the request params ok.
func (this *AlienService) ValidMatter( writer http.ResponseWriter, request *http.Request, uuid string, filename string) *Matter { matter := this.matterDao.CheckByUuid(uuid) if matter.Name != filename { panic(result.BadRequest("filename in url incorrect")) } //only private file need auth. if matter.Privacy { //1.use downloadToken to auth. downloadTokenUuid := request.FormValue("downloadTokenUuid") if downloadTokenUuid != "" { downloadToken := this.downloadTokenDao.CheckByUuid(downloadTokenUuid) if downloadToken.ExpireTime.Before(time.Now()) { panic(result.BadRequest("downloadToken has expired")) } if downloadToken.MatterUuid != uuid { panic(result.BadRequest("token and file info not match")) } tokenUser := this.userDao.CheckByUuid(downloadToken.UserUuid) if matter.UserUuid != tokenUser.Uuid { panic(result.UNAUTHORIZED) } //TODO: expire the download token. If download by chunk, do this later. downloadToken.ExpireTime = time.Now() this.downloadTokenDao.Save(downloadToken) } else { //whether this is myself's matter. operator := this.findUser(request) if operator == nil { panic(result.BadRequest("no auth")) } if matter.SpaceUuid != operator.SpaceUuid { //whether user has the space's read auth. this.spaceService.CheckReadableByUuid(request, operator, matter.SpaceUuid) } } } return matter }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) HasParams() bool { return len(r.params) != 0 }", "func (r *Request) HasParams() bool { return len(r.params) != 0 }", "func CheckParameters(r *rest.Request, needed_fields []string) (bool, map[string]string) {\n\tvar result map[string]string\n\tresult = make(map[string]string)\n\tfor _, field := range needed_fields {\n\t\tvalues, _ := r.URL.Query()[field]\n\t\tif len(values) < 1 {\n\t\t\treturn false, result\n\t\t}\n\t\tresult[field] = values[0]\n\t}\n\treturn true, result\n}", "func IsValidParameterPresent(vars map[string]string, sp []string) error {\n\n\tfor i := range sp {\n\t\tv := vars[sp[i]]\n\t\tif v == \"\" {\n\t\t\terrMessage := fmt.Sprintf(\"Missing %v in GET request\", sp[i])\n\t\t\treturn fmt.Errorf(errMessage)\n\t\t}\n\n\t}\n\treturn nil\n\n}", "func checkParameter(parms [3]string, r *http.Request) (map[string]string, error){\n\tresult := make(map[string]string)\n\tfmt.Printf(\"==> \")\n for i := 0; i < len(parms); i++ {\n value, ok := r.URL.Query()[parms[i]]\n if !ok || len(value) < 1 {\n\n\t\t\treturn result, errors.New(fmt.Sprintf(\"==> Error %s not filled\", parms[i]))\n }\n fmt.Printf(\"%s=%s \", parms[i], value[0])\n result[parms[i]] = value[0]\n }\n\tfmt.Printf(\"\\n\")\n return result, nil\n\n}", "func requiredParam(w http.ResponseWriter, req *http.Request, key string) (string, bool) {\n\tvalue, exists := getParams(req, key)\n\n\tif !exists {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - Bad Request!\"))\n\t\treturn \"\", false\n\t}\n\n\treturn value, true\n}", "func isValidParam(data Data) (result bool, err error) {\n\t// check length of param From\n\tif len(data.From) > 3 || len(data.From) < 3 {\n\t\tresult = false\n\t\terr = ErrInvalidParamFrom\n\t\treturn\n\t}\n\n\t// check length of param To\n\tif len(data.To) > 3 || len(data.To) < 3 {\n\t\tresult = false\n\t\terr = ErrInvalidParamTo\n\t\treturn\n\t}\n\n\tresult = true\n\treturn\n}", "func CheckParams(params Setting, passwordType string) bool {\n\n\tminLen := params.MinLength\n\tminSpecials := params.MinSpecialCharacters\n\tminDigits := params.MinDigits\n\tminLowers := params.MinLowercase\n\tminUppers := params.MinUppercase\n\n\tif minLen < AbsoluteMinLen ||\n\t\tminDigits < config[passwordType].MinDigits ||\n\t\tminLowers < config[passwordType].MinLowercase ||\n\t\tminUppers < config[passwordType].MinUppercase ||\n\t\tminSpecials < config[passwordType].MinSpecialCharacters {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (x *fastReflection_QueryParamsRequest) IsValid() bool {\n\treturn x != nil\n}", "func TestAllowedParams(t *testing.T) {\n\tif len(AllowedParams()) == 0 {\n\t\tt.Fatalf(\"pages: no allowed params\")\n\t}\n}", "func validateParams(method model.Method, params map[string]interface{}) (bool, error) {\n\tvar notSpecified []model.Parameter\n\tfor _, param := range method.Parameters {\n\t\tvalue := params[param.Name]\n\t\tif param.Required {\n\t\t\tif value != \"\" && value != nil{\n\t\t\t\tactualType := getTypeName(value)\n\t\t\t\tif actualType != param.Type {\n\t\t\t\t\tmsg := fmt.Sprintf(\"Wrong argument '%s' for method '%s'. Expected type '%s', but found '%s'\", param.Name, method.Name, param.Type, actualType)\n\t\t\t\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\t\t\t\treturn false, errors.New(msg)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnotSpecified = append(notSpecified, param)\n\t\t\t}\n\t\t} else {\n\t\t\tif value != \"\" && value != nil {\n\t\t\t\t// optional parameters check\n\t\t\t\tactualType := getTypeName(value)\n\t\t\t\tif actualType != param.Type {\n\t\t\t\t\tmsg := fmt.Sprintf(\"Wrong argument '%s' for method '%s'. Expected type '%s', but found '%s'\", param.Name, method.Name, param.Type, actualType)\n\t\t\t\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\t\t\t\treturn false, errors.New(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(notSpecified) != 0 {\n\t\tvar paramStr string = \"\"\n\t\tfor _, param := range notSpecified {\n\t\t\tparamStr += fmt.Sprintf(\"'%s', \", param.Name)\n\t\t}\n\t\tmsg := fmt.Sprintf(\"Required parameters are not provided for '%s' method. Please specify: %s\", method.Name, paramStr[:len(paramStr) - 2])\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn false, errors.New(msg)\n\t}\n\treturn true, nil\n}", "func check_args(parsed_query []string, num_expected int) bool {\n\treturn (len(parsed_query) >= num_expected)\n}", "func requestOk(w http.ResponseWriter, r *http.Request) bool {\n\tif r.Body == nil {\n\t\thttp.Error(w, \"Please send a request body\", 400)\n\t\treturn false\n\t}\n\treturn true\n}", "func (m *MongoStore) validateParams(args ...interface{}) bool {\n\tfor _, v := range args {\n\t\tval, ok := v.(string)\n\t\tif ok {\n\t\t\tif val == \"\" {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tif v == nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func checkInputVars() {\n\n\tvar err error\n\n\t_, err = url.ParseRequestURI(swiftAuthUrl)\n\tif err != nil {\n\t\tlog.Fatalf(\"Wrong or empty URL for Swift Endpoint: %s \\n\", err.Error())\n\t}\n\n\tif swiftUserName == \"\" {\n\t\tlogFatalfwithUsage(\"Empty username for Swift login!\\n\")\n\t}\n\n\tif swiftPassword == \"\" {\n\t\tlogFatalfwithUsage(\"Empty password for Swift login!\\n\")\n\t}\n\n}", "func validateParams(params map[string][]string) error {\n\tfor param, values := range params {\n\t\tswitch param {\n\t\tcase timeRangeQS:\n\t\t\tvalue := values[len(values)-1]\n\t\t\tif !validTimeRange(value) {\n\t\t\t\treturn errors.New(\"invalid time_range query string param\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func checkSetParameter(param interface{}) bool {\n\tswitch param.(type) {\n\tcase string:\n\t\tif param.(string) == \"\" {\n\t\t\treturn false\n\t\t}\n\tcase int:\n\t\tif param.(int) == 0 {\n\t\t\treturn false\n\t\t}\n\tcase uint:\n\t\tif param.(uint) == 0 {\n\t\t\treturn false\n\t\t}\n\tcase float64:\n\t\tif param.(float64) == 0 {\n\t\t\treturn false\n\t\t}\n\tcase []Namespace:\n\t\tif param.([]Namespace) == nil {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}", "func IsRequestValid(strings ...string) (result bool) {\n\tresult = true\n\tfor _, s := range strings {\n\t\tif s == \"\" {\n\t\t\tresult = false\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func validateParams() {\n\tif domain == \"\" {\n\t\tprintAndExit(\"-domain is required!\", true)\n\t}\n\n\tif passLength < 1 {\n\t\tprintAndExit(\"-password-length must be a positive number!\", true)\n\t}\n\n\tif passLength < 8 {\n\t\tfmt.Println(\"WARN: -password-length is too short. We will grant your wish, but this might be a security risk. Consider using longer password.\", false)\n\t}\n}", "func getParams(req *http.Request, key string) (string, bool) {\n\tif req.Method != http.MethodGet {\n\t\treturn \"\", false\n\t}\n\n\tvalues := req.URL.Query()\n\tvalue := values.Get(key)\n\n\tif value == \"\" {\n\t\treturn \"\", false\n\t}\n\n\treturn value, true\n}", "func (r *Request) OK() error {\n\tif len(r.URL) == 0 {\n\t\treturn ErrRequired{Msg: \"url must be specified\"}\n\t}\n\treturn nil\n}", "func VerifyParameters(key string, qs map[string]interface{}) bool {\n\tparams := url.Values{}\n\n\tfor k, v := range qs {\n\t\ts, ok := v.(string)\n\t\tif ok {\n\t\t\tparams.Set(k, s)\n\t\t\tcontinue\n\t\t}\n\n\t\tl, ok := v.([]string)\n\t\tif ok {\n\t\t\tfor i := range l {\n\t\t\t\tparams.Add(k, l[i])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn VerifySign(key, params.Encode())\n}", "func hasAttributes(request *http.Request, response http.ResponseWriter) bool {\n\n\tlog.Printf(\"Request for %s is in progress....\", request.RequestURI)\n\tif request.Header.Get(\"Api-Key\") != \"nobelApp\" {\n\t\thttp.Error(response, \"Request Header: Invalid Api-Key\", http.StatusBadRequest)\n\t\treturn false\n\t}\n\treturn true\n}", "func (c *Config) Valid(r *http.Request) bool {\n\theader := strings.Split(r.Header.Get(\"Authorization\"), \"Bearer \")\n\treturn len(header) == 2\n}", "func verifyArgs() (bool, string) {\n\tvar errMsg string\n\tvar webhookURL string\n\n\tif *auth == \"\" {\n\t\terrMsg = \"Invalid authentication! It must not be empty.\\n\"\n\t\treturn false, errMsg\n\t}\n\n\tif *address == \"\" {\n\t\terrMsg = \"Invalid URL! It must not be empty.\\n\"\n\t\treturn false, errMsg\n\t}\n\n\tif *port < 1025 || *port > 65535 {\n\t\terrMsg = \"Invalid port! Please, check it is between 1025 and 65535.\\n\"\n\t\treturn false, errMsg\n\t}\n\n\tif *prefix != \"\" {\n\t\t*prefix = strings.Trim(*prefix, \"/\")\n\t}\n\n\twebhookURL = fmt.Sprintf(\"%s:%d\", *address, *port)\n\n\treturn true, webhookURL\n}", "func checkRequest(req *http.Request) error {\n\treturn nil\n}", "func (r SSOLoginConsoleReq) Check() error {\n\tif r.RedirectURL == \"\" {\n\t\treturn trace.BadParameter(\"missing RedirectURL\")\n\t}\n\tif len(r.PublicKey) == 0 {\n\t\treturn trace.BadParameter(\"missing PublicKey\")\n\t}\n\tif r.ConnectorID == \"\" {\n\t\treturn trace.BadParameter(\"missing ConnectorID\")\n\t}\n\treturn nil\n}", "func (r *Request) ParamOk(name string) (*validation.Value, bool) {\n\tp, ok := r.Input[name]\n\treturn p, ok\n}", "func (p *GenerateAppTokenRequest) Check() error {\n\tif p.Username == \"\" {\n\t\treturn trace.BadParameter(\"username missing\")\n\t}\n\tif p.Expires.IsZero() {\n\t\treturn trace.BadParameter(\"expires missing\")\n\t}\n\tif p.URI == \"\" {\n\t\treturn trace.BadParameter(\"uri missing\")\n\t}\n\treturn nil\n}", "func (x *fastReflection_Params) IsValid() bool {\n\treturn x != nil\n}", "func (c customerio) verifyParams() {\n\tif c.from.Email == \"\" {\n\t\tpanic(\"gomailer: you must provide from\")\n\t}\n\tif len(c.toList) <= 0 {\n\t\tpanic(\"gomailer: you must provide at least one receipent\")\n\t}\n\tif len(c.toList)+len(c.ccList)+len(c.bccList) > customerioMaxReceipents {\n\t\tpanic(fmt.Sprintf(\"mailer: total number of receipents including to/cc/bcc can not be greater than %d for customerio\", customerioMaxReceipents))\n\t}\n\tif c.bodyText == \"\" && c.bodyHTML == \"\" {\n\t\tpanic(\"gomailer: you must provide a Text or HTML body\")\n\t}\n}", "func (a *authenticator) isV1(r *http.Request) bool {\n\treturn r.Form.Get(v1Arg) != \"\"\n}", "func (p *Params) Check() error {\n\t// Validate Memory\n\tif p.Memory < minMemoryValue {\n\t\treturn ErrInvalidParams\n\t}\n\n\t// Validate Iterations\n\tif p.Iterations < 1 {\n\t\treturn ErrInvalidParams\n\t}\n\n\t// Validate Parallelism\n\tif p.Parallelism < 1 {\n\t\treturn ErrInvalidParams\n\t}\n\n\t// Validate salt length\n\tif p.SaltLength < minSaltLength {\n\t\treturn ErrInvalidParams\n\t}\n\n\t// Validate key length\n\tif p.KeyLength < minKeyLength {\n\t\treturn ErrInvalidParams\n\t}\n\n\treturn nil\n}", "func isRequestParameter(t *surface_v1.Type) bool {\n\tif strings.Contains(t.Description, t.GetName()+\" holds parameters to\") {\n\t\treturn true\n\t}\n\treturn false\n}", "func checkDSNParams(dsn string) error {\n\tdsnURL, err := url.Parse(dsn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparams, err := url.ParseQuery(dsnURL.RawQuery)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif params.Get(\"parseTime\") != \"true\" {\n\t\treturn ErrDSNParam\n\t}\n\n\treturn nil\n}", "func (r RequestTester) Check(req *http.Request) error {\n\tif r.Path > \"\" && r.Path != req.URL.Path {\n\t\treturn fmt.Errorf(\"expected request path %s; got %s\", r.Path, req.URL.Path)\n\t}\n\tif r.Auth > \"\" && r.Auth != req.Header.Get(\"Authorization\") {\n\t\treturn fmt.Errorf(\"expecte auth header %s; got %s\", r.Auth, req.Header.Get(\"Authorization\"))\n\t}\n\tif r.Method > \"\" && r.Method != req.Method {\n\t\treturn fmt.Errorf(\"expected method %s; got %s\", r.Method, req.Method)\n\t}\n\tif r.Query > \"\" && r.Query != req.URL.RawQuery {\n\t\treturn fmt.Errorf(\"expected query args %s; got %s\", r.Query, req.URL.RawQuery)\n\t}\n\tif r.Host > \"\" && r.Host != req.URL.Host {\n\t\treturn fmt.Errorf(\"expected host %s; got %s\", r.Host, req.URL.Host)\n\t}\n\tif r.ContentType > \"\" && r.ContentType != req.Header.Get(\"ContentType\") {\n\t\treturn fmt.Errorf(\"expected content-type %s; got %s\", r.ContentType, req.Header.Get(\"ContentType\"))\n\t}\n\tfor k := range r.Header {\n\t\tif r.Header.Get(k) != req.Header.Get(k) {\n\t\t\treturn fmt.Errorf(\"expected header %s = %s; got %s\", k, r.Header.Get(k), req.Header.Get(k))\n\t\t}\n\t}\n\tif len(r.Payload) > 0 {\n\t\tb, err := ioutil.ReadAll(req.Body)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to read request body: %v\", err)\n\t\t}\n\t\tif bytes.Compare(b, r.Payload) != 0 {\n\t\t\treturn fmt.Errorf(\"expected body %s; got %s\", string(r.Payload), string(b))\n\t\t}\n\n\t}\n\treturn nil\n}", "func (vpc *VampClientProvider) checkAndSetParameters() {\n\tif vpc.URL == \"\" {\n\t\tvpc.URL = viper.GetString(\"url\")\n\t\tvpc.Token = viper.GetString(\"token\")\n\t\tvpc.APIVersion = viper.GetString(\"apiversion\")\n\t\tvpc.Cert = viper.GetString(\"cert\")\n\t\tvpc.Project = viper.GetString(\"project\")\n\t\tvpc.Cluster = viper.GetString(\"cluster\")\n\t\tvpc.VirtualCluster = viper.GetString(\"virtualcluster\")\n\t}\n}", "func (api *Api) isValidCalculateRequest() bool {\n\treturn api.calculateBody.A != nil && api.calculateBody.B != nil\n}", "func (req *WidgetRequest) Valid() bool {\n\treq.issues = []string{}\n\tif stringutil.IsWhiteSpace(req.SerialNumber) {\n\t\treq.issues = append(req.issues, \"SerialNumber cannot be blank\")\n\t}\n\tif stringutil.IsWhiteSpace(req.Description) {\n\t\treq.issues = append(req.issues, \"Description cannot be blank\")\n\t}\n\treturn 0 == len(req.issues)\n}", "func isSearchRequest(destination, fileName, request, keywords string) bool {\n\treturn isNull(destination) && isNull(fileName) && isNull(request) && !isNull(keywords)\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 (x *fastReflection_QueryParamsResponse) IsValid() bool {\n\treturn x != nil\n}", "func checkArguments(hash string, privateKey string) bool {\n\t// easy check\n\t// if len(hash) != 46 || len(privateKey) != 64 {\n\t// \treturn false\n\t// }\n\n\treturn true\n}", "func validQueryStringParams(metric string, params map[string][]string) map[string][]string {\n\tvalidParams := make(map[string][]string)\n\tfor key, value := range params {\n\t\tif util.SliceContains(statsQueryStringParams[metric], key) {\n\t\t\tvalidParams[key] = value\n\t\t}\n\t}\n\treturn validParams\n}", "func (c MethodParams) ValidateParams(params url.Values) error {\n\tfor _, p := range c {\n\t\tif err := p.ValidateValue(params.Get(p.Name)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r WADORequest) Validate() bool {\n\tswitch r.Type {\n\tcase StudyRaw:\n\t\treturn r.StudyInstanceUID != \"\" && r.SeriesInstanceUID == \"\" && r.SOPInstanceUID == \"\"\n\tcase StudyRendered:\n\t\treturn r.StudyInstanceUID != \"\" && r.SeriesInstanceUID == \"\" && r.SOPInstanceUID == \"\"\n\tcase SeriesRaw:\n\t\treturn r.StudyInstanceUID != \"\" && r.SeriesInstanceUID != \"\" && r.SOPInstanceUID == \"\"\n\tcase SeriesRendered:\n\t\treturn r.StudyInstanceUID != \"\" && r.SeriesInstanceUID != \"\" && r.SOPInstanceUID == \"\"\n\tcase SeriesMetadata:\n\t\treturn r.StudyInstanceUID != \"\" && r.SeriesInstanceUID != \"\" && r.SOPInstanceUID == \"\"\n\tcase InstanceRaw:\n\t\treturn r.StudyInstanceUID != \"\" && r.SeriesInstanceUID != \"\" && r.SOPInstanceUID != \"\"\n\tcase InstanceRendered:\n\t\treturn r.StudyInstanceUID != \"\" && r.SeriesInstanceUID != \"\" && r.SOPInstanceUID != \"\"\n\tcase InstanceMetadata:\n\t\treturn r.StudyInstanceUID != \"\" && r.SeriesInstanceUID != \"\" && r.SOPInstanceUID != \"\"\n\tcase Frame:\n\t\treturn r.StudyInstanceUID != \"\" && r.SeriesInstanceUID != \"\" && r.SOPInstanceUID != \"\" && r.FrameID != 0\n\tcase URIReference:\n\t\treturn r.RetrieveURL != \"\"\n\t}\n\treturn false\n}", "func (p *Params) validateRequiredParameters() error {\n\tif p.Input == nil {\n\t\treturn errors.New(\"Input must not be nil\")\n\t}\n\tif p.Output == nil {\n\t\treturn errors.New(\"Output must not be nil\")\n\t}\n\treturn nil\n}", "func HasQueryParam(r *http.Request, param string) bool {\n\tvalues := r.URL.Query()\n\t_, ok := values[param]\n\treturn ok\n}", "func (r *Request) ParamPresent(key string) *Request {\n\tr.MatchParam(key, \".*\")\n\treturn r\n}", "func (o *ObservedProperty) ContainsMandatoryParams() (bool, []error) {\n\terr := []error{}\n\tCheckMandatoryParam(&err, o.Name, o.GetEntityType(), \"name\")\n\tCheckMandatoryParam(&err, o.Definition, o.GetEntityType(), \"definition\")\n\tCheckMandatoryParam(&err, o.Description, o.GetEntityType(), \"description\")\n\n\tif len(err) != 0 {\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}", "func ParamOK(ctx context.Context, name string) (string, bool) {\n\tparams := Params(ctx)\n\tfor i := range params {\n\t\tif params[i].Key == name {\n\t\t\treturn params[i].Value, true\n\t\t}\n\t}\n\treturn \"\", false\n}", "func QueryHasParam(request *http.Request, paramName string) bool {\n\t_, ok := request.URL.Query()[paramName]\n\n\treturn ok\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 HasParam(values url.Values, param string) bool {\n\t_, ok := values[param]\n\treturn ok\n}", "func checkValidPassport(passport map[string]string) bool {\n\treturn passport[\"byr\"] != \"\" && passport[\"pid\"] != \"\" && passport[\"ecl\"] != \"\" && passport[\"eyr\"] != \"\" && passport[\"hcl\"] != \"\" && passport[\"hgt\"] != \"\" && passport[\"iyr\"] != \"\"\n}", "func assertQuery(t *testing.T, expected map[string]string, req *http.Request) {\n\tqueryValues := req.URL.Query() // net/url Values is a map[string][]string\n\texpectedValues := url.Values{}\n\tfor key, value := range expected {\n\t\texpectedValues.Add(key, value)\n\t}\n\tif !reflect.DeepEqual(expectedValues, queryValues) {\n\t\tt.Errorf(\"expected parameters %v, got %v\", expected, req.URL.RawQuery)\n\t}\n}", "func validMethodAndContentType(w http.ResponseWriter, r *http.Request) bool {\n\tct := r.Header.Get(\"Content-type\")\n\tif ct != commContentType {\n\t\thttp.Error(w, fmt.Sprintf(\"Unsupported Content-type \\\"%s\\\"\", ct), http.StatusUnsupportedMediaType)\n\t\treturn false\n\t}\n\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, \"HTTP Method not allowed\", http.StatusMethodNotAllowed)\n\t\treturn false\n\t}\n\treturn true\n}", "func validateRequest(r *http.Request) (int, error) {\n\tif r.Method == http.MethodPut || r.Method == http.MethodDelete {\n\t\treturn http.StatusMethodNotAllowed, errors.New(\"method not allowed\")\n\t}\n\tif r.ContentLength > maxRequestContentLength {\n\t\terr := fmt.Errorf(\"content length too large (%d>%d)\", r.ContentLength, maxRequestContentLength)\n\t\treturn http.StatusRequestEntityTooLarge, err\n\t}\n\t// Allow OPTIONS (regardless of content-type)\n\tif r.Method == http.MethodOptions {\n\t\treturn 0, nil\n\t}\n\t// Check content-type\n\tif mt, _, err := mime.ParseMediaType(r.Header.Get(\"content-type\")); err == nil {\n\t\tfor _, accepted := range acceptedContentTypes {\n\t\t\tif accepted == mt {\n\t\t\t\treturn 0, nil\n\t\t\t}\n\t\t}\n\t}\n\t// Invalid content-type\n\terr := fmt.Errorf(\"invalid content type, only %s is supported\", contentType)\n\treturn http.StatusUnsupportedMediaType, err\n}", "func (o *Content) GetHasParametersOk() (*bool, bool) {\n\tif o == nil || o.HasParameters == nil {\n\t\treturn nil, false\n\t}\n\treturn o.HasParameters, true\n}", "func WCSParamsChecker(params map[string][]string, compREMap map[string]*regexp.Regexp) (WCSParams, error) {\n\n\tjsonFields := []string{}\n\n\tif service, serviceOK := params[\"service\"]; serviceOK {\n\t\tif compREMap[\"service\"].MatchString(service[0]) {\n\t\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"service\":\"%s\"`, service[0]))\n\t\t}\n\t}\n\n\tif version, versionOK := params[\"version\"]; versionOK {\n\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"version\":\"%s\"`, version[0]))\n\t}\n\n\tif request, requestOK := params[\"request\"]; requestOK {\n\t\tif compREMap[\"request\"].MatchString(request[0]) {\n\t\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"request\":\"%s\"`, request[0]))\n\t\t}\n\t}\n\n\tif coverage, coverageOK := params[\"coverage\"]; coverageOK {\n\t\tif compREMap[\"coverage\"].MatchString(coverage[0]) {\n\t\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"coverage\":[\"%s\"]`, coverage[0]))\n\t\t}\n\t}\n\n\tif crs, crsOK := params[\"crs\"]; crsOK {\n\t\tif compREMap[\"crs\"].MatchString(crs[0]) {\n\t\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"crs\":\"%s\"`, crs[0]))\n\t\t}\n\t}\n\n\tif bbox, bboxOK := params[\"bbox\"]; bboxOK {\n\t\tif compREMap[\"bbox\"].MatchString(bbox[0]) {\n\t\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"bbox\":[%s]`, bbox[0]))\n\t\t}\n\t}\n\n\tif width, widthOK := params[\"width\"]; widthOK {\n\t\tif compREMap[\"width\"].MatchString(width[0]) {\n\t\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"width\":%s`, width[0]))\n\t\t}\n\t}\n\n\tif height, heightOK := params[\"height\"]; heightOK {\n\t\tif compREMap[\"height\"].MatchString(height[0]) {\n\t\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"height\":%s`, height[0]))\n\t\t}\n\t}\n\n\tif time, timeOK := params[\"time\"]; timeOK {\n\t\tif compREMap[\"time\"].MatchString(time[0]) {\n\t\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"time\":\"%s\"`, time[0]))\n\t\t}\n\t}\n\n\tif format, formatOK := params[\"format\"]; formatOK {\n\t\tif compREMap[\"format\"].MatchString(format[0]) {\n\t\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"format\":\"%s\"`, format[0]))\n\t\t}\n\t}\n\n\tif styles, stylesOK := params[\"styles\"]; stylesOK {\n\t\tif !strings.Contains(styles[0], \"\\\"\") {\n\t\t\tjsonFields = append(jsonFields, fmt.Sprintf(`\"styles\":[\"%s\"]`, strings.Replace(styles[0], \",\", \"\\\",\\\"\", -1)))\n\t\t}\n\t}\n\n\tjsonParams := fmt.Sprintf(\"{%s}\", strings.Join(jsonFields, \",\"))\n\n\tvar wcsParams WCSParams\n\terr := json.Unmarshal([]byte(jsonParams), &wcsParams)\n\treturn wcsParams, err\n}", "func checkRequest(httpClient *dphttp.ClienterMock, callIndex int, expectedMethod, expectedURI string, expectedIfMatch string) {\n\tSo(httpClient.DoCalls()[callIndex].Req.URL.RequestURI(), ShouldEqual, expectedURI)\n\tSo(httpClient.DoCalls()[callIndex].Req.Method, ShouldEqual, http.MethodPatch)\n\tSo(httpClient.DoCalls()[callIndex].Req.Header.Get(dprequest.AuthHeaderKey), ShouldEqual, \"Bearer \"+testServiceToken)\n\tactualIfMatch := httpClient.DoCalls()[callIndex].Req.Header.Get(\"If-Match\")\n\tSo(actualIfMatch, ShouldResemble, expectedIfMatch)\n}", "func (cors *Cors) areReqHeadersAllowed(reqHeaders string) bool {\n\tif len(reqHeaders) == 0 {\n\t\treturn true\n\t}\n\n\trequestHeaders := strings.Split(reqHeaders, \",\")\n\tfor _, v := range requestHeaders {\n\t\t// cors.logWrap(\"TRACE areReqHeadersAllowed: v = %s\", v)\n\t\tcanonicalHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))\n\t\t// cors.logWrap(\"TRACE areReqHeadersAllowed: canonicalHeader = %s\", canonicalHeader)\n\t\tif !cors.isHeaderAllowed(canonicalHeader) {\n\t\t\t// cors.logWrap(\"TRACE areReqHeadersAllowed: header not allowed return ''\")\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n\n}", "func (r *RequestValidator) ValidateRequestParameters() pulumi.BoolOutput {\n\treturn (pulumi.BoolOutput)(r.s.State[\"validateRequestParameters\"])\n}", "func (a *authenticator) isV2(r *http.Request) bool {\n\treturn r.Form.Get(v2Arg) != \"\"\n}", "func (s APIParams) Len() int {\n\treturn len(s)\n}", "func (args *RequestArgs) Check() *constant.YiError {\n\tif args.AcceptedDomains == nil {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Nil accepted domains\")\n\t}\n\treturn nil\n}", "func (r *QueryRequest) Valid() error {\n\tif !r.OrganizationID.Valid() {\n\t\treturn &errors.Error{\n\t\t\tMsg: \"organization_id is not valid\",\n\t\t\tCode: errors.EInvalid,\n\t\t}\n\t}\n\treturn r.Authorization.Valid()\n}", "func ValidateParameters(r *Request) {\n\tif r.ParamsFilled() {\n\t\tv := validator{errors: []string{}}\n\t\tv.validateAny(reflect.ValueOf(r.Params), \"\")\n\n\t\tif count := len(v.errors); count > 0 {\n\t\t\tformat := \"%d validation errors:\\n- %s\"\n\t\t\tmsg := fmt.Sprintf(format, count, strings.Join(v.errors, \"\\n- \"))\n\t\t\tr.Error = apierr.New(\"InvalidParameter\", msg, nil)\n\t\t}\n\t}\n}", "func AllowedParams() []string {\n\treturn []string{\"status\", \"email\", \"name\", \"role\"}\n}", "func shouldSendReqContentLength(method string, contentLength int64) bool {\n\tif contentLength > 0 {\n\t\treturn true\n\t}\n\tif contentLength < 0 {\n\t\treturn false\n\t}\n\t// For zero bodies, whether we send a content-length depends on the method.\n\t// It also kinda doesn't matter for http2 either way, with END_STREAM.\n\tswitch method {\n\tcase \"POST\", \"PUT\", \"PATCH\":\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func ValidateRouterParamsFromPath(w http.ResponseWriter, p httprouter.Params, routerPath string) bool {\n\tfor _, n := range getParamNamesFromRouterPath(routerPath) {\n\t\tif p.ByName(n) == \"\" {\n\t\t\thttp.Error(w, \"404 page not found\", http.StatusNotFound)\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p *Params) ValidateRequiredProperties() (bool, []error, []string) {\n\n\terrors := []error{}\n\twarnings := []string{}\n\n\t// validate app params\n\tif p.App == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Application name is required; either define an app label or use app property on this stage\"))\n\t}\n\tif p.Namespace == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Namespace is required; either use credentials with a defaultNamespace or set it via namespace property on this stage\"))\n\t}\n\n\tif p.Action == \"rollback-canary\" {\n\t\t// the above properties are all you need for a rollback\n\t\treturn len(errors) == 0, errors, warnings\n\t}\n\n\t// validate container params\n\tif p.Container.ImageRepository == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Image repository is required; set it via container.repository property on this stage\"))\n\t}\n\tif p.Container.ImageName == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Image name is required; set it via container.name property on this stage\"))\n\t}\n\tif p.Container.ImageTag == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Image tag is required; set it via container.tag property on this stage\"))\n\t}\n\n\t// validate cpu params\n\tif p.Container.CPU.Request == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Cpu request is required; set it via container.cpu.request property on this stage\"))\n\t}\n\tif p.Container.CPU.Limit == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Cpu limit is required; set it via container.cpu.limit property on this stage\"))\n\t}\n\n\t// validate memory params\n\tif p.Container.Memory.Request == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Memory request is required; set it via container.memory.request property on this stage\"))\n\t}\n\tif p.Container.Memory.Limit == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Memory limit is required; set it via container.memory.limit property on this stage\"))\n\t}\n\n\t// defaults for rollingupdate\n\tif p.RollingUpdate.MaxSurge == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Rollingupdate max surge is required; set it via rollingupdate.maxsurge property on this stage\"))\n\t}\n\tif p.RollingUpdate.MaxUnavailable == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Rollingupdate max unavailable is required; set it via rollingupdate.maxunavailable property on this stage\"))\n\t}\n\n\tif p.Kind == \"job\" || p.Kind == \"cronjob\" {\n\t\tif p.Kind == \"cronjob\" {\n\t\t\tif p.Schedule == \"\" {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"Schedule is required for a cronjob; set it via schedule property on this stage\"))\n\t\t\t}\n\n\t\t\tif p.ConcurrencyPolicy != \"Allow\" && p.ConcurrencyPolicy != \"Forbid\" && p.ConcurrencyPolicy != \"Replace\" {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"ConcurrencyPolicy is invalid; allowed values are Allow, Forbid or Replace\"))\n\t\t\t}\n\t\t}\n\n\t\t// the above properties are all you need for a worker\n\t\treturn len(errors) == 0, errors, warnings\n\t}\n\n\t// validate params with respect to incoming requests\n\tif p.Visibility == \"\" || (p.Visibility != \"private\" && p.Visibility != \"public\" && p.Visibility != \"iap\" && p.Visibility != \"public-whitelist\") {\n\t\terrors = append(errors, fmt.Errorf(\"Visibility property is required; set it via visibility property on this stage; allowed values are private, iap, public-whitelist or public\"))\n\t}\n\tif p.Visibility == \"iap\" && p.IapOauthCredentialsClientID == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"With visibility 'iap' property iapOauthClientID is required; set it via iapOauthClientID property on this stage\"))\n\t}\n\tif p.Visibility == \"iap\" && p.IapOauthCredentialsClientSecret == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"With visibility 'iap' property iapOauthClientSecret is required; set it via iapOauthClientSecret property on this stage\"))\n\t}\n\n\tif len(p.Hosts) == 0 {\n\t\terrors = append(errors, fmt.Errorf(\"At least one host is required; set it via hosts array property on this stage\"))\n\t}\n\tfor _, host := range p.Hosts {\n\t\tif len(host) > 253 {\n\t\t\terrors = append(errors, fmt.Errorf(\"Host %v is longer than the allowed 253 characters, which is invalid for DNS; please shorten your host\", host))\n\t\t\tbreak\n\t\t}\n\n\t\tmatchesInvalidChars, _ := regexp.MatchString(\"[^a-zA-Z0-9-.]\", host)\n\t\tif matchesInvalidChars {\n\t\t\terrors = append(errors, fmt.Errorf(\"Host %v has invalid characters; only a-z, 0-9, - and . are allowed; please fix your host\", host))\n\t\t}\n\n\t\thostLabels := strings.Split(host, \".\")\n\t\tfor _, label := range hostLabels {\n\t\t\tif len(label) > 63 {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"Host %v has label %v - the parts between dots - that is longer than the allowed 63 characters, which is invalid for DNS; please shorten your host label\", host, label))\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, host := range p.InternalHosts {\n\t\tif len(host) > 253 {\n\t\t\terrors = append(errors, fmt.Errorf(\"Internal host %v is longer than the allowed 253 characters, which is invalid for DNS; please shorten your host\", host))\n\t\t\tbreak\n\t\t}\n\n\t\tmatchesInvalidChars, _ := regexp.MatchString(\"[^a-zA-Z0-9-.]\", host)\n\t\tif matchesInvalidChars {\n\t\t\terrors = append(errors, fmt.Errorf(\"Internal host %v has invalid characters; only a-z, 0-9, - and . are allowed; please fix your host\", host))\n\t\t}\n\n\t\thostLabels := strings.Split(host, \".\")\n\t\tfor _, label := range hostLabels {\n\t\t\tif len(label) > 63 {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"Internal host %v has label %v - the parts between dots - that is longer than the allowed 63 characters, which is invalid for DNS; please shorten your host label\", host, label))\n\t\t\t}\n\t\t}\n\t}\n\n\tif p.Basepath == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Basepath property is required; set it via basepath property on this stage\"))\n\t}\n\tif p.Container.Port <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Container port must be larger than zero; set it via container.port property on this stage\"))\n\t}\n\n\t// validate autoscale params\n\tif p.Autoscale.MinReplicas <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Autoscaling min replicas must be larger than zero; set it via autoscale.min property on this stage\"))\n\t}\n\tif p.Autoscale.MaxReplicas <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Autoscaling max replicas must be larger than zero; set it via autoscale.max property on this stage\"))\n\t}\n\tif p.Autoscale.CPUPercentage <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Autoscaling cpu percentage must be larger than zero; set it via autoscale.cpu property on this stage\"))\n\t}\n\n\t// validate liveness params\n\tif p.Container.LivenessProbe.Path == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness path is required; set it via container.liveness.path property on this stage\"))\n\t}\n\tif p.Container.LivenessProbe.Port <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness port must be larger than zero; set it via container.liveness.port property on this stage\"))\n\t}\n\tif p.Container.LivenessProbe.InitialDelaySeconds <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness initial delay must be larger than zero; set it via container.liveness.delay property on this stage\"))\n\t}\n\tif p.Container.LivenessProbe.TimeoutSeconds <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Liveness timeout must be larger than zero; set it via container.liveness.timeout property on this stage\"))\n\t}\n\n\t// validate readiness params\n\tif p.Container.ReadinessProbe.Path == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"Readiness path is required; set it via container.readiness.path property on this stage\"))\n\t}\n\tif p.Container.ReadinessProbe.Port <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Readiness port must be larger than zero; set it via container.readiness.port property on this stage\"))\n\t}\n\tif p.Container.ReadinessProbe.TimeoutSeconds <= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"Readiness timeout must be larger than zero; set it via container.readiness.timeout property on this stage\"))\n\t}\n\n\t// validate metrics params\n\tif p.Container.Metrics.Scrape == nil {\n\t\terrors = append(errors, fmt.Errorf(\"Metrics scrape is required; set it via container.metrics.scrape property on this stage; allowed values are true or false\"))\n\t}\n\tif p.Container.Metrics.Scrape != nil && *p.Container.Metrics.Scrape {\n\t\tif p.Container.Metrics.Path == \"\" {\n\t\t\terrors = append(errors, fmt.Errorf(\"Metrics path is required; set it via container.metrics.path property on this stage\"))\n\t\t}\n\t\tif p.Container.Metrics.Port <= 0 {\n\t\t\terrors = append(errors, fmt.Errorf(\"Metrics port must be larger than zero; set it via container.metrics.port property on this stage\"))\n\t\t}\n\t}\n\n\t// The \"sidecar\" field is deprecated, so it can be empty. But if it's specified, then we validate it.\n\tif p.Sidecar.Type != \"\" && p.Sidecar.Type != \"none\" {\n\t\terrors = p.validateSidecar(&p.Sidecar, errors)\n\t\twarnings = append(warnings, \"The sidecar field is deprecated, the sidecars list should be used instead.\")\n\t}\n\n\t// validate sidecars params\n\tfor _, sidecar := range p.Sidecars {\n\t\terrors = p.validateSidecar(sidecar, errors)\n\t}\n\n\treturn len(errors) == 0, errors, warnings\n}", "func (o Request) Valid() error {\n\tif len(o.GroupBy) == 0 {\n\t\treturn skerr.Fmt(\"at least one GroupBy value must be supplied.\")\n\t}\n\n\tvalid := false\n\tfor _, op := range AllOperations {\n\t\tif op == o.Operation {\n\t\t\tvalid = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !valid {\n\t\treturn skerr.Fmt(\"invalid Operation value: %q\", o.Operation)\n\t}\n\n\tvalid = false\n\tfor _, incomingOp := range o.Summary {\n\t\tfor _, op := range AllOperations {\n\t\t\tif op == incomingOp {\n\t\t\t\tvalid = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !valid {\n\t\t\treturn skerr.Fmt(\"invalid Summary value: %q\", incomingOp)\n\t\t}\n\t}\n\treturn nil\n}", "func ValidateRequest(key string) bool {\n\treturn true\n}", "func (lc *imgListCfg) checkParams(cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\t//check and get persistent flag\n\tvar pf *PersistentFlags\n\tpf, err = CheckPersistentFlags()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//check Flags using common parameter checker\n\tvar params utils.Params\n\tparams, err = utils.CheckFlags(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlc.params = params\n\tlc.pf = pf\n\n\treturn err\n}", "func checkInitRequest(msg *Message, conn Conn, config *Config, log log.Logger) error {\n\tif err := msg.CheckFlags(); err != nil {\n\t\treturn err\n\t}\n\tinit, err := parseInit(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := _checkInitRequest(config, init, msg.RemoteAddr); err != nil {\n\t\t// handle errors that need reply: COOKIE or DH\n\t\tif reply := initErrorNeedsReply(init, config, msg.RemoteAddr, err); reply != nil {\n\t\t\tlog.Log(\"INIT_REPLY\", err.Error())\n\t\t\tWriteMessage(conn, reply, nil, false, log)\n\t\t}\n\t\treturn err\n\t}\n\tmsg.Params = init\n\treturn nil\n}", "func TestValidParams(t *testing.T) {\n\tvalidator, err := openrtb_ext.NewBidderParamsValidator(\"../../static/bidder-params\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to fetch the json-schemas. %v\", err)\n\t}\n\n\tfor _, validParam := range validParams {\n\t\tif err := validator.Validate(openrtb_ext.BidderSmartAdserver, json.RawMessage(validParam)); err != nil {\n\t\t\tt.Errorf(\"Schema rejected smartadserver params: %s \\n Error: %s\", validParam, err)\n\t\t}\n\t}\n}", "func (d *DockerRequestPayload) valid() bool {\n\tif d.PushData.Tag == \"\" {\n\t\treturn false\n\t}\n\tif d.Repository.Name == \"\" {\n\t\treturn false\n\t}\n\tif d.Repository.Namespace == \"\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func doAnyParametersExist(args ...string) bool {\n\tif args == nil {\n\t\treturn false\n\t}\n\tfor _, arg := range args {\n\t\tif arg != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func testFormValues(t *testing.T, r *http.Request, values values) {\n\twant := url.Values{}\n\tfor k, v := range values {\n\t\twant.Add(k, v)\n\t}\n\n\tr.ParseForm()\n\tif got := r.Form; !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"Request parameters: %v, want %v\", got, want)\n\t}\n}", "func (x *fastReflection_MsgUpdateParams) IsValid() bool {\n\treturn x != nil\n}", "func isValidKeyPair(param []string) bool {\n\treturn len(param) == 2\n}", "func TestParam(t *testing.T) {\n\tparamCode := \"123456\"\n\tparamFields := \"f1;f2;f3\"\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Form.Get(\"code\") != paramCode {\n\t\t\tt.Errorf(\"Expected 'code' == %s; got %v\", paramCode, r.Form.Get(\"code\"))\n\t\t}\n\n\t\tif r.Form.Get(\"fields\") != paramFields {\n\t\t\tt.Errorf(\"Expected 'fields' == %s; got %v\", paramFields, r.Form.Get(\"fields\"))\n\t\t}\n\t}))\n\n\tdefer ts.Close()\n\n\tNew().Get(ts.URL).\n\t\tParam(\"code\", paramCode).\n\t\tParam(\"fields\", paramFields)\n}", "func (p *Params) Validate() (valid bool, warnings []string) {\n\treturn len(warnings) == 0, warnings\n}", "func (e BadRequest) IsBadRequest() {}", "func checkIfRequiredStringSliceParameterIsSupplied(propName, optionName, in string, parsedBody interface{}, varValue []string) error {\n\tif in == \"body\" {\n\t\tcontains := doesBodyContainParameter(parsedBody, propName)\n\t\tif !contains && len(varValue) == 0 {\n\t\t\treturn fmt.Errorf(\"required parameter '%s' in body (or command line option '%s') is not specified\", propName, optionName)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif len(varValue) == 0 {\n\t\treturn fmt.Errorf(\"required parameter '%s' is not specified\", optionName)\n\t}\n\treturn nil\n}", "func (req fedSearchRequest) empty() bool {\n\treturn req.Name == \"\" && req.RoutingNumber == \"\" && req.City == \"\" &&\n\t\treq.State == \"\" && req.PostalCode == \"\"\n}", "func (m *Method) HasParameters() bool {\n\treturn len(m.Parameters) != 0\n}", "func (p *ctx) ParamOk(key string) (string, bool) {\n\tfor _, p := range p.params {\n\t\tif p.Key == key {\n\t\t\treturn p.Val, true\n\t\t}\n\t}\n\n\tif c, ok := p.parent.(Context); ok {\n\t\treturn c.ParamOk(key)\n\t} else if val, ok := p.parent.Value(key).(string); ok {\n\t\treturn val, ok\n\t}\n\n\treturn \"\", false\n}", "func validateQueryParameter(field *surface_v1.Field) {\n\t_, isScalar := protoBufScalarTypes[field.NativeType]\n\tif !(field.Kind == surface_v1.FieldKind_SCALAR ||\n\t\t(field.Kind == surface_v1.FieldKind_ARRAY && isScalar) ||\n\t\t(field.Kind == surface_v1.FieldKind_REFERENCE)) {\n\t\tlog.Println(\"The query parameter with the Name \" + field.Name + \" is invalid. \" +\n\t\t\t\"Note that fields which are mapped to URL query parameters must have a primitive type or\" +\n\t\t\t\" a repeated primitive type or a non-repeated message type. \" +\n\t\t\t\"See: https://github.com/googleapis/googleapis/blob/master/google/api/http.proto#L118 for more information.\")\n\t}\n\n}", "func validateBoolParam(ctx *HttpContext, param *HttpParam) {\n\n\tparam.Raw = retrieveParamValue(ctx, param).(string)\n\n\tif len(param.Raw) == 0 && param.Required {\n\t\tappendInvalidErrorCode(ctx, param)\n\t\treturn\n\t}\n\n\tif len(param.Raw) == 0 { return }\n\n\tif val, err := strconv.ParseBool(param.Raw); err != nil {\n\t\tappendInvalidErrorCode(ctx, param)\n\t} else {\n\t\tparam.setPresentValue(val)\n\t}\n}", "func Validate(req *http.Request, required []string) (bool, string) {\n\tfor _, v := range required {\n\t\tif req.FormValue(v) == \"\" {\n\t\t\treturn false, v\n\t\t}\n\t}\n\n\treturn true, \"\"\n}", "func (d *Direct) Valid() error {\n\tswitch strings.ToUpper(d.Method) {\n\tcase GET, POST, PUT:\n\tdefault:\n\t\treturn errInvalidMethod\n\t}\n\n\treturn d.Web.Valid()\n}", "func (s *STS) validateStsRequest(req *http.Request) (StsRequestParameters, error) {\n\treqParam := StsRequestParameters{}\n\tif req == nil {\n\t\treturn reqParam, errors.New(\"request is nil\")\n\t}\n\n\t//if stsServerLog.DebugEnabled() {\n\t//\treqDump, _ := httputil.DumpRequest(req, true)\n\t//\tstsServerLog.Debugf(\"Received STS request: %s\", string(reqDump))\n\t//}\n\tif req.Method != \"POST\" {\n\t\treturn reqParam, fmt.Errorf(\"request method is invalid, should be POST but get %s\", req.Method)\n\t}\n\tif req.Header.Get(\"Content-Type\") != URLEncodedForm {\n\t\treturn reqParam, fmt.Errorf(\"request content type is invalid, should be %s but get %s\", URLEncodedForm,\n\t\t\treq.Header.Get(\"Content-type\"))\n\t}\n\tif parseErr := req.ParseForm(); parseErr != nil {\n\t\treturn reqParam, fmt.Errorf(\"failed to parse query from STS request: %v\", parseErr)\n\t}\n\tif req.PostForm.Get(\"grant_type\") != TokenExchangeGrantType {\n\t\treturn reqParam, fmt.Errorf(\"request query grant_type is invalid, should be %s but get %s\",\n\t\t\tTokenExchangeGrantType, req.PostForm.Get(\"grant_type\"))\n\t}\n\t// Only a JWT token is accepted.\n\tif req.PostForm.Get(\"subject_token\") == \"\" {\n\t\treturn reqParam, errors.New(\"subject_token is empty\")\n\t}\n\tif req.PostForm.Get(\"subject_token_type\") != SubjectTokenType {\n\t\treturn reqParam, fmt.Errorf(\"subject_token_type is invalid, should be %s but get %s\",\n\t\t\tSubjectTokenType, req.PostForm.Get(\"subject_token_type\"))\n\t}\n\treqParam.GrantType = req.PostForm.Get(\"grant_type\")\n\treqParam.Resource = req.PostForm.Get(\"resource\")\n\treqParam.Audience = req.PostForm.Get(\"audience\")\n\treqParam.Scope = req.PostForm.Get(\"scope\")\n\treqParam.RequestedTokenType = req.PostForm.Get(\"requested_token_type\")\n\treqParam.SubjectToken = req.PostForm.Get(\"subject_token\")\n\treqParam.SubjectTokenType = req.PostForm.Get(\"subject_token_type\")\n\treqParam.ActorToken = req.PostForm.Get(\"actor_token\")\n\treqParam.ActorTokenType = req.PostForm.Get(\"actor_token_type\")\n\treturn reqParam, nil\n}", "func (w *whisperer) HasParameters(paths ...*string) (bool, error) {\n\tfilters := []*ssm.ParameterStringFilter{\n\t\t{\n\t\t\tKey: aws.String(\"Name\"),\n\t\t\tOption: aws.String(\"Equals\"),\n\t\t\tValues: paths,\n\t\t},\n\t}\n\tparameters := []*ssm.ParameterMetadata{}\n\tinput := &ssm.DescribeParametersInput{ParameterFilters: filters}\n\terr := w.SSMClient.DescribeParametersPages(input, func(out *ssm.DescribeParametersOutput, lastPage bool) bool {\n\t\tparameters = append(parameters, out.Parameters...)\n\t\treturn !lastPage\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfmt.Printf(\"Parameters: %+v\\n\", parameters)\n\treturn len(parameters) == len(paths), nil\n}", "func (b *AuctionReq) Ok() error {\r\n\tswitch {\r\n\tcase strings.TrimSpace(b.AuctionID) == \"\":\r\n\t\treturn errors.IsRequiredErr(\"auction id\")\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (o Offset) Valid() error {\n\t_, err := strconv.Atoi(string(o))\n\tif err != nil {\n\t\tlog.Println(\"error while validating query param: offset\")\n\t\tlog.Printf(\"value: %s, error: %s\", string(o), err.Error())\n\t\treturn errors.New(\"invalid query param: offset\")\n\t}\n\treturn nil\n}", "func (r loginConsoleReq) Check() error {\n\tif r.RedirectURL == \"\" {\n\t\treturn trace.BadParameter(\"missing RedirectURL\")\n\t}\n\treturn nil\n}", "func (x *fastReflection_MsgUpdateParamsResponse) IsValid() bool {\n\treturn x != nil\n}", "func TestGetParams(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, r.FormValue(\"p\"))\n\t}))\n\tdefer ts.Close()\n\n\tj := jaguar.New()\n\tj.Params.Add(\"p\", \"hello\")\n\tresp, err := j.Url(ts.URL).Send()\n\tif err != nil {\n\t\tt.Errorf(\"Error: %v\", err)\n\t}\n\n\tif resp.String() != \"hello\" {\n\t\tt.Errorf(\"Unexpected result: %v\", resp.String())\n\t}\n}", "func validateQueryString(req *http.Request, key string) (string, error) {\n\tquery := req.URL.Query()\n\tvalues, ok := query[key]\n\tif !ok {\n\t\treturn \"\", NewErrMissingParam(key)\n\t}\n\n\tif len(values) != 1 {\n\t\treturn \"\", NewErrAmbigousParam(key)\n\t}\n\n\tvalue := values[0]\n\tif value == \"\" {\n\t\treturn \"\", NewErrEmptyParam(key)\n\t}\n\n\treturn value, nil\n}" ]
[ "0.74811405", "0.74811405", "0.7162727", "0.6325771", "0.6319379", "0.6283475", "0.6260787", "0.623527", "0.62105334", "0.6191409", "0.6141861", "0.61360765", "0.61277443", "0.61157846", "0.6067052", "0.60405546", "0.59803396", "0.5971343", "0.59706", "0.5940333", "0.59213793", "0.5874216", "0.5860453", "0.5825472", "0.58212715", "0.5793949", "0.5771785", "0.57646143", "0.57597417", "0.57505506", "0.5745898", "0.57166654", "0.57122976", "0.5669066", "0.5657772", "0.5628909", "0.56247187", "0.56008697", "0.5591105", "0.5568522", "0.55525917", "0.5498554", "0.5495246", "0.54887605", "0.5480333", "0.54560935", "0.5456079", "0.54547024", "0.54536325", "0.5447296", "0.5438878", "0.5435066", "0.5413189", "0.54048455", "0.5403901", "0.53982705", "0.5391183", "0.53869236", "0.5386502", "0.53789926", "0.53579867", "0.53462875", "0.5339144", "0.53365284", "0.53283894", "0.5328109", "0.53112173", "0.53097457", "0.5305496", "0.5304277", "0.5300134", "0.5295785", "0.52906567", "0.5290012", "0.5287456", "0.52839917", "0.5278646", "0.5270724", "0.52696025", "0.52686113", "0.525558", "0.5249336", "0.5248389", "0.5247594", "0.5244809", "0.52409494", "0.52328396", "0.5231518", "0.5230696", "0.5210405", "0.5204445", "0.5204284", "0.520217", "0.51994884", "0.5194251", "0.51911205", "0.5183135", "0.51825154", "0.51815474", "0.51808995", "0.51664233" ]
0.0
-1
TableName returns the table name
func (*ActivityStageDataAccessObject) TableName() string { return "activity_stages" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *Kanban) GetTableName() string {\n\treturn \"\"\n}", "func (o *Echo) GetTableName() string {\n\treturn EchoTable.String()\n}", "func (a *adapter) GetTableName() string {\n\treturn a.database\n}", "func (User) TableName() string {\n\treturn tableName\n}", "func TableName(key string) string {\n\treturn strings.TrimSuffix(key, sqlIDSuffix)\n}", "func (k *SKey) TableName() string {\n\treturn k.tableName\n}", "func (r *Role) TableName() string {\n\treturn r.tableName\n}", "func (sc SnakeCaseConvention) TableName(typeName string) string {\n\treturn sc.Convert(typeName)\n}", "func (Server) TableName() string {\n\treturn \"Server\"\n}", "func (s *DbRecorder) TableName() string {\n\treturn s.table\n}", "func (o *ProjectWebhook) GetTableName() string {\n\treturn ProjectWebhookTable.String()\n}", "func (sc SameCaseConvention) TableName(typeName string) string {\n\treturn sc.Convert(typeName)\n}", "func (c *Candle) TableName() string {\n\treturn GetCandleTableName(c.ProductCode, c.Duration)\n}", "func (upd *Update) GetTableName() string {\n\tif upd.Table != nil {\n\t\treturn upd.Table.Name.String()\n\t}\n\treturn \"\"\n}", "func (n *QualifiedTableName) TableName() string {\n\tif s := IdentName(n.Alias); s != \"\" {\n\t\treturn s\n\t}\n\treturn IdentName(n.Name)\n}", "func GetTableName(s string) (table string, err error) {\n\tif s == \"\" {\n\t\treturn \"\", errors.New(\"sql statement cannot be empty\")\n\t}\n\n\tvar selectAST sql.Select\n\tif err = sql.SQLParser.ParseString(s, &selectAST); err != nil {\n\t\treturn\n\t}\n\n\ttable = selectAST.From.Table.String()\n\treturn table, nil\n}", "func (o TopicRuleDynamodbOutput) TableName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleDynamodb) string { return v.TableName }).(pulumi.StringOutput)\n}", "func (u *User) TableName() string {\n\treturn LUTUserTableName\n}", "func (o *ExportData) GetTableName() string {\n\treturn \"\"\n}", "func (dml *DML) GetTableName() string {\n\tsort.Strings(dml.TableNames)\n\tvar tableNames []string\n\tvar previousTbl string\n\tfor _, name := range dml.TableNames {\n\t\tif name != previousTbl {\n\t\t\ttableNames = append(tableNames, name)\n\t\t\tpreviousTbl = name\n\t\t}\n\t}\n\treturn strings.Join(tableNames, \", \")\n}", "func (jn *SemiJoin) GetTableName() string {\n\treturn jn.Left.GetTableName() + \"_\" + jn.Right.GetTableName()\n}", "func (o TopicRuleErrorActionDynamodbOutput) TableName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleErrorActionDynamodb) string { return v.TableName }).(pulumi.StringOutput)\n}", "func (TblUser) TableName() string {\n\treturn \"tblUser\"\n}", "func (User) TableName() string {\n\treturn \"dbo.Users\"\n}", "func (d *DynamoDBMetastore) GetTableName() string {\n\treturn d.tableName\n}", "func (s *Set) GetTableName() string {\n\treturn \"\"\n}", "func (lc LowerCaseConvention) TableName(typeName string) string {\n\treturn lc.Convert(typeName)\n}", "func (um UserModel) GetTableName() string {\n\treturn UserTabName\n}", "func (o TableOutput) TableName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Table) pulumi.StringPtrOutput { return v.TableName }).(pulumi.StringPtrOutput)\n}", "func (l *Lock) GetTableName() string {\n\treturn \"dual\"\n}", "func (f *Film) TableName() string {\n\treturn \"film\"\n}", "func (u *User) TableName() string {\n\treturn userTableName\n}", "func (Account) TableName() string {\n\ttableName := \"accounts\"\n\n\tif namespace.GetNamespace() != \"\" {\n\t\treturn namespace.GetNamespace() + \"_\" + tableName\n\t}\n\n\treturn tableName\n}", "func (a *Action) TableName() string {\n\tconst ormTableName = \"actions\"\n\treturn ormTableName\n}", "func getTableName(metricName string) string {\n\tparts := strings.Split(metricName, \"_\")\n\tname := parts[0]\n\tif len(parts) > 1 {\n\t\tname = fmt.Sprintf(\"%s_%s\", name, parts[1])\n\t}\n\treturn name\n}", "func getTableName(object interface{}) string {\n\tstringName := fmt.Sprintf(\"%ss\", strings.ToLower(getType(object)))\n\treturn stringName\n}", "func TableName(name string) string {\n\tif IsTest {\n\t\treturn fmt.Sprintf(\"%v_test\", name)\n\t}\n\treturn fmt.Sprintf(\"%v_development\", name)\n}", "func (Bank) TableName() string {\n\treturn \"bank\"\n}", "func (Alumno) TableName() string {\n\treturn \"alumnos\"\n}", "func (z *Zzz) SqlTableName() string { //nolint:dupl false positive\n\treturn `\"zzz\"`\n}", "func (t *Commit) TableName() string {\n\treturn CommitTableName\n}", "func (m *Migration) TableName() string {\n\treturn \"dbMigration\"\n}", "func (o SecondaryIndexOutput) TableName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SecondaryIndex) pulumi.StringOutput { return v.TableName }).(pulumi.StringOutput)\n}", "func (o *<%= classedName %>) TableName() string {\n\treturn \"<%= tableName %>\"\n}", "func (u User) Table() string {\n\treturn tableName\n}", "func (m *JfscSyTuFile) TableName() string {\n\treturn \"jfsc_sy_tu_file\"\n}", "func (recordFile) TableName() string {\n\treturn \"record_file\"\n}", "func (s *SchemaMigration) TableName() string {\n\treturn \"schema_migrations\"\n}", "func (TramDoTrieu) TableName() string {\n\treturn \"TramDoTrieu\"\n}", "func (s *Schema) TableName() string {\n\treturn \"p2p_preheat_policy\"\n}", "func (o TopicRuleErrorActionTimestreamOutput) TableName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleErrorActionTimestream) string { return v.TableName }).(pulumi.StringOutput)\n}", "func (o TopicRuleTimestreamOutput) TableName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleTimestream) string { return v.TableName }).(pulumi.StringOutput)\n}", "func (i *Install) TableName() string {\r\n\treturn \"install\"\r\n}", "func (s *Stage) TableName() string {\n\treturn \"stage\"\n}", "func (sub *Transcription) TableName() string {\n\treturn \"transcriptions\"\n}", "func (u StudentInfo) TableName() string {\n\treturn \"student\"\n}", "func (c *Contract) TableName() string {\n\treturn `1_contracts`\n}", "func (Client) TableName() string {\n\treturn \"client\"\n}", "func (t *ACLRole) TableName() string {\n\treturn ACLRoleTableName\n}", "func (s *UpBaseInfo) TableName() string {\n\treturn TableNameUpBaseInfo\n}", "func (o TopicRuleDynamodbPtrOutput) TableName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TopicRuleDynamodb) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.TableName\n\t}).(pulumi.StringPtrOutput)\n}", "func (obj *Code) TableName() string {\n\treturn \"codes_records\"\n}", "func (ReplaceStrings) TableName() string {\n\treturn \"dbo.SMART_Invoice_Porting_Validation\"\n}", "func (model *Barang) TableName() string {\n\treturn BarangTableName\n}", "func (config *AccountConfig) GetTableName() string {\n\treturn \"accounts\"\n}", "func TableNameNoSchema(dialect Dialect, mapper names.Mapper, tableName interface{}) string {\n\tquote := dialect.Quoter().Quote\n\tswitch tableName.(type) {\n\tcase []string:\n\t\tt := tableName.([]string)\n\t\tif len(t) > 1 {\n\t\t\treturn fmt.Sprintf(\"%v AS %v\", quote(t[0]), quote(t[1]))\n\t\t} else if len(t) == 1 {\n\t\t\treturn quote(t[0])\n\t\t}\n\tcase []interface{}:\n\t\tt := tableName.([]interface{})\n\t\tl := len(t)\n\t\tvar table string\n\t\tif l > 0 {\n\t\t\tf := t[0]\n\t\t\tswitch f.(type) {\n\t\t\tcase string:\n\t\t\t\ttable = f.(string)\n\t\t\tcase names.TableName:\n\t\t\t\ttable = f.(names.TableName).TableName()\n\t\t\tdefault:\n\t\t\t\tv := utils.ReflectValue(f)\n\t\t\t\tt := v.Type()\n\t\t\t\tif t.Kind() == reflect.Struct {\n\t\t\t\t\ttable = names.GetTableName(mapper, v)\n\t\t\t\t} else {\n\t\t\t\t\ttable = quote(fmt.Sprintf(\"%v\", f))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif l > 1 {\n\t\t\treturn fmt.Sprintf(\"%v AS %v\", quote(table), quote(fmt.Sprintf(\"%v\", t[1])))\n\t\t} else if l == 1 {\n\t\t\treturn quote(table)\n\t\t}\n\tcase names.TableName:\n\t\treturn tableName.(names.TableName).TableName()\n\tcase string:\n\t\treturn tableName.(string)\n\tcase reflect.Value:\n\t\tv := tableName.(reflect.Value)\n\t\treturn names.GetTableName(mapper, v)\n\tdefault:\n\t\tv := utils.ReflectValue(tableName)\n\t\tt := v.Type()\n\t\tif t.Kind() == reflect.Struct {\n\t\t\treturn names.GetTableName(mapper, v)\n\t\t}\n\t\treturn quote(fmt.Sprintf(\"%v\", tableName))\n\t}\n\treturn \"\"\n}", "func (u UserUpload) TableName() string {\n\treturn \"user_uploads\"\n}", "func (User) TableName() string {\n\treturn \"user\"\n}", "func (User) TableName() string {\n\treturn \"user\"\n}", "func (User) TableName() string {\n\treturn \"user\"\n}", "func (User) TableName() string {\n\treturn \"user\"\n}", "func (u User) TableName() string {\n\treturn \"Users\"\n}", "func (Project) TableName() string {\n\treturn \"project\"\n}", "func (e *Permission) TableName() string {\n\treturn \"permission\"\n}", "func (m Resource) TableName() string {\n\treturn \"resource\"\n}", "func (b *Binary) TableName() string {\n\tif b.ecosystem == 0 {\n\t\tb.ecosystem = 1\n\t}\n\treturn `1_binaries`\n}", "func (user *User) TableName() string {\n return \"users\"\n}", "func (m *Stucasting) TableName() string {\n\treturn \"stucasting\"\n}", "func (m *Stucasting) TableName() string {\n\treturn \"stucasting\"\n}", "func (m *Files) TableName() string {\n\treturn \"files\"\n}", "func (StudentRecord) TableName() string {\n\treturn \"StudentRecords\"\n}", "func FullTableName(tableName string) string {\n\tconf, confErr := config.GetAppConfig()\n\tif confErr != nil {\n\t\tlog.Fatalf(\"read database config err %v \", confErr)\n\t}\n\n\treturn conf.App.DataBase.Prefix + tableName\n}", "func (p Project) TableName() string {\n\treturn \"project\"\n}", "func (d *Daily) TableName() string {\n\treturn \"daily\"\n}", "func (cd *ConnectionDetails) MigrationTableName() string {\n\treturn defaults.String(cd.Options[\"migration_table_name\"], \"schema_migration\")\n}", "func (c *Center) TableName() string {\n\treturn \"center\"\n}", "func (Practica) TableName() string {\n\treturn \"practicas\"\n}", "func (a *Action) TableName() string {\n\treturn \"action\"\n}", "func (model *Produk) TableName() string {\n\treturn ProdukTableName\n}", "func (s Course) TableName() string {\n\treturn \"course\"\n}", "func TableName(schema, name string) string {\n\treturn fmt.Sprintf(\"`%s`.`%s`\", escapeName(schema), escapeName(name))\n}", "func (n *TableValuedFunction) TableName() string {\n\tif s := IdentName(n.Alias); s != \"\" {\n\t\treturn s\n\t}\n\treturn IdentName(n.Name)\n}", "func (Company) TableName() string {\n\treturn \"company\"\n}", "func (m *StuFailToLive) TableName() string {\n\treturn \"stu_fail_to_live\"\n}", "func (o GetSecondaryIndexesResultOutput) TableName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecondaryIndexesResult) string { return v.TableName }).(pulumi.StringOutput)\n}", "func (o TopicRuleErrorActionDynamodbPtrOutput) TableName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TopicRuleErrorActionDynamodb) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.TableName\n\t}).(pulumi.StringPtrOutput)\n}", "func (Metric) TableName() string {\r\n\treturn tableNameMetrics\r\n}", "func (o TopicRuleDynamodbv2PutItemOutput) TableName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleDynamodbv2PutItem) string { return v.TableName }).(pulumi.StringOutput)\n}", "func (Files) TableName() string {\n\treturn \"files\"\n}", "func (Person) TableName() string {\n\treturn \"person\"\n}", "func (m *ExportLog) TableName() string {\n\treturn \"export_log\"\n}" ]
[ "0.79145706", "0.7840827", "0.778527", "0.7717833", "0.7699883", "0.76872", "0.7672675", "0.7612454", "0.76049006", "0.7603398", "0.757601", "0.7575903", "0.754835", "0.7546384", "0.75206995", "0.75073695", "0.7501995", "0.7449985", "0.74470353", "0.7442914", "0.743858", "0.74336046", "0.74301434", "0.7412265", "0.740654", "0.7403747", "0.73793596", "0.7375192", "0.737279", "0.7364457", "0.73543113", "0.7333242", "0.73168564", "0.73163927", "0.7297773", "0.72819835", "0.7256667", "0.72538126", "0.72530425", "0.7250132", "0.7247612", "0.72470266", "0.72405165", "0.7232273", "0.722293", "0.7220026", "0.72134435", "0.72092444", "0.72020763", "0.72001386", "0.7184364", "0.7183542", "0.71661776", "0.71534467", "0.7149589", "0.71456784", "0.7144463", "0.7134644", "0.7130387", "0.7130088", "0.7129824", "0.71257025", "0.712497", "0.7120579", "0.711354", "0.71094733", "0.7107595", "0.7106795", "0.7106795", "0.7106795", "0.7106795", "0.71044415", "0.70998424", "0.709794", "0.70966005", "0.7094108", "0.7089023", "0.7084053", "0.7084053", "0.7077539", "0.7074552", "0.7068246", "0.70612794", "0.7055711", "0.7055656", "0.7052509", "0.70451623", "0.7044426", "0.70414823", "0.70414704", "0.70326227", "0.70266604", "0.7020472", "0.70181954", "0.7012964", "0.70117563", "0.70108443", "0.7008349", "0.7004977", "0.6992018", "0.6990217" ]
0.0
-1
InsertOne inserts a new activity stage
func (*ActivityStageDataAccessObject) InsertOne(stage *ActivityStage) { _, err := orm.Table(ActivityStageDAO.TableName()).Insert(stage) logger.LogIfError(err) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *DBRepository) insertOne(ctx context.Context, travel *Travel) error {\n\ttravel.ObjectID = primitive.NewObjectID()\n\tif _, err := d.Collection.InsertOne(ctx, travel); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func insertOneMovie(movie model.Netflix){\n\tinserted, err := collection.InsertOne(context.Background(),movie)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Inserted one movie in db with id:\", inserted.InsertedID)\n}", "func (h *handler) InsertOne(ctx context.Context, params db.Params) error {\n\treturn h.getDatabase(params.Database).C(params.Collection).Insert(params.UpsertData)\n}", "func insertOneTask(task models.ToDoList) {\n\tinsertResult, err := collection.InsertOne(context.Background(), task)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Inserted a Single Record \", insertResult.InsertedID)\n}", "func InsertOne(i interface{}, coll string) {\n\tfmt.Println(\"controllers: insert one invoked\")\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\n\n\t_, err := db.Collection(coll).InsertOne(ctx, i)\n\tutilities.Catch(err)\n\n}", "func (a *Activity) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif a._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetActivityTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`name, activity_type_id, activity_type_code, content, activity_image, image_url, image_color, status, sort, extend, admin_id, admin_name, start_time, end_time, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, a.Name, a.ActivityTypeID, a.ActivityTypeCode, a.Content, a.ActivityImage, a.ImageURL, a.ImageColor, a.Status, a.Sort, a.Extend, a.AdminID, a.AdminName, a.StartTime, a.EndTime, a.CreatedAt, a.UpdatedAt)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, a.Name, a.ActivityTypeID, a.ActivityTypeCode, a.Content, a.ActivityImage, a.ImageURL, a.ImageColor, a.Status, a.Sort, a.Extend, a.AdminID, a.AdminName, a.StartTime, a.EndTime, a.CreatedAt, a.UpdatedAt)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, a.Name, a.ActivityTypeID, a.ActivityTypeCode, a.Content, a.ActivityImage, a.ImageURL, a.ImageColor, a.Status, a.Sort, a.Extend, a.AdminID, a.AdminName, a.StartTime, a.EndTime, a.CreatedAt, a.UpdatedAt)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\ta.ID = uint(id)\n\ta._exists = true\n\n\treturn nil\n}", "func (*SeatDataAccessObject) InsertOne(s *Seat) error {\n\t_, err := orm.InsertOne(s)\n\treturn err\n}", "func (link *Link) insertOne(ctx context.Context, exec *sqlx.Tx) (id int64, err error) {\n\terr = exec.QueryRowxContext(\n\t\tctx,\n\t\t`\n INSERT INTO entityone(entityone_id, time_created)\n VALUES(DEFAULT, DEFAULT)\n RETURNING entityone_id\n `).Scan(&id)\n\tif err != nil {\n\t\treturn id, fmt.Errorf(\"entityone Insert(): %v\", err)\n\t}\n\n\treturn id, nil\n}", "func InsertActivity(name *string) (*int64, error) {\n\tvar db, err = GetDatabase()\n\tif db == nil {\n\t\tlog.Println(\"Error in InsertActivity: DB connection unsuccessful.\")\n\t\treturn nil, err\n\t}\n\n\tvar res sql.Result\n\tres, err = db.Exec(`INSERT INTO activities (name) VALUES ($1)`, *name)\n\tif err != nil {\n\t\tlog.Println(\"Error in InsertActivity: \", err)\n\t\treturn nil, err\n\t}\n\n\tvar lastInsertID int64\n\tlastInsertID, err = res.LastInsertId()\n\tif err != nil {\n\t\tlog.Println(\"Error in InsertActivity: \", err)\n\t\treturn nil, err\n\t}\n\n\treturn &lastInsertID, nil\n}", "func (mgr *EntryManager) InsertOne(entry *Entry) {\n\tdb, err := sql.Open(\"postgres\", mgr.ConnStr)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tdefer db.Close()\n\n\tqueryStr := `\n\t\tINSERT INTO entries (id, title, date_posted, tags) \n\t\tVALUES ($1, $2, $3, $4);\n\t`\n\n\t// Create a \"prepared\" SQL statement context\n\tstmt, err := db.Prepare(queryStr)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer stmt.Close()\n\n\t// Execute statement\n\t_, err = stmt.Exec(\n\t\tentry.ID,\n\t\tentry.Title,\n\t\tentry.DatePosted,\n\t\tstrings.Join(entry.Tags, \",\"),\n\t)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (r *TaskRepository) Insert(db db.DB, Task *entities.Task) error {\n\t_, err := db.NamedExec(`\n\tINSERT INTO tasks (uuid,title,user_id,status,created_at,updated_at)\n\tVALUES (:uuid, :title, :user_id, :status, now(), now())`, Task)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error inserting task to db: %w\", err)\n\t}\n\n\treturn nil\n}", "func (m MongoClient) InsertOne(ctx context.Context, data interface{}) (interface{}, error) {\n\tres, err := m.Conn.InsertOne(ctx, data)\n\treturn res.InsertedID, err\n}", "func (a *Activity) createActivity() error {\n\n\ttags := map[string]string{\n\t\t\"unit\": a.Unit,\n\t\t\"type\": \"activity\",\n\t}\n\tfields := map[string]interface{}{\n\t\t\"value\": a.Value,\n\t}\n\n\tbps, err := client.NewBatchPoints(client.BatchPointsConfig{\n\t\tDatabase: database.Dbname,\n\t\tPrecision: \"ms\",\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpoint, err := client.NewPoint(\n\t\ta.Name,\n\t\ttags,\n\t\tfields,\n\t\ttime.Now(),\n\t)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbps.AddPoint(point)\n\n\terr = database.InfluxDBcon.Write(bps)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func insertObject(object *remember.DataObject, connection *sql.DB) error {\n\tstatement, err := connection.Prepare(CREATE)\n\tif nil != err {\n\t\treturn err\n\t}\n\tdefer statement.Close()\n\n\tobject.CreatedAt = time.Now()\n\tobject.UpdatedAt = time.Now()\n\n\tresponse, err := statement.Exec(\n\t\tobject.Title,\n\t\tobject.GroupId,\n\t\tobject.Payload,\n\t\tobject.CreatedAt.Unix(),\n\t\tobject.UpdatedAt.Unix(),\n\t)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tobject.ID, err = response.LastInsertId()\n\treturn err\n}", "func (xpss *XPipelineSalesStage) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif xpss._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tconst sqlstr = `INSERT INTO x_showroom.x_pipeline_sales_stages (` +\n\t\t`name, probability, seq_num, active_flag, sales_method_id, created_by, updated_by, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, xpss.Name, xpss.Probability, xpss.SeqNum, xpss.ActiveFlag, xpss.SalesMethodID, xpss.CreatedBy, xpss.UpdatedBy, xpss.CreatedAt, xpss.UpdatedAt)\n\tres, err := db.Exec(sqlstr, xpss.Name, xpss.Probability, xpss.SeqNum, xpss.ActiveFlag, xpss.SalesMethodID, xpss.CreatedBy, xpss.UpdatedBy, xpss.CreatedAt, xpss.UpdatedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\txpss.ID = uint(id)\n\txpss._exists = true\n\n\treturn nil\n}", "func InsertOneBoard(board schema.Board, ownerID string) {\n\tfmt.Println(board)\n\tboard.ID = primitive.NewObjectID()\n\tboard.OwnerID = ownerID\n\n\t_, err := db.Collection(COLLNAME).InsertOne(context.Background(), board)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (link *Link) Create(\n\tctx context.Context,\n\ttx *sqlx.Tx,\n\tactionID int,\n\tstatusID int,\n) (int64, error) {\n\tid, err := link.insertOne(ctx, tx)\n\tif err != nil {\n\t\treturn id, fmt.Errorf(\"entityone Create(): %v\", err)\n\t}\n\n\terr = link.SaveStatus(ctx, tx, id, actionID, statusID)\n\tif err != nil {\n\t\treturn id, fmt.Errorf(\"entityone Create(): %v\", err)\n\t}\n\n\treturn id, nil\n}", "func (session *Session) InsertOne(bean interface{}) (int64, error) {\n\treturn session.Session.InsertOne(bean)\n}", "func (repo *mongoBaseRepo) InsertOne(doc interface{}, args ...interface{}) (interface{}, error) {\n\ttimeout := DefaultTimeout\n\topts := &options.InsertOneOptions{}\n\tvar authUser interface{}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tswitch val := args[i].(type) {\n\t\tcase time.Duration:\n\t\t\ttimeout = val\n\t\tcase *options.InsertOneOptions:\n\t\t\topts = val\n\t\tcase *AuditAuth:\n\t\t\tauthUser = val.User\n\t\t}\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tres, err := repo.collection.InsertOne(ctx, doc, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif authUser != nil && repo.audit != nil && repo.audit.IsActive() {\n\n\t\t// Convert doc to bson.M\n\t\tbm, err := ToBsonMap(doc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Add _id to data\n\t\tif _, ok := bm[\"_id\"]; !ok {\n\t\t\tbm[\"_id\"] = res.InsertedID\n\t\t}\n\n\t\t// Send to audit\n\t\trepo.audit.Send(bson.M{\n\t\t\t\"collection\": repo.collection.Name(),\n\t\t\t\"action\": Insert,\n\t\t\t\"user\": authUser,\n\t\t\t\"data\": bm,\n\t\t})\n\t}\n\n\treturn res.InsertedID, nil\n}", "func (db *Client) InsertOne(collection string, document *bson.M) (*mongo.InsertOneResult, error) {\n\treturn db.Database.Collection(collection).InsertOne(context.TODO(), document)\n}", "func (this *ActivityREST) Create(c *hera.Context) error {\n\t\tparams\t\t:= c.Params\n\t\tuid\t\t\t:= params[\"uid\"]\n\t\ttitle\t\t:= params[\"title\"]\n\t\ttime\t\t:= params[\"time\"]\n\t\tsite\t\t:= params[\"site\"]\n\t\tis_discuss\t:= params[\"is_discuss\"]\n\t\ttags\t\t:= params[\"tags\"]\n\t\tremark\t\t:= params[\"remark\"]\n\t\tsex\t\t\t:= params[\"sex\"]\n\t\tpeople_num\t:= params[\"people_num\"]\n\t\tlongitude, _ \t:= strconv.ParseFloat(params[\"longitude\"], 64) //jingdu\n\t\tlatitude, _\t:= strconv.ParseFloat(params[\"latitude\"], 64) //weidu\n\n\t\tentity_obj := NewActivity()\n\t\tentity_obj.Create(uid, title, time, site, is_discuss, tags, remark, sex, people_num, longitude, latitude)\n\t\treturn c.Success(\"\")\n}", "func (s *Store) InsertOne(collection string, data interface{}) (*mongo.InsertOneResult, error) {\n\tvar ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tdb := s.db.Database(dbName)\n\tcol := db.Collection(collection)\n\tr, err := col.InsertOne(ctx, data)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(\"Inserted to: \", col.Name())\n\n\treturn r, nil\n}", "func (repo *ActorRepository) Insert(ctx context.Context, ent *entity.Actor) error {\n\tif err := repo.db.\n\t\tWithContext(ctx).\n\t\tModel(&entity.Actor{}).\n\t\tCreate(ent).\n\t\tError; err != nil {\n\t\treturn errors.Wrap(err, \"[ActorRepository-Insert]\")\n\t}\n\treturn nil\n}", "func (ac *ActivityCreate) Save(ctx context.Context) (*Activity, error) {\n\tif ac.activity == nil {\n\t\treturn nil, errors.New(\"ent: missing required field \\\"activity\\\"\")\n\t}\n\tif ac.logged_at == nil {\n\t\tv := activity.DefaultLoggedAt()\n\t\tac.logged_at = &v\n\t}\n\treturn ac.sqlSave(ctx)\n}", "func (backRepoTask *BackRepoTaskStruct) CommitPhaseOneInstance(task *models.Task) (Error error) {\n\n\t// check if the task is not commited yet\n\tif _, ok := (*backRepoTask.Map_TaskPtr_TaskDBID)[task]; ok {\n\t\treturn\n\t}\n\n\t// initiate task\n\tvar taskDB TaskDB\n\ttaskDB.CopyBasicFieldsFromTask(task)\n\n\tquery := backRepoTask.db.Create(&taskDB)\n\tif query.Error != nil {\n\t\treturn query.Error\n\t}\n\n\t// update stores\n\t(*backRepoTask.Map_TaskPtr_TaskDBID)[task] = taskDB.ID\n\t(*backRepoTask.Map_TaskDBID_TaskPtr)[taskDB.ID] = task\n\t(*backRepoTask.Map_TaskDBID_TaskDB)[taskDB.ID] = &taskDB\n\n\treturn\n}", "func (r *FloodlightActivitiesService) Insert(profileId int64, floodlightactivity *FloodlightActivity) *FloodlightActivitiesInsertCall {\n\tc := &FloodlightActivitiesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.profileId = profileId\n\tc.floodlightactivity = floodlightactivity\n\treturn c\n}", "func (m *BookingModel) Insert(booking models.Booking) (*mongo.InsertOneResult, error) {\n\treturn m.C.InsertOne(context.TODO(), booking)\n}", "func (s *SQL) InsertOne(block interface{}) error {\n\tif err := s.C.Insert(block); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}", "func insertPracticeActivity(log LoginActivity) error {\n\tdbinfo := dbinfo.Db()\n\tdb, err := sql.Open(dbinfo[0], dbinfo[1]) // gets the database information from the dbinfo package and enters the returned slice values as arguments\n\tif err != nil {\n\t\treturn errors.New(\"Unable to open the database connecting in the insertPracticeActivity log\")\n\t}\n\tdefer db.Close()\n\n\tinitUser := \"INSERT INTO testPracticeLog (id, userid, loginTime, failures, refreshes, secretLength) VALUES (DEFAULT, ?, ?, ?, ?, ?)\"\n\tstmtIns, err := db.Prepare(initUser)\n\tif err != nil {\n\t\treturn errors.New(\"Issue preparing to log user's practice activity\")\n\t}\n\tdefer stmtIns.Close()\n\n\t_, err = stmtIns.Exec(log.UserID, log.LoginTime, log.Failures, log.Refreshes, log.SecretLength)\n\tif err != nil {\n\t\terrMessage := fmt.Sprintf(\"%v\\nThere was an issue executing the query to insert a new practice activity log.\\nError is\", err)\n\t\treturn errors.New(errMessage)\n\t}\n\n\treturn nil\n}", "func (f *MongoFactory) InsertOne(collectionName string, element interface{}) *mongo.InsertOneResult {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tcollection := f.Database.Collection(collectionName)\n\n\tinsertResult, err := collection.InsertOne(ctx, element)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn insertResult\n}", "func Insertintoeventdb(usercollection *mongo.Collection, e Event) {\n\n\tinsertResult, err := usercollection.InsertOne(context.TODO(), e)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Inserted a single document: \", insertResult.InsertedID)\n}", "func (a *Actor) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif a._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key must be provided\n\tconst sqlstr = `INSERT INTO public.actor (` +\n\t\t`actor_id, first_name, last_name, last_update` +\n\t\t`) VALUES (` +\n\t\t`$1, $2, $3, $4` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, a.ActorID, a.FirstName, a.LastName, a.LastUpdate)\n\terr = db.QueryRow(sqlstr, a.ActorID, a.FirstName, a.LastName, a.LastUpdate).Scan(&a.ActorID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\ta._exists = true\n\n\treturn nil\n}", "func (v *Visit) Insert(db XODB) error {\n\tvar err error\n\n\t// sql insert query, primary key must be provided\n\tconst sqlstr = `INSERT INTO custmchat.visit (` +\n\t\t`id, ent_id, trace_id, visit_page_cnt, residence_time_sec, browser_family, browser_version_string, browser_version, os_category, os_family, os_version_string, os_version, platform, ua_string, ip, country, province, city, isp, first_page_source, first_page_source_keyword, first_page_source_domain, first_page_source_url, first_page_title, first_page_domain, first_page_url, latest_title, latest_url, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, v.ID, v.EntID, v.TraceID, v.VisitPageCnt, v.ResidenceTimeSec, v.BrowserFamily, v.BrowserVersionString, v.BrowserVersion, v.OsCategory, v.OsFamily, v.OsVersionString, v.OsVersion, v.Platform, v.UaString, v.IP, v.Country, v.Province, v.City, v.Isp, v.FirstPageSource, v.FirstPageSourceKeyword, v.FirstPageSourceDomain, v.FirstPageSourceURL, v.FirstPageTitle, v.FirstPageDomain, v.FirstPageURL, v.LatestTitle, v.LatestURL, v.CreatedAt, v.UpdatedAt)\n\t_, err = db.Exec(sqlstr, v.ID, v.EntID, v.TraceID, v.VisitPageCnt, v.ResidenceTimeSec, v.BrowserFamily, v.BrowserVersionString, v.BrowserVersion, v.OsCategory, v.OsFamily, v.OsVersionString, v.OsVersion, v.Platform, v.UaString, v.IP, v.Country, v.Province, v.City, v.Isp, v.FirstPageSource, v.FirstPageSourceKeyword, v.FirstPageSourceDomain, v.FirstPageSourceURL, v.FirstPageTitle, v.FirstPageDomain, v.FirstPageURL, v.LatestTitle, v.LatestURL, v.CreatedAt, v.UpdatedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CreateActivity(ex db.Execer, deviceid, activitytype string) error {\n\n\tstr := `\n\t\tINSERT INTO users_activity\n\t\t\t(device_id, activity_type)\n\t\t\tVALUES\n\t\t\t(?, ?)\n\t\t`\n\t_, err := ex.Exec(str, deviceid, activitytype)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func insertPost(post Post) {\n\tcollection := client.Database(\"Go_task\").Collection(\"posts\")\n\tinsertResult, err := collection.InsertOne(context.TODO(), post)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Inserted post with ID:\", insertResult.InsertedID)\n}", "func (ac *ActivityCreate) Save(ctx context.Context) (*Activity, error) {\n\tif _, ok := ac.mutation.ACTIVITYNAME(); !ok {\n\t\treturn nil, &ValidationError{Name: \"ACTIVITYNAME\", err: errors.New(\"ent: missing required field \\\"ACTIVITYNAME\\\"\")}\n\t}\n\tif v, ok := ac.mutation.ACTIVITYNAME(); ok {\n\t\tif err := activity.ACTIVITYNAMEValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"ACTIVITYNAME\", err: fmt.Errorf(\"ent: validator failed for field \\\"ACTIVITYNAME\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := ac.mutation.Added(); !ok {\n\t\treturn nil, &ValidationError{Name: \"added\", err: errors.New(\"ent: missing required field \\\"added\\\"\")}\n\t}\n\tif _, ok := ac.mutation.Hours(); !ok {\n\t\treturn nil, &ValidationError{Name: \"hours\", err: errors.New(\"ent: missing required field \\\"hours\\\"\")}\n\t}\n\tif v, ok := ac.mutation.Hours(); ok {\n\t\tif err := activity.HoursValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"hours\", err: fmt.Errorf(\"ent: validator failed for field \\\"hours\\\": %w\", err)}\n\t\t}\n\t}\n\tvar (\n\t\terr error\n\t\tnode *Activity\n\t)\n\tif len(ac.hooks) == 0 {\n\t\tnode, err = ac.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*ActivityMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tac.mutation = mutation\n\t\t\tnode, err = ac.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(ac.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = ac.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, ac.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func InsertGoal(goal *models.Goal) error {\n\t// begin transaction\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// insert goal into goals table\n\tres, err := tx.Exec(\"INSERT INTO goal(name,date,note) VALUES(?,?,?)\", goal.Name, goal.Date, goal.Note)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tgoal.ID, err = res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check if goal has progresses\n\tif len(goal.Progress) > 0 {\n\n\t\tfor i := range goal.Progress {\n\t\t\tres, err = tx.Exec(\"INSERT INTO progress (goal_id, value, date, note) VALUES(?,?,?,?)\",\n\t\t\t\tgoal.ID, goal.Progress[i].Value, goal.Progress[i].Date, goal.Progress[i].Note)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tgoal.Progress[i].ID, err = res.LastInsertId()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// commit transaction\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *BasePlSqlParserListener) EnterSingle_table_insert(ctx *Single_table_insertContext) {}", "func (a *Activity) Save(ctx context.Context) error {\n\tif a.Exists() {\n\t\treturn a.Update(ctx)\n\t}\n\n\treturn a.Insert(ctx)\n}", "func (a *Agent) PreInsert(s gorp.SqlExecutor) error {\n\ta.Created = time.Now() // or time.Now().UnixNano()\n\ta.Updated = a.Created\n\treturn nil\n}", "func (smr *StoryMongoRepository) Insert(entity interface{}) (string, error) {\n\ts := entity.(models.Story)\n\treturn smr.bmr.Insert(&s, \"stories\")\n}", "func (t *Transaction) Stage(db *pg.DB) error {\n\t// Ensure the sender exists\n\tsender, err := account.GetAccountByID(t.FromID, db)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\t// Block funds\n\terr = sender.Reserve(t.Amount, db)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tt.Delete(db)\n\t\treturn err\n\t}\n\t// Create the transaction\n\t_, err = db.Model(t).Insert()\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\treturn err\n}", "func (o *ActivityLog) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"dbmodel: no activity_logs provided for insertion\")\n\t}\n\n\tvar err error\n\tif !boil.TimestampsAreSkipped(ctx) {\n\t\tcurrTime := time.Now().In(boil.GetLocation())\n\n\t\tif o.CreatedAt.IsZero() {\n\t\t\to.CreatedAt = currTime\n\t\t}\n\t\tif o.UpdatedAt.IsZero() {\n\t\t\to.UpdatedAt = currTime\n\t\t}\n\t}\n\n\tif err := o.doBeforeInsertHooks(ctx, exec); err != nil {\n\t\treturn err\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(activityLogColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\tactivityLogInsertCacheMut.RLock()\n\tcache, cached := activityLogInsertCache[key]\n\tactivityLogInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\tactivityLogAllColumns,\n\t\t\tactivityLogColumnsWithDefault,\n\t\t\tactivityLogColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(activityLogType, activityLogMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(activityLogType, activityLogMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO \\\"activity_logs\\\" (\\\"%s\\\") %%sVALUES (%s)%%s\", strings.Join(wl, \"\\\",\\\"\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO \\\"activity_logs\\\" () VALUES ()%s%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT \\\"%s\\\" FROM \\\"activity_logs\\\" WHERE %s\", strings.Join(returnColumns, \"\\\",\\\"\"), strmangle.WhereClause(\"\\\"\", \"\\\"\", 0, activityLogPrimaryKeyColumns))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, vals)\n\t}\n\tresult, err := exec.ExecContext(ctx, cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"dbmodel: unable to insert into activity_logs\")\n\t}\n\n\tvar lastID int64\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tlastID, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn ErrSyncFail\n\t}\n\n\to.ID = int64(lastID)\n\tif lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == activityLogMapping[\"id\"] {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.ID,\n\t}\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.retQuery)\n\t\tfmt.Fprintln(writer, identifierCols...)\n\t}\n\terr = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"dbmodel: unable to populate default values for activity_logs\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\tactivityLogInsertCacheMut.Lock()\n\t\tactivityLogInsertCache[key] = cache\n\t\tactivityLogInsertCacheMut.Unlock()\n\t}\n\n\treturn o.doAfterInsertHooks(ctx, exec)\n}", "func (t *Transform) Create(db *DB) error {\n\tif t.CreatedAt != nil {\n\t\treturn errors.New(\"Transform already appears to be persisted\")\n\t}\n\n\tnow := util.TimePtr(time.Now())\n\tt.CreatedAt = now\n\tt.UpdatedAt = now\n\terr := db.Insert(t)\n\treturn err\n}", "func (d *DeliveryCity) Insert() (code int, err error) {\n mConn := mymongo.Conn()\n defer mConn.Close()\n\n c := mConn.DB(\"\").C(DBTableDeliveryCity)\n d.ID = bson.NewObjectId()\n\n err = c.Insert(d)\n if err != nil {\n if mgo.IsDup(err) {\n code = ErrDupRows\n } else {\n code = ErrDatabase\n }\n } else {\n code = 0\n }\n\n return\n}", "func (m *mongoDriver) InsertOne(ctx context.Context, query bson.M, opts *options.InsertOneOptions) (primitive.ObjectID, error) {\n\tcoll := m.client.Database(database).Collection(collection)\n\tres, err := coll.InsertOne(ctx, query, opts)\n\tif err != nil {\n\t\treturn primitive.ObjectID{}, fmt.Errorf(\"InsertOne: unable to insert book: %s\", err.Error())\n\t}\n\n\treturn res.InsertedID.(primitive.ObjectID), nil\n}", "func (d *DB) Insert(title string, status string) error {\n\tdb, err := gorm.Open(\"sqlite3\", \"model/DB/test.sqlite3\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdb.Create(&Todo{Title: title, Status: status})\n\tdb.Close()\n\n\treturn err\n}", "func (c *Client) CreateLiveActivity(startLatitude, startLongitude float64, startTime int64) (*Activity, error) {\n\tvar data = struct {\n\t\tStartLatitude float64 `json:\"startLatitude\"`\n\t\tStartLongitude float64 `json:\"startLongitude\"`\n\t\tStartTime int64 `json:\"startTime\"`\n\t}{\n\t\tStartLatitude: startLatitude,\n\t\tStartLongitude: startLongitude,\n\t\tStartTime: startTime,\n\t}\n\treq, err := c.newRequestJSON(\"POST\", c.apiURL+\"/activity/create\", &data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta := &Activity{\n\t\tc: c,\n\t}\n\tif err := c.doRequest(req, a); err != nil {\n\t\treturn nil, err\n\t}\n\treturn a, nil\n}", "func (t TaskInstanceRepoCassandra) Insert(ctx context.Context, taskInstance TaskInstance) (err error) {\n\terr = t.insertTaskInstance(ctx, taskInstance)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = t.insertTaskInstanceStartedAt(ctx, taskInstance)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn t.insertInstancesByID(ctx, taskInstance)\n}", "func insertConfigActivity(log ConfigActivity) error {\n\tdbinfo := dbinfo.Db()\n\tdb, err := sql.Open(dbinfo[0], dbinfo[1]) // gets the database information from the dbinfo package and enters the returned slice values as arguments\n\tif err != nil {\n\t\treturn errors.New(\"Unable to open the database connecting in the insertConfigActivity log\")\n\t}\n\tdefer db.Close()\n\n\tfmt.Println(\"User id is\", log.UserID)\n\tfmt.Println(\"TotalCreation time is\", log.TotalTime)\n\tfmt.Println(\"Avg length is\", log.AvgSecretLength)\n\n\tinitUser := \"INSERT INTO testConfigLog (id, userid, totalCreationTime, avgSecretLength) VALUES (DEFAULT, ?, ?, ?)\"\n\tstmtIns, err := db.Prepare(initUser)\n\tif err != nil {\n\t\treturn errors.New(\"Issue preparing to log user's config activity\")\n\t}\n\tdefer stmtIns.Close()\n\n\t_, err = stmtIns.Exec(log.UserID, log.TotalTime, log.AvgSecretLength)\n\tif err != nil {\n\t\terrMessage := fmt.Sprintf(\"%v\\nThere was an issue executing the query to insert a new config activity log.\\nError is\", err)\n\t\treturn errors.New(errMessage)\n\t}\n\n\treturn nil\n}", "func (hr Repository) Insert(startDate time.Time, endDate time.Time, area string) (*uuid.UUID, error) {\n\tid, err := uuid.NewV4()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = hr.db.Exec(\"insert into history values($1, $2, $3, $4)\", id, startDate, endDate, area)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &id, nil\n}", "func insertAudit(db gorp.SqlExecutor, pva *sdk.ProjectVariableAudit) error {\n\tdbProjVarAudit := dbProjectVariableAudit(*pva)\n\tif err := db.Insert(&dbProjVarAudit); err != nil {\n\t\treturn sdk.WrapError(err, \"Cannot insert audit for variable %d\", pva.VariableID)\n\t}\n\t*pva = sdk.ProjectVariableAudit(dbProjVarAudit)\n\treturn nil\n}", "func addActivity(echoReq *alexa.EchoRequest, col *mgo.Collection, user *User) *alexa.EchoResponse {\n\tmsg := \"\"\n\n\tfmt.Println(\"In addActivity\")\n\tactivityName, err := echoReq.GetSlotValue(\"Activity\")\n\tif err != nil {\n\t\tlog.Println(\"error\")\n\t\tmsg = \"There was an error adding your activity\"\n\t\techoResp := alexa.NewEchoResponse().OutputSpeech(msg).EndSession(false)\n\t\treturn echoResp\n\t}\n\n\tfmt.Println(\"Activity name is \" + activityName)\n\n\tif user.Activities != nil {\n\t\tfor _, value := range user.Activities {\n\t\t\tif value.Name == activityName {\n\t\t\t\tmsg = activityName + \" is already added in the list of activities\"\n\t\t\t\techoResp := alexa.NewEchoResponse().OutputSpeech(msg).EndSession(false)\n\t\t\t\treturn echoResp\n\t\t\t}\n\t\t}\n\t}\n\n\t//create an activity variable to add to the list in the database\n\tvar activity = Activity{\n\t\tName: activityName,\n\t\tWhoseCurrent: 0,\n\t}\n\tspew.Dump(activity)\n\n\t//adds to db\n\tuser.Activities = append(user.Activities, activity)\n\tcol.Upsert(bson.M{\"id\": user.ID}, user)\n\n\tmsg = \"Added \" + activityName + \" to list of activities\"\n\tfmt.Println(msg)\n\techoResp := alexa.NewEchoResponse().OutputSpeech(msg).EndSession(false)\n\n\treturn echoResp\n}", "func (g *GameDBModel) Insert(game Game) error {\n\tgame.ID = bson.NewObjectId()\n\terr := database.C(COLLECTION).Insert(&game)\n\n\treturn err\n}", "func (m MariaDB) Insert(ctx context.Context, document entity.PersonalData) (entity.PersonalData, error) {\n\tp := receive(document)\n\tsqlQuery := \"INSERT INTO person (id, name, last_name, phone, email, year_od_birth ) VALUES (?,?,?,?,?,?)\"\n\t_, err := m.Person.ExecContext(ctx, sqlQuery, p.ID, p.Name, p.LastName, p.Phone, p.Email, p.YearOfBirth)\n\tif err != nil {\n\t\treturn entity.PersonalData{}, errors.Wrap(err, \"could not exec query statement\")\n\t}\n\treturn document, nil\n}", "func (*ActivityStageDataAccessObject) UpdateOne(activityStage *ActivityStage) {\n\t_, err := orm.Table(ActivityStageDAO.TableName()).ID(activityStage.ID).\n\t\tUpdate(activityStage)\n\tlogger.LogIfError(err)\n}", "func InsertAero(aeronave schema.Aero)(err error){\n db := connection.Connect()\n _,err = db.Exec(\"INSERT INTO AERONAVE VALUES (?,?,?,?,?)\",aeronave.Id,aeronave.Nombre,aeronave.Nave_o,aeronave.Nave_d,aeronave.Cant_max)\n if(err != nil) {\n log.Println(\"error en el modelo!\")\n }else{ log.Println(\"Insertando!!\")}\n connection.Disconnect(db)\n return err\n}", "func (db *jsonDB) Add(t common.Task) (string, error) {\n\tt.ID = reverse(xid.New().String())\n\tt.Node = \"None\"\n\tt.Status = \"Created\"\n\tdb.data = append(db.data, t)\n\terr := db.save()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn t.ID, nil\n}", "func (q *Queue) insert(entities interface{}, mutex *sync.Mutex) *gorm.DB {\n\tmutex.Lock()\n\tres := q.db.Clauses(clause.OnConflict{DoNothing: true}).Create(entities)\n\tmutex.Unlock()\n\n\treturn res\n}", "func insert(ctx context.Context, tx *sqlx.Tx, todo *Todo) error {\n\tres, err := tx.NamedExecContext(ctx, insertTodo, todo)\n\tif err == nil {\n\t\ttodo.ID, err = res.LastInsertId()\n\t}\n\treturn err\n}", "func (s *Session) InsertOne(ctx context.Context, doc interface{}) (primitive.ObjectID, error) {\n\tcoll, err := s.getStructColl(doc)\n\tif err != nil {\n\t\treturn [12]byte{}, err\n\t}\n\tresult, err := coll.InsertOne(ctx, doc, s.insertOneOpts...)\n\tif err != nil {\n\t\treturn [12]byte{}, err\n\t}\n\tif id, ok := result.InsertedID.(primitive.ObjectID); ok {\n\t\treturn id, err\n\t}\n\treturn [12]byte{}, err\n}", "func (r postActions) CreateOne(\n\t_published postWithPrismaPublishedSetParams, _title postWithPrismaTitleSetParams, _author postWithPrismaAuthorSetParams,\n\toptional ...postSetParams,\n) postCreateOne {\n\tvar v postCreateOne\n\tv.query = builder.NewQuery()\n\tv.query.Client = r.client\n\n\tv.query.Operation = \"mutation\"\n\tv.query.Method = \"createOne\"\n\tv.query.Model = \"Post\"\n\tv.query.Outputs = postOutput\n\n\tvar fields []builder.Field\n\n\tfields = append(fields, _published.data)\n\tfields = append(fields, _title.data)\n\n\tfields = append(fields, _author.data)\n\n\tfor _, q := range optional {\n\t\tfields = append(fields, q.data)\n\t}\n\n\tv.query.Inputs = append(v.query.Inputs, builder.Input{\n\t\tName: \"data\",\n\t\tFields: fields,\n\t})\n\treturn v\n}", "func (dao *PlayerDAO) Insert(player models.Player) error {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\t_, err := db.Collection(PCOLLECTION).InsertOne(ctx, bson.D{\n\t\t{\"firstname\", player.FirstName},\n\t\t{\"lastname\", player.LastName},\n\t\t{\"nickname\", player.NickName},\n\t\t{\"skilllevel\", player.SkillLevel},\n\t})\n\treturn err\n}", "func (b *Build) Insert() error {\n\treturn db.Insert(Collection, b)\n}", "func (trace *Trace) save(database *mongo.Database, traceCollection string) error {\n\ttrace.ID = uuid.Must(uuid.NewRandom()).String()\n\ttrace.CreatedAt = time.Now().UTC()\n\t_, err := database.Collection(traceCollection).InsertOne(context.TODO(), trace)\n\treturn err\n}", "func (m *MongoDB) InsertOne(name string, doc interface{}) error {\n\tcoll, err := m.selCollection(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = coll.InsertOne(m.ctx, doc)\n\treturn err\n}", "func (o *<%= classedName %>) Insert() error {\n\tif _, err := orm.NewOrm().Insert(o); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func insertPerson(persona person) {\n\n\tdb, err := getDB()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t_, err = db.Exec(\"INSERT INTO Personas (Persona, Apellido, Email) VALUES (?, ?, ?)\", persona.Nombre, persona.Apellido, persona.Email)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer db.Close()\n}", "func SaveVisitActivityToEs(va *VisitActivity) error {\n\to := es.NewOrm()\n\tva.IsOverTime = false\n\treturn o.Insert(va)\n}", "func (s StoryRepository) Insert(story chronicle.Story) (createdStory chronicle.Story, err error) {\n\tdefer func() {\n\t\tif err != nil && err != sql.ErrNoRows {\n\t\t\terr = errors.Wrap(err, function.GetFunctionName(s.Insert))\n\t\t}\n\t}()\n\n\tquery := `INSERT INTO stories (\n\t\t\t\t\t\t\ttitle, \n\t\t\t\t\t\t\tslug, \n\t\t\t\t\t\t\texcerpt, \n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\treporter,\n\t\t\t\t\t\t\teditor,\n\t\t\t\t\t\t\tauthor,\n\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\tmedia, \n\t\t\t\t\t\t\tcreatedAt, \n\t\t\t\t\t\t\tupdatedAt\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t:title, \n\t\t\t\t\t\t\t:slug, \n\t\t\t\t\t\t\t:excerpt, \n\t\t\t\t\t\t\t:content,\n\t\t\t\t\t\t\t:reporter,\n\t\t\t\t\t\t\t:editor,\n\t\t\t\t\t\t\t:author,\n\t\t\t\t\t\t\t:status,\n\t\t\t\t\t\t\t:media, \n\t\t\t\t\t\t\tnow(), \n\t\t\t\t\t\t\tnow()\n\t\t\t\t\t\t) RETURNING id`\n\n\trows, err := s.db.NamedQuery(query, story)\n\tif err != nil {\n\t\treturn chronicle.Story{}, err\n\t}\n\n\tif rows.Next() {\n\t\trows.Scan(&story.ID)\n\t}\n\n\tif err := s.setTopicsForStory(story.ID, story.Topics); err != nil {\n\t\treturn chronicle.Story{}, err\n\t}\n\n\treturn s.Find(story.ID)\n}", "func (au *audit) One(kit *kit.Kit, audit *table.Audit, opt *AuditOption) error {\n\tif audit == nil || opt == nil {\n\t\treturn errors.New(\"invalid input audit or opt\")\n\t}\n\n\t// generate an audit id and update to audit.\n\tid, err := au.idGen.One(kit, table.AuditTable)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taudit.ID = id\n\n\tvar q gen.IAuditDo\n\n\tif opt.genQ != nil && au.db.Migrator().CurrentDatabase() == opt.genQ.CurrentDatabase() {\n\t\t// 使用同一个库,事务处理\n\t\tq = opt.genQ.Audit.WithContext(kit.Ctx)\n\t} else {\n\t\t// 使用独立的 DB\n\t\tq = au.genQ.Audit.WithContext(kit.Ctx)\n\t}\n\n\tif err := q.Create(audit); err != nil {\n\t\treturn fmt.Errorf(\"insert audit failed, err: %v\", err)\n\t}\n\treturn nil\n}", "func insertUser(user User) {\n\tcollection := client.Database(\"Go_task\").Collection(\"users\")\n\tinsertResult, err := collection.InsertOne(context.TODO(), user)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Inserted user with ID:\", insertResult.InsertedID)\n}", "func (c WrapperCollection) InsertOne(ctx context.Context, document interface{}, opts ...option.InsertOneOptioner) (InsertOneResultLayer, error) {\n\tvar insertResult *WrapperInsertOneResult\n\tvar err error\n\n\t// Recover on panic() from mongo driver.\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tinsertResult = nil\n\t\t\terr = errors.New(\"mongodb: collection insert error\")\n\t\t}\n\t}()\n\n\tres, err := c.Collection.InsertOne(ctx, document, opts...)\n\tinsertResult = &WrapperInsertOneResult{res}\n\treturn insertResult, err\n}", "func addPerson(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tvar person models.Person\r\n\t_ = json.NewDecoder(r.Body).Decode(&person)\r\n\tperson.UUID = primitive.NewObjectID()\r\n\r\n\tcollection := models.ConnectDB()\r\n\tnewPerson, err := collection.InsertOne(context.TODO(), person)\r\n\tif err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\tjson.NewEncoder(w).Encode(newPerson.InsertedID.(primitive.ObjectID))\r\n}", "func (c *User) CreateGoal(goalCol *mgo.Collection, g *goal.Goal) (bson.ObjectId, error) {\n\tnid := bson.NewObjectId()\n\tg.Username, g.ID = c.Username, nid\n\tg.LastUpdated = time.Now()\n\terr := goalCol.Insert(g)\n\tif err != nil {\n\t\treturn nid, fmt.Errorf(\"create goal: %s\", err)\n\t}\n\treturn nid, nil\n}", "func (m *MovieModel) Insert(movie *Movie) error {\n\t// Define the SQL query for inserting a new record in the movies table and returning the system generated data\n\tquery := `INSERT INTO movies (title, year, runtime, genres) \n\t\t\t\t\t\tVALUES ($1, $2, $3, $4)\n\t\t\t\t\t\tRETURNING id, created_at, version`\n\n\t// Create an args slice containing the values for the placeholder parameters from the movie struct\n\targs := []interface{}{movie.Title, movie.Year, movie.Runtime, pq.Array(movie.Genres)}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\t// Execute the query.\n\treturn m.DB.QueryRowContext(ctx, query, args...).Scan(&movie.ID, &movie.CreatedAt, &movie.Version)\n}", "func create(c *gin.Context) {\n\tdb, _ := c.Get(\"db\")\n\tconn := db.(*pgx.Conn)\n\n\n\tstream := config.CreateLiveStream()\n\ti, err := strconv.ParseInt(stream.Data.CreatedAt, 10, 64) // convert unit timestamp from string to int64 then create the time stamp with time.Unix\n\t\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttm := time.Unix(i, 0)\n\t_, err = conn.Exec(context.Background(), \"INSERT INTO streaming (stream_id, created_at) VALUES ($1, $2)\", stream.Data.Id, tm)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tc.JSON(http.StatusOK,stream)\n}", "func Insert(db *mongo.Client, r Record) (Record, error) {\n\tctx, _ := context.WithTimeout(context.Background(), 3*time.Second)\n\tres, err := db.Database(\"url-shortener\").Collection(\"urls\").InsertOne(ctx, r)\n\t\n\tif err != nil {\n\t\treturn Record{}, err\n\t}\n\tlog.Printf(\"New record created with the ID: %s\", res.InsertedID)\n\treturn r, nil\n}", "func (e *ExpenseModel) Insert(expense Expense) (interface{}, error) {\n\tcollection := e.db.Client.Database(e.db.DBName).Collection(\"expenses\")\n\tinsertResult, err := collection.InsertOne(context.TODO(), expense)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error on inserting new expense: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\treturn insertResult.InsertedID, nil\n}", "func (db *Gorm) InsertEvent(e kcp.Event) error {\n\treturn db.Create(&Visit{\n\t\tVisitedAt: e.VisitedAt,\n\t\tIP: e.IP,\n\t\tDay: e.Day,\n\t}).Error\n}", "func insertEntry(db *sql.DB, stamp time.Time, watts int) error {\n\tstampStr := stamp.Format(RFC3339NoZ)\n\tinsertSQLFormat := insertSQLFormat(db)\n\tinsertSQL := fmt.Sprintf(insertSQLFormat, stampStr, watts)\n\t_, err := db.Exec(insertSQL)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (postgres *Postgres) CreateOne(order *proto.Order) (*proto.Order, error) {\n\tquery := fmt.Sprintf(\"INSERT INTO orders (product_id, user_id, status)\"+\n\t\t\" VALUES (%d, %d, 'waiting for payment')\", order.ProductId, order.UserId)\n\t_, err := postgres.DB.Exec(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn order, err\n}", "func insertLoginActivity(log LoginActivity) error {\n\tdbinfo := dbinfo.Db()\n\tdb, err := sql.Open(dbinfo[0], dbinfo[1]) // gets the database information from the dbinfo package and enters the returned slice values as arguments\n\tif err != nil {\n\t\treturn errors.New(\"Unable to open the database connecting in the insertLogActivity log\")\n\t}\n\tdefer db.Close()\n\n\tinitUser := \"INSERT INTO testLoginLog (id, userid, loginTime, failures, refreshes, secretLength) VALUES (DEFAULT, ?, ?, ?, ?, ?)\"\n\tstmtIns, err := db.Prepare(initUser)\n\tif err != nil {\n\t\treturn errors.New(\"Issue preparing to log user's login activity\")\n\t}\n\tdefer stmtIns.Close()\n\n\t_, err = stmtIns.Exec(log.UserID, log.LoginTime, log.Failures, log.Refreshes, log.SecretLength)\n\tif err != nil {\n\t\terrMessage := fmt.Sprintf(\"%v\\nThere was an issue executing the query to insert a new login activity log.\\nError is\", err)\n\t\treturn errors.New(errMessage)\n\t}\n\n\treturn nil\n}", "func (p *Project) Insert(session *xorm.Session) (int, error) {\n\taffected, err := session.Insert(p)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn 0, err\n\t}\n\treturn int(affected), nil\n}", "func (d DB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, time time.Time) error {\n\treturn nil\n}", "func (r *RoomDAO) Insert(room RoomDTO) error {\n\terr := r.db.C(r.collection).Insert(&room)\n\treturn err\n}", "func InsertProgress(p *models.Progress, g *models.Goal) error {\n\t// prepare statement\n\tstmt, err := db.Prepare(\"INSERT INTO progress (goal_id, value, date, note) values (?,?,?,?)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// exec statement\n\tres, err := stmt.Exec(g.ID, p.Value, p.Date, p.Note)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// update progress id\n\tp.ID, err = res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *DbRecorder) Insert() error {\n\tswitch s.flavor {\n\tcase \"postgres\":\n\t\treturn s.insertPg()\n\tdefault:\n\t\treturn s.insertStd()\n\t}\n}", "func (db *pg) Add(ctx context.Context, action string) error {\n\tuserID := ctx.Value(\"userId\").(string)\n\tconst stmt = `INSERT INTO audit.\"Logs\" VALUES (NOW(), $1, $2);`\n\tif _, err := db.ExecContext(ctx, stmt, userID, action); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (l LiveAgent) Save() error {\n\n\tvar db = data.GetDB()\n\n\tquery := fmt.Sprintf(`\n\t\tINSERT INTO vicidial_live_agents \n\t\t\t(live_agent_id, user, server_ip, conf_exten, extension, status, lead_id, campaign_id, uniqueid, callerid, channel, random_id, \n\t\t\tlast_call_time, last_update_time, last_call_finish, closer_campaigns, call_server_ip, user_level, \n\t\t\tcomments, campaign_weight, calls_today, external_hangup, external_status, external_pause, external_dial, \n\t\t\texternal_ingroups, external_blended, external_igb_set_user, external_update_fields, external_update_fields_data, \n\t\t\texternal_timer_action, external_timer_action_message, external_timer_action_seconds, agent_log_id, last_state_change, \n\t\t\tagent_territories, outbound_autodial, manager_ingroup_set, ra_user, ra_extension, external_dtmf, external_transferconf, \n\t\t\texternal_park, external_timer_action_destination, on_hook_agent, on_hook_ring_time, ring_callerid, last_inbound_call_time, \n\t\t\tlast_inbound_call_finish, campaign_grade, external_recording, external_pause_code, pause_code, preview_lead_id, external_lead_id, \n\t\t\tlast_inbound_call_time_filtered, last_inbound_call_finish_filtered) \n\t\tVALUES \n\t\t\t(NULL, 'duser2', '172.16.10.209', '8600051', 'SIP/102', 'PAUSED', '0', 'DCAMP', '', '', '', '11036487', \n\t\t\t'2020-08-19 16:29:09', '2020-08-19 16:30:03', '2020-08-19 16:29:09', '-', NULL, '1', \n\t\t\tNULL, '0', '0', '', '', '', '', \n\t\t\tNULL, '0', '', '0', '', \n\t\t\t'', '', '-1', '196', '2020-08-19 16:29:14', NULL, 'N', 'N', '', '', '', '', '', '', 'N', '60', '', '2020-08-19 16:29:09', '2020-08-19 16:29:09', '10', '', '', 'LOGIN', '0', '0', '2020-08-19 16:29:09', '2020-08-19 16:29:09')\n\t`)\n\n\treturn db.Exec(query).Error\n}", "func (table *Table) Insert(db DB, record Map) (Result, error) {\n\tc := Context{StateInsert, db, table, table, record, Field{}}\n\treturn table.execAction(c, table.OnInsert, table.DefaultInsert)\n}", "func Insert(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif r.Body == nil {\n\t\thttp.Error(w, http.StatusText(400), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstnds, err := insertDB(r)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsjson, err := json.Marshal(stnds)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated) // 201\n\tfmt.Fprintf(w, \"%s\\n\", sjson)\n}", "func (a *Article) Insert(db *database.DB) error {\n\tq := `insert into bot.articles (title, link, image, published) values (:title, :link, :image, :published);`\n\n\tstmt, stmtErr := db.PrepareNamed(q)\n\tif stmtErr != nil {\n\t\treturn stmtErr\n\t}\n\tdefer stmt.Close()\n\n\t_, execErr := stmt.Exec(a)\n\n\treturn execErr\n}", "func (a *Advert) Insert(e *models.Advert) error {\n\tvar result sql.Result\n\tresult, err := Storage.Run(\"INSERT INTO advert (locality, link, hash_id, price, name, description, status, created) VALUES( ?, ?, ?, ?, ?, ?, ?, ? )\",\n\t\te.Locality, e.Link, e.HashID, e.Price, e.Name, e.Description, e.Status, e.GetCreated().Unix())\n\tif err != nil {\n\t\treturn err\n\t}\n\te.ID, err = result.LastInsertId()\n\treturn err\n}", "func (a *adapter) insert(e cloudevents.Event, ctx context.Context) error {\n\tipd := &InsertPayload{}\n\tif err := e.DataAs(ipd); err != nil {\n\t\treturn err\n\t}\n\tcol := a.defaultCollection\n\tdb := a.defaultDatabase\n\n\t// override default collection and database if specified in the event\n\tif ipd.Collection != \"\" {\n\t\tcol = ipd.Collection\n\t}\n\tif ipd.Database != \"\" {\n\t\tdb = ipd.Database\n\t}\n\n\tcollection := a.mclient.Database(db).Collection(col)\n\tif ipd.Document != nil {\n\t\t_, err := collection.InsertOne(ctx, ipd.Document)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"no data to insert\")\n}", "func insert(w http.ResponseWriter, r *http.Request) {\n\tvar todo Todo\n\ttodo.Todo = r.FormValue(\"todo\")\n\ttodo.ID = uuid.NewV4().String()\n\ttodo.CreatedAt = time.Now().UTC()\n\n\t_, err := mainDB.Exec(\"INSERT INTO todos(id, todo, created_at) values($1, $2, $3)\", todo.ID, todo.Todo, todo.CreatedAt)\n\tcheckErr(err)\n\tjsonB, errMarshal := json.Marshal(todo)\n\tcheckErr(errMarshal)\n\n\tw.Header().Set(\"Location\", \"/\")\n\tw.WriteHeader(301)\n\tw.Write(jsonB)\n}", "func (article Article) insertIntoDB(parent Issue, db *sql.DB) error {\n\t// Determine if the article has already been entered into the DB\n\tnumInstances, _ := util.NumResults(db, \"SELECT * FROM four_u_articles WHERE four_u_article = $1 AND four_u_article_name = $2\", parent.ID, article.Name)\n\tif numInstances != 0 {\n\t\treturn errors.New(\"article already exists\")\n\t}\n\n\t// Insert into the DB, if there is a failure that generally implies that the parent was invalid\n\tif _, err := db.Exec(\"INSERT INTO four_u_articles (four_u_article, page_start, four_u_article_name, four_u_article_desc) VALUES ($1, $2, $3, $4)\",\n\t\tparent.ID, article.Page, article.Name, article.Desc); err != nil {\n\t\treturn errors.New(\"unable to insert article into DB, most likely because the parent provided did not exist\")\n\t}\n\n\treturn nil\n}", "func (backRepoFoo *BackRepoFooStruct) CommitPhaseOneInstance(foo *models.Foo) (Error error) {\n\n\t// check if the foo is not commited yet\n\tif _, ok := (*backRepoFoo.Map_FooPtr_FooDBID)[foo]; ok {\n\t\treturn\n\t}\n\n\t// initiate foo\n\tvar fooDB FooDB\n\tfooDB.CopyBasicFieldsFromFoo(foo)\n\n\tquery := backRepoFoo.db.Create(&fooDB)\n\tif query.Error != nil {\n\t\treturn query.Error\n\t}\n\n\t// update stores\n\t(*backRepoFoo.Map_FooPtr_FooDBID)[foo] = fooDB.ID\n\t(*backRepoFoo.Map_FooDBID_FooPtr)[fooDB.ID] = foo\n\t(*backRepoFoo.Map_FooDBID_FooDB)[fooDB.ID] = &fooDB\n\n\treturn\n}", "func (mdb MongoDBConnection) Save(a Agent) error {\n\tmdb.session = mdb.GetSession()\n\tdefer mdb.session.Close()\n\tdb := mdb.session.DB(\"dockmaster\").C(\"containers\")\n\tdb.Remove(bson.M{\"agentid\": a.AgentID})\n\n\tnow := time.Now()\n\t//This is necessary to convert time.Now() to UTC which is CET by default\n\tdate := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second(), now.Nanosecond(), time.UTC)\n\ta.CreatedAt = date\n\terr := db.Insert(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Create(record Record) {\r\n\tdb.QueryRow(\"insert into records values($1,$2,$3,$4,$5)\", record.Uuid, record.Mail, record.Seq, record.Pssm, record.Result)\r\n}" ]
[ "0.6713875", "0.6497619", "0.64175105", "0.60334396", "0.6026915", "0.601768", "0.6017192", "0.6014032", "0.5920214", "0.5836816", "0.5703741", "0.5632357", "0.5602113", "0.55855733", "0.5567582", "0.55642295", "0.555056", "0.5546107", "0.55420107", "0.55146766", "0.5506226", "0.54840815", "0.5478146", "0.5431222", "0.537917", "0.5376132", "0.5348355", "0.53415036", "0.5328963", "0.5328", "0.53238916", "0.5318272", "0.52884424", "0.52875453", "0.52812505", "0.5267933", "0.5267798", "0.52664554", "0.52643484", "0.52553654", "0.5255244", "0.52515113", "0.5242573", "0.5228602", "0.5221859", "0.5209196", "0.5203753", "0.51795304", "0.51697177", "0.51659626", "0.5164099", "0.51597667", "0.5151861", "0.5146353", "0.514231", "0.5120435", "0.511253", "0.510991", "0.510363", "0.5095191", "0.5094994", "0.50910956", "0.50848377", "0.50842345", "0.5080503", "0.5073454", "0.5063962", "0.506231", "0.5061822", "0.5056401", "0.5053923", "0.5050436", "0.505028", "0.5047238", "0.5044721", "0.5041943", "0.50399125", "0.5034675", "0.5018952", "0.50129104", "0.5007791", "0.5001432", "0.49972335", "0.499675", "0.49960777", "0.4993151", "0.49930602", "0.49918237", "0.49859822", "0.49848962", "0.49843532", "0.49815714", "0.49654007", "0.49449804", "0.49432203", "0.493868", "0.49339065", "0.49328053", "0.49322236", "0.49245352" ]
0.75430804
0
FindByAID finds activity stages of an activity
func (*ActivityStageDataAccessObject) FindByAID(aid int) []ActivityStage { l := make([]ActivityStage, 0) err := orm.Table(ActivityStageDAO.TableName()).Where("activity_id=?", aid). Find(&l) logger.LogIfError(err) return l }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*ActivityStageDataAccessObject) FindByID(id int) (ActivityStage, bool) {\n\tvar result ActivityStage\n\thas, err := orm.Table(ActivityStageDAO.TableName()).ID(id).Get(&result) \n\tlogger.LogIfError(err)\n\treturn result, has\n}", "func FindActivityLog(ctx context.Context, exec boil.ContextExecutor, iD int64, selectCols ...string) (*ActivityLog, error) {\n\tactivityLogObj := &ActivityLog{}\n\n\tsel := \"*\"\n\tif len(selectCols) > 0 {\n\t\tsel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), \",\")\n\t}\n\tquery := fmt.Sprintf(\n\t\t\"select %s from \\\"activity_logs\\\" where \\\"id\\\"=?\", sel,\n\t)\n\n\tq := queries.Raw(query, iD)\n\n\terr := q.Bind(ctx, exec, activityLogObj)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"dbmodel: unable to select from activity_logs\")\n\t}\n\n\treturn activityLogObj, nil\n}", "func (*ActivityStageDataAccessObject) DeleteByAID(aid int) {\n\tvar buf ActivityStage\n\t_, err := orm.Table(ActivityStageDAO.TableName()).\n\t\tWhere(\"activity_id=?\", aid).Delete(&buf)\n\tlogger.LogIfError(err)\n}", "func (*ActivityStageDataAccessObject) FindFullByDay(\n\tdate time.Time) []ActivityStageFull {\n\n\tstartDate := time.Date(date.Year(), date.Month(), date.Day(),\n\t\t0, 0, 0, 0, time.Local)\n\tendDate := startDate.AddDate(0, 0, 1)\n\tstart := startDate.Format(mysqlTimeFormat)\n\tend := time.Date(endDate.Year(), endDate.Month(), endDate.Day(),\n\t\t0, 0, 0, 0, time.Local).Format(mysqlTimeFormat)\n\tresult := make([]ActivityStageFull, 0)\n\n\terr := orm.Table(ActivityDAO.TableName()).\n\t\tWhere(\"activity_stages.activity_id=activities.id\").\n\t\tJoin(\"INNER\", ActivityStageDAO.TableName(),\n\t\t\"start_time>=?\", start).And(\"end_time<?\", end).\n\t\tFind(&result)\n\tlogger.LogIfError(err)\n\treturn result\n}", "func getActivityIndex(activities []Activity, activityName string) int {\n\tactivityIndex := -1\n\tfor index, activity := range activities {\n\t\tif activity.Name == activityName {\n\t\t\tactivityIndex = index\n\t\t\tbreak\n\t\t}\n\t}\n\treturn activityIndex\n}", "func (*ActivityStageDataAccessObject) FindAll() []ActivityStage {\n\tl := make([]ActivityStage, 0)\n\terr := orm.Table(ActivityStageDAO.TableName()).Find(&l)\n\n\tlogger.LogIfError(err)\n\treturn l\n}", "func (c *Client) FindCrmStage(criteria *Criteria) (*CrmStage, error) {\n\tcss := &CrmStages{}\n\tif err := c.SearchRead(CrmStageModel, criteria, NewOptions().Limit(1), css); err != nil {\n\t\treturn nil, err\n\t}\n\tif css != nil && len(*css) > 0 {\n\t\treturn &((*css)[0]), nil\n\t}\n\treturn nil, fmt.Errorf(\"crm.stage was not found with criteria %v\", criteria)\n}", "func findBuildStageDurations(stepId string, builds []*cloudbuild.Build) ([]time.Duration, error) {\n\tdurations := []time.Duration{}\n\tfor _, b := range builds {\n\t\tfor _, bs := range b.Steps {\n\t\t\tif bs.Id != stepId || bs.Status != successStatus {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tparsedStartTime, err := time.Parse(time.RFC3339Nano, bs.Timing.StartTime)\n\t\t\tif err != nil {\n\t\t\t\treturn []time.Duration{}, err\n\t\t\t}\n\t\t\tparsedEndTime, err := time.Parse(time.RFC3339Nano, bs.Timing.EndTime)\n\t\t\tif err != nil {\n\t\t\t\treturn []time.Duration{}, err\n\t\t\t}\n\t\t\tdurations = append(durations, parsedEndTime.Sub(parsedStartTime).Truncate(time.Second))\n\t\t}\n\t}\n\treturn durations, nil\n}", "func (c *Client) FindCrmStageId(criteria *Criteria, options *Options) (int64, error) {\n\tids, err := c.Search(CrmStageModel, criteria, options)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tif len(ids) > 0 {\n\t\treturn ids[0], nil\n\t}\n\treturn -1, fmt.Errorf(\"crm.stage was not found with criteria %v and options %v\", criteria, options)\n}", "func ActivityByID(ctx context.Context, id uint, key ...interface{}) (*Activity, error) {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\ttableName, err := GetActivityTableName(key...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sql query\n\tsqlstr := `SELECT ` +\n\t\t`id, name, activity_type_id, activity_type_code, content, activity_image, image_url, image_color, status, sort, extend, admin_id, admin_name, start_time, end_time, created_at, updated_at ` +\n\t\t`FROM ` + tableName +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, id)))\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetSlaveConn()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\ta := Activity{\n\t\t_exists: true,\n\t}\n\n\tif tx != nil {\n\t\terr = tx.QueryRow(sqlstr, id).Scan(&a.ID, &a.Name, &a.ActivityTypeID, &a.ActivityTypeCode, &a.Content, &a.ActivityImage, &a.ImageURL, &a.ImageColor, &a.Status, &a.Sort, &a.Extend, &a.AdminID, &a.AdminName, &a.StartTime, &a.EndTime, &a.CreatedAt, &a.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\terr = dbConn.QueryRow(sqlstr, id).Scan(&a.ID, &a.Name, &a.ActivityTypeID, &a.ActivityTypeCode, &a.Content, &a.ActivityImage, &a.ImageURL, &a.ImageColor, &a.Status, &a.Sort, &a.Extend, &a.AdminID, &a.AdminName, &a.StartTime, &a.EndTime, &a.CreatedAt, &a.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &a, nil\n}", "func (c *Client) FindCrmStages(criteria *Criteria, options *Options) (*CrmStages, error) {\n\tcss := &CrmStages{}\n\tif err := c.SearchRead(CrmStageModel, criteria, options, css); err != nil {\n\t\treturn nil, err\n\t}\n\treturn css, nil\n}", "func findAssetID(assets []Asset, name string) int {\n\tfor _, asset := range assets {\n\t\tif asset.Name == name {\n\t\t\treturn asset.Id\n\t\t}\n\t}\n\treturn -1\n}", "func FindCRBRRunningPipeline(appID uint64, env string, ymlName string, bdl *bundle.Bundle) ([]apistructs.PagePipeline, error) {\n\tvar result []apistructs.PagePipeline\n\tpipelinePageReq := apistructs.PipelinePageListRequest{\n\t\tSources: []apistructs.PipelineSource{apistructs.PipelineSourceDice},\n\t\tStatuses: []string{\"Running\"},\n\t}\n\tif appID != 0 {\n\t\tpipelinePageReq.MustMatchLabelsQueryParams = []string{\"appID=\" + strconv.FormatUint(appID, 10)}\n\t}\n\tif ymlName != \"\" {\n\t\tpipelinePageReq.YmlNames = []string{ymlName}\n\t}\n\n\tresp, err := bdl.PageListPipeline(pipelinePageReq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, v := range resp.Pipelines {\n\t\tif strings.Contains(v.YmlName, \"dice-deploy-release\") &&\n\t\t\tstrings.ToUpper(v.Extra.DiceWorkspace) == strings.ToUpper(env) {\n\t\t\tresult = append(result, v)\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (this *activitiesStruct) searchActivity(begin time.Time) (int, bool) {\n\tgroups := this.groups\n\tnumGroups := len(groups)\n\tidxLeft := int(0)\n\n\t/*\n\t * The case that there are no groups requires special handling.\n\t */\n\tif numGroups > 0 {\n\t\tidxRight := numGroups - 1\n\n\t\t/*\n\t\t * Binary search algorithm.\n\t\t */\n\t\tfor idxLeft <= idxRight {\n\t\t\tdiff := idxRight - idxLeft\n\t\t\tdiffHalf := diff / 2\n\t\t\tidxPivot := idxLeft + diffHalf\n\t\t\tpivot := groups[idxPivot]\n\t\t\tpivotBegin := pivot.begin\n\n\t\t\t/*\n\t\t\t * Check if we have to continue searching in left or\n\t\t\t * right half.\n\t\t\t */\n\t\t\tif pivotBegin.After(begin) {\n\t\t\t\tidxRight = idxPivot - 1\n\n\t\t\t\t/*\n\t\t\t\t * Prevent underflow.\n\t\t\t\t */\n\t\t\t\tif idxRight > idxPivot {\n\t\t\t\t\tidxRight = idxPivot\n\t\t\t\t}\n\n\t\t\t} else if pivotBegin.Before(begin) {\n\t\t\t\tidxLeft = idxPivot + 1\n\n\t\t\t\t/*\n\t\t\t\t * Prevent overflow.\n\t\t\t\t */\n\t\t\t\tif idxLeft < idxPivot {\n\t\t\t\t\tidxLeft = idxPivot\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\treturn idxPivot, true\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn idxLeft, false\n}", "func (c *CaptureList) Find(captureID string) *Capture {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\tidInt, _ := strconv.Atoi(captureID)\n\tfor _, c := range c.items {\n\t\tif c.ID == idInt {\n\t\t\treturn &c\n\t\t}\n\t}\n\treturn nil\n}", "func (db *Db) Activities() ([]*Activity, error) {\n\tactivities := []*Activity{}\n\n\t//query := \"SELECT * FROM sport_summary ORDER BY start_time DESC;\"\n\tquery := \"SELECT sport_summary.*, Group_Concat(latitude || ',' || longitude, '|') AS points FROM sport_summary LEFT JOIN location_data ON sport_summary.track_id=location_data.track_id GROUP BY sport_summary.track_id ORDER BY location_data.timestamp ASC;\"\n\n\trows, err := db.connection.Query(query)\n\tif err != nil {\n\t\treturn activities, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tactivity := &Activity{}\n\n\t\t//err = rows.Scan(StructForScan(&activity)...)\n\t\terr = rows.Scan(&activity.Id, &activity.Type, &activity.Parent,\n\t\t\t&activity.StartTime, &activity.EndTime, &activity.Calories,\n\t\t\t&activity.CurrentStatus, &activity.ContentJSON, &activity.PointsData)\n\t\tif err != nil {\n\t\t\treturn activities, err\n\t\t}\n\n\t\tactivity.ParseContent()\n\n\t\t// Fetch activity points\n\t\tquery = \"SELECT latitude || ',' || longitude FROM location_data WHERE track_id=\" + strconv.Itoa(activity.Id) + \" ORDER BY timestamp ASC\"\n\t\tpointRows, err := db.connection.Query(query)\n\t\tif err != nil {\n\t\t\treturn activities, err\n\t\t}\n\t\tdefer pointRows.Close()\n\n\t\tpoints := []string{}\n\t\tvar point string\n\t\tfor pointRows.Next() {\n\t\t\terr = pointRows.Scan(&point)\n\t\t\tif err != nil {\n\t\t\t\tpanic(\"Couldn't parse point from database: \" + err.Error())\n\t\t\t}\n\t\t\tpoints = append(points, point)\n\t\t}\n\t\terr = pointRows.Err()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tactivity.PointsData = strings.Join(points, \"|\")\n\n\t\tactivities = append(activities, activity)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn activities, err\n\t}\n\n\treturn activities, nil\n}", "func (nullActivityStatsStorer) RecordActives(tlf.ID, string) {}", "func (t *Cases) FindBySessionID(sessionID string) []models.Case {\n\tvar cases []models.Case\n\n\tquery := func(db *gorm.DB) {\n\t\tdb.Where(&models.Case{SessionID: sessionID}).Find(&cases)\n\t}\n\n\terror := t.context.Execute(query)\n\n\tif error != nil {\n\t\treturn nil\n\t}\n\n\treturn cases\n}", "func (c *Client) GetActivity(id string, filters ...Filter) (Activity, error) {\n\tresp, err := c.doRequest(http.MethodGet, fmt.Sprintf(EndpointFormatGetObject, TypeActivity, id, formatFilters(filters)), nil)\n\tif err != nil {\n\t\treturn Activity{}, err\n\t}\n\n\t// Check if we didn't get a result and return an error if true.\n\tif len(resp.Activities) <= 0 {\n\t\treturn Activity{}, fmt.Errorf(\"get activity id %s returned an empty result\", id)\n\t}\n\n\t// Return the object.\n\treturn resp.Activities[0], nil\n}", "func (a *LocalActivations) Find(name string) *Local {\n\tcurrent := a.Current()\n\tif current == nil {\n\t\treturn nil\n\t}\n\treturn current.Find(name)\n}", "func (f *fileActivityFinder) FindAll() ([]domain.Activity, error) {\n\tvar activities []domain.Activity\n\n\tbyteValue, _ := ioutil.ReadAll(f.reader)\n\n\terr := json.Unmarshal(byteValue, &activities)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn activities, nil\n}", "func (ew *Eyewitness) Investigate(status whodunit.AssetStatus) {\n\ttotalCount := 0\n\ttable := whodunit.NewStatusTable(whodunit.AssetTypeRecognition, status)\n\tjep := ew.jobEpisodeMap()\n\tfor season := 1; season <= whodunit.SeasonCount; season++ {\n\t\ts := whodunit.NewSeason(season)\n\t\tif err := s.PopulateEpisodes(); err != nil {\n\t\t\tpanic(\"Could not get season episodes\")\n\t\t}\n\n\t\tfor _, ep := range s.AllEpisodes() {\n\t\t\tje := jep[ep.Name()]\n\t\t\tif je != nil {\n\t\t\t\tep.SetAssetStatus(je.AssetStatus(whodunit.AssetTypeRecognition))\n\t\t\t}\n\n\t\t\tif table.AddRow(ep) {\n\t\t\t\ttotalCount++\n\t\t\t}\n\t\t}\n\t}\n\n\ttable.RenderTable(totalCount)\n}", "func getTaskInfoByContainerID(containerID string, tasks []TaskInfo) *TaskInfo {\n\tfor _, task := range tasks {\n\t\tif len(task.Statuses) > 0 && task.Statuses[0].ContainerStatusInfo.ID.Value == containerID {\n\t\t\treturn &task\n\t\t}\n\t}\n\treturn nil\n}", "func SelectActivityByID(ID *int64) *models.Activity {\n\tvar db, _ = GetDatabase()\n\tif db == nil {\n\t\tlog.Println(\"Error in SelectActivityByID: DB connection unsuccessful.\")\n\t\treturn nil\n\t}\n\n\tvar activity models.Activity\n\tactivity.ID = *ID\n\tvar row = db.QueryRow(\"SELECT name FROM activities WHERE id = $1\", *ID)\n\terr := row.Scan(&activity.Name)\n\n\tswitch err {\n\tcase sql.ErrNoRows:\n\t\tlog.Println(\"No activity found for ID: \", *ID)\n\t\treturn nil\n\tcase nil:\n\t\treturn &activity\n\tdefault:\n\t\tlog.Println(\"Error SelectActivityByID: \", err)\n\t\treturn nil\n\t}\n}", "func (m *Manager) FindChannelAdActiveByAdID(adID int64, status ActiveStatus) ([]ChannelAd, error) {\n\tres := []ChannelAd{}\n\t_, err := m.GetDbMap().Select(\n\t\t&res,\n\t\tfmt.Sprintf(\"SELECT * FROM %s WHERE ad_id=? AND active=?\", ChannelAdTableFull),\n\t\tadID,\n\t\tstatus,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func (m *Manager) FindChannelAdByChannelIDActive(a int64) ([]ChannelAdD, error) {\n\tres := []ChannelAdD{}\n\t_, err := m.GetDbMap().Select(\n\t\t&res,\n\t\tfmt.Sprintf(\"SELECT %[1]s.*,%[2]s.cli_message_id AS cli_message_ad,%[2]s.promote_data,%[2]s.src, \"+\n\t\t\t\"%[3]s.view AS plan_view,%[3]s.position AS plan_position\"+\n\t\t\t\" FROM %[1]s INNER JOIN %[2]s ON %[2]s.id=%[1]s.ad_id \"+\n\t\t\t\" INNER JOIN %[3]s ON %[3]s.id=%[2]s.plan_id \"+\n\t\t\t\" WHERE channel_id=? \"+\n\t\t\t\" AND %[1]s.active='yes' \"+\n\t\t\t\" AND %[2]s.active_status='yes' \"+\n\t\t\t\" AND end IS NULL\",\n\t\t\tChannelAdTableFull,\n\t\t\tAdTableFull,\n\t\t\tPlanTableFull,\n\t\t),\n\t\ta,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func ActivitiesByStatus(ctx context.Context, status int, key ...interface{}) ([]*Activity, error) {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\ttableName, err := GetActivityTableName(key...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sql query\n\tsqlstr := `SELECT ` +\n\t\t`id, name, activity_type_id, activity_type_code, content, activity_image, image_url, image_color, status, sort, extend, admin_id, admin_name, start_time, end_time, created_at, updated_at ` +\n\t\t`FROM ` + tableName +\n\t\t` WHERE status = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, status)))\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetSlaveConn()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar queryData *sql.Rows\n\tif tx != nil {\n\t\tqueryData, err = tx.Query(sqlstr, status)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tqueryData, err = dbConn.Query(sqlstr, status)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdefer queryData.Close()\n\n\t// load results\n\tres := make([]*Activity, 0)\n\tfor queryData.Next() {\n\t\ta := Activity{\n\t\t\t_exists: true,\n\t\t}\n\n\t\t// scan\n\t\terr = queryData.Scan(&a.ID, &a.Name, &a.ActivityTypeID, &a.ActivityTypeCode, &a.Content, &a.ActivityImage, &a.ImageURL, &a.ImageColor, &a.Status, &a.Sort, &a.Extend, &a.AdminID, &a.AdminName, &a.StartTime, &a.EndTime, &a.CreatedAt, &a.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres = append(res, &a)\n\t}\n\n\treturn res, nil\n}", "func (r attestationRepo) Find(id string) (*Attestation, error) {\n\tconst Query = `\n\t\tSELECT id,\n\t\t\t claimant_id,\n\t\t\t attestor_id,\n\t\t\t claim\n\t\tFROM attestation\n\t\tWHERE id = $1;`\n\tvar a Attestation\n\terr := r.dao.\n\t\tQueryRow(Query, id).\n\t\tScan(\n\t\t\t&a.ID,\n\t\t\t&a.ClaimantID,\n\t\t\t&a.AttestorID,\n\t\t\t&a.Claim,\n\t\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to retrieve attestation\")\n\t}\n\treturn &a, nil\n}", "func findID(root *Container, id string) (*Container, error) {\n\tif id == \"\" {\n\t\treturn nil, errors.New(\"the container ID must not be empty\")\n\t}\n\n\tvar (\n\t\terrStr string\n\t\tcont *Container\n\t)\n\tpreOrder(root, &errStr, visitFunc(func(c *Container) error {\n\t\tif c.opts.id == id {\n\t\t\tcont = c\n\t\t}\n\t\treturn nil\n\t}))\n\tif cont == nil {\n\t\treturn nil, fmt.Errorf(\"cannot find container with ID %q\", id)\n\t}\n\treturn cont, nil\n}", "func (t *Cases) Find(id int) *models.Case {\n\tvar result models.Case\n\n\tquery := func(db *gorm.DB) {\n\t\tdb.Find(&result, id)\n\t}\n\n\terror := t.context.Execute(query)\n\n\tif error != nil {\n\t\treturn nil\n\t}\n\n\treturn &result\n}", "func XPipelineSalesStageByID(db XODB, id uint) (*XPipelineSalesStage, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, name, probability, seq_num, active_flag, sales_method_id, created_by, updated_by, created_at, updated_at ` +\n\t\t`FROM x_showroom.x_pipeline_sales_stages ` +\n\t\t`WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, id)\n\txpss := XPipelineSalesStage{\n\t\t_exists: true,\n\t}\n\n\terr = db.QueryRow(sqlstr, id).Scan(&xpss.ID, &xpss.Name, &xpss.Probability, &xpss.SeqNum, &xpss.ActiveFlag, &xpss.SalesMethodID, &xpss.CreatedBy, &xpss.UpdatedBy, &xpss.CreatedAt, &xpss.UpdatedAt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &xpss, nil\n}", "func (c *Client) FindCrmStageIds(criteria *Criteria, options *Options) ([]int64, error) {\n\tids, err := c.Search(CrmStageModel, criteria, options)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\treturn ids, nil\n}", "func (m *Manager) FindChannelAdActiveByChannelID(channelID int64, status ActiveStatus) ([]ChannelAd, error) {\n\tres := []ChannelAd{}\n\t_, err := m.GetDbMap().Select(\n\t\t&res,\n\t\tfmt.Sprintf(\"SELECT * FROM %s WHERE channel_id=? AND active=? AND end IS NULL\", ChannelAdTableFull),\n\t\tchannelID,\n\t\tstatus,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func (c *Client) GetCrmStage(id int64) (*CrmStage, error) {\n\tcss, err := c.GetCrmStages([]int64{id})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif css != nil && len(*css) > 0 {\n\t\treturn &((*css)[0]), nil\n\t}\n\treturn nil, fmt.Errorf(\"id %v of crm.stage not found\", id)\n}", "func XPipelineSalesStagesBySalesMethodID(db XODB, salesMethodID uint) ([]*XPipelineSalesStage, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, name, probability, seq_num, active_flag, sales_method_id, created_by, updated_by, created_at, updated_at ` +\n\t\t`FROM x_showroom.x_pipeline_sales_stages ` +\n\t\t`WHERE sales_method_id = ?`\n\n\t// run query\n\tXOLog(sqlstr, salesMethodID)\n\tq, err := db.Query(sqlstr, salesMethodID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer q.Close()\n\n\t// load results\n\tres := []*XPipelineSalesStage{}\n\tfor q.Next() {\n\t\txpss := XPipelineSalesStage{\n\t\t\t_exists: true,\n\t\t}\n\n\t\t// scan\n\t\terr = q.Scan(&xpss.ID, &xpss.Name, &xpss.Probability, &xpss.SeqNum, &xpss.ActiveFlag, &xpss.SalesMethodID, &xpss.CreatedBy, &xpss.UpdatedBy, &xpss.CreatedAt, &xpss.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres = append(res, &xpss)\n\t}\n\n\treturn res, nil\n}", "func VisitsByEntIDCreatedAt(db XODB, entID string, createdAt time.Time) ([]*Visit, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, ent_id, trace_id, visit_page_cnt, residence_time_sec, browser_family, browser_version_string, browser_version, os_category, os_family, os_version_string, os_version, platform, ua_string, ip, country, province, city, isp, first_page_source, first_page_source_keyword, first_page_source_domain, first_page_source_url, first_page_title, first_page_domain, first_page_url, latest_title, latest_url, created_at, updated_at ` +\n\t\t`FROM custmchat.visit ` +\n\t\t`WHERE ent_id = ? AND created_at = ?`\n\n\t// run query\n\tXOLog(sqlstr, entID, createdAt)\n\tq, err := db.Query(sqlstr, entID, createdAt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer q.Close()\n\n\t// load results\n\tres := []*Visit{}\n\tfor q.Next() {\n\t\tv := Visit{}\n\n\t\t// scan\n\t\terr = q.Scan(&v.ID, &v.EntID, &v.TraceID, &v.VisitPageCnt, &v.ResidenceTimeSec, &v.BrowserFamily, &v.BrowserVersionString, &v.BrowserVersion, &v.OsCategory, &v.OsFamily, &v.OsVersionString, &v.OsVersion, &v.Platform, &v.UaString, &v.IP, &v.Country, &v.Province, &v.City, &v.Isp, &v.FirstPageSource, &v.FirstPageSourceKeyword, &v.FirstPageSourceDomain, &v.FirstPageSourceURL, &v.FirstPageTitle, &v.FirstPageDomain, &v.FirstPageURL, &v.LatestTitle, &v.LatestURL, &v.CreatedAt, &v.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres = append(res, &v)\n\t}\n\n\treturn res, nil\n}", "func (d *Data) FindAirportByICAO(icao string) *Airport {\n\treturn d.airportICAOIdx[icao]\n}", "func (_obj *DataService) GetActivityRecords(index int32, batch int32, activity_id string, nextIndex *int32, recordList *[]ActivityRecord, _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_int32(index, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(batch, 2)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_string(activity_id, 3)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*nextIndex), 4)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.WriteHead(codec.LIST, 5)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(int32(len((*recordList))), 0)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tfor _, v := range *recordList {\n\n\t\terr = v.WriteBlock(_os, 0)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\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, \"getActivityRecords\", _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(&(*nextIndex), 4, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr, have, ty = _is.SkipToNoCheck(5, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif ty == codec.LIST {\n\t\terr = _is.Read_int32(&length, 0, true)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t\t(*recordList) = make([]ActivityRecord, length)\n\t\tfor i20, e20 := int32(0), length; i20 < e20; i20++ {\n\n\t\t\terr = (*recordList)[i20].ReadBlock(_is, 0, false)\n\t\t\tif err != nil {\n\t\t\t\treturn ret, err\n\t\t\t}\n\n\t\t}\n\t} else if ty == codec.SIMPLE_LIST {\n\t\terr = fmt.Errorf(\"not support simple_list type\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t} else {\n\t\terr = fmt.Errorf(\"require vector, but not\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\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 (a ProcessInstanceApi) FindTaskInstancesByInstanceAndTaskIdStarted(instanceId string, taskId string) (*TaskInstanceCollection, *APIResponse, error) {\n\n\tvar localVarHttpMethod = strings.ToUpper(\"Get\")\n\t// create path and map variables\n\tlocalVarPath := a.Configuration.BasePath + \"/instances/{instance_id}/tasks/{task_id}/task_instances/started\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"instance_id\"+\"}\", fmt.Sprintf(\"%v\", instanceId), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"task_id\"+\"}\", fmt.Sprintf(\"%v\", taskId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := make(map[string]string)\n\tvar localVarPostBody interface{}\n\tvar localVarFileName string\n\tvar localVarFileBytes []byte\n\t// authentication '(PasswordGrant)' required\n\t// set key with prefix in header\n\tlocalVarHeaderParams[\"Authorization\"] = a.Configuration.GetAPIKeyWithPrefix(\"Authorization\")\n\t// add default headers if any\n\tfor key := range a.Configuration.DefaultHeader {\n\t\tlocalVarHeaderParams[key] = a.Configuration.DefaultHeader[key]\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tvar successPayload = new(TaskInstanceCollection)\n\tlocalVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\n\tvar localVarURL, _ = url.Parse(localVarPath)\n\tlocalVarURL.RawQuery = localVarQueryParams.Encode()\n\tvar localVarAPIResponse = &APIResponse{Operation: \"FindTaskInstancesByInstanceAndTaskIdStarted\", Method: localVarHttpMethod, RequestURL: localVarURL.String()}\n\tif localVarHttpResponse != nil {\n\t\tlocalVarAPIResponse.Response = localVarHttpResponse.RawResponse\n\t\tlocalVarAPIResponse.Payload = localVarHttpResponse.Body()\n\t}\n\n\tif err != nil {\n\t\treturn successPayload, localVarAPIResponse, err\n\t}\n\terr = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)\n\treturn successPayload, localVarAPIResponse, err\n}", "func (o EipAddressOutput) ActivityId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EipAddress) pulumi.StringPtrOutput { return v.ActivityId }).(pulumi.StringPtrOutput)\n}", "func (database *Database) FindActivityByID(activity *Activity, id int) error {\n\terr := database.DB.Preload(\"OrderItems\").\n\t\tPreload(\"Restaurants\").\n\t\tPreload(\"Restaurants.Menus\").\n\t\tWhere(\"id = ?\", id).\n\t\tFirst(activity).Error\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to get an activity with ID = %d: %s\", id, err)\n\t}\n\n\treturn nil\n}", "func (jbobject *TaskContext) StageId() int {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"stageId\", javabind.Int)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(int)\n}", "func Stage(ctx context.Context, id, endpoint, binary, st string) (retrievalToken string, err error) {\n\tctx = grpcx.WriteWorkerID(ctx, id)\n\tcc, err := grpcx.Dial(ctx, endpoint, 2*time.Minute)\n\tif err != nil {\n\t\treturn \"\", errors.WithContext(err, \"connecting to artifact service\")\n\t}\n\tdefer cc.Close()\n\n\tif err := StageViaPortableAPI(ctx, cc, binary, st); err == nil {\n\t\treturn \"\", nil\n\t}\n\tlog.Warnf(ctx, \"unable to stage with PortableAPI: %v; falling back to legacy\", err)\n\n\treturn StageViaLegacyAPI(ctx, cc, binary, st)\n}", "func findByID(node *ProjectNode, projectSFID string) *ProjectNode {\n\tif node == nil {\n\t\treturn nil\n\t}\n\tif node.ID == projectSFID {\n\t\treturn node\n\t}\n\n\tfor _, child := range node.Children {\n\t\tfoundNode := findByID(child, projectSFID)\n\t\tif foundNode != nil {\n\t\t\treturn foundNode\n\t\t}\n\t}\n\n\treturn nil\n}", "func (this *activitiesStruct) Get(id uint32) (ActivityGroup, error) {\n\tthis.mutex.RLock()\n\tgroups := this.groups\n\tnumGroups := len(groups)\n\tnumGroups64 := uint64(numGroups)\n\tid64 := uint64(id)\n\n\t/*\n\t * Check if group exists.\n\t */\n\tif id64 >= numGroups64 {\n\t\tthis.mutex.RUnlock()\n\t\treturn nil, fmt.Errorf(\"Activity group with id %d does not exist. There are only %d groups.\", id, numGroups)\n\t} else {\n\t\tg := groups[id]\n\t\tthis.mutex.RUnlock()\n\t\treturn &g, nil\n\t}\n\n}", "func (c *ActivitiesClient) Get(ctx context.Context, id int) (*Activities, error) {\n\treturn c.Query().Where(activities.ID(id)).Only(ctx)\n}", "func (s *Service) VideoAudit(c context.Context, stime, etime time.Time) (reports []*archive.Report, err error) {\n\tif reports, err = s.arc.Reports(c, archive.ReportTypeVideoAudit, stime, etime); err != nil {\n\t\tlog.Error(\"s.arc.Reports(%d) err(%v)\", archive.ReportTypeVideoAudit, err)\n\t\treturn\n\t}\n\treturn\n}", "func GetStages(ctx context.Context) []buildapi.StageInfo {\n\tstages := fromContext(ctx)\n\treturn *stages\n}", "func (m *Manager) FindChannelIDAdByAdIDByActive(channelID int64, addID int64, userID int64) (*ChannelAdActive, error) {\n\tvar res ChannelAdActive\n\terr := m.GetDbMap().SelectOne(\n\t\t&res,\n\t\tfmt.Sprintf(\"SELECT ca.*,u.id AS user_id, p.share AS share\"+\n\t\t\t\"FROM %s AS ca \"+\n\t\t\t\"INNER JOIN %s AS c \"+\n\t\t\t\"ON ca.channel_id = c.id \"+\n\t\t\t\"INNER JOIN %s AS u \"+\n\t\t\t\"ON u.id = c.user_id\"+\n\t\t\t\"INNER JOIN %s as a \"+\n\t\t\t\"ON ca.ad_id = a.id \"+\n\t\t\t\"INNER JOIN %s AS p \"+\n\t\t\t\"ON p.id = a.plan_id\"+\n\t\t\t\"WHERE c.user_id = u.id \"+\n\t\t\t\"AND ca.active = ? \"+\n\t\t\t\"AND u.id = ? \"+\n\t\t\t\"AND ca.channel_id = ? \"+\n\t\t\t\"AND ca.ad_id = ?\", ChannelAdTableFull, ChannelTableFull, aaa.UserTableFull, AdTableFull, PlanTableFull),\n\t\tActiveStatusYes,\n\t\tuserID,\n\t\tchannelID,\n\t\taddID,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &res, nil\n}", "func (s *ASAEngine) GetScenariosFromMatchingASAs(ctx context.Context, objectID string, objType graphql.FormationObjectType) ([]string, error) {\n\tlog.C(ctx).Infof(\"Getting scenarios matching from ASA for object with ID: %q and type: %q\", objectID, objType)\n\ttenantID, err := tenant.LoadFromContext(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatchFunc, err := s.GetMatchingFuncByFormationObjectType(objType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscenarioAssignments, err := s.asaRepository.ListAll(ctx, tenantID)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"while listing Automatic Scenario Assignments in tenant: %s\", tenantID)\n\t}\n\tlog.C(ctx).Infof(\"Found %d ASA(s) in tenant with ID: %q\", len(scenarioAssignments), tenantID)\n\n\tmatchingASAs := make([]*model.AutomaticScenarioAssignment, 0, len(scenarioAssignments))\n\tfor _, scenarioAssignment := range scenarioAssignments {\n\t\tmatches, err := matchFunc(ctx, scenarioAssignment, objectID)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"while checking if asa matches runtime with ID %s\", objectID)\n\t\t}\n\t\tif matches {\n\t\t\tmatchingASAs = append(matchingASAs, scenarioAssignment)\n\t\t}\n\t}\n\n\tscenarios := make([]string, 0)\n\tfor _, sa := range matchingASAs {\n\t\tscenarios = append(scenarios, sa.ScenarioName)\n\t}\n\tlog.C(ctx).Infof(\"Matched scenarios from ASA are: %v\", scenarios)\n\n\treturn scenarios, nil\n}", "func RtpAttribIdFind(attrib string) RtpAttrib {\n\treturn 0\n}", "func (_obj *DataService) GetActivityInfo(activity_id string, activityInfo *ActivityInfo, _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(activity_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = (*activityInfo).WriteBlock(_os, 2)\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, \"getActivityInfo\", _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 = (*activityInfo).ReadBlock(_is, 2, 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 findItemInSequence(sequenceKey string, findVal *goyaml.Node, sequenceNode *goyaml.Node) int {\n\tchildren := sequenceNode.Content\n\tfor i, val := range children {\n\t\tif sequenceItemMatch(sequenceKey, val, findVal) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func ActivitySelection(activities []Activity) (int, []Activity) {\n\tpreviousFinish := 0\n\tresults := []Activity{}\n\tfor _, currentActivity := range activities {\n\t\tif currentActivity.Start >= previousFinish {\n\t\t\tresults = append(results, currentActivity)\n\t\t\tpreviousFinish = currentActivity.Finish\n\t\t}\n\t}\n\treturn len(results), results\n}", "func (p Program) Find(id uint) Program {\n\t//Preload preloads structs - Creates a SQL query pr. Preload. Should be fixed in Gorm V2.\n\tif err := db.Model(p).\n\t\tPreload(\"Production\").\n\t\tPreload(\"Category\").\n\t\tPreload(\"Genres\").\n\t\tPreload(\"Serie\").\n\t\tPreload(\"Season\").\n\t\tPreload(\"Credits\").\n\t\tPreload(\"Credits.Persons\").\n\t\tPreload(\"Credits.CreditGroup\").\n\t\tWhere(\"id = ?\", id).\n\t\tFirst(&p).Error; err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn p\n}", "func (m *Manager) FindChannelAdActive() ([]ChannelAdD, error) {\n\tres := []ChannelAdD{}\n\t_, err := m.GetDbMap().Select(\n\t\t&res,\n\t\tfmt.Sprintf(\"SELECT %[1]s.*,%[2]s.cli_message_id AS cli_message_ad,%[2]s.promote_data,%[2]s.src, \"+\n\t\t\t\"%[3]s.view AS plan_view,%[3]s.position AS plan_position\"+\n\t\t\t\" FROM %[1]s INNER JOIN %[2]s ON %[2]s.id=%[1]s.ad_id \"+\n\t\t\t\" INNER JOIN %[3]s ON %[3]s.id=%[2]s.plan_id \"+\n\t\t\t\" AND %[1]s.active='yes' \"+\n\t\t\t\" AND %[2]s.active_status='yes' \"+\n\t\t\t\" AND end IS NULL\",\n\t\t\tChannelAdTableFull,\n\t\t\tAdTableFull,\n\t\t\tPlanTableFull,\n\t\t),\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func (r *WikiActorsRepo) Find(kind wikiactors.Kind, id int) *wikiactors.Actor {\n\tr.mutex.RLock()\n\tdefer r.mutex.RUnlock()\n\n\tp, found := r.byIDByKind[kind][id]\n\tif found != true {\n\t\treturn nil\n\t}\n\treturn p\n}", "func (st *Stages) Run(id string, seed interface{}) error {\n\tsyncData, err := st.syncer.GetAll(id)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Cannot fetch synced data\")\n\t}\n\tprevResult := &StageResult{Data: seed}\n\tfor _, stage := range st.stages {\n\t\tsyncedStageResult, ok := syncData[stage.name]\n\t\tif !ok {\n\t\t\tsyncedStageResult = &StageResult{}\n\t\t}\n\t\tif syncedStageResult.Status == \"done\" {\n\t\t\tprevResult = syncedStageResult\n\t\t\tcontinue\n\t\t}\n\t\tstageResult, bookmark, err := stage.execStage(st.syncer, id, prevResult.Data, seed)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"Unable to execute stage %s:%s\", stage.name, id)\n\t\t}\n\t\tprevResult = stageResult\n\t\tif bookmark { // Bookmark is an explicit termination to be resumed later\n\t\t\tbreak\n\t\t}\n\t}\n\tst.lastResult = prevResult\n\treturn nil\n}", "func (filter TaskReliabilityFilter) buildMatchStageForTask() bson.M {\n\tboundaries := filter.dateBoundaries()\n\n\tstart := boundaries[0]\n\tend := boundaries[len(boundaries)-1]\n\n\tmatch := bson.M{\n\t\ttaskstats.DBTaskStatsIDDateKeyFull: bson.M{\n\t\t\t\"$lt\": start,\n\t\t\t\"$gte\": end,\n\t\t},\n\t\ttaskstats.DBTaskStatsIDProjectKeyFull: filter.Project,\n\t\ttaskstats.DBTaskStatsIDRequesterKeyFull: bson.M{\"$in\": filter.Requesters},\n\t}\n\tif len(filter.Tasks) > 0 {\n\t\tmatch[taskstats.DBTaskStatsIDTaskNameKeyFull] = taskstats.BuildMatchArrayExpression(filter.Tasks)\n\t}\n\tif len(filter.BuildVariants) > 0 {\n\t\tmatch[taskstats.DBTaskStatsIDBuildVariantKeyFull] = taskstats.BuildMatchArrayExpression(filter.BuildVariants)\n\t}\n\tif len(filter.Distros) > 0 {\n\t\tmatch[taskstats.DBTaskStatsIDDistroKeyFull] = taskstats.BuildMatchArrayExpression(filter.Distros)\n\t}\n\n\tif filter.StartAt != nil {\n\t\tmatch[\"$or\"] = filter.buildTaskPaginationOrBranches()\n\t}\n\treturn bson.M{\"$match\": match}\n}", "func Find(agent Agent, worldState StateList, goalState StateList) []Action {\n\t// we cannot plan without any goals\n\tif len(goalState) == 0 {\n\t\tpanic(\"cannot plan without a goal\")\n\t}\n\n\tvar result []Action\n\n\t// check what actions can run\n\tvar usableActions []Action\n\tfor _, action := range agent.AvailableActions() {\n\t\taction.Reset()\n\t\tusableActions = append(usableActions, action)\n\t}\n\n\t// early out, this agent doesn't have any actions\n\tif len(usableActions) == 0 {\n\t\treturn result\n\t}\n\n\tvar plans []*node\n\tif !buildGraph(&node{state: worldState}, &plans, usableActions, goalState, agent) {\n\t\treturn result\n\t}\n\n\t// get the cheapest plan\n\tcheapest := plans[0]\n\tfor i := 1; i < len(plans); i++ {\n\t\tif plans[i].runningCost < cheapest.runningCost {\n\t\t\tcheapest = plans[i]\n\t\t}\n\t}\n\n\t// invert the list so that we get the end action at the end of the result list\n\tfor n := cheapest; n != nil && n.action != nil; n = n.parent {\n\t\tresult = append([]Action{n.action}, result...)\n\t}\n\treturn result\n}", "func (b *Executor) waitForStage(ctx context.Context, name string, stages imagebuilder.Stages) (bool, error) {\n\tfound := false\n\tfor _, otherStage := range stages {\n\t\tif otherStage.Name == name || strconv.Itoa(otherStage.Position) == name {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn false, nil\n\t}\n\tfor {\n\t\tif b.lastError != nil {\n\t\t\treturn true, b.lastError\n\t\t}\n\n\t\tb.stagesLock.Lock()\n\t\tterminationError, terminated := b.terminatedStage[name]\n\t\tb.stagesLock.Unlock()\n\n\t\tif terminationError != nil {\n\t\t\treturn false, terminationError\n\t\t}\n\t\tif terminated {\n\t\t\treturn true, nil\n\t\t}\n\n\t\tb.stagesSemaphore.Release(1)\n\t\ttime.Sleep(time.Millisecond * 10)\n\t\tif err := b.stagesSemaphore.Acquire(ctx, 1); err != nil {\n\t\t\treturn true, fmt.Errorf(\"reacquiring job semaphore: %w\", err)\n\t\t}\n\t}\n}", "func (visual *Visual) FindParameter(id uuid.UUID) (*Group, *parameters.Parameter) {\n\tvisual.mux.Lock()\n\tdefer visual.mux.Unlock()\n\n\t// iterate over shows, visuals and groups\n\tfor _, group := range visual.Groups() {\n\t\tfor _, parameter := range group.Effect.Parameters() {\n\t\t\tif parameter.ID == id {\n\t\t\t\treturn group, parameter\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, nil\n}", "func (m *IndustryDataRunActivity) GetActivity()(IndustryDataActivityable) {\n val, err := m.GetBackingStore().Get(\"activity\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(IndustryDataActivityable)\n }\n return nil\n}", "func (a *API) GetActivityByID(id string) (Activity, error) {\n\tactivites, err := a.ReadActivities()\n\tif err != nil {\n\t\treturn Activity{}, err\n\t}\n\tfor _, a := range activites.Activities {\n\t\tif a.ID == id {\n\t\t\treturn a, nil\n\t\t}\n\t}\n\n\treturn Activity{}, nil\n}", "func getActivity(meta *client.AccountMeta) error {\n\tig, err := meta.Delayed()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ig.Debug {\n\t\tlog.Debug(\"Checking feed for %v\", ig.Username)\n\t}\n\t// get recent activity\n\tract, err := ig.GetRecentActivity()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// fetch old stories\n\tfor _, story := range append(ract.OldStories, ract.NewStories...) {\n\t\terr := fillFeed(story, meta)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func ParseActivity(stravaActivity Activity) ([]Point, error) {\n\tfilename := stravaActivity.Filename\n\tif filename != \"\" { // Stationary activities (such as indoor row) do not have route files\n\t\tfile, err := ioutil.ReadFile(filepath.Join(ArchivePath, filename)) // Byte array of decompresed file\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfileParts := strings.Split(filename, \".\") // Used to determine file type and compression status\n\t\tif len(fileParts) == 3 && fileParts[2] == \"gz\" { // File is compressed\n\t\t\tb := bytes.NewBuffer(file)\n\t\t\tvar r io.Reader\n\t\t\tr, err := gzip.NewReader(b)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tvar fileBuffer bytes.Buffer\n\t\t\t_, err = fileBuffer.ReadFrom(r)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfile = fileBuffer.Bytes()\n\t\t}\n\n\t\tswitch fileParts[1] { // Parse the actual file\n\t\tcase \"gpx\":\n\t\t\treturn ParseGPXFile(file)\n\t\tcase \"tcx\":\n\t\t\treturn ParseTCXFile(file, false)\n\t\tcase \"fit\":\n\t\t\treturn ParseFITFile(file)\n\t\tdefault:\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\n\treturn nil, nil\n}", "func (b *Executor) startStage(ctx context.Context, stage *imagebuilder.Stage, stages imagebuilder.Stages, output string) *StageExecutor {\n\tstageExec := &StageExecutor{\n\t\tctx: ctx,\n\t\texecutor: b,\n\t\tlog: b.log,\n\t\tindex: stage.Position,\n\t\tstages: stages,\n\t\tname: stage.Name,\n\t\tvolumeCache: make(map[string]string),\n\t\tvolumeCacheInfo: make(map[string]os.FileInfo),\n\t\toutput: output,\n\t\tstage: stage,\n\t}\n\tb.stages[stage.Name] = stageExec\n\tif idx := strconv.Itoa(stage.Position); idx != stage.Name {\n\t\tb.stages[idx] = stageExec\n\t}\n\treturn stageExec\n}", "func (m *Manager) FindActiveChannelAdByChannelID(channelID int64) []ChannelAd {\n\tvar res []ChannelAd\n\tq := fmt.Sprintf(\"SELECT * FROM %s WHERE channel_id=? AND active = ?\", ChannelAdTableFull)\n\t_, err := m.GetDbMap().Select(\n\t\t&res,\n\t\tq,\n\t\tchannelID,\n\t\tActiveStatusYes,\n\t)\n\tassert.Nil(err)\n\treturn res\n}", "func (o *orm) PipelineRunsByJobID(jobID int32, offset, size int) ([]pipeline.Run, int, error) {\n\tvar pipelineRuns []pipeline.Run\n\tvar count int64\n\terr := o.db.\n\t\tModel(pipeline.Run{}).\n\t\tJoins(\"INNER JOIN jobs ON pipeline_runs.pipeline_spec_id = jobs.pipeline_spec_id\").\n\t\tWhere(\"jobs.id = ?\", jobID).\n\t\tCount(&count).\n\t\tError\n\n\tif err != nil {\n\t\treturn pipelineRuns, 0, err\n\t}\n\n\terr = o.db.\n\t\tPreload(\"PipelineSpec\").\n\t\tPreload(\"PipelineTaskRuns\", func(db *gorm.DB) *gorm.DB {\n\t\t\treturn db.\n\t\t\t\tOrder(\"created_at ASC, id ASC\")\n\t\t}).\n\t\tJoins(\"INNER JOIN jobs ON pipeline_runs.pipeline_spec_id = jobs.pipeline_spec_id\").\n\t\tWhere(\"jobs.id = ?\", jobID).\n\t\tLimit(size).\n\t\tOffset(offset).\n\t\tOrder(\"created_at DESC, id DESC\").\n\t\tFind(&pipelineRuns).\n\t\tError\n\n\t// can skip preloadJobIDs since we already know the jobID\n\tfor i := range pipelineRuns {\n\t\tpipelineRuns[i].PipelineSpec.JobID = jobID\n\t}\n\n\treturn pipelineRuns, int(count), err\n}", "func (a GetSLITriggeredAdapter) GetStage() string {\n\treturn a.event.Stage\n}", "func getChildrenAsset(id int) ([]Asset, error) {\n\tparams := map[string]string{\n\t\t\"predicate\": fmt.Sprintf(\"parent='%d'\", id),\n\t}\n\tresp, err := get(\"asset\", params)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed TCMD request\")\n\t}\n\n\tvar result []Asset\n\terr = json.Unmarshal(resp, &result)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed to unmarshal TCMD response\")\n\t}\n\n\tif len(result) > 0 {\n\t\treturn result, nil\n\t}\n\treturn nil, nil\n}", "func VisitsByEntIDTraceID(db XODB, entID string, traceID string) ([]*Visit, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, ent_id, trace_id, visit_page_cnt, residence_time_sec, browser_family, browser_version_string, browser_version, os_category, os_family, os_version_string, os_version, platform, ua_string, ip, country, province, city, isp, first_page_source, first_page_source_keyword, first_page_source_domain, first_page_source_url, first_page_title, first_page_domain, first_page_url, latest_title, latest_url, created_at, updated_at ` +\n\t\t`FROM custmchat.visit ` +\n\t\t`WHERE ent_id = ? AND trace_id = ?`\n\n\t// run query\n\tXOLog(sqlstr, entID, traceID)\n\tq, err := db.Query(sqlstr, entID, traceID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer q.Close()\n\n\t// load results\n\tres := []*Visit{}\n\tfor q.Next() {\n\t\tv := Visit{}\n\n\t\t// scan\n\t\terr = q.Scan(&v.ID, &v.EntID, &v.TraceID, &v.VisitPageCnt, &v.ResidenceTimeSec, &v.BrowserFamily, &v.BrowserVersionString, &v.BrowserVersion, &v.OsCategory, &v.OsFamily, &v.OsVersionString, &v.OsVersion, &v.Platform, &v.UaString, &v.IP, &v.Country, &v.Province, &v.City, &v.Isp, &v.FirstPageSource, &v.FirstPageSourceKeyword, &v.FirstPageSourceDomain, &v.FirstPageSourceURL, &v.FirstPageTitle, &v.FirstPageDomain, &v.FirstPageURL, &v.LatestTitle, &v.LatestURL, &v.CreatedAt, &v.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres = append(res, &v)\n\t}\n\n\treturn res, nil\n}", "func isStepRunning(index int, stageSteps []v1.CoreActivityStep) bool {\n\tif len(stageSteps) > 0 {\n\t\tpreviousStep := stageSteps[index-1]\n\t\treturn previousStep.CompletedTimestamp != nil\n\t}\n\treturn true\n}", "func (adb *AniDB) EpisodeByID(eid EID) <-chan *Episode {\n\tkey := []fscache.CacheKey{\"eid\", eid}\n\tch := make(chan *Episode, 1)\n\n\tif eid < 1 {\n\t\tch <- nil\n\t\tclose(ch)\n\t\treturn ch\n\t}\n\n\tic := make(chan notification, 1)\n\tgo func() { ch <- (<-ic).(*Episode); close(ch) }()\n\tif intentMap.Intent(ic, key...) {\n\t\treturn ch\n\t}\n\n\tif !Cache.IsValid(InvalidKeyCacheDuration, key...) {\n\t\tintentMap.NotifyClose((*Episode)(nil), key...)\n\t\treturn ch\n\t}\n\n\te := eid.Episode()\n\tif !e.IsStale() {\n\t\tintentMap.NotifyClose(e, key...)\n\t\treturn ch\n\t}\n\n\tgo func() {\n\t\t// The UDP API data is worse than the HTTP API anime data and\n\t\t// might even get truncated on some pathological cases;\n\t\t// try and get from the corresponding Anime, which uses the HTTP\n\t\t// API episode list.\n\n\t\taid := AID(0)\n\t\t_, err := Cache.Get(&aid, \"aid\", \"by-eid\", eid)\n\t\tok := err == nil\n\n\t\tudpDone := false\n\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tif !ok && udpDone {\n\t\t\t\t// couldn't get anime and we already ran the EPISODE query\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif !ok {\n\t\t\t\t// We don't know what the AID is yet.\n\t\t\t\treply := <-adb.udp.SendRecv(\"EPISODE\", paramMap{\"eid\": eid})\n\n\t\t\t\tif reply.Error() == nil {\n\t\t\t\t\tparts := strings.Split(reply.Lines()[1], \"|\")\n\n\t\t\t\t\tif id, err := strconv.ParseInt(parts[1], 10, 32); err == nil {\n\t\t\t\t\t\tok = true\n\t\t\t\t\t\taid = AID(id)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} else if reply.Code() == 340 {\n\t\t\t\t\tCache.SetInvalid(key...)\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\tudpDone = true\n\t\t\t}\n\t\t\ta := <-adb.AnimeByID(AID(aid)) // updates the episode cache as well\n\t\t\tep := a.EpisodeByEID(eid)\n\n\t\t\tif ep != nil {\n\t\t\t\te = ep\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\t// the EID<->AID map broke\n\t\t\t\tok = false\n\t\t\t\tCache.Delete(\"aid\", \"by-eid\", eid)\n\t\t\t}\n\t\t}\n\t\tintentMap.NotifyClose(e, key...)\n\t}()\n\treturn ch\n}", "func (d *Data) FindAirport(id string) *Airport {\n\taip := d.FindAirportByICAO(id)\n\tif aip == nil {\n\t\taip = d.FindAirportByIATA(id)\n\t}\n\treturn aip\n}", "func (a *API) ReadActivities() (*Activities, error) {\n\tdst := new(Activities)\n\turl := BuildURL(a.url, \"/activities\")\n\terr := a.Get(url, dst)\n\treturn dst, err\n}", "func (d *Data) FindAirportByIATA(iata string) *Airport {\n\treturn d.airportIATAIdx[iata]\n}", "func (this *activitiesStruct) End(id uint32) (time.Time, error) {\n\tthis.mutex.RLock()\n\tgroups := this.groups\n\tnumGroups := len(groups)\n\tnumGroups64 := uint64(numGroups)\n\tlastGroupIdx := numGroups64 - 1\n\tid64 := uint64(id)\n\n\t/*\n\t * Check if group exists or is the last group.\n\t */\n\tif id64 >= numGroups64 {\n\t\tthis.mutex.RUnlock()\n\t\treturn time.Time{}, fmt.Errorf(\"No activity group with index %d. (There are %d activity groups.)\", id64, numGroups64)\n\t} else if id64 == lastGroupIdx {\n\t\tg := groups[lastGroupIdx]\n\t\tthis.mutex.RUnlock()\n\t\ttimeLast := g.begin\n\t\tresult := timeLast.Add(TIME_DAY)\n\t\treturn result, nil\n\t} else {\n\t\tidInc64 := id64 + 1\n\t\tg := groups[idInc64]\n\t\tthis.mutex.RUnlock()\n\t\tresult := g.begin\n\t\treturn result, nil\n\t}\n\n}", "func TaskFind(db *pg.DB) (*[]Task, error) {\n\tvar tasks []Task\n\terr := db.Model(&tasks).Where(\"state='queue' AND exec_time < CURRENT_TIMESTAMP\").Select()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &tasks, err\n}", "func CommandShowActive(conf Config, ctx, query Query) error {\n\tts, err := LoadTaskSet(conf.Repo, conf.IDsFile, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tquery = query.Merge(ctx)\n\tts.Filter(query)\n\tts.FilterByStatus(STATUS_ACTIVE)\n\tts.DisplayByNext(ctx, true)\n\n\treturn nil\n}", "func containerRunningById(id string) (bool, error) {\n\tcontainers, err := getContainers()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfor _, c := range containers {\n\t\tif c.ID == id {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}", "func (s *stepRotator) getVersionIDFromVersionStage(vStage versionStage) (string, error) {\n\tversionIDsToStages, err := s.getVersionIDsToStages()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor id, stages := range versionIDsToStages {\n\t\tfor _, stage := range stages {\n\t\t\tif *stage == string(vStage) {\n\t\t\t\treturn id, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", nil\n}", "func (t Trade) GetStage(idx uint) (*TradeStage, errstack.E) {\n\n\tif int(idx) >= len(t.Stages) {\n\t\treturn nil, errstack.NewReq(\"Stage Index out of range\")\n\t}\n\treturn &t.Stages[idx], nil\n}", "func (a *Campaigns_ChallengesApiService) GetChallengeActivity(ctx context.Context, id int64, challengeId int64) (ChallengeActivityResource, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t \tsuccessPayload ChallengeActivityResource\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/challenges/{challenge_id}/activities/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", fmt.Sprintf(\"%v\", id), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"challenge_id\"+\"}\", fmt.Sprintf(\"%v\", challengeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\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{\n\t\t\"application/json\",\n\t\t}\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, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\t localVarHttpResponse, err := a.client.callAPI(r)\n\t if err != nil || localVarHttpResponse == nil {\n\t\t return successPayload, localVarHttpResponse, err\n\t }\n\t defer localVarHttpResponse.Body.Close()\n\t if localVarHttpResponse.StatusCode >= 300 {\n\t\treturn successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status)\n\t }\n\t\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t \treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func (u teamHandler) findAllocation(req *restful.Request, resp *restful.Response) {\n\thandleErrors(req, resp, func() error {\n\t\tteam := req.PathParameter(\"team\")\n\t\tname := req.PathParameter(\"name\")\n\t\tassigned := req.QueryParameter(\"assigned\")\n\n\t\tif assigned == \"false\" {\n\t\t\tobj, err := u.Teams().Team(team).Allocations().Get(req.Request.Context(), name)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn resp.WriteHeaderAndEntity(http.StatusOK, obj)\n\t\t}\n\n\t\tobj, err := u.Teams().Team(team).Allocations().GetAssigned(req.Request.Context(), name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn resp.WriteHeaderAndEntity(http.StatusOK, obj)\n\t})\n}", "func (m *Manager) FindBundleChannelAdActive() ([]FindBundleChannelAdActiveType, error) {\n\tres := []FindBundleChannelAdActiveType{}\n\t_, err := m.GetDbMap().Select(\n\t\t&res,\n\t\tfmt.Sprintf(\"SELECT %[1]s.*,%[2]s.cli_message_id,%[2]s.promote_data,%[2]s.src, %[3]s.code\"+\n\t\t\t\"(%[3]s.view -((%[3]s.view * %[3]s.percent_finish)/100)) AS target_view,%[3]s.position\"+\n\t\t\t\" FROM %[1]s \"+\n\t\t\t\" INNER JOIN %[2]s ON %[2]s.id=%[1]s.ad_id AND %[1]s.ad_id = %[3]s.target_ad \"+\n\t\t\t\" INNER JOIN %[3]s ON %[3]s.id=%[1]s.bundle_id \"+\n\t\t\t\" AND %[1]s.active=? \",\n\t\t\tBundleChannelAdTableFull,\n\t\t\tAdTableFull,\n\t\t\tBundlesTableFull,\n\t\t),\n\t\tActiveStatusYes,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func FindCreatingRuntimesByRelease(appID uint64, envs map[string][]string, ymlName string, bdl *bundle.Bundle) ([]apistructs.RuntimeSummaryDTO, error) {\n\tvar result []apistructs.RuntimeSummaryDTO\n\tpipelinePageReq := apistructs.PipelinePageListRequest{\n\t\tSources: []apistructs.PipelineSource{apistructs.PipelineSourceDice},\n\t\tStatuses: []string{\"Running\"},\n\t}\n\tif appID != 0 {\n\t\tpipelinePageReq.MustMatchLabelsQueryParams = []string{\"appID=\" + strconv.FormatUint(appID, 10)}\n\t}\n\tif ymlName != \"\" {\n\t\tpipelinePageReq.YmlNames = []string{ymlName}\n\t}\n\n\tresp, err := bdl.PageListPipeline(pipelinePageReq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, v := range resp.Pipelines {\n\t\tif !strings.Contains(v.YmlName, \"dice-deploy-release\") {\n\t\t\t// not the target pipeline\n\t\t\tcontinue\n\t\t}\n\n\t\tbranchSlice := strings.SplitN(v.YmlName, \"-\", 4)\n\t\tif len(branchSlice) != 4 {\n\t\t\treturn nil, errors.Errorf(\"Invalid yaml name %s\", v.YmlName)\n\t\t}\n\t\tbranch := branchSlice[3]\n\t\truntimeBranchs, ok := envs[strings.ToLower(v.Extra.DiceWorkspace)]\n\n\t\tif !ok || strutil.Exist(runtimeBranchs, branch) {\n\t\t\t// first condition means user have permission\n\t\t\t// second condition means that the runtime data of db has higher priority\n\t\t\t// And one branch corresponds to only one rutime\n\t\t\tcontinue\n\t\t}\n\n\t\t// get pipeline detail to confirm whether the runtime has been created\n\t\tpiplineDetail, err := bdl.GetPipeline(v.ID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !isUndoneTaskOFDeployByRelease(piplineDetail) {\n\t\t\t// Task has been completed\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, apistructs.RuntimeSummaryDTO{\n\t\t\tRuntimeInspectDTO: apistructs.RuntimeInspectDTO{\n\t\t\t\tName: v.FilterLabels[\"branch\"],\n\t\t\t\tSource: apistructs.RELEASE,\n\t\t\t\tStatus: \"Init\",\n\t\t\t\tDeployStatus: apistructs.DeploymentStatusDeploying,\n\t\t\t\tClusterName: v.ClusterName,\n\t\t\t\tExtra: map[string]interface{}{\"applicationId\": v.FilterLabels[\"appID\"], \"buildId\": v.ID,\n\t\t\t\t\t\"workspace\": v.Extra.DiceWorkspace, \"commitId\": v.Commit, \"fakeRuntime\": true},\n\t\t\t\tTimeCreated: *v.TimeBegin,\n\t\t\t\tCreatedAt: *v.TimeBegin,\n\t\t\t\tUpdatedAt: *v.TimeBegin,\n\t\t\t},\n\t\t\tLastOperateTime: *v.TimeBegin,\n\t\t\tLastOperator: fmt.Sprintf(\"%v\", v.Extra.RunUser.ID),\n\t\t})\n\t}\n\n\treturn result, nil\n}", "func (_obj *DataService) GetActivityRecordsWithContext(tarsCtx context.Context, index int32, batch int32, activity_id string, nextIndex *int32, recordList *[]ActivityRecord, _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_int32(index, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(batch, 2)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_string(activity_id, 3)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*nextIndex), 4)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.WriteHead(codec.LIST, 5)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(int32(len((*recordList))), 0)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tfor _, v := range *recordList {\n\n\t\terr = v.WriteBlock(_os, 0)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\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\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"getActivityRecords\", _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(&(*nextIndex), 4, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr, have, ty = _is.SkipToNoCheck(5, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif ty == codec.LIST {\n\t\terr = _is.Read_int32(&length, 0, true)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t\t(*recordList) = make([]ActivityRecord, length)\n\t\tfor i21, e21 := int32(0), length; i21 < e21; i21++ {\n\n\t\t\terr = (*recordList)[i21].ReadBlock(_is, 0, false)\n\t\t\tif err != nil {\n\t\t\t\treturn ret, err\n\t\t\t}\n\n\t\t}\n\t} else if ty == codec.SIMPLE_LIST {\n\t\terr = fmt.Errorf(\"not support simple_list type\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t} else {\n\t\terr = fmt.Errorf(\"require vector, but not\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\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 (c *cache) find(id int) (item, bool) {\n\tfor i := 0; i < c.curSize; i++ {\n\t\tif c.stories[i].Item.ID == id {\n\t\t\treturn c.stories[i], true\n\t\t}\n\t}\n\treturn item{}, false\n}", "func (m *AppConsentAppConsentRequestsItemUserConsentRequestsItemApprovalStagesApprovalStageItemRequestBuilder) Get(ctx context.Context, requestConfiguration *AppConsentAppConsentRequestsItemUserConsentRequestsItemApprovalStagesApprovalStageItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.ApprovalStageable, 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.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateApprovalStageFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.ApprovalStageable), nil\n}", "func (database *Database) ListActivities(activities *[]Activity, organizationID int, status string) error {\n\tnow := time.Now().UTC().Format(time.UnixDate)\n\n\tfilteredActivities := database.DB\n\tswitch status {\n\tcase \"open\":\n\t\tfilteredActivities = database.DB.Where(\"closed_at > ?\", now)\n\tcase \"closed\":\n\t\tfilteredActivities = database.DB.Where(\"closed_at <= ?\", now)\n\t}\n\n\terr := filteredActivities.Order(\"closed_at asc\").\n\t\tPreload(\"OrderItems\").\n\t\tPreload(\"Restaurants\").\n\t\tPreload(\"Restaurants.Menus\").\n\t\tWhere(&Activity{OrganizationID: organizationID}).\n\t\tFind(activities).Error\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to select all activites: %s\", err)\n\t}\n\n\treturn nil\n}", "func (e *OverlayEnv) GetEnvByID(id int) (Expander, bool) {\n\t// do we have a stack to work with?\n\tif e == nil {\n\t\treturn nil, false\n\t}\n\n\t// do we have the environment that has been requested?\n\tif id >= len(e.envs) || id < 0 {\n\t\treturn nil, false\n\t}\n\n\t// yes, we do\n\treturn e.envs[id], true\n}", "func (agents *Agents) FindAgent(agentID string) *Agent {\n\tagents.mux.RLock()\n\tdefer agents.mux.RUnlock()\n\treturn agents.agentsById[agentID]\n}", "func (*ActivityStageDataAccessObject) FindFullByMonth(\n\tdate time.Time) [][]ActivityStageFull {\n\n\tstart := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.Local)\n\tend := start.AddDate(0, 1, 0).AddDate(0, 0, -1)\n\tresult := make([][]ActivityStageFull, 0)\n\tfor i := start.Day(); i <= end.Day(); i++ {\n\t\tcurDate := time.Date(date.Year(), date.Month(), i, 0, 0, 0, 0,\n\t\t\ttime.Local)\n\t\tresult = append(result, ActivityStageDAO.FindFullByDay(curDate))\n\t}\n\n\treturn result\n}", "func LoadByWorkflowID(db gorp.SqlExecutor, workflowID int64) ([]sdk.Pipeline, error) {\n\tpips := []sdk.Pipeline{}\n\tquery := `SELECT DISTINCT pipeline.*\n\tFROM pipeline\n\t\tJOIN workflow_node ON pipeline.id = workflow_node.pipeline_id\n\t\tJOIN workflow ON workflow_node.workflow_id = workflow.id\n\tWHERE workflow.id = $1`\n\n\tif _, err := db.Select(&pips, query, workflowID); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn pips, nil\n\t\t}\n\t\treturn nil, sdk.WrapError(err, \"Unable to load pipelines linked to workflow id %d\", workflowID)\n\t}\n\n\treturn pips, nil\n}", "func (rm *resourceManager) sdkFind(\n\tctx context.Context,\n\tr *resource,\n) (*resource, error) {\n\t// If any required fields in the input shape are missing, AWS resource is\n\t// not created yet. Return NotFound here to indicate to callers that the\n\t// resource isn't yet created.\n\tif rm.requiredFieldsMissingFromReadOneInput(r) {\n\t\treturn nil, ackerr.NotFound\n\t}\n\n\tinput, err := rm.newDescribeRequestPayload(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, respErr := rm.sdkapi.GetStageWithContext(ctx, input)\n\trm.metrics.RecordAPICall(\"READ_ONE\", \"GetStage\", respErr)\n\tif respErr != nil {\n\t\tif awsErr, ok := ackerr.AWSError(respErr); ok && awsErr.Code() == \"NotFoundException\" {\n\t\t\treturn nil, ackerr.NotFound\n\t\t}\n\t\treturn nil, respErr\n\t}\n\n\t// Merge in the information we read from the API call above to the copy of\n\t// the original Kubernetes object we passed to the function\n\tko := r.ko.DeepCopy()\n\n\tif resp.AccessLogSettings != nil {\n\t\tf0 := &svcapitypes.AccessLogSettings{}\n\t\tif resp.AccessLogSettings.DestinationArn != nil {\n\t\t\tf0.DestinationARN = resp.AccessLogSettings.DestinationArn\n\t\t}\n\t\tif resp.AccessLogSettings.Format != nil {\n\t\t\tf0.Format = resp.AccessLogSettings.Format\n\t\t}\n\t\tko.Spec.AccessLogSettings = f0\n\t}\n\tif resp.ApiGatewayManaged != nil {\n\t\tko.Status.APIGatewayManaged = resp.ApiGatewayManaged\n\t}\n\tif resp.AutoDeploy != nil {\n\t\tko.Spec.AutoDeploy = resp.AutoDeploy\n\t}\n\tif resp.ClientCertificateId != nil {\n\t\tko.Spec.ClientCertificateID = resp.ClientCertificateId\n\t}\n\tif resp.CreatedDate != nil {\n\t\tko.Status.CreatedDate = &metav1.Time{*resp.CreatedDate}\n\t}\n\tif resp.DefaultRouteSettings != nil {\n\t\tf5 := &svcapitypes.RouteSettings{}\n\t\tif resp.DefaultRouteSettings.DataTraceEnabled != nil {\n\t\t\tf5.DataTraceEnabled = resp.DefaultRouteSettings.DataTraceEnabled\n\t\t}\n\t\tif resp.DefaultRouteSettings.DetailedMetricsEnabled != nil {\n\t\t\tf5.DetailedMetricsEnabled = resp.DefaultRouteSettings.DetailedMetricsEnabled\n\t\t}\n\t\tif resp.DefaultRouteSettings.LoggingLevel != nil {\n\t\t\tf5.LoggingLevel = resp.DefaultRouteSettings.LoggingLevel\n\t\t}\n\t\tif resp.DefaultRouteSettings.ThrottlingBurstLimit != nil {\n\t\t\tf5.ThrottlingBurstLimit = resp.DefaultRouteSettings.ThrottlingBurstLimit\n\t\t}\n\t\tif resp.DefaultRouteSettings.ThrottlingRateLimit != nil {\n\t\t\tf5.ThrottlingRateLimit = resp.DefaultRouteSettings.ThrottlingRateLimit\n\t\t}\n\t\tko.Spec.DefaultRouteSettings = f5\n\t}\n\tif resp.DeploymentId != nil {\n\t\tko.Spec.DeploymentID = resp.DeploymentId\n\t}\n\tif resp.Description != nil {\n\t\tko.Spec.Description = resp.Description\n\t}\n\tif resp.LastDeploymentStatusMessage != nil {\n\t\tko.Status.LastDeploymentStatusMessage = resp.LastDeploymentStatusMessage\n\t}\n\tif resp.LastUpdatedDate != nil {\n\t\tko.Status.LastUpdatedDate = &metav1.Time{*resp.LastUpdatedDate}\n\t}\n\tif resp.RouteSettings != nil {\n\t\tf10 := map[string]*svcapitypes.RouteSettings{}\n\t\tfor f10key, f10valiter := range resp.RouteSettings {\n\t\t\tf10val := &svcapitypes.RouteSettings{}\n\t\t\tif f10valiter.DataTraceEnabled != nil {\n\t\t\t\tf10val.DataTraceEnabled = f10valiter.DataTraceEnabled\n\t\t\t}\n\t\t\tif f10valiter.DetailedMetricsEnabled != nil {\n\t\t\t\tf10val.DetailedMetricsEnabled = f10valiter.DetailedMetricsEnabled\n\t\t\t}\n\t\t\tif f10valiter.LoggingLevel != nil {\n\t\t\t\tf10val.LoggingLevel = f10valiter.LoggingLevel\n\t\t\t}\n\t\t\tif f10valiter.ThrottlingBurstLimit != nil {\n\t\t\t\tf10val.ThrottlingBurstLimit = f10valiter.ThrottlingBurstLimit\n\t\t\t}\n\t\t\tif f10valiter.ThrottlingRateLimit != nil {\n\t\t\t\tf10val.ThrottlingRateLimit = f10valiter.ThrottlingRateLimit\n\t\t\t}\n\t\t\tf10[f10key] = f10val\n\t\t}\n\t\tko.Spec.RouteSettings = f10\n\t}\n\tif resp.StageName != nil {\n\t\tko.Spec.StageName = resp.StageName\n\t}\n\tif resp.StageVariables != nil {\n\t\tf12 := map[string]*string{}\n\t\tfor f12key, f12valiter := range resp.StageVariables {\n\t\t\tvar f12val string\n\t\t\tf12val = *f12valiter\n\t\t\tf12[f12key] = &f12val\n\t\t}\n\t\tko.Spec.StageVariables = f12\n\t}\n\tif resp.Tags != nil {\n\t\tf13 := map[string]*string{}\n\t\tfor f13key, f13valiter := range resp.Tags {\n\t\t\tvar f13val string\n\t\t\tf13val = *f13valiter\n\t\t\tf13[f13key] = &f13val\n\t\t}\n\t\tko.Spec.Tags = f13\n\t}\n\n\trm.setStatusDefaults(ko)\n\treturn &resource{ko}, nil\n}", "func (s *Service) GetByVisitID(ctx context.Context, visitID string) ([]types.CusVisitAssoc, error) {\n\treturn s.repo.FindByVisitID(ctx, visitID)\n}", "func GetStage() string {\n\treturn stage\n}", "func (_GameJam *GameJamCaller) Stage(opts *bind.CallOpts) (uint8, error) {\n\tvar (\n\t\tret0 = new(uint8)\n\t)\n\tout := ret0\n\terr := _GameJam.contract.Call(opts, out, \"stage\")\n\treturn *ret0, err\n}", "func (a *UtilsApiService) GetStageUsingGet(ctx context.Context, stageId string) (Stage, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Stage\n\t)\n\n\t// create path and map variables\n\ta.client = NewAPIClient(&Configuration{\n\t\tBasePath: ctx.Value(\"BasePath\").(string),\n\t\tDefaultHeader: make(map[string]string),\n\t\tUserAgent: \"Swagger-Codegen/1.0.0/go\",\n\t})\n\tlocalVarPath := a.client.cfg.BasePath + \"/nucleus/v1/stage/{stage_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"stage_id\"+\"}\", fmt.Sprintf(\"%v\", stageId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.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{\"*/*\"}\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, 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\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v Stage\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\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}" ]
[ "0.5946413", "0.5098795", "0.50590104", "0.49747327", "0.4861036", "0.48117957", "0.47268587", "0.47217435", "0.46902663", "0.4633593", "0.46109742", "0.45819175", "0.4572194", "0.45163527", "0.44331208", "0.442984", "0.4408243", "0.43807614", "0.43689042", "0.435238", "0.4326599", "0.43155822", "0.43140826", "0.43080926", "0.42862198", "0.42689058", "0.42630634", "0.4260156", "0.42402926", "0.42193282", "0.42117038", "0.41992632", "0.41889518", "0.4169656", "0.41676944", "0.41606116", "0.414338", "0.41430724", "0.41416043", "0.4128784", "0.412506", "0.41205332", "0.4111794", "0.41053948", "0.4102027", "0.410114", "0.4097766", "0.4095927", "0.40916228", "0.40846", "0.40712187", "0.4069639", "0.40690124", "0.40657973", "0.40593743", "0.40552303", "0.40537918", "0.40528578", "0.40496856", "0.40420276", "0.4037492", "0.40225694", "0.40202522", "0.40184078", "0.40159702", "0.40109473", "0.40057385", "0.4003445", "0.400262", "0.399891", "0.3995961", "0.3994278", "0.39706987", "0.39636472", "0.39607868", "0.39594093", "0.3955948", "0.39518982", "0.39430633", "0.39421517", "0.39396757", "0.39374277", "0.39217696", "0.39205635", "0.39204472", "0.3907549", "0.39072514", "0.39067933", "0.39036524", "0.38950363", "0.38924265", "0.3886581", "0.38834164", "0.38808262", "0.3877467", "0.38772234", "0.38722637", "0.38681883", "0.38680807", "0.3866408" ]
0.75475377
0
FindAll find all activity stages
func (*ActivityStageDataAccessObject) FindAll() []ActivityStage { l := make([]ActivityStage, 0) err := orm.Table(ActivityStageDAO.TableName()).Find(&l) logger.LogIfError(err) return l }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetStages(ctx context.Context) []buildapi.StageInfo {\n\tstages := fromContext(ctx)\n\treturn *stages\n}", "func (f *fileActivityFinder) FindAll() ([]domain.Activity, error) {\n\tvar activities []domain.Activity\n\n\tbyteValue, _ := ioutil.ReadAll(f.reader)\n\n\terr := json.Unmarshal(byteValue, &activities)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn activities, nil\n}", "func (p *PipelineActivity) StagesByStatus() map[ActivityStatusType][]string {\n\tstatusMap := make(map[ActivityStatusType][]string)\n\n\tfor _, stage := range p.Spec.Steps {\n\t\tif stage.Kind == ActivityStepKindTypeStage && stage.Stage != nil {\n\t\t\tif _, exists := statusMap[stage.Stage.Status]; !exists {\n\t\t\t\tstatusMap[stage.Stage.Status] = []string{}\n\t\t\t}\n\t\t\tstatusMap[stage.Stage.Status] = append(statusMap[stage.Stage.Status], stage.Stage.Name)\n\t\t}\n\t}\n\n\treturn statusMap\n}", "func (db *Db) Activities() ([]*Activity, error) {\n\tactivities := []*Activity{}\n\n\t//query := \"SELECT * FROM sport_summary ORDER BY start_time DESC;\"\n\tquery := \"SELECT sport_summary.*, Group_Concat(latitude || ',' || longitude, '|') AS points FROM sport_summary LEFT JOIN location_data ON sport_summary.track_id=location_data.track_id GROUP BY sport_summary.track_id ORDER BY location_data.timestamp ASC;\"\n\n\trows, err := db.connection.Query(query)\n\tif err != nil {\n\t\treturn activities, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tactivity := &Activity{}\n\n\t\t//err = rows.Scan(StructForScan(&activity)...)\n\t\terr = rows.Scan(&activity.Id, &activity.Type, &activity.Parent,\n\t\t\t&activity.StartTime, &activity.EndTime, &activity.Calories,\n\t\t\t&activity.CurrentStatus, &activity.ContentJSON, &activity.PointsData)\n\t\tif err != nil {\n\t\t\treturn activities, err\n\t\t}\n\n\t\tactivity.ParseContent()\n\n\t\t// Fetch activity points\n\t\tquery = \"SELECT latitude || ',' || longitude FROM location_data WHERE track_id=\" + strconv.Itoa(activity.Id) + \" ORDER BY timestamp ASC\"\n\t\tpointRows, err := db.connection.Query(query)\n\t\tif err != nil {\n\t\t\treturn activities, err\n\t\t}\n\t\tdefer pointRows.Close()\n\n\t\tpoints := []string{}\n\t\tvar point string\n\t\tfor pointRows.Next() {\n\t\t\terr = pointRows.Scan(&point)\n\t\t\tif err != nil {\n\t\t\t\tpanic(\"Couldn't parse point from database: \" + err.Error())\n\t\t\t}\n\t\t\tpoints = append(points, point)\n\t\t}\n\t\terr = pointRows.Err()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tactivity.PointsData = strings.Join(points, \"|\")\n\n\t\tactivities = append(activities, activity)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn activities, err\n\t}\n\n\treturn activities, nil\n}", "func (q activityLogQuery) All(ctx context.Context, exec boil.ContextExecutor) (ActivityLogSlice, error) {\n\tvar o []*ActivityLog\n\n\terr := q.Bind(ctx, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"dbmodel: failed to assign all query results to ActivityLog slice\")\n\t}\n\n\tif len(activityLogAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (ap *ActivePipelines) GetAll() []gaia.Pipeline {\n\tc := make([]gaia.Pipeline, 0)\n\tap.RLock()\n\tdefer ap.RUnlock()\n\tc = append(c, ap.Pipelines...)\n\treturn c\n}", "func (c *controller) FindAll() []entity.Video {\n\treturn c.service.FindAll()\n}", "func (self *WorkingTreeCommands) StageAll() error {\n\tcmdArgs := NewGitCmd(\"add\").Arg(\"-A\").ToArgv()\n\n\treturn self.cmd.New(cmdArgs).Run()\n}", "func explodeStages() ([]*stage, error) {\n\t// First, create the DAG.\n\tdag := map[string]map[string]struct{}{}\n\tfor name, d := range byName {\n\t\tm := map[string]struct{}{}\n\t\tfor _, p := range d.Prerequisites() {\n\t\t\tif _, ok := byName[p]; !ok {\n\t\t\t\treturn nil, errors.New(\"periph: unsatisfied dependency \" + strconv.Quote(name) + \"->\" + strconv.Quote(p) + \"; it is missing; skipping\")\n\t\t\t}\n\t\t\tm[p] = struct{}{}\n\t\t}\n\t\tfor _, p := range d.After() {\n\t\t\t// Skip undefined drivers silently, unlike Prerequisites().\n\t\t\tif _, ok := byName[p]; ok {\n\t\t\t\tm[p] = struct{}{}\n\t\t\t}\n\t\t}\n\t\tdag[name] = m\n\t}\n\n\t// Create stages.\n\tvar stages []*stage\n\tfor len(dag) != 0 {\n\t\ts := &stage{drvs: map[string]Driver{}}\n\t\tfor name, deps := range dag {\n\t\t\t// This driver has no dependency, add it to the current stage.\n\t\t\tif len(deps) == 0 {\n\t\t\t\ts.drvs[name] = byName[name]\n\t\t\t\tdelete(dag, name)\n\t\t\t}\n\t\t}\n\t\tif len(s.drvs) == 0 {\n\t\t\t// Print out the remaining DAG so users can diagnose.\n\t\t\t// It'd probably be nicer if it were done in Register()?\n\t\t\ts := make([]string, 0, len(dag))\n\t\t\tfor name, deps := range dag {\n\t\t\t\tx := make([]string, 0, len(deps))\n\t\t\t\tfor d := range deps {\n\t\t\t\t\tx = insertString(x, d)\n\t\t\t\t}\n\t\t\t\ts = insertString(s, name+\": \"+strings.Join(x, \", \"))\n\t\t\t}\n\t\t\treturn nil, errors.New(\"periph: found cycle(s) in drivers dependencies:\\n\" + strings.Join(s, \"\\n\"))\n\t\t}\n\t\tstages = append(stages, s)\n\n\t\t// Trim the dependencies for the items remaining in the dag.\n\t\tfor passed := range s.drvs {\n\t\t\tfor name := range dag {\n\t\t\t\tdelete(dag[name], passed)\n\t\t\t}\n\t\t}\n\t}\n\treturn stages, nil\n}", "func (c *Client) FindCrmStages(criteria *Criteria, options *Options) (*CrmStages, error) {\n\tcss := &CrmStages{}\n\tif err := c.SearchRead(CrmStageModel, criteria, options, css); err != nil {\n\t\treturn nil, err\n\t}\n\treturn css, nil\n}", "func collectTasks(entity ProjectEntity, filterLocal bool) ([]*ecs.Task, error) {\n\t// TODO, parallelize, perhaps using channels\n\tresult := []*ecs.Task{}\n\tecsTasks, err := CollectTasksWithStatus(entity, ecs.DesiredStatusRunning, filterLocal)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult = append(result, ecsTasks...)\n\n\tecsTasks, err = CollectTasksWithStatus(entity, ecs.DesiredStatusStopped, filterLocal)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult = append(result, ecsTasks...)\n\treturn result, nil\n}", "func (s lifecycleService) GetAll() ([]*Lifecycle, error) {\n\titems := []*Lifecycle{}\n\tpath, err := getAllPath(s)\n\tif err != nil {\n\t\treturn items, err\n\t}\n\n\t_, err = apiGet(s.getClient(), &items, path)\n\treturn items, err\n}", "func (hs *HistoryService) All(actionType string) ([]*TransactionHistory, error) {\n\tvar transHist []*TransactionHistory\n\tif err := hs.client.Get(buildString(\"history/\", actionType, \"/\", strconv.Itoa(hs.assetId)),\n\t\t&transHist); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn transHist, nil\n}", "func (wq *WorkflowQuery) All(ctx context.Context) ([]*Workflow, error) {\n\tif err := wq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn wq.sqlAll(ctx)\n}", "func (s *Service) GetAll(ctx context.Context) ([]types.Visit, error) {\n\treturn s.repo.FindAll(ctx)\n}", "func (p Pipeline) GetAllRunners() []Runner {\n\tres := []Runner{}\n\tres = append(res, p.localRunner.Copy())\n\treturn res\n}", "func (p Pipelines) AllSteps() []Step {\n\tresult := make([]Step, 0)\n\tfor _, pipeline := range p {\n\t\tresult = append(result, pipeline...)\n\t}\n\treturn result\n}", "func collectContainers(entity ProjectEntity, filterLocal bool) ([]composecontainer.Container, error) {\n\tecsTasks, err := collectTasks(entity, filterLocal)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn getContainersForTasks(entity, ecsTasks)\n}", "func (svc StepService) getAllSteps() []Step {\n\treturn svc.repo.getAllSteps()\n}", "func (m *TaskManager) All() []*Task {\n return m.tasks\n}", "func (s *LifecycleService) GetAll() ([]*Lifecycle, error) {\n\tpath, err := services.GetAllPath(s)\n\tif err != nil {\n\t\treturn []*Lifecycle{}, err\n\t}\n\n\tresponse, err := api.ApiGet(s.GetClient(), new([]*Lifecycle), path)\n\tif err != nil {\n\t\treturn []*Lifecycle{}, err\n\t}\n\n\titems := response.(*[]*Lifecycle)\n\treturn *items, nil\n}", "func (s *Service) GetAll(ctx context.Context) ([]types.CusVisitAssoc, error) {\n\treturn s.repo.FindAll(ctx)\n}", "func (wewq *WorkflowEventsWaitQuery) All(ctx context.Context) ([]*WorkflowEventsWait, error) {\n\tif err := wewq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn wewq.sqlAll(ctx)\n}", "func (*ActivityStageDataAccessObject) FindFullByDay(\n\tdate time.Time) []ActivityStageFull {\n\n\tstartDate := time.Date(date.Year(), date.Month(), date.Day(),\n\t\t0, 0, 0, 0, time.Local)\n\tendDate := startDate.AddDate(0, 0, 1)\n\tstart := startDate.Format(mysqlTimeFormat)\n\tend := time.Date(endDate.Year(), endDate.Month(), endDate.Day(),\n\t\t0, 0, 0, 0, time.Local).Format(mysqlTimeFormat)\n\tresult := make([]ActivityStageFull, 0)\n\n\terr := orm.Table(ActivityDAO.TableName()).\n\t\tWhere(\"activity_stages.activity_id=activities.id\").\n\t\tJoin(\"INNER\", ActivityStageDAO.TableName(),\n\t\t\"start_time>=?\", start).And(\"end_time<?\", end).\n\t\tFind(&result)\n\tlogger.LogIfError(err)\n\treturn result\n}", "func generateTimeFilterStage(rangeInitDays, rangeEndDays int) []bson.M {\n\treturn []bson.M{\n\t\tbson.M{\n\t\t\t\"$match\": bson.M{\n\t\t\t\t\"finishedAt\": bson.M{\n\t\t\t\t\t\"$gte\": util.BeginningOfTheDay(time.Now().AddDate(0, 0, rangeInitDays)),\n\t\t\t\t\t\"$lte\": util.EndOfTheDay(time.Now().AddDate(0, 0, rangeEndDays)),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func findBuildStageDurations(stepId string, builds []*cloudbuild.Build) ([]time.Duration, error) {\n\tdurations := []time.Duration{}\n\tfor _, b := range builds {\n\t\tfor _, bs := range b.Steps {\n\t\t\tif bs.Id != stepId || bs.Status != successStatus {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tparsedStartTime, err := time.Parse(time.RFC3339Nano, bs.Timing.StartTime)\n\t\t\tif err != nil {\n\t\t\t\treturn []time.Duration{}, err\n\t\t\t}\n\t\t\tparsedEndTime, err := time.Parse(time.RFC3339Nano, bs.Timing.EndTime)\n\t\t\tif err != nil {\n\t\t\t\treturn []time.Duration{}, err\n\t\t\t}\n\t\t\tdurations = append(durations, parsedEndTime.Sub(parsedStartTime).Truncate(time.Second))\n\t\t}\n\t}\n\treturn durations, nil\n}", "func (q taskQuery) All(ctx context.Context, exec boil.ContextExecutor) (TaskSlice, error) {\n\tvar o []*Task\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 Task slice\")\n\t}\n\n\tif len(taskAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (m *User) GetActivities()([]UserActivityable) {\n return m.activities\n}", "func (*ActivityStageDataAccessObject) FindByAID(aid int) []ActivityStage {\n\tl := make([]ActivityStage, 0)\n\terr := orm.Table(ActivityStageDAO.TableName()).Where(\"activity_id=?\", aid).\n\t\tFind(&l)\n\t\n\tlogger.LogIfError(err)\n\treturn l\n}", "func (q rawVisitQuery) All(ctx context.Context, exec boil.ContextExecutor) (RawVisitSlice, error) {\n\tvar o []*RawVisit\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 RawVisit slice\")\n\t}\n\n\tif len(rawVisitAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (tq *TeamQuery) All(ctx context.Context) ([]*Team, error) {\n\tctx = setContextOp(ctx, tq.ctx, \"All\")\n\tif err := tq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\tqr := querierAll[[]*Team, *TeamQuery]()\n\treturn withInterceptors[[]*Team](ctx, tq, qr, tq.inters)\n}", "func (s *MemoryStorage) FindAll() []*Task {\n\ts.RLock()\n\tdefer s.RUnlock()\n\tvar tasks []*Task\n\n\tfor _, t := range s.tasks {\n\t\ttasks = append(tasks, t)\n\t}\n\n\treturn tasks\n}", "func (r *ResourceHandler) GetAllStageResources(project string, stage string) ([]*models.Resource, error) {\n\tr.ensureHandlerIsSet()\n\treturn r.resourceHandler.GetAllStageResources(context.TODO(), project, stage, v2.ResourcesGetAllStageResourcesOptions{})\n}", "func (c *ControlPlaneProjectRetriever) GetStages(projectName string) ([]string, error) {\n\tproject, kErr := c.getProject(projectName)\n\n\tif kErr != nil {\n\t\treturn nil, fmt.Errorf(\"error getting project %s definition: %w\", projectName, kErr.ToError())\n\t}\n\n\tvar retStages []string\n\tfor _, stage := range project.Stages {\n\t\tretStages = append(retStages, stage.StageName)\n\t}\n\n\treturn retStages, nil\n}", "func ActivitiesByStatus(ctx context.Context, status int, key ...interface{}) ([]*Activity, error) {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\ttableName, err := GetActivityTableName(key...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sql query\n\tsqlstr := `SELECT ` +\n\t\t`id, name, activity_type_id, activity_type_code, content, activity_image, image_url, image_color, status, sort, extend, admin_id, admin_name, start_time, end_time, created_at, updated_at ` +\n\t\t`FROM ` + tableName +\n\t\t` WHERE status = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, status)))\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetSlaveConn()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar queryData *sql.Rows\n\tif tx != nil {\n\t\tqueryData, err = tx.Query(sqlstr, status)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tqueryData, err = dbConn.Query(sqlstr, status)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdefer queryData.Close()\n\n\t// load results\n\tres := make([]*Activity, 0)\n\tfor queryData.Next() {\n\t\ta := Activity{\n\t\t\t_exists: true,\n\t\t}\n\n\t\t// scan\n\t\terr = queryData.Scan(&a.ID, &a.Name, &a.ActivityTypeID, &a.ActivityTypeCode, &a.Content, &a.ActivityImage, &a.ImageURL, &a.ImageColor, &a.Status, &a.Sort, &a.Extend, &a.AdminID, &a.AdminName, &a.StartTime, &a.EndTime, &a.CreatedAt, &a.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres = append(res, &a)\n\t}\n\n\treturn res, nil\n}", "func loadStages(file *os.File, stages []buildStage) ([]buildStage, error) {\n\tvar stage *buildStage\n\tscanner := bufio.NewScanner(file)\n\tfor i := 1; scanner.Scan(); i++ {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tswitch line {\n\t\tcase \"[include]\":\n\t\t\tstages = append(stages, buildStage{\n\t\t\t\tinclude: true,\n\t\t\t\tsource: file.Name(),\n\t\t\t})\n\t\t\tstage = &stages[len(stages)-1]\n\t\tcase \"[exclude]\":\n\t\t\tstages = append(stages, buildStage{\n\t\t\t\tinclude: false,\n\t\t\t\tsource: file.Name(),\n\t\t\t})\n\t\t\tstage = &stages[len(stages)-1]\n\t\tcase \"\": // don't add empty lines\n\t\tdefault:\n\t\t\tif stage == nil {\n\t\t\t\t// if we haven't reached an [include] or [exclude] header\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tstage.rules = append(stage.rules, buildRule{glob: line, line: i})\n\t\t}\n\t}\n\treturn stages, nil\n}", "func getAllTask() []primitive.M {\n\tcur, err := collection.Find(context.Background(), bson.D{{}})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar results []primitive.M\n\tfor cur.Next(context.Background()) {\n\t\tvar result bson.M\n\t\te := cur.Decode(&result)\n\t\tif e != nil {\n\t\t\tlog.Fatal(e)\n\t\t}\n\t\tresults = append(results, result)\n\t}\n\tif err := cur.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcur.Close(context.Background())\n\treturn results\n}", "func getAllTask() []primitive.M {\n\tcur, err := collection.Find(context.Background(), bson.D{{}})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar results []primitive.M\n\tfor cur.Next(context.Background()) {\n\t\tvar result bson.M\n\t\terr := cur.Decode(&result)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tresults = append(results, result)\n\t}\n\tif err := cur.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcur.Close(context.Background())\n\treturn results\n}", "func getAllTask() []primitive.M {\n\tcur, err := collection.Find(context.Background(), bson.D{{}})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar results []primitive.M\n\tfor cur.Next(context.Background()) {\n\t\tvar result bson.M\n\t\te := cur.Decode(&result)\n\t\tif e != nil {\n\t\t\tlog.Fatal(e)\n\t\t}\n\t\t// fmt.Println(\"cur..>\", cur, \"result\", reflect.TypeOf(result), reflect.TypeOf(result[\"_id\"]))\n\t\tresults = append(results, result)\n\n\t}\n\n\tif err := cur.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcur.Close(context.Background())\n\treturn results\n}", "func getAllTask() []primitive.M {\n\tcur, err := collection.Find(context.Background(), bson.D{{}})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar results []primitive.M\n\tfor cur.Next(context.Background()) {\n\t\tvar result bson.M\n\t\te := cur.Decode(&result)\n\t\tif e != nil {\n\t\t\tlog.Fatal(e)\n\t\t}\n\t\t// fmt.Println(\"cur..>\", cur, \"result\", reflect.TypeOf(result), reflect.TypeOf(result[\"_id\"]))\n\t\tresults = append(results, result)\n\n\t}\n\n\tif err := cur.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcur.Close(context.Background())\n\treturn results\n}", "func All() []model.Project {\n projects := []model.Project{}\n\n // Find Projects and eager-load ProjectConfig.\n app.DB.\n Preload(\"ProjectConfig\").\n Order(\"nsp desc\").\n Find(&projects)\n\n return projects\n}", "func (database *Database) ListActivities(activities *[]Activity, organizationID int, status string) error {\n\tnow := time.Now().UTC().Format(time.UnixDate)\n\n\tfilteredActivities := database.DB\n\tswitch status {\n\tcase \"open\":\n\t\tfilteredActivities = database.DB.Where(\"closed_at > ?\", now)\n\tcase \"closed\":\n\t\tfilteredActivities = database.DB.Where(\"closed_at <= ?\", now)\n\t}\n\n\terr := filteredActivities.Order(\"closed_at asc\").\n\t\tPreload(\"OrderItems\").\n\t\tPreload(\"Restaurants\").\n\t\tPreload(\"Restaurants.Menus\").\n\t\tWhere(&Activity{OrganizationID: organizationID}).\n\t\tFind(activities).Error\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to select all activites: %s\", err)\n\t}\n\n\treturn nil\n}", "func (*ActivityStageDataAccessObject) FindFullByMonth(\n\tdate time.Time) [][]ActivityStageFull {\n\n\tstart := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.Local)\n\tend := start.AddDate(0, 1, 0).AddDate(0, 0, -1)\n\tresult := make([][]ActivityStageFull, 0)\n\tfor i := start.Day(); i <= end.Day(); i++ {\n\t\tcurDate := time.Date(date.Year(), date.Month(), i, 0, 0, 0, 0,\n\t\t\ttime.Local)\n\t\tresult = append(result, ActivityStageDAO.FindFullByDay(curDate))\n\t}\n\n\treturn result\n}", "func (p *PlanetHandler) FindAll(c *fiber.Ctx) error {\n\tplnts, err := p.PUsecase.FindAll()\n\n\tif err != nil {\n\t\treturn c.Status(getStatusCode(err)).JSON(ResponseError{Message: err.Error()})\n\t}\n\n\tfor _, plnt := range plnts {\n\t\tswapi_plnt, errl := p.SWapi.GetPlanetByName(plnt.Name)\n\t\tif errl != nil {\n\t\t\treturn c.Status(getStatusCode(err)).JSON(ResponseError{Message: err.Error()})\n\t\t}\n\t\tplnt.Appearances = len(swapi_plnt.Films)\n\t}\n\n\treturn c.Status(fiber.StatusOK).JSON(&plnts)\n}", "func Find(agent Agent, worldState StateList, goalState StateList) []Action {\n\t// we cannot plan without any goals\n\tif len(goalState) == 0 {\n\t\tpanic(\"cannot plan without a goal\")\n\t}\n\n\tvar result []Action\n\n\t// check what actions can run\n\tvar usableActions []Action\n\tfor _, action := range agent.AvailableActions() {\n\t\taction.Reset()\n\t\tusableActions = append(usableActions, action)\n\t}\n\n\t// early out, this agent doesn't have any actions\n\tif len(usableActions) == 0 {\n\t\treturn result\n\t}\n\n\tvar plans []*node\n\tif !buildGraph(&node{state: worldState}, &plans, usableActions, goalState, agent) {\n\t\treturn result\n\t}\n\n\t// get the cheapest plan\n\tcheapest := plans[0]\n\tfor i := 1; i < len(plans); i++ {\n\t\tif plans[i].runningCost < cheapest.runningCost {\n\t\t\tcheapest = plans[i]\n\t\t}\n\t}\n\n\t// invert the list so that we get the end action at the end of the result list\n\tfor n := cheapest; n != nil && n.action != nil; n = n.parent {\n\t\tresult = append([]Action{n.action}, result...)\n\t}\n\treturn result\n}", "func (t *Cases) FindAll() []models.Case {\n\tvar cases []models.Case\n\n\tquery := func(db *gorm.DB) {\n\t\tdb.Find(&cases)\n\t}\n\n\terror := t.context.Execute(query)\n\n\tif error != nil {\n\t\treturn nil\n\t}\n\n\treturn cases\n}", "func (db *Service) FindAll(\n\tsc datatype.ServiceContainer,\n\tuser *datatype.User,\n\ttimelineFilter datatype.TimelineFilter,\n\toffset int,\n\tlimit int,\n) ([]datatype.TimelineEntry, bool, error) {\n\tresult := []datatype.TimelineEntry{}\n\tvar clause string\n\tif timelineFilter.Type == datatype.HOMETIMELINE {\n\t\tclause = \"WHERE b.status=1\"\n\t} else if timelineFilter.Type == datatype.ASSETTIMELINE {\n\t\tclause = fmt.Sprintf(\n\t\t\t\" WHERE b.status<>%d AND asset.id = %d\",\n\t\t\tdatatype.BlockRejected,\n\t\t\ttimelineFilter.AssetID,\n\t\t)\n\t} else if timelineFilter.Type == datatype.USERTIMELINE {\n\t\tclause = fmt.Sprintf(\n\t\t\t\" WHERE b.status<>%d AND (doer.id = %d OR oracle.id = %d)\",\n\t\t\tdatatype.BlockRejected,\n\t\t\ttimelineFilter.UserID,\n\t\t\ttimelineFilter.UserID,\n\t\t)\n\t}\n\trows, err := db.Query(fmt.Sprintf(`\n\t\t\tSELECT\n\t\t\t\tb.id,\n\t\t\t\tb.userId,\n\t\t\t\tdoer.username,\n\t\t\t\tdoer.profileImageUrl,\n\t\t\t\tasset.id,\n\t\t\t\tasset.name,\n\t\t\t\tasset.symbol,\n\t\t\t\toracle.id,\n\t\t\t\toracle.username,\n\t\t\t\tb.text,\n\t\t\t\tb.status,\n\t\t\t\tb.ethereumTransactionAddress,\n\t\t\t\tb.videoID,\n\t\t\t\tb.favoritesCounter,\n\t\t\t\tb.createdAt,\n\t\t\t\tIF(favorites.blockId, TRUE, FALSE),\n\t\t\t\tIF(asset_favorites.assetId, TRUE, FALSE) as following\n\t\t\tFROM asset_block b\n\t\t\tLEFT JOIN asset asset ON b.assetId=asset.Id\n\t\t\tLEFT JOIN user doer ON doer.id=b.userId\n\t\t\tLEFT JOIN user oracle ON oracle.id=asset.creatorId\n\t\t\tLEFT JOIN asset_block_favorites favorites ON b.id=favorites.blockId AND favorites.userId=?\n\t\t\tLEFT JOIN asset_favorites ON asset.id=asset_favorites.assetId AND asset_favorites.userId=?\n\t\t\t%s\n\t\t\tORDER BY b.createdAt DESC\n\t\t\tLIMIT ? OFFSET ?\n\t\t\t`, clause), user.ID, user.ID, limit+1, offset)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar c datatype.TimelineEntry\n\t\terr := rows.Scan(\n\t\t\t&c.BlockID,\n\t\t\t&c.UserID,\n\t\t\t&c.UserName,\n\t\t\t&c.UserProfileImageURL,\n\t\t\t&c.AssetID,\n\t\t\t&c.AssetName,\n\t\t\t&c.AssetSymbol,\n\t\t\t&c.OracleID,\n\t\t\t&c.OracleName,\n\t\t\t&c.Text,\n\t\t\t&c.Status,\n\t\t\t&c.EthereumTransactionAddress,\n\t\t\t&c.YtVideoID,\n\t\t\t&c.FavoritesCount,\n\t\t\t&c.CreatedAt,\n\t\t\t&c.DidUserLike,\n\t\t\t&c.DidUserLikeTopic,\n\t\t)\n\t\tif timelineFilter.Type == datatype.HOMETIMELINE && c.DidUserLikeTopic == false {\n\t\t\tcontinue\n\t\t}\n\t\tc.CreatedAtHuman = helpers.DateToHuman(c.CreatedAt)\n\t\tif err != nil {\n\t\t\tapperrors.Critical(\"timelineservice:find-all:1\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\t// TODO optimize fetching images, bring all images for all at once,\n\t\t// not query for each entry\n\t\tc.Images, err = sc.AssetService.GetAssetBlockImages(c.BlockID)\n\t\tif err != nil {\n\t\t\tapperrors.Critical(\"timelineservice:find-all:2\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\tc.Reactions, err = db.FindClaimReactions(c.BlockID)\n\t\tif err != nil {\n\t\t\tapperrors.Critical(\"timelineservice:find-all:3\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\tresult = append(result, c)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, false, err\n\t}\n\thasMore := len(result) == limit+1\n\tif hasMore {\n\t\tresult = result[:len(result)-1]\n\t}\n\treturn result, hasMore, nil\n}", "func Ls(tasks []*task.Task, q query.Query) []*ShowTask {\n\treturn filterRoot(tasks, q)\n}", "func (o JobOutput) StageStates() ExecutionStageStateResponseArrayOutput {\n\treturn o.ApplyT(func(v *Job) ExecutionStageStateResponseArrayOutput { return v.StageStates }).(ExecutionStageStateResponseArrayOutput)\n}", "func (q cmfUserExperienceLogQuery) All(ctx context.Context, exec boil.ContextExecutor) (CMFUserExperienceLogSlice, error) {\n\tvar o []*CMFUserExperienceLog\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 CMFUserExperienceLog slice\")\n\t}\n\n\tif len(cmfUserExperienceLogAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (h *Hub) AllRuns(id string) (pending Runs, active Runs, archive Runs) {\n\treturn h.runs.allRuns(id)\n}", "func (o *operator) InitStagesStatus() {\n\tif o.wfr.Status.Stages == nil {\n\t\to.wfr.Status.Stages = make(map[string]*v1alpha1.StageStatus)\n\t}\n\n\tfor _, stg := range o.wf.Spec.Stages {\n\t\tif _, ok := o.wfr.Status.Stages[stg.Name]; !ok {\n\t\t\to.wfr.Status.Stages[stg.Name] = &v1alpha1.StageStatus{\n\t\t\t\tStatus: v1alpha1.Status{\n\t\t\t\t\tPhase: v1alpha1.StatusPending,\n\t\t\t\t},\n\t\t\t\tDepends: stg.Depends,\n\t\t\t\tTrivial: stg.Trivial,\n\t\t\t}\n\t\t}\n\t}\n}", "func (ew *Eyewitness) Investigate(status whodunit.AssetStatus) {\n\ttotalCount := 0\n\ttable := whodunit.NewStatusTable(whodunit.AssetTypeRecognition, status)\n\tjep := ew.jobEpisodeMap()\n\tfor season := 1; season <= whodunit.SeasonCount; season++ {\n\t\ts := whodunit.NewSeason(season)\n\t\tif err := s.PopulateEpisodes(); err != nil {\n\t\t\tpanic(\"Could not get season episodes\")\n\t\t}\n\n\t\tfor _, ep := range s.AllEpisodes() {\n\t\t\tje := jep[ep.Name()]\n\t\t\tif je != nil {\n\t\t\t\tep.SetAssetStatus(je.AssetStatus(whodunit.AssetTypeRecognition))\n\t\t\t}\n\n\t\t\tif table.AddRow(ep) {\n\t\t\t\ttotalCount++\n\t\t\t}\n\t\t}\n\t}\n\n\ttable.RenderTable(totalCount)\n}", "func (rc *RenderCore) GetAll() []*RenderTask {\n\treturn rc.queue\n}", "func (o DeliveryPipelineSerialPipelineOutput) Stages() DeliveryPipelineSerialPipelineStageArrayOutput {\n\treturn o.ApplyT(func(v DeliveryPipelineSerialPipeline) []DeliveryPipelineSerialPipelineStage { return v.Stages }).(DeliveryPipelineSerialPipelineStageArrayOutput)\n}", "func CollectTasksWithStatus(entity ProjectEntity, status string, filterLocal bool) ([]*ecs.Task, error) {\n\trequest := constructListPagesRequest(entity, status, filterLocal)\n\tresult := []*ecs.Task{}\n\n\terr := entity.Context().ECSClient.GetTasksPages(request, func(respTasks []*ecs.Task) error {\n\t\tresult = append(result, respTasks...)\n\t\treturn nil\n\t})\n\n\treturn result, err\n}", "func Convert(pipelineStates []PipelineState) []Project {\n\tprojects := make([]Project, 0)\n\n\tfor _, pipeline := range pipelineStates {\n\t\tfor _, stage := range pipeline.StageStates {\n\t\t\tprojects = append(projects,\n\t\t\t\tProject{\n\t\t\t\t\tName: buildName(pipeline.Name, stage),\n\t\t\t\t\tLastBuildStatus: buildLastBuildStatus(stage),\n\t\t\t\t\tActivity: buildActivity(stage),\n\t\t\t\t\tLastBuildTime: buildLastBuildTime(pipeline.Created, stage),\n\t\t\t\t})\n\t\t}\n\t}\n\n\treturn projects\n}", "func (irq *InstanceRuntimeQuery) All(ctx context.Context) ([]*InstanceRuntime, error) {\n\tif err := irq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn irq.sqlAll(ctx)\n}", "func (c Cache) Stages() Path {\n\treturn c.Join(\"stages\")\n}", "func GetAllAnalyzeJobs() []*AnalyzeJob {\n\tanalyzeStatus.Lock()\n\tjobs := make([]*AnalyzeJob, 0, len(analyzeStatus.jobs)+len(analyzeStatus.history))\n\tfor job := range analyzeStatus.jobs {\n\t\tjobs = append(jobs, job)\n\t}\n\tjobs = append(jobs, analyzeStatus.history...)\n\tanalyzeStatus.Unlock()\n\tsort.Slice(jobs, func(i int, j int) bool { return jobs[i].updateTime.Before(jobs[j].updateTime) })\n\treturn jobs\n}", "func (q segmentQuery) All(ctx context.Context, exec boil.ContextExecutor) (SegmentSlice, error) {\n\tvar o []*Segment\n\n\terr := q.Bind(ctx, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"boiler: failed to assign all query results to Segment slice\")\n\t}\n\n\tif len(segmentAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func GetAllExecutions(count int, start int) ([]V_testlink_testexecution_tree, error) {\n\tvar rs []V_testlink_testexecution_tree\n\terr := orm.Limit(count, start).Find(&rs)\n\treturn rs, err\n}", "func (ss *StoreService) All(ctx context.Context, in *todo.AllTasksParams, out *todo.TaskList) error {\n\tvar tasks []todo.TaskDefinition\n\treturn ss.Store.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"todoStore\"))\n\t\ttasks = make([]todo.TaskDefinition, 0, b.Stats().KeyN)\n\t\treturn b.ForEach(func(_, taskData []byte) error {\n\t\t\tvar task *todo.TaskDefinition = &todo.TaskDefinition{}\n\t\t\tif err := json.Unmarshal(taskData, task); err != nil {\n\t\t\t\tss.log.Errorf(\"Error unmarshaling for all tasks: \\n%s\\n\\n%#v\", err.Error(), b.Stats())\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttasks = append(tasks, *task)\n\t\t\treturn nil\n\t\t})\n\t})\n}", "func AllAMVs() []*AMV {\n\tall := make([]*AMV, 0, DB.Collection(\"AMV\").Count())\n\n\tstream := StreamAMVs()\n\n\tfor obj := range stream {\n\t\tall = append(all, obj)\n\t}\n\n\treturn all\n}", "func (p *PipelineDefinition) Pipelines() (*Pipelines, error) {\n\tif p.pipelines == nil {\n\t\t// Collect ignored and selected step names\n\t\tignoredSteps := types.StringSet{}\n\t\tselectedSteps := types.StringSet{}\n\t\tfor name, step := range p.Steps {\n\t\t\tif step.Meta.Ignore {\n\t\t\t\tignoredSteps[name] = true\n\t\t\t}\n\t\t\tif step.Meta.Selected {\n\t\t\t\tselectedSteps[name] = true\n\t\t\t\tif step.Meta.Ignore {\n\t\t\t\t\treturn nil, fmt.Errorf(\"instructed to ignore selected step '%s'\", step.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// If steps or services are marked es selected, expand the selection\n\t\tqueue := make([]string, 0)\n\t\tfor name := range selectedSteps {\n\t\t\tqueue = append(queue, name)\n\t\t}\n\t\tfor len(queue) > 0 {\n\t\t\tname := queue[0]\n\t\t\tqueue = queue[1:]\n\t\t\tif s, ok := p.Steps[name]; ok {\n\t\t\t\tif s.Meta.Ignore {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor dep := range s.Dependencies() {\n\t\t\t\t\tqueue = append(queue, dep)\n\t\t\t\t}\n\t\t\t\tif s.Meta.Selected {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ts.Meta.Selected = true\n\t\t\t\tselectedSteps[name] = true\n\t\t\t\tp.Steps[name] = s\n\t\t\t}\n\t\t}\n\t\tif len(selectedSteps) > 0 {\n\t\t\t// Ignore all not selected steps\n\t\t\tfor name, step := range p.Steps {\n\t\t\t\tif step.Meta.Selected {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tstep.Meta.Ignore = true\n\t\t\t\tp.Steps[name] = step\n\t\t\t\tignoredSteps[name] = true\n\t\t\t}\n\t\t}\n\n\t\t// Build list of active steps\n\t\tsteps := make(map[string]Step)\n\t\tfor name, step := range p.Steps {\n\t\t\tsteps[name] = step\n\t\t}\n\t\t// Calculate order and indepenence\n\t\tpipelines, err := NewTarjan(steps)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Verify pipelines\n\t\terr = pipelines.Check()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tp.pipelines = pipelines\n\t}\n\treturn p.pipelines, nil\n}", "func (g *Group) FindAll(db *gorm.DB) (*gorm.DB, []Group) {\r\n\tgroupList := []Group{}\r\n\tresult := db.Debug().Find(&groupList)\r\n\treturn result, groupList\r\n}", "func (s *Stage) ReadAll() []string {\n\tmsgs := make([]string, len(s.actors))\n\n\tfor i, a := range s.actors {\n\t\tmsgs[i] = strings.TrimSuffix(a.Read(), \"\\n\")\n\t}\n\n\treturn msgs\n}", "func List(ctx context.Context) (err error) {\n\tif t.Status == constants.TaskStatusCreated {\n\t\t_, err = model.CreateJob(ctx, \"/\")\n\t\tif err != nil {\n\t\t\tlogrus.Panic(err)\n\t\t}\n\n\t\tt.Status = constants.TaskStatusRunning\n\t\terr = t.Save(ctx)\n\t\tif err != nil {\n\t\t\tlogrus.Panic(err)\n\t\t}\n\t}\n\n\t// Traverse already running but not finished object.\n\tp := \"\"\n\tfor {\n\t\to, err := model.NextObject(ctx, p)\n\t\tif err != nil {\n\t\t\tlogrus.Panic(err)\n\t\t}\n\t\tif o == nil {\n\t\t\tbreak\n\t\t}\n\n\t\toc <- o\n\t\tp = o.Key\n\t}\n\n\t// Traverse already running but not finished job.\n\tp = \"\"\n\tfor {\n\t\tj, err := model.NextJob(ctx, p)\n\t\tif err != nil {\n\t\t\tlogrus.Panic(err)\n\t\t}\n\t\tif j == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tjwg.Add(1)\n\t\tjc <- j\n\t\tp = j.Path\n\t}\n\n\treturn\n}", "func GetState(w http.ResponseWriter, r *http.Request) {\n\n\tvar moduleRequest moduleRequest\n\treqBody, _ := ioutil.ReadAll(r.Body)\n\tjson.Unmarshal(reqBody, &moduleRequest)\n\n\tmoduleName := strings.Join(strings.Split(moduleRequest.ModuleName, \" \"), \"/\")\n\tcommandCenter := command.New(getFlags(r.URL.Query())).ReturnStateForDir(moduleName)\n\tstateMap := commandCenter.ReturnStateMap\n\n\tregexFile := regexp.MustCompile(\"([0-9]+-)\")\n\tregexDir := regexp.MustCompile(\"([a-zA-Z0-9/]+/[0-9-]*)\")\n\tstateJSON := stateJSON{}\n\tstepInstance := step{}\n\tstepList := []step{}\n\tvar stateOfExecution string\n\n\tvar sortedDirkeys []string\n\tfor key := range stateMap {\n\t\tsortedDirkeys = append(sortedDirkeys, key)\n\t}\n\tsort.Strings(sortedDirkeys)\n\n\tfor _, dir := range sortedDirkeys {\n\t\tstepInstance.Module = regexDir.ReplaceAllString(dir, \"\")\n\t\ttaskInstance := task{}\n\t\ttaskList := []task{}\n\n\t\tmapDir := stateMap[dir]\n\t\tvar sortedFileKeys []string\n\t\tfor key := range mapDir {\n\t\t\tsortedFileKeys = append(sortedFileKeys, key)\n\t\t}\n\t\tsort.Strings(sortedFileKeys)\n\n\t\tfor _, file := range sortedFileKeys {\n\t\t\ttaskInstance.TaskName = regexFile.ReplaceAllString(strings.TrimSuffix(file, \".sh\"), \"\")\n\t\t\ttaskInstance.FileExecStatus = mapDir[file]\n\t\t\tif taskInstance.FileExecStatus.State == \"running\" { //update running time\n\t\t\t\ttaskInstance.FileExecStatus.TimeTaken = time.Since(taskInstance.FileExecStatus.StartTime).String()\n\t\t\t}\n\t\t\tif taskInstance.FileExecStatus.State != \"\" {\n\t\t\t\tstateOfExecution = string(taskInstance.FileExecStatus.State)\n\t\t\t}\n\t\t\ttaskList = append(taskList, taskInstance)\n\t\t}\n\t\tstepInstance.Tasks = taskList\n\t\tstepList = append(stepList, stepInstance)\n\t}\n\tstateJSON.Steps = stepList\n\tstateJSON.State = stateOfExecution\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(stateJSON)\n}", "func (q assetQuery) All() (AssetSlice, error) {\n\tvar o AssetSlice\n\n\terr := q.Bind(&o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to Asset slice\")\n\t}\n\n\tif len(assetAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(queries.GetExecutor(q.Query)); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func stageNewRuns(ctx context.Context, c *prjpb.Component, cls map[int64]*clInfo, pm pmState) ([]*runcreator.Creator, time.Time, error) {\n\tvar next time.Time\n\tvar out []*runcreator.Creator\n\n\trs := runStage{\n\t\tpm: pm,\n\t\tc: c,\n\t\tcls: cls,\n\t\tvisitedCLs: make(map[int64]struct{}, len(cls)),\n\t}\n\t// For determinism, iterate in fixed order:\n\tfor _, clid := range c.GetClids() {\n\t\tinfo := cls[clid]\n\t\tswitch rcs, nt, err := rs.stageNewRunsFrom(ctx, clid, info); {\n\t\tcase err != nil:\n\t\t\treturn nil, time.Time{}, err\n\t\tcase len(rcs) != 0:\n\t\t\tout = append(out, rcs...)\n\t\tdefault:\n\t\t\tnext = earliest(next, nt)\n\t\t}\n\t}\n\treturn out, next, nil\n}", "func (db *Tool) All() ([]Tool, error) {\n\ttools, err := db.fetchTools()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn tools, nil\n}", "func (ac *Activity) getTasksInfo(ctx context.Context) (tasks []taskInfo, err error) {\n\t// TODO(ricardoq): parse the dumpsys protobuf output instead.\n\t// As it is now, it gets complex and error-prone to parse each ActivityRecord.\n\tcmd := ac.a.Command(ctx, \"dumpsys\", \"activity\", \"activities\")\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not get 'dumpsys activity activities' output\")\n\t}\n\toutput := string(out)\n\t// Looking for:\n\t// Stack #2: type=standard mode=freeform\n\t// isSleeping=false\n\t// mBounds=Rect(0, 0 - 0, 0)\n\t// Task id #5\n\t// mBounds=Rect(1139, 359 - 1860, 1640)\n\t// mMinWidth=-1\n\t// mMinHeight=-1\n\t// mLastNonFullscreenBounds=Rect(1139, 359 - 1860, 1640)\n\t// * TaskRecordArc{TaskRecordArc{TaskRecord{54ef88b #5 A=com.android.settings.root U=0 StackId=2 sz=1}, WindowState{freeform restore-bounds=Rect(1139, 359 - 1860, 1640)}} , WindowState{freeform restore-bounds=Rect(1139, 359 - 1860, 1640)}}\n\t// \tuserId=0 effectiveUid=1000 mCallingUid=1000 mUserSetupComplete=true mCallingPackage=org.chromium.arc.applauncher\n\t// \taffinity=com.android.settings.root\n\t// \tintent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10210000 cmp=com.android.settings/.Settings}\n\t// \torigActivity=com.android.settings/.Settings\n\t// \trealActivity=com.android.settings/.Settings\n\t// \tautoRemoveRecents=false isPersistable=true numFullscreen=1 activityType=1\n\t// \trootWasReset=true mNeverRelinquishIdentity=true mReuseTask=false mLockTaskAuth=LOCK_TASK_AUTH_PINNABLE\n\t// \tActivities=[ActivityRecord{64b5e83 u0 com.android.settings/.Settings t5}]\n\t// \taskedCompatMode=false inRecents=true isAvailable=true\n\t// \tmRootProcess=ProcessRecord{8dc5d68 5809:com.android.settings/1000}\n\t// \tstackId=2\n\t// \thasBeenVisible=true mResizeMode=RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION mSupportsPictureInPicture=false isResizeable=true lastActiveTime=1470240 (inactive for 4s)\n\t// \tArc Window State:\n\t// \tmWindowMode=5 mRestoreBounds=Rect(1139, 359 - 1860, 1640) taskWindowState=0\n\t// * Hist #2: ActivityRecord{2f9c16c u0 com.android.settings/.SubSettings t8}\n\t// packageName=com.android.settings processName=com.android.settings\n\t// [...] Abbreviated to save space\n\t// state=RESUMED stopped=false delayedResume=false finishing=false\n\t// keysPaused=false inHistory=true visible=true sleeping=false idle=true mStartingWindowState=STARTING_WINDOW_NOT_SHOWN\n\tregStr := `(?m)` + // Enable multiline.\n\t\t`^\\s+Task id #(\\d+)` + // Grab task id (group 1).\n\t\t`\\s+mBounds=Rect\\((-?\\d+),\\s*(-?\\d+)\\s*-\\s*(\\d+),\\s*(\\d+)\\)` + // Grab bounds (groups 2-5).\n\t\t`(?:\\n.*?)*` + // Non-greedy skip lines.\n\t\t`.*TaskRecord{.*StackId=(\\d+)\\s+sz=(\\d*)}.*$` + // Grab stack Id (group 6) and stack size (group 7).\n\t\t`(?:\\n.*?)*` + // Non-greedy skip lines.\n\t\t`\\s+realActivity=(.*)\\/(.*)` + // Grab package name (group 8) and activity name (group 9).\n\t\t`(?:\\n.*?)*` + // Non-greedy skip lines.\n\t\t`.*\\s+isResizeable=(\\S+).*$` + // Grab window resizeablitiy (group 10).\n\t\t`(?:\\n.*?)*` + // Non-greedy skip lines.\n\t\t`\\s+mWindowMode=\\d+.*taskWindowState=(\\d+).*$` + // Grab window state (group 11).\n\t\t`(?:\\n.*?)*` + // Non-greedy skip lines.\n\t\t`\\s+ActivityRecord{.*` + // At least one ActivityRecord must be present.\n\t\t`(?:\\n.*?)*` + // Non-greedy skip lines.\n\t\t`.*\\s+idle=(\\S+)` // Idle state (group 12).\n\tre := regexp.MustCompile(regStr)\n\tmatches := re.FindAllStringSubmatch(string(output), -1)\n\t// At least it must match one activity. Home and/or Dummy activities must be present.\n\tif len(matches) == 0 {\n\t\ttesting.ContextLog(ctx, \"Using regexp: \", regStr)\n\t\ttesting.ContextLog(ctx, \"Output for regexp: \", string(output))\n\t\treturn nil, errors.New(\"could not match any activity; regexp outdated perhaps?\")\n\t}\n\tfor _, groups := range matches {\n\t\tvar t taskInfo\n\t\tvar windowState int\n\t\tt.bounds, err = parseBounds(groups[2:6])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, dst := range []struct {\n\t\t\tv *int\n\t\t\tgroup int\n\t\t}{\n\t\t\t{&t.id, 1},\n\t\t\t{&t.stackID, 6},\n\t\t\t{&t.stackSize, 7},\n\t\t\t{&windowState, 11},\n\t\t} {\n\t\t\t*dst.v, err = strconv.Atoi(groups[dst.group])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"could not parse %q\", groups[dst.group])\n\t\t\t}\n\t\t}\n\t\tt.pkgName = groups[8]\n\t\tt.activityName = groups[9]\n\t\tt.resizable, err = strconv.ParseBool(groups[10])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tt.idle, err = strconv.ParseBool(groups[12])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tt.windowState = WindowState(windowState)\n\t\ttasks = append(tasks, t)\n\t}\n\treturn tasks, nil\n}", "func extract_schedules(hull []fpoint) []vrp.Schedule {\n\tschedules := make([]vrp.Schedule, len(hull))\n\tfor i, h := range hull {\n\t\tschedules[i] = h.schedule\n\t}\n\treturn schedules\n}", "func (w *WorkflowInstances) LoadAll(opt *db.Options) error {\n\tif err := db.SelectStruct(constants.TableCoreBPMInstances, w, opt); err != nil {\n\t\treturn customerror.New(http.StatusInternalServerError, \"workflow instances load\", err.Error())\n\t}\n\treturn nil\n}", "func (_obj *DataService) GetActivityRecords(index int32, batch int32, activity_id string, nextIndex *int32, recordList *[]ActivityRecord, _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_int32(index, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(batch, 2)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_string(activity_id, 3)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*nextIndex), 4)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.WriteHead(codec.LIST, 5)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(int32(len((*recordList))), 0)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tfor _, v := range *recordList {\n\n\t\terr = v.WriteBlock(_os, 0)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\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, \"getActivityRecords\", _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(&(*nextIndex), 4, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr, have, ty = _is.SkipToNoCheck(5, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif ty == codec.LIST {\n\t\terr = _is.Read_int32(&length, 0, true)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t\t(*recordList) = make([]ActivityRecord, length)\n\t\tfor i20, e20 := int32(0), length; i20 < e20; i20++ {\n\n\t\t\terr = (*recordList)[i20].ReadBlock(_is, 0, false)\n\t\t\tif err != nil {\n\t\t\t\treturn ret, err\n\t\t\t}\n\n\t\t}\n\t} else if ty == codec.SIMPLE_LIST {\n\t\terr = fmt.Errorf(\"not support simple_list type\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t} else {\n\t\terr = fmt.Errorf(\"require vector, but not\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\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 (bc *BlueprintController) GetAllBlueprint(bi usecase.BlueprintInteractor) func(*gin.Context) {\n\treturn func(c *gin.Context) {\n\t\tkey := \"j9uzyqp6cyzq\"\n\t\tsecret := \"5y485r8nq9jre4fk6anpu59sqdcpq8xdkuqbd5jxqpvw455gek3aw27ysx4uq7tz\"\n\n\t\tclient, _ := stream.NewClient(key, secret)\n\n\t\tnotifFeed := client.NotificationFeed(\"agency\", \"125\")\n\n\t\tresp, _ := notifFeed.GetActivities()\n\n\t\tvar activities []stream.Activity\n\n\t\tfor _, res := range resp.Results {\n\t\t\tfor _, activity := range res.Activities {\n\t\t\t\tactivities = append(activities, activity)\n\t\t\t}\n\t\t}\n\n\t\tc.JSON(http.StatusOK, activities)\n\t}\n}", "func (service *Service) All() (models []ModelOperationsLog, err error) {\n\trows, err := service.pool.Query(context.Background(), `SELECT id, name, number,recipientSender,count, balanceold, balancenew, time, owner_id FROM historyoperationslog;`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't get sys-test-history from db: %w\", err)\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tmodel := ModelOperationsLog{}\n\t\terr = rows.Scan(\n\t\t\t&model.Id,\n\t\t\t&model.Name,\n\t\t\t&model.Number,\n\t\t\t&model.RecipientSender,\n\t\t\t&model.Count,\n\t\t\t&model.BalanceOld,\n\t\t\t&model.BalanceNew,\n\t\t\t&model.Time,\n\t\t\t&model.OwnerID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"can't get sys-test-history from db: %w\", err)\n\t\t}\n\t\tmodels = append(models, model)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't get sys-test-history from db: %w\", err)\n\t}\n\treturn models, nil\n}", "func XPipelineSalesStagesBySalesMethodID(db XODB, salesMethodID uint) ([]*XPipelineSalesStage, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, name, probability, seq_num, active_flag, sales_method_id, created_by, updated_by, created_at, updated_at ` +\n\t\t`FROM x_showroom.x_pipeline_sales_stages ` +\n\t\t`WHERE sales_method_id = ?`\n\n\t// run query\n\tXOLog(sqlstr, salesMethodID)\n\tq, err := db.Query(sqlstr, salesMethodID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer q.Close()\n\n\t// load results\n\tres := []*XPipelineSalesStage{}\n\tfor q.Next() {\n\t\txpss := XPipelineSalesStage{\n\t\t\t_exists: true,\n\t\t}\n\n\t\t// scan\n\t\terr = q.Scan(&xpss.ID, &xpss.Name, &xpss.Probability, &xpss.SeqNum, &xpss.ActiveFlag, &xpss.SalesMethodID, &xpss.CreatedBy, &xpss.UpdatedBy, &xpss.CreatedAt, &xpss.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres = append(res, &xpss)\n\t}\n\n\treturn res, nil\n}", "func getDailyTaskStatsPipeline(projectId string, requester string, start time.Time, end time.Time, tasks []string, lastUpdate time.Time, oldTasks bool) []bson.M {\n\tvar taskIdExpr string\n\tvar displayTaskLookupCollection string\n\tif oldTasks {\n\t\ttaskIdExpr = \"$old_task_id\"\n\t\tdisplayTaskLookupCollection = task.OldCollection\n\t} else {\n\t\ttaskIdExpr = \"$_id\"\n\t\tdisplayTaskLookupCollection = task.Collection\n\t}\n\tpipeline := []bson.M{\n\t\t{\"$match\": bson.M{\n\t\t\ttask.ProjectKey: projectId,\n\t\t\ttask.RequesterKey: requester,\n\t\t\ttask.CreateTimeKey: bson.M{\"$gte\": start, \"$lt\": end},\n\t\t\ttask.DisplayNameKey: bson.M{\"$in\": tasks},\n\t\t}},\n\t\t{\"$project\": bson.M{\n\t\t\ttask.IdKey: 0,\n\t\t\t\"task_id\": taskIdExpr,\n\t\t\t\"execution\": taskExecutionRef,\n\t\t\t\"project\": taskProjectKeyRef,\n\t\t\t\"task_name\": taskDisplayNameKeyRef,\n\t\t\t\"variant\": taskBuildVariantKeyRef,\n\t\t\t\"distro\": taskDistroIdKeyRef,\n\t\t\t\"requester\": taskRequesterKeyRef,\n\t\t\t\"status\": taskStatusKeyRef,\n\t\t\t\"details\": taskDetailsKeyRef,\n\t\t\t\"time_taken\": bson.M{\"$divide\": array{taskTimeTakenKeyRef, nsInASecond}},\n\t\t}},\n\t\t{\"$lookup\": bson.M{\n\t\t\t\"from\": displayTaskLookupCollection,\n\t\t\t\"localField\": \"task_id\",\n\t\t\t\"foreignField\": task.ExecutionTasksKey,\n\t\t\t\"as\": \"display_task\",\n\t\t}},\n\t\t{\"$match\": bson.M{\"display_task\": array{}}}, // Excluding the execution tasks\n\t\t{\"$group\": bson.M{\n\t\t\t\"_id\": bson.D{\n\t\t\t\t{Name: \"task_name\", Value: \"$task_name\"},\n\t\t\t\t{Name: \"variant\", Value: \"$variant\"},\n\t\t\t\t{Name: \"distro\", Value: \"$distro\"},\n\t\t\t\t{Name: \"project\", Value: \"$project\"},\n\t\t\t\t{Name: \"requester\", Value: \"$requester\"}},\n\t\t\t\"num_success\": makeSum(bson.M{\"$eq\": array{\"$status\", \"success\"}}),\n\t\t\t\"num_failed\": makeSum(bson.M{\"$eq\": array{\"$status\", \"failed\"}}),\n\t\t\t\"num_timeout\": makeSum(bson.M{\"$and\": array{\n\t\t\t\tbson.M{\"$eq\": array{\"$status\", \"failed\"}},\n\t\t\t\tbson.M{\"$eq\": array{\"$details.timed_out\", true}}}}),\n\t\t\t\"num_test_failed\": makeSum(bson.M{\"$and\": array{\n\t\t\t\tbson.M{\"$eq\": array{\"$status\", \"failed\"}},\n\t\t\t\tbson.M{\"$eq\": array{\"$details.type\", \"test\"}},\n\t\t\t\tbson.M{\"$ne\": array{\"$details.timed_out\", true}}}}),\n\t\t\t\"num_system_failed\": makeSum(bson.M{\"$and\": array{\n\t\t\t\tbson.M{\"$eq\": array{\"$status\", \"failed\"}},\n\t\t\t\tbson.M{\"$eq\": array{\"$details.type\", \"system\"}},\n\t\t\t\tbson.M{\"$ne\": array{\"$details.timed_out\", true}}}}),\n\t\t\t\"num_setup_failed\": makeSum(bson.M{\"$and\": array{\n\t\t\t\tbson.M{\"$eq\": array{\"$status\", \"failed\"}},\n\t\t\t\tbson.M{\"$eq\": array{\"$details.type\", \"setup\"}},\n\t\t\t\tbson.M{\"$ne\": array{\"$details.timed_out\", true}}}}),\n\t\t\t\"avg_duration_success\": bson.M{\"$avg\": bson.M{\"$cond\": bson.M{\"if\": bson.M{\"$eq\": array{\"$status\", \"success\"}},\n\t\t\t\t\"then\": \"$time_taken\", \"else\": \"IGNORE\"}}}}},\n\t\t{\"$addFields\": bson.M{\n\t\t\t\"_id.date\": start,\n\t\t\t\"last_update\": lastUpdate,\n\t\t}},\n\t}\n\treturn pipeline\n}", "func (s *Stage) Start() {\n\tfor _, a := range s.actors {\n\t\ts.wg.Add(1)\n\t\ta.Start(s.wg)\n\t}\n}", "func (tr *Repository) All() []es.Event {\n\tdata := tr.DB.Get()\n\treturn data\n}", "func (e *ExecutionsFeature) IListAllJobExecutionHistory() error {\n\trequest, err := http.NewRequest(\"GET\", \"\", nil)\n\te.response = httptest.NewRecorder()\n\tps := httprouter.Params{}\n\trest.FindExecutions(e.response, request, ps)\n\treturn err\n}", "func getRunningTasks(\n\taws awsECSClient,\n\tstate *ecsState,\n\tcurrentCluster string,\n) (map[arn]taskInst, error) {\n\tclusterTasks := map[arn]taskInst{}\n\tfor _, svc := range state.meta.clusterSvcs[currentCluster] {\n\t\tconsole.Debug().Printf(\"%s.%s\", currentCluster, svc)\n\t\t// 1. first get the running tasks\n\t\tsvcTasksARNs, err := aws.ListTasks(currentCluster, svc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, a := range svcTasksARNs {\n\t\t\tconsole.Debug().Printf(\" %s\", a)\n\t\t}\n\t\tif _, exists := state.live.svcTasks[currentCluster]; !exists {\n\t\t\tstate.live.svcTasks[currentCluster] = map[arn][]arn{}\n\t\t}\n\t\tstate.live.svcTasks[currentCluster][svc] = svcTasksARNs\n\n\t\t// 2. ...and get details about each task\n\t\tsvcTasksARNs = sortDedupeARNs(svcTasksARNs)\n\t\tnewClusterTasks, err := aws.GetTasks(clusterTasks, currentCluster, svcTasksARNs...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor k, v := range newClusterTasks {\n\t\t\tclusterTasks[k] = v\n\t\t\tif _, ok := state.live.taskInstances[k]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstate.live.taskInstances[k] = v\n\t\t}\n\t}\n\n\treturn clusterTasks, nil\n}", "func GetActiveChildren(gtid int64) ([]*Task, error) {\n\tvar tasks []*Task\n\n\trows, err := db.Query(\"SELECT tasks.id, users.token FROM tasks \"+\n\t\t\"INNER JOIN group_tasks ON tasks.gid = group_tasks.id \"+\n\t\t\"INNER JOIN users ON group_tasks.uid = users.id \"+\n\t\t\"WHERE group_tasks.id = $1 AND tasks.status IN ($2, $3, $4)\", gtid,\n\t\tPending, Scheduled, Running)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn tasks, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar tid, user_token string\n\t\tif err := rows.Scan(&tid, &user_token); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttask, err := GetTask(tid, user_token)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttasks = append(tasks, task)\n\t}\n\treturn tasks, err\n}", "func (v TaskView) Collect(ctx context.Context, f func([]types.TaskInfo)) error {\n\t// Using TaskHistoryCollector would be less clunky, but it isn't supported on ESX at all.\n\tref := v.Reference()\n\tfilter := new(property.WaitFilter).Add(ref, \"Task\", []string{\"info\"}, v.TraversalSpec())\n\n\tif v.Watch != nil {\n\t\tfilter.Add(*v.Watch, v.Watch.Type, []string{\"recentTask\"})\n\t}\n\n\tpc := property.DefaultCollector(v.Client())\n\n\tcompleted := make(map[string]bool)\n\n\treturn property.WaitForUpdates(ctx, pc, filter, func(updates []types.ObjectUpdate) bool {\n\t\tvar infos []types.TaskInfo\n\t\tvar prune []types.ManagedObjectReference\n\t\tvar tasks []types.ManagedObjectReference\n\t\tvar reset func()\n\n\t\tfor _, update := range updates {\n\t\t\tfor _, change := range update.ChangeSet {\n\t\t\t\tif change.Name == \"recentTask\" {\n\t\t\t\t\ttasks = change.Val.(types.ArrayOfManagedObjectReference).ManagedObjectReference\n\t\t\t\t\tif len(tasks) != 0 {\n\t\t\t\t\t\treset = func() {\n\t\t\t\t\t\t\t_ = v.Reset(ctx, tasks)\n\n\t\t\t\t\t\t\t// Remember any tasks we've reported as complete already,\n\t\t\t\t\t\t\t// to avoid reporting multiple times when Reset is triggered.\n\t\t\t\t\t\t\trtasks := make(map[string]bool)\n\t\t\t\t\t\t\tfor i := range tasks {\n\t\t\t\t\t\t\t\tif _, ok := completed[tasks[i].Value]; ok {\n\t\t\t\t\t\t\t\t\trtasks[tasks[i].Value] = true\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcompleted = rtasks\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tinfo, ok := change.Val.(types.TaskInfo)\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif !completed[info.Task.Value] {\n\t\t\t\t\tinfos = append(infos, info)\n\t\t\t\t}\n\n\t\t\t\tif v.Follow && info.CompleteTime != nil {\n\t\t\t\t\tprune = append(prune, info.Task)\n\t\t\t\t\tcompleted[info.Task.Value] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(infos) != 0 {\n\t\t\tf(infos)\n\t\t}\n\n\t\tif reset != nil {\n\t\t\treset()\n\t\t} else if len(prune) != 0 {\n\t\t\t_ = v.Remove(ctx, prune)\n\t\t}\n\n\t\tif len(tasks) != 0 && len(infos) == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\treturn !v.Follow\n\t})\n}", "func (q cmfTurntableQuery) All(ctx context.Context, exec boil.ContextExecutor) (CMFTurntableSlice, error) {\n\tvar o []*CMFTurntable\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 CMFTurntable slice\")\n\t}\n\n\tif len(cmfTurntableAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (s *LeadService) FindAll(_ context.Context, p *reqModel.FindAll) (*resModel.FindAll, error) {\n\t// res := []domain.Lead{}\n\t// return res, s.db.Find(&res).Error\n\tfmt.Println(\"Logic FindAll!\")\n\treturn nil, nil\n}", "func flattenProjectLifecycleStateEnumSlice(c *Client, i interface{}) []ProjectLifecycleStateEnum {\n\ta, ok := i.([]interface{})\n\tif !ok {\n\t\treturn []ProjectLifecycleStateEnum{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn []ProjectLifecycleStateEnum{}\n\t}\n\n\titems := make([]ProjectLifecycleStateEnum, 0, len(a))\n\tfor _, item := range a {\n\t\titems = append(items, *flattenProjectLifecycleStateEnum(item.(interface{})))\n\t}\n\n\treturn items\n}", "func (w WaitListStatusRepository) GetAll() ([]interface{}, error) {\n\tvar sqlStm = `\tSELECT \ta.id, \n\t\t\t\t\t\t\ta.description,\n\t\t\t\t\t\t\ta.value\n\t\t\t\t\tFROM reservations_waitlist_status a`\n\n\tvar objects []models.WaitListStatusModel\n\n\trows, err := w.DB.Query(sqlStm)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s\", err)\n\t}\n\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\n\t\tvar id int\n\t\tvar description string\n\t\tvar value int\n\n\t\tif err = rows.Scan(\n\t\t\t&id,\n\t\t\t&description,\n\t\t\t&value); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s\", err)\n\t\t}\n\n\t\tobjects = append(objects, models.WaitListStatusModel{\n\t\t\tID: id,\n\t\t\tDescription: description,\n\t\t\tValue: value,\n\t\t})\n\t}\n\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%s\", err)\n\t}\n\n\tintfObjects := make([]interface{}, len(objects))\n\n\tfor i, obj := range objects {\n\t\tintfObjects[i] = obj\n\t}\n\n\treturn intfObjects, nil\n}", "func (c *controller) FindAll() []string {\n\treturn c.service.FindAll()\n}", "func (q buildingQuery) All(ctx context.Context, exec boil.ContextExecutor) (BuildingSlice, error) {\n\tvar o []*Building\n\n\terr := q.Bind(ctx, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"record: failed to assign all query results to Building slice\")\n\t}\n\n\tif len(buildingAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (o UsagePlanOutput) ApiStages() UsagePlanApiStageArrayOutput {\n\treturn o.ApplyT(func(v *UsagePlan) UsagePlanApiStageArrayOutput { return v.ApiStages }).(UsagePlanApiStageArrayOutput)\n}", "func XPipelineSalesStagesByUpdatedBy(db XODB, updatedBy uint) ([]*XPipelineSalesStage, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, name, probability, seq_num, active_flag, sales_method_id, created_by, updated_by, created_at, updated_at ` +\n\t\t`FROM x_showroom.x_pipeline_sales_stages ` +\n\t\t`WHERE updated_by = ?`\n\n\t// run query\n\tXOLog(sqlstr, updatedBy)\n\tq, err := db.Query(sqlstr, updatedBy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer q.Close()\n\n\t// load results\n\tres := []*XPipelineSalesStage{}\n\tfor q.Next() {\n\t\txpss := XPipelineSalesStage{\n\t\t\t_exists: true,\n\t\t}\n\n\t\t// scan\n\t\terr = q.Scan(&xpss.ID, &xpss.Name, &xpss.Probability, &xpss.SeqNum, &xpss.ActiveFlag, &xpss.SalesMethodID, &xpss.CreatedBy, &xpss.UpdatedBy, &xpss.CreatedAt, &xpss.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres = append(res, &xpss)\n\t}\n\n\treturn res, nil\n}", "func (q projectQuery) All(ctx context.Context, exec boil.ContextExecutor) (ProjectSlice, error) {\n\tvar o []*Project\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 Project slice\")\n\t}\n\n\tif len(projectAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (q projectQuery) All(ctx context.Context, exec boil.ContextExecutor) (ProjectSlice, error) {\n\tvar o []*Project\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 Project slice\")\n\t}\n\n\tif len(projectAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (r Plugin) All() []RouteInfo {\n\treturn r.routes\n}", "func (o DeliveryPipelineSerialPipelinePtrOutput) Stages() DeliveryPipelineSerialPipelineStageArrayOutput {\n\treturn o.ApplyT(func(v *DeliveryPipelineSerialPipeline) []DeliveryPipelineSerialPipelineStage {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Stages\n\t}).(DeliveryPipelineSerialPipelineStageArrayOutput)\n}", "func (wq *WorkflowQuery) AllX(ctx context.Context) []*Workflow {\n\tnodes, err := wq.All(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn nodes\n}", "func (r *SeasonsService) All(showTraktID string,extraInfo string) (seasons *Season, result *Result) {\n\tvar url *url.URL\n\tif extraInfo == \"\"{\n\t\turl, _ = showSeasonsURL.Expand(M{\"showTraktID\": showTraktID})\n\t}else {\n\t\turl, _ = showSeasonsExtendedURL.Expand(M{\"showTraktID\": showTraktID,\"extraInfo\":extraInfo})\n\t}\n\tresult = r.client.get(url, &seasons)\n\treturn\n}" ]
[ "0.56243634", "0.56039673", "0.54407847", "0.5414238", "0.5307082", "0.52988636", "0.52879316", "0.52166355", "0.52071583", "0.51802707", "0.51562804", "0.51196283", "0.5105953", "0.5103522", "0.50913906", "0.5088773", "0.50811064", "0.50527316", "0.50188595", "0.49797422", "0.49659127", "0.4946901", "0.49388012", "0.4919551", "0.49112126", "0.48825875", "0.48824593", "0.4881504", "0.48694703", "0.48214105", "0.48117697", "0.48089096", "0.47771743", "0.47483006", "0.47292736", "0.4714956", "0.47111467", "0.4699396", "0.46734363", "0.46734363", "0.46718776", "0.46650395", "0.46286452", "0.46171135", "0.46058103", "0.46055943", "0.46033147", "0.459634", "0.4592585", "0.4565485", "0.45632988", "0.4542695", "0.45411316", "0.45293105", "0.4527027", "0.45205256", "0.45199716", "0.45164698", "0.45074272", "0.4503527", "0.45030132", "0.44942588", "0.4493276", "0.4488679", "0.44813076", "0.4477129", "0.4474314", "0.44648805", "0.4464874", "0.44628954", "0.44604284", "0.4438622", "0.44253412", "0.4425208", "0.4418955", "0.441702", "0.441632", "0.44129097", "0.44127503", "0.44067752", "0.44025034", "0.44015083", "0.43985802", "0.43969372", "0.43935746", "0.4389393", "0.43890116", "0.4383194", "0.43812588", "0.4380556", "0.437523", "0.4375152", "0.43727496", "0.4361089", "0.43577933", "0.43577933", "0.43535328", "0.43532282", "0.43508387", "0.4346116" ]
0.6611906
0
DeleteByAID deletes all activity stages of an activity
func (*ActivityStageDataAccessObject) DeleteByAID(aid int) { var buf ActivityStage _, err := orm.Table(ActivityStageDAO.TableName()). Where("activity_id=?", aid).Delete(&buf) logger.LogIfError(err) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_obj *DataService) DeleteActivity(activity_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(activity_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*affectRows), 2)\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, \"deleteActivity\", _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), 2, 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 (d *Activity) ADelete() error {\n\treturn nil\n}", "func (a *Campaigns_ChallengesApiService) DeleteChallengeActivity(ctx context.Context, id int64, challengeId int64) ( *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/challenges/{challenge_id}/activities/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", fmt.Sprintf(\"%v\", id), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"challenge_id\"+\"}\", fmt.Sprintf(\"%v\", challengeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\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{\n\t\t\"application/json\",\n\t\t}\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, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t localVarHttpResponse, err := a.client.callAPI(r)\n\t if err != nil || localVarHttpResponse == nil {\n\t\t return localVarHttpResponse, err\n\t }\n\t defer localVarHttpResponse.Body.Close()\n\t if localVarHttpResponse.StatusCode >= 300 {\n\t\treturn localVarHttpResponse, reportError(localVarHttpResponse.Status)\n\t }\n\n\treturn localVarHttpResponse, err\n}", "func (s S) Remove(a *A) {\n\tif _, present := s.Actors[a.Id]; !present {\n\t\treturn\n\t}\n\n\tdelete(s.Actors, a.Id)\n\n\tfor t := range a.properties {\n\t\ts.uncache(a, t)\n\t}\n}", "func (a *Activity) Delete() error {\n\treq, err := a.c.newRequest(\"DELETE\", a.URL(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := a.c.doRequest(req, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a *Activity) Delete(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif a._deleted {\n\t\treturn nil\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetActivityTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//1\n\n\t// sql query with composite primary key\n\tsqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, a.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, a.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, a.ID)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\ta._deleted = true\n\n\treturn nil\n}", "func (this *activitiesStruct) Remove(id uint32) error {\n\terr := error(nil)\n\tthis.mutex.Lock()\n\tgroups := this.groups\n\tlength := len(groups)\n\tlength64 := uint64(length)\n\tid64 := uint64(id)\n\n\t/*\n\t * Check if activity group exists.\n\t */\n\tif id64 >= length64 {\n\t\terr = fmt.Errorf(\"No activity group with id = %d.\", id64)\n\t} else {\n\t\tidInc64 := id64 + 1\n\t\tgroups = append(groups[:id64], groups[idInc64:]...)\n\t\tthis.groups = groups\n\t\tthis.revision++\n\t}\n\n\tthis.mutex.Unlock()\n\treturn err\n}", "func (a *UtilsApiService) DeleteStageUsingDelete(ctx context.Context, stageId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\ta.client = NewAPIClient(&Configuration{\n\t\tBasePath: ctx.Value(\"BasePath\").(string),\n\t\tDefaultHeader: make(map[string]string),\n\t\tUserAgent: \"Swagger-Codegen/1.0.0/go\",\n\t})\n\tlocalVarPath := a.client.cfg.BasePath + \"/nucleus/v1/stage/{stage_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"stage_id\"+\"}\", fmt.Sprintf(\"%v\", stageId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.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{\"*/*\"}\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, 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 := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (_obj *DataService) DeleteActivityRecord(activity_id string, wx_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(activity_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_string(wx_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, \"deleteActivityRecord\", _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 (s *Service) Delete(ctx context.Context, id string) error {\n\tif err := s.assocRepo.DeleteByCusVisitAssocID(ctx, id); err != nil {\n\t\treturn err\n\t}\n\n\treturn s.repo.Delete(ctx, id)\n}", "func delete(ds datastore.Datastore, memberID, activityID int) error {\n\tquery := `DELETE FROM ce_m_activity WHERE member_id = %d AND id = %d LIMIT 1`\n\tquery = fmt.Sprintf(query, memberID, activityID)\n\t_, err := ds.MySQL.Session.Exec(query)\n\treturn err\n}", "func (a *ActivitiesApiService) DeleteActivity(ctx context.Context, id int64) ( *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/activities/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", fmt.Sprintf(\"%v\", id), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\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{\n\t\t\"application/json\",\n\t\t}\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, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t localVarHttpResponse, err := a.client.callAPI(r)\n\t if err != nil || localVarHttpResponse == nil {\n\t\t return localVarHttpResponse, err\n\t }\n\t defer localVarHttpResponse.Body.Close()\n\t if localVarHttpResponse.StatusCode >= 300 {\n\t\treturn localVarHttpResponse, reportError(localVarHttpResponse.Status)\n\t }\n\n\treturn localVarHttpResponse, err\n}", "func DeleteTrafficJam(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tid, err := getID(r)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t_, _ = w.Write([]byte(\"unable to parse id\"))\n\t\treturn\n\t}\n\n\t// Check for object existence\n\t_, err = app.GlobalTrafficJamStore.GetTrafficJam(id)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\t_, _ = w.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\t// Delete object\n\tapp.GlobalTrafficJamStore.DeleteTrafficJam(id)\n\tw.WriteHeader(http.StatusOK)\n\t_, _ = w.Write([]byte(fmt.Sprintf(\"TrafficJam %d deleted\", id)))\n}", "func Delete(uid, aid string) error {\n\tdb := pg.Connection()\n\n\tdb.\n\t\tWhere(\"user_id = ? and achievement_id = ?\", uid, aid).\n\t\tDelete(&models.Accomplished{})\n\n\treturn db.Error\n}", "func (xpss *XPipelineSalesStage) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !xpss._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif xpss._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM x_showroom.x_pipeline_sales_stages WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, xpss.ID)\n\t_, err = db.Exec(sqlstr, xpss.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\txpss._deleted = true\n\n\treturn nil\n}", "func (s *Service) DelActivity(c context.Context, limit int64) (rows int64, err error) {\n\trows, err = s.dao.DelActivity(c, limit)\n\tif err != nil {\n\t\tlog.Error(\"growup-job s.DelActivity error(%v)\", err)\n\t}\n\treturn\n}", "func delete_asset(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tfmt.Println(\"starting delete_asset\")\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tid := args[0]\n\t// get the asset\n\t_, err := get_asset(stub, id)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to find asset by id \" + id)\n\t\treturn nil, errors.New(err.Error())\n\t}\n\n\t// remove the asset\n\terr = stub.DelState(id) //remove the key from chaincode state\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to delete state\")\n\t}\n\n\tfmt.Println(\"- end delete_asset\")\n\treturn nil, nil\n}", "func deleteFromDatabase(activityType, activityDate string) {\n\tif err := utils.InitDB.Driver.Delete(activityType, activityDate); err != nil {\n\t\tfmt.Println(\"An error occured\", err)\n\t}\n\tfmt.Println(\"Succesfully deleted activity.\")\n}", "func (*ActivityStageDataAccessObject) FindByAID(aid int) []ActivityStage {\n\tl := make([]ActivityStage, 0)\n\terr := orm.Table(ActivityStageDAO.TableName()).Where(\"activity_id=?\", aid).\n\t\tFind(&l)\n\t\n\tlogger.LogIfError(err)\n\treturn l\n}", "func hMissionAbandoned(json UnstructuredJson) {\n\tmissionId := json[\"MissionID\"].(float64)\n\tif _, ok := activeTradeMissions[missionId]; ok {\n\t\tdelete(activeTradeMissions, missionId)\n\t}\n\n\tif _, ok := activePirateMissions[missionId]; ok {\n\t\tdelete(activePirateMissions, missionId)\n\t}\n}", "func (c *ActivitiesClient) DeleteOne(a *Activities) *ActivitiesDeleteOne {\n\treturn c.DeleteOneID(a.ID)\n}", "func (_obj *DataService) DeleteActivityWithContext(tarsCtx context.Context, activity_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(activity_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*affectRows), 2)\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\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"deleteActivity\", _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), 2, 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 (foo *Foo) DeleteStageAndCommit() *Foo {\n\tfoo.Unstage()\n\tDeleteORMFoo(foo)\n\treturn foo\n}", "func (sc *ScreenlyClient) Delete(id string) error {\n\tpath := fmt.Sprintf(\"assets/%s\", id)\n\t_, err := sc.doHttp(\"DELETE\", path, nil)\n\treturn err\n}", "func (m *AppConsentAppConsentRequestsItemUserConsentRequestsItemApprovalStagesApprovalStageItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *AppConsentAppConsentRequestsItemUserConsentRequestsItemApprovalStagesApprovalStageItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func deleteTask(w http.ResponseWriter, r *http.Request) {\r\n\tvars := mux.Vars(r) //copio del anterior porque el metodo de busqueda es el mismo\r\n\ttaskID, err := strconv.Atoi(vars[\"id\"])\r\n\tif err != nil {\r\n\t\tfmt.Fprintf(w, \"Invalid ID\")\r\n\t\treturn\r\n\t}\r\n\tfor i, task := range tasks { //misma busqueda que en el caso anterior\r\n\t\tif task.ID == taskID {\r\n\t\t\ttasks = append(tasks[:i], tasks[i+1:]...) //en realidad no borra sino que arma un slice con los elementos previos y posteriores al indice dado\r\n\t\t\tfmt.Fprintf(w, \"The task with ID: %v has been successfully removed.\", taskID)\r\n\t\t}\r\n\t}\r\n}", "func (c *Client) DeleteCrmStage(id int64) error {\n\treturn c.DeleteCrmStages([]int64{id})\n}", "func (*UsersFollowActivitiesDataAccessObject) DeleteByID(id int) {\n\tvar usersFollowActivities UsersFollowActivities\n\t_, err := orm.Table(UsersFollowActivitiesDAO.TableName()).\n\t\tID(id).Delete(&usersFollowActivities)\n\tlogger.LogIfError(err)\n}", "func (mdb MongoDBConnection) Delete(a Agent) error {\n\tmdb.session = mdb.GetSession()\n\tdefer mdb.session.Close()\n\tdb := mdb.session.DB(\"dockmaster\").C(\"containers\")\n\terr := db.Remove(bson.M{\"agentid\": a.AgentID})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func deleteRace(w http.ResponseWriter, r *http.Request) {\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().Delete()\n if err != nil {\n w.WriteHeader(http.StatusInternalServerError)\n json.NewEncoder(w).Encode(&core_module.CoreException{\n Message: \"Could not insert into database!\",\n })\n log.Println(err)\n return\n }\n\n w.WriteHeader(http.StatusAccepted)\n}", "func deleteTask(w http.ResponseWriter, r *http.Request){\n\t//definimos variable de vars que devuelve las variables de ruta\n\tvars := mux.Vars(r)\n\n\ttaskID, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil{\n\t\tfmt.Fprintf(w, \"Invalid ID\")\n\t\treturn\n\t}\n\n\t//Se elimina la task a la lista, guardando todas las que estan hasta su indice, y la que le sigue en adelante.\n\tfor i, task := range tasks {\n\t\tif task.ID == taskID {\n\t\t\ttasks = append(tasks[:i], tasks[i + 1:] ...)\n\t\t\tfmt.Fprintf(w, \"The task with ID %v has been removed succesfully\", taskID)\n\t\t}\n\t}\n}", "func (u teamHandler) deleteAllocation(req *restful.Request, resp *restful.Response) {\n\thandleErrors(req, resp, func() error {\n\t\tteam := req.PathParameter(\"team\")\n\t\tname := req.PathParameter(\"name\")\n\n\t\tobj, err := u.Teams().Team(team).Allocations().Delete(req.Request.Context(), name, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn resp.WriteHeaderAndEntity(http.StatusOK, obj)\n\t})\n}", "func (mdb *db) DeleteFromActivityInfoMaps(\n\tctx context.Context,\n\tfilter sqlplugin.ActivityInfoMapsFilter,\n) (sql.Result, error) {\n\tquery, args, err := sqlx.In(\n\t\tdeleteKeyInActivityInfoMapQry,\n\t\tfilter.ShardID,\n\t\tfilter.NamespaceID,\n\t\tfilter.WorkflowID,\n\t\tfilter.RunID,\n\t\tfilter.ScheduleIDs,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mdb.conn.ExecContext(ctx,\n\t\tmdb.conn.Rebind(query),\n\t\targs...,\n\t)\n}", "func (d DB) DeleteWorkflow(ctx context.Context, id string, state int32) error {\n\treturn nil\n}", "func (o *ActivityLog) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"dbmodel: no ActivityLog provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), activityLogPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"activity_logs\\\" WHERE \\\"id\\\"=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"dbmodel: unable to delete from activity_logs\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"dbmodel: failed to get rows affected by delete for activity_logs\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (gc *GarbageCollector) deleteCandidates(ctx job.Context) error {\n\tif os.Getenv(\"UTTEST\") == \"true\" {\n\t\tgc.logger = ctx.GetLogger()\n\t}\n\t// default is not to clean trash\n\tflushTrash := false\n\tdefer func() {\n\t\tif flushTrash {\n\t\t\tgc.logger.Info(\"flush artifact trash\")\n\t\t\tif err := gc.artrashMgr.Flush(ctx.SystemContext(), 0); err != nil {\n\t\t\t\tgc.logger.Errorf(\"failed to flush artifact trash: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// handle the optional ones, and the artifact controller will move them into trash.\n\tif gc.deleteUntagged {\n\t\tuntagged, err := gc.artCtl.List(ctx.SystemContext(), &q.Query{\n\t\t\tKeywords: map[string]interface{}{\n\t\t\t\t\"Tags\": \"nil\",\n\t\t\t},\n\t\t}, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgc.logger.Info(\"start to delete untagged artifact.\")\n\t\tfor _, art := range untagged {\n\t\t\tif err := gc.artCtl.Delete(ctx.SystemContext(), art.ID); err != nil {\n\t\t\t\t// the failure ones can be GCed by the next execution\n\t\t\t\tgc.logger.Errorf(\"failed to delete untagged:%d artifact in DB, error, %v\", art.ID, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgc.logger.Infof(\"delete the untagged artifact: ProjectID:(%d)-RepositoryName(%s)-MediaType:(%s)-Digest:(%s)\",\n\t\t\t\tart.ProjectID, art.RepositoryName, art.ManifestMediaType, art.Digest)\n\t\t}\n\t\tgc.logger.Info(\"end to delete untagged artifact.\")\n\t}\n\n\t// handle the trash\n\trequired, err := gc.artrashMgr.Filter(ctx.SystemContext(), 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgc.logger.Info(\"required candidate: %+v\", required)\n\tfor _, art := range required {\n\t\tif err := deleteManifest(art.RepositoryName, art.Digest); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete manifest, %s:%s with error: %v\", art.RepositoryName, art.Digest, err)\n\t\t}\n\t\tgc.logger.Infof(\"delete the manifest with registry v2 API: RepositoryName(%s)-MediaType:(%s)-Digest:(%s)\",\n\t\t\tart.RepositoryName, art.ManifestMediaType, art.Digest)\n\t}\n\tgc.logger.Info(\"end to delete required artifact.\")\n\tflushTrash = true\n\treturn nil\n}", "func DeleteIncident(incidentId int) {\n\tsess := SetupDB()\n\n\tcomponentId, err := sess.Select(\"component_id\").\n\t\tFrom(\"incidents\").\n\t\tWhere(\"id = ?\", incidentId).\n\t\tReturnInt64()\n\tCheckErr(err)\n\n\t_, err1 := sess.Update(\"components\").\n\t\tSet(\"active\", true).\n\t\tWhere(\"id = ?\", componentId).\n\t\tExec()\n\tCheckErr(err1)\n\n\t_, err2 := sess.DeleteFrom(\"incidents\").\n\t\tWhere(\"id = ?\", incidentId).\n\t\tExec()\n\tCheckErr(err2)\n}", "func Delete(ds datastore.Datastore, memberID, activityID int) error {\n\treturn delete(ds, memberID, activityID)\n}", "func (a *Api) Delete(db *system.DB) (err error) {\n\tif a.ID == 0 {\n\t\ta.Errors(ErrorMissingID, \"id\")\n\t\treturn\n\t}\n\n\ta.IsActive = false\n\n\treturn a.Update(db)\n}", "func (gc *GraphClient) DeleteAssets(assets []knowledge.Asset) error {\n\trequestBody := DeleteGraphAssetRequestBody{}\n\trequestBody.Assets = assets\n\n\tb, err := json.Marshal(requestBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to marshall request body\")\n\t}\n\n\treq, err := gc.newRequest(context.Background(), \"DELETE\", \"/api/graph/assets\", bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := gc.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode == http.StatusUnauthorized {\n\t\treturn fmt.Errorf(\"Unauthorized access. Check your auth token\")\n\t} else if res.StatusCode == http.StatusTooManyRequests {\n\t\treturn ErrTooManyRequests\n\t} else if res.StatusCode != http.StatusOK {\n\t\treturn handleUnexpectedResponse(res)\n\t}\n\treturn nil\n}", "func (mdb *db) DeleteAllFromActivityInfoMaps(\n\tctx context.Context,\n\tfilter sqlplugin.ActivityInfoMapsAllFilter,\n) (sql.Result, error) {\n\treturn mdb.conn.ExecContext(ctx,\n\t\tdeleteActivityInfoMapQry,\n\t\tfilter.ShardID,\n\t\tfilter.NamespaceID,\n\t\tfilter.WorkflowID,\n\t\tfilter.RunID,\n\t)\n}", "func DeleteByID() {\n\n}", "func (c *ovnClient) DeleteAcls(parentName, parentType string, direction string) error {\n\texternalIDs := map[string]string{aclParentKey: parentName}\n\n\t/* delete acls from port group or logical switch */\n\tacls, err := c.ListAcls(direction, externalIDs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"list type %s %s acls: %v\", parentType, parentName, err)\n\t}\n\n\taclUUIDs := make([]string, 0, len(acls))\n\tfor _, acl := range acls {\n\t\taclUUIDs = append(aclUUIDs, acl.UUID)\n\t}\n\n\tvar removeAclOp []ovsdb.Operation\n\tif parentType == portGroupKey { // remove acl from port group\n\t\tremoveAclOp, err = c.portGroupUpdateAclOp(parentName, aclUUIDs, ovsdb.MutateOperationDelete)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"generate operations for deleting acls from port group %s: %v\", parentName, err)\n\t\t}\n\t} else { // remove acl from logical switch\n\t\tremoveAclOp, err = c.logicalSwitchUpdateAclOp(parentName, aclUUIDs, ovsdb.MutateOperationDelete)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"generate operations for deleting acls from logical switch %s: %v\", parentName, err)\n\t\t}\n\t}\n\n\t// delete acls\n\tdelAclsOp, err := c.WhereCache(aclFilter(direction, externalIDs)).Delete()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"generate operation for deleting acls: %v\", err)\n\t}\n\n\tops := make([]ovsdb.Operation, 0, len(removeAclOp)+len(delAclsOp))\n\tops = append(ops, removeAclOp...)\n\tops = append(ops, delAclsOp...)\n\n\tif err = c.Transact(\"acls-del\", ops); err != nil {\n\t\treturn fmt.Errorf(\"del acls from type %s %s: %v\", parentType, parentName, err)\n\t}\n\n\treturn nil\n}", "func DeleteApplyByID(actid int, applyid int) bool{\n\t_, err := Engine.Where(\"actid=?\", actid).And(\"id=?\", applyid).Delete(&ActApplyInfo{})\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false\n\t}\n\treturn true\n}", "func (s *Service) deleteExperiment(c *gin.Context) {}", "func (_obj *DataService) DeleteActivityRecordWithContext(tarsCtx context.Context, activity_id string, wx_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(activity_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_string(wx_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\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"deleteActivityRecord\", _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 (i *Docker) Delete(assembly *global.AssemblyWithComponents, id string) (string, error) {\n\n\tpair_endpoint, perrscm := global.ParseKeyValuePair(assembly.Inputs, \"endpoint\")\n\tif perrscm != nil {\n\t\tlog.Error(\"Failed to get the endpoint value : %s\", perrscm)\n\t}\n\n\tpair_id, iderr := global.ParseKeyValuePair(assembly.Components[0].Outputs, \"id\")\n\tif iderr != nil {\n\t\tlog.Error(\"Failed to get the endpoint value : %s\", iderr)\n\t}\n\n\tvar endpoint string\n\tif pair_endpoint.Value == BAREMETAL {\n\n\t\tapi_host, _ := config.GetString(\"docker:swarm_host\")\n\t\tendpoint = api_host\n\n\t} else {\n\t\tendpoint = pair_endpoint.Value\n\t}\n\n\tclient, _ := docker.NewClient(endpoint)\n\tkerr := client.KillContainer(docker.KillContainerOptions{ID: pair_id.Value})\n\tif kerr != nil {\n\t\tlog.Error(\"Failed to kill the container : %s\", kerr)\n\t\treturn \"\", kerr\n\t}\n\tlog.Info(\"Container is killed\")\n\treturn \"\", nil\n}", "func (r Repository) DeleteMovie(id int) string {\n\tfor index, element := range movieList {\n\t\tfmt.Println(\"Index :\", index, \" Element :\", element)\n\t\tfmt.Println(element.Title)\n\t\tif element.ID == id {\n\t\t\tmovieList = append(movieList[:index], movieList[index+1:]...)\n\n\t\t}\n\t}\n\tfmt.Println(\"Deleted Movie ID - \", id)\n\treturn \"OK\"\n}", "func (c *Client) DeleteCrmStages(ids []int64) error {\n\treturn c.Delete(CrmStageModel, ids)\n}", "func (b *Executor) deleteSuccessfulIntermediateCtrs() error {\n\tvar lastErr error\n\tfor _, s := range b.stages {\n\t\tfor _, ctr := range s.containerIDs {\n\t\t\tif err := b.store.DeleteContainer(ctr); err != nil {\n\t\t\t\tb.logger.Errorf(\"error deleting build container %q: %v\\n\", ctr, err)\n\t\t\t\tlastErr = err\n\t\t\t}\n\t\t}\n\t\t// The stages map includes some stages under multiple keys, so\n\t\t// clearing their lists after we process a given stage is\n\t\t// necessary to avoid triggering errors that would occur if we\n\t\t// tried to delete a given stage's containers multiple times.\n\t\ts.containerIDs = nil\n\t}\n\treturn lastErr\n}", "func (controller *ActivityController) Delete(res http.ResponseWriter, req *http.Request) {\n\tif req.Method == http.MethodPost {\n\t\tif !controller.auth.IsLogin(res, req) {\n\t\t\thttp.Redirect(res, req, \"/login\", http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\t\tuser := controller.auth.GetUserData(res, req)\n\t\tactivityID := req.FormValue(\"hidden_activity_id\")\n\t\tcontroller.activity.DeleteActivity(strconv.Itoa(user.ID), activityID)\n\t\tcontroller.participant.DeleteParticipantsByActivityID(activityID)\n\t\thttp.Redirect(res, req, \"/activity\", http.StatusSeeOther)\n\t\treturn\n\t}\n\thttp.Error(res, \"No page. Did U understand???\", http.StatusNotFound)\n}", "func DeleteScenarioScript(id int64) (err error) {\n\to := orm.NewOrm()\n\tv := ScenarioScript{Id: id}\n\t// ascertain id exists in the database\n\tif err = o.Read(&v); err == nil {\n\t\tvar num int64\n\t\tif num, err = o.Delete(&ScenarioScript{Id: id}); err == nil {\n\t\t\tfmt.Println(\"Number of records deleted in database:\", num)\n\t\t}\n\t}\n\treturn\n}", "func (a *AmsiApiService) AppMobilityServiceByIdDELETE(ctx context.Context, appMobilityServiceId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/app_mobility_services/{appMobilityServiceId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"appMobilityServiceId\"+\"}\", fmt.Sprintf(\"%v\", appMobilityServiceId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.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, 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 := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 401 {\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\treturn localVarHttpResponse, newErr\n\t\t}\n\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\treturn localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 404 {\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\treturn localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 429 {\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\treturn localVarHttpResponse, newErr\n\t\t}\n\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (o ActivityLogSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif len(o) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tif len(activityLogBeforeDeleteHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t}\n\n\tvar args []interface{}\n\tfor _, obj := range o {\n\t\tpkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), activityLogPrimaryKeyMapping)\n\t\targs = append(args, pkeyArgs...)\n\t}\n\n\tsql := \"DELETE FROM \\\"activity_logs\\\" WHERE \" +\n\t\tstrmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, activityLogPrimaryKeyColumns, len(o))\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"dbmodel: unable to delete all from activityLog slice\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"dbmodel: failed to get rows affected by deleteall for activity_logs\")\n\t}\n\n\tif len(activityLogAfterDeleteHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rowsAff, nil\n}", "func (atuo *ActivityTypeUpdateOne) RemoveActivities(a ...*Activities) *ActivityTypeUpdateOne {\n\tids := make([]int, len(a))\n\tfor i := range a {\n\t\tids[i] = a[i].ID\n\t}\n\treturn atuo.RemoveActivityIDs(ids...)\n}", "func deletePlaceTagsById(w http.ResponseWriter, r *http.Request) {\n\traw, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to read request body: %s\", err)\n\t\thttp.Error(w, \"Failed to read request body\", 400)\n\t\treturn\n\t}\n\tlog.Print(\"Read request body\")\n\n\tdeletePlaceTagsInput := &DeletePlaceTagsInput{}\n\terr = json.Unmarshal(raw, deletePlaceTagsInput)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to unmarshal: %s\", err)\n\t\thttp.Error(w, \"Failed to unmarshal\", 400)\n\t\treturn\n\t}\n\tlog.Print(\"Unmarshaled\")\n\n\tdeletePlaceTagsOutput := &DeletePlaceTagsOutput{}\n\tfor _, id := range deletePlaceTagsInput.IDs {\n\t\tdeleteItemInput := &dynamodb.DeleteItemInput{\n\t\t\tTableName: aws.String(DDB_TABLE_NAME),\n\t\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\tKEY_ID: {\n\t\t\t\t\tS: aws.String(id),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\t_, err := ddb.DeleteItem(deleteItemInput)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error deleting item: %s\", id)\n\t\t} else {\n\t\t\tdeletePlaceTagsOutput.IDs = append(deletePlaceTagsOutput.IDs, id)\n\t\t}\n\t}\n\n\traw, err = json.Marshal(deletePlaceTagsOutput)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to marshal response: %s\", err)\n\t\thttp.Error(w, \"Failed to marshal response\", 400)\n\t\treturn\n\t}\n\tw.Write(raw)\n}", "func DeleteMeeting(c *gin.Context) {\n // Get model if exist\n var meeting models.Meeting\n if err := models.DB.First(&meeting, \"id = ?\", c.Param(\"id\")).Error; err != nil {\n c.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n return\n }\n\n models.DB.Delete(&meeting)\n\n c.JSON(http.StatusOK, gin.H{\"data\": true})\n}", "func (d *Dataset) Delete(a *config.AppContext) error {\n\t/*\n\t * We will start the transaction\n\t * We will remove the nodes\n\t * We will remove the node metadata\n\t * We will remove the file upload errors\n\t * We will remove the uploaded file info if any\n\t * We will delete the dataset user mappings\n\t * dataset info\n\t * We will commit the changes\n\t */\n\t//starting the transaction\n\ttx := a.Db.Begin()\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\tif err := tx.Error; err != nil {\n\t\treturn err\n\t}\n\n\t//deleting the nodes\n\terr := tx.Where(\"dataset_id = ?\", d.ID).Delete(&models.Node{}).Error\n\tif err != nil {\n\t\t//error while deleting the nodes\n\t\ta.Log.Error(\"error while deleting the nodes associated with the dataset\")\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\t//deleting the node metadata\n\terr = tx.Where(\"dataset_id = ?\", d.ID).Delete(&models.NodeMetadata{}).Error\n\tif err != nil {\n\t\t//error while deleting the node metadata\n\t\ta.Log.Error(\"error while deleting the node metadata associated with the dataset\")\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\t//deleting the file uploads errors if any\n\terr = tx.Where(\"file_upload_id = ?\", d.ResourceID).Delete(&fModels.FileUploadError{}).Error\n\tif err != nil {\n\t\t//error while deleting the file upload errors\n\t\ta.Log.Error(\"error while deleting the file upload errors associated with the dataset\")\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\t//deleting the file uploads if any\n\terr = tx.Where(\"id = ?\", d.ResourceID).Delete(&FileUpload{}).Error\n\tif err != nil {\n\t\t//error while deleting the file uploads\n\t\ta.Log.Error(\"error while deleting the file uploads associated with the dataset\")\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\t//deleting the datset user mappings\n\terr = tx.Where(\"dataset_id = ?\", d.ID).Delete(&DatsetUserMapping{}).Error\n\tif err != nil {\n\t\t//error while deleting the user mappings\n\t\ta.Log.Error(\"error while deleting the user mappings associated with the dataset\")\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\t//deleting the dataset\n\terr = tx.Where(\"id = ?\", d.ID).Delete(&Dataset{}).Error\n\tif err != nil {\n\t\t//error while deleting the dataset\n\t\ta.Log.Error(\"error while deleting the dataset associated with the dataset\")\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\t//commiting everything\n\treturn tx.Commit().Error\n}", "func (svc *AuditLogService) DeleteAuditLog(id string) error {\n\tif len(id) == 0 {\n\t\treturn fmt.Errorf(\"DeleteAuditLog: invalid parameter specified, %s\", id)\n\t}\n\terr := svc.objectSet.DeleteObject(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Service) DeleteByVisitID(ctx context.Context, visitID string) error {\n\tif err := s.assocRepo.DeleteByCusVisitAssocID(ctx, visitID); err != nil {\n\t\treturn err\n\t}\n\n\treturn s.repo.DeleteByVisitID(ctx, visitID)\n\n}", "func (a *apiServer) DeletePipelines(ctx context.Context, request *pps.DeletePipelinesRequest) (response *pps.DeletePipelinesResponse, retErr error) {\n\tvar (\n\t\tprojects = make(map[string]bool)\n\t\tdr = &pps.DeletePipelineRequest{\n\t\t\tForce: request.Force,\n\t\t\tKeepRepo: request.KeepRepo,\n\t\t}\n\t\tps []*pps.Pipeline\n\t)\n\tfor _, p := range request.GetProjects() {\n\t\tprojects[p.String()] = true\n\t}\n\tdr.Pipeline = &pps.Pipeline{}\n\tpipelineInfo := &pps.PipelineInfo{}\n\tdeleted := make(map[string]struct{})\n\tif err := a.pipelines.ReadOnly(ctx).List(pipelineInfo, col.DefaultOptions(), func(string) error {\n\t\tif _, ok := deleted[pipelineInfo.Pipeline.String()]; ok {\n\t\t\t// while the delete pipeline call will delete historical versions,\n\t\t\t// they could still show up in the list. Ignore them.\n\t\t\treturn nil\n\t\t}\n\t\tif !request.GetAll() && !projects[pipelineInfo.GetPipeline().GetProject().GetName()] {\n\t\t\treturn nil\n\t\t}\n\t\tdeleted[pipelineInfo.Pipeline.String()] = struct{}{}\n\t\tps = append(ps, pipelineInfo.Pipeline)\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, errors.EnsureStack(err)\n\t}\n\tfor _, p := range ps {\n\t\tif _, err := a.StopPipeline(ctx, &pps.StopPipelineRequest{Pipeline: p}); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"stop pipeline %q\", p.String())\n\t\t}\n\n\t}\n\tif err := a.env.TxnEnv.WithWriteContext(ctx, func(txnCtx *txncontext.TransactionContext) error {\n\t\tvar rs []*pfs.Repo\n\t\tfor _, p := range ps {\n\t\t\tdeleteRepos, err := a.deletePipelineInTransaction(ctx, txnCtx, &pps.DeletePipelineRequest{Pipeline: p, KeepRepo: request.KeepRepo})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trs = append(rs, deleteRepos...)\n\t\t}\n\t\treturn a.env.PFSServer.DeleteReposInTransaction(ctx, txnCtx, rs, request.Force)\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pps.DeletePipelinesResponse{Pipelines: ps}, nil\n}", "func DeleteSolution(s dbr.SessionRunner, id int64, taskID int64) error {\n\tif id == 0 && taskID == 0 {\n\t\treturn ErrNoKeysSpecified\n\t}\n\n\tsqlQuery := \"UPDATE employee_post AS p \" +\n\t\t\"INNER JOIN solution AS t \" +\n\t\t\"ON p.id=t.post_id SET p.status=? \" +\n\t\t\"WHERE p.status != ? AND \"\n\tvalues := []interface{}{PostStatusDeleted, PostStatusDeleted}\n\tif id != 0 {\n\t\tsqlQuery += \"p.id = ?\"\n\t\tvalues = append(values, id)\n\t} else if taskID != 0 {\n\t\tsqlQuery += \"t.task_id = ?\"\n\t\tvalues = append(values, taskID)\n\t}\n\n\tq := s.UpdateBySql(sqlQuery, values...)\n\tres, err := q.Exec()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn database.SomeAffected(res)\n}", "func (cm *Runc) delByID(id string) {\n\tcm.lock.Lock()\n\tdelete(cm.containers, id)\n\tdelete(cm.libContainers, id)\n\tcm.lock.Unlock()\n\tlog.Infof(\"removed dead container: %s\", id)\n}", "func (f *RemoteStepService) ActionDelete(id int) error {\n\to := orm.NewOrm()\n\n\taction := &models.RemoteAction{}\n\n\t_, err := o.QueryTable(action).Filter(\"id\", id).Delete()\n\n\treturn err\n}", "func deleteFact(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvars := mux.Vars(r)\n\tkey := vars[\"id\"]\n\n\tstmt, err := db.Prepare(\"DELETE FROM Facts WHERE id = ?\")\n\tif err != nil {\n\t\tflushResponseWriter(w, 0)\n\t\tpanic(err.Error())\n\t}\n\n\t_, err = stmt.Exec(key)\n\tif err != nil {\n\t\tflushResponseWriter(w, 0)\n\t\tpanic(err.Error())\n\t}\n\n\tw.WriteHeader(http.StatusNoContent) //204 to the client\n}", "func deleteTask(id interface{}) {\n\ti, ok := getTaskPosition(id)\n\tif ok == true {\n\t\ttasks_mutex.Lock()\n\t\ttasks = append(tasks[:i], tasks[i+1:]...)\n\t\ttasks_mutex.Unlock()\n\t}\n}", "func (t Task) Delete(id string) error {\n\terr := os.RemoveAll(path.Dir(t.Path))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, user := range DB.Users {\n\t\tdelete(user.Tasks, id)\n\t}\n\n\tdelete(DB.Tasks, id)\n\tWriteJSON(\"db.json\", DB)\n\n\treturn nil\n}", "func deleteAnArticle(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tfor index, article := range articles {\n\t\tif article.ID == params[\"id\"] {\n\t\t\tarticles = append(articles[:index],articles[index+1:]...)\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(&article{})\n\tw.WriteHeader(http.StatusOK)\n}", "func (es *Connection) DeletePipeline(\n\tid string,\n\tparams map[string]string,\n) (int, *QueryResult, error) {\n\treturn withQueryResult(es.apiCall(\"DELETE\", \"_ingest\", \"pipeline\", id, \"\", params, nil))\n}", "func (c *AviController) DeleteModels() {\n\tutils.AviLog.Infof(\"Deletion of all avi objects triggered\")\n\tpublisher := status.NewStatusPublisher()\n\tpublisher.AddStatefulSetAnnotation(lib.ObjectDeletionStartStatus)\n\tallModels := objects.SharedAviGraphLister().GetAll()\n\tallModelsMap := allModels.(map[string]interface{})\n\tif len(allModelsMap) == 0 {\n\t\tutils.AviLog.Infof(\"No Avi Object to delete, status would be updated in Statefulset\")\n\t\tpublisher.AddStatefulSetAnnotation(lib.ObjectDeletionDoneStatus)\n\t\treturn\n\t}\n\tsharedQueue := utils.SharedWorkQueue().GetQueueByName(utils.GraphLayer)\n\tfor modelName, avimodelIntf := range allModelsMap {\n\t\tobjects.SharedAviGraphLister().Save(modelName, nil)\n\t\tif avimodelIntf != nil {\n\t\t\tavimodel := avimodelIntf.(*nodes.AviObjectGraph)\n\t\t\t// for vrf, delete all static routes\n\t\t\tif avimodel.IsVrf {\n\t\t\t\tnewAviModel := nodes.NewAviObjectGraph()\n\t\t\t\tnewAviModel.IsVrf = true\n\t\t\t\taviVrfNode := &nodes.AviVrfNode{\n\t\t\t\t\tName: lib.GetVrf(),\n\t\t\t\t}\n\t\t\t\tnewAviModel.AddModelNode(aviVrfNode)\n\t\t\t\tnewAviModel.CalculateCheckSum()\n\t\t\t\tobjects.SharedAviGraphLister().Save(modelName, newAviModel)\n\t\t\t}\n\t\t}\n\t\tbkt := utils.Bkt(modelName, sharedQueue.NumWorkers)\n\t\tutils.AviLog.Infof(\"Deleting objects for model: %s\", modelName)\n\t\tsharedQueue.Workqueue[bkt].AddRateLimited(modelName)\n\t}\n\n\tDeleteNPLAnnotations()\n}", "func (a *API) DeleteDerivedAssetsByTransformation(ctx context.Context, params DeleteDerivedAssetsByTransformationParams) (*DeleteAssetsResult, error) {\n\tparams.KeepOriginal = true\n\n\tres := &DeleteAssetsResult{}\n\t_, err := a.delete(ctx, api.BuildPath(assets, params.AssetType, params.DeliveryType), params, res)\n\n\treturn res, err\n}", "func removeActivity(echoReq *alexa.EchoRequest, col *mgo.Collection, user *User) *alexa.EchoResponse {\n\tmsg := \"\"\n\n\tactivityName, err := echoReq.GetSlotValue(\"Activity\")\n\tif err != nil {\n\t\tlog.Println(\"error\")\n\t\tmsg = \"There was an error adding your activity\"\n\t\techoResp := alexa.NewEchoResponse().OutputSpeech(msg).EndSession(false)\n\t\treturn echoResp\n\t}\n\n\tactivityIndex := getActivityIndex(user.Activities, activityName)\n\n\tif activityIndex == -1 {\n\t\tmsg = \"There is no activity by that name\"\n\t\techoResp := alexa.NewEchoResponse().OutputSpeech(msg).EndSession(false)\n\t\treturn echoResp\n\t}\n\n\tuser.Activities = append(user.Activities[:activityIndex], user.Activities[activityIndex+1:]...)\n\n\tupdateUser(col, user)\n\n\tmsg = \"Removed \" + activityName + \" from the list of activities\"\n\n\techoResp := alexa.NewEchoResponse().OutputSpeech(msg).EndSession(false)\n\treturn echoResp\n}", "func deleteTask(taskID int) {\n\n\ttrepo := sqlite.NewTaskRepo()\n\n\ttrepo.DeleteTask(taskID)\n\tfmt.Println(\"Tarea borrada correctamente\")\n}", "func DeletePessoa(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tfor index, item := range pessoas {\n\t\tif item.ID == params[\"id\"] {\n\t\t\tpessoas = append(pessoas[:index], pessoas[index+1:]...)\n\t\t\tbreak\n\t\t}\n\t\tjson.NewEncoder(w).Encode(pessoas)\n\t}\n}", "func deletePost(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n params := mux.Vars(r)\n for index, item := range posts {\n if item.ID == params[\"id\"] {\n posts = append(posts[:index], posts[index+1:]...)\n break\n }\n }\n json.NewEncoder(w).Encode(posts)\n}", "func (a *AclsApiService) DeleteAcls(ctx _context.Context) ApiDeleteAclsRequest {\n\treturn ApiDeleteAclsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func Delete(id string) error {\n\tbp, err := common.New()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn bp.DeleteCollector(id)\n}", "func (w *WorkflowInstance) Delete(trs *db.Transaction) error {\n\tif err := db.DeleteStructTx(trs.Tx, constants.TableCoreGroups, &db.Options{\n\t\tConditions: builder.Equal(\"code\", w.ID),\n\t}); err != nil {\n\t\treturn customerror.New(http.StatusInternalServerError, \"workflow instance delete\", err.Error())\n\t}\n\treturn nil\n}", "func (d *Activity) BDelete() error {\n\treturn nil\n}", "func deleteTask(writer http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\tcreatedAt, err := time.Parse(time.RFC3339, vars[\"createdAt\"])\n\tif err != nil {\n\t\tlog.Print(\"error:\", err)\n\t\thttp.Error(writer, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdatabase, err := loadJsonFile()\n\tif err != nil {\n\t\tlog.Print(\"error:\", err)\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tfor i, _ := range database.Tasks {\n\t\tif database.Tasks[i].CreatedAt.Equal(createdAt) {\n\t\t\tdatabase.Tasks = append(database.Tasks[:i], database.Tasks[i+1:]...)\n\t\t\treturnJson(database, writer)\n\t\t\treturn\n\t\t}\n\t}\n\t//this code runs only if no taks was found with the correct createdAt timestamp\n\thttp.Error(writer, err.Error(), http.StatusBadRequest)\n}", "func DeleteActionsByUserID(c *gin.Context) {\n\tvar (\n\t\tuserID = c.Param(\"user_id\")\n\t\taction = []models.Action{}\n\t)\n\n\tresult := models.DB.Find(&action, \"created_by = ?\", userID)\n\n\tif result.RowsAffected == 0 {\n\t\tc.JSON(http.StatusOK, helpers.NoResults())\n\t\treturn\n\t}\n\n\tmodels.DB.Exec(\"DELETE FROM actions WHERE created_by = ?\", userID)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": helpers.Results{\n\t\tCount: len(action),\n\t\tResults: action,\n\t}})\n}", "func hMissionCompleted(json UnstructuredJson) {\n\tmissionId := json[\"MissionID\"].(float64)\n\tif _, ok := activeTradeMissions[missionId]; ok {\n\t\tdelete(activeTradeMissions, missionId)\n\t}\n\n\tif _, ok := activePirateMissions[missionId]; ok {\n\t\tdelete(activePirateMissions, missionId)\n\t}\n}", "func (store *dbStore) DeleteChoiceByID(id string) error {\r\n\r\n\tsqlStatement := fmt.Sprint(\"DELETE FROM movie where choice_id= \", id)\r\n\tfmt.Println(id)\r\n\r\n\tfmt.Println(sqlStatement)\r\n\t_, err := store.db.Query(sqlStatement)\r\n\tif err != nil {\r\n\t\tfmt.Printf(\"failed to execute delete movie query on the database: %v\", err)\r\n\t\treturn err\r\n\t}\r\n\r\n\tsqlStatement = fmt.Sprint(\"DELETE FROM restaurant where choice_id= \", id)\r\n\r\n\tfmt.Println(sqlStatement)\r\n\r\n\t_, err = store.db.Query(sqlStatement)\r\n\tif err != nil {\r\n\t\tfmt.Printf(\"failed to execute delete restaurant query on the database: %v\", err)\r\n\t\treturn err\r\n\t}\r\n\r\n\tsqlStatement = fmt.Sprint(\"DELETE FROM choice where id= \", id)\r\n\r\n\tfmt.Println(sqlStatement)\r\n\r\n\t_, err = store.db.Query(sqlStatement)\r\n\tif err != nil {\r\n\t\tfmt.Printf(\"failed to execute delete choice query on the database: %v\", err)\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn nil\r\n}", "func TestDeleteVpa(t *testing.T) {\n\tcluster := NewClusterState()\n\tvpa := addTestVpa(cluster)\n\tpod := addTestPod(cluster)\n\tcluster.DeleteVpa(vpa.ID)\n\tassert.Nil(t, pod.Vpa)\n\tassert.NotContains(t, cluster.Vpas, vpa.ID)\n}", "func (v *Visit) Delete(db XODB) error {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM custmchat.visit WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, v.ID)\n\t_, err = db.Exec(sqlstr, v.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\treturn nil\n}", "func deleteWorkflowRunsHistory(db gorp.SqlExecutor) error {\n\tquery := `DELETE FROM workflow_run WHERE workflow_run.id IN (SELECT id FROM workflow_run WHERE to_delete = true LIMIT 30)`\n\n\tif _, err := db.Exec(query); err != nil {\n\t\tlog.Warning(\"deleteWorkflowRunsHistory> Unable to delete workflow history %s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_obj *DataService) DeleteActivityOneWayWithContext(tarsCtx context.Context, activity_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(activity_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*affectRows), 2)\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\n\terr = _obj.s.Tars_invoke(tarsCtx, 1, \"deleteActivity\", _os.ToBytes(), _status, _context, _resp)\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 DeletePipeline(key, name string) error {\n\tpath := fmt.Sprintf(\"/project/%s/pipeline/%s\", key, name)\n\n\t_, code, err := Request(\"DELETE\", path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif code >= 300 {\n\t\treturn fmt.Errorf(\"HTTP %d\", code)\n\t}\n\n\treturn nil\n}", "func deleteOneTask(task string) {\n\tfmt.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\td, err := collection.DeleteOne(context.Background(), filter)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Documento eliminado\", d.DeletedCount)\n}", "func apiArchiveDelete(\n\tctx *ApiContext, req *http.Request, params httprouter.Params,\n) *ApiResponse {\n\tcollectionId := params.ByName(\"collection\")\n\tcollection, err := ctx.Repository.Use(collectionId)\n\tif err != nil {\n\t\treturn JsonError(err, 500)\n\t}\n\tarchiveId, err := strconv.ParseUint(params.ByName(\"id\"), 10, 64)\n\n\tarchive, err := collection.Find(uint64(archiveId))\n\tif err != nil {\n\t\treturn JsonError(\"archive not found\", 404)\n\t}\n\n\terr = archive.Destroy(\"destroyed via api\")\n\tif err != nil {\n\t\treturn JsonError(\"archive delete error\", 500)\n\t}\n\n\treturn JsonSuccess(\"OK\")\n}", "func (t *CAChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tA := args[0]\n\n\t// Delete the key from the state in ledger\n\terr := stub.DelState(A)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to delete state\")\n\t}\n\n\treturn shim.Success(nil)\n}", "func cleanupAssets(ctx context.Context, collection *kabanerov1alpha1.Collection, c client.Client, reqLogger logr.Logger) error {\n\townerIsController := false\n\tassetOwner := metav1.OwnerReference{\n\t\tAPIVersion: collection.APIVersion,\n\t\tKind: collection.Kind,\n\t\tName: collection.Name,\n\t\tUID: collection.UID,\n\t\tController: &ownerIsController,\n\t}\n\n\t// Run thru the status and delete everything.... we're just going to try once since it's unlikely\n\t// that anything that goes wrong here would be rectified by a retry.\n\tfor _, version := range collection.Status.Versions {\n\t\tfor _, pipeline := range version.Pipelines {\n\t\t\tfor _, asset := range pipeline.ActiveAssets {\n\t\t\t\t// Old assets may not have a namespace set - correct that now.\n\t\t\t\tif len(asset.Namespace) == 0 {\n\t\t\t\t\tasset.Namespace = collection.GetNamespace()\n\t\t\t\t}\n\n\t\t\t\tdeleteAsset(c, asset, assetOwner)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (process *Process) Delete() {\n\tsql := \"DELETE FROM `process` WHERE id=?\"\n\tquery, err := database.Connection.Prepare(sql)\n\tif err != nil {\n\t\tfmt.Println(\"Delete #1 error for process:\")\n\t\tfmt.Println(err)\n\t}\n\tquery.Exec(process.Action.ID)\n}", "func Delete(projectID, taskID int) {\n\n\tif projectID > 0 {\n\t\tdeleteProject(projectID)\n\t}\n\n\tif taskID > 0 {\n\t\tdeleteTask(taskID)\n\t}\n}", "func (a *API) DeleteCompetence(ctx *app.Context, w http.ResponseWriter, r *http.Request) error {\n\tid := getIDFromRequest(\"id\", r)\n\tintID, err := strconv.Atoi(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ctx.DeleteCompetence(uint16(intID))\n}", "func (d TinkDB) DeleteWorkflow(ctx context.Context, id string, state int32) error {\n\ttx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"BEGIN transaction\")\n\t}\n\n\t_, err = tx.Exec(`\n\tDELETE FROM workflow_worker_map\n\tWHERE\n\t\tworkflow_id = $1;\n\t`, id)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Delete Workflow Error\")\n\t}\n\n\t_, err = tx.Exec(`\n\tDELETE FROM workflow_state\n\tWHERE\n\t\tworkflow_id = $1;\n\t`, id)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Delete Workflow Error\")\n\t}\n\n\t_, err = tx.Exec(`\n\tUPDATE workflow\n\tSET\n\t\tdeleted_at = NOW()\n\tWHERE\n\t\tid = $1;\n\t`, id)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"UPDATE\")\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"COMMIT\")\n\t}\n\treturn nil\n}", "func (svc record) DeleteByID(namespaceID, moduleID uint64, recordIDs ...uint64) (err error) {\n\tvar (\n\t\taProps = &recordActionProps{\n\t\t\tnamespace: &types.Namespace{ID: namespaceID},\n\t\t\tmodule: &types.Module{ID: moduleID},\n\t\t}\n\n\t\tisBulkDelete = len(recordIDs) > 1\n\n\t\tns *types.Namespace\n\t\tm *types.Module\n\t\tr *types.Record\n\t)\n\n\terr = func() error {\n\t\tif namespaceID == 0 {\n\t\t\treturn RecordErrInvalidNamespaceID()\n\t\t}\n\t\tif moduleID == 0 {\n\t\t\treturn RecordErrInvalidModuleID()\n\t\t}\n\n\t\tns, m, _, err = svc.loadCombo(namespaceID, moduleID, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\taProps.setNamespace(ns)\n\t\taProps.setModule(m)\n\n\t\tif !svc.ac.CanDeleteRecord(svc.ctx, m) {\n\t\t\treturn RecordErrNotAllowedToDelete()\n\t\t}\n\n\t\treturn nil\n\t}()\n\n\tif err != nil {\n\t\treturn svc.recordAction(svc.ctx, aProps, RecordActionDelete, err)\n\t}\n\n\tfor _, recordID := range recordIDs {\n\t\terr := func() (err error) {\n\t\t\tr, err = svc.delete(namespaceID, moduleID, recordID)\n\t\t\taProps.setRecord(r)\n\n\t\t\t// Record each record deletion action\n\t\t\treturn svc.recordAction(svc.ctx, aProps, RecordActionDelete, err)\n\t\t}()\n\n\t\t// We'll not break for failed delete,\n\t\t// if we are deleting records in bulk.\n\t\tif err != nil && !isBulkDelete {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\t// all errors (if any) were recorded\n\t// and in case of error for a non-bulk record deletion\n\t// error is already returned\n\treturn nil\n}", "func DeleteInversionEstadoInversion(id int) (err error) {\n\to := orm.NewOrm()\n\tv := InversionEstadoInversion{Id: id}\n\t// ascertain id exists in the database\n\tif err = o.Read(&v); err == nil {\n\t\tvar num int64\n\t\tif num, err = o.Delete(&InversionEstadoInversion{Id: id}); err == nil {\n\t\t\tfmt.Println(\"Number of records deleted in database:\", num)\n\t\t}\n\t}\n\treturn\n}", "func deleteTeam(c *gin.Context) {\n\tidentifier := c.Params.ByName(\"identifier\")\n\tvar tm Team\n\tif err := db.Where(\"identifier = ?\", identifier).Find(&tm).Error; err != nil {\n\t\tcreateNotFoundResponse(c)\n\t\treturn\n\t}\n\tdb.Delete(&tm)\n\tc.JSON(200, gin.H{\"Message\": identifier + \" deleted\"})\n}", "func (client ConversationsClient) DeleteActivityMethodPreparer(ctx context.Context, conversationID string, activityID string) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"activityId\": autorest.Encode(\"path\",activityID),\n \"conversationId\": autorest.Encode(\"path\",conversationID),\n }\n\n preparer := autorest.CreatePreparer(\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPathParameters(\"/v3/conversations/{conversationId}/activities/{activityId}\",pathParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }" ]
[ "0.57413393", "0.57042164", "0.5298612", "0.5154209", "0.5108312", "0.50848323", "0.5073462", "0.5073002", "0.50524205", "0.5045732", "0.5044127", "0.5041667", "0.50361633", "0.5023286", "0.5019291", "0.49611187", "0.4944929", "0.4899914", "0.48942277", "0.4885482", "0.48824793", "0.48812196", "0.48648477", "0.47912997", "0.47897822", "0.47855365", "0.47750768", "0.4771071", "0.47640696", "0.47632378", "0.47581822", "0.47559777", "0.47474238", "0.47453305", "0.47194508", "0.4709839", "0.47039056", "0.4681806", "0.46659783", "0.46496207", "0.4639664", "0.4638407", "0.46302745", "0.46209478", "0.46093854", "0.45720208", "0.45711693", "0.45623448", "0.45515326", "0.45387888", "0.45379263", "0.45301166", "0.45241112", "0.4519001", "0.45112398", "0.45018476", "0.4500988", "0.44965214", "0.44861358", "0.44829476", "0.44814885", "0.44783226", "0.4469771", "0.4464087", "0.44604197", "0.44556335", "0.44536233", "0.445328", "0.44460183", "0.44420162", "0.4439022", "0.4437587", "0.4428472", "0.44272462", "0.44065014", "0.440624", "0.4400343", "0.43978328", "0.43953905", "0.43950027", "0.4392806", "0.43924612", "0.43896687", "0.4389125", "0.43853438", "0.43848312", "0.43828434", "0.43808872", "0.43808556", "0.43805927", "0.43750143", "0.43736434", "0.43718833", "0.43681034", "0.43666437", "0.43641973", "0.43632513", "0.43602294", "0.43583986", "0.43582818" ]
0.76443285
0
UpdateOne update an activity stage
func (*ActivityStageDataAccessObject) UpdateOne(activityStage *ActivityStage) { _, err := orm.Table(ActivityStageDAO.TableName()).ID(activityStage.ID). Update(activityStage) logger.LogIfError(err) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *ActivitiesClient) UpdateOne(a *Activities) *ActivitiesUpdateOne {\n\tmutation := newActivitiesMutation(c.config, OpUpdateOne, withActivities(a))\n\treturn &ActivitiesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *ActivityTypeClient) UpdateOne(at *ActivityType) *ActivityTypeUpdateOne {\n\tmutation := newActivityTypeMutation(c.config, OpUpdateOne, withActivityType(at))\n\treturn &ActivityTypeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (d *DBRepository) updateOne(ctx context.Context, id string, travel *Travel) error {\n\ttravel.ObjectID, _ = primitive.ObjectIDFromHex(id)\n\tfilter := bson.M{\"_id\": travel.ObjectID}\n\tif _, err := d.Collection.ReplaceOne(ctx, filter, travel); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (su *PostUseCase) UpdateOne(id string, request data.Post) error {\n\tpost := &models.Post{ID: id}\n\terr := post.Get()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpost.Post = request\n\terr = post.Update()\n\treturn err\n}", "func (c *PostVideoClient) UpdateOne(pv *PostVideo) *PostVideoUpdateOne {\n\tmutation := newPostVideoMutation(c.config, OpUpdateOne, withPostVideo(pv))\n\treturn &PostVideoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UnsavedPostVideoClient) UpdateOne(upv *UnsavedPostVideo) *UnsavedPostVideoUpdateOne {\n\tmutation := newUnsavedPostVideoMutation(c.config, OpUpdateOne, withUnsavedPostVideo(upv))\n\treturn &UnsavedPostVideoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UnsavedPostAttachmentClient) UpdateOne(upa *UnsavedPostAttachment) *UnsavedPostAttachmentUpdateOne {\n\tmutation := newUnsavedPostAttachmentMutation(c.config, OpUpdateOne, withUnsavedPostAttachment(upa))\n\treturn &UnsavedPostAttachmentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *PlanetClient) UpdateOne(pl *Planet) *PlanetUpdateOne {\n\treturn c.UpdateOneID(pl.ID)\n}", "func (c *PostAttachmentClient) UpdateOne(pa *PostAttachment) *PostAttachmentUpdateOne {\n\tmutation := newPostAttachmentMutation(c.config, OpUpdateOne, withPostAttachment(pa))\n\treturn &PostAttachmentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *WorkExperienceClient) UpdateOne(we *WorkExperience) *WorkExperienceUpdateOne {\n\tmutation := newWorkExperienceMutation(c.config, OpUpdateOne, withWorkExperience(we))\n\treturn &WorkExperienceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func UpdateOne(w http.ResponseWriter, r *http.Request) {\n\tpostID := mux.Vars(r)[\"id\"]\n\tvar editPost EditPostDto\n\tif err := json.NewDecoder(r.Body).Decode(&editPost); err != nil {\n\t\tresponse.Error(w, http.StatusBadGateway, err.Error())\n\t\treturn\n\t}\n\n\tresult, err := editPost.EditPost(postID)\n\tif err != nil {\n\t\tresponse.Error(w, http.StatusBadGateway, err.Error())\n\t\treturn\n\t}\n\tresponse.Success(w, r,\n\t\thttp.StatusOK,\n\t\tresult,\n\t)\n\treturn\n}", "func (c *RoomuseClient) UpdateOne(r *Roomuse) *RoomuseUpdateOne {\n\tmutation := newRoomuseMutation(c.config, OpUpdateOne, withRoomuse(r))\n\treturn &RoomuseUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *PositionassingmentClient) UpdateOne(po *Positionassingment) *PositionassingmentUpdateOne {\n\tmutation := newPositionassingmentMutation(c.config, OpUpdateOne, withPositionassingment(po))\n\treturn &PositionassingmentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (atuo *ActivityTypeUpdateOne) Save(ctx context.Context) (*ActivityType, error) {\n\tif v, ok := atuo.mutation.Name(); ok {\n\t\tif err := activitytype.NameValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"name\", err: fmt.Errorf(\"ent: validator failed for field \\\"name\\\": %w\", err)}\n\t\t}\n\t}\n\n\tvar (\n\t\terr error\n\t\tnode *ActivityType\n\t)\n\tif len(atuo.hooks) == 0 {\n\t\tnode, err = atuo.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*ActivityTypeMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tatuo.mutation = mutation\n\t\t\tnode, err = atuo.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(atuo.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = atuo.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, atuo.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (atuo *ActivityTypeUpdateOne) Exec(ctx context.Context) error {\n\t_, err := atuo.Save(ctx)\n\treturn err\n}", "func (*SeatDataAccessObject) UpdateOne(seat *Seat) {\n\t_, err := orm.Table(seat).ID(seat.SeatID).Update(seat)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (d *Activity) AUpdate() error {\n\treturn nil\n}", "func (*ActivityStageDataAccessObject) InsertOne(stage *ActivityStage) {\n\t_, err := orm.Table(ActivityStageDAO.TableName()).Insert(stage)\n\tlogger.LogIfError(err)\n}", "func (c *PostClient) UpdateOne(po *Post) *PostUpdateOne {\n\tmutation := newPostMutation(c.config, OpUpdateOne, withPost(po))\n\treturn &PostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *AppointmentClient) UpdateOne(a *Appointment) *AppointmentUpdateOne {\n\tmutation := newAppointmentMutation(c.config, OpUpdateOne, withAppointment(a))\n\treturn &AppointmentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (s *Service) UpdateOne(value Value, identifiable Identifiable) error {\n\tid := identifiable.Identifier()\n\tif err := s.ensureIdIsComplete(id); err != nil {\n\t\treturn err\n\t}\n\treturn s.storage.Update(value, identifiable.Identifier())\n}", "func (e *engine) UpdateOne(c *httpEngine.ServerContext) {\n\t// check iid exists or not\n\tid, err := c.GetURLParam(\"iid\")\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\t}\n\n\tvar product = &domain.Product{}\n\t// check is valid json for product\n\terr = c.BindToJson(product)\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\n\t}\n\tproduct.Iid = id\n\tres, err := e.ProductLogic.UpdateProduct(product)\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\n\t}\n\tc.JSON(200, res)\n}", "func (s *Store) Update(w http.ResponseWriter, r *http.Request) {\n\t// We don't set up the: \"defer dphttp.DrainBody(r)\" here, as the body is fully read in function unmarshalInstance() below\n\t// and a call to DrainBody() puts this error: \"invalid Read on closed Body\" into the logs - to no good effect\n\t// because there is no more body to be read - so instead we just set up the usual Close() on the Body.\n\tdefer func() {\n\t\tif bodyCloseErr := r.Body.Close(); bodyCloseErr != nil {\n\t\t\tlog.Error(r.Context(), \"could not close response body\", bodyCloseErr)\n\t\t}\n\t}()\n\n\tctx := r.Context()\n\tvars := mux.Vars(r)\n\tinstanceID := vars[\"instance_id\"]\n\teTag := getIfMatch(r)\n\n\tlogData := log.Data{\"instance_id\": instanceID}\n\n\tinstance, err := unmarshalInstance(ctx, r.Body, false)\n\tif err != nil {\n\t\tlog.Error(ctx, \"update instance: failed unmarshalling json to model\", err, logData)\n\t\thandleInstanceErr(ctx, taskError{error: err, status: 400}, w, logData)\n\t\treturn\n\t}\n\n\tif err = validateInstanceUpdate(instance); err != nil {\n\t\thandleInstanceErr(ctx, taskError{error: err, status: 400}, w, logData)\n\t\treturn\n\t}\n\n\t// acquire instance lock so that the dp-graph call to AddVersionDetailsToInstance and the mongoDB update are atomic\n\tlockID, err := s.AcquireInstanceLock(ctx, instanceID)\n\tif err != nil {\n\t\tlog.Error(ctx, \"update instance: failed to lock the instance\", err, logData)\n\t\thandleInstanceErr(ctx, taskError{error: err, status: http.StatusInternalServerError}, w, logData)\n\t\treturn\n\t}\n\tdefer s.UnlockInstance(ctx, lockID)\n\n\t// Get the current document\n\tcurrentInstance, err := s.GetInstance(ctx, instanceID, eTag)\n\tif err != nil {\n\t\tlog.Error(ctx, \"update instance: store.GetInstance returned error\", err, logData)\n\t\thandleInstanceErr(ctx, err, w, logData)\n\t\treturn\n\t}\n\n\tlogData[\"current_state\"] = currentInstance.State\n\tlogData[\"requested_state\"] = instance.State\n\tif instance.State != \"\" && instance.State != currentInstance.State {\n\t\tif err = validateInstanceStateUpdate(instance, currentInstance); err != nil {\n\t\t\tlog.Error(ctx, \"update instance: instance state invalid\", err, logData)\n\t\t\thandleInstanceErr(ctx, err, w, logData)\n\t\t\treturn\n\t\t}\n\t}\n\n\tdatasetID := currentInstance.Links.Dataset.ID\n\n\t// edition confirmation is a one time process - cannot be edited for an instance once done\n\tif instance.State == models.EditionConfirmedState && instance.Version == 0 {\n\t\tif instance.Edition == \"\" {\n\t\t\tinstance.Edition = currentInstance.Edition\n\t\t}\n\n\t\tedition := instance.Edition\n\t\teditionLogData := log.Data{\"instance_id\": instanceID, \"dataset_id\": datasetID, \"edition\": edition}\n\n\t\teditionDoc, editionConfirmErr := s.confirmEdition(ctx, datasetID, edition, instanceID)\n\t\tif editionConfirmErr != nil {\n\t\t\tlog.Error(ctx, \"update instance: store.getEdition returned an error\", editionConfirmErr, editionLogData)\n\t\t\thandleInstanceErr(ctx, editionConfirmErr, w, logData)\n\t\t\treturn\n\t\t}\n\n\t\t// update instance with confirmed edition details\n\t\tinstance.Links = currentInstance.Links\n\t\tinstance.Links.Edition = &models.LinkObject{\n\t\t\tID: instance.Edition,\n\t\t\tHRef: editionDoc.Next.Links.Self.HRef,\n\t\t}\n\n\t\tinstance.Links.Version = editionDoc.Next.Links.LatestVersion\n\t\tinstance.Version, editionConfirmErr = strconv.Atoi(editionDoc.Next.Links.LatestVersion.ID)\n\t\tif editionConfirmErr != nil {\n\t\t\tlog.Error(ctx, \"update instance: failed to convert edition latestVersion id to instance.version int\", editionConfirmErr, editionLogData)\n\t\t\thandleInstanceErr(ctx, editionConfirmErr, w, logData)\n\t\t\treturn\n\t\t}\n\n\t\t// update dp-graph instance node (only for non-cantabular types)\n\t\tif currentInstance.Type == models.CantabularBlob.String() || currentInstance.Type == models.CantabularTable.String() || currentInstance.Type == models.CantabularFlexibleTable.String() || currentInstance.Type == models.CantabularMultivariateTable.String() {\n\t\t\teditionLogData[\"instance_type\"] = instance.Type\n\t\t\tlog.Info(ctx, \"skipping dp-graph instance update because it is not required by instance type\", editionLogData)\n\t\t} else {\n\t\t\tif versionErr := s.AddVersionDetailsToInstance(ctx, currentInstance.InstanceID, datasetID, edition, instance.Version); versionErr != nil {\n\t\t\t\tlog.Error(ctx, \"update instance: datastore.AddVersionDetailsToInstance returned an error\", versionErr, editionLogData)\n\t\t\t\thandleInstanceErr(ctx, versionErr, w, logData)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlog.Info(ctx, \"update instance: added version details to instance\", editionLogData)\n\t}\n\n\t// Set the current mongo timestamp on instance document\n\tinstance.UniqueTimestamp = currentInstance.UniqueTimestamp\n\tnewETag, err := s.UpdateInstance(ctx, currentInstance, instance, eTag)\n\tif err != nil {\n\t\tlog.Error(ctx, \"update instance: store.UpdateInstance returned an error\", err, logData)\n\t\thandleInstanceErr(ctx, err, w, logData)\n\t\treturn\n\t}\n\n\tif instance, err = s.GetInstance(ctx, instanceID, newETag); err != nil {\n\t\tlog.Error(ctx, \"update instance: store.GetInstance for response returned an error\", err, logData)\n\t\thandleInstanceErr(ctx, err, w, logData)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(instance)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance: failed to marshal instance to json\", err, logData)\n\t\thandleInstanceErr(ctx, err, w, logData)\n\t\treturn\n\t}\n\n\tsetJSONContentType(w)\n\tdpresponse.SetETag(w, newETag)\n\tw.WriteHeader(http.StatusOK)\n\twriteBody(ctx, w, b, logData)\n\n\tlog.Info(ctx, \"update instance: request successful\", logData)\n}", "func (auo *AnnouncementUpdateOne) Exec(ctx context.Context) error {\n\t_, err := auo.Save(ctx)\n\treturn err\n}", "func (_obj *DataService) UpdateActivity(activityIndo *ActivityInfo, 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 = activityIndo.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*affectRows), 2)\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, \"updateActivity\", _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), 2, 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 (c *OperationroomClient) UpdateOne(o *Operationroom) *OperationroomUpdateOne {\n\tmutation := newOperationroomMutation(c.config, OpUpdateOne, withOperationroom(o))\n\treturn &OperationroomUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *ExaminationroomClient) UpdateOne(e *Examinationroom) *ExaminationroomUpdateOne {\n\tmutation := newExaminationroomMutation(c.config, OpUpdateOne, withExaminationroom(e))\n\treturn &ExaminationroomUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (a *Activity) Update(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif a._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetActivityTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql query\n\tsqlstr := `UPDATE ` + tableName + ` SET ` +\n\t\t`name = ?, activity_type_id = ?, activity_type_code = ?, content = ?, activity_image = ?, image_url = ?, image_color = ?, status = ?, sort = ?, extend = ?, admin_id = ?, admin_name = ?, start_time = ?, end_time = ?, created_at = ?, updated_at = ?` +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, a.Name, a.ActivityTypeID, a.ActivityTypeCode, a.Content, a.ActivityImage, a.ImageURL, a.ImageColor, a.Status, a.Sort, a.Extend, a.AdminID, a.AdminName, a.StartTime, a.EndTime, a.CreatedAt, a.UpdatedAt, a.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, a.Name, a.ActivityTypeID, a.ActivityTypeCode, a.Content, a.ActivityImage, a.ImageURL, a.ImageColor, a.Status, a.Sort, a.Extend, a.AdminID, a.AdminName, a.StartTime, a.EndTime, a.CreatedAt, a.UpdatedAt, a.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, a.Name, a.ActivityTypeID, a.ActivityTypeCode, a.Content, a.ActivityImage, a.ImageURL, a.ImageColor, a.Status, a.Sort, a.Extend, a.AdminID, a.AdminName, a.StartTime, a.EndTime, a.CreatedAt, a.UpdatedAt, a.ID)\n\t}\n\treturn err\n}", "func (c *UnsavedPostClient) UpdateOne(up *UnsavedPost) *UnsavedPostUpdateOne {\n\tmutation := newUnsavedPostMutation(c.config, OpUpdateOne, withUnsavedPost(up))\n\treturn &UnsavedPostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *BillingstatusClient) UpdateOne(b *Billingstatus) *BillingstatusUpdateOne {\n\tmutation := newBillingstatusMutation(c.config, OpUpdateOne, withBillingstatus(b))\n\treturn &BillingstatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *RentalstatusClient) UpdateOne(r *Rentalstatus) *RentalstatusUpdateOne {\n\tmutation := newRentalstatusMutation(c.config, OpUpdateOne, withRentalstatus(r))\n\treturn &RentalstatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *ClubappStatusClient) UpdateOne(cs *ClubappStatus) *ClubappStatusUpdateOne {\n\tmutation := newClubappStatusMutation(c.config, OpUpdateOne, withClubappStatus(cs))\n\treturn &ClubappStatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (e *ExpenseModel) UpdateOne(updatedData interface{}, filter interface{}) (int64, error) {\n\tcollection := e.db.Client.Database(e.db.DBName).Collection(\"expenses\")\n\tatualizacao := bson.D{{Key: \"$set\", Value: updatedData}}\n\tupdatedResult, err := collection.UpdateOne(context.TODO(), filter, atualizacao)\n\tif err != nil {\n\t\tlog.Fatal(\"Error on updating one expense\", err)\n\t\treturn 0, err\n\t}\n\treturn updatedResult.ModifiedCount, nil\n}", "func (c *PatientroomClient) UpdateOne(pa *Patientroom) *PatientroomUpdateOne {\n\tmutation := newPatientroomMutation(c.config, OpUpdateOne, withPatientroom(pa))\n\treturn &PatientroomUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *BedtypeClient) UpdateOne(b *Bedtype) *BedtypeUpdateOne {\n\tmutation := newBedtypeMutation(c.config, OpUpdateOne, withBedtype(b))\n\treturn &BedtypeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *DepartmentClient) UpdateOne(d *Department) *DepartmentUpdateOne {\n\tmutation := newDepartmentMutation(c.config, OpUpdateOne, withDepartment(d))\n\treturn &DepartmentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *StatusdClient) UpdateOne(s *Statusd) *StatusdUpdateOne {\n\tmutation := newStatusdMutation(c.config, OpUpdateOne, withStatusd(s))\n\treturn &StatusdUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (a *Adult) Update() *AdultUpdateOne {\n\treturn (&AdultClient{config: a.config}).UpdateOne(a)\n}", "func (c *BeerClient) UpdateOne(b *Beer) *BeerUpdateOne {\n\tmutation := newBeerMutation(c.config, OpUpdateOne, withBeer(b))\n\treturn &BeerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *BuildingClient) UpdateOne(b *Building) *BuildingUpdateOne {\n\tmutation := newBuildingMutation(c.config, OpUpdateOne, withBuilding(b))\n\treturn &BuildingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *FacultyClient) UpdateOne(f *Faculty) *FacultyUpdateOne {\n\tmutation := newFacultyMutation(c.config, OpUpdateOne, withFaculty(f))\n\treturn &FacultyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (b *BidPawnClient) UpdateOne(bidId string, status int, loanStartTime string) bool {\n\tfullPath := fmt.Sprintf(\"%v%v/%v\", b.host, b.path, bidId)\n\tclient := &http.Client{}\n\n\tpayload, _ := json.Marshal(map[string]interface{}{\n\t\t\"status\": status,\n\t\t\"loan_start_time\": loanStartTime,\n\t})\n\tpayloadBytes := bytes.NewBuffer(payload)\n\treq, err := http.NewRequest(http.MethodPatch, fullPath, payloadBytes)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tsb := string(body)\n\tfmt.Println(sb)\n\treturn true\n}", "func (c *ToolClient) UpdateOne(t *Tool) *ToolUpdateOne {\n\tmutation := newToolMutation(c.config, OpUpdateOne, withTool(t))\n\treturn &ToolUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *PharmacistClient) UpdateOne(ph *Pharmacist) *PharmacistUpdateOne {\n\tmutation := newPharmacistMutation(c.config, OpUpdateOne, withPharmacist(ph))\n\treturn &PharmacistUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *BookingClient) UpdateOne(b *Booking) *BookingUpdateOne {\n\tmutation := newBookingMutation(c.config, OpUpdateOne, withBooking(b))\n\treturn &BookingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *ActivitiesClient) UpdateOneID(id int) *ActivitiesUpdateOne {\n\tmutation := newActivitiesMutation(c.config, OpUpdateOne, withActivitiesID(id))\n\treturn &ActivitiesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *ActivityTypeClient) UpdateOneID(id int) *ActivityTypeUpdateOne {\n\tmutation := newActivityTypeMutation(c.config, OpUpdateOne, withActivityTypeID(id))\n\treturn &ActivityTypeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *RoomdetailClient) UpdateOne(r *Roomdetail) *RoomdetailUpdateOne {\n\tmutation := newRoomdetailMutation(c.config, OpUpdateOne, withRoomdetail(r))\n\treturn &RoomdetailUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (t *Task) Update() *TaskUpdateOne {\n\treturn NewTaskClient(t.config).UpdateOne(t)\n}", "func (c *OperativeClient) UpdateOne(o *Operative) *OperativeUpdateOne {\n\tmutation := newOperativeMutation(c.config, OpUpdateOne, withOperative(o))\n\treturn &OperativeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func updateSingleRecord(conf *Configuration, v interface{}, c *mgo.Collection) {\n\tresultv := reflect.ValueOf(v)\n\tif resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Struct {\n\t\tlog.Printf(\"Not updated. Record is not a pointer to a struct %v\", v)\n\t\treturn\n\t}\n\tid := resultv.Elem().FieldByName(\"Id\")\n\tif id.IsValid() {\n\t\toid := internal.ObjectIdFromString(id.String())\n\t\tc.UpdateId(oid, bson.M{\"$set\": bson.M{conf.StateFld: conf.ProcessedState, conf.ProcessedTimeFld: time.Now().Unix()}})\n\t} else {\n\t\tlog.Printf(\"Not updated. Struct doesn't have an ID field %v\", v)\n\t}\n}", "func (c *ClubapplicationClient) UpdateOne(cl *Clubapplication) *ClubapplicationUpdateOne {\n\tmutation := newClubapplicationMutation(c.config, OpUpdateOne, withClubapplication(cl))\n\treturn &ClubapplicationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *AnnotationClient) UpdateOne(a *Annotation) *AnnotationUpdateOne {\n\tmutation := newAnnotationMutation(c.config, OpUpdateOne, withAnnotation(a))\n\treturn &AnnotationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *PostImageClient) UpdateOne(pi *PostImage) *PostImageUpdateOne {\n\tmutation := newPostImageMutation(c.config, OpUpdateOne, withPostImage(pi))\n\treturn &PostImageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *EatinghistoryClient) UpdateOne(e *Eatinghistory) *EatinghistoryUpdateOne {\n\tmutation := newEatinghistoryMutation(c.config, OpUpdateOne, withEatinghistory(e))\n\treturn &EatinghistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *StatustClient) UpdateOne(s *Statust) *StatustUpdateOne {\n\tmutation := newStatustMutation(c.config, OpUpdateOne, withStatust(s))\n\treturn &StatustUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (xpss *XPipelineSalesStage) Update(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !xpss._exists {\n\t\treturn errors.New(\"update failed: does not exist\")\n\t}\n\n\t// if deleted, bail\n\tif xpss._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\t// sql query\n\tconst sqlstr = `UPDATE x_showroom.x_pipeline_sales_stages SET ` +\n\t\t`name = ?, probability = ?, seq_num = ?, active_flag = ?, sales_method_id = ?, created_by = ?, updated_by = ?, created_at = ?, updated_at = ?` +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, xpss.Name, xpss.Probability, xpss.SeqNum, xpss.ActiveFlag, xpss.SalesMethodID, xpss.CreatedBy, xpss.UpdatedBy, xpss.CreatedAt, xpss.UpdatedAt, xpss.ID)\n\t_, err = db.Exec(sqlstr, xpss.Name, xpss.Probability, xpss.SeqNum, xpss.ActiveFlag, xpss.SalesMethodID, xpss.CreatedBy, xpss.UpdatedBy, xpss.CreatedAt, xpss.UpdatedAt, xpss.ID)\n\treturn err\n}", "func (c *PositionInPharmacistClient) UpdateOne(pip *PositionInPharmacist) *PositionInPharmacistUpdateOne {\n\tmutation := newPositionInPharmacistMutation(c.config, OpUpdateOne, withPositionInPharmacist(pip))\n\treturn &PositionInPharmacistUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *MealplanClient) UpdateOne(m *Mealplan) *MealplanUpdateOne {\n\tmutation := newMealplanMutation(c.config, OpUpdateOne, withMealplan(m))\n\treturn &MealplanUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *PatientInfoClient) UpdateOne(pi *PatientInfo) *PatientInfoUpdateOne {\n\tmutation := newPatientInfoMutation(c.config, OpUpdateOne, withPatientInfo(pi))\n\treturn &PatientInfoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *SituationClient) UpdateOne(s *Situation) *SituationUpdateOne {\n\tmutation := newSituationMutation(c.config, OpUpdateOne, withSituation(s))\n\treturn &SituationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UnsavedPostVideoClient) UpdateOneID(id int) *UnsavedPostVideoUpdateOne {\n\tmutation := newUnsavedPostVideoMutation(c.config, OpUpdateOne, withUnsavedPostVideoID(id))\n\treturn &UnsavedPostVideoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *PartorderClient) UpdateOne(pa *Partorder) *PartorderUpdateOne {\n\tmutation := newPartorderMutation(c.config, OpUpdateOne, withPartorder(pa))\n\treturn &PartorderUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *PatientClient) UpdateOne(pa *Patient) *PatientUpdateOne {\n\tmutation := newPatientMutation(c.config, OpUpdateOne, withPatient(pa))\n\treturn &PatientUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *PatientClient) UpdateOne(pa *Patient) *PatientUpdateOne {\n\tmutation := newPatientMutation(c.config, OpUpdateOne, withPatient(pa))\n\treturn &PatientUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *PatientClient) UpdateOne(pa *Patient) *PatientUpdateOne {\n\tmutation := newPatientMutation(c.config, OpUpdateOne, withPatient(pa))\n\treturn &PatientUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func handleActivityUpdate(w http.ResponseWriter, r *http.Request) {\r\n\t//[TODO: query param approach is not the effecient way to handle, as the parameters values in the url are visible to anyone,a nd it could pose security issues. so, need to explore the way in which we can pass the values as part of the HTTP header/body instead of URL]\r\n\ti := strings.Index(r.RequestURI, \"?\") // since url.ParseQuery is not able to retrieve the first key (of the query string) correctly, find the position of ? in the url and\r\n\tqs := r.RequestURI[i+1 : len(r.RequestURI)] // substring it and then\r\n\r\n\tm, _ := url.ParseQuery(qs) // parse it\r\n\tc := appengine.NewContext(r)\r\n\r\n\terr := helpers.UpdateActivity(c, m[\"ActivityName\"][0], m[\"StartTime\"][0], m[\"Status\"][0], m[\"NewStatus\"][0])\r\n\r\n\tif err != nil {\r\n\t\thttp.Error(w, \"Error while changing the status: \"+err.Error(), http.StatusInternalServerError)\r\n\t\treturn\r\n\t}\r\n\r\n\thttp.Redirect(w, r, \"/\", http.StatusFound)\r\n}", "func (auo *AnnouncementUpdateOne) Save(ctx context.Context) (*Announcement, error) {\n\tif v, ok := auo.mutation.Title(); ok {\n\t\tif err := announcement.TitleValidator(v); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ent: validator failed for field \\\"title\\\": %v\", err)\n\t\t}\n\t}\n\tif v, ok := auo.mutation.Description(); ok {\n\t\tif err := announcement.DescriptionValidator(v); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ent: validator failed for field \\\"description\\\": %v\", err)\n\t\t}\n\t}\n\tif v, ok := auo.mutation.Time(); ok {\n\t\tif err := announcement.TimeValidator(v); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ent: validator failed for field \\\"time\\\": %v\", err)\n\t\t}\n\t}\n\n\tvar (\n\t\terr error\n\t\tnode *Announcement\n\t)\n\tif len(auo.hooks) == 0 {\n\t\tnode, err = auo.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*AnnouncementMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tauo.mutation = mutation\n\t\t\tnode, err = auo.sqlSave(ctx)\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(auo.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = auo.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, auo.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (repo *mongoBaseRepo) UpdateOne(filter interface{}, update interface{}, args ...interface{}) error {\n\ttimeout := DefaultTimeout\n\topts := &options.UpdateOptions{}\n\tvar authUser interface{}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tswitch val := args[i].(type) {\n\t\tcase time.Duration:\n\t\t\ttimeout = val\n\t\tcase *options.UpdateOptions:\n\t\t\topts = val\n\t\tcase *AuditAuth:\n\t\t\tauthUser = val.User\n\t\t}\n\t}\n\n\tif repo.locale != nil && opts.Collation == nil {\n\t\topts.SetCollation(&options.Collation{\n\t\t\tLocale: *repo.locale,\n\t\t})\n\t}\n\n\tif authUser != nil && repo.audit != nil && repo.audit.IsActive() {\n\t\t// When audit then save doc before update for compare\n\t\tvar beforeUpdate bson.M\n\t\tif err := repo.FindOne(filter, &beforeUpdate); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\n\t\t// Find and update doc save doc after updated\n\t\tfoaOpts := &options.FindOneAndUpdateOptions{}\n\t\tfoaOpts.SetReturnDocument(options.After)\n\t\tvar afterUpdate bson.M\n\t\tif err := repo.collection.FindOneAndUpdate(ctx, filter, update, foaOpts).Decode(&afterUpdate); err != nil {\n\t\t\tif errors.Is(err, mongo.ErrNoDocuments) {\n\t\t\t\treturn ErrNotFound\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\t// Audit only is updated\n\t\tif !cmp.Equal(beforeUpdate, afterUpdate) {\n\t\t\t// Send to audit\n\t\t\trepo.audit.Send(bson.M{\n\t\t\t\t\"collection\": repo.collection.Name(),\n\t\t\t\t\"action\": Update,\n\t\t\t\t\"user\": authUser,\n\t\t\t\t\"data\": afterUpdate,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Without audit can simple update\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\t// Simple update doc\n\tres, err := repo.collection.UpdateOne(ctx, filter, update, opts)\n\n\tif res != nil && res.MatchedCount == 0 {\n\t\t//return NewNotFoundError()\n\t\treturn ErrNotFound\n\t}\n\n\treturn err\n}", "func (c *DoctorClient) UpdateOne(d *Doctor) *DoctorUpdateOne {\n\tmutation := newDoctorMutation(c.config, OpUpdateOne, withDoctor(d))\n\treturn &DoctorUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (muo *MannerUpdateOne) Exec(ctx context.Context) error {\n\t_, err := muo.Save(ctx)\n\treturn err\n}", "func (c *OperativerecordClient) UpdateOne(o *Operativerecord) *OperativerecordUpdateOne {\n\tmutation := newOperativerecordMutation(c.config, OpUpdateOne, withOperativerecord(o))\n\treturn &OperativerecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (a *App) update(c *echo.Context) error {\n\tid := c.Param(\"id\")\n\ttask := &model.Task{}\n\tif a.GetDB().First(task, id) != nil {\n\t\terr := errors.New(\"Task is not found.\")\n\t\tc.JSON(http.StatusNotFound, ErrorMsg{Msg: err.Error()})\n\t\treturn err\n\t}\n\tstatus, err := task.Update(a.GetDB(), c)\n\tif err == nil {\n\t\tc.JSON(status, task)\n\t} else {\n\t\tc.JSON(status, ErrorMsg{Msg: err.Error()})\n\t}\n\treturn err\n}", "func (po *Pointpendingkyctransaction) Update() *PointpendingkyctransactionUpdateOne {\n\treturn (&PointpendingkyctransactionClient{config: po.config}).UpdateOne(po)\n}", "func (t *Training) Update() *TrainingUpdateOne {\n\treturn (&TrainingClient{config: t.config}).UpdateOne(t)\n}", "func (s *Statusd) Update() *StatusdUpdateOne {\n\treturn (&StatusdClient{config: s.config}).UpdateOne(s)\n}", "func UpdateOne(ctx context.Context, tx pgx.Tx, sb sq.UpdateBuilder) error {\n\tq, vs, err := sb.ToSql()\n\tif err != nil {\n\t\treturn err\n\t}\n\ttag, err := tx.Exec(ctx, q, vs...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tag.RowsAffected() != 1 {\n\t\treturn ErrNoRowsAffected\n\t}\n\treturn nil\n}", "func (c *ComplaintClient) UpdateOne(co *Complaint) *ComplaintUpdateOne {\n\tmutation := newComplaintMutation(c.config, OpUpdateOne, withComplaint(co))\n\treturn &ComplaintUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (m *IndustryDataRunActivity) SetActivity(value IndustryDataActivityable)() {\n err := m.GetBackingStore().Set(\"activity\", value)\n if err != nil {\n panic(err)\n }\n}", "func (fuo *FlowUpdateOne) Exec(ctx context.Context) error {\n\t_, err := fuo.Save(ctx)\n\treturn err\n}", "func (auo *ArticleUpdateOne) Exec(ctx context.Context) error {\n\t_, err := auo.Save(ctx)\n\treturn err\n}", "func (auo *ArticleUpdateOne) Exec(ctx context.Context) error {\n\t_, err := auo.Save(ctx)\n\treturn err\n}", "func (c *TagClient) UpdateOne(t *Tag) *TagUpdateOne {\n\tmutation := newTagMutation(c.config, OpUpdateOne, withTag(t))\n\treturn &TagUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (wuo *WechatUpdateOne) Exec(ctx context.Context) error {\n\t_, err := wuo.Save(ctx)\n\treturn err\n}", "func (c *PartClient) UpdateOne(pa *Part) *PartUpdateOne {\n\tmutation := newPartMutation(c.config, OpUpdateOne, withPart(pa))\n\treturn &PartUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *PetruleClient) UpdateOne(pe *Petrule) *PetruleUpdateOne {\n\tmutation := newPetruleMutation(c.config, OpUpdateOne, withPetrule(pe))\n\treturn &PetruleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *EventClient) UpdateOne(e *Event) *EventUpdateOne {\n\tmutation := newEventMutation(c.config, OpUpdateOne, withEvent(e))\n\treturn &EventUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *UnsavedPostImageClient) UpdateOne(upi *UnsavedPostImage) *UnsavedPostImageUpdateOne {\n\tmutation := newUnsavedPostImageMutation(c.config, OpUpdateOne, withUnsavedPostImage(upi))\n\treturn &UnsavedPostImageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (a *Agentkyc) Update() *AgentkycUpdateOne {\n\treturn (&AgentkycClient{config: a.config}).UpdateOne(a)\n}", "func (c *OperationClient) UpdateOne(o *Operation) *OperationUpdateOne {\n\tmutation := newOperationMutation(c.config, OpUpdateOne, withOperation(o))\n\treturn &OperationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *AdminSessionClient) UpdateOne(as *AdminSession) *AdminSessionUpdateOne {\n\tmutation := newAdminSessionMutation(c.config, OpUpdateOne, withAdminSession(as))\n\treturn &AdminSessionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (puo *PostUpdateOne) Exec(ctx context.Context) error {\n\t_, err := puo.Save(ctx)\n\treturn err\n}", "func (puo *PostUpdateOne) Exec(ctx context.Context) error {\n\t_, err := puo.Save(ctx)\n\treturn err\n}", "func (c *ReviewClient) UpdateOne(r *Review) *ReviewUpdateOne {\n\tmutation := newReviewMutation(c.config, OpUpdateOne, withReview(r))\n\treturn &ReviewUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *StaytypeClient) UpdateOne(s *Staytype) *StaytypeUpdateOne {\n\tmutation := newStaytypeMutation(c.config, OpUpdateOne, withStaytype(s))\n\treturn &StaytypeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func UpdateOne(query interface{}, update interface{}) error {\n\treturn db.Update(Collection, query, update)\n}", "func (rec *SetupStepRecord) Update(db *sql.DB) error {\n var err error\n if nil == rec.Step.Owner {\n _, err = db.Exec(\"UPDATE setup_steps SET done = $1 WHERE session_id = $2 AND setup_rule_id = $3 AND player_id IS NULL\",\n rec.Step.Done, rec.SessionId, rec.Step.Rule.Id)\n } else {\n _, err = db.Exec(\"UPDATE setup_steps SET done = $1 WHERE session_id = $2 AND setup_rule_id = $3 AND player_id = $4\",\n rec.Step.Done, rec.SessionId, rec.Step.Rule.Id, rec.Step.Owner.Id)\n }\n return err\n}", "func (tuo *TeamUpdateOne) Exec(ctx context.Context) error {\n\t_, err := tuo.Save(ctx)\n\treturn err\n}", "func (c *PatientofphysicianClient) UpdateOne(pa *Patientofphysician) *PatientofphysicianUpdateOne {\n\tmutation := newPatientofphysicianMutation(c.config, OpUpdateOne, withPatientofphysician(pa))\n\treturn &PatientofphysicianUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (puo *PatientrecordUpdateOne) Exec(ctx context.Context) error {\n\t_, err := puo.Save(ctx)\n\treturn err\n}" ]
[ "0.6647596", "0.63848096", "0.60485387", "0.6035013", "0.58787274", "0.5838664", "0.58378613", "0.5766803", "0.57484245", "0.5733748", "0.5729118", "0.56673074", "0.5636767", "0.560241", "0.55692375", "0.5568402", "0.5566554", "0.55593145", "0.5557507", "0.5551724", "0.55385077", "0.55376536", "0.5533891", "0.55312055", "0.5527604", "0.5525551", "0.55154175", "0.55059844", "0.54899687", "0.5475566", "0.5447525", "0.54340065", "0.54323494", "0.54238987", "0.5420321", "0.54185236", "0.54091597", "0.539309", "0.539279", "0.5390728", "0.53903157", "0.5382387", "0.5379539", "0.5369834", "0.536964", "0.536523", "0.5362309", "0.5360683", "0.5349147", "0.5347913", "0.5342764", "0.5340552", "0.5337225", "0.53334343", "0.5331351", "0.53274447", "0.5322592", "0.53223515", "0.5321858", "0.5318471", "0.53155476", "0.53105974", "0.5303673", "0.5296962", "0.5296962", "0.5296962", "0.5283359", "0.5281617", "0.52803826", "0.5278296", "0.52708757", "0.5270773", "0.52568454", "0.52450573", "0.52432907", "0.52429646", "0.52426344", "0.5240791", "0.522726", "0.5223778", "0.5216414", "0.5216414", "0.52147496", "0.52085423", "0.5201664", "0.5200471", "0.5197444", "0.51955324", "0.51954645", "0.5189882", "0.5185416", "0.5181871", "0.5181871", "0.5181647", "0.5179236", "0.5176126", "0.51730067", "0.51717436", "0.5169596", "0.5166488" ]
0.7742671
0
FindFullByDay finds all joined activity stages on a day
func (*ActivityStageDataAccessObject) FindFullByDay( date time.Time) []ActivityStageFull { startDate := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.Local) endDate := startDate.AddDate(0, 0, 1) start := startDate.Format(mysqlTimeFormat) end := time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 0, 0, 0, 0, time.Local).Format(mysqlTimeFormat) result := make([]ActivityStageFull, 0) err := orm.Table(ActivityDAO.TableName()). Where("activity_stages.activity_id=activities.id"). Join("INNER", ActivityStageDAO.TableName(), "start_time>=?", start).And("end_time<?", end). Find(&result) logger.LogIfError(err) return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*ActivityStageDataAccessObject) FindFullByMonth(\n\tdate time.Time) [][]ActivityStageFull {\n\n\tstart := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.Local)\n\tend := start.AddDate(0, 1, 0).AddDate(0, 0, -1)\n\tresult := make([][]ActivityStageFull, 0)\n\tfor i := start.Day(); i <= end.Day(); i++ {\n\t\tcurDate := time.Date(date.Year(), date.Month(), i, 0, 0, 0, 0,\n\t\t\ttime.Local)\n\t\tresult = append(result, ActivityStageDAO.FindFullByDay(curDate))\n\t}\n\n\treturn result\n}", "func (*ActivityStageDataAccessObject) FindAll() []ActivityStage {\n\tl := make([]ActivityStage, 0)\n\terr := orm.Table(ActivityStageDAO.TableName()).Find(&l)\n\n\tlogger.LogIfError(err)\n\treturn l\n}", "func (filter TaskReliabilityFilter) BuildMatchStageForTask(boundaries []time.Time) bson.M {\n\tstart := boundaries[0]\n\tend := boundaries[len(boundaries)-1]\n\n\tmatch := bson.M{\n\t\tstats.DbTaskStatsIdDateKeyFull: bson.M{\n\t\t\t\"$lt\": start,\n\t\t\t\"$gte\": end,\n\t\t},\n\t\tstats.DbTestStatsIdProjectKeyFull: filter.Project,\n\t\tstats.DbTestStatsIdRequesterKeyFull: bson.M{\"$in\": filter.Requesters},\n\t}\n\tif len(filter.Tasks) > 0 {\n\t\tmatch[stats.DbTaskStatsIdTaskNameKeyFull] = stats.BuildMatchArrayExpression(filter.Tasks)\n\t}\n\tif len(filter.BuildVariants) > 0 {\n\t\tmatch[stats.DbTaskStatsIdBuildVariantKeyFull] = stats.BuildMatchArrayExpression(filter.BuildVariants)\n\t}\n\tif len(filter.Distros) > 0 {\n\t\tmatch[stats.DbTaskStatsIdDistroKeyFull] = stats.BuildMatchArrayExpression(filter.Distros)\n\t}\n\n\tif filter.StartAt != nil {\n\t\tmatch[\"$or\"] = filter.BuildTaskPaginationOrBranches()\n\t}\n\n\treturn bson.M{\"$match\": match}\n}", "func ParseDateRangeFullDay(vars map[string]string) (startDate time.Time, endDate time.Time, err error) {\n\tstartDate, endDate, err = ParseDateRange(vars)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// set time to beginning of day\n\tstartDate = time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 0, 0,\n\t\t0, 0, time.Local)\n\t// set the time to the end of day\n\tendDate = time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 23, 59,\n\t\t59, 1000, time.Local)\n\treturn\n}", "func (filter TaskReliabilityFilter) buildMatchStageForTask() bson.M {\n\tboundaries := filter.dateBoundaries()\n\n\tstart := boundaries[0]\n\tend := boundaries[len(boundaries)-1]\n\n\tmatch := bson.M{\n\t\ttaskstats.DBTaskStatsIDDateKeyFull: bson.M{\n\t\t\t\"$lt\": start,\n\t\t\t\"$gte\": end,\n\t\t},\n\t\ttaskstats.DBTaskStatsIDProjectKeyFull: filter.Project,\n\t\ttaskstats.DBTaskStatsIDRequesterKeyFull: bson.M{\"$in\": filter.Requesters},\n\t}\n\tif len(filter.Tasks) > 0 {\n\t\tmatch[taskstats.DBTaskStatsIDTaskNameKeyFull] = taskstats.BuildMatchArrayExpression(filter.Tasks)\n\t}\n\tif len(filter.BuildVariants) > 0 {\n\t\tmatch[taskstats.DBTaskStatsIDBuildVariantKeyFull] = taskstats.BuildMatchArrayExpression(filter.BuildVariants)\n\t}\n\tif len(filter.Distros) > 0 {\n\t\tmatch[taskstats.DBTaskStatsIDDistroKeyFull] = taskstats.BuildMatchArrayExpression(filter.Distros)\n\t}\n\n\tif filter.StartAt != nil {\n\t\tmatch[\"$or\"] = filter.buildTaskPaginationOrBranches()\n\t}\n\treturn bson.M{\"$match\": match}\n}", "func generateTimeFilterStage(rangeInitDays, rangeEndDays int) []bson.M {\n\treturn []bson.M{\n\t\tbson.M{\n\t\t\t\"$match\": bson.M{\n\t\t\t\t\"finishedAt\": bson.M{\n\t\t\t\t\t\"$gte\": util.BeginningOfTheDay(time.Now().AddDate(0, 0, rangeInitDays)),\n\t\t\t\t\t\"$lte\": util.EndOfTheDay(time.Now().AddDate(0, 0, rangeEndDays)),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func DailyServiceFlavor(filter bson.M) []bson.M {\n\tquery := []bson.M{\n\t\t{\"$match\": filter},\n\t\t{\"$group\": bson.M{\n\t\t\t\"_id\": bson.M{\n\t\t\t\t\"date\": bson.D{{\"$substr\", list{\"$date\", 0, 8}}},\n\t\t\t\t\"name\": \"$name\",\n\t\t\t\t\"supergroup\": \"$supergroup\",\n\t\t\t\t\"availability\": \"$availability\",\n\t\t\t\t\"reliability\": \"$reliability\",\n\t\t\t\t\"unknown\": \"$unknown\",\n\t\t\t\t\"up\": \"$up\",\n\t\t\t\t\"down\": \"$down\",\n\t\t\t\t\"report\": \"$report\"}}},\n\t\t{\"$project\": bson.M{\n\t\t\t\"date\": \"$_id.date\",\n\t\t\t\"name\": \"$_id.name\",\n\t\t\t\"availability\": \"$_id.availability\",\n\t\t\t\"reliability\": \"$_id.reliability\",\n\t\t\t\"unknown\": \"$_id.unknown\",\n\t\t\t\"up\": \"$_id.up\",\n\t\t\t\"down\": \"$_id.down\",\n\t\t\t\"supergroup\": \"$_id.supergroup\",\n\t\t\t\"report\": \"$_id.report\"}},\n\t\t{\"$sort\": bson.D{\n\t\t\t{\"supergroup\", 1},\n\t\t\t{\"name\", 1},\n\t\t\t{\"date\", 1}}}}\n\n\treturn query\n}", "func (s *TimerService) GetCompletedTasksForDay(year int, month time.Month, day int, user *models.TeamUser) ([]*models.TaskAggregation, error) {\n\t//log.Printf(\"GetCompletedTasksForDay, Year: %d, Month: %d, Day: %d\", year, month, day)\n\n\ttzOffset := user.SlackUserInfo.TZOffset\n\t//log.Printf(\"GetCompletedTasksForDay, tzOffset: %d\", tzOffset)\n\n\tstartDate := time.Date(year, month, day, 0, 0, 0, 0, time.UTC).Add(time.Duration(tzOffset) * time.Second * -1)\n\tendDate := time.Date(year, month, day, 23, 59, 59, 0, time.UTC).Add(time.Duration(tzOffset) * time.Second * -1)\n\n\t//log.Printf(\"GetCompletedTasksForDay, startDate: %+v\", startDate)\n\t//log.Printf(\"GetCompletedTasksForDay, endDate: %+v\", endDate)\n\n\ttasks, err := s.repository.completedTasksForUser(user.ID.Hex(), startDate, endDate)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tasks, nil\n}", "func AllGameEnded() []Game_Detail {\n\torm := get_DBFront()\n\tvar allGame, allEndedGame []Game_Detail\n\terr := orm.SetTable(\"game\").FindAll(&allGame)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_358\", err})\n\t\treturn allGame\n\t}\n\n\tfor _, v := range allGame {\n\t\tif v.Isover == 1 {\n\t\t\tallEndedGame = append(allEndedGame, v)\n\t\t}\n\t}\n\n\tSliceReverse(allEndedGame)\n\treturn allEndedGame\n}", "func (*ActivityStageDataAccessObject) FindByAID(aid int) []ActivityStage {\n\tl := make([]ActivityStage, 0)\n\terr := orm.Table(ActivityStageDAO.TableName()).Where(\"activity_id=?\", aid).\n\t\tFind(&l)\n\t\n\tlogger.LogIfError(err)\n\treturn l\n}", "func GetMemberCtByDay() ([]*Event, error) {\n\tdb, err := getDB()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar events []*Event\n\trows, err := db.Query(\"select name, date, count(attendance.member_id) from event join attendance on (attendance.event_id = event.event_id) group by name, date\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\te := Event{}\n\t\t// something funky here where we overwrite the member info each time, but thats okay\n\t\tif err := rows.Scan(&e.Name, &e.Date, &e.Attendees); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tevents = append(events, &e)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn events, nil\n}", "func findBuildStageDurations(stepId string, builds []*cloudbuild.Build) ([]time.Duration, error) {\n\tdurations := []time.Duration{}\n\tfor _, b := range builds {\n\t\tfor _, bs := range b.Steps {\n\t\t\tif bs.Id != stepId || bs.Status != successStatus {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tparsedStartTime, err := time.Parse(time.RFC3339Nano, bs.Timing.StartTime)\n\t\t\tif err != nil {\n\t\t\t\treturn []time.Duration{}, err\n\t\t\t}\n\t\t\tparsedEndTime, err := time.Parse(time.RFC3339Nano, bs.Timing.EndTime)\n\t\t\tif err != nil {\n\t\t\t\treturn []time.Duration{}, err\n\t\t\t}\n\t\t\tdurations = append(durations, parsedEndTime.Sub(parsedStartTime).Truncate(time.Second))\n\t\t}\n\t}\n\treturn durations, nil\n}", "func (r *MemoryRepo) GetDayEvents(date time.Time) ([]Event, error) {\n\treturn r.getEventsInRange(date, date.AddDate(0, 0, 1))\n}", "func (m *Manager) FindChannelAdActive() ([]ChannelAdD, error) {\n\tres := []ChannelAdD{}\n\t_, err := m.GetDbMap().Select(\n\t\t&res,\n\t\tfmt.Sprintf(\"SELECT %[1]s.*,%[2]s.cli_message_id AS cli_message_ad,%[2]s.promote_data,%[2]s.src, \"+\n\t\t\t\"%[3]s.view AS plan_view,%[3]s.position AS plan_position\"+\n\t\t\t\" FROM %[1]s INNER JOIN %[2]s ON %[2]s.id=%[1]s.ad_id \"+\n\t\t\t\" INNER JOIN %[3]s ON %[3]s.id=%[2]s.plan_id \"+\n\t\t\t\" AND %[1]s.active='yes' \"+\n\t\t\t\" AND %[2]s.active_status='yes' \"+\n\t\t\t\" AND end IS NULL\",\n\t\t\tChannelAdTableFull,\n\t\t\tAdTableFull,\n\t\t\tPlanTableFull,\n\t\t),\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func getSearchQueryDay(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\n\tt, err := time.Parse(\"2006-01-02\", vars[\"date\"])\n\tif err != nil {\n\t\tlog.Printf(\"getSearchQueryDay Handler: time.Parse(%s): %s\\n\", vars[\"date\"], err.Error())\n\t\thandleError(w, http.StatusBadRequest, \"Bad request\")\n\t\treturn\n\t}\n\n\tloc, _ := time.LoadLocation(\"Europe/Vienna\")\n\tsince := time.Date(\n\t\tt.Year(),\n\t\tt.Month(),\n\t\tt.Day(),\n\t\t0, 0, 0, 0,\n\t\tloc,\n\t)\n\tuntil := time.Date(\n\t\tt.Year(),\n\t\tt.Month(),\n\t\tt.Day(),\n\t\t23, 59, 59, 0,\n\t\tloc,\n\t)\n\n\ttracks, err := conf.DS.GetSearchResult(strings.Replace(vars[\"query\"], \"+\", \",\", -1), since, until)\n\tif err != nil {\n\t\tlog.Printf(\"getSearchQueryDay Handler: GetSearchResult(%s, %q, %q): %s\\n\",\n\t\t\tstrings.Replace(vars[\"query\"], \"+\", \",\", -1), since, until, err.Error())\n\t\thandleError(w, http.StatusInternalServerError, \"Internal server error\")\n\t\treturn\n\t}\n\n\tresp, err := orderSearchResults(tracks, since, time.Time{}, 0)\n\tif err != nil {\n\t\tlog.Printf(\"getSearchQueryWeek Handler: orderSearchResults(%q, %q, %q, %d): %s\\n\",\n\t\t\ttracks, since, time.Time{}, 0, err.Error())\n\t\thandleError(w, http.StatusInternalServerError, \"Internal server error\")\n\t\treturn\n\t}\n\n\tj, err := jsonMarshal(resp)\n\tif err != nil {\n\t\tlog.Printf(\"getSearchQueryWeek Handler: %s\\n\", err.Error())\n\t\thandleError(w, http.StatusInternalServerError, \"Internal server error\")\n\t\treturn\n\t}\n\twriteJSONResponse(w, j)\n}", "func FindActivityLog(ctx context.Context, exec boil.ContextExecutor, iD int64, selectCols ...string) (*ActivityLog, error) {\n\tactivityLogObj := &ActivityLog{}\n\n\tsel := \"*\"\n\tif len(selectCols) > 0 {\n\t\tsel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), \",\")\n\t}\n\tquery := fmt.Sprintf(\n\t\t\"select %s from \\\"activity_logs\\\" where \\\"id\\\"=?\", sel,\n\t)\n\n\tq := queries.Raw(query, iD)\n\n\terr := q.Bind(ctx, exec, activityLogObj)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"dbmodel: unable to select from activity_logs\")\n\t}\n\n\treturn activityLogObj, nil\n}", "func (s *JobDB) GetJobsByDay(weekday time.Weekday) []BusInfoJob {\n\tjobsOnDay := []BusInfoJob{}\n\n\tdb, err := bolt.Open(s.dbFile, 0600, nil)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer db.Close()\n\n\terr = db.View(func(tx *bolt.Tx) error {\n\n\t\tchatIDs := s.getChatIDsByDay(weekday, tx)\n\n\t\tif len(chatIDs) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tfor _, chatID := range chatIDs {\n\t\t\tuserJobsOnDay := s.getJobsByChatIDandDay(chatID, weekday, tx)\n\t\t\tif len(userJobsOnDay) == 0 {\n\t\t\t\tlog.Panicln(\"Desync of information between the two buckets\")\n\t\t\t}\n\t\t\tjobsOnDay = append(jobsOnDay, userJobsOnDay...)\n\t\t}\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\treturn jobsOnDay\n}", "func (ads *ArticleDS) QueryTagSummaryForDay(tag string, pd time.Time) (*articles.TagSummary, error) {\n\ttags := []string{tag}\n\ttagSumy := &articles.TagSummary{Tag: tag}\n\n\tqRelArtStmt := `SELECT ARRAY(\n\t\tSELECT id FROM articles.article WHERE $1 <@ tags AND publish_date = $2::date ORDER BY created_on DESC LIMIT 10\n\t\t)`\n\tqRelTagsStmt := `select ARTICLES.ARRAY_DISTINCT_MINUS(\n\t\tARRAY(SELECT UNNEST(tags) FROM articles.article WHERE $1 <@ tags AND publish_date = $2::date ORDER BY created_on DESC LIMIT 10), $1\n\t\t)`\n\n\tdb := ads.db\n\n\terr := db.QueryRow(qRelArtStmt, pq.Array(tags), pd).Scan(pq.Array(&tagSumy.ArticleIDs))\n\tif err != nil || len(tagSumy.ArticleIDs) == 0 {\n\t\treturn nil, status.ErrNotFound\n\t}\n\terr = db.QueryRow(qRelTagsStmt, pq.Array(tags), pd).Scan(pq.Array(&tagSumy.RelatedTags))\n\tif err != nil {\n\t\treturn nil, status.ErrNotFound.WithMessage(err.Error())\n\t}\n\ttagSumy.Count = len(tagSumy.ArticleIDs)\n\treturn tagSumy, nil\n}", "func createGameDayReport(date string) (*gameDayReport, error) {\n\tmatches, err := findMatchesByGameDateID(date)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(matches) == 0 {\n\t\treturn nil, fmt.Errorf(\"no matches found for date %s\", date)\n\t}\n\n\treportGames := make(map[int64]gameReport)\n\tfor _, game := range matches {\n\t\tgameReport := gameReport{\n\t\t\tHomeTeam: game.HomeTeam,\n\t\t\tAwayTeam: game.AwayTeam,\n\t\t\tVenue: game.Venue,\n\t\t\tDate: game.StartDate,\n\t\t}\n\n\t\treportGames[game.ID] = gameReport\n\t}\n\n\treport := gameDayReport{\n\t\tID: date,\n\t\tGames: reportGames,\n\t\tDeadline: matches[0].StartDate,\n\t\tEvaluated: false,\n\t}\n\n\terr = upsertGameDayReport(report)\n\treturn &report, err\n}", "func (r CompetitionFixturesRequest) Matchday(matchday uint16) CompetitionFixturesRequest {\n\tr.urlValues.Set(\"matchday\", fmt.Sprintf(\"%d\", matchday))\n\treturn r\n}", "func createMeetingFixtures_FindByTime(ms *ModelSuite) Meetings {\n\tuf := createUserFixtures(ms.DB, 1)\n\tusers := uf.Users\n\n\tlocations := make(Locations, 4)\n\tfor i := range locations {\n\t\tcreateFixture(ms, &locations[i])\n\t}\n\n\tmeetings := Meetings{\n\t\t{\n\t\t\tCreatedByID: users[0].ID,\n\t\t\tName: \"Mtg Past\",\n\t\t\tLocationID: locations[0].ID,\n\n\t\t\tStartDate: time.Now().Add(-domain.DurationWeek * 10),\n\t\t\tEndDate: time.Now().Add(-domain.DurationWeek * 8),\n\t\t},\n\t\t{\n\t\t\tCreatedByID: users[0].ID,\n\t\t\tName: \"Mtg Recent\",\n\t\t\tLocationID: locations[1].ID,\n\n\t\t\tStartDate: time.Now().Add(-domain.DurationWeek * 4),\n\t\t\tEndDate: time.Now().Add(-domain.DurationWeek * 2),\n\t\t},\n\t\t{\n\t\t\tCreatedByID: users[0].ID,\n\t\t\tName: \"Mtg Now\",\n\t\t\tLocationID: locations[2].ID,\n\t\t\tStartDate: time.Now().Add(-domain.DurationWeek * 2),\n\t\t\tEndDate: time.Now().Add(domain.DurationWeek * 2),\n\t\t},\n\t\t{\n\t\t\tCreatedByID: users[0].ID,\n\t\t\tName: \"Mtg Future\",\n\t\t\tLocationID: locations[3].ID,\n\t\t\tStartDate: time.Now().Add(domain.DurationWeek * 2),\n\t\t\tEndDate: time.Now().Add(domain.DurationWeek * 4),\n\t\t},\n\t}\n\n\tfor i := range meetings {\n\t\tmeetings[i].UUID = domain.GetUUID()\n\t\tcreateFixture(ms, &meetings[i])\n\t}\n\treturn meetings\n}", "func DailyEndpointGroup(filter bson.M) []bson.M {\n\t// Mongo aggregation pipeline\n\t// Select all the records that match q\n\t// Project to select just the first 8 digits of the date YYYYMMDD\n\t// Sort by profile->supergroup->endpointGroup->datetime\n\tquery := []bson.M{\n\t\t{\"$match\": filter},\n\t\t{\"$project\": bson.M{\n\t\t\t\"date\": bson.M{\"$substr\": list{\"$date\", 0, 8}},\n\t\t\t\"availability\": 1,\n\t\t\t\"reliability\": 1,\n\t\t\t\"unknown\": 1,\n\t\t\t\"up\": 1,\n\t\t\t\"down\": 1,\n\t\t\t\"report\": 1,\n\t\t\t\"supergroup\": 1,\n\t\t\t\"name\": 1}},\n\t\t{\"$sort\": bson.D{\n\t\t\t{\"report\", 1},\n\t\t\t{\"supergroup\", 1},\n\t\t\t{\"name\", 1},\n\t\t\t{\"date\", 1}}}}\n\n\treturn query\n}", "func (m *DayMutation) Day() (r string, exists bool) {\n\tv := m._Day\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func TodayStat(startTime time.Time, n int) ([]*model.SumStat, error) {\n\tvar debug_print_time = false\n\n\tvar conn *sql.DB\n\tvar stmt *sql.Stmt\n\tvar err error\n\tif conn, err = db.Connect(); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\n\tstartTime = startTime.UTC().Truncate(time.Hour*24).AddDate(0, 0, 1)\n\tendTime := startTime.AddDate(0, 0, -n).Truncate(time.Hour * 24)\n\tif debug_print_time {\n\t\tfmt.Println(\"((((())))) ---- start time:\", startTime)\n\t\tfmt.Println(\"((((())))) ---- end time:\", endTime)\n\t}\n\n\t// 这个sql会自动将时间转换为utc时间进行搜索。因此传入的时间无需转换时区。\n\t_sql := `\nselect DATE_FORMAT(o.create_time, '%Y-%m-%d') as 'date', \n count(distinct o.track_number) as 'norder',\n sum(od.quantity) as 'nsold',\n sum(od.quantity * od.selling_price) as '总价' ` +\n\t\t\"from `order` o \" + `\n right join order_detail od on o.track_number = od.order_track_number\nwhere\n o.create_time<?\n and o.create_time >= ?\n and DATEDIFF(o.create_time,?) > ?\n and o.type in (?,?)\n and o.status in (?,?,?,?)\n and od.product_id<>?\ngroup by DATEDIFF(o.create_time,?)\norder by DATEDIFF(o.create_time,?) asc\n`\n\tif stmt, err = conn.Prepare(_sql); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer stmt.Close()\n\n\t// now := time.Now()\n\trows, err := stmt.Query(\n\t\tstartTime,\n\t\tendTime,\n\t\tstartTime, -n,\n\t\tmodel.Wholesale, model.SubOrder, // model.ShippingInstead, // 查子订单\n\t\t\"toprint\", \"todeliver\", \"delivering\", \"done\",\n\t\tbase.STAT_EXCLUDED_PRODUCT,\n\t\tstartTime,\n\t\tstartTime,\n\t)\n\tif db.Err(err) {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close() // db.CloseRows(rows) // use db.CloseRows or rows.Close()? Is rows always nun-nil?\n\n\t// the final result\n\tps := []*model.SumStat{}\n\tfor rows.Next() {\n\t\tp := new(model.SumStat)\n\t\trows.Scan(&p.Id, &p.NOrder, &p.NSold, &p.TotalPrice)\n\n\t\t// update average.\n\t\tp.AvgPrice = p.TotalPrice / float64(p.NSold)\n\n\t\tps = append(ps, p)\n\t}\n\treturn ps, nil\n}", "func (db *Db) Activities() ([]*Activity, error) {\n\tactivities := []*Activity{}\n\n\t//query := \"SELECT * FROM sport_summary ORDER BY start_time DESC;\"\n\tquery := \"SELECT sport_summary.*, Group_Concat(latitude || ',' || longitude, '|') AS points FROM sport_summary LEFT JOIN location_data ON sport_summary.track_id=location_data.track_id GROUP BY sport_summary.track_id ORDER BY location_data.timestamp ASC;\"\n\n\trows, err := db.connection.Query(query)\n\tif err != nil {\n\t\treturn activities, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tactivity := &Activity{}\n\n\t\t//err = rows.Scan(StructForScan(&activity)...)\n\t\terr = rows.Scan(&activity.Id, &activity.Type, &activity.Parent,\n\t\t\t&activity.StartTime, &activity.EndTime, &activity.Calories,\n\t\t\t&activity.CurrentStatus, &activity.ContentJSON, &activity.PointsData)\n\t\tif err != nil {\n\t\t\treturn activities, err\n\t\t}\n\n\t\tactivity.ParseContent()\n\n\t\t// Fetch activity points\n\t\tquery = \"SELECT latitude || ',' || longitude FROM location_data WHERE track_id=\" + strconv.Itoa(activity.Id) + \" ORDER BY timestamp ASC\"\n\t\tpointRows, err := db.connection.Query(query)\n\t\tif err != nil {\n\t\t\treturn activities, err\n\t\t}\n\t\tdefer pointRows.Close()\n\n\t\tpoints := []string{}\n\t\tvar point string\n\t\tfor pointRows.Next() {\n\t\t\terr = pointRows.Scan(&point)\n\t\t\tif err != nil {\n\t\t\t\tpanic(\"Couldn't parse point from database: \" + err.Error())\n\t\t\t}\n\t\t\tpoints = append(points, point)\n\t\t}\n\t\terr = pointRows.Err()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tactivity.PointsData = strings.Join(points, \"|\")\n\n\t\tactivities = append(activities, activity)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn activities, err\n\t}\n\n\treturn activities, nil\n}", "func (c *Client) FindCrmStages(criteria *Criteria, options *Options) (*CrmStages, error) {\n\tcss := &CrmStages{}\n\tif err := c.SearchRead(CrmStageModel, criteria, options, css); err != nil {\n\t\treturn nil, err\n\t}\n\treturn css, nil\n}", "func (db *Service) FindAll(\n\tsc datatype.ServiceContainer,\n\tuser *datatype.User,\n\ttimelineFilter datatype.TimelineFilter,\n\toffset int,\n\tlimit int,\n) ([]datatype.TimelineEntry, bool, error) {\n\tresult := []datatype.TimelineEntry{}\n\tvar clause string\n\tif timelineFilter.Type == datatype.HOMETIMELINE {\n\t\tclause = \"WHERE b.status=1\"\n\t} else if timelineFilter.Type == datatype.ASSETTIMELINE {\n\t\tclause = fmt.Sprintf(\n\t\t\t\" WHERE b.status<>%d AND asset.id = %d\",\n\t\t\tdatatype.BlockRejected,\n\t\t\ttimelineFilter.AssetID,\n\t\t)\n\t} else if timelineFilter.Type == datatype.USERTIMELINE {\n\t\tclause = fmt.Sprintf(\n\t\t\t\" WHERE b.status<>%d AND (doer.id = %d OR oracle.id = %d)\",\n\t\t\tdatatype.BlockRejected,\n\t\t\ttimelineFilter.UserID,\n\t\t\ttimelineFilter.UserID,\n\t\t)\n\t}\n\trows, err := db.Query(fmt.Sprintf(`\n\t\t\tSELECT\n\t\t\t\tb.id,\n\t\t\t\tb.userId,\n\t\t\t\tdoer.username,\n\t\t\t\tdoer.profileImageUrl,\n\t\t\t\tasset.id,\n\t\t\t\tasset.name,\n\t\t\t\tasset.symbol,\n\t\t\t\toracle.id,\n\t\t\t\toracle.username,\n\t\t\t\tb.text,\n\t\t\t\tb.status,\n\t\t\t\tb.ethereumTransactionAddress,\n\t\t\t\tb.videoID,\n\t\t\t\tb.favoritesCounter,\n\t\t\t\tb.createdAt,\n\t\t\t\tIF(favorites.blockId, TRUE, FALSE),\n\t\t\t\tIF(asset_favorites.assetId, TRUE, FALSE) as following\n\t\t\tFROM asset_block b\n\t\t\tLEFT JOIN asset asset ON b.assetId=asset.Id\n\t\t\tLEFT JOIN user doer ON doer.id=b.userId\n\t\t\tLEFT JOIN user oracle ON oracle.id=asset.creatorId\n\t\t\tLEFT JOIN asset_block_favorites favorites ON b.id=favorites.blockId AND favorites.userId=?\n\t\t\tLEFT JOIN asset_favorites ON asset.id=asset_favorites.assetId AND asset_favorites.userId=?\n\t\t\t%s\n\t\t\tORDER BY b.createdAt DESC\n\t\t\tLIMIT ? OFFSET ?\n\t\t\t`, clause), user.ID, user.ID, limit+1, offset)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar c datatype.TimelineEntry\n\t\terr := rows.Scan(\n\t\t\t&c.BlockID,\n\t\t\t&c.UserID,\n\t\t\t&c.UserName,\n\t\t\t&c.UserProfileImageURL,\n\t\t\t&c.AssetID,\n\t\t\t&c.AssetName,\n\t\t\t&c.AssetSymbol,\n\t\t\t&c.OracleID,\n\t\t\t&c.OracleName,\n\t\t\t&c.Text,\n\t\t\t&c.Status,\n\t\t\t&c.EthereumTransactionAddress,\n\t\t\t&c.YtVideoID,\n\t\t\t&c.FavoritesCount,\n\t\t\t&c.CreatedAt,\n\t\t\t&c.DidUserLike,\n\t\t\t&c.DidUserLikeTopic,\n\t\t)\n\t\tif timelineFilter.Type == datatype.HOMETIMELINE && c.DidUserLikeTopic == false {\n\t\t\tcontinue\n\t\t}\n\t\tc.CreatedAtHuman = helpers.DateToHuman(c.CreatedAt)\n\t\tif err != nil {\n\t\t\tapperrors.Critical(\"timelineservice:find-all:1\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\t// TODO optimize fetching images, bring all images for all at once,\n\t\t// not query for each entry\n\t\tc.Images, err = sc.AssetService.GetAssetBlockImages(c.BlockID)\n\t\tif err != nil {\n\t\t\tapperrors.Critical(\"timelineservice:find-all:2\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\tc.Reactions, err = db.FindClaimReactions(c.BlockID)\n\t\tif err != nil {\n\t\t\tapperrors.Critical(\"timelineservice:find-all:3\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\tresult = append(result, c)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, false, err\n\t}\n\thasMore := len(result) == limit+1\n\tif hasMore {\n\t\tresult = result[:len(result)-1]\n\t}\n\treturn result, hasMore, nil\n}", "func (db *MongoDBAccess) GetAll() ([]Record, error) {\n\tvar records []Record\n\tcursor, err := db.client.Database(db.database).Collection(\"days\").Find(context.Background(), bson.D{})\n\tif err != nil {\n\t\treturn []Record{}, err\n\t}\n\tdefer cursor.Close(context.Background())\n\tfor cursor.Next(context.Background()) {\n\t\tvar record Record\n\t\tif err = cursor.Decode(&record); err != nil {\n\t\t\treturn []Record{}, err\n\t\t}\n\t\trecords = append(records, record)\n\t}\n\treturn records, nil\n}", "func getDailyTaskStatsPipeline(projectId string, requester string, start time.Time, end time.Time, tasks []string, lastUpdate time.Time, oldTasks bool) []bson.M {\n\tvar taskIdExpr string\n\tvar displayTaskLookupCollection string\n\tif oldTasks {\n\t\ttaskIdExpr = \"$old_task_id\"\n\t\tdisplayTaskLookupCollection = task.OldCollection\n\t} else {\n\t\ttaskIdExpr = \"$_id\"\n\t\tdisplayTaskLookupCollection = task.Collection\n\t}\n\tpipeline := []bson.M{\n\t\t{\"$match\": bson.M{\n\t\t\ttask.ProjectKey: projectId,\n\t\t\ttask.RequesterKey: requester,\n\t\t\ttask.CreateTimeKey: bson.M{\"$gte\": start, \"$lt\": end},\n\t\t\ttask.DisplayNameKey: bson.M{\"$in\": tasks},\n\t\t}},\n\t\t{\"$project\": bson.M{\n\t\t\ttask.IdKey: 0,\n\t\t\t\"task_id\": taskIdExpr,\n\t\t\t\"execution\": taskExecutionRef,\n\t\t\t\"project\": taskProjectKeyRef,\n\t\t\t\"task_name\": taskDisplayNameKeyRef,\n\t\t\t\"variant\": taskBuildVariantKeyRef,\n\t\t\t\"distro\": taskDistroIdKeyRef,\n\t\t\t\"requester\": taskRequesterKeyRef,\n\t\t\t\"status\": taskStatusKeyRef,\n\t\t\t\"details\": taskDetailsKeyRef,\n\t\t\t\"time_taken\": bson.M{\"$divide\": array{taskTimeTakenKeyRef, nsInASecond}},\n\t\t}},\n\t\t{\"$lookup\": bson.M{\n\t\t\t\"from\": displayTaskLookupCollection,\n\t\t\t\"localField\": \"task_id\",\n\t\t\t\"foreignField\": task.ExecutionTasksKey,\n\t\t\t\"as\": \"display_task\",\n\t\t}},\n\t\t{\"$match\": bson.M{\"display_task\": array{}}}, // Excluding the execution tasks\n\t\t{\"$group\": bson.M{\n\t\t\t\"_id\": bson.D{\n\t\t\t\t{Name: \"task_name\", Value: \"$task_name\"},\n\t\t\t\t{Name: \"variant\", Value: \"$variant\"},\n\t\t\t\t{Name: \"distro\", Value: \"$distro\"},\n\t\t\t\t{Name: \"project\", Value: \"$project\"},\n\t\t\t\t{Name: \"requester\", Value: \"$requester\"}},\n\t\t\t\"num_success\": makeSum(bson.M{\"$eq\": array{\"$status\", \"success\"}}),\n\t\t\t\"num_failed\": makeSum(bson.M{\"$eq\": array{\"$status\", \"failed\"}}),\n\t\t\t\"num_timeout\": makeSum(bson.M{\"$and\": array{\n\t\t\t\tbson.M{\"$eq\": array{\"$status\", \"failed\"}},\n\t\t\t\tbson.M{\"$eq\": array{\"$details.timed_out\", true}}}}),\n\t\t\t\"num_test_failed\": makeSum(bson.M{\"$and\": array{\n\t\t\t\tbson.M{\"$eq\": array{\"$status\", \"failed\"}},\n\t\t\t\tbson.M{\"$eq\": array{\"$details.type\", \"test\"}},\n\t\t\t\tbson.M{\"$ne\": array{\"$details.timed_out\", true}}}}),\n\t\t\t\"num_system_failed\": makeSum(bson.M{\"$and\": array{\n\t\t\t\tbson.M{\"$eq\": array{\"$status\", \"failed\"}},\n\t\t\t\tbson.M{\"$eq\": array{\"$details.type\", \"system\"}},\n\t\t\t\tbson.M{\"$ne\": array{\"$details.timed_out\", true}}}}),\n\t\t\t\"num_setup_failed\": makeSum(bson.M{\"$and\": array{\n\t\t\t\tbson.M{\"$eq\": array{\"$status\", \"failed\"}},\n\t\t\t\tbson.M{\"$eq\": array{\"$details.type\", \"setup\"}},\n\t\t\t\tbson.M{\"$ne\": array{\"$details.timed_out\", true}}}}),\n\t\t\t\"avg_duration_success\": bson.M{\"$avg\": bson.M{\"$cond\": bson.M{\"if\": bson.M{\"$eq\": array{\"$status\", \"success\"}},\n\t\t\t\t\"then\": \"$time_taken\", \"else\": \"IGNORE\"}}}}},\n\t\t{\"$addFields\": bson.M{\n\t\t\t\"_id.date\": start,\n\t\t\t\"last_update\": lastUpdate,\n\t\t}},\n\t}\n\treturn pipeline\n}", "func Find(agent Agent, worldState StateList, goalState StateList) []Action {\n\t// we cannot plan without any goals\n\tif len(goalState) == 0 {\n\t\tpanic(\"cannot plan without a goal\")\n\t}\n\n\tvar result []Action\n\n\t// check what actions can run\n\tvar usableActions []Action\n\tfor _, action := range agent.AvailableActions() {\n\t\taction.Reset()\n\t\tusableActions = append(usableActions, action)\n\t}\n\n\t// early out, this agent doesn't have any actions\n\tif len(usableActions) == 0 {\n\t\treturn result\n\t}\n\n\tvar plans []*node\n\tif !buildGraph(&node{state: worldState}, &plans, usableActions, goalState, agent) {\n\t\treturn result\n\t}\n\n\t// get the cheapest plan\n\tcheapest := plans[0]\n\tfor i := 1; i < len(plans); i++ {\n\t\tif plans[i].runningCost < cheapest.runningCost {\n\t\t\tcheapest = plans[i]\n\t\t}\n\t}\n\n\t// invert the list so that we get the end action at the end of the result list\n\tfor n := cheapest; n != nil && n.action != nil; n = n.parent {\n\t\tresult = append([]Action{n.action}, result...)\n\t}\n\treturn result\n}", "func FindMeetings(c *gin.Context) {\n query := c.Request.URL.Query()\n\n var meetings []models.Meeting\n\n if len(query) == 0 {\n models.DB.Find(&meetings)\n } else if query.Get(\"id\") != \"\" {\n if err := models.DB.Find(&meetings, \"id = ?\", query.Get(\"id\")).Error; err != nil {\n c.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n return\n }\n } else if query.Get(\"created_by\") != \"\" {\n var searchMeeting SearchMeetingInput\n\n if bindErr := c.BindQuery(&searchMeeting); bindErr != nil {\n c.JSON(http.StatusBadRequest, gin.H{\"error\": bindErr.Error()})\n return\n }\n\n if err := models.DB.Where(&models.Meeting{Title: searchMeeting.Title, StartDate: searchMeeting.StartDate, EndDate: searchMeeting.EndDate, Location: searchMeeting.Location}).Find(&meetings, \"created_by = ?\", query.Get(\"created_by\")).Error; err != nil {\n c.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n return\n }\n } else {\n var searchMeeting SearchMeetingInput\n\n if bindErr := c.BindQuery(&searchMeeting); bindErr != nil {\n c.JSON(http.StatusBadRequest, gin.H{\"error\": bindErr.Error()})\n return\n }\n\n if err := models.DB.Where(&models.Meeting{Title: searchMeeting.Title, StartDate: searchMeeting.StartDate, EndDate: searchMeeting.EndDate, Location: searchMeeting.Location}).Find(&meetings).Error; err != nil {\n c.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n return\n }\n }\n\n c.JSON(http.StatusOK, gin.H{\"data\": meetings})\n}", "func (d *Dao) GetAllDayExpenseInfo(c context.Context, beginDate time.Time, ctype, from, limit int) (infos []*model.BudgetDayStatistics, err error) {\n\trows, err := d.rddb.Query(c, _getAllDayExpenseSQL, beginDate, ctype, from, limit)\n\tif err != nil {\n\t\tlog.Error(\"dao.GetAllDayExpenseInfo query error(%v)\", err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\ta := &model.BudgetDayStatistics{}\n\t\tif err = rows.Scan(&a.DayExpense, &a.UpCount, &a.AvCount, &a.UpAvgExpense, &a.AvAvgExpense, &a.TotalExpense, &a.Date); err != nil {\n\t\t\tlog.Error(\"dao.GetAllDayExpenseInfo scan error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t\tinfos = append(infos, a)\n\t}\n\terr = rows.Err()\n\treturn\n}", "func (f *fileActivityFinder) FindAll() ([]domain.Activity, error) {\n\tvar activities []domain.Activity\n\n\tbyteValue, _ := ioutil.ReadAll(f.reader)\n\n\terr := json.Unmarshal(byteValue, &activities)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn activities, nil\n}", "func (c *Client) FindCrmStage(criteria *Criteria) (*CrmStage, error) {\n\tcss := &CrmStages{}\n\tif err := c.SearchRead(CrmStageModel, criteria, NewOptions().Limit(1), css); err != nil {\n\t\treturn nil, err\n\t}\n\tif css != nil && len(*css) > 0 {\n\t\treturn &((*css)[0]), nil\n\t}\n\treturn nil, fmt.Errorf(\"crm.stage was not found with criteria %v\", criteria)\n}", "func FindMeetingByTime(startTime string, endTime string) ([]entity.Meeting, error) {\n\tif err := checkIfLoggedin(); err != nil {\n\t\treturn nil, err\n\t}\n\terr := validateNewTimeInterval(startTime, endTime)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresults := entity.FindMeetingsByTime(startTime, endTime, err)\n\treturn results, nil\n}", "func (m *Manager) FindBundleChannelAdActive() ([]FindBundleChannelAdActiveType, error) {\n\tres := []FindBundleChannelAdActiveType{}\n\t_, err := m.GetDbMap().Select(\n\t\t&res,\n\t\tfmt.Sprintf(\"SELECT %[1]s.*,%[2]s.cli_message_id,%[2]s.promote_data,%[2]s.src, %[3]s.code\"+\n\t\t\t\"(%[3]s.view -((%[3]s.view * %[3]s.percent_finish)/100)) AS target_view,%[3]s.position\"+\n\t\t\t\" FROM %[1]s \"+\n\t\t\t\" INNER JOIN %[2]s ON %[2]s.id=%[1]s.ad_id AND %[1]s.ad_id = %[3]s.target_ad \"+\n\t\t\t\" INNER JOIN %[3]s ON %[3]s.id=%[1]s.bundle_id \"+\n\t\t\t\" AND %[1]s.active=? \",\n\t\t\tBundleChannelAdTableFull,\n\t\t\tAdTableFull,\n\t\t\tBundlesTableFull,\n\t\t),\n\t\tActiveStatusYes,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func (g *Group) FindAll(db *gorm.DB) (*gorm.DB, []Group) {\r\n\tgroupList := []Group{}\r\n\tresult := db.Debug().Find(&groupList)\r\n\treturn result, groupList\r\n}", "func FindLocalEvents(postalCodes []string, genres []string, timeToday TimeToday) []SeatGeekEvent {\n\n\tt4 := time.Now()\n\n\tvar seatGeekEventChannels []chan []SeatGeekEvent\n\tvar seatGeekEvents []SeatGeekEvent\n\n\tfor _, postCode := range postalCodes {\n\n\t\tpostCodeAlreadyCached, err := redisLayer.Exists(postCode)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error checking if postcode key %s exists in Redis: \"+err.Error(), postCode)\n\t\t}\n\n\t\tif postCodeAlreadyCached {\n\t\t\tredisData, err := redisLayer.GetKeyBytes(postCode)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Error getting value for postcode key %s in Redis: \"+err.Error(), postCode)\n\t\t\t}\n\n\t\t\tvar cachedSeatgeekEvents []SeatGeekEvent\n\t\t\tjson.Unmarshal(redisData, &cachedSeatgeekEvents)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Error unmarshalling value for postcode key %s from Redis: \"+err.Error(), postCode)\n\t\t\t}\n\n\t\t\tseatGeekEvents = append(seatGeekEvents, cachedSeatgeekEvents...)\n\t\t} else {\n\t\t\tBaseSeatGeekLocalEventsURL := \"https://api.seatgeek.com/2/events?client_id=\" +\n\t\t\t\tSEATGEEK_ID +\n\t\t\t\t\"&range=\" +\n\t\t\t\t\"50mi\"\n\n\t\t\tseatGeekChan := make(chan []SeatGeekEvent)\n\t\t\tseatGeekEventChannels = append(seatGeekEventChannels, seatGeekChan)\n\t\t\tgo MakeSeatgeekEventsRequest(BaseSeatGeekLocalEventsURL, postCode, timeToday, seatGeekChan)\n\t\t}\n\t}\n\n\tcases := make([]reflect.SelectCase, len(seatGeekEventChannels))\n\n\tfor i, seatGeekEventChan := range seatGeekEventChannels {\n\t\tcases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(seatGeekEventChan)}\n\t}\n\n\tremainingCases := len(cases)\n\n\tfor remainingCases > 0 {\n\t\tchosen, value, ok := reflect.Select(cases)\n\t\tif !ok {\n\t\t\t//Channel has been closed; zero out channel to disable the case\n\t\t\tcases[chosen].Chan = reflect.ValueOf(nil)\n\t\t\tremainingCases--\n\t\t\tcontinue\n\t\t}\n\n\t\tseatGeekEvents = append(seatGeekEvents, value.Interface().([]SeatGeekEvent)...)\n\t}\n\n\tfmt.Println(\"[Time benchmark] Makin slow calls \" + time.Since(t4).String())\n\treturn FilterByGenres(seatGeekEvents, genres)\n}", "func (qs DaytypeQS) All(db models.DBInterface) ([]*Daytype, error) {\n\ts, p := qs.queryFull()\n\n\trows, err := db.Query(s, p...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tvar ret []*Daytype\n\tfor rows.Next() {\n\t\tobj := Daytype{existsInDB: true}\n\t\tif err = rows.Scan(&obj.id, &obj.Name); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tret = append(ret, &obj)\n\t}\n\n\treturn ret, nil\n}", "func FindLatestStable(ctx context.Context, board string) (*Delta, error) {\n\tchannel := \"stable\"\n\tdeltaType := \"OMAHA\"\n\n\tpaygen, err := LoadPaygenFromGS(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfiltered := paygen.FilterBoardChannelDeltaType(board, channel, deltaType)\n\n\treturn filtered.FindLatest()\n}", "func buildDateStageGroupID(fieldName string, inputDateFieldName string, start time.Time, end time.Time, numDays int) interface{} {\n\tinputDateFieldRef := \"$\" + inputDateFieldName\n\tif numDays <= 1 {\n\t\treturn inputDateFieldRef\n\t}\n\tboundaries := dateBoundaries(start, end, numDays)\n\tbranches := make([]bson.M, 0, len(boundaries)-1)\n\n\tfor i := 0; i < len(boundaries)-1; i++ {\n\t\tbranches = append(branches, bson.M{\n\t\t\t\"case\": bson.M{\"$and\": stats.Array{\n\t\t\t\tbson.M{\"$lt\": stats.Array{inputDateFieldRef, boundaries[i]}},\n\t\t\t\tbson.M{\"$gte\": stats.Array{inputDateFieldRef, boundaries[i+1]}},\n\t\t\t}},\n\t\t\t\"then\": boundaries[i+1],\n\t\t})\n\t}\n\treturn bson.M{\"$switch\": bson.M{\"branches\": branches}}\n}", "func getFullBuilds(c context.Context, masterName, builderName string, finished bool) ([]*buildbotBuild, error) {\n\t// TODO(hinoka): Builder specific structs.\n\tq := ds.NewQuery(\"buildbotBuild\")\n\tq = q.Eq(\"finished\", finished)\n\tq = q.Eq(\"master\", masterName)\n\tq = q.Eq(\"builder\", builderName)\n\tq = q.Order(\"-number\")\n\tq.Finalize()\n\t// Ignore the cursor, we don't need it.\n\tbuildbots, _, err := runBuildsQuery(c, q, 25)\n\treturn buildbots, err\n}", "func (this *activitiesStruct) searchActivity(begin time.Time) (int, bool) {\n\tgroups := this.groups\n\tnumGroups := len(groups)\n\tidxLeft := int(0)\n\n\t/*\n\t * The case that there are no groups requires special handling.\n\t */\n\tif numGroups > 0 {\n\t\tidxRight := numGroups - 1\n\n\t\t/*\n\t\t * Binary search algorithm.\n\t\t */\n\t\tfor idxLeft <= idxRight {\n\t\t\tdiff := idxRight - idxLeft\n\t\t\tdiffHalf := diff / 2\n\t\t\tidxPivot := idxLeft + diffHalf\n\t\t\tpivot := groups[idxPivot]\n\t\t\tpivotBegin := pivot.begin\n\n\t\t\t/*\n\t\t\t * Check if we have to continue searching in left or\n\t\t\t * right half.\n\t\t\t */\n\t\t\tif pivotBegin.After(begin) {\n\t\t\t\tidxRight = idxPivot - 1\n\n\t\t\t\t/*\n\t\t\t\t * Prevent underflow.\n\t\t\t\t */\n\t\t\t\tif idxRight > idxPivot {\n\t\t\t\t\tidxRight = idxPivot\n\t\t\t\t}\n\n\t\t\t} else if pivotBegin.Before(begin) {\n\t\t\t\tidxLeft = idxPivot + 1\n\n\t\t\t\t/*\n\t\t\t\t * Prevent overflow.\n\t\t\t\t */\n\t\t\t\tif idxLeft < idxPivot {\n\t\t\t\t\tidxLeft = idxPivot\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\treturn idxPivot, true\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn idxLeft, false\n}", "func GetTeamFull(id int64) (Team, error) {\n\tt, err := GetTeam(id)\n\tif t.Venue.ID != 0 && err == nil {\n\t\tt.Venue, err = GetVenue(t.Venue.ID)\n\t}\n\treturn t, err\n}", "func getTracksDay(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tif _, err := conf.DS.GetRadiostationID(vars[\"station\"]); err != nil {\n\t\tlog.Printf(\"getTracksDay Handler: GetRadiostationID(%s): %s\\n\", vars[\"station\"], err.Error())\n\t\thandleError(w, http.StatusBadRequest, \"Bad request\")\n\t\treturn\n\t}\n\n\tt, err := time.Parse(\"2006-01-02\", vars[\"date\"])\n\tif err != nil {\n\t\tlog.Printf(\"getTracksDay Handler: time.Parse(%s): %s\\n\", vars[\"date\"], err.Error())\n\t\thandleError(w, http.StatusBadRequest, \"Bad request\")\n\t\treturn\n\t}\n\n\tloc, _ := time.LoadLocation(\"Europe/Vienna\")\n\tsince := time.Date(\n\t\tt.Year(),\n\t\tt.Month(),\n\t\tt.Day(),\n\t\t0, 0, 0, 0,\n\t\tloc,\n\t)\n\tuntil := time.Date(\n\t\tt.Year(),\n\t\tt.Month(),\n\t\tt.Day(),\n\t\t23, 59, 59, 0,\n\t\tloc,\n\t)\n\n\tvar tracks []model.Track\n\tif vars[\"filter\"] == \"top\" {\n\t\ttracks, err = conf.DS.GetTopTracks(vars[\"station\"], since, until)\n\t} else {\n\t\ttracks, err = conf.DS.GetAllTracks(vars[\"station\"], since, until)\n\t}\n\tif err != nil {\n\t\tlog.Printf(\"getTracksDay Handler: GetTopTracks/GetAllTracks(%s, %q, %q): %s\\n\", vars[\"station\"],\n\t\t\tsince, until, err.Error())\n\t\thandleError(w, http.StatusInternalServerError, \"Internal server error\")\n\t\treturn\n\t}\n\n\ttype response struct {\n\t\tStation string `json:\"station\"`\n\t\tDate string `json:\"date\"`\n\t\tPlays []model.Track `json:\"plays\"`\n\t}\n\n\tresp := response{vars[\"station\"], vars[\"date\"], tracks}\n\tj, err := jsonMarshal(resp)\n\tif err != nil {\n\t\tlog.Printf(\"getTracksDay Handler: %s\\n\", err.Error())\n\t\thandleError(w, http.StatusInternalServerError, \"Internal server error\")\n\t\treturn\n\t}\n\twriteJSONResponse(w, j)\n}", "func DayInList(time *time.Time, days []int) bool {\n\treturn fieldInList(time.Day, days)\n}", "func (filter TaskReliabilityFilter) buildDateStageGroupID(fieldName string, inputDateFieldName string) interface{} {\n\tnumDays := filter.GroupNumDays\n\tinputDateFieldRef := \"$\" + inputDateFieldName\n\tif numDays <= 1 {\n\t\treturn inputDateFieldRef\n\t}\n\tboundaries := filter.dateBoundaries()\n\tbranches := make([]bson.M, 0, len(boundaries)-1)\n\n\tfor i := 0; i < len(boundaries)-1; i++ {\n\t\tbranches = append(branches, bson.M{\n\t\t\t\"case\": bson.M{\"$and\": taskstats.Array{\n\t\t\t\tbson.M{\"$lt\": taskstats.Array{inputDateFieldRef, boundaries[i]}},\n\t\t\t\tbson.M{\"$gte\": taskstats.Array{inputDateFieldRef, boundaries[i+1]}},\n\t\t\t}},\n\t\t\t\"then\": boundaries[i+1],\n\t\t})\n\t}\n\treturn bson.M{\"$switch\": bson.M{\"branches\": branches}}\n}", "func evaluateGameDayReport(date string) error {\n\treport, err := findGameDayReportByID(date)\n\n\tif err != nil {\n\t\tif !errors.Is(err, mongo.ErrNoDocuments) {\n\t\t\treturn err\n\t\t}\n\n\t\t// report doesn't exist for whatever reason, so make one\n\t\treport, err = createGameDayReport(date)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tgames, err := findMatchesByGameDateID(date)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, game := range games {\n\t\tgameReport := report.Games[game.ID]\n\t\tgameReport.HomeTeam.Score = game.HomeTeam.Score\n\t\tgameReport.AwayTeam.Score = game.AwayTeam.Score\n\t\tgameReport.WinnerID = determineWinner(game.HomeTeam, game.AwayTeam)\n\n\t\treport.Games[game.ID] = gameReport\n\t}\n\n\treport.Evaluated = true\n\n\tif err := upsertGameDayReport(*report); err != nil {\n\t\treturn err\n\t}\n\n\terr = evaluatePicks(*report, date)\n\treturn err\n}", "func (m *postgersDBRepo) SearchAvailabilityByDates(start, end time.Time, roomID int) (bool, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tvar numRows int\n\tquery := ` \n\t\t\tselect\n\t\t\t\tcount(id)\n\t\t\tfrom\n\t\t\t\troom_restrictions\n\t\t\twhere\n\t\t\t\troom_id = $1 \n\t\t\t\t$2 < end_date and $3 > start_date \n\t`\n\n\trow := m.DB.QueryRowContext(ctx, query, roomID, start, end)\n\n\terr := row.Scan(&numRows)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif numRows == 0 {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}", "func FindSimpleEvents(table string, strategyID int) ([]*SimpleEventDB, error) {\n\tsqlStr := fmt.Sprintf(findSimpleEventsSQL, table, strategyID)\n\trows, err := clerkDB.Queryx(sqlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tvar events []*SimpleEventDB\n\tfor rows.Next() {\n\t\tevent := new(SimpleEventDB)\n\t\tif err = rows.StructScan(event); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tevents = append(events, event)\n\t}\n\treturn events, nil\n}", "func (m *Mongo) FindConfirmedCases(ctx context.Context, outbreakID string, reportingDate time.Time, endDate *time.Time) ([]Case, error) {\n\tcollection := m.Client.Database(m.Database).Collection(m.personCollection())\n\tlastDate := endDate\n\tif lastDate == nil {\n\t\tl := reportingDate.Add(time.Hour * 24)\n\t\tlastDate = &l\n\t}\n\tfilter := bson.M{\n\t\t\"outbreakId\": outbreakID,\n\t\t\"classification\": \"LNG_REFERENCE_DATA_CATEGORY_CASE_CLASSIFICATION_CONFIRMED\",\n\t\t\"deleted\": false,\n\t\t\"$and\": bson.A{\n\t\t\tbson.M{\"dateOfReporting\": bson.M{\"$gte\": reportingDate}},\n\t\t\tbson.M{\"dateOfReporting\": bson.M{\"$lt\": lastDate}},\n\t\t},\n\t}\n\n\tvar cases []Case\n\tcursor, err := collection.Find(ctx, filter)\n\tif err != nil {\n\t\treturn cases, MongoQueryErr{\n\t\t\tReason: fmt.Sprintf(\"failed to retrieve cases for outbreak %s on reporting date %v\", outbreakID, reportingDate),\n\t\t\tInner: err,\n\t\t}\n\t}\n\tif err := cursor.All(ctx, &cases); err != nil {\n\t\treturn cases, MongoQueryErr{\n\t\t\tReason: fmt.Sprintf(\"error executing query for outbreak %s on reporting date %v\", outbreakID, reportingDate),\n\t\t\tInner: err,\n\t\t}\n\t}\n\n\treturn cases, nil\n}", "func (c *constructedSchedule) findAttendeeOverlap(se ScheduledEvent) (*CalendarEvent, bool, error) {\n\n\t// Now we check if the user already has a meeting.\n\n\tfor _, a := range se.Attendees {\n\t\tev, overlaps, err := a.Calendar.Overlap(se.TimeInterval)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t\tif overlaps {\n\t\t\treturn ev, true, nil\n\t\t}\n\n\t\tif _, exist := c.eventsByAttendee[a.ID]; exist {\n\t\t\tfor _, scheduled := range c.eventsByAttendee[a.ID].Scheduled {\n\t\t\t\t// TODO: This loop can be optimized. We could iterate from the\n\t\t\t\t// end and once we are seeing events where\n\t\t\t\t// scheduled.End.Before(se.Start) we can stop iterating.\n\n\t\t\t\tif scheduled.TimeInterval.Overlaps(se.TimeInterval) {\n\t\t\t\t\treturn &CalendarEvent{scheduled.TimeInterval}, true, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, false, nil\n}", "func Find(param string) []Data {\n\tvar res []Data\n\n\tfor _, d := range D {\n\t\tif d.Date == param || d.Region == param {\n\t\t\tres = append(res, d)\n\n\t\t}\n\t}\n\treturn res\n}", "func (s *Service) EventBySportByDate(options *EventBySportByDateOptions) (TheRunDownAPILines, int, error) {\n\terrorPayload := make(map[string]interface{})\n\tmapping := TheRunDownAPILines{}\n\n\t// make sure we have all the required elements to build the full required url string.\n\terr := validateEventBySportByDateURI(options)\n\tif err != nil {\n\t\treturn mapping, 0, err\n\t}\n\n\tt := time.Now()\n\tcacheBuster := t.Format(\"20060102150405\")\n\n\turi := fmt.Sprintf(\"%s/sports/%s/events/%s?cachebuster=%s\", options.URL, options.Sport, options.Date, cacheBuster)\n\n\tif options.AllPeriods {\n\t\turi = fmt.Sprintf(\"%s&include=%s\", uri, \"all_periods\")\n\t}\n\n\tif options.Scores {\n\t\turi = fmt.Sprintf(\"%s&include=%s\", uri, \"scores\")\n\t}\n\n\tif options.Teams {\n\t\turi = fmt.Sprintf(\"%s&include=%s\", uri, \"teams\")\n\t}\n\n\tif len(options.Offset) > 0 {\n\t\turi = fmt.Sprintf(\"%s&offset=%s\", uri, options.Offset)\n\t}\n\n\ts.Logger = s.Logger.WithFields(logrus.Fields{\n\t\t\"URI\": uri,\n\t})\n\ts.Logger.Debug(\"EventBySportByDate API Call\")\n\n\t// make you a client\n\tclient, err := blaster.NewClient(uri)\n\tif err != nil {\n\t\ts.Logger.Errorf(\"failed to create a http client: %s\", err.Error())\n\t\treturn mapping, 0, err\n\t}\n\n\tclient.SetHeader(\"Accept\", \"application/json\")\n\tclient.SetHeader(\"X-RapidAPI-Key\", s.Config.XRapidAPIKey)\n\tclient.SetHeader(\"X-RapidAPI-Host\", s.Config.XRapidAPIHost)\n\tclient.WillSaturateOnError(&errorPayload)\n\tclient.WillSaturate(&mapping)\n\n\tstatusCode, err := client.Get(context.Background())\n\tif err != nil {\n\t\ts.Logger.Errorf(\"something went wrong making the get request for EventBySportByDate: %s\", err.Error())\n\t\treturn mapping, statusCode, err\n\t}\n\n\ts.Logger.Infof(\"EventBySportByDate Status Code: %d\", statusCode)\n\n\tif client.StatusCodeIsError() {\n\t\ts.Logger.Errorf(\"EventBySportByDate retuned an unsuccessful status code. Error: %+v\", errorPayload)\n\t}\n\n\treturn mapping, statusCode, nil\n}", "func FindLogsGroupFilial(w http.ResponseWriter, r *http.Request) {\n\tenableCors(&w)\n\tlogs, err := logDAO.FindGroupFilialTipo()\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\trespondWithJSON(w, http.StatusOK, logs)\n}", "func (m *postgresDBRepo) SearchAvailableRoomsByDates(start, end time.Time) ([]models.Room, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tstmt := `\n\t\tselect\n\t\t\tr.id, r.room_name\n\t\tfrom\n\t\t\trooms r\n\t\twhere\n\t\t\tr.id not in\n\t\t(select rr.room_id from room_restrictions rr where $1 < rr.end_date and rr.start_date <= $2)\n\n\t`\n\trows, err := m.DB.QueryContext(ctx, stmt, start, end)\n\tif err != nil {\n\t\treturn []models.Room{}, err\n\t}\n\tdefer rows.Close()\n\n\tvar rooms []models.Room\n\n\tfor rows.Next() {\n\t\troom := models.Room{}\n\t\terr := rows.Scan(&room.ID, &room.RoomName)\n\t\tif err != nil {\n\t\t\treturn rooms, err\n\t\t}\n\t\trooms = append(rooms, room)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn rooms, err\n\t}\n\n\treturn rooms, nil\n}", "func (o *MaintenanceWindowRecurrence) HasDay() bool {\n\tif o != nil && o.Day != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (q *StatsPeriodQuery) FindByStarted(cond kallax.ScalarCond, v time.Time) *StatsPeriodQuery {\n\treturn q.Where(cond(Schema.StatsPeriod.Started, v))\n}", "func (ew *Eyewitness) Investigate(status whodunit.AssetStatus) {\n\ttotalCount := 0\n\ttable := whodunit.NewStatusTable(whodunit.AssetTypeRecognition, status)\n\tjep := ew.jobEpisodeMap()\n\tfor season := 1; season <= whodunit.SeasonCount; season++ {\n\t\ts := whodunit.NewSeason(season)\n\t\tif err := s.PopulateEpisodes(); err != nil {\n\t\t\tpanic(\"Could not get season episodes\")\n\t\t}\n\n\t\tfor _, ep := range s.AllEpisodes() {\n\t\t\tje := jep[ep.Name()]\n\t\t\tif je != nil {\n\t\t\t\tep.SetAssetStatus(je.AssetStatus(whodunit.AssetTypeRecognition))\n\t\t\t}\n\n\t\t\tif table.AddRow(ep) {\n\t\t\t\ttotalCount++\n\t\t\t}\n\t\t}\n\t}\n\n\ttable.RenderTable(totalCount)\n}", "func RunDay(verbose bool) {\n\tvar aResult int\n\tvar bResult int\n\tvar err error\n\n\tif verbose {\n\t\tfmt.Printf(\"\\n%v Output:\\n\", name)\n\t}\n\n\taResult, err = a()\n\tif err != nil {\n\t\tfmt.Printf(\"%va: **** Error: %q ****\\n\", name, err)\n\t} else {\n\t\tfmt.Printf(\"%va: Total Orbits = %v\\n\", name, aResult)\n\t}\n\n\tbResult, err = b()\n\tif err != nil {\n\t\tfmt.Printf(\"%vb: **** Error: %q ****\\n\", name, err)\n\t} else {\n\t\tfmt.Printf(\"%vb: Orbital Steps Required = %v\\n\", name, bResult)\n\t}\n}", "func (ec *executionContext) _Day_id(ctx context.Context, field graphql.CollectedField, obj *model.Day) (ret graphql.Marshaler) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tfc := &graphql.FieldContext{\n\t\tObject: \"Day\",\n\t\tField: field,\n\t\tArgs: nil,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t}\n\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.ID, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(int)\n\tfc.Result = res\n\treturn ec.marshalNID2int(ctx, field.Selections, res)\n}", "func FindRoom(db *gorm.DB, user User) (Room, error) {\n\tvar room Room\n\n\tdb.Where(`((owner_id = ? AND owner_app = ?) OR (guest_id = ? AND guest_app = ?))\n\t\t\t\t\t\t\t\t\tAND active = TRUE`, user.ID, user.App, user.ID, user.App).First(&room)\n\n\tif db.NewRecord(room) {\n\t\treturn Room{}, errors.New(\"no rooms found\")\n\t}\n\n\treturn room, nil\n}", "func (o *ViewProjectMinMaxAvailableDates) HasDeadlinesFound() bool {\n\tif o != nil && o.DeadlinesFound != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *constructedSchedule) findAvailableRoom(se ScheduledEvent, excluded []Room) (*Room, bool, error) {\n\tlookup := make(map[RoomID]struct{})\n\tfor _, r := range excluded {\n\t\tlookup[r.ID] = struct{}{}\n\t}\n\n\tfor _, room := range se.Request.PossibleRooms {\n\t\tif _, ignored := lookup[room.ID]; ignored {\n\t\t\tcontinue\n\t\t}\n\n\t\t_, overlaps, err := room.Calendar.Overlap(se.TimeInterval)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t\tif !overlaps {\n\t\t\treturn &room, true, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}", "func GetByDateRange(rw http.ResponseWriter, r *http.Request) {\n\tuserID := r.Header.Get(\"userid\")\n\tstartDate := r.URL.Query().Get(\"startDate\")\n\tendDate := r.URL.Query().Get(\"endDate\")\n\n\t// Validate startDate and endDate\n\tif startDate == \"\" || endDate == \"\" {\n\t\tlog.Printf(\"Invalid params, startDate or endDate is missing\\n\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Missing startDate or endDate\"))\n\t\treturn\n\t}\n\n\tif _, err := time.Parse(time.RFC3339, startDate); err != nil {\n\t\tlog.Printf(\"Invalid value for startDate\\n\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Invalid startDate\"))\n\t\treturn\n\t}\n\n\tif _, err := time.Parse(time.RFC3339, endDate); err != nil {\n\t\tlog.Printf(\"Invalid value for endDate\\n\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Invalid endDate\"))\n\t\treturn\n\t}\n\n\tquery := `SELECT * FROM events\n\t\tWHERE owner_id = $1 AND\n\t\t(start_time BETWEEN $2 AND $3 OR\n\t\tend_time BETWEEN $2 AND $3)`\n\n\trows, err := conn.DB.Query(query, userID, startDate, endDate)\n\tif err != nil {\n\t\tlog.Printf(\"DB error: %s\\n\", err)\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Unable to communicate with database\"))\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tevents := []Event{}\n\tfor rows.Next() {\n\t\te := Event{}\n\t\tloc := sql.NullString{}\n\t\tnotes := sql.NullString{}\n\n\t\terr = rows.Scan(&e.EventID, &e.Title, &e.StartTime, &e.EndTime, &loc, &notes, &e.OwnerID)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"DB error: %s\\n\", err)\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write([]byte(\"Error reading from database\"))\n\t\t\treturn\n\t\t}\n\n\t\te.Location = loc.String\n\t\te.Notes = notes.String\n\n\t\tevents = append(events, e)\n\t}\n\n\trw.WriteHeader(http.StatusOK)\n\trw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(rw).Encode(events)\n}", "func getCoveredDays(start, end time.Time) []string {\n\tdays := []string{start.Format(timestamp.DayLayout)}\n\n\tday := start.Day()\n\tfor start.Before(end) {\n\t\tstart = start.Add(time.Hour)\n\t\tnextDay := start.Day()\n\t\tif nextDay != day {\n\t\t\tdays = append(days, start.Format(timestamp.DayLayout))\n\t\t}\n\t\tday = nextDay\n\t}\n\n\treturn days\n}", "func OperationByWeekdayStat(dbname string) (interface{}, error) {\n\n\tpipeline := []bson.M{\n\t\tbson.M{\"$group\": bson.M{\"_id\": bson.M{\"weekday\": \"$dayofweek\", \"department\": \"$departmentname\"}, \"count\": bson.M{\"$sum\": 1}}},\n\t}\n\tresponse, err := doPipe(dbname, pipeline)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttype output map[string]interface{}\n\tresult := make([]output, 0)\n\tfor _, submap := range response {\n\t\titem := make(output)\n\t\tidmap := submap[\"_id\"].(bson.M)\n\t\titem[\"department\"] = idmap[\"department\"].(string)\n\t\titem[\"weekday\"] = RevDayOfWeek[time.Weekday(idmap[\"weekday\"].(int))]\n\t\titem[\"count\"] = submap[\"count\"].(int)\n\t\tresult = append(result, item)\n\t}\n\treturn result, nil\n}", "func FullFinder(url, server string, timeout time.Duration, verbose bool) (*FullOutput, error) {\n\traw, err := discoverResources(url, timeout, verbose)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif verbose {\n\t\tlog.Println(raw)\n\t}\n\treturn parseraw(raw, server, verbose), nil\n}", "func FindOffers(c *fiber.Ctx) {\n\tLat := c.Params(\"lat\")\n\tLon := c.Params(\"lon\")\n\n\tvar offers FOffers\n\tvar array []FOffers\n\tvar OffersIDStruct OffersID\n\tvar arrOffersID []OffersID\n\tvar OffersFind OffersFromSQLFind\n\tvar OffersArr []OffersFromSQLFind\n\tvar OffersPointer OffersFindPointer\n\tvar OffersArrPointer []OffersFindPointer\n\n\tLatI, _ := strconv.ParseFloat(Lat, 64)\n\tLonI, _ := strconv.ParseFloat(Lon, 64)\n\n\tQuery := new(FindOfferQuery)\n\n\tif err := c.QueryParser(Query); err != nil {\n\t\tfmt.Println(err, \"Error parsing Query\")\n\t}\n\n\tQuery.LastOfferID = c.Query(\"last_offer_id\")\n\n\tLastIDS := strings.Split(Query.LastOfferID, \",\")\n\n\tLimit, _ := strconv.Atoi(Query.Limit)\n\tMinDistance, _ := strconv.ParseFloat(Query.MinDistance, 64)\n\n\t_, errTime := time.LoadLocation(\"America/Mexico_City\")\n\n\tif errTime != nil {\n\t\tfmt.Println(errTime)\n\t}\n\n\tTimeUnParsing := time.Now()\n\tTimeString := fmt.Sprintf(\"%s\", TimeUnParsing)\n\tTimePaser := strings.Split(TimeString, \" \")\n\tTimeRemoveSpace := strings.TrimRight(TimePaser[0], \" \")\n\n\tAggregate := []bson.M{\n\t\tbson.M{\n\t\t\t\"$geoNear\": bson.M{\n\t\t\t\t\"near\": bson.M{\n\t\t\t\t\t\"type\": \"Point\",\n\t\t\t\t\t\"coordinates\": []float64{LonI, LatI},\n\t\t\t\t},\n\t\t\t\t\"minDistance\": MinDistance,\n\t\t\t\t\"spherical\": true,\n\t\t\t\t\"distanceField\": \"distance\",\n\t\t\t},\n\t\t},\n\t\tbson.M{\n\t\t\t\"$match\": bson.M{\n\t\t\t\t\"active\": true,\n\t\t\t\t\"offer_id\": bson.M{\n\t\t\t\t\t\"$nin\": LastIDS,\n\t\t\t\t},\n\t\t\t\t\"date_end\": bson.M{\n\t\t\t\t\t\"$gt\": TimeRemoveSpace,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tbson.M{\n\t\t\t\"$limit\": Limit,\n\t\t},\n\t}\n\n\tcurl, error := mongodb.Collection(\"offers\").Aggregate(context.TODO(), Aggregate, options.Aggregate())\n\n\tif error != nil {\n\t\tfmt.Println(error)\n\t}\n\n\tfor curl.Next(context.TODO()) {\n\t\t_ = curl.Decode(&offers)\n\t\tOffersIDStruct.OfferID = offers.OfferID\n\t\tOffersIDStruct.Distance = offers.Distance\n\t\tarrOffersID = append(arrOffersID, OffersIDStruct)\n\n\t\tarray = append(array, offers)\n\t}\n\t// fmt.Println(array)\n\tIDs := \"\"\n\n\tfor i := 0; i < len(arrOffersID); i++ {\n\t\tif len(arrOffersID)-1 == i {\n\t\t\tIDs = fmt.Sprintf(\"%s%v\", IDs, arrOffersID[i].OfferID)\n\t\t} else {\n\t\t\tIDs = fmt.Sprintf(\"%s%v,\", IDs, arrOffersID[i].OfferID)\n\t\t}\n\t}\n\n\twhere := fmt.Sprintf(\"offers_id IN (%s)\", IDs)\n\n\toffersSQL := sq.Select(\n\t\t\"offers_id\",\n\t\t\"title\",\n\t\t\"offers.description\",\n\t\t\"date_init\",\n\t\t\"date_end\",\n\t\t\"image_url\",\n\t\t\"shop.shop_id\",\n\t\t\"shop_name\",\n\t\t\"cover_image\",\n\t).\n\t\tFrom(\"offers\").\n\t\tLeftJoin(\"shop on shop.shop_id = offers.shop_id\")\n\n\tif len(IDs) > 0 {\n\t\toffersSQL = offersSQL.Where(where)\n\t} else {\n\t\toffersSQL = offersSQL.Where(\"offers_id IS NULL\")\n\t}\n\n\tOffersFromSQL, ErrorOffers := offersSQL.\n\t\tRunWith(database).\n\t\tQuery()\n\n\tif ErrorOffers != nil {\n\t\tfmt.Println(ErrorOffers, \"Error get Offers find\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get Offers find\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tfor OffersFromSQL.Next() {\n\t\t_ = OffersFromSQL.Scan(\n\t\t\t&OffersFind.OfferID,\n\t\t\t&OffersFind.Title,\n\t\t\t&OffersFind.Description,\n\t\t\t&OffersFind.DateInit,\n\t\t\t&OffersFind.DateEnd,\n\t\t\t&OffersFind.ImageURL,\n\t\t\t&OffersFind.ShopID,\n\t\t\t&OffersFind.ShopName,\n\t\t\t&OffersFind.CoverImage,\n\t\t)\n\n\t\tOffersArr = append(OffersArr, OffersFind)\n\t}\n\n\tfor i := 0; i < len(OffersArr); i++ {\n\t\tOffersPointer.OfferID = &OffersArr[i].OfferID.String\n\t\tOffersPointer.Title = &OffersArr[i].Title.String\n\t\tOffersPointer.Description = &OffersArr[i].Description.String\n\t\tOffersPointer.DateInit = &OffersArr[i].DateInit.String\n\t\tOffersPointer.DateEnd = &OffersArr[i].DateEnd.String\n\t\tOffersPointer.ImageURL = &OffersArr[i].ImageURL.String\n\t\tOffersPointer.ShopID = &OffersArr[i].ShopID.String\n\t\tOffersPointer.ShopName = &OffersArr[i].ShopName.String\n\t\tOffersPointer.CoverImage = &OffersArr[i].CoverImage.String\n\n\t\tfor e := 0; e < len(arrOffersID); e++ {\n\t\t\tif arrOffersID[e].OfferID == OffersArr[i].OfferID.String {\n\t\t\t\tOffersPointer.Distance = arrOffersID[e].Distance\n\t\t\t}\n\t\t}\n\n\t\tOffersArrPointer = append(OffersArrPointer, OffersPointer)\n\t}\n\n\tsort.Slice(OffersArrPointer, func(i, j int) bool {\n\t\treturn OffersArrPointer[i].Distance < OffersArrPointer[j].Distance\n\t})\n\n\tvar LastOffer ResponsePointerLasts\n\tif len(OffersArrPointer) > 0 {\n\t\tLastOffer.LastID = OffersArrPointer[len(OffersArrPointer)-1].OfferID\n\t\tLastOffer.Distance = OffersArrPointer[len(OffersArrPointer)-1].Distance\n\t} else {\n\t\tOffersArrPointer = []OffersFindPointer{}\n\t}\n\n\tc.JSON(ResponseFinalFindOffers{\n\t\tOffers: OffersArrPointer,\n\t\tLastOfferID: LastOffer.LastID,\n\t\tLastDistance: LastOffer.Distance,\n\t})\n}", "func getActivity(meta *client.AccountMeta) error {\n\tig, err := meta.Delayed()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ig.Debug {\n\t\tlog.Debug(\"Checking feed for %v\", ig.Username)\n\t}\n\t// get recent activity\n\tract, err := ig.GetRecentActivity()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// fetch old stories\n\tfor _, story := range append(ract.OldStories, ract.NewStories...) {\n\t\terr := fillFeed(story, meta)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o *ViewProjectMinMaxAvailableDates) GetDeadlinesFound() bool {\n\tif o == nil || o.DeadlinesFound == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.DeadlinesFound\n}", "func (filter TaskReliabilityFilter) BuildTaskStatsQueryGroupStage() bson.M {\n\treturn bson.M{\n\t\t\"$group\": bson.M{\n\t\t\t\"_id\": filter.buildGroupID(),\n\t\t\ttaskstats.TaskStatsNumSuccessKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumSuccessKey},\n\t\t\ttaskstats.TaskStatsNumFailedKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumFailedKey},\n\t\t\ttaskstats.TaskStatsNumTimeoutKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumTimeoutKey},\n\t\t\ttaskstats.TaskStatsNumTestFailedKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumTestFailedKey},\n\t\t\ttaskstats.TaskStatsNumSystemFailedKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumSystemFailedKey},\n\t\t\ttaskstats.TaskStatsNumSetupFailedKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumSetupFailedKey},\n\t\t\t\"total_duration_success\": bson.M{\"$sum\": bson.M{\"$multiply\": taskstats.Array{\"$\" + taskstats.DBTaskStatsNumSuccessKey, \"$\" + taskstats.DBTaskStatsAvgDurationSuccessKey}}},\n\t\t}}\n}", "func (b *OGame) GetFleetsFromEventList() []ogame.Fleet {\n\treturn b.WithPriority(taskRunner.Normal).GetFleetsFromEventList()\n}", "func (m *RecManager) GetAllFull() ([]*RecFull, error) {\n\treturn m.getFull(\"\")\n}", "func getEndPoint(fromDate, toDate string) string {\r\n\t// Setting the Base URL\r\n\tendpoint, _ := url.Parse(\"https://digitalcrew.teamwork.com/projects/api/v2/projects/263073/tasks.json\")\r\n\r\n\t// Setting the query params\r\n\tparams := url.Values{}\r\n\r\n\tparams.Add(\"includeBlockedTasks\", \"true\")\r\n\tparams.Add(\"include\", \"taskListNames\")\r\n\tparams.Add(\"includeCompletedTasks\", \"true\")\r\n\tparams.Add(\"tagIds\", \"3871\")\r\n\tparams.Add(\"matchAllTags\", \"true\")\r\n\tparams.Add(\"matchAllExcludedTags\", \"false\")\r\n\tparams.Add(\"createdAfterDate\", fromDate)\r\n\tparams.Add(\"createdBeforeDate\", toDate)\r\n\r\n\t//Adding the query params to the base url\r\n\tendpoint.RawQuery = params.Encode()\r\n\treturn endpoint.String()\r\n}", "func (t *Cases) FindAll() []models.Case {\n\tvar cases []models.Case\n\n\tquery := func(db *gorm.DB) {\n\t\tdb.Find(&cases)\n\t}\n\n\terror := t.context.Execute(query)\n\n\tif error != nil {\n\t\treturn nil\n\t}\n\n\treturn cases\n}", "func (dt DateTime) FloorDay() DateTime {\n\treturn dt.Replace(dt.Year(), dt.Month(), dt.Day(), 0, 0, 0, 0)\n}", "func ByDate(date time.Time) FilterFunc {\n\treturn func(c *Collection) bool {\n\t\tif c.Ref == nil {\n\t\t\tlog.Warningln(\"Error finding ref of the current git collection. Make sure the branch is pushed to origin\")\n\t\t\treturn false\n\t\t}\n\t\trevWalk, err := c.Repository.Walk()\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Could not walk repo %v\", err)\n\t\t\treturn false\n\t\t}\n\t\tif err := revWalk.PushGlob(\"*\"); err != nil {\n\t\t\tlog.Warningf(\"Error pushing glob %v\", err)\n\t\t\tif err := revWalk.Push(c.Ref.Target()); err != nil {\n\t\t\t\tlog.Warningf(\"Error pushing git reference target %v\", err)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\trevWalk.Sorting(git2go.SortTime)\n\t\t\trevWalk.SimplifyFirstParent()\n\t\t\tid := &(git2go.Oid{})\n\t\t\tfor revWalk.Next(id) == nil {\n\t\t\t\tg, err := c.Repository.LookupCommit(id)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warningf(\"Error finding commit id %v %v\", id, err)\n\t\t\t\t}\n\t\t\t\tif g.Author().When.Before(date) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tc.Commits = append(c.Commits, g)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}", "func ReduceVolumeByDay(hourMap map[int][]time.Time) map[int][]int {\n\tvolumeMap := make(map[int][]int)\n\tfor hour, timestamps := range hourMap {\n\t\tvolumeMap[hour] = ReduceVolume(timestamps)\n\t}\n\treturn volumeMap\n}", "func (d *defaultJobRepository) GetByStatusAndBefore(ctxIn context.Context, status []JobStatus, deltaHours int) ([]*Job, error) {\n _, span := trace.StartSpan(ctxIn, \"(*defaultJobRepository).GetByStatusAndBefore\")\n defer span.End()\n\n var jobs []*Job \n db := d.storageService.DB()\n\n err := db.Model(&jobs).\n Where(\"audit_deleted_timestamp is null\").\n WhereGroup(func(sub *orm.Query) (*orm.Query, error) {\n return sub.\n WhereGroup(func(sub *orm.Query) (*orm.Query, error) {\n return sub.\n Where(\"audit_updated_timestamp is null\").\n Where(\"audit_created_timestamp < NOW()-interval '1 hour'*?\", deltaHours), nil\n }).\n WhereOrGroup(func(sub *orm.Query) (*orm.Query, error) {\n return sub.\n Where(\"audit_updated_timestamp is not null\").\n Where(\"audit_updated_timestamp < NOW()-interval '1 hour'*?\", deltaHours), nil\n }), nil\n }).\n Where(\"status in (?)\", pg.In(status)).\n Select()\n\n if err != nil {\n return jobs, fmt.Errorf(\"error during executing get job by status statement: %s\", err)\n }\n\n return jobs, nil\n}", "func (st *SqliteStoreMatchup) GetMatchups(league *data.League, season *data.Season) ([]data.Matchup, error) {\n\tvar matchups []data.Matchup\n\trows, err := st.database.Query(`SELECT league_id, season_year, id,\n\thome, away, round, start FROM matchup WHERE league_id=? AND season_year=?`, league.ID, season.Year)\n\tif err != nil {\n\t\tfmt.Printf(\"GetMatchups query Err: %v\\n\", err)\n\t\treturn []data.Matchup{}, err\n\t}\n\tvar leagueID string\n\tvar seasonYear int\n\tvar ID string\n\tvar homeID string\n\tvar awayID string\n\tvar round int\n\tvar start string\n\tfor rows.Next() {\n\t\tmatchup := &data.Matchup{}\n\t\terr := rows.Scan(&leagueID, &seasonYear, &ID, &homeID, &awayID, &round, &start)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GetMatchup Scan Err: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tleague, _ := st.store.League().GetLeague(leagueID)\n\t\tseason, _ := st.store.Season().GetSeason(seasonYear, league)\n\t\thome, _ := st.store.Team().GetTeam(homeID, league)\n\t\taway, _ := st.store.Team().GetTeam(awayID, league)\n\t\tmatchup.League = *league\n\t\tmatchup.Season = *season\n\t\tmatchup.ID = ID\n\t\tif home != nil {\n\t\t\tmatchup.Home = *home\n\t\t}\n\t\tif away != nil {\n\t\t\tmatchup.Away = *away\n\t\t}\n\t\tmatchup.Round = round\n\t\tmatchup.Start, err = time.Parse(time.RFC3339, start)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GetMatchup Invalid time Err: %v\\n\", err)\n\n\t\t}\n\t\tif home != nil && away != nil {\n\t\t\tmatchup.SeasonGames, _ = st.store.Game().GetSeasonGames(league, season, home, away)\n\t\t\tmatchup.PlayoffGames, _ = st.store.Game().GetPlayoffGames(league, season, home, away)\n\t\t}\n\t\tmatchup.CalculateResult()\n\t\tmatchups = append(matchups, *matchup)\n\t}\n\trows.Close()\n\treturn matchups, nil\n}", "func (m *mysqlDBRepo) SearchAvailabilityByDatesByRoomID(start, end time.Time, roomID int) (bool, error) {\n\t// request last longer 3 second so discard write record into db\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tquery := `select count(id) from room_restrictions where room_id = ? and ? < end_date and ? > start_date`\n\n\tvar numRows int\n\n\terr := m.DB.QueryRowContext(ctx, query, roomID, start, end).Scan(&numRows)\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\n\treturn numRows == 0, nil\n}", "func (m *postgresDBRepo) SearchAvailabilityByDatesByRoomID(start, end time.Time, roomID int) (bool, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\tstmt := `\n\t\tselect \n\t\t\tcount(id)\n\t\tfrom \n\t\t\troom_restrictions\n\t\twhere\n\t\t\troom_id = $1 and\n\t\t\t$2 < end_date and start_date < $3;`\n\tvar numRows int\n\trow := m.DB.QueryRowContext(ctx, stmt, roomID, start, end)\n\terr := row.Scan(&numRows)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif numRows == 0 {\n\t\treturn true, nil\n\t} else {\n\t\treturn false, nil\n\t}\n}", "func DefaultListHealthMenstruationDailyEntry(ctx context.Context, db *gorm1.DB, f *query1.Filtering, s *query1.Sorting, p *query1.Pagination, fs *query1.FieldSelection) ([]*HealthMenstruationDailyEntry, error) {\n\tin := HealthMenstruationDailyEntry{}\n\tormObj, err := in.ToORM(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(HealthMenstruationDailyEntryORMWithBeforeListApplyQuery); ok {\n\t\tif db, err = hook.BeforeListApplyQuery(ctx, db, f, s, p, fs); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdb, err = gorm2.ApplyCollectionOperators(ctx, db, &HealthMenstruationDailyEntryORM{}, &HealthMenstruationDailyEntry{}, f, s, p, fs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(HealthMenstruationDailyEntryORMWithBeforeListFind); ok {\n\t\tif db, err = hook.BeforeListFind(ctx, db, f, s, p, fs); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdb = db.Where(&ormObj)\n\tdb = db.Order(\"id\")\n\tormResponse := []HealthMenstruationDailyEntryORM{}\n\tif err := db.Find(&ormResponse).Error; err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(HealthMenstruationDailyEntryORMWithAfterListFind); ok {\n\t\tif err = hook.AfterListFind(ctx, db, &ormResponse, f, s, p, fs); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tpbResponse := []*HealthMenstruationDailyEntry{}\n\tfor _, responseEntry := range ormResponse {\n\t\ttemp, err := responseEntry.ToPB(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpbResponse = append(pbResponse, &temp)\n\t}\n\treturn pbResponse, nil\n}", "func (s *Service) Live(c context.Context, roomIDs []int64) (res []*livemdl.RoomInfo, err error) {\n\tlive, err := s.liveDao.LiveByRIDs(c, roomIDs)\n\tif err != nil {\n\t\tlog.Error(\"%+v\", err)\n\t\treturn\n\t}\n\tif len(live) == 0 {\n\t\tres = []*livemdl.RoomInfo{}\n\t\treturn\n\t}\n\tfor _, lv := range live {\n\t\titem := &livemdl.RoomInfo{\n\t\t\tRoomID: lv.RoomID,\n\t\t\tURI: model.FillURI(\"live\", strconv.FormatInt(lv.RoomID, 10), model.LiveHandler(lv)),\n\t\t}\n\t\tif lv.Status == 1 {\n\t\t\titem.Status = lv.Status\n\t\t}\n\t\tres = append(res, item)\n\t}\n\treturn\n}", "func (c *StatsGetSearchapplicationCall) EndDateDay(endDateDay int64) *StatsGetSearchapplicationCall {\n\tc.urlParams_.Set(\"endDate.day\", fmt.Sprint(endDateDay))\n\treturn c\n}", "func MonthlyServiceFlavor(filter bson.M) []bson.M {\n\tquery := []bson.M{\n\t\t{\"$match\": filter},\n\t\t{\"$group\": bson.M{\n\t\t\t\"_id\": bson.M{\n\t\t\t\t\"date\": bson.D{{\"$substr\", list{\"$date\", 0, 6}}},\n\t\t\t\t\"name\": \"$name\",\n\t\t\t\t\"supergroup\": \"$supergroup\",\n\t\t\t\t\"report\": \"$report\"},\n\t\t\t\"avgup\": bson.M{\"$avg\": \"$up\"},\n\t\t\t\"avgunknown\": bson.M{\"$avg\": \"$unknown\"},\n\t\t\t\"avgdown\": bson.M{\"$avg\": \"$down\"}}},\n\t\t{\"$project\": bson.M{\n\t\t\t\"date\": \"$_id.date\",\n\t\t\t\"name\": \"$_id.name\",\n\t\t\t\"supergroup\": \"$_id.supergroup\",\n\t\t\t\"report\": \"$_id.report\",\n\t\t\t\"unknown\": \"$avgunknown\",\n\t\t\t\"up\": \"$avgup\",\n\t\t\t\"down\": \"$avgdown\",\n\t\t\t\"availability\": bson.M{\n\t\t\t\t\"$multiply\": list{\n\t\t\t\t\tbson.M{\"$divide\": list{\n\t\t\t\t\t\t\"$avgup\", bson.M{\"$subtract\": list{1.00000001, \"$avgunknown\"}}}},\n\t\t\t\t\t100}},\n\t\t\t\"reliability\": bson.M{\n\t\t\t\t\"$multiply\": list{\n\t\t\t\t\tbson.M{\"$divide\": list{\n\t\t\t\t\t\t\"$avgup\", bson.M{\"$subtract\": list{bson.M{\"$subtract\": list{1.00000001, \"$avgunknown\"}}, \"$avgdown\"}}}},\n\t\t\t\t\t100}}}},\n\t\t{\"$sort\": bson.D{\n\t\t\t{\"supergroup\", 1},\n\t\t\t{\"name\", 1},\n\t\t\t{\"date\", 1}}}}\n\treturn query\n}", "func (filter TaskReliabilityFilter) BuildTaskStatsQueryGroupStage() bson.M {\n\treturn bson.M{\n\t\t\"$group\": bson.M{\n\t\t\t\"_id\": filter.buildGroupID(),\n\t\t\tstats.TaskStatsNumSuccessKey: bson.M{\"$sum\": \"$\" + stats.DbTaskStatsNumSuccessKey},\n\t\t\tstats.TaskStatsNumFailedKey: bson.M{\"$sum\": \"$\" + stats.DbTaskStatsNumFailedKey},\n\t\t\tstats.TaskStatsNumTimeoutKey: bson.M{\"$sum\": \"$\" + stats.DbTaskStatsNumTimeoutKey},\n\t\t\tstats.TaskStatsNumTestFailedKey: bson.M{\"$sum\": \"$\" + stats.DbTaskStatsNumTestFailedKey},\n\t\t\tstats.TaskStatsNumSystemFailedKey: bson.M{\"$sum\": \"$\" + stats.DbTaskStatsNumSystemFailedKey},\n\t\t\tstats.TaskStatsNumSetupFailedKey: bson.M{\"$sum\": \"$\" + stats.DbTaskStatsNumSetupFailedKey},\n\t\t\t\"total_duration_success\": bson.M{\"$sum\": bson.M{\"$multiply\": stats.Array{\"$\" + stats.DbTaskStatsNumSuccessKey, \"$\" + stats.DbTaskStatsAvgDurationSuccessKey}}},\n\t\t}}\n}", "func (d *Dao) RelationFansDayCache(c context.Context, mid int64, dt string) (res map[string]map[string]int, err error) {\n\tvar (\n\t\tconn = d.mc.Get(c)\n\t\tr *memcache.Item\n\t)\n\tdefer conn.Close()\n\t// get cache\n\tr, err = conn.Get(keyRfd(mid, dt))\n\tif err != nil {\n\t\tif err == memcache.ErrNotFound {\n\t\t\terr = nil\n\t\t} else {\n\t\t\tlog.Error(\"conn.Get(%d) error(%v)\", mid, err)\n\t\t}\n\t\treturn\n\t}\n\tif err = conn.Scan(r, &res); err != nil {\n\t\tlog.Error(\"json.Unmarshal(%s) error(%v)\", r.Value, err)\n\t\tres = nil\n\t}\n\treturn\n}", "func (a *LocalActivations) Find(name string) *Local {\n\tcurrent := a.Current()\n\tif current == nil {\n\t\treturn nil\n\t}\n\treturn current.Find(name)\n}", "func (f FileRepo) FindAddedByPeriod(context context.Context, start, end time.Time) ([]model.FileDTO, error) {\n\tquery := bson.M{\n\t\t\"addDate\": bson.M{\"$gte\": start, \"$lte\": end},\n\t}\n\tvar files model.Files\n\tcursor, err := f.collection.Find(context, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = cursor.All(context, &files)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn files.DTO(), nil\n}", "func extract_schedules(hull []fpoint) []vrp.Schedule {\n\tschedules := make([]vrp.Schedule, len(hull))\n\tfor i, h := range hull {\n\t\tschedules[i] = h.schedule\n\t}\n\treturn schedules\n}", "func (o TransferJobScheduleScheduleStartDatePtrOutput) Day() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TransferJobScheduleScheduleStartDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Day\n\t}).(pulumi.IntPtrOutput)\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekOutput) Day() ResourcePolicyWeeklyCycleDayOfWeekDayPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeek) *ResourcePolicyWeeklyCycleDayOfWeekDay { return v.Day }).(ResourcePolicyWeeklyCycleDayOfWeekDayPtrOutput)\n}", "func GetDailyMeetingsByBot(botID string, teamDailyMeetings *[]api.DailyMeeting) error {\n\n\t// TODO: we are not filtering by botID\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\t// Assume bucket exists and has keys\n\t\tb := tx.Bucket([]byte(\"dailymeetings\"))\n\t\tif b == nil {\n\t\t\treturn fmt.Errorf(\"dbutils: bucket dailymeetings not created\")\n\t\t}\n\n\t\td := b.Cursor()\n\t\tvar daily api.DailyMeeting\n\n\t\tfor k, v := d.First(); k != nil; k, v = d.Next() {\n\n\t\t\tbuf := *bytes.NewBuffer(v)\n\t\t\tdec := gob.NewDecoder(&buf)\n\t\t\tdec.Decode(&daily)\n\t\t\t*teamDailyMeetings = append(*teamDailyMeetings, daily)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn err\n}", "func dailyTestStatsFromHourlyPipeline(projectId string, requester string, start time.Time, end time.Time, tasks []string, lastUpdate time.Time) []bson.M {\n\tpipeline := []bson.M{\n\t\t{\"$match\": bson.M{\n\t\t\t\"_id.project\": projectId,\n\t\t\t\"_id.requester\": requester,\n\t\t\t\"_id.date\": bson.M{\"$gte\": start, \"$lt\": end},\n\t\t\t\"_id.task_name\": bson.M{\"$in\": tasks},\n\t\t}},\n\t\t{\n\t\t\t\"$group\": bson.M{\n\t\t\t\t\"_id\": bson.D{\n\t\t\t\t\t{Name: \"test_file\", Value: \"$_id.test_file\"},\n\t\t\t\t\t{Name: \"task_name\", Value: \"$_id.task_name\"},\n\t\t\t\t\t{Name: \"variant\", Value: \"$_id.variant\"},\n\t\t\t\t\t{Name: \"distro\", Value: \"$_id.distro\"},\n\t\t\t\t\t{Name: \"project\", Value: \"$_id.project\"},\n\t\t\t\t\t{Name: \"requester\", Value: \"$_id.requester\"},\n\t\t\t\t},\n\t\t\t\t\"num_pass\": bson.M{\"$sum\": \"$num_pass\"},\n\t\t\t\t\"num_fail\": bson.M{\"$sum\": \"$num_fail\"},\n\t\t\t\t\"total_duration_pass\": bson.M{\"$sum\": bson.M{\"$multiply\": array{\"$num_pass\", \"$avg_duration_pass\"}}},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"$project\": bson.M{\n\t\t\t\t\"_id\": 1,\n\t\t\t\t\"num_pass\": 1,\n\t\t\t\t\"num_fail\": 1,\n\t\t\t\t\"avg_duration_pass\": bson.M{\"$cond\": bson.M{\"if\": bson.M{\"$ne\": array{\"$num_pass\", 0}},\n\t\t\t\t\t\"then\": bson.M{\"$divide\": array{\"$total_duration_pass\", \"$num_pass\"}},\n\t\t\t\t\t\"else\": nil}},\n\t\t\t},\n\t\t},\n\t\t{\"$addFields\": bson.M{\n\t\t\t\"_id.date\": start,\n\t\t\t\"last_update\": lastUpdate,\n\t\t}},\n\t}\n\treturn pipeline\n}", "func GetStartedBy(entity ProjectEntity) string {\n\treturn composeutils.GetStartedBy(getProjectPrefix(entity), GetProjectName(entity))\n}", "func (q *InfluxQuery) GetAll(dateStart string) []Session {\n\n\t// Getting all activities\n\tdriveSessions := q.GetDrives(dateStart)\n\tchargeSessions := q.GetCharges(dateStart)\n\tsleepSessions := q.GetSleeps(dateStart)\n\n\ttotalSession := driveSessions\n\ttotalSession = append(totalSession, chargeSessions...)\n\ttotalSession = append(totalSession, sleepSessions...)\n\tsort.Slice(totalSession, func(i, j int) bool { return totalSession[i].Start < totalSession[j].Start })\n\n\t// Getting idle sessions\n\tvar lastEnd time.Time\n\tvar returnSession []Session\n\tfor i, v := range totalSession {\n\n\t\tstart, _ := time.Parse(time.RFC3339, v.Start)\n\t\tend, _ := time.Parse(time.RFC3339, v.End)\n\n\t\tv.Start = start.Format(\"15:04:05\")\n\t\tv.End = end.Format(\"15:04:05\")\n\n\t\tif len(totalSession) > i+1 {\n\n\t\t\tnextStart, _ := time.Parse(time.RFC3339, totalSession[i+1].Start)\n\n\t\t\tif nextStart.After(end.Add(time.Minute * 2)) {\n\n\t\t\t\treturnSession = append(returnSession, Session{\n\n\t\t\t\t\tType: \"idle\",\n\t\t\t\t\tStart: end.Format(\"15:04:05\"),\n\t\t\t\t\tEnd: nextStart.Format(\"15:04:05\"),\n\t\t\t\t\tData: q.getIdleData(end.Format(time.RFC3339), nextStart.Format(time.RFC3339)),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\treturnSession = append(returnSession, v)\n\t\tlastEnd = end\n\t}\n\n\tloc, err := time.LoadLocation(q.TimeZone)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tnow := time.Now().In(loc)\n\n\tif dateStart == now.Format(\"2006-01-02\") {\n\n\t\tif lastEnd.Add(time.Minute).Before(now) {\n\n\t\t\treturnSession = append(returnSession, Session{\n\t\t\t\tType: \"idle\",\n\t\t\t\tStart: lastEnd.Format(\"15:04:05\"),\n\t\t\t\tEnd: now.Format(\"15:04:05\"),\n\t\t\t\tData: q.getIdleData(lastEnd.Format(time.RFC3339), time.Now().Format(time.RFC3339)),\n\t\t\t})\n\t\t}\n\t}\n\n\t// Ordering and returning data\n\tsort.Slice(returnSession, func(i, j int) bool { return returnSession[i].Start < returnSession[j].Start })\n\treturn returnSession\n}", "func FindLogsFilialIntegracaoEndPoint(w http.ResponseWriter, r *http.Request) {\n\tenableCors(&w)\n\tparams := mux.Vars(r)\n\tlogs, err := logDAO.FindByIntegracaoFilial(params[\"integracao\"], params[\"codigo\"])\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\trespondWithJSON(w, http.StatusOK, logs)\n}", "func AllGamePending() []Game_Detail {\n\torm := get_DBFront()\n\tvar allGame, allPendingGame []Game_Detail\n\terr := orm.SetTable(\"game\").FindAll(&allGame)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_334\", err})\n\t\treturn allGame\n\t}\n\n\tfor _, v := range allGame {\n\t\tstartTime, _ := time.Parse(layout, v.Timestarted)\n\t\ttimeNow, _ := time.Parse(layout, time.Now().String())\n\t\tif startTime.Sub(timeNow) > 15*time.Minute {\n\t\t\tallPendingGame = append(allPendingGame, v)\n\t\t}\n\t}\n\n\tSliceReverse(allPendingGame)\n\treturn allPendingGame\n}" ]
[ "0.63564366", "0.49491245", "0.47966608", "0.47555003", "0.4714396", "0.47017792", "0.46695235", "0.44264024", "0.4393", "0.4355171", "0.43491647", "0.43194723", "0.42972758", "0.42735258", "0.42670387", "0.4263874", "0.4263281", "0.42480522", "0.4246253", "0.42045623", "0.41688672", "0.41577125", "0.41434887", "0.4131741", "0.41037303", "0.4101996", "0.40735376", "0.40729937", "0.40509197", "0.40300712", "0.40282068", "0.40213814", "0.40127602", "0.40062997", "0.40042615", "0.39743173", "0.39716414", "0.39691916", "0.3962718", "0.3950866", "0.39376482", "0.3927837", "0.3923399", "0.39223412", "0.39207163", "0.39056957", "0.3880653", "0.3880008", "0.38791254", "0.38757887", "0.3857384", "0.38498887", "0.384668", "0.38448918", "0.38314635", "0.3806811", "0.37995988", "0.37853646", "0.3777666", "0.3774243", "0.3760213", "0.37564766", "0.3744551", "0.3743418", "0.37404737", "0.37349966", "0.37324288", "0.37280792", "0.37258196", "0.3724511", "0.37141302", "0.36966562", "0.36925542", "0.36904386", "0.3685462", "0.3685393", "0.3681251", "0.3677758", "0.3675718", "0.36736184", "0.36660457", "0.3662552", "0.36582872", "0.36566415", "0.36377218", "0.3635958", "0.36216614", "0.3617031", "0.36102214", "0.36095664", "0.3606931", "0.36060536", "0.36044723", "0.36012983", "0.35908303", "0.3584876", "0.35836393", "0.358221", "0.3576186", "0.35726354" ]
0.81337386
0
FindFullByMonth finds all joined activity stages in a month
func (*ActivityStageDataAccessObject) FindFullByMonth( date time.Time) [][]ActivityStageFull { start := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.Local) end := start.AddDate(0, 1, 0).AddDate(0, 0, -1) result := make([][]ActivityStageFull, 0) for i := start.Day(); i <= end.Day(); i++ { curDate := time.Date(date.Year(), date.Month(), i, 0, 0, 0, 0, time.Local) result = append(result, ActivityStageDAO.FindFullByDay(curDate)) } return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*ActivityStageDataAccessObject) FindFullByDay(\n\tdate time.Time) []ActivityStageFull {\n\n\tstartDate := time.Date(date.Year(), date.Month(), date.Day(),\n\t\t0, 0, 0, 0, time.Local)\n\tendDate := startDate.AddDate(0, 0, 1)\n\tstart := startDate.Format(mysqlTimeFormat)\n\tend := time.Date(endDate.Year(), endDate.Month(), endDate.Day(),\n\t\t0, 0, 0, 0, time.Local).Format(mysqlTimeFormat)\n\tresult := make([]ActivityStageFull, 0)\n\n\terr := orm.Table(ActivityDAO.TableName()).\n\t\tWhere(\"activity_stages.activity_id=activities.id\").\n\t\tJoin(\"INNER\", ActivityStageDAO.TableName(),\n\t\t\"start_time>=?\", start).And(\"end_time<?\", end).\n\t\tFind(&result)\n\tlogger.LogIfError(err)\n\treturn result\n}", "func FetchByMonth(year int, month int) []history.OneCollection {\n\tif month < 1 || month > 12 {\n\t\treturn nil\n\n\t}\n\tcollections := FetchByYear(year)\n\tvar data []history.OneCollection\n\tfor _, collection := range collections {\n\t\tcollectionTime, _ := time.Parse(\"2006/01/02\", collection.End)\n\t\tif int(collectionTime.Month()) == month {\n\t\t\tdata = append(data, collection)\n\t\t}\n\t}\n\treturn data\n}", "func (s *Service) OfflineActivityQueryActivityByMonth(ctx context.Context, arg *offlineactivity.QueryActvityMonthArg) (res *offlineactivity.QueryActivityMonthResult, err error) {\n\tvar db = s.dao.OfflineActivityGetDB()\n\n\tvar bonusInfo []*offlineactivity.OfflineActivityBonus\n\tvar limit, offset = 100, 0\n\tvar lastCount = limit\n\tfor limit == lastCount {\n\t\tvar bonusInfoTmp []*offlineactivity.OfflineActivityBonus\n\t\tif err = db.Find(&bonusInfoTmp).Error; err != nil {\n\t\t\tlog.Error(\"get from db fail, err=%s\", err)\n\t\t\treturn\n\t\t}\n\t\tbonusInfo = append(bonusInfo, bonusInfoTmp...)\n\t\tlastCount = len(bonusInfoTmp)\n\t\toffset += lastCount\n\t}\n\n\tvar now = time.Now()\n\tvar dateStr = now.Format(dateFmt)\n\tvar monthDataMap = make(map[string]*offlineactivity.ActivityMonthInfo)\n\tfor _, v := range bonusInfo {\n\t\tvar date = v.CTime.Time().Format(\"200601\")\n\t\tvar monthData, ok = monthDataMap[date]\n\t\tif !ok {\n\t\t\tmonthData = &offlineactivity.ActivityMonthInfo{\n\t\t\t\tCreateTime: date,\n\t\t\t}\n\t\t\tmonthDataMap[date] = monthData\n\t\t\tmonthData.GenerateDay = dateStr\n\t\t}\n\t\tmonthData.AddBonus(v)\n\t}\n\n\tvar monthInfoS []*offlineactivity.ActivityMonthInfo\n\tfor _, v := range monthDataMap {\n\t\tmonthInfoS = append(monthInfoS, v)\n\t\tv.Finish()\n\t}\n\n\tsort.Slice(monthInfoS, func(i, j int) bool {\n\t\treturn monthInfoS[i].CreateTime > monthInfoS[j].CreateTime\n\t})\n\n\tvar lastIndex = len(monthInfoS) - 1\n\tif lastIndex >= 0 {\n\t\tmonthInfoS[lastIndex].TotalMoneyAccumulate = monthInfoS[lastIndex].TotalBonusMoneyMonth\n\t}\n\n\tfor i := len(monthInfoS) - 1; i > 0; i-- {\n\t\tmonthInfoS[i-1].TotalMoneyAccumulate = monthInfoS[i].TotalMoneyAccumulate + monthInfoS[i-1].TotalBonusMoneyMonth\n\t}\n\n\tres = new(offlineactivity.QueryActivityMonthResult)\n\tres.Result = monthInfoS\n\treturn\n}", "func byMonth(cmds []string, cmdInfo CommandInfo) {\n\tif !checkValid(cmds) {\n\t\tcmdInfo.createMsgEmbed(\"Error\", errThumbURL, \"Please specify 'bug' or 'fish'\", errColor,\n\t\t\tformat(createFields(\"EXAMPLE\", cmdInfo.Prefix+\"search south fish\", true)))\n\t\treturn\n\t}\n\tvar entries []models.Entry\n\tif cmds[0] == \"north\" {\n\t\tif strings.ToLower(cmds[1]) == \"bug\" {\n\t\t\tentries = cmdInfo.Service.Entry.ByMonth(\"north_hemi_months\", time.Now().Month().String(), \"bug\")\n\t\t} else {\n\t\t\tentries = cmdInfo.Service.Entry.ByMonth(\"north_hemi_months\", time.Now().Month().String(), \"fish\")\n\t\t}\n\t} else {\n\t\tif strings.ToLower(cmds[1]) == \"bug\" {\n\t\t\tentries = cmdInfo.Service.Entry.ByMonth(\"south_hemi_months\", time.Now().Month().String(), \"bug\")\n\t\t} else {\n\t\t\tentries = cmdInfo.Service.Entry.ByMonth(\"south_hemi_months\", time.Now().Month().String(), \"fish\")\n\t\t}\n\t}\n\tvar fields []*discordgo.MessageEmbedField\n\tfor _, val := range entries {\n\t\tfields = append(fields, createFields(strings.Title(removeUnderscore(val.Location)), strings.Title(removeUnderscore(val.Name)), true))\n\t}\n\tmassPrint(fields, \"Search By Hemisphere & Current Month\", strings.Title(cmds[0]), cmdInfo)\n}", "func MonthlyServiceFlavor(filter bson.M) []bson.M {\n\tquery := []bson.M{\n\t\t{\"$match\": filter},\n\t\t{\"$group\": bson.M{\n\t\t\t\"_id\": bson.M{\n\t\t\t\t\"date\": bson.D{{\"$substr\", list{\"$date\", 0, 6}}},\n\t\t\t\t\"name\": \"$name\",\n\t\t\t\t\"supergroup\": \"$supergroup\",\n\t\t\t\t\"report\": \"$report\"},\n\t\t\t\"avgup\": bson.M{\"$avg\": \"$up\"},\n\t\t\t\"avgunknown\": bson.M{\"$avg\": \"$unknown\"},\n\t\t\t\"avgdown\": bson.M{\"$avg\": \"$down\"}}},\n\t\t{\"$project\": bson.M{\n\t\t\t\"date\": \"$_id.date\",\n\t\t\t\"name\": \"$_id.name\",\n\t\t\t\"supergroup\": \"$_id.supergroup\",\n\t\t\t\"report\": \"$_id.report\",\n\t\t\t\"unknown\": \"$avgunknown\",\n\t\t\t\"up\": \"$avgup\",\n\t\t\t\"down\": \"$avgdown\",\n\t\t\t\"availability\": bson.M{\n\t\t\t\t\"$multiply\": list{\n\t\t\t\t\tbson.M{\"$divide\": list{\n\t\t\t\t\t\t\"$avgup\", bson.M{\"$subtract\": list{1.00000001, \"$avgunknown\"}}}},\n\t\t\t\t\t100}},\n\t\t\t\"reliability\": bson.M{\n\t\t\t\t\"$multiply\": list{\n\t\t\t\t\tbson.M{\"$divide\": list{\n\t\t\t\t\t\t\"$avgup\", bson.M{\"$subtract\": list{bson.M{\"$subtract\": list{1.00000001, \"$avgunknown\"}}, \"$avgdown\"}}}},\n\t\t\t\t\t100}}}},\n\t\t{\"$sort\": bson.D{\n\t\t\t{\"supergroup\", 1},\n\t\t\t{\"name\", 1},\n\t\t\t{\"date\", 1}}}}\n\treturn query\n}", "func (eg *entryGorm) ByMonth(colName, month, entryType string) []Entry {\n\tvar entries []Entry\n\tmon := strings.Title(month[:3])\n\teg.db.Table(\"bug_and_fish\").Where(colName+\" LIKE ? AND type = ?\", \"%\"+mon+\"%\", entryType).Find(&entries)\n\treturn entries\n}", "func (*ActivityStageDataAccessObject) FindAll() []ActivityStage {\n\tl := make([]ActivityStage, 0)\n\terr := orm.Table(ActivityStageDAO.TableName()).Find(&l)\n\n\tlogger.LogIfError(err)\n\treturn l\n}", "func MonthlyTotalSpent(startDate, endDate time.Time) ([]MonthTotals, error) {\n // query to return budget and ledger amount spent by month and year\n rows, err := db.Query(`SELECT\n mon,\n yyyy,\n sum(actual) as actual,\n sum(budget) as budget\n FROM\n (\n SELECT\n to_char(trans_date,'Mon') as mon, extract(year from trans_date) as yyyy,\n sum(credit-debit) as actual , 0 as budget, date_trunc('month', trans_date) as num_month\n FROM ledger\n WHERE trans_date >= $1 AND trans_date < $2\n GROUP BY mon, yyyy, date_trunc('month', trans_date)\n UNION ALL\n SELECT to_char(trans_date,'Mon') as mon, extract(year from trans_date) as yyyy,\n 0 as actual, sum(credit-debit) as budget, date_trunc('month', trans_date) as num_month\n FROM budget\n WHERE trans_date >= $1 AND trans_date < $2\n GROUP BY mon, yyyy, date_trunc('month', trans_date)\n ) x\n GROUP BY mon, yyyy, num_month\n ORDER BY yyyy, num_month ASC`, startDate, endDate)\n\n if err != nil {\n fmt.Println(err)\n return nil, err\n }\n defer rows.Close()\n\n var arrMonthTotals []MonthTotals\n\n for rows.Next() {\n var mt MonthTotals\n err := rows.Scan(&mt.Month, &mt.Year, &mt.LedgerTotal, &mt.BudgetTotal)\n if err != nil {\n fmt.Println(\"err: \", err)\n return nil, err\n }\n arrMonthTotals = append(arrMonthTotals, mt)\n }\n\n if err = rows.Err(); err != nil {\n fmt.Println(\"error scanning a row\", err)\n return nil, err\n }\n\n return arrMonthTotals, nil\n}", "func (d *Dao) GetAllMonthExpenseInfo(c context.Context, month, beginMonth string, ctype, from, limit int) (infos []*model.BudgetMonthStatistics, err error) {\n\trows, err := d.rddb.Query(c, _getAllMonthExpenseSQL, month, beginMonth, ctype, from, limit)\n\tif err != nil {\n\t\tlog.Error(\"dao.GetAllMonthExpenseInfo query error(%v)\", err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\ta := &model.BudgetMonthStatistics{}\n\t\tif err = rows.Scan(&a.MonthExpense, &a.UpCount, &a.AvCount, &a.UpAvgExpense, &a.AvAvgExpense, &a.TotalExpense, &a.Date, &a.Month); err != nil {\n\t\t\tlog.Error(\"dao.GetAllMonthExpenseInfo scan error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t\tinfos = append(infos, a)\n\t}\n\terr = rows.Err()\n\treturn\n}", "func (m Month) Includes(t time.Time) bool {\n\treturn t.Month() == time.Month(m)\n}", "func (filter TaskReliabilityFilter) buildMatchStageForTask() bson.M {\n\tboundaries := filter.dateBoundaries()\n\n\tstart := boundaries[0]\n\tend := boundaries[len(boundaries)-1]\n\n\tmatch := bson.M{\n\t\ttaskstats.DBTaskStatsIDDateKeyFull: bson.M{\n\t\t\t\"$lt\": start,\n\t\t\t\"$gte\": end,\n\t\t},\n\t\ttaskstats.DBTaskStatsIDProjectKeyFull: filter.Project,\n\t\ttaskstats.DBTaskStatsIDRequesterKeyFull: bson.M{\"$in\": filter.Requesters},\n\t}\n\tif len(filter.Tasks) > 0 {\n\t\tmatch[taskstats.DBTaskStatsIDTaskNameKeyFull] = taskstats.BuildMatchArrayExpression(filter.Tasks)\n\t}\n\tif len(filter.BuildVariants) > 0 {\n\t\tmatch[taskstats.DBTaskStatsIDBuildVariantKeyFull] = taskstats.BuildMatchArrayExpression(filter.BuildVariants)\n\t}\n\tif len(filter.Distros) > 0 {\n\t\tmatch[taskstats.DBTaskStatsIDDistroKeyFull] = taskstats.BuildMatchArrayExpression(filter.Distros)\n\t}\n\n\tif filter.StartAt != nil {\n\t\tmatch[\"$or\"] = filter.buildTaskPaginationOrBranches()\n\t}\n\treturn bson.M{\"$match\": match}\n}", "func getPrsPerMonth(date date, count int) ([]nodes, error) {\n\tsrc := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: *token},\n\t)\n\thttpClient := oauth2.NewClient(context.Background(), src)\n\tclient := githubv4.NewEnterpriseClient(\"https://api.github.com/graphql\", httpClient)\n\n\tvar query struct {\n\t\tSearch struct {\n\t\t\tNodes []nodes\n\t\t} `graphql:\"search(first: $count, query: $searchQuery, type: ISSUE)\"`\n\t}\n\n\tvariables := map[string]interface{}{\n\t\t\"searchQuery\": githubv4.String(fmt.Sprintf(`repo:ministryofjustice/cloud-platform-infrastructure is:pr is:closed merged:%s..%s`, date.first.Format(\"2006-01-02\"), date.last.Format(\"2006-01-02\"))),\n\t\t\"count\": githubv4.Int(count),\n\t}\n\n\terr := client.Query(context.Background(), &query, variables)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn query.Search.Nodes, nil\n}", "func (filter TaskReliabilityFilter) BuildMatchStageForTask(boundaries []time.Time) bson.M {\n\tstart := boundaries[0]\n\tend := boundaries[len(boundaries)-1]\n\n\tmatch := bson.M{\n\t\tstats.DbTaskStatsIdDateKeyFull: bson.M{\n\t\t\t\"$lt\": start,\n\t\t\t\"$gte\": end,\n\t\t},\n\t\tstats.DbTestStatsIdProjectKeyFull: filter.Project,\n\t\tstats.DbTestStatsIdRequesterKeyFull: bson.M{\"$in\": filter.Requesters},\n\t}\n\tif len(filter.Tasks) > 0 {\n\t\tmatch[stats.DbTaskStatsIdTaskNameKeyFull] = stats.BuildMatchArrayExpression(filter.Tasks)\n\t}\n\tif len(filter.BuildVariants) > 0 {\n\t\tmatch[stats.DbTaskStatsIdBuildVariantKeyFull] = stats.BuildMatchArrayExpression(filter.BuildVariants)\n\t}\n\tif len(filter.Distros) > 0 {\n\t\tmatch[stats.DbTaskStatsIdDistroKeyFull] = stats.BuildMatchArrayExpression(filter.Distros)\n\t}\n\n\tif filter.StartAt != nil {\n\t\tmatch[\"$or\"] = filter.BuildTaskPaginationOrBranches()\n\t}\n\n\treturn bson.M{\"$match\": match}\n}", "func (p Paygen) FilterMilestone(milestone int) *Paygen {\n\tvar filtered Paygen\n\tfor _, delta := range p.Deltas {\n\t\tif delta.Milestone == milestone {\n\t\t\tfiltered.Deltas = append(filtered.Deltas, delta)\n\t\t}\n\t}\n\n\treturn &filtered\n}", "func (dt DateTime) SpanMonth() (DateTime, DateTime) {\n\treturn dt.FloorMonth(), dt.CeilMonth()\n}", "func (ms *MySQLStore) GetCompletedWithinMonth(userID int64) ([]*tasks.Task, error) {\n\tquery := \"SELECT ID, Name, Description, IsComplete, IsHidden, CreatedAt, EditedAt FROM TodoList WHERE UserID = ? AND CreatedAt > DATEADD(month,-1,GETDATE()) AND IsComplete\"\n\trows, err := ms.Client.Query(query, userID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\t// Extract each task\n\ttodoList := []*tasks.Task{}\n\tfor rows.Next() {\n\t\tdescription := sql.NullString{}\n\t\ttask := &tasks.Task{}\n\t\tif err := rows.Scan(&task.ID, &task.Name, &description, &task.IsComplete,\n\t\t\t&task.IsHidden, &task.CreatedAt, &task.EditedAt); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttask.Description = description.String\n\t\ttodoList = append(todoList, task)\n\t}\n\n\t// Set all todoList to the same user\n\tuser, err := ms.UserStore.GetByID(userID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, task := range todoList {\n\t\ttask.User = user\n\t}\n\n\treturn todoList, nil\n}", "func generateTimeFilterStage(rangeInitDays, rangeEndDays int) []bson.M {\n\treturn []bson.M{\n\t\tbson.M{\n\t\t\t\"$match\": bson.M{\n\t\t\t\t\"finishedAt\": bson.M{\n\t\t\t\t\t\"$gte\": util.BeginningOfTheDay(time.Now().AddDate(0, 0, rangeInitDays)),\n\t\t\t\t\t\"$lte\": util.EndOfTheDay(time.Now().AddDate(0, 0, rangeEndDays)),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func FromLocalMonth(month tyme.LocalMonth) IntermediateTime {\n\tdateTime := time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, time.Local)\n\treturn IntermediateTime(dateTime)\n}", "func PrintListByMonth(e *Event, s string) {\n\tfor i := e; i != nil; i = i.Next {\n\t\tif i.Month == s {\n\t\t\tfmt.Println(i.Name, i.Link, i.Month, i.Days, i.Year, i.IndividualDays)\n\t\t}\n\t}\n}", "func MonthInList(time *time.Time, months []int) bool {\n\treturn fieldInList(time.Month, months)\n}", "func filterConditionByMonthOrAndLine(time time.Time, lineNo ...int) bson.M {\n\tvar filter bson.M\n\tif lineNo != nil {\n\t\tfilter = bson.M{\n\t\t\t\"income.income_month\": bson.M{\"$eq\": time},\n\t\t\t\"line.line_no\": bson.M{\"$eq\": lineNo[0]},\n\t\t}\n\t} else {\n\t\tfilter = bson.M{\n\t\t\t\"income.income_month\": bson.M{\"$eq\": time},\n\t\t}\n\t}\n\tglog.Infof(\"filter content is : %#v\", filter)\n\treturn filter\n}", "func splitIntoBounds(month time.Time) (string, string) {\n\tconst iso8601 = \"2006-01-02\"\n\n\ty, m, _ := month.Date()\n\tfirstOfMonth := time.Date(y, m, 1, 0, 0, 0, 0, time.UTC)\n\tfirstOfNextMonth := firstOfMonth.AddDate(0, 1, 0)\n\n\tstart := firstOfMonth.Format(iso8601)\n\tend := firstOfNextMonth.Format(iso8601)\n\n\treturn start, end\n}", "func (s *EventDatabase) GetEventsForMonth(ctx context.Context, date time.Time) ([]*eventapi.Event, error) {\n\tstartTime := date.Truncate(24 * time.Hour)\n\tendTime := date.Truncate(24*time.Hour).AddDate(0, 1, 0)\n\treturn s.getEvents(ctx, startTime, endTime)\n}", "func (d *DetailedActionCommitments) GetAll(year int64, db *sql.DB) (err error) {\n\tsy := strconv.FormatInt(year, 10)\n\trows, err := db.Query(`SELECT budget.chapter, budget.sector, budget.subfunction, \n\t\tbudget.program, budget.action, budget.action_name, op.number, op.name, \n\t\tpg.value AS y0, ct.y1, ct.y2, ct.y3\n\tFROM physical_op op\n\tLEFT OUTER JOIN (SELECT * FROM\n\t\tcrosstab('SELECT pc.physical_op_id, pc.year, pc.value*0.01 FROM \n\t\t\t\t\t\t\t(SELECT * FROM prev_commitment WHERE year>=`+sy+` AND year<=`+sy+`+2) pc\n\t\t\t\t\t\t\tORDER BY 1,2',\n\t\t\t\t\t\t'SELECT m FROM generate_series(`+sy+`,`+sy+`+ 2) AS m')\n\t\tAS (physical_op_id INTEGER, y1 NUMERIC, y2 NUMERIC, y3 NUMERIC)) ct\n\tON ct.physical_op_id = op.id \n\tLEFT OUTER JOIN (SELECT physical_op_id, SUM(value) * 0.01 AS value \n\t\tFROM programmings WHERE year = $1 GROUP BY 1) pg ON pg.physical_op_id = op.id\n\tLEFT OUTER JOIN \n\t\t(SELECT ba.id, bc.code AS chapter, bs.code AS sector, \n\t\t\tbp.code_function || COALESCE(bp.code_subfunction, '') AS subfunction,\n\t\t\tbp.code_contract || bp.code_function || bp.code_number as program,\n\t\t\tbp.code_contract || bp.code_function || bp.code_number || ba.code as action, \n\t\t\tba.name AS action_name\n\t\t\tFROM budget_chapter bc, budget_program bp, budget_action ba, budget_sector bs\n\t\t\tWHERE ba.program_id=bp.id AND bp.chapter_id=bc.id AND ba.sector_id=bs.id) AS budget\n\t\tON op.budget_action_id = budget.id\n\tWHERE pg.value IS NOT NULL OR (ct.y1<>0 AND ct.y1 NOTNULL) OR \n\t\t(ct.y2<>0 AND ct.y2 NOTNULL) OR (ct.y3<>0 AND ct.y3 NOTNULL)\n\tORDER BY 1, 2, 3, 4, 5`, year)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar r DetailedActionCommitment\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tif err = rows.Scan(&r.Chapter, &r.Sector, &r.Subfunction, &r.Program, &r.Action,\n\t\t\t&r.ActionName, &r.Name, &r.Number, &r.Y0, &r.Y1, &r.Y2, &r.Y3); err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.DetailedActionCommitments = append(d.DetailedActionCommitments, r)\n\t}\n\terr = rows.Err()\n\tif len(d.DetailedActionCommitments) == 0 {\n\t\td.DetailedActionCommitments = []DetailedActionCommitment{}\n\t}\n\treturn err\n}", "func (t Time) Month() Month {}", "func Months(months ...time.Month) TemporalExpression {\n\tee := make([]TemporalExpression, len(months))\n\tfor i, m := range months {\n\t\tee[i] = Month(m)\n\t}\n\treturn Or(ee...)\n}", "func (ln *localen) MonthAbbreviated(month time.Month) string {\n\treturn ln.fnMonthAbbreviated(ln, month)\n}", "func (ms *MySQLStore) GetAllWithinMonth(userID int64) ([]*tasks.Task, error) {\n\tquery := \"SELECT ID, Name, Description, IsComplete, IsHidden, CreatedAt, EditedAt FROM TodoList WHERE UserID = ? AND CreatedAt > DATEADD(month,-1,GETDATE())\"\n\trows, err := ms.Client.Query(query, userID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\t// Extract each task\n\ttodoList := []*tasks.Task{}\n\tfor rows.Next() {\n\t\tdescription := sql.NullString{}\n\t\ttask := &tasks.Task{}\n\t\tif err := rows.Scan(&task.ID, &task.Name, &description, &task.IsComplete,\n\t\t\t&task.IsHidden, &task.CreatedAt, &task.EditedAt); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttask.Description = description.String\n\t\ttodoList = append(todoList, task)\n\t}\n\n\t// Set all todoList to the same user\n\tuser, err := ms.UserStore.GetByID(userID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, task := range todoList {\n\t\ttask.User = user\n\t}\n\n\treturn todoList, nil\n}", "func (o InstanceDenyMaintenancePeriodStartDateOutput) Month() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceDenyMaintenancePeriodStartDate) *int { return v.Month }).(pulumi.IntPtrOutput)\n}", "func (incident *Incident) isResolvedInMonthYear(month int, year int) bool {\n\tvar resolvedTime time.Time\n\tif incident.CorrectedTime != \"\" {\n\t\tresolvedTime = incident.CorrectedSolved\n\t} else {\n\t\tresolvedTime = incident.SolvedAt\n\t}\n\treturn resolvedTime.Year() == year && int(resolvedTime.Month()) == month\n}", "func (mr MonthRangeExpression) Includes(t time.Time) bool {\n\tm := t.Month()\n\treturn mr.Start <= m && m <= mr.End\n}", "func Month() int {\n\tt_start, _ := time.Parse(layout, app_start)\n\tt_now, _ := time.Parse(layout, time.Now().Format(layout))\n\ti := 0\n\tfor {\n\t\ti += 1\n\t\tif t_start.AddDate(0, i, 0).After(t_now) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn 0\n}", "func (t *SmartContract) query_by_month(stub shim.ChaincodeStubInterface, args []string, flag int) pb.Response {\n\n if len(args) != 4 {\n return shim.Error(\"Incorrect number of arguments. Expecting 4(Id, gatewayId, monthStart, monthEnd)\")\n }\n\n id := args[0]\n gatewayid := args[1]\n\tmonthStart := args[2]\n\tmonthEnd := args[3]\n\n\t//Get State of CompositeKey \"Id~GIdTimestamp\"\n\tidResultsIterator, err := stub.GetStateByPartialCompositeKey(\"Id~GIdTimestamp\", []string{id})\n\n if err != nil {\n return shim.Error(\"Fail to partial Composite key!\")\n }\n defer idResultsIterator.Close()\n\n\n var buffer bytes.Buffer\n buffer.WriteString(\"\\n[\")\n\n bArrayMemberAlreadyWritten := false\n for idResultsIterator.HasNext() {\n queryResponse, err := idResultsIterator.Next()\n if err != nil {\n return shim.Error(err.Error())\n }\n\n objectType, compositeKeys, err := stub.SplitCompositeKey(string(queryResponse.Key))\n fmt.Printf(\"%s\", objectType)\n returnKey := compositeKeys[1]\n\n //fmt.Println(compositeKeys[0])\tId~GIdTimestampId\n //fmt.Println(compositeKeys[1])\tGatewayId,Id,Timestamp\n\n // Get the attribute of return key\n valAsbytes, err := stub.GetState(returnKey)\n if err != nil {\n return shim.Error(\"Failed to get smartmeter:\" + err.Error())\n } else if valAsbytes == nil {\n return shim.Error(\"Smartmeter does not exist\")\n }\n\n // Retrieve the valAsbytes and check the input gatewayId\n Sep_gatewayId := Smartmeter{}\n err = json.Unmarshal(valAsbytes, &Sep_gatewayId) //unmarshal it\n if err != nil {\n return shim.Error(err.Error())\n }\n\n\t\t// Compare GatewatId and Timestamp, >= monthStart && < (month of monthEnd)+1\n if Sep_gatewayId.GatewayId == gatewayid {\n\t\t\tmonthOfEnd, err := strconv.Atoi(strings.SplitAfter(monthEnd, \"-\")[1])\n\t\t\tif err != nil {\n\t\t\t\treturn shim.Error(err.Error())\n\t\t\t}\n\n\t\t\tif Sep_gatewayId.Timestamp >= monthStart && Sep_gatewayId.Timestamp < (strings.SplitAfter(monthEnd, \"-\")[0] + strconv.Itoa(monthOfEnd + 1)) {\n\t\t\t\tif flag == 0 {\n\n\t\t\t\t\tif bArrayMemberAlreadyWritten == true {\n\t\t\t\t\t\tbuffer.WriteString(\",\")\n\t\t\t\t\t}\n\t\t\t\t\tbuffer.WriteString(\"{\\\"Key\\\":\")\n\t\t\t\t\tbuffer.WriteString(\"\\\"\")\n\t\t\t\t\tbuffer.WriteString(returnKey)\n\t\t\t\t\tbuffer.WriteString(\"\\\"\")\n\t\t\t\t\tbuffer.WriteString(\", \\\"Record\\\":\")\n\t\t\t\t\tbuffer.WriteString(string(valAsbytes))\n\t\t\t\t\tbuffer.WriteString(\"}\")\n\t\t\t\t\tbArrayMemberAlreadyWritten = true\n\n\t\t\t\t}else if Sep_gatewayId.Status == \"A\"{\n\t\t\t\t\tabnormal += 1\n\t\t\t\t}\n\n\t\t\t\t// Change string to float and compute the consumption\n\t\t\t\tparse, err := strconv.ParseFloat(Sep_gatewayId.Consumption, 8)\n\t\t\t\tif err != nil {\n\t\t return shim.Error(\"Failed to compute the consumption:\")\n\t\t\t\t}\n\t\t\t\tconsumption += parse\n\t\t\t}\n\t\t}\n }\n\n buffer.WriteString(\"]\\n\")\n return shim.Success(buffer.Bytes())\n}", "func (c *Client) FindCrmStages(criteria *Criteria, options *Options) (*CrmStages, error) {\n\tcss := &CrmStages{}\n\tif err := c.SearchRead(CrmStageModel, criteria, options, css); err != nil {\n\t\treturn nil, err\n\t}\n\treturn css, nil\n}", "func OptmonthByEquinoxLrn(db XODB, equinoxLrn int64) (*Optmonth, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`ommonth, omcustsnqservs1, omcustsnqservs2, omcustsnqservs3, omcustsnqservs4, omcustsnqservs5, omcustsqservs1, omcustsqservs2, omcustsqservs3, omcustsqservs4, omcustsqservs5, equinox_prn, equinox_lrn, equinox_sec ` +\n\t\t`FROM equinox.optmonth ` +\n\t\t`WHERE equinox_lrn = $1`\n\n\t// run query\n\tXOLog(sqlstr, equinoxLrn)\n\to := Optmonth{}\n\n\terr = db.QueryRow(sqlstr, equinoxLrn).Scan(&o.Ommonth, &o.Omcustsnqservs1, &o.Omcustsnqservs2, &o.Omcustsnqservs3, &o.Omcustsnqservs4, &o.Omcustsnqservs5, &o.Omcustsqservs1, &o.Omcustsqservs2, &o.Omcustsqservs3, &o.Omcustsqservs4, &o.Omcustsqservs5, &o.EquinoxPrn, &o.EquinoxLrn, &o.EquinoxSec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &o, nil\n}", "func (ln *localen) MonthsAbbreviated() []string {\n\treturn ln.monthsAbbreviated\n}", "func monthlyVestTimes(startTime time.Time, months int, timeOfDay time.Time) ([]time.Time, error) {\n\tif months < 1 {\n\t\treturn nil, fmt.Errorf(\"must have at least one vesting period\")\n\t}\n\tlocation := startTime.Location()\n\thour := timeOfDay.Hour()\n\tminute := timeOfDay.Minute()\n\tsecond := timeOfDay.Second()\n\ttimes := make([]time.Time, months)\n\tfor i := 1; i <= months; i++ {\n\t\ttm := startTime.AddDate(0, i, 0)\n\t\tif tm.Day() != startTime.Day() {\n\t\t\t// The starting day-of-month cannot fit in this month,\n\t\t\t// and we've wrapped to the next month. Back up to the\n\t\t\t// end of the previous month.\n\t\t\ttm = tm.AddDate(0, 0, -tm.Day())\n\t\t}\n\t\ttimes[i-1] = time.Date(tm.Year(), tm.Month(), tm.Day(), hour, minute, second, 0, location)\n\t}\n\t// Integrity check: dates must be sequential and 26-33 days apart.\n\tlastTime := startTime\n\tfor _, tm := range times {\n\t\tduration := tm.Sub(lastTime)\n\t\tif duration < 26*24*time.Hour {\n\t\t\treturn nil, fmt.Errorf(\"vesting dates too close: %v and %v\", lastTime, tm)\n\t\t}\n\t\tif duration > 33*24*time.Hour {\n\t\t\treturn nil, fmt.Errorf(\"vesting dates too distant: %v and %v\", lastTime, tm)\n\t\t}\n\t\tlastTime = tm\n\t}\n\treturn times, nil\n}", "func funcMonth(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\treturn dateWrapper(vals, enh, func(t time.Time) float64 {\n\t\treturn float64(t.Month())\n\t})\n}", "func FormatMonthLongLocal(t time.Time, timeZone string) string {\n\tloc := GetLocation(timeZone)\n\tlocalDate := t.In(loc)\n\treturn localDate.Format(layoutMonthLong)\n}", "func getCoveredMonths(start, end time.Time) []string {\n\tmonths := []string{start.Format(timestamp.MonthLayout)}\n\n\tmonth := start.Month()\n\tfor start.Before(end) {\n\t\tstart = start.Add(time.Hour * 24)\n\t\tnextMonth := start.Month()\n\t\tif nextMonth != month {\n\t\t\tmonths = append(months, start.Format(timestamp.MonthLayout))\n\t\t}\n\t\tmonth = nextMonth\n\t}\n\n\treturn months\n}", "func (c *StatsGetQueryCall) FromDateMonth(fromDateMonth int64) *StatsGetQueryCall {\n\tc.urlParams_.Set(\"fromDate.month\", fmt.Sprint(fromDateMonth))\n\treturn c\n}", "func (date Nakamura) Month() string {\n\treturn Month(date.date, date.format)\n}", "func (my *AttunedMonth) Contains(d int) bool {\n\treturn d >= 1 && d <= my.lastDay\n}", "func (o InstanceDenyMaintenancePeriodEndDateOutput) Month() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceDenyMaintenancePeriodEndDate) *int { return v.Month }).(pulumi.IntPtrOutput)\n}", "func (c *StatsGetSearchapplicationCall) StartDateMonth(startDateMonth int64) *StatsGetSearchapplicationCall {\n\tc.urlParams_.Set(\"startDate.month\", fmt.Sprint(startDateMonth))\n\treturn c\n}", "func GetSortedTwoMonthComparedIncomesByDate(c *gin.Context) {\n\tstatus := http.StatusBadRequest\n\tvar results interface{}\n\tif ok, year, month := util.ConvertYearAndMonth(c.Param(\"year\"), c.Param(\"month\")); ok {\n\t\ttime := util.GetMonthlyStandardTime(year, month)\n\t\tresults = s.SortMonthLinesIncomes(s.GetTwoNextMonthIncomes(time))\n\t\tstatus = http.StatusOK\n\t}\n\tc.JSON(status, results)\n}", "func DailyServiceFlavor(filter bson.M) []bson.M {\n\tquery := []bson.M{\n\t\t{\"$match\": filter},\n\t\t{\"$group\": bson.M{\n\t\t\t\"_id\": bson.M{\n\t\t\t\t\"date\": bson.D{{\"$substr\", list{\"$date\", 0, 8}}},\n\t\t\t\t\"name\": \"$name\",\n\t\t\t\t\"supergroup\": \"$supergroup\",\n\t\t\t\t\"availability\": \"$availability\",\n\t\t\t\t\"reliability\": \"$reliability\",\n\t\t\t\t\"unknown\": \"$unknown\",\n\t\t\t\t\"up\": \"$up\",\n\t\t\t\t\"down\": \"$down\",\n\t\t\t\t\"report\": \"$report\"}}},\n\t\t{\"$project\": bson.M{\n\t\t\t\"date\": \"$_id.date\",\n\t\t\t\"name\": \"$_id.name\",\n\t\t\t\"availability\": \"$_id.availability\",\n\t\t\t\"reliability\": \"$_id.reliability\",\n\t\t\t\"unknown\": \"$_id.unknown\",\n\t\t\t\"up\": \"$_id.up\",\n\t\t\t\"down\": \"$_id.down\",\n\t\t\t\"supergroup\": \"$_id.supergroup\",\n\t\t\t\"report\": \"$_id.report\"}},\n\t\t{\"$sort\": bson.D{\n\t\t\t{\"supergroup\", 1},\n\t\t\t{\"name\", 1},\n\t\t\t{\"date\", 1}}}}\n\n\treturn query\n}", "func (c *Client) FindCrmStage(criteria *Criteria) (*CrmStage, error) {\n\tcss := &CrmStages{}\n\tif err := c.SearchRead(CrmStageModel, criteria, NewOptions().Limit(1), css); err != nil {\n\t\treturn nil, err\n\t}\n\tif css != nil && len(*css) > 0 {\n\t\treturn &((*css)[0]), nil\n\t}\n\treturn nil, fmt.Errorf(\"crm.stage was not found with criteria %v\", criteria)\n}", "func (c *StatsGetSearchapplicationCall) EndDateMonth(endDateMonth int64) *StatsGetSearchapplicationCall {\n\tc.urlParams_.Set(\"endDate.month\", fmt.Sprint(endDateMonth))\n\treturn c\n}", "func (o TransferJobScheduleScheduleStartDatePtrOutput) Month() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TransferJobScheduleScheduleStartDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Month\n\t}).(pulumi.IntPtrOutput)\n}", "func (t *TwoYearsCommitments) Get(db *sql.DB) error {\n\tquery := `WITH cmt_month as \n\t(SELECT MAX(EXTRACT(month FROM creation_date))::int max_month\n \tFROM commitment WHERE year=$1)\n\tSELECT cmt.m,SUM(0.01 * cmt.v) OVER (ORDER BY m) FROM\n\t\t(SELECT q.m as m,COALESCE(sum_cmt.v,0) v FROM\n\t\t\t(SELECT GENERATE_SERIES(1,max_month) m FROM cmt_month) q\n\t\t\tLEFT OUTER JOIN\n\t\t\t(SELECT EXTRACT(month FROM creation_date)::int m,SUM(value)::bigint v\n\t\t\tFROM commitment WHERE year=$1 GROUP BY 1) sum_cmt\n\t\tON sum_cmt.m=q.m) cmt;`\n\tactualYear := time.Now().Year()\n\trows, err := db.Query(query, actualYear)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\tvar row MonthCumulatedValue\n\tfor rows.Next() {\n\t\tif err = rows.Scan(&row.Month, &row.Value); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tt.CurrentYear = append(t.CurrentYear, row)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(t.CurrentYear) == 0 {\n\t\tt.CurrentYear = []MonthCumulatedValue{}\n\t}\n\trows, err = db.Query(query, actualYear-1)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tif err = rows.Scan(&row.Month, &row.Value); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tt.PreviousYear = append(t.PreviousYear, row)\n\t}\n\terr = rows.Err()\n\tif len(t.PreviousYear) == 0 {\n\t\tt.PreviousYear = []MonthCumulatedValue{}\n\t}\n\treturn err\n}", "func (c *StatsQuerySearchapplicationsGetCall) FromDateMonth(fromDateMonth int64) *StatsQuerySearchapplicationsGetCall {\n\tc.urlParams_.Set(\"fromDate.month\", fmt.Sprint(fromDateMonth))\n\treturn c\n}", "func FetchMonthHolidayCount(year int, month int) int {\n\tcollections := FetchByMonth(year, month)\n\tvar count int\n\tfor _, collection := range collections {\n\t\tcount += countOneHoliday(collection)\n\t}\n\treturn count\n}", "func (c *StatsGetIndexCall) FromDateMonth(fromDateMonth int64) *StatsGetIndexCall {\n\tc.urlParams_.Set(\"fromDate.month\", fmt.Sprint(fromDateMonth))\n\treturn c\n}", "func (c *StatsGetIndexCall) FromDateMonth(fromDateMonth int64) *StatsGetIndexCall {\n\tc.urlParams_.Set(\"fromDate.month\", fmt.Sprint(fromDateMonth))\n\treturn c\n}", "func (dt DateTime) FloorMonth() DateTime {\n\treturn dt.Replace(dt.Year(), dt.Month(), 1, 0, 0, 0, 0)\n}", "func (c *StatsUserSearchapplicationsGetCall) FromDateMonth(fromDateMonth int64) *StatsUserSearchapplicationsGetCall {\n\tc.urlParams_.Set(\"fromDate.month\", fmt.Sprint(fromDateMonth))\n\treturn c\n}", "func (c *StatsIndexDatasourcesGetCall) FromDateMonth(fromDateMonth int64) *StatsIndexDatasourcesGetCall {\n\tc.urlParams_.Set(\"fromDate.month\", fmt.Sprint(fromDateMonth))\n\treturn c\n}", "func (c *StatsIndexDatasourcesGetCall) FromDateMonth(fromDateMonth int64) *StatsIndexDatasourcesGetCall {\n\tc.urlParams_.Set(\"fromDate.month\", fmt.Sprint(fromDateMonth))\n\treturn c\n}", "func (o TransferJobScheduleScheduleEndDatePtrOutput) Month() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TransferJobScheduleScheduleEndDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Month\n\t}).(pulumi.IntPtrOutput)\n}", "func (c *StatsSessionSearchapplicationsGetCall) FromDateMonth(fromDateMonth int64) *StatsSessionSearchapplicationsGetCall {\n\tc.urlParams_.Set(\"fromDate.month\", fmt.Sprint(fromDateMonth))\n\treturn c\n}", "func (r DasboardRepository) GetData(q validator.DashboardRequest) (*model.Dashboard, error) {\n\tnow := time.Now()\n\tif q.MonthStart.IsZero() {\n\t\tq.MonthStart = time.Date(now.Year(), time.January, 1, 0, 0, 0, 0, time.Local)\n\t}\n\tif q.MonthEnd.IsZero() {\n\t\tq.MonthEnd = time.Date(now.Year(), time.December, 31, 0, 0, 0, 0, time.Local)\n\t}\n\n\tsql := `select x.yearmonth,x.type,sum(x.count) count,sum(x.alerts) alerts,sum(x.news) news,sum(x.bigger) bigger\n\tfrom (\n\t\tselect q.yearmonth,q.type,count(*) count,sum(q.alerts) alerts,0 news,0 bigger\n\t\tfrom (\n\t\t\tselect to_char(a.created_at, 'YYYY-MM') yearmonth,a.type,(\n\t\t\t\tselect count(*) from alert_user where alert_user.alert_id=a.id\n\t\t\t) alerts\n\t\t\tfrom alert a\n\t\t) q\n\t\t group by q.yearmonth,q.type\n\t\tunion all\n\t\tselect to_char(c.created_at, 'YYYY-MM') yearmonth,4,0,0,count(*),0\n\t\tfrom customer c\n\t\tgroup by yearmonth\n\t\tunion all\n\t\tselect to_char(u.created_at, 'YYYY-MM') yearmonth,3,0,0,count(*),0\n\t\tfrom \"user\" u\n\t\tgroup by yearmonth\n\t\tunion all\n\t\tselect to_char(p.created_at, 'YYYY-MM') yearmonth,1,0,0,count(*),0\n\t\tfrom public_agent p\n\t\tgroup by yearmonth\n\t\tunion all\n\t\tselect z.yearmonth,1,0,0,0,count(*)\n\t\tfrom (\n\t\t\tselect to_char(a.created_at, 'YYYY-MM') yearmonth,a.type,(\n\t\t\t\tselect count(*) from alert_user where alert_user.alert_id=a.id\n\t\t\t) alerts\n\t\t\tfrom alert a\n\t\t\twhere a.type=2 and not a.public_agent_id is null\n\t\t) z\n\t\t group by z.yearmonth,z.type\n\t) x\n\twhere x.yearmonth >= ? and x.yearmonth <= ?\n\tgroup by x.yearmonth,x.type\n\torder by x.yearmonth,x.type`\n\tresults, err := r.DB.Query(sql, q.MonthStart.Format(YearMonthFormat), q.MonthEnd.Format(YearMonthFormat))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsqlTotal := `select 4 \"type\",count(*) count\n\tfrom customer c\n\tunion all\n\tselect 3,count(*)\n\tfrom \"user\" u\n\tunion all\n\tselect 1,count(*)\n\tfrom public_agent p`\n\n\ttotals, err := r.DB.Query(sqlTotal)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td := builder.DashboardFromDB(results, totals)\n\n\treturn d, nil\n}", "func (d *Dao) RelationFansMonthCache(c context.Context, mid int64, dt string) (res map[string]map[string]int, err error) {\n\tvar (\n\t\tconn = d.mc.Get(c)\n\t\tr *memcache.Item\n\t)\n\tdefer conn.Close()\n\tr, err = conn.Get(keyRfm(mid, dt))\n\tif err != nil {\n\t\tif err == memcache.ErrNotFound {\n\t\t\terr = nil\n\t\t} else {\n\t\t\tlog.Error(\"conn.Get(%d) error(%v)\", mid, err)\n\t\t}\n\t\treturn\n\t}\n\tif err = conn.Scan(r, &res); err != nil {\n\t\tlog.Error(\"json.Unmarshal(%s) error(%v)\", r.Value, err)\n\t\tres = nil\n\t}\n\treturn\n}", "func MonthlyEndpointGroup(filter bson.M) []bson.M {\n\n\t// Mongo aggregation pipeline\n\t// Select all the records that match q\n\t// Group them by the first six digits of their date (YYYYMM), their supergroup, their endpointGroup, their profile, etc...\n\t// from that group find the average of the uptime, u, downtime\n\t// Project the result to a better format and do this computation\n\t// availability = (avgup/(1.00000001 - avgu))*100\n\t// reliability = (avgup/((1.00000001 - avgu)-avgd))*100\n\t// Sort the results by namespace->profile->supergroup->endpointGroup->datetime\n\n\tquery := []bson.M{\n\t\t{\"$match\": filter},\n\t\t{\"$group\": bson.M{\n\t\t\t\"_id\": bson.M{\n\t\t\t\t\"date\": bson.M{\"$substr\": list{\"$date\", 0, 6}},\n\t\t\t\t\"name\": \"$name\",\n\t\t\t\t\"supergroup\": \"$supergroup\",\n\t\t\t\t\"report\": \"$report\"},\n\t\t\t\"avgup\": bson.M{\"$avg\": \"$up\"},\n\t\t\t\"avgunknown\": bson.M{\"$avg\": \"$unknown\"},\n\t\t\t\"avgdown\": bson.M{\"$avg\": \"$down\"}}},\n\t\t{\"$project\": bson.M{\n\t\t\t\"date\": \"$_id.date\",\n\t\t\t\"name\": \"$_id.name\",\n\t\t\t\"report\": \"$_id.report\",\n\t\t\t\"supergroup\": \"$_id.supergroup\",\n\t\t\t\"unknown\": \"$avgunknown\",\n\t\t\t\"up\": \"$avgup\",\n\t\t\t\"down\": \"$avgdown\",\n\t\t\t\"avgup\": 1,\n\t\t\t\"avgunknown\": 1,\n\t\t\t\"avgdown\": 1,\n\t\t\t\"availability\": bson.M{\n\t\t\t\t\"$multiply\": list{\n\t\t\t\t\tbson.M{\"$divide\": list{\n\t\t\t\t\t\t\"$avgup\", bson.M{\"$subtract\": list{1.00000001, \"$avgunknown\"}}}},\n\t\t\t\t\t100}},\n\t\t\t\"reliability\": bson.M{\n\t\t\t\t\"$multiply\": list{\n\t\t\t\t\tbson.M{\"$divide\": list{\n\t\t\t\t\t\t\"$avgup\", bson.M{\"$subtract\": list{bson.M{\"$subtract\": list{1.00000001, \"$avgunknown\"}}, \"$avgdown\"}}}},\n\t\t\t\t\t100}}}},\n\t\t{\"$sort\": bson.D{\n\t\t\t{\"report\", 1},\n\t\t\t{\"supergroup\", 1},\n\t\t\t{\"name\", 1},\n\t\t\t{\"date\", 1}}}}\n\n\treturn query\n}", "func (o TransferJobScheduleScheduleStartDateOutput) Month() pulumi.IntOutput {\n\treturn o.ApplyT(func(v TransferJobScheduleScheduleStartDate) int { return v.Month }).(pulumi.IntOutput)\n}", "func MonthRange(start, end time.Month) MonthRangeExpression {\n\treturn MonthRangeExpression{start, end}\n}", "func (db *Service) FindAll(\n\tsc datatype.ServiceContainer,\n\tuser *datatype.User,\n\ttimelineFilter datatype.TimelineFilter,\n\toffset int,\n\tlimit int,\n) ([]datatype.TimelineEntry, bool, error) {\n\tresult := []datatype.TimelineEntry{}\n\tvar clause string\n\tif timelineFilter.Type == datatype.HOMETIMELINE {\n\t\tclause = \"WHERE b.status=1\"\n\t} else if timelineFilter.Type == datatype.ASSETTIMELINE {\n\t\tclause = fmt.Sprintf(\n\t\t\t\" WHERE b.status<>%d AND asset.id = %d\",\n\t\t\tdatatype.BlockRejected,\n\t\t\ttimelineFilter.AssetID,\n\t\t)\n\t} else if timelineFilter.Type == datatype.USERTIMELINE {\n\t\tclause = fmt.Sprintf(\n\t\t\t\" WHERE b.status<>%d AND (doer.id = %d OR oracle.id = %d)\",\n\t\t\tdatatype.BlockRejected,\n\t\t\ttimelineFilter.UserID,\n\t\t\ttimelineFilter.UserID,\n\t\t)\n\t}\n\trows, err := db.Query(fmt.Sprintf(`\n\t\t\tSELECT\n\t\t\t\tb.id,\n\t\t\t\tb.userId,\n\t\t\t\tdoer.username,\n\t\t\t\tdoer.profileImageUrl,\n\t\t\t\tasset.id,\n\t\t\t\tasset.name,\n\t\t\t\tasset.symbol,\n\t\t\t\toracle.id,\n\t\t\t\toracle.username,\n\t\t\t\tb.text,\n\t\t\t\tb.status,\n\t\t\t\tb.ethereumTransactionAddress,\n\t\t\t\tb.videoID,\n\t\t\t\tb.favoritesCounter,\n\t\t\t\tb.createdAt,\n\t\t\t\tIF(favorites.blockId, TRUE, FALSE),\n\t\t\t\tIF(asset_favorites.assetId, TRUE, FALSE) as following\n\t\t\tFROM asset_block b\n\t\t\tLEFT JOIN asset asset ON b.assetId=asset.Id\n\t\t\tLEFT JOIN user doer ON doer.id=b.userId\n\t\t\tLEFT JOIN user oracle ON oracle.id=asset.creatorId\n\t\t\tLEFT JOIN asset_block_favorites favorites ON b.id=favorites.blockId AND favorites.userId=?\n\t\t\tLEFT JOIN asset_favorites ON asset.id=asset_favorites.assetId AND asset_favorites.userId=?\n\t\t\t%s\n\t\t\tORDER BY b.createdAt DESC\n\t\t\tLIMIT ? OFFSET ?\n\t\t\t`, clause), user.ID, user.ID, limit+1, offset)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar c datatype.TimelineEntry\n\t\terr := rows.Scan(\n\t\t\t&c.BlockID,\n\t\t\t&c.UserID,\n\t\t\t&c.UserName,\n\t\t\t&c.UserProfileImageURL,\n\t\t\t&c.AssetID,\n\t\t\t&c.AssetName,\n\t\t\t&c.AssetSymbol,\n\t\t\t&c.OracleID,\n\t\t\t&c.OracleName,\n\t\t\t&c.Text,\n\t\t\t&c.Status,\n\t\t\t&c.EthereumTransactionAddress,\n\t\t\t&c.YtVideoID,\n\t\t\t&c.FavoritesCount,\n\t\t\t&c.CreatedAt,\n\t\t\t&c.DidUserLike,\n\t\t\t&c.DidUserLikeTopic,\n\t\t)\n\t\tif timelineFilter.Type == datatype.HOMETIMELINE && c.DidUserLikeTopic == false {\n\t\t\tcontinue\n\t\t}\n\t\tc.CreatedAtHuman = helpers.DateToHuman(c.CreatedAt)\n\t\tif err != nil {\n\t\t\tapperrors.Critical(\"timelineservice:find-all:1\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\t// TODO optimize fetching images, bring all images for all at once,\n\t\t// not query for each entry\n\t\tc.Images, err = sc.AssetService.GetAssetBlockImages(c.BlockID)\n\t\tif err != nil {\n\t\t\tapperrors.Critical(\"timelineservice:find-all:2\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\tc.Reactions, err = db.FindClaimReactions(c.BlockID)\n\t\tif err != nil {\n\t\t\tapperrors.Critical(\"timelineservice:find-all:3\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\tresult = append(result, c)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, false, err\n\t}\n\thasMore := len(result) == limit+1\n\tif hasMore {\n\t\tresult = result[:len(result)-1]\n\t}\n\treturn result, hasMore, nil\n}", "func statsStatusQuery(projectId string) bson.M {\n\treturn bson.M{\"_id\": projectId}\n}", "func GetAllPlanes(ds *mgo.Session, db string) (planes []model.Plane, err error) {\n\tsession := ds\n\tclone := session.Clone()\n\tdefer clone.Close()\n\tdatab := clone.DB(db)\n\tdal := NewMongoDBDAL(datab)\n\terr = dal.C(\"planes\").Find(bson.M{}).All(&planes)\n\treturn\n}", "func getFullBuilds(c context.Context, masterName, builderName string, finished bool) ([]*buildbotBuild, error) {\n\t// TODO(hinoka): Builder specific structs.\n\tq := ds.NewQuery(\"buildbotBuild\")\n\tq = q.Eq(\"finished\", finished)\n\tq = q.Eq(\"master\", masterName)\n\tq = q.Eq(\"builder\", builderName)\n\tq = q.Order(\"-number\")\n\tq.Finalize()\n\t// Ignore the cursor, we don't need it.\n\tbuildbots, _, err := runBuildsQuery(c, q, 25)\n\treturn buildbots, err\n}", "func StartMonth(month int, layout string) string {\n\ttimeNow := time.Now().In(zoneLocal).Format(LayoutMonth)\n\ttimeStart, _ := time.Parse(LayoutMonth, timeNow)\n\treturn timeStart.\n\t\tAddDate(0, month, 0).\n\t\tIn(zoneLocal).\n\t\tFormat(layout)\n}", "func (d *Dao) GetMonthExpenseCount(c context.Context, month, beginMonth string, ctype int) (total int, err error) {\n\terr = d.rddb.QueryRow(c, _expenseMonthCountSQL, month, beginMonth, ctype).Scan(&total)\n\treturn\n}", "func (m Month) String() string {}", "func (o InstanceDenyMaintenancePeriodStartDatePtrOutput) Month() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *InstanceDenyMaintenancePeriodStartDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Month\n\t}).(pulumi.IntPtrOutput)\n}", "func (ln *localen) MonthWide(month time.Month) string {\n\treturn ln.monthsWide[month]\n}", "func (dt DateTime) Month() time.Month {\n\treturn dt.src.Month()\n}", "func MonthInRange(time *time.Time, minMonth, maxMonth int) bool {\n\treturn fieldInRange(time.Month, minMonth, maxMonth)\n}", "func (c *StatsGetUserCall) FromDateMonth(fromDateMonth int64) *StatsGetUserCall {\n\tc.urlParams_.Set(\"fromDate.month\", fmt.Sprint(fromDateMonth))\n\treturn c\n}", "func GetPaymentsByUserAndMonthAndClass(userID uint, startDate, endDate time.Time, class string) []paymentsModel.Payment {\n\tpayments := make([]paymentsModel.Payment, 0)\n\tdbInstance.GetDBConnection().Where(\"user_id = ? AND start_date >= ? AND end_date < ? AND class_hash = ?\",\n\t\tuserID, startDate, endDate, class).Find(&payments)\n\treturn payments\n}", "func GetDetailedActionCommitment(ctx iris.Context) {\n\ty1, err := ctx.URLParamInt64(\"FirstYear\")\n\tif err != nil {\n\t\ty1 = int64(time.Now().Year()) + 1\n\t}\n\tvar resp models.DetailedActionCommitments\n\tdb := ctx.Values().Get(\"db\").(*sql.DB)\n\tif err = resp.GetAll(y1, db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Prévisions AP détaillées par actions budgétaires, requête : \" + err.Error()})\n\t\treturn\n\t}\n\tctx.StatusCode(http.StatusOK)\n\tctx.JSON(resp)\n}", "func (o TransferJobScheduleScheduleEndDateOutput) Month() pulumi.IntOutput {\n\treturn o.ApplyT(func(v TransferJobScheduleScheduleEndDate) int { return v.Month }).(pulumi.IntOutput)\n}", "func ListMonthCmd(opts *config.ClientOptions) *cobra.Command {\n\n\tcmdOpts := listMonthOptions{\n\t\tEventDate: &eventapi.EventDate{},\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"listmonth\",\n\t\tShort: \"get events for month command\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\teventTime, err := time.Parse(dateFormat, cmdOpts.date)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"could not parse time\")\n\t\t\t}\n\t\t\tcmdOpts.EventDate.Date = &eventTime\n\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\t\tdefer cancel()\n\n\t\t\tconnection, err := grpc.DialContext(ctx, fmt.Sprintf(\"%s:%d\", opts.GRPCHost, opts.GRPCPort),\n\t\t\t\tgrpc.WithInsecure(), grpc.WithBlock())\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"could not connect: %v\", err)\n\t\t\t}\n\t\t\tdefer connection.Close()\n\t\t\tlog.Println(\"Connected to remote server\")\n\n\t\t\tclient := eventapi.NewApiServerClient(connection)\n\n\t\t\tvar events *eventapi.EventList\n\t\t\tif events, err = client.GetEventsForMonth(context.Background(), cmdOpts.EventDate); err != nil {\n\t\t\t\tlog.Fatalf(\"could not get events: %v\", err)\n\t\t\t}\n\t\t\tlog.Println(\"event list:\")\n\t\t\tfor _, remoteEvent := range events.Events {\n\t\t\t\tlog.Printf(\"uuid: %s, time: %s\\n\", remoteEvent.Uuid, remoteEvent.StartTime)\n\t\t\t}\n\t\t},\n\t}\n\n\tcmd.PersistentFlags().StringVar(&cmdOpts.date, \"date\", \"\", \"events date - 2019.03.04\")\n\tif err := cmd.MarkPersistentFlagRequired(\"date\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn cmd\n\n}", "func (c Cookie) Month() Cookie {\n\treturn c.Expires(time.Now().AddDate(0, 1, 0))\n}", "func (*ActivityStageDataAccessObject) FindByAID(aid int) []ActivityStage {\n\tl := make([]ActivityStage, 0)\n\terr := orm.Table(ActivityStageDAO.TableName()).Where(\"activity_id=?\", aid).\n\t\tFind(&l)\n\t\n\tlogger.LogIfError(err)\n\treturn l\n}", "func logAgencyMonthlyInfo(ag storage.AgencyMonthlyInfo) error {\n\tfor _, e := range ag.Employee {\n\t\tbasicInfo := fmt.Sprintf(\"%q, %d, %d,\", ag.AgencyID, ag.Year, ag.Month)\n\t\tempInfo := empInfo(e)\n\t\tfmt.Println(basicInfo + empInfo[:len(empInfo)-1])\n\t}\n\treturn nil\n}", "func (modulo *Modulo) FindAllModulo(db *gorm.DB) (*[]Modulo, error) {\n\n\tallModulo := []Modulo{}\n\n\terr := db.Debug().Model(&Modulo{}).Find(&allModulo).Error\n\tif err != nil {\n\t\treturn &[]Modulo{}, err\n\t}\n\n\treturn &allModulo, err\n}", "func (p *PipelineActivity) StagesByStatus() map[ActivityStatusType][]string {\n\tstatusMap := make(map[ActivityStatusType][]string)\n\n\tfor _, stage := range p.Spec.Steps {\n\t\tif stage.Kind == ActivityStepKindTypeStage && stage.Stage != nil {\n\t\t\tif _, exists := statusMap[stage.Stage.Status]; !exists {\n\t\t\t\tstatusMap[stage.Stage.Status] = []string{}\n\t\t\t}\n\t\t\tstatusMap[stage.Stage.Status] = append(statusMap[stage.Stage.Status], stage.Stage.Name)\n\t\t}\n\t}\n\n\treturn statusMap\n}", "func Month() string {\n\treturn randomFrom(jsonData.Months)\n}", "func (o InstanceDenyMaintenancePeriodEndDatePtrOutput) Month() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *InstanceDenyMaintenancePeriodEndDate) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Month\n\t}).(pulumi.IntPtrOutput)\n}", "func (m MarketDataSnapshotFullRefresh) HasMaturityMonthYear() bool {\n\treturn m.Has(tag.MaturityMonthYear)\n}", "func checkMonth(searchMonth string) (bool, string, string) {\n\tvalidMonths := map[string]string{\n\t\t\"January\": \"01\",\n\t\t\"February\": \"02\",\n\t\t\"March\": \"03\",\n\t\t\"April\": \"04\",\n\t\t\"May\": \"05\",\n\t\t\"June\": \"06\",\n\t\t\"July\": \"07\",\n\t\t\"August\": \"08\",\n\t\t\"September\": \"09\",\n\t\t\"October\": \"10\",\n\t\t\"November\": \"11\",\n\t\t\"December\": \"12\",\n\t}\n\n\tmonthNum, ok := validMonths[searchMonth]\n\tif !ok {\n\t\treturn false, \"\", \"Invalid month.\"\n\t}\n\n\treturn true, monthNum, \"valid\"\n}", "func (c *Calendar) Month() int {\n\tmonths := 1\n\tcreatedAtTime := c.StartDate\n\tmonth := createdAtTime.Month()\n\tfor createdAtTime.Before(c.EndDate) {\n\t\tcreatedAtTime = createdAtTime.Add(time.Hour * 24)\n\t\tnextMonth := createdAtTime.Month()\n\t\tif nextMonth != month {\n\t\t\tmonths++\n\t\t}\n\t\tmonth = nextMonth\n\t}\n\treturn months\n}", "func (c *StatsGetSessionCall) FromDateMonth(fromDateMonth int64) *StatsGetSessionCall {\n\tc.urlParams_.Set(\"fromDate.month\", fmt.Sprint(fromDateMonth))\n\treturn c\n}", "func (e *ExportedCommitments) Get(db *sql.DB, q *ExportQuery) error {\n\trows, err := db.Query(`SELECT c.id,c.year,c.code,c.number,c.line,\n\tc.creation_date,c.modification_date,c.caducity_date,c.name,c.value*0.01,\n\tc.sold_out, b.name, c.iris_code,a.name,s.name,copro.name,housing.address,\n\trenew_project.name\n\tFROM commitment c\n\tJOIN beneficiary b ON c.beneficiary_id = b.id\n\tJOIN budget_action a ON a.id = c.action_id\n\tJOIN budget_sector s ON s.id=a.sector_id\n\tLEFT JOIN copro ON copro.id = c.copro_id\n\tLEFT JOIN housing ON housing.id = c.housing_id\n\tLEFT JOIN renew_project ON renew_project.id = c.renew_project_id\n\tWHERE year >= $1 AND (c.name ILIKE $2 OR c.number::varchar ILIKE $2 OR \n\t\tc.code ILIKE $2 OR b.name ILIKE $2 OR a.name ILIKE $2)\n\tORDER BY 2,6,7,3,4,5`, q.Year, \"%\"+q.Search+\"%\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar row ExportedCommitment\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tif err = rows.Scan(&row.ID, &row.Year, &row.Code, &row.Number, &row.Line,\n\t\t\t&row.CreationDate, &row.ModificationDate, &row.CaducityDate, &row.Name,\n\t\t\t&row.Value, &row.SoldOut, &row.BeneficiaryName, &row.IrisCode,\n\t\t\t&row.ActionName, &row.Sector, &row.CoproName, &row.HousingName,\n\t\t\t&row.RenewProjectName); err != nil {\n\t\t\treturn err\n\t\t}\n\t\te.ExportedCommitments = append(e.ExportedCommitments, row)\n\t}\n\terr = rows.Err()\n\tif len(e.ExportedCommitments) == 0 {\n\t\te.ExportedCommitments = []ExportedCommitment{}\n\t}\n\treturn err\n}", "func IsShowMonth(on bool) Option {\n\treturn func(args *Configs) {\n\t\targs.IsShowMonth = on\n\t}\n}", "func (o *PeriodModel) HasMonths() bool {\n\tif o != nil && o.Months != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (filter TaskReliabilityFilter) BuildTaskStatsQueryGroupStage() bson.M {\n\treturn bson.M{\n\t\t\"$group\": bson.M{\n\t\t\t\"_id\": filter.buildGroupID(),\n\t\t\ttaskstats.TaskStatsNumSuccessKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumSuccessKey},\n\t\t\ttaskstats.TaskStatsNumFailedKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumFailedKey},\n\t\t\ttaskstats.TaskStatsNumTimeoutKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumTimeoutKey},\n\t\t\ttaskstats.TaskStatsNumTestFailedKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumTestFailedKey},\n\t\t\ttaskstats.TaskStatsNumSystemFailedKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumSystemFailedKey},\n\t\t\ttaskstats.TaskStatsNumSetupFailedKey: bson.M{\"$sum\": \"$\" + taskstats.DBTaskStatsNumSetupFailedKey},\n\t\t\t\"total_duration_success\": bson.M{\"$sum\": bson.M{\"$multiply\": taskstats.Array{\"$\" + taskstats.DBTaskStatsNumSuccessKey, \"$\" + taskstats.DBTaskStatsAvgDurationSuccessKey}}},\n\t\t}}\n}", "func (m *RecManager) GetAllFull() ([]*RecFull, error) {\n\treturn m.getFull(\"\")\n}", "func (q assetRevisionQuery) All() (AssetRevisionSlice, error) {\n\tvar o AssetRevisionSlice\n\n\terr := q.Bind(&o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"public: failed to assign all query results to AssetRevision slice\")\n\t}\n\n\tif len(assetRevisionAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(queries.GetExecutor(q.Query)); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (o ScheduledAuditOutput) DayOfMonth() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScheduledAudit) pulumi.StringPtrOutput { return v.DayOfMonth }).(pulumi.StringPtrOutput)\n}" ]
[ "0.6485961", "0.5838887", "0.54939", "0.50618786", "0.49783215", "0.4971028", "0.46449506", "0.46276957", "0.45600504", "0.453128", "0.45056736", "0.4474794", "0.44515705", "0.4356057", "0.4317667", "0.4312884", "0.42955038", "0.42806733", "0.42327458", "0.42143032", "0.418069", "0.41432834", "0.41288993", "0.41209784", "0.41160142", "0.4110358", "0.41073382", "0.4100624", "0.40827006", "0.4072224", "0.40671054", "0.4062684", "0.40584797", "0.40537623", "0.40505895", "0.40500778", "0.40242505", "0.40202317", "0.4015884", "0.39979684", "0.39969996", "0.39952964", "0.3976926", "0.39720136", "0.3960706", "0.39490673", "0.39425558", "0.3933185", "0.39311442", "0.39306372", "0.39268795", "0.392502", "0.39201877", "0.39084217", "0.39084217", "0.39080572", "0.39062956", "0.3902206", "0.3902206", "0.3898127", "0.38946754", "0.38909006", "0.38898793", "0.38773224", "0.38653398", "0.38638592", "0.3854737", "0.38524976", "0.38452935", "0.38425493", "0.38423708", "0.3828981", "0.38285598", "0.3825916", "0.38257444", "0.38242102", "0.38234147", "0.3822375", "0.3820411", "0.3814563", "0.38106155", "0.37962112", "0.37937143", "0.37643108", "0.3746464", "0.3744775", "0.3737107", "0.37271377", "0.3723654", "0.37111297", "0.37110028", "0.37103862", "0.37097156", "0.37040886", "0.36921072", "0.36917943", "0.3685329", "0.3684668", "0.36721784", "0.36699852" ]
0.7959822
0
FindByID finds activityStage by ID
func (*ActivityStageDataAccessObject) FindByID(id int) (ActivityStage, bool) { var result ActivityStage has, err := orm.Table(ActivityStageDAO.TableName()).ID(id).Get(&result) logger.LogIfError(err) return result, has }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*ActivityStageDataAccessObject) FindByAID(aid int) []ActivityStage {\n\tl := make([]ActivityStage, 0)\n\terr := orm.Table(ActivityStageDAO.TableName()).Where(\"activity_id=?\", aid).\n\t\tFind(&l)\n\t\n\tlogger.LogIfError(err)\n\treturn l\n}", "func XPipelineSalesStageByID(db XODB, id uint) (*XPipelineSalesStage, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, name, probability, seq_num, active_flag, sales_method_id, created_by, updated_by, created_at, updated_at ` +\n\t\t`FROM x_showroom.x_pipeline_sales_stages ` +\n\t\t`WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, id)\n\txpss := XPipelineSalesStage{\n\t\t_exists: true,\n\t}\n\n\terr = db.QueryRow(sqlstr, id).Scan(&xpss.ID, &xpss.Name, &xpss.Probability, &xpss.SeqNum, &xpss.ActiveFlag, &xpss.SalesMethodID, &xpss.CreatedBy, &xpss.UpdatedBy, &xpss.CreatedAt, &xpss.UpdatedAt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &xpss, nil\n}", "func (c *Client) FindCrmStageId(criteria *Criteria, options *Options) (int64, error) {\n\tids, err := c.Search(CrmStageModel, criteria, options)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tif len(ids) > 0 {\n\t\treturn ids[0], nil\n\t}\n\treturn -1, fmt.Errorf(\"crm.stage was not found with criteria %v and options %v\", criteria, options)\n}", "func (planetDeliveryRest *PlanetDeliveryRest) FindByID(w http.ResponseWriter, r *http.Request) {\n\tplanetID := mux.Vars(r)[\"id\"]\n\tplanet, err := planetDeliveryRest.planetUsecase.FindByID(r.Context(), planetID)\n\tif err != nil {\n\t\tError(w, err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\tJSON(w, planet, http.StatusOK)\n}", "func (c *Client) FindCrmStage(criteria *Criteria) (*CrmStage, error) {\n\tcss := &CrmStages{}\n\tif err := c.SearchRead(CrmStageModel, criteria, NewOptions().Limit(1), css); err != nil {\n\t\treturn nil, err\n\t}\n\tif css != nil && len(*css) > 0 {\n\t\treturn &((*css)[0]), nil\n\t}\n\treturn nil, fmt.Errorf(\"crm.stage was not found with criteria %v\", criteria)\n}", "func (c *Client) GetCrmStage(id int64) (*CrmStage, error) {\n\tcss, err := c.GetCrmStages([]int64{id})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif css != nil && len(*css) > 0 {\n\t\treturn &((*css)[0]), nil\n\t}\n\treturn nil, fmt.Errorf(\"id %v of crm.stage not found\", id)\n}", "func XPipelineSalesStageByNameSalesMethodID(db XODB, name string, salesMethodID uint) (*XPipelineSalesStage, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, name, probability, seq_num, active_flag, sales_method_id, created_by, updated_by, created_at, updated_at ` +\n\t\t`FROM x_showroom.x_pipeline_sales_stages ` +\n\t\t`WHERE name = ? AND sales_method_id = ?`\n\n\t// run query\n\tXOLog(sqlstr, name, salesMethodID)\n\txpss := XPipelineSalesStage{\n\t\t_exists: true,\n\t}\n\n\terr = db.QueryRow(sqlstr, name, salesMethodID).Scan(&xpss.ID, &xpss.Name, &xpss.Probability, &xpss.SeqNum, &xpss.ActiveFlag, &xpss.SalesMethodID, &xpss.CreatedBy, &xpss.UpdatedBy, &xpss.CreatedAt, &xpss.UpdatedAt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &xpss, nil\n}", "func (p *API) FindByID(c *gin.Context) {\n\tif p.Engine.CheckAccess(c, \"roles:read\") {\n\t\tresponse.NoPermissionRecord(c, p.Engine, \"role-view-forbidden\")\n\t\treturn\n\t}\n\tid, err := strconv.ParseUint(c.Param(\"id\"), 10, 16)\n\tif err != nil {\n\t\tresponse.InvalidID(c, err)\n\t\treturn\n\t}\n\n\trole, err := p.Service.FindByID(id)\n\n\tif err != nil {\n\t\tresponse.RecordNotFound(c, err, \"role\")\n\t\treturn\n\t}\n\n\tp.Engine.Record(c, \"role-view\")\n\tresponse.Success(c, role)\n}", "func (jbobject *TaskContext) StageId() int {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"stageId\", javabind.Int)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(int)\n}", "func (s *Postgres) FindByID(teamID string) (server.Team, error) {\n\n\tteam := server.Team{}\n\n\trows, err := s.db.Query(s.selectOneSQL(), teamID)\n\tif err != nil {\n\t\treturn team, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\terr := rows.Scan(&team.ID, &team.Clicks)\n\t\tif err != nil {\n\t\t\treturn team, err\n\t\t}\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn team, err\n\t}\n\n\tif team.ID == \"\" {\n\t\treturn team, errors.New(\"team not found\")\n\t}\n\n\treturn team, nil\n}", "func (t Trade) GetStage(idx uint) (*TradeStage, errstack.E) {\n\n\tif int(idx) >= len(t.Stages) {\n\t\treturn nil, errstack.NewReq(\"Stage Index out of range\")\n\t}\n\treturn &t.Stages[idx], nil\n}", "func (ds *DealStages) GetStage(stage string) *DealStage {\n\tif ds == nil {\n\t\treturn nil\n\t}\n\n\tfor _, s := range ds.Stages {\n\t\tif s.Name == stage {\n\t\t\treturn s\n\t\t}\n\t}\n\n\treturn nil\n}", "func (t *Cases) Find(id int) *models.Case {\n\tvar result models.Case\n\n\tquery := func(db *gorm.DB) {\n\t\tdb.Find(&result, id)\n\t}\n\n\terror := t.context.Execute(query)\n\n\tif error != nil {\n\t\treturn nil\n\t}\n\n\treturn &result\n}", "func (*ActivityStageDataAccessObject) DeleteByAID(aid int) {\n\tvar buf ActivityStage\n\t_, err := orm.Table(ActivityStageDAO.TableName()).\n\t\tWhere(\"activity_id=?\", aid).Delete(&buf)\n\tlogger.LogIfError(err)\n}", "func findAssetID(assets []Asset, name string) int {\n\tfor _, asset := range assets {\n\t\tif asset.Name == name {\n\t\t\treturn asset.Id\n\t\t}\n\t}\n\treturn -1\n}", "func FindById(DB db.IDb, table *db.Table, instance interface{}, id int64) (bool, error) {\r\n\tlogger.CallerAt(1).Debugf(\"DAOUtils.FindById: %v\", id)\r\n\r\n\tkeyColumn := table.GetKeyColumns().Enumerator().Next().(*db.Column)\r\n\r\n\treturn DB.Query(table).\r\n\t\tAll().\r\n\t\tWhere(keyColumn.Matches(id)).\r\n\t\tSelectTo(instance)\r\n}", "func (s *Service) FindSourceByID(ctx context.Context, id influxdb.ID) (*influxdb.Source, error) {\n\tvar sr *influxdb.Source\n\n\terr := s.kv.View(ctx, func(tx Tx) error {\n\t\tsrc, pe := s.findSourceByID(ctx, tx, id)\n\t\tif pe != nil {\n\t\t\treturn &influxdb.Error{\n\t\t\t\tErr: pe,\n\t\t\t}\n\t\t}\n\t\tsr = src\n\t\treturn nil\n\t})\n\treturn sr, err\n}", "func (db *Tool) FindByID(id int) (*Tool, error) {\n\ttools, err := db.fetchTools()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, t := range tools {\n\t\tif t.ID == id {\n\t\t\treturn &t, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"tool not found\")\n}", "func (this *Route) FindById(id int) error {\n\tif id <= 0 {\n\t\treturn errors.New(\"id不能为空\")\n\t}\n\n\to := orm.NewOrm()\n\treturn o.QueryTable(this.TableName()).Filter(\"id\", id).One(this)\n}", "func findID(root *Container, id string) (*Container, error) {\n\tif id == \"\" {\n\t\treturn nil, errors.New(\"the container ID must not be empty\")\n\t}\n\n\tvar (\n\t\terrStr string\n\t\tcont *Container\n\t)\n\tpreOrder(root, &errStr, visitFunc(func(c *Container) error {\n\t\tif c.opts.id == id {\n\t\t\tcont = c\n\t\t}\n\t\treturn nil\n\t}))\n\tif cont == nil {\n\t\treturn nil, fmt.Errorf(\"cannot find container with ID %q\", id)\n\t}\n\treturn cont, nil\n}", "func (a *UtilsApiService) GetStageUsingGet(ctx context.Context, stageId string) (Stage, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Stage\n\t)\n\n\t// create path and map variables\n\ta.client = NewAPIClient(&Configuration{\n\t\tBasePath: ctx.Value(\"BasePath\").(string),\n\t\tDefaultHeader: make(map[string]string),\n\t\tUserAgent: \"Swagger-Codegen/1.0.0/go\",\n\t})\n\tlocalVarPath := a.client.cfg.BasePath + \"/nucleus/v1/stage/{stage_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"stage_id\"+\"}\", fmt.Sprintf(\"%v\", stageId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.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{\"*/*\"}\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, 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\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v Stage\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\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (r *Resource) FindByID(ctx context.Context, id string) (*flare.Resource, error) {\n\tr.mutex.RLock()\n\tdefer r.mutex.RUnlock()\n\n\tres, err := r.findByID(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &res.base, nil\n}", "func (smr *StoryMongoRepository) FindByID(ID string) (interface{}, error) {\n\treturn smr.bmr.FindByID(ID, &models.Story{}, \"stories\")\n}", "func findByID(node *ProjectNode, projectSFID string) *ProjectNode {\n\tif node == nil {\n\t\treturn nil\n\t}\n\tif node.ID == projectSFID {\n\t\treturn node\n\t}\n\n\tfor _, child := range node.Children {\n\t\tfoundNode := findByID(child, projectSFID)\n\t\tif foundNode != nil {\n\t\t\treturn foundNode\n\t\t}\n\t}\n\n\treturn nil\n}", "func (st *Stages) Run(id string, seed interface{}) error {\n\tsyncData, err := st.syncer.GetAll(id)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Cannot fetch synced data\")\n\t}\n\tprevResult := &StageResult{Data: seed}\n\tfor _, stage := range st.stages {\n\t\tsyncedStageResult, ok := syncData[stage.name]\n\t\tif !ok {\n\t\t\tsyncedStageResult = &StageResult{}\n\t\t}\n\t\tif syncedStageResult.Status == \"done\" {\n\t\t\tprevResult = syncedStageResult\n\t\t\tcontinue\n\t\t}\n\t\tstageResult, bookmark, err := stage.execStage(st.syncer, id, prevResult.Data, seed)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"Unable to execute stage %s:%s\", stage.name, id)\n\t\t}\n\t\tprevResult = stageResult\n\t\tif bookmark { // Bookmark is an explicit termination to be resumed later\n\t\t\tbreak\n\t\t}\n\t}\n\tst.lastResult = prevResult\n\treturn nil\n}", "func SelectActivityByID(ID *int64) *models.Activity {\n\tvar db, _ = GetDatabase()\n\tif db == nil {\n\t\tlog.Println(\"Error in SelectActivityByID: DB connection unsuccessful.\")\n\t\treturn nil\n\t}\n\n\tvar activity models.Activity\n\tactivity.ID = *ID\n\tvar row = db.QueryRow(\"SELECT name FROM activities WHERE id = $1\", *ID)\n\terr := row.Scan(&activity.Name)\n\n\tswitch err {\n\tcase sql.ErrNoRows:\n\t\tlog.Println(\"No activity found for ID: \", *ID)\n\t\treturn nil\n\tcase nil:\n\t\treturn &activity\n\tdefault:\n\t\tlog.Println(\"Error SelectActivityByID: \", err)\n\t\treturn nil\n\t}\n}", "func (explenation *Explenation) FindByID(id string) error {\n\tif isObjectID := bson.IsObjectIdHex(id); !isObjectID {\n\t\treturn helpers.ErrInvalidObjectID\n\t}\n\treturn explenation.FindByObjectID(bson.ObjectIdHex(id))\n}", "func (e *OverlayEnv) GetEnvByID(id int) (Expander, bool) {\n\t// do we have a stack to work with?\n\tif e == nil {\n\t\treturn nil, false\n\t}\n\n\t// do we have the environment that has been requested?\n\tif id >= len(e.envs) || id < 0 {\n\t\treturn nil, false\n\t}\n\n\t// yes, we do\n\treturn e.envs[id], true\n}", "func (m *Module) RunStage(ctx *jobs.Ctx) error {\n\tstage := ctx.Stage\n\tremoteSession := ctx.RemoteCon\n\tenv := ctx.Env\n\n\tif stage.Action == \"save-local\" {\n\t\treturn backupLocally(stage, env, remoteSession)\n\t}\n\tif stage.Action == \"save-googleDrive\" {\n\t\treturn backupGoogleDrive(stage, env, remoteSession)\n\t}\n\n\tif stage.Action == \"restore-local\" {\n\t\treturn restoreLocally(stage, env, remoteSession)\n\t}\n\tif stage.Action == \"restore-googleDrive\" {\n\t\treturn restoreGoogleDrive(stage, env, remoteSession)\n\t}\n\n\tif stage.Action == \"delete-local\" {\n\t\treturn deleteLocally(stage, env, remoteSession)\n\t}\n\tif stage.Action == \"delete-googleDrive\" {\n\t\treturn deleteGoogleDrive(stage, env, remoteSession)\n\t}\n\n\treturn fmt.Errorf(\"could not find Action in 'backup'-Category: '%s'\", stage.Action)\n}", "func findMovie(c *gin.Context) {\n\t// Get model if exist\n\tvar movie Movie\n\tif err := DB.Where(\"id = ?\", c.Param(\"id\")).First(&movie).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": movie})\n}", "func (s lifecycleService) GetByID(id string) (*Lifecycle, error) {\n\tpath, err := getByIDPath(s, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := apiGet(s.getClient(), new(Lifecycle), path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.(*Lifecycle), nil\n}", "func FindTitleByID(id int64) (*Title, error) {\n\treturn FindTitle(\"id = ?\", id)\n}", "func (ts *TechStoryService) findById (w http.ResponseWriter, r *http.Request) {\n\tvar techStory model.TechStory\n\ttechStory.Key = mux.Vars(r)[\"id\"]\n\tWithTechStoryDao(func(dao techStoryDao) {\n\t\terr := dao.FindById(&techStory)\n\t\tmodel.CheckErr(err)\n\t\tmodel.WriteResponse(true, nil, techStory, w)\n\t})\n}", "func (r *Resource) FindOne(_ context.Context, id string) (*flare.Resource, error) {\n\tr.mutex.RLock()\n\tdefer r.mutex.RUnlock()\n\n\tfor _, resource := range r.resources {\n\t\tif resource.ID == id {\n\t\t\treturn &resource, nil\n\t\t}\n\t}\n\treturn nil, &errMemory{message: fmt.Sprintf(\"resource '%s' not found\", id), notFound: true}\n}", "func GetStage() string {\n\treturn stage\n}", "func (a GetSLITriggeredAdapter) GetStage() string {\n\treturn a.event.Stage\n}", "func (*ActivityStageDataAccessObject) UpdateOne(activityStage *ActivityStage) {\n\t_, err := orm.Table(ActivityStageDAO.TableName()).ID(activityStage.ID).\n\t\tUpdate(activityStage)\n\tlogger.LogIfError(err)\n}", "func (r *Resource) FindByID(ctx context.Context, id string) (*flare.Resource, error) {\n\tresource, err := r.findByID(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.resourceEntityToFlareResource(resource), nil\n}", "func (s *stepRotator) getVersionIDFromVersionStage(vStage versionStage) (string, error) {\n\tversionIDsToStages, err := s.getVersionIDsToStages()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor id, stages := range versionIDsToStages {\n\t\tfor _, stage := range stages {\n\t\t\tif *stage == string(vStage) {\n\t\t\t\treturn id, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", nil\n}", "func (visual *Visual) FindParameter(id uuid.UUID) (*Group, *parameters.Parameter) {\n\tvisual.mux.Lock()\n\tdefer visual.mux.Unlock()\n\n\t// iterate over shows, visuals and groups\n\tfor _, group := range visual.Groups() {\n\t\tfor _, parameter := range group.Effect.Parameters() {\n\t\t\tif parameter.ID == id {\n\t\t\t\treturn group, parameter\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, nil\n}", "func FindSingleById(object interface{}, id int) interface{} {\n\terr := GetDB().Table(getTableName(object)).Where(\"id = ?\", id).First(object).Error\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn object\n}", "func (c *CaptureList) Find(captureID string) *Capture {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\tidInt, _ := strconv.Atoi(captureID)\n\tfor _, c := range c.items {\n\t\tif c.ID == idInt {\n\t\t\treturn &c\n\t\t}\n\t}\n\treturn nil\n}", "func (g *GameDBModel) FindByID(id string) (Game, error) {\n\tvar game Game\n\terr := database.C(COLLECTION).FindId(bson.ObjectIdHex(id)).One(&game)\n\n\treturn game, err\n}", "func (database *Database) FindActivityByID(activity *Activity, id int) error {\n\terr := database.DB.Preload(\"OrderItems\").\n\t\tPreload(\"Restaurants\").\n\t\tPreload(\"Restaurants.Menus\").\n\t\tWhere(\"id = ?\", id).\n\t\tFirst(activity).Error\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to get an activity with ID = %d: %s\", id, err)\n\t}\n\n\treturn nil\n}", "func (r *WikiActorsRepo) Find(kind wikiactors.Kind, id int) *wikiactors.Actor {\n\tr.mutex.RLock()\n\tdefer r.mutex.RUnlock()\n\n\tp, found := r.byIDByKind[kind][id]\n\tif found != true {\n\t\treturn nil\n\t}\n\treturn p\n}", "func (dao *PlayerDAO) FindByID(playerID string) (models.Player, error) {\n\tvar player models.Player\n\n\tid, errconvert := primitive.ObjectIDFromHex(playerID)\n\tif errconvert != nil {\n\t\treturn player, errconvert\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tfilter := bson.M{\"_id\": id}\n\n\terr := db.Collection(PCOLLECTION).FindOne(ctx, filter).Decode(&player)\n\tif err != nil {\n\t\treturn player, err\n\t}\n\treturn player, nil\n}", "func (h *JourneyRepository) GetByID(id int) (*models.Journey, error) {\n\tjourney := &models.Journey{}\n\tlog.Println(id)\n\tif err := h.Db.Set(\"gorm:auto_preload\", true).First(&journey, id).Error; err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\treturn journey, nil\n\n}", "func ActivityByID(ctx context.Context, id uint, key ...interface{}) (*Activity, error) {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\ttableName, err := GetActivityTableName(key...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sql query\n\tsqlstr := `SELECT ` +\n\t\t`id, name, activity_type_id, activity_type_code, content, activity_image, image_url, image_color, status, sort, extend, admin_id, admin_name, start_time, end_time, created_at, updated_at ` +\n\t\t`FROM ` + tableName +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, id)))\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetSlaveConn()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\ta := Activity{\n\t\t_exists: true,\n\t}\n\n\tif tx != nil {\n\t\terr = tx.QueryRow(sqlstr, id).Scan(&a.ID, &a.Name, &a.ActivityTypeID, &a.ActivityTypeCode, &a.Content, &a.ActivityImage, &a.ImageURL, &a.ImageColor, &a.Status, &a.Sort, &a.Extend, &a.AdminID, &a.AdminName, &a.StartTime, &a.EndTime, &a.CreatedAt, &a.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\terr = dbConn.QueryRow(sqlstr, id).Scan(&a.ID, &a.Name, &a.ActivityTypeID, &a.ActivityTypeCode, &a.Content, &a.ActivityImage, &a.ImageURL, &a.ImageColor, &a.Status, &a.Sort, &a.Extend, &a.AdminID, &a.AdminName, &a.StartTime, &a.EndTime, &a.CreatedAt, &a.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &a, nil\n}", "func (mm *MutMap) FindByID(teamID string) (server.Team, error) {\n\tmm.mutex.RLock()\n\tdefer mm.mutex.RUnlock()\n\n\tteam, ok := mm.teams[teamID]\n\tif !ok {\n\t\treturn team, errors.New(\"not found\")\n\t}\n\n\treturn team, nil\n}", "func (rm *resourceManager) sdkFind(\n\tctx context.Context,\n\tr *resource,\n) (*resource, error) {\n\t// If any required fields in the input shape are missing, AWS resource is\n\t// not created yet. Return NotFound here to indicate to callers that the\n\t// resource isn't yet created.\n\tif rm.requiredFieldsMissingFromReadOneInput(r) {\n\t\treturn nil, ackerr.NotFound\n\t}\n\n\tinput, err := rm.newDescribeRequestPayload(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, respErr := rm.sdkapi.GetStageWithContext(ctx, input)\n\trm.metrics.RecordAPICall(\"READ_ONE\", \"GetStage\", respErr)\n\tif respErr != nil {\n\t\tif awsErr, ok := ackerr.AWSError(respErr); ok && awsErr.Code() == \"NotFoundException\" {\n\t\t\treturn nil, ackerr.NotFound\n\t\t}\n\t\treturn nil, respErr\n\t}\n\n\t// Merge in the information we read from the API call above to the copy of\n\t// the original Kubernetes object we passed to the function\n\tko := r.ko.DeepCopy()\n\n\tif resp.AccessLogSettings != nil {\n\t\tf0 := &svcapitypes.AccessLogSettings{}\n\t\tif resp.AccessLogSettings.DestinationArn != nil {\n\t\t\tf0.DestinationARN = resp.AccessLogSettings.DestinationArn\n\t\t}\n\t\tif resp.AccessLogSettings.Format != nil {\n\t\t\tf0.Format = resp.AccessLogSettings.Format\n\t\t}\n\t\tko.Spec.AccessLogSettings = f0\n\t}\n\tif resp.ApiGatewayManaged != nil {\n\t\tko.Status.APIGatewayManaged = resp.ApiGatewayManaged\n\t}\n\tif resp.AutoDeploy != nil {\n\t\tko.Spec.AutoDeploy = resp.AutoDeploy\n\t}\n\tif resp.ClientCertificateId != nil {\n\t\tko.Spec.ClientCertificateID = resp.ClientCertificateId\n\t}\n\tif resp.CreatedDate != nil {\n\t\tko.Status.CreatedDate = &metav1.Time{*resp.CreatedDate}\n\t}\n\tif resp.DefaultRouteSettings != nil {\n\t\tf5 := &svcapitypes.RouteSettings{}\n\t\tif resp.DefaultRouteSettings.DataTraceEnabled != nil {\n\t\t\tf5.DataTraceEnabled = resp.DefaultRouteSettings.DataTraceEnabled\n\t\t}\n\t\tif resp.DefaultRouteSettings.DetailedMetricsEnabled != nil {\n\t\t\tf5.DetailedMetricsEnabled = resp.DefaultRouteSettings.DetailedMetricsEnabled\n\t\t}\n\t\tif resp.DefaultRouteSettings.LoggingLevel != nil {\n\t\t\tf5.LoggingLevel = resp.DefaultRouteSettings.LoggingLevel\n\t\t}\n\t\tif resp.DefaultRouteSettings.ThrottlingBurstLimit != nil {\n\t\t\tf5.ThrottlingBurstLimit = resp.DefaultRouteSettings.ThrottlingBurstLimit\n\t\t}\n\t\tif resp.DefaultRouteSettings.ThrottlingRateLimit != nil {\n\t\t\tf5.ThrottlingRateLimit = resp.DefaultRouteSettings.ThrottlingRateLimit\n\t\t}\n\t\tko.Spec.DefaultRouteSettings = f5\n\t}\n\tif resp.DeploymentId != nil {\n\t\tko.Spec.DeploymentID = resp.DeploymentId\n\t}\n\tif resp.Description != nil {\n\t\tko.Spec.Description = resp.Description\n\t}\n\tif resp.LastDeploymentStatusMessage != nil {\n\t\tko.Status.LastDeploymentStatusMessage = resp.LastDeploymentStatusMessage\n\t}\n\tif resp.LastUpdatedDate != nil {\n\t\tko.Status.LastUpdatedDate = &metav1.Time{*resp.LastUpdatedDate}\n\t}\n\tif resp.RouteSettings != nil {\n\t\tf10 := map[string]*svcapitypes.RouteSettings{}\n\t\tfor f10key, f10valiter := range resp.RouteSettings {\n\t\t\tf10val := &svcapitypes.RouteSettings{}\n\t\t\tif f10valiter.DataTraceEnabled != nil {\n\t\t\t\tf10val.DataTraceEnabled = f10valiter.DataTraceEnabled\n\t\t\t}\n\t\t\tif f10valiter.DetailedMetricsEnabled != nil {\n\t\t\t\tf10val.DetailedMetricsEnabled = f10valiter.DetailedMetricsEnabled\n\t\t\t}\n\t\t\tif f10valiter.LoggingLevel != nil {\n\t\t\t\tf10val.LoggingLevel = f10valiter.LoggingLevel\n\t\t\t}\n\t\t\tif f10valiter.ThrottlingBurstLimit != nil {\n\t\t\t\tf10val.ThrottlingBurstLimit = f10valiter.ThrottlingBurstLimit\n\t\t\t}\n\t\t\tif f10valiter.ThrottlingRateLimit != nil {\n\t\t\t\tf10val.ThrottlingRateLimit = f10valiter.ThrottlingRateLimit\n\t\t\t}\n\t\t\tf10[f10key] = f10val\n\t\t}\n\t\tko.Spec.RouteSettings = f10\n\t}\n\tif resp.StageName != nil {\n\t\tko.Spec.StageName = resp.StageName\n\t}\n\tif resp.StageVariables != nil {\n\t\tf12 := map[string]*string{}\n\t\tfor f12key, f12valiter := range resp.StageVariables {\n\t\t\tvar f12val string\n\t\t\tf12val = *f12valiter\n\t\t\tf12[f12key] = &f12val\n\t\t}\n\t\tko.Spec.StageVariables = f12\n\t}\n\tif resp.Tags != nil {\n\t\tf13 := map[string]*string{}\n\t\tfor f13key, f13valiter := range resp.Tags {\n\t\t\tvar f13val string\n\t\t\tf13val = *f13valiter\n\t\t\tf13[f13key] = &f13val\n\t\t}\n\t\tko.Spec.Tags = f13\n\t}\n\n\trm.setStatusDefaults(ko)\n\treturn &resource{ko}, nil\n}", "func (f *Format) FindByID(rep repository.Repository, id uint) (*Format, error) {\n\tvar format Format\n\tif error := rep.Where(\"id = ?\", id).First(&format).Error; error != nil {\n\t\treturn nil, error\n\t}\n\treturn &format, nil\n}", "func (d *DBRepository) findOne(ctx context.Context, id string) (*Travel, error) {\n\tobjectId, err := primitive.ObjectIDFromHex(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := d.Collection.FindOne(ctx, bson.M{\"_id\": objectId})\n\tvar travel Travel\n\tif err := res.Decode(&travel); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &travel, nil\n}", "func (k *Keeper) GetStage(ctx sdk.Context, round uint64) string {\n\tstore := ctx.KVStore(k.storeKey)\n\tkeyBytes := createKeyBytesByRound(round, keyStage)\n\tif !store.Has(keyBytes) {\n\t\treturn stageUnstarted\n\t}\n\tstage := string(store.Get(keyBytes))\n\treturn stage\n}", "func (a *LocalActivations) Find(name string) *Local {\n\tcurrent := a.Current()\n\tif current == nil {\n\t\treturn nil\n\t}\n\treturn current.Find(name)\n}", "func (repo *SingleStoryRepository) FindByID(ID uuid.UUID) *model.SingleStory {\n\tstory := &model.SingleStory{}\n\tif repo.Database.First(&story, \"id = ? and is_deleted = ?\", ID, false).RowsAffected == 0 {\n\t\treturn nil\n\t}\n\n\tif time.Now().After(story.CreationDate.Add(24 * time.Hour)){\n\t\t// PASSED TIME SHOULD SET STORY AS EXPIRED\n\t\t//stories[i].IsExpired = true\n\t\trepo.Database.Model(&model.SingleStory{}).Where(\"id = ?\", story.ID).Update(\"is_expired\", true)\n\t\trepo.Database.Model(&model.Story{}).Where(\"id = ?\", story.ID).Update(\"is_expired\", true)\n\t}\n\n\treturn story\n}", "func XPipelineSalesStagesBySalesMethodID(db XODB, salesMethodID uint) ([]*XPipelineSalesStage, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, name, probability, seq_num, active_flag, sales_method_id, created_by, updated_by, created_at, updated_at ` +\n\t\t`FROM x_showroom.x_pipeline_sales_stages ` +\n\t\t`WHERE sales_method_id = ?`\n\n\t// run query\n\tXOLog(sqlstr, salesMethodID)\n\tq, err := db.Query(sqlstr, salesMethodID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer q.Close()\n\n\t// load results\n\tres := []*XPipelineSalesStage{}\n\tfor q.Next() {\n\t\txpss := XPipelineSalesStage{\n\t\t\t_exists: true,\n\t\t}\n\n\t\t// scan\n\t\terr = q.Scan(&xpss.ID, &xpss.Name, &xpss.Probability, &xpss.SeqNum, &xpss.ActiveFlag, &xpss.SalesMethodID, &xpss.CreatedBy, &xpss.UpdatedBy, &xpss.CreatedAt, &xpss.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres = append(res, &xpss)\n\t}\n\n\treturn res, nil\n}", "func (m Manager) FindServiceInstanceByID(instanceID string) (*ServiceInstance, error) {\n\tserviceInstance := &ServiceInstance{ID: instanceID}\n\terr := m.db.Select(serviceInstance)\n\tif err != nil {\n\t\treturn &ServiceInstance{}, err\n\t}\n\treturn serviceInstance, nil\n}", "func (o *AwaitStageResultParams) SetStageID(stageID string) {\n\to.StageID = stageID\n}", "func (mm *Model) FindOneId(v interface{}, key string, id interface{}) error {\n\treturn mm.execute(func(c CachedCollection) error {\n\t\treturn c.FindOneId(v, key, id)\n\t})\n}", "func (t TaskService) FindRunByID(ctx context.Context, taskID, runID platform.ID) (*taskmodel.Run, error) {\n\tspan, _ := tracing.StartSpanFromContext(ctx)\n\tdefer span.Finish()\n\n\tvar rs = &runResponse{}\n\terr := t.Client.\n\t\tGet(taskIDRunIDPath(taskID, runID)).\n\t\tDecodeJSON(rs).\n\t\tDo(ctx)\n\n\tif err != nil {\n\t\tif errors2.ErrorCode(err) == errors2.ENotFound {\n\t\t\t// ErrRunNotFound is expected as part of the FindRunByID contract,\n\t\t\t// so return that actual error instead of a different error that looks like it.\n\t\t\t// TODO cleanup backend error implementation\n\t\t\treturn nil, taskmodel.ErrRunNotFound\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn convertRun(rs.httpRun), nil\n}", "func (d *Document) FindByID(ctx context.Context, id url.URL) (*flare.Document, error) {\n\td.mutex.RLock()\n\tdefer d.mutex.RUnlock()\n\n\tdocument, ok := d.documents[id]\n\tif !ok {\n\t\tidString, err := url.QueryUnescape(id.String())\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"error during transform and escape id to string\")\n\t\t}\n\n\t\treturn nil, &errMemory{message: fmt.Sprintf(\"document '%s' not found\", idString), notFound: true}\n\t}\n\treturn &document, nil\n}", "func (c *Context) Stage(s Stage) {\n\tif c.stage != nil {\n\t\tpanic(\"scene: context already initialized\")\n\t}\n\tc.stageId = s\n}", "func GetByID(id bson.ObjectId) (*Instance, error) {\n\tvar err error\n\tvar i Instance\n\n\tif id.Valid() == false {\n\t\treturn nil, errmsg.ErrInvalidID\n\t}\n\n\tres := InstanceCollection.Find(db.Cond{\n\t\t\"_id\": id,\n\t})\n\n\tif k, _ := res.Count(); k < 1 {\n\t\treturn nil, errmsg.ErrNoSuchItem\n\t}\n\n\tif err = res.One(&i); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &i, err\n}", "func (t TaskService) FindTaskByID(ctx context.Context, id platform.ID) (*taskmodel.Task, error) {\n\tspan, _ := tracing.StartSpanFromContext(ctx)\n\tdefer span.Finish()\n\n\tvar tr taskResponse\n\terr := t.Client.Get(taskIDPath(id)).DecodeJSON(&tr).Do(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn convertTask(tr.Task), nil\n}", "func VideoPlayerByID(rootView View, id string) VideoPlayer {\n\tif view := ViewByID(rootView, id); view != nil {\n\t\tif canvas, ok := view.(VideoPlayer); ok {\n\t\t\treturn canvas\n\t\t}\n\t\tErrorLog(`VideoPlayerByID(_, \"` + id + `\"): The found View is not VideoPlayer`)\n\t}\n\treturn nil\n}", "func (h *HistoricalRecords) FindRecord(id string) *TransferRecord {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\tfor _, dr := range h.records {\n\t\tif dr.UUID.String() == id {\n\t\t\treturn dr\n\t\t}\n\t}\n\n\treturn nil\n}", "func FindContainerByID(cli client.ContainerAPIClient, id string) (Container, error) {\n\tcontainers, err := cliContainerList(cli)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i, container := range containers {\n\t\tif container.ID == id {\n\t\t\treturn makeContainer(&containers[i]), nil\n\t\t}\n\t}\n\treturn nil, nil\n}", "func (s *tagStore) FindByID(ctx context.Context, id int64) (*models.Tag, error) {\n\tdefer metrics.InstrumentQuery(\"tag_find_by_id\")()\n\tq := `SELECT\n\t\t\tid,\n\t\t\ttop_level_namespace_id,\n\t\t\tname,\n\t\t\trepository_id,\n\t\t\tmanifest_id,\n\t\t\tcreated_at,\n\t\t\tupdated_at\n\t\tFROM\n\t\t\ttags\n\t\tWHERE\n\t\t\tid = $1`\n\trow := s.db.QueryRowContext(ctx, q, id)\n\n\treturn scanFullTag(row)\n}", "func (essenceDao EssenceDao) FindEssenceByID(id int64) (*models.Essence, error) {\n\tlog.Printf(\"Finding essence: %d\\r\\n\", id)\n\tessence := models.Essence{}\n\tdb, err := InitDB()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.Close()\n\tres, err := db.Query(\"Select essences_id, name, code from essences where essences_id=?\", id)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.Next() {\n\t\tres.Scan(&essence.ID, &essence.Name, &essence.Code)\n\t\treturn &essence, nil\n\t}\n\treturn nil, nil\n}", "func (c WorkItemTypeResource) FindOne(id string, r api2go.Request) (api2go.Responder, error) {\n\tutils.DebugLog.Printf(\"Received FindOne with ID %s.\", id)\n\tres, err := c.WorkItemTypeStorage.GetOne(bson.ObjectIdHex(id))\n\treturn &api2go.Response{Res: res}, err\n}", "func (r RepresentativeRepo) FindByID(id string) (d.Representative, error) {\n\ttx, err := r.DB.Begin()\n\tif err != nil {\n\t\treturn d.Representative{}, err\n\t}\n\n\trepresentative, err := r.FindByIDTx(tx, id)\n\tif err != nil {\n\t\treturn d.Representative{}, err\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn d.Representative{}, err\n\t}\n\n\treturn representative, nil\n}", "func (es *EventStore) FindByID(id string) (*Event, error) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tmetrics.EventStoreLatency(\"Find\", start)\n\t}()\n\tevt, err := es.ds.FindByID(id, true)\n\tif err != nil {\n\t\tmetrics.DBError(\"read\")\n\t\treturn nil, errors.Wrap(err, \"Error executing find in data source\")\n\t}\n\tif evt == nil {\n\t\treturn nil, errors.New(\"Could not find event matching id \" + id)\n\t}\n\tpropertiesSchema := es.getTopicSchemaProperties(evt.TopicID)\n\tif evt.Data == nil {\n\t\tevt.Data = make(map[string]interface{})\n\t}\n\tes.insertDefaults(propertiesSchema, evt.Data)\n\treturn evt, nil\n}", "func (p *RoleServ) FindByID(id types.RowID) (role model.Role, err error) {\n\trole, err = p.Repo.FindByID(id)\n\tp.Engine.CheckError(err, fmt.Sprintf(\"Role with id %v\", id))\n\n\treturn\n}", "func getAssetByID(id int) (*Asset, error) {\n\tpath := fmt.Sprintf(\"asset/%d\", id)\n\tresp, err := get(path, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed TCMD request\")\n\t}\n\n\tvar result Asset\n\terr = json.Unmarshal(resp, &result)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed to unmarshal TCMD response\")\n\t}\n\treturn &result, nil\n}", "func (m *Manager) Stage(name, dest string) error {\n\tif m.stager == nil {\n\t\tstager, err := m.newStager()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm.stager = stager\n\t}\n\n\ti := sort.SearchStrings(m.manifest, name)\n\tif i < len(m.manifest) && m.manifest[i] == name {\n\t\treturn m.stager.Stage(name, dest)\n\t}\n\n\treturn errors.Errorf(\"Requested asset %q not in manifest\", name)\n}", "func (p Program) Find(id uint) Program {\n\t//Preload preloads structs - Creates a SQL query pr. Preload. Should be fixed in Gorm V2.\n\tif err := db.Model(p).\n\t\tPreload(\"Production\").\n\t\tPreload(\"Category\").\n\t\tPreload(\"Genres\").\n\t\tPreload(\"Serie\").\n\t\tPreload(\"Season\").\n\t\tPreload(\"Credits\").\n\t\tPreload(\"Credits.Persons\").\n\t\tPreload(\"Credits.CreditGroup\").\n\t\tWhere(\"id = ?\", id).\n\t\tFirst(&p).Error; err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn p\n}", "func (s *LifecycleService) GetByID(id string) (*Lifecycle, error) {\n\tif internal.IsEmpty(id) {\n\t\treturn nil, internal.CreateInvalidParameterError(constants.OperationGetByID, constants.ParameterID)\n\t}\n\n\tpath, err := services.GetByIDPath(s, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := api.ApiGet(s.GetClient(), new(Lifecycle), path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.(*Lifecycle), nil\n}", "func (p *ProfilesExperiences) Find(qu Queryer, id int64) error {\n\tconst stmt = \"SELECT \" + selectProfilesExperiences + \" FROM `profiles__experiences__` WHERE id = ?\"\n\trow := qu.QueryRow(stmt, id)\n\treturn row.Scan(&p.ID, &p.ProfileID, &p.Start, &p.End, &p.Role, &p.TagLine, &p.Description)\n}", "func FindSource(exec boil.Executor, id int64, selectCols ...string) (*Source, error) {\n\tsourceObj := &Source{}\n\n\tsel := \"*\"\n\tif len(selectCols) > 0 {\n\t\tsel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), \",\")\n\t}\n\tquery := fmt.Sprintf(\n\t\t\"select %s from \\\"sources\\\" where \\\"id\\\"=$1\", sel,\n\t)\n\n\tq := queries.Raw(exec, query, id)\n\n\terr := q.Bind(sourceObj)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"mdbmdbmodels: unable to select from sources\")\n\t}\n\n\treturn sourceObj, nil\n}", "func FindByID(eventID string) (*EventLogEntry, error) {\n\tquery := bson.M{\n\t\tidKey: eventID,\n\t}\n\n\tvar e EventLogEntry\n\tif err := db.FindOneQ(EventCollection, db.Query(query), &e); err != nil {\n\t\tif adb.ResultsNotFound(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"finding event by ID\")\n\t}\n\treturn &e, nil\n}", "func (h *Handle) GetEpisodeByID(episodeid int64) (*Episode, error) {\n\tvar ep Episode\n\terr := h.db.Preload(\"Show\").Find(&ep, episodeid).Error\n\treturn &ep, err\n}", "func (*ActivityStageDataAccessObject) FindAll() []ActivityStage {\n\tl := make([]ActivityStage, 0)\n\terr := orm.Table(ActivityStageDAO.TableName()).Find(&l)\n\n\tlogger.LogIfError(err)\n\treturn l\n}", "func (t *Cases) FindBySessionID(sessionID string) []models.Case {\n\tvar cases []models.Case\n\n\tquery := func(db *gorm.DB) {\n\t\tdb.Where(&models.Case{SessionID: sessionID}).Find(&cases)\n\t}\n\n\terror := t.context.Execute(query)\n\n\tif error != nil {\n\t\treturn nil\n\t}\n\n\treturn cases\n}", "func Stage(ctx context.Context, id, endpoint, binary, st string) (retrievalToken string, err error) {\n\tctx = grpcx.WriteWorkerID(ctx, id)\n\tcc, err := grpcx.Dial(ctx, endpoint, 2*time.Minute)\n\tif err != nil {\n\t\treturn \"\", errors.WithContext(err, \"connecting to artifact service\")\n\t}\n\tdefer cc.Close()\n\n\tif err := StageViaPortableAPI(ctx, cc, binary, st); err == nil {\n\t\treturn \"\", nil\n\t}\n\tlog.Warnf(ctx, \"unable to stage with PortableAPI: %v; falling back to legacy\", err)\n\n\treturn StageViaLegacyAPI(ctx, cc, binary, st)\n}", "func (p *PlanetHandler) GetByID(c *fiber.Ctx) error {\n\n\tidP := c.Params(\"id\")\n\n\tif idP == \"\" {\n\t\treturn c.Status(fiber.StatusNotFound).JSON(domain.ErrNotFound.Error())\n\t}\n\n\tplnt, err := p.PUsecase.GetByID(idP)\n\n\tif err != nil {\n\t\treturn c.Status(getStatusCode(err)).JSON(ResponseError{Message: err.Error()})\n\t}\n\n\tswapi_plnt, err := p.SWapi.GetPlanetByName(plnt.Name)\n\n\tif err != nil {\n\t\treturn c.Status(getStatusCode(err)).JSON(ResponseError{Message: err.Error()})\n\t}\n\n\tif swapi_plnt != nil {\n\t\tplnt.Appearances = len(swapi_plnt.Films)\n\t}\n\n\treturn c.Status(fiber.StatusOK).JSON(&plnt)\n}", "func (s *Server) FindOne(c echo.Context) error {\n\tspan := opentracing.StartSpan(\"API.FindOne\")\n\tdefer span.Finish()\n\n\tquery := c.Param(\"id\")\n\n\tjob, err := s.Storage.FindOne(query)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn err\n\t}\n\n\tc.JSON(http.StatusOK, job)\n\treturn nil\n}", "func (m Manager) FindServiceBindingByID(instanceID string) (*ServiceBinding, error) {\n\tserviceBinding := &ServiceBinding{ID: instanceID}\n\terr := m.db.Select(serviceBinding)\n\tif err != nil {\n\t\treturn &ServiceBinding{}, err\n\t}\n\treturn serviceBinding, nil\n}", "func (s *Service) FindByID(ctx context.Context, id string) (*Article, error) {\n\ta, err := s.repo.FindByID(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn a, nil\n}", "func FindContainerByShortID(cli client.ContainerAPIClient, id string) (Container, error) {\n\tcontainers, err := cliContainerList(cli)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i, container := range containers {\n\t\tif strings.HasPrefix(container.ID, id) {\n\t\t\treturn makeContainer(&containers[i]), nil\n\t\t}\n\t}\n\treturn nil, nil\n}", "func (*SeatDataAccessObject) FindByID(seatID int) *Seat {\n\tvar seat Seat\n\thas, err := orm.Table(seat).ID(seatID).Get(&seat)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !has {\n\t\treturn nil\n\t}\n\treturn &seat\n}", "func (stage *Stage) execStage(syncer Syncer, id string, input, seed interface{}) (*StageResult, bool, error) {\n\t// Take exclusive lock\n\tok, err := syncer.Lock(id, stage.name, stage.ttl)\n\tif err != nil {\n\t\treturn nil, false, StageConflictError(err)\n\t}\n\tif !ok {\n\t\treturn nil, false, StageConflictError(fmt.Errorf(\"cannot get exclusive lock for %s:%s\", stage.name, id))\n\t}\n\tdefer func() {\n\t\tif err := syncer.Unlock(id, stage.name); err != nil {\n\t\t\tlog.Printf(\"Cannot unset execution lock %+v\", err)\n\t\t}\n\t}()\n\n\t// execute stage\n\tstageResultWriter := &StageResultWriter{}\n\tif err := stage.handler(stageResultWriter, input, seed); err != nil {\n\t\treturn nil, false, err\n\t}\n\tstageResult := stageResultWriter.result\n\tstageResult.Status = \"done\"\n\t// sync stage data\n\tif err := syncer.Set(id, stage.name, &stageResult); err != nil {\n\t\treturn nil, false, errors.Wrap(err, \"Cannot sync state result\")\n\t}\n\treturn &stageResult, stageResultWriter.bookmark, nil\n}", "func (f FileRepo) FindByID(context context.Context, id string) (*model.FileDTO, error) {\n\tobjID, err := primitive.ObjectIDFromHex(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tquery := bson.M{\n\t\t\"_id\": objID,\n\t}\n\tvar file model.File\n\terr = f.collection.FindOne(context, query).Decode(&file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn file.DTO(), nil\n}", "func (t *Transaction) FindByID(searchID string) {\n\tif bson.IsObjectIdHex(searchID) {\n\t\terr := Transactions.FindId(bson.ObjectIdHex(searchID)).One(&t)\n\t\tif err != nil {\n\t\t\tlog.Println(\"[MONGO] ERROR FINDING TRANSACTION:\", err.Error())\n\t\t}\n\t}\n}", "func (o MonitoredResourceDescriptorOutput) LaunchStage() MonitoredResourceDescriptorLaunchStagePtrOutput {\n\treturn o.ApplyT(func(v MonitoredResourceDescriptor) *MonitoredResourceDescriptorLaunchStage { return v.LaunchStage }).(MonitoredResourceDescriptorLaunchStagePtrOutput)\n}", "func (col *Collection) FindById(id int) (doc map[string]interface{}, err error) {\n\tcol.db.access.RLock()\n\tdefer col.db.access.RUnlock()\n\n\tpart := col.parts[id%col.db.numParts]\n\tpart.Lock.RLock()\n\tdocB, err := part.Read(id)\n\tpart.Lock.RUnlock()\n\tif err != nil {\n\t\treturn\n\t}\n\terr = json.Unmarshal(docB, &doc)\n\treturn\n\n}", "func (h *Hub) FindRun(flowID, runID string) *Run {\n\treturn h.runs.find(flowID, runID)\n}", "func GetByID(ctx *routing.Context) error {\n\tlogger := logger.GetLogInstance(\"\", \"\")\n\tdb := ctx.Get(\"db\").(*gorm.DB)\n\n\tcmp := models.CampaingModel{}\n\n\tif err := db.Model(&[]dbmodels.Campaign{}).Where(\"id = ?\", ctx.Param(\"id\")).Scan(&cmp).Error; err != nil {\n\t\tlogger.Error(err)\n\t\tctx.Response.SetStatusCode(404)\n\t\tres := models.NewResponse(false, nil, \"not found\")\n\t\treturn ctx.WriteData(res.MustMarshal())\n\t}\n\tres := models.NewResponse(true, cmp, \"OK\")\n\treturn ctx.WriteData(res.MustMarshal())\n}", "func (db Db) findPortfolio(pid string) (primitive.ObjectID, error) {\n\tid, err := primitive.ObjectIDFromHex(pid)\n\tif err != nil {\n\t\treturn id, err\n\t}\n\n\tctx := db.context()\n\tfilter := bson.M{\"_id\": id}\n\topts := options.FindOne()\n\n\tr := db.portfolios.FindOne(ctx, filter, opts)\n\tvar result struct {\n\t\tID primitive.ObjectID `bson:\"_id\"`\n\t}\n\n\tif r.Err() != nil {\n\t\treturn result.ID, nil\n\t}\n\n\tr.Decode(&result)\n\treturn result.ID, nil\n}", "func (foo *Foo) Stage() *Foo {\n\tStage.Foos[foo] = __member\n\tStage.Foos_mapString[foo.Name] = foo\n\n\treturn foo\n}", "func (o UsagePlanApiStageOutput) Stage() pulumi.StringOutput {\n\treturn o.ApplyT(func(v UsagePlanApiStage) string { return v.Stage }).(pulumi.StringOutput)\n}" ]
[ "0.7213947", "0.6356022", "0.61952245", "0.5932387", "0.5759876", "0.5512548", "0.5455825", "0.54276675", "0.5356593", "0.5345344", "0.5340388", "0.526985", "0.52464676", "0.52199566", "0.5216761", "0.5199165", "0.5181279", "0.5174388", "0.51244295", "0.5110674", "0.50951016", "0.50814617", "0.5070981", "0.5065987", "0.5059258", "0.50478876", "0.50420594", "0.50256", "0.5023823", "0.50184923", "0.500972", "0.50065494", "0.5004354", "0.50006324", "0.4988825", "0.4986739", "0.49829227", "0.49598294", "0.4956848", "0.4955429", "0.49549034", "0.49431947", "0.4941312", "0.49308655", "0.49158835", "0.49127603", "0.49077547", "0.49019203", "0.489753", "0.48906326", "0.48810622", "0.4876042", "0.48728958", "0.48728058", "0.48614645", "0.48594296", "0.48583785", "0.48583695", "0.48559391", "0.4852603", "0.48520425", "0.48479217", "0.48391047", "0.48189732", "0.4815762", "0.4806557", "0.48044008", "0.47924337", "0.47814646", "0.47748184", "0.47712842", "0.4760365", "0.4758895", "0.47532353", "0.47529382", "0.4751107", "0.47327897", "0.47269437", "0.4725376", "0.4724119", "0.4714944", "0.47119313", "0.47005352", "0.4698634", "0.4696912", "0.46927428", "0.469238", "0.46910688", "0.46865645", "0.46858528", "0.46792507", "0.46792224", "0.46772513", "0.46711177", "0.46675828", "0.46592084", "0.46550027", "0.4651866", "0.4650683", "0.46485746" ]
0.7757321
0
Retrieves a token from a local file.
func tokenFromFile(file string) (*oauth2.Token, error) { f, err := os.Open(file) defer f.Close() if err != nil { return nil, err } tok := &oauth2.Token{} err = json.NewDecoder(f).Decode(tok) return tok, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func tokenFromFile(file string) (*oauth2.Token, error) {\n f, err := os.Open(file)\n if err != nil {\n return nil, err\n }\n defer f.Close()\n tok := &oauth2.Token{}\n err = json.NewDecoder(f).Decode(tok)\n return tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n f, err := os.Open(file)\n if err != nil {\n return nil, err\n }\n defer f.Close()\n tok := &oauth2.Token{}\n err = json.NewDecoder(f).Decode(tok)\n return tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n f, err := os.Open(file)\n if err != nil {\n return nil, err\n }\n t := &oauth2.Token{}\n err = json.NewDecoder(f).Decode(t)\n defer f.Close()\n return t, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n f, err := os.Open(file)\n if err != nil {\n return nil, err\n }\n t := &oauth2.Token{}\n err = json.NewDecoder(f).Decode(t)\n defer f.Close()\n return t, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n f, err := os.Open(file)\n if err != nil {\n return nil, err\n }\n t := &oauth2.Token{}\n err = json.NewDecoder(f).Decode(t)\n defer f.Close()\n return t, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\r\n\tf, err := os.Open(file)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tdefer f.Close()\r\n\ttok := &oauth2.Token{}\r\n\terr = json.NewDecoder(f).Decode(tok)\r\n\treturn tok, err\r\n}", "func getTokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttoken := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(token)\n\treturn token, err\n}", "func fetchTokenFromFile(path string) (*oauth2.Token, bool) {\n\t// Check if file exists, if YES, return token\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\n\tt := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(t)\n\tdefer f.Close()\n\treturn t, true \n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(t)\n\tdefer f.Close()\n\treturn t, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(t)\n\tdefer f.Close()\n\treturn t, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(t)\n\tdefer f.Close()\n\treturn t, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(t)\n\tdefer f.Close()\n\treturn t, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() { _ = f.Close() }()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tvar err error\n\tvar f *os.File\n\tif f, err = os.Open(file); err != nil {\n\t\treturn nil, err\n\t}\n\tt := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(t)\n\tdefer f.Close()\n\treturn t, err\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"os.Open: %w\", err)\n\t}\n\tdefer f.Close()\n\n\ttok := &oauth2.Token{}\n\tif err := json.NewDecoder(f).Decode(tok); err != nil {\n\t\treturn nil, fmt.Errorf(\"json.NewDecoder(f).Decode: %w\", err)\n\t}\n\treturn tok, nil\n}", "func tokenFromFile(file string) (*oauth2.Token, error) {\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &oauth2.Token{}\n\terr = json.Unmarshal(b, t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn t, err\n}", "func loadToken(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tt := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(t)\n\treturn t, err\n}", "func GetTokenFromFile(tokenFile string) (string, error) {\n\tfile, err := os.Stat(tokenFile)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to stat token file %s, falling back to login\", tokenFile)\n\t}\n\n\tttl := time.Duration(GetTTL())\n\texpiryTime := time.Now().Add((0 - ttl + TokenGracePeriod) * time.Second)\n\n\tif file.ModTime().Before(expiryTime) {\n\t\treturn \"\", errors.New(\"Token too close to expiry\")\n\t}\n\n\trawToken, err := ioutil.ReadFile(tokenFile)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlog.Infof(\"Re-using Vault token from token file: %s\", tokenFile)\n\n\treturn strings.TrimSpace(string(rawToken)), nil\n}", "func gDriveTokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tdefer CloseCheck(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func TokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(t)\n\tdefer f.Close()\n\treturn t, err\n}", "func TokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func (t *DefaultTokenStorage) Get(key string) (*oauth2.Token, error) {\n\tfn := path.Join(t.fsPath, key)\n\tfmt.Printf(\"TOK_DEBUG:: looking for token in %s\\n\", fn)\n\tif _, err := os.Stat(fn); err != nil {\n\t\tfmt.Printf(\"TOK_DEBUG:: no token found in %s\\n\", fn)\n\t\treturn nil, nil\n\t}\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttoken := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Printf(\"TOK_DEBUG:: got token from %s\\n\", fn)\n\treturn token, nil\n}", "func loadToken(absPath string) (*oauth2.Token, error) {\n\ttok := &oauth2.Token{}\n\n\tf, err := os.Open(absPath)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"open token file %s for read: %w\", absPath, err)\n\t}\n\tdefer func() { _ = f.Close() }() // don't care about close when reading\n\n\tif err = json.NewDecoder(f).Decode(tok); err != nil {\n\t\terr = xerrors.Errorf(\"reading token from %s: %w\", absPath, err)\n\t}\n\n\treturn tok, err\n}", "func (f *FileStorage) GetToken() (*oauth2.Token, error) {\n\tf.mu.RLock()\n\tdefer f.mu.RUnlock()\n\tin, err := os.Open(f.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer in.Close()\n\tvar t *oauth2.Token\n\tdata := json.NewDecoder(in)\n\treturn t, data.Decode(&t)\n}", "func GetToken() string {\n\tvar tkn Token\n\n\tif _, err := toml.DecodeFile(path, &tkn); err != nil {\n\t\tlog.Fatalf(\"Token not received: %v\", err)\n\t}\n\treturn tkn.Token\n}", "func TokenFromFile(jsonFile string) (*oauth2.Token, error) {\n\tf, err := os.Open(jsonFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func GetTokenFromFile() error {\n\thome, _ := os.UserHomeDir()\n\tdir := home + \"/.config/cuack.config\"\n\tfile, err := os.Open(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tscanner := bufio.NewScanner(file)\n\tscanner.Split(bufio.ScanLines)\n\tfor scanner.Scan() {\n\t\tToken = scanner.Text()\n\t\tif strings.HasPrefix(Token, \"key\") && strings.Fields(Token)[1] != \"\" {\n\t\t\tToken = strings.Fields(Token)[1]\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"error getting the token from file\")\n}", "func GetToken(tokenPath string) (string, error) {\n\n\t// Get user home directory\n\tuserHome, err := util.GetUserHomeDir()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"ACL error. %s\", err)\n\t}\n\n\t// open data file\n\tdataFile, err := os.Open(userHome + tokenPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to retrieve token file at %s. %s\", tokenPath, err)\n\t}\n\n\tdataDecoder := gob.NewDecoder(dataFile)\n\tresult := \"\"\n\terr = dataDecoder.Decode(&result)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"failed to decode token file at .cybr/config. %s\", err)\n\t}\n\n\tdataFile.Close()\n\n\treturn result, nil\n}", "func (i *InternalTokenHelper) Get() (string, error) {\n\ti.populateTokenPath()\n\tf, err := os.Open(i.tokenPath)\n\tif os.IsNotExist(err) {\n\t\treturn \"\", nil\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(buf, f); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn strings.TrimSpace(buf.String()), nil\n}", "func getGoogleTokenFromFile(file string) (*oauth2.Token, error) {\n\n\t// os.Open opens the credential file.\n\t// creates File object\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// initialize Token object\n\tt := &oauth2.Token{}\n\n\t// json.NewDecoder returns a new decoder that reads from r.\n\t// the decoder introduces its own buddering and may read data\n\t// from r beyond the JSON values requested.\n\td := json.NewDecoder(f)\n\n\t// Decode reads the next JSON-encoded value from its input\n\t// and stores it in the value pointed to by v.\n\terr = d.Decode(t)\n\tdefer f.Close()\n\treturn t, err\n}", "func readToken(filePath string) (string, error) {\n\tb, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}", "func FromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}", "func (t *ServiceAccountToken) readTokenFromFile() (*oauth2.Token, error) {\n\t// Read the token from the file.\n\tcontents, err := ioutil.ReadFile(t.filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttok := new(oauth2.Token)\n\tif err := json.NewDecoder(bytes.NewReader(contents)).Decode(tok); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Validate the token.\n\tif err := ValidateToken(tok); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tok, nil\n}", "func readToken() (*oauth2.Token, error) {\n\tdata, err := os.ReadFile(tokenFilePath())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttok := &oauth2.Token{}\n\tif err := json.Unmarshal(data, tok); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tok, nil\n}", "func (ts *FileTokenStorage) Load() (*Token, error) {\n\tif _,err := os.Stat(ts.tokenFileName); err == nil {\n\t\tout, err := ioutil.ReadFile(ts.tokenFileName)\n\t\tts.token = string(out)\n\t\treturn NewToken(ts.token), err\n\t}\n\ttoken := NewToken(\"\")\n\ttoken.Invalidate()\n\treturn token, nil\n}", "func ReadToken(filename string) (string, error) {\n\tdat, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimSpace(string(dat)), nil\n}", "func Token() (token string, err error) {\n\ttokenFile, err := ioutil.ReadFile(\"API/models/telegram/token.txt\")\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(tokenFile), nil\n}", "func tokenFromStringOrFile(s string) (token clccam.Token, err error) {\n\tif _, err := os.Stat(s); err == nil { // @s points to a file\n\t\tcontents, err := ioutil.ReadFile(s)\n\t\tif err != nil {\n\t\t\treturn token, errors.Wrapf(err, \"failed to read %s\", s)\n\t\t}\n\t\treturn clccam.Token(string(bytes.TrimSpace(contents))), nil\n\t} else if s == \"\" { // @s probably contains a token\n\t\treturn token, errors.Errorf(\"empty token string\")\n\t} else if _, err := clccam.Token(s).Decode(); err != nil {\n\t\treturn token, errors.Wrapf(err, \"failed to decode %q\", s)\n\t}\n\treturn clccam.Token(s), nil\n}", "func checkForToken() (*oauth2.Token, error) {\n\t// open file for reading\n\tfile, err := os.Open(tokenPath)\n\tdefer file.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttoken := &oauth2.Token{}\n\n\t// parse token json into Token\n\terr = json.NewDecoder(file).Decode(token)\n\treturn token, err\n}", "func (h *Handler) GetFromFile(filename string) (*corev1.Secret, error) {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn h.GetFromBytes(data)\n}", "func TokenRecover(fileName string) {\n\tfileContent, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = json.Unmarshal(fileContent, &tokens); err != nil {\n\t\treturn\n\t}\n}", "func Token(config *config.SubmitConfig) (string, error) {\n\ttokenbytes, err := ioutil.ReadFile(filepath.Join(pathutil.UserHomeDir(), \".paddle\", \"token_cache\"))\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"previous token not found, fetching a new one...\\n\")\n\t\t// Authenticate to the cloud endpoint\n\t\tauthJSON := map[string]string{}\n\t\tauthJSON[\"username\"] = config.ActiveConfig.Username\n\t\tauthJSON[\"password\"] = config.ActiveConfig.Password\n\t\tauthStr, _ := json.Marshal(authJSON)\n\t\tbody, err := getToken(config.ActiveConfig.Endpoint+\"/api-token-auth/\", authStr)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvar respObj interface{}\n\t\tif errJSON := json.Unmarshal(body, &respObj); errJSON != nil {\n\t\t\treturn \"\", errJSON\n\t\t}\n\t\ttokenStr := respObj.(map[string]interface{})[\"token\"].(string)\n\t\terr = ioutil.WriteFile(filepath.Join(pathutil.UserHomeDir(), \".paddle\", \"token_cache\"), []byte(tokenStr), 0600)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"write cache token file error: %v\", err)\n\t\t}\n\t\t// Ignore write token error, fetch a new one next time\n\t\treturn tokenStr, nil\n\t}\n\treturn string(tokenbytes), nil\n}", "func GetToken() string {\n\ttoken, err := d.Read(key)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\treturn string(token)\n}", "func getAuthHeaderFromToken(path string) (string, error) {\n\tvar token string\n\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"reading bearer token file\")\n\t}\n\n\tif len(b) != 0 {\n\t\tif b[len(b)-1] == '\\n' {\n\t\t\tb = b[0 : len(b)-1]\n\t\t}\n\t\ttoken = fmt.Sprintf(\"Bearer %s\", string(b))\n\t}\n\n\treturn token, nil\n}", "func findToken() string {\n\tvar contents []byte\n\tvar err error\n\ttokenFilename := \"STRAVA_TOKEN\"\n\t_, err = os.Stat(tokenFilename)\n\tif err == nil {\n\t\tcontents, err = ioutil.ReadFile(tokenFilename)\n\t\tif err == nil {\n\t\t\treturn strings.TrimSpace(string(contents))\n\t\t}\n\t}\n\treturn \"\"\n}", "func loadToken() (string, error) {\n\tif loadFromLocal {\n\t\t//load from Disk\n\t\tuserDir, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tvaultFileName := path.Join(userDir, \".vault-token\")\n\n\t\tif _, err := os.Stat(vaultFileName); os.IsNotExist(err) {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tb, error := ioutil.ReadFile(vaultFileName)\n\t\tif error != nil {\n\t\t\tpanic(error)\n\t\t}\n\n\t\tvaultToken = string(b) // convert to string\n\t} else {\n\t\t// load rootToken from AWS Parameter Store\n\t\tvar ps ParameterStore\n\t\terr := ps.NewParameterStore()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error: Could not connect to AWS Parameter store using your credentials?\")\n\t\t\tpanic(err)\n\t\t}\n\n\t\trootToken := vaultClusterName + \".roottoken\"\n\t\tpArray := make([]string, 1)\n\t\tpArray[0] = rootToken\n\t\tpVals, err := ps.Get(pArray)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error: Could not find root token for cluster in AWS.\")\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, token := range pVals {\n\t\t\tvaultToken = *token.Value\n\t\t}\n\t}\n\treturn vaultToken, nil\n}", "func getToken(config *oauth2.Config) *oauth2.Token {\n\t// The file token.json stores the user's access and refresh tokens, and is\n\t// created automatically when the authorization flow completes for the first\n\t// time.\n\ttokFile := \"token.json\"\n\ttok, err := tokenFromFile(tokFile)\n\tif err != nil {\n\t\ttok = getTokenFromWeb(config)\n\t\tSaveToken(tokFile, tok)\n\t\tlog.Println(\"OAuth token renewed.\")\n\t}\n\treturn tok\n}", "func (m *Manager) getTokens() (*Token, error) {\n\thome, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\ttokensFilePath := filepath.Join(home, authTokenPath)\n\tf, err := os.Open(tokensFilePath)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\t// ignoring errors here\n\t// as we fall back to retrieving acces token from env\n\t// if not found in env then will finally return an error\n\tvar tokens Token\n\tcontents, _ := ioutil.ReadAll(f)\n\tjson.Unmarshal(contents, &tokens)\n\n\t// first priority to aws access token\n\tif tokens.AccessToken != \"\" {\n\t\treturn &tokens, nil\n\t}\n\n\t// if no congito token\n\tm.bearerAuth = false\n\n\t// check the env first for deta access token\n\tdetaAccessToken := os.Getenv(detaAccessTokenEnv)\n\n\t// if not in env, check from tokens retreived from file\n\tif detaAccessToken == \"\" {\n\t\tdetaAccessToken = tokens.DetaAccessToken\n\t}\n\n\t// if still no token found, return err\n\tif detaAccessToken == \"\" {\n\t\treturn nil, ErrNoAuthTokenFound\n\t}\n\treturn &Token{\n\t\tDetaAccessToken: detaAccessToken,\n\t}, nil\n}", "func NewAuthenticationTokenFromFile(tokenFilePath string) *TokenAuthProvider {\n\treturn &TokenAuthProvider{\n\t\ttokenSupplier: func() (string, error) {\n\t\t\tdata, err := ioutil.ReadFile(tokenFilePath)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\ttoken := strings.Trim(string(data), \" \\n\")\n\t\t\tif token == \"\" {\n\t\t\t\treturn \"\", errors.New(\"empty token credentials\")\n\t\t\t}\n\t\t\treturn token, nil\n\t\t},\n\t}\n}", "func (conf *OnboardingConfig) Token() (string, error) {\n\ttoken, err := utils.TryReadValueAsFile(conf.TokenValue)\n\tif err != nil {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\n\treturn token, nil\n}", "func tokenCacheFile() (string, error) {\n\treturn \"data/hide-youtube-live.json\", nil\n}", "func (c *GithubTokenController) Read(ctx *app.ReadGithubTokenContext) error {\n\t// GithubTokenController_Read: start_implement\n\n\t// Put your logic here\n\tbytes, err := ioutil.ReadFile(\"./.deploy/github_api.txt\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tvar token string = string(bytes)\n\n\t// GithubTokenController_Read: end_implement\n\tres := &app.GithubtokenMt{&token}\n\treturn ctx.OK(res)\n}", "func getGitHubToken() (string, error) {\n\tfile := filepath.Join(config.Home(), \"upspin\", \"issueserver-github-token\")\n\ttoken, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(bytes.TrimSpace(token)), nil\n}", "func cliToken(tenantID, userID string) (*spToken, error) {\n\ttokensPath, err := azcli.AccessTokensPath()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// azcli.LoadTokens doesn't handle service principals\n\tb, err := ioutil.ReadFile(tokensPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar toks []*spToken\n\tif err = json.Unmarshal(b, &toks); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, t := range toks {\n\t\tif (t.IsMRRT && t.UserID == userID &&\n\t\t\tstrings.HasSuffix(t.Authority, tenantID)) ||\n\t\t\t(t.ServicePrincipalID == userID &&\n\t\t\t\tt.ServicePrincipalTenant == tenantID) {\n\t\t\treturn t, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"az: access token not found in %q\", tokensPath)\n}", "func getVaultToken(tokenURL string) string {\n\tvaultTokenEnv := os.Getenv(\"VAULT_TOKEN\")\n\tif vaultTokenEnv != \"\"{\n\t\treturn vaultTokenEnv\n\t}else {\n\t\tif strings.Contains(\"http\", tokenURL) {\n\t\t\tresp, err := http.Get(tokenURL)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error( \"Get token error: \", err)\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\n\t\t\tif resp.StatusCode == http.StatusOK {\n\t\t\t\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t\tvaultToken = string(bodyBytes)\n\t\t\t} else {\n\t\t\t\tlog.Error( \"Can not retrieve token: \", resp.Status)\n\t\t\t}\n\t\t\treturn vaultToken\n\t\t} else {\n\t\t\t_, err := os.Stat(tokenURL)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error( \"vault token not found: \", err)\n\t\t\t}\n\t\t\tb, err := ioutil.ReadFile(tokenURL)\n\t\t\tvaultToken = string(b)\n\t\t\treturn vaultToken\n\t\t}\n\t}\n}", "func (p *tokenSource) Token() (*oauth2.Token, error) {\n\ttoken, err := readFileContent(path.Join(p.path, fmt.Sprintf(\"%s-token-secret\", p.name)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokenType, err := readFileContent(path.Join(p.path, fmt.Sprintf(\"%s-token-type\", p.name)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// parse the token claims to get expiry time\n\tclaims, err := jwt.ParseClaims(token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &oauth2.Token{\n\t\tAccessToken: token,\n\t\tTokenType: tokenType,\n\t\tExpiry: time.Unix(int64(claims.Exp), 0),\n\t}, nil\n}", "func LoadCachedToken() (*Token, error) {\n\tvar t Token\n\n\tbody, err := ioutil.ReadFile(TokenCachePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Parse response, get token structure\n\terr = json.Unmarshal(body, &t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &t, nil\n}", "func tokenSource(ctx context.Context) (oauth2.TokenSource, error) {\n\tok, err := credsFile.Exists()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar bootstrapToken *oauth2.Token\n\tif !ok {\n\t\ttok, err := authenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbootstrapToken = tok\n\t}\n\treturn newCachedTokenFile(ctx, bootstrapToken, credsFile.Path())\n}", "func GetToken(client *http.Client, urlString string) (string, error) {\n\treq, _ := http.NewRequest(\"GET\", urlString, nil)\n\tres, err := client.Do(req)\n\tdefer func() {\n\t\tif res.Body != nil {\n\t\t\tres.Body.Close()\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn parseToken(res)\n}", "func (tp *singleUseTokenProvider) GetToken(uri string) (*auth.Token, error) {\n\treturn (*auth.Token)(tp), nil\n}", "func ReadServiceAccountToken() string {\n\tcontent, err := ioutil.ReadFile(\"/run/secrets/kubernetes.io/serviceaccount/token\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn string(content)\n}", "func LoadTokenConfig(filename string) (TokenConfig, error) {\n\tcfr, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tdefer cfr.Close()\n\ttokenConfig := new(tokenConfig)\n\terr = json.NewDecoder(cfr).Decode(tokenConfig)\n\tif err != nil {\n\t\treturn nil, errors.WithMessagef(err, \"failed to decode file: %s\", filename)\n\t}\n\n\tpin := tokenConfig.Pin()\n\tif strings.HasPrefix(pin, \"file:\") {\n\t\tpinfile := pin[5:]\n\n\t\t// try to resolve pin file\n\t\tcwd, _ := os.Getwd()\n\t\tfolders := []string{\n\t\t\t\"\",\n\t\t\tcwd,\n\t\t\tfilepath.Dir(filename),\n\t\t}\n\n\t\tfor _, folder := range folders {\n\t\t\tif resolved, err := resolve.File(pinfile, folder); err == nil {\n\t\t\t\tpinfile = resolved\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlogger.Warningf(\"reason=resolve, pinfile=%q, basedir=%q\", pinfile, folder)\n\t\t}\n\n\t\tpb, err := ioutil.ReadFile(pinfile)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessagef(err, \"unable to load PIN for configuration: %s\", filename)\n\t\t}\n\t\ttokenConfig.Pwd = string(pb)\n\t}\n\n\treturn tokenConfig, nil\n}", "func OpenTokenList(filename string) error {\n\tvar jsonList []TokenList\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = json.Unmarshal(file, &jsonList)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttokenList = jsonList\n\treturn err\n}", "func LoadTokens() (*Tokens, error) {\n\tfile, err := ioutil.ReadFile(TokensFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttokens := &Tokens{}\n\tlines := strings.Split(string(file), \"\\n\")\n\tfor _, line := range lines {\n\t\ttoken := strings.Fields(line)\n\t\tif len(token) > 0 {\n\t\t\tswitch token[0] {\n\t\t\tcase \"twitterConsumerKey\":\n\t\t\t\ttokens.twitter.twitterConsumerKey = token[2]\n\t\t\tcase \"twitterConsumerSecret\":\n\t\t\t\ttokens.twitter.twitterConsumerSecret = token[2]\n\t\t\tcase \"twitterAccessToken\":\n\t\t\t\ttokens.twitter.twitterAccessToken = token[2]\n\t\t\tcase \"twitterAccessSecret\":\n\t\t\t\ttokens.twitter.twitterAccessSecret = token[2]\n\t\t\tcase \"githubPersonalAccessToken\":\n\t\t\t\ttokens.github.githubPersonalAccessToken = token[2]\n\t\t\tdefault:\n\t\t\t\treturn tokens, fmt.Errorf(\"Cannot identify token in line %q\", line)\n\t\t\t}\n\t\t}\n\t}\n\treturn tokens, nil\n}", "func GToken() string {\n\treturn viper.GetString(\"google-safile\")\n}", "func Token(c *cli.Context) {\n\tconfigPath := c.GlobalString(\"config\")\n\n\tconfig, err := parseConfig(configPath)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error parsing the config : %s\", err)\n\t\treturn\n\t}\n\n\tfmt.Print(string(authtoken.Token(config.HTTP.Login, config.HTTP.Password, config.HTTP.Salt)))\n}", "func NewTokensFromFile(filename string) (ts Tokens, err error) {\n\tvar f *os.File\n\tif f, err = os.Open(filename); err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\tvar bs []byte\n\tif bs, err = ioutil.ReadFile(filename); err != nil {\n\t\treturn\n\t}\n\n\tts = NewTokens(string(bs))\n\treturn\n}", "func (c *DiskTokenCache) GetToken(key *CacheKey) (*Token, error) {\n\tcache, err := c.readCacheFile()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, entry := range cache.Cache {\n\t\tif EqualCacheKeys(&entry.Key, key) {\n\t\t\treturn &Token{\n\t\t\t\tToken: entry.Token,\n\t\t\t\tEmail: entry.Email,\n\t\t\t}, nil\n\t\t}\n\t}\n\treturn nil, nil\n}", "func (t *ServiceAccountToken) Get() (*oauth2.Token, error) {\n\tt.mtx.RLock()\n\tdefer t.mtx.RUnlock()\n\treturn t.tok, nil\n}", "func (f *CLIAuthCodeFlow) GetToken(ctx context.Context) (*oauth2.Token, error) {\n\tf.Config.RedirectURL = \"urn:ietf:wg:oauth:2.0:oob\"\n\tstate, err := generateOAuthState()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthCodeURL := f.Config.AuthCodeURL(state)\n\tlog.Printf(\"Open %s for authorization\", authCodeURL)\n\tfmt.Print(\"Enter code: \")\n\tvar code string\n\tif _, err := fmt.Scanln(&code); err != nil {\n\t\treturn nil, err\n\t}\n\ttoken, err := f.Config.Exchange(ctx, code)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not exchange oauth code: %s\", err)\n\t}\n\treturn token, nil\n}", "func GetToken(c *gin.Context) {\n\tcode = c.Query(\"code\")\n\t//fmt.Println(\"code: \" + code)\n\tTokenRequest(code, c)\n}", "func tokenCacheFile() (string, error) {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ttokenCacheDir := filepath.Join(usr.HomeDir, \".credentials\")\n\tfmt.Println(tokenCacheDir)\n\tos.MkdirAll(tokenCacheDir, 0700)\n\treturn filepath.Join(tokenCacheDir,\n\t\turl.QueryEscape(\"youtube-go-quickstart.json\")), err\n}", "func saveToken(file string, token *oauth2.Token) {\n fmt.Printf(\"Saving credential file to: %s\\n\", file)\n f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n if err != nil {\n log.Fatalf(\"Unable to cache oauth token: %v\", err)\n }\n defer f.Close()\n json.NewEncoder(f).Encode(token)\n}", "func (c ThreeLeggedClient) GetToken(scope string) (*Token, error) {\n\t// In the authorize flow, user will paste a verification code back to console.\n\tcode, err := authorizeFlow(c.secret, scope, c.authorizeHandler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The verify flow takes in the verification code from authorize flow, sends a\n\t// POST request containing the code to fetch oauth token.\n\treturn verifyFlow(c.secret, scope, code)\n}", "func (src *tokenProvider) token() (string, error) {\n\ttoken, err := src.tokenSource.Token()\n\tif err != nil {\n\t\treturn \"\", errors.New(\"fcm: failed to generate Bearer token\")\n\t}\n\treturn token.AccessToken, nil\n}", "func GetToken(frob string) (*TokenRecord, error) {\n\targs := map[string]string{\n\t\t\"frob\": frob,\n\t\t\"api_key\": api.APIKey,\n\t}\n\n\tvar tokenRecord TokenRecord\n\tunmarshal := func(body []byte) error {\n\t\treturn json.Unmarshal(body, &tokenRecord)\n\t}\n\n\terr := api.GetMethod(\"rtm.auth.getToken\", args, unmarshal)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &tokenRecord, nil\n}", "func getUserToken(decryptToken string, mToken models.Token) (*oauth2.Token, error) {\n\tvar err error\n\ttoken := new(oauth2.Token)\n\ttoken.AccessToken, err = common.Decrypt([]byte(decryptToken), mToken.Access)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\ttoken.RefreshToken, err = common.Decrypt([]byte(decryptToken), mToken.Refresh)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\ttoken.TokenType, err = common.Decrypt([]byte(decryptToken), mToken.Type)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\ttimeString, err := common.Decrypt([]byte(decryptToken), mToken.Expiry)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\ttoken.Expiry, err = time.Parse(\"2006-01-02 15:04:05.0000000 -0700 MST\", timeString)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\n\treturn token, err\n}", "func (s *reloadingTokenSource) Token() (*oauth2.Token, error) {\n\treturn &oauth2.Token{\n\t\tAccessToken: string(s.getToken()),\n\t}, nil\n}", "func (s *ClientLookupTokenRetriever) GetToken(namespace, name string) (string, error) {\n\tfor i := 0; i < 30; i++ {\n\t\t// Wait on subsequent retries\n\t\tif i != 0 {\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\n\t\t// Get the service account\n\t\tserviceAccount, err := s.Client.ServiceAccounts(namespace).Get(name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the secrets\n\t\t// TODO: JTL: create one directly once we have that ability\n\t\tfor _, secretRef := range serviceAccount.Secrets {\n\t\t\tsecret, err2 := s.Client.Secrets(namespace).Get(secretRef.Name)\n\t\t\tif err2 != nil {\n\t\t\t\t// Tolerate fetch errors on a particular secret\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif IsValidServiceAccountToken(serviceAccount, secret) {\n\t\t\t\t// Return a valid token\n\t\t\t\treturn string(secret.Data[kapi.ServiceAccountTokenKey]), nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"Could not get token for %s/%s\", namespace, name)\n}" ]
[ "0.82035756", "0.8169969", "0.8149797", "0.8149797", "0.8149797", "0.7902627", "0.7876369", "0.78476423", "0.78393304", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7832817", "0.7819348", "0.7819348", "0.7819348", "0.7819348", "0.7811667", "0.78050846", "0.77936524", "0.7742203", "0.7520251", "0.751417", "0.7512271", "0.7493346", "0.7489419", "0.7487022", "0.73657465", "0.7241538", "0.7187277", "0.7186326", "0.718485", "0.7158501", "0.7149525", "0.70870906", "0.70501786", "0.6956221", "0.6936012", "0.6881657", "0.6817406", "0.671079", "0.6704595", "0.66373485", "0.66187733", "0.6495374", "0.6445545", "0.64417005", "0.64027613", "0.63909334", "0.63611346", "0.6306097", "0.6298412", "0.62195235", "0.61574006", "0.6087902", "0.6054928", "0.6041971", "0.5995364", "0.59427553", "0.59385496", "0.5912775", "0.5910178", "0.59086424", "0.588382", "0.58686006", "0.58413124", "0.58340865", "0.5809017", "0.5777758", "0.57775253", "0.5728781", "0.5702829", "0.56981635", "0.5693109", "0.56902397", "0.5674094", "0.5672207", "0.5667131", "0.5651671", "0.56422186", "0.56356543", "0.5607959", "0.5607401", "0.55937886" ]
0.78188163
31
Request a token from the web, then returns the retrieved token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token { authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) fmt.Printf("Go to the following link in your browser then type the "+ "authorization code: \n%v\n", authURL) var authCode string if _, err := fmt.Scan(&authCode); err != nil { log.Fatalf("Unable to read authorization code: %v", err) } tok, err := config.Exchange(oauth2.NoContext, authCode) if err != nil { log.Fatalf("Unable to retrieve token from web: %v", err) } return tok }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c ProwlClient) RequestToken() (*Tokens, error) {\n\tbody, err := makeHTTPRequestToURL(\n\t\t\"GET\",\n\t\tapiURL+\"/retrieve/token\",\n\t\tmap[string]string{\n\t\t\t\"providerkey\": c.ProviderKey,\n\t\t},\n\t\tnil,\n\t)\n\n\ttoken := tokenResponse{}\n\n\terr = xml.Unmarshal(body, &token)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &token.Retrieve, err\n}", "func GetToken(client *http.Client, urlString string) (string, error) {\n\treq, _ := http.NewRequest(\"GET\", urlString, nil)\n\tres, err := client.Do(req)\n\tdefer func() {\n\t\tif res.Body != nil {\n\t\t\tres.Body.Close()\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn parseToken(res)\n}", "func GetToken(c *gin.Context) {\n\tcode = c.Query(\"code\")\n\t//fmt.Println(\"code: \" + code)\n\tTokenRequest(code, c)\n}", "func requestToken(client *http.Client, username, password string) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", cfg.tokenRequestEndpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(username, password)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\treturn ioutil.ReadAll(resp.Body)\n}", "func (c Client) GetToken(username string, password string) (string, error) {\n\t// The SchedulesDirect token url\n\turl := fmt.Sprint(DefaultBaseURL, APIVersion, \"/token\")\n\n\t// encrypt the password\n\tsha1hexPW := encryptPassword(password)\n\n\t// TODO: Evaluate performance of this string concatenation, not that this\n\t// should run often.\n\tvar jsonStr = []byte(\n\t\t`{\"username\":\"` + username +\n\t\t\t`\", \"password\":\"` + sha1hexPW + `\"}`)\n\n\t// setup the request\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonStr))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\t// perform the POST\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close() //resp.Body.Close() will run when we're finished.\n\n\t// create a TokenResponse struct, return if err\n\tr := new(TokenResponse)\n\n\t// decode the response body into the new TokenResponse struct\n\terr = json.NewDecoder(resp.Body).Decode(r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Print some debugging output\n\t//fmt.Println(\"response Status:\", resp.Status)\n\t//fmt.Println(\"response Headers:\", resp.Header)\n\t//body, _ := ioutil.ReadAll(resp.Body)\n\t//fmt.Println(\"response Body:\", string(body))\n\n\t// return the token string\n\treturn r.Token, nil\n}", "func (a Auth0Tokener) GetToken(ctx context.Context) (string, error) {\n\treq, _ := http.NewRequest(\"POST\", a.url, strings.NewReader(a.payload))\n\treq.Header.Add(\"content-type\", \"application/json\")\n\n\tresp, err := a.doer.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed obtaining new access token: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn \"\", fmt.Errorf(\"failed obtaining new access token: status code %v\", resp.StatusCode)\n\t}\n\n\tvar tr tokenResponse\n\terr = json.NewDecoder(resp.Body).Decode(&tr)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed decoding new access token: %w\", err)\n\t}\n\n\treturn tr.AT, nil\n}", "func (c ThreeLeggedClient) GetToken(scope string) (*Token, error) {\n\t// In the authorize flow, user will paste a verification code back to console.\n\tcode, err := authorizeFlow(c.secret, scope, c.authorizeHandler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The verify flow takes in the verification code from authorize flow, sends a\n\t// POST request containing the code to fetch oauth token.\n\treturn verifyFlow(c.secret, scope, code)\n}", "func (us *ItemsUseCase) GetToken() (model.Token, *model.Error) {\n\treturn us.httpservice.CreateUrlToken()\n}", "func (a *Client) GetToken(params *GetTokenParams) (*GetTokenOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetTokenParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getToken\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/asset/tokens/{symbol}\",\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: &GetTokenReader{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.(*GetTokenOK)\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 getToken: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func GetToken(service Service, tokenType string, authToken string, authType string, verifier string, httpOrigin string) (token string, err error) {\n\trParams := map[string]string{\n\t\t\"client_id\": service[\"client_id\"],\n\t\t\"redirect_uri\": service[\"redirect_uri\"],\n\t}\n\tswitch tokenType {\n\tcase AUTHORIZE:\n\t\trParams[\"code\"] = authToken\n\t\trParams[\"grant_type\"] = AUTHORIZE\n\tcase REFRESH:\n\t\trParams[\"refresh_token\"] = authToken\n\t\trParams[\"grant_type\"] = REFRESH\n\tdefault:\n\t\terr = errors.New(\"Unknown tokType\")\n\t\treturn\n\t}\n\tswitch authType {\n\tcase SECRET:\n\t\trParams[\"client_secret\"] = service[\"client_secret\"]\n\tcase PKCE:\n\t\trParams[\"code_verifier\"] = verifier\n\tdefault:\n\t\terr = errors.New(\"Unknown authType\")\n\t\treturn\n\t}\n\tendpoint := service[\"token_endpoint\"]\n\tpostType := service[\"post_type\"]\n\tvar resp *http.Response\n\tswitch postType {\n\tcase \"json\":\n\t\tvar requestBody []byte\n\t\trequestBody, err = json.Marshal(rParams)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp, err = post(endpoint, \"application/json\", bytes.NewBuffer(requestBody), httpOrigin)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\tcase \"form\":\n\t\tvals := url.Values{}\n\t\tfor k, v := range rParams {\n\t\t\tvals.Set(k, v)\n\t\t}\n\t\tresp, err = post(endpoint, \"application/x-www-form-urlencoded\", strings.NewReader(vals.Encode()), httpOrigin)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\terr = errors.New(\"Unknown post_type\")\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\tif resp.StatusCode != 200 {\n\t\terr = errors.New(string(body))\n\t\treturn\n\t}\n\n\t//check for expires_at\n\tvar tokMap map[string]interface{}\n\tdecoder := json.NewDecoder(strings.NewReader(string(body)))\n\tdecoder.UseNumber()\n\terr = decoder.Decode(&tokMap)\n\tif err != nil {\n\t\terr = errors.New(\"token endpoint result error! decoder.Decode: \" + err.Error())\n\t\treturn\n\t}\n\texpire, exists := tokMap[\"expires_at\"]\n\tif exists {\n\t\ttoken = string(body)\n\t\treturn\n\t}\n\tvar expiresIn int64\n\texpire, exists = tokMap[\"expires_in\"]\n\tif !exists { //no expiration, so make it a year\n\t\texpiresIn = 31536000\n\t} else {\n\t\texpiresIn, err = expire.(json.Number).Int64()\n\t\tif err != nil {\n\t\t\terr = errors.New(\"expire to number! json.Marshal: \" + err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\ttokMap[\"expires_at\"] = epochSeconds() + expiresIn - DELTASECS\n\tb, err := json.Marshal(tokMap)\n\tif err != nil {\n\t\terr = errors.New(\"json.Marshal: \" + err.Error())\n\t\treturn\n\t}\n\ttoken = string(b)\n\treturn\n}", "func GetToken(w http.ResponseWriter, r *http.Request) {\n\tbytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"GetToken failed with error: %v\", err)\n\t}\n\tvar t map[string]string\n\n\terr = json.Unmarshal(bytes, &t)\n\tif err != nil {\n\t\tlog.Errorf(\"unmarshal failed with error: %v\", err)\n\t}\n\tlog.Infof(\"map %v\", t)\n\n\tsecurityCode := t[\"code\"]\n\taccessToken := t[\"accessToken\"]\n\n\tlog.Infof(\"securityCode %s\", securityCode)\n\tlog.Infof(\"acessToken %s\", accessToken)\n\n\tif securityCode != \"\" {\n\t\t//getToken\n\t\ttoken, err := server.GetToken(securityCode)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"GetToken failed with error: %v\", err)\n\t\t\tReturnHTTPError(w, r, http.StatusInternalServerError, fmt.Sprintf(\"Error getting the token: %v\", err))\n\t\t} else {\n\t\t\tjson.NewEncoder(w).Encode(token)\n\t\t}\n\t} else if accessToken != \"\" {\n\t\t//getToken\n\t\ttoken, err := server.RefreshToken(accessToken)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"GetToken failed with error: %v\", err)\n\t\t\tReturnHTTPError(w, r, http.StatusInternalServerError, fmt.Sprintf(\"Error getting the token: %v\", err))\n\t\t} else {\n\t\t\tjson.NewEncoder(w).Encode(token)\n\t\t}\n\t} else {\n\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad Request, Please check the request content\")\n\t}\n}", "func (c TwoLeggedClient) GetToken(scope string) (*Token, error) {\n\t// Read the private key in service account secret.\n\tpemBytes := []byte(toString(c.secret[\"private_key\"]))\n\tblock, _ := pem.Decode(pemBytes)\n\tif block == nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read private key pem block.\")\n\t}\n\n\t// Ignore error, handle the error case below.\n\tpkcs8key, err := x509.ParsePKCS8PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a pkeyInterface object containing the private key. The\n\t// pkeyInterface object has a sign function to sign a hash.\n\tpkey, ok := pkcs8key.(pkeyInterface)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Failed to parse private key.\")\n\t}\n\n\t// Get the JWT token\n\tjwt, err := createJWT(c.secret, scope, pkey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Construct the POST request to fetch the OAuth token.\n\tparams := url.Values{\n\t\t\"assertion\": []string{jwt},\n\t\t\"grant_type\": []string{jwtBearerUrn},\n\t}\n\n\t// Send the POST request and return token.\n\treturn retrieveAccessToken(toString(c.secret[\"token_uri\"]), params)\n}", "func (c *Client) GetToken(username, siteID, clientIP string) (string, error) {\n\tform := url.Values{}\n\tform.Add(\"username\", username)\n\tif siteID != \"\" {\n\t\tform.Add(\"target_site\", siteID)\n\t}\n\tif clientIP != \"\" {\n\t\tform.Add(\"client_ip\", clientIP)\n\t}\n\tresp, err := c.HTTPClient.PostForm(c.BaseURL+\"/trusted\", form)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tticket, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(ticket), nil\n}", "func (tp *singleUseTokenProvider) GetToken(uri string) (*auth.Token, error) {\n\treturn (*auth.Token)(tp), nil\n}", "func GetTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func (tm *IAMTokenManager) requestToken() (*IAMTokenInfo, error) {\n\tbuilder := NewRequestBuilder(POST).\n\t\tConstructHTTPURL(tm.iamURL, nil, nil)\n\n\tbuilder.AddHeader(CONTENT_TYPE, DEFAULT_CONTENT_TYPE).\n\t\tAddHeader(Accept, APPLICATION_JSON)\n\n\tbuilder.AddFormData(\"grant_type\", \"\", \"\", REQUEST_TOKEN_GRANT_TYPE).\n\t\tAddFormData(\"apikey\", \"\", \"\", tm.iamAPIkey).\n\t\tAddFormData(\"response_type\", \"\", \"\", REQUEST_TOKEN_RESPONSE_TYPE)\n\n\treq, err := builder.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(tm.iamClientId, tm.iamClientSecret)\n\n\tresp, err := tm.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\tif resp != nil {\n\t\t\tbuff := new(bytes.Buffer)\n\t\t\tbuff.ReadFrom(resp.Body)\n\t\t\treturn nil, fmt.Errorf(buff.String())\n\t\t}\n\t}\n\n\ttokenInfo := IAMTokenInfo{}\n\tjson.NewDecoder(resp.Body).Decode(&tokenInfo)\n\tdefer resp.Body.Close()\n\treturn &tokenInfo, nil\n}", "func (a *Authenticator) requestNewToken() (jwt.Token, error) {\n\trestRequest, err := a.getAuthRequest()\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error during auth request creation: %w\", err)\n\t}\n\n\tgetMethod := rest.PostMethod\n\n\thttpRequest, err := restRequest.GetHTTPRequest(a.BasePath, getMethod.Method)\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error constructing token http request: %w\", err)\n\t}\n\tbodyToSign, err := restRequest.GetJSONBody()\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error marshalling token request: %w\", err)\n\t}\n\tsignature, err := signWithKey(bodyToSign, a.PrivateKeyBody)\n\tif err != nil {\n\t\treturn jwt.Token{}, err\n\t}\n\thttpRequest.Header.Add(signatureHeader, signature)\n\n\thttpResponse, err := a.HTTPClient.Do(httpRequest)\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error requesting token: %w\", err)\n\t}\n\n\tdefer httpResponse.Body.Close()\n\n\t// read entire response body\n\tb, err := ioutil.ReadAll(httpResponse.Body)\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error requesting token: %w\", err)\n\t}\n\n\trestResponse := rest.Response{\n\t\tBody: b,\n\t\tStatusCode: httpResponse.StatusCode,\n\t\tMethod: getMethod,\n\t}\n\n\tvar tokenToReturn tokenResponse\n\terr = restResponse.ParseResponse(&tokenToReturn)\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error requesting token: %w\", err)\n\t}\n\n\treturn jwt.New(tokenToReturn.Token)\n}", "func GetToken(frob string) *methods.Method {\n\tname := \"rtm.auth.getToken\"\n\n\tp := url.Values{}\n\tp.Add(\"method\", name)\n\tp.Add(\"frob\", frob)\n\t\n\treturn &methods.Method{Name: name, Params: p}\n}", "func getTokenFromWeb(c *oauth2.Config) *oauth2.Token {\n\tauthURL := c.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := c.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tconfig.RedirectURL = fmt.Sprintf(\"http://127.0.0.1:%v\", options.loopbackPort)\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\t// Setup channel to receive code and start up loopback server to receive it\n\tauthCodeChan = make(chan string)\n\tserver, err := startLoopbackServer()\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to start loopback server: %v\", err)\n\t}\n\tdefer server.Shutdown(context.Background())\n\n\tauthCode := <-authCodeChan\n\ttok, err := config.Exchange(oauth2.NoContext, authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func GetToken(w http.ResponseWriter, r *http.Request) {\n\n\tFillAnswerHeader(w)\n\tOptionsAnswer(w)\n\n\tswitch r.Method {\n\n\tcase \"POST\":\n\n\t\tlog.Println(\"POST /token\")\n\t\tvar usi UserSignIn\n\t\terr := json.NewDecoder(r.Body).Decode(&usi)\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\tvar currentUser User\n\t\tDb.Where(\"name = ?\", usi.Name).Find(&currentUser)\n\t\tif currentUser.Name == \"\" {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\tfmt.Fprintf(w, \"{\\\"message\\\":\\\"User not found\\\"}\")\n\t\t\treturn\n\t\t}\n\n\t\tif !currentUser.Enabled {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\tfmt.Fprintf(w, \"{\\\"message\\\":\\\"User is not active\\\"}\")\n\t\t\treturn\n\t\t}\n\n\t\tif comparePasswords(currentUser.Hash, []byte(usi.Password)) {\n\n\t\t\tapiTokenResponse, _ := json.Marshal(APITokenResponse(currentUser))\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tfmt.Fprintf(w, string(apiTokenResponse))\n\n\t\t\tlog.Println(\"POST /token DONE\")\n\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\tfmt.Fprintf(w, \"{\\\"message\\\":\\\"Wrong password\\\"}\")\n\t\t\treturn\n\t\t}\n\n\tdefault:\n\t\tfmt.Fprintf(w, \"Sorry, only POST method are supported.\")\n\t}\n\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Open the following link in your browser: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tfmt.Printf(\"Enter Auth Code: \")\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n authURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n fmt.Printf(\"Go to the following link in your browser then type the \"+\n \"authorization code: \\n%v\\n\", authURL)\n\n var authCode string\n if _, err := fmt.Scan(&authCode); err != nil {\n log.Fatalf(\"Unable to read authorization code: %v\", err)\n }\n\n tok, err := config.Exchange(context.TODO(), authCode)\n if err != nil {\n log.Fatalf(\"Unable to retrieve token from web: %v\", err)\n }\n return tok\n}", "func (c *Client) obtainToken(auth *loginResult) error {\n\treq, err := http.NewRequest(\"GET\", c.baseURL+\"/settings\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.AddCookie(&http.Cookie{\n\t\tName: cookieNameSwicus,\n\t\tValue: auth.Swicus,\n\t})\n\treq.AddCookie(&http.Cookie{\n\t\tName: cookieNameSwiSettings,\n\t\tValue: c.swiSettings,\n\t})\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"visit callback URL failed, status %d\", resp.StatusCode)\n\t}\n\tdoc, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif token, err := extractCSRFToken(doc); err != nil {\n\t\treturn err\n\t} else {\n\t\tc.csrfToken = token\n\t}\n\treturn nil\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n authURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n fmt.Printf(\"Go to the following link in your browser then type the \"+\n \"authorization code: \\n%v\\n\", authURL)\n\n var code string\n if _, err := fmt.Scan(&code); err != nil {\n log.Fatalf(\"Unable to read authorization code %v\", err)\n }\n\n tok, err := config.Exchange(oauth2.NoContext, code)\n if err != nil {\n log.Fatalf(\"Unable to retrieve token from web %v\", err)\n }\n return tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n authURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n fmt.Printf(\"Go to the following link in your browser then type the \"+\n \"authorization code: \\n%v\\n\", authURL)\n\n var code string\n if _, err := fmt.Scan(&code); err != nil {\n log.Fatalf(\"Unable to read authorization code %v\", err)\n }\n\n tok, err := config.Exchange(oauth2.NoContext, code)\n if err != nil {\n log.Fatalf(\"Unable to retrieve token from web %v\", err)\n }\n return tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n authURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n fmt.Printf(\"Go to the following link in your browser then type the \"+\n \"authorization code: \\n%v\\n\", authURL)\n\n var code string\n if _, err := fmt.Scan(&code); err != nil {\n log.Fatalf(\"Unable to read authorization code %v\", err)\n }\n\n tok, err := config.Exchange(oauth2.NoContext, code)\n if err != nil {\n log.Fatalf(\"Unable to retrieve token from web %v\", err)\n }\n return tok\n}", "func tokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tlog.Printf(\"Go to the following link in your browser then type the authorization code: \\n%v\\n\", authURL)\n\n\tvar code string\n\tif _, err := fmt.Scan(&code); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code %v\", err)\n\t}\n\n\ttok, err := config.Exchange(oauth2.NoContext, code)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"HOLDING: Cannot find token - Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(oauth2.NoContext, authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n authURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n fmt.Printf(\"Go to the following link in your browser then type the \"+\n \"authorization code: \\n%v\\n\", authURL)\n\n var authCode string\n if _, err := fmt.Scan(&authCode); err != nil {\n log.Fatalf(\"Unable to read authorization code: %v\", err)\n }\n\n tok, err := config.Exchange(context.TODO(), authCode)\n if err != nil {\n log.Fatalf(\"Unable to retrieve token from web: %v\", err)\n }\n return tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\\nPlease enter code: \", authURL)\n\n\tvar code string\n\tif _, err := fmt.Scan(&code); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code %v\", err)\n\t}\n\n\ttok, err := config.Exchange(oauth2.NoContext, code)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser, follow the instructions, then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(oauth2.NoContext, authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar code string\n\tif _, err := fmt.Scan(&code); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code %v\", err)\n\t}\n\n\ttok, err := config.Exchange(oauth2.NoContext, code)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar code string\n\tif _, err := fmt.Scan(&code); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code %v\", err)\n\t}\n\n\ttok, err := config.Exchange(oauth2.NoContext, code)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(ctx context.Context, config *oauth2.Config) (*oauth2.Token, error) {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\treturn nil, fmt.Errorf(\"fmt.Scan: %w\", err)\n\t}\n\n\ttok, err := config.Exchange(ctx, authCode)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"config.Exchange: %w\", err)\n\t}\n\treturn tok, nil\n}", "func getTokenFromWeb(config *oauth2.Config) (*oauth2.Token, error) {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\t_, err := fmt.Scan(&authCode)\n\tif err != nil {\n\t\treturn nil, utils.NewError(ErrUserAuthCodeError, err)\n\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\treturn nil, utils.NewError(ErrAuthWebCode, err)\n\n\t}\n\treturn tok, nil\n}", "func requestNewToken(config *oauth2.Config) (*oauth2.Token, error) {\n\t// get authorization code\n\tlog.Printf(\"Enter auth code from: \\n%v\\n\", config.AuthCodeURL(stateToken, oauth2.AccessTypeOffline))\n\tvar auth string\n\t_, err := fmt.Scan(&auth)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to scan auth code: \" + err.Error())\n\t}\n\n\t// get new token using auth code, passing empty context (same as TODO())\n\ttoken, err := config.Exchange(oauth2.NoContext, auth)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get token: \" + err.Error())\n\t}\n\treturn token, nil\n}", "func (c Client) OAuthRequestTokenGet(input OAuthRequestTokenInput) (OAuthRequestTokenOutput, error) {\n\turi := \"https://api.twitter.com/oauth/request_token\"\n\tparams := processParams(input)\n\n\tres, err := c.executeRequest(http.MethodPost, uri, params)\n\tif err != nil {\n\t\treturn OAuthRequestTokenOutput{}, err\n\t}\n\tdefer res.Body.Close()\n\n\tvalues, err := bodyToValues(res.Body)\n\tif err != nil {\n\t\treturn OAuthRequestTokenOutput{}, err\n\t}\n\n\tvar output = OAuthRequestTokenOutput{}\n\tvar decoder = schema.NewDecoder()\n\terr = decoder.Decode(&output, values)\n\n\treturn output, nil\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthUrl := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Please visit this URL to authenticate: \\n%v\\n\", authUrl)\n\n\tfmt.Print(\"Code: \")\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Println(\"Failed to read code:\", err)\n\t\treturn nil\n\t}\n\n\ttoken, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Println(\"Failed to exchange OAuth token:\", err)\n\t\treturn nil\n\t}\n\treturn token\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func (a *AuthClient) GetTokenFromWeb() *oauth2.Token {\n\tauthURL := a.config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\nAuth Code: \", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\ta.logger.Fatal(\"Unable to read authorization code\", zap.Error(err))\n\t}\n\n\ttok, err := a.config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\ta.logger.Fatal(\"Unable to retrieve token from web\", zap.Error(err))\n\t}\n\n\ta.saveToken(tok)\n\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link and type the authorization code: \\n%v\\n\",\n\t\tauthURL)\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\\n\", err)\n\t}\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func GetToken(w http.ResponseWriter, r *http.Request) (string, error) {\n\n\tcookie, err := r.Cookie(\"token\")\n\tif err != nil {\n\t\tif err == http.ErrNoCookie {\n\t\t\t// If there is no cookie in the request the client is not authorized to proceed\n\t\t\tMakeErrorResponse(w, http.StatusUnauthorized, \"No token provided\")\n\t\t\tlog.Println(\"No token provided\")\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// Any other error occurring during the cookie read results in a Bad request error\n\t\tMakeErrorResponse(w, http.StatusBadRequest, \"Bad request\")\n\t\tlog.Println(\"Bad request\")\n\t\treturn \"\", err\n\t}\n\n\treturn cookie.Value, nil\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser, follow the instructions, then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tvar tok *oauth2.Token\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar err error\n\tvar code string\n\tif _, err = fmt.Scan(&code); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code %v\", err)\n\t}\n\n\tif tok, err = config.Exchange(oauth2.NoContext, code); err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web %v\", err)\n\t}\n\treturn tok\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\r\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\r\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\r\n\t\t\"authorization code: \\n%v\\n\", authURL)\r\n\r\n\tvar authCode string\r\n\tif _, err := fmt.Scan(&authCode); err != nil {\r\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\r\n\t}\r\n\r\n\ttok, err := config.Exchange(context.TODO(), authCode)\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\r\n\t}\r\n\treturn tok\r\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-Token_path\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.Background(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve Token_path from web: %v\", err)\n\t}\n\treturn tok\n}", "func GetLoginToken(rancherURI string) (client.Token, error) {\n\ttoken := client.Token{}\n\t// Generate a private key, to encrypt/decrypt the authKey token\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\tpublicKey := privateKey.PublicKey\n\tmarshalKey, err := json.Marshal(publicKey)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\tencodedKey := base64.StdEncoding.EncodeToString(marshalKey)\n\tid, err := generateKey()\n\tif err != nil {\n\t\treturn token, err\n\t}\n\t// Set response type to json\n\tresponseType := \"json\"\n\ttokenURL := fmt.Sprintf(authTokenURL, rancherURI, id)\n\treq, err := http.NewRequest(http.MethodGet, tokenURL, bytes.NewBuffer(nil))\n\tif err != nil {\n\t\treturn token, err\n\t}\n\treq.Header.Set(\"content-type\", \"application/json\")\n\treq.Header.Set(\"accept\", \"application/json\")\n\n\t// Don´t verify certificates\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t}\n\n\tclient := &http.Client{Transport: tr, Timeout: 300 * time.Second}\n\n\tloginRequest := fmt.Sprintf(\"%s/login?requestId=%s&publicKey=%s&responseType=%s\",\n\t\trancherURI, id, encodedKey, responseType)\n\n\tfmt.Printf(\"\\nOpening browser for login to: %s \\n\", rancherURI)\n\topenbrowser(loginRequest)\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt)\n\n\t// Timeout for user to login and get token\n\ttimeout := time.NewTicker(15 * time.Minute)\n\tdefer timeout.Stop()\n\n\tpoll := time.NewTicker(10 * time.Second)\n\tdefer poll.Stop()\n\n\t// Loop until we get the token\n\tfor {\n\t\tselect {\n\t\tcase <-poll.C:\n\t\t\tres, err := client.Do(req)\n\t\t\tif err != nil {\n\t\t\t\treturn token, err\n\t\t\t}\n\t\t\tcontent, err := ioutil.ReadAll(res.Body)\n\t\t\tif err != nil {\n\t\t\t\tres.Body.Close()\n\t\t\t\treturn token, err\n\t\t\t}\n\t\t\tres.Body.Close()\n\t\t\terr = json.Unmarshal(content, &token)\n\t\t\tif err != nil {\n\t\t\t\treturn token, err\n\t\t\t}\n\t\t\tif token.Token == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdecoded, err := base64.StdEncoding.DecodeString(token.Token)\n\t\t\tif err != nil {\n\t\t\t\treturn token, err\n\t\t\t}\n\t\t\tdecryptedBytes, err := privateKey.Decrypt(nil, decoded, &rsa.OAEPOptions{Hash: crypto.SHA256})\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\ttoken.Token = string(decryptedBytes)\n\t\t\t// delete token\n\t\t\treq, err = http.NewRequest(http.MethodDelete, tokenURL, bytes.NewBuffer(nil))\n\t\t\tif err != nil {\n\t\t\t\treturn token, err\n\t\t\t}\n\t\t\treq.Header.Set(\"content-type\", \"application/json\")\n\t\t\treq.Header.Set(\"accept\", \"application/json\")\n\t\t\ttr := &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t},\n\t\t\t}\n\t\t\tclient = &http.Client{Transport: tr, Timeout: 150 * time.Second}\n\t\t\tres, err = client.Do(req)\n\t\t\tif err != nil {\n\t\t\t\t// log error and use the token if login succeeds\n\t\t\t\tfmt.Printf(\"DeleteToken: %v\", err)\n\t\t\t}\n\t\t\treturn token, nil\n\n\t\tcase <-timeout.C:\n\t\t\tbreak\n\n\t\tcase <-interrupt:\n\t\t\tfmt.Printf(\"received interrupt\\n\")\n\t\t\tbreak\n\t\t}\n\n\t\treturn token, nil\n\t}\n}", "func GetToken(client TokenAuthHandler) (err error) {\n\tvar token string\n\n\tif tokenFile := os.Getenv(\"VAULT_TOKEN_FILE\"); tokenFile != \"\" {\n\t\ttoken, err = GetTokenFromFile(tokenFile)\n\t}\n\n\tif err == nil && token != \"\" {\n\t\t// Reach out to the API to make sure it's good\n\t\tt, err := client.Validate(token)\n\n\t\tif err == nil && t != nil {\n\t\t\tclient.SetToken(token)\n\t\t\treturn nil\n\t\t}\n\n\t\tlog.Warn(\"Retrieved token is not valid, falling back\")\n\t}\n\n\tif err != nil {\n\t\tlog.Warn(err.Error())\n\t}\n\n\t// Fall back to logging in with user/pass creds\n\ttoken, err = GetTokenWithLogin(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.SetToken(token)\n\treturn nil\n}", "func TokenGET(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\ttoken, err := jwt.GetToken(r)\n\tif err != nil {\n\t\ts := &Status{}\n\t\ts.Unauthorized(err.Error()).Render(w)\n\t\treturn\n\t}\n\n\tclm, err := jwt.VerifyToken(token)\n\tif err != nil && err != jwt.ErrExpiredToken {\n\t\ts := &Status{}\n\t\ts.Unauthorized(err.Error()).Render(w)\n\t\treturn\n\t}\n\n\tusr, err := user.GetByID(clm.Subject)\n\tif err != nil {\n\t\thandleError(err, w)\n\t\treturn\n\t}\n\n\tif usr.Locked {\n\t\ts := &Status{}\n\t\ts.Forbidden(\"User is locked\").Render(w)\n\t\treturn\n\t}\n\n\ttoken, err = jwt.CreateToken(clm)\n\tif err != nil {\n\t\ts := &Status{}\n\t\ts.UnprocessableEntity(fmt.Sprintf(\"Creation error: %s\", err)).Render(w)\n\t\treturn\n\t}\n\n\tview.RenderJSON(Token{token}, http.StatusCreated, w)\n}", "func (s *ClientLookupTokenRetriever) GetToken(namespace, name string) (string, error) {\n\tfor i := 0; i < 30; i++ {\n\t\t// Wait on subsequent retries\n\t\tif i != 0 {\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\n\t\t// Get the service account\n\t\tserviceAccount, err := s.Client.ServiceAccounts(namespace).Get(name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the secrets\n\t\t// TODO: JTL: create one directly once we have that ability\n\t\tfor _, secretRef := range serviceAccount.Secrets {\n\t\t\tsecret, err2 := s.Client.Secrets(namespace).Get(secretRef.Name)\n\t\t\tif err2 != nil {\n\t\t\t\t// Tolerate fetch errors on a particular secret\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif IsValidServiceAccountToken(serviceAccount, secret) {\n\t\t\t\t// Return a valid token\n\t\t\t\treturn string(secret.Data[kapi.ServiceAccountTokenKey]), nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"Could not get token for %s/%s\", namespace, name)\n}", "func (s *Server) GetToken(c context.Context, req *pb.Request) (*pb.Response, error) {\n\tt, found := s.cache.Get(req.Token)\n\n\tif !found {\n\t\treturn &pb.Response{}, errors.New(\"token not found\")\n\t}\n\n\tif t != req.Token {\n\t\treturn &pb.Response{}, errors.New(\"token is not valid\")\n\t}\n\treturn &pb.Response{}, nil\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 (a *Authenticator) GetToken() (jwt.Token, error) {\n\t// If token is not set, and we have a token cache,\n\t// try to retrieve it from the token cache\n\tif a.Token.ExpiryDate == 0 && a.TokenCache != nil {\n\t\tif err := a.retrieveTokenFromCache(); err != nil {\n\t\t\treturn jwt.Token{}, err\n\t\t}\n\t}\n\n\tif a.Token.Expired() && a.PrivateKeyBody == nil {\n\t\treturn jwt.Token{}, ErrTokenExpired\n\t}\n\tif a.Token.Expired() {\n\t\tvar err error\n\t\ta.Token, err = a.requestNewToken()\n\n\t\tif err != nil {\n\t\t\treturn jwt.Token{}, err\n\t\t}\n\n\t\t// if a TokenCache is set we want to write acquired tokens to the cache\n\t\tif a.TokenCache != nil {\n\t\t\tif err = a.TokenCache.Set(a.getTokenCacheKey(), a.Token); err != nil {\n\t\t\t\treturn jwt.Token{}, fmt.Errorf(\"error writing token to cache: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn a.Token, nil\n}", "func (p *ServerGatedServiceClient) GetToken(project_id int32, key string, uid int64) (r *Token, err error) {\n\tif err = p.sendGetToken(project_id, key, uid); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetToken()\n}", "func (arb *ArbiterClient) RequestToken(href string, method string, caveat string) ([]byte, error) {\n\n\tu, err := url.Parse(href)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\thost, _, err1 := net.SplitHostPort(u.Host)\n\tif err != nil {\n\t\treturn []byte{}, err1\n\t}\n\n\trouteHash := host + strings.ToUpper(u.Path) + method + caveat\n\tarb.tokenCacheMutex.Lock()\n\ttoken, exists := arb.tokenCache[routeHash]\n\tarb.tokenCacheMutex.Unlock()\n\tif !exists {\n\t\tvar status int\n\t\tpayload := []byte(`{\"target\":\"` + host + `\",\"path\":\"` + u.Path + `\",\"method\":\"` + method + `\",\"caveats\":[` + caveat + `]}`)\n\n\t\ttoken, status = arb.makeArbiterPostRequest(\"/token\", host, u.Path, payload)\n\t\tif status != 200 {\n\t\t\terr = errors.New(strconv.Itoa(status) + \": \" + string(token))\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tarb.tokenCacheMutex.Lock()\n\t\tarb.tokenCache[routeHash] = token\n\t\tarb.tokenCacheMutex.Unlock()\n\t}\n\n\treturn token, err\n}", "func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\n\tauthURL += \"&prompt=consent\"\n\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code: %v\", err)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web: %v\", err)\n\t}\n\treturn tok\n}", "func getToken(config *oauth2.Config) *oauth2.Token {\n\t// The file token.json stores the user's access and refresh tokens, and is\n\t// created automatically when the authorization flow completes for the first\n\t// time.\n\ttokFile := \"token.json\"\n\ttok, err := tokenFromFile(tokFile)\n\tif err != nil {\n\t\ttok = getTokenFromWeb(config)\n\t\tSaveToken(tokFile, tok)\n\t\tlog.Println(\"OAuth token renewed.\")\n\t}\n\treturn tok\n}", "func (t *TokenHandler) GetToken(c echo.Context) error {\n\tuserID, err := retrieveUserID(c)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"Empty id\") {\n\t\t\treturn c.JSON(http.StatusBadRequest, echo.Map{\n\t\t\t\t\"message\": \"No id provided\",\n\t\t\t})\n\t\t}\n\t\treturn c.JSON(http.StatusBadRequest, echo.Map{\n\t\t\t\"message\": \"ID should be in UUID format\",\n\t\t})\n\t}\n\n\tAtTokenString, RtTokenString, err := t.tokenHelper.CreateToken(userID)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, echo.Map{\n\t\t\t// \"message\": \"Could not create token\",\n\t\t\t\"message\": err.Error(),\n\t\t})\n\t}\n\n\t//Encode rt to base64\n\trtsEncoded := base64.StdEncoding.EncodeToString([]byte(RtTokenString))\n\n\treturn c.JSON(http.StatusOK, echo.Map{\n\t\t\"access_token\": AtTokenString,\n\t\t\"refresh_token\": rtsEncoded,\n\t})\n}", "func (c *Client) Token(ctx context.Context, r TokenRequest) (*TokenReply, error) {\r\n\treq, err := http.NewRequestWithContext(\r\n\t\tctx,\r\n\t\thttp.MethodGet,\r\n\t\tfmt.Sprintf(\"%s/%s\", c.getTokenBaseEndpoint(r.AccountID, r.ChannelID), r.TokenID),\r\n\t\tnil,\r\n\t)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tres := TokenReply{}\r\n\tif err := c.sendRequest(req, &res); err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn &res, nil\r\n}", "func (c *MockRegistry) GetToken(username, password, org, space string, url string) (string, error) {\n\treturn c.GetTokenString, c.GetTokenError\n}", "func (c *ActionController) GetToken(ctx *app.GetTokenActionContext) error {\n\t// ActionController_GetToken: start_implement\n\n\t// Put your logic here\n\tuser, _, ok := ctx.Request.BasicAuth()\n\tif !ok {\n\t\tgoa.LogInfo(ctx, \"failed basic auth\")\n\t\treturn ctx.BadRequest(&app.GorestsecurityError{Msg: \"failed basic auth\", Code: \"001\"})\n\t}\n\t// fmt.Println(\"User: \", user)\n\ttoken := custommiddleware.GenerateJWT(user)\n\tsignedToken, err := token.SignedString(c.privateKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to sign token: %s\", err) // internal error\n\t}\n\t// Set auth header for client retrieval\n\tctx.ResponseData.Header().Set(\"Authorization\", \"Bearer \"+signedToken)\n\n\t// Send response\n\treturn ctx.NoContent()\n\t// ActionController_GetToken: end_implement\n}", "func (f *CLIAuthCodeFlow) GetToken(ctx context.Context) (*oauth2.Token, error) {\n\tf.Config.RedirectURL = \"urn:ietf:wg:oauth:2.0:oob\"\n\tstate, err := generateOAuthState()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthCodeURL := f.Config.AuthCodeURL(state)\n\tlog.Printf(\"Open %s for authorization\", authCodeURL)\n\tfmt.Print(\"Enter code: \")\n\tvar code string\n\tif _, err := fmt.Scanln(&code); err != nil {\n\t\treturn nil, err\n\t}\n\ttoken, err := f.Config.Exchange(ctx, code)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not exchange oauth code: %s\", err)\n\t}\n\treturn token, nil\n}", "func FetchToken(ctx context.Context, settings *Settings) (*Token, error) {\n\tif settings.APIKey != \"\" {\n\t\treturn nil, nil\n\t}\n\tsrc, err := newTokenSource(ctx, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tts := internal.ReuseTokenSource(nil, *src)\n\tt, err := ts.Token()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Token{*t}, nil\n}", "func (user *User) GetToken() (string, error) {\n\treturn NewJSONWebToken(user.Username, Team(user.Team), user.Admin, user.UUID)\n}", "func getGoogleTokenFromWeb(config *oauth2.Config) *oauth2.Token {\n\n\t// AuthCodeURL returns a URL to OAuth 2.0 provider's consent page\n\t// that asks for permissions for the required scopes explicitly.\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go to the following link in your browser then type the \"+\n\t\t\"authorization code: \\n%v\\n\", authURL)\n\n\tvar code string\n\tif _, err := fmt.Scan(&code); err != nil {\n\t\tlog.Fatalf(\"Unable to read authorization code %v\", err)\n\t}\n\n\t// config.Exchange converts an authorization code into a Token object.\n\ttok, err := config.Exchange(oauth2.NoContext, code)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve token from web %v\", err)\n\t}\n\treturn tok\n}", "func (k Keeper) GetToken(ctx sdk.Context, denom string) (types.TokenI, error) {\n\t// query token by symbol\n\tif token, err := k.getTokenBySymbol(ctx, denom); err == nil {\n\t\treturn &token, nil\n\t}\n\n\t// query token by min unit\n\tif token, err := k.getTokenByMinUnit(ctx, denom); err == nil {\n\t\treturn &token, nil\n\t}\n\n\treturn nil, sdkerrors.Wrapf(types.ErrTokenNotExists, \"token: %s does not exist\", denom)\n}", "func GetToken() string {\n\tif !viper.IsSet(\"cookie\") {\n\t\tlog.Fatalln(\"Cookie not found, run nm5 sc [cookie] to set cookie\")\n\t}\n\tvar token string\n\tcookie := fmt.Sprintf(\"%v=%v\", cookieName, viper.GetString(\"cookie\"))\n\n\treq, err := http.NewRequest(http.MethodGet, homePage, nil)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\treq.Header.Add(\"cookie\", cookie)\n\n\tresponse, err := http.DefaultClient.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error making get-token request, %v\\n\", err)\n\t}\n\n\tdefer response.Body.Close()\n\n\tdoc, err := goquery.NewDocumentFromReader(response.Body)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\thtml, err := doc.Html()\n\n\tif !strings.Contains(html, \"ACCESS_TOKEN\") {\n\t\tlog.Fatalln(\"Error getting token: Invalid or Expired cookie\")\n\t}\n\n\tdoc.Find(\"script\").Each(func(i int, s *goquery.Selection) {\n\t\ttagText := s.Text()\n\n\t\tif strings.Contains(tagText, \"ACCESS_TOKEN\") {\n\t\t\ttagTextArr := strings.Split(tagText, \"\\n\")\n\t\t\tfor _, line := range tagTextArr {\n\t\t\t\tif strings.Contains(line, \"ACCESS_TOKEN\") {\n\t\t\t\t\tre := regexp.MustCompile(`\\'(.*)\\'`)\n\t\t\t\t\tmatches := re.FindStringSubmatch(line)\n\t\t\t\t\ttoken = matches[1]\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\treturn token\n}", "func (t *ServiceAccountToken) Get() (*oauth2.Token, error) {\n\tt.mtx.RLock()\n\tdefer t.mtx.RUnlock()\n\treturn t.tok, nil\n}", "func Token(config *config.SubmitConfig) (string, error) {\n\ttokenbytes, err := ioutil.ReadFile(filepath.Join(pathutil.UserHomeDir(), \".paddle\", \"token_cache\"))\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"previous token not found, fetching a new one...\\n\")\n\t\t// Authenticate to the cloud endpoint\n\t\tauthJSON := map[string]string{}\n\t\tauthJSON[\"username\"] = config.ActiveConfig.Username\n\t\tauthJSON[\"password\"] = config.ActiveConfig.Password\n\t\tauthStr, _ := json.Marshal(authJSON)\n\t\tbody, err := getToken(config.ActiveConfig.Endpoint+\"/api-token-auth/\", authStr)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvar respObj interface{}\n\t\tif errJSON := json.Unmarshal(body, &respObj); errJSON != nil {\n\t\t\treturn \"\", errJSON\n\t\t}\n\t\ttokenStr := respObj.(map[string]interface{})[\"token\"].(string)\n\t\terr = ioutil.WriteFile(filepath.Join(pathutil.UserHomeDir(), \".paddle\", \"token_cache\"), []byte(tokenStr), 0600)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"write cache token file error: %v\", err)\n\t\t}\n\t\t// Ignore write token error, fetch a new one next time\n\t\treturn tokenStr, nil\n\t}\n\treturn string(tokenbytes), nil\n}", "func requestToken(user, pass, agent, public, private string) string {\n\tclient := &http.Client{}\n\tURL := \"https://www.reddit.com/api/v1/access_token\"\n\t// set values for post request body\n\tvals := url.Values{}\n\tvals.Set(\"grant_type\", \"password\")\n\tvals.Set(\"username\", user)\n\tvals.Set(\"password\", pass)\n\treq, err := http.NewRequest(\"POST\", URL, strings.NewReader(vals.Encode()))\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to create new POST request for %s\\n\", URL)\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\t// set user agent and sets Oauth tokens\n\treq.Header.Add(\"User-Agent\", agent)\n\treq.SetBasicAuth(public, private)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to get resposnse\")\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\n\ttype redditResponse struct {\n\t\tAccessToken string `json:\"access_token\"`\n\t\tTokenType string `json:\"token_type\"`\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tdefer resp.Body.Close()\n\n\tif err != nil {\n\t\tfmt.Println(\"Failed to read body\")\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\tres := redditResponse{}\n\t_ = json.Unmarshal(body, &res)\n\ttoken := res.AccessToken + \" \" + res.TokenType\n\n\treturn token\n}", "func GetToken(frob string) (*TokenRecord, error) {\n\targs := map[string]string{\n\t\t\"frob\": frob,\n\t\t\"api_key\": api.APIKey,\n\t}\n\n\tvar tokenRecord TokenRecord\n\tunmarshal := func(body []byte) error {\n\t\treturn json.Unmarshal(body, &tokenRecord)\n\t}\n\n\terr := api.GetMethod(\"rtm.auth.getToken\", args, unmarshal)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &tokenRecord, nil\n}", "func GetToken(tokenString string) *jwt.Token {\n\treturn oauth.GetToken(tokenString)\n}", "func GetToken() (string, error) {\n\tf := logrus.Fields{\n\t\t\"functionName\": \"token.GetToken\",\n\t}\n\n\t// set 2.75 hrs duration for new token\n\tif (time.Now().Unix()-expiry.Unix()) > 9900 || token == \"\" {\n\t\tlog.WithFields(f).Debug(\"token is either empty or expired, retrieving new token\")\n\t\terr := retrieveToken()\n\t\tif err != nil {\n\t\t\tlog.WithFields(f).WithError(err).Warn(\"unable to retrieve a new token\")\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn token, nil\n}", "func (a *Authenticator) GetToken(r *http.Request) (*oauth2.Token, error) {\n\tsession := a.getSession(r)\n\tif session.Token == nil {\n\t\treturn nil, ErrNotAuthenticated\n\t}\n\treturn session.Token, nil\n}", "func getToken(r *http.Request) (token string) {\n\ttoken, _, _ = r.BasicAuth()\n\treturn token\n}", "func (p *Provider) GetToken(code string) (*oauth2.Token, error) {\n\ttok, err := p.config.Exchange(oauth2.NoContext, code)\n\treturn tok, err\n}", "func (p *Provider) GetToken(code string) (*oauth2.Token, error) {\n\ttok, err := p.config.Exchange(oauth2.NoContext, code)\n\treturn tok, err\n}", "func (a *API) Token(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\tgrantType := r.FormValue(\"grant_type\")\n\n\tswitch grantType {\n\tcase \"password\":\n\t\treturn a.ResourceOwnerPasswordGrant(ctx, w, r)\n\tcase \"refresh_token\":\n\t\treturn a.RefreshTokenGrant(ctx, w, r)\n\tcase \"id_token\":\n\t\treturn a.IdTokenGrant(ctx, w, r)\n\tdefault:\n\t\treturn oauthError(\"unsupported_grant_type\", \"\")\n\t}\n}", "func TokenGet(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-type\", \"application/json;charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tvar a auth\n\n\terr = json.Unmarshal(body, &a)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t// Verify that the user exists in database\n\tuser := repositories.UserGetByUsername(a.Username)\n\n\tif user.ID == 0 {\n\t\tjson.NewEncoder(w).Encode(models.JSONError{Message: \"User Not Found\", Code: 404})\n\t} else {\n\t\tcompare := compareHashPassword(user.Password, a.Password)\n\t\tif compare {\n\t\t\tjwtToken := jwt.New(jwt.SigningMethodHS256)\n\t\t\tclaims := jwtToken.Claims.(jwt.MapClaims)\n\n\t\t\tclaims[\"username\"] = user.Username\n\t\t\tclaims[\"role\"] = user.RoleID\n\t\t\tclaims[\"exp\"] = time.Now().Add(time.Hour * 24).Unix()\n\n\t\t\ttokenString, errSign := jwtToken.SignedString(JwtSalt)\n\t\t\tif errSign != nil {\n\t\t\t\tlog.Info(err)\n\t\t\t}\n\t\t\tjson.NewEncoder(w).Encode(token{Token: tokenString})\n\t\t} else {\n\t\t\tjson.NewEncoder(w).Encode(models.JSONError{Message: \"Your login / Password is wrong\", Code: 403})\n\t\t}\n\t}\n}", "func (s *SessHelper) GetToken(appid, uuid string) (string, error) {\n\treturn \"\", nil\n}", "func (c *Client) Token(ctx context.Context, opts *tokenOptions) (*logical.Response, error) {\n\t// Marshal a request body only if there are any user-specified GitHub App\n\t// token constraints.\n\tvar body io.ReadWriter\n\tif opts != nil {\n\t\tbody = new(bytes.Buffer)\n\t\tif err := json.NewEncoder(body).Encode(opts); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Build the token request.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url.String(), body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %v\", errUnableToBuildAccessTokenReq, err)\n\t}\n\n\treq.Header.Set(\"User-Agent\", projectName)\n\n\tif body != nil {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\t// Perform the request, re-using the shared transport.\n\tres, err := c.transport.RoundTrip(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: RoundTrip error: %v\", errUnableToCreateAccessToken, err)\n\t}\n\n\tdefer res.Body.Close()\n\n\tif statusCode(res.StatusCode).Unsuccessful() {\n\t\tbodyBytes, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: %s: error reading error response body: %v\",\n\t\t\t\terrUnableToCreateAccessToken, res.Status, err)\n\t\t}\n\n\t\tbodyErr := fmt.Errorf(\"%w: %v\", errBody, string(bodyBytes))\n\n\t\treturn nil, fmt.Errorf(\"%w: %s: %v\", errUnableToCreateAccessToken,\n\t\t\tres.Status, bodyErr)\n\t}\n\n\tvar resData map[string]interface{}\n\tif err := json.NewDecoder(res.Body).Decode(&resData); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %v\", errUnableToDecodeAccessTokenRes, err)\n\t}\n\n\ttokenRes := &logical.Response{Data: resData}\n\n\t// As per the issue request in https://git.io/JUhRk, return a Vault \"lease\"\n\t// aligned to the GitHub token's `expires_at` field.\n\tif expiresAt, ok := resData[\"expires_at\"]; ok {\n\t\tif expiresAtStr, ok := expiresAt.(string); ok {\n\t\t\tif expiresAtTime, err := time.Parse(time.RFC3339, expiresAtStr); err == nil {\n\t\t\t\ttokenRes.Secret = &logical.Secret{\n\t\t\t\t\tInternalData: map[string]interface{}{\"secret_type\": backendSecretType},\n\t\t\t\t\tLeaseOptions: logical.LeaseOptions{\n\t\t\t\t\t\tTTL: time.Until(expiresAtTime),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tokenRes, nil\n}", "func GetToken(w http.ResponseWriter, r *http.Request) {\r\n\tfmt.Println()\r\n\tlog.Println(\"*** GetToken(),请求参数\", r)\r\n\r\n\tif err := r.ParseForm(); err != nil {\r\n log.Println(err)\r\n\t}\r\n\t\t\r\n\tvar response AppResponse\r\n\t \r\n\tinstance := GetTokenInstance()\t\t\t\r\n\r\n\tif IsEmpty(instance.AccessToken) {\t\t\r\n\t\tresponse.Rel = false\r\n\t\tresponse.Msg = \"get access_token fail\"\t\t\t\r\n\t} else {\t\t\r\n\t\tresponse.Rel = true\r\n\t\tresponse.Result.AccessToken = instance.AccessToken\t\r\n\t}\r\n\tlog.Println(\"*** 返回结果:\", response, instance.AccessToken)\t\t\r\n\tfmt.Println()\r\n\tjson.NewEncoder(w).Encode(response) \r\n}", "func (a API) GetToken() (t string) {\r\n\treturn a.access_token\r\n}", "func (c *Cache) requestToken(req *http.Request) (string, error) {\n\tauthorization := req.Header.Get(\"Authorization\")\n\tif authorization == \"\" {\n\t\treturn \"\", failure.New(\"request contains no authorization header\")\n\t}\n\tfields := strings.Fields(authorization)\n\tif len(fields) != 2 || fields[0] != \"Bearer\" {\n\t\treturn \"\", failure.New(\"invalid authorization header: %q\", authorization)\n\t}\n\treturn fields[1], nil\n}", "func (tp *TokenProvider) GetToken(uri string) (*auth.Token, error) {\n\ttoken, _, err := tp.getTokenImpl(uri)\n\treturn token, err\n}", "func getToken(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\n\tsymbol := chi.URLParam(r, \"address\")\n\tret, err := db.GetToken(ctx, symbol)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgotils.WriteObject(w, http.StatusOK, map[string]interface{}{\n\t\t\"token\": ret,\n\t})\n\treturn nil\n}", "func (ts *apiTokenSource) Token() (*oauth2.Token, error) {\n\tts.m.Lock()\n\tdefer ts.m.Unlock()\n\tif ts.token.Valid() {\n\t\treturn ts.token, nil\n\t}\n\n\tresp, err := ts.requestToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := ts.treatResponseBody(resp.Body); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ts.token, nil\n}", "func (ap *oauth2ClientCredentialsAuthPlugin) requestToken() (*oauth2Token, error) {\n\tbody := url.Values{\"grant_type\": []string{\"client_credentials\"}}\n\tif len(*ap.Scopes) > 0 {\n\t\tbody[\"scope\"] = []string{strings.Join(*ap.Scopes, \" \")}\n\t}\n\n\tr, err := http.NewRequest(\"POST\", ap.TokenURL, strings.NewReader(body.Encode()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tr.SetBasicAuth(ap.ClientID, ap.ClientSecret)\n\n\tclient := defaultRoundTripperClient(&tls.Config{InsecureSkipVerify: ap.tlsSkipVerify}, 10)\n\tresponse, err := client.Do(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbodyRaw, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif response.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"error in response from OAuth2 token endpoint: %v\", string(bodyRaw))\n\t}\n\n\tvar tokenResponse tokenEndpointResponse\n\terr = json.Unmarshal(bodyRaw, &tokenResponse)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif strings.ToLower(tokenResponse.TokenType) != \"bearer\" {\n\t\treturn nil, errors.New(\"unknown token type returned from token endpoint\")\n\t}\n\n\treturn &oauth2Token{\n\t\tToken: strings.TrimSpace(tokenResponse.AccessToken),\n\t\tExpiresAt: time.Now().Add(time.Duration(tokenResponse.ExpiresIn) * time.Second),\n\t}, nil\n}", "func GetToken() (token types.OaToken, err error) {\n\tconfigures := config.Conf\n\tlog = logging.GetLogger(configures.Log.Level)\n\toaConf := configures.OA\n\toaUrl := oaConf.OaUrl\n\toaTokenApi := oaConf.TokenApi\n\toaClient := oaConf.OaClient\n\toaSecret := oaConf.OaSecret\n\n\t\tqueryUrl := fmt.Sprintf(\"%s%s?client=%s&secret=%s\", oaUrl, oaTokenApi, oaClient, oaSecret)\n\t\tlog.Debugf(\"Debug oa tokens api url:%s\", queryUrl)\n\n\t\tresp, err := http.Get(queryUrl)\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"query oa token api error!%s\", err)\n\t\t\treturn \"\", err\n\t\t}\n\t\tres, err := bodyResolve(resp)\n\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t}\n\t\tlog.Debugf(\"Debug oa token api returned:%d\", res.Code)\n\t\tcode := res.Code\n\t\tif code != consts.OAOkCode {\n\t\t\tlog.Fatalf(\"Getting token error!%s\", res.Message)\n\t\t\treturn \"\", errors.New(res.Message)\n\t\t}\n\t\t//logging.Printf(\"Debug oa tokens api return:%d, %s\", code, data.Token)\n\t\ttoken = res.Data.Token\n\t\tlog.Debugf(\"Debug oa token:%s\", token)\n\t\treturn token, nil\n\n}" ]
[ "0.72204053", "0.7070667", "0.70199656", "0.6922571", "0.6916076", "0.67902523", "0.67825055", "0.6761922", "0.6761285", "0.6712056", "0.67068917", "0.67068774", "0.66799116", "0.6648291", "0.66390216", "0.65898794", "0.6586725", "0.6575673", "0.6575005", "0.6569359", "0.6566772", "0.6550741", "0.65397865", "0.65350634", "0.65303457", "0.65303457", "0.65303457", "0.65264875", "0.6506091", "0.64861166", "0.6481266", "0.6464036", "0.64609456", "0.64609456", "0.64595616", "0.6457456", "0.64570725", "0.6455078", "0.64518756", "0.6450461", "0.6450461", "0.6450461", "0.6450461", "0.6450461", "0.6450461", "0.6450461", "0.6450461", "0.6450461", "0.6447327", "0.6444802", "0.64359224", "0.64333713", "0.64318264", "0.6424004", "0.64234895", "0.64122665", "0.6388864", "0.63878834", "0.63876027", "0.6385306", "0.63773096", "0.63772297", "0.63771623", "0.6369241", "0.63560176", "0.63557994", "0.6352785", "0.634574", "0.6318541", "0.6316278", "0.6311384", "0.6308899", "0.6280565", "0.62687993", "0.62679553", "0.62614286", "0.6253261", "0.6240823", "0.62285435", "0.62154204", "0.62013257", "0.6195362", "0.61945915", "0.6167215", "0.6152962", "0.6152962", "0.6148244", "0.61400366", "0.6134779", "0.6110853", "0.61087906", "0.610572", "0.6105321", "0.6093036", "0.6085072", "0.6076354", "0.6074072", "0.60673153" ]
0.64674515
33
Saves a token to a file path.
func saveToken(path string, token *oauth2.Token) { fmt.Printf("Saving credential file to: %s\n", path) f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) defer f.Close() if err != nil { log.Fatalf("Unable to cache oauth token: %v", err) } json.NewEncoder(f).Encode(token) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func saveToken(absPath string, token *oauth2.Token) error {\n\tf, err := os.OpenFile(absPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"open token file %s for write: %w\", absPath, err)\n\t}\n\n\terr = json.NewEncoder(f).Encode(token)\n\tif err != nil {\n\t\terr = xerrors.Errorf(\"write token to %s: %w\", absPath, err)\n\t}\n\n\tif err := f.Close(); err != nil {\n\t\terr = xerrors.Errorf(\"close token file %s after write: %v\", absPath, err)\n\t}\n\n\treturn err\n}", "func (ts *FileTokenStorage) Save(token Token) error {\n\tencodedToken := base64.StdEncoding.EncodeToString([]byte(token.tokenString))\n\tts.token = encodedToken\n\treturn ioutil.WriteFile(ts.tokenFileName, []byte(encodedToken), 0644)\n}", "func saveToken(path string, token *oauth2.Token) error {\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"os.OpenFile: %w\", err)\n\t}\n\tdefer f.Close()\n\treturn json.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tdefer f.Close()\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth Token_path: %v\", err)\n\t}\n\tjson.NewEncoder(f).Encode(token)\n}", "func SaveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func SaveToken(token string, tokenPath string) error {\n\t// Get user home directory\n\tuserHome, err := util.GetUserHomeDir()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"ACL error. %s\", err)\n\t}\n\n\t// Check if .cybr directory already exists, create if not\n\tif _, err = os.Stat(userHome + \"/.cybr\"); os.IsNotExist(err) {\n\t\t// Create .cybr folder in user home directory\n\t\terr = os.Mkdir(userHome+\"/.cybr\", 0766)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not create folder %s/.cybr on local file system. %s\", userHome, err)\n\t\t}\n\t}\n\n\t// Check for config file and remove if existing\n\tif _, err = os.Stat(userHome + tokenPath); !os.IsNotExist(err) {\n\t\terr = os.Remove(userHome + tokenPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not remove existing %s%s file. %s\", userHome, tokenPath, err)\n\t\t}\n\t}\n\t// Create config file in user home directory\n\tdataFile, err := os.Create(userHome + tokenPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create configuration file at %s%s. %s\", userHome, tokenPath, err)\n\t}\n\n\t// serialize the data\n\tdataEncoder := gob.NewEncoder(dataFile)\n\tdataEncoder.Encode(token)\n\n\tdataFile.Close()\n\n\treturn nil\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tdefer f.Close()\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache OAuth token: %v\", err)\n\t}\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tdefer f.Close()\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache OAuth token: %v\", err)\n\t}\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(file string, token *oauth2.Token) error {\n\tif exists(file) {\n\t\treturn nil\n\t}\n\tlog.Infof(\"Saving credential file to: %s\\n\", file)\n\ttokenJSON, err := json.Marshal(token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to marshal token into json: %v\", err)\n\t}\n\treturn ioutil.WriteFile(file, tokenJSON, 0644)\n}", "func saveToken(path string, token *oauth2.Token) error {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn utils.NewError(ErrCacheOauth, err)\n\t}\n\tdefer f.Close()\n\terr = json.NewEncoder(f).Encode(token)\n\n\treturn err\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tif err := json.NewEncoder(f).Encode(token); err != nil {\n\t\tlog.Fatalf(\"Encoding issue: %v\", err)\n\t}\n}", "func saveAuthToken(token, tokenPath string) error {\n\treturn ioutil.WriteFile(tokenPath, []byte(token), 0600)\n}", "func saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\t_ = json.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\r\n\tfmt.Printf(\"Saving credential file to: %s\\n\", path)\r\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\r\n\t}\r\n\tdefer f.Close()\r\n\tjson.NewEncoder(f).Encode(token)\r\n}", "func TokenSave(fileName string) {\n\tjsonTokens, err := json.Marshal(tokens)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(fileName, jsonTokens, os.ModePerm)\n}", "func saveToken(path string, token *oauth2.Token) {\n fmt.Printf(\"Saving credential file to: %s\\n\", path)\n f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n if err != nil {\n log.Fatalf(\"Unable to cache oauth token: %v\", err)\n }\n defer f.Close()\n json.NewEncoder(f).Encode(token)\n}", "func saveToken(path string, token *oauth2.Token) {\n fmt.Printf(\"Saving credential file to: %s\\n\", path)\n f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n if err != nil {\n log.Fatalf(\"Unable to cache oauth token: %v\", err)\n }\n defer f.Close()\n json.NewEncoder(f).Encode(token)\n}", "func (t *DefaultTokenStorage) Save(key string, token *oauth2.Token) error {\n\tif _, err := os.Stat(t.fsPath); err != nil {\n\t\tfmt.Printf(\"TOK_DEBUG:: making dir %s\\n\", t.fsPath)\n\t\terr = os.MkdirAll(t.fsPath, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfn := path.Join(t.fsPath, key)\n\tfmt.Printf(\"TOK_DEBUG:: saving token in %s\\n\", fn)\n\tf, err := os.Create(fn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn json.NewEncoder(f).Encode(token)\n}", "func Save(path string, token *oauth2.Token) {\n\tlog.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(file string, token *oauth2.Token) {\n\tlog.Printf(\"Saving credential file to: %s\\n\", file)\n\tf, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(file string, token *oauth2.Token) {\n\tfmt.Println(\"trying to save token\")\n\tfmt.Printf(\"Saving credential file to: %s\\n\", file)\n\tf, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(file string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", file)\n\tf, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(file string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", file)\n\tf, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(file string, token *oauth2.Token) {\n\tvar err error\n\tvar f *os.File\n\tfmt.Printf(\"Saving credential file to: %s\\n\", file)\n\tif f, err = os.Create(file); err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func saveToken(file string, token *oauth2.Token) {\n fmt.Printf(\"Saving credential file to: %s\\n\", file)\n f, err := os.Create(file)\n if err != nil {\n log.Fatalf(\"Unable to cache oauth token: %v\", err)\n }\n defer f.Close()\n json.NewEncoder(f).Encode(token)\n}", "func saveToken(file string, token *oauth2.Token) {\n fmt.Printf(\"Saving credential file to: %s\\n\", file)\n f, err := os.Create(file)\n if err != nil {\n log.Fatalf(\"Unable to cache oauth token: %v\", err)\n }\n defer f.Close()\n json.NewEncoder(f).Encode(token)\n}", "func saveToken(file string, token *oauth2.Token) {\n fmt.Printf(\"Saving credential file to: %s\\n\", file)\n f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n if err != nil {\n log.Fatalf(\"Unable to cache oauth token: %v\", err)\n }\n defer f.Close()\n json.NewEncoder(f).Encode(token)\n}", "func SaveToken(token string) {\n\td.Write(key, []byte(token))\n}", "func saveGDriveToken(path string, token *oauth2.Token, logger *log.Logger) {\n\tlogger.Printf(\"Saving credential file to: %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tdefer CloseCheck(f)\n\tif err != nil {\n\t\tlogger.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\n\terr = json.NewEncoder(f).Encode(token)\n\tif err != nil {\n\t\tlogger.Fatalf(\"Unable to encode oauth token: %v\", err)\n\t}\n}", "func writeToken(filePath string, token string) {\n\t// Check if file exists\n\tif _, err := os.Stat(filePath); os.IsNotExist(err) {\n\t\t// Doesn't exist; lets create it\n\t\terr = os.MkdirAll(filepath.Dir(filePath), 0700)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tb := []byte(token)\n\tif err := ioutil.WriteFile(filePath, b, 0600); err != nil {\n\t\treturn\n\t}\n}", "func (a *AuthClient) saveToken(token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", a.tokenPath)\n\tf, err := os.OpenFile(a.tokenPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\ta.logger.Fatal(\"Unable to cache oauth token\", zap.Error(err))\n\t}\n\tdefer f.Close()\n\t_ = json.NewEncoder(f).Encode(token)\n}", "func saveTokenToFile(file string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credentials to file '%s'\\n\", file)\n\tf, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Println(\"Failed to cache OAuth token:\", err)\n\t\treturn\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n}", "func writeToken(tok *oauth2.Token) (err error) {\n\tp := tokenFilePath()\n\tif err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {\n\t\treturn err\n\t}\n\tdata, err := json.Marshal(tok)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn os.WriteFile(p, data, 0600)\n}", "func saveCachedToken(t *Token) error {\n\ttokenJson, err := json.Marshal(t)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// write to local file\n\terr = ioutil.WriteFile(TokenCachePath+TokenCachePathNewSuffix, tokenJson, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Move into place\n\terr = os.Rename(TokenCachePath+TokenCachePathNewSuffix, TokenCachePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func TokenToFile(path string, token *oauth2.Token) error {\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to save oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n\treturn nil\n}", "func (f *FileStorage) SetToken(t *oauth2.Token) error {\n\tif t == nil || !t.Valid() {\n\t\treturn errors.New(\"bad token\")\n\t}\n\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tout, err := os.OpenFile(f.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\tdata, err := json.Marshal(&t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = out.Write(data)\n\treturn err\n}", "func saveGoogleToken(filepath string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to: %s\\n\", filepath)\n\tf, err := os.Create(filepath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache oauth token: %v\", err)\n\t}\n\tdefer f.Close()\n\n\t// json.NewEncoder returns a new encoder that writes to f, io.Writer.\n\te := json.NewEncoder(f)\n\n\t// Encode writes the JSON encoding of v to the stream, following by a new\n\t// character.\n\te.Encode(token)\n}", "func (c *FileTokenCache) Save(token *oauth2.Token) error {\n\tc.Log.Info(\"Saving credential\", \"file\", c.CacheFile)\n\n\tdir := filepath.Dir(c.CacheFile)\n\n\t_, err := os.Stat(dir)\n\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tc.Log.Info(\"Create cache directory\", \"dir\", dir)\n\t\t\terr := os.MkdirAll(dir, CredentialDirPermMode)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tf, err := os.OpenFile(c.CacheFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tc.Log.Error(err, \"Unable to cache oauth token: %v\")\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tjson.NewEncoder(f).Encode(token)\n\treturn nil\n}", "func SaveToken(inToken *kcauth.Token) configo.ActionFunc {\n\t// first successful action wins\n\treturn actions.Or(\n\t\tcache.SaveTokenInKeyring(inToken, &kcauth.DefaultAppName, &kcauth.DefaultKeyringUsername),\n\t\tcache.SaveToken(inToken, &kcauth.DefaultTokenFilePath),\n\t)\n}", "func (i *InternalTokenHelper) Store(input string) error {\n\ti.populateTokenPath()\n\ttmpFile := i.tokenPath + \".tmp\"\n\tf, err := os.OpenFile(tmpFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tdefer os.Remove(tmpFile)\n\n\t_, err = io.WriteString(f, input)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// We don't care so much about atomic writes here. We're using this package\n\t// because we don't have a portable way of verifying that the target file\n\t// is owned by the correct user. The simplest way of ensuring that is\n\t// to simply re-write it, and the simplest way to ensure that we don't\n\t// damage an existing working file due to error is the write-rename pattern.\n\t// os.Rename on Windows will return an error if the target already exists.\n\treturn atomic.ReplaceFile(tmpFile, i.tokenPath)\n}", "func SaveRefreshToken(token *RefreshToken) error {\n\tpixieAuthFilePath, err := utils.EnsureDefaultAuthFilePath()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.OpenFile(pixieAuthFilePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treturn json.NewEncoder(f).Encode(token)\n}", "func SaveToken(token string) {\n\tviper.Set(\"auth.token\", strings.TrimSpace(token))\n\t_ = viper.WriteConfig()\n}", "func (t *tokenStorage) SaveToken(deviceID string, token string) error {\n\tt.mapLock.Lock()\n\tdefer t.mapLock.Unlock()\n\n\tt.tokens[deviceID] = token\n\treturn nil\n}", "func SaveToken(hashed_usr string, token string) {\n\tcurr_time := time.Now().Unix()\n\tquery := \"INSERT OR REPLACE INTO tokens VALUES (?,?,?);\"\n\tExecDB(query, hashed_usr, token, curr_time)\n}", "func (tm *IAMTokenManager) saveToken(tokenInfo *IAMTokenInfo) {\n\taccessToken := tokenInfo.AccessToken\n\n\tclaims := jwt.StandardClaims{}\n\tif token, _ := jwt.ParseWithClaims(accessToken, &claims, nil); token != nil {\n\t\ttimeToLive := claims.ExpiresAt - claims.IssuedAt\n\t\texpireTime := claims.ExpiresAt\n\t\tfractionOfTimeToLive := 0.8\n\t\ttimeForNewToken := expireTime - (timeToLive * int64(1.0-fractionOfTimeToLive))\n\t\ttm.timeForNewToken = timeForNewToken\n\t}\n\n\ttm.tokenInfo = tokenInfo\n}", "func cacheToken(token *oauth2.Token) {\n\t// open file for writing, allow it to be read/written to, create if doesn't exist, truncate it to length 0\n\tfile, err := os.OpenFile(tokenPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Printf(\"\\nFailed to write token to file: %v\", err)\n\t\treturn\n\t}\n\n\t// encode the token into json\n\tjson.NewEncoder(file).Encode(token)\n}", "func (s PgTokenStore) Save(token *model.Token) *model.AppErr {\n\tq := \"INSERT INTO public.token (user_id, token, type, created_at, expires_at) values(:user_id, :token, :type, :created_at, :expires_at)\"\n\tif _, err := s.db.NamedExec(q, token); err != nil {\n\t\treturn model.NewAppErr(\"PgTokenStore.Save\", model.ErrInternal, locale.GetUserLocalizer(\"en\"), msgSaveToken, http.StatusInternalServerError, nil)\n\t}\n\treturn nil\n}", "func (at *AuthtokenToken) Save(db XODB) error {\n\tif at.Exists() {\n\t\treturn at.Update(db)\n\t}\n\n\treturn at.Insert(db)\n}", "func (m *Manager) storeTokens(tokens *Token) error {\n\texpiresIn, err := m.expiresFromToken(tokens.AccessToken)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttokens.Expires = expiresIn\n\n\tmarshalled, err := json.Marshal(tokens)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO: windows compatibility\n\thome, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdetaDirPath := filepath.Join(home, detaDir)\n\terr = os.MkdirAll(detaDirPath, 0760)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttokensFilePath := filepath.Join(home, authTokenPath)\n\n\terr = ioutil.WriteFile(tokensFilePath, marshalled, 0660)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func SaveToken(id int, token string, refreshToken string) error{\n\n\tuserPos,err := findUser(id)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tfmt.Errorf(\"Error: \",err.Error())\n\t\treturn err\n\t}\n\n\tuserList.UserList[userPos].RefreshToken = refreshToken\n\tuserList.UserList[userPos].AccessToken = token\n\n\tupdateUserList()\n\n\t// se cargan los nuevos datos en el usuario que se esta utilizando\n\tloadUserDataAt(userPos)\n\n\treturn nil\n}", "func (c *CredCache) SaveToken(token OAuthTokenInfo) error {\n\tc.lock.Lock()\n\terr := c.saveTokenInternal(token)\n\tc.lock.Unlock()\n\treturn err\n}", "func (tc *TokenCreate) Save(ctx context.Context) (*Token, error) {\n\tif _, ok := tc.mutation.Name(); !ok {\n\t\treturn nil, errors.New(\"ent: missing required field \\\"name\\\"\")\n\t}\n\tif v, ok := tc.mutation.Name(); ok {\n\t\tif err := token.NameValidator(v); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ent: validator failed for field \\\"name\\\": %v\", err)\n\t\t}\n\t}\n\tif _, ok := tc.mutation.Secret(); !ok {\n\t\treturn nil, errors.New(\"ent: missing required field \\\"secret\\\"\")\n\t}\n\tif v, ok := tc.mutation.Secret(); ok {\n\t\tif err := token.SecretValidator(v); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ent: validator failed for field \\\"secret\\\": %v\", err)\n\t\t}\n\t}\n\tif _, ok := tc.mutation.Permissions(); !ok {\n\t\tv := token.DefaultPermissions\n\t\ttc.mutation.SetPermissions(v)\n\t}\n\tif v, ok := tc.mutation.Permissions(); ok {\n\t\tif err := token.PermissionsValidator(v); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ent: validator failed for field \\\"permissions\\\": %v\", err)\n\t\t}\n\t}\n\tif _, ok := tc.mutation.CreatedAt(); !ok {\n\t\tv := token.DefaultCreatedAt()\n\t\ttc.mutation.SetCreatedAt(v)\n\t}\n\tif _, ok := tc.mutation.UserID(); !ok {\n\t\treturn nil, errors.New(\"ent: missing required edge \\\"user\\\"\")\n\t}\n\tvar (\n\t\terr error\n\t\tnode *Token\n\t)\n\tif len(tc.hooks) == 0 {\n\t\tnode, err = tc.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*TokenMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\ttc.mutation = mutation\n\t\t\tnode, err = tc.sqlSave(ctx)\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(tc.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = tc.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, tc.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (w TokenFileWriter) CreateAndWrite(rootToken string, tokenFilePath string,\n\tcreateTokenFunc tokencreatable.CreateTokenFunc) (tokencreatable.RevokeFunc, error) {\n\tif len(rootToken) == 0 {\n\t\treturn nil, fmt.Errorf(\"rootToken is required\")\n\t}\n\n\t// creates the token\n\tcreateTokenFuncName := getFunctionName(createTokenFunc)\n\ttokenCreated, revokeTokenFunc, createErr := createTokenFunc(rootToken)\n\tif createErr != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create token with %s: %s\", createTokenFuncName, createErr.Error())\n\t}\n\n\tw.logClient.Infof(\"created token with %s\", createTokenFuncName)\n\n\tvar fileErr error\n\tdefer func() {\n\t\t// call revokeTokenFunc if there is some fileErr and revokeTokenFunc itself is not nil\n\t\tif fileErr != nil && revokeTokenFunc != nil {\n\t\t\trevokeTokenFunc()\n\t\t}\n\t}()\n\n\t// Write the created token to the specified file\n\ttokenFileAbsPath, fileErr := filepath.Abs(tokenFilePath)\n\tif fileErr != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert tokenFile to absolute path %s: %s\", tokenFilePath, fileErr.Error())\n\t}\n\n\tdirOfCreatedToken := filepath.Dir(tokenFileAbsPath)\n\tfileErr = w.fileOpener.MkdirAll(dirOfCreatedToken, 0700)\n\tif fileErr != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create tokenpath base dir: %s\", fileErr.Error())\n\t}\n\n\tfileWriter, fileErr := w.fileOpener.OpenFileWriter(tokenFileAbsPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)\n\tif fileErr != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create token file %s: %s\", tokenFileAbsPath, fileErr.Error())\n\t}\n\n\tif fileErr = json.NewEncoder(fileWriter).Encode(tokenCreated); fileErr != nil {\n\t\t_ = fileWriter.Close()\n\t\treturn nil, fmt.Errorf(\"failed to write created token: %s\", fileErr.Error())\n\t}\n\n\tif fileErr = fileWriter.Close(); fileErr != nil {\n\t\treturn nil, fmt.Errorf(\"failed to close token file: %s\", fileErr.Error())\n\t}\n\n\tw.logClient.Infof(\"token is written to %s\", tokenFilePath)\n\n\treturn revokeTokenFunc, nil\n}", "func (s *FilesystemStore) save(session *SessionImp) error {\n\tencoded, err := securecookie.EncodeMulti(session.name, session.Values,\n\t\ts.Codecs...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfilename := filepath.Join(s.path, \"session_\"+session.ID)\n\tfileMutex.Lock()\n\tdefer fileMutex.Unlock()\n\treturn ioutil.WriteFile(filename, []byte(encoded), 0600)\n}", "func tokenFilePath() string {\n\td := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif d == \"\" {\n\t\thome := os.Getenv(\"HOME\")\n\t\tif home == \"\" {\n\t\t\tu, err := user.Current()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\thome = u.HomeDir\n\t\t}\n\t\td = filepath.Join(home, \".config\")\n\t}\n\treturn filepath.Join(d, \"benchsave\", \"token.json\")\n}", "func Save(path string, v interface{}, opts Options) (err error) {\n\tvar (\n\t\tfile *os.File\n\t\ttmp = path + \".tmp.\" + cmn.GenTie()\n\t)\n\tif file, err = cmn.CreateFile(tmp); err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\t_ = file.Close()\n\t\tif err != nil {\n\t\t\tos.Remove(tmp)\n\t\t}\n\t}()\n\tif err = Encode(file, v, opts); err != nil {\n\t\treturn\n\t}\n\tif err = file.Close(); err != nil {\n\t\treturn\n\t}\n\terr = os.Rename(tmp, path)\n\treturn\n}", "func Save(path string, v interface{}) error {\n\tformatter, err := parsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.OpenFile(path, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\treturn formatter.Encode(file, v)\n}", "func (k KMP) Save(filepath, format string) error {\n\tvar err error\n\tswitch format {\n\tcase \"json\":\n\t\tf, err := os.Open(filepath)\n\t\tif err != nil {\n\t\t\tf, err = os.Create(filepath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tdefer f.Close()\n\t\tout, err := json.Marshal(k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = f.Write(out)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid save format, %s\", format)\n\t}\n\treturn err\n}", "func saveToken(token string, timeNum int64, parentDin string) {\n timeData := time.Unix(timeNum, 0).In(loc)\n now := time.Now().In(loc)\n expireTime := timeData.Sub(now)\n model.RedisClient.Set(genTokenKey(parentDin, GateWayTokenKey), token, expireTime)\n log.WithFields(log.Fields{\n \"patentDin\": parentDin,\n \"token\": token,\n }).Info(\"Save token to redis server.\")\n}", "func (token *Token) Save(db *sqlx.DB) {\n\n\tif strings.TrimSpace(token.AccessToken) == \"\" || strings.TrimSpace(token.RefreshToken) == \"\" || token.RefreshTokenExpiry == 0 || token.AccessTokenExpiry == 0 || strings.TrimSpace(token.DeviceID) == \"\" || strings.TrimSpace(token.MacAddress) == \"\" || strings.TrimSpace(token.APIKey) == \"\" || token.Status == 0{\n\t\tfmt.Println(\"Missing Fields from tokens\")\n\t\treturn\n\t}\n\t\n\tif strings.TrimSpace(token.ID) == \"\" {\n\t\ttoken.ID, _ = shortid.Generate()\n\t}\n\t\n\tsql := \"INSERT INTO tokens(id,access_token, access_token_time, access_token_expiry, user_id, status, api_key, refresh_token, refresh_token_time, refresh_token_expiry, device_id, mac_address) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)\"\n\n\t_, err := db.Exec(sql,\n\t\ttoken.ID,\n\t\ttoken.AccessToken,\n\t\ttoken.AccessTokenTime,\n\t\ttoken.AccessTokenExpiry,\n\t\ttoken.UserID,\n\t\ttoken.Status,\n\t\ttoken.APIKey,\n\t\ttoken.RefreshToken,\n\t\ttoken.RefreshTokenTime,\n\t\ttoken.RefreshTokenExpiry,\n\t\ttoken.DeviceID,\n\t\ttoken.MacAddress,\n\t)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (d deck) saveToFile(fileName string) error{\n\n\t// WriteFile (filename, [] byte, permission)\n\treturn ioutil.WriteFile(fileName, []byte (d.toString()), 0666)\n}", "func (s *AuthStore) SaveRefreshToken(t *auth.Token) error {\n\tvar err error\n\tif t.ID == 0 {\n\t\terr = s.db.Insert(t)\n\t} else {\n\t\terr = s.db.Update(t)\n\t}\n\treturn err\n}", "func (c *CredCache) saveTokenInternal(token OAuthTokenInfo) error {\n\tc.isPermSet = false\n\tc.key = nil\n\n\tb, err := token.toJSON()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal during saving token, %v\", err)\n\t}\n\tkeyring, err := keyctl.SessionKeyring()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get keyring during saving token, %v\", err)\n\t}\n\tk, err := keyring.Add(c.keyName, b)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to save key, %v\", err)\n\t}\n\tc.key = k\n\n\t// Set permissions to only current user.\n\terr = keyctl.SetPerm(k, keyctl.PermUserAll)\n\tif err != nil {\n\t\t// which indicates Permission is by default ProcessAll\n\t\tunlinkErr := k.Unlink()\n\t\tif unlinkErr != nil {\n\t\t\tpanic(errors.New(\"failed to set permission, and cannot unlink key, please logout current login session for safety consideration\"))\n\t\t}\n\t\treturn fmt.Errorf(\"failed to set permission for cached token, %v\", err)\n\t}\n\n\tc.isPermSet = true\n\n\treturn nil\n}", "func (p *DefaultParser) Save(buf *bytes.Buffer, filename string) error {\n\terr := ioutil.WriteFile(filename, buf.Bytes(), 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (api *CacophonyUserAPI) SaveTemporaryToken(ttl string) error {\n\tif api.token == \"\" {\n\t\treturn errors.New(\"No Token found\")\n\t}\n\tdata := map[string]interface{}{\n\t\t\"ttl\": ttl,\n\t\t\"access\": map[string]string{\"devices\": \"r\"},\n\t}\n\n\tpayload, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", joinURL(api.serverURL, \"/token\"),\n\t\tbytes.NewReader(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Authorization\", api.token)\n\tpostResp, err := api.httpClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer postResp.Body.Close()\n\tif err := handleHTTPResponse(postResp); err != nil {\n\t\treturn err\n\t}\n\n\tvar resp tokenResponse\n\td := json.NewDecoder(postResp.Body)\n\tif err := d.Decode(&resp); err != nil {\n\t\treturn fmt.Errorf(\"decode: %v\", err)\n\t}\n\n\terr = saveTokenConfig(\"JWT \"+resp.Token, api.username)\n\treturn nil\n}", "func Save(filePath string, t Tomler, secure bool) error {\n\tvar fd *os.File\n\tvar err error\n\tif secure {\n\t\tfd, err = fs.CreateSecureFile(filePath)\n\t} else {\n\t\tfd, err = os.Create(filePath)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"config: can't save %s to %s: %w\", reflect.TypeOf(t).String(), filePath, err)\n\t}\n\tdefer fd.Close()\n\treturn toml.NewEncoder(fd).Encode(t.TOML())\n}", "func (g *Generator) SaveToFile(path string) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn g.Save(f)\n}", "func Save(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tr, err := Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(f, r)\n\treturn err\n}", "func Save(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tr, err := Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(f, r)\n\treturn err\n}", "func Save(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tr, err := Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(f, r)\n\treturn err\n}", "func saveDeviceToken(deviceToken, userId string, lc *lambdacontext.LambdaContext) (bool, string) {\n\tapimodel.Anlogger.Debugf(lc, \"update_fmc_token.go : save device token [%s] for userId [%s]\",\n\t\tdeviceToken, userId)\n\n\tinput := &dynamodb.UpdateItemInput{\n\t\tExpressionAttributeNames: map[string]*string{\n\t\t\t\"#deviceDeviceToken\": aws.String(commons.DeviceTokenColumnName),\n\t\t},\n\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\":deviceDeviceTokenV\": {\n\t\t\t\tS: aws.String(deviceToken),\n\t\t\t},\n\t\t},\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\tcommons.UserIdColumnName: {\n\t\t\t\tS: aws.String(userId),\n\t\t\t},\n\t\t},\n\t\tTableName: aws.String(apimodel.TokenTableName),\n\t\tUpdateExpression: aws.String(\"SET #deviceDeviceToken = :deviceDeviceTokenV\"),\n\t}\n\n\t_, err := apimodel.AwsDynamoDbClient.UpdateItem(input)\n\tif err != nil {\n\t\tapimodel.Anlogger.Errorf(lc, \"update_fmc_token.go : error update device token [%s] for userId [%s] : %v\",\n\t\t\tdeviceToken, userId, err)\n\t\treturn false, commons.InternalServerError\n\t}\n\n\tapimodel.Anlogger.Debugf(lc, \"update_fmc_token.go : successfully update device token [%s] for userId [%s]\",\n\t\tdeviceToken, userId)\n\treturn true, \"\"\n}", "func (tc *TokenCreate) SaveX(ctx context.Context) *Token {\n\tv, err := tc.Save(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\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 SaveFile(name string, content string) {\n\tmyself, error := user.Current()\n\n\tif error != nil {\n\t\tfmt.Println(error)\n\t}\n\n\tfullPath := myself.HomeDir + \"/Documents/Server/\" + name\n\tfmt.Println(\"FILE SAVED AT => \" + fullPath)\n\tioutil.WriteFile(fullPath, []byte(content), 0644)\n}", "func SaveAPIToken(serverURI, username, password string) {\n\ttoken, id := GetAPIToken(serverURI, username, password)\n\tAPIToken = token\n\tAPIID = id\n}", "func SaveAccessToken(\n\tstate, code, expectedState, env, controllerURL string,\n\thosts map[string]string,\n\tfs FileSystem,\n\tclient ClientInterface,\n) error {\n\tif state != expectedState {\n\t\terr := errors.NewOAuthError(\"GoogleCallback\", fmt.Sprintf(\"invalid oauth state, expected '%s', got '%s'\", expectedState, state), http.StatusBadRequest)\n\t\treturn err\n\t}\n\n\turl := fmt.Sprintf(\"%s/access?code=%s\", controllerURL, code)\n\tresp, status, err := client.Get(url, hosts[\"controller\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif status != http.StatusOK {\n\t\treturn errors.NewOAuthError(\"GoogleCallback\", string(resp), status)\n\t}\n\n\tvar bodyObj map[string]interface{}\n\tjson.Unmarshal(resp, &bodyObj)\n\ttoken := bodyObj[\"token\"].(string)\n\n\tc := NewConfig(env, token, controllerURL, hosts)\n\terr = c.Write(fs)\n\treturn err\n}", "func (d deck) saveToFile(filename string) error {\n\treturn ioutil.WriteFile(filename, []byte(d.toString()), 0666) //0666 is a default permission\n}", "func (l Login) storeToken(tokens *Tokens, refresh bool) {\n\n\t// http://blog.golang.org/json-and-go#TOC_5.\n\tl.config.AccessToken = tokens.AccessToken\n\t// typically 14 days\n\tl.config.AccessExpires = tokens.AccessExpires\n\t// A refresh doesn't repeat the refresh token, so let's not\n\t// overwrite with an empty value here!\n\tif !refresh {\n\t\tl.config.RefreshToken = tokens.RefreshToken\n\t\t// typically 90 days\n\t\tl.config.RefreshExpires = tokens.RefreshExpires\n\t}\n\tlog.Println(\"Saving config\")\n\tl.config.Save()\n\n}", "func Token(config *config.SubmitConfig) (string, error) {\n\ttokenbytes, err := ioutil.ReadFile(filepath.Join(pathutil.UserHomeDir(), \".paddle\", \"token_cache\"))\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"previous token not found, fetching a new one...\\n\")\n\t\t// Authenticate to the cloud endpoint\n\t\tauthJSON := map[string]string{}\n\t\tauthJSON[\"username\"] = config.ActiveConfig.Username\n\t\tauthJSON[\"password\"] = config.ActiveConfig.Password\n\t\tauthStr, _ := json.Marshal(authJSON)\n\t\tbody, err := getToken(config.ActiveConfig.Endpoint+\"/api-token-auth/\", authStr)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvar respObj interface{}\n\t\tif errJSON := json.Unmarshal(body, &respObj); errJSON != nil {\n\t\t\treturn \"\", errJSON\n\t\t}\n\t\ttokenStr := respObj.(map[string]interface{})[\"token\"].(string)\n\t\terr = ioutil.WriteFile(filepath.Join(pathutil.UserHomeDir(), \".paddle\", \"token_cache\"), []byte(tokenStr), 0600)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"write cache token file error: %v\", err)\n\t\t}\n\t\t// Ignore write token error, fetch a new one next time\n\t\treturn tokenStr, nil\n\t}\n\treturn string(tokenbytes), nil\n}", "func (f *File) Save(name string) error {\n\treturn ioutil.WriteFile(name, []byte(f.String()), 0666)\n}", "func (d deck) saveToFile(fileName string) error {\n\treturn ioutil.WriteFile(fileName, []byte(d.toString()), 0776)\n}", "func (u *UserModel) SaveAuthToken(token string, userID int) error {\n\treturn u.Redis.Set(context.Background(), fmt.Sprintf(`%s:%s`, AUTH_TOKEN_KEY_PREFIX, token), userID, time.Second*300).Err()\n}", "func netrcFromToken(tok string) {\n\tfileContent := fmt.Sprintf(\"machine github.com login %s\\n\", tok)\n\thdir, err := homedir.Dir()\n\tif err != nil {\n\t\tlog.Fatalf(\"netrcFromToken: could not get homedir: %v\", err)\n\t}\n\trcp := filepath.Join(hdir, getNETRCFilename())\n\tif err := os.WriteFile(rcp, []byte(fileContent), 0o600); err != nil {\n\t\tlog.Fatalf(\"netrcFromToken: could not write to file: %v\", err)\n\t}\n}", "func Save(path string, x interface{}) error {\n\tmtx.Lock()\n\tdefer mtx.Unlock()\n\n\tfile, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tdata, err := toJSON(x)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(file, data)\n\treturn err\n}", "func (settings *Settings) Save(path string) error {\n\tcontent, err := json.Marshal(settings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(path, content, 0644)\n}" ]
[ "0.848786", "0.8343423", "0.8224254", "0.8123389", "0.8078807", "0.80605614", "0.8045947", "0.8045947", "0.8043074", "0.8043074", "0.8043074", "0.8043074", "0.8043074", "0.8043074", "0.8043074", "0.8043074", "0.8043074", "0.8043074", "0.8043074", "0.8040915", "0.8035313", "0.80334073", "0.801399", "0.7988418", "0.79789734", "0.7933091", "0.79116386", "0.78899395", "0.78810585", "0.785632", "0.7767795", "0.77617884", "0.77596134", "0.77596134", "0.7751501", "0.77072144", "0.77072144", "0.7644681", "0.76344085", "0.7500787", "0.74404335", "0.7437428", "0.7390637", "0.7292708", "0.7176621", "0.71125156", "0.7100446", "0.7042769", "0.7041058", "0.7031466", "0.6777556", "0.6747782", "0.67200756", "0.66671216", "0.6572217", "0.6405489", "0.62867796", "0.62440896", "0.6228246", "0.6228116", "0.62084186", "0.5943692", "0.59238106", "0.5912008", "0.5836471", "0.5725376", "0.5719304", "0.5707876", "0.56820464", "0.5665912", "0.56334686", "0.55999106", "0.5573748", "0.55502975", "0.55439585", "0.5534876", "0.5508251", "0.546189", "0.54574764", "0.54574764", "0.54574764", "0.54376644", "0.54309976", "0.54286885", "0.54183", "0.5416972", "0.54159003", "0.5402099", "0.5394207", "0.5391309", "0.53878653", "0.5385452", "0.5383804", "0.5380719", "0.53759944", "0.5367924" ]
0.8051372
10
Load returns Configuration struct
func Load(env string) (*Configuration, error) { bytes, err := ioutil.ReadFile("config." + env + ".yaml") if err != nil { return nil, fmt.Errorf("error reading config file, %s", err) } var cfg = new(Configuration) if err := yaml.Unmarshal(bytes, cfg); err != nil { return nil, fmt.Errorf("unable to decode into struct, %v", err) } return cfg, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Load() Configuration {\n\tif cfg.APIAiToken != \"\" {\n\t\treturn cfg\n\t}\n\tconf, err := os.Open(\"config/config.json\")\n\n\tif err != nil {\n\t\tlog.Fatal(\"config:Load error : \", err)\n\t}\n\n\tdecoder := json.NewDecoder(conf)\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\tlog.Fatal(\"config:Load error : \", err)\n\t}\n\n\treturn cfg\n}", "func Load() *Config {\n\treturn &Config{}\n}", "func Load() (cfg *Config, err error) {\n\tfile, err := Location()\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = os.Stat(file)\n\tif os.IsNotExist(err) {\n\t\tcfg = &Config{}\n\t\terr = nil\n\t\treturn\n\t}\n\tif err != nil {\n\t\terr = fmt.Errorf(\"can't check if config file '%s' exists: %v\", file, err)\n\t\treturn\n\t}\n\t// #nosec G304\n\tdata, err := os.ReadFile(file)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"can't read config file '%s': %v\", file, err)\n\t\treturn\n\t}\n\tcfg = &Config{}\n\tif len(data) == 0 {\n\t\treturn\n\t}\n\terr = json.Unmarshal(data, cfg)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"can't parse config file '%s': %v\", file, err)\n\t\treturn\n\t}\n\treturn\n}", "func Load(path string) (*Configuration, error) {\n\tbytes, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading config file, %s\", err)\n\t}\n\tvar cfg = new(Configuration)\n\terr = json.Unmarshal(bytes, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg, nil\n}", "func Load() Config {\n\tif config != nil {\n\t\treturn *config\n\t}\n\tfile, e := ioutil.ReadFile(getFilename())\n\tif e != nil {\n\t\tlog.Fatalf(\"Error while reading config file: %v\\n\", e)\n\t}\n\tconfig = &Config{}\n\tif json.Unmarshal(file, config) != nil {\n\t\tlog.Fatalf(\"Error while parsing config file: %v\\n\", e)\n\t}\n\treturn *config\n}", "func (s *Store) Load() *Config {\n\tconfig := &Config{\n\t\tDomain: s.UntypedLoad(DomainConfigName).(*Domain).DeepCopy(),\n\t\tGC: s.UntypedLoad(gc.ConfigName).(*gc.Config).DeepCopy(),\n\t\tNetwork: s.UntypedLoad(netcfg.ConfigMapName).(*netcfg.Config).DeepCopy(),\n\t\tFeatures: nil,\n\t}\n\n\tif featureConfig := s.UntypedLoad(cfgmap.FeaturesConfigName); featureConfig != nil {\n\t\tconfig.Features = featureConfig.(*cfgmap.Features).DeepCopy()\n\t}\n\n\treturn config\n}", "func (l *Loader) Load() (*Config, error) {\n\tif l.ConfigPath == \"\" {\n\t\treturn nil, errors.Reason(\"-qscheduler-config is required\").Err()\n\t}\n\n\tblob, err := ioutil.ReadFile(l.ConfigPath)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to open the config file\").Err()\n\t}\n\n\tcfg := &Config{}\n\tif err := proto.UnmarshalText(string(blob), cfg); err != nil {\n\t\treturn nil, errors.Annotate(err, \"not a valid Config proto message\").Err()\n\t}\n\n\tl.lastGood.Store(cfg)\n\treturn cfg, nil\n}", "func Load(fileName string) Configuration {\n\tvar config Configuration\n\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening configuration file from %s: %s\", fileName, err)\n\t}\n\tdefer file.Close()\n\n\tdecoder := json.NewDecoder(file)\n\tif err := decoder.Decode(&config); err != nil {\n\t\tlog.Fatalf(\"Error decoding JSON from %s: %s\", fileName, err)\n\t}\n\n\treturn config\n}", "func Load(path string) (*Config, error) {\n\tdata, err := ioutil.ReadFile(path)\n\tconfig := new(Config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\terr = json.Unmarshal(data, config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\treturn config, nil\n}", "func Load(filename string) Config {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.WithField(`error`, err).Fatal(`Opening config file`)\n\t}\n\n\tdec := json.NewDecoder(file)\n\tconf := Config{}\n\tif err = dec.Decode(&conf); err != nil {\n\t\tlog.WithField(`error`, err).Fatal(`Parsing config file`)\n\t}\n\n\treturn conf\n}", "func Load(filename string) (*Configuration, error) {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// To allow comments in the json, we minify the file with js minifer before parsing\n\tm := minify.New()\n\tm.AddFunc(\"text/javascript\", js.Minify)\n\tfile, err = m.Bytes(\"text/javascript\", file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td := Default()\n\terr = json.Unmarshal(file, d)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, d.Validate()\n}", "func Load(p string) (cfg *Config, err error) {\n\tvar d []byte\n\td, err = ioutil.ReadFile(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg = new(Config)\n\tif err = yaml.Unmarshal(d, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.ClusterState == nil {\n\t\tcfg.ClusterState = &ClusterState{}\n\t}\n\tif cfg.ALBIngressController == nil {\n\t\tcfg.ALBIngressController = &ALBIngressController{}\n\t}\n\n\tcfg.ConfigPath, err = filepath.Abs(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cfg.ClusterState.UpTook != \"\" {\n\t\tcfg.ClusterState.upTook, err = time.ParseDuration(cfg.ClusterState.UpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif cfg.ALBIngressController.IngressUpTook != \"\" {\n\t\tcfg.ALBIngressController.ingressUpTook, err = time.ParseDuration(cfg.ALBIngressController.IngressUpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}", "func (c *Config) Load() (*Config, error) {\n\tf, err := ioutil.ReadFile(\"config.json\")\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tlogin := &Login{}\n\terr = json.Unmarshal(f, login)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tc.login = *login\n\treturn c, err\n}", "func Load(confFname string) (*Config, error) {\n\tvar conf Config\n\terr := conf.Load(confFname)\n\treturn &conf, err\n}", "func Load(cfg interface{}) error { return c.Load(cfg) }", "func (viperConfig *Configurator) Load() (*config.SBConfiguration, error) {\n\tif err := viperConfig.viper.ReadInConfig(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsbConfig := &config.SBConfiguration{}\n\tif err := viperConfig.viper.Unmarshal(sbConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sbConfig, nil\n}", "func (cfg *Configuration) Load() error {\n\tcfg.locker.Lock()\n\tdefer cfg.locker.Unlock()\n\tif cfg.FilePath == \"\" {\n\t\treturn errors.New(\"Configuration.FilePath was not set\")\n\t}\n\treturn gonfig.Read(cfg)\n}", "func Load(path string) (*Configuration, error) {\n\n\tbytes, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar c Configuration\n\terr = goyaml.Unmarshal(bytes, &c)\n\n\treturn &c, err\n}", "func Load(fileName string) Configuration {\n\tcontents, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tconfiguration := Configuration{}\n\n\tif err = yaml.Unmarshal(contents, &configuration); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn configuration\n}", "func Load() error {\n\tif configPathRaw == \"\" {\n\t\treturn errors.New(\"No configuration file path defined! See '-h'!\")\n\t}\n\n\tlog.Println(\"Loading configuration from file:\", configPathRaw)\n\n\t// Replace home directory if \"~\" was specified.\n\tif strings.Contains(configPathRaw, \"~\") {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\t// Well, I don't know how to test this.\n\t\t\treturn errors.New(\"Failed to get current user's data: \" + err.Error())\n\t\t}\n\n\t\tconfigPathRaw = strings.Replace(configPathRaw, \"~\", u.HomeDir, 1)\n\t}\n\n\t// Get absolute path to configuration file.\n\tconfigPath, err := filepath.Abs(configPathRaw)\n\tif err != nil {\n\t\t// Can't think of situation when it's testable.\n\t\treturn errors.New(\"Failed to get real configuration file path:\" + err.Error())\n\t}\n\n\t// Read it.\n\tconfigFileData, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn errors.New(\"Failed to load configuration file data:\" + err.Error())\n\t}\n\n\t// Parse it.\n\terr1 := yaml.Unmarshal(configFileData, Cfg)\n\tif err1 != nil {\n\t\treturn errors.New(\"Failed to parse configuration file:\" + err1.Error())\n\t}\n\n\tlog.Printf(\"Configuration file parsed: %+v\\n\", Cfg)\n\treturn nil\n}", "func (c *Config) Load() error {\n\tif _, err := os.Stat(c.filePath); os.IsNotExist(err) {\n\t\treturn errors.New(\"pharos hasn't been configured yet\")\n\t}\n\traw, err := ioutil.ReadFile(c.filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif string(raw) == \"\" {\n\t\treturn errors.New(\"pharos hasn't been configured yet\")\n\t}\n\n\treturn json.Unmarshal(raw, c)\n}", "func Load(p string) (cfg *Config, err error) {\n\tvar d []byte\n\td, err = ioutil.ReadFile(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg = new(Config)\n\tif err = yaml.Unmarshal(d, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.ConfigPath != p {\n\t\tcfg.ConfigPath = p\n\t}\n\tcfg.ConfigPath, err = filepath.Abs(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cfg, nil\n}", "func (cfg *Config) Load(filename string) {\n\tdata,err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tcfg.GethHost = GethHost\n\t\tcfg.ServerDBConnectString = ServerDBConnectString\n\t\tcfg.BlockDataConnectString = BlockDataConnectString\n\t\tcfg.AffiremBlockHeigh = AffiremBlockHeigh\n\t\tcfg.TimeDelayInSecand = TimeDelayInSecand\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(data,cfg)\n\tif err != nil {\n\t\tcfg.GethHost = GethHost\n\t\tcfg.ServerDBConnectString = ServerDBConnectString\n\t\tcfg.BlockDataConnectString = BlockDataConnectString\n\t\tcfg.AffiremBlockHeigh = AffiremBlockHeigh\n\t\tcfg.TimeDelayInSecand = TimeDelayInSecand\n\t}\n}", "func Load(configFileName string) Config {\n\tvar config Config\n\n\tconfigFile, err := os.Open(configFileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer configFile.Close()\n\n\terr = json.NewDecoder(configFile).Decode(&config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// get the current time stamp\n\tsCurDttmStmp := time.Now().Format(\"20060102150405\")\n\t// set the UUID\n\tconfig.UUID = sCurDttmStmp\n\t// for different format please refer to the below URL\n\t// https://medium.com/@Martynas/formatting-date-and-time-in-golang-5816112bf098\n\t// set the run date time\n\tconfig.RunDttmStmp = time.Now().Format(\"2006-Jan-02 15:04:05.000\")\n\n\treturn config\n}", "func Load(path string) (*Configuration, error) {\n\tbytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading config file, %s\", err)\n\t}\n\tvar cfg = new(Configuration)\n\tif err := yaml.Unmarshal(bytes, cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to decode into struct, %v\", err)\n\t}\n\treturn cfg, nil\n}", "func Load() *Configuration {\n\t// Todo - better way to work out where the config.yml file is?\n\t// Do we have a sensible default for this?\n\treturn LoadFrom(\n\t\t[]string{\".\", \"../\", \"../config\", \"./config\"},\n\t\t\"config\",\n\t)\n}", "func (c *Configuration) Load() {\n\t// TODO:change this to log to stderr, actuall all logs to stderr?\n\t//log.Printf(\"Using configuration at %s\\n\", configFile)\n\n\tif _, err := toml.DecodeFile(configFile, &c); err != nil {\n\t\tlog.Fatalln(\"Failed to open file\", err)\n\t\treturn\n\t}\n\n\t//TODO: check if empty after loading, else initalize\n\tif c.RedirectUri == \"\" {\n\t\tc.RedirectUri = redirectUrl\n\t}\n\tif c.Scope == \"\" {\n\t\tc.Scope = scope\n\t}\n\tif c.BaseUrl == \"\" {\n\t\tc.BaseUrl = baseUrl\n\t}\n}", "func Load(dataDirPath string) (config *Config, err error) {\n // load the config json into memory\n byteArr, err := ioutil.ReadFile(filepath.Join(dataDirPath, configFileName))\n if err != nil {\n return nil, fmt.Errorf(\"failed to read configuration file: %v\", err)\n }\n cfgJSON := &configJSON{}\n if err = json.Unmarshal(byteArr, cfgJSON); err != nil {\n return nil, fmt.Errorf(\"failed to parse configuration json: %v\", err)\n }\n\n // decode the private and public pem files\n pubPem, _ := pem.Decode([]byte(cfgJSON.PubPem))\n if pubPem == nil {\n return nil, fmt.Errorf(\"invalid public key data\")\n }\n privPem, _ := pem.Decode([]byte(cfgJSON.PrivPem))\n if privPem == nil {\n return nil, fmt.Errorf(\"invalid private key data\")\n }\n return &Config{privPem, pubPem, dataDirPath}, nil\n}", "func Load(path string, maxSize int64) (*Config, error) {\n\tb, readErr := store.FileRead(path, maxSize)\n\tif readErr != nil {\n\t\treturn nil, readErr\n\t}\n\tc := New()\n\tif err := yaml.Unmarshal(b, c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}", "func (c *Config) Load() error {\n\tm := c.createMultiConfig()\n\terr := m.Load(c)\n\n\tif c.UUID == \"\" {\n\t\tc.UUID = uuid.New().String()\n\t}\n\n\treturn err\n}", "func Load() (Config, error) {\n\tcfg := defaultConfig\n\terr := util.LoadConfig(&cfg, &defaultConfig)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\treturn cfg, nil\n}", "func (s *store) Load() error {\n\t// if the config doesn't exist, create it.\n\tconfigExists, err := s.configExists()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !configExists {\n\t\tc := &Config{\n\t\t\tGames: make([]Game, 0),\n\t\t}\n\n\t\t// Write a new config with default settings.\n\t\treturn s.Write(c)\n\t}\n\n\treturn nil\n}", "func Load(config *Config) error {\n\treturn NewLoader(config).Load()\n}", "func Load(path string) (*Config, error) {\n\tconfigFile, err := os.Open(path)\n\tdefer configFile.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar config Config\n\tjsonParser := json.NewDecoder(configFile)\n\tparseErr := jsonParser.Decode(&config)\n\n\tif parseErr != nil {\n\t\treturn nil, parseErr\n\t}\n\tconfig.fillFlags()\n\treturn &config, nil\n}", "func (v *Config) Loads(conf string) error {\n\tv.conf = conf\n\n\t// set default config values.\n\tv.SetDefaults()\n\n\t// json style should not be *.conf\n\tif !strings.HasSuffix(conf, \".conf\") {\n\t\t// read the whole config to []byte.\n\t\tvar d *json.Decoder\n\t\tif f, err := os.Open(conf); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tdefer f.Close()\n\n\t\t\td = json.NewDecoder(NewReader(f))\n\t\t\t//d = json.NewDecoder(f)\n\t\t}\n\n\t\tif err := d.Decode(v); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// srs-style config.\n\t\tvar p *srsConfParser\n\t\tif f, err := os.Open(conf); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tdefer f.Close()\n\n\t\t\tp = NewSrsConfParser(f)\n\t\t}\n\n\t\tif err := p.Decode(v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// when parse EOF, reparse the config.\n\tif err := v.reparse(); err != nil {\n\t\treturn err\n\t}\n\n\t// validate the config.\n\tif err := v.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load() (cfg *Configuration, err error) {\n\tlog := zaplog.New(version)\n\tif err = zaplog.ZLog(validateEnvironment()); err != nil {\n\t\treturn\n\t}\n\n\thomeDir = fmt.Sprintf(\"%s/%s\", os.Getenv(\"DATADIR\"), \"goinagbe\")\n\tassetsDir = fmt.Sprintf(\"%s/%s/assets\", os.Getenv(\"DATADIR\"), \"goinagbe\")\n\tuploadsDir = fmt.Sprintf(\"%s/%s/uploads\", os.Getenv(\"DATADIR\"), \"goinagbe\")\n\n\tcfg = &Configuration{\n\t\tVersion: version,\n\t\tAssets: assetsDir,\n\t\tUploads: uploadsDir,\n\t\tLog: log,\n\t\tServer: &Server{\n\t\t\tPort: os.Getenv(\"APP_PORT\"),\n\t\t\tDebug: os.Getenv(\"ENVIRONMENT\") != \"production\",\n\t\t\tReadTimeout: 30, //seconds\n\t\t\tWriteTimeout: 30, //seconds\n\t\t},\n\t\tAWS: &AWS{\n\t\t\tKey: os.Getenv(\"AWS_ACCESS_KEY_ID\"),\n\t\t\tSecret: os.Getenv(\"AWS_SECRET_ACCESS_KEY\"),\n\t\t\tBucket: os.Getenv(\"BUCKET\"),\n\t\t\tPublicPrefix: os.Getenv(\"BUCKET_PUBLIC_PREFIX\"),\n\t\t\tPrivatePrefix: os.Getenv(\"BUCKET_PRIVATE_PREFIX\"),\n\t\t\tRegion: os.Getenv(\"AWS_REGION\"),\n\t\t\tSender: os.Getenv(\"SES_SENDER\"),\n\t\t},\n\t\tDB: &Database{\n\t\t\tHost: os.Getenv(\"DB_HOST\"),\n\t\t\tPort: os.Getenv(\"DB_PORT\"),\n\t\t\tUser: os.Getenv(\"DB_USER\"),\n\t\t\tPassword: os.Getenv(\"DB_PASSWORD\"),\n\t\t\tDatabase: os.Getenv(\"DB_NAME\"),\n\t\t\tLogQueries: os.Getenv(\"ENVIRONMENT\") != \"production\",\n\t\t},\n\t\tJWT: &JWT{\n\t\t\tSecret: os.Getenv(\"JWT_SECRET\"),\n\t\t\tDuration: 60, //1 hour\n\t\t\tRefreshDuration: 43200, //1 month\n\t\t\tMaxRefresh: 129600, //3 months\n\t\t\tSigningAlgorithm: \"HS256\",\n\t\t},\n\t\tApp: &Application{\n\t\t\tFQDN: os.Getenv(\"FQDN\"),\n\t\t\tFrontend: os.Getenv(\"FRONTEND\"),\n\t\t\tCompany: os.Getenv(\"COMPANY\"),\n\t\t\tAdminEmail: os.Getenv(\"ADMIN_EMAIL\"),\n\t\t\tAdminPassword: os.Getenv(\"ADMIN_PASSWORD\"),\n\t\t\tEnvironment: os.Getenv(\"ENVIRONMENT\"),\n\t\t\tMinPasswordStr: 1,\n\t\t\tSwaggerUIPath: \"assets/swaggerui\",\n\t\t},\n\t}\n\n\tif err = zaplog.ZLog(EnsureDirs([]string{homeDir, assetsDir, uploadsDir}, 0700)); err != nil {\n\t\treturn\n\t}\n\n\tif err = zaplog.ZLog(os.Setenv(\"UPLOADS\", uploadsDir)); err != nil {\n\t\treturn\n\t}\n\n\tif err = zaplog.ZLog(os.Setenv(\"ASSETS\", assetsDir)); err != nil {\n\t\treturn\n\t}\n\n\tcfg.DB.Db, err = orm.New(cfg.DB.User, cfg.DB.Password, cfg.DB.Host, cfg.DB.Port, cfg.DB.Database, cfg.Log.GetLogger())\n\tif err = zaplog.ZLog(err); err != nil {\n\t\treturn\n\t}\n\n\t//Initialize Cache\n\tif err = zaplog.ZLog(util.New()); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func Load(logger log.Logger) (*Config, error) {\n\t// default config\n\tc := Config{\n\t\tJWTExpiration: defaultJWTExpirationHours,\n\t}\n\t// load from YAML config file\n\tbytes, err := ioutil.ReadFile(*configFile)\n\tif err != nil {\n\t\treturn nil, errors.New(\"config file fs read failed\")\n\t}\n\tif err = yaml.Unmarshal(bytes, &c); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// load from environment variables prefixed with \"APP_\"\n\terr = env.New(\"APP_\", logger.Infof).Load(&c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// validation\n\tif err = c.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &c, err\n}", "func Load() error {\n\tvar err error\n\tvar hd string\n\tvar conf []byte\n\n\tif hd, err = homedir.Dir(); err != nil {\n\t\treturn err\n\t}\n\n\tcdir := hd + \"/.config/\"\n\tcf := cdir + \"goploader.conf.yml\"\n\n\tif _, err = os.Stat(cdir); os.IsNotExist(err) {\n\t\tlog.Printf(\"Creating %v directory.\\n\", cdir)\n\t\tos.Mkdir(cdir, 0700)\n\t} else if err != nil {\n\t\treturn err\n\t}\n\tif _, err = os.Stat(cf); os.IsNotExist(err) {\n\t\tlog.Printf(\"Configuration file %v not found. Writing default configuration.\\n\", cf)\n\t\tC.Service = \"https://gpldr.in/\"\n\t\tif conf, err = yaml.Marshal(C); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn ioutil.WriteFile(cf, conf, 0644)\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\tif conf, err = ioutil.ReadFile(cf); err != nil {\n\t\treturn err\n\t}\n\treturn yaml.Unmarshal(conf, &C)\n}", "func Load(path string) (*Config, error) {\n\tcfg := new(Config)\n\n\tswitch path {\n\tcase \"\":\n\t\tcfg.path = configFilePath()\n\tdefault:\n\t\tcfg.path = path\n\t}\n\n\tswitch exists, err := configFileExists(cfg.path); {\n\tcase err != nil:\n\t\treturn nil, errors.Wrap(err, \"failed to stat config file\")\n\tcase !exists:\n\t\tcfg.setDefaults()\n\t\treturn cfg, cfg.Write()\n\tdefault:\n\t\tfh, err := os.Open(cfg.path)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to open config file\")\n\t\t}\n\t\tdefer fh.Close()\n\n\t\tbuf, err := ioutil.ReadAll(fh)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to read file\")\n\t\t}\n\n\t\treturn cfg, yaml.Unmarshal(buf, &cfg)\n\t}\n}", "func Load(filename string) (c *Config, err error) {\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"config load: %w\", err)\n\t}\n\n\treturn Parse(content, filename)\n}", "func loadConfig() SQLImportConfStruct {\n\t//-- Check Config File File Exists\n\tcwd, _ := os.Getwd()\n\tconfigurationFilePath := cwd + \"/\" + configFileName\n\tlogger(1, \"Loading Config File: \"+configurationFilePath, false)\n\tif _, fileCheckErr := os.Stat(configurationFilePath); os.IsNotExist(fileCheckErr) {\n\t\tlogger(4, \"No Configuration File\", true)\n\t\tos.Exit(102)\n\t}\n\n\t//-- Load Config File\n\tfile, fileError := os.Open(configurationFilePath)\n\t//-- Check For Error Reading File\n\tif fileError != nil {\n\t\tlogger(4, \"Error Opening Configuration File: \"+fmt.Sprintf(\"%v\", fileError), true)\n\t}\n\t//-- New Decoder\n\tdecoder := json.NewDecoder(file)\n\n\teldapConf := SQLImportConfStruct{}\n\n\t//-- Decode JSON\n\terr := decoder.Decode(&eldapConf)\n\t//-- Error Checking\n\tif err != nil {\n\t\tlogger(4, \"Error Decoding Configuration File: \"+fmt.Sprintf(\"%v\", err), true)\n\t}\n\n\t//-- Return New Congfig\n\treturn eldapConf\n}", "func (c *Config) Load(path string) error {\n\n\t// Read the config json file\n\tfile, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error opening config %s %v\", path, err)\n\t}\n\n\tvar data map[string]map[string]string\n\terr = json.Unmarshal(file, &data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading config %s %v\", path, err)\n\t}\n\n\tif len(data) < 3 {\n\t\treturn fmt.Errorf(\"error reading config - not enough configs, got :%d expected 3\", len(data))\n\t}\n\n\tc.configs[ModeDevelopment] = data[\"development\"]\n\tc.configs[ModeProduction] = data[\"production\"]\n\tc.configs[ModeTest] = data[\"test\"]\n\n\treturn nil\n}", "func Load() Config {\n\tconfigf, err := os.Open(\"./config.yaml\")\n\tif err != nil {\n\t\tlogger.Panic(fmt.Sprintf(\"could not find config\"))\n\t}\n\tdefer configf.Close()\n\n\tvar config Config\n\n\terr = yaml.NewDecoder(configf).Decode(&config)\n\tif err != nil {\n\t\tlogger.Panic(fmt.Sprintf(\"invalid config file\"))\n\t}\n\n\treturn config\n}", "func Load(filePath string) error {\n\treturn config.Load(filePath, &cfg)\n}", "func loadConfig() *cfg {\n\tconfig, err := ioutil.ReadFile(\"config.json\")\n\n\tif os.IsNotExist(err) {\n\t\tfmt.Println(\"Config file not found. Generating it now...\")\n\t\tcreateConfig()\n\t\tloadConfig()\n\t}\n\n\tcfg := new(cfg)\n\terr = json.Unmarshal(config, &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error loading config file: %v\", err)\n\t}\n\n\treturn cfg\n}", "func Load(filename string) (*Config, error) {\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\t\treturn nil, fmt.Errorf(\"file doesn't exists: %s\", filename)\n\t}\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := loader.New(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar logOutput io.Writer\n\tswitch {\n\tcase c.Logging.Output == \"stderr\":\n\t\tlogOutput = os.Stderr\n\tcase c.Logging.Output == \"stdout\":\n\t\tlogOutput = os.Stdout\n\tdefault:\n\t\tlogOutput = os.Stderr\n\t}\n\n\tif c.Logging.Level == \"\" {\n\t\tc.Logging.Level = DefaultLogLevel\n\t}\n\n\trawMc, err := NewMemberlistConfig(c.Memberlist.Environment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmemberlistConfig, err := loadMemberlistConfig(c, rawMc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tjoinRetryInterval,\n\t\tkeepAlivePeriod,\n\t\tidleClose,\n\t\tbootstrapTimeout,\n\t\ttriggerBalancerInterval,\n\t\tleaveTimeout,\n\t\troutingTablePushInterval time.Duration\n\t)\n\n\tif c.Olricd.KeepAlivePeriod != \"\" {\n\t\tkeepAlivePeriod, err = time.ParseDuration(c.Olricd.KeepAlivePeriod)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err,\n\t\t\t\tfmt.Sprintf(\"failed to parse olricd.keepAlivePeriod: '%s'\", c.Olricd.KeepAlivePeriod))\n\t\t}\n\t}\n\n\tif c.Olricd.IdleClose != \"\" {\n\t\tidleClose, err = time.ParseDuration(c.Olricd.IdleClose)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err,\n\t\t\t\tfmt.Sprintf(\"failed to parse olricd.idleClose: '%s'\", c.Olricd.IdleClose))\n\t\t}\n\t}\n\n\tif c.Olricd.BootstrapTimeout != \"\" {\n\t\tbootstrapTimeout, err = time.ParseDuration(c.Olricd.BootstrapTimeout)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err,\n\t\t\t\tfmt.Sprintf(\"failed to parse olricd.bootstrapTimeout: '%s'\", c.Olricd.BootstrapTimeout))\n\t\t}\n\t}\n\tif c.Memberlist.JoinRetryInterval != \"\" {\n\t\tjoinRetryInterval, err = time.ParseDuration(c.Memberlist.JoinRetryInterval)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err,\n\t\t\t\tfmt.Sprintf(\"failed to parse memberlist.joinRetryInterval: '%s'\",\n\t\t\t\t\tc.Memberlist.JoinRetryInterval))\n\t\t}\n\t}\n\tif c.Olricd.RoutingTablePushInterval != \"\" {\n\t\troutingTablePushInterval, err = time.ParseDuration(c.Olricd.RoutingTablePushInterval)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err,\n\t\t\t\tfmt.Sprintf(\"failed to parse olricd.routingTablePushInterval: '%s'\", c.Olricd.RoutingTablePushInterval))\n\t\t}\n\t}\n\n\tif c.Olricd.TriggerBalancerInterval != \"\" {\n\t\ttriggerBalancerInterval, err = time.ParseDuration(c.Olricd.TriggerBalancerInterval)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err,\n\t\t\t\tfmt.Sprintf(\"failed to parse olricd.triggerBalancerInterval: '%s'\", c.Olricd.TriggerBalancerInterval))\n\t\t}\n\t}\n\n\tif c.Olricd.LeaveTimeout != \"\" {\n\t\tleaveTimeout, err = time.ParseDuration(c.Olricd.LeaveTimeout)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err,\n\t\t\t\tfmt.Sprintf(\"failed to parse olricd.leaveTimeout: '%s'\", c.Olricd.LeaveTimeout))\n\t\t}\n\t}\n\n\tclientConfig := Client{}\n\terr = mapYamlToConfig(&clientConfig, &c.Client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdmapConfig, err := loadDMapConfig(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := &Config{\n\t\tBindAddr: c.Olricd.BindAddr,\n\t\tBindPort: c.Olricd.BindPort,\n\t\tInterface: c.Olricd.Interface,\n\t\tServiceDiscovery: c.ServiceDiscovery,\n\t\tMemberlistInterface: c.Memberlist.Interface,\n\t\tMemberlistConfig: memberlistConfig,\n\t\tClient: &clientConfig,\n\t\tLogLevel: c.Logging.Level,\n\t\tJoinRetryInterval: joinRetryInterval,\n\t\tRoutingTablePushInterval: routingTablePushInterval,\n\t\tTriggerBalancerInterval: triggerBalancerInterval,\n\t\tEnableClusterEventsChannel: c.Olricd.EnableClusterEventsChannel,\n\t\tMaxJoinAttempts: c.Memberlist.MaxJoinAttempts,\n\t\tPeers: c.Memberlist.Peers,\n\t\tPartitionCount: c.Olricd.PartitionCount,\n\t\tReplicaCount: c.Olricd.ReplicaCount,\n\t\tWriteQuorum: c.Olricd.WriteQuorum,\n\t\tReadQuorum: c.Olricd.ReadQuorum,\n\t\tReplicationMode: c.Olricd.ReplicationMode,\n\t\tReadRepair: c.Olricd.ReadRepair,\n\t\tLoadFactor: c.Olricd.LoadFactor,\n\t\tMemberCountQuorum: c.Olricd.MemberCountQuorum,\n\t\tLogger: log.New(logOutput, \"\", log.LstdFlags),\n\t\tLogOutput: logOutput,\n\t\tLogVerbosity: c.Logging.Verbosity,\n\t\tHasher: hasher.NewDefaultHasher(),\n\t\tKeepAlivePeriod: keepAlivePeriod,\n\t\tIdleClose: idleClose,\n\t\tBootstrapTimeout: bootstrapTimeout,\n\t\tLeaveTimeout: leaveTimeout,\n\t\tDMaps: dmapConfig,\n\t}\n\n\tif err := cfg.Sanitize(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := cfg.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg, nil\n}", "func Load(r io.Reader) (*Config, error) {\n\tb, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := &Config{}\n\terr = yaml.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// check name exist, if not, use addr instead\n\tfor _, client := range c.Clients {\n\t\tif client.ClientName == \"\" {\n\t\t\tclient.ClientName = client.TransmissionAddr\n\t\t}\n\t}\n\n\treturn c, nil\n}", "func Load() Config {\n\tvip := viper.New()\n\n\tvip.SetConfigName(\"config\")\n\tvip.SetConfigType(\"yml\")\n\tvip.AddConfigPath(\".\")\n\n\terr := vip.ReadInConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"Config file used:\", vip.ConfigFileUsed())\n\n\tcfg := Config{}\n\terr = vip.Unmarshal(&cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn cfg\n}", "func Load(path string) (*Config, error) {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn load(b)\n}", "func LoadConfig(confPath string) (Config, error){\n var conf Config\n _, err := toml.DecodeFile(confPath, &conf)\n return conf, err\n}", "func Load(cfg interface{}, configPath string) error {\n\tif err := readConfigFile(configPath, cfg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(config interface{}, filename string) error {\n\tv := reflect.ValueOf(config).Elem()\n\tif err := applyDefaults(reflect.StructField{}, v); err != nil {\n\t\treturn fmt.Errorf(\"init config with default values: %s\", err)\n\t}\n\n\tif err := mergeJSONConfig(config, filename); err != nil {\n\t\treturn err\n\t}\n\n\tif err := applyEnv(config); err != nil {\n\t\treturn err\n\t}\n\n\treturn validate(config)\n}", "func Load(fileName string) (Config, error) {\n\trawConfig := RawConfig{}\n\terr := configor.Load(&rawConfig, fileName)\n\tif err != nil {\n\t\treturn Config{}, errors.Wrapf(err, \"Could not load config from file: '%s'\", fileName)\n\t}\n\n\treturn transformFromRawConfig(rawConfig)\n}", "func LoadConfig(conf interface{}, filename string) (err error) {\n\tvar decoder *json.Decoder\n\tfile := OpenFile(conf, filename)\n\tdefer file.Close()\n\tdecoder = json.NewDecoder(file)\n\tif err = decoder.Decode(conf); err != nil {\n\t\treturn\n\t}\n\tjson.Marshal(&conf)\n\treturn\n}", "func Load(fp string, verbose bool) error {\n\tvar err error\n\tvar uc UnparsedConf\n\tconf, err := ioutil.ReadFile(fp)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = yaml.Unmarshal(conf, &uc); err != nil {\n\t\treturn err\n\t}\n\tC = Conf{\n\t\tNameServer: uc.NameServer,\n\t\tUploadDir: uc.UploadDir,\n\t\tDB: uc.DB,\n\t\tPort: uc.Port,\n\t\tUniURILength: uc.UniURILength,\n\t\tSizeLimit: uc.SizeLimit,\n\t\tFullDoc: uc.FullDoc,\n\t\tDebug: uc.Debug,\n\t}\n\tif verbose {\n\t\tlog.Printf(\"[INFO][System]\\tLoaded configuration file %s :\\n\", fp)\n\t\tlog.Printf(\"[INFO][System]\\tName Server : %s\\n\", C.NameServer)\n\t\tlog.Printf(\"[INFO][System]\\tUpload Directory : %s\\n\", C.UploadDir)\n\t\tlog.Printf(\"[INFO][System]\\tDatabase : %s\\n\", C.DB)\n\t\tlog.Printf(\"[INFO][System]\\tPort : %v\\n\", C.Port)\n\t\tlog.Printf(\"[INFO][System]\\tUni URI Length : %v\\n\", C.UniURILength)\n\t\tlog.Printf(\"[INFO][System]\\tSize Limit : %v Mo\\n\", C.SizeLimit)\n\t\tlog.Printf(\"[INFO][System]\\tFull Documentation : %v\\n\", C.FullDoc)\n\t\tlog.Printf(\"[INFO][System]\\tDebug : %v\\n\", C.Debug)\n\t}\n\treturn err\n}", "func Load() (*Config, error) {\n\tcfg := &Config{}\n\terr := envconfig.Process(\"\", cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.TranslationsPath == \"\" {\n\t\tv, err := promtParameter(\"TRANSLATIONS_PATH\", true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcfg.TranslationsPath = v\n\t}\n\n\tif cfg.TargetAPIAuthorizationKey == \"\" {\n\t\tv, err := promtParameter(\"TARGET_API_AUTHORIZATION_KEY\", true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg.TargetAPIAuthorizationKey = v\n\t}\n\n\tif cfg.TargetAPIHost == \"\" {\n\t\tv, err := promtParameter(\"TARGET_API_HOST\", true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg.TargetAPIHost = v\n\t}\n\n\tif cfg.OrgIDSNCF == \"\" {\n\t\tv, err := promtParameter(\"ORGID_SNCF\", false)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif v == \"\" {\n\t\t\tfmt.Println(fmt.Sprintf(\"Note! Translations won't be uploaded for SNCF\"))\n\t\t}\n\n\t\tcfg.OrgIDSNCF = v\n\t}\n\n\tif cfg.OrgIDThalys == \"\" {\n\t\tv, err := promtParameter(\"ORGID_THALYS\", false)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif v == \"\" {\n\t\t\tfmt.Println(fmt.Sprintf(\"Note! Translations won't be uploaded for THALYS\"))\n\t\t}\n\n\t\tcfg.OrgIDThalys = v\n\t}\n\n\treturn cfg, nil\n}", "func Load(r io.Reader) (*Config, error) {\n\tb, err := io.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not read config: %s\", err)\n\t}\n\n\tc := &Config{}\n\terr = yaml.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not parse config: %s\", err)\n\t}\n\n\treturn c, nil\n}", "func Load() Config {\n\n\tvar config Config\n\tvar configFile *os.File\n\tvar err error\n\n\tif configFile, err = os.Open(\"/usr/local/bin/mailtos3/config.json\"); err != nil {\n\t\t// if config not fund under /usr/local/bin/ try current working dir\n\t\tdir, _ := os.Getwd()\n\t\tconfigFile, err = os.Open(dir + \"/config.json\")\n\t}\n\tdefer configFile.Close()\n\n\tif err != nil {\n\t\tlogger.Log.Printf(\"[ERROR] Unable to load config file, %s\", err)\n\t\t// let mta know that there is a problem with configuration\n\t\tos.Exit(sysexits.EX_CONFIG)\n\t}\n\tjsonParser := json.NewDecoder(configFile)\n\terr = jsonParser.Decode(&config)\n\tif err != nil {\n\t\tlogger.Log.Printf(\"[ERROR] Invalid syntax in config file: %s\", err)\n\t\t// let mta know that there is a problem with configuration\n\t\tos.Exit(sysexits.EX_CONFIG)\n\t}\n\n\tif dupes, found := checkDuplicates(config.Mailboxes); found {\n\t\tlogger.Log.Printf(\"[WARNING] Duplicate mailbox configuration found for user(s): %s. \"+\n\t\t\t\"Only the first configured mailbox will be matched.\", *dupes)\n\t}\n\treturn config\n}", "func LoadConf() (conf Configuration) {\n\tfile, err := os.Open(\"./config/conf.json\")\n\tdefer file.Close()\n\tif err != nil {\n\t\tfmt.Println(\"read json file error:\", err)\n\t}\n\tdecoder := json.NewDecoder(file)\n\te := decoder.Decode(&conf)\n\tif e != nil {\n\t\tfmt.Println(\"parse json error:\", e)\n\t}\n\treturn conf\n}", "func (self *JsonConfig) Load() (err error) {\n\tvar data []byte = make([]byte, 1024)\n\tif data, err = ioutil.ReadFile(self.Path); err != nil {\n\t\treturn err\n\t}\n\tout, err := unmarshalJson(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tself.Configurable.Reset(out)\n\treturn nil\n}", "func loadConfiguration() Config {\n\tvar conf Config\n\t_, b, _, _ := runtime.Caller(0)\n\tbasepath := filepath.Dir(b)\n\tfilename := fmt.Sprintf(\"%s/config.json\", basepath)\n\tconfigFile, err := os.Open(filename)\n\tdefer configFile.Close()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n\tjsonParser := json.NewDecoder(configFile)\n\tjsonParser.Decode(&conf)\n\t// Use ENV var if it's set\n\tconf.Port = getEnvIntValue(\"Port\", conf.Port)\n\tconf.ReqPerSec = getEnvIntValue(\"ReqPerSec\", conf.ReqPerSec)\n\tconf.ReqPerMin = getEnvIntValue(\"ReqPerMin\", conf.ReqPerMin)\n\tconf.ReqPerHour = getEnvIntValue(\"ReqPerHour\", conf.ReqPerHour)\n\tconf.RedisHost = getEnvStrValue(\"RedisHost\", conf.RedisHost)\n\tconf.RedisPort = getEnvIntValue(\"RedisPort\", conf.RedisPort)\n\n\treturn conf\n}", "func Load(fileName string) (Config, error) {\n\tcfg := DefaultConfig\n\tif fileName == \"\" {\n\t\treturn cfg, nil\n\t}\n\tconfigBytes, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\treturn DefaultConfig, err\n\t}\n\treturn LoadBytes(configBytes)\n}", "func Load() *Config {\n\tif savedConfig != nil {\n\t\treturn savedConfig\n\t}\n\n\tif os.Getenv(envUseEnvConfig) == \"true\" {\n\t\tlog.Println(\"Info: [config] Load from env\")\n\t\tsavedConfig = loadFromEnv()\n\t} else {\n\t\tpath := os.Getenv(envConfigPath)\n\t\tif len(path) == 0 {\n\t\t\tpath = defaultConfigPath\n\t\t}\n\t\tlog.Println(\"Info: [config] Load from file: \", path)\n\t\tsavedConfig = loadFromConfig(path)\n\t}\n\n\tlog.Printf(\"Info: [config] Load, load: %+v\\n\", savedConfig)\n\treturn savedConfig\n}", "func Load(file string) *Config {\r\n\tdata, err := ioutil.ReadFile(file)\r\n\tif err != nil {\r\n\t\tlogrus.WithError(err).Fatal(\"Error loading configuration file\")\r\n\t}\r\n\r\n\tvar config Config\r\n\tif err := yaml.Unmarshal(data, &config); err != nil {\r\n\t\tlogrus.WithError(err).Fatal(\"Error loading parsing configuration file\")\r\n\t}\r\n\r\n\tif l, ok := logLevel[config.Loglevel]; ok {\r\n\t\tlogrus.SetLevel(l)\r\n\t}\r\n\r\n\tif config.Auth.PrivateKeyPath == \"\" {\r\n\t\tconfig.Auth.PrivateKeyPath = \"secrets/token.private\"\r\n\t}\r\n\r\n\tif config.Auth.PublicKeyPath == \"\" {\r\n\t\tconfig.Auth.PublicKeyPath = \"secrets/token.public\"\r\n\t}\r\n\r\n\tskipWine = config.SkipWine\r\n\r\n\treturn &config\r\n}", "func (config *ScrabblerConfiguration) Load() {\n\tlog.Do.Info(\"Load configuration...\")\n\tvar configFilePath string\n\tvar tmpScreabblerConfiguration ScrabblerConfiguration\n\n\tif config.ConfigFilePath != \"\" {\n\t\tconfigFilePath = config.ConfigFilePath\n\t} else {\n\t\tconfigFilePath = DefaultConfigPath\n\t}\n\n\tif _, err := toml.DecodeFile(configFilePath, &tmpScreabblerConfiguration); err != nil {\n\t\tlog.Do.Error(err)\n\t}\n\n\ttmpConfigStructureValues := reflect.ValueOf(&tmpScreabblerConfiguration).Elem()\n\trealConfigStructureValues := reflect.ValueOf(config).Elem()\n\trealConfigStructureTypes := reflect.TypeOf(*config)\n\n\tfor indexRealConfigStructure := 0; indexRealConfigStructure < realConfigStructureValues.NumField(); indexRealConfigStructure++ {\n\t\tvar fieldName string\n\t\tvar field reflect.Value\n\n\t\t// Get field from real configuration structure\n\t\tfieldName = realConfigStructureTypes.Field(indexRealConfigStructure).Name\n\t\tfield = realConfigStructureValues.FieldByName(fieldName)\n\n\t\t// Check if field is empty\n\t\tif isEmpty(field.Interface()) && field.CanSet() {\n\t\t\tconfig.Lock()\n\t\t\t// Try to get field from tmp configuration structure (form configuration file)\n\t\t\ttmpField := tmpConfigStructureValues.FieldByName(fieldName)\n\t\t\tf := tmpField.Interface()\n\t\t\tval := reflect.ValueOf(f)\n\n\t\t\t// Try to set values to global configuration structure\n\t\t\tswitch field.Kind() {\n\t\t\tcase reflect.Bool:\n\t\t\t\tfield.SetBool(val.Bool())\n\t\t\t\tbreak\n\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\tfield.SetInt(val.Int())\n\t\t\t\tbreak\n\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t\t\tfield.SetUint(val.Uint())\n\t\t\t\tbreak\n\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\tfield.SetFloat(val.Float())\n\t\t\t\tbreak\n\t\t\tcase reflect.Complex64, reflect.Complex128:\n\t\t\t\tfield.SetComplex(val.Complex())\n\t\t\t\tbreak\n\t\t\tcase reflect.String:\n\t\t\t\tfield.SetString(val.String())\n\t\t\t\tbreak\n\t\t\tcase reflect.Array:\n\t\t\t\tbreak\n\t\t\tcase reflect.Slice:\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tconfig.Unlock()\n\t\t}\n\t}\n}", "func Load(filename string) (*Configfile, error) {\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tabs, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg, err := Parse(b)\n\tif err != nil {\n\t\treturn cfg, err\n\t}\n\tcfg.filename = abs\n\tif cfg.Repos.Dir == \"\" {\n\t\tcfg.Repos.Dir = filepath.Join(filepath.Dir(abs), \"cache\")\n\t}\n\n\tif cfg.Workspace == nil {\n\t\tcfg.Workspace = &Workspace{}\n\t}\n\n\tif cfg.Workspace.Dir == \"\" {\n\t\tcfg.Workspace.Dir = filepath.Join(filepath.Dir(abs), \"workspace\")\n\t}\n\n\treturn cfg, nil\n}", "func LoadConfiguration(path string, dest interface{}) error {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tdecoder := json.NewDecoder(file)\n\n\terr = decoder.Decode(dest)\n\treturn err\n}", "func (c *Config) Load(filename string) (err error) {\n\tlog.Println(\"[DEBUG] Load\", filename)\n\n\terr = c.ensureFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbody, err := c.readFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(body, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(filePath string) error {\n\tConfig = new(config)\n\n\tif err := Config.load(filePath); err != nil {\n\t\treturn err\n\t}\n\n\treturn Config.verifySettings()\n}", "func loadConfig() {\n\tfile, err := os.Open(\"config.json\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Cannot open config file\", err)\n\t}\n\tdecoder := json.NewDecoder(file)\n\tconfig = Configuration{}\n\terr = decoder.Decode(&config)\n\tif err != nil {\n\t\tlog.Fatalln(\"Cannot get configuration from file\", err)\n\t}\n}", "func Load(filename string, result interface{}) error {\n\tfile, err := os.Open(filename)\n\tdefer file.Close()\n\tif err != nil {\n\t\tcf, err := os.Create(filename)\n\t\tdefer cf.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn err\n\t\t}\n\t\tdata, err := json.MarshalIndent(result, \"\", \" \")\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn err\n\t\t}\n\t\tcf.Write(data)\n\t\tmsg := \"config file not exist, created\"\n\t\tlog.Println(msg)\n\t\treturn errors.New(msg)\n\t}\n\tdec := json.NewDecoder(file)\n\terr = dec.Decode(&result)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn err\n}", "func Load(cli model.Cli, version string) (*Config, error) {\n\tvar err error\n\tvar cfg = Config{\n\t\tCli: cli,\n\t\tApp: model.App{\n\t\t\tID: \"diun\",\n\t\t\tName: \"Diun\",\n\t\t\tDesc: \"Docker image update notifier\",\n\t\t\tURL: \"https://github.com/crazy-max/diun\",\n\t\t\tAuthor: \"CrazyMax\",\n\t\t\tVersion: version,\n\t\t},\n\t\tDb: model.Db{\n\t\t\tPath: \"diun.db\",\n\t\t},\n\t\tWatch: model.Watch{\n\t\t\tWorkers: 10,\n\t\t\tSchedule: \"0 * * * *\",\n\t\t\tFirstCheckNotif: utl.NewFalse(),\n\t\t},\n\t}\n\n\tif _, err = os.Lstat(cli.Cfgfile); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to open config file, %s\", err)\n\t}\n\n\tbytes, err := ioutil.ReadFile(cli.Cfgfile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read config file, %s\", err)\n\t}\n\n\tif err := yaml.UnmarshalStrict(bytes, &cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to decode into struct, %v\", err)\n\t}\n\n\tif err := cfg.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &cfg, nil\n}", "func LoadCfg(path string) Config {\r\n\tjsonBytes, err := ioutil.ReadFile(path)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tres := Config{}\r\n\terr = json.Unmarshal(jsonBytes, &res)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\treturn res\r\n}", "func Load() (*Config, error) {\n\tv := viper.New()\n\n\t// Set config name and path.\n\tv.SetConfigName(\"config\")\n\tv.AddConfigPath(\".\")\n\n\t// Read in config file.\n\terr := v.ReadInConfig()\n\tif err != nil {\n\t\t// FIXME - does not require a config file for now.\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); !ok {\n\t\t\treturn nil, errors.Wrap(err, \"failed to read in config\")\n\t\t}\n\t}\n\n\t// Load in the default config values.\n\tv.SetDefault(\"server.address\", \":8000\")\n\n\t// Marshall config options into Config struct.\n\tvar cfg = Config{}\n\tif err := v.Unmarshal(&cfg); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal config options\")\n\t}\n\n\treturn &cfg, nil\n}", "func Load() error {\n\tfile, err := os.Open(\".env/config.json\")\n\tdefer file.Close()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparser := json.NewDecoder(file)\n\terr = parser.Decode(&config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(config.Backend.MongoDB.URI) < 1 {\n\t\tconfig.Backend.MongoDB.URI = \"mongodb://127.0.0.1:27017\"\n\t}\n\n\tif len(config.Backend.MongoDB.Database) < 1 {\n\t\tconfig.Backend.MongoDB.Database = \"ikuta\"\n\t}\n\n\tif len(config.HTTP.Address) < 1 {\n\t\tconfig.HTTP.Address = \":7136\"\n\t}\n\n\treturn nil\n}", "func Load(r io.Reader) (*Config, error) {\n\tb, err := io.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read bytes from reader: %w\", err)\n\t}\n\n\tvar cfg Config\n\tif err = yaml.Unmarshal(b, &cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal bytes to config: %w\", err)\n\t}\n\n\treturn &cfg, nil\n}", "func Load() (*Cfg, error) {\n\tlog.Debug(\"loading\")\n\tvar v Cfg\n\tvar err error\n\tvar store s3local.Store\n\tlocation := os.Getenv(\"GOLPJE_STORAGE\")\n\tif location == \"\" {\n\t\tlog.Info(\"using current directory\")\n\t\treturn nil, errors.New(\"not implemented yet\")\n\n\t} else if location == \"s3://\" {\n\t\tlog.Info(\"using s3\")\n\t\tstore, err = s3local.New(s3local.Config{\n\t\t\tType: \"s3\",\n\t\t\tSettings: map[string]string{\n\t\t\t\t\"host\": os.Getenv(\"S3_HOST\"),\n\t\t\t\t\"secretaccesskey\": os.Getenv(\"S3_SECRET_ACCESS_KEY\"),\n\t\t\t\t\"accesskeyid\": os.Getenv(\"S3_ACCESS_KEY_ID\"),\n\t\t\t\t\"bucket\": os.Getenv(\"S3_BUCKET\"),\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Error(\"Creating s3 store failed\")\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tlog.Info(\"using filesystem\")\n\t\tstore, _ = s3local.New(s3local.Config{\n\t\t\tType: \"local\",\n\t\t\tSettings: map[string]string{\n\t\t\t\t\"path\": location,\n\t\t\t},\n\t\t})\n\t}\n\n\tv.Store = store\n\tlog.Debug(\"loading golpje.toml\")\n\tf, err := v.Store.Read(\"golpje.toml\")\n\tif err != nil {\n\t\tlog.WithField(\"err\", err).Warning(\"could not read golpje.toml\")\n\t\treturn nil, err\n\t}\n\tlog.WithField(\"config\", string(f)).Debug(\"decoding golpje.toml\")\n\t_, err = toml.Decode(string(f), &v)\n\tif err != nil {\n\t\tlog.WithField(\"err\", err).Warning(\"could not decode golpje.toml\")\n\t\treturn nil, err\n\t}\n\tlog.Debug(\"loaded config\")\n\n\treturn &v, nil\n}", "func Load() (Config, error) {\n\tvar cfg Config\n\tcfg.AwsRegion = findEnvVar(\"AWS_REGION\")\n\treturn cfg, nil\n}", "func LoadConfiguration() Configuration {\n\tvar configuration Configuration\n\tconfigFile, err := os.Open(\"conf.json\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tparser := json.NewDecoder(configFile)\n\tparser.Decode(&configuration)\n\n\tconfigFile.Close()\n\n\treturn configuration\n}", "func Load(path string, cfg *Config) error {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"faild to open configuration file\")\n\t}\n\n\terr = yaml.NewDecoder(f).Decode(cfg)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"faild to decode\")\n\t}\n\n\treturn nil\n}", "func Load(r io.Reader) (*Config, error) {\n\tvar c Config\n\tif err := defaults.Set(&c); err != nil {\n\t\treturn nil, err\n\t}\n\tc.init()\n\tvar raw map[string]any\n\tif _, err := toml.NewDecoder(r).Decode(&raw); err != nil {\n\t\treturn nil, errors.Wrap(err, \"config: error decoding toml data\")\n\t}\n\tif err := c.parse(raw); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func Load(configFile string, p Parser) {\n\n\tjsonBytes := []byte(`{\"Database\":{\"Type\":\"Bolt\",\"Bolt\":{\"Path\":\"gowebapp.db\"}},\"Email\":{\"Username\":\"\",\"Password\":\"\",\"Hostname\":\"\",\"Port\":25,\"From\":\"\"},\"Recaptcha\":{\"Enabled\":false,\"Secret\":\"\",\"SiteKey\":\"\"},\"Server\":{\"Hostname\":\"\",\"UseHTTP\":true,\"UseHTTPS\":false,\"HTTPPort\":8080,\"HTTPSPort\":443,\"CertFile\":\"tls/server.crt\",\"KeyFile\":\"tls/server.key\"},\"Session\":{\"SecretKey\":\"@r4B?EThaSEh_drudR7P_hub=s#s2Pah\",\"Name\":\"gosess\",\"Options\":{\"Path\":\"/\",\"Domain\":\"\",\"MaxAge\":28800,\"Secure\":false,\"HttpOnly\":true}},\"Template\":{\"Root\":\"base\",\"Children\":[\"partial/menu\",\"partial/footer\"]},\"View\":{\"BaseURI\":\"/\",\"Extension\":\"tmpl\",\"Folder\":\"template\",\"Name\":\"blank\",\"Caching\":true}}`)\n\t// Parse the config\n\tif err := p.ParseJSON(jsonBytes); err != nil {\n\t\tlog.Fatalln(\"Could not parse %q: %v\", configFile, err)\n\t}\n}", "func Load(data []byte) (*clientcmdapi.Config, error) {\n\tconfig := clientcmdapi.NewConfig()\n\t// if there's no data in a file, return the default object instead of failing (DecodeInto reject empty input)\n\tif len(data) == 0 {\n\t\treturn config, nil\n\t}\n\tdecoded, _, err := clientcmdlatest.Codec.Decode(data, &schema.GroupVersionKind{Version: clientcmdlatest.Version, Kind: \"Config\"}, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn decoded.(*clientcmdapi.Config), nil\n}", "func LoadConfiguration(filename string) Config {\n\tvar config Config\n\tconfigFile, err := os.Open(filename)\n\tdefer configFile.Close()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tjsonParser := json.NewDecoder(configFile)\n\terr = jsonParser.Decode(&config)\n\treturn config\n}", "func Load(l log.Logger) (*Config, error) {\n\tlogger = l\n\t// return loadDefault()\n\t// return loadFromSecretsPath()\n\treturn loadFromEnvvar()\n\n}", "func (g *Gonf) Load() error {\n\tb, err := ioutil.ReadFile(g.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg := map[string]interface{}{}\n\tif err := json.Unmarshal(b, &cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// forbids access to Get/Set local and HTTP while reloading\n\tg.confLock.Lock()\n\tdefer g.confLock.Unlock()\n\tg.conf = cfg\n\n\treturn g.load(cfg, []string{}, []otoFlag{})\n}", "func (config *Config) Load(path string) {\n\tif dat, err := ioutil.ReadFile(path); err == nil {\n\t\tif err := json.Unmarshal(dat, config); err != nil {\n\t\t\tlog.Printf(\"%v\", err)\n\t\t}\n\t} else {\n\t\tlog.Printf(\"Configfile %s doesn't exist\", path)\n\t}\n}", "func Load_Config(path string) ServiceConfiguration {\n\ts := ServiceConfiguration{}\n\tb, err := ioutil.ReadFile(path)\n\tcheckerr(err)\n\n\terr = json.Unmarshal(b, &s)\n\tcheckerr(err)\n\n\treturn s\n}", "func (c *Config) LoadConfig(path string, v interface{}) error {\n // get config map\n resMap, err := c.LoadFile(path)\n if err != nil {\n return err\n }\n // parse map to struct\n err = c.parseMap(resMap, v)\n if err != nil {\n return err\n }\n return nil\n}", "func (me *DB) Load(cluster string) (*pb.Configuration, error) {\n\tconfb := make([]byte, 0)\n\terr := me.session.Query(\"SELECT conf FROM \"+tblConf+\" WHERE cluster=?\",\n\t\tcluster).Scan(&confb)\n\tif err != nil && err.Error() == gocql.ErrNotFound.Error() {\n\t\treturn &pb.Configuration{}, nil\n\t}\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, 500, errors.E_database_error)\n\t}\n\n\tconf := &pb.Configuration{}\n\tif err := proto.Unmarshal(confb, conf); err != nil {\n\t\treturn nil, errors.Wrap(err, 500, errors.E_proto_marshal_error)\n\t}\n\tconf.Cluster = cluster\n\treturn conf, nil\n}", "func Load() (Config, error) {\n\t// STEP 1: try to load config file from SCW_CONFIG_PATH\n\tconfigPath := os.Getenv(scwConfigPathEnv)\n\tif configPath != \"\" {\n\t\tcontent, err := ioutil.ReadFile(configPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot read config file %s: %s\", scwConfigPathEnv, err)\n\t\t}\n\t\tconfV1, err := unmarshalConfV1(content)\n\t\tif err == nil {\n\t\t\t// do not migrate automatically when using SCW_CONFIG_PATH\n\t\t\tlogger.Warningf(\"loaded config V1 from %s: config V1 is deprecated, please switch your config file to the V2: %s\", configPath, documentationLink)\n\t\t\treturn confV1.toV2().catchInvalidProfile()\n\t\t}\n\t\tconfV2, err := unmarshalConfV2(content)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"content of config file %s is invalid: %s\", configPath, err)\n\t\t}\n\n\t\tlogger.Infof(\"successfully loaded config V2 from %s\", configPath)\n\t\treturn confV2.catchInvalidProfile()\n\t}\n\n\t// STEP 2: try to load config file V2\n\tv2Path, v2PathOk := GetConfigV2FilePath()\n\tif v2PathOk && fileExist(v2Path) {\n\t\tfile, err := ioutil.ReadFile(v2Path)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot read config file: %s\", err)\n\t\t}\n\n\t\tconfV2, err := unmarshalConfV2(file)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"content of config file %s is invalid: %s\", v2Path, err)\n\t\t}\n\n\t\tlogger.Infof(\"successfully loaded config V2 from %s\", v2Path)\n\t\treturn confV2.catchInvalidProfile()\n\t}\n\n\t// STEP 3: try to load config file V1\n\tlogger.Debugf(\"no config V2 found, fall back to config V1\")\n\tv1Path, v1PathOk := GetConfigV1FilePath()\n\tif !v1PathOk {\n\t\tlogger.Infof(\"config file not found: no home directory\")\n\t\treturn (&configV2{}).catchInvalidProfile()\n\t}\n\tfile, err := ioutil.ReadFile(v1Path)\n\tif err != nil {\n\t\tlogger.Infof(\"cannot read config file: %s\", err)\n\t\treturn (&configV2{}).catchInvalidProfile() // ignore if file doesn't exist\n\t}\n\tconfV1, err := unmarshalConfV1(file)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"content of config file %s is invalid json: %s\", v1Path, err)\n\t}\n\n\t// STEP 4: migrate V1 config to V2 config file\n\tif v2PathOk {\n\t\terr = migrateV1toV2(confV1, v2Path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn confV1.toV2().catchInvalidProfile()\n}", "func Load() (*Config, error) {\n\tvar config Config\n\terr := envconfig.Process(\"BENJERRY\", &config)\n\treturn &config, err\n}", "func LoadConfig(path string) *Config {\n\tdefaultConfig := defaultConfig()\n\tfmt.Println(path)\n\tfmt.Println(defaultConfig)\n\tif _, err := toml.DecodeFile(path, defaultConfig); err != nil {\n\t\tlog.Fatal(\"error\", err.Error())\n\t}\n\tfmt.Println(defaultConfig)\n\treturn defaultConfig\n}", "func Load(appName string) (*Configuration, error) {\n\tvar cfg Configuration\n\tif err := envconfig.Process(appName, &cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"error loading configuration for %s: %s\", appName, err)\n\t}\n\n\treturn &cfg, nil\n}", "func Load(configFile string) (*Config, error) {\n\tlog.Printf(\"[config][Load] Reading configuration from configFile=%s\", configFile)\n\tcfg, err := readConfigurationFile(configFile)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, ErrConfigFileNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\tcfg.filePath = configFile\n\tcfg.UpdateLastFileModTime()\n\treturn cfg, nil\n}", "func (p Config) Load(file string) Config {\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar config Config\n\tif err := config.ParseYAML(data); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn config\n}", "func (c *Config) Load(r io.Reader) error {\n\tbytes, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to read config: %v\", err)\n\t}\n\n\thashChanged, err := c.unmarshal(bytes)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to unmarshal config: %v\", err)\n\t}\n\n\tif !hashChanged {\n\t\treturn nil\n\t}\n\n\t// Config actually changed... log this and notify observers\n\tdata := (*configData)(atomic.LoadPointer(&c.data))\n\tlog.Infof(\"[Config] Initialised config, loaded hash: %s\", data.hash)\n\n\t// Notify observers\n\tc.observersMtx.RLock()\n\tdefer c.observersMtx.RUnlock()\n\tfor _, ch := range c.observers {\n\t\t// Non-blocking send\n\t\tselect {\n\t\tcase ch <- true:\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *store) Load() *configstore {\n\treturn s.UntypedLoad(storeName).(*configstore)\n}", "func Load(s string) (*Config, error) {\n\tconfig := defaultConfig\n\n\tif err := yaml.UnmarshalStrict([]byte(s), &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := config.validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid config: %v\", err)\n\t}\n\n\treturn &config, nil\n}" ]
[ "0.80342543", "0.79178953", "0.76763994", "0.76631093", "0.7566076", "0.7560627", "0.7531301", "0.75200117", "0.751207", "0.7468938", "0.74641955", "0.7426541", "0.7426379", "0.73921025", "0.7327033", "0.7315701", "0.7297896", "0.7289633", "0.72649884", "0.7218762", "0.7207211", "0.7198609", "0.71965104", "0.7177329", "0.71685004", "0.7158905", "0.7154653", "0.71406066", "0.71313584", "0.7120512", "0.7118618", "0.7114387", "0.71096975", "0.709645", "0.70811844", "0.7072527", "0.7056117", "0.70522845", "0.7032392", "0.70291376", "0.7026575", "0.7020979", "0.70187306", "0.7017858", "0.7016009", "0.7015538", "0.7013414", "0.70129746", "0.7010247", "0.6996589", "0.69944364", "0.6990975", "0.6989984", "0.69810253", "0.6970438", "0.69690585", "0.6967132", "0.6938153", "0.69352657", "0.6928934", "0.6923556", "0.6910239", "0.6910236", "0.69044065", "0.69016176", "0.6901105", "0.6900465", "0.6892136", "0.68880063", "0.6882105", "0.68800944", "0.6874119", "0.6869325", "0.6865981", "0.6864667", "0.6863292", "0.68605", "0.68516856", "0.6850884", "0.68502885", "0.68426824", "0.6841287", "0.6838956", "0.6838803", "0.68312657", "0.68208784", "0.6815629", "0.6811681", "0.6806459", "0.6804861", "0.6804204", "0.6795637", "0.6793133", "0.6790605", "0.67797214", "0.6779705", "0.67751604", "0.6766766", "0.67594045" ]
0.6871756
73
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
func singleNumber(nums []int) int { ones, twos := 0, 0 for i := 0; i < len(nums); i++ { ones = (ones ^ nums[i]) & ^twos twos = (twos ^ nums[i]) & ^ones } return ones }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func repeatedNTimes(A []int) int {\n m := make(map[int]int)\n for _, v := range A {\n m[v]++\n if m[v] > 1 {\n return v\n }\n }\n return 0\n}", "func repeatedNTimes(A []int) int {\n cache := map[int]bool {}\n for _,a := range A {\n if cache[a] {\n return a\n }\n cache[a] = true\n }\n return -1\n}", "func detectRepeats(numbers []int) error {\n searched_nums := map[int]int{}\n\n for i, num := range numbers {\n _, searched := searched_nums[num]\n\n num_count := 0\n if !searched {\n for j := i; j < len(numbers); j++ {\n if numbers[j] == num {\n num_count++\n }\n\n if num_count > 3 {\n return fmt.Errorf(\"%d found >3 times.\", numbers[j])\n }\n }\n searched_nums[num] = num\n }\n }\n return nil\n}", "func FindDuplicates(input []int) int {\n\t// using XOR\n\tresult := 0\n\t//for _, val := range input {\n\t//result ^= val\n\t//}\n\t//for key, _ := range input {\n\t//result ^= key\n\t//}\n\n\t// using constant space\n\tfor _, val := range input {\n\t\tif input[val] < 0 {\n\t\t\treturn input[val]\n\t\t}\n\t\tinput[val] = input[val] * -1\n\t}\n\treturn result\n}", "func FindFirstRepeated(in []int) (int, error) {\n\n\thmap := make(map[int]bool)\n\n\tfor _, val := range in {\n\t\tif hmap[val] == true {\n\t\t\treturn val, nil\n\t\t} else {\n\t\t\thmap[val] = true\n\t\t}\n\t}\n\n\treturn 0, errFindFirstRepeated\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tn := len(A)\n\tsum := n * (n + 1) / 2\n\n\tisSeen := make(map[int]bool)\n\n\tfor _, el := range A {\n\t\tdup := isSeen[el]\n\t\tif dup {\n\t\t\treturn 0\n\t\t}\n\t\tisSeen[el] = true\n\t\tsum -= el\n\t}\n\tif sum != 0 {\n\t\treturn 0\n\t}\n\treturn 1\n}", "func getDuplicate(numbers []int) int {\n\tfor _, num1 := range numbers {\n\t\tcheck := false\n\t\tfor _, num2 := range numbers {\n\t\t\tflag := num1 == num2\n\t\t\tif flag && check {\n\t\t\t\treturn num1\n\t\t\t} else if flag {\n\t\t\t\tcheck = true\n\t\t\t}\n\t\t}\n\t}\n\treturn 0\n}", "func uniqueOccurrences(arr []int) bool {\n\toccCount := make(map[int]int)\n\tfor _, val := range arr {\n\t\tc, ok := occCount[val]\n\t\tif !ok {\n\t\t\toccCount[val] = 1\n\t\t} else {\n\t\t\toccCount[val] = c + 1\n\t\t}\n\t}\n\tdistincNumCount := len(occCount) // all repeat numbers are collapsed\n\tdistinctOcc := make(map[int]int)\n\tfor val, occ := range occCount {\n\t\tdistinctOcc[occ] = val\n\t}\n\treturn len(distinctOcc) == distincNumCount\n}", "func findDuplicate(arr []int) {\n\t// Vars\n\tarrayCount := len(arr) // input array counts\n\tvisited := []int{} // visited array\n\n\t// First loop to iterate the array\n\tfor i := 0; i < arrayCount; i++ {\n\n\t\t// Check visited var with current element\n\t\tfor _, v := range visited {\n\t\t\tif v == arr[i] {\n\t\t\t\tfmt.Printf(\"Found duplicates: %v\\n\", v)\n\t\t\t}\n\t\t}\n\n\t\t// Flag into visited var for each element\n\t\tvisited = append(visited, arr[i])\n\t}\n}", "func FindDuplicated(in []int) []int {\n\n\thm := make(map[int]int)\n\n\tfor _, value := range in {\n\t\thm[value] += 1\n\t}\n\n\tvar res []int\n\n\tfor key, val := range hm {\n\t\tif val >= 2 {\n\t\t\tres = append(res, key)\n\t\t}\n\t}\n\n\treturn res\n}", "func FindRepeatNumber(nums []int) int {\n\texist := make(map[int]bool)\n\tfor i := range nums {\n\t\tif _, ok := exist[nums[i]]; ok {\n\t\t\treturn nums[i]\n\t\t}\n\t\texist[nums[i]] = true\n\t}\n\treturn 0\n}", "func main() {\n\t// input := []int{1, 2, 2, 1, 1, 3}\n\t// input := []int{1, 2}\n\tinput := []int{-3, 0, 1, -3, 1, 1, 1, -3, 10, 0}\n\toutput := uniqueOccurrences(input)\n\tfmt.Println(output)\n}", "func main() {\n\tnums := []int{1,3,5,2,6,4,5}\n\tfmt.Println(findDuplicate(nums))\n\tnums2 := []int{3,1,3,4,2}\n\tfmt.Println(findDuplicate(nums2))\n}", "func FirstDuplicateValue(array []int) int {\n\tm := make(map[int]int)\n\n\tfor i := 0; i < len(array); i++ {\n\t\tm[array[i]]++\n\n\t\tif m[array[i]] == 2 {\n\t\t\treturn array[i]\n\t\t}\n\t}\n\treturn -1\n}", "func migratoryBirds(arr []int32) int32 {\n repetitions := make([]int32, 5)\n\n for i := int32(0); i < 5; i++ {\n for j := 0; j < len(arr); j++ {\n if (i + 1) == arr[j] {\n repetitions[i]++\n }\n }\n }\n\n var winner int32\n var higher int32 = repetitions[0]\n\n for _, value := range repetitions {\n if higher < value {\n higher = value\n }\n }\n\n for index, value := range repetitions {\n if higher == value {\n winner = int32(index) + 1\n break\n }\n }\n return winner\n}", "func findDuplicate(nums []int) int {\n\tif nums == nil || len(nums) == 0 {\n\t\treturn -1\n\t}\n\tslow, fast := nums[0], nums[nums[0]]\n\tfor slow != fast {\n\t\tslow, fast = nums[slow], nums[nums[fast]]\n\t}\n\n\tslow = 0\n\tfor slow != fast {\n\t\tslow, fast = nums[slow], nums[fast]\n\t}\n\treturn slow\n}", "func Solution(X int, A []int) int {\n // write your code in Go 1.4\n bucket := make([]bool, X + 1)\n count := 0\n \n for i, n := range A {\n if (bucket[n] == false) {\n bucket[n] = true\n count++\n }\n \n if (count == X) {\n return i\n }\n\t}\n\t\n\treturn -1\n}", "func removeDuplicates(nums []int) int {\n size := len(nums)\n if size == 0 {return 0}\n fixedNum := 1\n for i:=1; i<size; i++ {\n if nums[i] != nums[i-1] {\n nums[fixedNum] = nums[i]\n fixedNum++\n }\n }\n return fixedNum\n}", "func singleNumberA(nums []int) int {\n result:=0\n for _,data := range nums{\n result^=data\n }\n return result\n}", "func Gimme(array [3]int) int {\n\ts := make([]int, len(array))\n\tcopy(s, array[:])\n\n\tsort.Ints(s)\n\n\tvar middle int\n\tfor i, value := range array {\n\t\tif value == s[1] {\n\t\t\tmiddle = i\n\t\t}\n\t}\n\treturn middle\n}", "func main() {\n\tnums := []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}\n\tlength := removeDuplicates(nums)\n\tfor i := 0; i < length; i++ {\n\t\tfmt.Printf(\"%d \", nums[i])\n\t}\n\n\tnums = []int{1, 1, 1, 1, 1, 1}\n\tlength = removeDuplicates(nums)\n\tfor i := 0; i < length; i++ {\n\t\tfmt.Printf(\"%d \", nums[i])\n\t}\n\n\tnums = []int{1}\n\tlength = removeDuplicates(nums)\n\tfor i := 0; i < length; i++ {\n\t\tfmt.Printf(\"%d \", nums[i])\n\t}\n}", "func containsNearbyDuplicate(nums []int, k int) bool {\n m := make(map[int]int, 0)\n for i := 0; i < len(nums); i++ {\n if _, ok := m[nums[i]]; ok {\n if i - m[nums[i]] <= k {\n return true\n }\n }\n m[nums[i]] = i\n }\n return false\n}", "func findDup(ints []int) (dup int) {\n\tvar start, end, cycle int\n\n\tstart = len(ints) - 1\n\tfor _ = range ints {\n\t\tstart = ints[start]\n\t}\n\tend = ints[start]\n\tcycle++\n\tfor {\n\t\tend = ints[end]\n\t\tcycle++\n\t\tif start == end {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tstart = len(ints) - 1\n\tend = start\n\tfor i := 0; i < cycle; i++ {\n\t\tend = ints[end]\n\t}\n\tfor start != end {\n\t\tstart = ints[start]\n\t\tend = ints[end]\n\t}\n\treturn start\n}", "func NoRepeated(numbersInput []int) []int {\n\n\tnumbersInput = algoritms.Quick_sort(numbersInput)\n\n\tr := make([]int, 0, len(numbersInput))\n\tr = append(r, numbersInput[0])\n\n\tfor _, number := range numbersInput {\n\t\trTemp := r\n\t\tsearchResult := algoritms.BinarySearch(rTemp, number)\n\n\t\t//Add number if not present\n\t\tif searchResult == -1 {\n\t\t\tr = append(r, number)\n\t\t}\n\t}\n\treturn r\n}", "func singleNumberB(nums []int) int {\n \n mp := make(map[int]int)\n result:= 0\n for _,data := range nums{\n if _,exist := mp[data]; exist{ //if element exist we remove the elemtn\n delete(mp, data)\n \n }else{\n mp[data] = data\n }\n\t}\n\t//really O(1) since there's always one element left\n for _, data := range mp{ \n result = data\n }\n return result \n}", "func uniqueNumber(slice []int) int {\n\tunique := slice[0]\n\tfor i := 1; i < len(slice); i++ {\n\t\tunique ^= slice[i]\n\t}\n\treturn unique\n}", "func singleNumber(nums []int) int {\n\tones, twos := 0, 0\n\tfor i := range nums {\n\t\tones = (ones ^ nums[i]) & (^twos)\n\t\ttwos = (twos ^ nums[i]) & (^ones)\n\t}\n\treturn ones\n}", "func SimpleRemoveDuplicates(arr []int) []int {\n\t//..\n\tpocket := make([]int, 0)\n\tpocket = append(pocket, arr...)\n\n\tfor index, num := range pocket {\n\t\tif contains(pocket, num) == true {\n\t\t\tfmt.Println(\"pocket: \", pocket)\n\t\t\tfmt.Println(\"pocket[index]: \", pocket[index:])\n\t\t\tpocket = pocket[index:]\n\t\t}\n\t}\n\n\t// for _, item := range arr {\n\t// \tif contains(pocket, item) == true {\n\t// \t\tcontinue\n\t// \t} else {\n\t// \t\tpocket = append(pocket, item)\n\t// \t}\n\t// }\n\treturn pocket\n}", "func RemoveDuplicates(arr []int) []int {\n\tisDuplicate := make(map[int]bool)\n\tres := make([]int, 0, 1)\n\tfor _, val := range arr {\n\t\tif !isDuplicate[val] {\n\t\t\tisDuplicate[val] = true\n\t\t\tres = append(res, val)\n\t\t}\n\t}\n\treturn res\n}", "func HasRepeat(arr []int) bool {\n\n\tcheckRepeat := make(map[int]bool)\n\n\tif len(arr) <= 1 {\n\t\treturn false\n\t}\n\n\tfor _, val := range arr {\n\t\tif checkRepeat[val] == true {\n\t\t\treturn true\n\t\t}\n\t\tcheckRepeat[val] = true\n\t}\n\treturn false\n\n}", "func singleNumber(nums []int) int {\n\tt := make(map[int]int)\n\n\tfor _, v := range nums {\n\t\tt[v]++\n\t}\n\n\tfor v, c := range t {\n\t\tif c == 1 {\n\t\t\treturn v\n\t\t}\n\t}\n\n\treturn 0\n}", "func singleNumber(nums []int) []int {\n\tbitmap := 0\n\tfor _, num := range nums {\n\t\tbitmap = bitmap ^ num\n\t}\n\tdiff, x := bitmap&(-bitmap), 0\n\tfor _, num := range nums {\n\t\tif num&diff != 0 {\n\t\t\tx = x ^ num\n\t\t}\n\t}\n\treturn []int{x, bitmap ^ x}\n}", "func minIncrementForUnique(A []int) int {\n\tarr := [80000]int{}\n\tfor _, v := range A {\n\t\tarr[v]++\n\t}\n\n\tvar (\n\t\tans int\n\t\ttoken int\n\t)\n\tfor i := 0; i < 80000; i++ {\n\t\tif arr[i] > 1 {\n\t\t\ttoken += arr[i] - 1\n\t\t\tans -= i * (arr[i] - 1)\n\t\t} else if token > 0 && arr[i] == 0 {\n\t\t\ttoken--\n\t\t\tans += i\n\t\t}\n\t}\n\n\treturn ans\n}", "func minIncrementForUnique(A []int) int {\n \n}", "func FindDuplicateNumber(nums []int) int {\n\ti := 0\n\tfor i < len(nums) {\n\t\tvalue := nums[i]\n\t\tif nums[value-1] != value {\n\t\t\tnums[value-1], nums[i] = value, nums[value-1]\n\t\t} else if value-1 != i {\n\t\t\treturn value\n\t\t} else {\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn -1\n}", "func containsNearbyDuplicate(nums []int, k int) bool {\n m := make(map[int]int)\n for i := 0; i < len(nums); i++ {\n index, exists := m[nums[i]]\n if exists {\n if math.Abs(float64(index - i)) <= float64(k) {\n return true\n }\n }\n m[nums[i]] = i \n }\n return false\n}", "func singleNumber(nums []int) int {\n\tln := len(nums)\n\tif ln == 1 {\n\t\treturn nums[0]\n\t}\n\tsingle := make(map[int]bool)\n\tfor _, n := range nums {\n\t\t_, ok := single[n]\n\t\tif ok {\n\t\t\tdelete(single, n)\n\t\t} else {\n\t\t\tsingle[n] = true\n\t\t}\n\t}\n\tfor n, _ := range single {\n\t\treturn n\n\t}\n\treturn 0 // error condition\n}", "func singleNumber(nums []int) int {\n res := 0\n for _, v := range nums {\n res = res ^ v\n }\n\n return res\n}", "func FindDupFreq(snums []string) int {\n\tcurrent := 0\n\tfreqs := make(map[int]bool)\n\tfreqs[current] = true\n\ti := 0\n\tfor {\n\t\tv, _ := strconv.Atoi(snums[i])\n\t\tcurrent = current + v\n\t\tif _, ok := freqs[current]; ok == true {\n\t\t\treturn current\n\t\t}\n\n\t\tif i++; i == len(snums) {\n\t\t\ti = 0 // index has wrapped around\n\t\t}\n\t\tfreqs[current] = true\n\t}\n}", "func removeDuplicates(nums []int) int {\n if len(nums) < 1 {\n return 0\n }\n \n count := 0\n \n for i := 0 ; i < len(nums); i++ {\n if i == len(nums) - 1 || nums[i] != nums[i+1] {\n // fmt.Println(count, i, nums[i])\n nums[count] = nums[i]\n count++\n continue\n }\n if nums[i] == nums[i+1] && (i == len(nums) - 2 || nums[i] != nums[i+2]) {\n\n nums[count] = nums[i]\n nums[count+1] = nums[i]\n count += 2\n i++\n continue\n }\n \n j := i+1\n for j< len(nums) && nums[i] == nums[j] {\n j++\n }\n\n nums[count] = nums[i]\n nums[count+1] = nums[i]\n count += 2 \n i = j - 1\n }\n \n return count\n}", "func singleNumber(nums []int) int {\r\n\tbit := 0\r\n\tfor i := 0; i < len(nums); i++ {bit ^= nums[i]}\r\n\treturn bit\r\n}", "func duplicateZeros1(arr []int) {\n\tvar count int\n\tn := len(arr)\n\tfor _, v := range arr {\n\t\tif v == 0 {\n\t\t\tcount++\n\t\t}\n\t}\n\n\tfor i := n - 1; i >= 0; i-- {\n\t\tif i+count >= n {\n\t\t\tif arr[i] == 0 {\n\t\t\t\tif i+count-1 < n {\n\t\t\t\t\tarr[i+count-1] = 0\n\t\t\t\t}\n\t\t\t\tcount--\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif count != 0 {\n\t\t\tarr[i+count] = arr[i]\n\t\t\tif arr[i] == 0 {\n\t\t\t\tarr[i+count-1] = 0\n\t\t\t\tcount--\n\t\t\t}\n\t\t}\n\t}\n}", "func removeDuplicates(a []int) []int {\n\tresult := []int{}\n\tseen := map[int]int{}\n\tfor _, val := range a {\n\t\tif _, ok := seen[val]; !ok {\n\t\t\tresult = append(result, val)\n\t\t\tseen[val] = val\n\t\t}\n\t}\n\treturn result\n}", "func main() {\n\tnums := []int{1, 2, 3, 1}\n\tprintln(containsDuplicate(nums))\n}", "func removeDuplicatesII(nums []int) int {\n\tres := len(nums)\n\tfor i := 0; i < len(nums); {\n\t\tv := nums[i]\n\t\tif i < res-1 && nums[i] == nums[i+1] {\n\t\t\ti++\n\t\t\t// 此处优化为记录t后copy一次,可以100%\n\t\t\tj, t := i+1, 0\n\t\t\tfor ; j < res && nums[j] == v; j++ {\n\t\t\t\tt++\n\t\t\t}\n\t\t\tif t > 0 {\n\t\t\t\tcopy(nums[i+1:], nums[j:])\n\t\t\t\tres -= t\n\t\t\t}\n\t\t\ti++\n\t\t} else {\n\t\t\ti++\n\t\t}\n\t}\n\treturn res\n}", "func threeConsecutiveOdds(arr []int) bool {\n c := 0\n for _, num := range arr {\n if num % 2 != 0 {\n c++\n if c == 3 {\n return true\n }\n continue\n }\n c = 0\n }\n return false\n}", "func Unique(input []int) []int {\n\tu := make([]int, 0, len(input))\n\tm := make(map[int]bool)\n\n\tfor _, val := range input {\n\t\tif _, ok := m[val]; !ok {\n\t\t\tm[val] = true\n\t\t\tu = append(u, val)\n\t\t}\n\t}\n\n\treturn u\n}", "func ArrayIntUniq(arr []int) []int {\n\tm := make(map[int]bool)\n\tuniq := []int{}\n\tfor _, v := range arr {\n\t\tif !m[v] {\n\t\t\tm[v] = true\n\t\t\tuniq = append(uniq, v)\n\t\t}\n\t}\n\treturn uniq\n}", "func MajoirtyElement(arr []int) (majority int) {\n\tmajority = -1\n\tcount := 1\n\tfor i := 1; i < len(arr); i++ {\n\t\tif arr[i] == majority {\n\t\t\tcount++\n\t\t} else {\n\t\t\tcount--\n\t\t}\n\n\t\tif count == 0 {\n\t\t\tmajority = arr[i]\n\t\t\tcount = 1\n\t\t}\n\t}\n\n\tnewCount := 0\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] == majority {\n\t\t\tnewCount++\n\t\t}\n\t}\n\n\tif newCount > len(arr)/2 {\n\t\treturn majority\n\t}\n\treturn -1\n\n}", "func main() {\n\tnums := []int{1, 2, 3, 1}\n\tre := containsDuplicate(nums)\n\tfmt.Print(re)\n}", "func FindTriplet(arr []int) {\n\t/*\n\t\t\tAnd they should full fil this condition also\n\t\t\t X = arr[i] ^ arr[i+1] ^ ... ^ arr[j - 1]\n\t\t Y = arr[j] ^ arr[j+1] ^ ... ^ arr[k]\n\t*/\n\n\tvar count int\n\n\tfor i := 0; i < len(arr)-1; i++ {\n\t\tfmt.Println(\"The value of i is \", i)\n\t\tcurrent := arr[i]\n\t\tfor j := i + 1; j < len(arr); j++ {\n\t\t\tcurrent = current ^ arr[j]\n\t\t\tif current == 0 {\n\t\t\t\tcount += j - i\n\t\t\t}\n\t\t}\n\n\t}\n\tfmt.Println(count)\n\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tsort.Ints(A)\n\tfor i, a := range A {\n\t\tif i+1 != a {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn 1\n}", "func removeDuplicates(nums []int) int {\n\tfor i := 0; i < len(nums)-1; i++ {\n\t\tif nums[i] == nums[i+1] {\n\t\t\tj := i + 1\n\t\t\tfor j < len(nums) {\n\t\t\t\tif nums[i] != nums[j] {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tj++\n\t\t\t}\n\t\t\tnums = append(nums[:i], nums[j-1:]...)\n\t\t\ti--\n\t\t}\n\t}\n\n\treturn len(nums)\n}", "func singleNumber(nums []int) int {\n\tres := nums[0]\n\tfor i:=1; i<len(nums); i++{\n\t\tres ^= nums[i]\n\t}\n\n\treturn res\n}", "func unique(nums []int, max int) int {\n\tvar count, prev int\n\tfor _, n := range nums {\n\t\tif n == max {\n\t\t\tcount++\n\t\t\tbreak\n\t\t}\n\n\t\tif n == prev {\n\t\t\tcontinue\n\t\t}\n\n\t\tprev = n\n\t\tcount++\n\t}\n\n\treturn count\n}", "func majorityElement(nums []int) []int {\n \n}", "func removeDuplicates(a []int) int {\n\tleft, right, l := 0, 1, len(a)\n\n\tfor ; right < l; right++ {\n\t\tif a[left] == a[right] {\n\t\t\tcontinue\n\t\t}\n\t\tleft++\n\t\ta[left], a[right] = a[right], a[left]\n\t}\n\n\treturn left +1\n}", "func containsDuplicate(nums []int) bool {\n\tnumMap := make(map[int]bool)\n\tfor _, num := range nums {\n\t\tif _, ok := numMap[num]; ok {\n\t\t\treturn true\n\t\t} else {\n\t\t\tnumMap[num] = true\n\t\t}\n\t}\n\treturn false\n}", "func findDuplicate(nums []int) int {\n N := len(nums)\n if N < 1 {\n return -1 \n }\n\n l := 1\n r := N - 1\n\n for l < r {\n // Divide number into: (l->m) & (m+1->r)\n mid := l + (r - l) / 2\n\n // Count numbers which is less or equal to m\n count := 0\n for _, num := range nums {\n if num <= mid {\n count++\n }\n }\n\n if count > mid {\n // Duplicate number must in left part, i.e. range: l->m\n r = mid\n } else {\n // Duplicate number must in right part, i.e. range: m+1->r\n l = mid + 1\n }\n }\n \n return l\n}", "func solution(a []int) int {\n\tmostFreq, count := 0, 0\n\n\tfor _, v := range a {\n\t\tif count <= 0 {\n\t\t\t//start a new subset\n\t\t\tmostFreq = v\n\t\t}\n\n\t\tif mostFreq == v {\n\t\t\tcount++\n\t\t} else {\n\t\t\t//reaches 0 when is not the maj in the subset\n\t\t\tcount--\n\t\t}\n\t}\n\n\tcount = 0\n\tfor _, v := range a {\n\t\tif v == mostFreq {\n\t\t\tcount++\n\t\t}\n\t}\n\n\tif count > len(a)/2 {\n\t\treturn mostFreq\n\t}\n\n\treturn -1\n}", "func find3Sum(nums []int){\n lenS := len(nums)\n fmt.Println(lenS)\n fmt.Println(nums[0: lenS-2])\n sort.Ints(nums)\n fmt.Println(nums)\n numsMap := make(map[int]int)\n var res [] int\n for i,v := range nums[0: lenS-2] {\n if i >= 1 && nums[i] == nums[i-1] {\n continue\n }\n for _,x := range nums[i: lenS] {\n _, ok := numsMap[x]\n if ok {\n res = append(res, v)\n res = append(res, x)\n res = append(res, -v-x)\n } else {\n numsMap[-x-v] = 1\n }\n }\n }\n\n}", "func removeDuplicates(nums []int) int {\n\tcursor := 1\n\n\tfor i := 1; i < len(nums); i++ {\n\t\tif nums[i-1] != nums[i] {\n\t\t\tnums[cursor] = nums[i]\n\t\t\tcursor++\n\t\t}\n\t}\n\treturn cursor\n}", "func removeDuplicates(nums []int) int {\n\tlength := len(nums)\n\tif length < 2 {\n\t\treturn length\n\t}\n\n\tc := 1\n\tfor i := 1; i < length; i++ {\n\t\tif nums[i] != nums[i-1] {\n\t\t\tnums[c] = nums[i]\n\t\t\tc++\n\t\t}\n\t}\n\n\treturn c\n}", "func ContainsDuplicate(nums []int) bool {\n\tnumTable := make(map[int]struct{})\n\tfor _, num := range nums {\n\t\tif _, ok := numTable[num]; ok {\n\t\t\treturn true\n\t\t}\n\t\tnumTable[num] = struct{}{}\n\t}\n\n\treturn false\n}", "func RemoveDuplicates(nums []int) int {\n\n\tif len(nums) <= 1 || len(nums) > 30000 {\n\t\treturn len(nums)\n\t}\n\n\ti := 0\n\tj := 1\n\tfor {\n\n\t\tif len(nums) <= 1 || j > (len(nums)-1) {\n\t\t\treturn len(nums)\n\t\t}\n\n\t\tif nums[i] < -10000 || nums[i] > 10000 {\n\t\t\treturn 0\n\t\t}\n\n\t\tif nums[i] == nums[j] {\n\t\t\tnums = remove(nums, j)\n\t\t} else {\n\t\t\tif j == (len(nums) - 1) {\n\t\t\t\tif i == (len(nums) - 1) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\ti++\n\t\t\t\tj = i + 1\n\t\t\t\tif j > (len(nums) - 1) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tj++\n\t\t}\n\t}\n\n\treturn len(nums)\n}", "func removeDuplicates(nums []int) int {\n\tif len(nums) == 0 {\n\t\treturn 0\n\t}\n\n\tif len(nums) == 1 {\n\t\treturn 1\n\t}\n\n\tleft, right := 0, 1\n\tfor right < len(nums) {\n\t\tif nums[left] != nums[right] {\n\t\t\tleft++\n\t\t\tnums[left] = nums[right]\n\t\t}\n\t\tright++\n\t}\n\n\treturn left + 1\n}", "func findKey(s []int) int{\n\tn := len(s)\n\tm := make(map[int]int)\n\tvar ans,temp int\n\tans = 0\n\tfor i := 0; i < n; i++ {\n\t\tfor j := i+1; j < n; j++ {\n\t\t\tif true==checkValid(s[i]^s[j]){\n\t\t\t\tm[s[i]]++\n\t\t\t\tm[s[j]]++\n\t\t\t}\n\t\t}\n\t}\n\tfor a,b := range m{\n\t\tif b>temp {\n\t\t\ttemp = b\n\t\t\tans = a\n\t\t}\n\t}\n\tif ans != 0{\n\t\treturn ans^32 \t\n\t}\n\treturn 0\n}", "func removeDuplicates(nums []int) int { // Score: 83.33 :)\n\tduplicates := 0\n\tfor i := 1; i < len(nums); i++ {\n\t\tif nums[i] == nums[i-1] {\n\t\t\tduplicates++\n\t\t} else {\n\t\t\tnums[i-duplicates] = nums[i]\n\t\t}\n\t}\n\treturn len(nums) - duplicates\n}", "func threeSum(nums []int) [][]int {\n\tres := make([][]int, 0)\n\thash := make(map[string]bool)\n\tif len(nums) < 3 {\n\t\treturn res\n\t}\n\tsort.Ints(nums)\n\n\tfor i := 0; i < len(nums)-2; i++ {\n\t\tleft, rig := i+1, len(nums)-1\n\t\tfor left < rig {\n\t\t\tif nums[left]+nums[rig] == 0-nums[i] {\n\t\t\t\ttmp := strconv.Itoa(nums[i]) + strconv.Itoa(nums[left]) + strconv.Itoa(nums[rig])\n\t\t\t\tif _, ok := hash[tmp]; !ok {\n\t\t\t\t\tres = append(res, []int{nums[i], nums[left], nums[rig]})\n\t\t\t\t\thash[tmp] = true\n\t\t\t\t}\n\t\t\t\tleft++\n\t\t\t\trig--\n\t\t\t} else if nums[left]+nums[rig] < 0-nums[i] {\n\t\t\t\tleft++\n\t\t\t} else {\n\t\t\t\trig--\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n\n}", "func findJudge(N int, trust [][]int) int {\n if N == 1 && len(trust) == 0 {\n return 1\n }\n if len(trust) == 0 {\n return -1\n }\n m := make(map[int]int)\n for _, row := range trust {\n m[row[1]]++\n m[row[0]]--\n }\n for key, value := range m {\n if value == N-1 {\n return key\n }\n }\n return -1\n}", "func SingleNumber(nums []int) int {\n\tif len(nums) == 1 {\n\t\treturn nums[0]\n\t}\n\n\tresult := 0\n\tfor _, n := range nums {\n\t\tresult ^= n\n\t}\n\treturn result\n}", "func UniqueInt(a []int) []int {\n\tr := make([]int, 0, len(a))\n\n\tsort.Ints(a)\n\n\tr = append(r, a[0])\n\ti := a[0]\n\n\tfor _, v := range a {\n\t\tif v != i {\n\t\t\tr = append(r, v)\n\t\t\ti = v\n\t\t}\n\t}\n\n\treturn r\n}", "func containsDuplicate(nums []int) bool {\n\tm := map[int]bool{}\n\n\tfor i := 0; i < len(nums); i++ {\n\t\tif !m[nums[i]] {\n\t\t\tm[nums[i]] = true\n\t\t} else {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func removeDuplicates80(nums []int) int {\n\ti := 0\n\tfor _, n := range nums {\n\t\tif i < 2 || n != nums[i-2] {\n\t\t\tnums[i] = n\n\t\t\ti++\n\t\t}\n\t}\n\treturn i\n}", "func threeSum(nums []int) [][]int {\n\ts := make([][]int, len(nums))[0:0]\n\tm2 := make(map[int][][2]int, len(nums))\n\tfor i, v := range nums {\n\t\tfor j := i + 1; j < len(nums); j++ {\n\t\t\tm2[v+nums[j]] = append(m2[v+nums[j]], [2]int{i, j})\n\t\t}\n\t}\n\n\tfor i, v := range nums {\n\t\tif t2s, ok := m2[-v]; ok {\n\t\t\tfor _, t2 := range t2s {\n\t\t\t\tif i == t2[0] || i == t2[1] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\te := []int{nums[i], nums[t2[0]], nums[t2[1]]}\n\t\t\t\tsort.Ints(e)\n\t\t\t\texisted := false\n\t\t\t\tfor _, ee := range s {\n\t\t\t\t\tif e[0] == ee[0] && e[1] == ee[1] && e[2] == ee[2] {\n\t\t\t\t\t\texisted = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !existed {\n\t\t\t\t\ts = append(s, e)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn s\n}", "func CheckDuplicates(array []int) bool {\n\tfor i := 1; i < len(array); i++ {\n\t\tif array[i-1] == array[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func accumulate(nums []int) int {\n\tanswer := 0\n\ttotalLength := len(nums)\n\tfor i := 0; i < totalLength; i++ {\n\t\tif nums[i] == nums[(i+1)%totalLength] {\n\t\t\tanswer += nums[i]\n\t\t}\n\t}\n\treturn answer\n}", "func FindReplications(items []string) []int {\n\t// hash method\n\thashMap := make(map[string]*[2]int)\n\t// int8[0]: 0=none, 1=first_encounter, 2=duplicated,\n\t// int8[1]: first_index\n\tresult := make([]int, 0, len(items))\n\tfor i, item := range items {\n\t\tkey, ok := hashMap[item]\n\t\tif !ok {\n\t\t\thashMap[item] = &[2]int{1, i}\n\t\t\tcontinue\n\t\t}\n\t\tswitch key[0] {\n\t\tcase 1:\n\t\t\thashMap[item][0] = 2\n\t\t\tresult = append(result, hashMap[item][1], i)\n\t\tcase 2:\n\t\t\tresult = append(result, i)\n\t\tdefault:\n\t\t\tpanic(\"???how???\")\n\t\t}\n\t}\n\tsort.Ints(result)\n\treturn result\n}", "func removeDuplicates(nums []int) int {\n\tif len(nums) == 0 {\n\t\treturn 0\n\t}\n\tj := 0\n\tfor i := 1; i < len(nums); i++ {\n\t\tif nums[i] > nums[j] {\n\t\t\tj++\n\t\t\tnums[j] = nums[i]\n\t\t}\n\t}\n\treturn j + 1\n}", "func ArrayInt64Uniq(arr []int64) []int64 {\n\tm := make(map[int64]bool)\n\tuniq := []int64{}\n\tfor _, v := range arr {\n\t\tif !m[v] {\n\t\t\tm[v] = true\n\t\t\tuniq = append(uniq, v)\n\t\t}\n\t}\n\treturn uniq\n}", "func permuteUnique(nums []int) [][]int {\n\texist = make(map[[8]int]struct{}) // for leetcode\n\n\treturn recurse(nums, make([]bool, 8), make([]int, 0), make([][]int, 0))\n}", "func countElements(arr []int) int {\n\tcount := 0\n\tif len(arr) == 1 {\n\t\treturn 0\n\t}\n\tfor i := 1; i < len(arr); i++ {\n\t\tif arr[i] == arr[i-1]+1 {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count\n}", "func candies(n int32, arr []int32) int64 {\n var result int64\n LtoR := make([]int32, len(arr))\n RtoL := make([]int32, len(arr))\n\n LtoR[0] = 1\n RtoL[len(arr)-1] = 1\n \n for i := 1; i < len(arr); i++ {\n if arr[i-1] < arr[i] {\n LtoR[i] = LtoR[i-1] + 1\n } else {\n LtoR[i] = 1\n }\n }\n \n for i := len(arr)-2; i >= 0; i-- {\n if arr[i] <= arr[i+1] {\n RtoL[i] = 1\n } else {\n RtoL[i] = RtoL[i+1] + 1\n }\n }\n result = compare(LtoR, RtoL)\n \n return result\n}", "func Array_find_element_occur_more_nby2_unsorted_01(arr []int) string {\n\n\tdic := make(map[int]int)\n\n\tfor _, e := range arr {\n\t\tdic[e]++\n\t}\n\n\tfor k, v := range dic {\n\t\tif v >= len(arr)/2 {\n\t\t\treturn strconv.Itoa(k)\n\t\t}\n\t}\n\treturn \"NaN\"\n}", "func countDuplicates(s []byte) int {\n\tbytes := make(map[byte]int)\n\tfor _, b := range s {\n\t\tif _, ok := bytes[b]; ok != true {\n\t\t\tbytes[b] = 1\n\t\t} else {\n\t\t\tbytes[b]++\n\t\t}\n\t}\n\tnum := 0\n\tfor _, v := range bytes {\n\t\tif v > 1 {\n\t\t\tnum += v - 1\n\t\t}\n\t}\n\treturn num\n}", "func findShortestSubArray(nums []int) int {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn n\n\t}\n\tfirst := make(map[int]int, n) //第一次出现当前元素的位置\n\tcount := make(map[int]int, n) //记录当前元素出现的个数\n\tmaxCount := 1\n\tminLen := n\n\tfor i, v := range nums {\n\t\tcount[v]++\n\t\tif count[v] == 1 {\n\t\t\tfirst[v] = i\n\t\t} else {\n\t\t\tl := i - first[v] + 1 //度\n\t\t\tif maxCount < count[v] || (maxCount == count[v] && minLen > l) {\n\t\t\t\tmaxCount = count[v]\n\t\t\t\tminLen = l\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(count) == n {\n\t\treturn 1\n\t}\n\treturn minLen\n}", "func minimumSwaps(arr []int32) int32 {\n\n\tvar trackArray []visit\n\tfor _, v := range arr {\n\t\ttrackArray = append(trackArray, visit{int(v), false})\n\t}\n\t// traversing through array finding cycles\n\tvar swapCount int\n\tfor i, v := range trackArray {\n\t\tif v.seen {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Mark this number as seen (note that we have to access the original array rather than v)\n\t\ttrackArray[i].seen = true\n\n\t\tif i == v.val {\n\t\t\t// Number already in correct place\n\t\t\tcontinue\n\t\t}\n\t\t// Start tracking a cycle\n\t\t// Check the number sitting in v's \"home\"\n\t\tcurrent := v\n\t\tfor {\n\t\t\tnext := trackArray[current.val-1]\n\n\t\t\t// Mark next as seen (have to update original array)\n\t\t\ttrackArray[current.val-1].seen = true\n\n\t\t\tif next.val == v.val {\n\t\t\t\t// End of the cycle\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Necessary swaps is (length of cycle) - 1\n\t\t\tswapCount++\n\t\t\tcurrent = next\n\t\t}\n\t}\n\n\treturn int32(swapCount)\n\n}", "func threeSumSlow(nums []int) [][]int {\n\ttarget := 0\n\t// O(nlogn)\n\tsort.Ints(nums)\n\toutput := [][]int{}\n\n\tusedMap := make(map[int]map[int]int)\n\n\t// -2 since we don't have to iterate last 2 elements, it will check by inner loop\n\t// iterations are n-1 + n-2 + .... 2 => n*(n-1) / 2 => O(n^2)\n\tfor i := 0; i < len(nums)-2; i++ {\n\t\tleft, right := i+1, len(nums)-1\n\n\t\tfor left < right {\n\n\t\t\tleftRightResult := nums[left] + nums[right]\n\t\t\tsum := nums[i] + leftRightResult\n\n\t\t\t_, leftUsed := usedMap[nums[i]][nums[left]]\n\t\t\t_, rightUsed := usedMap[nums[i]][nums[right]]\n\n\t\t\tif leftUsed == true && rightUsed == true {\n\t\t\t\tleft++\n\t\t\t\tright--\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif sum == target {\n\t\t\t\toutput = append(output, []int{nums[i], nums[left], nums[right]})\n\n\t\t\t\t_, ok := usedMap[nums[i]]\n\n\t\t\t\tif ok == false {\n\t\t\t\t\tusedMap[nums[i]] = make(map[int]int)\n\t\t\t\t}\n\n\t\t\t\tusedMap[nums[i]][nums[left]] = nums[left]\n\t\t\t\tusedMap[nums[i]][nums[right]] = nums[right]\n\n\t\t\t\tleft++\n\t\t\t\tright--\n\t\t\t} else if sum > target {\n\t\t\t\tright--\n\t\t\t} else {\n\t\t\t\tleft++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn output\n}", "func removeDuplicates(nums []int) int {\n\tlength, newLength := len(nums), 1\n\tfor i := 1; i < length; i++ {\n\t\tif nums[i-1] != nums[i] {\n\t\t\tnums[newLength] = nums[i]\n\t\t\tnewLength++\n\t\t}\n\t}\n\treturn newLength\n}", "func findMaxConsecutiveOnes(nums []int) int {\n\tvar (\n\t\tres int\n\t\tcnt int\n\t)\n\tfor _, n := range nums {\n\t\tif n == 0 {\n\t\t\tcnt = 0\n\t\t} else {\n\t\t\tcnt++\n\t\t\tres = max(res, cnt)\n\t\t}\n\t}\n\n\treturn res\n}", "func PermCheck(A []int) int {\n\tsum := 0\n\tseen := make(map[int]bool)\n\tarrayLen := len(A)\n\n\tfor _, value := range A {\n\t\tif seen[value] {\n\t\t\t// early exit in case of duplicate value\n\t\t\treturn 0\n\t\t}\n\n\t\tseen[value] = true\n\t\tsum += value\n\t}\n\n\tif (arrayLen * (arrayLen + 1) / 2) == sum {\n\t\treturn 1\n\t} else {\n\t\treturn 0\n\t}\n}", "func FindNoOfRedistributionCycles(bank []int) int {\n\thashList := []uint64{hash(bank)}\n\tfor {\n\t\tcurrentElement := getMaxIndex(bank)\n\t\tvalue := bank[currentElement]\n\t\tbank[currentElement] = 0\n\n\t\tfor i := 0; i < value; i++ {\n\t\t\tcurrentElement++\n\t\t\tif currentElement > len(bank)-1 {\n\t\t\t\tcurrentElement = 0\n\t\t\t}\n\t\t\tbank[currentElement]++\n\t\t}\n\n\t\thash := hash(bank)\n\t\tfor _, h := range hashList {\n\t\t\tif h == hash {\n\t\t\t\treturn len(hashList)\n\t\t\t}\n\t\t}\n\t\thashList = append(hashList, hash)\n\t}\n}", "func findSmallestCommonNumber(arr1, arr2, arr3 []int) int {\n // initiate the array index counters to zero\n i, j, k := 0, 0, 0\n\n for i < len(arr1) && j < len(arr2) && k < len(arr3) {\n if arr1[i] == arr2[j] && arr2[j] == arr3[k] {\n // all values are the same, so return\n return arr1[i]\n }\n\n // as the arrays are sorted, just increment the smallest value's\n // index for the next comparison check\n if arr1[i] <= arr2[j] && arr1[i] <= arr3[k] {\n i += 1\n } else if arr2[j] <= arr1[i] && arr2[j] <= arr3[k] {\n j += 1\n } else if arr3[k] <= arr1[i] && arr3[k] <= arr2[j] {\n k += 1\n }\n }\n\n // number common to all arrays not found\n return -1\n}", "func ContainsNearbyDuplicate(nums []int, k int) bool {\n\tnumTable := make(map[int][]int)\n\tfor i, num := range nums {\n\t\tij, ok := numTable[num]\n\t\tif !ok || len(ij) == 1 {\n\t\t\tnumTable[num] = append(numTable[num], i)\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(ij) == 2 {\n\t\t\tif ij[1]-ij[0] > i-ij[1] {\n\t\t\t\tij[0], ij[1] = ij[1], i\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, ij := range numTable {\n\t\tif len(ij) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif ij[1]-ij[0] <= k {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func findMaxConsecutiveOnes(nums []int) int {\n \n}", "func UniqueInts(input []int) []int {\n\tkeys := make(map[int]bool)\n\tlist := []int{}\n\tfor _, entry := range input {\n\t\tif _, value := keys[entry]; !value {\n\t\t\tkeys[entry] = true\n\t\t\tlist = append(list, entry)\n\t\t}\n\t}\n\treturn list\n}", "func naiveCount(arr []int32) int64 {\n\t// nested loop algo - will be very inefficient O(n^2)\n\tvar count int64\n\tfor i := 0; i < len(arr); i++ {\n\t\tfor j := i + 1; j < len(arr); j++ {\n\t\t\tif arr[i] > arr[j] {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n\treturn count\n}", "func permuteUnique(nums []int) [][]int {\n\tres := make([][]int, 0)\n\tsort.Ints(nums) //sort first so that duplicate numbers will only occur adjacently,but here actually no need\n\n\tloop(0, &res, nums)\n\treturn res\n}", "func HasRepeat(elems []int) bool {\n\tfor i := 0; i < len(elems); i++ {\n\t\tfor j := i + 1; j < len(elems); j++ {\n\t\t\tif elems[j] == elems[i] {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tresult := 0\n\tsort.Ints(A)\n\tfor i := range A {\n\t\tif i == 0 {\n\t\t\tresult++\n\t\t} else {\n\t\t\tif A[i] != A[i-1] {\n\t\t\t\tresult++\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}" ]
[ "0.75747204", "0.74628955", "0.73518026", "0.7143766", "0.69932", "0.68078774", "0.66555685", "0.66521645", "0.66019005", "0.65978277", "0.65269494", "0.6464587", "0.6464505", "0.64367026", "0.63171303", "0.6292975", "0.6219294", "0.6209139", "0.61373633", "0.6132399", "0.6120109", "0.6116606", "0.6112016", "0.6107256", "0.60601133", "0.604656", "0.60366374", "0.6027166", "0.6015691", "0.6006951", "0.59879106", "0.5985558", "0.5983567", "0.5964163", "0.5939113", "0.5938941", "0.5925798", "0.5913357", "0.5908385", "0.5895051", "0.58778787", "0.58738506", "0.58720285", "0.586029", "0.5859993", "0.5832941", "0.58281595", "0.58258516", "0.5815373", "0.5807454", "0.5801273", "0.5789273", "0.5781399", "0.5769901", "0.5765219", "0.5757902", "0.5741573", "0.57375574", "0.5714898", "0.5712165", "0.5676584", "0.56746936", "0.5670282", "0.5657834", "0.56278497", "0.5623859", "0.5622183", "0.55990463", "0.5595797", "0.55952525", "0.5590096", "0.55791295", "0.55759084", "0.5570141", "0.5562442", "0.5548707", "0.5521828", "0.5518249", "0.55103576", "0.5501039", "0.5492658", "0.5478503", "0.5475991", "0.5473567", "0.5472269", "0.54684013", "0.54672396", "0.5465907", "0.5462171", "0.5452521", "0.54390746", "0.54321545", "0.5414545", "0.54061455", "0.53997165", "0.5395424", "0.53836656", "0.5383623", "0.5377425", "0.5368728" ]
0.60810876
24
var syncSignal chan bool
func init() { logFile.InitLog() channel = make(chan int,50) //syncSignal = transfer.SyncSignal }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Eventer) sync() {\n\tc.syncc <- struct{}{}\n\t<-c.syncDonec\n}", "func Sync(f func()) {\n\tsyncChan <- f\n}", "func (q *queue) Signal() {\n\tq.notEmpty.Broadcast()\n}", "func (c *Cond) Signal() {\n\tc.Do(func() {})\n}", "func signal() {\n\tnoEvents = true\n}", "func (lb *Elb) Sync() {\n\tlb.syncCh <- 1\n}", "func Synchronising() {\n\tdone := make(chan bool, 1)\n\n\tgo worker(done)\n\n\t<-done\n}", "func (p *promise) Signal(waitChan chan Controller) Promise {\n\tp.Always(func(p2 Controller) {\n\t\twaitChan <- p2\n\t})\n\n\treturn p\n}", "func (r *ResetReady) Signal() {\n\tr.lock.Lock()\n\tr.ready.Signal()\n\tr.lock.Unlock()\n}", "func signal_enable(s uint32) {\n\tif !sig.inuse {\n\t\t// The first call to signal_enable is for us\n\t\t// to use for initialization. It does not pass\n\t\t// signal information in m.\n\t\tsig.inuse = true // enable reception of signals; cannot disable\n\t\tnoteclear(&sig.note)\n\t\treturn\n\t}\n}", "func(syncObj *Sync)ReadRestServiceExitSignal() {\n <-syncObj.restExitFlag\n}", "func (g *GPIOControllerPCF8574T) sync() {\n\terr := g.bus.WriteByte(g.address, g.valuePinMask)\n\tif err != nil {\n\t\tfmt.Printf(\"Error syncing gpio controller: %v\\n\", err)\n\t}\n}", "func initSignal() chan os.Signal {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM,\n\t\tsyscall.SIGINT, syscall.SIGSTOP)\n\treturn c\n}", "func (srv *server) signalShutdown() {\n\tsrv.once.Do(func() {\n\t\tsrv.cond.L.Lock()\n\t\tsrv.cond.Signal()\n\t\tsrv.cond.L.Unlock()\n\t})\n}", "func (d *LoopVars) askForSync() {\n\td.ensureInit()\n\tselect {\n\tcase d.syncSoon <- struct{}{}:\n\tdefault:\n\t}\n}", "func InitSignal() {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGSTOP)\n\tfor {\n\t\ts := <-c\n\t\tlog.Info(\"job[%s] get a signal %s\", Ver, s.String())\n\t\tswitch s {\n\t\tcase syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGSTOP, syscall.SIGINT:\n\t\t\treturn\n\t\tcase syscall.SIGHUP:\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (p *Panorama) ToggleSignalDetection() {\n\tp.signalDetectionActive = !p.signalDetectionActive\n}", "func (b *Bluez) WatchSignal() chan *dbus.Signal {\n\tsignalMatch := \"type='signal',interface='org.freedesktop.DBus.ObjectManager',path='/'\"\n\tb.conn.BusObject().Call(\"org.freedesktop.DBus.AddMatch\", 0, signalMatch)\n\tch := make(chan *dbus.Signal, 1)\n\tb.conn.Signal(ch)\n\treturn ch\n}", "func (uc *Userclient) iToggleSync(args *userproto.ToggleSyncArgs, reply *userproto.ToggleSyncReply) error {\r\n\t<-uc.fileKeyMutex\r\n\tfilekey := uc.fileKeyMap[args.Filepath].Key\r\n\tuc.fileKeyMutex <- 1\r\n\tsyncFile := uc.iGet(filekey)\r\n\tif syncFile == nil {\r\n\t\tlog.Fatal(\"Unable to get file.\")\r\n\t}\r\n\tsyncFile.Synced = false\r\n\tuc.iPush(filekey, syncFile)\r\n\treturn nil\r\n}", "func (this *ThreadCtl) WaitSignal() string {\n\tselect {\n\tcase signal := <-this.signalChan:\n\t\treturn signal\n\t}\n}", "func (e *AutoResetEvent) Signal() {\n\te.l.Lock()\n\tif len(e.c) == 0 {\n\t\te.c <- struct{}{}\n\t}\n\te.l.Unlock()\n}", "func NotifySignal(c chan<- Signal, sig ...Signal) error {\n\tif c == nil {\n\t\treturn fmt.Errorf(\"NotifySignal using nil channel\")\n\t}\n\n\tvar pid = os.Getpid()\n\tevts := make([]windows.Handle, 0, len(sig))\n\n\tfor _, s := range sig {\n\t\tname, err := windows.UTF16PtrFromString(eventName(s, pid))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\th, err := windows.CreateEvent(nil, 1, 0, name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tevts = append(evts, h)\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tev, err := windows.WaitForMultipleObjects(evts, false, windows.INFINITE)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"WaitForMultipleObjects failed: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toffset := ev - windows.WAIT_OBJECT_0\n\t\t\tc <- sig[offset]\n\t\t\tif err := windows.ResetEvent(evts[offset]); err != nil {\n\t\t\t\tlog.Printf(\"ResetEvent failed: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}", "func (s *countingSemaphore) Signal() {\n\ts.sem <- 1\n}", "func printSyncWith(sender string) {\n\tfmt.Println(\"IN SYNC WITH \" + sender)\n}", "func (d *specialDevice) sync() error {\n\tif d.toLimb != nil {\n\t\tif err := d.toLimb(d.instance); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif d.mqttClient != nil {\n\t\tif err := d.mqttClient.Publish(mqtt.PublishMessage{Payload: d.instance.Status}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\td.log.V(1).Info(\"Synced\")\n\treturn nil\n}", "func setupSignal(d chan int) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\tfor sig := range c {\n\t\t\tfmt.Printf(\"\\nCaptured signal %v\\n\", sig)\n\t\t\tfmt.Printf(\"Output in %v\\n\", \"proc.log\")\n\t\t\tos.Exit(1) // Will exit immediately.\n\t\t\td <- 0\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n}", "func InitSignal() chan os.Signal {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGSTOP)\n\treturn c\n}", "func signalHandler() {\n\t// time in microseconds since wiringPiSetup was called\n\tvar timeSinceInit = int(C.micros())\n\n\t// ____| <- time elapsed before the signal change\n\tsignalDuration := timeSinceInit - lastTime\n\n\t// if the signal is longer than the max time allowed between signals then it's probably:\n\t// - a too long signal\n\t// - a silence\n\t// - a gap between two signals\n\tif signalDuration > pt2262.Gap {\n\n\t\t// if the signal duration is close to the first recorded signal duration then it's probably:\n\t\t// x a too long signal\n\t\t// x a silence\n\t\t// v a gap between two signals\n\t\tif diff(signalDuration, frame[0]) < 200 {\n\n\t\t\t// increment the repeat counter which is used to confirm since most of protocol repeat twice a signal on\n\t\t\t// sent\n\t\t\trepeatCount++\n\n\t\t\t// if it equals 2 then we assume that the signal is saved in the frame\n\t\t\tif repeatCount == 2 {\n\n\t\t\t\t// since the signal is saved to the global frame we need to decode it following a protocol\n\t\t\t\tdecode()\n\n\t\t\t\t// reset the confirm counter\n\t\t\t\trepeatCount = 0\n\t\t\t}\n\t\t}\n\n\t\t// reset change counter\n\t\tchangeCount = 0\n\t}\n\n\t// prevent frame overflow, if there is no success but we filled the 32 bit frame then drop it and start\n\t// again\n\tif changeCount >= MaxChangesPerFrame {\n\t\tchangeCount = 0\n\t\trepeatCount = 0\n\t}\n\n\t// add the signal duration to the frame and increment the index\n\tframe[changeCount] = signalDuration\n\tchangeCount++\n\n\t// save the last signal time, it will permit to calculate the next signal duration\n\tlastTime = timeSinceInit\n}", "func sendNote(s *byte) bool {\n\tif !sig.inuse {\n\t\treturn false\n\t}\n\n\t// Add signal to outgoing queue.\n\tif !sig.q.push(s) {\n\t\treturn false\n\t}\n\n\tlock(&sig.lock)\n\tif sig.sleeping {\n\t\tsig.sleeping = false\n\t\tnotewakeup(&sig.note)\n\t}\n\tunlock(&sig.lock)\n\n\treturn true\n}", "func sendSignal(cmd *exec.Cmd, ch <-chan error, sig syscall.Signal, timeout time.Duration) bool {\n\tif cmd.Process == nil {\n\t\tlog.Debug(\"Not terminating process, it seems to have not started yet\")\n\t\treturn false\n\t}\n\t// This is a bit of a fiddle. We want to wait for the process to exit but only for just so\n\t// long (we do not want to get hung up if it ignores our SIGTERM).\n\tlog.Debug(\"Sending signal %s to -%d\", sig, cmd.Process.Pid)\n\tsyscall.Kill(-cmd.Process.Pid, sig) // Kill the group - we always set one in ExecCommand.\n\n\tselect {\n\tcase <-ch:\n\t\treturn true\n\tcase <-time.After(timeout):\n\t\treturn false\n\t}\n}", "func (s *ShutdownManager) EnableSignalMonitor() {\n\tsignal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)\n\tgo func() {\n\t\t<-sigchan\n\t\ts.SignalShutdown()\n\t}()\n}", "func (mp *MockProducer) HandleSync(context.Context, *pkg.Job) {\n\tmp.SyncSignal <- struct{}{}\n}", "func (e *Exit) Signal() {\n\te.once.Do(func() {\n\t\tclose(e.c)\n\n\t\te.mtx.Lock()\n\t\texits := e.exits\n\t\te.exits = nil\n\t\te.mtx.Unlock()\n\n\t\tfor i := len(exits); i > 0; i-- {\n\t\t\texits[i-1]()\n\t\t}\n\t})\n}", "func setCloseSignal(closeSignal *uint32, closeLock *sync.Mutex) bool {\n\tcloseLock.Lock()\n\tdefer closeLock.Unlock()\n\n\tshouldClose := atomic.LoadUint32(closeSignal)\n\tif shouldClose > 0 {\n\t\treturn false\n\t}\n\n\tatomic.AddUint32(closeSignal, 1)\n\n\treturn true\n\n}", "func BoolRace() {\n\tvar s bool\n\tdone := make(chan bool)\n\n\tgo func() {\n\t\ts = true\n\t\tdone <- true\n\t}()\n\n\ts = false\n\t<-done\n\tfmt.Println(s)\n}", "func main() {\n\tcloseChan := make(chan os.Signal, 1)\n\tsignal.Notify(closeChan, syscall.SIGINT)\n\n var wg sync.WaitGroup\n wg.Add(1) // HLwg\n\tsig := boring(&wg)\n\t<-closeChan\n\n\tsig<-1\n\twg.Wait() // HLwg\n}", "func pushSync(t *testing.T, r *RingStore, e *model.ProcessEvent) {\n\tdone := make(chan bool)\n\terr := r.Push(e, done)\n\trequire.NoError(t, err)\n\tok := <-done\n\trequire.True(t, ok)\n}", "func WaitSignal(stop chan struct{}) {\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\t<-sigs\n\tclose(stop)\n}", "func syncParentReady(pipe io.ReadWriter) error {\n\t// Tell parent.\n\tif err := utils.WriteJSON(pipe, syncT{procReady}); err != nil {\n\t\treturn err\n\t}\n\t// Wait for parent to give the all-clear.\n\tvar procSync syncT\n\tif err := json.NewDecoder(pipe).Decode(&procSync); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn fmt.Errorf(\"parent closed synchronisation channel\")\n\t\t}\n\t\tif procSync.Type != procRun {\n\t\t\treturn fmt.Errorf(\"invalid synchronisation flag from parent\")\n\t\t}\n\t}\n\treturn nil\n}", "func (s *syncRatio) ReportSyncEvent() {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.syncEvents++\n}", "func (server *Server) Sync() {\n\n}", "func (nopBroadcaster) SendSync(Message) error { return nil }", "func Notify() {\n\t// close(done)\n\tfor i := 0; i < count; i++ {\n\t\tdone <- true\n\t}\n\tcount = 0\n}", "func (wl *dummyLogger) Wait() error {\n wait := make(chan os.Signal, 1)\n signal.Notify(wait, syscall.SIGUSR1)\n <-wait\n return nil\n}", "func (bot *ExchangeBot) signalUpdate(token string) {\n\tvar signal *UpdateSignal\n\tif bot.IsFailed() {\n\t\tsignal = &UpdateSignal{\n\t\t\tToken: token,\n\t\t\tState: nil,\n\t\t\tBytes: []byte{},\n\t\t}\n\t} else {\n\t\tsignal = &UpdateSignal{\n\t\t\tToken: token,\n\t\t\tState: bot.State(),\n\t\t\tBytes: bot.StateBytes(),\n\t\t}\n\t}\n\tfor _, ch := range bot.updateChans {\n\t\tselect {\n\t\tcase ch <- signal:\n\t\tdefault:\n\t\t}\n\t}\n}", "func chanSend(ch *channel, value unsafe.Pointer) {\n\tif ch.trySend(value) {\n\t\t// value immediately sent\n\t\tchanDebug(ch)\n\t\treturn\n\t}\n\n\tif ch == nil {\n\t\t// A nil channel blocks forever. Do not schedule this goroutine again.\n\t\tdeadlock()\n\t}\n\n\t// wait for reciever\n\tsender := getCoroutine()\n\tch.state = chanStateSend\n\tsenderState := sender.state()\n\tsenderState.ptr = value\n\tch.blocked = &channelBlockedList{\n\t\tnext: ch.blocked,\n\t\tt: sender,\n\t}\n\tchanDebug(ch)\n\tyield()\n\tsenderState.ptr = nil\n}", "func (lc *Closer) Signal() {\n\tlc.cancel()\n}", "func (s *Syncer) Sync() error {\n\ts.called = true\n\treturn s.err\n}", "func (_m *Session) Signals(c chan<- ssh.Signal) {\n\t_m.Called(c)\n}", "func TestSignal(t *testing.T) {\n\t// Ask for SIGHUP\n\tc := make(chan os.Signal, 1)\n\tNotify(c, syscall.SIGHUP)\n\tdefer Stop(c)\n\n\t// Send this process a SIGHUP\n\tt.Logf(\"sighup...\")\n\tsyscall.Kill(syscall.Getpid(), syscall.SIGHUP)\n\twaitSig(t, c, syscall.SIGHUP)\n\n\t// Ask for everything we can get. The buffer size has to be\n\t// more than 1, since the runtime might send SIGURG signals.\n\t// Using 10 is arbitrary.\n\tc1 := make(chan os.Signal, 10)\n\tNotify(c1)\n\t// Stop relaying the SIGURG signals. See #49724\n\tReset(syscall.SIGURG)\n\tdefer Stop(c1)\n\n\t// Send this process a SIGWINCH\n\tt.Logf(\"sigwinch...\")\n\tsyscall.Kill(syscall.Getpid(), syscall.SIGWINCH)\n\twaitSigAll(t, c1, syscall.SIGWINCH)\n\n\t// Send two more SIGHUPs, to make sure that\n\t// they get delivered on c1 and that not reading\n\t// from c does not block everything.\n\tt.Logf(\"sighup...\")\n\tsyscall.Kill(syscall.Getpid(), syscall.SIGHUP)\n\twaitSigAll(t, c1, syscall.SIGHUP)\n\tt.Logf(\"sighup...\")\n\tsyscall.Kill(syscall.Getpid(), syscall.SIGHUP)\n\twaitSigAll(t, c1, syscall.SIGHUP)\n\n\t// The first SIGHUP should be waiting for us on c.\n\twaitSig(t, c, syscall.SIGHUP)\n}", "func (w *WaitingPod) GetSignal() *framework.Status {\n\treturn <-w.s\n}", "func IsSync(sync unsafe.Pointer) bool {\n ret := C.glowIsSync(gpIsSync, (C.GLsync)(sync))\n return ret == TRUE\n}", "func handleSig(sig <-chan int, sigv *int) {\n\tgo func() {\n\t\tfor *sigv = range sig {\n\t\t}\n\t\t*sigv = -1\n\t}()\n}", "func (t *tracer) flushSync() {\n\tdone := make(chan struct{})\n\tt.flush <- done\n\t<-done\n}", "func signals(signals ...os.Signal) (<-chan os.Signal, func()) {\n\tsigchan := make(chan os.Signal)\n\tsigrecv := events.Signal(sigchan)\n\tsignal.Notify(sigchan, signals...)\n\treturn sigrecv, func() { signal.Stop(sigchan) }\n}", "func WaitSignal(stop chan struct{}) {\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\t<-sigs\n\tglog.Warningln(\"Finishing with signal handling.\")\n\tclose(stop)\n}", "func (d *dispatcher) dispatchBlockSyncReq(sender string, msg proto.Message, done chan bool) {\n\tif atomic.LoadInt32(&d.shutdown) != 0 {\n\t\tif done != nil {\n\t\t\tclose(done)\n\t\t}\n\t\treturn\n\t}\n\td.newsChan <- &blockSyncMsg{sender, (msg).(*pb.BlockSync), done}\n}", "func main() {\n\tprintln(\"start - async\")\n\tgo process(nil)\n\tprintln(\"end - async\")\n\n\ttime.Sleep(time.Second)\n\tprintln(\"---------\")\n\n\tsig := make(chan int)\n\tprintln(\"start - sync\")\n\tgo process(sig)\n\t<-sig\n\tprintln(\"end - sync\")\n}", "func (g *Goer) installSignal() {\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGUSR2)\n\tfor signalType := range ch {\n\t\tswitch signalType {\n\t\t// stop process in debug mode with Ctrl+c.\n\t\tcase syscall.SIGINT:\n\t\t\tg.stopAll(ch, signalType)\n\t\t// kill signal in bash shell.\n\t\tcase syscall.SIGKILL | syscall.SIGTERM:\n\t\t\tg.stopAll(ch, signalType)\n\t\t// graceful reload\n\t\tcase syscall.SIGQUIT:\n\t\t\tsignal.Stop(ch)\n\t\t\tg.reload()\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n}", "func (rm *ResponseManager) synchronize() {\n\tsync := make(chan error)\n\trm.send(&synchronizeMessage{sync}, nil)\n\tselect {\n\tcase <-rm.ctx.Done():\n\tcase <-sync:\n\t}\n}", "func TestSignals(t *testing.T) {\n\tseq := make(chan int)\n\twait := make(chan int)\n\tfreq := make(chan time.Time)\n\n\tqueue := &WaitQueue{\n\t\tsem: new(sync.WaitGroup),\n\t\tseq: seq,\n\t\twait: wait,\n\t}\n\n\t// begin listening\n\tgo waitListen(queue, freq, seq)\n\n\t// send a tick, this should start a call to Poll()\n\tfreq <- time.Now()\n\n\t// when that call starts, we should get `1` on the sequence channel\n\tval := <-seq\n\trequire.Equal(t, val, 1)\n\n\t// send a signal, this should start the graceful exit\n\tsignals <- os.Interrupt\n\n\t// tell Poll() that it can exit\n\twait <- 1\n\n\t// first Poll() should exit\n\tval = <-seq\n\trequire.Equal(t, val, 2)\n\n\t// then Listen() should exit\n\tval = <-seq\n\trequire.Equal(t, val, 3)\n}", "func (b *BoatHandle) Signal(sig os.Signal) error { return b.cmd.Process.Signal(sig) }", "func setupWaitingChannel() (ch chan os.Signal) {\n\tch = make(chan os.Signal)\n\tsignal.Notify(ch, os.Interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)\n\treturn\n}", "func (a *Agent) PauseSync() {\n\t// Do this outside of lock as it has it's own locking\n\ta.sync.Pause()\n\n\t// Coordinate local state watchers\n\ta.syncMu.Lock()\n\tdefer a.syncMu.Unlock()\n\tif a.syncCh == nil {\n\t\ta.syncCh = make(chan struct{})\n\t}\n}", "func DeferChannelSendTrue(endChan chan bool) {\n\tendChan <- true\n}", "func sendStartSignal() {\n\n\tvar status int\n\n\tlog.Debugf(\"Sending GET to: %s\", configFile.urlSignalServer)\n\tvar netClient = &http.Client{\n\t\tTimeout: time.Second * 30,\n\t}\n\tresponse, err := netClient.Get(configFile.urlSignalServer)\n\tif err != nil {\n\t\tlog.Errorf(\"The HTTP request failed with error %s\\n\", err)\n\t} else {\n\t\tstatus = response.StatusCode\n\t\tbody, _ := ioutil.ReadAll(response.Body)\n\t\tlog.Info(status, \" - \"+string(body))\n\t}\n}", "func (s *SFUSignalBridge) Signal(sstream sfu.SFU_SignalServer) error {\n\tvar peer *Peer\n\tvar cstream sfu.SFU_SignalClient = nil\n\treqCh := make(chan *sfu.SignalRequest)\n\trepCh := make(chan *sfu.SignalReply)\n\terrCh := make(chan error)\n\n\tdefer func() {\n\t\tif cstream != nil {\n\t\t\terr := cstream.CloseSend()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"cstream.CloseSend() failed %v\", err)\n\t\t\t}\n\t\t}\n\t\tclose(errCh)\n\t\tlog.Infof(\"SFU.Signal loop done\")\n\t}()\n\n\tgo func() {\n\t\tdefer close(reqCh)\n\t\tfor {\n\t\t\treq, err := sstream.Recv()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Singal server stream.Recv() err: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\treqCh <- req\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase err := <-errCh:\n\t\t\treturn err\n\t\tcase req, ok := <-reqCh:\n\n\t\t\tif !ok {\n\t\t\t\treturn io.EOF\n\t\t\t}\n\n\t\t\tif cstream != nil {\n\t\t\t\terr := cstream.Send(req)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"cstream.Send(req) failed %v\", err)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tswitch payload := req.Payload.(type) {\n\t\t\tcase *sfu.SignalRequest_Join:\n\t\t\t\t//TODO: Check if you have permission to connect to the SFU node\n\t\t\t\tr := s.BizServer.getRoom(payload.Join.Sid)\n\t\t\t\tif r != nil {\n\t\t\t\t\tpeer = r.getPeer(payload.Join.Uid)\n\t\t\t\t\tif peer != nil {\n\t\t\t\t\t\t// Use nats-grpc or grpc\n\t\t\t\t\t\t// TODO: change to util.NewGRPCClientConnForNode.\n\t\t\t\t\t\tcli := sfu.NewSFUClient(nrpc.NewClient(s.BizServer.nc, r.sfunid))\n\t\t\t\t\t\tvar err error\n\t\t\t\t\t\tcstream, err = cli.Signal(context.Background())\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Errorf(\"Singal cli.Signal() err: %v\", err)\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\tdefer close(repCh)\n\t\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\t\treply, err := cstream.Recv()\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\tlog.Errorf(\"Singal client stream.Recv() err: %v\", err)\n\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\trepCh <- reply\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}()\n\n\t\t\t\t\t\terr = cstream.Send(req)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"cstream.Send(req) failed %v\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn fmt.Errorf(\"peer [%v] not found\", payload.Join.Uid)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn fmt.Errorf(\"session [%v] not found\", payload.Join.Sid)\n\t\t\t\t}\n\t\t\t}\n\t\tcase reply, ok := <-repCh:\n\t\t\tif ok {\n\t\t\t\terr := sstream.Send(reply)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"sstream.Send(reply) failed %v\", err)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn io.EOF\n\t\t}\n\t}\n}", "func SetupSignal() {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM)\n\tfor {\n\t\ts := <-c\n\t\tlog.WithField(\"signal\", s.String()).Info(\"signal\")\n\t\tswitch s {\n\t\tcase os.Interrupt, syscall.SIGTERM:\n\t\t\treturn\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}", "func testServiceSignalReceiver(cmd cmdType, t *testing.T) {\n\texpectedCmd := cmd.toServiceSignal()\n\tserviceCmd := <-globalServiceSignalCh\n\tif serviceCmd != expectedCmd {\n\t\tt.Errorf(\"Expected service command %v but received %v\", expectedCmd, serviceCmd)\n\t}\n}", "func (m *Manager) SendSignals() {\n\tnow := time.Now()\n\tfor m.notifications.Len() > 0 {\n\t\tpeek := m.notifications.Peek()\n\t\tif now.Before(peek.timestamp) {\n\t\t\treturn\n\t\t}\n\t\tnote := heap.Pop(&m.notifications).(*Notification)\n\t\tnote.sensor.Notify(note.signal)\n\t}\n}", "func (srv *Server) StopNotify() <-chan struct{} {\n return srv.stopc\n}", "func syncChain(ctx context.Context, l log.Logger, safe *cryptoSafe, from *Beacon, toRound uint64, client net.ProtocolClient) (chan *Beacon, error) {\n\toutCh := make(chan *Beacon, toRound-from.Round)\n\tfromRound := from.Round\n\tdefer l.Debug(\"sync_from\", fromRound, \"leaving\")\n\n\tinfo, err := safe.GetInfo(fromRound)\n\tif err != nil {\n\t\tl.Error(\"sync_no_round_info\", fromRound)\n\t\treturn nil, errors.New(\"no round info\")\n\t}\n\tvar lastBeacon = from\n\tids := shuffleNodes(info.group.Nodes)\n\tgo func() {\n\t\tdefer close(outCh)\n\t\tfor _, id := range ids {\n\t\t\tif id.Equal(info.id) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trequest := &proto.SyncRequest{\n\t\t\t\tFromRound: lastBeacon.Round + 1,\n\t\t\t}\n\t\t\tl.Debug(\"sync_from\", \"try_sync\", \"to\", id.Addr, \"from_round\", fromRound+1)\n\t\t\tcctx, ccancel := context.WithCancel(context.Background())\n\t\t\trespCh, err := client.SyncChain(cctx, id, request)\n\t\t\tif err != nil {\n\t\t\t\tl.Error(\"sync_from\", fromRound+1, \"error\", err, \"from\", id.Address())\n\t\t\t\tccancel()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfunc() {\n\t\t\t\taddr := id.Address()\n\t\t\t\tdefer ccancel()\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase proto := <-respCh:\n\t\t\t\t\t\tif proto == nil {\n\t\t\t\t\t\t\t// because of the \"select\" behavior, sync returns an\n\t\t\t\t\t\t\t// default proto beacon - that means channel is down\n\t\t\t\t\t\t\t// so we log that as so\n\t\t\t\t\t\t\tl.Debug(\"sync_from\", addr, \"from_round\", fromRound, \"sync_stopped\")\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tl.Debug(\"sync_from\", addr, \"from_round\", fromRound, \"got_round\", proto.GetRound())\n\t\t\t\t\t\tnewBeacon := protoToBeacon(proto)\n\t\t\t\t\t\tif !isAppendable(lastBeacon, newBeacon) {\n\t\t\t\t\t\t\tl.Error(\"sync_from\", addr, \"from_round\", fromRound, \"want_round\", lastBeacon.Round+1, \"got_round\", newBeacon.Round)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tinfo, err := safe.GetInfo(newBeacon.Round)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tl.Error(\"sync_from\", addr, \"invalid_round_info\", newBeacon.Round)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\terr = VerifyBeacon(info.pub.Commit(), newBeacon)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tl.Error(\"sync_from\", addr, \"invalid_beacon_sig\", err, \"round\", newBeacon.Round)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastBeacon = newBeacon\n\t\t\t\t\t\toutCh <- newBeacon\n\t\t\t\t\tcase <-time.After(MaxSyncWaitTime):\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase <-ctx.Done():\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\tif lastBeacon.Round == toRound {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn outCh, nil\n}", "func (s *ShutdownManager) SignalShutdown() {\n\ts.ShutdownState = true\n}", "func (t *Broadcaster) Signal(ctx context.Context) error {\n\tif !t.mutex.RTryLock(ctx) {\n\t\treturn context.DeadlineExceeded\n\t}\n\tdefer t.mutex.RUnlock()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn context.DeadlineExceeded\n\tcase t.channel <- struct{}{}:\n\tdefault:\n\t}\n\n\treturn nil\n}", "func (c *Client) syncChannel(ctx context.Context, ch *persistence.Channel, p wire.Address) (err error) {\n\trecv := wire.NewReceiver()\n\tdefer recv.Close() // ignore error\n\tid := ch.ID()\n\terr = c.conn.Subscribe(recv, func(m *wire.Envelope) bool {\n\t\tmsg, ok := m.Msg.(*ChannelSyncMsg)\n\t\treturn ok && msg.ID() == id\n\t})\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"subscribing on relay\")\n\t}\n\n\tsendError := make(chan error, 1)\n\t// syncMsg needs to be a clone so that there's no data race when updating the\n\t// own channel data later.\n\tsyncMsg := newChannelSyncMsg(persistence.CloneSource(ch))\n\tgo func() { sendError <- c.conn.pubMsg(ctx, syncMsg, p) }()\n\tdefer func() {\n\t\t// When returning, either log the send error, or return it.\n\t\tsendErr := <-sendError\n\t\tif err == nil {\n\t\t\terr = errors.WithMessage(sendErr, \"sending sync message\")\n\t\t} else if err != nil && sendErr != nil {\n\t\t\tc.logChan(id).Errorf(\"Error sending sync message: %v\", sendErr)\n\t\t}\n\t}()\n\n\t// Receive sync message.\n\tenv, err := recv.Next(ctx)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"receiving sync message\")\n\t}\n\tmsg, ok := env.Msg.(*ChannelSyncMsg)\n\tif !ok {\n\t\tlog.Panic(\"internal error: wrong message type\")\n\t}\n\t// Validate sync message.\n\tif err := validateMessage(ch, msg); err != nil {\n\t\treturn errors.WithMessage(err, \"invalid message\")\n\t}\n\t// Merge restored state with received state.\n\tif msg.CurrentTX.Version > ch.CurrentTXV.Version {\n\t\tch.CurrentTXV = msg.CurrentTX\n\t}\n\n\treturn revisePhase(ch)\n}", "func (s *engine) signalShutdown() {\n\ts.cond.L.Lock()\n\ts.cond.Signal()\n\ts.cond.L.Unlock()\n}", "func asyncNotifyCh(ch chan struct{}) {\n\tselect {\n\tcase ch <- struct{}{}:\n\tdefault:\n\t}\n}", "func wait() {\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, os.Interrupt, os.Kill)\n\t<-sig\n\tfmt.Println()\n}", "func wait() {\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, os.Interrupt, os.Kill)\n\t<-sig\n\tfmt.Println()\n}", "func indefLoop() { \n\nc := make(chan os.Signal, 1)\nsignal.Notify(c,\n\n\tsyscall.SIGINT,)\n//En uendlig for loop som skriver \"Loooooooooop\" og sjekker etter syscall\nfor {\n\n\tfmt.Println(\"Loooooooooooooop\")\n\n\ta := <-c\n\n\tswitch a {\n\n\tcase syscall.SIGINT:\n\n\t\tfmt.Println(\"You shall not pass SIGINT\")\n\t}\n\tbreak\n}\n}", "func signal_recv() string {\n\tfor {\n\t\tnote := sig.q.pop()\n\t\tif note != nil {\n\t\t\treturn gostring(note)\n\t\t}\n\n\t\tlock(&sig.lock)\n\t\tsig.sleeping = true\n\t\tnoteclear(&sig.note)\n\t\tunlock(&sig.lock)\n\t\tnotetsleepg(&sig.note, -1)\n\t}\n}", "func chanMonitor( wg *sync.WaitGroup, ch chan string ){\n\twg.Wait()\n\tclose( ch )\n}", "func (srv *Server) handleSignal(msg *Message) {\n\tsrv.opsLock.Lock()\n\t// Ignore incoming signals during shutdown\n\tif srv.shutdown {\n\t\tsrv.opsLock.Unlock()\n\t\treturn\n\t}\n\tsrv.currentOps++\n\tsrv.opsLock.Unlock()\n\n\tsrv.hooks.OnSignal(context.WithValue(context.Background(), Msg, *msg))\n\n\t// Mark signal as done and shutdown the server if scheduled and no ops are left\n\tsrv.opsLock.Lock()\n\tsrv.currentOps--\n\tif srv.shutdown && srv.currentOps < 1 {\n\t\tclose(srv.shutdownRdy)\n\t}\n\tsrv.opsLock.Unlock()\n}", "func handlerSignal() {\n\texpectedSignals := make(chan os.Signal, 1)\n\tdoneSignals := make(chan bool, 1)\n\n\t// register channel to receive 2 signals\n\tsignal.Notify(expectedSignals, syscall.SIGTERM, syscall.SIGINT)\n\n\t// this routine is blocking, i.e. when it gets one signal it prints it and notifies the program that it can finish\n\tgo func() {\n\t\tsig := <-expectedSignals\n\t\tfmt.Println()\n\t\tfmt.Println(sig.String())\n\t\tdoneSignals <- true\n\t}()\n\n\tfmt.Println(\"awaiting signal...\")\n\n\t<-doneSignals\n\n\tfmt.Println(\"exiting...\")\n}", "func (s *stream) Sync() error {\n\tx := C.hipStreamSynchronize((s.s))\n\tif x == 0 {\n\t\treturn nil\n\t}\n\treturn errors.New(\"Error with HIP stream \")\n}", "func (p *hub) SyncPush(caller ICaller, ds IDataSet) error {\n return p.notify(C_Mode_Push, caller, ds)\n}", "func (o *Wireless) HasSignal() bool {\n\tif o != nil && o.Signal != nil {\n\t\treturn true\n\t}\n\n\treturn false\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 (d *Data) SyncPending() bool {\n\tif manager == nil {\n\t\treturn false\n\t}\n\tr, err := manager.repoFromUUID(d.rootUUID)\n\tif err != nil {\n\t\treturn false\n\t}\n\t// Check if this data instance has any subscriptions and if so, are there messages in the channel.\n\tfor _, subs := range r.subs {\n\t\tfor _, sub := range subs {\n\t\t\tif sub.Notify == d.dataUUID && len(sub.Ch) > 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func sendSignal(status string) {\n\tcf := cloudformation.New(session.New(&aws.Config{Region: &region}))\n\tparams := &cloudformation.SignalResourceInput{\n\t\tLogicalResourceId: &resource,\n\t\tStackName: &stack,\n\t\tStatus: &status,\n\t\tUniqueId: &uniqueID,\n\t}\n\t_, err := cf.SignalResource(params)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to signal CloudFormation: %q.\\n\", err.Error())\n\t}\n\tlog.Printf(\"Sent a %q signal to CloudFormation.\\n\", status)\n\treturn\n}", "func (f *Pub) CloseNotify() <-chan bool {\n\treturn f.csignal\n}", "func (f *ClientFD) Sync(ctx context.Context) error {\n\treq := FsyncReq{FDs: []FDID{f.fd}}\n\tctx.UninterruptibleSleepStart(false)\n\terr := f.client.SndRcvMessage(FSync, uint32(req.SizeBytes()), req.MarshalBytes, NoopUnmarshal, nil)\n\tctx.UninterruptibleSleepFinish(false)\n\treturn err\n}", "func (p *Peer) subscribeSync(po int) {\n\terr := subscriptionFunc(p.streamer, p.ID(), uint8(po))\n\tif err != nil {\n\t\tlog.Error(\"subscription\", \"err\", err)\n\t}\n}", "func (s *BasevhdlListener) EnterSignal_mode(ctx *Signal_modeContext) {}", "func (l *CommandQueueStatusListener) Notify() {\n\tselect {\n\tcase <-l.closeSignal:\n\tcase l.signal <- true:\n\tdefault:\n\t}\n}", "func (o *Wireless) SetSignal(v int32) {\n\to.Signal = &v\n}", "func notifyReady() {\n}", "func Lock(ch chan os.Signal) {\n\tdefer func() {\n\t\tch <- os.Interrupt\n\t}()\n\t// The correctness of the application is closed by a signal\n\tsignal.Notify(ch,\n\t\tsyscall.SIGHUP,\n\t\tsyscall.SIGINT,\n\t\tsyscall.SIGTERM,\n\t\tsyscall.SIGQUIT,\n\t)\n\t<-ch\n}", "func (g *Pin) Notify(sig ...os.Signal) {\n\tc := make(chan os.Signal)\n\tsignal.Notify(c, sig...)\n\tgo func() {\n\t\tn := 0\n\t\tfor sig := range c {\n\t\t\tif n == 1 {\n\t\t\t\tpanic(\"got too many signals\")\n\t\t\t}\n\t\t\tg.Pull(fmt.Errorf(\"Recieved signal %s\", sig))\n\t\t\tn++\n\t\t}\n\t}()\n}", "func doSignal() {\n\tstop := signals.NewStopChannel()\n\t<-stop\n\tlog.Println(\"Exit signal received. Shutting down.\")\n\tos.Exit(0)\n}" ]
[ "0.6650585", "0.6324423", "0.63086694", "0.6296415", "0.62081987", "0.6200955", "0.6140189", "0.61061984", "0.59654105", "0.59500754", "0.58846843", "0.5803719", "0.57892984", "0.57802", "0.57111305", "0.57061064", "0.5697602", "0.5669667", "0.56544584", "0.5636042", "0.5623236", "0.556044", "0.55548316", "0.55434126", "0.5532824", "0.5526143", "0.55219287", "0.55045366", "0.54942924", "0.5485344", "0.5466279", "0.5462069", "0.54608107", "0.546006", "0.5448269", "0.54480237", "0.54459226", "0.5438751", "0.5438294", "0.54357445", "0.54316854", "0.5431174", "0.5430128", "0.542887", "0.54232144", "0.54033196", "0.540272", "0.53852904", "0.5382137", "0.5352207", "0.53425735", "0.5335638", "0.5333996", "0.5320865", "0.5320211", "0.5313571", "0.5305791", "0.5298265", "0.52970207", "0.5296193", "0.5293576", "0.5288104", "0.52860403", "0.5277854", "0.5268446", "0.5260596", "0.5254872", "0.52520216", "0.52445424", "0.5236484", "0.523106", "0.5225364", "0.5222203", "0.52211636", "0.52195626", "0.5210735", "0.5202025", "0.5190674", "0.5190674", "0.51905847", "0.5183875", "0.51749045", "0.5171535", "0.5171425", "0.51701605", "0.5165951", "0.51587355", "0.5156384", "0.51496303", "0.51477367", "0.5147611", "0.5146208", "0.5146169", "0.51441455", "0.51437193", "0.51432234", "0.5142129", "0.51383215", "0.5135536", "0.5121604" ]
0.5385494
47
NewPoolingHandler creates a new http handler that checks if the user is authenticated if so it gets the user's waiting messages
func NewPoolingHandler(validator auth.Validator, handler MessagesRetriever, logger log.FieldLogger) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { logger.Info("received new pooling request") w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin")) w.Header().Set("Access-Control-Allow-Credentials", "true") cookie, err := r.Cookie(config.TokenName) if err != nil { w.WriteHeader(http.StatusUnauthorized) logger.Warn("request with no token") return } username, err := validator.Validate(cookie.Value) if err != nil { w.WriteHeader(http.StatusUnauthorized) logger.Warn("validate error\t", err) return } logger.Info("validated user\t", username) msgs := handler.GetUserMessages(username) if len(msgs) == 0 { w.WriteHeader(http.StatusNoContent) logger.Warn("no messages found for user:\t", username) return } logger.Debug(fmt.Sprintf("found %v messages for user:\t%s", len(msgs), username)) content, err := json.Marshal(msgs) if err != nil { w.WriteHeader(http.StatusInternalServerError) logger.Warn("err while marshaling the messages:\t", err) return } _, err = w.Write(content) if err != nil { w.WriteHeader(http.StatusInternalServerError) logger.Warn("err while writing the messages to the respond:\t", err) return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func createPoolHandler(cliCtx client.Context) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar req CreatePoolReq\n\t\tif !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) {\n\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, \"failed to parse request\")\n\t\t\treturn\n\t\t}\n\n\t\treq.BaseReq = req.BaseReq.Sanitize()\n\t\tif !req.BaseReq.ValidateBasic(w) {\n\t\t\treturn\n\t\t}\n\n\t\tsigner, err := sdk.AccAddressFromBech32(req.Signer)\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tmsg := types.NewMsgCreatePool(signer, req.ExternalAsset, req.NativeAssetAmount, req.ExternalAssetAmount)\n\n\t\terr = msg.ValidateBasic()\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, &msg)\n\t}\n}", "func NewHandler(bouncer *security.RequestBouncer, rateLimiter *security.RateLimiter, authDisabled bool) *Handler {\n\th := &Handler{\n\t\tRouter: mux.NewRouter(),\n\t\tauthDisabled: authDisabled,\n\t}\n\th.Handle(\"/auth\",\n\t\trateLimiter.LimitAccess(bouncer.PublicAccess(httperror.LoggerHandler(h.authenticate)))).Methods(http.MethodPost)\n\n\treturn h\n}", "func NewUserHandler() *UserHandler {\n h := &UserHandler{\n Router: httprouter.New(),\n Logger: log.New(os.Stderr, \"\", log.LstdFlags),\n }\n h.POST(\"/api/user\", h.handlePostUser)\n return h\n}", "func RegisterPoolHandler(httpSvr *HTTPService, logic *netservice.NetService) *PoolHandler {\n\thandler := &PoolHandler{\n\t\tnetSvr: logic,\n\t}\n\twebSvr := new(restful.WebService)\n\t//add http handler\n\twebSvr.Path(\"/v1/pool\").Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON)\n\t//Add pool\n\twebSvr.Route(webSvr.POST(\"\").To(handler.Add))\n\t//get all pool info\n\twebSvr.Route(webSvr.GET(\"\").To(handler.List))\n\t//Delete by pool net\n\twebSvr.Route(webSvr.DELETE(\"/{cluster}/{net}\").To(handler.Delete))\n\t//update by pool net\n\twebSvr.Route(webSvr.PUT(\"/{cluster}/{net}\").To(handler.Update))\n\t//get one pool by net\n\twebSvr.Route(webSvr.GET(\"/{cluster}/{net}\").To(handler.ListByID))\n\t//query cluster info, query parameter\n\t//info:\n\t// static(default): static info for cluster\n\t// detail: all pool info under cluster\n\t//sort: (todo feature)\n\twebSvr.Route(webSvr.GET(\"/{cluster}\").To(handler.Query))\n\n\thttpSvr.Register(webSvr)\n\n\treturn handler\n}", "func NewHandler(s service.Service) http.Handler {\n\tr := mux.NewRouter()\n\t// base handler\n\tbase := alice.New(newSetUserMid(s))\n\t// handler with auth required\n\tauthRequired := base.Append(newAuthRequiredMid)\n\n\th := &handler{s}\n\n\t// r.PathPrefix(\"/images\").Handler(httputil.NewSingleHostReverseProxy(proxyURL))\n\tr.Handle(\"/v1/login\", base.Then(errHandler(h.register))).Methods(http.MethodPost)\n\tr.Handle(\"/v1/me\", authRequired.Then(errHandler(h.me))).Methods(http.MethodGet)\n\tr.Handle(\"/v1/me\", authRequired.Then(errHandler(h.update))).Methods(http.MethodPatch)\n\tr.Handle(\"/v1/me/reacts\", authRequired.Then(errHandler(h.react))).Methods(http.MethodPost)\n\tr.Handle(\"/v1/me/abuses\", authRequired.Then(errHandler(h.reportAbuse))).Methods(http.MethodPost)\n\n\tr.Handle(\"/v1/me/discover-people\", authRequired.Then(errHandler(h.discoverPeople))).Methods(http.MethodGet)\n\n\tr.Handle(\"/v1/me/pictures\", authRequired.Then(errHandler(h.uploadPicture))).Methods(http.MethodPost)\n\tr.Handle(\"/v1/me/pictures\", authRequired.Then(errHandler(h.pictures))).Methods(http.MethodGet)\n\tr.Handle(\"/v1/me/pictures/{id}\", authRequired.Then(errHandler(h.deletePicture))).Methods(http.MethodDelete)\n\tr.Handle(\"/v1/me/pictures/{id}/profile\", authRequired.Then(errHandler(h.setProfilePicture))).Methods(http.MethodPut)\n\n\treturn r\n}", "func NewHandler(entrypoint, network, address string) http.Handler {\n\tconnFactory := gofast.SimpleConnFactory(network, address)\n\tpool := gofast.NewClientPool(\n\t\tgofast.SimpleClientFactory(connFactory),\n\t\t10,\n\t\t60*time.Second,\n\t)\n\th := gofast.NewHandler(\n\t\tgofast.NewFileEndpoint(entrypoint)(gofast.BasicSession),\n\t\tpool.CreateClient,\n\t)\n\treturn h\n}", "func (s *Server) newHandler() http.Handler {\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/register\", s.wrapMiddleware(registerHandler)).Methods(\"POST\")\n\tr.HandleFunc(\"/session/{id}\", s.wrapMiddleware(getHandler)).Methods(\"GET\")\n\tr.HandleFunc(\"/session\", s.wrapMiddleware(createHandler)).Methods(\"POST\")\n\tr.HandleFunc(\"/readiness\", predis.NewReadinessCheck(s.pool))\n\n\treturn r\n}", "func (p DirectHandler) AuthHandler(http.ResponseWriter, *http.Request) {}", "func (p *PoolID) Handler(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\n\t\tr = r.WithContext(context.WithValue(r.Context(), poolIDKey, p.Pool))\n\t\tr.Header.Set(Conf.GetString(ConfigPoolHeaderName), p.Pool)\n\n\t\tnext.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func authHandler(handler http.Handler) http.Handler {\n\tauth := readBasicAuth()\n\tif auth.Username != \"\" && auth.Password != \"\" {\n\t\tlog.Println(\"HTTP Basic authentication is enabled.\")\n\t\treturn &basicAuthHandler{basicAuth: *auth, nextHandler: handler}\n\t}\n\n\treturn handler\n}", "func NewHandler(e *echo.Group, us domain.UserService) *Handler {\n\th := &Handler{us}\n\te.POST(\"/user/login\", h.Login)\n\te.POST(\"/user/register\", h.Register)\n\treturn h\n}", "func addPool(\n\thandle string, context ServerContext, access Access,\n) (*pool, error) {\n\tthis := &pool{\n\t\thandle: handle,\n\t\tusers: newUserPool(),\n\t}\n\n\t// Add self to pool\n\tthis.users.add(handle)\n\n\t// Update data\n\tif err := access.Save(this, true, context); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"Created new pool for user \\\"%s\\\"\", this.handle)\n\n\treturn this, nil\n}", "func MustAuth(handler http.Handler) http.Handler {\n return &authHandler{next: handler}\n}", "func NoAuthHandler(handler RequestHandler) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\t\t// Measure time spent executing shit\n\t\tstart := time.Now()\n\n\t\t// Pass to the real handler\n\t\tresponse, statusCode, err := handler(r, params)\n\n\t\t// Logs [source IP] [request method] [request URL] [HTTP status] [time spent serving request]\n\t\tlog.Printf(\"%v\\t \\\"%v - %v\\\"\\t%v\\t%v\", sourceIP(r), r.Method, r.RequestURI, statusCode, time.Since(start))\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), statusCode)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(statusCode)\n\t\tfmt.Fprintln(w, response)\n\t}\n}", "func NewHandler(userHelper *Helper, allowUserCreation bool) *Handler {\n\t//Build a new User Handler\n\thandler := Handler{\n\t\tuserHelper: userHelper,\n\t\tallowUserCreation: allowUserCreation,\n\t}\n\n\treturn &handler\n}", "func CreateHandler(r *mux.Router, usecase user.UserUsecase) {\n\tuserHandler := UserHandler{usecase}\n\n\tr.HandleFunc(\"/login\", userHandler.loginUser).Methods(http.MethodPost)\n\tr.HandleFunc(\"/register\", userHandler.createUser).Methods(http.MethodPost)\n\n\t// make a new subrouter when you want to grouping where path want to be protect and nah\n\tauthorized := r.NewRoute().Subrouter()\n\tauthorized.Use(middlewares.SetMiddlewareAuthentication)\n\tauthorized.HandleFunc(\"/user\", userHandler.findAll).Methods(http.MethodGet)\n\tauthorized.HandleFunc(\"/user/{id}\", userHandler.findByID).Methods(http.MethodGet)\n\tauthorized.HandleFunc(\"/user/{id}\", userHandler.updateUser).Methods(http.MethodPut)\n\tauthorized.HandleFunc(\"/user/{id}\", userHandler.deleteUser).Methods(http.MethodDelete)\n\n\t// make a new subrouter extends a authorized path\n\tuploadRequest := authorized.PathPrefix(\"/user\").Subrouter()\n\tuploadRequest.Use(middlewares.FileSizeLimiter) // use middleware to limited size when upload file\n\tuploadRequest.HandleFunc(\"/photo/{id}\", userHandler.handlingPhoto).Methods(http.MethodPost)\n}", "func (e VerifyHandler) AuthHandler(http.ResponseWriter, *http.Request) {}", "func NewPylonHandler(p *Pylon) http.HandlerFunc {\r\n\treturn func(w http.ResponseWriter, r *http.Request) {\r\n\t\t//route, err := p.getRoute(r.URL.Path)\r\n\t\t//if err != nil {\r\n\t\t//\tlogError(err)\r\n\t\t//\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\t\t//\treturn\r\n\t\t//}\r\n\t\tm, err := p.getMicroServiceFromRoute(r.URL.Path)\r\n\t\tif err != nil || m == nil {\r\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\t\t\treturn\r\n\t\t}\r\n\t\tinst, _, err := m.getLoadBalancedInstance()\r\n\t\tif err != nil {\r\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\t\t\treturn\r\n\t\t}\r\n\r\n\t\tm.ReqCount <- 1\r\n\t\tinst.ReqCount <- 1\r\n\r\n\t\tlogVerbose(\"Serving \" + r.URL.Path + r.URL.RawQuery + \", current request count: \" + strconv.Itoa(len(m.ReqCount)))\r\n\t\tlogVerbose(\"Instance is \" + inst.Host)\r\n\t\tproxy := proxyPool.Get()\r\n\t\tsetUpProxy(proxy, m, inst.Host)\r\n\t\tproxy.ServeHTTP(w, r)\r\n\t\tproxyPool.Put(proxy)\r\n\r\n\t\t<-inst.ReqCount\r\n\t\t<-m.ReqCount\r\n\t\tlogVerbose(\"Request served, count: \" + strconv.Itoa(len(m.ReqCount)))\r\n\t}\r\n}", "func NewHandler(_ context.Context, svr *server.Server) (http.Handler, apiutil.APIServiceGroup, error) {\n\tautoScalingHandler := http.NewServeMux()\n\trd := render.New(render.Options{\n\t\tIndentJSON: true,\n\t})\n\tautoScalingHandler.Handle(autoScalingPrefix, negroni.New(\n\t\tserverapi.NewRedirector(svr),\n\t\tnegroni.Wrap(NewHTTPHandler(svr, rd))),\n\t)\n\treturn autoScalingHandler, autoscalingServiceGroup, nil\n}", "func NewHTTPHandler(bh *handler.BaseHTTPHandler, bu *usecase.BaseUsecase, br *repository.BaseRepository, s *infrastructure.SQL) *HTTPHandler {\n\t// user set.\n\tuserRepo := NewRepository(br, s.Master, s.Read)\n\tuserUsecase := NewUsecase(bu, s.Master, userRepo)\n\treturn &HTTPHandler{BaseHTTPHandler: *bh, usecase: userUsecase}\n}", "func NewHandler() inputs.Handler {\n\treturn &Handler{\n\t\tin: make(chan inputs.Data, 20),\n\t\thosts: []string{},\n\t\tcreds: []scanners.Credential{},\n\t}\n}", "func newPortPoolHandler(ns, region string,\n\tlbClient cloud.LoadBalance, k8sClient client.Client, poolCache *portpoolcache.Cache) *PortPoolHandler {\n\treturn &PortPoolHandler{\n\t\tnamespace: ns,\n\t\tregion: region,\n\t\tk8sClient: k8sClient,\n\t\tlbClient: lbClient,\n\t\tpoolCache: poolCache,\n\t}\n}", "func NewHandler(config *config.Config) *handler {\n\th := &handler{\n\t\tdailInfo: &mgo.DialInfo{\n\t\t\tPoolLimit: 4096,\n\t\t\tTimeout: time.Second,\n\t\t\tFailFast: true,\n\t\t\tUsername: config.Storage.Username,\n\t\t\tPassword: config.Storage.Password,\n\t\t\tAddrs: []string{config.Storage.Address},\n\t\t\tDatabase: config.Storage.Database,\n\t\t},\n\t\tdatabase: config.Storage.Database,\n\t}\n\treturn h\n}", "func makeHealthHandler() func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch r.Method {\n\t\tcase http.MethodGet:\n\t\t\tif atomic.LoadInt32(&acceptingConnections) == 0 || lockFilePresent() == false {\n\t\t\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tw.Write([]byte(\"OK\"))\n\n\t\t\tbreak\n\t\tdefault:\n\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t}\n\t}\n}", "func (s server) Handle(w http.ResponseWriter, r *http.Request) {\n\t/* If we have creds set, check them */\n\tif \"\" != s.username || \"\" != s.password {\n\t\tw.Header().Set(\n\t\t\t\"WWW-Authenticate\",\n\t\t\t`Basic realm=\"Auth Required\"`,\n\t\t)\n\t\tu, p, ok := r.BasicAuth()\n\t\tif !ok || (\"\" == u && \"\" == p) { /* Client didn't know? */\n\t\t\tlog.Printf(\"[%v] No auth\", r.RemoteAddr)\n\t\t\thttp.Error(w, \"Not authorized\", 401)\n\t\t\treturn\n\t\t}\n\t\tif u != s.username || p != s.password {\n\t\t\tlog.Printf(\n\t\t\t\t\"[%s] Auth fail (%q / %q)\",\n\t\t\t\tr.RemoteAddr,\n\t\t\t\tu,\n\t\t\t\tp,\n\t\t\t)\n\t\t\thttp.Error(w, \"Not authorized\", 401)\n\t\t\treturn\n\t\t}\n\t}\n\n\tlogReq(r)\n\n\t/* Special cases sometimes */\n\tswitch r.Method {\n\tcase http.MethodDelete: /* We may not allow deletes */\n\t\tif s.noDelete {\n\t\t\treturn\n\t\t}\n\tcase http.MethodGet: /* Maybe serve a single file */\n\t\tif \"\" != s.serveFile {\n\t\t\thttp.ServeFile(w, r, s.serveFile)\n\t\t\treturn\n\t\t}\n\t}\n\n\t/* If we're only allowing read access, whitelist the allowed methods */\n\tif s.readOnly {\n\t\tswitch r.Method {\n\t\tcase \"OPTIONS\", \"GET\", \"HEAD\", \"PROPFIND\":\n\t\t\t/* These are ok */\n\t\tdefault:\n\t\t\t/* This is not ok */\n\t\t\treturn\n\t\t}\n\t}\n\n\ts.w.ServeHTTP(w, r)\n}", "func HandleNew() http.HandlerFunc {\n\tdb, err := sql.Open(\"mysql\", \"root:my-secret-pw@/goauth\")\n\tif err != nil {\n\t\tlog.Fatalf(\"could not establish database connection: %v\", err)\n\t}\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tencoder := json.NewEncoder(w)\n\t\tvars := mux.Vars(r)\n\t\temail, ok := vars[\"email\"]\n\t\tif !ok {\n\t\t\tlog.Fatalln(\"no `email` in URL for HandleNew() handler\")\n\t\t}\n\n\t\tvar id int64\n\t\trow := db.QueryRow(\"SELECT id FROM users WHERE email = ?\", email)\n\t\terr := row.Scan(&id)\n\t\tif err == sql.ErrNoRows {\n\t\t\tw.WriteHeader(404)\n\t\t\terr := encoder.Encode(map[string]string{\n\t\t\t\t\"error\": \"email not found\",\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tvar req createNewRequest\n\t\terr = json.NewDecoder(r.Body).Decode(&req)\n\t\tif err != nil {\n\t\t\t// TODO make response format consistent\n\t\t\thttp.Error(w, \"bad request\", 400)\n\t\t\treturn\n\t\t}\n\n\t\terrors := req.validate()\n\t\tif len(errors) > 0 {\n\t\t\tw.WriteHeader(400)\n\t\t\terr := encoder.Encode(map[string]interface{}{\n\t\t\t\t\"errors\": errors,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tstmt, err := db.Prepare(\"INSERT INTO scopes (user_id, scope) VALUES (?, ?)\")\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"internal error\", 500)\n\t\t\tlog.Printf(\"could not create insert statement: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\t_, err = stmt.Exec(id, req.Scope)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"internal error\", 500)\n\t\t\tlog.Printf(\"error while inserting scope: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(201)\n\t\tencoder.Encode(map[string]string{\n\t\t\t\"message\": \"scope created\",\n\t\t})\n\t}\n}", "func newHandler(conn net.Conn, l logger, c *config, users map[string]string) (*handler, error) {\n\t// get current directory\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a new handler object\n\th := &handler{\n\t\tconfig: c,\n\t\tconn: conn,\n\t\tlogger: l,\n\t\tdir: dir,\n\t\tusers: users,\n\t\tisLoggedIn: false,\n\t\tcommands: make(map[CommandCode]handleFunc),\n\t}\n\n\th.logMessage(fmt.Sprintf(\"Accepted connection from %v\", h.conn.RemoteAddr()))\n\n\t// initialize commands for not logged in state\n\th.initCommandTable()\n\n\t//initialize default data connection\n\tif h.config.pasv {\n\t\th.initPassiveDataConn()\n\t} else {\n\t\t// calculate default data port\n\t\thost, port, err := net.SplitHostPort(conn.RemoteAddr().String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar portNum int\n\t\t_, err = fmt.Sscanf(port, \"%d\", &portNum)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tportNum++\n\t\tport = fmt.Sprintf(\"%d\", portNum)\n\t\th.initActiveDataConn(net.JoinHostPort(host, port))\n\t}\n\n\treturn h, nil\n}", "func NewHandler() http.Handler {\n\tuserMap = make(map[int]*User)\n\tlastId = 0\n\n\tmux := mux.NewRouter()\n\tmux.HandleFunc(\"/\", indexHandler)\n\tmux.HandleFunc(\"/users\", usersHandler).Methods(http.MethodGet)\n\tmux.HandleFunc(\"/users\", createUserHandler).Methods(http.MethodPost)\n\tmux.HandleFunc(\"/users/{id:[0-9a-z]+}\", getUserInfoHandler).Methods(http.MethodGet)\n\tmux.HandleFunc(\"/users/{id:[0-9a-z]+}\", deleteUserInfoHandler).Methods(http.MethodDelete)\n\tmux.HandleFunc(\"/users/{id:[0-9a-z]+}\", updateUserInfoHandler).Methods(http.MethodPut)\n\treturn mux\n}", "func handlerAuthCheck(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch adminConfig.Auth {\n\t\tcase settings.AuthDB:\n\t\t\t// Check if user is already authenticated\n\t\t\tauthenticated, session := sessionsmgr.CheckAuth(r)\n\t\t\tif !authenticated {\n\t\t\t\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Set middleware values\n\t\t\ts := make(sessions.ContextValue)\n\t\t\ts[ctxUser] = session.Username\n\t\t\ts[ctxCSRF] = session.Values[ctxCSRF].(string)\n\t\t\tctx := context.WithValue(r.Context(), sessions.ContextKey(\"session\"), s)\n\t\t\t// Update metadata for the user\n\t\t\tif err := adminUsers.UpdateMetadata(session.IPAddress, session.UserAgent, session.Username, s[\"csrftoken\"]); err != nil {\n\t\t\t\tlog.Printf(\"error updating metadata for user %s: %v\", session.Username, err)\n\t\t\t}\n\t\t\t// Access granted\n\t\t\th.ServeHTTP(w, r.WithContext(ctx))\n\t\tcase settings.AuthSAML:\n\t\t\t_, err := samlMiddleware.Session.GetSession(r)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"GetSession %v\", err)\n\t\t\t}\n\t\t\tcookiev, err := r.Cookie(samlConfig.TokenName)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error extracting JWT data: %v\", err)\n\t\t\t\thttp.Redirect(w, r, samlConfig.LoginURL, http.StatusFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tjwtdata, err := parseJWTFromCookie(samlData.KeyPair, cookiev.Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error parsing JWT: %v\", err)\n\t\t\t\thttp.Redirect(w, r, samlConfig.LoginURL, http.StatusFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Check if user is already authenticated\n\t\t\tauthenticated, session := sessionsmgr.CheckAuth(r)\n\t\t\tif !authenticated {\n\t\t\t\t// Create user if it does not exist\n\t\t\t\tif !adminUsers.Exists(jwtdata.Username) {\n\t\t\t\t\tlog.Printf(\"user not found: %s\", jwtdata.Username)\n\t\t\t\t\thttp.Redirect(w, r, forbiddenPath, http.StatusFound)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tu, err := adminUsers.Get(jwtdata.Username)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"error getting user %s: %v\", jwtdata.Username, err)\n\t\t\t\t\thttp.Redirect(w, r, forbiddenPath, http.StatusFound)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\taccess, err := adminUsers.GetEnvAccess(u.Username, u.DefaultEnv)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"error getting access for %s: %v\", jwtdata.Username, err)\n\t\t\t\t\thttp.Redirect(w, r, forbiddenPath, http.StatusFound)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Create new session\n\t\t\t\tsession, err = sessionsmgr.Save(r, w, u, access)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"session error: %v\", err)\n\t\t\t\t\thttp.Redirect(w, r, samlConfig.LoginURL, http.StatusFound)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Set middleware values\n\t\t\ts := make(sessions.ContextValue)\n\t\t\ts[ctxUser] = session.Username\n\t\t\ts[ctxCSRF] = session.Values[ctxCSRF].(string)\n\t\t\tctx := context.WithValue(r.Context(), sessions.ContextKey(\"session\"), s)\n\t\t\t// Update metadata for the user\n\t\t\terr = adminUsers.UpdateMetadata(session.IPAddress, session.UserAgent, session.Username, s[\"csrftoken\"])\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error updating metadata for user %s: %v\", session.Username, err)\n\t\t\t}\n\t\t\t// Access granted\n\t\t\tsamlMiddleware.RequireAccount(h).ServeHTTP(w, r.WithContext(ctx))\n\t\t}\n\t})\n}", "func NewHandler(gp types.GamePoolAbstraction, m persistence.MongoAbstraction, l *log.Logger) (h *Handler) {\n\tif gp == nil {\n\t\tpanic(\"GamePool argument is nil\")\n\t}\n\tif m == nil {\n\t\tpanic(\"MongoSession argument is nil\")\n\t}\n\tif l == nil {\n\t\tpanic(\"Logger argument is nil\")\n\t}\n\th = &Handler{\n\t\tgPool: gp,\n\t\tmongo: m,\n\t\tlogger: l,\n\t}\n\tl.Printf(\"Startup: Handler created\")\n\treturn\n}", "func NewHandler(bouncer *security.RequestBouncer) *Handler {\n\th := &Handler{\n\t\tRouter: mux.NewRouter(),\n\t}\n\th.Handle(\"/endpoint_groups\",\n\t\tbouncer.AdministratorAccess(httperror.LoggerHandler(h.endpointGroupCreate))).Methods(http.MethodPost)\n\th.Handle(\"/endpoint_groups\",\n\t\tbouncer.RestrictedAccess(httperror.LoggerHandler(h.endpointGroupList))).Methods(http.MethodGet)\n\th.Handle(\"/endpoint_groups/{id}\",\n\t\tbouncer.AdministratorAccess(httperror.LoggerHandler(h.endpointGroupInspect))).Methods(http.MethodGet)\n\th.Handle(\"/endpoint_groups/{id}\",\n\t\tbouncer.AdministratorAccess(httperror.LoggerHandler(h.endpointGroupUpdate))).Methods(http.MethodPut)\n\th.Handle(\"/endpoint_groups/{id}/access\",\n\t\tbouncer.AdministratorAccess(httperror.LoggerHandler(h.endpointGroupUpdateAccess))).Methods(http.MethodPut)\n\th.Handle(\"/endpoint_groups/{id}\",\n\t\tbouncer.AdministratorAccess(httperror.LoggerHandler(h.endpointGroupDelete))).Methods(http.MethodDelete)\n\n\treturn h\n}", "func UserHandler(w http.ResponseWriter, r *http.Request) {\n\n\tlog.Debug(\"userservice.UserHandler called\")\n\n\tvar request msgs.UserRequest\n\t_ = json.NewDecoder(r.Body).Decode(&request)\n\n\tresp := msgs.UserResponse{}\n\tusername, err := apiserver.Authn(apiserver.USER_PERM, w, r)\n\tif err != nil {\n\t\tresp.Status = msgs.Status{Code: msgs.Error, Msg: apiserver.VERSION_MISMATCH_ERROR}\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"WWW-Authenticate\", `Basic realm=\"Restricted\"`)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\n\tif request.ClientVersion != msgs.PGO_VERSION {\n\t\tresp.Status = msgs.Status{Code: msgs.Error, Msg: apiserver.VERSION_MISMATCH_ERROR}\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tvar ns string\n\tns, err = apiserver.GetNamespace(apiserver.Clientset, username, request.Namespace)\n\tif err != nil {\n\t\tresp.Status = msgs.Status{Code: msgs.Error, Msg: err.Error()}\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tresp = User(&request, ns)\n\n\tjson.NewEncoder(w).Encode(resp)\n}", "func NewHandler(k Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) sdk.Result {\n\t\tswitch msg := msg.(type) {\n\t\tcase MsgRecordReputation:\n\t\t\treturn handleMsgRecordReputation(ctx, k, msg)\n\t\tdefault:\n\t\t\terrMsg := fmt.Sprintf(\"unrecognized %s message type: %T\", types.ModuleName, msg)\n\t\t\treturn sdk.ErrUnknownRequest(errMsg).Result()\n\t\t}\n\t}\n}", "func NewHandler(actions []webhook.Action) func(w http.ResponseWriter, r *http.Request) {\n\thttpHandler := func(w http.ResponseWriter, r *http.Request) {\n\n\t\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tdefer r.Body.Close()\n\n\t\tvar message DockerHub\n\t\tif err := json.Unmarshal(body, &message); err != nil {\n\t\t\tlog.Printf(\"got invalid webhook message %q\", err)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\t\tw.WriteHeader(422) // unprocessable entity\n\t\t\tfmt.Fprintf(w, \"Got an invalid webhook message. Please check the logs.\")\n\t\t} else {\n\t\t\tlog.Printf(\"got webhook message %v\", message)\n\n\t\t\tbackendImage := fmt.Sprintf(\"foo/backend:%s\", message.PushData.Images[0])\n\t\t\tfrontendImage := fmt.Sprintf(\"foo/frontend:%s\", message.PushData.Images[0])\n\t\t\tlog.Printf(\"going to deploy %q and %q\", frontendImage, backendImage)\n\n\t\t\t// docker pull foo/ansible:latest\n\t\t\t// docker run --rm -it .... foo/ansible deploy -t message.Docker.Images[0].Tag\n\t\t}\n\n\t}\n\treturn httpHandler\n}", "func NewHandler(keeper Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) sdk.Result {\n\t\tswitch msg := msg.(type) {\n\t\tcase MsgRegisterKey:\n\t\t\treturn handleMsgRegisterKey(ctx, keeper, msg)\n\t\tcase MsgUpdateParams:\n\t\t\treturn handleMsgUpdateParams(ctx, keeper, msg)\n\t\tdefault:\n\t\t\terrMsg := fmt.Sprintf(\"Unrecognized auth message type: %T\", msg)\n\t\t\treturn sdk.ErrUnknownRequest(errMsg).Result()\n\t\t}\n\t}\n}", "func AuthHandler(handler AuthorisedRequestHandler) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\t\t// Measure time spent executing shit\n\t\tstart := time.Now()\n\n\t\t// Authorize request\n\t\terr := authorize(r)\n\t\tif err != nil {\n\t\t\t// Logs [source IP] [request method] [request URL] [HTTP status] [time spent serving request]\n\t\t\tlog.Printf(\"%v\\t \\\"%v - %v\\\"\\t%v\\t%v\", sourceIP(r), r.Method, r.RequestURI, http.StatusUnauthorized, time.Since(start))\n\t\t\thttp.Error(w, err.Error(), http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\t// Pass to the real handler\n\t\tresponse, statusCode, err := handler(r, params)\n\n\t\t// Logs [source IP] [request method] [request URL] [HTTP status] [time spent serving request]\n\t\tlog.Printf(\"%v\\t \\\"%v - %v\\\"\\t%v\\t%v\", sourceIP(r), r.Method, r.RequestURI, statusCode, time.Since(start))\n\n\t\tif err != nil {\n\t\t\t// If we run into an error, throw it back to the client (as plain text)\n\t\t\thttp.Error(w, err.Error(), statusCode)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(statusCode)\n\t\tfmt.Fprintln(w, response)\n\t}\n}", "func (pool *PoolHandler) Add(request *restful.Request, response *restful.Response) {\n\tstarted := time.Now()\n\tnetReq := &types.NetRequest{}\n\tif err := request.ReadEntity(netReq); err != nil {\n\t\tresponse.AddHeader(\"Content-Type\", \"text/plain\")\n\t\tblog.Errorf(\"PoolHandler[Add] json decode Err: %s\", err.Error())\n\t\tresponse.WriteErrorString(http.StatusBadRequest, err.Error())\n\t\treportMetrics(\"createIPPool\", \"4xx\", started)\n\t\treturn\n\t}\n\tnetRes := &types.NetResponse{\n\t\tType: types.ResponseType_POOL,\n\t}\n\tif netReq.Type != types.RequestType_POOL || netReq.Pool == nil {\n\t\tnetRes.Code = 1\n\t\tnetRes.Message = \"Request Type Err or Pool lost\"\n\t\tblog.Errorf(\"PoolHandler check Pool request, but got unexpect type %d, pool %v\", netReq.Type, netReq.Pool)\n\t\tresponse.WriteEntity(netRes)\n\t\treportMetrics(\"createIPPool\", \"4xx\", started)\n\t\treturn\n\t}\n\tif !netReq.Pool.IsValid() {\n\t\tnetRes.Code = 1\n\t\tnetRes.Message = \"Request Pool data lost\"\n\t\tblog.Errorf(\"PoolHandler check pool data err, data lost, Net: %s, Mask: %d, Gateway: %s\", netReq.Pool.Net, netReq.Pool.Mask, netReq.Pool.Gateway)\n\t\tresponse.WriteEntity(netRes)\n\t\treportMetrics(\"createIPPool\", \"4xx\", started)\n\t\treturn\n\t}\n\tnetRes.Pool = append(netRes.Pool, netReq.Pool)\n\tif err := pool.netSvr.AddPool(netReq.Pool); err != nil {\n\t\tnetRes.Code = 2\n\t\tnetRes.Message = err.Error()\n\t\tblog.Errorf(\"PoolHandler add pool Err: %s\", err.Error())\n\t\tresponse.WriteEntity(netRes)\n\t\treportMetrics(\"createIPPool\", \"5xx\", started)\n\t\treturn\n\t}\n\tblog.Info(\"NetPool %s/%s mask %d gateway %s add succ\", netReq.Pool.Cluster, netReq.Pool.Net, netReq.Pool.Mask, netReq.Pool.Gateway)\n\tnetRes.Code = 0\n\tnetRes.Message = \"success\"\n\tif err := response.WriteEntity(netRes); err != nil {\n\t\tblog.Errorf(\"PoolHandler reply client POST request Err: %v\", err)\n\t}\n\treportMetrics(\"createIPPool\", \"2xx\", started)\n}", "func New(cfg config.Proxy, bp httputil.BufferPool, token ntokend.TokenProvider, access service.AccessProvider, role service.RoleProvider, svcCert service.SvcCertProvider) Handler {\n\treturn &handler{\n\t\tproxy: &httputil.ReverseProxy{\n\t\t\tBufferPool: bp,\n\t\t},\n\t\ttoken: token,\n\t\taccess: access,\n\t\trole: role,\n\t\tcfg: cfg,\n\t\tsvcCert: svcCert,\n\t}\n}", "func GetUserProfileHandler(w http.ResponseWriter, r *http.Request) {\n\n}", "func wakeupHandler(username, password string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\torigin := r.FormValue(\"origin\")\n\n\t\tif origin == \"\" {\n\t\t\thttp.Error(w, \"The origin connection URL should be provided!\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tc := goha.NewClient(username, password)\n\t\tresp, err := c.Get(origin)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"An error occurred with the CPE communication!\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(resp.StatusCode)\n\t}\n}", "func MakeStats(handler http.Handler, stats *Stats) http.Handler {\r\n return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\r\n \t//Save time everytime we get a request\r\n \tstart := time.Now()\r\n\r\n //Log connection\r\n log.Printf(\"%s %s\", r.RemoteAddr, r.URL)\r\n\r\n //Print all info for request\r\n //log.Printf(\"Request: %v\", r)\r\n\r\n \t//Route and fulfil request\r\n handler.ServeHTTP(w, r)\r\n\r\n //Only count hash requests in stats (even if request is broken) from client side\r\n //This does not count the background hash-write operations as user is not aware\r\n //of these as per requirement. If requirement changes, this will need to be changed\r\n if strings.Contains(r.URL.Path, \"hash\"){\r\n //Calculate request time\r\n end := time.Now()\r\n requestTime := end.Sub(start)\r\n\r\n //Update server stats - thread-safe\r\n stats.timeLock.Lock()\r\n stats.totalTime = stats.totalTime + requestTime\r\n stats.Requests++\r\n stats.AverageTime = float32(stats.totalTime / time.Millisecond) / float32(stats.Requests)\r\n stats.timeLock.Unlock()\r\n log.Printf(\"Request Complete: %v Average: %v\",requestTime,stats.AverageTime)\r\n } \r\n })\r\n}", "func createHandler(w http.ResponseWriter, r *http.Request) {\n\tuser := new(User)\n\tuser.Token = validateToken(r.FormValue(\"token\"))\n\tuser.PasswordHash = validatePassHash(r.FormValue(\"passHash\"))\n\tuser.PublicKey = validatePublicKey(r.FormValue(\"publicKey\"))\n\tuser.PublicHash = computePublicHash(user.PublicKey)\n\tuser.CipherPrivateKey = validateHex(r.FormValue(\"cipherPrivateKey\"))\n\n\tlog.Printf(\"Woot! New user %s %s\\n\", user.Token, user.PublicHash)\n\n\tif !SaveUser(user) {\n\t\thttp.Error(w, \"That username is taken\", http.StatusBadRequest)\n\t}\n}", "func Handler(s *Services) http.Handler {\n\tro := httprouter.New()\n\tro.GET(\"/groups/update/:groupID\", s.groupMW(s.views.EditGroupForm))\n\tro.GET(\"/roles/create/:groupID\", s.groupMW(s.views.NewRoleForm))\n\tro.GET(\"/roles/update/:roleID\", s.roleMW(s.views.UpdateRoleForm))\n\tro.GET(\"/chores/create/:groupID\", s.groupMW(s.views.NewChoreForm))\n\tro.GET(\"/chores/update/:choreID\", s.choreMW(s.views.UpdateChoreForm))\n\tro.POST(\"/groups/update/:groupID\", s.groupMW(s.groups.UpdateGroup))\n\tro.POST(\"/roles/create/:groupID\", s.groupMW(s.groups.AddRole))\n\tro.POST(\"/roles/update/:roleID\", s.roleMW(s.roles.Update))\n\tro.POST(\"/chores/create/:groupID\", s.groupMW(s.chores.Create))\n\tro.POST(\"/chores/update/:choreID\", s.choreMW(s.chores.Update))\n\tro.HandlerFunc(\"GET\", \"/\", s.views.Index)\n\tro.HandlerFunc(\"GET\", \"/login\", s.views.LoginForm)\n\tro.HandlerFunc(\"GET\", \"/logout\", s.auth.Logout)\n\tro.HandlerFunc(\"GET\", \"/dashboard\", s.authorize(s.views.Dashboard))\n\tro.HandlerFunc(\"GET\", \"/register\", s.views.RegisterForm)\n\tro.HandlerFunc(\"GET\", \"/groups/create\", s.authorize(s.views.NewGroupForm))\n\tro.HandlerFunc(\"POST\", \"/login\", s.auth.Login)\n\tro.HandlerFunc(\"POST\", \"/register\", s.users.CreateUser)\n\tro.HandlerFunc(\"POST\", \"/groups/create\", s.authorize(s.groups.CreateGroup))\n\tro.ServeFiles(\"/public/*filepath\", http.Dir(os.Getenv(\"CS_STATIC_PATH\")))\n\treturn ro\n}", "func newHTTPHandler(web3Handler Web3Handler) *hTTPHandler {\n\treturn &hTTPHandler{\n\t\tmsgHandler: web3Handler,\n\t}\n}", "func NewHandler(bouncer security.BouncerService,\n\tstatus *portainer.Status,\n\tdemoService *demo.Service,\n\tdataStore dataservices.DataStore,\n\tupgradeService upgrade.Service) *Handler {\n\n\th := &Handler{\n\t\tRouter: mux.NewRouter(),\n\t\tdataStore: dataStore,\n\t\tdemoService: demoService,\n\t\tstatus: status,\n\t\tupgradeService: upgradeService,\n\t}\n\n\trouter := h.PathPrefix(\"/system\").Subrouter()\n\n\tadminRouter := router.PathPrefix(\"/\").Subrouter()\n\tadminRouter.Use(bouncer.AdminAccess)\n\n\tadminRouter.Handle(\"/upgrade\", httperror.LoggerHandler(h.systemUpgrade)).Methods(http.MethodPost)\n\n\tauthenticatedRouter := router.PathPrefix(\"/\").Subrouter()\n\tauthenticatedRouter.Use(bouncer.AuthenticatedAccess)\n\n\tauthenticatedRouter.Handle(\"/version\", http.HandlerFunc(h.version)).Methods(http.MethodGet)\n\tauthenticatedRouter.Handle(\"/nodes\", httperror.LoggerHandler(h.systemNodesCount)).Methods(http.MethodGet)\n\tauthenticatedRouter.Handle(\"/info\", httperror.LoggerHandler(h.systemInfo)).Methods(http.MethodGet)\n\n\tpublicRouter := router.PathPrefix(\"/\").Subrouter()\n\tpublicRouter.Use(bouncer.PublicAccess)\n\n\tpublicRouter.Handle(\"/status\", httperror.LoggerHandler(h.systemStatus)).Methods(http.MethodGet)\n\n\t// Deprecated /status endpoint, will be removed in the future.\n\th.Handle(\"/status\",\n\t\tbouncer.PublicAccess(httperror.LoggerHandler(h.statusInspectDeprecated))).Methods(http.MethodGet)\n\th.Handle(\"/status/version\",\n\t\tbouncer.AuthenticatedAccess(http.HandlerFunc(h.versionDeprecated))).Methods(http.MethodGet)\n\th.Handle(\"/status/nodes\",\n\t\tbouncer.AuthenticatedAccess(httperror.LoggerHandler(h.statusNodesCountDeprecated))).Methods(http.MethodGet)\n\n\treturn h\n}", "func makeThrottleHandler(perMin, burst, storeSize int) func(http.Handler) http.Handler {\n\tstore, err := memstore.New(storeSize)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tquota := throttled.RateQuota{\n\t\tMaxRate: throttled.PerMin(perMin),\n\t\tMaxBurst: burst,\n\t}\n\trateLimiter, err := throttled.NewGCRARateLimiter(store, quota)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\thttpRateLimiter := throttled.HTTPRateLimiter{\n\t\tRateLimiter: rateLimiter,\n\t\tVaryBy: new(ipVaryBy),\n\t\tDeniedHandler: http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tWriteJSONError(w, ErrLimitExceeded)\n\t\t})),\n\t}\n\n\treturn httpRateLimiter.RateLimit\n}", "func basicAuthHandler(store *configstore.Store) (func(*http.Request) (string, []string, error), error) {\n\tuserGroupsMap := map[string][]string{}\n\tgroupsAuthStr, err := configstore.Filter().Slice(groupsAuthKey).Squash().Store(store).MustGetFirstItem().Value()\n\tif err == nil {\n\t\tgroupsMap := map[string][]string{}\n\t\tif err = json.Unmarshal([]byte(groupsAuthStr), &groupsMap); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to unmarshal utask configuration: %s\", err)\n\t\t}\n\t\tfor group, users := range groupsMap {\n\t\t\tfor _, user := range users {\n\t\t\t\tuserGroupsMap[user] = append(userGroupsMap[user], group)\n\t\t\t}\n\t\t}\n\t}\n\n\tauthMap := map[string]string{}\n\tbasicAuthStr, err := configstore.Filter().Slice(basicAuthKey).Squash().Store(store).MustGetFirstItem().Value()\n\tif err == nil {\n\t\tuserPasswords := map[string]string{}\n\t\tif err := json.Unmarshal([]byte(basicAuthStr), &userPasswords); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to unmarshal utask configuration: %s\", err)\n\t\t}\n\t\tfor user, pass := range userPasswords {\n\t\t\theader := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(user+\":\"+pass))\n\t\t\tauthMap[header] = user\n\t\t}\n\t}\n\tif len(authMap) > 0 {\n\t\treturn func(r *http.Request) (string, []string, error) {\n\t\t\tauthHeader := r.Header.Get(\"Authorization\")\n\t\t\tuser, found := authMap[authHeader]\n\t\t\tif !found {\n\t\t\t\treturn \"\", nil, errors.Unauthorizedf(\"User not found\")\n\t\t\t}\n\t\t\treturn user, userGroupsMap[user], nil\n\t\t}, nil\n\t}\n\t// fallback to expecting a username in x-remote-user header\n\treturn func(r *http.Request) (string, []string, error) {\n\t\tuser := r.Header.Get(\"x-remote-user\")\n\t\treturn user, userGroupsMap[user], nil\n\t}, nil\n}", "func CreateHandler(w http.ResponseWriter, r *http.Request) {\n\t_, _, ok := r.BasicAuth()\n\tif !ok {\n\t\tw.Header().Set(\"WWW-Authenticate\", fmt.Sprintf(`Basic realm=\"%s\"`, BasicAuthRealm))\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(http.StatusText(http.StatusUnauthorized) + \"\\n\"))\n\t\treturn\n\t}\n\tif !reqIsAdmin(r) {\n\t\thttp.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)\n\t\treturn\n\t}\n\tvar bad bool\n\tvar badmin bool\n\tif r.FormValue(\"ad\") != \"\" {\n\t\tvar err error\n\t\tbad, err = strconv.ParseBool(r.FormValue(\"ad\"))\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n\tif r.FormValue(\"admin\") != \"\" {\n\t\tvar err error\n\t\tbadmin, err = strconv.ParseBool(r.FormValue(\"admin\"))\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n\tvar pass string\n\tif !bad {\n\t\tpass = r.FormValue(\"password\")\n\t}\n\tu := &User{\n\t\tUsername: strings.ToLower(r.FormValue(\"username\")),\n\t\tPassword: pass,\n\t\tAD: bad,\n\t\tAdmin: badmin,\n\t\tNamespaces: strings.Split(r.FormValue(\"namespaces\"), \",\"),\n\t}\n\tvar err error\n\tu, err = u.Create()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tfmt.Fprint(w, \"User created\")\n}", "func WrapHandlerInBasicAuth(h http.Handler, b BasicAuth) http.HandlerFunc {\n\tif b.Username == \"\" || b.Password == \"\" {\n\t\tlogrus.Warn(\"Metrics are exposed without protection. Make sure you set up protection at proxy level.\")\n\t}\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// Serve without authorization if either Username or Password is unset\n\t\tif b.Username == \"\" || b.Password == \"\" {\n\t\t\th.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t\tuser, pass, ok := r.BasicAuth()\n\n\t\tif !ok || user != b.Username || pass != b.Password {\n\t\t\thttp.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t\th.ServeHTTP(w, r)\n\t}\n}", "func (l *Middleware) Handler(next http.Handler) http.Handler {\n\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\n\t\tif l.inLogFlags(None) { // skip logging\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tww := newCustomResponseWriter(w)\n\t\tbody, user := l.getBodyAndUser(r)\n\t\tt1 := time.Now()\n\t\tdefer func() {\n\t\t\tt2 := time.Now()\n\n\t\t\tq := l.sanitizeQuery(r.URL.String())\n\t\t\tif qun, err := url.QueryUnescape(q); err == nil {\n\t\t\t\tq = qun\n\t\t\t}\n\n\t\t\tremoteIP := strings.Split(r.RemoteAddr, \":\")[0]\n\t\t\tif strings.HasPrefix(r.RemoteAddr, \"[\") {\n\t\t\t\tremoteIP = strings.Split(r.RemoteAddr, \"]:\")[0] + \"]\"\n\t\t\t}\n\n\t\t\tif l.ipFn != nil { // mask ip with ipFn\n\t\t\t\tremoteIP = l.ipFn(remoteIP)\n\t\t\t}\n\n\t\t\tvar bld strings.Builder\n\t\t\tif l.prefix != \"\" {\n\t\t\t\tbld.WriteString(l.prefix)\n\t\t\t\tbld.WriteString(\" \")\n\t\t\t}\n\n\t\t\tbld.WriteString(fmt.Sprintf(\"%s - %s - %s - %d (%d) - %v\", r.Method, q, remoteIP, ww.status, ww.size, t2.Sub(t1)))\n\n\t\t\tif user != \"\" {\n\t\t\t\tbld.WriteString(\" - \")\n\t\t\t\tbld.WriteString(user)\n\t\t\t}\n\n\t\t\tif l.subjFn != nil {\n\t\t\t\tif subj, err := l.subjFn(r); err == nil {\n\t\t\t\t\tbld.WriteString(\" - \")\n\t\t\t\t\tbld.WriteString(subj)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif traceID := r.Header.Get(\"X-Request-ID\"); traceID != \"\" {\n\t\t\t\tbld.WriteString(\" - \")\n\t\t\t\tbld.WriteString(traceID)\n\t\t\t}\n\n\t\t\tif body != \"\" {\n\t\t\t\tbld.WriteString(\" - \")\n\t\t\t\tbld.WriteString(body)\n\t\t\t}\n\n\t\t\tl.log.Logf(\"%s\", bld.String())\n\t\t}()\n\n\t\tnext.ServeHTTP(ww, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func CreateUserHandler(w http.ResponseWriter, req *http.Request) {\n // Validate internal token.\n if internalToken := req.Header.Get(app.Config.AuthHeaderName); internalToken != app.Config.RestApiToken {\n respond.Error(w, errmsg.Unauthorized())\n return\n }\n\n // Parse & validate payload.\n var pl payload.CreateUserPayload\n\n if !pl.Validate(req) {\n respond.Error(w, errmsg.InvalidPayload())\n return\n }\n\n // Check if the executor is using the USER_CREATION_HASH to create this user.\n usingUserCreationPw := pl.ExecutorEmail == \"\" && app.Config.UserCreationHash != \"\" &&\n crypt.VerifySha256(pl.ExecutorPassword, app.Config.UserCreationHash)\n\n // If not using USER_CREATION_HASH for auth, verify executor exists using email/pw.\n if !usingUserCreationPw {\n // Get executor user by email.\n executorUser, err := usersvc.FromEmail(pl.ExecutorEmail)\n\n if err != nil {\n app.Log.Errorln(err.Error())\n respond.Error(w, errmsg.UserNotFound())\n return\n }\n\n // Ensure executor user's password is correct.\n if !crypt.VerifyBcrypt(pl.ExecutorPassword, executorUser.HashedPw) {\n app.Log.Errorln(\"error creating new User: invalid executor user password\")\n respond.Error(w, errmsg.Unauthorized())\n return\n }\n\n // Only admin users can create other users.\n if !executorUser.Admin {\n app.Log.Errorln(\"error creating new User: executor user must be an admin\")\n respond.Error(w, errmsg.Unauthorized())\n return\n }\n }\n\n // Hash provided user password.\n hashedPw, err := crypt.BcryptHash(pl.NewPassword)\n\n if err != nil {\n app.Log.Errorf(\"error creating new User: bcrypt password hash failed with %s\\n\", err.Error())\n respond.Error(w, errmsg.ISE())\n return\n }\n\n // Create new User.\n newUser, err := usersvc.Create(pl.NewEmail, hashedPw, pl.Admin)\n\n if err != nil {\n app.Log.Errorln(err.Error())\n pqError, ok := err.(*pq.Error)\n\n if ok && pqError.Code.Name() == \"unique_violation\" {\n respond.Error(w, errmsg.EmailNotAvailable())\n } else {\n respond.Error(w, errmsg.UserCreationFailed())\n }\n\n return\n }\n\n // Create response payload and respond.\n respData := successmsg.UserCreationSuccess\n respData[\"uid\"] = newUser.Uid\n\n respond.Created(w, respData)\n}", "func MakeHandler(csvc clients.Service, psvc policies.Service, mux *bone.Mux, logger logger.Logger) http.Handler {\n\topts := []kithttp.ServerOption{\n\t\tkithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, api.EncodeError)),\n\t}\n\tmux.Post(\"/connect\", kithttp.NewServer(\n\t\totelkit.EndpointMiddleware(otelkit.WithOperation(\"connect\"))(connectThingsEndpoint(psvc)),\n\t\tdecodeConnectList,\n\t\tapi.EncodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Post(\"/disconnect\", kithttp.NewServer(\n\t\totelkit.EndpointMiddleware(otelkit.WithOperation(\"disconnect\"))(disconnectThingsEndpoint(psvc)),\n\t\tdecodeConnectList,\n\t\tapi.EncodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Post(\"/channels/:chanID/things/:thingID\", kithttp.NewServer(\n\t\totelkit.EndpointMiddleware(otelkit.WithOperation(\"connect_thing\"))(connectEndpoint(psvc)),\n\t\tdecodeConnectThing,\n\t\tapi.EncodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Delete(\"/channels/:chanID/things/:thingID\", kithttp.NewServer(\n\t\totelkit.EndpointMiddleware(otelkit.WithOperation(\"disconnect_thing\"))(disconnectEndpoint(psvc)),\n\t\tdecodeDisconnectThing,\n\t\tapi.EncodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Post(\"/identify\", kithttp.NewServer(\n\t\totelkit.EndpointMiddleware(otelkit.WithOperation(\"identify\"))(identifyEndpoint(csvc)),\n\t\tdecodeIdentify,\n\t\tapi.EncodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Put(\"/things/policies\", kithttp.NewServer(\n\t\totelkit.EndpointMiddleware(otelkit.WithOperation(\"update_policy\"))(updatePolicyEndpoint(psvc)),\n\t\tdecodeUpdatePolicy,\n\t\tapi.EncodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Get(\"/things/policies\", kithttp.NewServer(\n\t\totelkit.EndpointMiddleware(otelkit.WithOperation(\"list_policies\"))(listPoliciesEndpoint(psvc)),\n\t\tdecodeListPolicies,\n\t\tapi.EncodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Post(\"/channels/:chanID/access\", kithttp.NewServer(\n\t\totelkit.EndpointMiddleware(otelkit.WithOperation(\"authorize\"))(authorizeEndpoint(psvc)),\n\t\tdecodeCanAccess,\n\t\tapi.EncodeResponse,\n\t\topts...,\n\t))\n\treturn mux\n\n}", "func (s *AppServer) new(w http.ResponseWriter, r *http.Request, params *AppParams, handlers []Middleware) *Context {\n\t// adjust request id\n\trequestId := r.Header.Get(s.requestId)\n\tif requestId == \"\" {\n\t\trequestId = NewObjectId().Hex()\n\n\t\t// inject request header with new request id\n\t\tr.Header.Set(s.requestId, requestId)\n\t}\n\tw.Header().Set(s.requestId, requestId)\n\n\tctx := s.pool.Get().(*Context)\n\tctx.Request = r\n\tctx.Response = &ctx.writer\n\tctx.Params = params\n\tctx.Logger = s.logger.New(requestId)\n\tctx.settings = nil\n\tctx.frozenSettings = nil\n\tctx.writer.reset(w)\n\tctx.handlers = handlers\n\tctx.index = -1\n\tctx.startedAt = time.Now()\n\tctx.downAfter = ctx.startedAt.Add(s.slowdown)\n\n\treturn ctx\n}", "func MessageLaunchHandlerCreator(registrationDS registrationDatastore.RegistrationDatastore, cache ltiCache.Cache, store sessions.Store, sessionName string, debug bool) func(http.Handler) http.Handler {\n\tbase := ltiBase{registrationDS, cache, store, sessionName}\n\treturn func(handla http.Handler) http.Handler {\n\t\t// initialize the jwt middleware\n\t\topts := jwtmiddleware.Options{\n\t\t\tSigningMethod: jwt.SigningMethodRS256,\n\t\t\tUserProperty: userKeyName,\n\t\t\tExtractor: FromAnyParameter(\"id_token\"),\n\t\t\tDebug: debug,\n\t\t\tValidationKeyGetter: base.getValidationKey,\n\t\t\tErrorHandler: tokenMWErrorHandler,\n\t\t}\n\t\tjwtMW := jwtmiddleware.New(opts)\n\t\t// now create the inner handler\n\t\thandlerFunc := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\t// create this request handler's messageLaunch object\n\t\t\tmsgL := NewMessageLaunch(registrationDS, cache, store, sessionName, debug)\n\t\t\tsess, _ := msgL.store.Get(req, msgL.ltiBase.sessionName)\n\n\t\t\t// get id_token claims (which was validated and placed in the context by jwt middleware)\n\t\t\tclaims := GetClaims(req)\n\n\t\t\t// Note: token validity, security, expired handled by wrapper\n\t\t\tif err := msgL.validateState(req); err != nil {\n\t\t\t\thttp.Error(w, err.Error(), 401)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// validate the nonce\n\t\t\ttokNonce := claims[\"nonce\"].(string)\n\t\t\tif err := msgL.validateNonce(req, tokNonce); err != nil {\n\t\t\t\thttp.Error(w, err.Error(), 401)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := msgL.validateClientID(GetClaims(req)); err != nil {\n\t\t\t\thttp.Error(w, err.Error(), 401)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := msgL.validateDeployment(GetClaims(req)); err != nil {\n\t\t\t\thttp.Error(w, err.Error(), 401)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := msgL.validateMessage(GetClaims(req)); err != nil {\n\t\t\t\thttp.Error(w, err.Error(), 401)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tbytes, err := json.Marshal(claims)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, \"failed to cache claims\", 500)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// save the launch in our cache, for future use\n\t\t\tclaimsStr := string(bytes)\n\t\t\tlog.Printf(\"launchData length: %d\", len(claimsStr))\n\t\t\t// log.Printf(\"launchData: %s\", claimsStr)\n\t\t\tmsgL.cache.PutLaunchData(req, msgL.launchID, string(bytes))\n\t\t\t// save the launchID in the request context\n\t\t\treq = requestWithLaunchIDContext(req, msgL.launchID)\n\t\t\tif err := sess.Save(req, w); err != nil {\n\t\t\t\tlog.Printf(\"error while saving session: %v\", err)\n\t\t\t}\n\t\t\thandla.ServeHTTP(w, req)\n\t\t})\n\t\treturn jwtMW.Handler(handlerFunc)\n\t}\n}", "func initJWTAuthHandler() func(ctx *neptulon.ReqCtx) error {\n\treturn func(ctx *neptulon.ReqCtx) error {\n\t\t// todo: this could rather send the remaining queue size for the client so client can disconnect if there is nothing else to do\n\t\tctx.Res = client.ACK\n\t\treturn ctx.Next()\n\t}\n}", "func CreateUserHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Debug(\"userservice.CreateUserHandler called\")\n\tusername, err := apiserver.Authn(apiserver.CREATE_USER_PERM, w, r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tw.Header().Set(\"WWW-Authenticate\", `Basic realm=\"Restricted\"`)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\n\tvar request msgs.CreateUserRequest\n\t_ = json.NewDecoder(r.Body).Decode(&request)\n\n\tresp := msgs.CreateUserResponse{}\n\n\tvar ns string\n\tns, err = apiserver.GetNamespace(apiserver.Clientset, username, request.Namespace)\n\tif err != nil {\n\t\tresp.Status.Code = msgs.Error\n\t\tresp.Status.Msg = apiserver.VERSION_MISMATCH_ERROR\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tif request.ClientVersion != msgs.PGO_VERSION {\n\t\tresp.Status.Code = msgs.Error\n\t\tresp.Status.Msg = apiserver.VERSION_MISMATCH_ERROR\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tresp = CreateUser(&request, ns)\n\tjson.NewEncoder(w).Encode(resp)\n\n}", "func NewHTTPPool(self string) *HTTPPool {\n\tp := NewHTTPPoolOpts(self, nil)\n\thttp.Handle(p.opts.BasePath, p)\n\treturn p\n}", "func (s *SubmissionSpawner) Spawn() ConnHandler {\n\treturn &SubmissionHandler{}\n}", "func (h *Handler) serveAuthenticateDBUser(w http.ResponseWriter, r *http.Request) {}", "func Handle(w http.ResponseWriter, r *http.Request, HandleFunc HandleFunc) {\n\thandler := pool.Get().(*Handler)\n\tdefer pool.Put(handler)\n\n\thandler.Reset(HandleFunc)\n\thandler.ServeHTTP(w, r)\n\thandler.Reset(nil)\n}", "func New(\n\tctx *snow.ConsensusContext,\n\tvalidators validators.Set,\n\tmsgFromVMChan <-chan common.Message,\n\tgossipFrequency time.Duration,\n\tthreadPoolSize int,\n\tresourceTracker tracker.ResourceTracker,\n\tsubnetConnector validators.SubnetConnector,\n\tsubnet subnets.Subnet,\n\tpeerTracker commontracker.Peers,\n) (Handler, error) {\n\th := &handler{\n\t\tctx: ctx,\n\t\tvalidators: validators,\n\t\tmsgFromVMChan: msgFromVMChan,\n\t\tpreemptTimeouts: subnet.OnBootstrapCompleted(),\n\t\tgossipFrequency: gossipFrequency,\n\t\tasyncMessagePool: worker.NewPool(threadPoolSize),\n\t\ttimeouts: make(chan struct{}, 1),\n\t\tclosingChan: make(chan struct{}),\n\t\tclosed: make(chan struct{}),\n\t\tresourceTracker: resourceTracker,\n\t\tsubnetConnector: subnetConnector,\n\t\tsubnet: subnet,\n\t\tpeerTracker: peerTracker,\n\t}\n\n\tvar err error\n\n\th.metrics, err = newMetrics(\"handler\", h.ctx.Registerer)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing handler metrics errored with: %w\", err)\n\t}\n\tcpuTracker := resourceTracker.CPUTracker()\n\th.syncMessageQueue, err = NewMessageQueue(h.ctx.Log, h.validators, cpuTracker, \"handler\", h.ctx.Registerer, message.SynchronousOps)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing sync message queue errored with: %w\", err)\n\t}\n\th.asyncMessageQueue, err = NewMessageQueue(h.ctx.Log, h.validators, cpuTracker, \"handler_async\", h.ctx.Registerer, message.AsynchronousOps)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing async message queue errored with: %w\", err)\n\t}\n\treturn h, nil\n}", "func MakeHandler(svc manager.Service) http.Handler {\n\topts := []kithttp.ServerOption{\n\t\tkithttp.ServerErrorEncoder(encodeError),\n\t}\n\n\tregistration := kithttp.NewServer(\n\t\tregistrationEndpoint(svc),\n\t\tdecodeCredentials,\n\t\tencodeResponse,\n\t\topts...,\n\t)\n\n\tlogin := kithttp.NewServer(\n\t\tloginEndpoint(svc),\n\t\tdecodeCredentials,\n\t\tencodeResponse,\n\t\topts...,\n\t)\n\n\taddClient := kithttp.NewServer(\n\t\taddClientEndpoint(svc),\n\t\tdecodeAddClient,\n\t\tencodeResponse,\n\t\topts...,\n\t)\n\n\tviewClient := kithttp.NewServer(\n\t\tviewClientEndpoint(svc),\n\t\tdecodeViewClient,\n\t\tencodeResponse,\n\t\topts...,\n\t)\n\n\tremoveClient := kithttp.NewServer(\n\t\tremoveClientEndpoint(svc),\n\t\tdecodeViewClient,\n\t\tencodeResponse,\n\t\topts...,\n\t)\n\n\tr := bone.New()\n\n\tr.Post(\"/users\", registration)\n\tr.Post(\"/tokens\", login)\n\tr.Post(\"/clients\", addClient)\n\tr.Get(\"/clients/:id\", viewClient)\n\tr.Delete(\"/clients/:id\", removeClient)\n\tr.Handle(\"/metrics\", promhttp.Handler())\n\n\treturn r\n}", "func NewHandler(clusterService agent.ClusterService, agentTags *agent.InfoTags, notaryService *security.NotaryService) *Handler {\n\th := &Handler{\n\t\tRouter: mux.NewRouter(),\n\t\tconnectionUpgrader: websocket.Upgrader{},\n\t\tclusterService: clusterService,\n\t\tagentTags: agentTags,\n\t}\n\n\th.Handle(\"/websocket/attach\", notaryService.DigitalSignatureVerification(httperror.LoggerHandler(h.websocketAttach)))\n\th.Handle(\"/websocket/exec\", notaryService.DigitalSignatureVerification(httperror.LoggerHandler(h.websocketExec)))\n\treturn h\n}", "func genericRequestHandler(w http.ResponseWriter, r *http.Request) {\n\temail := getUser(r)\n\tif email != \"\" {\n\t\tlog.Println(email, r.URL.String())\n\t\tproxy(w, r)\n\t} else {\n\t\tsession, _ := store.Get(r, serverConfig.CookieName)\n\t\tsession.Values[\"next\"] = r.URL.String()\n\t\tsession.Save(r, w)\n\t\tlog.Println(\"Asking for login, request from unknown user to:\", r.URL.String())\n\t\taskForLogin(w, r)\n\t}\n}", "func MakeHandler(svc users.Service, tracer opentracing.Tracer, l log.Logger) http.Handler {\n\tlogger = l\n\n\topts := []kithttp.ServerOption{\n\t\tkithttp.ServerErrorEncoder(encodeError),\n\t}\n\n\tmux := bone.New()\n\n\tmux.Post(\"/users\", kithttp.NewServer(\n\t\tkitot.TraceServer(tracer, \"register\")(registrationEndpoint(svc)),\n\t\tdecodeCredentials,\n\t\tencodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Get(\"/users\", kithttp.NewServer(\n\t\tkitot.TraceServer(tracer, \"user_info\")(userInfoEndpoint(svc)),\n\t\tdecodeViewInfo,\n\t\tencodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Put(\"/users\", kithttp.NewServer(\n\t\tkitot.TraceServer(tracer, \"update_user\")(updateUserEndpoint(svc)),\n\t\tdecodeUpdateUser,\n\t\tencodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Post(\"/password/reset-request\", kithttp.NewServer(\n\t\tkitot.TraceServer(tracer, \"res-req\")(passwordResetRequestEndpoint(svc)),\n\t\tdecodePasswordResetRequest,\n\t\tencodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Put(\"/password/reset\", kithttp.NewServer(\n\t\tkitot.TraceServer(tracer, \"reset\")(passwordResetEndpoint(svc)),\n\t\tdecodePasswordReset,\n\t\tencodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Patch(\"/password\", kithttp.NewServer(\n\t\tkitot.TraceServer(tracer, \"reset\")(passwordChangeEndpoint(svc)),\n\t\tdecodePasswordChange,\n\t\tencodeResponse,\n\t\topts...,\n\t))\n\n\tmux.Post(\"/tokens\", kithttp.NewServer(\n\t\tkitot.TraceServer(tracer, \"login\")(loginEndpoint(svc)),\n\t\tdecodeCredentials,\n\t\tencodeResponse,\n\t\topts...,\n\t))\n\n\tmux.GetFunc(\"/version\", mainflux.Version(\"users\"))\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\n\treturn mux\n}", "func newGameHandle(w http.ResponseWriter, r *http.Request) {\n\t// Use non-blocking send\n\tselect {\n\tcase model.NewGameCh <- 1:\n\tdefault:\n\t}\n}", "func HandleAuthentication(session core.Session) 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\tctx := r.Context()\n\t\t\tlog := logger.FromContext(ctx)\n\t\t\tuser, err := session.Get(r)\n\n\t\t\t// this block of code checks the error message and user\n\t\t\t// returned from the session, including some edge cases,\n\t\t\t// to prevent a session from being falsely created.\n\t\t\tif err != nil || user == nil || user.ID == 0 {\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\tlog.Debugln(\"api: guest access\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif user.Machine {\n\t\t\t\tlog = log.WithField(\"user.machine\", user.Machine)\n\t\t\t}\n\t\t\tif user.Admin {\n\t\t\t\tlog = log.WithField(\"user.admin\", user.Admin)\n\t\t\t}\n\t\t\tlog = log.WithField(\"user.login\", user.Login)\n\t\t\tctx = logger.WithContext(ctx, log)\n\t\t\tnext.ServeHTTP(w, r.WithContext(\n\t\t\t\trequest.WithUser(ctx, user),\n\t\t\t))\n\t\t})\n\t}\n}", "func newHealthServiceHandler(db *sqlx.DB) (http.Handler, *healthz.StatusChecker) {\n\tstatus := healthz.NewStatusChecker(healthz.Healthy)\n\thealthMux := healthz.NewHealthServiceHandler(healthz.NewCheckers(), healthz.NewCheckers(status, healthz.NewPingChecker(db)))\n\n\treturn healthMux, status\n}", "func newHTTPHandler(c ServiceController, k8sStorage ServiceStorage) *httpHandler {\n\treturn &httpHandler{\n\t\tcontroller: c,\n\t\tk8sStorage: k8sStorage,\n\t}\n}", "func newCallBackHandler() (raw.OnewayHandler, <-chan map[string]string) {\n\tserverCalledBack := make(chan map[string]string)\n\treturn func(ctx context.Context, body []byte) error {\n\t\tserverCalledBack <- extractBaggage(ctx)\n\t\treturn nil\n\t}, serverCalledBack\n}", "func NewHandler(\n\tstateDecoder oidc.Decoder,\n\tcookieDecoder oidc.Decoder,\n\tgetHandler HandlerFunc, // use NewGetHandler() for production\n\tpostHandler HandlerFunc, // use NewPostHandler() for production\n) http.Handler {\n\tloginHandler := httperr.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {\n\t\tvar handler HandlerFunc\n\t\tswitch r.Method {\n\t\tcase http.MethodGet:\n\t\t\thandler = getHandler\n\t\tcase http.MethodPost:\n\t\t\thandler = postHandler\n\t\tdefault:\n\t\t\treturn httperr.Newf(http.StatusMethodNotAllowed, \"%s (try GET or POST)\", r.Method)\n\t\t}\n\n\t\tencodedState, decodedState, err := oidc.ReadStateParamAndValidateCSRFCookie(r, cookieDecoder, stateDecoder)\n\t\tif err != nil {\n\t\t\tplog.InfoErr(\"state or CSRF error\", err)\n\t\t\treturn err\n\t\t}\n\n\t\tswitch decodedState.UpstreamType {\n\t\tcase string(idpdiscoveryv1alpha1.IDPTypeLDAP), string(idpdiscoveryv1alpha1.IDPTypeActiveDirectory):\n\t\t\t// these are the types supported by this endpoint, so no error here\n\t\tdefault:\n\t\t\treturn httperr.Newf(http.StatusBadRequest, \"not a supported upstream IDP type for this endpoint: %q\", decodedState.UpstreamType)\n\t\t}\n\n\t\treturn handler(w, r, encodedState, decodedState)\n\t})\n\n\treturn wrapSecurityHeaders(loginHandler)\n}", "func basicAuthHandler(next http.Handler, username, password string) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"WWW-Authenticate\", `Basic realm=\"knut\"`)\n\t\trUser, rPassword, ok := r.BasicAuth()\n\t\tif ok && rUser == username && password == rPassword {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t} else {\n\t\t\twriteStatus(w, http.StatusUnauthorized)\n\t\t}\n\t})\n}", "func (h *handler) getHandler(w http.ResponseWriter, req *http.Request) error {\n\tvars := mux.Vars(req)\n\n\t// Proxy the request to the lock service.\n\turl := fmt.Sprintf(\"%s/mod/v2/lock/%s?field=value\", h.addr, vars[\"key\"])\n\tresp, err := h.client.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tw.WriteHeader(resp.StatusCode)\n\tio.Copy(w, resp.Body)\n\treturn nil\n}", "func New(handler http.Handler) backend.CallResourceHandler {\n\treturn &httpResourceHandler{\n\t\thandler: handler,\n\t}\n}", "func NewHandler() Handler {\n\th := &basicHandler{\n\t\tlivenessChecks: make(map[string]Check),\n\t\treadinessChecks: make(map[string]Check),\n\t}\n\th.Handle(\"/live\", http.HandlerFunc(h.LiveEndpoint))\n\th.Handle(\"/ready\", http.HandlerFunc(h.ReadyEndpoint))\n\treturn h\n}", "func (fblh *frontendBackendLoggingHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tstartTime := time.Now()\n\tinfoRw := &logInfoResponseWriter{rw: rw}\n\tinfoRwMap.Set(fblh.reqid, infoRw)\n\tfblh.handlerFunc(infoRw, req)\n\n\tusername := \"-\"\n\turl := *req.URL\n\tif url.User != nil {\n\t\tif name := url.User.Username(); name != \"\" {\n\t\t\tusername = name\n\t\t}\n\t}\n\n\tip, _, err := net.SplitHostPort(req.RemoteAddr)\n\tif err != nil {\n\t\tip = req.RemoteAddr\n\t}\n\n\thost, port, err := net.SplitHostPort(req.Host)\n\tif err != nil {\n\t\thost = req.Host\n\t\tport = \"80\"\n\t}\n\n\turi := url.RequestURI()\n\tif qmIndex := strings.Index(uri, \"?\"); qmIndex > 0 {\n\t\turi = uri[0:qmIndex]\n\t}\n\n\te := logEntryPool.Get().(*mdtpLogEntry)\n\tdefer logEntryPool.Put(e)\n\ttime.Since(startTime).Seconds()\n\n\te.BodyBytesSent = strconv.Itoa(infoRw.GetSize())\n\te.Connection = fblh.reqid\n\te.BytesSent = strconv.Itoa(infoRw.GetSize()) //todo - difference between this and body bytes sent\n\te.GzipRatio = \"-\" //todo calculate gzip ratio\n\te.HttpHost = req.Host\n\te.HttpReferrer = req.Referer()\n\te.HttpUserAgent = req.UserAgent()\n\te.HttpXRequestChain = req.Header.Get(\"X-Request-Chain\")\n\te.HttpXSessionId = req.Header.Get(\"X-Session-ID\")\n\te.HttpXRequestId = req.Header.Get(\"X-Request-ID\")\n\te.RemoteAddr = ip\n\te.HttpTrueClientIp = req.Header.Get(\"True-Client-IP\")\n\te.ProxyHost = infoRw.backend\n\te.RemoteUser = username\n\te.Request = fmt.Sprintf(\"%s %s %s\", req.Method, req.RequestURI, req.Proto)\n\te.RequestMethod = req.Method\n\te.RequestTime = strconv.FormatFloat(time.Since(startTime).Seconds(), 'f', 3, 64)\n\te.RequestLength = \"-\" //todo request length\n\te.SentHttpLocation = rw.Header().Get(\"Location\")\n\te.ServerName = host\n\te.ServerPort = port\n\te.Status = strconv.Itoa(infoRw.GetStatus())\n\te.TimeLocal = startTime.Format(\"02/Jan/2006:15:04:05 -0700\")\n\te.UpstreamAddr = \"-\" //todo get ip of actual backend used\n\te.UpstreamHttpProxyAgent = \"-\" //todo\n\te.UpstreamHttpServer = \"-\" //todo\n\te.UpstreamResponseLength = \"-\" //todo\n\te.UpstreamResponseTime = \"-\" //todo\n\te.UpstreamStatus = \"-\" //todo\n\te.HttpXForwardedFor = req.Header.Get(\"X-Forwarded-For\")\n\n\t//e.Username = username\n\t//e.Timestamp = startTime.Format(\"02/Jan/2006:15:04:05 -0700\")\n\t//e.Method = req.Method\n\t//e.URI = uri\n\t//e.Protocol = req.Proto\n\t//e.Status = infoRw.GetStatus()\n\t//e.Size = infoRw.GetSize()\n\t//e.Referer = req.Referer()\n\t//e.UserAgent = req.UserAgent()\n\t//e.RequestID = fblh.reqid\n\t//e.Frontend = strings.TrimPrefix(infoRw.GetFrontend(), \"frontend-\")\n\t//e.Backend = infoRw.GetBackend()\n\t//e.ElapsedMillis = time.Since(startTime).Nanoseconds() / 1000000\n\t//e.Host = req.Host\n\n\tif fblh.format == \"json\" {\n\t\tfblh.writeJSON(e)\n\t} else {\n\t\tfblh.writeText(e)\n\t}\n}", "func New(s *service.Service) http.Handler {\n h := &handler{s}\n api := way.NewRouter()\n api.HandleFunc(\"POST\", \"/login\", h.login)\n api.HandleFunc(\"POST\", \"/send_magic_link\", h.sendMagicLink)\n api.HandleFunc(\"GET\", \"/auth_redirect\", h.authRedirect)\n api.HandleFunc(\"GET\", \"/user\", h.authUser)\n api.HandleFunc(\"POST\", \"/users/:username/toggle_follow\", h.toggleFollow)\n api.HandleFunc(\"PUT\", \"/user/avatar\", h.updateAvatar)\n api.HandleFunc(\"POST\", \"/users\", h.createUser)\n api.HandleFunc(\"GET\", \"/users\", h.users)\n api.HandleFunc(\"GET\", \"/users/:username\", h.user)\n api.HandleFunc(\"GET\", \"/users/:username/followers\", h.followers)\n api.HandleFunc(\"GET\", \"/users/:username/posts\", h.posts)\n api.HandleFunc(\"GET\", \"/users/:username/followees\", h.followees)\n\n api.HandleFunc(\"POST\", \"/posts\", h.createPost)\n api.HandleFunc(\"GET\", \"/posts/:post_id\", h.post)\n api.HandleFunc(\"POST\", \"/posts/:post_id/toggle_like\", h.togglePostLike)\n api.HandleFunc(\"POST\", \"/posts/:post_id/comments\", h.createComment)\n api.HandleFunc(\"GET\", \"/posts/:post_id/comments\", h.comments)\n\n api.HandleFunc(\"POST\", \"/comments/:comment_id/toggle_like\", h.toggleCommentLike)\n api.HandleFunc(\"GET\", \"/timeline\", h.timeline)\n api.HandleFunc(\"POST\", \"/posts/:post_id/toggle_subscription\", h.togglePostSubscription)\n\n api.HandleFunc(\"GET\", \"/notifications\", h.notifications)\n api.HandleFunc(\"POST\", \"/notifications/:notification_id/mark_as_read\", h.markNotificationAsRead)\n api.HandleFunc(\"POST\", \"/mark_notifications_as_read\", h.markAllNotificationsAsRead)\n\n fs := http.FileServer(&spaFileSystem{http.Dir(\"public\")})\n r := way.NewRouter()\n r.Handle(\"*\", \"/api...\", http.StripPrefix(\"/api\", h.withAuth(api)))\n r.Handle(\"GET\", \"/...\", fs)\n return r\n}", "func NewHandler(k Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {\n\t\tctx = ctx.WithEventManager(sdk.NewEventManager())\n\t\tswitch msg := msg.(type) {\n\t\t// TODO: Define your msg cases\n\t\t//\n\t\t//Example:\n\t\t// case Msg<Action>:\n\t\t// \treturn handleMsg<Action>(ctx, k, msg)\n\t\tcase MsgSetFileAuth:\n\t\t\treturn handleMsgSetFileAuth(ctx, k, msg)\n\t\tcase MsgTransFileAuth:\n\t\t\treturn handleMsgTransFileAuth(ctx, k, msg)\n\t\tcase MsgDelFileAuth:\n\t\t\treturn handleMsgDelFileAuth(ctx, k, msg)\n\t\tdefault:\n\t\t\terrMsg := fmt.Sprintf(\"unrecognized %s message type: %T\", ModuleName, msg)\n\t\t\treturn nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg)\n\t\t}\n\t}\n}", "func NewLoginRequiredHandler() func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\t\tctx := req.Context()\n\t\t\tu, _ := UserFromContext(ctx)\n\t\t\t// only update context if user is not already populated.\n\t\t\t// what if it was ok, but user is an empty User{}?\n\t\t\t// nil user means that user has not been able to be authenticated yet. This will generally be\n\t\t\t// the last middleware to run\n\t\t\tif u == nil {\n\t\t\t\t// http.StatusUnauthorized == 403\n\t\t\t\thttp.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnext.ServeHTTP(rw, req.WithContext(ctx))\n\t\t})\n\t}\n}", "func NewPool(opts ...PoolOpt) *Pool {\n\tp := &Pool{\n\t\tnum: defaultNumOfRoutines,\n\t\tmax: defaultMaxRequestBufferSize,\n\t\tctx: context.TODO(),\n\t\topen: false,\n\t\tclose: make(chan bool),\n\t}\n\tfor _, o := range opts {\n\t\to(p)\n\t}\n\tp.reqs = make(chan *request, p.max)\n\treturn p\n}", "func emptyHandler(w http.ResponseWriter, req *http.Request) {}", "func NewHandler(keeper Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) sdk.Result {\n\t\tswitch msg := msg.(type) {\n\t\tcase MsgLockCoins:\n\t\t\treturn handleMsgLockCoins(ctx, keeper, msg)\n\t\tcase MsgUnlockCoins:\n\t\t\treturn handleMsgUnlockCoins(ctx, keeper, msg)\n\n\t\tdefault:\n\t\t\terrMsg := fmt.Sprintf(\"unrecognized %s message type: %T\", RouterKey, msg)\n\t\t\treturn sdk.ErrUnknownRequest(errMsg).Result()\n\t\t}\n\t}\n}", "func NewMemLoadHandler(res http.ResponseWriter, req *http.Request) {\n\tlog.Println(\"Entered NewMemLoadHandler\")\n\tflusher, ok := res.(http.Flusher)\n\tif !ok {\n\t\thttp.Error(res, \"Server does not support flusher\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tmemUsed := parseOrDefault(req, \"mib\", 1000)\n\n\tfmt.Fprintf(res, \"Starting new mem test with %d MiB memory used ۞\\n\", memUsed)\n\tflusher.Flush()\n\n\tmemory := make([]byte, memUsed*1024*1024)\n\terr := syscall.Mlock(memory)\n\tif err != nil {\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttime.Sleep(10 * time.Second)\n\n\tfmt.Fprint(res, \"New memory test finished!! 🏁\\n\")\n\tlog.Println(\"Leaving NewMemLoadHandler\")\n}", "func newPool(server, password string) *redis.Pool {\n\treturn &redis.Pool{\n\t\tMaxIdle: 3,\n\t\tIdleTimeout: 240 * time.Second,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", server)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif password != \"\" {\n\t\t\t\tif _, err := c.Do(\"AUTH\", password); err != nil {\n\t\t\t\t\tc.Close()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn c, err\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t}\n}", "func SessionsNewHandler(c buffalo.Context) error {\n\treturn c.Render(200, r.HTML(\"sessions/new.html\"))\n}", "func NewHTTPPool(serverID string) *HTTPPool {\n\treturn &HTTPPool{\n\t\tbasePath: defaultBasePath,\n\t\tserverID: serverID,\n\t}\n}", "func (app *Goa) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif len(app.middlewares) > 0 {\n\t\tc := app.pool.Get().(*Context)\n\t\t// c.middlewares = app.middlewares\n\t\tc.init(w, r)\n\n\t\tapp.handleRequest(c)\n\n\t\tapp.pool.Put(c)\n\t}\n}", "func NewHandler(c net.Client, priv *key.Pair, sh *key.Share, group *key.Group, s Store) *Handler {\n\tidx, exists := group.Index(priv.Public)\n\tif !exists {\n\t\t// XXX\n\t\tpanic(\"that's just plain wrong and I should be an error\")\n\t}\n\taddr := group.Nodes[idx].Addr\n\treturn &Handler{\n\t\tclient: c,\n\t\tgroup: group,\n\t\tshare: sh,\n\t\tpub: share.NewPubPoly(key.G2, key.G2.Point().Base(), sh.Commits),\n\t\tindex: idx,\n\t\tstore: s,\n\t\tclose: make(chan bool),\n\t\tcache: newSignatureCache(),\n\t\taddr: addr,\n\t}\n}", "func New() *Handler {\n\tp := &Handler{}\n\tp.reverseProxy = &httputil.ReverseProxy{\n\t\tTransport: &http.Transport{\n\t\t\tDial: func(network, address string) (net.Conn, error) {\n\t\t\t\treturn p.dial(context.TODO(), address)\n\t\t\t},\n\t\t},\n\t\tDirector: func(*http.Request) {\n\t\t\t// Do nothing, the request is self-sufficient\n\t\t},\n\t}\n\treturn p\n}", "func Handler(handler http.HandlerFunc, security *Config) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tusernameEntered, passwordEntered, ok := r.BasicAuth()\n\t\tif !ok || usernameEntered != security.Basic.Username || Sha512(passwordEntered) != strings.ToLower(security.Basic.PasswordSha512Hash) {\n\t\t\tw.Header().Set(\"WWW-Authenticate\", \"Basic\")\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t_, _ = w.Write([]byte(\"Unauthorized\"))\n\t\t\treturn\n\t\t}\n\t\thandler(w, r)\n\t}\n}", "func httpAvailHandler(c *web.C, h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tif httpUnavailable(w) || blockedRequest(w, r) {\n\t\t\treturn\n\t\t}\n\t\th.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func makeHandler(server *ServerContext, privs handlerPrivs, method handlerMethod) http.Handler {\n\treturn http.HandlerFunc(func(r http.ResponseWriter, rq *http.Request) {\n\t\th := newHandler(server, privs, r, rq)\n\t\terr := h.invoke(method)\n\t\th.writeError(err)\n\t\th.logDuration(true) \n\t})\n}", "func NewHandler(handler *multichannelfanout.Handler, logger *zap.Logger) *Handler {\n\th := &Handler{\n\t\tlogger: logger.With(zap.String(\"httpHandler\", \"swappable\")),\n\t}\n\th.setMultiChannelFanoutHandler(handler)\n\treturn h\n}", "func NewHandler(keeper Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) sdk.Result {\n\t\tswitch msg := msg.(type) {\n\t\tcase MsgCreateGroup:\n\t\t\treturn handleMsgCreateGroup(ctx, keeper, msg)\n\t\tdefault:\n\t\t\terrMsg := fmt.Sprintf(\"Unrecognized data Msg type: %v\", msg.Type())\n\t\t\treturn sdk.ErrUnknownRequest(errMsg).Result()\n\t\t}\n\t}\n}", "func AuthHandler(w http.ResponseWriter, r *http.Request) {\n\t/* Print to stdout */\n\tfmt.Println(\"Start AuthHandler\")\n\t/* defer will run the line at the very end of the scope (i.e the function) */\n\tdefer fmt.Println(\"End AuthHandler\")\n\t/* Reading the body of the request, r */\n\treqBody, _ := ioutil.ReadAll(r.Body)\n\tin := []byte(reqBody)\n\tvar raw map[string]interface{}\n\tjson.Unmarshal(in, &raw)\n\tdb, err := sql.Open(\"mysql\", \"Richard:SteveIsTheBest@tcp(localhost:3306)/logic\")\n\tdefer db.Close()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tstmt, serr := db.Prepare(\"INSERT user SET userid=?,username=? ON DUPLICATE KEY UPDATE username=?\")\n\tif serr != nil {\n\t\tpanic(serr.Error())\n\t}\n\tres, rerr := stmt.Exec(raw[\"user\"], raw[\"username\"], raw[\"username\"])\n\tif rerr != nil {\n\t\t// panic(rerr.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - Something bad happened!\"))\n\t\tfmt.Fprintf(w, rerr.Error())\n\t\treturn\n\t}\n\tfmt.Println(res)\n\n\t/* Forming a response */\n\tfmt.Fprintf(w, \"Hello, you called %q, %s\", html.EscapeString(r.URL.Path), &reqBody)\n}", "func NewHandler(next http.Handler) Handler {\n\treturn Handler{\n\t\tNext: next,\n\t\tLogger: JSONLogger,\n\t\tSkip: SkipHealthEndpoint,\n\t}\n}", "func MiddlewareHandle(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlogger.WriteLog(\"Call On URI:\", r.Host, r.URL, \" from the following IP address:\", utils.GetIpAddr(r))\n\t\tif IsAuthenticated(r) {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t} else {\n\t\t\tlogger.WriteLog(\"Call On \", r.Host, r.URL, \" from the following IP address:\", utils.GetIpAddr(r), \" is not authenticated\")\n\t\t\tUnauthenticated().ServeHTTP(w, r)\n\t\t}\n\t})\n}", "func authWrap(h http.Handler) http.Handler {\n\treturn negroni.New(&AuthMiddleware{}, negroni.Wrap(h))\n}", "func NewHandler(cfg Config) http.Handler {\n\tr := resolver.New(\n\t\tresolver.Config{\n\t\t\tLogger: cfg.Logger,\n\t\t\tReceiverFactory: cfg.ReceiverFactory,\n\t\t},\n\t)\n\tu := &jobs{cfg.Logger, r}\n\trouter := mux.NewRouter()\n\trouter.Use(\n\t\tfunc(next http.Handler) http.Handler {\n\t\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tctx := newServicesContext(r.Context())\n\t\t\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t\t\t})\n\t\t})\n\troutes := []struct {\n\t\tname string\n\t\thandler http.HandlerFunc\n\t}{\n\t\t{\"sync_services\", u.syncServices},\n\t\t{\"gc\", u.garbageCollector},\n\t}\n\tfor _, route := range routes {\n\t\trouter.Path(\"/\" + route.name).\n\t\t\tMethods(http.MethodPost).\n\t\t\tHandlerFunc(route.handler).\n\t\t\tName(route.name)\n\t}\n\treturn router\n}", "func NewHandler(c *HandlerConfig) func(http.ResponseWriter, *http.Request) {\n\n\t// pushback receives the push request and writes it into a file\n\t// according to a mapping provided by a json configuration\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tt := r.Header.Get(\"Content-Type\")\n\n\t\tif t != \"binary/octet-stream\" {\n\t\t\tlog.Printf(\"Wrong Content-Type %s\", t)\n\t\t\tw.Write([]byte(fmt.Sprintf(\"%s is not a supported Content-Type\", t)))\n\t\t\treturn\n\t\t}\n\n\t\t// Open test file\n\t\tf, err := os.Create(fmt.Sprintf(\"%s/%s.pushback\", c.Path, \"test\"))\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Could not open file %e\", err)\n\t\t}\n\n\t\tn, err := io.Copy(f, r.Body)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Could only receive %d\", n)\n\t\t}\n\n\t\tw.Write([]byte(\"OK\"))\n\t}\n}" ]
[ "0.6308564", "0.60520667", "0.5913176", "0.5886266", "0.5859235", "0.5858492", "0.56993854", "0.56641823", "0.5658737", "0.55474234", "0.55255514", "0.55111474", "0.54744065", "0.5461709", "0.5401738", "0.5391314", "0.53664947", "0.53589886", "0.53545034", "0.53520846", "0.5347174", "0.5345794", "0.53241384", "0.5314514", "0.5289641", "0.52827907", "0.52783084", "0.52602303", "0.5255884", "0.5248551", "0.5231653", "0.5226117", "0.52092177", "0.5205651", "0.5197796", "0.519749", "0.51959217", "0.5191588", "0.51777905", "0.5154911", "0.51528937", "0.51502424", "0.51440126", "0.51428485", "0.51335496", "0.5126199", "0.51152736", "0.5112976", "0.5104057", "0.5096985", "0.5095832", "0.50921965", "0.509163", "0.50801766", "0.50766677", "0.5072961", "0.506509", "0.5062888", "0.50588125", "0.50569046", "0.5049952", "0.50492", "0.5045234", "0.50359356", "0.5035727", "0.50258136", "0.50234467", "0.5018651", "0.50152236", "0.50100964", "0.5006673", "0.5003156", "0.49982756", "0.4998203", "0.49981028", "0.49974683", "0.49958917", "0.49956232", "0.4993364", "0.49884912", "0.49825552", "0.49767596", "0.49758852", "0.4964675", "0.4960087", "0.4958347", "0.49569923", "0.49537697", "0.49530682", "0.49431047", "0.49368346", "0.49368256", "0.49340445", "0.49315697", "0.49179667", "0.49147674", "0.49111167", "0.4898283", "0.48979515", "0.48977286" ]
0.7755426
0
Connects to a file server and attaches to it as the specified user.
func Mount(netw, addr, aname string, user g9p.User, log g9p.Logger) (*Client, error) { conn, err := net.Dial(netw, addr) if conn == nil { return nil, err } clnt, err := NewClient(conn, 8192+g9p.IOHDRSZ, true, log) if clnt == nil { return nil, err } fid, err := clnt.Attach(nil, user, aname) if err != nil { clnt.Unmount() return nil, err } clnt.root = fid return clnt, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) Attach(afile *Remote, user, aname string) (*Remote, error) {\n\tfid := c.nextFID()\n\n\tafid := NoFID\n\tif afile != nil {\n\t\tafid = afile.fid\n\t}\n\n\trsp, err := c.Send(&Tattach{\n\t\tFID: fid,\n\t\tAFID: afid,\n\t\tUname: user,\n\t\tAname: aname,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tattach := rsp.(*Rattach)\n\n\treturn &Remote{\n\t\tclient: c,\n\t\tfid: fid,\n\t\tqid: attach.QID,\n\t}, nil\n}", "func main() {\n\treader := bufio.NewReader(os.Stdin)\n\targs := os.Args[1:]\n\n\tvar uploadingFile string\n\tif len(args) == 1 {\n\t\tif args[0] == \"server\" {\n\t\t\tsignalingServer()\n\t\t\treturn\n\t\t} else {\n\t\t\tuploadingFile = args[0]\n\t\t}\n\t}\n\n\tvar f *os.File\n\tif uploadingFile != \"\" {\n\t\tfmt.Printf(\"Uploading %s\\n\", uploadingFile)\n\n\t\tvar err error\n\t\tf, err = os.Open(uploadingFile)\n\t\tcheckError(err)\n\t} else {\n\t\tfor {\n\t\t\tfmt.Printf(\"Save to: \")\n\n\t\t\tfilePath, err := reader.ReadString('\\n')\n\t\t\tcheckError(err)\n\t\t\tf, err = os.Create(strings.Trim(filePath, \"\\n\\r\"))\n\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tfmt.Printf(err.Error())\n\t\t\t}\n\t\t}\n\t}\n\tdefer f.Close()\n\n\tvar connIO io.ReadWriteCloser\n\tif transport == \"tcp\" {\n\t\tuploaderAddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:8888\")\n\t\tif uploadingFile != \"\" {\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t\tconnIO, err = net.Dial(\"tcp\", uploaderAddr.String())\n\t\t\tcheckError(err)\n\t\t} else {\n\t\t\tlistener, err := net.ListenTCP(\"tcp\", uploaderAddr)\n\t\t\tcheckError(err)\n\t\t\tfmt.Printf(\"Listening tcp....\\n\")\n\t\t\tconn, err := listener.Accept()\n\t\t\tcheckError(err)\n\t\t\tconnIO = conn\n\t\t}\n\t} else if transport == \"udp\" {\n\t\tuploaderAddr, err := net.ResolveUDPAddr(\"udp\", \"localhost:8888\")\n\t\tif uploadingFile != \"\" {\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t\tconnIO, err = net.Dial(\"udp\", uploaderAddr.String())\n\t\t\tcheckError(err)\n\t\t} else {\n\t\t\tlistener, err := net.ListenUDP(\"udp\", uploaderAddr)\n\t\t\tcheckError(err)\n\t\t\tfmt.Printf(\"Listening udp....\\n\")\n\t\t\tcheckError(err)\n\t\t\tconnIO = listener\n\t\t}\n\t} else {\n\t\tstunUrl, err := ice.ParseURL(stun)\n\t\tcandidateSelectionTimeout := 30 * time.Second\n\t\tconnectionTimeout := 5 * time.Second\n\t\tconfig := &ice.AgentConfig{\n\t\t\tUrls: []*ice.URL{stunUrl},\n\t\t\tNetworkTypes: []ice.NetworkType{\n\t\t\t\tice.NetworkTypeUDP4,\n\t\t\t\tice.NetworkTypeTCP4,\n\t\t\t},\n\t\t\tCandidateTypes: []ice.CandidateType{\n\t\t\t\tice.CandidateTypeHost,\n\t\t\t\tice.CandidateTypeServerReflexive,\n\t\t\t\tice.CandidateTypePeerReflexive,\n\t\t\t\tice.CandidateTypeRelay,\n\t\t\t},\n\t\t\tCandidateSelectionTimeout: &candidateSelectionTimeout,\n\t\t\tConnectionTimeout: &connectionTimeout,\n\t\t}\n\n\t\tagent, err := ice.NewAgent(config)\n\t\tcheckError(err)\n\n\t\tdefer agent.Close()\n\n\t\terr = agent.OnConnectionStateChange(func(state ice.ConnectionState) {\n\t\t\tfmt.Printf(\"State Change: %s\\n\", state.String())\n\t\t\tif state == ice.ConnectionStateDisconnected {\n\t\t\t\tif connIO != nil {\n\t\t\t\t\terr := connIO.Close()\n\t\t\t\t\tcheckError(err)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tmyCandidates, err := agent.GetLocalCandidates()\n\t\tmyIceCandidates, err := newICECandidatesFromICE(myCandidates)\n\t\tcheckError(err)\n\t\tuflag, pass := agent.GetLocalUserCredentials()\n\n\t\tpartnerData := exchange(ExchangeData{\n\t\t\tCandidates: myIceCandidates,\n\t\t\tUflag: uflag,\n\t\t\tPass: pass,\n\t\t})\n\n\t\tfor _, c := range partnerData.Candidates {\n\t\t\ti, err := c.toICE()\n\t\t\tcheckError(err)\n\n\t\t\terr = agent.AddRemoteCandidate(i)\n\t\t\tcheckError(err)\n\t\t}\n\n\t\tvar conn *ice.Conn\n\t\tif uploadingFile != \"\" {\n\t\t\tconn, err = agent.Accept(context.Background(), partnerData.Uflag, partnerData.Pass)\n\t\t} else {\n\t\t\tconn, err = agent.Dial(context.Background(), partnerData.Uflag, partnerData.Pass)\n\t\t}\n\t\tcheckError(err)\n\t\tdefer conn.Close()\n\n\t\tgo func() {\n\t\t\tif uploadingFile != \"\" {\n\t\t\t\tconn.Write([]byte(\"hello\"))\n\t\t\t} else {\n\t\t\t\tconn.Write([]byte(\"world\"))\n\t\t\t}\n\t\t}()\n\n\t\tbuffer := make([]byte, 32 * 1000)\n\t\tconn.Read(buffer)\n\t\tfmt.Printf(\"Receive msg: %s\\n\", string(buffer))\n\n\n\t\tif transport == \"sctp\" {\n\t\t\tvar association *sctp.Association\n\t\t\tconfig := sctp.Config{\n\t\t\t\tNetConn: conn,\n\t\t\t\tLoggerFactory: logging.NewDefaultLoggerFactory(),\n\t\t\t\tMaxReceiveBufferSize: 10 * 1024 * 1024,\n\t\t\t}\n\t\t\tif uploadingFile != \"\" {\n\t\t\t\tassociation, err = sctp.Client(config)\n\t\t\t} else {\n\t\t\t\tassociation, err = sctp.Server(config)\n\t\t\t}\n\t\t\tcheckError(err)\n\t\t\tdefer association.Close()\n\n\t\t\tvar stream *sctp.Stream\n\t\t\tif uploadingFile != \"\" {\n\t\t\t\tstream, err = association.OpenStream(777, sctp.PayloadTypeWebRTCBinary)\n\t\t\t} else {\n\t\t\t\tstream, err = association.AcceptStream()\n\t\t\t}\n\t\t\tcheckError(err)\n\n\t\t\tdefer stream.Close()\n\n\t\t\tconnIO = stream\n\t\t} else {\n\t\t\tconnIO = conn\n\t\t}\n\t}\n\n\tif uploadingFile != \"\" {\n\t\ttime.Sleep(2 * time.Second)\n\t\tfmt.Printf(\"Uploading....\\n\")\n\t} else {\n\t\tfmt.Printf(\"Downloading....\\n\")\n\t}\n\n\tif uploadingFile != \"\" {\n\t\tvar n int64\n\t\tvar err error\n\t\tif transport == \"ice\" || transport == \"sctp\" {\n\t\t\tn, err = io.CopyBuffer(connIO, f, make([]byte, 5 * 1200))\n\t\t\t//n = copy(connIO, f)\n\t\t} else {\n\t\t\tn, err = io.Copy(connIO, f)\n\t\t\t//n = copy(connIO, f)\n\t\t}\n\t\tcheckError(err)\n\n\t\tfmt.Printf(\"Success %v bytes sent!\\n\", n)\n\t\tconnIO.Close()\n\t} else {\n\t\tn, err := io.Copy(f, connIO)\n\t\tcheckError(err)\n\n\t\t//n := copy(f, connIO)\n\n\t\tfmt.Printf(\"Saved %v bytes!\\n\", n)\n\t\tconnIO.Close()\n\t}\n}", "func (sock *Server) user(username, hostname, Servername, realname string) {\n\tsock.Send(\"USER \" + username + \" \" + hostname + \" \" + Servername + \" :\" + realname)\n}", "func UserFileCredentials(username string, password string, filename string) (Addr string, E []byte){\n\t//Generating address of UserFile structure\n\tAddr = getAddress([]byte(username+password+filename))\n\n\t//Generating Key for UserFile structure\n\tE =userlib.Argon2Key([]byte(string([]rune(password+username))),[]byte(filename),16)\n\tuserlib.DebugMsg(\"User %v File %v stored at Addr=%v E=%v\",username,filename,Addr,E)\n\n\treturn \n}", "func ListenAndServe(targetUser, addr string, handler http.Handler) error {\n\tif !flag.Parsed() {\n\t\tflag.Parse()\n\t}\n\tu, err := user.Current()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif u.Uid != \"0\" && *listenFD == 0 {\n\t\t// we are not root and we have no listen fd. Error.\n\t\treturn fmt.Errorf(\"need to run as root. Running as %s (%s)\", u.Name, u.Uid)\n\t} else if u.Uid == \"0\" && *listenFD == 0 {\n\t\t// we are root and we have no listen fd. Do the listen.\n\t\tl, err := net.Listen(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Listen error: %s\", err)\n\n\t\t}\n\t\tf, err := l.(*net.TCPListener).File()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tuid, gid, err := lookupUser(targetUser)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// First extra file: fd == 3\n\t\tcmd := exec.Command(os.Args[0])\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tcmd.ExtraFiles = append(cmd.ExtraFiles, f)\n\t\tcmd.Args = append(cmd.Args, []string{\"-listen-fd\", fmt.Sprint(2 + len(cmd.ExtraFiles))}...)\n\t\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\t\tCredential: &syscall.Credential{\n\t\t\t\tUid: uint32(uid),\n\t\t\t\tGid: uint32(gid),\n\t\t\t},\n\t\t}\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn fmt.Errorf(\"cmd.Run error: %s\", err)\n\t\t}\n\t\treturn nil\n\t} else if u.Uid != \"0\" && *listenFD != 0 {\n\t\t// We are not root and we have a listen fd. Do the accept.\n\t\tl, err := net.FileListener(os.NewFile(uintptr(*listenFD), \"net\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := http.Serve(l, handler); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn fmt.Errorf(\"setuid fail: %s, %d\", u.Uid, *listenFD)\n}", "func (h *Host) SetUser(u string) {\n}", "func Connect(host string, port int, user string) error {\n\tvar err error\n\tfilesystem, err = zyxar.ConnectAsUser(host, uint16(port), user)\n\tif err != nil {\n\t\tlog.Fatal(\"Cannot connect to local filesystem\")\n\t}\n\treturn err\n}", "func userFileHandler(w http.ResponseWriter, r *http.Request) {\n\tfile, err := ioutil.ReadFile(\"user.txt\")\n\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"unable to open user.txt: %s\", err)\n\t}\n\n\tfmt.Fprintf(w, \"%s\\n\", string(file))\n}", "func register(client interfaces.Client) (interfaces.Client, error) {\n\tfile, err := os.OpenFile(\"users.txt\", os.O_APPEND|os.O_CREATE|os.O_WRONLY, os.ModeAppend)\n\tif err != nil {\n\t\treturn client, err\n\t}\n\tdefer file.Close()\n\twriter := bufio.NewWriter(file)\n\tdefer writer.Flush()\n\t_, err = writer.WriteString(\"\\n\" + client.GetHandle() + \",\" + client.GetPass())\n\tif err != nil {\n\t\treturn client, err\n\t}\n\treturn client, err\n}", "func (userdata *User) StoreFile(filename string, data []byte) (err error) {\r\n\tvar fileKey FileKey\r\n\tvar fileElem FileElem\r\n\t//TODO: This is a toy implementation.\r\n\t/**\r\n\tstorageKey, _ := uuid.FromBytes([]byte(filename + userdata.Username)[:16])\r\n\tjsonData, _ := json.Marshal(data)\r\n\tuserlib.DatastoreSet(storageKey, jsonData)\r\n\t*/\r\n\t//End of toy implementation\r\n\t//2 cases: already exists, doesnt exist : create new file, encrypt using SymEnc and marshal it\r\n\tupdatedUser, err := GetLatestUser(userdata.UUID_, userdata.PasswordHash, userdata.HMACKey, userdata.EncKey)\r\n\tif err != nil {\r\n\t\treturn errors.New(\"Failed to retrieve latest user info.\")\r\n\t}\r\n\t//storing to revoked file does nothing, as long as it doesn't update the original file\r\n\r\n\tfileKey, exists := updatedUser.Filespace[filename]\r\n\tif !exists {\r\n\t\t//create new fileKey\r\n\t\t//creating the UUID for the FileKey\r\n\t\tstorageKey := userlib.RandomBytes(16)\r\n\t\tfileKey.KeyId, _ = uuid.FromBytes(storageKey)\r\n\r\n\t\tenc_key, _ := userlib.HashKDF(storageKey, []byte(\"encryption\"))\r\n\t\tfileKey.Enc_key = enc_key[:16]\r\n\t\thmac_key, _ := userlib.HashKDF(storageKey, []byte(\"mac\"))\r\n\t\tfileKey.HMAC_key = hmac_key[:16]\r\n\t\tfileKey.NumFiles = 1\r\n\t\tfileKey.SharedUsers = make(map[string][]string)\r\n\t\tfileKey.UserTokens = make(map[string]uuid.UUID)\r\n\t\tupdatedUser.FilesOwned[filename] = fileKey\r\n\t} else { //overwrite file - shared users can overwrite this file\r\n\t\t//retrieve fileKey and delete any appended files from datastore if they exist\r\n\r\n\t\t//if this file was shared, retrieve fileKey through access token\r\n\t\t//access could have been revoked\r\n\t\t_, own := updatedUser.FilesOwned[filename]\r\n\t\tvar thisFileKey FileKey\r\n\t\tif !own {\r\n\t\t\tat := userdata.AccessTokens[filename]\r\n\t\t\tthisFileKey, err = updatedUser.RetrieveAccessToken(at)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn errors.New(\"Failed to retrieve access token.\")\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tcurrFileKey, _ := userlib.DatastoreGet(fileKey.KeyId)\r\n\t\t\tlen_data := len(currFileKey) - userlib.HashSizeBytes\r\n\r\n\t\t\tif len_data < 0 || len_data > len(currFileKey) || len(currFileKey[:len_data]) < userlib.HashSizeBytes {\r\n\t\t\t\t//automatically return error, file has been changed\r\n\t\t\t\treturn errors.New(\"FileKey data length has changed.\")\r\n\t\t\t}\r\n\t\t\t//verify integrity of both fileKey struct and the file itself\r\n\t\t\tcomputedMac, _ := userlib.HMACEval(fileKey.HMAC_key, currFileKey[:len_data])\r\n\t\t\tif !userlib.HMACEqual(computedMac, currFileKey[len_data:]) {\r\n\t\t\t\treturn errors.New(\"File key struct has been tampered with in Datastore.\")\r\n\t\t\t}\r\n\t\t\t//decrypt + depad fileKey from DS to current fileKey var (overwrite)\r\n\t\t\tdecrypt := userlib.SymDec(fileKey.Enc_key, currFileKey[:len_data])\r\n\t\t\tdecrypt = PKCS(decrypt, \"remove\")\r\n\r\n\t\t\terr = json.Unmarshal(decrypt, &thisFileKey)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn errors.New(\"Error demarshaling.\")\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//delete appended files from key store\r\n\t\tfor i := 1; i <= thisFileKey.NumFiles; i++ {\r\n\t\t\t//retrieve appropriate fileElem from Datastore, generate correct file ID\r\n\t\t\tkeyMsg := thisFileKey.KeyId.String() + \"_\" + strconv.Itoa(i) //i is index of file\r\n\t\t\tkey_bytes, _ := userlib.HMACEval(thisFileKey.HMAC_key, []byte(keyMsg))\r\n\t\t\tfileID, _ := uuid.FromBytes(key_bytes[:16])\r\n\t\t\t//deletes entry if it exists\r\n\t\t\tuserlib.DatastoreDelete(fileID)\r\n\t\t}\r\n\t\t//generate new fileElem to send to datastore and update fileKey accordingly\r\n\t\tfileKey.KeyId = thisFileKey.KeyId\r\n\t\tfileKey.Enc_key = thisFileKey.Enc_key\r\n\t\tfileKey.HMAC_key = thisFileKey.HMAC_key\r\n\t\tfileKey.NumFiles = 1\r\n\t\tfileKey.SharedUsers = thisFileKey.SharedUsers\r\n\t\tfileKey.UserTokens = thisFileKey.UserTokens\r\n\t}\r\n\t//updates user's filespace, depending on share or not\r\n\tupdatedUser.Filespace[filename] = fileKey\r\n\tfileElem.File_ind = 1\r\n\t//generates a new FileElem for overwrite as well\r\n\tkey_msg := fileKey.KeyId.String() + \"_\" + strconv.Itoa(fileElem.File_ind)\r\n\tkey_bytes, _ := userlib.HMACEval(fileKey.HMAC_key, []byte(key_msg))\r\n\tfileElem.FileID, _ = uuid.FromBytes(key_bytes[:16]) //new file ID based on file index and original fileKey\r\n\tfileElem.Filedata = data\r\n\r\n\t//now encrypt the FileKey, FileElem, and userData add HMACs, and send to datastore\r\n\tfk_marshal, _ := json.Marshal(fileKey)\r\n\tfe_marshal, _ := json.Marshal(fileElem)\r\n\tuser_marshal, _ := json.Marshal(updatedUser)\r\n\r\n\tfk_IV := userlib.RandomBytes(userlib.AESBlockSizeBytes) //if IV isnt random, not secure\r\n\tfe_IV := userlib.RandomBytes(userlib.AESBlockSizeBytes)\r\n\tuser_IV := userlib.RandomBytes(userlib.AESBlockSizeBytes) //random IV each time\r\n\r\n\tenc_fileKey := userlib.SymEnc(fileKey.Enc_key, fk_IV, PKCS(fk_marshal, \"add\"))\r\n\tenc_fileElem := userlib.SymEnc(fileKey.Enc_key, fe_IV, PKCS(fe_marshal, \"add\"))\r\n\tenc_user := userlib.SymEnc(updatedUser.EncKey, user_IV, PKCS(user_marshal, \"add\"))\r\n\tfk_hmac, _ := userlib.HMACEval(fileKey.HMAC_key, enc_fileKey)\r\n\tfe_hmac, _ := userlib.HMACEval(fileKey.HMAC_key, enc_fileElem)\r\n\tuser_hmac, _ := userlib.HMACEval(userdata.HMACKey, enc_user)\r\n\r\n\tenc_fileKey = append(enc_fileKey, fk_hmac...)\r\n\tenc_fileElem = append(enc_fileElem, fe_hmac...)\r\n\tenc_user = append(enc_user, user_hmac...)\r\n\t//Set can overwrite current data!\r\n\tuserlib.DatastoreSet(fileKey.KeyId, enc_fileKey)\r\n\tuserlib.DatastoreSet(fileElem.FileID, enc_fileElem)\r\n\tuserlib.DatastoreSet(userdata.UUID_, enc_user)\r\n\r\n\treturn\r\n}", "func FileServer(c Config) Server {\n abs, err := filepath.Abs(c.Root)\n if err != nil { panic(err) }\n c.Root = abs\n\n if c.TempDir == \"\" {\n c.TempDir = filepath.Join(c.Root, \"tmp\")\n } else {\n abs, err = filepath.Abs(c.TempDir)\n if err != nil { panic(err) }\n c.TempDir = abs\n }\n\n return &fileServer{ assets: make(map[string]*assetMeta), config: c }\n}", "func (userdata *User) AppendFile(filename string, data []byte) (err error) {\n\tvar Mapping UserFile\n\tvar File FileData\n\tvar Data FileBlock\n\n\t//////////////////////////////////////////////\n\t//////////// UserFile Record /////////////////\n\t//////////////////////////////////////////////\n\n // Generating address and key for UserFile pair\n\tAddr,E := UserFileCredentials(userdata.Username,userdata.Password,filename)\t\n\tuserlib.DebugMsg(\"APPEND: User %v File %v stored at Addr=%v E=%v\",userdata.Username,filename,Addr,E)\n\n\t// Fetching Encrypted UserFile structure from memory\n\tciphertext,valid := userlib.DatastoreGet(Addr)\n\tif(!valid){\n\t\terr3 := errors.New(strings.ToTitle(\"No such file\"))\n\t\treturn err3\n\t}\n\n\t// Decrypting UserFileData\n\tplaintext,err10 := decryptAES(ciphertext,E)\n\tif(err10!=nil) {\n\t\treturn err10\n\t}\n \n // Unmarshaling and checking for errors\n\terr3 := json.Unmarshal(plaintext,&Mapping)\n\n\tif(err3!=nil){\n\t\treturn err3\n\t}\n\n\t// Verifying HMAC\n\tvar temp UserFile\n\ttemp.Location=Mapping.Location\n\ttemp.Key=Mapping.Key\n\n\tstr,_ := json.Marshal(temp)\n\n\thmac := userlib.NewHMAC(E)\n\thmac.Write([]byte(string([]rune(string(str)))))\n\ttemp.Hmac=hmac.Sum(nil)\n\n\tif !userlib.Equal(temp.Hmac, Mapping.Hmac) {\n\t\terr3 = errors.New(strings.ToTitle(\"UserFile record corrupted by server.\"))\n\t\tuserlib.DebugMsg(\"%v\",err3)\n\t\treturn err3\n\t}\n\n\t////////////////////////////////////////////////////////\n\t////////////////// FileData structure //////////////////\n\t////////////////////////////////////////////////////////\n\n\t// Fetching Address and Key used for FileData structure\n\tAddr1 := Mapping.Location\n\tE1 := Mapping.Key\n\tuserlib.DebugMsg(\"APPEND: User %v File %v stored at Addr1=%v E1=%v\",userdata.Username,filename,Addr1,E1)\n\n\t// Fetching Encrypted FileData structure from memory\n\tciphertext1,valid1 := userlib.DatastoreGet(Addr1)\n\tif(!valid1){\n\t\terr1 := errors.New(strings.ToTitle(\"File Data lost\"))\n\t\treturn err1\n\t}\n\n\t// Decrypting FileData record\n\tplaintext1,err11 := decryptAES(ciphertext1, []byte(string(E1))[:16])\n\tif(err11!=nil){\n\t\treturn err11\n\t}\n\n\terr1 := json.Unmarshal(plaintext1, &File)\n\n\tif(err1!=nil){\n\t\treturn err1\n\t}\n\n\t// Verifying HMAC\n\tvar temp1 FileData\n\ttemp1.Blocks=File.Blocks\n\ttemp1.Keys=File.Keys\n\ttemp1.Hmac=File.Hmac\n\n\tFile.Hmac=nil\n\tstr1,_ := json.Marshal(File)\n\thmac1 := userlib.NewHMAC([]byte(string(E1)))\n\thmac1.Write([]byte(str1))\n\tFile.Hmac=hmac1.Sum(nil)\n\n\tif !userlib.Equal(temp1.Hmac, File.Hmac) {\n\t\terr1 = errors.New(strings.ToTitle(\"Append: FileData record corrupted by server.\"))\n\t\tuserlib.DebugMsg(\"%v\",err1)\n\t\treturn err1\n\t}\n\n//////////////////////// Updating FileData structure //////////////////////// \n//////////////////////// and storing it back in Datastore //////////////////////// \n\n\t// Generating Addr2- address for this block of this file\n\tAddr2 := getAddress(userlib.RandomBytes(256))\n\n\n\t// Generating E2- Key to encrypt and generate HMAC for this block of this file\n\tE2 :=[]rune(string(userlib.Argon2Key(userlib.RandomBytes(256),userlib.RandomBytes(256),16)))\n\tuserlib.DebugMsg(\"APPEND: User %v File %v stored at Addr2=%v E2=%v\",userdata.Username,filename,Addr2,E2)\n\n // Updating slices of FileData structure\n\tFile.Keys=append(File.Keys,E2)\n\tFile.Blocks=append(File.Blocks, Addr2)\n\tFile.Hmac=nil\n\n\t// Calculating HMAC and updating FileData structure\n\tstr2,_ := json.Marshal(File)\n\thmac2 := userlib.NewHMAC([]byte(string(E1)))\n\thmac2.Write([]byte(str2))\n\tFile.Hmac=hmac2.Sum(nil)\n\n\t// Marshalling FileData structure\n\tstr2,_ = json.Marshal(File)\n\n\t// Encrypting FileData structure with E1\n\tciphertext2 := encryptAES([]byte(str2), []byte(string(E1))[:16])\n\n\t// Storing encrypted FileData structure at Addr1\n\tuserlib.DatastoreSet(Addr1,ciphertext2)\n\n\n\n\t////////////////////////////////////////////////////////////////////\n\t///////////////////// Appending FileBlock //////////////////////////\n\t////////////////////////////////////////////////////////////////////\n\n\tData.Data=[]rune(string(data))\n\n\t//Calculating HMAC and updating FileBlock structure\n\tstr3,_ := json.Marshal(Data)\n\thmac3 := userlib.NewHMAC([]byte(string(E2)))\n\thmac3.Write([]byte(str3))\n\tData.Hmac=hmac3.Sum(nil)\t\n\n\t//Marshalling FileBlock structure\n\tstr3,_ = json.Marshal(Data)\n\n\t//Encrypting FileBlock structure with E2\n\tciphertext3 := encryptAES([]byte(str3), []byte(string(E2))[:16]) \n\n\t// Storing encrypted FileBlock structure at Addr2\n\tuserlib.DatastoreSet(Addr2,ciphertext3)\n\tuserlib.DebugMsg(\"Stored at %v, Value=%v\",Addr2,ciphertext3)\n\n\n\treturn nil\n}", "func putUserToKeyServer(cfg upspin.Config, ep *upspin.Endpoint) (upspin.Config, error) {\n\tcfg = config.SetStoreEndpoint(cfg, *ep)\n\tcfg = config.SetDirEndpoint(cfg, *ep)\n\tuser := &upspin.User{\n\t\tName: cfg.UserName(),\n\t\tDirs: []upspin.Endpoint{cfg.DirEndpoint()},\n\t\tStores: []upspin.Endpoint{cfg.StoreEndpoint()},\n\t\tPublicKey: cfg.Factotum().PublicKey(),\n\t}\n\tkey, err := bind.KeyServer(cfg, cfg.KeyEndpoint())\n\tif err != nil {\n\t\treturn cfg, err\n\t}\n\terr = key.Put(user)\n\treturn cfg, err\n}", "func (r *Router) FileServer(path string) {\n\tif path[0] != '/' {\n\t\tpanic(\"Path has to start with a /.\")\n\t}\n\tr.tree.addFileServer(path)\n}", "func (c *Client) Share(path string, username string, write bool) (err error) {\n\tvar ret string\n\terr = c.server.Call(\"share\", &ret, path, username, write, c.session)\n\tif err != nil {\n\t\treturn client.MakeFatalError(err)\n\t}\n\tif ret != \"\" {\n\t\treturn fmt.Errorf(ret)\n\t}\n\treturn nil\n}", "func NewServer(cfg *Config) (svr *Server, err error) {\n\tif cfg.RootPath == \"\" {\n\t\tusr, err := user.Current()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tcfg.RootPath = filepath.Join(usr.HomeDir, \".gdav\")\n\t}\n\tcfg.RootPath, err = filepath.Abs(cfg.RootPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsvr = &Server{\n\t\tCfg: cfg,\n\n\t\tDavHandlers: make(map[string]*webdav.Handler),\n\t\tUsers: new(sync.Map), //,\n\n\t\tRouter: httprouter.New(),\n\n\t\tSesstions: sessions.NewFilesystemStore(cfg.RootPath+\"/.sesstions\", securecookie.GenerateRandomKey(32)),\n\t}\n\n\t//make webdav\n\tfor uid, user := range cfg.Users {\n\t\tuser.UID = uid\n\n\t\t// user root\n\t\tif !filepath.IsAbs(user.Root) {\n\t\t\tuser.Root = filepath.Join(cfg.RootPath, user.Root)\n\t\t}\n\n\t\trootInfo, statErr := os.Stat(user.Root)\n\t\tif os.IsNotExist(statErr) {\n\t\t\tlog.Printf(\"path not exist: %s\", user.Root)\n\t\t\terr = os.MkdirAll(user.Root, 0770)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trootInfo, statErr = os.Stat(user.Root)\n\t\t}\n\t\tif statErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s err: %v\", user.Root, statErr)\n\t\t}\n\t\tif !rootInfo.IsDir() {\n\t\t\treturn nil, fmt.Errorf(\"%s is file not dir\", user.Root)\n\t\t}\n\n\t\tif _, ok := svr.DavHandlers[user.Root]; !ok {\n\t\t\tuserHides := []string{}\n\t\t\tfor _, hidePath := range user.Hides {\n\t\t\t\tuserHides = append(userHides, \"/\"+cfg.Prefix+\"/\"+hidePath)\n\t\t\t}\n\n\t\t\tsvr.DavHandlers[user.Root] = &webdav.Handler{\n\t\t\t\tPrefix: \"/\" + cfg.Prefix,\n\t\t\t\tFileSystem: webdav.Dir(user.Root),\n\t\t\t\tLockSystem: webdav.NewMemLS(),\n\t\t\t\tHides: userHides, // user.Hides,\n\t\t\t}\n\t\t}\n\t\tuser.WebDav = svr.DavHandlers[user.Root]\n\n\t\tsvr.Users.Store(user.UID, user)\n\t}\n\n\tsvr.RegRouter()\n\n\treturn\n}", "func server(Users []user) {\n\tgUsers = make(map[int]user)\n\n\tfor i := 0; i < len(Users); i++ {\n\t\tgUsers[i] = Users[i]\n\t}\n\n\thttp.HandleFunc(\"/\", handler) // asignamos un handler global\n\thttp.HandleFunc(\"/saveFile\", handlerSaveFile) // asignamos un handler global\n\tSetupCloseHandler()\n\n\t// escuchamos el puerto 10443 con https y comprobamos el error\n\t// Para generar certificados autofirmados con openssl usar:\n\t// openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes -subj \"/C=ES/ST=Alicante/L=Alicante/O=UA/OU=Org/CN=www.ua.com\"\n\tchk(http.ListenAndServeTLS(\":10443\", \"cert.pem\", \"key.pem\", nil))\n}", "func (ks *KopiaSnapshotter) ConnectOrCreateFilesystemWithServer(serverAddr, repoPath string) (*exec.Cmd, error) {\n\treturn nil, nil\n}", "func File(path, mime string) (f *FileServer) {\n\tf = &FileServer{\n\t\tmime: mime,\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tdata, err := ioutil.ReadFile(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error:\", err)\n\t\t\t} else {\n\t\t\t\tf.data = data\n\t\t\t}\n\t\t\tsleep()\n\t\t}\n\t}()\n\treturn f\n}", "func AddUser(username string, Conn *net.TCPConn, manifest map[string]entry) {\n\tmanifest[username] = entry{Conn}\n}", "func setFsUser(usr *sysuser) {\n\terr := syscall.Setuid(usr.uid)\n\thandleErr(err)\n\n\terr = syscall.Setgid(usr.gid)\n\thandleErr(err)\n}", "func userConnect(username string) {\n\tfor key := range connMap {\n\t\tconnMap[key].Write([]byte(\"TCCHAT_USERIN\\t\" + username + \"\\n\"))\n\t}\n}", "func (userdata *User) AppendFile(filename string, data []byte) (err error) {\r\n\t//if file DNE return error\r\n\tupdatedUser, err := GetLatestUser(userdata.UUID_, userdata.PasswordHash, userdata.HMACKey, userdata.EncKey)\r\n\tif err != nil {\r\n\t\treturn errors.New(\"Failed to retrieve latest user info.\")\r\n\t}\r\n\t//again use access token if appending to shared file\r\n\t_, own := updatedUser.FilesOwned[filename]\r\n\tvar fileKey FileKey\r\n\tif !own { //this is just in case a revocation has happened and the fileKey data has changed\r\n\t\tat := userdata.AccessTokens[filename]\r\n\t\tfileKey, err = updatedUser.RetrieveAccessToken(at)\r\n\t\tif err != nil {\r\n\t\t\treturn errors.New(\"Failed to retrieve access token.\")\r\n\t\t}\r\n\t} else { //but if you own the file, just directly retrieve fileKey\r\n\t\tfk, found := updatedUser.Filespace[filename]\r\n\t\tfileKeyDS, in_DS := userlib.DatastoreGet(fk.KeyId)\r\n\r\n\t\tif !found || !in_DS { //if file not in users file space or not found in Datastore, error\r\n\t\t\treturn errors.New(\"File does not exist\")\r\n\t\t}\r\n\t\tlen_data := len(fileKeyDS) - userlib.HashSizeBytes //used for slicing out HMAC later\r\n\r\n\t\tif len(fileKeyDS[:len_data]) < userlib.HashSizeBytes {\r\n\t\t\t//automatically return error, file has been changed\r\n\t\t\treturn errors.New(\"File key data length has changed.\")\r\n\t\t}\r\n\r\n\t\t//need to check that the fileKey struct hasnt been corrupted, but not the last file\r\n\t\t//dont need to decrypt to do this\r\n\t\tcomputedMac, _ := userlib.HMACEval(fk.HMAC_key, fileKeyDS[:len_data])\r\n\t\tif !userlib.HMACEqual(computedMac, fileKeyDS[len_data:]) {\r\n\t\t\treturn errors.New(\"File key has been tampered with in Datastore.\")\r\n\t\t}\r\n\r\n\t\t//decrypt + depad fileKey from DS to current fileKey var (overwrite)\r\n\t\tdecrypt := userlib.SymDec(fk.Enc_key, fileKeyDS[:len_data])\r\n\t\tdecrypt = PKCS(decrypt, \"remove\")\r\n\t\terr = json.Unmarshal(decrypt, &fileKey)\r\n\t\tif err != nil {\r\n\t\t\treturn errors.New(\"Error demarshaling.\")\r\n\t\t}\r\n\t}\r\n\r\n\t//generate new file under same FileKey\r\n\tnumFiles := fileKey.NumFiles\r\n\tfile_ind := numFiles + 1\r\n\tfileKey.NumFiles = file_ind //increment number of files by 1\r\n\r\n\tkeyMsg := fileKey.KeyId.String() + \"_\" + strconv.Itoa(file_ind)\r\n\tkey_bytes, _ := userlib.HMACEval(fileKey.HMAC_key, []byte(keyMsg))\r\n\tfileID, _ := uuid.FromBytes(key_bytes[:16])\r\n\r\n\t//populate a new fileElem struct for the append\r\n\tfileElem := FileElem{fileID, data, file_ind}\r\n\t//question: does users Filespace get updated too automatically?\r\n\r\n\t//Marshal, pad, encrypt, append HMAC and send to Datastore (for updated FileKey and fileElem)\r\n\tfileElem_json, _ := json.Marshal(fileElem)\r\n\tfileKey_json, _ := json.Marshal(fileKey)\r\n\r\n\tfk_IV := userlib.RandomBytes(userlib.AESBlockSizeBytes)\r\n\tfe_IV := userlib.RandomBytes(userlib.AESBlockSizeBytes)\r\n\tfileElem_enc := userlib.SymEnc(fileKey.Enc_key, fe_IV, PKCS(fileElem_json, \"add\"))\r\n\tfileKey_enc := userlib.SymEnc(fileKey.Enc_key, fk_IV, PKCS(fileKey_json, \"add\"))\r\n\r\n\t//Add HMACs for both file key and file elem struct (runtime corresponds to size of appended file, nothing else)\r\n\tfk_hmac, _ := userlib.HMACEval(fileKey.HMAC_key, fileKey_enc)\r\n\tfe_hmac, _ := userlib.HMACEval(fileKey.HMAC_key, fileElem_enc)\r\n\r\n\tfileKey_enc = append(fileKey_enc, fk_hmac...)\r\n\tfileElem_enc = append(fileElem_enc, fe_hmac...)\r\n\tuserlib.DatastoreSet(fileKey.KeyId, fileKey_enc)\r\n\tuserlib.DatastoreSet(fileElem.FileID, fileElem_enc)\r\n\r\n\treturn err\r\n}", "func NewUserFile(store *Dir, user string) (u *UserFile) {\n\tu = &UserFile{}\n\tu.store = store\n\tu.user = user\n\treturn\n}", "func SaveFile(name string, content string) {\n\tmyself, error := user.Current()\n\n\tif error != nil {\n\t\tfmt.Println(error)\n\t}\n\n\tfullPath := myself.HomeDir + \"/Documents/Server/\" + name\n\tfmt.Println(\"FILE SAVED AT => \" + fullPath)\n\tioutil.WriteFile(fullPath, []byte(content), 0644)\n}", "func runServerToClientCopyAs(who, ttype string, conn *xsnet.Conn, srcPath string, chaffing bool) (exitStatus uint32, err error) {\n\tu, err := user.Lookup(who)\n\tif err != nil {\n\t\texitStatus = 1\n\t\treturn\n\t}\n\tvar uid, gid uint32\n\t_, _ = fmt.Sscanf(u.Uid, \"%d\", &uid) // nolint: gosec\n\t_, _ = fmt.Sscanf(u.Gid, \"%d\", &gid) // nolint: gosec\n\tlog.Println(\"uid:\", uid, \"gid:\", gid)\n\n\t// Need to clear server's env and set key vars of the\n\t// target user. This isn't perfect (TERM doesn't seem to\n\t// work 100%; ANSI/xterm colour isn't working even\n\t// if we set \"xterm\" or \"ansi\" here; and line count\n\t// reported by 'stty -a' defaults to 24 regardless\n\t// of client shell window used to run client.\n\t// Investigate -- rlm 2018-01-26)\n\tos.Clearenv()\n\t_ = os.Setenv(\"HOME\", u.HomeDir) // nolint: gosec\n\t_ = os.Setenv(\"TERM\", ttype) // nolint: gosec\n\t_ = os.Setenv(\"XS_SESSION\", \"1\") // nolint: gosec\n\n\tvar c *exec.Cmd\n\tcmdName := xs.GetTool(\"tar\")\n\tif !path.IsAbs(srcPath) {\n\t\tsrcPath = fmt.Sprintf(\"%s%c%s\", u.HomeDir, os.PathSeparator, srcPath)\n\t}\n\n\tsrcDir, srcBase := path.Split(srcPath)\n\tcmdArgs := []string{\"-cz\", \"-C\", srcDir, \"-f\", \"-\", srcBase}\n\n\tc = exec.Command(cmdName, cmdArgs...) // nolint: gosec\n\n\t//If os.Clearenv() isn't called by server above these will be seen in the\n\t//client's session env.\n\t//c.Env = []string{\"HOME=\" + u.HomeDir, \"SUDO_GID=\", \"SUDO_UID=\", \"SUDO_USER=\", \"SUDO_COMMAND=\", \"MAIL=\", \"LOGNAME=\"+who}\n\tc.Dir = u.HomeDir\n\tc.SysProcAttr = &syscall.SysProcAttr{}\n\tc.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}\n\tc.Stdout = conn\n\t// Stderr sinkholing (or buffering to something other than stdout)\n\t// is important. Any extraneous output to tarpipe messes up remote\n\t// side as it's expecting pure tar data.\n\t// (For example, if user specifies abs paths, tar outputs\n\t// \"Removing leading '/' from path names\")\n\tstdErrBuffer := new(bytes.Buffer)\n\tc.Stderr = stdErrBuffer\n\t//c.Stderr = nil\n\n\tif chaffing {\n\t\tconn.EnableChaff()\n\t}\n\t//defer conn.Close()\n\tdefer conn.DisableChaff()\n\tdefer conn.ShutdownChaff()\n\n\t// Start the command (no pty)\n\tlog.Printf(\"[%v %v]\\n\", cmdName, cmdArgs)\n\terr = c.Start() // returns immediately\n\tif err != nil {\n\t\tlog.Printf(\"Command finished with error: %v\", err)\n\t\treturn xsnet.CSEExecFail, err // !?\n\t}\n\tif err := c.Wait(); err != nil {\n\t\t//fmt.Println(\"*** c.Wait() done ***\")\n\t\tif exiterr, ok := err.(*exec.ExitError); ok {\n\t\t\t// The program has exited with an exit code != 0\n\n\t\t\t// This works on both Unix and Windows. Although package\n\t\t\t// syscall is generally platform dependent, WaitStatus is\n\t\t\t// defined for both Unix and Windows and in both cases has\n\t\t\t// an ExitStatus() method with the same signature.\n\t\t\tif status, ok := exiterr.Sys().(syscall.WaitStatus); ok {\n\t\t\t\texitStatus = uint32(status.ExitStatus())\n\t\t\t\tif len(stdErrBuffer.Bytes()) > 0 {\n\t\t\t\t\tlog.Print(stdErrBuffer)\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"Exit Status: %d\", exitStatus)\n\t\t\t}\n\t\t}\n\t}\n\t//fmt.Println(\"*** server->client cp finished ***\")\n\treturn\n}", "func (endpoint *VhostUserEndpoint) Attach(h hypervisor) error {\n\tnetworkLogger().WithField(\"endpoint-type\", \"vhostuser\").Info(\"Attaching endpoint\")\n\n\t// Generate a unique ID to be used for hypervisor commandline fields\n\trandBytes, err := utils.GenerateRandomBytes(8)\n\tif err != nil {\n\t\treturn err\n\t}\n\tid := hex.EncodeToString(randBytes)\n\n\td := config.VhostUserDeviceAttrs{\n\t\tDevID: id,\n\t\tSocketPath: endpoint.SocketPath,\n\t\tMacAddress: endpoint.HardAddr,\n\t\tType: config.VhostUserNet,\n\t}\n\n\treturn h.addDevice(d, vhostuserDev)\n}", "func StartServer(port string) error {\n\tconfig, err := loadConfig(configPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := newRolledLogger(config.logDir, config.nLogFiles)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer l.close()\n\n\tif !config.pasv && !config.port {\n\t\terr := errors.New(\"ftpserver: port_mode and pasv_mode cannot both be NO\")\n\t\tl.logError(err)\n\t\treturn err\n\t}\n\n\t// populate users\n\tu, err := ioutil.ReadFile(config.usersFile)\n\tif err != nil {\n\t\tl.logError(err)\n\t\treturn err\n\t}\n\n\tlines := strings.Split(string(u), \"\\n\")\n\tusers := make(map[string]string)\n\tfor _, l := range lines {\n\t\tuser := strings.Split(l, \" \")\n\t\tif len(user) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tusers[user[0]] = user[1]\n\t}\n\n\t// create listener\n\tln, err := net.Listen(\"tcp\", net.JoinHostPort(\"\", port))\n\tif err != nil {\n\t\tl.logError(err)\n\t\treturn err\n\t}\n\n\t//listen loop\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tl.logError(err)\n\t\t\treturn err\n\t\t}\n\n\t\thandler, err := newHandler(conn, l, config, users)\n\t\tif err != nil {\n\t\t\tl.logError(err)\n\t\t\tconn.Close()\n\t\t\tcontinue\n\t\t}\n\n\t\tgo handler.handle()\n\t}\n}", "func mount(\n\tdir string,\n\tcfg *MountConfig,\n\tready chan<- error) (dev *os.File, err error) {\n\t// On linux, mounting is never delayed.\n\tready <- nil\n\n\t// Create a socket pair.\n\tfds, err := syscall.Socketpair(syscall.AF_FILE, syscall.SOCK_STREAM, 0)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Socketpair: %v\", err)\n\t\treturn\n\t}\n\n\t// Wrap the sockets into os.File objects that we will pass off to fusermount.\n\twriteFile := os.NewFile(uintptr(fds[0]), \"fusermount-child-writes\")\n\tdefer writeFile.Close()\n\n\treadFile := os.NewFile(uintptr(fds[1]), \"fusermount-parent-reads\")\n\tdefer readFile.Close()\n\n\t// Start fusermount, passing it pipes for stdout and stderr.\n\tcmd := exec.Command(\n\t\t\"fusermount\",\n\t\t\"-o\", cfg.toOptionsString(),\n\t\t\"--\",\n\t\tdir,\n\t)\n\n\tcmd.Env = append(os.Environ(), \"_FUSE_COMMFD=3\")\n\tcmd.ExtraFiles = []*os.File{writeFile}\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"StdoutPipe: %v\", err)\n\t\treturn\n\t}\n\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"StderrPipe: %v\", err)\n\t\treturn\n\t}\n\n\terr = cmd.Start()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Starting fusermount: %v\", err)\n\t\treturn\n\t}\n\n\t// Log fusermount output until it closes stdout and stderr.\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\tgo lineLogger(&wg, \"mount helper output\", stdout)\n\tgo lineLogger(&wg, \"mount helper error\", stderr)\n\twg.Wait()\n\n\t// Wait for the command.\n\terr = cmd.Wait()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"fusermount: %v\", err)\n\t\treturn\n\t}\n\n\t// Wrap the socket file in a connection.\n\tc, err := net.FileConn(readFile)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"FileConn: %v\", err)\n\t\treturn\n\t}\n\tdefer c.Close()\n\n\t// We expect to have a Unix domain socket.\n\tuc, ok := c.(*net.UnixConn)\n\tif !ok {\n\t\terr = fmt.Errorf(\"Expected UnixConn, got %T\", c)\n\t\treturn\n\t}\n\n\t// Read a message.\n\tbuf := make([]byte, 32) // expect 1 byte\n\toob := make([]byte, 32) // expect 24 bytes\n\t_, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ReadMsgUnix: %v\", err)\n\t\treturn\n\t}\n\n\t// Parse the message.\n\tscms, err := syscall.ParseSocketControlMessage(oob[:oobn])\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ParseSocketControlMessage: %v\", err)\n\t\treturn\n\t}\n\n\t// We expect one message.\n\tif len(scms) != 1 {\n\t\terr = fmt.Errorf(\"expected 1 SocketControlMessage; got scms = %#v\", scms)\n\t\treturn\n\t}\n\n\tscm := scms[0]\n\n\t// Pull out the FD returned by fusermount\n\tgotFds, err := syscall.ParseUnixRights(&scm)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"syscall.ParseUnixRights: %v\", err)\n\t\treturn\n\t}\n\n\tif len(gotFds) != 1 {\n\t\terr = fmt.Errorf(\"wanted 1 fd; got %#v\", gotFds)\n\t\treturn\n\t}\n\n\t// Turn the FD into an os.File.\n\tdev = os.NewFile(uintptr(gotFds[0]), \"/dev/fuse\")\n\n\treturn\n}", "func add_user(uname string, psw string) (string, bool) {\n\tuser_map_lock.Lock()\n\tdefer user_map_lock.Unlock()\n\t_, is_exist := user_map[uname]\n\tif !is_exist {\n\t\t//create user if not exist\n\t\tuser_map[uname] = psw\n\t\t//open user list file to write to end of it\n\t\tcreate_and_lock(USERLIST_FILENAME) // lock userlist file for editing\n\t\tdefer lock_for_files_map[USERLIST_FILENAME].Unlock()\n\t\tfile, open_err := os.OpenFile(USERLIST_FILENAME, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)\n\t\tdefer file.Close()\n\t\tif open_err != nil {\n\t\t\treturn fmt.Sprintf(\"error: Server open error%s\\n\", END_TAG), false\n\t\t}\n\n\t\ttext := uname + \" : \" + psw + \"\\r\\n\"\n\t\tif _, write_err := file.WriteString(text); write_err != nil {\n\t\t\treturn fmt.Sprintf(\"error: Server write file error%s\\n\", END_TAG), false\n\t\t}\n\t\t//create user data file\n\t\tu_file_name := uname + \".txt\"\n\t\tcreate_and_lock(u_file_name) // lock user file for deleting and recreating\n\t\tdefer lock_for_files_map[u_file_name].Unlock()\n\t\tos.Remove(u_file_name) // clear old junk\n\t\tcreated_file, create_err := os.Create(u_file_name)\n\t\tdefer created_file.Close()\n\t\tif create_err != nil {\n\t\t\treturn fmt.Sprintf(\"error: Server create error%s\\n\", END_TAG), false\n\t\t} else {\n\t\t\t//response\n\t\t\treturn fmt.Sprintf(\"success: I added user %s.%s\\n\", uname, END_TAG), true\n\t\t}\n\t} else {\n\t\t//negative response\n\t\treturn fmt.Sprintf(\"error: user, %s, already exists.%s\\n\", uname, END_TAG), false\n\t}\n}", "func (c *Connection) Login(user string, password string) error {\n\tif user == \"\" {\n\t\treturn fmt.Errorf(\"FTP Connection Error: User can not be blank!\")\n\t}\n\tif password == \"\" {\n\t\treturn fmt.Errorf(\"FTP Connection Error: Password can not be blank!\")\n\t}\n\t// TODO: Check the server's response codes.\n\t_, _, err := c.Cmd(\"USER\", user)\n\t_, _, err = c.Cmd(\"PASS\", password)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (userdata *User) ShareFile(filename string, recipient string) (\n\tmsgid string, err error) {\n\t\n\t\n\t////////////////// Loading The file //////////////////////////\n\n\n\tvar Mapping UserFile\n\tvar Share UserFile\n\n // Generating address and key for UserFile pair\n\tAddr,E := UserFileCredentials(userdata.Username,userdata.Password,filename)\t\n\tuserlib.DebugMsg(\"SHARE: User %v File %v stored at Addr=%v E=%v\",userdata.Username,filename,Addr,E)\n\n\t//Fetching Encrypted UserFile structure from memory\n\tciphertext,valid := userlib.DatastoreGet(Addr)\n\tif(!valid){\n\t\terr3 := errors.New(strings.ToTitle(\"No such file\"))\n\t\treturn msgid,err3\n\t}\n\n\t//Decrypting UserFileData\n\tplaintext,err10 := decryptAES(ciphertext, E)\n\tif(err10!=nil) {\n\t\treturn msgid,err10\n\t}\n\n\terr3 := json.Unmarshal(plaintext,&Mapping)\n\n\tif(err!=nil){\n\t\treturn msgid,err\n\t}\n\n\t//////Verifying HMAC\n\tvar temp UserFile\n\ttemp.Location=Mapping.Location\n\ttemp.Key=Mapping.Key\n\n\tstr,_ := json.Marshal(temp)\n\n\thmac := userlib.NewHMAC(E)\n\thmac.Write([]byte(str))\n\ttemp.Hmac=hmac.Sum(nil)\n\n\tif !userlib.Equal(temp.Hmac, Mapping.Hmac) {\n\t\terr3 = errors.New(strings.ToTitle(\"UserFile record corrupted by server.\"))\n\t\tuserlib.DebugMsg(\"%v\",err3)\n\t\treturn msgid,err3\n\t}\n\n\t//Fetching Sender's and recipient's Keys\n\tKey := userdata.RSAKey\n\tReceiverKey,valid := userlib.KeystoreGet(recipient) \n\tif(!valid){\n\t\treturn msgid,errors.New(strings.ToTitle(\"Recipient not found\"))\n\t}\n\n\t/////////////////////////////////////////////////////////////////////////////////////////\n\t// Storing sharing information\n\t/////////////////////////////////////////////////////////////////////////////////////////\n\n\tseed1 := uuid.New().String()\n\tseed2 := uuid.New().String()\n\tseed3 := uuid.New().String() \n\n // Generating address and key for record containing sharing information\n\tRecordLocation := getAddress([]byte(seed1))\n\tE1 :=[]rune(string(userlib.Argon2Key([]byte(seed2),[]byte(seed3),16)))\n\tuserlib.DebugMsg(\"SHARE: Sharing Record stored at Addr=%v E=%v\",RecordLocation,E1)\n\n\t// Populating sharingRecord (message to be sent)\n\tvar Data sharingRecord \n\t//Data.Location = RecordLocation\n\tData.Seed1 = seed1\n\tData.Seed2 = seed2\n\tData.Seed3 = seed3\n\n\t// Populating Share\n\tShare.Location = Mapping.Location\n\tShare.Key=Mapping.Key\n\tstr1,_ := json.Marshal(Share)\n\n\thmac1 := userlib.NewHMAC([]byte(string(E1)))\n\thmac1.Write([]byte(str1))\n\tShare.Hmac=hmac1.Sum(nil)\n\n\t//Marshalling FileData structure\n\tstr3,_ := json.Marshal(Share)\n\n\t//Encrypting FileData structure with E1\n\tciphertext3 := encryptAES([]byte(str3), []byte(string(E1))[:16]) \n\n\t// Storing encrypted FileData structure at Addr1\n\tuserlib.DebugMsg(\"Stored at %v is %v\",RecordLocation,ciphertext3)\n\tuserlib.DatastoreSet(RecordLocation,ciphertext3)\n\n\t//Encrypting with recipient's public key\n\tstr2,_ := json.Marshal(Data)\n\tencrypted,err := userlib.RSAEncrypt(&ReceiverKey,str2,nil)\n\tif(err!=nil){\n\t\treturn msgid,err\n\t}\n\n\t//RSA signing\n\tsign, err := userlib.RSASign(Key, str2)\n\tif err != nil {\n\t\treturn msgid,err\n\t}\n\t\n\tmsgid = string(encrypted)\n\n\tuserlib.DatastoreSet(getAddress(encrypted),sign)\n\n\treturn msgid,nil\n}", "func InitUser(username string, password string) (userdataptr *User, err error) {\n\tvar userdata User\n\tuserdataptr = &userdata\n\n\tuserdata.Username = username\n\tuserdata.Password = password\n\n\t//map for all the files\n\thm := make(map[string]FileKeys)\n\tuserdata.Files = hm\n\n\t//map for sharedFiles\n\tsf := make(map[string]userlib.UUID)\n\tuserdata.SharedFiles = sf\n\n\t//map for receivedFiles\n\t//rf := make(map[string]AccessRecord)\n\t//userdata.ReceivedFiles = rf\n\n\t//map for recordKeys\n\trk := make(map[string][]byte)\n\tuserdata.RecordKeys = rk\n\n\t//RSA key\n\t//generate public encryption keys and digital signature keys\n\tpublicEncryptionKey, publicDecryptionKey, _ := userlib.PKEKeyGen()\n\tdigitalPrivateKey, digitalPublicKey, _ := userlib.DSKeyGen()\n\n\t//set users private RSA key and private DS Key\n\tuserdata.RSA = publicDecryptionKey\n\tuserdata.DS = digitalPrivateKey\n\n\t//check if username already exists\n\t_, duplicate := userlib.KeystoreGet(username + \"PK\")\n\tif (duplicate) {\n\t\treturn nil, errors.New(\"This user already exists\")\n\t}\n\n\t//set users public RSA key\n\tuserlib.KeystoreSet(username + \"PK\", publicEncryptionKey)\n\tuserlib.KeystoreSet(username + \"DS\", digitalPublicKey)\n\n\t//create salt and generate the key using this salt\n\tsalt := userlib.Hash([]byte(username + password))\n\n\t//userKey is the key used to store the user struct in Datastore\n\tvar userKey []byte\n\tuserKey = userlib.Argon2Key([]byte(password), salt[:16], uint32(userlib.AESKeySize))\n\n\t//UUID should be userKEy\n\tnew_UUID, _ := uuid.FromBytes([]byte(userKey))\n\n\t//data should be marshaled version of the user struct\n\tdata, _ := json.Marshal(userdata)\n\n\t//padding for userstruct, must be multiple of AESBlockSize\n\tdata = padFile(data)\n\n\t//generate IV\n\tIV := userlib.RandomBytes(userlib.AESKeySize)\n\n\t//generate key for Symmetric encryption\n\tsalt2 := userlib.Hash([]byte(password + username))\n\tencryptionKey := userlib.Argon2Key([]byte(password), salt2[:16], uint32(userlib.AESKeySize))\n\n\t//encrypt the user struct\n\tencryptedMessage := userlib.SymEnc(encryptionKey, IV, data)\n\n\t//Get the HMAC key\n\thashKey := userlib.Argon2Key([]byte(password), salt2[16:], uint32(userlib.AESKeySize))\n\tUser_HMAC, _ := userlib.HMACEval(hashKey, []byte(encryptedMessage))\n\n\t//store everything in the datastore\n\t//make a slice containing HMAC, and encrypted struct\n\t//then marshal this 2D slice so it converts into []byte format\n\tvar output Stored\n\toutput.HMAC = User_HMAC\n\toutput.EncryptedM = encryptedMessage\n\n\t//output := [][]byte{User_HMAC, encryptedMessage}\n\tmarshalOutput, _ := json.Marshal(output)\n\n\tuserlib.DatastoreSet(new_UUID, marshalOutput)\n\treturn &userdata, nil\n}", "func (ghost *Ghost) StartUploadServer() error {\n\tlog.Println(\"StartUploadServer: started\")\n\n\tdefer func() {\n\t\tlog.Println(\"StartUploadServer: terminated\")\n\t}()\n\n\tfilePath := ghost.fileOp.Filename\n\tdirPath := filepath.Dir(filePath)\n\tif _, err := os.Stat(dirPath); os.IsNotExist(err) {\n\t\tos.MkdirAll(dirPath, 0755)\n\t}\n\n\tfile, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tfor {\n\t\tbuffer := <-ghost.uploadContext.Data\n\t\tif buffer == nil {\n\t\t\tbreak\n\t\t}\n\t\tfile.Write(buffer)\n\t}\n\n\tif ghost.fileOp.Perm > 0 {\n\t\tfile.Chmod(os.FileMode(ghost.fileOp.Perm))\n\t}\n\n\treturn nil\n}", "func (c *Client) writeUser() {\n\tmessage := NewMessage(\"USER\", []string{\n\t\tc.UserName, // <user>\n\t\tstrconv.Itoa(c.Mode), // <mode>\n\t\t\"*\", // <unused>\n\t\tc.RealName, // <realname>\n\t})\n\tc.Write(message)\n}", "func Listen(targetUser, network, addr string) (net.Listener, error) {\n\tif !flag.Parsed() {\n\t\tflag.Parse()\n\t}\n\tu, err := user.Current()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif u.Uid != \"0\" && *listenFD == 0 {\n\t\t// we are not root and we have no listen fd. Error.\n\t\treturn nil, fmt.Errorf(\"need to run as root. Running as %s (%s)\", u.Name, u.Uid)\n\t} else if u.Uid == \"0\" && *listenFD == 0 {\n\t\t// we are root and we have no listen fd. Do the listen.\n\t\tln, err := net.Listen(network, addr)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Listen error: %s\", err)\n\n\t\t}\n\t\tvar f *os.File\n\t\tswitch ln := ln.(type) {\n\t\tcase *net.TCPListener:\n\t\t\tf, err = ln.File()\n\t\tcase *net.UnixListener:\n\t\t\tf, err = ln.File()\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"unsupported network: %T\", ln)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tuid, gid, err := lookupUser(targetUser)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// First extra file: fd == 3\n\t\tcmd := exec.Command(os.Args[0])\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tcmd.ExtraFiles = append(cmd.ExtraFiles, f)\n\t\tcmd.Args = append(cmd.Args, []string{\"-listen-fd\", fmt.Sprint(2 + len(cmd.ExtraFiles))}...)\n\t\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\t\tCredential: &syscall.Credential{\n\t\t\t\tUid: uint32(uid),\n\t\t\t\tGid: uint32(gid),\n\t\t\t},\n\t\t}\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cmd.Run error: %s\", err)\n\t\t}\n\t\treturn nil, nil\n\t} else if u.Uid != \"0\" && *listenFD != 0 {\n\t\t// We are not root and we have a listen fd. Do the accept.\n\t\tln, err := net.FileListener(os.NewFile(uintptr(*listenFD), \"net\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn ln, nil\n\t}\n\treturn nil, fmt.Errorf(\"setuid fail: %s, %d\", u.Uid, *listenFD)\n}", "func newFSConn(token, infoPath string) (conn *FSConn, err error) {\n\tvar info slack.Info\n\tconn = new(FSConn)\n\n\tif infoPath != \"\" {\n\t\tbuf, err := ioutil.ReadFile(infoPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ReadFile(%s): %s\", infoPath, err)\n\t\t}\n\t\terr = json.Unmarshal(buf, &info)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unmarshal: %s\", err)\n\t\t}\n\t} else {\n\t\tconn.api = slack.New(token)\n\t\t//conn.api.SetDebug(true)\n\t\tconn.ws, err = conn.api.StartRTM(\"\", \"https://slack.com\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"StartRTM(): %s\\n\", err)\n\t\t}\n\t\tinfo = conn.api.GetInfo()\n\t}\n\n\tconn.in = make(chan slack.SlackEvent)\n\tconn.sinks = make([]EventHandler, 0, 5)\n\tconn.Super = NewSuper()\n\n\tusers := make([]*User, 0, len(info.Users))\n\tfor _, u := range info.Users {\n\t\tusers = append(users, NewUser(u, conn))\n\t}\n\tconn.users, err = NewUserSet(\"users\", conn, NewUserDir, users)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewUserSet: %s\", err)\n\t}\n\n\tconn.self, err = NewSelf(conn, info.User, info.Team)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewSelf: %s\", err)\n\t}\n\n\tchans := make([]Room, 0, len(info.Channels))\n\tfor _, c := range info.Channels {\n\t\tchans = append(chans, NewChannel(c, conn))\n\t}\n\tconn.channels, err = NewRoomSet(\"channels\", conn, NewChannelDir, chans)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewRoomSet: %s\", err)\n\t}\n\n\tgroups := make([]Room, 0, len(info.Groups))\n\tfor _, g := range info.Groups {\n\t\tgroups = append(groups, NewGroup(g, conn))\n\t}\n\tconn.groups, err = NewRoomSet(\"groups\", conn, NewGroupDir, groups)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewRoomSet: %s\", err)\n\t}\n\n\tims := make([]Room, 0, len(info.IMs))\n\tfor _, im := range info.IMs {\n\t\tims = append(ims, NewIM(im, conn))\n\t}\n\tconn.ims, err = NewRoomSet(\"ims\", conn, NewIMDir, ims)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewRoomSet: %s\", err)\n\t}\n\n\t// simplify dispatch code by keeping track of event handlers\n\t// in a slice. We (FSConn) are an event sink too - add\n\t// ourselves to the list first, so that we can separate\n\t// routing logic from connection-level handling logic.\n\tconn.sinks = append(conn.sinks, conn,\n\t\tconn.users, conn.channels, conn.groups, conn.ims)\n\n\t// only spawn goroutines in online mode\n\tif infoPath == \"\" {\n\t\tgo conn.ws.HandleIncomingEvents(conn.in)\n\t\tgo conn.ws.Keepalive(10 * time.Second)\n\t\tgo conn.consumeEvents()\n\t}\n\n\treturn conn, nil\n}", "func setFsUser(usr *sysuser) {\n\terr := syscall.Setfsuid(usr.uid)\n\thandleErr(err)\n\n\terr = syscall.Setfsgid(usr.gid)\n\thandleErr(err)\n\n\terr = syscall.Setfsgid(usr.gid)\n\thandleErr(err)\n}", "func StartServer(config ServerConfig) {\n\tgo control.Run(config.ControlBindAddr)\n\tgo data.Run(config.DataBindAddr)\n\tgo user.Run(config.UserBindAddr, config.CertFile, config.KeyFile, config.ClientCaFile, config.ClientAuth)\n\n\t// Wait for ever\n\tselect {}\n}", "func AttachUserCmd(host *HostCmd) {\n\tvar user = &UserCmd{\n\t\tCommand: &cobra.Command{\n\t\t\tUse: \"user\",\n\t\t\tShort: \"Configure user access to Inertia Web\",\n\t\t\tLong: `Configure user access to the Inertia Web application.`,\n\t\t},\n\t\thost: host,\n\t}\n\n\t// attach children\n\tuser.attachLoginCmd()\n\tAttachTotpCmd(user)\n\tuser.attachAddCmd()\n\tuser.attachRemoveCmd()\n\tuser.attachListCmd()\n\tuser.attachResetCmd()\n\n\t// attach to parent\n\thost.AddCommand(user.Command)\n}", "func (c *Config) AddServerSSHUser(serverKey string, username string, identityFile string, allowUsers *[]string) (string, *SSHUser) {\n\tsshUser := &SSHUser{\n\t\tSSHUsername: username,\n\t\tIdentityFile: identityFile,\n\t\tAllowUsers: allowUsers,\n\t}\n\n\tserver := (*c.Servers)[serverKey]\n\tif server == nil {\n\t\treturn \"\", nil\n\t}\n\n\tif server.SSHUsers == nil {\n\t\tsshUsers := make(map[string]*SSHUser)\n\t\tserver.SSHUsers = &sshUsers\n\t}\n\n\tserverSSHUserAmount := len(*server.SSHUsers) + 1\n\tlog.Printf(\"Add server ssh user, server ssh user amount: %d\", serverSSHUserAmount)\n\tkey := fmt.Sprintf(\"%s%d\", \"sshUser\", serverSSHUserAmount)\n\n\t(*server.SSHUsers)[key] = sshUser\n\treturn key, sshUser\n}", "func open(u string) (backend.Backend, error) {\n\turl, err := url.Parse(u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif url.Scheme == \"\" {\n\t\treturn backend.OpenLocal(url.Path)\n\t}\n\n\targs := []string{url.Host}\n\tif url.User != nil && url.User.Username() != \"\" {\n\t\targs = append(args, \"-l\")\n\t\targs = append(args, url.User.Username())\n\t}\n\targs = append(args, \"-s\")\n\targs = append(args, \"sftp\")\n\treturn backend.OpenSFTP(url.Path[1:], \"ssh\", args...)\n}", "func (u *User) Files(opts ...Option) <-chan *File {\n\treturn filesChannel(\n\t\tu.client, u.id(\"/users/%d/files\"),\n\t\tConcurrentErrorHandler, opts, nil,\n\t)\n}", "func FileSyscallConn(f *os.File,) (syscall.RawConn, error)", "func (userdata *User) ReceiveFile(filename string, sender string,\r\n\taccessToken uuid.UUID) error {\r\n\tvar invitation ShareInvitation\r\n\tpublic_key, valid := userlib.KeystoreGet(sender)\r\n\r\n\tif !valid {\r\n\t\treturn errors.New(\"invalid user\")\r\n\t}\r\n\r\n\tmarshal_invitation, exists := userlib.DatastoreGet(accessToken)\r\n\tif !exists {\r\n\t\treturn errors.New(\"file not found\")\r\n\t}\r\n\terror := json.Unmarshal(marshal_invitation, &invitation)\r\n\tif error != nil {\r\n\t\treturn errors.New(\"error with unmarshal\")\r\n\t}\r\n\r\n\terror = userlib.DSVerify(public_key, invitation.Access_Key, invitation.Signature)\r\n\taccess_token, error := userlib.PKEDec(userdata.RSA_Secret_Key, invitation.Access_Key)\r\n\t// fmt.Print(\"Access Token #2: \")\r\n\t// fmt.Println(access_token)\r\n\tkey := access_token[:16]\r\n\thmac := access_token[16:]\r\n\t// fmt.Print(\"Received HMAC Key: \")\r\n\t// fmt.Println(hmac)\r\n\r\n\tuserdata.Files[filename] = FileStorage{invitation.File_Location, key, hmac}\r\n\tmarshaled_user, _ := json.Marshal(userdata)\r\n\tmarshaled_user = Pad(marshaled_user, 16)\r\n\tencrypted_user := userlib.SymEnc(userdata.Personal_Key, userlib.RandomBytes(16), marshaled_user)\r\n\tuser_hmac, _ := userlib.HMACEval(userdata.HMAC_Key, encrypted_user)\r\n\tciphertext := append(encrypted_user, user_hmac...)\r\n\tuserlib.DatastoreSet(userdata.UUID, ciphertext)\r\n\treturn error\r\n}", "func (userdata *User) AppendFile(filename string, data []byte) (err error) {\n\t//case where the file is in the user's stored files\n\tif fileKeys, ok := userdata.Files[filename]; ok {\n\t\t//encrypt the file block and add onto the datastore\n\t\t//encrypt the file first\n\t\t//need datastore key, HMAC, and encryption key\n\t\t//encryption key\n\n\t\tsalt := userlib.Hash([]byte(userdata.Username + userdata.Password + filename))\n\t\tencryptionKey := userlib.Argon2Key([]byte(userdata.Password), salt[:16], uint32(userlib.AESKeySize))\n\t\tIV := userlib.RandomBytes(userlib.AESKeySize)\n\n\t\tdata = padFile(data)\n\t\tencryptedFile := userlib.SymEnc(encryptionKey, IV, data)\n\n\t\t//HMAC\n\t\tsalt2 := userlib.Hash([]byte(filename + userdata.Password + userdata.Username))\n\t\tHashKey :=userlib.Argon2Key([]byte(userdata.Password), salt2[:16], uint32(userlib.AESKeySize))\n\t\tfileHMAC, _ := userlib.HMACEval(HashKey, encryptedFile)\n\n\t\t//datastore key\n\t\tdsKey := userlib.RandomBytes(userlib.AESKeySize)\n\t\tdsKey_UUID,_ := uuid.FromBytes(dsKey)\n\n\t\t//store the file in the datastore\n\t\t//datastore key -> (HMAC, encryptedFile plaintext)\n\t\toutput := Stored{fileHMAC, encryptedFile}\n\t\tmarshalFile, _ := json.Marshal(output)\n\t\tuserlib.DatastoreSet(dsKey_UUID, marshalFile)\n\n\t\t//get the file struct UUID\n\t\tfile_header_UUID := fileKeys.FileStruct\n\t\t//get the decryption key for the file struct\n\t\t//eKey := fileKeys.EKey; doesn't seem to be useful since encryptionKey (calculated above) should = eKey\n\t\t//get the hmac of the file struct\n\t\thmacKey := fileKeys.HMACKey\n\n\t\t//get the encrypted store struct from the datastore, decrypt it, and check if the hmac is good\n\t\tstoredBytes, _ := userlib.DatastoreGet(file_header_UUID)\n\t\tvar checkStored Stored\n\t\t_ = json.Unmarshal(storedBytes, &checkStored)\n\t\thmac,_ := userlib.HMACEval(hmacKey, checkStored.EncryptedM)\n\t\tif !userlib.HMACEqual(hmac, checkStored.HMAC) {\n\t\t\treturn errors.New(\"The file struct storing the map of file data locations has been tampered with\")\n\t\t}\n\n\t\t//hmac is good, so continue with getting the file struct\n\t\tcipherFilestruct := checkStored.EncryptedM\n\t\tmarshFilestruct := userlib.SymDec(encryptionKey, cipherFilestruct)\n\t\tmarshFilestruct = dePad(marshFilestruct)\n\n\t\tvar header File\n\t\t//unmarshal the data structure\n\t\tjson.Unmarshal(marshFilestruct, &header)\n\n\t\theader.Files = append(header.Files, dsKey_UUID)\n\n\t\t//encrypt the File Struct again\n\t\tmarshalFileStruct, _ := json.Marshal(header)\n\t\tmarshalFileStruct = padFile(marshalFileStruct)\n\t\tencryptedFileStruct := userlib.SymEnc(encryptionKey, IV, marshalFileStruct)\n\n\t\tfileStructHMAC, _ := userlib.HMACEval(HashKey, encryptedFileStruct)\n\n\t\toutput = Stored{fileStructHMAC, encryptedFileStruct}\n\t\tstoredFileStruct, _ := json.Marshal(output)\n\t\tuserlib.DatastoreSet(file_header_UUID, storedFileStruct)\n\n\t\tptr := userdata.Files[filename]\n\t\tptr.HMACKey = HashKey\n\n\t\tptr2 := userdata\n\t\tptr2.Files[filename] = ptr\n\n\t\t//case where file is in user's received files (user has been shared the file from someone else)\n\t} else if _, ok2 := userdata.ReceivedFiles[filename]; ok2 {\n\t\t//case where user still has access to the file\n\t\tif userdata.stillShared(filename) {\n\t\t\t//get location of sharing record and decrypt it (stillShared already checks if properly encrypted, abstracted away to that function)\n\t\t\t//first get user's accessstruct values to find and properly decrypt the sharing record\n\t\t\taccessRec := userdata.ReceivedFiles[filename]\n\t\t\tshareKey := accessRec.Key\n\t\t\tshareLoc := accessRec.Recordlocation\n\t\t\tshareHmac := accessRec.RecordHMAC\n\t\t\t//now get the sharing record, verify if it hasn't been tampered with through hmac verification, then decrypt if proper\n\t\t\tcheckShare, _ := userlib.DatastoreGet(shareLoc)\n\t\t\tvar checkStore Stored\n\t\t\t_ = json.Unmarshal(checkShare, &checkStore)\n\n\t\t\t//if the the sharing record has been tampered with, going to have to delete malicious sharing record and return error\n\t\t\tif !userlib.HMACEqual(shareHmac, checkStore.HMAC) {\n\t\t\t\tuserlib.DatastoreDelete(shareLoc)\n\t\t\t\tdelete(userdata.ReceivedFiles, filename)\n\t\t\t\treturn errors.New(\"sharing record has been tampered with, so user doesn't have access to the file anymore\")\n\n\t\t\t\t//else proceed as normal, and decrypt the proper sharing record, append new file data with same keys/hmac sharing record has\n\t\t\t} else {\n\t\t\t\tcipherShare := checkStore.EncryptedM\n\t\t\t\tmarshShare := userlib.SymDec(shareKey, cipherShare)\n\t\t\t\tmarshShare = dePad(marshShare)\n\t\t\t\tvar shareRec SharingRecord\n\t\t\t\t_ = json.Unmarshal(marshShare, &shareRec)\n\n\t\t\t\t//check if the fileStruct that the sharing record points to hasn't been tampered with, else return error\n\t\t\t\tmarshStore, _ := userlib.DatastoreGet(shareRec.Datalocation)\n\t\t\t\tvar checkStore Stored\n\t\t\t\t_ = json.Unmarshal(marshStore, &checkStore)\n\t\t\t\tshareHMAC,_ := userlib.HMACEval(shareRec.HmacKey, checkStore.EncryptedM)\n\n\t\t\t\t//fileStruct has been tampered with, delete sharing record on datastore and access record in userdata, create new file struct/file w !ok2 and !ok3 case\n\t\t\t\tif !userlib.HMACEqual(shareHMAC, checkStore.HMAC) {\n\t\t\t\t\tuserlib.DatastoreDelete(shareLoc)\n\t\t\t\t\tdelete(userdata.ReceivedFiles, filename)\n\t\t\t\t\treturn errors.New(\"file struct has been tampered with, so user no longer has access to the file struct\")\n\n\t\t\t\t\t//else proceed as normal, proper sharing record and proper file struct, so create a file, store it with hmac in sharing record and\n\t\t\t\t\t//encrypted with key in sharing record, then update file struct by deleting old data and updating with new\n\t\t\t\t} else {\n\t\t\t\t\t//encrypt the file first\n\t\t\t\t\t//need datastore key, HMAC, and encryption key\n\t\t\t\t\t//encryption key = key in shareRec = owner's encryption key for files/file struct\n\t\t\t\t\tencryptionKey := shareRec.Ekey\n\t\t\t\t\tIV := userlib.RandomBytes(userlib.AESKeySize)\n\t\t\t\t\t//pad data file before using symEnc!!!\n\t\t\t\t\tdata = padFile(data)\n\n\t\t\t\t\t//encrypted file data, properly padded\n\t\t\t\t\tencryptedFile := userlib.SymEnc(encryptionKey, IV, data)\n\n\t\t\t\t\t//use shareRec hmac key to calculate file hmac\n\t\t\t\t\tfileHMAC, _ := userlib.HMACEval(shareRec.HmacKey, encryptedFile)\n\t\t\t\t\tdsKey := userlib.RandomBytes(userlib.AESKeySize)\n\t\t\t\t\tdsKey_UUID,_ := uuid.FromBytes(dsKey)\n\n\t\t\t\t\t//store the file in the datastore\n\t\t\t\t\t//datastore key -> (HMAC, encryptedFile plaintext)\n\t\t\t\t\toutput := Stored{fileHMAC, encryptedFile}\n\t\t\t\t\tmarshalFile, _ := json.Marshal(output)\n\t\t\t\t\tuserlib.DatastoreSet(dsKey_UUID, marshalFile)\n\n\t\t\t\t\t//append new data's uuid to the end of the file map\n\t\t\t\t\t//check error!\n\n\t\t\t\t\tfileStructuuid := shareRec.Datalocation\n\t\t\t\t\tmarshFile := userlib.SymDec(shareRec.Ekey, checkStore.EncryptedM)\n\t\t\t\t\tmarshFile = dePad(marshFile)\n\n\t\t\t\t\tvar sharedFile File\n\t\t\t\t\t_ = json.Unmarshal(marshFile, &sharedFile)\n\t\t\t\t\tsharedFile.Files = append(sharedFile.Files, dsKey_UUID)\n\n\t\t\t\t\t//reencrypt file struct and store in datastore\n\t\t\t\t\t//encrypt the File struct with the same keys used to encrypt the file plaintext\n\t\t\t\t\tmarshalFileStruct, _ := json.Marshal(sharedFile)\n\n\t\t\t\t\t//pad marshalled file struct prior to encryption\n\t\t\t\t\tmarshalFileStruct = padFile(marshalFileStruct)\n\n\t\t\t\t\t//encrypt filestruct + compute HMAC + datastore key for file struct\n\t\t\t\t\tencryptedFileStruct := userlib.SymEnc(encryptionKey, IV, marshalFileStruct)\n\t\t\t\t\tfileStructHMAC,_ := userlib.HMACEval(shareRec.HmacKey, encryptedFileStruct)\n\n\t\t\t\t\toutput = Stored{fileStructHMAC, encryptedFileStruct}\n\t\t\t\t\tstoredFileStruct, _ := json.Marshal(output)\n\t\t\t\t\tuserlib.DatastoreSet(fileStructuuid, storedFileStruct)\n\t\t\t\t\t//now the updated file struct has been reencrypted / restored from where it came\n\t\t\t\t}\n\t\t\t}\n\t\t\t//case where user's access to the file has been revoked\n\t\t} else {\n\t\t\t//built in function that deletes the record of access to a revoked file\n\t\t\tdelete(userdata.ReceivedFiles, filename)\n\t\t\treturn errors.New(\"user no longer has access to this file\")\n\t\t}\n\t\t//case where the user does not have the file\n\t} else {\n\t\treturn errors.New(\"file does not exist for this user\")\n\t}\n\treturn nil\n}", "func DoServer(\n\tversion string,\n\tkeyFile string,\n\taddr string,\n\ttimeout time.Duration,\n\ttaskingDir string,\n\toutputDir string,\n) {\n\t/* Get the server hostkey */\n\tkey, err := getHostKey(keyFile)\n\tif nil != err {\n\t\tlog.Fatalf(\"Error reading key from %s: %v\", keyFile, err)\n\t}\n\n\t/* Make the server config */\n\tconf := &ssh.ServerConfig{\n\t\tKeyboardInteractiveCallback: func(\n\t\t\tconn ssh.ConnMetadata,\n\t\t\tclient ssh.KeyboardInteractiveChallenge,\n\t\t) (*ssh.Permissions, error) {\n\t\t\treturn handleClientAuth(\n\t\t\t\tconn,\n\t\t\t\tclient,\n\t\t\t\ttaskingDir,\n\t\t\t\toutputDir,\n\t\t\t)\n\t\t},\n\t\tServerVersion: version,\n\t}\n\tconf.AddHostKey(key)\n\n\t/* Listen for clients */\n\tl, err := net.Listen(\"tcp\", addr)\n\tif nil != err {\n\t\tlog.Fatalf(\"Unable to listen for clients on %v: %v\", addr, err)\n\t}\n\tlog.Printf(\n\t\t\"Listening for SSH clients on %v with fingerprint %v\",\n\t\tl.Addr(),\n\t\tssh.FingerprintSHA256(key.PublicKey()),\n\t)\n\n\t/* Handle clients */\n\tfor {\n\t\t/* Get a client */\n\t\tc, err := l.Accept()\n\t\tif nil != err {\n\t\t\tlog.Fatalf(\"Error accepting new clients: %v\", err)\n\t\t\t/* TODO: Check for too many clients */\n\t\t}\n\t\t/* Upgrade to SSH and wait for tasking to finish */\n\t\tgo handleClientConn(c, conf, timeout)\n\t}\n}", "func (n *node) addFileServer(path string) {\n\tcomponents := strings.Split(path, \"/\")[1:]\n\tcount := len(components)\n\n\tfor {\n\t\taNode, component := n.traverse(components, nil)\n\t\tif aNode.component == component && count == 1 { // update an existing node.\n\t\t\taNode.isFileServer = true\n\t\t\treturn\n\t\t}\n\t\tnewNode := node{component: component, isNamedParam: false}\n\t\tif count == 1 { // this is the last component of the url resource, so it gets the handler.\n\t\t\tnewNode.isFileServer = true\n\t\t}\n\t\taNode.children = append(aNode.children, &newNode)\n\t\tcount--\n\t\tif count == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (pf PwdFile) Save(baseDir, user string) error {\n\treturn util.JsonMarshal(ClientPwdFile(baseDir, user), &pf)\n}", "func ftpServer(args []string) {\n\tcommander.CheckArgs(args, 1, \"ftpServer <port>\")\n\tlistener, err := net.Listen(\"tcp\", \":\"+args[0])\n\tgobro.CheckErr(err)\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tgobro.CheckErr(err)\n\t\tgo handleFtpConn(conn)\n\t}\n}", "func initializeAuthFile(path string) {\n\tif path == \"\" {\n\t\treturn\n\t}\n\n\tfileBts, err := os.ReadFile(filepath.Clean(path))\n\tif err != nil {\n\t\tlog.Fatalf(\"could not read %s: %v\", path, err)\n\t}\n\n\thdir, err := homedir.Dir()\n\tif err != nil {\n\t\tlog.Fatalf(\"could not get homedir: %v\", err)\n\t}\n\n\tfileName := transformAuthFileName(filepath.Base(path))\n\trcp := filepath.Join(hdir, fileName)\n\tif err := os.WriteFile(rcp, fileBts, 0o600); err != nil {\n\t\tlog.Fatalf(\"could not write to file: %v\", err)\n\t}\n}", "func (userdata *User) ShareFile(filename string, recipient string) (\n\tmagic_string string, err error) {\n\t//initialize the \"sender string\" for sharing record\n\tsender := userdata.Username\n\trecipPublic, exists := userlib.KeystoreGet(recipient + \"PK\")\n\tif exists != true {\n\t\treturn \"\", errors.New(\"recipient does not exist\")\n\t}\n\tvar recordUuid userlib.UUID\n\tstillShared := userdata.stillShared(filename)\n\t//encryption key for sharing record, to share to recipient through accesstruct\n\tvar eKey []byte\n\tvar User_HMAC []byte\n\t//if the user has stored the file themself:\n\t//pull the user's fileKeys for specific filename\n\tif fileKeys, ok := userdata.Files[filename]; ok {\n\t\t//pull the user's filestruct encryption key from file's fileKeys struct\n\t\tplainkey := fileKeys.EKey\n\n\t\t//get data location from fileKeys\n\t\tfilelocation := fileKeys.FileStruct\n\n\t\t//get hmac from fileKeys\n\t\thmacKey := fileKeys.HMACKey\n\n\t\t//create and populate the sharing record with its arguments\n\t\tvar record SharingRecord\n\t\trecord.Datalocation = filelocation\n\t\trecord.Ekey = plainkey\n\t\trecord.Sender = sender\n\t\tsalt2 := userlib.Hash([]byte(filename + userdata.Password + userdata.Username))\n\t\tHashKey := userlib.Argon2Key([]byte(userdata.Password), salt2[:16], uint32(userlib.AESKeySize))\n\t\trecord.HmacKey = HashKey\n\t\trecord.Hmac = hmacKey\n\n\t\t//checks if file is tampered with before sharing\n\t\tvar storedFileStruct Stored\n\t\tstoredfileCheck, _ := userlib.DatastoreGet(filelocation)\n\t\tjson.Unmarshal(storedfileCheck, storedFileStruct)\n\t\tHmacStored, _ := userlib.HMACEval(HashKey, storedFileStruct.EncryptedM)\n\t\tif userlib.HMACEqual(HmacStored, storedFileStruct.HMAC) {\n\t\t\treturn \"\", errors.New(\"file has been tampered with\")\n\n\t\t}\n\n\t\t//symmetrically encrypt sharingRecord with randomly generated key\n\t\t//first marshal then pad record struct\n\t\tmarshRecord, _ := json.Marshal(record)\n\t\tmarshRecord = padFile(marshRecord)\n\t\t//generate IV\n\t\tIV := userlib.RandomBytes(userlib.AESKeySize)\n\t\t//generate key for Symmetric encryption\n\t\tsalt := userlib.Hash([]byte(userdata.Password + userdata.Username))\n\t\tencryptionKey := userlib.Argon2Key([]byte(userdata.Password), salt[:16], uint32(userlib.AESKeySize))\n\t\t//encrypt the user struct\n\t\tencryptedMessage := userlib.SymEnc(encryptionKey, IV, marshRecord)\n\t\t//Get the HMAC key\n\t\thashKey := userlib.Argon2Key([]byte(userdata.Password), salt[16:], uint32(userlib.AESKeySize))\n\t\tUser_HMAC, _ = userlib.HMACEval(hashKey, []byte(encryptedMessage))\n\n\t\tstoredRecord := Stored{User_HMAC, encryptedMessage}\n\t\tmarshStoredrecord, _ := json.Marshal(storedRecord)\n\n\t\t//store signed/marshalled/encrypted sharing record in the datastore at a random uuid\n\t\trecordUuid = uuid.New()\n\t\tuserlib.DatastoreSet(recordUuid, marshStoredrecord)\n\n\t\tuserdata.RecordKeys[filename + recipient] = encryptionKey\n\n\t\teKey = encryptionKey\n\n\t\t//else if the user has received the file from someone else and user still has access to the file they received\n\t} else if senderAccess, ok := userdata.ReceivedFiles[filename]; ok && stillShared {\n\t\t//share the same sharing record sender uses with the recipient (when sender access gets revoked, so does recipient's)\n\t\trecordUuid = senderAccess.Recordlocation\n\t\teKey = senderAccess.Key\n\t\tUser_HMAC = senderAccess.RecordHMAC\n\t\t//if sender doesn't have access to the file, this should be untested behavior\n\t} else if ok {\n\t\t//delete the accessStruct for sender's file because senders access to the file is gone, no point in having an access struct for it\n\t\tdelete(userdata.ReceivedFiles, filename)\n\t\tstillShared = false\n\t\treturn \"\", errors.New(\"the sender no longer has the file in question\")\n\t} else {\n\t\treturn \"\", errors.New(\"the sender does not have the file in question\")\n\t}\n\n\t//set pointer to the new sharing record in the user's userdata\n\tuserdata.SharedFiles[filename + recipient] = recordUuid\n\n\t//create accessRecord with necessary info to point to sharingRecord, properly encrypt/format as a magic_string, then return this magic_string\n\tvar access AccessRecord\n\taccess.Key = eKey\n\taccess.Recordlocation = recordUuid\n\taccess.RecordHMAC = User_HMAC\n\tmarshAccess, _ := json.Marshal(access)\n\n\tcipherAccess, _ := userlib.PKEEnc(recipPublic, marshAccess[:len(marshAccess)/2])\n\tcipherAccess2, _ := userlib.PKEEnc(recipPublic, marshAccess[len(marshAccess)/2:])\n\n\n\taccessSig, _ := userlib.DSSign(userdata.DS, marshAccess)\n\tsignedAccess := Signed{accessSig, cipherAccess, cipherAccess2}\n\n\tmarshSignedaccess, _ := json.Marshal(signedAccess)\n\n\tmagic_string = hex.EncodeToString(marshSignedaccess)\n\n\treturn magic_string, nil\n}", "func (u HostUser) Setup() {\n\t//u.socket.Join(u.username) //not necessary socket ID namespace\n\tu.socket.Join(fmt.Sprintf(\"%d\", u.Sess.SessionId()))\n\tgo u.sendHandler()\n\tu.receiveHandler()\n}", "func setFilePermissions(path string, user, group, mode string) error {\n\tvar err error\n\tuid, gid := os.Getuid(), os.Getgid()\n\n\tif user != \"\" {\n\t\tif uid, err = strconv.Atoi(user); err == nil {\n\t\t\tgoto GROUP\n\t\t}\n\n\t\t// Try looking up the user by name\n\t\tu, err := osuser.Lookup(user)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to look up user %s: %v\", user, err)\n\t\t}\n\t\tuid, _ = strconv.Atoi(u.Uid)\n\t}\n\nGROUP:\n\tif group != \"\" {\n\t\tif gid, err = strconv.Atoi(group); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid group specified: %v\", group)\n\t\t}\n\t}\n\tif err := os.Chown(path, uid, gid); err != nil {\n\t\treturn fmt.Errorf(\"failed setting ownership to %d:%d on %q: %s\",\n\t\t\tuid, gid, path, err)\n\t}\n\n\tif mode != \"\" {\n\t\tmode, err := strconv.ParseUint(mode, 8, 32)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid mode specified: %v\", mode)\n\t\t}\n\t\tif err := os.Chmod(path, os.FileMode(mode)); err != nil {\n\t\t\treturn fmt.Errorf(\"failed setting permissions to %d on %q: %s\",\n\t\t\t\tmode, path, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func setupUser(config *initConfig) error {\n\t// Set up defaults.\n\tdefaultExecUser := user.ExecUser{\n\t\tUid: syscall.Getuid(),\n\t\tGid: syscall.Getgid(),\n\t\tHome: \"/\",\n\t}\n\tpasswdPath, err := user.GetPasswdPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgroupPath, err := user.GetGroupPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\texecUser, err := user.GetExecUserPath(config.User, &defaultExecUser, passwdPath, groupPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar addGroups []int\n\tif len(config.Config.AdditionalGroups) > 0 {\n\t\taddGroups, err = user.GetAdditionalGroupsPath(config.Config.AdditionalGroups, groupPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// before we change to the container's user make sure that the processes STDIO\n\t// is correctly owned by the user that we are switching to.\n\tif err := fixStdioPermissions(execUser); err != nil {\n\t\treturn err\n\t}\n\tsuppGroups := append(execUser.Sgids, addGroups...)\n\tif err := syscall.Setgroups(suppGroups); err != nil {\n\t\treturn err\n\t}\n\n\tif err := system.Setgid(execUser.Gid); err != nil {\n\t\treturn err\n\t}\n\tif err := system.Setuid(execUser.Uid); err != nil {\n\t\treturn err\n\t}\n\t// if we didn't get HOME already, set it based on the user's HOME\n\tif envHome := os.Getenv(\"HOME\"); envHome == \"\" {\n\t\tif err := os.Setenv(\"HOME\", execUser.Home); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (userdata *User) ShareFile(filename string, recipient string) (\r\n\taccessToken uuid.UUID, err error) {\r\n\tvar shareInvite ShareInvite\r\n\tvar fileKeyMeta FileKeyMeta\r\n\t//IMPLEMENT SHAREDUSERS AND USERTOKENS in FILEKEYSTRUCT\r\n\r\n\t//check is file exists in users file space\r\n\tupdatedUser, err := GetLatestUser(userdata.UUID_, userdata.PasswordHash, userdata.HMACKey, userdata.EncKey)\r\n\tif err != nil {\r\n\t\treturn uuid.Nil, errors.New(\"Failed to retrieve latest user info.\")\r\n\t}\r\n\r\n\tvar fk FileKey\r\n\tfileKey, fileFound := updatedUser.Filespace[filename]\r\n\r\n\tif !fileFound {\r\n\t\treturn uuid.Nil, errors.New(\"File does not exist in caller's personal filespace.\")\r\n\t}\r\n\r\n\t//what if this person is sharing a shared file? check access token!\r\n\t_, own := updatedUser.FilesOwned[filename]\r\n\tif !own { //this is just in case a revocation has happened and the fileKey data has changed\r\n\t\tat := userdata.AccessTokens[filename]\r\n\t\tfk, err = updatedUser.RetrieveAccessToken(at)\r\n\t\tif err != nil {\r\n\t\t\treturn uuid.Nil, errors.New(\"Failed to retrieve access token.\")\r\n\t\t}\r\n\t} else { //just in case fileKey data has changed from a recent session\r\n\t\tcurrFileKey, _ := userlib.DatastoreGet(fileKey.KeyId)\r\n\t\tlen_data := len(currFileKey) - userlib.HashSizeBytes\r\n\r\n\t\tif len_data < 0 || len_data > len(currFileKey) || len(currFileKey[:len_data]) < userlib.HashSizeBytes {\r\n\t\t\t//automatically return error, file has been changed\r\n\t\t\treturn uuid.Nil, errors.New(\"FileKey data length has changed.\")\r\n\t\t}\r\n\t\t//verify integrity of both fileKey struct and the file itself\r\n\t\tcomputedMac, _ := userlib.HMACEval(fileKey.HMAC_key, currFileKey[:len_data])\r\n\t\tif !userlib.HMACEqual(computedMac, currFileKey[len_data:]) {\r\n\t\t\treturn uuid.Nil, errors.New(\"File key struct has been tampered with in Datastore.\")\r\n\t\t}\r\n\t\t//decrypt + depad fileKey from DS to current fileKey var (overwrite)\r\n\t\tdecrypt := userlib.SymDec(fileKey.Enc_key, currFileKey[:len_data])\r\n\t\tdecrypt = PKCS(decrypt, \"remove\")\r\n\r\n\t\terr = json.Unmarshal(decrypt, &fk)\r\n\t\tif err != nil {\r\n\t\t\treturn uuid.Nil, errors.New(\"Error demarshaling.\")\r\n\t\t}\r\n\t}\r\n\r\n\t//check if recipient exists\r\n\tpubKey, userFound := userlib.KeystoreGet(recipient + \"public_key\")\r\n\tif !userFound {\r\n\t\treturn uuid.Nil, errors.New(\"Recepient not found.\")\r\n\t}\r\n\r\n\t//populate Shareinvite and FileKeyMeta struct\r\n\tfileKeyMeta.DSid = fk.KeyId\r\n\tfileKeyMeta.HMACkey = fk.HMAC_key\r\n\tfileKeyMeta.ENCkey = fk.Enc_key\r\n\r\n\tfkm_json, _ := json.Marshal(fileKeyMeta)\r\n\t//encrypt FileKeyMeta using RSA\r\n\tfileKeyMeta_enc, _ := userlib.PKEEnc(pubKey, fkm_json) //dont need to pad?\r\n\r\n\t//Marshal the fileKeyMeta info\r\n\tshareInvite.RSAFileKey = fileKeyMeta_enc\r\n\t//msg for signature is the RSA encrypted, MARSHALED FileMetaKey struct\r\n\tshareInvite.Signature, _ = userlib.DSSign(userdata.PrivSignKey, shareInvite.RSAFileKey)\r\n\tshareInvite.Sender = updatedUser.Username\r\n\tshareInvite_json, _ := json.Marshal(shareInvite)\r\n\r\n\taccessToken = uuid.New() //generate random accessToken\r\n\tuserlib.DatastoreSet(accessToken, shareInvite_json)\r\n\r\n\t//update SharedUsers and UserTokens fields in fileKey\r\n\t//if they are a DIRECT sharer (meaning theyre one level below owner) generate key\r\n\t//and put recipient in their list\r\n\t//else, put them under the direct sharer from their lineage\r\n\tfk.UserTokens[recipient] = accessToken //update user tokens for possible revoking later\r\n\tlist, direct_user := fk.SharedUsers[updatedUser.Username] //should return true if user is a key\r\n\tif own {\r\n\t\tvar emptyList []string\r\n\t\tfk.SharedUsers[recipient] = emptyList\r\n\t} else if direct_user {\r\n\t\tlist = append(list, recipient) //add recipient to direct sharer's list\r\n\t\tfk.SharedUsers[recipient] = list\r\n\t} else { //indirect user case, iterate over map of shared users\r\n\t\tvar originalSharer string\r\n\t\t//provides each key and respective value\r\n\t\tfor directSharer, listShared := range fk.SharedUsers {\r\n\t\t\tfor _, indirectSharer := range listShared {\r\n\t\t\t\tif updatedUser.Username == indirectSharer {\r\n\t\t\t\t\toriginalSharer = directSharer\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif originalSharer != \"\" {\r\n\t\t\t\tbreak //break out of second for loop if you've found the original sharer\r\n\t\t\t}\r\n\t\t}\r\n\t\tif originalSharer == \"\" {\r\n\t\t\treturn uuid.Nil, errors.New(\"User is not owner but could not find who shared file with them.\")\r\n\t\t}\r\n\t\tlist = append(list, recipient)\r\n\t\tfk.SharedUsers[originalSharer] = list //add the recipient of this indirect user to list\r\n\t}\r\n\t//Now lets send the updated fileKey to the Datastore\r\n\tfileKey_json, _ := json.Marshal(fk)\r\n\tfk_IV := userlib.RandomBytes(userlib.AESBlockSizeBytes)\r\n\tfileKey_enc := userlib.SymEnc(fk.Enc_key, fk_IV, PKCS(fileKey_json, \"add\"))\r\n\t//Add HMACs for both file key and file elem struct (runtime corresponds to size of appended file, nothing else)\r\n\tfk_hmac, _ := userlib.HMACEval(fk.HMAC_key, fileKey_enc)\r\n\tfileKey_enc = append(fileKey_enc, fk_hmac...)\r\n\tuserlib.DatastoreSet(fileKey.KeyId, fileKey_enc)\r\n\r\n\treturn accessToken, nil\r\n}", "func AddUserPath() string {\n\treturn \"/users\"\n}", "func FileServer(r chi.Router, path string, root http.FileSystem) {\n\tif strings.ContainsAny(path, \"{}*\") {\n\t\tpanic(\"FileServer does not permit URL parameters.\")\n\t}\n\tfs := http.StripPrefix(path, http.FileServer(root))\n\n\tif path != \"/\" && path[len(path)-1] != '/' {\n\t\tr.Get(path, http.RedirectHandler(path+\"/\", http.StatusMovedPermanently).ServeHTTP)\n\t\tpath += \"/\"\n\t}\n\tpath += \"*\"\n\n\tr.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfs.ServeHTTP(w, r)\n\t}))\n}", "func FileServer(r chi.Router, path string, root http.FileSystem) {\n\n\tif strings.ContainsAny(path, \"{}*\") {\n\t\tpanic(\"FileServer does not permit URL parameters.\")\n\t}\n\n\tfs := http.FileServer(root)\n\n\tif path != \"/\" && path[len(path)-1] != '/' {\n\t\tr.Get(path, http.RedirectHandler(path+\"/\", 301).ServeHTTP)\n\t\tpath += \"/\"\n\t}\n\tpath += \"*\"\n\n\tr.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfs.ServeHTTP(w, r)\n\t}))\n}", "func CreateDefaultUserConfigFile(keyPath string) error {\n\tuser, err := GetDefaultSSHUser()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif user == \"\" {\n\t\treturn nil\n\t}\n\n\terr = MakeDotSSH()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := os.Stat(shared.ExpandPathWithTilde(\"~/.ssh/config\")); os.IsNotExist(err) {\n\t\tf, err := os.OpenFile(shared.ExpandPathWithTilde(\"~/.ssh/config\"), os.O_RDONLY|os.O_CREATE, 0644)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to touch ~/.ssh/config: %v\", err)\n\t\t}\n\t\tf.Close()\n\t}\n\n\t// This config file sets a default ssh user and a default ssh key. This ensures that kssh's signed key will be used.\n\tconfig := fmt.Sprintf(\"# kssh config file to set a default SSH user\\n\"+\n\t\t\"Include config\\n\"+\n\t\t\"Host *\\n\"+\n\t\t\" User %s\\n\"+\n\t\t\" IdentityFile %s\\n\"+\n\t\t\" IdentitiesOnly yes\\n\", user, keyPath)\n\n\tf, err := os.OpenFile(AlternateSSHConfigFile, os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\t_, err = f.WriteString(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Test2(t *testing.T) {\n alice,_ := InitUser(\"alice\",\"fubar\")\n // Having previously created a user \"alice\" with password \"fubar\"...\n alice, _ = GetUser(\"alice\", \"fubar\")\n also_alice, _ := GetUser(\"alice\", \"fubar\")\n\n alice.StoreFile(\"todo\", []byte(\"write tests\"))\n todo, _ := also_alice.LoadFile(\"todo\")\n if string(todo) != \"write tests\" {\n t.Error(\"Same user and password could not access file: \", todo)\n }\n}", "func InitUsers() error {\n file, err := os.OpenFile(UsersFile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, os.ModePerm)\n if err != nil {\n return err\n }\n defer file.Close()\n\n writer := csv.NewWriter(file)\n headers := []string{\"username\", \"passwordHash\", \"FirstName\", \"LastName\"}\n if err := writer.Write(headers); err != nil {\n return fmt.Errorf(\"error setting user csv headers: %s\", err)\n }\n writer.Flush()\n\n return nil\n}", "func (userdata *User) StoreFile(filename string, data []byte) {\n\n\tvar Mapping UserFile\n\tvar File FileData\n\tvar Data FileBlock\n\n\t//////////////////////////////////////////////\n\t//////////// UserFile Record /////////////////\n\t//////////////////////////////////////////////\n\n\t// get address and Encryption Key for UserFile\n\tAddr,E := UserFileCredentials(userdata.Username,userdata.Password,filename)\t\n\n\tflag := false //Will be true if a valid file with this name already exists\n\n\t//Checking if this file already exists and getting Index and Key for FileData if it exists\n\tciphertext,valid := userlib.DatastoreGet(Addr)\n\n\n\tif(valid){\n\t\tflag=true\n\t\tuserlib.DebugMsg(\"Stored at %v is %v\",Addr,ciphertext)\n\n\t\t//Decrypting UserFileData\n\t\tplaintext,err10 := decryptAES(ciphertext, E)\n\t\tif(err10!=nil) {\n\t\t\tflag = false\n\t\t} else {\n\n\t\terr := json.Unmarshal(plaintext,&Mapping)\n\n\t\tif(err!=nil){\n\t\t\tflag=false\n\t\t\tuserlib.DebugMsg(\"Error in unmarshalling already available\")\n\t\t} else{\n\n\t\t\t//Verifying HMAC\n\t\t\tvar temp UserFile\n\t\t\ttemp.Location=Mapping.Location\n\t\t\ttemp.Key=Mapping.Key\n\n\t\t\tstr,_ := json.Marshal(temp)\n\n\t\t\thmac := userlib.NewHMAC(E)\n\t\t\thmac.Write([]byte(str))\n\t\t\ttemp.Hmac=hmac.Sum(nil)\n\n\t\t\tif !userlib.Equal(temp.Hmac, Mapping.Hmac) {\n\t\t\t\tuserlib.DebugMsg(\"%v\",errors.New(strings.ToTitle(\"UserFile record corrupted by server.\")))\n\t\t\t\tflag=false\t\n\t\t\t}\n\n\t\t}\n\t}\n}\n\n\n\n\t\t///////////////////////////////////////////////\n\t\t/////////////// FileData Record ///////////////\n\t\t///////////////////////////////////////////////\n\n\t\tvar Addr1 string\n\t\tvar E1 []rune\n\t\tif(!flag){\n\n\t\t\t//Generate Address for FileData\n\t\t\tAddr1 = getAddress(userlib.RandomBytes(256))\t\n\t\t\t\n\t\t\t//Generate Key for Encrypting and generating HMAC for FileData record\n\t\t\tE1 =[]rune(string(userlib.Argon2Key([]byte(string([]rune(userdata.Password+filename))),userlib.RandomBytes(16),16)))\n\t\t\tuserlib.DebugMsg(\"User %v File %v stored at Addr1=%v E1=%v\",userdata.Username,filename,Addr1,E1)\n\t\n\n\t\t\t//Populating UserFile structure \n\t\t\tMapping.Location=Addr1\n\t\t\tMapping.Key=E1\n\n\t\t\t//Calculating HMAC and updating UserFile structure\n\t\t\tstr1,_ := json.Marshal(Mapping)\n\t\t\thmac1 := userlib.NewHMAC(E)\n\t\t\thmac1.Write([]byte(str1))\n\t\t\tMapping.Hmac=hmac1.Sum(nil)\t\n\n\t\t\t//Marshalling UserFile structure\n\t\t\tstr1,_ = json.Marshal(Mapping)\n\n\n\t\t\t//Encrypting UserFile structure with E\n\t\t\tciphertext1 := encryptAES( []byte(str1), E) \n\n\t\t\t// Storing encrypted UserFile structure at Addr\n\t\t\tuserlib.DebugMsg(\"Stored at %v is %v\",Addr,ciphertext1)\n\t\t\tuserlib.DatastoreSet(Addr,ciphertext1)\n\t\t} else\n\t\t{\n\t\t\t//Getting Addr1 and E1 from existing UserFile structure(Overwriting existing file)\n\t\t\tE1=Mapping.Key\n\t\t\tAddr1=Mapping.Location\n\t\t\tuserlib.DebugMsg(\"User %v File %v stored at Addr1=%v E1=%v\",userdata.Username,filename,Addr1,E1)\n\t\t}\n\n\t\t//Generating Addr2- address for the first block of this file\n\t\tAddr2 := getAddress(userlib.RandomBytes(256))\n\n\n\t\t//Generating E2- Key to encrypt and generate HMAC for the first block of this file\n\t\tE2 :=[]rune(string(userlib.Argon2Key(userlib.RandomBytes(256),userlib.RandomBytes(256),16)))\n\t\tuserlib.DebugMsg(\"User %v File %v stored at Addr2=%v E2=%v\",userdata.Username,filename,Addr2,E2)\n\n\t\t//Populating FileData structure\n\t\tFile.Keys=nil\n\t\tFile.Keys=append(File.Keys,E2)\n\t\tFile.Blocks=nil\n\t\tFile.Blocks=append(File.Blocks, Addr2)\n\n\t\t//Calculating HMAC and updating FileData structure\n\t\tstr2,_ := json.Marshal(File)\n\t\thmac2 := userlib.NewHMAC([]byte(string(E1)))\n\t\thmac2.Write([]byte(str2))\n\t\tFile.Hmac=hmac2.Sum(nil)\n\n\t\t//Marshalling FileData structure\n\t\tstr2,_ = json.Marshal(File)\n\n\t\t//Encrypting FileData structure with E1\n\t\tciphertext2 := encryptAES([]byte(str2),[]byte(string(E1))[:16]) \n\n\t\t// Storing encrypted FileData structure at Addr1\n\t\tuserlib.DatastoreSet(Addr1,ciphertext2)\n\t\tuserlib.DebugMsg(\"Stored at %v, Value=%v\",Addr1,ciphertext2)\n\n\t\t///////////////////////////////////////////////\n\t\t////////////// FileBlock Record ///////////////\n\t\t///////////////////////////////////////////////\n\n\t\tData.Data=[]rune(string(data))\n\n\t\t//Calculating HMAC and updating FileBlock structure\n\t\tstr3,_ := json.Marshal(Data)\n\t\thmac3 := userlib.NewHMAC([]byte(string(E2)))\n\t\thmac3.Write([]byte(str3))\n\t\tData.Hmac=hmac3.Sum(nil)\t\n\n\t\t//Marshalling FileBlock structure\n\t\tstr3,_ = json.Marshal(Data)\n\n\t\t//Encrypting FileBlock structure with E2\n\t\tciphertext3 := encryptAES([]byte(str3),[]byte(string(E2))[:16]) \n\n\t\t// Storing encrypted FileBlock structure at Addr2\n\t\tuserlib.DatastoreSet(Addr2,ciphertext3)\n\t\tuserlib.DebugMsg(\"Stored at %v, Value=%v\",Addr2,ciphertext3)\n\n}", "func send_file_dup_request(n *net_node.Node, from_server int32, to_server int32, filename string) {\n\t// Open a TCP connection\n\tremote_addr := net_node.ConvertToAddr(n.Table[from_server].Address)\n\tremote_tcp_addr := net_node.ConvertUDPToTCP(*remote_addr)\n\tconn, err := net.DialTCP(\"tcp\", nil, remote_tcp_addr)\n\tnet_node.CheckError(err)\n\tdefer conn.Close()\n\n\t// Now, send over the file metadata\n\tto_server_str := fmt.Sprintf(\"%32d\", to_server)\n\tfilename_str := fmt.Sprintf(\"%100s\", filename)\n\tfirst_line := []byte(\"DR\" + to_server_str + filename_str)\n\tconn.Write(first_line)\n}", "func create(u string) (backend.Backend, error) {\n\turl, err := url.Parse(u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif url.Scheme == \"\" {\n\t\treturn backend.CreateLocal(url.Path)\n\t}\n\n\targs := []string{url.Host}\n\tif url.User != nil && url.User.Username() != \"\" {\n\t\targs = append(args, \"-l\")\n\t\targs = append(args, url.User.Username())\n\t}\n\targs = append(args, \"-s\")\n\targs = append(args, \"sftp\")\n\treturn backend.CreateSFTP(url.Path[1:], \"ssh\", args...)\n}", "func (s *Server) LaunchServer() error {\n\t//ok if this fails - we're just clearing out the sock if it still exists.\n\t_ = unix.Unlink(s.SockAddr.Name)\n\n\tfd, err := unix.Socket(unix.AF_LOCAL, unix.SOCK_STREAM|unix.SOCK_NONBLOCK, 0)\n\n\tif err != nil {\n\t\tfmt.Println(\"main failed to initialize socket\")\n\t\treturn err\n\t}\n\n\tif err = unix.Bind(fd, s.SockAddr); err != nil {\n\t\treturn err\n\t}\n\n\t//ensure user-only rwx perms\n\tif err = unix.Chmod(s.SockAddr.Name, unix.S_IRWXU); err != nil {\n\t\tgoto errOut\n\t}\n\n\t//Tell the OS we're ready to listen on the socket.\n\tif err = unix.Listen(fd, 10); err != nil {\n\t\tfmt.Println(\"failed connecting: \", err.Error())\n\t\tgoto errOut\n\t}\n\n\t{\n\t\tvar flg int\n\n\t\t//Possibly-unnecessary checks for ensuring file descriptor state\n\t\tif flg, err = unix.FcntlInt(uintptr(fd), unix.F_GETFL, 0); err != nil {\n\t\t\tfmt.Println(\"FcntlInt: \", err.Error())\n\t\t\tgoto errOut\n\t\t}\n\n\t\tif flg&unix.SOCK_NONBLOCK == 0 {\n\t\t\tfmt.Println(\"checking for blocking socket - unblocked sock\")\n\t\t\tgoto errOut\n\t\t}\n\t}\n\n\t//fmt.Println(\"launching listenForConnections goroutine\")\n\tgo s.listenForConections(fd)\n\treturn nil\n\nerrOut:\n\tsyscall.Close(fd)\n\t_ = syscall.Unlink(s.SockAddr.Name)\n\treturn err\n}", "func (d *Doctor) RequestFile(user, fileName string) error {\n\tH := sha1.New()\n\ts := user + fileName\n\tH.Write([]byte(s))\n\th := H.Sum(nil)\n\tentryHash := hex.EncodeToString(h)\n\thmac, fr := SignMessage(d.secret, d.Q, entryHash, d.g.GetIdentifier())\n\tif hmac == \"\" || fr == nil {\n\t\treturn errors.New(\"Hmac fail\")\n\t}\n\tfileReq := &project.FileRequest{Fr: fr, Hmac: hmac}\n\tvar pkt GossipPacket\n\tpkt.Hippo = &project.HippoMsg{FileReq: fileReq}\n\td.g.BroadcastMessageAmong(pkt, d.cothorityAddr)\n\treturn nil\n}", "func (userdata *User) ReceiveFile(filename string, sender string,\r\n\taccessToken uuid.UUID) error {\r\n\t//IMPLEMENT AccessTokens field IN USER STRUCT\r\n\t//even if revoked ok to not error, but bob cant see new file updates\r\n\tupdatedUser, err := GetLatestUser(userdata.UUID_, userdata.PasswordHash, userdata.HMACKey, userdata.EncKey)\r\n\tif err != nil {\r\n\t\treturn errors.New(\"Failed to retrieve latest user info.\")\r\n\t}\r\n\t_, already_received := updatedUser.Filespace[filename]\r\n\r\n\tif already_received {\r\n\t\treturn errors.New(\"File already in user's file space.\")\r\n\t}\r\n\r\n\tsharedInviteDS, fileKeyFound := userlib.DatastoreGet(accessToken)\r\n\r\n\tif !fileKeyFound {\r\n\t\treturn errors.New(\"Access token did not find a shared file.\")\r\n\t}\r\n\r\n\tvar sharedInvite ShareInvite\r\n\terr = json.Unmarshal(sharedInviteDS, &sharedInvite)\r\n\r\n\tif err != nil {\r\n\t\treturn errors.New(\"Error unmarshaling shared file key.\")\r\n\t}\r\n\r\n\t//now verify that sharedInvite has not been tampered with\r\n\tvar senderKey userlib.PKEEncKey\r\n\tif sharedInvite.Sender == sender {\r\n\t\tsenderKey, _ = userlib.KeystoreGet(sender + \"ds\")\r\n\t} else { //owner has updated ShareInvite\r\n\t\tsenderKey, _ = userlib.KeystoreGet(sharedInvite.Sender + \"ds\")\r\n\t}\r\n\t//should check out if owner changes invite too\r\n\terr = userlib.DSVerify(senderKey, sharedInvite.RSAFileKey, sharedInvite.Signature)\r\n\r\n\tif err != nil {\r\n\t\treturn errors.New(\"Failed to verify sender.\")\r\n\t}\r\n\r\n\t//now we can finally receive the fileKey after unmarshaling\r\n\t//trying to decrypt marshaled RSAFileKey\r\n\trsaFK_dec, err := userlib.PKEDec(userdata.PrivRSAKey, sharedInvite.RSAFileKey)\r\n\tif err != nil {\r\n\t\treturn errors.New(\"Failed to decrypt FileKeyMeta info.\")\r\n\t}\r\n\r\n\tvar rsaFK FileKeyMeta\r\n\terr = json.Unmarshal(rsaFK_dec, &rsaFK)\r\n\tif err != nil {\r\n\t\treturn errors.New(\"Error unmarshaling file key metadata.\")\r\n\t}\r\n\r\n\t//now lets retrieve the fileKey from the datastore and append that to our users filespace\r\n\tfileKey, fkFound := userlib.DatastoreGet(rsaFK.DSid)\r\n\r\n\tif !fkFound {\r\n\t\treturn errors.New(\"Could not find original file.\")\r\n\t}\r\n\r\n\t//authenticate HMAC, decrypt, depad, demarshal fileKey and add to users filespace\r\n\tlen_fk := len(fileKey) - userlib.HashSizeBytes\r\n\tif len(fileKey[:len_fk]) < userlib.HashSizeBytes {\r\n\t\t//automatically return error, file has been changed\r\n\t\treturn errors.New(\"File key data length has changed.\")\r\n\t}\r\n\r\n\tcomputedMac, _ := userlib.HMACEval(rsaFK.HMACkey, fileKey[:len_fk])\r\n\tif !userlib.HMACEqual(computedMac, fileKey[len_fk:]) {\r\n\t\t//should error if access revoked!\r\n\t\treturn errors.New(\"File key struct has been tampered with in Datastore.\")\r\n\t}\r\n\t//decrypt\r\n\tfileKey_dec := userlib.SymDec(rsaFK.ENCkey, fileKey[:len_fk])\r\n\tfileKey_dec = PKCS(fileKey_dec, \"remove\")\r\n\tvar finalFK FileKey\r\n\terr = json.Unmarshal(fileKey_dec, &finalFK)\r\n\r\n\tif err != nil {\r\n\t\treturn errors.New(\"Error unmarshaling actual file key.\")\r\n\t}\r\n\t//generate a new fileKey for user! user can name file whatever they want\r\n\r\n\t//marshal, pad, encrypt, add HMAC and send userdata to DS\r\n\tuserdata.Filespace[filename] = finalFK\r\n\tuserdata.AccessTokens[filename] = accessToken\r\n\tuser_json, _ := json.Marshal(userdata)\r\n\tuser_IV := userlib.RandomBytes(userlib.AESBlockSizeBytes)\r\n\tuser_enc := userlib.SymEnc(userdata.EncKey, user_IV, PKCS(user_json, \"add\"))\r\n\r\n\tuser_mac, _ := userlib.HMACEval(userdata.HMACKey, user_enc)\r\n\tuser_enc = append(user_enc, user_mac...)\r\n\tuserlib.DatastoreSet(userdata.UUID_, user_enc)\r\n\r\n\treturn nil\r\n}", "func (Server) RemoteFile(gp *core.Goploy) *core.Response {\n\tid, err := strconv.ParseInt(gp.URLQuery.Get(\"id\"), 10, 64)\n\tif err != nil {\n\t\treturn &core.Response{Code: core.Error, Message: \"invalid server id\"}\n\t}\n\n\tfilename := gp.URLQuery.Get(\"file\")\n\tserver, err := (model.Server{ID: id}).GetData()\n\tif err != nil {\n\t\treturn &core.Response{Code: core.Error, Message: err.Error()}\n\t}\n\tclient, err := utils.DialSSH(server.Owner, server.Password, server.Path, server.IP, server.Port)\n\tif err != nil {\n\t\treturn &core.Response{Code: core.Error, Message: err.Error()}\n\t}\n\t//defer client.Close()\n\tsftpClient, err := sftp.NewClient(client)\n\tif err != nil {\n\t\treturn &core.Response{Code: core.Error, Message: err.Error()}\n\t}\n\tsrcFile, _ := sftpClient.Open(filename) //远程\n\tFileStat, _ := srcFile.Stat()\n\tFileSize := strconv.FormatInt(FileStat.Size(), 10)\n\tgp.ResponseWriter.Header().Set(\"Content-Disposition\", \"attachment; filename=\"+path.Base(filename))\n\tgp.ResponseWriter.Header().Set(\"Content-Type\", \"application/octet-stream\")\n\tgp.ResponseWriter.Header().Set(\"Content-Length\", FileSize)\n\t_, _ = io.Copy(gp.ResponseWriter, srcFile)\n\t_ = srcFile.Close()\n\t_ = sftpClient.Close()\n\treturn nil\n}", "func userPeers() string {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn filepath.Join(usr.HomeDir, \".\"+dirname, filename)\n}", "func setFilePermissions(path string, p FilePermissions) error {\n\tvar err error\n\tuid, gid := os.Getuid(), os.Getgid()\n\n\tif p.User() != \"\" {\n\t\tif uid, err = strconv.Atoi(p.User()); err == nil {\n\t\t\tgoto GROUP\n\t\t}\n\n\t\t// Try looking up the user by name\n\t\tif u, err := user.Lookup(p.User()); err == nil {\n\t\t\tuid, _ = strconv.Atoi(u.Uid)\n\t\t\tgoto GROUP\n\t\t}\n\n\t\treturn fmt.Errorf(\"invalid user specified: %v\", p.User())\n\t}\n\nGROUP:\n\tif p.Group() != \"\" {\n\t\tif gid, err = strconv.Atoi(p.Group()); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid group specified: %v\", p.Group())\n\t\t}\n\t}\n\tif err := os.Chown(path, uid, gid); err != nil {\n\t\treturn fmt.Errorf(\"failed setting ownership to %d:%d on %q: %s\",\n\t\t\tuid, gid, path, err)\n\t}\n\n\tif p.Mode() != \"\" {\n\t\tmode, err := strconv.ParseUint(p.Mode(), 8, 32)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid mode specified: %v\", p.Mode())\n\t\t}\n\t\tif err := os.Chmod(path, os.FileMode(mode)); err != nil {\n\t\t\treturn fmt.Errorf(\"failed setting permissions to %d on %q: %s\",\n\t\t\t\tmode, path, err)\n\t\t}\n\t}\n\n\treturn nil\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 SendFile(n *net_node.Node, connection net.Conn) {\n\t// Get the server_index\n\tserver_index_buff := make([]byte, 32)\n\tconnection.Read(server_index_buff)\n\tserver_index_str := strings.Trim(string(server_index_buff), \" \")\n\ti, _ := strconv.ParseInt(server_index_str, 10, 32)\n\tserver_index := int32(i)\n\n\t// Get the local file path\n\tfile_path_buff := make([]byte, 100)\n\tconnection.Read(file_path_buff)\n\tlocal_filepath := strings.Trim(string(file_path_buff), \" \")\n\n\t// Now, get the file name\n\tfile_name_buff := make([]byte, 100)\n\tconnection.Read(file_name_buff)\n\tfilename := strings.Trim(string(file_name_buff), \" \")\n\n\t// Determine if the file we are putting actually exists\n\tf, err := os.Stat(local_filepath)\n\tif os.IsNotExist(err) {\n\t\tfmt.Println(local_filepath, \"does not exist, cant send this file\")\n\t\treturn\n\t}\n\tfile_size := f.Size()\n\n\tSend_file_tcp(n, server_index, local_filepath, filename, file_size, \"\", false)\n}", "func handleClientAuth(\n\tconn ssh.ConnMetadata,\n\tclient ssh.KeyboardInteractiveChallenge,\n\ttaskingDir string,\n\toutputDir string,\n) (*ssh.Permissions, error) {\n\t/* Username will be the filename for the tasking. It should only have\n\tallowed characters. */\n\tfn := conn.User()\n\tif \"\" != strings.Trim(fn, IDOK) {\n\t\treturn nil, fmt.Errorf(\"invalid id %q\", fn)\n\t}\n\n\t/* Make sure the output file exists */\n\tf, err := openOutputFile(outputDir, fn)\n\tif nil != f {\n\t\tf.Close()\n\t}\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\t/* Update the last seen time on the file */\n\tnow := time.Now()\n\tif err := os.Chtimes(\n\t\tfilepath.Join(outputDir, fn),\n\t\tnow,\n\t\tnow,\n\t); nil != err {\n\t\tlog.Printf(\"[%v] Unable to update file times: %v\", fn, err)\n\t}\n\n\t/* See if we have tasking */\n\tp := filepath.Join(taskingDir, fn)\n\ttlock.Lock()\n\tt, rerr := ioutil.ReadFile(p)\n\tuerr := os.Remove(p)\n\ttlock.Unlock()\n\tif nil != rerr {\n\t\tif os.IsNotExist(rerr) {\n\t\t\treturn nil, ErrWorked\n\t\t}\n\t\treturn nil, rerr\n\t}\n\tif 0 == len(t) { /* Empty file */\n\t\treturn nil, ErrWorked\n\t}\n\tif nil != uerr {\n\t\tlog.Printf(\"Unable to remove tasking file %v: %v\", p, uerr)\n\t}\n\n\t/* Send tasking and get response */\n\tas, err := client(fn, \"\", []string{string(t)}, []bool{true})\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tif 0 == len(as) {\n\t\treturn nil, fmt.Errorf(\"got no output from ID %s\", fn)\n\t}\n\tif 1 != len(as) {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"got %v outputs (expecting 1) from ID %v\",\n\t\t\tlen(as),\n\t\t\tfn,\n\t\t)\n\t}\n\n\t/* Write the output to a file */\n\tof, err := openOutputFile(outputDir, fn)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tdefer of.Close()\n\tn, err := io.WriteString(of, as[0])\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\n\t\t\"[%v] Sent %v bytes of tasking and got %v bytes of output\",\n\t\tfn,\n\t\tlen(t),\n\t\tn,\n\t)\n\n\treturn nil, ErrWorked\n}", "func (s *Server) setupSockets(remoteID string) {\n log.Infof(\"server: dialing client socket\")\n out, err := net.DialUnix(\n udsType,\n nil,\n &net.UnixAddr{path.Join(os.TempDir(), remoteID), udsType},\n )\n if err != nil {\n log.Infof(\"problem dialing client's socket: %s\", err)\n return\n }\n\n if err := out.SetWriteBuffer(5 * MiB); err != nil {\n log.Errorf(\"cannot set the Unix Domain Socket buffer to 5 MiB\")\n return\n }\n\n log.Infof(\"server: preparing to listen on new socket\")\n uid := uuid.New()\n p := path.Join(os.TempDir(), uid)\n in, err := net.ListenUnixgram(udsType, &net.UnixAddr{p, udsType})\n if err != nil {\n out.Close()\n log.Infof(\"could not listen on domain socket %q: %s\", p, err)\n return\n }\n\n log.Infof(\"server: sending a uid to the client\")\n if err := SetupEncode(uid, out); err != nil {\n out.Close()\n log.Infof(\"problem encoding UUIDv4 for setup: %s\", err)\n return\n }\n\n go s.serveConn(in, out)\n}", "func FileServer(r chi.Router, path string, root http.FileSystem) {\n\tif strings.ContainsAny(path, \"{}*\") {\n\t\tpanic(\"FileServer does not permit URL parameters.\")\n\t}\n\n\tfs := http.StripPrefix(path, http.FileServer(root))\n\n\tif path != \"/\" && path[len(path)-1] != '/' {\n\t\tr.Get(path, http.RedirectHandler(path+\"/\", 301).ServeHTTP)\n\t\tpath += \"/\"\n\t}\n\tpath += \"*\"\n\n\tr.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfs.ServeHTTP(w, r)\n\t}))\n}", "func FileServer(r chi.Router, path string, root http.FileSystem) {\n\tif strings.ContainsAny(path, \"{}*\") {\n\t\tpanic(\"FileServer does not permit URL parameters.\")\n\t}\n\n\tfs := http.StripPrefix(path, http.FileServer(root))\n\n\tif path != \"/\" && path[len(path)-1] != '/' {\n\t\tr.Get(path, http.RedirectHandler(path+\"/\", 301).ServeHTTP)\n\t\tpath += \"/\"\n\t}\n\tpath += \"*\"\n\n\tr.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfs.ServeHTTP(w, r)\n\t}))\n}", "func FileServer(directory string, opts ...DirOptions) context.Handler {\n\tif directory == \"\" {\n\t\tpanic(\"FileServer: directory is empty. The directory parameter should point to a physical system directory or to an embedded one\")\n\t}\n\n\toptions := getDirOptions(opts...)\n\n\t// `embeddedFileSystem` (if AssetInfo, Asset and AssetNames are defined) or `http.Dir`.\n\tvar fs http.FileSystem = http.Dir(directory)\n\n\tif options.Asset != nil && options.AssetInfo != nil && options.AssetNames != nil {\n\t\t// Depends on the command the user gave to the go-bindata\n\t\t// the assset path (names) may be or may not be prepended with a slash.\n\t\t// What we do: we remove the ./ from the vdir which should be\n\t\t// the same with the asset path (names).\n\t\t// we don't pathclean, because that will prepend a slash\n\t\t//\t\t\t\t\t go-bindata should give a correct path format.\n\t\t// On serve time we check the \"paramName\" (which is the path after the \"requestPath\")\n\t\t// so it has the first directory part missing, we use the \"vdir\" to complete it\n\t\t// and match with the asset path (names).\n\t\tvdir := directory\n\n\t\tif vdir[0] == '.' {\n\t\t\tvdir = vdir[1:]\n\t\t}\n\n\t\t// second check for /something, (or ./something if we had dot on 0 it will be removed)\n\t\tif vdir[0] == '/' || vdir[0] == os.PathSeparator {\n\t\t\tvdir = vdir[1:]\n\t\t}\n\n\t\t// check for trailing slashes because new users may be do that by mistake\n\t\t// although all examples are showing the correct way but you never know\n\t\t// i.e \"./assets/\" is not correct, if was inside \"./assets\".\n\t\t// remove last \"/\".\n\t\tif trailingSlashIdx := len(vdir) - 1; vdir[trailingSlashIdx] == '/' {\n\t\t\tvdir = vdir[0:trailingSlashIdx]\n\t\t}\n\n\t\t// select only the paths that we care;\n\t\t// that have prefix of the directory and\n\t\t// skip any unnecessary the end-dev or the 3rd party tool may set.\n\t\tvar names []string\n\t\tfor _, name := range options.AssetNames() {\n\t\t\t// i.e: name = static/css/main.css (including the directory, see `embeddedFileSystem.vdir`)\n\n\t\t\tif !strings.HasPrefix(name, vdir) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tnames = append(names, strings.TrimPrefix(name, vdir))\n\t\t}\n\n\t\tif len(names) == 0 {\n\t\t\tpanic(\"FileServer: zero embedded files\")\n\t\t}\n\n\t\tasset := func(name string) ([]byte, error) {\n\t\t\treturn options.Asset(vdir + name)\n\t\t}\n\n\t\tassetInfo := func(name string) (os.FileInfo, error) {\n\t\t\treturn options.AssetInfo(vdir + name)\n\t\t}\n\n\t\tdirNames := make(map[string]*embeddedDir)\n\n\t\t// sort filenames by smaller path.\n\t\tsort.Slice(names, func(i, j int) bool {\n\t\t\treturn strings.Count(names[j], \"/\") > strings.Count(names[i], \"/\")\n\t\t})\n\n\t\tfor _, name := range names {\n\t\t\tdirName := path.Dir(name)\n\t\t\td, ok := dirNames[dirName]\n\n\t\t\tif !ok {\n\t\t\t\td = &embeddedDir{\n\t\t\t\t\tname: dirName,\n\t\t\t\t\tmodTimeUnix: time.Now().Unix(),\n\t\t\t\t}\n\t\t\t\tdirNames[dirName] = d\n\t\t\t}\n\n\t\t\tinfo, err := assetInfo(name)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"FileServer: report as bug: file info: %s not found in: %s\", name, dirName))\n\t\t\t}\n\t\t\td.list = append(d.list, &embeddedBaseFileInfo{path.Base(name), info})\n\t\t}\n\n\t\tfs = &embeddedFileSystem{\n\t\t\tvdir: vdir,\n\t\t\tdirNames: dirNames,\n\n\t\t\tasset: asset,\n\t\t\tassetInfo: assetInfo,\n\t\t}\n\t}\n\t// Let it for now.\n\t// else if !DirectoryExists(directory) {\n\t// \tpanic(\"FileServer: system directory: \" + directory + \" does not exist\")\n\t// }\n\n\tplainStatusCode := func(ctx context.Context, statusCode int) {\n\t\tif writer, ok := ctx.ResponseWriter().(*context.GzipResponseWriter); ok && writer != nil {\n\t\t\twriter.ResetBody()\n\t\t\twriter.Disable()\n\t\t}\n\t\tctx.StatusCode(statusCode)\n\t}\n\n\thtmlReplacer := strings.NewReplacer(\n\t\t\"&\", \"&amp;\",\n\t\t\"<\", \"&lt;\",\n\t\t\">\", \"&gt;\",\n\t\t// \"&#34;\" is shorter than \"&quot;\".\n\t\t`\"`, \"&#34;\",\n\t\t// \"&#39;\" is shorter than \"&apos;\" and apos was not in HTML until HTML5.\n\t\t\"'\", \"&#39;\",\n\t)\n\n\tdirList := options.DirList\n\tif dirList == nil {\n\t\tdirList = func(ctx context.Context, dirName string, dir http.File) error {\n\t\t\tdirs, err := dir.Readdir(-1)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// dst, _ := dir.Stat()\n\t\t\t// dirName := dst.Name()\n\n\t\t\tsort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() })\n\n\t\t\tctx.ContentType(context.ContentHTMLHeaderValue)\n\t\t\t_, err = ctx.WriteString(\"<pre>\\n\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, d := range dirs {\n\t\t\t\tname := d.Name()\n\t\t\t\tif d.IsDir() {\n\t\t\t\t\tname += \"/\"\n\t\t\t\t}\n\t\t\t\t// name may contain '?' or '#', which must be escaped to remain\n\t\t\t\t// part of the URL path, and not indicate the start of a query\n\t\t\t\t// string or fragment.\n\t\t\t\turl := url.URL{Path: joinPath(\"./\"+dirName, name)} // edit here to redirect correctly, standard library misses that.\n\t\t\t\t_, err = ctx.Writef(\"<a href=\\\"%s\\\">%s</a>\\n\", url.String(), htmlReplacer.Replace(name))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, err = ctx.WriteString(\"</pre>\\n\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\th := func(ctx context.Context) {\n\t\tname := prefix(ctx.Request().URL.Path, \"/\")\n\t\tctx.Request().URL.Path = name\n\n\t\tgzip := options.Gzip\n\t\tif !gzip {\n\t\t\t// if false then check if the dev did something like `ctx.Gzip(true)`.\n\t\t\t_, gzip = ctx.ResponseWriter().(*context.GzipResponseWriter)\n\t\t}\n\n\t\tf, err := fs.Open(name)\n\t\tif err != nil {\n\t\t\tplainStatusCode(ctx, http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\tdefer f.Close()\n\n\t\tinfo, err := f.Stat()\n\t\tif err != nil {\n\t\t\tplainStatusCode(ctx, http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\t// use contents of index.html for directory, if present\n\t\tif info.IsDir() && options.IndexName != \"\" {\n\t\t\t// Note that, in contrast of the default net/http mechanism;\n\t\t\t// here different handlers may serve the indexes\n\t\t\t// if manually then this will block will never fire,\n\t\t\t// if index handler are automatically registered by the framework\n\t\t\t// then this block will be fired on indexes because the static site routes are registered using the static route's handler.\n\t\t\t//\n\t\t\t// End-developers must have the chance to register different logic and middlewares\n\t\t\t// to an index file, useful on Single Page Applications.\n\n\t\t\tindex := strings.TrimSuffix(name, \"/\") + options.IndexName\n\t\t\tfIndex, err := fs.Open(index)\n\t\t\tif err == nil {\n\t\t\t\tdefer fIndex.Close()\n\t\t\t\tinfoIndex, err := fIndex.Stat()\n\t\t\t\tif err == nil {\n\t\t\t\t\tinfo = infoIndex\n\t\t\t\t\tf = fIndex\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Still a directory? (we didn't find an index.html file)\n\t\tif info.IsDir() {\n\t\t\tif !options.ShowList {\n\t\t\t\tplainStatusCode(ctx, http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif modified, err := ctx.CheckIfModifiedSince(info.ModTime()); !modified && err == nil {\n\t\t\t\tctx.WriteNotModified()\n\t\t\t\tctx.StatusCode(http.StatusNotModified)\n\t\t\t\tctx.Next()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx.SetLastModified(info.ModTime())\n\t\t\terr = dirList(ctx, info.Name(), f)\n\t\t\tif err != nil {\n\t\t\t\tplainStatusCode(ctx, http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tctx.Next()\n\t\t\treturn\n\t\t}\n\n\t\t// index requested, send a moved permanently status\n\t\t// and navigate back to the route without the index suffix.\n\t\tif strings.HasSuffix(name, options.IndexName) {\n\t\t\tlocalRedirect(ctx, \"./\")\n\t\t\treturn\n\t\t}\n\n\t\tif options.AssetValidator != nil {\n\t\t\tif !options.AssetValidator(ctx, info.Name()) {\n\t\t\t\terrCode := ctx.GetStatusCode()\n\t\t\t\tif ctx.ResponseWriter().Written() <= context.StatusCodeWritten {\n\t\t\t\t\t// if nothing written as body from the AssetValidator but 200 status code(which is the default),\n\t\t\t\t\t// then we assume that the end-developer just returned false expecting this to be not found.\n\t\t\t\t\tif errCode == http.StatusOK {\n\t\t\t\t\t\terrCode = http.StatusNotFound\n\t\t\t\t\t}\n\t\t\t\t\tplainStatusCode(ctx, errCode)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// try to find and send the correct content type based on the filename\n\t\t// and the binary data inside \"f\".\n\t\tdetectOrWriteContentType(ctx, info.Name(), f)\n\n\t\tif gzip {\n\t\t\t// set the last modified as \"serveContent\" does.\n\t\t\tctx.SetLastModified(info.ModTime())\n\n\t\t\t// write the file to the response writer.\n\t\t\tcontents, err := ioutil.ReadAll(f)\n\t\t\tif err != nil {\n\t\t\t\tctx.Application().Logger().Debugf(\"err reading file: %v\", err)\n\t\t\t\tplainStatusCode(ctx, http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Use `WriteNow` instead of `Write`\n\t\t\t// because we need to know the compressed written size before\n\t\t\t// the `FlushResponse`.\n\t\t\t_, err = ctx.GzipResponseWriter().Write(contents)\n\t\t\tif err != nil {\n\t\t\t\tctx.Application().Logger().Debugf(\"short write: %v\", err)\n\t\t\t\tplainStatusCode(ctx, http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\thttp.ServeContent(ctx.ResponseWriter(), ctx.Request(), info.Name(), info.ModTime(), f)\n\t\tif serveCode := ctx.GetStatusCode(); context.StatusCodeNotSuccessful(serveCode) {\n\t\t\tplainStatusCode(ctx, serveCode)\n\t\t\treturn\n\t\t}\n\n\t\tctx.Next() // fire any middleware, if any.\n\t}\n\n\treturn h\n}", "func fileServer(root string, bools []bool) http.Handler {\n\tf := &fileHandler{root: root}\n\tif len(bools) > 0 {\n\t\tf.dirList = bools[0]\n\t}\n\tif len(bools) > 1 {\n\t\tf.enc = bools[1]\n\t}\n\treturn f\n}", "func runClientToServerCopyAs(who, ttype string, conn *xsnet.Conn, fpath string, chaffing bool) (exitStatus uint32, err error) {\n\tu, _ := user.Lookup(who) // nolint: gosec\n\tvar uid, gid uint32\n\tfmt.Sscanf(u.Uid, \"%d\", &uid) // nolint: gosec,errcheck\n\tfmt.Sscanf(u.Gid, \"%d\", &gid) // nolint: gosec,errcheck\n\tlog.Println(\"uid:\", uid, \"gid:\", gid)\n\n\t// Need to clear server's env and set key vars of the\n\t// target user. This isn't perfect (TERM doesn't seem to\n\t// work 100%; ANSI/xterm colour isn't working even\n\t// if we set \"xterm\" or \"ansi\" here; and line count\n\t// reported by 'stty -a' defaults to 24 regardless\n\t// of client shell window used to run client.\n\t// Investigate -- rlm 2018-01-26)\n\tos.Clearenv()\n\tos.Setenv(\"HOME\", u.HomeDir) // nolint: gosec,errcheck\n\tos.Setenv(\"TERM\", ttype) // nolint: gosec,errcheck\n\tos.Setenv(\"XS_SESSION\", \"1\") // nolint: gosec,errcheck\n\n\tvar c *exec.Cmd\n\tcmdName := xs.GetTool(\"tar\")\n\n\tvar destDir string\n\tif path.IsAbs(fpath) {\n\t\tdestDir = fpath\n\t} else {\n\t\tdestDir = path.Join(u.HomeDir, fpath)\n\t}\n\n\tcmdArgs := []string{\"-xz\", \"-C\", destDir}\n\n\t// NOTE the lack of quotes around --xform option's sed expression.\n\t// When args are passed in exec() format, no quoting is required\n\t// (as this isn't input from a shell) (right? -rlm 20180823)\n\t//cmdArgs := []string{\"-x\", \"-C\", destDir, `--xform=s#.*/\\(.*\\)#\\1#`}\n\tfmt.Println(cmdName, cmdArgs)\n\tc = exec.Command(cmdName, cmdArgs...) // nolint: gosec\n\n\tc.Dir = destDir\n\n\t//If os.Clearenv() isn't called by server above these will be seen in the\n\t//client's session env.\n\t//c.Env = []string{\"HOME=\" + u.HomeDir, \"SUDO_GID=\", \"SUDO_UID=\", \"SUDO_USER=\", \"SUDO_COMMAND=\", \"MAIL=\", \"LOGNAME=\"+who}\n\t//c.Dir = u.HomeDir\n\tc.SysProcAttr = &syscall.SysProcAttr{}\n\tc.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}\n\tc.Stdin = conn\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\n\tif chaffing {\n\t\tconn.EnableChaff()\n\t}\n\tdefer conn.DisableChaff()\n\tdefer conn.ShutdownChaff()\n\n\t// Start the command (no pty)\n\tlog.Printf(\"[%v %v]\\n\", cmdName, cmdArgs)\n\terr = c.Start() // returns immediately\n\t/////////////\n\t// NOTE: There is, apparently, a bug in Go stdlib here. Start()\n\t// can actually return immediately, on a command which *does*\n\t// start but exits quickly, with c.Wait() error\n\t// \"c.Wait status: exec: not started\".\n\t// As in this example, attempting a client->server copy to\n\t// a nonexistent remote dir (it's tar exiting right away, exitStatus\n\t// 2, stderr\n\t// /bin/tar -xz -C /home/someuser/nosuchdir\n\t// stderr: fork/exec /bin/tar: no such file or directory\n\t//\n\t// In this case, c.Wait() won't give us the real\n\t// exit status (is it lost?).\n\t/////////////\n\tif err != nil {\n\t\tlog.Println(\"cmd exited immediately. Cannot get cmd.Wait().ExitStatus()\")\n\t\terr = errors.New(\"cmd exited prematurely\")\n\t\t//exitStatus = uint32(254)\n\t\texitStatus = xsnet.CSEExecFail\n\t} else {\n\t\tif err := c.Wait(); err != nil {\n\t\t\t//fmt.Println(\"*** c.Wait() done ***\")\n\t\t\tif exiterr, ok := err.(*exec.ExitError); ok {\n\t\t\t\t// The program has exited with an exit code != 0\n\n\t\t\t\t// This works on both Unix and Windows. Although package\n\t\t\t\t// syscall is generally platform dependent, WaitStatus is\n\t\t\t\t// defined for both Unix and Windows and in both cases has\n\t\t\t\t// an ExitStatus() method with the same signature.\n\t\t\t\tif status, ok := exiterr.Sys().(syscall.WaitStatus); ok {\n\t\t\t\t\texitStatus = uint32(status.ExitStatus())\n\t\t\t\t\t//err = errors.New(\"cmd returned nonzero status\")\n\t\t\t\t\tlog.Printf(\"Exit Status: %d\\n\", exitStatus)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlog.Println(\"*** client->server cp finished ***\")\n\t}\n\treturn\n}", "func (c *ServerConn) Login(user, password string) error {\n\tcode, message, err := c.cmd(-1, \"USER %s\", user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch code {\n\tcase StatusLoggedIn:\n\tcase StatusUserOK:\n\t\t_, _, err = c.cmd(StatusLoggedIn, \"PASS %s\", password)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn errors.New(message)\n\t}\n\n\tc.username = user\n\tc.password = password\n\n\t// Switch to binary mode\n\t_, _, err = c.cmd(StatusCommandOK, \"TYPE I\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// logged, check features again\n\tif err = c.Feat(); err != nil {\n\t\tc.Quit()\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (userdata *User) StoreFile(filename string, data []byte) (err error) {\r\n\r\n\t//TODO: This is a toy implementation.\r\n\tmeta_storage_location := uuid.New()\r\n\tencryption_key := userlib.Argon2Key([]byte(uuid.New().String()), userlib.RandomBytes(16), uint32(userlib.AESBlockSizeBytes))\r\n\thmac_key := userlib.Argon2Key([]byte(uuid.New().String()), userlib.RandomBytes(16), uint32(16))\r\n\r\n\towner_key, _ := userlib.KeystoreGet(userdata.Username)\r\n\tencrypted_owner, _ := userlib.PKEEnc(owner_key, []byte(userdata.Username))\r\n\r\n\tchanges := 0\r\n\tmeta_data := FileMetaData{changes, encrypted_owner}\r\n\r\n\tmarshaled_meta_data, _ := json.Marshal(meta_data)\r\n\r\n\tmeta_string := meta_storage_location.String()\r\n\tnew_file_name := meta_string + string(rune(changes))\r\n\tfile_storage_location, _ := uuid.FromBytes([]byte(new_file_name))\r\n\tnew_file := File{data}\r\n\r\n\tmarshaled_new_file, _ := json.Marshal(new_file)\r\n\r\n\tpadded_meta := Pad(marshaled_meta_data, 16)\r\n\tpadded_file := Pad(marshaled_new_file, 16)\r\n\r\n\tencrypted_meta := userlib.SymEnc(encryption_key, userlib.RandomBytes(16), padded_meta)\r\n\tencrypted_file := userlib.SymEnc(encryption_key, userlib.RandomBytes(16), padded_file)\r\n\r\n\tmeta_hmac_tag, _ := userlib.HMACEval(hmac_key, encrypted_meta)\r\n\tfile_hmac_tag, _ := userlib.HMACEval(hmac_key, encrypted_file)\r\n\t// fmt.Print(\"Meta HMAC: \")\r\n\t// fmt.Println(meta_hmac_tag)\r\n\t// fmt.Print(\"Store File HMAC Key: \")\r\n\t// fmt.Println(hmac_key)\r\n\r\n\tmac_meta := append(encrypted_meta, meta_hmac_tag...)\r\n\tmac_file := append(encrypted_file, file_hmac_tag...)\r\n\r\n\tuserlib.DatastoreSet(meta_storage_location, mac_meta)\r\n\tuserlib.DatastoreSet(file_storage_location, mac_file)\r\n\r\n\tuserdata.Files[filename] = FileStorage{meta_storage_location, encryption_key, hmac_key}\r\n\r\n\tmarshaled_user, _ := json.Marshal(userdata)\r\n\tpadded_user := Pad(marshaled_user, 16)\r\n\tuserdata_encrypted := userlib.SymEnc(userdata.Personal_Key, userlib.RandomBytes(16), padded_user)\r\n\tuser_hmac_tag, _ := userlib.HMACEval(userdata.HMAC_Key, userdata_encrypted)\r\n\r\n\tuser_ciphertext := append(userdata_encrypted, user_hmac_tag...)\r\n\tuserlib.DatastoreSet(userdata.UUID, user_ciphertext)\r\n\t// storageKey, _ := uuid.FromBytes([]byte(filename + userdata.Username)[:16])\r\n\t// jsonData, _ := json.Marshal(data)\r\n\t// userlib.DatastoreSet(storageKey, jsonData)\r\n\t//End of toy implementation\r\n\treturn\r\n}", "func (ghost *Ghost) StartDownloadServer() error {\n\tlog.Println(\"StartDownloadServer: started\")\n\n\tdefer func() {\n\t\tghost.quit = true\n\t\tghost.Conn.Close()\n\t\tlog.Println(\"StartDownloadServer: terminated\")\n\t}()\n\n\tfile, err := os.Open(ghost.fileOp.Filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tio.Copy(ghost.Conn, file)\n\treturn nil\n}", "func EstablishConnection(client *Client) error {\n\t// Error if server or user id is empty or non-alphanumeric.\n\tr, _ := regexp.Compile(\"^[0-9A-Za-z]+$\")\n\tmatched := r.MatchString(client.ServerID)\n\tif !matched {\n\t\treturn errors.New(\"establishing connection: server id invalid\")\n\t}\n\tmatched = r.MatchString(client.UserID)\n\tif !matched {\n\t\treturn errors.New(\"establishing connection: user id invalid\")\n\t}\n\n\t// Error if hostname is empty.\n\tif len(client.Server.Host) < 1 {\n\t\treturn errors.New(\"establishing connection: hostname too short\")\n\t}\n\n\t// Error if port is too low.\n\tif client.Server.Port == 0 {\n\t\treturn errors.New(\"establishing connection: port too low\")\n\t}\n\n\t// Error if nickname is empty.\n\tif len(client.User.Nick) < 1 {\n\t\treturn errors.New(\"establishing connection: nickname too short\")\n\t}\n\n\t// Attempt connection establishment. Use TLS if secure is specified. Timeout\n\t// after one minute.\n\tvar conn net.Conn\n\tvar err error\n\tif client.Server.Secure {\n\t\tconn, err = tls.DialWithDialer(&(net.Dialer{Timeout: time.Minute}), \"tcp\",\n\t\t\tfmt.Sprintf(\"%s:%d\", client.Server.Host, client.Server.Port), nil)\n\t} else {\n\t\tconn, err = net.DialTimeout(\"tcp\", fmt.Sprintf(\"%s:%d\",\n\t\t\tclient.Server.Host, client.Server.Port), time.Minute)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tLogf(client, \"Connected to server %s:%d (%s)\", client.Server.Host,\n\t\tclient.Server.Port, conn.RemoteAddr())\n\n\t// Update connection in client and start reading from server and pinging\n\t// periodically.\n\tclient.Conn = conn\n\tgo readLoop(client)\n\tgo pingLoop(client)\n\n\t// Send required user registration messages to server, including password if\n\t// specified.\n\tif len(client.Authentication.ServerPassword) > 0 {\n\t\tSendPass(client, client.Authentication.ServerPassword)\n\t}\n\tSendNick(client, client.User.Nick)\n\tSendUser(client, client.User.User, client.User.Real)\n\n\treturn nil\n}", "func NewFileUserProvider(configuration *schema.FileAuthenticationBackendConfiguration) *FileUserProvider {\n\tlogger := logging.Logger()\n\n\terrs := checkDatabase(configuration.Path)\n\tif errs != nil {\n\t\tfor _, err := range errs {\n\t\t\tlogger.Error(err)\n\t\t}\n\n\t\tos.Exit(1)\n\t}\n\n\tdatabase, err := readDatabase(configuration.Path)\n\tif err != nil {\n\t\t// Panic since the file does not exist when Authelia is starting.\n\t\tpanic(err)\n\t}\n\n\t// Early check whether hashed passwords are correct for all users\n\terr = checkPasswordHashes(database)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &FileUserProvider{\n\t\tconfiguration: configuration,\n\t\tdatabase: database,\n\t\tlock: &sync.Mutex{},\n\t}\n}", "func Execute() {\n\trootPath = \"D://MediaTest//\"\n\tsqlAddress = \"192.168.2.200\"\n\tsqlPort = 43306\n\tsqlPassword = \"my-secret-pw\"\n\n\tsrv := &webdav.Handler{\n\t\tFileSystem: DynamicFileSystem{webdav.Dir(rootPath)},\n\t\tLockSystem: webdav.NewMemLS(),\n\t\tLogger: func(r *http.Request, err error) {\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"WEBDAV [%s]: %s, ERROR: %s\\n\", r.Method, r.URL, err)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"WEBDAV [%s]: %s \\n\", r.Method, r.URL)\n\t\t\t}\n\t\t},\n\t}\n\n\tsqlServer, err := setupDatabase()\n\tif err != nil {\n\t\tlog.Printf(\"SQL-Database Error: %s\", err.Error())\n\t\treturn\n\t}\n\n\tif authEnabled {\n\t\tif authDigest {\n\t\t\t//Add the authentication \"Handler\" that checks the user credentials\n\t\t\tauthenticator := getDigestAuth(sqlServer)\n\n\t\t\t//Add the above created authentication handler as a pre-WebDAV-authentication-layer\n\t\t\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tif username, authinfo := authenticator.CheckAuth(r); username == \"\" {\n\t\t\t\t\tauthenticator.RequireAuth(w, r)\n\t\t\t\t} else {\n\t\t\t\t\trN := r.WithContext(context.WithValue(r.Context(), \"username\", username))\n\t\t\t\t\tar := auth.AuthenticatedRequest{Request: *rN, Username: username}\n\t\t\t\t\tar.Header.Set(auth.AuthUsernameHeader, ar.Username)\n\n\t\t\t\t\tif authinfo != nil {\n\t\t\t\t\t\tw.Header().Set(authenticator.Headers.V().AuthInfo, *authinfo)\n\t\t\t\t\t}\n\t\t\t\t\tsrv.ServeHTTP(w, &ar.Request)\n\t\t\t\t}\n\t\t\t})\n\t\t} else {\n\t\t\t//Add the authentication \"Handler\" that checks the user credentials\n\t\t\tauthenticator := getBasicAuth(sqlServer)\n\n\t\t\t//Add the above created authentication handler as a pre-WebDAV-authentication-layer\n\t\t\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tprintln(\"Request from:\", r.RemoteAddr)\n\t\t\t\tif username := authenticator.CheckAuth(r); username == \"\" {\n\t\t\t\t\tauthenticator.RequireAuth(w, r)\n\t\t\t\t} else {\n\t\t\t\t\trN := r.WithContext(context.WithValue(r.Context(), \"username\", username))\n\t\t\t\t\tar := &auth.AuthenticatedRequest{Request: *rN, Username: username}\n\t\t\t\t\tar.Header.Set(auth.AuthUsernameHeader, ar.Username)\n\n\t\t\t\t\tsrv.ServeHTTP(w, &ar.Request)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t} else {\n\t\thttp.HandleFunc(\"/\", srv.ServeHTTP)\n\t}\n\n\tif httpsEnabled {\n\t\t//Create the cert.pem and key.pem file paths for check and later use\n\t\tcertFile := fmt.Sprintf(\"%s/cert.pem\", certificatePath)\n\t\tkeyFile := fmt.Sprintf(\"%s/key.pem\", certificatePath)\n\n\t\t//Check if there is a valid cert and key file at the given path\n\t\tif _, err := os.Stat(certFile); err != nil {\n\t\t\tfmt.Println(\"[x] No cert.pem in the given directory. Please provide a valid cert\")\n\t\t\treturn\n\t\t}\n\t\tif _, er := os.Stat(keyFile); er != nil {\n\t\t\tfmt.Println(\"[x] No key.pem in the given directory. Please provide a valid cert\")\n\t\t\treturn\n\t\t}\n\n\t\t//Start webserver(s) with checked and valid cert and key file\n\t\tif httpEnabled {\n\t\t\tgo http.ListenAndServeTLS(fmt.Sprintf(\":%d\", httpsPort), certFile, keyFile, nil)\n\t\t} else if err := http.ListenAndServeTLS(fmt.Sprintf(\":%d\", httpsPort), certFile, keyFile, nil); err != nil {\n\t\t\tlog.Fatalf(\"Error with WebDAV server: %v\", err)\n\t\t}\n\t}\n\n\tif httpEnabled {\n\t\tif err := http.ListenAndServe(fmt.Sprintf(\":%d\", httpPort), nil); err != nil {\n\t\t\tlog.Fatalf(\"Error with WebDAV server: %v\", err)\n\t\t}\n\t}\n\n}", "func UnixLogin(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\tresult := login.FTPConnect(username, password)\n\tif result == \"\" {\n\t\tw.Write([]byte(\"Login successful!\"))\n\t}\n\tw.Write([]byte(\"Wrong username or password!\"))\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 (ac *activeClient) Upload(c *ishell.Context) {\n\tpath := strings.Join(c.Args, \" \")\n\tinfo, _ := os.Stat(path)\n\n\tc.ProgressBar().Indeterminate(true)\n\tc.ProgressBar().Start()\n\n\tcontent, err := os.ReadFile(path)\n\tif err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Upload failed could not read local file:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tf := shared.File{\n\t\tContent: content,\n\t\tPath: path,\n\t\tPerm: info.Mode(),\n\t}\n\n\tif err := ac.RPC.Call(\"API.RecvFile\", f, &void); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Upload failed:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tc.ProgressBar().Final(green(\"[Server] \") + green(\"[+] Upload Successful\"))\n\tc.ProgressBar().Final(yellow(\"[\"+ac.Data().Name+\"] \") + green(\"[+] Upload successfully received\"))\n\tc.ProgressBar().Stop()\n}", "func (client *Client) Start(username string) {\n\tfmt.Printf(\"[Client] Connecting to %v:%v\\n\", client.host, client.port)\n\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"%v:%v\", client.host, client.port))\n\n\tif err != nil {\n\t\tlog.Fatal(\"[Error] Failed to connect to server: \", err.Error())\n\t}\n\tclient.reader = bufio.NewReader(conn)\n\tclient.writer = bufio.NewWriter(conn)\n\n\tgo client.read()\n\tgo client.write()\n\n\tclient.Send(username)\n}", "func fileServer(r chi.Router, path string, root http.FileSystem) {\n\tif strings.ContainsAny(path, \"{}*\") {\n\t\tpanic(\"fileServer does not permit URL parameters.\")\n\t}\n\n\tfs := http.StripPrefix(path, http.FileServer(root))\n\n\tif path != \"/\" && path[len(path)-1] != '/' {\n\t\tr.Get(path, http.RedirectHandler(path+\"/\", 301).ServeHTTP)\n\t\tpath += \"/\"\n\t}\n\tpath += \"*\"\n\n\tr.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfs.ServeHTTP(w, r)\n\t}))\n}", "func (h *Handler) writeToClient(user uuid.UUID, cmd, data []byte) error {\n\tif c, ok := h.writeChannels[user]; ok {\n\t\tprep := append(cmd, ':', ' ')\n\t\tc <- append(prep, data...)\n\t\treturn nil\n\t}\n\treturn errors.New(\"client not found\")\n}", "func (r *Redis) AddUser(id, key string) (err error) {\n\terr = r.client.HMSet(id, \"timestamp\", strconv.FormatInt(time.Now().UTC().Unix(), 10), \"key\", key, \"files\", \"\").Err()\n\treturn\n}", "func (s *Server) AddUser(user *User) {\n\ts.mutex.Lock()\n\ts.users[user.username] = user\n\ts.mutex.Unlock()\n}", "func (this *File) Setattr(ctx context.Context, req *fuse.SetattrRequest, resp *fuse.SetattrResponse) error {\n\t// Get the filepath, so chmod in hdfs can work\n\tpath := this.AbsolutePath()\n\tvar err error\n\n\tif req.Valid.Mode() {\n\t\tInfo.Println(\"Chmod [\", path, \"] to [\", req.Mode, \"]\")\n\t\t(func() {\n\t\t\terr = this.FileSystem.HdfsAccessor.Chmod(path, req.Mode)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t})()\n\n\t\tif err != nil {\n\t\t\tError.Println(\"Chmod failed with error: \", err)\n\t\t} else {\n\t\t\tthis.Attrs.Mode = req.Mode\n\t\t}\n\t}\n\n\tif req.Valid.Uid() {\n\t\tu, err := user.LookupId(fmt.Sprint(req.Uid))\n\t\towner := fmt.Sprint(req.Uid)\n\t\tgroup := fmt.Sprint(req.Gid)\n\t\tif err != nil {\n\t\t\tError.Println(\"Chown: username for uid\", req.Uid, \"not found, use uid/gid instead\")\n\t\t} else {\n\t\t\towner = u.Username\n\t\t\tgroup = owner // hardcoded the group same as owner\n\t\t}\n\n\t\tInfo.Println(\"Chown [\", path, \"] to [\", owner, \":\", group, \"]\")\n\t\t(func() {\n\t\t\terr = this.FileSystem.HdfsAccessor.Chown(path, fmt.Sprint(req.Uid), fmt.Sprint(req.Gid))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t})()\n\n\t\tif err != nil {\n\t\t\tError.Println(\"Chown failed with error:\", err)\n\t\t} else {\n\t\t\tthis.Attrs.Uid = req.Uid\n\t\t\tthis.Attrs.Gid = req.Gid\n\t\t}\n\t}\n\n\treturn err\n}", "func FileDescriptor_NewServer(s FileDescriptor_Server) *server.Server {\n\tc, _ := s.(server.Shutdowner)\n\treturn server.New(FileDescriptor_Methods(nil, s), s, c)\n}", "func InitHtpasswd(filePath, user, password string) {\n\tif err := generateHtpasswdFile(filePath, user, password); err != nil {\n\t\tfatal(err)\n\t}\n}", "func ConnectWithKeyFile(host, username, privKeyPath string) (*Client, error) {\n\treturn ConnectWithKeyFileTimeout(host, username, privKeyPath, DefaultTimeout)\n}", "func (s *UserStoreFile) Create(user *app.User) error {\r\n\treturn nil\r\n}", "func (c *Client) User(u string) (err error) {\n\tif _, err = c.Cmd(\"%s %s\\r\\n\", USER, u); err != nil {\n\t\treturn\n\t}\n\treturn\n}" ]
[ "0.55712706", "0.5384361", "0.5338686", "0.5322527", "0.51540524", "0.51157945", "0.5093057", "0.5075457", "0.50744027", "0.5068816", "0.5059154", "0.50112545", "0.4942917", "0.49192628", "0.49105898", "0.4879357", "0.487523", "0.4864919", "0.4827859", "0.48217505", "0.47795215", "0.47760805", "0.4766909", "0.47432265", "0.47194248", "0.46925423", "0.4680241", "0.46755627", "0.46663624", "0.46471688", "0.46446994", "0.4637033", "0.4630025", "0.4622807", "0.46053392", "0.45991316", "0.45749903", "0.45715815", "0.45402884", "0.45310083", "0.45225257", "0.45192292", "0.451049", "0.44968146", "0.4489999", "0.44803727", "0.4474357", "0.44500774", "0.44266754", "0.44263723", "0.4423308", "0.4419744", "0.44162038", "0.44144627", "0.44140485", "0.44118315", "0.44104522", "0.44102973", "0.44023594", "0.43988544", "0.43981487", "0.43929082", "0.43857044", "0.43857", "0.43840048", "0.4376614", "0.43727535", "0.43716696", "0.4362008", "0.4360694", "0.43602115", "0.43591815", "0.43591666", "0.43574834", "0.43560287", "0.43534538", "0.43534538", "0.43492675", "0.43459833", "0.43435073", "0.43412367", "0.4332119", "0.4330378", "0.43299276", "0.43195492", "0.43160802", "0.43119153", "0.43115225", "0.43082148", "0.43059927", "0.43057472", "0.43052182", "0.43045908", "0.43042645", "0.43039107", "0.42931026", "0.42855245", "0.4284995", "0.42836112", "0.42830116" ]
0.5210085
4
Closes the connection to the file sever.
func (clnt *Client) Unmount() { clnt.conn.Close() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (self *File_Client) Close() {\n\tself.cc.Close()\n}", "func (file *Remote) Close() error {\n\t_, err := file.client.Send(&Tclunk{\n\t\tFID: file.fid,\n\t})\n\treturn err\n}", "func FileClose(f *os.File,) error", "func (res *respondent) Close() error {\n\tif res.fileChannel == nil {\n\t\treturn errors.New(utils.ErrorListenDial)\n\t}\n\tres.fileChannel.Destroy()\n\treturn nil\n}", "func (f *FTPS) Close() {\n\tf.ftpsclient.Quit()\n}", "func (c *fileClient) Close() error {\n\treturn errNotImplemented.New(Kind)\n}", "func (hd *hostDownloader) Close() error {\n\t// don't care about these errors\n\t_, _ = verifySettings(hd.conn, hd.host, hd.contractor.hdb)\n\t_ = modules.WriteNegotiationStop(hd.conn)\n\treturn hd.conn.Close()\n}", "func (bc BufConn) Close() error { return nil }", "func (s *Server) CloseConnection() {}", "func (s *HTTPServer) Close() error { s.ln.Close(); return nil }", "func (s *Server) Close() {\n\t//s.storager.Close()\n}", "func (c *Client) Close() error {\n\tif err := c.ssh.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.sftp.Close(); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Conn) Close() error { return nil }", "func (s *Server) Close() error {\n if s.ln != nil {\n s.ln.Close()\n }\n return nil\n}", "func (c *client) Close() error { return c.c.Close() }", "func (n *NSCAServer) Close() {\n\tif n.conn != nil {\n\t\tn.conn.Close()\n\t\tn.conn = nil\n\t}\n\tn.serverTimestamp = 0\n\tn.encryption = nil\n}", "func (f *realFile) Close() error { return f.file.Close() }", "func (prov *FtpProvider) Close() error {\n\treturn prov.client.Close()\n}", "func (t *ssh2Server) Close() (err error) {\n\n\tlogrus.Debugln(\"Close\")\n\treturn nil\n\n\t// =================================== original code ======================================\n\t// t.mu.Lock()\n\t// if t.state == closing {\n\t// \tt.mu.Unlock()\n\t// \treturn errors.New(\"transport: Close() was already called\")\n\t// }\n\t// t.state = closing\n\t// streams := t.activeStreams\n\t// t.activeStreams = nil\n\t// t.mu.Unlock()\n\t// close(t.shutdownChan)\n\t// err = t.conn.Close()\n\t// // Notify all active streams.\n\t// for _, s := range streams {\n\t// \ts.write(recvMsg{err: ErrConnClosing})\n\t// }\n\t// return\n}", "func (c *Client) Close() error {\n\treturn c.ftp.Quit()\n}", "func (s *Server) Close() {\n s.setupConn.Close()\n}", "func (rrs *remoteReadServer) Close() {\n\trrs.server.Close()\n}", "func (f fileauth) Terminate() {\n\tf.fh.Close()\n}", "func (s *Server) Close() {\n\ts.closed = true\n\ts.conn.Close()\n}", "func (f *File) Close() {\n\tf.src.Close()\n}", "func (conn *Tunnel) Close() {\n\tconn.once.Do(func() {\n\t\tconn.requestDisc()\n\n\t\tclose(conn.done)\n\t\tconn.wait.Wait()\n\n\t\tconn.sock.Close()\n\t})\n}", "func (f *FileHandler) Close() {}", "func (s *TLSServer) Close() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.ln == nil {\n\t\treturn errors.New(\"not serving\")\n\t}\n\ts.done = true\n\treturn s.ln.Close()\n}", "func (c *Client) Close() {}", "func (c *Client) Close() {}", "func (wt *WireTap) Close() {\n\twt.file.Close()\n}", "func (r *ResourceConn) Close() {\n\tr.ClientConn.Close()\n}", "func (s *Fs) Close() error {\n\treturn nil\n}", "func (s *Server) Close() {\n\ts.conn.Close()\n}", "func (rw *NopConn) Close() error { return nil }", "func (c *fileStorageClient) Close() error {\n\treturn c.db.Close()\n}", "func (s *ServerCodec) Close() error {\n\treturn s.w.Close()\n}", "func (s *Server) Close() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.ln == nil {\n\t\treturn errors.New(\"not serving\")\n\t}\n\ts.done = true\n\treturn s.ln.Close()\n}", "func (s *Server) Close() error {\n\treturn s.ln.Close()\n}", "func (s *Server) Close() error {\n\treturn s.ln.Close()\n}", "func (b *BIRDClient) Close() error { return b.conn.Close() }", "func (rw *DataRW) Close() {\n\te := rw.fd.Close()\n\tif e != nil {\n\t\tfmt.Println(\"connection Close error \", e.Error())\n\t}\n}", "func (s *Server) Close() (err error) {\n\treturn\n}", "func (f *fetcher) Close() error {\n\treturn f.conn.Close()\n}", "func (server *TempestServer) Close() error {\n\treturn server.conn.Close()\n}", "func (c *Conn) Close() error { return c.pc.Close() }", "func (s *APIServer) Close() {\n\tif s.conn == nil {\n\t\treturn\n\t}\n\ts.conn.Close()\n\ts.conn = nil\n}", "func (serv *Server) Close() (e error) {\n log.Println(\"Shutting down server.\")\n\n if serv.logFile != nil {\n e = serv.logFile.Close()\n }\n\n if serv.db != nil {\n e = serv.db.Close()\n }\n\n return e\n}", "func (s *Stream) Close() error {\n\treturn s.file.Close()\n}", "func (r ResourceConn) Close() {\n\tr.Conn.Close()\n}", "func (s *Server) Close() {\n\ts.Conn.Close()\n}", "func (c *Conn) Close() error {\n\treturn syscall.Close(c.fd)\n}", "func (s *Server) Close() {\n\terr := s.zkConn.Delete(path.Join(s.zkPath, s.hostname), 0)\n\tif err != nil {\n\t\ts.logger.Error(err)\n\t}\n\ts.zkConn.Close()\n\ts.routerSocket.Close()\n\ts.dealerSocket.Close()\n\t//s.context.Term()\n\ts.wg.Wait()\n}", "func (ff *File) Close() error {\n\treturn nil\n}", "func (s *Server) Close() error {\n\tif s.ln != nil {\n\t\ts.ln.Close()\n\t}\n\treturn nil\n}", "func (self *Client) close() {\n\t// TODO: Cleanly close connection to remote\n}", "func (self *FileBaseDataStore) Close() {}", "func (hd *Downloader) Close() error {\n\t// using once ensures that Close is idempotent\n\thd.once.Do(hd.shutdown)\n\treturn hd.conn.Close()\n}", "func (spi *SPI) Close() error {\n\treturn spi.file.Close()\n}", "func (c *RemoteHTTP) Close() {\n\tc.HTTPClient = nil\n\n\tif c.SSHSession != nil {\n\t\tc.SSHSession.Close()\n\t\tc.SSHSession = nil\n\t}\n\n\tif c.SSHClient != nil {\n\t\tc.SSHClient.Close()\n\t\tc.SSHClient = nil\n\t}\n}", "func (v *connection) Close() error {\n\tconnectionLogger.Trace(\"connection.Close()\")\n\n\tv.sendMessage(&msgs.FETerminateMsg{})\n\n\tvar result error = nil\n\n\tif v.conn != nil {\n\t\tresult = v.conn.Close()\n\t\tv.conn = nil\n\t}\n\n\treturn result\n}", "func (s *server) close() error {\n\treturn s.ln.Close()\n}", "func (s *Server) Close() error {\n\ts.instruments.Log(octo.LOGINFO, s.info.UUID, \"udp.Server.Close\", \"Started : %#v\", s.info)\n\n\tif !s.IsRunning() {\n\t\treturn nil\n\t}\n\n\ts.rl.Lock()\n\t{\n\t\ts.running = false\n\t\ts.doClose = true\n\t}\n\ts.rl.Unlock()\n\n\t// Await for last request.\n\ts.rg.Wait()\n\n\tif err := s.conn.Close(); err != nil {\n\t\ts.instruments.Log(octo.LOGERROR, s.info.UUID, \"udp.Server.Close\", \"Completed : %s\", err.Error())\n\t}\n\n\ts.wg.Wait()\n\n\ts.instruments.Log(octo.LOGINFO, s.info.UUID, \"udp.Server.Close\", \"Completed\")\n\treturn nil\n}", "func (f *file) Close() error {\n\treturn nil\n}", "func Close() error {\n\treturn server.Close()\n}", "func (c *SodaClient) Close() {\n\tc.conn.Close()\n}", "func (c *Connection) Close() error {\n\trerr := c.ReadCloser.Close()\n\twerr := c.WriteCloser.Close()\n\tif rerr != nil {\n\t\treturn rerr\n\t}\n\treturn werr\n}", "func ConnClose(c *tls.Conn,) error", "func (r *RTC) Close() error {\n\treturn r.file.Close()\n}", "func (t *TrudyPipe) Close() {\n\tt.serverConn.Close()\n\tt.clientConn.Close()\n}", "func (c *conn) Close() error {\n\tif atomic.CompareAndSwapInt32(&c.closed, 0, 1) {\n\t\tc.log(\"close connection\", c.url.Scheme, c.url.Host, c.url.Path)\n\t\tcancel := c.cancel\n\t\ttransport := c.transport\n\t\tc.transport = nil\n\t\tc.cancel = nil\n\n\t\tif cancel != nil {\n\t\t\tcancel()\n\t\t}\n\t\tif transport != nil {\n\t\t\ttransport.CloseIdleConnections()\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Server) Close() error {\n\t// TODO(sajjadm): Determine if some pending connections were forcefully closed by s.cancel()\n\t// and report that as an error.\n\ts.cancel()\n\treturn s.ln.Close()\n}", "func (s *UDPServer) close() {\n\ts.sock.Close()\n}", "func (con *IRCConn) Close() {\n close(con.read);\n close(con.Write);\n con.sock.Close();\n}", "func (c *Client) Close() {\n\tif c.Torrent != nil {\n\t\tc.Torrent.Drop()\n\t}\n\tif c.TorrentClient != nil {\n\t\tc.TorrentClient.Close()\n\t}\n\tc.Started = false\n\tc.Downloading = false\n\tc.Progress = 0\n\tc.Uploaded = 0\n}", "func (c *Client) Close() { c.streamLayer.Close() }", "func (cl *Client) Close(fh *FileHandle) (err error) {\n\tif fh == nil {\n\t\treturn nil\n\t}\n\tvar (\n\t\tlogp = \"Close\"\n\t\treq = cl.generatePacket()\n\t\tpayload = req.fxpClose(fh)\n\t)\n\n\tres, err := cl.send(payload)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %w\", logp, err)\n\t}\n\tif res.kind != packetKindFxpStatus {\n\t\treturn errUnexpectedResponse(packetKindFxpStatus, res.kind)\n\t}\n\tif res.code != statusCodeOK {\n\t\treturn handleStatusCode(res.code, res.message)\n\t}\n\n\treturn nil\n}", "func (c *connection) Close() {\n\tbaseurl := \"http://fritz.box/webservices/homeautoswitch.lua\"\n\tparameters := make(map[string]string)\n\tparameters[\"sid\"] = c.sid\n\tparameters[\"logout\"] = \"logout\"\n\tUrl := prepareRequest(baseurl, parameters)\n\tsendRequest(Url)\n}", "func (c *Connection) Close() error { return c.pump.Close() }", "func (c *Conn) Close(ctx context.Context) error {\n\treturn c.redfishwrapper.Close(ctx)\n}", "func (ch *Channel) Close() {}", "func (t *T) Close() {\n\tt.file.Close()\n}", "func (srv *Server) Close() error {\n\therr := srv.http.server.Close()\n\thherr := srv.http.health.Close()\n\tserr := srv.ssh.server.Close()\n\tif herr != nil || hherr != nil || serr != nil {\n\t\treturn fmt.Errorf(\"one or more servers had an error closing: %s %s %s\", herr, hherr, serr)\n\t}\n\terr := srv.Config.DB.Close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"db close error: %s\", err)\n\t}\n\tif srv.Config.Stats != nil {\n\t\tif err := srv.Config.Stats.Close(); err != nil {\n\t\t\treturn fmt.Errorf(\"db close error: %s\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *stream) Close() error {\n\treturn nil\n}", "func (s *LocalServer) Close() {\n\t_ = s.httpServer.Close()\n}", "func (s *Stream) Close() error {\n\tlog.Print(\"[INFO] Closing \", s.URL)\n\treturn s.rc.Close()\n}", "func closeFile(f *os.File) {\n\t_ = f.Close()\n}", "func (t *Tail) Close() error {\n\terr := t.posFd.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = t.fileFd.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *whoisClient) Close() error {\n\tc.Conn.SetWriteDeadline(time.Now().Add(time.Second))\n\n\tc.w.Write([]byte(\"end\"))\n\tc.w.Write(ncEOL)\n\t// This error is not important, because the previous are a courtesy.\n\tc.w.Flush()\n\treturn c.Conn.Close()\n}", "func (s *SshConnection) Close() {\n\tif s.Client != nil {\n\t\ts.Client.Close()\n\t}\n\ts.connectionStatusMU.Lock()\n\ts.connectionStatus = STATUS_CLOSED\n\ts.connectionStatusMU.Unlock()\n}", "func (s *Server) Close() error {\n\treturn s.httpSrv.Close()\n}", "func (v *vsockConn) Close() error {\n\treturn v.vsock.Close()\n}", "func (r *remoteReplicator) Close() {\n\tr.closeStream()\n}", "func (r *repository) Close() {\n\tr.conn.Close()\n}", "func (st *fakeConn) Close() {\n}", "func (c *Client) Close() error {\n\tif c.tempDir != nil {\n\t\treturn c.tempDir.Close()\n\t}\n\treturn nil\n}", "func (rc *OneByteWriteConn) Close() error {\n\treturn rc.conn.Close()\n}", "func (s *Sniffer) close() error {\n\tif err := unix.Close(s.fd); err != nil {\n\t\treturn fmt.Errorf(\"can't close sniffer socket: %w\", err)\n\t}\n\ts.fd = -1\n\treturn nil\n}", "func (fs *EmbedFs) Close() error {\n\treturn fs.origin.Close()\n}", "func (filebackend *FileBackend) Close() {\n\tfilebackend.mutex.Lock()\n\tdefer filebackend.mutex.Unlock()\n\tif filebackend.handle != nil {\n\t\tfilebackend.handle.Close()\n\t\tfilebackend.handle = nil\n\t}\n}", "func (t *Client) Close() error { return nil }" ]
[ "0.68455344", "0.6525067", "0.64819026", "0.6373658", "0.63064545", "0.62601066", "0.6202454", "0.6155793", "0.6113124", "0.6092815", "0.6038928", "0.60178185", "0.6003053", "0.5995619", "0.59876317", "0.59375936", "0.59373987", "0.59329754", "0.5901486", "0.5890322", "0.5886762", "0.58666646", "0.5815811", "0.58131105", "0.58125323", "0.58093685", "0.5804307", "0.58034325", "0.5793686", "0.5793686", "0.5785086", "0.5780748", "0.57602984", "0.5734633", "0.5729928", "0.572941", "0.5727428", "0.5723332", "0.571972", "0.571972", "0.5706579", "0.5706436", "0.57059175", "0.5693873", "0.56932604", "0.56918883", "0.5682706", "0.5676549", "0.5671784", "0.5668139", "0.5666744", "0.56650114", "0.5662728", "0.5660033", "0.5653495", "0.5645262", "0.5641441", "0.56382185", "0.5634641", "0.5627596", "0.5619452", "0.56182665", "0.561044", "0.55978197", "0.5585198", "0.55830806", "0.5582198", "0.5579257", "0.55782765", "0.5576857", "0.5575701", "0.55694896", "0.55640197", "0.5549307", "0.55464613", "0.5539983", "0.55393654", "0.552944", "0.5525066", "0.552274", "0.5521635", "0.55118585", "0.5508063", "0.5507155", "0.5506866", "0.5506438", "0.5505938", "0.54936564", "0.5490686", "0.5489532", "0.5479381", "0.54785514", "0.54771113", "0.54762363", "0.5475624", "0.54751045", "0.5471765", "0.547026", "0.5468953", "0.54603964", "0.54596627" ]
0.0
-1
/ > x | | | | | | r1 | | | | | | | | | | | | | | | | | | | | r2 | | | | | V y
func (r1 Rectangle) collidesWith(r2 Rectangle) bool { if r1.LowerRight.x > r2.UpperLeft.x && r1.LowerRight.y > r2.UpperLeft.y && r2.LowerRight.x > r1.UpperLeft.x && r2.LowerRight.y > r1.UpperLeft.y { return true } if r2.LowerRight.x > r1.UpperLeft.x && r2.LowerRight.y > r1.UpperLeft.y && r1.LowerRight.x > r2.UpperLeft.x && r1.LowerRight.y > r2.UpperLeft.y { return true } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RORXL(i, mr, r operand.Op) { ctx.RORXL(i, mr, r) }", "func _line(x1o, y1o, x2o, y2o *FloatOrInt) chan FloatPair {\n\tc := make(chan FloatPair)\n\n\tgo func() {\n\t\tx1 := x1o.Normalized()\n\t\ty1 := y1o.Normalized()\n\t\tx2 := x2o.Normalized()\n\t\ty2 := y2o.Normalized()\n\n\t\txdiff := sub(max(x1, x2), min(x1, x2))\n\t\tydiff := sub(max(y1, y2), min(y1, y2))\n\n\t\txdir := -1\n\t\tif lessEqual(x1, x2) {\n\t\t\txdir = 1\n\t\t}\n\n\t\tydir := -1\n\t\tif lessEqual(y1, y2) {\n\t\t\tydir = 1\n\t\t}\n\n\t\tr := max(xdiff, ydiff)\n\n\t\tfor i := 0; i < r.Int()+1; i++ {\n\t\t\tx := x1.Float()\n\t\t\ty := y1.Float()\n\n\t\t\tif ydiff.Bool() {\n\t\t\t\ty += (float64(i) * ydiff.Float()) / r.Float() * float64(ydir)\n\t\t\t}\n\t\t\tif xdiff.Bool() {\n\t\t\t\tx += (float64(i) * xdiff.Float()) / r.Float() * float64(xdir)\n\t\t\t}\n\n\t\t\tc <- FloatPair{x, y} // yield\n\t\t}\n\t\tclose(c)\n\n\t}()\n\n\treturn c\n}", "func R(ox, oy, vx, vy float64) Ray {\n\treturn Ray{Vec{ox, oy}, Vec{vx, vy}}\n}", "func RORXQ(i, mr, r operand.Op) { ctx.RORXQ(i, mr, r) }", "func VPXOR(mxy, xy, xy1 operand.Op) { ctx.VPXOR(mxy, xy, xy1) }", "func part2(mem []int64) int64 {\n\tg := readGrid(mem)\n\tvar r robot\n\tfor y, row := range g {\n\t\tfor x, c := range row {\n\t\t\tif strings.ContainsRune(\"^v<>\", c) {\n\t\t\t\tr = robot{point{x, y}, north}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tprev := r.pos.move(west)\n\tpath := []direction{east}\n\tfor {\n\t\tadj := adjacent(g, r.pos)\n\t\tif len(path) > 2 && len(adj) == 1 {\n\t\t\tbreak\n\t\t}\n\t\tif 0 < len(adj) && len(adj) <= 2 {\n\t\t\tnext := adj[0]\n\t\t\tif len(adj) == 2 && adj[0] == prev {\n\t\t\t\tnext = adj[1]\n\t\t\t}\n\t\t\tif r.pos.x < next.x {\n\t\t\t\tr.dir = east\n\t\t\t}\n\t\t\tif r.pos.x > next.x {\n\t\t\t\tr.dir = west\n\t\t\t}\n\t\t\tif r.pos.y < next.y {\n\t\t\t\tr.dir = south\n\t\t\t}\n\t\t\tif r.pos.y > next.y {\n\t\t\t\tr.dir = north\n\t\t\t}\n\t\t}\n\t\tpath = append(path, r.dir)\n\t\tprev = r.pos\n\t\tr.move()\n\t}\n\n\tqueue := []step{{0, right}}\n\tfor i, d := range path[1:] {\n\t\trot := path[i].rotation(d)\n\t\tif len(queue) > 0 && rot == none {\n\t\t\tqueue[len(queue)-1].n++\n\t\t\tcontinue\n\t\t}\n\t\tqueue = append(queue, step{1, rot})\n\t}\n\n\tvar out string\n\tfor _, v := range queue {\n\t\tout += v.String() + \",\"\n\t}\n\tfmt.Println(out)\n\n\tp := newProgram(mem)\n\tp.memory[0] = 2\n\t// I have to be honest. I used my editors \"highlight other occurrences\"\n\t// feature on the previous output.\n\tin := strings.Join([]string{\n\t\t\"A,B,A,C,A,B,C,C,A,B\",\n\t\t\"R,8,L,10,R,8\",\n\t\t\"R,12,R,8,L,8,L,12\",\n\t\t\"L,12,L,10,L,8\",\n\t\t\"n\",\n\t\t\"\",\n\t}, \"\\n\")\n\tfor _, c := range in {\n\t\tp.input = append(p.input, int64(c))\n\t}\n\tres, err := p.run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn res[len(res)-1]\n}", "func R(minX, minY, maxX, maxY float64) Rect {\n\treturn Rect{\n\t\tMin: Vec{minX, minY},\n\t\tMax: Vec{maxX, maxY},\n\t}\n}", "func MOVBLSX(mr, r operand.Op) { ctx.MOVBLSX(mr, r) }", "func VPALIGNR(ops ...operand.Op) { ctx.VPALIGNR(ops...) }", "func VPINSRB(i, mr, x, x1 operand.Op) { ctx.VPINSRB(i, mr, x, x1) }", "func (o Orbit) RV() ([]float64, []float64) {\n\treturn o.rVec, o.vVec\n}", "func VPOR(mxy, xy, xy1 operand.Op) { ctx.VPOR(mxy, xy, xy1) }", "func (p picReader) getRelCoords2(x1, y1 int) (int, int, error) {\n\tdy, err := p.bits.Read8(8)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\tdx, err := p.bits.Read8(8)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\tx2, y2 := x1, y1\n\n\tif dy&0x80 != 0 {\n\t\ty2 -= int(dy & 0x7F)\n\t} else {\n\t\ty2 += int(dy & 0x7F)\n\t}\n\n\tif dx&0x80 != 0 {\n\t\tx2 -= 128 - int(dx&0x7F)\n\t} else {\n\t\tx2 += int(dx & 0x7F)\n\t}\n\n\treturn x2, y2, nil\n}", "func RORB(ci, mr operand.Op) { ctx.RORB(ci, mr) }", "func elevateBoth(r1, r2 *Reference) (*Reference, *Reference, error) {\n\tflip := r1.chunk > r2.chunk\n\tif flip {\n\t\tr1, r2 = r2, r1\n\t}\n\tr1e, err := r1.elevated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tr2e, err := r2.elevated()\n\tif err != nil {\n\t\tr1e.Release()\n\t\treturn nil, nil, err\n\t}\n\tif flip {\n\t\treturn r2e, r1e, nil\n\t} else {\n\t\treturn r1e, r2e, nil\n\t}\n}", "func NextR(r, v, a [3]float64, h float64) [3]float64 {\n\treturn vector.Sum(vector.Sum(r, vector.Scale(v, h)), vector.Scale(a, 0.5*h*h))\n}", "func d12combineRect(rectA, rectB *d12rectT) d12rectT {\n\tvar newRect d12rectT\n\n\tfor index := 0; index < d12numDims; index++ {\n\t\tnewRect.min[index] = d12fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d12fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func d1combineRect(rectA, rectB *d1rectT) d1rectT {\n\tvar newRect d1rectT\n\n\tfor index := 0; index < d1numDims; index++ {\n\t\tnewRect.min[index] = d1fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d1fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func GetR1R2Orientation(p *IndexedPair) Orientation {\n\tif p.Left.R.Flags&sam.Read1 == p.Right.R.Flags&sam.Read1 {\n\t\tlog.Fatalf(\"Both reads are first or second for pair: %v %d %d\", p.Left.R.Name, p.Left.R.Flags, p.Right.R.Flags)\n\t}\n\n\tif p.Left.R.Flags&sam.Read1 != 0 {\n\t\treturn orientationBytePair(p.Left.R.Flags&sam.Reverse != 0, p.Right.R.Flags&sam.Reverse != 0)\n\t} else if p.Right.R.Flags&sam.Read1 != 0 {\n\t\treturn orientationBytePair(p.Right.R.Flags&sam.Reverse != 0, p.Left.R.Flags&sam.Reverse != 0)\n\t} else {\n\t\tlog.Fatalf(\"Could not find first read in pair: %v\", p.Left.R.Name)\n\t}\n\treturn 0\n}", "func RORW(ci, mr operand.Op) { ctx.RORW(ci, mr) }", "func d11combineRect(rectA, rectB *d11rectT) d11rectT {\n\tvar newRect d11rectT\n\n\tfor index := 0; index < d11numDims; index++ {\n\t\tnewRect.min[index] = d11fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d11fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func RPerp(v Vect) Vect { return Vect{v.Y, -v.X} }", "func RORL(ci, mr operand.Op) { ctx.RORL(ci, mr) }", "func rect(img *image.NRGBA, x1, y1, x2, y2 int, col color.Color) {\r\n\thLine(img, x1, y1, x2, col)\r\n\thLine(img, x1, y2, x2, col)\r\n\tvLine(img, x1, y1, y2, col)\r\n\tvLine(img, x2, y1, y2, col)\r\n}", "func d9combineRect(rectA, rectB *d9rectT) d9rectT {\n\tvar newRect d9rectT\n\n\tfor index := 0; index < d9numDims; index++ {\n\t\tnewRect.min[index] = d9fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d9fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func rcMoveR(p *TCompiler, code *TCode) (*value.Value, error) {\n\tp.regSet(code.A, p.regGet(code.B))\n\tp.moveNext()\n\treturn nil, nil\n}", "func SARXL(r, mr, r1 operand.Op) { ctx.SARXL(r, mr, r1) }", "func PALIGNR(i, mx, x operand.Op) { ctx.PALIGNR(i, mx, x) }", "func twoCoords(tls *libc.TLS, p1 int32, p2 int32, mx uint32, pX0 uintptr, pX1 uintptr) { /* speedtest1.c:1383:13: */\n\tvar d uint32\n\tvar x0 uint32\n\tvar x1 uint32\n\tvar span uint32\n\n\tspan = ((mx / uint32(100)) + uint32(1))\n\tif (speedtest1_random(tls) % uint32(3)) == uint32(0) {\n\t\tspan = span * (uint32(p1))\n\t}\n\tif (speedtest1_random(tls) % uint32(p2)) == uint32(0) {\n\t\tspan = (mx / uint32(2))\n\t}\n\td = ((speedtest1_random(tls) % span) + uint32(1))\n\tx0 = ((speedtest1_random(tls) % (mx - d)) + uint32(1))\n\tx1 = (x0 + d)\n\t*(*uint32)(unsafe.Pointer(pX0)) = x0\n\t*(*uint32)(unsafe.Pointer(pX1)) = x1\n}", "func ROLW(ci, mr operand.Op) { ctx.ROLW(ci, mr) }", "func d8combineRect(rectA, rectB *d8rectT) d8rectT {\n\tvar newRect d8rectT\n\n\tfor index := 0; index < d8numDims; index++ {\n\t\tnewRect.min[index] = d8fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d8fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func VPINSRW(i, mr, x, x1 operand.Op) { ctx.VPINSRW(i, mr, x, x1) }", "func (p *Path) Vr(ys ...float64) *Path {\n\treturn p.addCmd(\"v\", vCmd{ys: ys})\n}", "func gtrr(a, b, c int, r register) register {\n\tif r[a] > r[b] {\n\t\tr[c] = 1\n\t} else {\n\t\tr[c] = 0\n\t}\n\treturn r\n}", "func (c *CPU) Xor_r(r Reg8) {\n\tget, _ := c.getReg8(r)\n\td8 := get()\n\tres := c.A ^ d8\n\n\t// FLAGS\n\t// z\n\tif res == 0 {\n\t\tc.setFlagZ(true)\n\t} else {\n\t\tc.setFlagZ(false)\n\t}\n\t// n\n\tc.setFlagN(false)\n\t// h\n\tc.setFlagH(false)\n\t// c\n\tc.setFlagC(false)\n\n\tc.A = res\n}", "func VBLENDVPD(xy, mxy, xy1, xy2 operand.Op) { ctx.VBLENDVPD(xy, mxy, xy1, xy2) }", "func (bitmap *bitmap) Xor(other *bitmap) *bitmap {\n\tif bitmap.Size != other.Size {\n\t\tpanic(\"size not the same\")\n\t}\n\n\tdistance := newBitmap(bitmap.Size)\n\tdiv, mod := distance.Size/8, distance.Size%8\n\n\tfor i := 0; i < div; i++ {\n\t\tdistance.data[i] = bitmap.data[i] ^ other.data[i]\n\t}\n\n\tfor i := div * 8; i < div*8+mod; i++ {\n\t\tdistance.set(i, bitmap.Bit(i)^other.Bit(i))\n\t}\n\n\treturn distance\n}", "func SHRXL(r, mr, r1 operand.Op) { ctx.SHRXL(r, mr, r1) }", "func crossover(v1, v2 float32) float32 {\r\n\tconst delta = 0.10\r\n\tswitch {\r\n\tcase isNan(v1) && isNan(v2):\r\n\t\treturn randFloat32()\r\n\tcase isNan(v1):\r\n\t\treturn v2\r\n\tcase isNan(v2) || v1 == v2:\r\n\t\treturn v1\r\n\tdefault: // e.g. [5, 10], move by x% towards 10\r\n\t\treturn v1 + ((v2 - v1) * delta)\r\n\t}\r\n}", "func eqrr(a, b, c int, r register) register {\n\tif r[a] == r[b] {\n\t\tr[c] = 1\n\t} else {\n\t\tr[c] = 0\n\t}\n\treturn r\n}", "func VPINSRD(i, mr, x, x1 operand.Op) { ctx.VPINSRD(i, mr, x, x1) }", "func d2combineRect(rectA, rectB *d2rectT) d2rectT {\n\tvar newRect d2rectT\n\n\tfor index := 0; index < d2numDims; index++ {\n\t\tnewRect.min[index] = d2fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d2fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func OverlapR(p Pattern) int {\n\treturn aggregateOverlap(p, overlapR)\n}", "func multiply(x, y int) (r1, r2 int) {\n\tr1 = x * 10\n\tr2 = y * 20\n\treturn r1, r2\n}", "func overlaps(r1, r2 Rect) bool {\n\treturn r1.X < r2.X+r2.Width &&\n\t\tr1.X+r1.Width > r2.X &&\n\t\tr1.Y+r1.Height > r2.Y &&\n\t\tr1.Y < r2.Y+r2.Height\n}", "func d16combineRect(rectA, rectB *d16rectT) d16rectT {\n\tvar newRect d16rectT\n\n\tfor index := 0; index < d16numDims; index++ {\n\t\tnewRect.min[index] = d16fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d16fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func MOVBLZX(mr, r operand.Op) { ctx.MOVBLZX(mr, r) }", "func VPRORQ(ops ...operand.Op) { ctx.VPRORQ(ops...) }", "func RORQ(ci, mr operand.Op) { ctx.RORQ(ci, mr) }", "func d19combineRect(rectA, rectB *d19rectT) d19rectT {\n\tvar newRect d19rectT\n\n\tfor index := 0; index < d19numDims; index++ {\n\t\tnewRect.min[index] = d19fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d19fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func VPERMI2D(ops ...operand.Op) { ctx.VPERMI2D(ops...) }", "func VRCPPS(mxy, xy operand.Op) { ctx.VRCPPS(mxy, xy) }", "func VPINSRQ(i, mr, x, x1 operand.Op) { ctx.VPINSRQ(i, mr, x, x1) }", "func intercambiar(x, y string) (string, string) {\n\treturn y, x\n}", "func Eql(v1, v2 Vect) bool { return v1.X == v2.X && v1.Y == v2.Y }", "func d20combineRect(rectA, rectB *d20rectT) d20rectT {\n\tvar newRect d20rectT\n\n\tfor index := 0; index < d20numDims; index++ {\n\t\tnewRect.min[index] = d20fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d20fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func (a line2) IntersectPoint(b line2) (vector2, bool) {\n\tswaped := false\n\tif math.Abs(a.end.y-a.start.y) > math.Abs(a.end.x-a.start.x) {\n\t\tswaped = true\n\t\ta.start.x, a.start.y = a.start.y, a.start.x\n\t\ta.end.x, a.end.y = a.end.y, a.end.x\n\t\tb.start.x, b.start.y = b.start.y, b.start.x\n\t\tb.end.x, b.end.y = b.end.y, b.end.x\n\t}\n\tif a.start.x > a.end.x {\n\t\ta.start, a.end = a.end, a.start\n\t}\n\tif b.start.x > b.end.x {\n\t\tb.start, b.end = b.end, b.start\n\t}\n\t// we are interested in the 'common' parts.\n\tif a.start.x > b.end.x || b.start.x > a.end.x {\n\t\treturn vector2{}, false\n\t}\n\tsa, ia := a.SlopeIntercept()\n\t// shear b to y direction.\n\tb.start.y = b.start.y - (sa * b.start.x) - ia\n\tb.end.y = b.end.y - (sa * b.end.x) - ia\n\tif math.Signbit(b.start.y) == math.Signbit(b.end.y) {\n\t\treturn vector2{}, false\n\t}\n\t// find x if y == 0\n\ttb := math.Abs(b.start.y) / math.Abs(b.end.y-b.start.y)\n\tx := tb*(b.end.x-b.start.x) + b.start.x\n\tif x < a.start.x || a.end.x < x {\n\t\treturn vector2{}, false\n\t}\n\ty := sa*x + ia\n\tif swaped {\n\t\tx, y = y, x\n\t}\n\treturn vector2{x, y}, true\n}", "func main() {\n\traster := bridge.RasterRenderer{}\n\tvector := bridge.VectorRenderer{}\n\n\tcircleR := bridge.NewCircle(&raster, 5)\n\tcircleR.Draw()\n\tcircleR.Resize(2)\n\tcircleR.Draw()\n\n\tcircleV := bridge.NewCircle(&vector, 5)\n\tcircleV.Draw()\n\tcircleV.Resize(2)\n\tcircleV.Draw()\n\n\ttriangleR := bridge.NewTriangle(&raster, 1,2,3.5)\n\ttriangleR.Draw()\n\ttriangleR.Resize(3)\n\ttriangleR.Draw()\n\n\ttriangleV := bridge.NewTriangle(&vector, 2,4,7)\n\ttriangleV.Draw()\n\ttriangleV.Resize(5)\n\ttriangleV.Draw()\n}", "func ORPD(mx, x operand.Op) { ctx.ORPD(mx, x) }", "func d10combineRect(rectA, rectB *d10rectT) d10rectT {\n\tvar newRect d10rectT\n\n\tfor index := 0; index < d10numDims; index++ {\n\t\tnewRect.min[index] = d10fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d10fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func linePointsGen(p1, p2 Point, speed float64) (gen func() (x, y float64, e error)) {\n\t// Set up math\n\tslopeT, slope, _ := getLineParams(p1, p2)\n\n\tx := p1.X\n\txPrev := x\n\ty := p1.Y\n\tyPrev := y\n\te := fmt.Errorf(\"End of path reached\")\n\ttheta := math.Atan(slope)\n\n\t// Every slope type has a different iterator, since they change the\n\t// x and y values in different combinations, as well as do different\n\t// comparisons on the values.\n\tswitch slopeT {\n\tcase ZERORIGHT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif x > p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\txPrev = x\n\t\t\tx += speed\n\n\t\t\treturn xPrev, y, nil\n\t\t}\n\tcase ZEROLEFT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif x < p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\txPrev = x\n\t\t\tx -= speed\n\n\t\t\treturn xPrev, y, nil\n\t\t}\n\tcase POSRIGHT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y > p2.Y || x > p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev = y\n\t\t\txPrev = x\n\n\t\t\ty += speed * math.Sin(theta)\n\t\t\tx += speed * math.Cos(theta)\n\n\t\t\treturn xPrev, yPrev, nil\n\t\t}\n\tcase NEGRIGHT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y < p2.Y || x > p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev = y\n\t\t\txPrev = x\n\n\t\t\ty += speed * math.Sin(theta)\n\t\t\tx += speed * math.Cos(theta)\n\n\t\t\treturn xPrev, yPrev, nil\n\t\t}\n\tcase POSLEFT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y < p2.Y || x < p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev = y\n\t\t\txPrev = x\n\n\t\t\ty -= speed * math.Sin(theta)\n\t\t\tx -= speed * math.Cos(theta)\n\n\t\t\treturn xPrev, yPrev, nil\n\t\t}\n\tcase NEGLEFT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y > p2.Y || x < p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev = y\n\t\t\txPrev = x\n\n\t\t\ty -= speed * math.Sin(theta)\n\t\t\tx -= speed * math.Cos(theta)\n\n\t\t\treturn xPrev, yPrev, nil\n\t\t}\n\tcase INFUP:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y > p2.Y {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev := y\n\t\t\ty += speed\n\n\t\t\treturn x, yPrev, nil\n\t\t}\n\tcase INFDOWN:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y < p2.Y {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev := y\n\t\t\ty -= speed\n\n\t\t\treturn x, yPrev, nil\n\t\t}\n\t}\n\n\treturn nil\n}", "func VPRORVD(ops ...operand.Op) { ctx.VPRORVD(ops...) }", "func eqri(a, b, c int, r register) register {\n\tif r[a] == b {\n\t\tr[c] = 1\n\t} else {\n\t\tr[c] = 0\n\t}\n\treturn r\n}", "func d3combineRect(rectA, rectB *d3rectT) d3rectT {\n\tvar newRect d3rectT\n\n\tfor index := 0; index < d3numDims; index++ {\n\t\tnewRect.min[index] = d3fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d3fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func calculate(r float64) (float64, float64) {\n\tvar area = pi * (r * r)\n\n\tvar circle = 2 * pi * r\n\n\treturn area, circle\n}", "func ORPS(mx, x operand.Op) { ctx.ORPS(mx, x) }", "func (p picReader) getRelCoords1(x, y int) (int, int, error) {\n\txSign, err := p.bits.Read1()\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tdx, err := p.bits.Read8(3)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\tySign, err := p.bits.Read1()\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tdy, err := p.bits.Read8(3)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\tif xSign {\n\t\tx -= int(dx)\n\t} else {\n\t\tx += int(dx)\n\t}\n\n\tif ySign {\n\t\ty -= int(dy)\n\t} else {\n\t\ty += int(dy)\n\t}\n\n\treturn x, y, nil\n}", "func line(m draw.Image, x0, y0, x1, y1 int, c color.Color) {\n\tabs := func(x int) int {\n\t\tif x < 0 {\n\t\t\treturn -x\n\t\t}\n\t\treturn x\n\t}\n\n\tvar dx, dy, sx, sy, e, e2 int\n\n\tdx = abs(x1 - x0)\n\tdy = -abs(y1 - y0)\n\tif sx = -1; x0 < x1 {\n\t\tsx = 1\n\t}\n\tif sy = -1; y0 < y1 {\n\t\tsy = 1\n\t}\n\te = dx + dy\n\tfor {\n\t\tm.Set(x0, y0, c)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\tif e2 = 2 * e; e2 >= dy {\n\t\t\te += dy\n\t\t\tx0 += sx\n\t\t} else if e2 <= dx {\n\t\t\te += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}", "func (root *mTreap) rotateRight(y *treapNode) {\n\t// p -> (y (x a b) c)\n\tp := y.parent\n\tx, c := y.left, y.right\n\ta, b := x.left, x.right\n\n\tx.left = a\n\tif a != nil {\n\t\ta.parent = x\n\t}\n\tx.right = y\n\ty.parent = x\n\ty.left = b\n\tif b != nil {\n\t\tb.parent = y\n\t}\n\ty.right = c\n\tif c != nil {\n\t\tc.parent = y\n\t}\n\n\tx.parent = p\n\tif p == nil {\n\t\troot.treap = x\n\t} else if p.left == y {\n\t\tp.left = x\n\t} else {\n\t\tif p.right != y {\n\t\t\tthrow(\"large span treap rotateRight\")\n\t\t}\n\t\tp.right = x\n\t}\n\n\ty.updateInvariants()\n\tx.updateInvariants()\n}", "func VRCPSS(mx, x, x1 operand.Op) { ctx.VRCPSS(mx, x, x1) }", "func minY(d []float64, x, y *int, r int, asc bool) {\n\tfor *x < r {\n\t\tif asc {\n\t\t\t*y = MinRange(d, *x, r)\n\t\t} else {\n\t\t\t*y = MaxRange(d, *x, r)\n\t\t}\n\n\t\tif *y != *x {\n\t\t\tbreak\n\t\t}\n\t\t(*x)++\n\t}\n}", "func SARXQ(r, mr, r1 operand.Op) { ctx.SARXQ(r, mr, r1) }", "func VPXORQ(ops ...operand.Op) { ctx.VPXORQ(ops...) }", "func (re renderEdge) render(row string, vertIdx, vertDist int) string {\n\tsetEdgeChar := func(s string, i int, r rune) string {\n\t\tif s[i] == byte(r) {\n\t\t\treturn s\n\t\t} else if s[i] == ' ' {\n\t\t\treturn s[:i] + string(r) + s[i+1:]\n\t\t}\n\t\treturn s[:i] + \"+\" + s[i+1:] // set the coordinate to \"+\" if there's an edge crossing\n\t}\n\tif re.src == re.dest {\n\t\treturn setEdgeChar(row, re.src, '|')\n\t}\n\tconst srcEdgeCenterOffset = 1 // start drawing a diagonal edge one space away from the center of a node\n\tadjustedXDist := re.distance() - srcEdgeCenterOffset // number of horizontal spaces we must fill with edges\n\t// vertical line\n\tif vertDist > adjustedXDist && vertIdx >= adjustedXDist/2 && vertIdx < vertDist-adjustedXDist/2 {\n\t\treturn setEdgeChar(row, (re.src+re.dest)/2, '|')\n\t}\n\t// horizontal line\n\tif vertDist < adjustedXDist && vertIdx == vertDist/2 {\n\t\tstep := 1\n\t\tif re.src > re.dest {\n\t\t\tstep = -1\n\t\t}\n\t\tdiagCoverage := (vertDist / 2) * step\n\t\ttmp := re.src + diagCoverage\n\t\tfor tmp != re.dest-diagCoverage-(step*vertDist%2) {\n\t\t\ttmp += step\n\t\t\trow = setEdgeChar(row, tmp, '-')\n\t\t}\n\t\treturn row\n\t}\n\t// diagonal line\n\toffset := vertIdx + srcEdgeCenterOffset\n\t// calculate offset based on distance from the end in case we're on the bottom half of the edge\n\tif vertIdx > vertDist/2 {\n\t\toffset = adjustedXDist - (vertDist - offset)\n\t}\n\tif re.src > re.dest {\n\t\treturn setEdgeChar(row, re.src-offset, '/')\n\t} else {\n\t\treturn setEdgeChar(row, re.src+offset, '\\\\')\n\t}\n}", "func rprismIntersects(q *rprismIntersectQ) (float64, bool) {\n\tt := (q.bcPlane - q.v[0]) / q.d[0]\n\tif t < 0 {\n\t\treturn 0, false\n\t}\n\tb := q.v[1] + t*q.d[1]\n\tc := q.v[2] + t*q.d[2]\n\tif b >= q.minB && b <= q.maxB && c >= q.minC && c <= q.maxC {\n\t\treturn t, true\n\t}\n\treturn 0, false\n}", "func MOVWLZX(mr, r operand.Op) { ctx.MOVWLZX(mr, r) }", "func (v ivec2) readingLess(v1 ivec2) bool {\n\tif v.y == v1.y {\n\t\treturn v.x < v1.x\n\t}\n\treturn v.y < v1.y\n}", "func VORPD(ops ...operand.Op) { ctx.VORPD(ops...) }", "func DrawVLine(m draw.Image, x, y1, y2 int) {\n\tfor ; y1 <= y2; y1++ {\n\t\tm.Set(x, y1, color.RGBA{0, 0, 255, 255})\n\t}\n}", "func matchPositionInAxis(axis int, draw bool, from *Node, to *Node) {\n\tnodeName := from.Id\n\tfromX := from.CurrLoc.X\n\tfromY := from.CurrLoc.Y\n\ttoX := to.CurrLoc.X\n\ttoY := to.CurrLoc.Y\n\n\tnodeTrail := \"\"\n\tif draw {\n\t\tnodeTrail = \"t\" + nodeName[len(nodeName)-1:]\n\t}\n\n\tnodePlayer := getPlayerState(from.Id)\n\n\tif axis == AXIS_X { // Match X axis.\n\t\ti := fromX\n\t\tincrement := -1\n\t\tif toX > fromX {\n\t\t\tincrement = 1\n\t\t}\n\t\tfor i != toX {\n\t\t\tboard[fromY][i] = nodeTrail\n\t\t\ti = increment + i\n\t\t}\n\t\tboard[fromY][i] = nodePlayer\n\t\tfrom.CurrLoc.X = toX\n\t} else { // Match Y axis.\n\t\ti := fromY\n\t\tincrement := -1\n\t\tif toY > fromY {\n\t\t\tincrement = 1\n\t\t}\n\t\tfor i != toY {\n\t\t\tboard[fromY][i] = nodeTrail\n\t\t\ti = increment + i\n\t\t}\n\t\tboard[i][fromX] = nodePlayer\n\t\tfrom.CurrLoc.Y = toY\n\t}\n}", "func (llrb *LLRB) moveredright(nd *Llrbnode) *Llrbnode {\n\tllrb.flip(nd)\n\tif nd.left.left.isred() {\n\t\tnd = llrb.rotateright(nd)\n\t\tllrb.flip(nd)\n\t}\n\treturn nd\n}", "func ROLB(ci, mr operand.Op) { ctx.ROLB(ci, mr) }", "func interleave(x, y uint32) uint64 {\n\treturn stripe(x) | (stripe(y) << 1)\n}", "func commitTo(H *ristretto.Point, r, x *ristretto.Scalar) ristretto.Point {\n\t//ec.g.mul(r).add(H.mul(x));\n\tvar result, rPoint, transferPoint ristretto.Point\n\trPoint.ScalarMultBase(r)\n\ttransferPoint.ScalarMult(H, x)\n\tresult.Add(&rPoint, &transferPoint)\n\treturn result\n}", "func drw(context *Context) {\n x := context.opcode & 0x0F00 >> 8\n y := context.opcode & 0x00F0 >> 4\n n := context.opcode & 0x000F\n vx, vy := int(context.cpu.v[x]), int(context.cpu.v[y])\n\n sprite := context.memory[context.cpu.i:context.cpu.i + n]\n\n // Xor screen with sprite\n // Clear VF and set to 1 if there is any pixel collision\n context.cpu.v[0xF] = 0\n for j := 0; j < len(sprite); j++ {\n for i := 0; i < 8; i++ {\n shift := uint(8 - i - 1)\n pixel := context.screen[(vx + i) % 64][(vy + j) % 32] ^ (sprite[j] >> shift) & 0x1\n context.screen[(vx + i) % 64][(vy + j) % 32] = pixel\n context.cpu.v[0xF] |= pixel\n }\n }\n\n if context.cpu.v[0xF] > 0 {\n context.window.Draw(&context.screen)\n }\n context.cpu.pc += 2\n}", "func inner(r0, r1, r2, r3, r4 int) (int, int, int, int, int) {\n\tfor {\n\t\tr1 = r2 & 255\n\t\tr3 += r1\n\t\tr3 &= 16777215\n\t\tr3 *= 65899\n\t\tr3 &= 16777215\n\t\tif 256 > r2 {\n\t\t\treturn r0, r1, r2, r3, r4\n\t\t}\n\t\tr2 = r2 / 256\n\t}\n}", "func MOVBEQQ(mr, mr1 operand.Op) { ctx.MOVBEQQ(mr, mr1) }", "func LEAW(m, r operand.Op) { ctx.LEAW(m, r) }", "func VBLENDVPS(xy, mxy, xy1, xy2 operand.Op) { ctx.VBLENDVPS(xy, mxy, xy1, xy2) }", "func (r Rect) Union(s Rect) Rect {\n\treturn R(\n\t\tmath.Min(r.Min.X, s.Min.X),\n\t\tmath.Min(r.Min.Y, s.Min.Y),\n\t\tmath.Max(r.Max.X, s.Max.X),\n\t\tmath.Max(r.Max.Y, s.Max.Y),\n\t)\n}", "func (ev *evaluator) vectorBinop(op itemType, lhs, rhs vector, matching *VectorMatching, returnBool bool) vector {\n\tif matching.Card == CardManyToMany {\n\t\tpanic(\"many-to-many only allowed for set operators\")\n\t}\n\tvar (\n\t\tresult = vector{}\n\t\tsigf = signatureFunc(matching.On, matching.MatchingLabels...)\n\t)\n\n\t// The control flow below handles one-to-one or many-to-one matching.\n\t// For one-to-many, swap sidedness and account for the swap when calculating\n\t// values.\n\tif matching.Card == CardOneToMany {\n\t\tlhs, rhs = rhs, lhs\n\t}\n\n\t// All samples from the rhs hashed by the matching label/values.\n\trightSigs := map[uint64]*sample{}\n\n\t// Add all rhs samples to a map so we can easily find matches later.\n\tfor _, rs := range rhs {\n\t\tsig := sigf(rs.Metric)\n\t\t// The rhs is guaranteed to be the 'one' side. Having multiple samples\n\t\t// with the same signature means that the matching is many-to-many.\n\t\tif _, found := rightSigs[sig]; found {\n\t\t\t// Many-to-many matching not allowed.\n\t\t\tev.errorf(\"many-to-many matching not allowed: matching labels must be unique on one side\")\n\t\t}\n\t\trightSigs[sig] = rs\n\t}\n\n\t// Tracks the match-signature. For one-to-one operations the value is nil. For many-to-one\n\t// the value is a set of signatures to detect duplicated result elements.\n\tmatchedSigs := map[uint64]map[uint64]struct{}{}\n\n\t// For all lhs samples find a respective rhs sample and perform\n\t// the binary operation.\n\tfor _, ls := range lhs {\n\t\tsig := sigf(ls.Metric)\n\n\t\trs, found := rightSigs[sig] // Look for a match in the rhs vector.\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Account for potentially swapped sidedness.\n\t\tvl, vr := ls.Value, rs.Value\n\t\tif matching.Card == CardOneToMany {\n\t\t\tvl, vr = vr, vl\n\t\t}\n\t\tvalue, keep := vectorElemBinop(op, vl, vr)\n\t\tif returnBool {\n\t\t\tif keep {\n\t\t\t\tvalue = 1.0\n\t\t\t} else {\n\t\t\t\tvalue = 0.0\n\t\t\t}\n\t\t} else if !keep {\n\t\t\tcontinue\n\t\t}\n\t\tmetric := resultMetric(ls.Metric, rs.Metric, op, matching)\n\n\t\tinsertedSigs, exists := matchedSigs[sig]\n\t\tif matching.Card == CardOneToOne {\n\t\t\tif exists {\n\t\t\t\tev.errorf(\"multiple matches for labels: many-to-one matching must be explicit (group_left/group_right)\")\n\t\t\t}\n\t\t\tmatchedSigs[sig] = nil // Set existence to true.\n\t\t} else {\n\t\t\t// In many-to-one matching the grouping labels have to ensure a unique metric\n\t\t\t// for the result vector. Check whether those labels have already been added for\n\t\t\t// the same matching labels.\n\t\t\tinsertSig := uint64(metric.Metric.Fingerprint())\n\t\t\tif !exists {\n\t\t\t\tinsertedSigs = map[uint64]struct{}{}\n\t\t\t\tmatchedSigs[sig] = insertedSigs\n\t\t\t} else if _, duplicate := insertedSigs[insertSig]; duplicate {\n\t\t\t\tev.errorf(\"multiple matches for labels: grouping labels must ensure unique matches\")\n\t\t\t}\n\t\t\tinsertedSigs[insertSig] = struct{}{}\n\t\t}\n\n\t\tresult = append(result, &sample{\n\t\t\tMetric: metric,\n\t\t\tValue: value,\n\t\t\tTimestamp: ev.Timestamp,\n\t\t})\n\t}\n\treturn result\n}", "func VPRORD(ops ...operand.Op) { ctx.VPRORD(ops...) }", "func (z *Int) Rem(x, y *Int) *Int {}", "func d4combineRect(rectA, rectB *d4rectT) d4rectT {\n\tvar newRect d4rectT\n\n\tfor index := 0; index < d4numDims; index++ {\n\t\tnewRect.min[index] = d4fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d4fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func d14combineRect(rectA, rectB *d14rectT) d14rectT {\n\tvar newRect d14rectT\n\n\tfor index := 0; index < d14numDims; index++ {\n\t\tnewRect.min[index] = d14fmin(rectA.min[index], rectB.min[index])\n\t\tnewRect.max[index] = d14fmax(rectA.max[index], rectB.max[index])\n\t}\n\n\treturn newRect\n}", "func XorBuffer(first []byte, second []byte) ([]byte, error) {\n\tif len(first) != len(second) {\n\t\treturn nil, errors.New(\"Buffers are not equal length\")\n\t}\n\n\toutput := make([]byte, len(first))\n\n\tfor idx := range first {\n\t\t// XOR operation\n\t\toutput[idx] = first[idx] ^ second[idx]\n\t}\n\n\treturn output, nil\n}", "func VPORQ(ops ...operand.Op) { ctx.VPORQ(ops...) }", "func unite(x int, y int) {\n\tx = find(x)\n\ty = find(y)\n\t// Same root = x and y belongs to same group\n\tif x == y {\n\t\treturn\n\t}\n\tif rank[x] < rank[y] {\n\t\tpar[x] = y\n\t} else {\n\t\tpar[y] = x\n\t\tif rank[x] == rank[y] {\n\t\t\trank[x]++\n\t\t}\n\t}\n}", "func SHRXQ(r, mr, r1 operand.Op) { ctx.SHRXQ(r, mr, r1) }", "func (z *Int) Xor(x, y *Int) *Int {}", "func RotateY(v magica.VoxelObject, angle float64) (r magica.VoxelObject) {\n\tsin, cos := math.Sin(degToRad(angle)), math.Cos(degToRad(angle))\n\n\torgMidpointX := float64(v.Size.X) / 2\n\torgMidpointZ := float64(v.Size.Z) / 2\n\n\txVector := (orgMidpointX * math.Abs(cos)) + (orgMidpointZ * math.Abs(sin))\n\tzVector := (orgMidpointX * math.Abs(sin)) + (orgMidpointZ * math.Abs(cos))\n\n\tsizeX, sizeZ := int(math.Ceil(xVector*2)), int(math.Ceil(zVector*2))\n\n\tr = magica.VoxelObject{\n\t\tVoxels: nil,\n\t\tPaletteData: v.PaletteData,\n\t\tSize: geometry.Point{X: sizeX, Y: v.Size.Y, Z: sizeZ},\n\t}\n\n\t// Create the voxel array\n\tr.Voxels = make([][][]byte, r.Size.X)\n\tfor x := 0; x < r.Size.X; x++ {\n\t\tr.Voxels[x] = make([][]byte, r.Size.Y)\n\t\tfor y := 0; y < r.Size.Y; y++ {\n\t\t\tr.Voxels[x][y] = make([]byte, r.Size.Z)\n\t\t}\n\t}\n\n\tvMidpointX := float64(v.Size.X) / 2\n\tvMidpointZ := float64(v.Size.Z) / 2\n\n\titerator := func(x, y, z int) {\n\n\t\tfdx := float64(x) - (float64(r.Size.X) / 2)\n\t\tfdz := float64(z) - (float64(r.Size.Z) / 2)\n\n\t\tfdx, fdz = (fdx*cos)+(fdz*sin), (fdx*-sin)+(fdz*cos)\n\n\t\tdx := int(math.Ceil(fdx + vMidpointX))\n\t\tdz := int(math.Ceil(fdz + vMidpointZ))\n\n\t\tif dx >= 0 && dz >= 0 && dx < v.Size.X && dz < v.Size.Z {\n\t\t\tr.Voxels[x][y][z] = v.Voxels[dx][y][dz]\n\t\t}\n\t}\n\n\tr.Iterate(iterator)\n\n\treturn r\n}" ]
[ "0.56870407", "0.568445", "0.5499482", "0.53922296", "0.53533536", "0.52216274", "0.52045697", "0.51982224", "0.5175856", "0.5156145", "0.5147845", "0.5140594", "0.51337403", "0.5102799", "0.51022923", "0.5071687", "0.50376266", "0.5028927", "0.5028031", "0.5018365", "0.5015546", "0.5010175", "0.49897903", "0.4984129", "0.49796343", "0.49789265", "0.49567664", "0.4948648", "0.4947384", "0.49274793", "0.49165824", "0.4913757", "0.49124914", "0.490092", "0.48966432", "0.48932737", "0.48672593", "0.4865026", "0.48619273", "0.48615307", "0.48523265", "0.4849424", "0.48374182", "0.48341924", "0.48336348", "0.48213488", "0.481988", "0.4814192", "0.48042336", "0.48037085", "0.4802268", "0.48004875", "0.4798711", "0.47851408", "0.4771454", "0.47695234", "0.47631517", "0.47619194", "0.47550413", "0.47530398", "0.47530144", "0.47481182", "0.47437906", "0.47409925", "0.47401053", "0.4738045", "0.47363973", "0.47299218", "0.47296765", "0.47250122", "0.4721952", "0.47143638", "0.47136602", "0.47090426", "0.47081414", "0.47050983", "0.47050053", "0.46991873", "0.46972203", "0.46923813", "0.46919754", "0.4691199", "0.46856004", "0.4685599", "0.46824312", "0.46807516", "0.46806648", "0.46738446", "0.46567547", "0.4656665", "0.46496853", "0.46488506", "0.46488202", "0.46336532", "0.46313304", "0.46300507", "0.46261168", "0.4624892", "0.46248823", "0.46242306", "0.46182498" ]
0.0
-1
IntKeysToSortedArray is like StringKeysToSortedArray, but more idiomatic. It too is inapplicable to any other typed map
func IntKeysToSortedArray(m map[int]interface{}) (keys []int) { keys = make([]int, 0, len(m)) for key, _ := range m { keys = append(keys, key) } sort.Ints(keys) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func IntegerFieldToSortedArray(m []interface{}, fieldName string) (vKeys []int) {\n\tif len(m) > 1000 {\n\t\tpanic(\"this uses reflection - not for large structs\")\n\t}\n\tvKeys = make([]int, len(m))\n\tfor i, iface := range m {\n\t\tvKeys[i] = GetIntField(iface, fieldName)\n\t}\n\tsort.Ints(vKeys)\n\treturn\n}", "func sortedKeys(v any) []any {\n\tkeys := reflect.ValueOf(v).MapKeys()\n\tsort.Slice(keys, func(i, j int) bool {\n\t\ta := keys[i].Convert(u32).Interface().(uint32)\n\t\tb := keys[j].Convert(u32).Interface().(uint32)\n\t\treturn a < b\n\t})\n\tvals := make([]any, len(keys))\n\tfor i, key := range keys {\n\t\tvals[i] = key.Interface()\n\t}\n\treturn vals\n}", "func SortedKeys(i interface{}) []string {\n\tvMap := reflect.ValueOf(i)\n\tvKeys := vMap.MapKeys()\n\tkeys := make([]string, len(vKeys), len(vKeys))\n\tidx := 0\n\tfor _,vKey := range vKeys {\n\t\tkeys[idx] = vKey.String()\n\t\tidx++\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}", "func SortedMapKeys(m map[string]interface{}) (keyList []string) {\n\tfor key := range m {\n\t\tkeyList = append(keyList, key)\n\t}\n\tsort.Strings(keyList)\n\treturn\n}", "func sortMap(distributionMap map[int]int) []int {\n\tvar keys = make([]int, 10)\n\tfor k := range distributionMap {\n\t\tkeys[k] = k\n\t}\n\tsort.Ints(keys)\n\tkeys = removeIndex(keys, 0)\n\treturn keys\n}", "func sortKeys(m map[int]int) []int {\r\n\t// TODO: Implement sortKeys function.\r\n\tkeys:= make([]int,0,len(m))\r\n\tfor k := range m {\r\n\t\tkeys = append(keys,k)\r\n\t}\r\n su:=SortUser{m,keys}\r\n sort.Sort(&su)\r\n\treturn su.Keys\r\n}", "func SortedKeys(m map[string]interface{}) []string {\n\tkeys := Keys(m)\n\tsort.Strings(keys)\n\treturn keys\n}", "func sortedMapKeys(m *jsonschema.Index) []string {\n\tvar keys []string\n\tfor k, _ := range *m {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}", "func MapKey2Array(source map[string]string) []string {\n\tvar list []string\n\tfor k := range source {\n\t\tlist = append(list, k)\n\t}\n\treturn list\n}", "func GetSortedKeySlice(m map[string]string) []string {\n\tkeys := make([]string, 0)\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Sort(sort.StringSlice(keys))\n\treturn keys\n}", "func getSortedKeys(m map[string]string) []string {\n\tkeys := make([]string, 0, len(m))\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}", "func convertMapKeysToSlice(value map[string]string) []string {\n\tkeys := make([]string, len(value))\n\n\ti := 0\n\tfor k := range value {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\n\treturn keys\n}", "func orderStringKeys(m map[string]string) []string {\n\tret := make([]string, len(m))\n\ti := 0\n\n\tfor k := range m {\n\t\tret[i] = k\n\t\ti++\n\t}\n\tsort.Sort(sort.Reverse(sort.StringSlice(ret)))\n\treturn ret\n}", "func SortedKeys[K constraints.Ordered, V any](m map[K]V) []K {\n\t// sort\n\tkeys := maps.Keys(m)\n\tslices.Sort(keys)\n\n\treturn keys\n}", "func sortMapKeys(m map[string]string) []string {\n\tkeys := make([]string, len(m))\n\ti := 0\n\tfor k, _ := range m {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}", "func sortMap(m map[string]string) []string {\r\n keys := make([]string, 0)\r\n for name, _ := range m {\r\n keys = append(keys, name)\r\n }\r\n sort.Strings(keys)\r\n return keys\r\n}", "func SortedValues(i interface{}) []interface{} {\n\tm, ok := i.(map[string]interface{})\n\tif !ok {\n\t\tFatalf(\"SortedValues: expected map[string]interface{}, didn't get it\")\n\t}\n\tmapping := map[string]string{} // sort key: original key\n\tfor name, element := range m {\n\t\tsubmap, ok := element.(map[string]interface{})\n\t\tif !ok {\n\t\t\tmapping[name] = name\n\t\t\tcontinue\n\t\t}\n\t\tsortkey, ok := submap[\"sortkey\"]\n\t\tif !ok {\n\t\t\tmapping[name] = name\n\t\t\tcontinue\n\t\t}\n\t\tsortkeyString, ok := sortkey.(string)\n\t\tif !ok {\n\t\t\tmapping[name] = name\n\t\t\tcontinue\n\t\t}\n\t\tmapping[sortkeyString] = name\n\t}\n\n\tsortkeys := stringSlice{}\n\tfor sortkey, _ := range mapping {\n\t\tsortkeys = append(sortkeys, sortkey)\n\t}\n\tsort.Sort(sortkeys)\n\n\torderedValues := []interface{}{}\n\tfor _, k := range sortkeys {\n\t\torderedValues = append(orderedValues, m[mapping[k]])\n\t}\n\treturn orderedValues\n}", "func sortKeys(vals map[string]counter) (keys []string) {\n\tfor k := range vals {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\treturn keys\n}", "func sortKeys(v []reflect.Value) []reflect.Value {\n\tif len(v) <= 1 {\n\t\treturn v\n\t}\n\tswitch v[0].Kind() {\n\tcase reflect.Float32, reflect.Float64:\n\t\tsort.Sort(rvFloats{v})\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tsort.Sort(rvInts{v})\n\tcase reflect.String:\n\t\tsort.Sort(rvStrings{v})\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\tsort.Sort(rvUints{v})\n\t}\n\treturn v\n}", "func Keys(a interface{}) interface{} {\n\tkeys := reflect.ValueOf(a).MapKeys()\n\ttyp := reflect.TypeOf(a).Key()\n\n\t// Create result slice.\n\tresultValue := reflect.MakeSlice(reflect.SliceOf(typ),\n\t\tlen(keys), len(keys))\n\tfor i := range keys {\n\t\tresultValue.Index(i).Set(keys[i])\n\t}\n\tresult := resultValue.Interface()\n\tsortSlice(result) // Sort result, for consistency.\n\treturn result\n}", "func orderedKeys(kv map[string]interface{}) []string {\n\tfirst_keys := make([]string, len(keyOrder))\n\tkeys := make([]string, 0, len(kv))\n\n\tfor key := range kv {\n\t\tif index, found := keyOrder[key]; found {\n\t\t\tfirst_keys[index] = key\n\t\t} else {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t}\n\tsort.Strings(keys)\n\treturn append(removeEmptyStrings(first_keys, len(kv)), keys...)\n}", "func (e *Expr) sortedMapKeys(env *values.Env) []*Expr {\n\tvar keys []*Expr\n\tfor k := range e.Map {\n\t\tkeys = append(keys, k)\n\t}\n\tsortExprs(env, keys)\n\treturn keys\n}", "func SortMapByIntValue(inputMap map[string]int) PairListInt {\n\tpairList := make(PairListInt, 0, len(inputMap))\n\tfor k, v := range inputMap {\n\t\tpairList = append(pairList, PairInt{k, v})\n\t}\n\tsort.Sort(pairList)\n\treturn pairList\n}", "func sortKeys(m map[byte]*Node) []byte {\n\tkeys := make([]byte, 0, len(m))\n\tfor k := range m {\n\t\tkeys = append(keys, k)\n\t}\n\n\tsort.Slice(keys, func(i, j int) bool {\n\t\treturn keys[i] < keys[j]\n\t})\n\n\treturn keys\n}", "func (m Map) orderedKeys() []string {\n\tkeys := []string{}\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}", "func SortedKeys(m map[string]*Schema) (keys []string) {\n\tunorderedKeys := make([]string, 0)\n\torderedProperties := propertyOrderedKeys{}\n\n\tfor key := range m {\n\t\tif m[key].PropertyOrder == 0 {\n\t\t\tunorderedKeys = append(unorderedKeys, key)\n\t\t} else {\n\t\t\torderedProperties = append(orderedProperties, propertyOrderedKey{\n\t\t\t\tkey: key,\n\t\t\t\tpropertyOrder: m[key].PropertyOrder,\n\t\t\t})\n\t\t}\n\t}\n\n\t// sort unordered keys first\n\tsort.Strings(unorderedKeys)\n\n\t// sort order given properties\n\tsort.Sort(orderedProperties)\n\n\t// conbine them\n\treturn orderedProperties.prependKeysTo(unorderedKeys)\n}", "func mapKeys[K comparable, V any](m map[K]V) []K {\n\tks := make([]K, 0, len(m))\n\tfor k := range m {\n\t\tks = append(ks, k)\n\t}\n\treturn ks\n}", "func StringsMapKeys(data map[string]string) []string {\n\tkeys := make([]string, len(data))\n\ti := 0\n\tfor k := range data {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\n\tsort.Strings(keys)\n\n\treturn keys\n}", "func (m *OrderedIntMap) Keys() []int { return m.keys }", "func stringKeys(m map[string]interface{}) []string {\n\tvar ss []string\n\tfor k := range m {\n\t\tss = append(ss, k)\n\t}\n\treturn ss\n}", "func sortMap(m map[string]float64) []string {\n\tss := &storySlice{\n\t\tm: m,\n\t\tarr: make([]string, 0, len(m)),\n\t}\n\tfor k := range m {\n\t\tss.arr = append(ss.arr, k)\n\t}\n\tsort.Sort(ss)\n\treturn ss.arr\n}", "func TestMapKeys(t *testing.T) {\n\t// For an uninitialized map, an empty slice should be returned.\n\tvar nilMap map[uint]bool\n\treflect.DeepEqual(MapKeys(nilMap).([]uint), []uint{})\n\treflect.DeepEqual(MapKeys(map[string]struct{}{\"a\": {}}).([]string), []string{\"a\"})\n\t// Multiple elements need to be sorted to check equality.\n\tm := map[int]string{9: \"Hola\", 1: \"Señor\", 2: \"Espencie\"}\n\tsort.Ints(MapKeys(m).([]int))\n\treflect.DeepEqual(m, []int{1, 2, 9})\n}", "func (i IntHashMap[T, V]) Keys() []T {\n\tresult := make([]T, 0, len(i.hashToKey))\n\tfor _, key := range i.hashToKey {\n\t\tresult = append(result, key)\n\t}\n\treturn result\n}", "func (m *OrderedUintMap) Keys() []uint { return m.keys }", "func IntToKeys(v int) Keys {\n\tk := Keys{}\n\tfor _, c := range fmt.Sprintf(\"%d\", v) {\n\t\tk = append(k, keymap[c])\n\t}\n\treturn k\n}", "func (c *Scratch) GetSortedMapValues(key string) any {\n\tc.mu.RLock()\n\n\tif c.values[key] == nil {\n\t\tc.mu.RUnlock()\n\t\treturn nil\n\t}\n\n\tunsortedMap := c.values[key].(map[string]any)\n\tc.mu.RUnlock()\n\tvar keys []string\n\tfor mapKey := range unsortedMap {\n\t\tkeys = append(keys, mapKey)\n\t}\n\n\tsort.Strings(keys)\n\n\tsortedArray := make([]any, len(unsortedMap))\n\tfor i, mapKey := range keys {\n\t\tsortedArray[i] = unsortedMap[mapKey]\n\t}\n\n\treturn sortedArray\n}", "func sortMapByKey(hm map[string]string) []string {\n\tvar s []string\n\tfor key := range hm {\n\t\ts = append(s, key)\n\t}\n\n\tsort.Strings(s)\n\n\tout := make([]string, len(hm))\n\tfor i, hash := range s {\n\t\tout[i] = hm[hash]\n\t}\n\n\treturn out\n}", "func MapKeys(m interface{}) interface{} {\n\tv := vof(m)\n\tfailP1OnErrWhen(v.Kind() != reflect.Map, \"%v\", fEf(\"PARAM_INVALID_MAP\"))\n\n\tkeys := v.MapKeys()\n\tif L := len(keys); L > 0 {\n\t\tkType := tof(keys[0].Interface())\n\t\trstValue := mkSlc(sof(kType), L, L)\n\t\tfor i, k := range keys {\n\t\t\trstValue.Index(i).Set(vof(k.Interface()))\n\t\t}\n\t\t// sort keys if keys are int or float64 or string\n\t\trst := rstValue.Interface()\n\t\tswitch keys[0].Interface().(type) {\n\t\tcase int:\n\t\t\tsort.Ints(rst.([]int))\n\t\tcase float64:\n\t\t\tsort.Float64s(rst.([]float64))\n\t\tcase string:\n\t\t\tsort.Strings(rst.([]string))\n\t\t}\n\t\treturn rst\n\t}\n\treturn nil\n}", "func getKeysAlphabetically(labels map[string]string) []string {\n\tvar keys []string\n\tfor k := range labels {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}", "func Keys[K comparable, V any](in map[K]V) []K {\n\tresult := make([]K, 0, len(in))\n\n\tfor k := range in {\n\t\tresult = append(result, k)\n\t}\n\n\treturn result\n}", "func sortedMapKeysbyName(m *jsonschema.Index) []string {\n\tvar schemas []*jsonschema.Schema\n\tfor _, v := range *m {\n\t\tschemas = append(schemas, v)\n\t}\n\tsort.Sort(byName(schemas))\n\n\tvar keys []string\n\tfor _, v := range schemas {\n\t\tkeys = append(keys, v.Pointer)\n\t}\n\treturn keys\n}", "func keys(m map[string]int32) []string {\n\tkeys := make([]string, len(m))\n\ti := 0\n\tfor k := range m {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\treturn keys\n}", "func CompositeKeysToArray(keys []*dparval.Value) []byte {\n\tsecKey := dparval.NewValue(make([]interface{}, len(keys)))\n\tfor i, key := range keys {\n\t\tsecKey.SetIndex(i, key)\n\t}\n\treturn secKey.Bytes()\n}", "func newSortKeys() SortKeys {\n\treturn []sortKey{}\n}", "func (i StringHashMap[T, V]) Keys() []T {\n\tresult := make([]T, 0, len(i.hashToKey))\n\tfor _, key := range i.hashToKey {\n\t\tresult = append(result, key)\n\t}\n\treturn result\n}", "func (self *Map) StringKeys(tagName ...string) []string {\n\treturn sliceutil.Stringify(self.Keys(tagName...))\n}", "func (o *Aliyun) makeDictionarySort(arr map[string][]string) ([]string, map[string][]string) {\n\tkeys := make([]string, len(arr))\n\ti := 0\n\tfor k := range arr {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\tsort.Strings(keys)\n\treturn keys, arr\n}", "func getSortedKeys(modules map[string]*TerraformModule) []string {\n\tkeys := []string{}\n\tfor key := range modules {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Strings(keys)\n\n\treturn keys\n}", "func keys(m map[int]struct{}) []int {\n\ts := make([]int, 0, len(m))\n\tfor id := range m {\n\t\ts = append(s, id)\n\t}\n\treturn s\n}", "func MapKeys(rec map[string]interface{}) []string {\n\tkeys := make([]string, 0, len(rec))\n\tfor k := range rec {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}", "func (mm Uint64Uint64Map) OrderedSlice(keys Uint64List) Uint64Uint64Tuples {\n\ts := make(Uint64Uint64Tuples, 0, len(mm))\n\tfor _, k := range keys {\n\t\tv, found := mm[k]\n\t\tif found {\n\t\t\ts = append(s, Uint64Uint64Tuple{k, v})\n\t\t}\n\t}\n\treturn s\n}", "func SortMap(mp map[string]int) map[string]int {\n\tvar newMp = make([]int, 0)\n\tvar newMpKey = make([]string, 0)\n\n\tvar newMap map[string]int = make(map[string]int)\n\n\tfor oldk, v := range mp {\n\t\tnewMp = append(newMp, v)\n\t\tnewMpKey = append(newMpKey, oldk)\n\t}\n\tsort.Ints(newMp)\n\tfmt.Println(newMp)\n\tfor k, v := range newMp {\n\t\t// fmt.Printf(\"根据value排序后的新集合为:%v: [%v]=%v \\n\", k, newMpKey[k], v)\n\t\tnewMap[newMpKey[k]] = v\n\t}\n\n\treturn newMap\n}", "func (m *Map) Keys() []string {\n\tm.convert()\n\tif len(m.order) > 0 {\n\t\treturn m.order\n\t}\n\n\tresult := make([]string, len(m.items))\n\ti := 0\n\tfor key := range m.items {\n\t\tresult[i] = key\n\t\ti = i + 1\n\t}\n\n\tm.order = result\n\n\treturn result\n}", "func (s *Store) getKeysSortedByRank() (result []string) {\n\ttype pair struct {\n\t\tid string\n\t\trank int\n\t}\n\tsorting := make([]pair, 0)\n\n\tfor key, entry := range *s {\n\t\tsorting = append(sorting, pair{key, entry.rank()})\n\t}\n\n\tsort.Slice(sorting, func(i, j int) bool {\n\t\treturn sorting[i].rank < sorting[j].rank\n\t})\n\n\tresult = make([]string, 0)\n\tfor _, sortingEntry := range sorting {\n\t\tresult = append(result, sortingEntry.id)\n\t}\n\n\treturn result\n}", "func (m StringMap) MapSort() []string {\n\tvar keys []string\n\tfor k := range m {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}", "func NewLevelSliceKeySorted(cmp base.Compare, files []*FileMetadata) LevelSlice {\n\ttr, slice := makeBTree(btreeCmpSmallestKey(cmp), files)\n\ttr.Release()\n\tslice.verifyInvariants()\n\treturn slice\n}", "func Keys[K comparable, V any](m map[K]V) []K {\n\tr := make([]K, 0, len(m))\n\tfor k := range m {\n\t\tr = append(r, k)\n\t}\n\treturn r\n}", "func Keys(m map[string]string) []string {\n\tr := []string{}\n\n\tfor k := range m {\n\t\tr = append(r, k)\n\t}\n\n\tsort.Strings(r)\n\n\treturn r\n}", "func sortEntries(entries map[int]string) ([]string, []int) {\n\t// Sort the entries in order\n\tvar keys []int\n\tfor k := range entries {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Ints(keys)\n\n\tentriesInOrder := []string{}\n\tgtsInOrder := []int{}\n\tfor _, k := range keys {\n\t\tentriesInOrder = append(entriesInOrder, entries[k])\n\t\tgtsInOrder = append(gtsInOrder, k)\n\t}\n\tlogger.Debug(\"Sorted %d entries.\", len(entriesInOrder))\n\treturn entriesInOrder, gtsInOrder\n}", "func StringMapToSlice(in map[string]string) []string {\n\tret := []string{}\n\n\tfor _, val := range in {\n\t\tret = append(ret, val)\n\t}\n\n\tsort.Strings(ret)\n\n\treturn ret\n\n}", "func MapToSortedStrings(m map[string]bool) []string {\n\tstrs := make([]string, 0, len(m))\n\tfor s := range m {\n\t\tstrs = append(strs, s)\n\t}\n\tsort.Strings(strs)\n\treturn strs\n}", "func (self *Map) Keys(tagName ...string) []interface{} {\n\treturn Keys(self.MapNative(tagName...))\n}", "func (s *set) Sorted() *Array {\n\tcpy := make([]*Term, len(s.keys))\n\tcopy(cpy, s.sortedKeys())\n\treturn NewArray(cpy...)\n}", "func sortMapByKeyVals(keys, vals []reflect.Value) {\n\tif len(keys) != len(vals) {\n\t\tpanic(\"invalid map key val slice pair\")\n\t}\n\tif len(keys) == 0 {\n\t\treturn\n\t}\n\tsort.Sort(&mapSorter{keys: keys, vals: vals})\n}", "func IntSlice(k string, v []int) KeyValue {\n\treturn Key(k).IntSlice(v)\n}", "func (s *Store) GetKeysSortedByName() (result []string) {\n\tresult = make([]string, 0)\n\n\tfor key := range *s {\n\t\tresult = append(result, key)\n\t}\n\n\tsort.Strings(result)\n\n\treturn result\n}", "func FromSortedKeysAndValues(keys []string, values []interface{}) ByteMap {\n\treturn Build(func(cb func(string, interface{})) {\n\t\tfor i, key := range keys {\n\t\t\tcb(key, values[i])\n\t\t}\n\t}, nil, true)\n}", "func MapKeyAsStrings(m interface{}) []string {\n\tkeys := reflect.ValueOf(m).MapKeys()\n\tres := make([]string, len(keys))\n\tfor i, key := range keys {\n\t\tres[i] = key.String()\n\t}\n\treturn res\n}", "func KeysStr(m map[string]string) []string {\n\tkeys := make([]string, 0, len(m))\n\tfor k := range m {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}", "func SortMapByValueAsc(m map[string]int) PairList {\n\tp := make(PairList, len(m))\n\ti := 0\n\tfor k, v := range m {\n\t\tp[i] = Pair{k, v}\n\t}\n\tsort.Sort(p)\n\treturn p\n}", "func FromMap(m map[string]interface{}) []interface{} {\n\tif len(m) == 0 {\n\t\treturn make([]interface{}, 0)\n\t}\n\n\tkeyvals := make([]interface{}, len(m)*2)\n\ti := 0\n\n\tfor key, value := range m {\n\t\tkeyvals[i] = key\n\t\tkeyvals[i+1] = value\n\n\t\ti += 2\n\t}\n\n\treturn keyvals\n}", "func SortMapByValue(input map[int]int, reverse bool) IndexedIntList {\n\tpl := make(IndexedIntList, len(input))\n\ti := 0\n\tfor k, v := range input {\n\t\tpl[i] = IndexedInt{k, v}\n\t\ti++\n\t}\n\tif reverse {\n\t\tsort.Sort(sort.Reverse(pl))\n\t} else {\n\t\tsort.Sort(pl)\n\t}\n\treturn pl\n}", "func orderStackGroupKeys(m map[string]StackGroup) []string {\n\tret := make([]string, len(m))\n\ti := 0\n\n\tfor k := range m {\n\t\tret[i] = k\n\t\ti++\n\t}\n\tsort.Sort(sort.Reverse(sort.StringSlice(ret)))\n\treturn ret\n}", "func (m *OrderedMap) Keys() []string { return m.keys }", "func NewOrderedIntMap() *OrderedIntMap {\n\treturn &OrderedIntMap{\n\t\tkeys: make([]int, 0),\n\t\tm: make(map[int]interface{}),\n\t}\n}", "func (self *Encoder) SortKeys() *Encoder {\n self.Opts |= SortMapKeys\n return self\n}", "func Ints(a []int) { Sort(IntSlice(a)) }", "func keys(m map[string][]string) []string {\n\tres := make([]string, len(m))\n\tfor k := range m {\n\t\tres = append(res, string(k))\n\t}\n\treturn res\n}", "func keys(dict interface{}) interface{} {\n var m = dict.(map[interface{}]interface{})\n var keys = make([]interface{}, 0, len(m))\n for k := range m {\n keys = append(keys, k)\n }\n return keys\n}", "func uint16IntPairSort(m map[uint16]int) uint16IntPairList {\n\tp := make(uint16IntPairList, len(m))\n\ti := 0\n\tfor k, v := range m {\n\t\tp[i] = uint16IntPair{k, v}\n\t\ti++\n\t}\n\tsort.Sort(p)\n\treturn p\n}", "func (o *OrderedMap) SortKeys(sortFunc func(keys []string)) {\n\tsortFunc(o.keys)\n}", "func (p *SliceOfMap) ToInts() (slice []int) {\n\treturn ToIntSlice(p.O()).G()\n}", "func getMapToSlice(inMap map[int]bool) docList {\n\tvar retSlice docList\n\tfor k, _ := range inMap {\n\t\tretSlice = append(retSlice, k)\n\t}\n\tsort.Sort(retSlice)\n\treturn retSlice\n}", "func MapKeys[K comparable, V any, R comparable](in map[K]V, iteratee func(V, K) R) map[R]V {\n\tresult := map[R]V{}\n\n\tfor k, v := range in {\n\t\tresult[iteratee(v, k)] = v\n\t}\n\n\treturn result\n}", "func mapToKeyValueStrings(pairs map[string]string) []string {\n\tresult := make([]string, len(pairs))\n\ti := 0\n\tfor key, value := range pairs {\n\t\tresult[i] = key + \"=\" + value\n\t\ti++\n\t}\n\n\treturn result\n}", "func StringSliceToMapKeys(s []string) map[string]bool {\n\tret := map[string]bool{}\n\tfor _, v := range s {\n\t\tret[v] = true\n\t}\n\treturn ret\n}", "func orderStackIconKeys(m map[string]*v1alpha1.IconSpec) []string {\n\tret := make([]string, len(m))\n\ti := 0\n\n\tfor k := range m {\n\t\tret[i] = k\n\t\ti++\n\t}\n\tsort.Sort(sort.Reverse(sort.StringSlice(ret)))\n\treturn ret\n}", "func SortMap(m map[int]float64) []float64 {\n\tvalues := []float64{}\n\tfor _, value := range m {\n\t\tvalues = append(values, value)\n\t}\n\n\tsort.Slice(values, func(i, j int) bool {\n\t\treturn values[i] < values[j]\n\t})\n\treturn values\n}", "func (tx *Tx) KeysSorted(rev bool) []string {\n\tkeys := tx.Keys()\n\tif rev {\n\t\tsort.Sort(sort.Reverse(sort.StringSlice(keys)))\n\t} else {\n\t\tsort.Sort(sort.StringSlice(keys))\n\t}\n\treturn keys\n}", "func keys(m map[string]string) []string {\n\tvar keys []string\n\tfor k := range m {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}", "func orderStackResourceKeys(m map[string]StackResource) []string {\n\tret := make([]string, len(m))\n\ti := 0\n\n\tfor k := range m {\n\t\tret[i] = k\n\t\ti++\n\t}\n\tsort.Sort(sort.Reverse(sort.StringSlice(ret)))\n\treturn ret\n}", "func (arr *Array) Sorted() *Array {\n\tcpy := make([]*Term, len(arr.elems))\n\tfor i := range cpy {\n\t\tcpy[i] = arr.elems[i]\n\t}\n\tsort.Sort(termSlice(cpy))\n\ta := NewArray(cpy...)\n\ta.hashs = arr.hashs\n\treturn a\n}", "func MapToStrArray(m map[string]bool) []string {\n\ts := []string{}\n\tfor k := range m {\n\t\ts = append(s, k)\n\t}\n\n\treturn s\n}", "func FromSortedKeysAndFloats(keys []string, values []float64) ByteMap {\n\treturn Build(func(cb func(string, interface{})) {\n\t\tfor i, key := range keys {\n\t\t\tcb(key, values[i])\n\t\t}\n\t}, nil, true)\n}", "func sortMapByValue(m map[string]int) PairList {\r\n\tp := make(PairList, len(m))\r\n\ti := 0\r\n\tfor k, v := range m {\r\n\t\tp[i] = Pair{k, v}\r\n\t\ti++\r\n\t}\r\n\tsort.Sort(p)\r\n\treturn p\r\n}", "func orderStackCRDKeys(m map[string]apiextensions.CustomResourceDefinition) []string {\n\tret := make([]string, len(m))\n\ti := 0\n\n\tfor k := range m {\n\t\tret[i] = k\n\t\ti++\n\t}\n\tsort.Sort(sort.Reverse(sort.StringSlice(ret)))\n\treturn ret\n}", "func SortUints(a []uint) { sort.Sort(UintSlice(a)) }", "func SortedSchema(m map[string]*Schema) []*Schema {\n\tkeys := SortedKeys(m)\n\tss := make([]*Schema, len(m))\n\tfor i, k := range keys {\n\t\tss[i] = m[k]\n\t}\n\n\treturn ss\n}", "func (p OrderedMap) Keys() []interface{} {\n\treturn p.keys\n}", "func (m pbMetricMap) Keys() []string {\n\tkeys := make([]string, 0, len(m))\n\tfor k := range m {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}" ]
[ "0.7191739", "0.6965093", "0.66392714", "0.6519681", "0.6447743", "0.6400126", "0.6366391", "0.63271403", "0.6317922", "0.6162785", "0.61023504", "0.60431767", "0.5971988", "0.5960882", "0.59603155", "0.5925237", "0.58889574", "0.5844888", "0.5821268", "0.58011353", "0.57600725", "0.57507616", "0.57255507", "0.5709392", "0.56798124", "0.56618166", "0.5646171", "0.55880463", "0.5574259", "0.5568005", "0.55608606", "0.55597526", "0.555915", "0.5555298", "0.55503654", "0.55351317", "0.55174243", "0.550285", "0.54910773", "0.54374367", "0.5422196", "0.5390124", "0.5378632", "0.5372085", "0.5371019", "0.53450745", "0.53388256", "0.53377396", "0.5336848", "0.5317406", "0.5308416", "0.5276761", "0.5274523", "0.52685004", "0.5255563", "0.52486664", "0.52429885", "0.5235121", "0.5220607", "0.52116364", "0.5207818", "0.52047074", "0.52044266", "0.5203758", "0.52031744", "0.51939464", "0.51896584", "0.51766026", "0.5167277", "0.51598084", "0.51573366", "0.5129201", "0.5127085", "0.5112569", "0.50839615", "0.50745237", "0.5073521", "0.5073126", "0.50648445", "0.50520295", "0.5047304", "0.5043033", "0.5029466", "0.5028828", "0.5021515", "0.50090146", "0.5005296", "0.49962807", "0.4995622", "0.49656847", "0.49656436", "0.49603444", "0.49378842", "0.49333277", "0.4928951", "0.49245152", "0.4913836", "0.49095467", "0.49039832", "0.48920768" ]
0.8091329
0
generic approach I dont like it because of the O(n) reflecion
func IntegerFieldToSortedArray(m []interface{}, fieldName string) (vKeys []int) { if len(m) > 1000 { panic("this uses reflection - not for large structs") } vKeys = make([]int, len(m)) for i, iface := range m { vKeys[i] = GetIntField(iface, fieldName) } sort.Ints(vKeys) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func collect(n *Node, i *int, result *[]int64) {\n\tif n == nil {\n\t\treturn\n\t}\n\n\t// append existing values\n\tfor v := range n.val {\n\t\tif *i == 0 {\n\t\t\treturn\n\t\t}\n\t\t*i--\n\t\t*result = append(*result, v)\n\t}\n\n\t// sort keys\n\tsortedKeys := sortKeys(n.children)\n\tfor _, k := range sortedKeys {\n\t\tcurr := n.children[k]\n\t\tcollect(curr, i, result)\n\t}\n}", "func finder(result, n []Node, p Node, id int64) []Node {\n\tif len(result) > 0 {\n\t\treturn result\n\t}\n\tfor _, node := range n {\n\t\tif node.ID == id {\n\t\t\tresult = append(result, node)\n\t\t\treturn result\n\t\t}\n\t\tif len(node.Nodes) > 0 {\n\t\t\tfinder(result, node.Nodes, node, id)\n\t\t}\n\t}\n\treturn n\n}", "func sol2(nums []int, target int) []int {\n\tmemo := make(map[int]int)\n\tfor i, n := range nums {\n\t\tmemo[n] = i\n\t}\n\tfor i, n := range nums {\n\t\tif _, ok := memo[target-n]; ok && i != memo[target-n] {\n\t\t\treturn []int{i, memo[target-n]}\n\t\t}\n\t}\n\treturn nil\n}", "func (sc gloomList) optimize(i *Interpreter) (Reference, error) {\n\tfor idx := 0; idx < len(sc.Elems); idx++ {\n\t\tswitch v := sc.Elems[idx].(type) {\n\t\tcase gloomList:\n\t\t\tsubref, err := v.optimize(i)\n\t\t\tif err != nil {\n\t\t\t\treturn Reference(0), err\n\t\t\t}\n\n\t\t\tsc.Elems[idx] = subref\n\n\t\tcase literal:\n\t\t\targ := argMatch.FindStringSubmatch(string(v))\n\t\t\tswitch len(arg) {\n\t\t\tcase 0:\n\t\t\tcase 2:\n\t\t\t\targIdx, err := strconv.ParseInt(arg[1], 0, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn Reference(0), err\n\t\t\t\t}\n\n\t\t\t\tsc.Elems[idx] = argument(argIdx)\n\n\t\t\tdefault:\n\t\t\t\treturn Reference(0), fmt.Errorf(\"invalid argument found: %s\", string(v))\n\t\t\t}\n\t\t}\n\t}\n\n\tref := Reference(len(i.Lists))\n\ti.Lists = append(i.Lists, sc)\n\treturn ref, nil\n}", "func findUnique(r io.Reader, memLimit int) {\n\t// step.1 sort into file chunks, mapping stage\n\tparts := sort2Disk(r, memLimit, new(countMapper))\n\tlog.Println(\"Generated\", parts, \"parts\")\n\t// step2. merge all sstable and provides a continous input\n\tlog.Println(\"Reducing from#\", parts, \"sstable(s)\")\n\treducer := new(uniqueReducer)\n\tReduce(parts, reducer)\n\n\tif reducer.hasUnique {\n\t\tlog.Println(\"Found the first unique element:\", string(reducer.target.bytes()), reducer.target.ord())\n\t} else {\n\t\tlog.Println(\"Unique element not found!\")\n\t}\n}", "func resolve(idxsByClass map[string][]int) map[string]int {\n\tpopped := make(map[string]int, 0)\n\n\tlisted := make([]map[string][]int, 0)\n\tfor k, v := range idxsByClass {\n\t\tcurMap := map[string][]int{k: v}\n\t\tlisted = append(listed, curMap)\n\t}\n\n\tcurIdx := 0\n\tfor len(listed) != 0 {\n\t\tcurItem := listed[curIdx]\n\t\tfor k, v := range curItem {\n\t\t\tif len(v) == 1 {\n\t\t\t\tpopped[k] = v[0]\n\t\t\t\t// build new slice without k and v[0]\n\t\t\t\ttmp := make([]map[string][]int, len(listed)-1)\n\t\t\t\tcnt := 0\n\t\t\t\tfor i := range listed {\n\t\t\t\t\tif i == curIdx {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor itemKey, itemIdxs := range listed[i] {\n\t\t\t\t\t\tcurMap := map[string][]int{itemKey: remove(itemIdxs, v[0])}\n\t\t\t\t\t\ttmp[cnt] = curMap\n\t\t\t\t\t\tcnt++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlisted = tmp\n\t\t\t\t// start again from beginning\n\t\t\t\tcurIdx = 0\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcurIdx++\n\t\t}\n\n\t}\n\treturn popped\n}", "func helper(nums, rec []int, reference []bool, res *[][]int) {\n\tsize := len(nums)\n\tif len(rec) == size {\n\t\ttmp := make([]int, size, size)\n\t\tcopy(tmp, rec)\n\t\t*res = append(*res, tmp)\n\t}\n\tfor i := 0; i < size; i++ {\n\t\tif !reference[i] {\n\t\t\tif i > 0 && nums[i] == nums[i-1] && reference[i-1] {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trec = append(rec, nums[i])\n\t\t\treference[i] = true\n\t\t\thelper(nums, rec, reference, res)\n\t\t\treference[i] = false\n\t\t\trec = rec[:len(rec)-1]\n\t\t}\n\t}\n}", "func singleNumberB(nums []int) int {\n \n mp := make(map[int]int)\n result:= 0\n for _,data := range nums{\n if _,exist := mp[data]; exist{ //if element exist we remove the elemtn\n delete(mp, data)\n \n }else{\n mp[data] = data\n }\n\t}\n\t//really O(1) since there's always one element left\n for _, data := range mp{ \n result = data\n }\n return result \n}", "func contains(shorter, longer *TrieKey, prematchedBits uint) (matches, exact bool, common, child uint) {\n\t// Two variables important in finding which child to descend into\n\tvar pivotByte, numBytes uint\n\tpivotMask := byte(0x80)\n\n\t// calculate `exact`, `common`, and `child` at the end with defer\n\tdefer func() {\n\t\tif !matches {\n\t\t\tvar s, l byte\n\n\t\t\t// We know both of these slices are large enough to index with\n\t\t\t// `numBytes` because `matches` is false and therefore it must have\n\t\t\t// been a previous comparison of these bytes that got us here.\n\t\t\tfor i := prematchedBits / 8; i <= numBytes; i++ {\n\t\t\t\ts, l = shorter.Bits[i], longer.Bits[i]\n\t\t\t\tif s == l {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcommon = 8*i + uint(bits.LeadingZeros8(s^l))\n\n\t\t\t\t// Whether `longer` goes on the left (0) or right (1)\n\t\t\t\tif longer.Bits[i] < shorter.Bits[i] {\n\t\t\t\t\tchild = 0\n\t\t\t\t} else {\n\t\t\t\t\tchild = 1\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tcommon = shorter.Length\n\t\texact = shorter.Length == longer.Length\n\t\tif !exact {\n\t\t\t// Whether `longer` goes on the left (0) or right (1)\n\t\t\tif longer.Bits[pivotByte]&pivotMask == 0 {\n\t\t\t\tchild = 0\n\t\t\t} else {\n\t\t\t\tchild = 1\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Prefix length of 0 matches everything!\n\tif shorter.Length == 0 {\n\t\tmatches = true\n\t\treturn\n\t}\n\n\t// The bits to compare in the two keys always follows the following pattern:\n\t// 1. any number of leading \"full\" bytes which must match exactly\n\t// 2. 0 or 1 \"partial\" byte in the least significant (last) position which\n\t// must match up to the number of partial bits (1-7 bits).\n\t//\n\t// The strategy here is to compare the bytes from the least significant\n\t// (last) to the most significant (first) to avoid redundantly comparing\n\t// bytes that might have already matched higher in the tree.\n\n\t// Calculate number of bytes (including possible least-significant partial)\n\t// Decrement this as we compare bytes up to the most significant.\n\tnumBytes = bitsToBytes(shorter.Length)\n\n\t// Figure out how many bits are in the partial byte (0 means no partial)\n\tmaskLen := shorter.Length % 8\n\n\t// If the last byte is partial, compare using a bitmask\n\tif maskLen > 0 {\n\t\tvar mask byte\n\t\tmask = 0xff << (8 - maskLen)\n\n\t\t// decrement before comparing since the slices are indexed from 0\n\t\tnumBytes--\n\t\tif shorter.Bits[numBytes]&mask != longer.Bits[numBytes]&mask {\n\t\t\tmatches = false\n\t\t\treturn\n\t\t}\n\n\t\tpivotMask >>= maskLen\n\t}\n\n\tpivotByte = numBytes\n\n\t// The other bytes are all full and can be compared simply\n\tfor numBytes > (prematchedBits / 8) {\n\t\t// decrement before comparing since the slices are indexed from 0\n\t\tnumBytes--\n\t\tif shorter.Bits[numBytes] != longer.Bits[numBytes] {\n\t\t\tmatches = false\n\t\t\treturn\n\t\t}\n\t}\n\n\tmatches = true\n\treturn\n}", "func Solution(X int, A []int) int {\n // write your code in Go 1.4\n bucket := make([]bool, X + 1)\n count := 0\n \n for i, n := range A {\n if (bucket[n] == false) {\n bucket[n] = true\n count++\n }\n \n if (count == X) {\n return i\n }\n\t}\n\t\n\treturn -1\n}", "func orbitalTransfers(ob1, ob2 *orbit) int {\n\tvar lca *orbit // lowest common ancestor\n\tob1parents := make([]*orbit, 0)\n\tob1gen := 0 // how many steps from lca to ob1\n\tfor ptr := ob1; ptr != nil; ptr = ptr.parent {\n\t\tob1parents = append(ob1parents, ptr)\n\t}\n\tob2parents := make([]*orbit, 0)\nexterloop:\n\tfor ptr := ob2; ptr != nil; ptr = ptr.parent {\n\t\tfor count, key := range ob1parents {\n\t\t\tif key == ptr {\n\t\t\t\tlca = ptr // well ptr is the lca!\n\t\t\t\tob1gen = count\n\t\t\t\tbreak exterloop\n\t\t\t}\n\t\t}\n\t\tob2parents = append(ob2parents, ptr)\n\t}\n\t_ = lca // we didn't really use this did we?\n\treturn ob1gen + len(ob2parents) - 2\n}", "func traverse(que []string, seen map[string]struct{}) (nex []string) {\n\tfor _, page := range que {\n\t\tif _, ok := seen[page]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tseen[page] = struct{}{}\n\t\tnex = append(nex, get(page)...)\n\t}\n\treturn\n}", "func IterativeFindValue(key ID) ([]byte,Contact) {\n var dummy Contact\n\t// check if this node has the value\n\tif ThisNode.Data[key] != nil {\n\t\t//fmt.Printf(\"%v %v\\n\", ThisNode.ThisContact.NodeID, ThisNode.Data[key])\n\t\treturn ThisNode.Data[key],*ThisNode.ThisContact\n\t}\n // if this node doesn't have the value, search among the known nodes\n\tconst alpha = 3\n\t\n\tcontacted_nodes := make(Bucket,1600)\n\tshortlist := make(Bucket,20)\n\tshortlist_size := 0\n\t// The search begins by selecting alpha contacts from the non-empty k-bucket closest to the \n\t// bucket appropriate to the key being searched on.\n\t_, bucket_num := ThisNode.getBucket(key.Xor(ThisNode.ThisContact.NodeID))\n\tfor i := 0; i < 20 && shortlist_size < alpha; i++ {\n\t\tif ThisNode.K_Buckets[bucket_num][i] != nil {\n\t\t\tshortlist[shortlist_size] = ThisNode.K_Buckets[bucket_num][i]\n\t\t\tshortlist_size++\n\t\t}\n\t}\n\t// If there are fewer than alpha contacts in that bucket, contacts are selected from other buckets.\n\tfor b_idx := 0; b_idx < NumBuckets && shortlist_size < alpha; b_idx++ {\n\t\tif b_idx != bucket_num {\n\t\t\tfor i := 0; i < 20 && shortlist_size < alpha; i++ {\n\t\t\t\tif ThisNode.K_Buckets[bucket_num][i] != nil {\n\t\t\t\t\tshortlist[shortlist_size] = ThisNode.K_Buckets[bucket_num][i]\n\t\t\t\t\tshortlist_size++\n\t\t\t\t\tif shortlist_size >= alpha {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor true {\n\t// The node then sends parallel, asynchronous FIND_* RPCs to the alpha contacts in the \n\t// shortlist. Each contact, if it is live, should normally return k triples. If any of the \n\t// alpha contacts fails to reply, it is removed from the shortlist, at least temporarily.\n\t\n\t\tnew_shortlist := make(Bucket,400)\n\t\tfor i := 0; i < len(shortlist); i++ {\n\t\t\tnext_open_spot(contacted_nodes)\n\t\t\tcontacted_nodes[0] = shortlist[i]\n\t\t\tif shortlist[i] != nil {\n\t\t\t\thostPortStr := get_host_port(contacted_nodes[i])\n\t\t\n\t\t\t\tclient, err := rpc.DialHTTP(\"tcp\", hostPortStr)\n\t\t\t\tif err != nil {\n // if we can't contact the node, remove it from shortlist\n shortlist[i] = nil\n\t\t\t\t} else {\n\t\t\t\t\treq := new(FindValueRequest)\n\t\t\t\t\treq.MsgID = NewRandomID()\n\t\t\t\t\treq.Key = key\n\t\t\t\n\t\t\t\t\tvar res FindValueResult\n\t\t\t\t\terr = client.Call(\"Kademlia.FindValue\", req, &res)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Call: \", err)\n \t\t\t\t}\n client.Close()\n \t\t\t\t// if res.Err is nil, the node contains the value\n \t\t\t\tif res.Err == nil {\n \t\t\t\t//fmt.Printf(\"OK\\n\")\n \t\t\t\t\tfmt.Printf(\"%v %v\\n\", shortlist[i].NodeID, res.Value)\n \t\t\t\t\treturn res.Value,*shortlist[i]\n \t\t\t\t} else {\n \t\t\t\t\toffset:= 20 * i\n \t\t\t\t\tresBucket := foundNodeArr_to_Bucket(res.Nodes)\n\t\t\t\t\t\tfor j := 0; j<len(resBucket); j++{\n\t\t\t\t\t\t\tnew_shortlist[j+offset] = resBucket[j]\n\t\t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t\tshortlist_size = 0\n \t// assign contacts from new_shortlist to shortlist IF they haven't been contacted already\n \t\tfor i := 0; i < len(new_shortlist) && shortlist_size < alpha; i++ {\n \t\tif new_shortlist[i] != nil {\n \t\t\tif shortlist.FindNode(new_shortlist[i].NodeID) == nil && contacted_nodes.FindNode(new_shortlist[i].NodeID) == nil {\n \t\t\t\tshortlist[shortlist_size] = new_shortlist[i]\n \t\t\t\tshortlist_size++\n \t\t\t}\n \t\t}\n \t}\n \t\tif shortlist_size == 0 {\n \t\t\t//fmt.Printf(\"ERR\\n\")\n \t\t\treturn nil,dummy\n \t\t}\n \t}\n }\n return nil,dummy\n}", "func (d *Document) lookup(id uint, path []string) uint {\n\tvar (\n\t\tv *V\n\t\tn *node\n\t)\nlookup:\n\tfor _, key := range path {\n\t\tif n = d.get(id); n != nil {\n\t\t\tswitch n.info.Type() {\n\t\t\tcase TypeObject:\n\t\t\t\tfor i := range n.values {\n\t\t\t\t\tv = &n.values[i]\n\t\t\t\t\tif v.key == key {\n\t\t\t\t\t\tid = v.id\n\t\t\t\t\t\tcontinue lookup\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase TypeArray:\n\t\t\t\ti := 0\n\t\t\t\tfor _, c := range []byte(key) {\n\t\t\t\t\tif c -= '0'; 0 <= c && c <= 9 {\n\t\t\t\t\t\ti = i*10 + int(c)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn maxUint\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif 0 <= i && i < len(n.values) {\n\t\t\t\t\tv = &n.values[i]\n\t\t\t\t\tid = v.id\n\t\t\t\t\tcontinue lookup\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn maxUint\n\t}\n\treturn id\n}", "func BitonicMerge(arr []interface{}, comp goutils.TypeComparator, low, high int, order bool){\n if high > 1 {\n mid := high/2;\n BitonicCompare(arr, comp, low, mid, order);\n BitonicMerge(arr, comp, low, mid, order);\n BitonicMerge(arr, comp, low+mid, mid, order);\n }\n}", "func traverseIn(data []int, index int) []int {\n\tif bt[index] != nil {\n\t\tdata = traverseIn(data, (index*2)+1)\n\t\tdata = append(data, bt[index].value)\n\t\tdata = traverseIn(data, (index*2)+2)\n\t}\n\treturn data\n}", "func getInnerUnique(filter *Filter, indexOn int, item interface{}) interface{} {\n\ttn := filter.schemaItems[indexOn].typeName\n\tif tn == ItemTypeString {\n\t\treturn item\n\t} else if tn == ItemTypeObject {\n\t\t// Get item\n\t\tinnerItem := item.([]interface{})[filter.schemaItems[indexOn+1].dataIndex]\n\t\treturn getInnerUnique(filter, (indexOn + 1), innerItem)\n\t} else if filter.schemaItems[indexOn].IsNumeric() {\n\t\t// Convert both to the respective numeric type for comparison\n\t\tfilter.item, _ = makeTypeLiteral(filter.item, &filter.schemaItems[indexOn])\n\t\titem, _ := makeTypeLiteral(item, &filter.schemaItems[indexOn])\n\t\treturn item\n\t}\n\treturn nil\n}", "func FourSum(seq []int, target int) [][]int {\n res := [][]int{}\n seqPairMap := map[int][]int{} // { sum1: [i1, j1, i2, j2, ...], sum2: [i3, j3, i4, j4, ...], ... }\n for i := 0; i < len(seq) - 1; i++ {\n for j := i + 1; j < len(seq); j++ {\n sum := seq[i] + seq[j]\n if _, ok := seqPairMap[sum]; !ok { seqPairMap[sum] = []int{}; }\n seqPairMap[sum] = append(seqPairMap[sum], i)\n seqPairMap[sum] = append(seqPairMap[sum], j)\n }\n }\n // example: target = 14, sums are 5 + 9, 3 + 11 (map on smaller of the two i.e. 5, 3; other is implicit)\n sumMap := map[int][][]int{} // { 5: [[i1, j1, ...],[i5, j5, ...]], ...} 5 <-- [i1, j1, ...], 9 <-- [i5, j5, ...]\n for k, _ := range seqPairMap {\n if _, ok := seqPairMap[target-k]; ok {\n if k < target - k {\n sumMap[k] = [][]int{[]int{}, []int{}}\n sumMap[k][0] = seqPairMap[k]; sumMap[k][1] = seqPairMap[target-k];\n } else {\n sumMap[target-k] = [][]int{[]int{}, []int{}}\n sumMap[target-k][0] = seqPairMap[target-k]; sumMap[target-k][1] = seqPairMap[k];\n }\n }\n }\n \n for _, indexArr := range sumMap {\n arr0 := indexArr[0]; arr1 := indexArr[1]\n for m := 0; m < len(arr0); m += 2 {\n for n := 0; n < len(arr1); n += 2 {\n // check for distinctness of arr0[m], arr0[m+1], arr1[n], arr1[n+1]\n if arr0[m] != arr1[n] && arr0[m] != arr1[n+1] &&\n arr0[m+1] != arr1[n] && arr0[m+1] != arr1[n+1] {\n // still allows some dups to go through e.g. indexes [2 5 7 10], [2 7 5 10]\n res = append(res, []int{arr0[m], arr0[m+1], arr1[n], arr1[n+1]})\n }\n }\n }\n }\n // returns arrays of indices, convert to actual values as seq[i] for each i \n return res\n}", "func solution(knows func(a int, b int) bool) func(n int) int {\n\treturn func(n int) int {\n\t\ts := &stack{}\n\t\tfor i := 0; i< n; i++ {\n\t\t\ts.push(i)\n\t\t}\n\n\t\t//push them all on stack.\n\t\t//Selectively knock off one by one using one comparision.\n\t\t//if a knows b -> a cant be celebrity but b potentially is.\n\t\t//push b or a accordingly.\n\n\t\t//At the end - have on element left over due eleminations, this may\n\t\t//maynot be the celeb. Do one round of validation before declaring.\n\t\tfor len(*s) > 1 {\n\t\t\ta := s.pop()\n\t\t\tb := s.pop()\n\n\t\t\tif knows(a, b) {\n\t\t\t\ts.push(b)\n\t\t\t} else {\n\t\t\t\ts.push(a)\n\t\t\t}\n\t\t}\n\n\t\tfmt.Printf(\"length: %v\\n\", len(*s))\n\t\t//at this point we expect only one element in stack.\n\t\tc := s.pop()\n\n\n\n\t\t//double check if c is the celebrity.\n\t\tfor i:=0; i< n;i++ {\n\t\t\tif i != c && (knows(c, i) || !knows(i, c)) {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t}\n\t\treturn c\n\t}\n}", "func search(start *node, end *node , sp [676]wordlists, ep [676]wordlists) (*node){\n if start.name == end.name {\n return start\n }\n\n var st_index, en_index uint16\n var _arr_st_index, _arr_en_index []uint16\n var wlen uint8\n\n var cur [110000]node\n var child node\n var ndC uint64\n ndC = 0\n ftr := []node{}\n exp := []node{}\n depth := 0\n\n ftr = append(ftr, *start)\n\n for len(ftr) != 0 {\n cur[ndC], ftr = ftr[0], ftr[1:len(ftr)]\n\n if in_queue(cur[ndC], exp) {\n continue\n }\n\n child.parent = &cur[ndC]\n child.cost = cur[ndC].cost+1\n\n st_index = 26*(uint16(cur[ndC].name[0])-'a') + (uint16(cur[ndC].name[1])-'a')\n if !in_index_arr(st_index, _arr_st_index) {\n _arr_st_index = append(_arr_st_index, st_index)\n\n child.end = false\n for i:=0; i<len(ep[st_index].word); i++ {\n child.name = ep[st_index].word[i]\n if child.name == end.name {\n return &child\n }\n ftr = append(ftr, child)\n } \n } \n\n wlen = uint8(len(cur[ndC].name))\n en_index = 26*(uint16(cur[ndC].name[wlen-2])-'a') + (uint16(cur[ndC].name[wlen-1])-'a')\n if !in_index_arr(en_index, _arr_en_index) {\n _arr_en_index = append(_arr_en_index, en_index)\n\n child.end = true\n for i:=0; i<len(sp[en_index].word); i++ {\n child.name = sp[en_index].word[i]\n if child.name == end.name {\n return &child\n }\n ftr = append(ftr, child)\n } \n }\n if cur[ndC].cost != depth {\n depth = cur[ndC].cost\n }\n exp = append(exp, cur[ndC])\n ndC++\n }\n\n child.name = \"\"\n return &child\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 solution(knows func(a int, b int) bool) func(n int) int {\n\treturn func(n int) int {\n\t\ti := 0\n\t\tj := 0\n\n\t\tindeg := make([]int, n)\n\n\t\tfor i = 0; i < n; i++ {\n\t\t\tfor j = 0; j< n; j++ {\n\t\t\t\tif knows(i, j) && i != j{\n\t\t\t\t\tindeg[i]--\n\t\t\t\t\tindeg[j]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor index, val := range indeg {\n\t\t\tif val == n-1 {\n\t\t\t\treturn index\n\t\t\t}\n\t\t}\n\n\t\treturn -1\n\t}\n}", "func (this *AllOne) Inc(key string) {\n adr := this.m[key]\n if adr == nil{\n adr = &dll{k: key, v: 1}\n this.m[key] = adr\n if this.min == 0{\n this.min = 1\n this.max = 1\n this.g[1] = []*dll{adr, adr}\n return\n }\n adr.v = 0\n adr.nxt = this.g[this.min][0]\n this.g[this.min][0].prv = adr\n this.min = 1\n }else if this.g[adr.v][0] == this.g[adr.v][1]{\n if this.min == adr.v{\n this.min = adr.v + 1\n }\n delete(this.g, adr.v)\n }else if this.g[adr.v][1] == adr{\n this.g[adr.v][1] = adr.prv\n }else {\n adr.nxt.prv = adr.prv\n if this.g[adr.v][0] == adr{\n this.g[adr.v][0] = adr.nxt\n }\n if adr.prv != nil{\n adr.prv.nxt = adr.nxt\n }\n\n adr.nxt = this.g[adr.v][1].nxt\n adr.prv = this.g[adr.v][1]\n this.g[adr.v][1].nxt = adr\n if adr.nxt != nil{\n adr.nxt.prv = adr\n }\n }\n\n adr.v += 1\n if adr.v == this.max + 1{\n this.max += 1\n this.g[adr.v] = []*dll{adr, adr}\n }else if len(this.g[adr.v]) != 0{\n this.g[adr.v][0] = adr\n }else{\n this.g[adr.v] = []*dll{adr, adr}\n }\n return\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 replace(v []uint64, n int, x uint64) []uint64 {\n\tif n == 0 {\n\t\tif len(v) > 0 && v[0] == x {\n\t\t\treturn v\n\t\t}\n\t\tv = append(v, 0)\n\t\tcopy(v[1:], v)\n\t} else if n < len(v) {\n\t\tcopy(v[1:], v[n:])\n\t\tv = v[:len(v)-(n-1)]\n\t} else if len(v) == 0 {\n\t\treturn []uint64{x}\n\t} else {\n\t\tv = v[:1]\n\t}\n\tv[0] = x\n\treturn v\n}", "func computeLocationPath(fvdl FVDL, input int) []int {\n\tlog.Entry().Debug(\"Computing for ID \", input)\n\t// Find the successors of input\n\tvar subnodes []int\n\tvar result []int\n\tfor j := 0; j < len(fvdl.UnifiedNodePool.Node[input-1].Reason.Trace.Primary.Entry); j++ {\n\t\tif fvdl.UnifiedNodePool.Node[input-1].Reason.Trace.Primary.Entry[j].NodeRef.RefId != 0 && fvdl.UnifiedNodePool.Node[input-1].Reason.Trace.Primary.Entry[j].NodeRef.RefId != (input-1) {\n\t\t\tsubnodes = append(subnodes, fvdl.UnifiedNodePool.Node[input-1].Reason.Trace.Primary.Entry[j].NodeRef.RefId+1)\n\t\t}\n\t}\n\tresult = append(result, input)\n\tlog.Entry().Debug(\"Successors: \", subnodes)\n\tfor j := 0; j < len(subnodes); j++ {\n\t\tresult = append(result, computeLocationPath(fvdl, subnodes[j])...)\n\t}\n\tlog.Entry().Debug(\"Finishing computing for ID \", input)\n\treturn result\n}", "func (this *AllOne) Dec(key string) {\n if this.m[key] == nil{\n return\n }\n adr := this.m[key]\n if adr.v == 1{\n delete(this.m, key)\n if this.g[1][0] == this.g[1][1]{\n delete(this.g, 1)\n if this.max == 1{\n this.max = 0\n this.min = 0\n }else{\n this.min = adr.nxt.v\n adr.nxt.prv = nil\n }\n }else{\n if this.g[1][0] == adr{\n this.g[1][0] = adr.nxt\n }\n if this.g[1][1] == adr{\n this.g[1][1] = adr.prv\n }\n if adr.nxt != nil{\n adr.nxt.prv = adr.prv\n }\n if adr.prv != nil{\n adr.prv.nxt = adr.nxt\n }\n }\n return\n }\n\n\n if this.g[adr.v][0] == this.g[adr.v][1]{\n if this.max == adr.v{\n this.max = adr.v - 1\n }\n delete(this.g, adr.v)\n }else if this.g[adr.v][0] == adr{\n this.g[adr.v][0] = adr.nxt\n }else {\n adr.prv.nxt = adr.nxt\n if this.g[adr.v][1] == adr{\n this.g[adr.v][1] = adr.prv\n }\n if adr.nxt != nil{\n adr.nxt.prv = adr.prv\n }\n\n adr.nxt = this.g[adr.v][0]\n adr.prv = this.g[adr.v][0].prv\n this.g[adr.v][0].prv = adr\n if adr.prv != nil{\n adr.prv.nxt = adr\n }\n }\n\n adr.v -= 1\n if adr.v == this.min - 1{\n this.min -= 1\n this.g[adr.v] = []*dll{adr, adr}\n }else if len(this.g[adr.v]) != 0{\n this.g[adr.v][1] = adr\n }else{\n this.g[adr.v] = []*dll{adr, adr}\n }\n return\n}", "func get1N(indices *[]uint16, start, end int) []uint16 {\n\tif end > cap(*indices) {\n\t\t*indices = make([]uint16, end)\n\t\tfor i := range *indices {\n\t\t\t(*indices)[i] = uint16(i)\n\t\t}\n\t}\n\treturn (*indices)[start:end]\n}", "func Apply(op Op, data sort.Interface, pivots []int) (size int) {\n\tswitch len(pivots) {\n\tcase 0:\n\t\treturn 0\n\tcase 1:\n\t\treturn pivots[0]\n\tcase 2:\n\t\treturn op(data, pivots[0])\n\t}\n\n\tspans := make([]span, 0, len(pivots)+1)\n\n\t// convert pivots into spans (index intervals that represent sets)\n\ti := 0\n\tfor _, j := range pivots {\n\t\tspans = append(spans, span{i, j})\n\t\ti = j\n\t}\n\n\tn := len(spans) // original number of spans\n\tm := n / 2 // original number of span pairs (rounded down)\n\n\t// true if the span is being used\n\tinuse := make([]bool, n)\n\n\tch := make(chan span, m)\n\n\t// reverse iterate over every other span, starting with the last;\n\t// concurrent algo (further below) will pick available pairs operate on\n\tfor i := range spans[:m] {\n\t\ti = len(spans) - 1 - i*2\n\t\tch <- spans[i]\n\t}\n\n\tfor s := range ch {\n\t\tif len(spans) == 1 {\n\t\t\tif s.i != 0 {\n\t\t\t\tpanic(\"impossible final span\")\n\t\t\t}\n\t\t\t// this was the last operation\n\t\t\treturn s.j\n\t\t}\n\n\t\t// locate the span we received (match on start of span only)\n\t\ti := sort.Search(len(spans), func(i int) bool { return spans[i].i >= s.i })\n\n\t\t// store the result (this may change field j but not field i)\n\t\tspans[i] = s\n\n\t\t// mark the span as available for use\n\t\tinuse[i] = false\n\n\t\t// check the immediate neighbors for availability (prefer left)\n\t\tj, k := i-1, i+1\n\t\tswitch {\n\t\tcase j >= 0 && !inuse[j]:\n\t\t\ti, j = j, i\n\t\tcase k < len(spans) && !inuse[k]:\n\t\t\tj = k\n\t\tdefault:\n\t\t\t// nothing to do right now. wait for something else to finish\n\t\t\tcontinue\n\t\t}\n\n\t\ts, t := spans[i], spans[j]\n\n\t\tgo func(s, t span) {\n\t\t\t// sizes of the respective sets\n\t\t\tk, l := s.j-s.i, t.j-t.i\n\n\t\t\t// shift the right-hand span to be adjacent to the left\n\t\t\tslide(data, s.j, t.i, l)\n\n\t\t\t// prepare a view of the data (abs -> rel indices)\n\t\t\tb := boundspan{data, span{s.i, s.j + l}}\n\n\t\t\t// store result of op, adjusting for view (rel -> abs)\n\t\t\ts.j = s.i + op(b, k)\n\n\t\t\t// send the result back to the coordinating goroutine\n\t\t\tch <- s\n\t\t}(s, t)\n\n\t\t// account for the spawn merging that will occur\n\t\ts.j += t.j - t.i\n\n\t\tk = j + 1\n\n\t\t// shrink the lists to account for the merger\n\t\tspans = append(append(spans[:i], s), spans[k:]...)\n\n\t\t// (and the merged span is now in use as well)\n\t\tinuse = append(append(inuse[:i], true), inuse[k:]...)\n\t}\n\tpanic(\"unreachable\")\n}", "func sol2(nums1 []int, nums2 []int, k int) [][]int {\n if len(nums1) == 0 || len(nums2) == 0 {\n return nil\n }\n\n cursors := make([]int, len(nums1))\n var res [][]int\n for len(res) < k && len(res) < len(nums1) * len(nums2) {\n min := nums1[len(nums1)-1] + nums2[len(nums2)-1] + 1\n next := -1\n for i, j := range cursors {\n if j >= len(nums2) {\n continue\n }\n t := nums1[i] + nums2[j]\n if min > t {\n min = t\n next = i\n }\n // todo: skip condition\n }\n res = append(res, []int{nums1[next], nums2[cursors[next]]})\n cursors[next]++\n }\n\n return res\n}", "func (hash *SpaceHash) query(bin * SpaceHashBin, obj HashElement, \t\t\t\t\n fun SpaceHashQueryFunc, data HashElement) {\n for ; bin != nil ; bin = bin.next {\n hand \t := bin.handle\n other \t:= hand.obj \n // Skip over certain conditions\n if hand.stamp == hash.stamp || obj.Equals(other) || other == nil { \n continue \n } \n // Have we already tried this pair in this query? \n // Is obj the same as other?\n // Has other been removed since the last rehash? \n fun(obj, other, data)\n // Stamp that the handle was checked already against this object.\n hand.stamp = hash.stamp\n }\n}", "func resolveSubset(subset []string, resolved map[string]*rule) (bool, []string) {\n\t//fmt.Printf(\"RESOLVE SUBSET %+v\\n\", subset)\n\n\tif len(subset) == 1 {\n\t\tresolvedLeft, ok := resolved[subset[0]]\n\t\tif !ok {\n\t\t\treturn false, []string{}\n\t\t}\n\t\tresult := make([]string, 0)\n\t\tresult = append(result, resolvedLeft.resolvedOne...)\n\t\tresult = append(result, resolvedLeft.resolvedTwo...)\n\t\treturn true, result\n\t}\n\n\tresolvedLeft, ok := resolved[subset[0]]\n\tif !ok {\n\t\treturn false, []string{}\n\t}\n\n\tresolvedRight, ok := resolved[subset[1]]\n\tif !ok {\n\t\treturn false, []string{}\n\t}\n\t//fmt.Printf(\"RESOLVE LEFT %+v\\n\", resolvedLeft)\n\t//fmt.Printf(\"RESOLVE RIGHT %+v\\n\", resolvedRight)\n\n\tresult := make([]string, 0)\n\n\tfor _, v := range resolvedLeft.resolvedOne {\n\t\tfor _, v2 := range resolvedRight.resolvedOne {\n\t\t\tresult = append(result, v+v2)\n\t\t}\n\t}\n\n\tfor _, v := range resolvedLeft.resolvedOne {\n\t\tfor _, v2 := range resolvedRight.resolvedTwo {\n\t\t\tresult = append(result, v+v2)\n\t\t}\n\t}\n\n\tfor _, v := range resolvedLeft.resolvedTwo {\n\t\tfor _, v2 := range resolvedRight.resolvedOne {\n\t\t\tresult = append(result, v+v2)\n\t\t}\n\t}\n\n\tfor _, v := range resolvedLeft.resolvedTwo {\n\t\tfor _, v2 := range resolvedRight.resolvedTwo {\n\t\t\tresult = append(result, v+v2)\n\t\t}\n\t}\n\n\treturn true, result\n}", "func TwoSumMapSingleListTraverse(nums []int, target int) []int {\n\telements := make(map[int]int, len(nums))\n\tfor i, n := range nums {\n\t\tcomplement := target - n\n\t\tif j, ok := elements[complement]; ok && i != j{\n\t\t\treturn []int{i,j}\n\t\t}\n\n\t\telements[n] = i\n\t}\n\n\treturn nil\n}", "func tugOfWarUtil(array []int, n int, current_elements []bool, num_of_selected_elements int,\n ret []bool, min_diff *int, sum int, current_sum int, current_position int) {\n if current_position == n {\n return\n }\n\n if ((n/2 - num_of_selected_elements) > (n - current_position)) {\n return\n }\n\n tugOfWarUtil(array, n, current_elements, num_of_selected_elements, ret,\n min_diff, sum, current_sum, current_position + 1)\n\n num_of_selected_elements++\n current_sum = current_sum + array[current_position]\n current_elements[current_position] = true\n\n if num_of_selected_elements == (n/2) {\n if (math.Abs(float64(sum/2) - float64(current_sum)) < float64(*min_diff)) {\n *min_diff = int(math.Abs(float64(sum/2) - float64(current_sum)))\n for i := 0; i < n; i++ {\n ret[i] = current_elements[i]\n }\n }\n } else {\n tugOfWarUtil(array, n, current_elements, num_of_selected_elements, ret,\n min_diff, sum, current_sum, current_position + 1)\n }\n\n current_elements[current_position] = false\n}", "func twoSum1(nums []int, target int) []int {\n\thashTable := make(map[int]int)\n\tfor i, x := range nums {\n\t\tif j, ok := hashTable[target-x]; ok {\n\t\t\treturn []int{j, i}\n\t\t}\n\t\thashTable[x] = i\n\t}\n\treturn nil\n}", "func (rs *regionSet) add(r region) {\n\t// Iterate over the sorted region slice from the tail.\n\t// a) When an overwrap occurs, adjust `r` to fully contain the looking region\n\t// `l` and remove `l` from region slice.\n\t// b) Once l.e become less than r.b, no overwrap will occur again. So immediately\n\t// insert `r` which fully contains all overwrapped regions, to the region slice.\n\t// Here, `r` is inserted to the region slice with keeping it sorted, without\n\t// overwrapping to any regions.\n\t// *) If any `l` contains `r`, we don't need to do anything so return immediately.\n\tfor i := len(rs.rs) - 1; i >= 0; i-- {\n\t\tl := &rs.rs[i]\n\n\t\t// *) l contains r\n\t\tif l.b <= r.b && r.e <= l.e {\n\t\t\treturn\n\t\t}\n\n\t\t// a) r overwraps to l so adjust r to fully contain l and reomve l\n\t\t// from region slice.\n\t\tif l.b <= r.b && r.b <= l.e+1 && l.e <= r.e {\n\t\t\tr.b = l.b\n\t\t\trs.rs = append(rs.rs[:i], rs.rs[i+1:]...)\n\t\t\tcontinue\n\t\t}\n\t\tif r.b <= l.b && l.b <= r.e+1 && r.e <= l.e {\n\t\t\tr.e = l.e\n\t\t\trs.rs = append(rs.rs[:i], rs.rs[i+1:]...)\n\t\t\tcontinue\n\t\t}\n\t\tif r.b <= l.b && l.e <= r.e {\n\t\t\trs.rs = append(rs.rs[:i], rs.rs[i+1:]...)\n\t\t\tcontinue\n\t\t}\n\n\t\t// b) No overwrap will occur after this iteration. Instert r to the\n\t\t// region slice immediately.\n\t\tif l.e < r.b {\n\t\t\trs.rs = append(rs.rs[:i+1], append([]region{r}, rs.rs[i+1:]...)...)\n\t\t\treturn\n\t\t}\n\n\t\t// No overwrap occurs yet. See the next region.\n\t}\n\n\t// r is the topmost region among regions in the slice.\n\trs.rs = append([]region{r}, rs.rs...)\n}", "func (vlog *valueLog) iterate(lf *logFile, offset uint32, fn logEntry) (uint32, error) {\n\t_, err := lf.fd.Seek(int64(offset), io.SeekStart)\n\tif err != nil {\n\t\treturn 0, y.Wrap(err)\n\t}\n\n\treader := bufio.NewReader(lf.fd)\n\tread := &safeRead{\n\t\tk: make([]byte, 10),\n\t\tv: make([]byte, 10),\n\t\trecordOffset: offset,\n\t}\n\n\tvar lastCommit uint64\n\tvalidEndOffset := read.recordOffset\n\tfor {\n\t\te, err := read.Entry(reader)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err == io.ErrUnexpectedEOF || err == errTruncate {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn validEndOffset, err\n\t\t} else if e == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tread.recordOffset += uint32(headerBufSize + len(e.Key) + len(e.Value) + len(e.UserMeta) + 4) // len(crcBuf)\n\n\t\tif e.meta&bitTxn > 0 {\n\t\t\ttxnTs := y.ParseTs(e.Key)\n\t\t\tif lastCommit == 0 {\n\t\t\t\tlastCommit = txnTs\n\t\t\t}\n\t\t\tif lastCommit != txnTs {\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else if e.meta&bitFinTxn > 0 {\n\t\t\ttxnTs, err := strconv.ParseUint(string(e.Value), 10, 64)\n\t\t\tif err != nil || lastCommit != txnTs {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Got the end of txn. Now we can store them.\n\t\t\tlastCommit = 0\n\t\t\tvalidEndOffset = read.recordOffset\n\t\t} else {\n\t\t\tif lastCommit != 0 {\n\t\t\t\t// This is most likely an entry which was moved as part of GC.\n\t\t\t\t// We shouldn't get this entry in the middle of a transaction.\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tvalidEndOffset = read.recordOffset\n\t\t}\n\n\t\tif vlog.opt.ReadOnly {\n\t\t\treturn validEndOffset, ErrReplayNeeded\n\t\t}\n\t\tif err := fn(*e); err != nil {\n\t\t\tif err == errStop {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn validEndOffset, y.Wrap(err)\n\t\t}\n\t}\n\n\treturn validEndOffset, nil\n}", "func (da *cedar) get(key []byte, from, pos int) *int {\n\tfor ; pos < len(key); pos++ {\n\t\tif value := da.Array[from].Value; value >= 0 && value != ValueLimit {\n\t\t\tto := da.follow(from, 0)\n\t\t\tda.Array[to].Value = value\n\t\t}\n\t\tfrom = da.follow(from, key[pos])\n\t}\n\tto := from\n\tif da.Array[from].Value < 0 {\n\t\tto = da.follow(from, 0)\n\t}\n\treturn &da.Array[to].Value\n}", "func searchMergeDistinctList(db *sql.DB, listTable, setTable string, tb tokenTable, query rawTokenSet, k int, ignoreSelf bool) ([]searchResult, experimentResult) {\n\tvar expResult experimentResult\n\n\tstart := time.Now()\n\ttokens, _, gids := tb.process(query)\n\texpResult.PreprocDuration = int(time.Now().Sub(start) / time.Millisecond)\n\tac := newActionCollecter(len(tokens))\n\tstart = time.Now()\n\n\tac.start()\n\tcounter := make(map[int64]int)\n\tvar numSkipped int\n\tquerySize := len(tokens)\n\n\tfor i := 0; i < querySize; i, numSkipped = nextDistinctList(tokens, gids, i) {\n\t\ttoken := tokens[i]\n\t\tskippedOverlap := numSkipped\n\n\t\tentries := InvertedList(db, listTable, token)\n\t\texpResult.NumListRead++\n\t\texpResult.MaxListSizeRead = max(expResult.MaxListSizeRead, len(entries))\n\t\tac.addReadList(len(entries))\n\t\tfor _, entry := range entries {\n\t\t\tif ignoreSelf && entry.ID == query.ID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, seen := counter[entry.ID]; seen {\n\t\t\t\tcounter[entry.ID] += skippedOverlap + 1\n\t\t\t} else {\n\t\t\t\tcounter[entry.ID] = skippedOverlap + 1\n\t\t\t}\n\t\t}\n\t\texpResult.MaxCounterSize = max(expResult.MaxCounterSize, len(counter))\n\t}\n\th := &searchResultHeap{}\n\tfor id, overlap := range counter {\n\t\tpushCandidate(h, k, id, overlap)\n\t}\n\tresults := orderedResults(h)\n\tac.done()\n\n\texpResult.Duration = int(time.Now().Sub(start) / time.Millisecond)\n\texpResult.Actions = ac.collect()\n\texpResult.Results = writeResultString(results)\n\texpResult.QueryID = query.ID\n\texpResult.QuerySize = len(query.RawTokens)\n\texpResult.NumResult = len(results)\n\texpResult.QueryNumToken = len(tokens)\n\treturn results, expResult\n}", "func (m *cmap) insert(key keyt, upd Memop) (ret MemopRes) {\n\tnow := time.Now()\n\tival := cval{key: key}\n\n\t// we do some additional trickery here so that when we recompute bins\n\t// in the loop below, we don't need to do further allocations\n\tnh := int(m.hashes)\n\tvar bins_ [MAX_HASHES]int\n\tbins := bins_[0:nh]\n\tm.kbins(key, bins)\n\n\t// Check if this element is already present\n\tm.lock_in_order(bins...)\n\tfor bi, bin := range bins {\n\t\tb := &m.bins[bin]\n\t\tki, v := b.has(key, now)\n\t\tif ki != -1 {\n\t\t\tival.bno = bi\n\t\t\tival.val, ret = upd(v.val, true)\n\t\t\tif ret.T == STORED {\n\t\t\t\tb.setv(ki, &ival)\n\t\t\t\tb.vals[ki].read = true\n\t\t\t\tb.vals[ki].tag = key[0]\n\t\t\t}\n\t\t\tm.unlock(bins...)\n\t\t\treturn\n\t\t}\n\t}\n\tm.unlock(bins...)\n\n\t// if the operation fails if a current element does not exist,\n\t// there is no point doing the expensive insert search\n\t_, ret = upd(Memval{}, false)\n\tif ret.T != STORED {\n\t\treturn ret\n\t}\n\n\t// Item not currently present, is there room without a search?\n\tfor i, b := range bins {\n\t\tif m.bins[b].available(now) {\n\t\t\tival.bno = i\n\t\t\tret = m.bins[b].add(&ival, upd, now)\n\t\t\tif ret.T != SERVER_ERROR {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Keep trying to find a cuckoo path of replacements\n\tfor {\n\t\tpath := m.search(now, bins...)\n\t\tif path == nil {\n\t\t\tif m.evict() {\n\t\t\t\treturn m.insert(key, upd)\n\t\t\t}\n\t\t\treturn MemopRes{\n\t\t\t\tT: SERVER_ERROR,\n\t\t\t\tE: errors.New(\"no storage space found for element\"),\n\t\t\t}\n\t\t}\n\n\t\tfreeing := path[0].from\n\n\t\t// recompute bins because #hashes might have changed\n\t\tif nh != int(m.hashes) {\n\t\t\tnh = int(m.hashes)\n\t\t\tbins = bins_[0:nh]\n\t\t\tm.kbins(key, bins)\n\t\t}\n\n\t\t// sanity check that this path will make room in the right bin\n\t\ttobin := -1\n\t\tfor i, bin := range bins {\n\t\t\tif freeing == bin {\n\t\t\t\ttobin = i\n\t\t\t}\n\t\t}\n\t\tif tobin == -1 {\n\t\t\tpanic(fmt.Sprintf(\"path %v leads to occupancy in bin %v, but is unhelpful for key %s with bins: %v\", path, freeing, key, bins))\n\t\t}\n\n\t\t// only after the search do we acquire locks\n\t\tif m.validate_execute(path, now) {\n\t\t\tival.bno = tobin\n\n\t\t\t// after replacements, someone else might have beaten\n\t\t\t// us to the free slot, so we need to do add under a\n\t\t\t// lock too\n\t\t\tret = m.bins[freeing].add(&ival, upd, now)\n\t\t\tif ret.T != SERVER_ERROR {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func rec(nums []int, total, i int) int {\n\tct++\n\t// fmt.Printf(\"%d total %d i %d nums %v\\n\", ct, total, i, nums)\n\tif total == 0 {\n\t\tfmt.Printf(\"total 0, i %d nums %v\\n\", i, nums)\n\t\treturn 1\n\t} else if total < 0 {\n\t\t// fmt.Printf(\"%d total %d\\n\", ct, total)\n\t\treturn 0\n\t} else if i < 0 {\n\t\treturn 0\n\t} else if total < nums[i] {\n\t\t// if total < nums[i]\n\t\t// we cant find any subset add up to total, remove nums[i]\n\n\t\t// fmt.Printf(\"%d total %d nums[i] %d i %d\\n\", ct, total, nums[i], i)\n\t\treturn rec(nums, total, i-1)\n\t} else {\n\t\t//\n\t\t// fmt.Printf(\"%d total %d -nums[i] %d i %d \\n\", ct, total, nums[i], i)\n\t\treturn rec(nums, total-nums[i], i-1) + rec(nums, total, i-1)\n\t}\n}", "func (obj *object) insert(k, v *Term) {\n\thash := k.Hash()\n\thead := obj.elems[hash]\n\t// This `equal` utility is duplicated and manually inlined a number of\n\t// time in this file. Inlining it avoids heap allocations, so it makes\n\t// a big performance difference: some operations like lookup become twice\n\t// as slow without it.\n\tvar equal func(v Value) bool\n\n\tswitch x := k.Value.(type) {\n\tcase Null, Boolean, String, Var:\n\t\tequal = func(y Value) bool { return x == y }\n\tcase Number:\n\t\tif xi, err := json.Number(x).Int64(); err == nil {\n\t\t\tequal = func(y Value) bool {\n\t\t\t\tif y, ok := y.(Number); ok {\n\t\t\t\t\tif yi, err := json.Number(y).Int64(); err == nil {\n\t\t\t\t\t\treturn xi == yi\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// We use big.Rat for comparing big numbers.\n\t\t// It replaces big.Float due to following reason:\n\t\t// big.Float comes with a default precision of 64, and setting a\n\t\t// larger precision results in more memory being allocated\n\t\t// (regardless of the actual number we are parsing with SetString).\n\t\t//\n\t\t// Note: If we're so close to zero that big.Float says we are zero, do\n\t\t// *not* big.Rat).SetString on the original string it'll potentially\n\t\t// take very long.\n\t\tvar a *big.Rat\n\t\tfa, ok := new(big.Float).SetString(string(x))\n\t\tif !ok {\n\t\t\tpanic(\"illegal value\")\n\t\t}\n\t\tif fa.IsInt() {\n\t\t\tif i, _ := fa.Int64(); i == 0 {\n\t\t\t\ta = new(big.Rat).SetInt64(0)\n\t\t\t}\n\t\t}\n\t\tif a == nil {\n\t\t\ta, ok = new(big.Rat).SetString(string(x))\n\t\t\tif !ok {\n\t\t\t\tpanic(\"illegal value\")\n\t\t\t}\n\t\t}\n\n\t\tequal = func(b Value) bool {\n\t\t\tif bNum, ok := b.(Number); ok {\n\t\t\t\tvar b *big.Rat\n\t\t\t\tfb, ok := new(big.Float).SetString(string(bNum))\n\t\t\t\tif !ok {\n\t\t\t\t\tpanic(\"illegal value\")\n\t\t\t\t}\n\t\t\t\tif fb.IsInt() {\n\t\t\t\t\tif i, _ := fb.Int64(); i == 0 {\n\t\t\t\t\t\tb = new(big.Rat).SetInt64(0)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif b == nil {\n\t\t\t\t\tb, ok = new(big.Rat).SetString(string(bNum))\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tpanic(\"illegal value\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn a.Cmp(b) == 0\n\t\t\t}\n\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\tequal = func(y Value) bool { return Compare(x, y) == 0 }\n\t}\n\n\tfor curr := head; curr != nil; curr = curr.next {\n\t\tif equal(curr.key.Value) {\n\t\t\t// The ground bit of the value may change in\n\t\t\t// replace, hence adjust the counter per old\n\t\t\t// and new value.\n\n\t\t\tif curr.value.IsGround() {\n\t\t\t\tobj.ground--\n\t\t\t}\n\t\t\tif v.IsGround() {\n\t\t\t\tobj.ground++\n\t\t\t}\n\n\t\t\tcurr.value = v\n\t\t\treturn\n\t\t}\n\t}\n\telem := &objectElem{\n\t\tkey: k,\n\t\tvalue: v,\n\t\tnext: head,\n\t}\n\tobj.elems[hash] = elem\n\t// O(1) insertion, but we'll have to re-sort the keys later.\n\tobj.keys = append(obj.keys, elem)\n\t// Reset the sync.Once instance.\n\t// See https://github.com/golang/go/issues/25955 for why we do it this way.\n\tobj.sortGuard = new(sync.Once)\n\tobj.hash += hash + v.Hash()\n\n\tif k.IsGround() {\n\t\tobj.ground++\n\t}\n\tif v.IsGround() {\n\t\tobj.ground++\n\t}\n}", "func part1(arr []int) int {\n\tvar i, j int\n\tn := len(arr)\n\n\ti = 0\n\tj = n - 1\n\n\tfor i < n && j >= 0 {\n\t\tif arr[i]+arr[j] == target {\n\t\t\tbreak\n\t\t}\n\t\tif arr[i]+arr[j] < target {\n\t\t\ti++\n\t\t} else {\n\t\t\tj--\n\t\t}\n\t}\n\treturn arr[i] * arr[j]\n}", "func (decTree *Tree) findSplit(currData []*dataTypes.Data, classes []ClassAvg, setVal, stopCond float64) ([]*dataTypes.Data, []*dataTypes.Data) {\n\tif stoppingCond(currData, stopCond) {\n\t\tdecTree.Details.Leaf = true\n\t\tdecTree.Details.Class = getMajority(currData)\n\t\treturn nil, nil\n\t}\n\n\tnumFields := len(currData[0].FeatureSlice)\n\n\tvar splitVals []float64\n\tvar entropys []float64\n\tvar left []*dataTypes.Data\n\tvar right []*dataTypes.Data\n\n\t//for each attribute\n\tfor i := 0; i < numFields; i++ {\n\t\tindexUsed := false\n\t\tfor _, temp := range decTree.usedIndicies {\n\t\t\tif temp == i {\n\t\t\t\tentropys = append(entropys, setVal)\n\t\t\t\tsplitVals = append(splitVals, 0)\n\t\t\t\tindexUsed = true\n\t\t\t}\n\t\t}\n\n\t\tif indexUsed == false {\n\t\t\tvar tempVals []float64\n\t\t\tvar averages []float64\n\t\t\tvar stdDevs []float64\n\t\t\tvar tempEntropys []float64\n\n\t\t\tfor _, class := range classes {\n\t\t\t\tif len(class.averages) == 0 {\n\t\t\t\t\taverages = append(averages, setVal)\n\t\t\t\t\tstdDevs = append(stdDevs, setVal)\n\t\t\t\t\ttempVals = append(tempVals, setVal)\n\t\t\t\t\ttempEntropys = append(tempEntropys, setVal)\n\t\t\t\t} else {\n\t\t\t\t\taverages = append(averages, GetFloatReflectVal(class.averages[i]))\n\t\t\t\t\tstdDevs = append(stdDevs, GetFloatReflectVal(class.stdDev[i]))\n\t\t\t\t\ttempVals = append(tempVals, averages[len(averages)-1]+stdDevs[len(stdDevs)-1])\n\t\t\t\t\ttempEntropys = append(tempEntropys, findEntropy(i, len(classes), averages[len(averages)-1], stdDevs[len(stdDevs)-1], currData))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO modify to take unspecified number of classes using a slice\n\t\t\ttempIndex, tempEntropy := findLeast(tempEntropys)\n\n\t\t\t//Here we have a problem, we are appending the entropy not the value to split on\n\t\t\tsplitVals = append(splitVals, tempVals[tempIndex])\n\t\t\tentropys = append(entropys, tempEntropy)\n\t\t}\n\t}\n\n\tindex := findIndex(entropys)\n\n\t//don't use entropy as your stopping condition, find a way to measure the purity after a split\n\tdecTree.Details.Leaf = false\n\tdecTree.Details.SplitVal = splitVals[index]\n\tdecTree.Details.IndexSplit = index\n\n\tdecTree.Left = new(Tree)\n\tdecTree.Right = new(Tree)\n\n\tdecTree.Left.usedIndicies = append(decTree.usedIndicies, decTree.Details.IndexSplit)\n\tdecTree.Right.usedIndicies = append(decTree.usedIndicies, decTree.Details.IndexSplit)\n\n\tfor _, elem := range currData {\n\t\tcompVal := GetFloatReflectVal(elem.FeatureSlice[index])\n\n\t\tif compVal < splitVals[index] {\n\t\t\tleft = append(left, elem)\n\t\t} else {\n\t\t\tright = append(right, elem)\n\t\t}\n\t}\n\n\tif len(left) == len(currData) {\n\t\tdecTree.Details.Leaf = true\n\t\tdecTree.Details.Class = getMajority(currData)\n\t\tleft, right = nil, nil\n\t} else if len(right) == len(currData) {\n\t\tdecTree.Details.Leaf = true\n\t\tdecTree.Details.Class = getMajority(currData)\n\t\tleft, right = nil, nil\n\t}\n\n\treturn left, right\n}", "func uniquePaths(m int, n int) int {\n\t// dp:一维\n\t//dp := make([]int, n)\n\t//for i := 0; i < m; i++ {\n\t//\tdp[0] = 1\n\t//\tfor j := 1; j < n; j++ {\n\t//\t\tdp[j] += dp[j-1]\n\t//\t}\n\t//}\n\t//return dp[n-1]\n\n\t// dp:二维\n\t//dp := make([][]int, m+1)\n\t//for i := 0; i <= m; i++ {\n\t//\tdp[i] = make([]int, n+1)\n\t//}\n\t//dp[0][1] = 1\n\t//for i := 1; i <= m; i++ {\n\t//\tfor j := 1; j <= n; j++ {\n\t//\t\tdp[i][j] = dp[i-1][j] + dp[i][j-1]\n\t//\t}\n\t//}\n\t//return dp[m][n]\n\n\t// 递归:记忆化\n\tmemo := make(map[int]int)\n\tcount := memoRecursion(m, n, memo)\n\tfmt.Println(len(memo))\n\treturn count\n\n\t// 递归:超时\n\t//if m == 1 || n == 1 {\n\t//\treturn 1\n\t//}\n\t//return uniquePaths(m-1, n) + uniquePaths(m, n-1)\n}", "func furthestFunc(tmpIndex int, cache *map[string]bool, items *[]string) string {\n\n\t// Holds all the items in the cache\n\tcacheCopy := make(map[string]bool)\n\tfor key, held := range *cache {\n\t\tif held == true {\n\t\t\tcacheCopy[key] = true\n\t\t}\n\t}\n\n\t// scan the list of items, removing each until we reach the end of the\n\t// list, or we get the item used farthest in the future.\n\tfor ; tmpIndex < len(*items) && len(cacheCopy) > 1; tmpIndex++ {\n\t\tusedItem := (*items)[tmpIndex]\n\t\tdelete(cacheCopy, usedItem)\n\t}\n\n\tfurthestKey := \"\"\n\n\t// Return an item in the map\n\tfor k, _ := range cacheCopy {\n\t\tfurthestKey = k\n\t\tbreak\n\t}\n\n\treturn furthestKey\n}", "func backtrack(res *[][]int, nums []int, temp []int, used map[int]bool) {\n\t// check if we have a valid perm\n\tif len(temp) == len(nums) {\n\t\t// add copy of temp to res\n\t\ttmp := make([]int, len(nums))\n\t\tcopy(tmp, temp)\n\t\t*res = append(*res, tmp[:])\n\t\treturn\n\t}\n\n\t// go through all possible nums\n\tfor _, num := range nums {\n\t\t// check if we didnt already use this num\n\t\tif !used[num] {\n\t\t\t// add to used/temp, backtrack\n\t\t\tused[num] = true\n\t\t\ttemp = append(temp, num)\n\t\t\tbacktrack(res, nums, temp, used)\n\t\t\t// remove from used/temp\n\t\t\tdelete(used, num)\n\t\t\ttemp = temp[:len(temp)-1]\n\t\t}\n\t}\n}", "func findDifferenceOfTwoLists(bigList []string, smallList []string, N int) ([]string, int) {\n\tvar startIdx int\n\tvar res []string\n\tbigListLen := len(bigList)\n\n\tfor ; startIdx < bigListLen; startIdx++ {\n\t\tif bigList[startIdx] == smallList[0] {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tsmallListIdx := 1\n\n\tfor i := (startIdx + 1) % bigListLen; i != startIdx; i = (i + 1) % bigListLen {\n\t\tif N > 0 {\n\t\t\tif smallListIdx < len(smallList) && bigList[i] == smallList[smallListIdx] {\n\t\t\t\tsmallListIdx++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tres = append(res, bigList[i])\n\t\t\tN--\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn res, len(res)\n}", "func recurHelper2(mem map[string]int, data map[string]map[string]int, current string) int {\n\tcount := 1\n\n\tfor k, v := range data[current] {\n\t\tif _, exists := mem[k]; !exists {\n\t\t\tmem[k] = recurHelper2(mem, data, k)\n\t\t}\n\n\t\tcount += v * mem[k]\n\t}\n\n\treturn count\n}", "func backtrack(pos int, total *int, fill []int, avail map[int]bool) {\n\tif pos == len(fill) {\n\t\t*total++\n\t\treturn\n\t}\n\tfor n, ok := range avail {\n\t\tif !ok || (n%(pos+1) != 0 && (pos+1)%n != 0) {\n\t\t\tcontinue // Not beautiful!\n\t\t}\n\t\tavail[n] = false\n\t\tfill[pos] = n\n\t\tbacktrack(pos+1, total, fill, avail)\n\t\tavail[n] = true\n\t}\n}", "func (t *Tree) query(i int) int {\n\tvar ret int\n\tfor i >= 0 {\n\t\tret += t.bit[i]\n\t\ti = (i & (i + 1)) - 1\n\t}\n\treturn ret\n}", "func (tf tFiles) getOverlaps(dst tFiles, icmp *iComparer, umin, umax []byte, overlapped bool) tFiles {\n\tdst = dst[:0]\n\tfor i := 0; i < len(tf); {\n\t\tt := tf[i]\n\t\tif t.overlaps(icmp, umin, umax) {\n\t\t\tif umin != nil && icmp.uCompare(t.imin.ukey(), umin) < 0 {\n\t\t\t\tumin = t.imin.ukey()\n\t\t\t\tdst = dst[:0]\n\t\t\t\ti = 0\n\t\t\t\tcontinue\n\t\t\t} else if umax != nil && icmp.uCompare(t.imax.ukey(), umax) > 0 {\n\t\t\t\tumax = t.imax.ukey()\n\t\t\t\t// Restart search if it is overlapped.\n\t\t\t\tif overlapped {\n\t\t\t\t\tdst = dst[:0]\n\t\t\t\t\ti = 0\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdst = append(dst, t)\n\t\t}\n\t\ti++\n\t}\n\n\treturn dst\n}", "func naive(mappings map[int]map[int][]mapping, data *util.QueryDocumentSet, iterations int) []float64 {\n\tN := data.Size()\n\n\titerations = gomath.MinInt(iterations, N-1)\n\n\ts := &sortable{}\n\n\ts.n = N\n\ts.nodeInfo = make([]wrapper, N)\n\n\tdead := make([]bool, N)\n\tres := make([]float64, N)\n\n\tfor iterations > 0 {\n\n\t\tfor i := 0; i < N; i++ {\n\t\t\ts.nodeInfo[i].outDegree = 0\n\t\t\ts.nodeInfo[i].inDegree = 0\n\t\t}\n\n\t\tcountDegrees(s, dead, mappings)\n\t\tbestIndex, bestRatio := findBestRatio(s)\n\n\t\tdead[bestIndex] = true\n\n\t\tres[bestIndex] = bestRatio\n\n\t\titerations--\n\t}\n\treturn res\n}", "func getInts(l int, clear bool) []int {\n\tw := *poolInts[poolFor(uint(l))].Get().(*[]int)\n\tw = w[:l]\n\tif clear {\n\t\tfor i := range w {\n\t\t\tw[i] = 0\n\t\t}\n\t}\n\treturn w\n}", "func dp_rob(nums []int,l int, pos int,select_first bool,record_selectfirst map[int]int,record_notselectfirst map[int]int)int{\n\tif pos >= l{\n\t\treturn 0\n\t}\n\n\tif select_first{\n\t\tif _,ok := record_selectfirst[pos];ok{\n\t\t\treturn record_selectfirst[pos]\n\t\t}\n\t}else{\n\t\tif _,ok := record_notselectfirst[pos];ok{\n\t\t\treturn record_notselectfirst[pos]\n\t\t}\n\t}\n\n\tif pos == l - 1{\n\t\tif !select_first{\n\t\t\treturn nums[pos]\n\t\t}else{\n\t\t\treturn 0\n\t\t}\n\t}\n\n\tres := max_int(nums[pos] + dp_rob(nums,l,pos + 2,select_first,record_selectfirst,record_notselectfirst),\n\t\tdp_rob(nums,l,pos + 1,select_first,record_selectfirst,record_notselectfirst))\n\tif select_first{\n\t\trecord_selectfirst[pos] = res\n\t}else{\n\t\trecord_notselectfirst[pos] = res\n\t}\n\treturn res\n}", "func IterativeStore(key ID, value []byte) int {\n\n\tprevDistance := key.Xor(ThisNode.ThisContact.NodeID)\n\t\n\t//var closestNode kademlia.FoundNode\n\tclosestNode := ThisNode.ThisContact\n\tkClosestNodes := make(Bucket,20)\n \n\thostPortStr := get_host_port(ThisNode.ThisContact)\n\t\n\t//closestnode may want to be its own function that we call from FindNode, or at least\n\t//that code should be in FindNode, since we need to populate res.Nodes with more than one bucket\n\tfor true {\n\t\t//fmt.Printf(\"%s\\n\",hostPortStr)\n\t\tclient, err := rpc.DialHTTP(\"tcp\", hostPortStr)\n\t\tif err != nil {\n\t\t\t//fmt.Printf(\"1\\n\")\n\t\t\tlog.Fatal(\"DialHTTP: \", err)\n\t\t}\n\t\treq := new(FindNodeRequest)\n\t\treq.MsgID = NewRandomID()\n\t\treq.NodeID = key\n\t\n\t\tvar res FindNodeResult\n\t\t//if FindNode works, all of the closest nodes should be in res.\n\t\terr = client.Call(\"Kademlia.FindNode\", req, &res)\n \t\tif err != nil {\n\t\t\tlog.Fatal(\"Call: \", err)\n \t\t}\n client.Close()\n \t\t// obviously we need to do something with the array here, not just take the first element\n \t\t//fmt.Printf(\"Node 0: %v\\n\",res.Nodes[0])\n \t\tnextClosestNode, dist := res.Nodes[0], key.Xor(res.Nodes[0].NodeID)\n \t\tfor i:= 0; i < len(res.Nodes); i++ {\n \t\t\tif res.Nodes[i].Port != 0 {\n if res.Nodes[i].NodeID.Xor(key).Less(dist) {\n dist = res.Nodes[i].NodeID.Xor(key)\n nextClosestNode = res.Nodes[i]\n }\n // update kClosestNodes\n replace_idx := -1\n for j := 0; j < len(kClosestNodes); j++ {\n if kClosestNodes[j] == nil {\n kClosestNodes[j] = res.Nodes[i].ToContactPtr()\n replace_idx = -1\n break\n } else if res.Nodes[i].ToContactPtr().NodeID.Xor(key).Less(kClosestNodes[j].NodeID.Xor(key)) {\n if replace_idx != -1 {\n if kClosestNodes[replace_idx].NodeID.Xor(key).Less(kClosestNodes[j].NodeID.Xor(key)) {\n replace_idx = j\n }\n }\n }\n }\n if replace_idx != -1 {\n kClosestNodes[replace_idx] = res.Nodes[i].ToContactPtr()\n }\n }\n \t\t}\n \t\tcurDistance := key.Xor(nextClosestNode.NodeID)\n \t\tif !curDistance.Less(prevDistance) {\n \t\t\tbreak\n \t\t} else {\n \t\t\tclosestNode = nextClosestNode.ToContactPtr()\n prevDistance = curDistance\n \t\t}\n \t\thostPortStr = get_host_port(closestNode)\n\t\t}\n\thostPortStr = get_host_port(closestNode)\n\tstore(hostPortStr, key, value)\n // replicate data across k closest nodes\n for i:=0; i < len(kClosestNodes); i++ {\n if kClosestNodes[i] != nil {\n if !kClosestNodes[i].NodeID.Equals(closestNode.NodeID) {\n hostPortStr = get_host_port(kClosestNodes[i])\n store(hostPortStr, key, value)\n }\n }\n }\n\t//fmt.Printf(\"%v\\n\",closestNode.NodeID)\n\treturn 1\n}", "func deriveContains(list []int, item int) bool {\n\tfor _, v := range list {\n\t\tif v == item {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (iter *Iterator) tick(i, min int, delta []*vcache) (ok bool, err error) {\n\tnext := make([]*vcache, i)\n\n\t// The biggest outer loop is walking backwards over iter.In[i]\n\tx := len(iter.in[i])\n\tfor x > 0 {\n\t\tj := iter.in[i][x-1]\n\n\t\tif j <= min {\n\t\t\treturn false, iter.restore(next, i)\n\t\t} else if iter.blacklist[j] {\n\t\t\tx--\n\t\t\tcontinue\n\t\t}\n\n\t\tv := iter.variables[j]\n\n\t\tself := v.save()\n\n\t\tif v.value = v.Next(); v.value == NIL {\n\t\t\t// That sucks. Now we need to restore the value\n\t\t\t// that was changed and decrement x.\n\t\t\tv.value = v.Seek(self.ID)\n\t\t\tx--\n\t\t} else {\n\t\t\t// We got a non-nil value for v, so now we\n\t\t\t// propagate between j and i, then crawl forward\n\t\t\t// over the indices in iter.Out[q] that are less than i\n\t\t\t// and seek to their new values.\n\n\t\t\t// Propagate up to but not including i\n\t\t\tif err = iter.push(v, j, i); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Fantastic. Now that we've propagated the value we found for v,\n\t\t\t// we start \"the crawl\" from j to i, seeking to the new satisfying root\n\t\t\t// and recursing on tick when necessary.\n\t\t\tcursor := j\n\t\t\titer.blacklist[j] = true\n\t\t\tfor _, k := range iter.out[j] {\n\t\t\t\tif k >= i {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw := iter.variables[k]\n\n\t\t\t\tif next[k] == nil {\n\t\t\t\t\tnext[k] = w.save()\n\t\t\t\t}\n\n\t\t\t\td := make([]*vcache, k)\n\n\t\t\t\t// Here we keep seeking and ticking until we have a real value.\n\t\t\t\tfor w.value = w.Seek(w.root); w.value == NIL; w.value = w.Seek(w.root) {\n\t\t\t\t\tif ok, err = iter.tick(k, min, d); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else if ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err = iter.restore(d, i); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif w.value == NIL {\n\t\t\t\t\t// We were unable to complete the crawl.\n\t\t\t\t\t// We've already reset our state.\n\t\t\t\t\t// This is how far we got:\n\t\t\t\t\tcursor = k + 1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// We got a real value for w! Now we propagate the affected values\n\t\t\t\t// through i and stash them into next if they're not there already,\n\t\t\t\t// and then continue with the tick-crawl.\n\t\t\t\terr = iter.push(w, k, i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfor l, saved := range d {\n\t\t\t\t\tif saved != nil {\n\t\t\t\t\t\terr = iter.push(iter.variables[l], l, i)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif next[l] == nil {\n\t\t\t\t\t\t\tnext[l] = saved\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\t// We need to *unset* the blacklist after recursing.\n\t\t\t// Variables are only blacklisted when they appear as\n\t\t\t// a parent in the call stack - they might be visited\n\t\t\t// twice as siblings in the call tree, etc.\n\t\t\titer.blacklist[j] = false\n\n\t\t\tif cursor == j {\n\t\t\t\t// Hooray!\n\t\t\t\t// Now here we need to push every affected value\n\t\t\t\t// through to the rest of the domain\n\t\t\t\t// delta[j] = self\n\t\t\t\tnext[j] = self\n\t\t\t\tfor l, saved := range next {\n\t\t\t\t\tif saved != nil {\n\t\t\t\t\t\tif delta[l] == nil {\n\t\t\t\t\t\t\tdelta[l] = saved\n\t\t\t\t\t\t}\n\t\t\t\t\t\terr = iter.push(iter.variables[l], i, iter.Len())\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true, nil\n\t\t\t}\n\n\t\t\t// This means we reset (all) those affected to their previous state\n\t\t\terr = iter.restore(next, i)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func findItinerary(tickets [][]string) []string {\n\tvar (\n\t\tm = map[string][]string{}\n\t\tres []string\n\t)\n\n\tfor _, ticket := range tickets {\n\t\tsrc, dst := ticket[0], ticket[1]\n\t\tm[src] = append(m[src], dst)\n\t}\n\n\t// 排序\n\tfor key := range m {\n\t\tsort.Strings(m[key])\n\t}\n\n\tvar dfs func(curr string)\n\tdfs = func(curr string) {\n\t\tfor {\n\t\t\tif v, ok := m[curr]; !ok || len(v) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttmp := m[curr][0]\n\t\t\tm[curr] = m[curr][1:]\n\t\t\tdfs(tmp)\n\t\t}\n\t\tres = append(res, curr)\n\t}\n\n\tdfs(\"JFK\")\n\tfor i := 0; i < len(res) / 2; i++ {\n\t\tres[i], res[len(res)-1-i] = res[len(res)-1-i], res[i]\n\t}\n\treturn res\n}", "func checkAndProcessLeafList(existingEntry db.Value, tblRw db.Value, opcode int, d *db.DB, tblNm string, tblKey string) db.Value {\n\tdbTblSpec := &db.TableSpec{Name: tblNm}\n\tmergeTblRw := db.Value{Field: map[string]string{}}\n\tfor field, value := range tblRw.Field {\n\t\tif strings.HasSuffix(field, \"@\") {\n\t\t\texstLst := existingEntry.GetList(field)\n\t\t\tlog.Infof(\"Existing DB value for field %v - %v\", field, exstLst)\n\t\t\tvar valueLst []string\n\t\t\tif value != \"\" { //zero len string as leaf-list value is treated as delete entire leaf-list\n\t\t\t\tvalueLst = strings.Split(value, \",\")\n\t\t\t}\n\t\t\tlog.Infof(\"Incoming value for field %v - %v\", field, valueLst)\n\t\t\tif len(exstLst) != 0 {\n\t\t\t\tlog.Infof(\"Existing list is not empty for field %v\", field)\n\t\t\t\tfor _, item := range valueLst {\n\t\t\t\t\tif !contains(exstLst, item) {\n\t\t\t\t\t\tif opcode == UPDATE {\n\t\t\t\t\t\t\texstLst = append(exstLst, item)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif opcode == DELETE {\n\t\t\t\t\t\t\texstLst = utils.RemoveElement(exstLst, item)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlog.Infof(\"For field %v value after merging incoming with existing %v\", field, exstLst)\n\t\t\t\tif opcode == DELETE {\n\t\t\t\t\tif len(valueLst) > 0 {\n\t\t\t\t\t\tmergeTblRw.SetList(field, exstLst)\n\t\t\t\t\t\tif len(exstLst) == 0 {\n\t\t\t\t\t\t\ttblRw.Field[field] = \"\"\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdelete(tblRw.Field, field)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if opcode == UPDATE {\n\t\t\t\t\ttblRw.SetList(field, exstLst)\n\t\t\t\t}\n\t\t\t} else { //when existing list is empty(either empty string val in field or no field at all n entry)\n\t\t\t\tlog.Infof(\"Existing list is empty for field %v\", field)\n\t\t\t\tif opcode == UPDATE {\n\t\t\t\t\tif len(valueLst) > 0 {\n\t\t\t\t\t\texstLst = valueLst\n\t\t\t\t\t\ttblRw.SetList(field, exstLst)\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttblRw.Field[field] = \"\"\n\t\t\t\t\t}\n\t\t\t\t} else if opcode == DELETE {\n\t\t\t\t\t_, fldExistsOk := existingEntry.Field[field]\n\t\t\t\t\tif fldExistsOk && (len(valueLst) == 0) {\n\t\t\t\t\t\ttblRw.Field[field] = \"\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelete(tblRw.Field, field)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t/* delete specific item from leaf-list */\n\tif opcode == DELETE {\n\t\tif len(mergeTblRw.Field) == 0 {\n\t\t\tlog.Infof(\"mergeTblRow is empty - Returning Table Row %v\", tblRw)\n\t\t\treturn tblRw\n\t\t}\n\t\terr := d.ModEntry(dbTblSpec, db.Key{Comp: []string{tblKey}}, mergeTblRw)\n\t\tif err != nil {\n\t\t\tlog.Warning(\"DELETE case(merge leaf-list) - d.ModEntry() failure\")\n\t\t}\n\t}\n\tlog.Infof(\"Returning Table Row %v\", tblRw)\n\treturn tblRw\n}", "func run(input string) (interface{}, interface{}) {\n\tts, busList := parse(input)\n\n\tpart1, part2 := 0, 0\n\tmod := 1\n\tminID := 0\n\tfor i, b := range busList {\n\t\tfreq := b.ID - ts%b.ID\n\t\tif freq < busList[minID].ID-ts%busList[minID].ID {\n\t\t\tpart1 = b.ID * freq\n\t\t\tminID = i\n\t\t}\n\n\t\tfor (part2+b.Offset)%b.ID != 0 {\n\t\t\tpart2 += mod\n\t\t}\n\t\tmod *= b.ID\n\t}\n\treturn part1, part2\n}", "func isUnique(fl FieldLevel) bool {\n\tfield := fl.Field()\n\tparam := fl.Param()\n\tv := reflect.ValueOf(struct{}{})\n\n\tswitch field.Kind() {\n\tcase reflect.Slice, reflect.Array:\n\t\telem := field.Type().Elem()\n\t\tif elem.Kind() == reflect.Ptr {\n\t\t\telem = elem.Elem()\n\t\t}\n\n\t\tif param == \"\" {\n\t\t\tm := reflect.MakeMap(reflect.MapOf(elem, v.Type()))\n\n\t\t\tfor i := 0; i < field.Len(); i++ {\n\t\t\t\tm.SetMapIndex(reflect.Indirect(field.Index(i)), v)\n\t\t\t}\n\t\t\treturn field.Len() == m.Len()\n\t\t}\n\n\t\tsf, ok := elem.FieldByName(param)\n\t\tif !ok {\n\t\t\tpanic(fmt.Sprintf(\"Bad field name %s\", param))\n\t\t}\n\n\t\tsfTyp := sf.Type\n\t\tif sfTyp.Kind() == reflect.Ptr {\n\t\t\tsfTyp = sfTyp.Elem()\n\t\t}\n\n\t\tm := reflect.MakeMap(reflect.MapOf(sfTyp, v.Type()))\n\t\tvar fieldlen int\n\t\tfor i := 0; i < field.Len(); i++ {\n\t\t\tkey := reflect.Indirect(reflect.Indirect(field.Index(i)).FieldByName(param))\n\t\t\tif key.IsValid() {\n\t\t\t\tfieldlen++\n\t\t\t\tm.SetMapIndex(key, v)\n\t\t\t}\n\t\t}\n\t\treturn fieldlen == m.Len()\n\tcase reflect.Map:\n\t\tvar m reflect.Value\n\t\tif field.Type().Elem().Kind() == reflect.Ptr {\n\t\t\tm = reflect.MakeMap(reflect.MapOf(field.Type().Elem().Elem(), v.Type()))\n\t\t} else {\n\t\t\tm = reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type()))\n\t\t}\n\n\t\tfor _, k := range field.MapKeys() {\n\t\t\tm.SetMapIndex(reflect.Indirect(field.MapIndex(k)), v)\n\t\t}\n\n\t\treturn field.Len() == m.Len()\n\tdefault:\n\t\tif parent := fl.Parent(); parent.Kind() == reflect.Struct {\n\t\t\tuniqueField := parent.FieldByName(param)\n\t\t\tif uniqueField == reflect.ValueOf(nil) {\n\t\t\t\tpanic(fmt.Sprintf(\"Bad field name provided %s\", param))\n\t\t\t}\n\n\t\t\tif uniqueField.Kind() != field.Kind() {\n\t\t\t\tpanic(fmt.Sprintf(\"Bad field type %T:%T\", field.Interface(), uniqueField.Interface()))\n\t\t\t}\n\n\t\t\treturn field.Interface() != uniqueField.Interface()\n\t\t}\n\n\t\tpanic(fmt.Sprintf(\"Bad field type %T\", field.Interface()))\n\t}\n}", "func getTotalX(a []int, b []int) int {\n // Write your code here\n var c int\n sort.Ints(a)\n sort.Ints(b)\n for i:=a[0];i<=b[len(b)-1];i++{\n factor:=true\n for _,v:=range a{\n if i % v != 0{\n factor = false\n }\n }\n for _,v:=range b{\n if v%i!=0{\n factor=false\n }\n }\n if factor == true{\n c++\n }\n }\n return c\n}", "func minIncrementForUnique(A []int) int {\n \n}", "func (p *Processor) getHash(x *mat.Dense) int {\n\th := x.T().Mul(p.r.Value())\n\tconcat := mat.ConcatV(h, h.ProdScalar(-1.0))\n\treturn f64utils.ArgMax(concat.Data())\n}", "func (fileInode *fileInodeStruct) getReadPlan(fileOffset uint64, length uint64) (readPlan []interface{}, readPlanSpan uint64) {\n\tvar (\n\t\tchunkedPutContext *chunkedPutContextStruct\n\t\tchunkedPutContextAsElement *list.Element\n\t\tcurExtentAsValue sortedmap.Value\n\t\tcurExtentIndex int\n\t\tcurFileOffset uint64\n\t\tcurMultiObjectExtent *multiObjectExtentStruct\n\t\terr error\n\t\tmultiObjectReadPlanStep *multiObjectExtentStruct\n\t\tok bool\n\t\tremainingLength uint64\n\t)\n\n\t// First assemble readPlan based upon fileInode.extentMap\n\n\treadPlan = make([]interface{}, 0, 1)\n\n\tcurFileOffset = fileOffset\n\tremainingLength = length\n\n\tcurExtentIndex, _, err = fileInode.extentMap.BisectLeft(fileOffset)\n\tif nil != err {\n\t\tlogFatalf(\"getReadPlan() couldn't find curExtent: %v\", err)\n\t}\n\n\tfor remainingLength > 0 {\n\t\t_, curExtentAsValue, ok, err = fileInode.extentMap.GetByIndex(curExtentIndex)\n\t\tif nil != err {\n\t\t\tlogFatalf(\"getReadPlan() couldn't find curExtent [Case 1]: %v\", err)\n\t\t}\n\n\t\tif !ok {\n\t\t\t// Crossed EOF - stop here\n\n\t\t\tbreak\n\t\t}\n\n\t\tcurMultiObjectExtent, ok = curExtentAsValue.(*multiObjectExtentStruct)\n\t\tif !ok {\n\t\t\tlogFatalf(\"getReadPlan() couldn't find curExtent [Case 2]: %v\", err)\n\t\t}\n\n\t\tif (curMultiObjectExtent.fileOffset + curMultiObjectExtent.length) <= curFileOffset {\n\t\t\t// curExtent ends at or before curFileOffset - stop here\n\n\t\t\tbreak\n\t\t}\n\n\t\tmultiObjectReadPlanStep = &multiObjectExtentStruct{\n\t\t\tfileOffset: curFileOffset,\n\t\t\tcontainerName: curMultiObjectExtent.containerName,\n\t\t\tobjectName: curMultiObjectExtent.objectName, // May be == \"\"\n\t\t\tobjectOffset: curMultiObjectExtent.objectOffset + (curFileOffset - curMultiObjectExtent.fileOffset),\n\t\t\tlength: curMultiObjectExtent.length - (curFileOffset - curMultiObjectExtent.fileOffset),\n\t\t}\n\n\t\tif remainingLength < multiObjectReadPlanStep.length {\n\t\t\t// This is the last readPlanStep and needs to be truncated\n\n\t\t\tmultiObjectReadPlanStep.length = remainingLength\n\t\t}\n\n\t\tif 0 == multiObjectReadPlanStep.length {\n\t\t\t// Reached EOF - stop here\n\n\t\t\tbreak\n\t\t}\n\n\t\treadPlan = append(readPlan, multiObjectReadPlanStep)\n\n\t\tcurFileOffset += multiObjectReadPlanStep.length\n\t\tremainingLength -= multiObjectReadPlanStep.length\n\n\t\tcurExtentIndex++\n\t}\n\n\t// Compute tentative readPlanSpan\n\n\tif 0 == len(readPlan) {\n\t\treadPlanSpan = 0\n\t} else {\n\t\tmultiObjectReadPlanStep = readPlan[len(readPlan)-1].(*multiObjectExtentStruct)\n\t\treadPlanSpan = (multiObjectReadPlanStep.fileOffset + multiObjectReadPlanStep.length) - fileOffset\n\t}\n\n\t// But we must apply, in order, any changes due to chunkedPutContextStruct's\n\n\tchunkedPutContextAsElement = fileInode.chunkedPutList.Front()\n\tfor nil != chunkedPutContextAsElement {\n\t\tchunkedPutContext = chunkedPutContextAsElement.Value.(*chunkedPutContextStruct)\n\t\treadPlan, readPlanSpan = chunkedPutContext.getReadPlanHelper(fileOffset, length, readPlan)\n\t\tchunkedPutContextAsElement = chunkedPutContextAsElement.Next()\n\t}\n\n\t// And we are done...\n\n\treturn\n}", "func recInversionCount(v *array) (*array, int){\r\n\tif len(v.a) == 1{\r\n\t\treturn v, 0\r\n\t}\r\n\tmid := (len(v.a))/2\r\n\tleftHalf, leftInv := recInversionCount(&array{v.a[:mid]})\r\n\trightHalf, rightInv := recInversionCount(&array{v.a[mid:]})\r\n\tsortedArr := []int{}\r\n\tsplitInv := 0\r\n\ti, j := 0, 0\r\n\tfor i < len(leftHalf.a) && j < len(rightHalf.a){\r\n\t\tif leftHalf.a[i] <= rightHalf.a[j]{\r\n\t\t\tsortedArr = append(sortedArr, leftHalf.a[i])\r\n\t\t\ti++\r\n\t\t} else{\r\n\t\t\tsortedArr = append(sortedArr, rightHalf.a[j])\r\n\t\t\tsplitInv += len(leftHalf.a)-i\r\n\t\t\tj++\r\n\t\t}\r\n\t}\r\n\tif i<len(leftHalf.a) {\r\n\t\tsortedArr = append(sortedArr, leftHalf.a[i:]...)\r\n\t} \r\n\tfor j < len(rightHalf.a) {\r\n\t\tsortedArr = append(sortedArr, rightHalf.a[j])\r\n\t\tj++\r\n\t}\r\n\treturn &array{sortedArr}, leftInv+rightInv+splitInv\r\n}", "func (c *ldcache) resolveSelected(selected func(string) bool) ([]string, []string) {\n\tpaths := make(map[int][]string)\n\tprocessed := make(map[string]bool)\n\n\tfor _, e := range c.getEntries(selected) {\n\t\tpath, err := c.resolve(e.value)\n\t\tif err != nil {\n\t\t\tc.logger.Debugf(\"Could not resolve entry: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif processed[path] {\n\t\t\tcontinue\n\t\t}\n\t\tpaths[e.bits] = append(paths[e.bits], path)\n\t\tprocessed[path] = true\n\t}\n\n\treturn paths[32], paths[64]\n}", "func (a *Analyzer) findLargePriceSwings(resp *Response) (ois []OfInterest) {\n for i := 1; i < len(resp.Stock); i++ {\n swing := (resp.Stock[i].Adj - resp.Stock[i-1].Adj) / resp.Stock[i-1].Adj\n if a.threshold > 0.0 && swing > a.threshold {\n // XXX Abstract this\n oi := new(OfInterest)\n oi.Index = i\n oi.Stock = resp.Stock[i]\n oi.Swing = swing\n ois = append(ois, *oi)\n } else if a.threshold < 0.0 && swing < a.threshold {\n // XXX Abstract this\n oi := new(OfInterest)\n oi.Index = i\n oi.Stock = resp.Stock[i]\n oi.Swing = swing\n ois = append(ois, *oi)\n }\n }\n return\n}", "func (da *DoubleArray) _decideBaseOffset(firstChars []uint8, existsTerminator bool, offset uint8, rootIndex uint32, baseSearchOffset uint32) (uint32, uint32) {\n for {\n if baseSearchOffset >= uint32(len(da.Base)) {\n da._resizeDoubleArray()\n }\n if da.Check[baseSearchOffset] == 0 {\n break\n }\n baseSearchOffset++\n }\n var baseOffset uint32\n if baseSearchOffset <= charIndexCount + 2 {\n baseOffset = 2\n } else {\n baseOffset = baseSearchOffset - charIndexCount\n }\n for {\n if baseOffset + charIndexCount >= uint32(len(da.Base)) {\n da._resizeDoubleArray()\n }\n if !da._checkCollision(firstChars, existsTerminator, baseOffset) {\n // 衝突しない場合\n var i uint32\n for i = 1; i < charIndexCount; i++ {\n if firstChars[i] != 0 {\n da.Check[baseOffset + i] = rootIndex\n }\n }\n if existsTerminator {\n da.Check[baseOffset + charIndexCount] = rootIndex\n }\n\t\t\t//daCount++\n\t\t\t//if daCount % 1000 == 0 {\n\t\t\t//\tfmt.Printf(\"DEBUG decideBaseOffset %d %d %d\\n\", daCount, baseOffset, baseSearchOffset)\n\t\t\t//}\n return baseOffset, baseSearchOffset\n }\n baseOffset++\n }\n}", "func popcountSliceGeneric(s []uint64) (n uint64) {\n\tcnt := uint64(0)\n\tfor _, x := range s {\n\t\tx -= (x >> 1) & 0x5555555555555555\n\t\tx = (x>>2)&0x3333333333333333 + x&0x3333333333333333\n\t\tx += x >> 4\n\t\tx &= 0x0f0f0f0f0f0f0f0f\n\t\tx *= 0x0101010101010101\n\t\tcnt += x >> 56\n\t}\n\treturn cnt\n}", "func (ds *DatabaseService) Genericise(concept *Concept, generics map[Identifier]*Concept) (*Concept, bool) {\n\tpaths, err := ds.PathsToRoot(concept)\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\tvar bestPath []*Concept\n\tbestPos := -1\n\tfor _, path := range paths {\n\t\tfor i, concept := range path {\n\t\t\tif generics[concept.ConceptID] != nil {\n\t\t\t\tif i > 0 && (bestPos == -1 || bestPos > i) {\n\t\t\t\t\tbestPos = i\n\t\t\t\t\tbestPath = path\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif bestPos == -1 {\n\t\treturn nil, false\n\t}\n\treturn bestPath[bestPos], true\n}", "func Solution(A []int, K int) []int {\n lengthA := len(A)\n result := make([]int, lengthA)\n \n if K < 1 || len(A) == 0{\n return A\n }else{\n result[0] = A[lengthA-1] \n counter := 1\n //Iterate throught the original array, append to result array\n for x := 0; x < lengthA -1; x++{\n result[counter] = A[x]\n counter ++\n }\n result = Solution(result, K -1)\n \n }\n \n return result\n}", "func core(out *[64]byte, in *[16]byte, k *[32]byte) {\n\tj0 := uint32(0x61707865)\n\tj1 := uint32(0x3320646e)\n\tj2 := uint32(0x79622d32)\n\tj3 := uint32(0x6b206574)\n\tj4 := binary.LittleEndian.Uint32(k[0:4])\n\tj5 := binary.LittleEndian.Uint32(k[4:8])\n\tj6 := binary.LittleEndian.Uint32(k[8:12])\n\tj7 := binary.LittleEndian.Uint32(k[12:16])\n\tj8 := binary.LittleEndian.Uint32(k[16:20])\n\tj9 := binary.LittleEndian.Uint32(k[20:24])\n\tj10 := binary.LittleEndian.Uint32(k[24:28])\n\tj11 := binary.LittleEndian.Uint32(k[28:32])\n\tj12 := binary.LittleEndian.Uint32(in[0:4])\n\tj13 := binary.LittleEndian.Uint32(in[4:8])\n\tj14 := binary.LittleEndian.Uint32(in[8:12])\n\tj15 := binary.LittleEndian.Uint32(in[12:16])\n\n\tx0, x1, x2, x3, x4, x5, x6, x7 := j0, j1, j2, j3, j4, j5, j6, j7\n\tx8, x9, x10, x11, x12, x13, x14, x15 := j8, j9, j10, j11, j12, j13, j14, j15\n\n\tfor i := 0; i < rounds; i += 2 {\n\t\tx0 += x4\n\t\tx12 ^= x0\n\t\tx12 = (x12 << 16) | (x12 >> (16))\n\t\tx8 += x12\n\t\tx4 ^= x8\n\t\tx4 = (x4 << 12) | (x4 >> (20))\n\t\tx0 += x4\n\t\tx12 ^= x0\n\t\tx12 = (x12 << 8) | (x12 >> (24))\n\t\tx8 += x12\n\t\tx4 ^= x8\n\t\tx4 = (x4 << 7) | (x4 >> (25))\n\t\tx1 += x5\n\t\tx13 ^= x1\n\t\tx13 = (x13 << 16) | (x13 >> 16)\n\t\tx9 += x13\n\t\tx5 ^= x9\n\t\tx5 = (x5 << 12) | (x5 >> 20)\n\t\tx1 += x5\n\t\tx13 ^= x1\n\t\tx13 = (x13 << 8) | (x13 >> 24)\n\t\tx9 += x13\n\t\tx5 ^= x9\n\t\tx5 = (x5 << 7) | (x5 >> 25)\n\t\tx2 += x6\n\t\tx14 ^= x2\n\t\tx14 = (x14 << 16) | (x14 >> 16)\n\t\tx10 += x14\n\t\tx6 ^= x10\n\t\tx6 = (x6 << 12) | (x6 >> 20)\n\t\tx2 += x6\n\t\tx14 ^= x2\n\t\tx14 = (x14 << 8) | (x14 >> 24)\n\t\tx10 += x14\n\t\tx6 ^= x10\n\t\tx6 = (x6 << 7) | (x6 >> 25)\n\t\tx3 += x7\n\t\tx15 ^= x3\n\t\tx15 = (x15 << 16) | (x15 >> 16)\n\t\tx11 += x15\n\t\tx7 ^= x11\n\t\tx7 = (x7 << 12) | (x7 >> 20)\n\t\tx3 += x7\n\t\tx15 ^= x3\n\t\tx15 = (x15 << 8) | (x15 >> 24)\n\t\tx11 += x15\n\t\tx7 ^= x11\n\t\tx7 = (x7 << 7) | (x7 >> 25)\n\t\tx0 += x5\n\t\tx15 ^= x0\n\t\tx15 = (x15 << 16) | (x15 >> 16)\n\t\tx10 += x15\n\t\tx5 ^= x10\n\t\tx5 = (x5 << 12) | (x5 >> 20)\n\t\tx0 += x5\n\t\tx15 ^= x0\n\t\tx15 = (x15 << 8) | (x15 >> 24)\n\t\tx10 += x15\n\t\tx5 ^= x10\n\t\tx5 = (x5 << 7) | (x5 >> 25)\n\t\tx1 += x6\n\t\tx12 ^= x1\n\t\tx12 = (x12 << 16) | (x12 >> 16)\n\t\tx11 += x12\n\t\tx6 ^= x11\n\t\tx6 = (x6 << 12) | (x6 >> 20)\n\t\tx1 += x6\n\t\tx12 ^= x1\n\t\tx12 = (x12 << 8) | (x12 >> 24)\n\t\tx11 += x12\n\t\tx6 ^= x11\n\t\tx6 = (x6 << 7) | (x6 >> 25)\n\t\tx2 += x7\n\t\tx13 ^= x2\n\t\tx13 = (x13 << 16) | (x13 >> 16)\n\t\tx8 += x13\n\t\tx7 ^= x8\n\t\tx7 = (x7 << 12) | (x7 >> 20)\n\t\tx2 += x7\n\t\tx13 ^= x2\n\t\tx13 = (x13 << 8) | (x13 >> 24)\n\t\tx8 += x13\n\t\tx7 ^= x8\n\t\tx7 = (x7 << 7) | (x7 >> 25)\n\t\tx3 += x4\n\t\tx14 ^= x3\n\t\tx14 = (x14 << 16) | (x14 >> 16)\n\t\tx9 += x14\n\t\tx4 ^= x9\n\t\tx4 = (x4 << 12) | (x4 >> 20)\n\t\tx3 += x4\n\t\tx14 ^= x3\n\t\tx14 = (x14 << 8) | (x14 >> 24)\n\t\tx9 += x14\n\t\tx4 ^= x9\n\t\tx4 = (x4 << 7) | (x4 >> 25)\n\t}\n\n\tx0 += j0\n\tx1 += j1\n\tx2 += j2\n\tx3 += j3\n\tx4 += j4\n\tx5 += j5\n\tx6 += j6\n\tx7 += j7\n\tx8 += j8\n\tx9 += j9\n\tx10 += j10\n\tx11 += j11\n\tx12 += j12\n\tx13 += j13\n\tx14 += j14\n\tx15 += j15\n\n\tbinary.LittleEndian.PutUint32(out[0:4], x0)\n\tbinary.LittleEndian.PutUint32(out[4:8], x1)\n\tbinary.LittleEndian.PutUint32(out[8:12], x2)\n\tbinary.LittleEndian.PutUint32(out[12:16], x3)\n\tbinary.LittleEndian.PutUint32(out[16:20], x4)\n\tbinary.LittleEndian.PutUint32(out[20:24], x5)\n\tbinary.LittleEndian.PutUint32(out[24:28], x6)\n\tbinary.LittleEndian.PutUint32(out[28:32], x7)\n\tbinary.LittleEndian.PutUint32(out[32:36], x8)\n\tbinary.LittleEndian.PutUint32(out[36:40], x9)\n\tbinary.LittleEndian.PutUint32(out[40:44], x10)\n\tbinary.LittleEndian.PutUint32(out[44:48], x11)\n\tbinary.LittleEndian.PutUint32(out[48:52], x12)\n\tbinary.LittleEndian.PutUint32(out[52:56], x13)\n\tbinary.LittleEndian.PutUint32(out[56:60], x14)\n\tbinary.LittleEndian.PutUint32(out[60:64], x15)\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tn := len(A)\n\tsum := n * (n + 1) / 2\n\n\tisSeen := make(map[int]bool)\n\n\tfor _, el := range A {\n\t\tdup := isSeen[el]\n\t\tif dup {\n\t\t\treturn 0\n\t\t}\n\t\tisSeen[el] = true\n\t\tsum -= el\n\t}\n\tif sum != 0 {\n\t\treturn 0\n\t}\n\treturn 1\n}", "func (b *ringBuf) add(ents []raftpb.Entry) (addedBytes, addedEntries int32) {\n\tif afterCache := b.len > 0 && ents[0].Index > last(b).index(b)+1; afterCache {\n\t\t// If ents is non-contiguous and later than the currently cached range then\n\t\t// remove the current entries and add ents in their place.\n\t\tremovedBytes, removedEntries := b.clearTo(last(b).index(b) + 1)\n\t\taddedBytes, addedEntries = -1*removedBytes, -1*removedEntries\n\t}\n\tbefore, after, ok := computeExtension(b, ents[0].Index, ents[len(ents)-1].Index)\n\tif !ok {\n\t\treturn\n\t}\n\textend(b, before, after)\n\tit := first(b)\n\tif before == 0 && after != b.len { // skip unchanged prefix\n\t\tit, _ = iterateFrom(b, ents[0].Index) // safe by construction\n\t}\n\tfirstNewAfter := len(ents) - after\n\tfor i, e := range ents {\n\t\tif i < before || i >= firstNewAfter {\n\t\t\taddedEntries++\n\t\t\taddedBytes += int32(e.Size())\n\t\t} else {\n\t\t\taddedBytes += int32(e.Size() - it.entry(b).Size())\n\t\t}\n\t\tit = it.push(b, e)\n\t}\n\treturn\n}", "func main() {\n\tvar l1, l2 []int\n\t// fmt.Println(\"test\")\n\t// l1 = []int{-1, 0, 0, 3, 3, 3, 0, 0, 0}\n\t// l2 = []int{1, 2, 2}\n\t// merge(l1, 6, l2, 3)\n\t// fmt.Println(\"test\")\n\t// l1 = []int{1, 2, 3, 0, 0, 0}\n\t// l2 = []int{2, 5, 6}\n\t// merge(l1, 3, l2, 3)\n\t// l1 = []int{1, 0}\n\t// l2 = []int{2}\n\t// merge(l1, 1, l2, 1)\n\t// l1 = []int{2, 0}\n\t// l2 = []int{1}\n\t// merge(l1, 1, l2, 1)\n\t// l1 = []int{1, 5, 7, 0, 0, 0, 0, 0}\n\t// l2 = []int{3, 16, 500, 5001, 5001}\n\t// merge(l1, 3, l2, 5)\n\tl1 = []int{4, 5, 6, 0, 0, 0}\n\tl2 = []int{1, 2, 3}\n\tmerge(l1, 3, l2, 3)\n}", "func (m *Map) direct(seqno uint16) (bool, uint16, uint16) {\n\tif len(m.entries) == 0 {\n\t\treturn false, 0, 0\n\t}\n\ti := m.lastEntry\n\tfor {\n\t\tf := m.entries[i].first\n\t\tif compare(seqno, f) >= 0 {\n\t\t\tif compare(seqno, f+m.entries[i].count) < 0 {\n\t\t\t\treturn true,\n\t\t\t\t\tseqno + m.entries[i].delta,\n\t\t\t\t\tm.entries[i].pidDelta\n\t\t\t}\n\t\t\treturn false, 0, 0\n\t\t}\n\t\tif i > 0 {\n\t\t\ti--\n\t\t} else {\n\t\t\ti = uint16(len(m.entries) - 1)\n\t\t}\n\t\tif i == m.lastEntry {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn false, 0, 0\n}", "func computeDistanceCache(pos uint, starting_dist_cache []int, nodes []zopfliNode, dist_cache []int) {\n\tvar idx int = 0\n\tvar p uint = uint(nodes[pos].u.shortcut)\n\tfor idx < 4 && p > 0 {\n\t\tvar ilen uint = uint(nodes[p].dcode_insert_length & 0x7FFFFFF)\n\t\tvar clen uint = uint(zopfliNodeCopyLength(&nodes[p]))\n\t\tvar dist uint = uint(zopfliNodeCopyDistance(&nodes[p]))\n\t\tdist_cache[idx] = int(dist)\n\t\tidx++\n\n\t\t/* Because of prerequisite, p >= clen + ilen >= 2. */\n\t\tp = uint(nodes[p-clen-ilen].u.shortcut)\n\t}\n\n\tfor ; idx < 4; idx++ {\n\t\tdist_cache[idx] = starting_dist_cache[0]\n\t\tstarting_dist_cache = starting_dist_cache[1:]\n\t}\n}", "func sol1(nums []int, target int) []int {\n\tfor i, n := range nums {\n\t\tfor j, m := range nums {\n\t\t\tif i == j {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif n+m == target {\n\t\t\t\treturn []int{i, j}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func getVal(name, key string) (res interface{}) {\n\tif strings.Contains(key, \".\") {\n\t\tif v0, ok := respectiveMap[name]; ok {\n\t\t\treturn getVLink(strings.Split(key, \".\"), v0)\n\t\t}\n\t\treturn nil\n\t}\n\n\tfor n, v := range respectiveMap {\n\t\tif n != name {\n\t\t\tcontinue\n\t\t}\n\n\t\tif key == \"\" {\n\t\t\treturn v\n\t\t}\n\n\t\t{\n\t\t\tif _, ok := keyMap[key]; !ok {\n\t\t\t\tlog.Fatalf(\"not found:'%s', please check\", key)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tres = getV(key, v)\n\t\t}\n\t}\n\n\t//if strings.Contains(key, \".\") {\n\t//\tkeys = strings.Split(key, \".\")\n\t//\tfor _, k := range keys {\n\t//\t\tif _, ok := keyMap[k]; !ok {\n\t//\t\t\tlog.Fatalf(\"sub not found:'%s', please check\", k)\n\t//\t\t\treturn\n\t//\t\t}\n\t//\t}\n\t//} else {\n\t//\tif _, ok := keyMap[key]; !ok {\n\t//\t\tlog.Fatalf(\"not found:'%s', please check\", key)\n\t//\t\treturn\n\t//\t}\n\t//\tfor n, v := range respectiveMap {\n\t//\t\tif n != name {\n\t//\t\t\tcontinue\n\t//\t\t}\n\t//\n\t//\t\tres = getV(key, v)\n\t//\t}\n\t//}\n\n\treturn\n}", "func findEven(b []byte, m int, l int) result {\n\tif 0 == m {\n\t\treturn result{\n\t\t\tb: b[0:1],\n\t\t\tl: 1,\n\t\t}\n\t}\n\tif m == l {\n\t\tv := b[l-1 : l]\n\t\treturn result{\n\t\t\tb: v,\n\t\t\tl: len(v),\n\t\t}\n\t}\n\tmax := m + 1\n\tfmt.Println(\"max?\", max, len(b))\n\tfor d := 1; d < max; d++ {\n\t\txi := m - d\n\t\tx := b[xi : xi+1]\n\t\tyi := m + d - 1\n\t\ty := b[yi : yi+1]\n\t\tfmt.Println(\" m:\", m, string(b[m]))\n\t\tfmt.Println(\" x:\", xi, string(x[0]))\n\t\tfmt.Println(\" y:\", yi, string(y[0]))\n\t\tfmt.Println(\" range:\", string(b[xi:yi+1]))\n\t\tif x[0] != y[0] {\n\t\t\tv := b[m+1-d : m+d-1]\n\t\t\treturn result{\n\t\t\t\tb: v,\n\t\t\t\tl: len(v),\n\t\t\t}\n\t\t}\n\t}\n\tv := b[m-m : m+(m)]\n\treturn result{\n\t\tb: v,\n\t\tl: len(v),\n\t}\n}", "func binarySearchImpl(a []int, start, end, el int, recursionDepthLeft int) int {\n\tif recursionDepthLeft == 0 {\n\t\tpanic(\"recusion too deep\")\n\t}\n\t// fmt.Printf(\"\\t%v (%d %d) %d\\n\", a[start:end], start, end, el)\n\n\tswitch end - start {\n\tcase 0:\n\t\t// this should never happen\n\t\treturn -1\n\tcase 1:\n\t\tif a[start] == el {\n\t\t\treturn start\n\t\t} else {\n\t\t\treturn -1\n\t\t}\n\tdefault:\n\t\t// the core problem of binary search: how to split the array\n\t\t// so that it's always smaller than it was (no recursive loop)\n\t\t//\n\t\t// the idea about the solution is to split the thinking about the problem\n\t\t// into 2 separate sub-problems:\n\t\t// - how to split array into 2 smaller ones\n\t\t// - how to pick the proper array for later\n\t\t//\n\t\t// After the first problem is solved properly, second is simple \"if\" on indices.\n\t\t// The idea behind the split:\n\t\t// - 1st sub-array must be equal or larger by one than the 2nd:\n\t\t// [1 2 3 4] => [1 2] + [3 4]\n\t\t// [1 2 3] => [1 2] + [3]\n\t\t// [1 2] => [1] + [2]\n\t\tmid := (end + start + 1) / 2\n\t\tif el < a[mid] {\n\t\t\treturn binarySearchImpl(a, start, mid, el, recursionDepthLeft-1)\n\t\t} else {\n\t\t\treturn binarySearchImpl(a, mid, end, el, recursionDepthLeft-1)\n\t\t}\n\t}\n\n}", "func find(gs []*Geodesic, v Vector, minDistSq float64, start int) int {\n\tgs0 := gs[0]\n\tnextStart := start\n\tneighbors := gs0.Faces[start].Neighbors\n\tfor _, n := range neighbors {\n\t\tiDistSq := DistSq(gs0.Centers[n], v)\n\t\tif iDistSq < minDistSq {\n\t\t\tminDistSq = iDistSq\n\t\t\tnextStart = n\n\t\t}\n\t}\n\n\tif len(gs) == 1 {\n\t\t// There's a bug related to correctly classifying the neighbor of a\n\t\t// pentagon face, so this corrects for that.\n\t\tif nextStart == start {\n\t\t\treturn nextStart\n\t\t}\n\t\treturn find(gs, v, minDistSq, nextStart)\n\t}\n\n\treturn find(gs[1:], v, minDistSq, nextStart)\n}", "func getPermutations(iterable []int, r int) (permutations [][]int) {\n\tn := len(iterable)\n\tnFact := fact(n)\n\tfor i := 0; i < nFact; i++ {\n\t\tpermutations = append(permutations, make([]int, n))\n\t}\n\tpool := iterable\n\n\tif r > n {\n\t\treturn\n\t}\n\n\tindices := make([]int, n)\n\tfor i := range indices {\n\t\tindices[i] = i\n\t}\n\n\tcycles := make([]int, r)\n\tfor i := range cycles {\n\t\tcycles[i] = n - i\n\t}\n\n\tresult := make([]int, r)\n\tfor i, el := range indices[:r] {\n\t\tresult[i] = pool[el]\n\t}\n\tindex := 0\n\tcopy(permutations[index], result)\n\tindex++\n\n\tfor n > 0 {\n\t\ti := r - 1\n\t\tfor ; i >= 0; i-- {\n\t\t\tcycles[i]--\n\t\t\tif cycles[i] == 0 {\n\t\t\t\tindex := indices[i]\n\t\t\t\tfor j := i; j < n-1; j++ {\n\t\t\t\t\tindices[j] = indices[j+1]\n\t\t\t\t}\n\t\t\t\tindices[n-1] = index\n\t\t\t\tcycles[i] = n - i\n\t\t\t} else {\n\t\t\t\tj := cycles[i]\n\t\t\t\tindices[i], indices[n-j] = indices[n-j], indices[i]\n\n\t\t\t\tfor k := i; k < r; k++ {\n\t\t\t\t\tresult[k] = pool[indices[k]]\n\t\t\t\t}\n\t\t\t\tcopy(permutations[index], result)\n\t\t\t\tindex++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif i < 0 {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func insertKeyAndPtr(target *Node, key string, n *Node) {\n\tvar i int\n\tvar r Record\n\tfor i, r = range target.records {\n\t\tif key < r.key {\n\t\t\tbreak\n\t\t}\n\t}\n\n\trtmp := make([]Record, 0)\n\tctmp := make([]*Node, 0)\n\n\tswitch {\n\tcase key > r.key:\n\t\ttarget.records = append(target.records, Record{key: key, value: \"\"})\n\t\ttarget.childPtrs = append(target.childPtrs, n)\n\tcase i == 0:\n\t\trtmp = make([]Record, 1)\n\t\tctmp = make([]*Node, 1)\n\t\trtmp[0] = Record{key: key, value: \"\"}\n\t\trtmp = append(rtmp, target.records...)\n\n\t\tctmp[0] = target.childPtrs[0]\n\t\tctmp = append(ctmp, n)\n\t\tctmp = append(ctmp, target.childPtrs[1:]...)\n\t\ttarget.records = rtmp\n\t\ttarget.childPtrs = ctmp\n\tdefault:\n\t\trtmp = append(rtmp, target.records[:i]...)\n\t\trtmp = append(rtmp, Record{key: key, value: \"\"})\n\t\trtmp = append(rtmp, target.records[i:]...)\n\n\t\ti++ // Since we have more ptrs than records.\n\t\tctmp = append(ctmp, target.childPtrs[:i]...)\n\t\tctmp = append(ctmp, n)\n\t\tctmp = append(ctmp, target.childPtrs[i:]...)\n\t\ttarget.records = rtmp\n\t\ttarget.childPtrs = ctmp\n\n\t}\n}", "func arrayManipulation(n int32, queries [][]int32) int64 {\n\n\tvar ret int64\n\n\t// create a slice with n amount of zeros\n\tmainSlice := []int32{}\n\tvar i int32\n\tfor i = 0; i <= n; i++ {\n\t\t// append 'n' number of 0's to slice to begin\n\t\tmainSlice = append(mainSlice, 0)\n\t}\n\n\tmainSlice = addKValsToArr(mainSlice, queries)\n\n\ttemp := mainSlice[0]\n\tfor i = 0; i <= n; i++ {\n\t\tif mainSlice[i] > temp {\n\t\t\ttemp = mainSlice[i]\n\t\t}\n\t}\n\n\tret = int64(temp)\n\n\treturn ret\n}", "func fullIter[K comparable, V any](m map[K]V, f func(K, V)) {\n\tseen := map[K]bool{}\n\tfor done := false; !done; {\n\t\tdone = true\n\t\tfor k, v := range m {\n\t\t\tif seen[k] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseen[k] = true\n\t\t\tdone = false\n\n\t\t\tf(k, v)\n\t\t}\n\t}\n}", "func merge(nums1 []int, m int, nums2 []int, n int) {\n\tif n == 0 {\n\t\treturn\n\t}\n\n\tvar pos1, pos2 int\n\tfor i := 0; i < len(nums1); i++ {\n\t\tif pos1 < m {\n\t\t\tif nums1[pos1] <= nums2[pos2] {\n\t\t\t\tpos1++\n\t\t\t} else {\n\t\t\t\tidx := sort.SearchInts(nums2, nums1[pos1])\n\t\t\t\tif idx >= len(nums2) {\n\t\t\t\t\tnums2 = append(nums2, nums1[pos1])\n\t\t\t\t} else {\n\t\t\t\t\tnums2 = append(nums2[:idx], append([]int{nums1[pos1]}, nums2[idx:]...)...)\n\t\t\t\t}\n\t\t\t\tnums1[pos1] = nums2[0]\n\t\t\t\tnums2 = nums2[1:]\n\t\t\t\tpos1++\n\t\t\t}\n\t\t} else {\n\t\t\tnums1[i] = nums2[pos2]\n\t\t\tpos2++\n\t\t}\n\t}\n}", "func countAndSay(n int) string {\n\tif n == 1 { // special case\n\t\treturn \"1\"\n\t}\n\tpre, cur := \"\", \"1\"\n\thead, tail := 0, 0\n\n\ttmp := cur[0]\n\tlength := len(cur)\n\n\tfor i := 1; i < n; i++ { // 1 -> n -1\n\t\tlength = len(cur) // reset length\n\t\ttmp = cur[0] // reset tmp\n\t\thead = 0 // reset head and tail 0 0\n\t\tfor tail = 0; tail < length; tail++ {\n\t\t\tif cur[tail] == tmp { // find same as cache\n\t\t\t\thead++\n\t\t\t} else { // not found add tmp and cache pre then mark head -> 1\n\t\t\t\tpre = pre + strconv.Itoa(head) + string(tmp)\n\t\t\t\ttmp = cur[tail]\n\t\t\t\thead = 1\n\t\t\t}\n\n\t\t\tif tail == length-1 { // special case length-1 cache pre\n\t\t\t\tpre = pre + strconv.Itoa(head) + string(tmp)\n\t\t\t}\n\t\t}\n\t\tcur = pre // cur now\n\t\tpre = \"\" //reset\n\t}\n\treturn cur\n}", "func Tianyun_searchRange(nums []int, target int) []int {\n\n\t//O(n)\n//\tstartIndex:=-1\n//\tcount:=0\n//\n//\tfor i:=0;i<len(nums);i++{\n//\t\tif count==0&&nums[i]==target{\n//\t\t\tstartIndex = i\n//\t\t\tcount++\n//\n//\t\t}else if nums[i]==target{\n//\t\t\tcount++\n//\t\t}\n//}\n//\n// if count==0{\n// \treturn []int{-1,-1}\n// }else{\n// \treturn []int{startIndex,startIndex+count}\n// }\n\n\n\n//O(logn)\nif len(nums)==0{\n\treturn []int{-1,-1}\n}\n startIndex:=-1\n left:=0\n right:=len(nums)-1\n\n for left +1 <right{\n \tmid:=(left+right)/2\n \tif nums[mid]>=target{\n right = mid\n\t\t}else{\n\t\t\tleft =mid+1\n\t\t}\n\t }\n\t if nums[left]==target{\n\t \tstartIndex =left\n\t }else if nums[right]==target{\n\t \tstartIndex = right\n\t }else{\n\t \treturn []int{-1,-1}\n\t }\n\n\n\tleft=0\n\tright=len(nums)-1\n\n\tfor left +1 <right{\n\t\tmid:=(left+right)/2\n\t\tif nums[mid]<=target{\n\t\t\tleft = mid\n\t\t}else{\n\t\t\tright = mid\n\t\t}\n\t}\n\n\tif nums[right]==target{\n\t\treturn []int{startIndex,right}\n\t}else if nums[left]==target{\n\t\treturn []int{startIndex,left}\n\t}else{\n\t\treturn []int{-1,-1}\n\t}\n}", "func nomatch(arr []int16, ints []int16) []string {\n\n\tdmap := make(map[int16]bool)\n\tfor _, v := range arr {\n\t\tif _, ok := dmap[v]; !ok {\n\t\t\tdmap[v] = true\n\t\t}\n\t}\n\n\tfor _, v := range ints {\n\t\tdelete(dmap, v)\n\t}\n\n\tretval := []string{}\n\n\tfor k := range dmap {\n\t\tretval = append(retval, fmt.Sprintf(\"%d\", k))\n\t}\n\n\treturn retval\n}", "func get(seqno uint16, entries []entry, result []byte) (uint16, uint32, bool) {\n\tfor i := range entries {\n\t\tif entries[i].lengthAndMarker == 0 || entries[i].seqno != seqno {\n\t\t\tcontinue\n\t\t}\n\t\tvar n uint16\n\t\tif len(result) > 0 {\n\t\t\tn = uint16(copy(\n\t\t\t\tresult[:entries[i].length()],\n\t\t\t\tentries[i].buf[:]))\n\t\t} else {\n\t\t\tn = entries[i].length()\n\t\t}\n\t\treturn n, entries[i].timestamp, entries[i].marker()\n\t}\n\treturn 0, 0, false\n}", "func searchMergeList(db *sql.DB, listTable, setTable string, tb tokenTable, query rawTokenSet, k int, ignoreSelf bool) ([]searchResult, experimentResult) {\n\tvar expResult experimentResult\n\n\tstart := time.Now()\n\ttokens, _, _ := tb.process(query)\n\texpResult.PreprocDuration = int(time.Now().Sub(start) / time.Millisecond)\n\tac := newActionCollecter(len(tokens))\n\tstart = time.Now()\n\n\tac.start()\n\tcounter := make(map[int64]int)\n\tfor _, token := range tokens {\n\t\tentries := InvertedList(db, listTable, token)\n\t\texpResult.NumListRead++\n\t\texpResult.MaxListSizeRead = max(expResult.MaxListSizeRead, len(entries))\n\t\tac.addReadList(len(entries))\n\t\tfor _, entry := range entries {\n\t\t\tif ignoreSelf && entry.ID == query.ID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, seen := counter[entry.ID]; seen {\n\t\t\t\tcounter[entry.ID]++\n\t\t\t} else {\n\t\t\t\tcounter[entry.ID] = 1\n\t\t\t}\n\t\t}\n\t\texpResult.MaxCounterSize = max(expResult.MaxCounterSize, len(counter))\n\t}\n\th := &searchResultHeap{}\n\tfor id, overlap := range counter {\n\t\tpushCandidate(h, k, id, overlap)\n\t}\n\tresults := orderedResults(h)\n\tac.done()\n\n\texpResult.Duration = int(time.Now().Sub(start) / time.Millisecond)\n\texpResult.Actions = ac.collect()\n\texpResult.Results = writeResultString(results)\n\texpResult.QueryID = query.ID\n\texpResult.QuerySize = len(query.RawTokens)\n\texpResult.NumResult = len(results)\n\texpResult.QueryNumToken = len(tokens)\n\treturn results, expResult\n}", "func sink(data []pq.Key, i, l int) {\n\tfor 2*i+1 < l {\n\t\tj := 2*i + 1\n\t\tif j+1 < l && data[j].Less(data[j+1]) {\n\t\t\tj++\n\t\t}\n\t\tif data[j].Less(data[i]) {\n\t\t\treturn\n\t\t}\n\t\tswap(data, i, j)\n\t\ti = j\n\t}\n}", "func maybeOptimizeSetMembership(i Interpretable, inlist InterpretableCall) (Interpretable, error) {\n\targs := inlist.Args()\n\tlhs := args[0]\n\trhs := args[1]\n\tl, isConst := rhs.(InterpretableConst)\n\tif !isConst {\n\t\treturn i, nil\n\t}\n\t// When the incoming binary call is flagged with as the InList overload, the value will\n\t// always be convertible to a `traits.Lister` type.\n\tlist := l.Value().(traits.Lister)\n\tif list.Size() == types.IntZero {\n\t\treturn NewConstValue(inlist.ID(), types.False), nil\n\t}\n\tit := list.Iterator()\n\tvar typ ref.Type\n\tvalueSet := make(map[ref.Val]ref.Val)\n\tfor it.HasNext() == types.True {\n\t\telem := it.Next()\n\t\tif !types.IsPrimitiveType(elem) {\n\t\t\t// Note, non-primitive type are not yet supported.\n\t\t\treturn i, nil\n\t\t}\n\t\tif typ == nil {\n\t\t\ttyp = elem.Type()\n\t\t} else if typ.TypeName() != elem.Type().TypeName() {\n\t\t\treturn i, nil\n\t\t}\n\t\tvalueSet[elem] = types.True\n\t}\n\treturn &evalSetMembership{\n\t\tinst: inlist,\n\t\targ: lhs,\n\t\targTypeName: typ.TypeName(),\n\t\tvalueSet: valueSet,\n\t}, nil\n}", "func solveB(input []int) int {\n\t// We found a loop if we found the first occurrence of this first pattern.\n\tfirst := fmt.Sprintf(\"%v\", input)\n\tfor n := 0; ; n++ {\n\t\tredistribute(input)\n\t\tkey := fmt.Sprintf(\"%v\", input)\n\t\tif key == first {\n\t\t\treturn n + 1\n\t\t}\n\t}\n}", "func solve(check *[]bool, curList []int, ans *[][]int, nums []int) {\r\n n := len(nums)\r\n if len(curList) == n {\r\n tmp := make([]int, n)\r\n copy(tmp, curList)\r\n *ans = append(*ans, tmp)\r\n return\r\n }\r\n for i, num := range nums {\r\n if !(*check)[i] {\r\n curList = append(curList, num)\r\n (*check)[i] = true\r\n solve(check, curList, ans, nums)\r\n (*check)[i] = false\r\n curList = curList[:len(curList)-1]\r\n }\r\n }\r\n}", "func Test_DoIterativeStoreFindSucc(t *testing.T) {\n\tN := len(instance)\n\tfor i := 0; i < N/k+1; i++ {\n\t\tfrom := (rand.Int() % (N - 1)) + 1\n\t\tto := (rand.Int() % (N - 1)) + 1\n\t\tfor to == from {\n\t\t\tto = (rand.Int() % (N - 1)) + 1\n\t\t}\n\t\tkey := NewRandomID()\n\t\tvalue := []byte(key.AsString())\n\t\tfmt.Printf(\n\t\t\t\"IterativeStore from: %s\\nFind from: %s\\n\",\n\t\t\tinstance[from].NodeID.AsString(),\n\t\t\tinstance[to].NodeID.AsString())\n\t\tinstance[from].DoIterativeStore(key, value)\n\t\tassertContains(\n\t\t\tinstance[to].DoIterativeFindValue(key),\n\t\t\tstring(value),\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Cannot find value in %s stored by %s\\n\",\n\t\t\t\tinstance[to].NodeID.AsString(),\n\t\t\t\tinstance[from].NodeID.AsString()),\n\t\t\tt)\n\t\tassertContains(\n\t\t\tinstance[from].DoIterativeFindValue(key),\n\t\t\tstring(value),\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Cannot find value in %s stored by itself\\n\",\n\t\t\t\tinstance[from].NodeID.AsString()),\n\t\t\tt)\n\t}\n}", "func (uf unionFind) findRoot(i int) int {\n\t// if uf[i] == i {\n\t// \treturn i\n\t// }\n\n\t// uf[i] = uf.findRoot(uf[i])\n\t// return uf[i]\n\tp := uf[i]\n\tfor p != uf[i] {\n\t\ti = p\n\t\tp = uf[i]\n\t}\n\treturn p\n}", "func compute(opcode int, param []int, paramMode []int, memory []int, itrPtr *int, input int) (ret int) {\n\tret = -1\n\tvar input1, input2 int\n\tif paramMode[0] == 0 {\n\t\tinput1 = memory[param[0]]\n\t} else if paramMode[0] == 1 {\n\t\tinput1 = param[0]\n\t}\n\tif opcode != 3 && opcode != 4 {\n\t\tif paramMode[1] == 0 {\n\t\t\tinput2 = memory[param[1]]\n\t\t} else if paramMode[1] == 1 {\n\t\t\tinput2 = param[1]\n\t\t}\n\t}\n\n\tswitch opcode {\n\tcase 1:\n\t\tmemory[param[2]] = input1 + input2\n\t\t*itrPtr += 4\n\tcase 2:\n\t\tmemory[param[2]] = input1 * input2\n\t\t*itrPtr += 4\n\tcase 3:\n\t\tmemory[param[0]] = input\n\t\t*itrPtr += 2\n\tcase 4:\n\t\tif paramMode[0] == 0 {\n\t\t\tret = memory[param[0]]\n\t\t} else if paramMode[0] == 1 {\n\t\t\tret = param[0]\n\t\t}\n\t\t*itrPtr += 2\n\tcase 5:\n\t\tif input1 != 0 {\n\t\t\t*itrPtr = input2\n\t\t} else {\n\t\t\t*itrPtr += 3\n\t\t}\n\tcase 6:\n\t\tif input1 == 0 {\n\t\t\t*itrPtr = input2\n\t\t} else {\n\t\t\t*itrPtr += 3\n\t\t}\n\tcase 7:\n\t\tif input1 < input2 {\n\t\t\tmemory[param[2]] = 1\n\t\t} else {\n\t\t\tmemory[param[2]] = 0\n\t\t}\n\t\t*itrPtr += 4\n\tcase 8:\n\t\tif input1 == input2 {\n\t\t\tmemory[param[2]] = 1\n\t\t} else {\n\t\t\tmemory[param[2]] = 0\n\t\t}\n\t\t*itrPtr += 4\n\t}\n\treturn\n}" ]
[ "0.51199967", "0.4970042", "0.49105713", "0.49083084", "0.48748308", "0.485412", "0.48512843", "0.48137254", "0.47453874", "0.47391614", "0.47373337", "0.47229165", "0.4697703", "0.46932596", "0.46653837", "0.4663767", "0.46517563", "0.46424052", "0.46270257", "0.4625844", "0.46234512", "0.46135256", "0.46061948", "0.46046948", "0.45999008", "0.45983025", "0.45975864", "0.4593297", "0.45844164", "0.45838052", "0.45816568", "0.45741397", "0.45732152", "0.45726863", "0.4565319", "0.45638257", "0.45583394", "0.45538813", "0.45492685", "0.45429417", "0.4542569", "0.45403492", "0.45356947", "0.45328072", "0.45287874", "0.45253947", "0.4523547", "0.45213762", "0.452128", "0.45127618", "0.45104524", "0.45098275", "0.45087144", "0.45071116", "0.4505816", "0.4502775", "0.44991112", "0.44977993", "0.44953024", "0.4490953", "0.44908985", "0.4484807", "0.44818014", "0.44806296", "0.4480384", "0.44798732", "0.44739106", "0.44714916", "0.44706312", "0.44681644", "0.4464561", "0.44645128", "0.44595936", "0.44579345", "0.44489273", "0.4445706", "0.4445515", "0.44430867", "0.4440557", "0.4439604", "0.44317985", "0.44317788", "0.44308737", "0.44293213", "0.4427669", "0.4425082", "0.4424829", "0.442202", "0.44195503", "0.4417611", "0.44169477", "0.44138837", "0.44137406", "0.44093624", "0.4407914", "0.4406911", "0.4406885", "0.44068155", "0.44032273", "0.43988624", "0.43985397" ]
0.0
-1
fStudy is based on this
func GetIntField(myStruct interface{}, fieldName string) (ret int) { ps := reflect.ValueOf(&myStruct) // pointer to a struct => addressable s := ps.Elem() if s.Kind() == reflect.Struct { // exported field f := s.FieldByName(fieldName) if f.IsValid() { // A Value can be changed only if it is // addressable and was not obtained by // the use of unexported struct fields. if f.CanSet() { // instead of CanAdr if f.Kind() == reflect.Int { // the "set" case is incommented: // x := int64(7) // if !f.OverflowInt(x) { // f.SetInt(x) // } ret = int(f.Int()) } else { panic("not an int") } } else { panic("field can not set") } } else { panic("field invalid") } } else { panic("not a struct") } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *Deck) Study(filter Filter, shuffle bool) []*Card {\n\tcards := d.Sequence(shuffle)\n\tif filter == nil {\n\t\treturn cards\n\t}\n\n\tvar filtered []*Card\n\tfor _, c := range cards {\n\t\tif filter(c) {\n\t\t\tfiltered = append(filtered, c)\n\t\t}\n\t}\n\n\treturn filtered\n}", "func (o StudyOutput) StudyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Study) pulumi.StringOutput { return v.StudyId }).(pulumi.StringOutput)\n}", "func (st *State) Analysis() (_ analysisTmpl) { return }", "func (a *ClinicalMetadataServiceApiService) GetStudy(ctx _context.Context, studyId string) (Ga4ghStudy, *_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 Ga4ghStudy\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/studies/{study_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"study_id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", studyId)), -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 Ga4ghStudy\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 VerifyStudyGroup(GuildID string) uuid.UUID {\n\tvar sg StudyGroup\n\terr := DB.Where(\"guild_id = ? AND next_turn = ?\", GuildID, true).First(&sg).Error\n\tif err != nil {\n\t\tSid := uuid.NewV4()\n\t\tvar addDay int = (7 - int(time.Now().Weekday())) % 7\n\n\t\t// 獲得下個週日的晚上12:59\n\t\tendOfTime := time.Unix(GetTodayEnd(), 0).AddDate(0, 0, addDay)\n\t\tDB.Create(&StudyGroup{\n\t\t\tSID: Sid,\n\t\t\tTurn: 1,\n\t\t\tGuildID: GuildID,\n\t\t\tAttendance: 1,\n\t\t\tNextTurn: true,\n\t\t\tStartTime: Time(endOfTime),\n\t\t})\n\n\t\treturn Sid\n\t}\n\tt1 := time.Now().Unix()\n\tt2 := time.Time(sg.StartTime).Unix()\n\n\tif t1 >= t2 {\n\t\tSid := uuid.NewV4()\n\t\tvar addDay int = (7 - int(time.Now().Weekday())) % 7\n\n\t\t// 獲得下個週日的晚上12:59\n\t\tendOfTime := time.Unix(GetTodayEnd(), 0).AddDate(0, 0, addDay)\n\t\tDB.Create(&StudyGroup{\n\t\t\tSID: Sid,\n\t\t\tTurn: sg.Turn + 1,\n\t\t\tGuildID: GuildID,\n\t\t\tAttendance: 1,\n\t\t\tNextTurn: true,\n\t\t\tStartTime: Time(endOfTime),\n\t\t})\n\t\tsg.NextTurn = false\n\t\tDB.Save(&sg)\n\t\treturn Sid\n\t}\n\treturn sg.SID\n}", "func (suite *IndexerSuite) usfc(uid string, lang string) {\n\tr := require.New(suite.T())\n\terr := updateSourceFileContent(uid, lang)\n\tr.Nil(err)\n}", "func (GuitarBass) FriedmanAmplifiersCollection(){}", "func (f *Fragment) AddFullSample(s *FullSample) {\n\t//TODO. Handle multiple tracks and truns\n\t//Need to decide limits, like working on one Track/Trun at a time\n\t//Then need to set the offset finally\n\ttrun := f.Moof.Traf.Trun\n\tif trun.SampleCount() == 0 {\n\t\ttfdt := f.Moof.Traf.Tfdt\n\t\ttfdt.SetBaseMediaDecodeTime(s.DecodeTime)\n\t}\n\ttrun.AddSample(&s.Sample)\n\tmdat := f.Mdat\n\tmdat.AddSampleData(s.Data)\n}", "func (o StudyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Study) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (rf *Raft) Snapshot(index int, snapshot []byte) {\n\t// Your code here (2D).\n\n}", "func (rf *Raft) Snapshot(index int, snapshot []byte) {\n\t// Your code here (2D).\n\n}", "func (rf *Raft) Snapshot(index int, snapshot []byte) {\n\t// Your code here (2D).\n\n}", "func (rf *Raft) Snapshot(index int, snapshot []byte) {\n\t// Your code here (2D).\n\n}", "func (rf *Raft) Snapshot(index int, snapshot []byte) {\n\t// Your code here (2D).\n\n}", "func (rf *Raft) Snapshot(index int, snapshot []byte) {\n\t// Your code here (2D).\n\n}", "func (rf *Raft) Snapshot(index int, snapshot []byte) {\n\t// Your code here (2D).\n\n}", "func (f *Facts) Name() string {\n\treturn \"experiment\"\n}", "func (ctc *ClinicalTrialCreate) AddStudyEligibility(s ...*StudyEligibility) *ClinicalTrialCreate {\n\tids := make([]int, len(s))\n\tfor i := range s {\n\t\tids[i] = s[i].ID\n\t}\n\treturn ctc.AddStudyEligibilityIDs(ids...)\n}", "func IsStudyGroupExist(GuildID string) bool {\n\terr := DB.Where(\"guild_id = ? AND next_turn = ?\", GuildID, true).First(&StudyGroup{}).Error\n\treturn err != nil\n}", "func (m *MockStudyServiceApiClient) GetSurveyDefForStudy(arg0 context.Context, arg1 *api.SurveyVersionReferenceRequest, arg2 ...grpc.CallOption) (*api.Survey, 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, \"GetSurveyDefForStudy\", varargs...)\n\tret0, _ := ret[0].(*api.Survey)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func stsf() {\n\tswitch typ = implicitArrayDeref(x.typ.Underlying()); t := typ.(type) {\n\tcase *Basic:\n\t}\n}", "func CalculateAverage(grades map[string]Module) float64 {\n\tvar teamprojekt Module\n\t// var thesis Module\n\t// var research []Module\n\tvar csFundamentals []Module\n\tvar ieFundamentals []Module\n\tvar mmmFundamentals []Module\n\tvar specs []Module\n\tvar grade float64\n\tvar credits float64\n\tfor _, v := range grades {\n\t\t// Teamproject\n\t\tif v.ExamID == 420500 {\n\t\t\tteamprojekt = v\n\t\t\t// Scientific Research Seminar\n\t\t} else if v.ExamID == 420000 {\n\t\t\tspecs = append(specs, v)\n\t\t\t// Fundamental Course CS\n\t\t} else if 400499 < v.ExamID && v.ExamID < 400600 {\n\t\t\tcsFundamentals = append(csFundamentals, v)\n\t\t\t// Specialization Course CS\n\t\t} else if 400599 < v.ExamID && v.ExamID < 400700 {\n\t\t\tspecs = append(specs, v)\n\t\t\t// Fundamental Course IE\n\t\t} else if 410499 < v.ExamID && v.ExamID < 410600 {\n\t\t\tieFundamentals = append(ieFundamentals, v)\n\t\t\t// Specialization Course IE\n\t\t} else if 410599 < v.ExamID && v.ExamID < 410700 {\n\t\t\tspecs = append(specs, v)\n\t\t\t// Fundamental Course MMM\n\t\t} else if 140000 < v.ExamID && v.ExamID < 140900 {\n\t\t\tmmmFundamentals = append(mmmFundamentals, v)\n\t\t\t// Specialization Course Area IS\n\t\t} else if 170000 < v.ExamID && v.ExamID < 170999 {\n\t\t\tspecs = append(specs, v)\n\t\t\t// Specialization Course Seminar\n\t\t} else if 430000 < v.ExamID && v.ExamID < 430999 {\n\t\t\tspecs = append(specs, v)\n\t\t}\n\t}\n\tgrade += teamprojekt.Grade * teamprojekt.Bonus\n\tcredits += teamprojekt.Bonus\n\tc, a := AverageGroup(csFundamentals...)\n\tcredits += c\n\tgrade += a * c\n\tc, a = AverageGroup(ieFundamentals...)\n\tcredits += c\n\tgrade += a * c\n\tc, a = AverageGroup(mmmFundamentals...)\n\tcredits += c\n\tgrade += a * c\n\tc, a = AverageGroup(specs...)\n\tcredits += c\n\tgrade += a * c\n\treturn truncate(grade/credits, 2)\n}", "func (ctc *ClinicalTrialCreate) SetStudyID(s string) *ClinicalTrialCreate {\n\tctc.mutation.SetStudyID(s)\n\treturn ctc\n}", "func (s *studentState) selectQuestion() Question {\n\t// If the debugger set a specific next question, then that is the\n\t// question we are going to return.\n\tif s.nextQuestion != nil {\n\t\tq := s.nextQuestion\n\t\ts.nextQuestion = nil\n\t\treturn q\n\t}\n\t// Runs the training module.\n\tif err := s.train(); err != nil {\n\t\tpanic(fmt.Sprintf(\"training error: %v\", err))\n\t}\n\t// These are the possible questions.\n\tpossibles := make([]Question, 0)\n\t// Goes through the set of questions in the content.\n\tfor _, q := range s.content.Questions {\n\t\t// If we already answered the question (or it got burnt by the\n\t\t// debugger) then ignore this question.\n\t\tif _, ok := s.burnt[q]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tconcepts := q.getTrainingConcepts(nil)\n\t\t// If this question has no registered concepts that'd be weird, but\n\t\t// it is a possible question.\n\t\tif len(concepts) == 0 {\n\t\t\tpossibles = append(possibles, q)\n\t\t\tcontinue\n\t\t}\n\t\t// If this question has any concepts in it that are not mastered\n\t\t// yet, it is a possible question. This step skips any questions\n\t\t// that has concepts that are all mastered.\n\t\tfor _, c := range concepts {\n\t\t\tif s.scores[c] < threshold {\n\t\t\t\tpossibles = append(possibles, q)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\t// Did the student exhaust the content?\n\tif len(possibles) == 0 {\n\t\treturn nil\n\t}\n\t// Sorts the possible questions so that the question with the highest\n\t// average skill score is first. This is the \"race to mastery\" step.\n\tsort.Slice(possibles, func(i, j int) bool {\n\t\treturn s.avg(possibles[i]) > s.avg(possibles[j])\n\t})\n\t// If tracing is enabled, writes some tracing output.\n\tif trace != nil {\n\t\tfor _, q := range possibles {\n\t\t\ttrace.print(\"%32s\", q.getShortName())\n\t\t\tfor _, c := range q.getTrainingConcepts(nil) {\n\t\t\t\ttrace.print(\"%20s(%f)\", c.shortName, s.scores[c])\n\t\t\t}\n\t\t\ttrace.println(\" avg=%f\", s.avg(q))\n\t\t}\n\t}\n\treturn possibles[0]\n}", "func (h *DirectImageStreamMigrationHandler) getSAR() auth.SelfSubjectAccessReview {\n\treturn auth.SelfSubjectAccessReview{\n\t\tSpec: auth.SelfSubjectAccessReviewSpec{\n\t\t\tResourceAttributes: &auth.ResourceAttributes{\n\t\t\t\tGroup: \"apps\",\n\t\t\t\tResource: \"DirectImageStreamMigration\",\n\t\t\t\tNamespace: h.directImageStream.Namespace,\n\t\t\t\tName: h.directImageStream.Name,\n\t\t\t\tVerb: \"get\",\n\t\t\t},\n\t\t},\n\t}\n}", "func (m *MockStudyServiceApiClient) GetStudy(arg0 context.Context, arg1 *api.StudyReferenceReq, arg2 ...grpc.CallOption) (*api.Study, 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, \"GetStudy\", varargs...)\n\tret0, _ := ret[0].(*api.Study)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func(this*Window)File(file string)(io.ReadWriteSeeker,error){\nfid,ok:=this.files[file]\nif!ok{\nvar err error\nif fid,err= fsys.Open(fmt.Sprintf(\"%d/%s\",this.id,file),plan9.ORDWR);err!=nil{\nif fid,err= fsys.Open(fmt.Sprintf(\"%d/%s\",this.id,file),plan9.OREAD);err!=nil{\nif fid,err= fsys.Open(fmt.Sprintf(\"%d/%s\",this.id,file),plan9.OWRITE);err!=nil{\nreturn nil,err\n}\n}\n}\nthis.files[file]= fid\n}\nvar f io.ReadWriteSeeker= fid\n\n\n/*71:*/\n\n\n//line goacme.w:1016\n\nf= &wrapper{f:f}\n\n\n\n\n\n/*:71*/\n\n\n//line goacme.w:334\n\nreturn f,nil\n}", "func (l *leaf) survey(vs []*View, fun func(x, y float64, e interface{})) {\n\tfor i := range l.ps {\n\t\tp := &l.ps[i]\n\t\tif !p.zeroed() && contains(vs, p.x, p.y) {\n\t\t\tfor i := range p.elems {\n\t\t\t\tfun(p.x, p.y, p.elems[i])\n\t\t\t}\n\t\t}\n\t}\n}", "func (t *Biologist) Analysis(generation int) *Analysis {\n\tif generation < 0 {\n\t\treturn nil\n\t}\n\tif generation < t.analyses.Count() {\n\t\tanalysis := t.analyses.Get(generation)\n\t\treturn &analysis\n\t} else if t.stabilityDetector.Detected {\n\t\tcycleGen := t.stabilityDetector.CycleStart + ((generation - t.stabilityDetector.CycleStart) % t.stabilityDetector.CycleLength)\n\t\t// t.log.Printf(\"Stable generation '%d' translated to cycle generation '%d'\\n\", generation, cycleGen)\n\n\t\tstableAnalysis := new(Analysis)\n\t\t*stableAnalysis = t.analyses.Get(cycleGen)\n\t\tstableAnalysis.Status = Stable\n\n\t\treturn stableAnalysis\n\t}\n\treturn nil\n}", "func GetStudy(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *StudyState, opts ...pulumi.ResourceOption) (*Study, error) {\n\tvar resource Study\n\terr := ctx.ReadResource(\"google-native:ml/v1:Study\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func stage1() {\n\tlog.Println(\"stage 1\")\n\n\tminimal, err := pdf.Open(\"h7-minimal.pdf\")\n\tif err != nil {\n\t\tlog.Fatalln(errgo.Details(err))\n\t}\n\n\t// page\n\tpage := minimal.Get(pdf.ObjectReference{ObjectNumber: 4}).(pdf.Dictionary)\n\tpage[pdf.Name(\"Annots\")] = pdf.ObjectReference{ObjectNumber: 7}\n\tminimal.Add(pdf.IndirectObject{\n\t\tObjectReference: pdf.ObjectReference{ObjectNumber: 4},\n\t\tObject: page,\n\t})\n\n\t// annotation array\n\tminimal.Add(pdf.IndirectObject{\n\t\tObjectReference: pdf.ObjectReference{ObjectNumber: 7},\n\t\tObject: pdf.Array{\n\t\t\tpdf.ObjectReference{ObjectNumber: 8},\n\t\t\tpdf.ObjectReference{ObjectNumber: 9},\n\t\t\tpdf.ObjectReference{ObjectNumber: 10},\n\t\t\tpdf.ObjectReference{ObjectNumber: 11},\n\t\t},\n\t})\n\n\t// annotation\n\tminimal.Add(pdf.IndirectObject{\n\t\tObjectReference: pdf.ObjectReference{ObjectNumber: 8},\n\t\tObject: pdf.Dictionary{\n\t\t\tpdf.Name(\"Type\"): pdf.Name(\"Annot\"),\n\t\t\tpdf.Name(\"Subtype\"): pdf.Name(\"Text\"),\n\t\t\tpdf.Name(\"Rect\"): pdf.Array{\n\t\t\t\tpdf.Integer(44),\n\t\t\t\tpdf.Integer(616),\n\t\t\t\tpdf.Integer(162),\n\t\t\t\tpdf.Integer(735),\n\t\t\t},\n\t\t\tpdf.Name(\"Contents\"): pdf.String(\"Text #1\"),\n\t\t\tpdf.Name(\"Open\"): pdf.Boolean(true),\n\t\t},\n\t})\n\n\t// annotation\n\tminimal.Add(pdf.IndirectObject{\n\t\tObjectReference: pdf.ObjectReference{ObjectNumber: 9},\n\t\tObject: pdf.Dictionary{\n\t\t\tpdf.Name(\"Type\"): pdf.Name(\"Annot\"),\n\t\t\tpdf.Name(\"Subtype\"): pdf.Name(\"Text\"),\n\t\t\tpdf.Name(\"Rect\"): pdf.Array{\n\t\t\t\tpdf.Integer(224),\n\t\t\t\tpdf.Integer(668),\n\t\t\t\tpdf.Integer(457),\n\t\t\t\tpdf.Integer(735),\n\t\t\t},\n\t\t\tpdf.Name(\"Contents\"): pdf.String(\"Text #2\"),\n\t\t\tpdf.Name(\"Open\"): pdf.Boolean(false),\n\t\t},\n\t})\n\n\t// annotation\n\tminimal.Add(pdf.IndirectObject{\n\t\tObjectReference: pdf.ObjectReference{ObjectNumber: 10},\n\t\tObject: pdf.Dictionary{\n\t\t\tpdf.Name(\"Type\"): pdf.Name(\"Annot\"),\n\t\t\tpdf.Name(\"Subtype\"): pdf.Name(\"Text\"),\n\t\t\tpdf.Name(\"Rect\"): pdf.Array{\n\t\t\t\tpdf.Integer(239),\n\t\t\t\tpdf.Integer(393),\n\t\t\t\tpdf.Integer(328),\n\t\t\t\tpdf.Integer(622),\n\t\t\t},\n\t\t\tpdf.Name(\"Contents\"): pdf.String(\"Text #3\"),\n\t\t\tpdf.Name(\"Open\"): pdf.Boolean(true),\n\t\t},\n\t})\n\n\t// annotation\n\tminimal.Add(pdf.IndirectObject{\n\t\tObjectReference: pdf.ObjectReference{ObjectNumber: 11},\n\t\tObject: pdf.Dictionary{\n\t\t\tpdf.Name(\"Type\"): pdf.Name(\"Annot\"),\n\t\t\tpdf.Name(\"Subtype\"): pdf.Name(\"Text\"),\n\t\t\tpdf.Name(\"Rect\"): pdf.Array{\n\t\t\t\tpdf.Integer(34),\n\t\t\t\tpdf.Integer(398),\n\t\t\t\tpdf.Integer(225),\n\t\t\t\tpdf.Integer(575),\n\t\t\t},\n\t\t\tpdf.Name(\"Contents\"): pdf.String(\"Text #4\"),\n\t\t\tpdf.Name(\"Open\"): pdf.Boolean(false),\n\t\t},\n\t})\n\n\terr = minimal.Save()\n\tif err != nil {\n\t\tlog.Fatalln(errgo.Details(err))\n\t}\n}", "func (s *Service) getExperimentDetail(c *gin.Context) {}", "func (o StudyOutput) State() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Study) pulumi.StringOutput { return v.State }).(pulumi.StringOutput)\n}", "func (fdb *fdbSlice) Snapshot() (Snapshot, error) {\n\n\ts := &fdbSnapshot{id: fdb.id,\n\t\tidxDefnId: fdb.idxDefnId,\n\t\tidxInstId: fdb.idxInstId,\n\t\tmain: fdb.main[0],\n\t\tback: fdb.back[0]}\n\n\t//store snapshot seqnum for main index\n\t{\n\t\ti, err := fdb.main[0].DbInfo()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tseq := i.LastSeqNum()\n\t\ts.mainSeqNum = seq\n\t}\n\n\t//store snapshot seqnum for back index\n\t{\n\t\ti, err := fdb.back[0].DbInfo()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tseq := i.LastSeqNum()\n\t\ts.backSeqNum = seq\n\t}\n\n\tcommon.Debugf(\"ForestDBSlice::Snapshot \\n\\tSliceId %v IndexInstId %v Created New \"+\n\t\t\"Snapshot %v\", fdb.id, fdb.idxInstId, s)\n\n\treturn s, nil\n}", "func Medical_xray_upload(w http.ResponseWriter, r *http.Request) {\n\n// IN w : response-writer\n// IN r : request- paramete\n\n// fmt.Fprintf( w, \"medical_xray_upload start \\n\" )\n\n var bucket string\n\n var guest_medical_xray type6.Guest_Medical_Xray\n\n bucket = \"sample-7777\" // get bucket name\n\n///\n/// get file name\n///\n\n\tfile_data, fh, err := r.FormFile(\"image\")\n\n\tif err != nil {\n\t\treturn\n\n\t}\n\n//\tfmt.Fprintf( w, \"medical_xray_upload : fh %v\\n\", fh )\n\n\n//\tst_writer_minor , _ := storage2.Storage_basic( \"create\" ,bucket ,fh.Filename , w , r )\n\n// st_writer, _ := st_writer_minor.(*storage.Writer)\n\n f_name := fh.Filename\n\n// st_writer := storage2.File_Create ( w ,r ,bucket ,f_name )\n\n// content_type := \"image/png; charset=utf-8\"\n\n content_type := fh.Header.Get(\"Content-Type\")\n\n st_writer := storage2.File_Create2 ( w ,r ,bucket ,f_name ,content_type )\n\n///\n/// copy select file and create new file in storage\n///\n\n\tif _, err := io.Copy(st_writer, file_data); err != nil {\n\t http.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif err := st_writer.Close(); err != nil {\n\t http.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n///\n/// get current guest name\n///\n\n guest_temp_slice := trans5.Guest_temp ( w , r )\n\n// guest_name := guest_temp_slice[0].Guest_Name\n// _ = guest_temp_slice[0].Guest_Name\n\n date_w := time.Now()\n\n guest_medical_xray.Date = fmt.Sprintf(\"%04d/%02d/%02d/%02d/%02d/%02d\",date_w.Year(), date_w.Month(),date_w.Day(), date_w.Hour(), date_w.Minute(), date_w.Second())\n\n guest_medical_xray.Guest_No = guest_temp_slice[0].Guest_No\n\n guest_medical_xray.Guest_Name = guest_temp_slice[0].Guest_Name\n\n guest_medical_xray.File_Name = f_name\n\n\tconst publicURL = \"https://storage.googleapis.com/%s/%s\"\n\tguest_medical_xray.Url = fmt.Sprintf(publicURL, bucket , f_name )\n\n///\n/// put new xray inf. in d.s.\n///\n\n projectID := os.Getenv(\"GOOGLE_CLOUD_PROJECT\")\n\n if projectID == \"\" {\n\n projectID = \"sample-7777\"\n\n\t}\n\n ctx := context.Background()\n\n client, err := datastore.NewClient(ctx, projectID)\n if err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n new_key := datastore.IncompleteKey(\"Guest_Medical_Xray\", nil)\n\n if _, err = client.Put(ctx, new_key, &guest_medical_xray ); err != nil {\n\n\t\thttp.Error(w,err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n///\n/// show xray inf. on web\n///\n\n process4.Medical_xray_show(w , r ,guest_medical_xray.Guest_No)\n\n//\tfmt.Fprintf( w, \"medical_xray_upload : normal end \\n\" )\n\n}", "func stage2() {\n\tlog.Println(\"stage 2\")\n\n\tminimal, err := pdf.Open(\"h7-minimal.pdf\")\n\tif err != nil {\n\t\tlog.Fatalln(errgo.Details(err))\n\t}\n\n\tannotation := minimal.Get(pdf.ObjectReference{ObjectNumber: 10}).(pdf.Dictionary)\n\tannotation[pdf.Name(\"Contents\")] = pdf.String(\"Modified Text #3\")\n\tminimal.Add(pdf.IndirectObject{\n\t\tObjectReference: pdf.ObjectReference{ObjectNumber: 10},\n\t\tObject: annotation,\n\t})\n\n\terr = minimal.Save()\n\tif err != nil {\n\t\tlog.Fatalln(errgo.Details(err))\n\t}\n}", "func (o StudyOutput) StudyConfig() GoogleCloudMlV1__StudyConfigResponseOutput {\n\treturn o.ApplyT(func(v *Study) GoogleCloudMlV1__StudyConfigResponseOutput { return v.StudyConfig }).(GoogleCloudMlV1__StudyConfigResponseOutput)\n}", "func (s student) sayHello() {\n\tfmt.Println(\"halo\", s.name)\n\n}", "func Fac(logger Logger) LoggerFactory {\n\treturn func(_ Level, _ Scene) Logger {\n\t\treturn logger\n\t}\n}", "func (sampler *Sampler)PickVariable(esd *ESD) {\t\n rr := rand.Intn(3)\n if rr <=0 && esd.hasParticipants() {\n sampler.Resample_p(esd, Pick_participant(esd.Label))\n } else if rr<=1 && len(esd.Label) < numTop {\n sampler.Resample_t(esd, pick_event(esd.Tau))\n } else{\n sampler.Resample_v(esd)\n }\n}", "func InitReviewer() {\n\n}", "func journalAssessment(ctx context.Context, xbiz *XBusiness, d time.Time, a *Assessment, d1, d2 *time.Time) (Journal, error) {\n\tfuncname := \"journalAssessment\"\n\t// Console(\"*** Entered %s\\n\", funcname)\n\t// Console(\"%s: d = %s, d1 = %s, d2 = %s\\n\", funcname, d.Format(RRDATEREPORTFMT), d1.Format(RRDATEREPORTFMT), d2.Format(RRDATEREPORTFMT))\n\t// Console(\"%s: Assessment: PASMID = %d, RentCycle = %d, ProrationCycle = %d, Start = %s, Stop = %s\\n\", funcname, a.PASMID, a.RentCycle, a.ProrationCycle, a.Start.Format(RRDATETIMEW2UIFMT), a.Stop.Format(RRDATETIMEW2UIFMT))\n\tvar j Journal\n\n\t// pf, num, den, start, stop, err := ProrateAssessment(ctx, xbiz, a, &d, d1, d2)\n\tpf, _, _, _, _, err := ProrateAssessment(ctx, xbiz, a, &d, d1, d2)\n\tif err != nil {\n\t\t// Console(\"%s: exiting. err = %s\\n\", funcname, err.Error())\n\t\treturn j, err\n\t}\n\n\t// Console(\"%s: A:: **** AFTER PRORATION CHECK **** pf = %6.4f, num = %d, den = %d, start = %s, stop = %s\\n\", funcname, pf, num, den, start.Format(RRDATEFMT3), stop.Format(RRDATEFMT3))\n\t// Console(\"%s: B:: After ProrateAssessment: start = %s, stop = %s\\n\", funcname, start.Format(RRDATETIMEW2UIFMT), stop.Format(RRDATETIMEW2UIFMT))\n\n\t//--------------------------------------------------------------------------------------\n\t// This is a safeguard against issues encountered in Feb 2018 where rent assessments\n\t// continued after the RentalAgreement RentStop date.\n\t//--------------------------------------------------------------------------------------\n\tif pf < float64(0) {\n\t\tpf = float64(0)\n\t}\n\n\t// Console(\"%s: a.ASMTID = %d, d = %s, d1 = %s, d2 = %s\\n\", funcname, a.ASMID, d.Format(RRDATEFMT4), d1.Format(RRDATEFMT4), d2.Format(RRDATEFMT4))\n\t// Console(\"%s: pf = %f, num = %d, den = %d, start = %s, stop = %s\\n\", funcname, pf, num, den, start.Format(RRDATEFMT4), stop.Format(RRDATEFMT4))\n\n\tj = Journal{BID: a.BID, Dt: d, Type: JNLTYPEASMT, ID: a.ASMID}\n\n\tasmRules, err := GetAssessmentAccountRule(ctx, a)\n\tif err != nil {\n\t\t// Console(\"%s: exiting. err = %s\\n\", funcname, err.Error())\n\t\treturn j, err\n\t}\n\n\t// Console(\"%s: C:: Parsing account rule: %s Amount = %8.2f\\n\", funcname, asmRules, a.Amount)\n\tm, err := ParseAcctRule(ctx, xbiz, a.RID, d1, d2, asmRules, a.Amount, pf) // a rule such as \"d 11001 1000.0, c 40001 1100.0, d 41004 100.00\"\n\tif err != nil {\n\t\t// Console(\"%s: C1:: exiting. err = %s\\n\", funcname, err.Error())\n\t\treturn j, err\n\t}\n\n\t// Console(\"%s: m = %#v\\n\", funcname, m)\n\t// for i := 0; i < len(m); i++ {\n\t// \tConsole(\"D:: m[%d].Amount = %f, .Action = %s .Expr = %s\\n\", i, m[i].Amount, m[i].Action, m[i].Expr)\n\t// }\n\n\t_, j.Amount = sumAllocations(&m)\n\tj.Amount = RoundToCent(j.Amount)\n\n\t// Console(\"%s: E:: j.Amount = %8.2f, pf = %8.5f\\n\", funcname, j.Amount, pf)\n\n\t//------------------------------------------------------------------------------------------------------\n\t// THIS BLOCK OF CODE SHOULD BE DELETED. IT SHOULD BE HANDLED IN ASSESSMENT CODE, NOT JOURNAL CODE.\n\t//=====================================================================================================\n\t// the assessment amount may have\n\t// been prorated as it was a newly created recurring assessment for a RentalAgreement that was either\n\t// just beginning or just ending. If so, we'll update the assessment amount here the calculated\n\t// j.Amount != a.Amount\n\t//------------------------------------------------------------------------------------------------------\n\t// if pf < 1.0 {\n\t// \tConsole(\"%s: F:: will update assessment\\n\", funcname)\n\t// \ta.Amount = j.Amount // update to the prorated amount\n\t// \ta.Start = start // adjust to the dates used in the proration\n\t// \ta.Stop = stop // adjust to the dates used in the proration\n\t// \ta.Comment = fmt.Sprintf(\"Prorated for %d of %d %s\", num, den, ProrationUnits(a.ProrationCycle))\n\t// \tConsole(\"%s: G:: a.Amount = %8.2f\\n\", funcname, a.Amount)\n\t// \tif err := UpdateAssessment(ctx, a); err != nil {\n\t// \t\terr = fmt.Errorf(\"Error updating prorated assessment amount: %s\", err.Error())\n\t// \t\tConsole(\"%s: H:: exiting. err = %s\\n\", funcname, err.Error())\n\t// \t\treturn j, err\n\t// \t}\n\t// \tConsole(\"%s: I:: Updating ASMID = %d, Amount = %8.2f\\n\", funcname, a.ASMID, a.Amount)\n\t// }\n\t// Console(\"%s: J:: ASMID = %d, Amount = %8.2f\\n\", funcname, a.ASMID, a.Amount)\n\n\t//-------------------------------------------------------------------------------------------\n\t// In the event that we need to prorate, pull together the pieces and determine the\n\t// fractional amounts so that all the entries can net to 0.00. Essentially, this means\n\t// handling the $0.01 off problem when dealing with fractional numbers. The way we'll\n\t// handle this is to apply the extra cent to the largest number\n\t//-------------------------------------------------------------------------------------------\n\tif pf < 1.0 {\n\t\t// new method using ProcessSum\n\t\tvar asum []SumFloat\n\t\tfor i := 0; i < len(m); i++ {\n\t\t\tvar b SumFloat\n\t\t\tif m[i].Action == \"c\" {\n\t\t\t\tb.Val = -m[i].Amount\n\t\t\t} else {\n\t\t\t\tb.Val = m[i].Amount\n\t\t\t}\n\t\t\tb.Amount = RoundToCent(b.Val)\n\t\t\tb.Remainder = b.Amount - b.Val\n\t\t\tasum = append(asum, b)\n\t\t}\n\t\tProcessSumFloats(asum)\n\t\tfor i := 0; i < len(asum); i++ {\n\t\t\tif m[i].Action == \"c\" {\n\t\t\t\tm[i].Amount = -asum[i].Amount // the adjusted value after ProcessSumFloats\n\t\t\t} else {\n\t\t\t\tm[i].Amount = asum[i].Amount // the adjusted value after ProcessSumFloats\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// Console(\"INSERTING JOURNAL: Date = %s, Type = %d, amount = %f\\n\", j.Dt, j.Type, j.Amount)\n\n\tjid, err := InsertJournal(ctx, &j)\n\tif err != nil {\n\t\tLogAndPrintError(funcname, err)\n\t\t// Console(\"%s: exiting. err = %s\\n\", funcname, err.Error())\n\t\treturn j, err\n\t}\n\n\ts := \"\"\n\tfor i := 0; i < len(m); i++ {\n\t\ts += fmt.Sprintf(\"%s %s %.2f\", m[i].Action, m[i].AcctExpr, RoundToCent(m[i].Amount))\n\t\tif i+1 < len(m) {\n\t\t\ts += \", \"\n\t\t}\n\t}\n\tif jid > 0 {\n\t\tvar ja JournalAllocation\n\t\tja.JID = jid\n\t\tja.RID = a.RID\n\t\tja.ASMID = a.ASMID\n\t\tja.Amount = RoundToCent(j.Amount)\n\t\tja.AcctRule = s\n\t\tja.BID = a.BID\n\t\tja.RAID = a.RAID\n\n\t\t// Console(\"INSERTING JOURNAL-ALLOCATION: ja.JID = %d, ja.ASMID = %d, ja.RAID = %d\\n\", ja.JID, ja.ASMID, ja.RAID)\n\t\tif _, err = InsertJournalAllocationEntry(ctx, &ja); err != nil {\n\t\t\tLogAndPrintError(funcname, err)\n\t\t\t// Console(\"%s: exiting. err = %s\\n\", funcname, err.Error())\n\t\t\treturn j, err\n\t\t}\n\t\tj.JA = append(j.JA, ja)\n\t}\n\n\t// Console(\"%s: exiting\\n\", funcname)\n\treturn j, err\n}", "func (f *FaasController) Inherit(superSpec *supervisor.Spec, previousGeneration supervisor.Object) {\n\tpreviousGeneration.Close()\n\tf.Init(superSpec)\n}", "func pudding_stir(prime *pudding) {\n\n}", "func newAnalysis(ep *whodunit.Episode, d *Detective) *Analysis {\n\treturn &Analysis{\n\t\tEpisode: ep,\n\t\tdetective: d,\n\t\tassetType: assetTypeForCloudService(d.cloudService),\n\t}\n}", "func lesson43(){\n\tvar kohei Human = &Person{\"kohei\"}\n\tDriveCar(kohei)\n}", "func (a *ClinicalMetadataServiceApiService) SearchStudies(ctx _context.Context, body Ga4ghSearchStudiesRequest) (Ga4ghSearchStudiesResponse, *_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 Ga4ghSearchStudiesResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/studies/search\"\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{\"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 = &body\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 Ga4ghSearchStudiesResponse\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 MainObjectExam() {\n\tpeople := People{\n\t\t{\n\t\t\tname: \"Nam\",\n\t\t\tage: 19,\n\t\t\theight: 1.71,\n\t\t},\n\t\t{\n\t\t\tname: \"Ngọc\",\n\t\t\tage: 20,\n\t\t\theight: 1.81,\n\t\t},\n\t\t{\n\t\t\tname: \"Ảnh\",\n\t\t\tage: 22,\n\t\t\theight: 1.81,\n\t\t},\n\t\t{\n\t\t\tname: \"Việt\",\n\t\t\tage: 19,\n\t\t\theight: 1.81,\n\t\t},\n\t}\n\tfor i, s := range people {\n\t\tfmt.Println(i, s.in())\n\t}\n\t// fmt.Println(people[:2])\n\t// people.saveFile(\"user\")\n\t// name, _ := readFile(\"user\")\n\t// fmt.Println(\"Text from file\", name)\n\trandUser := people.getRandomPerson()\n\tfmt.Printf(\"Random user with name: %v\", randUser.name)\n\n\treturn\n}", "func (GuitarBass) SuhrSE100Amplifier(){}", "func FullStory(ctx context.Context, client streamexp.ReadMyStoryServiceClient) error {\n\n}", "func (f Fortune) Stake() decimal.Decimal { return f.stake }", "func (ctc *ClinicalTrialCreate) AddStudyEligibilityIDs(ids ...int) *ClinicalTrialCreate {\n\tctc.mutation.AddStudyEligibilityIDs(ids...)\n\treturn ctc\n}", "func main() {\n// \tfmt.Println(os.Args[0])\n\t// Read the file and dump into the slice of structs\n\tdm := SummaryReport.ReadFile(infile)\n// \tfor _, v := range dm {\n\t\tfmt.Println(*dm[0])\n// \t}\n\t\n// \tCompute number of subjects by treatment group\n\t\t\n// \tTurn values into strings\n\t\t\n// \tCompute number of non-mising Age values by TG\n\t\t\n// \tTurn values into strings\n\t\t\n// \tCompute mean of age by TG and SD by TG\n\t\t\n// \tTurn Mean and SD values into strings\n\t\t\n// \tCompute median values of Age by TG\n\t\t\n// \tTurn median values into strings\n\t\t\n// \tCompute min values of Age by TG\n\t\t\n// \tTurn min values into strings\n\t\t\n// \tCompute max values of Age by TG\n\t\t\n// \tTurn max values into strings\n\t\n// \tNew Report \n\t\n\th := titles()\n\terr := SummaryReport.WriteReport(outfile, h)\n\n\tfmt.Println(err)\n// \t\n// \t\n// \t\n// \tpdf.AddPage()\n// // \tbasicTable()\n// \n// \terr := pdf.OutputFileAndClose(*outputFile)\n// \tfmt.Println(err)\n}", "func (ChannelStrips) Ua610TubePreampEQCollection(){}", "func (s *scribe) fac(level Level) LoggerFactory {\n\tif level < s.enabled {\n\t\treturn nopFac\n\t}\n\tif loggerFac, ok := s.facs[level]; ok {\n\t\treturn loggerFac\n\t}\n\n\t// An invalid level was supplied\n\tpanic(fmt.Errorf(\"missing logger factory for level %s\", level.String()))\n}", "func (c *Chain) oneSample(updateVars bool) error {\n\tvarIdx, err := c.Sampler.Sample(c.LastSample)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error taking sample\")\n\t}\n\tif varIdx < 0 || c.Target.Vars[varIdx].FixedVal >= 0 {\n\t\treturn errors.New(\"Invalid sample\")\n\t}\n\n\tif updateVars {\n\t\tvalue := c.LastSample[varIdx]\n\n\t\tv := c.Target.Vars[varIdx]\n\t\tif !v.Collapsed {\n\t\t\tc.Target.Vars[varIdx].Marginal[value] += 1.0\n\t\t}\n\t\terr := c.ChainHistory[varIdx].Add(value)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Error taking sample and adding to ChainHistory\")\n\t\t}\n\n\t\tc.TotalSampleCount++\n\t}\n\n\treturn nil\n}", "func (o *Ga4ghTumourboard) HasPatientHasBeenReferredToAHereditaryCancerProgramBasedOnThisMolecularProfiling() bool {\n\tif o != nil && o.PatientHasBeenReferredToAHereditaryCancerProgramBasedOnThisMolecularProfiling != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (t *File_summary_by_instance) Collect(dbh *sql.DB) {\n\tstart := time.Now()\n\t// UPDATE current from db handle\n\tt.current = merge_by_table_name(select_fsbi_rows(dbh), t.global_variables)\n\n\t// copy in initial data if it was not there\n\tif len(t.initial) == 0 && len(t.current) > 0 {\n\t\tt.initial = make(file_summary_by_instance_rows, len(t.current))\n\t\tcopy(t.initial, t.current)\n\t}\n\n\t// check for reload initial characteristics\n\tif t.initial.needs_refresh(t.current) {\n\t\tt.initial = make(file_summary_by_instance_rows, len(t.current))\n\t\tcopy(t.initial, t.current)\n\t}\n\n\t// update results to current value\n\tt.results = make(file_summary_by_instance_rows, len(t.current))\n\tcopy(t.results, t.current)\n\n\t// make relative if need be\n\tif t.WantRelativeStats() {\n\t\tt.results.subtract(t.initial)\n\t}\n\n\t// sort the results\n\tt.results.sort()\n\n\t// setup the totals\n\tt.totals = t.results.totals()\n\tlib.Logger.Println(\"File_summary_by_instance.Collect() took:\", time.Duration(time.Since(start)).String())\n}", "func (t *testFuncs) Covered() string {\n\treturn \"\"\n}", "func (mr *MockStudyServiceApiClientMockRecorder) GetSurveyDefForStudy(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, \"GetSurveyDefForStudy\", reflect.TypeOf((*MockStudyServiceApiClient)(nil).GetSurveyDefForStudy), varargs...)\n}", "func sessionBecome(s *sess.Session, uid int) {\n\tvar d db.PersonDetail\n\td.Reports = make([]db.Person, 0)\n\td.UID = uid\n\tadminReadDetails(&d)\n\n\ts.Firstname = d.FirstName\n\tif 0 < len(d.PreferredName) {\n\t\ts.Firstname = d.PreferredName\n\t}\n\ts.UID = int64(uid)\n\ts.Username = d.UserName\n\ts.ImageURL = ui.GetImageLocation(uid)\n\tauthz.GetRoleInfo(d.RID, &s.PMap)\n\n\tif authz.Authz.SecurityDebug {\n\t\tfor i := 0; i < len(s.PMap.Urole.Perms); i++ {\n\t\t\tulog(\"f: %s, perm: %02x\\n\", s.PMap.Urole.Perms[i].Field, s.PMap.Urole.Perms[i].Perm)\n\t\t}\n\t}\n\n\tulog(\"user %d to BECOME user %d\", s.UIDorig, s.UID)\n}", "func interactiveSolution(testCases, numberOfElem, queryThreshold int) {\n\n}", "func (mock *InterfaceMock) AddStudyYearCalls() []struct {\n\tSy store.StudyYear\n} {\n\tvar calls []struct {\n\t\tSy store.StudyYear\n\t}\n\tmock.lockAddStudyYear.RLock()\n\tcalls = mock.calls.AddStudyYear\n\tmock.lockAddStudyYear.RUnlock()\n\treturn calls\n}", "func (f *formatter) Passed(_ *godog.Scenario, st *godog.Step, _ *godog.StepDefinition) {\n\tstep := f.step(st)\n\tstep.Status = Passed\n\tf.res.Steps = append(f.res.Steps, step)\n\tf.res.Status = Passed\n}", "func (mr *MockStudyServiceApiClientMockRecorder) GetStudy(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, \"GetStudy\", reflect.TypeOf((*MockStudyServiceApiClient)(nil).GetStudy), varargs...)\n}", "func (ctc *ClinicalTrialCreate) SetStudyType(s string) *ClinicalTrialCreate {\n\tctc.mutation.SetStudyType(s)\n\treturn ctc\n}", "func (t *TaigaManager) TimeTrackStories() {\n\tpoints, _, err := t.taigaClient.Points.ListPoints(&taiga.ListPointsOptions{})\n\tif err != nil {\n\t\tfmt.Println(\"Error while retrieving points\", err.Error())\n\t}\n\tpointListFloat := make(map[int]float64)\n\tfor _, point := range points {\n\t\tpointListFloat[point.ID] = point.Value\n\t}\n\t//roleList := t.RoleList\n\tfor _, usList := range t.StoriesTimeTrackedPerUsers {\n\t\tfor _, us := range usList {\n\t\t\tusTotalPoints := 0.0\n\t\t\tfor _, pointID := range us.Points {\n\t\t\t\tusTotalPoints += pointListFloat[pointID]\n\t\t\t}\n\t\t\tus.TotalPoint = usTotalPoints\n\t\t\tif us.ElapsedTime == 0 || usTotalPoints == 0 {\n\t\t\t\tus.Color = \"card-panel deep-orange lighten-2\"\n\t\t\t} else if us.ElapsedTime > usTotalPoints {\n\t\t\t\tus.Overtaking = true\n\t\t\t\tus.Color = \"card-panel red darken-4\"\n\t\t\t} else if us.ElapsedTime < usTotalPoints {\n\t\t\t\tus.Undertaking = true\n\t\t\t\tus.Color = \"card-panel teal lighten-1\"\n\t\t\t} else if (usTotalPoints == us.ElapsedTime) && usTotalPoints != 0 {\n\t\t\t\tus.RightTime = true\n\t\t\t\tus.Color = \"card-panel blue lighten-2\"\n\t\t\t}\n\t\t}\n\t}\n}", "func (suite *TrackvisitedTestSuite) SetupTest() {}", "func (g *GameSetUp) Summary(user *apigateway.AuthenticatedUser) *GameSetUpSummary {\n\toptions := make([]*SetUpOption, len(g.db.Options))\n\tplayers := make([]string, len(g.db.Players))\n\n\tfor i, v := range g.db.Options {\n\t\tcanEdit := *v.AddedByID == user.ViewID\n\t\toptions[i] = &SetUpOption{\n\t\t\tName: v.Name,\n\t\t\tDescription: v.Description,\n\t\t\tLink: v.Link,\n\t\t\tAddedBy: v.AddedByName,\n\t\t\tCanEdit: canEdit,\n\t\t}\n\t}\n\n\tuserInGame := false\n\tfor i, v := range g.db.Players {\n\t\tplayers[i] = v.Nickname\n\t\tif v.ID == user.ViewID {\n\t\t\tuserInGame = true\n\t\t}\n\t}\n\n\tcanBeStarted := g.canBeStarted(user) == CanBeStarted\n\n\tvar games []*GameSummary\n\tif !g.db.Active {\n\t\tgames, _ = FindActiveGameForSetUp(user, *g.db.ID)\n\t}\n\n\treturn &GameSetUpSummary{\n\t\tID: g.db.ID,\n\t\tCode: g.db.Code,\n\t\tGames: games,\n\t\tOptions: options,\n\t\tPlayers: players,\n\t\tUserInGame: userInGame,\n\t\tCanBeStarted: canBeStarted,\n\t\tTags: g.db.Tags,\n\t}\n}", "func (s *UniformSample) Snapshot() gometrics.Sample {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\tvalues := make([]int64, len(s.values))\n\tcopy(values, s.values)\n\treturn gometrics.NewSampleSnapshot(s.count, values)\n}", "func (st Student) display() {\n\tfmt.Println()\n\tfmt.Printf(\"Name: %s - Age: %d - Address: %s\", st.student_name, st.student_age, st.student_address)\n}", "func copyFromFToOutput(category string, f *xlsx.File) {\n\tfor _, sheet := range f.Sheets {\n\n\t\t// Parse person id\n\t\tpersonID, err := strconv.ParseInt(sheet.Name[2:4], 10, 32)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t//////////////////////////////////////////////////////\n\t\t///////////////// Extract F values ///////////////////\n\t\t//////////////////////////////////////////////////////\n\t\trowOffset := 5\n\t\trowBeta1Offset := 7\n\t\trowBeta3Offset := 8\n\t\trowPercentageOffset := 10\n\t\trowStep := 12\n\t\tfor {\n\t\t\t// Skip incomplete rows\n\t\t\tif len(sheet.Rows) < rowOffset {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Extract Beta1 and Beta3\n\t\t\ttableName := sheet.Rows[rowOffset].Cells[0]\n\t\t\ttableBeta1Mean := sheet.Rows[rowOffset+rowBeta1Offset].Cells[2]\n\t\t\ttableBeta3Mean := sheet.Rows[rowOffset+rowBeta3Offset].Cells[2]\n\t\t\ttablePercentage := sheet.Rows[rowOffset+rowPercentageOffset].Cells[0]\n\n\t\t\t// Check and map table name\n\t\t\ttableNameString, err := tableName.String()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\ttableNameString = strings.Split(strings.Split(tableNameString, \":\")[1], \"(\")[0]\n\t\t\ttableNameString = tableNameString[:len(tableNameString)-1]\n\t\t\ttableNameString = strings.Replace(tableNameString, \".\", \"\", 1)\n\t\t\tif strings.Contains(tableNameString, \"Baseline\") {\n\t\t\t\ttableNameString = strings.Replace(tableNameString, \"Baseline\", \"B\", 1)\n\t\t\t}\n\n\t\t\t// We do not need any Cue values...\n\t\t\tif !strings.Contains(tableNameString, \"Cue\") {\n\n\t\t\t\ttableBeta1MeanString, err := tableBeta1Mean.String()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\ttableBeta3MeanString, err := tableBeta3Mean.String()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\ttablePercentageString, err := tablePercentage.String()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\tpercentage, err := strconv.ParseFloat(strings.TrimSpace(strings.Split(tablePercentageString, \"%\")[0]), 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// Define LB column and cell value\n\t\t\t\tlbColName := fmt.Sprintf(\"%sLB_%s\", category, tableNameString)\n\t\t\t\tlbCellValue, err := strconv.ParseFloat(strings.TrimSpace(tableBeta1MeanString), 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// Define HB column and cell value\n\t\t\t\thbColName := fmt.Sprintf(\"%sHB_%s\", category, tableNameString)\n\t\t\t\thbCellValue, err := strconv.ParseFloat(strings.TrimSpace(tableBeta3MeanString), 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// Do something with these data...\n\t\t\t\t// log.Printf(\"[VP%d @ %f] %s: %f\", personID, percentage, lbColName, lbCellValue)\n\t\t\t\t// log.Printf(\"[VP%d @ %f] %s: %f\", personID, percentage, hbColName, hbCellValue)\n\n\t\t\t\t// Insert into sheet\n\t\t\t\tinsertCellIntoOutput(personID, percentage, lbColName, lbCellValue)\n\t\t\t\tinsertCellIntoOutput(personID, percentage, hbColName, hbCellValue)\n\t\t\t}\n\n\t\t\trowOffset += rowStep\n\t\t}\n\t}\n}", "func (tr *trooper) merge() {\n\ttr.trash()\n\ttr.neo = tr.part.AddPart().SetScale(0.5, 0.5, 0.5)\n\tm := tr.neo.MakeModel(\"flata\", \"msh:cube\", \"mat:tblue\")\n\tm.SetUniform(\"fd\", 1000)\n\ttr.addCenter()\n}", "func (f *familyAndMetrics) copyFamily() dto.MetricFamily {\n\treturn *f.family\n}", "func (su *SimulatedUser) Start(q *QLearning) {\n\tvar tdc int\n\tvar wts [][]float64\n\tvs := VirtualState{}\n\twts, su.vsa = GenerateTrainingSet()\n\n\tvar wa []int\n\n\tfor reps := 0; reps < 1; reps++ {\n\t\tfor d := 0; d < q.workdays; d++ {\n\t\t\t//drinkcount reset\n\t\t\ttdc = 0\n\t\t\tfor sl := 7; sl < 19; sl++ {\n\t\t\t\t//filter all from trainingsset equals day and slot\n\t\t\t\tfsc := FilterSlice(wts[d], GetCurrentTimeSlot(sl))\n\t\t\t\tfor st := 0; st < fsc+1; st++ {\n\t\t\t\t\ttdc += st\n\t\t\t\t\tq.state = vs.New(drinkcount{CoffeeCount: tdc, WaterCount: 0, MateCount: 0}, d, float64(sl))\n\t\t\t\t\tfb := su.UserMock(q.state)\n\t\t\t\t\tfmt.Println(q.state)\n\t\t\t\t\tq.learn(fb)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twa = append(wa /* q.sr.steps- */, q.sr.neg)\n\t\tq.sr.neg = 0\n\t}\n\n\twriteJsonFile(mapToString(q.qt))\n\n\t// fmt.Println(\"Q-Table \\n\", q.qt)\n\tfmt.Println(\"successratio\", wa)\n}", "func copyOriginalVariablesPsa() {\n\t// ---- transition probabilities -----\n\tfor i := 0; i < len(Inputs.TransitionProbabilities); i++ {\n\t\tInputs.TransitionProbabilities[i].Original_base = Inputs.TransitionProbabilities[i].Tp_base\n\t}\n\n\tvariableList := []*Variable{&AccessMonthlyProportionOfTrueNegativesThatAreTested, &AccessMonthlyProportionOfTruePositivesThatAreTested, &UsbTstSensitivity, &UsbTstSpecificity, &UsbQftSensitivity, &UsbQftSpecificity, &UsbTspotSensitivity, &UsbTspotSpecificity, &FbTstSensitivity, &FbTstSpecificity, &FbQftSensitivity, &FbQftSpecificity, &FbTspotSensitivity, &FbTspotSpecificity, &HivTstSensitivity, &HivTstSpecificity, &HivQftSensitivity, &HivQftSpecificity, &HivTspotSensitivity, &HivTspotSpecificity, &EsrdTstSensitivity, &EsrdTstSpecificity, &EsrdQftSensitivity, &EsrdQftSpecificity, &EsrdTspotSensitivity, &EsrdTspotSpecificity, &ProportionOfIndividualsThatEnrollInTreatmentAfterAPositiveTstLtbiTest, &ProportionOfIndividualsThatEnrollInTreatmentAfterAPositiveQftTspotTest, &NumberOfLtbiCasesCausedByOneActiveCase, &NumberOfSecondaryTbCasesCausedByOneActiveCase, &EfficacyOf9H, &EfficacyOf6H, &EfficacyOf4R, &EfficacyOf3Hp, &BaseRiskOfProgression, &ProportionOfLtbiTreated, &FastLatentProgression, &SlowLatentProgression, &TotalCostOfLtbiTreatment9H, &TotalCostOfLtbiTreatment6H, &TotalCostOfLtbiTreatment4R, &TotalCostOfLtbiTreatment3Hp, &ProportionOfStartedWhoCompleteTreatment9H, &ProportionOfStartedWhoCompleteTreatment6H, &ProportionOfStartedWhoCompleteTreatment4R, &ProportionOfStartedWhoCompleteTreatment3Hp, &CostOfTst, &CostOfQft, &CostOfTspot, &CostOfTstQft, &CostOfTstTspot, &CostOfActiveTbCase, &QalysGainedAvertingOneCaseOfActiveTb, &LtbiOverallAdjustmentStarting, &LtbiOverallFbAdjustmentStarting, &LtbiOverallUsbAdjustmentStarting, &LtbiAsianFbAdjustmentStarting, &LtbiAsianUsbAdjustmentStarting, &LtbiWhiteFbAdjustmentStarting, &LtbiWhiteUsbAdjustmentStarting, &LtbiHispanicFbAdjustmentStarting, &LtbiHispanicUsbAdjustmentStarting, &LtbiBlackFbAdjustmentStarting, &LtbiBlackUsbAdjustmentStarting, &LtbiOtherFbAdjustmentStarting, &LtbiOtherUsbAdjustmentStarting, &LtbiOverallAdjustment, &LtbiOverallFbAdjustment, &LtbiOverallUsbAdjustment, &LtbiAsianFbAdjustment, &LtbiAsianUsbAdjustment, &LtbiWhiteFbAdjustment, &LtbiWhiteUsbAdjustment, &LtbiHispanicFbAdjustment, &LtbiHispanicUsbAdjustment, &LtbiBlackFbAdjustment, &LtbiBlackUsbAdjustment, &LtbiOtherFbAdjustment, &LtbiOtherUsbAdjustment, &DiabetesPrevalenceAdjustment, &EsrdPrevalenceAdjustment, &SmokerPrevalenceAdjustment, &TnfAlphaPrevalenceAdjustment, &HivPrevalenceAdjustment, &TransplantsPrevalenceAdjustment}\n\n\tfor i := 0; i < len(variableList); i++ {\n\t\tvariableList[i].Original_base = variableList[i].Value\n\t}\n\n}", "func NewStudy(ctx *pulumi.Context,\n\tname string, args *StudyArgs, opts ...pulumi.ResourceOption) (*Study, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.StudyConfig == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'StudyConfig'\")\n\t}\n\tif args.StudyId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'StudyId'\")\n\t}\n\treplaceOnChanges := pulumi.ReplaceOnChanges([]string{\n\t\t\"location\",\n\t\t\"project\",\n\t\t\"studyId\",\n\t})\n\topts = append(opts, replaceOnChanges)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Study\n\terr := ctx.RegisterResource(\"google-native:ml/v1:Study\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func assessment(scan hooks.InternalMessage, internalChannel chan hooks.InternalMessage) {\n\t// Changes if test is done via SSL\n\tif scan.Domain.TestWithSSL {\n\n\t} else {\n\n\t}\n\n\t// Add your assessment logic\n\t//\t\trow = yourAssessment(...)\n\n\t//Handle error\n\tif err != nil {\n\t\tmanager.Logger.Errorf(\"Assessment failed for %v: %v\", scan.Domain.DomainName, err)\n\t\tscan.Results = row\n\t\tscan.StatusCode = hooks.InternalError\n\t\tinternalChannel <- scan\n\t\treturn\n\t}\n\n\t//return results\n\tscan.Results = row\n\tscan.StatusCode = hooks.InternalSuccess\n\tinternalChannel <- scan\n}", "func (a StoriesAllStories) construct() StoriesAllStoriesClass { return &a }", "func (g *Generation) UpdateStatisticalFields() {\n\tfor i := 0; i < len(g.Protagonists); i++ {\n\t\t// Populate Antagonist Fitness Values\n\t\tantagonist := g.Antagonists[i]\n\t\tg.AntagonistAvgFitnessValuesOfEveryIndividual = append(g.AntagonistAvgFitnessValuesOfEveryIndividual, antagonist.AverageFitness)\n\t\tg.AntagonistsAvgAgeOfEveryIndividual = append(g.AntagonistsAvgAgeOfEveryIndividual, float64(antagonist.Age))\n\t\tg.AntagonistsAvgBirthGenOfEveryIndividual = append(g.AntagonistsAvgBirthGenOfEveryIndividual, float64(antagonist.BirthGen))\n\n\t\t// Populate Protagonists Fitness Values\n\t\tprotagonist := g.Protagonists[i]\n\t\tg.ProtagonistAvgFitnessOfEveryIndividual = append(g.ProtagonistAvgFitnessOfEveryIndividual, protagonist.AverageFitness)\n\t\tg.ProtagonistsAvgAgeOfEveryIndividual = append(g.AntagonistsAvgAgeOfEveryIndividual, float64(protagonist.Age))\n\t\tg.ProtagonistsAvgBirthGenOfEveryIndividual = append(g.AntagonistsAvgBirthGenOfEveryIndividual, float64(protagonist.BirthGen))\n\t}\n\n\tg.AntagonistStdDevOfAvgFitnessValues = stat.StdDev(g.AntagonistAvgFitnessValuesOfEveryIndividual, nil)\n\tg.AntagonistVarianceOfAvgFitnessValues = stat.Variance(g.AntagonistAvgFitnessValuesOfEveryIndividual, nil)\n\tg.AntagonistAverage = stat.Mean(g.AntagonistAvgFitnessValuesOfEveryIndividual, nil)\n\tg.AntagonistsAvgAge = stat.Mean(g.AntagonistsAvgAgeOfEveryIndividual, nil)\n\tg.AntagonistsAvgBirthGen = stat.Mean(g.AntagonistsAvgBirthGenOfEveryIndividual, nil)\n\n\tg.ProtagonistStdDevOfAvgFitnessValues = stat.StdDev(g.ProtagonistAvgFitnessOfEveryIndividual, nil)\n\tg.ProtagonistVarianceOfAvgFitnessValues = stat.Variance(g.ProtagonistAvgFitnessOfEveryIndividual, nil)\n\tg.ProtagonistAverage = stat.Variance(g.ProtagonistAvgFitnessOfEveryIndividual, nil)\n\tg.ProtagonistsAvgAge = stat.Mean(g.ProtagonistsAvgAgeOfEveryIndividual, nil)\n\tg.ProtagonistsAvgBirthGen = stat.Mean(g.ProtagonistsAvgBirthGenOfEveryIndividual, nil)\n\n\tg.Correlation = stat.Correlation(g.AntagonistAvgFitnessValuesOfEveryIndividual, g.ProtagonistAvgFitnessOfEveryIndividual, nil)\n\tg.Covariance = stat.Covariance(g.AntagonistAvgFitnessValuesOfEveryIndividual, g.ProtagonistAvgFitnessOfEveryIndividual, nil)\n}", "func test(t *testing.T, scene string, f func(*testing.T)) {\n\tif t.Failed() {\n\t\treturn\n\t}\n\tConvey(scene, t, func() {\n\t\tf(t)\n\t})\n}", "func (af *AudioFrame) runFrequencyAnalysis() {\n\t// convert the data to freqpoints\n\t// first step is the window function.\n\ts := len(af.data)\n\tfor i := 0; i < s; i++ {\n\t\taf.data[i] = af.data[i] * af.windowFunction(i, s)\n\t}\n\t// we really want a power of 2 samples per frame\n\t// meaning we might need to grab more samples\n\t// and \"smooth\" over our time period... sounds complex.\n\t// lets just take the performance hit and work with our frame counts\n\tft := fft.FFTReal(af.data)\n\t// and now convert the fft data into the volumes at grequency band\n\tfor i := 0; i < s; i++ {\n\t\taf.freq[i] = math.Sqrt(real(ft[i])*real(ft[i])+imag(ft[i])*imag(ft[i])) * 100 / float64(s)\n\t}\n}", "func (s *UniformSample) Sum() int64 {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn gometrics.SampleSum(s.values)\n}", "func (LocalAPIs) Site4Dataset_phedex(dasquery dasql.DASQuery) []mongo.DASRecord {\n\tspec := dasquery.Spec\n\tinst := dasquery.Instance\n\t// DBS part, find total number of blocks and files for given dataset\n\tdataset := spec[\"dataset\"].(string)\n\tapi := \"filesummaries\"\n\tfurl := fmt.Sprintf(\"%s/%s?dataset=%s&validFileOnly=1\", DBSUrl(inst), api, dataset)\n\tclient := utils.HttpClient()\n\tresp := utils.FetchResponse(client, furl, \"\") // \"\" specify optional args\n\trecords := DBSUnmarshal(api, resp.Data)\n\tvar totblocks, totfiles int64\n\tif len(records) == 0 {\n\t\treturn []mongo.DASRecord{}\n\t}\n\ttotblocks = rec2num(records[0][\"num_block\"])\n\ttotfiles = rec2num(records[0][\"num_file\"])\n\t// Phedex part find block replicas for given dataset\n\tapi = \"blockReplicas\"\n\tfurl = fmt.Sprintf(\"%s/%s?dataset=%s\", PhedexUrl(), api, dataset)\n\tresp = utils.FetchResponse(client, furl, \"\") // \"\" specify optional args\n\trecords = PhedexUnmarshal(api, resp.Data)\n\tsiteInfo := make(mongo.DASRecord)\n\tvar bComplete, nfiles, nblks, bfiles int64\n\tbfiles = 0\n\tfor _, rec := range records {\n\t\tif rec[\"files\"] == nil || rec[\"replica\"] == nil {\n\t\t\tcontinue\n\t\t}\n\t\tbfiles += rec2num(rec[\"files\"])\n\t\treplicas := rec[\"replica\"].([]interface{})\n\t\tfor _, val := range replicas {\n\t\t\trow := val.(map[string]interface{})\n\t\t\tvar node, se, complete string\n\t\t\tswitch v := row[\"node\"].(type) {\n\t\t\tcase string:\n\t\t\t\tnode = v\n\t\t\t}\n\t\t\tswitch v := row[\"se\"].(type) {\n\t\t\tcase string:\n\t\t\t\tse = v\n\t\t\t}\n\t\t\tswitch v := row[\"complete\"].(type) {\n\t\t\tcase string:\n\t\t\t\tcomplete = v\n\t\t\t}\n\t\t\tif complete == \"y\" {\n\t\t\t\tbComplete = 1\n\t\t\t} else {\n\t\t\t\tbComplete = 0\n\t\t\t}\n\t\t\tnfiles = rec2num(row[\"files\"])\n\t\t\tskeys := utils.MapKeys(siteInfo)\n\t\t\tif utils.InList(node, skeys) {\n\t\t\t\tsInfo := siteInfo[node].(mongo.DASRecord)\n\t\t\t\tnfiles += rec2num(sInfo[\"files\"])\n\t\t\t\tnblks = rec2num(sInfo[\"blocks\"]) + 1\n\t\t\t\tbc := rec2num(sInfo[\"block_complete\"])\n\t\t\t\tif complete == \"y\" {\n\t\t\t\t\tbComplete = bc + 1\n\t\t\t\t} else {\n\t\t\t\t\tbComplete = bc\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnblks = 1\n\t\t\t}\n\t\t\tsiteInfo[node] = mongo.DASRecord{\"files\": nfiles, \"blocks\": nblks, \"block_complete\": bComplete, \"se\": se, \"kind\": _phedexNodes.NodeType(node)}\n\t\t}\n\t}\n\t// if utils.VERBOSE > 0 {\n\t// fmt.Println(\"### bfiles\", bfiles)\n\t// for s, v := range siteInfo {\n\t// fmt.Println(\"### site\", s, v)\n\t// }\n\t// }\n\tvar pfiles, pblks string\n\tvar out []mongo.DASRecord\n\tfor key, val := range siteInfo {\n\t\trow := val.(mongo.DASRecord)\n\t\tnfiles := rec2num(row[\"files\"])\n\t\tif totfiles > 0 {\n\t\t\tpfiles = fmt.Sprintf(\"%5.2f%%\", 100*float64(nfiles)/float64(totfiles))\n\t\t} else {\n\t\t\tpfiles = \"N/A\"\n\t\t\tpblks = \"N/A\"\n\t\t}\n\t\tif totblocks > 0 {\n\t\t\tnblks := rec2num(row[\"blocks\"])\n\t\t\tpblks = fmt.Sprintf(\"%5.2f%%\", 100*float64(nblks)/float64(totblocks))\n\t\t} else {\n\t\t\tpfiles = \"N/A\"\n\t\t\tpblks = \"N/A\"\n\t\t}\n\t\tratio := float64(rec2num(row[\"block_complete\"])) / float64(rec2num(row[\"blocks\"]))\n\t\tbc := fmt.Sprintf(\"%5.2f%%\", 100*ratio)\n\t\trf := fmt.Sprintf(\"%5.2f%%\", 100*float64(nfiles)/float64(bfiles))\n\t\tif utils.VERBOSE > 0 {\n\t\t\tfmt.Println(\"### site\", key, \"nfiles\", nfiles, \"bfiles\", bfiles)\n\t\t}\n\t\t// put into file das record, internal type must be list\n\t\trec := make(mongo.DASRecord)\n\t\trec[\"site\"] = []mongo.DASRecord{{\"name\": key,\n\t\t\t\"dataset_fraction\": pfiles, \"block_fraction\": pblks, \"block_completion\": bc,\n\t\t\t\"se\": row[\"se\"].(string), \"replica_fraction\": rf, \"kind\": row[\"kind\"].(string)}}\n\t\tout = append(out, rec)\n\t}\n\treturn out\n}", "func (tm *TeamMonitoring) RevealRooks() {\n\t//check if today is not saturday or sunday. During these days no notificatoins!\n\tif int(time.Now().Weekday()) == 6 || int(time.Now().Weekday()) == 0 {\n\t\treturn\n\t}\n\ttimeFrom := time.Now()\n\t// if today is monday, check 3 days of performance for user\n\tif int(time.Now().Weekday()) == 1 {\n\t\ttimeFrom = time.Now().AddDate(0, 0, -3)\n\t}\n\tallUsers, err := tm.db.ListAllChannelMembers()\n\tif err != nil {\n\t\tlogrus.Errorf(\"team monitoring: tm.GetCurrentDayNonReporters failed: %v\\n\", err)\n\t\treturn\n\t}\n\n\tdateFrom := fmt.Sprintf(\"%d-%02d-%02d\", timeFrom.Year(), timeFrom.Month(), timeFrom.Day())\n\n\tfor _, user := range allUsers {\n\t\tproject, err := tm.db.SelectChannel(user.ChannelID)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tuserInProject := fmt.Sprintf(\"%v/%v\", user.UserID, project.ChannelName)\n\n\t\tdata, err := GetCollectorData(tm.Config, \"user-in-project\", userInProject, dateFrom, dateFrom)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"team monitoring: getCollectorData failed: %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tisNonReporter, err := tm.db.IsNonReporter(user.UserID, user.ChannelID, timeFrom.AddDate(0, 0, -1), time.Now())\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"team monitoring: IsNonReporter failed: %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif (data.Worklogs < 8) || (data.TotalCommits == 0) || (isNonReporter == true) {\n\t\t\tfails := \"\"\n\t\t\tif data.Worklogs < 8 {\n\t\t\t\tfails += fmt.Sprintf(tm.Config.Translate.NoWorklogs, data.Worklogs)\n\t\t\t} else {\n\t\t\t\tfails += fmt.Sprintf(tm.Config.Translate.HasWorklogs, data.Worklogs)\n\t\t\t}\n\t\t\tif data.TotalCommits == 0 {\n\t\t\t\tfails += tm.Config.Translate.NoCommits\n\t\t\t} else {\n\t\t\t\tfails += fmt.Sprintf(tm.Config.Translate.HasCommits, data.TotalCommits)\n\t\t\t}\n\t\t\tif isNonReporter == true {\n\t\t\t\tfails += tm.Config.Translate.NoStandup\n\t\t\t} else {\n\t\t\t\tfails += tm.Config.Translate.HasStandup\n\t\t\t}\n\t\t\ttext := fmt.Sprintf(tm.Config.Translate.IsRook, user.UserID, project.ChannelName, fails)\n\t\t\tif int(time.Now().Weekday()) == 1 {\n\t\t\t\ttext = fmt.Sprintf(tm.Config.Translate.IsRookMonday, user.UserID, project.ChannelName, fails)\n\t\t\t}\n\t\t\ttm.Chat.SendMessage(tm.Config.ReportingChannel, text)\n\t\t}\n\t}\n}", "func (lhs *Readings) divide(scalar float64) (retval Readings) {\n\tretval = Readings{\n\t\tVoltage: ThreePhaseReadings{\n\t\t\tL1: F2fp(Fp2f(lhs.Voltage.L1) / scalar),\n\t\t\tL2: F2fp(Fp2f(lhs.Voltage.L2) / scalar),\n\t\t\tL3: F2fp(Fp2f(lhs.Voltage.L3) / scalar),\n\t\t},\n\t\tCurrent: ThreePhaseReadings{\n\t\t\tL1: F2fp(Fp2f(lhs.Current.L1) / scalar),\n\t\t\tL2: F2fp(Fp2f(lhs.Current.L2) / scalar),\n\t\t\tL3: F2fp(Fp2f(lhs.Current.L3) / scalar),\n\t\t},\n\t\tPower: ThreePhaseReadings{\n\t\t\tL1: F2fp(Fp2f(lhs.Power.L1) / scalar),\n\t\t\tL2: F2fp(Fp2f(lhs.Power.L2) / scalar),\n\t\t\tL3: F2fp(Fp2f(lhs.Power.L3) / scalar),\n\t\t},\n\t\tCosphi: ThreePhaseReadings{\n\t\t\tL1: F2fp(Fp2f(lhs.Cosphi.L1) / scalar),\n\t\t\tL2: F2fp(Fp2f(lhs.Cosphi.L2) / scalar),\n\t\t\tL3: F2fp(Fp2f(lhs.Cosphi.L3) / scalar),\n\t\t},\n\t\tImport: ThreePhaseReadings{\n\t\t\tL1: F2fp(Fp2f(lhs.Import.L1) / scalar),\n\t\t\tL2: F2fp(Fp2f(lhs.Import.L2) / scalar),\n\t\t\tL3: F2fp(Fp2f(lhs.Import.L3) / scalar),\n\t\t},\n\t\tTotalImport: F2fp(Fp2f(lhs.TotalImport) / scalar),\n\t\tExport: ThreePhaseReadings{\n\t\t\tL1: F2fp(Fp2f(lhs.Export.L1) / scalar),\n\t\t\tL2: F2fp(Fp2f(lhs.Export.L2) / scalar),\n\t\t\tL3: F2fp(Fp2f(lhs.Export.L3) / scalar),\n\t\t},\n\t\tTotalExport: F2fp(Fp2f(lhs.TotalExport) / scalar),\n\t\tTHD: THDInfo{\n\t\t\tVoltageNeutral: ThreePhaseReadings{\n\t\t\t\tL1: F2fp(Fp2f(lhs.THD.VoltageNeutral.L1) / scalar),\n\t\t\t\tL2: F2fp(Fp2f(lhs.THD.VoltageNeutral.L2) / scalar),\n\t\t\t\tL3: F2fp(Fp2f(lhs.THD.VoltageNeutral.L3) / scalar),\n\t\t\t},\n\t\t\tAvgVoltageNeutral: F2fp(Fp2f(lhs.THD.AvgVoltageNeutral) /\n\t\t\t\tscalar),\n\t\t},\n\t\tFrequency: F2fp(Fp2f(lhs.Frequency) / scalar),\n\t}\n\tretval.Timestamp = lhs.Timestamp\n\tretval.Unix = lhs.Unix\n\tretval.ModbusDeviceId = lhs.ModbusDeviceId\n\tretval.UniqueId = lhs.UniqueId\n\treturn retval\n}", "func (n *node) survey(vs []*View, fun func(x, y float64, e interface{})) {\n\tfor i := range n.children {\n\t\tchild := n.children[i]\n\t\tif overlaps(vs, child.View()) {\n\t\t\tn.children[i].survey(vs, fun)\n\t\t}\n\t}\n}", "func TeamSpecializationPEducationStaff() *TeamSpecialization {\n\tv := TeamSpecializationVEducationStaff\n\treturn &v\n}", "func (baseModel *BaseModel) Observe(specificModel AppliedAlgorithm) bool {\n min := 1000.0\n argminx := -1\n argminy := -1\n distribution := make([]float64, baseModel.T)\n\n // Find the point with minimum entropy (adding a little noise for randomness)\n for x := 0; x < baseModel.Fmx; x++ {\n for y := 0; y < baseModel.Fmy; y++ {\n if specificModel.OnBoundary(x, y) {\n continue\n }\n\n sum := 0.0\n\n for t := 0; t < baseModel.T; t++ {\n if baseModel.Wave[x][y][t] {\n distribution[t] = baseModel.Stationary[t]\n } else {\n distribution[t] = 0.0\n }\n sum += distribution[t]\n }\n\n if sum == 0.0 {\n baseModel.GenerationSuccessful = false\n return true // finished, unsuccessful\n }\n\n for t := 0; t < baseModel.T; t++ {\n distribution[t] /= sum\n }\n\n entropy := 0.0\n\n for i := 0; i < len(distribution); i++ {\n if distribution[i] > 0.0 {\n entropy += -distribution[i] * math.Log(distribution[i])\n }\n }\n\n noise := 0.000001 * baseModel.Rng()\n\n if entropy > 0 && entropy+noise < min {\n min = entropy + noise\n argminx = x\n argminy = y\n }\n }\n }\n\n if argminx == -1 && argminy == -1 {\n baseModel.GenerationSuccessful = true\n return true // finished, successful\n }\n\n for t := 0; t < baseModel.T; t++ {\n if baseModel.Wave[argminx][argminy][t] {\n distribution[t] = baseModel.Stationary[t]\n } else {\n distribution[t] = 0.0\n }\n }\n\n r := randomIndice(distribution, baseModel.Rng())\n\n for t := 0; t < baseModel.T; t++ {\n baseModel.Wave[argminx][argminy][t] = (t == r)\n }\n\n baseModel.Changes[argminx][argminy] = true\n\n return false // Not finished yet\n}", "func (ff *fftag) Create(eng vu.Eng, s *vu.State) {\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\t// create the overlay\n\tff.top = eng.Root().NewPov()\n\tview := ff.top.NewView()\n\tview.SetUI()\n\tff.cam = view.Cam()\n\tff.mmap = ff.top.NewPov().SetScale(10, 10, 0)\n\tff.mmap.SetLocation(30, 30, 0)\n\n\t// populate the map\n\tff.msize = 69\n\tff.plan = grid.New(grid.ROOMS_SKIRMISH)\n\tff.plan.Generate(ff.msize, ff.msize)\n\twidth, height := ff.plan.Size()\n\tfor x := 0; x < width; x++ {\n\t\tfor y := 0; y < height; y++ {\n\t\t\tif ff.plan.IsOpen(x, y) {\n\t\t\t\tblock := ff.mmap.NewPov()\n\t\t\t\tblock.SetLocation(float64(x), float64(y), 0)\n\t\t\t\tblock.NewModel(\"uv\").LoadMesh(\"icon\").AddTex(\"wall\")\n\t\t\t\tff.spots = append(ff.spots, ff.id(x, y))\n\t\t\t}\n\t\t}\n\t}\n\n\t// populate chasers and a goal.\n\tnumChasers := 30\n\tfor cnt := 0; cnt < numChasers; cnt++ {\n\t\tchaser := ff.mmap.NewPov()\n\t\tchaser.NewModel(\"uv\").LoadMesh(\"icon\").AddTex(\"token\")\n\t\tff.chasers = append(ff.chasers, chaser)\n\t}\n\tff.goal = ff.mmap.NewPov()\n\tff.goal.NewModel(\"uv\").LoadMesh(\"icon\").AddTex(\"goal\")\n\tff.flow = grid.NewFlow(ff.plan) // flow field for the given plan.\n\tff.resetLocations()\n\n\t// set non default engine state.\n\teng.SetColor(0.15, 0.15, 0.15, 1)\n\tff.resize(s.W, s.H)\n}", "func (repo *Repository) CurrentStudent(ctx context.Context, claims auth.Claims) (*Student, error) {\n\tuser, err := models.FindUser(ctx, repo.DbConn, claims.Subject)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstudentModel, err := models.Students(\n\t\tqm.Load(models.StudentRels.Class),\n\t\tqm.Load(models.StudentRels.Subclass),\n\t\tmodels.StudentWhere.Username.EQ(user.Email),\n\t).One(ctx, repo.DbConn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn FromModel(studentModel), nil\n}", "func (c *Controller) getPract(id string, pract *store.Practitioner) error {\n\tp, err := c.Sc.GetPractitioner(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpract.SCFHSRegistrationNumber = &p.Response.Info.Profile.RegistrationNumber\n\tpract.PractitionerID = pract.HealthID\n\tpract.IDNumber = &id\n\n\tpract.FirstNameAr = &p.Response.Info.Profile.Ar.FirstName\n\tpract.SecondNameAr = &p.Response.Info.Profile.Ar.SecondName\n\tpract.LastNameAr = &p.Response.Info.Profile.Ar.LastName\n\n\tpract.FirstNameEn = &p.Response.Info.Profile.En.FirstName\n\tpract.SecondNameEn = &p.Response.Info.Profile.En.SecondName\n\tpract.LastNameEn = &p.Response.Info.Profile.En.LastName\n\n\tpract.Gender_code = &p.Response.Info.Profile.Gender.Code\n\tpract.Gender_ar = &p.Response.Info.Profile.Gender.NameAr\n\tpract.Gender_en = &p.Response.Info.Profile.Gender.NameEn\n\n\tpract.SCFHSCategoryCode = &p.Response.Info.Professionality.Category.Code\n\tpract.SCFHSCategoryAr = &p.Response.Info.Professionality.Category.NameAr\n\tpract.SCFHSCategoryEn = &p.Response.Info.Professionality.Category.NameEn\n\n\tpract.SCFHSSpecialityCode = &p.Response.Info.Professionality.Specialty.Code\n\tpract.SCFHSSpecialityAr = &p.Response.Info.Professionality.Specialty.NameAr\n\tpract.SCFHSSpecialityEn = &p.Response.Info.Professionality.Specialty.NameEn\n\n\tpract.SCFHSPractitionerStatus = &p.Response.Info.Status.Code\n\tpract.SCFHSPractitionerStatusCode = &p.Response.Info.Status.DescAr\n\n\tpract.SCFHSRegistrationIssueDate = &p.Response.Info.Status.License.IssuedDate\n\tpract.SCFHSRegistrationExpiryDate = &p.Response.Info.Status.License.ExpiryDate\n\n\t// @TODO: change this\n\tpq := PatientQuery{ID: id}\n\tswitch pq.Kind() {\n\tcase KindCitizen:\n\t\tty := \"NationalId\"\n\t\tpract.IDType = &ty\n\tcase KindExpat:\n\t\tty := \"Iqama\"\n\t\tpract.IDType = &ty\n\t}\n\treturn nil\n}", "func (s *BasevhdlListener) EnterDesign_file(ctx *Design_fileContext) {}", "func (document *OpenScreenplay) FromFountain(screenplay *fountain.Fountain) {\n\tif screenplay.TitlePage != nil {\n\t\t// Build the Info section\n\t\tif document.Info == nil {\n\t\t\tdocument.Info = new(Info)\n\t\t}\n\t\t// Populate the TitlePage\n\t\tif document.TitlePage == nil {\n\t\t\tdocument.TitlePage = new(TitlePage)\n\t\t}\n\n\t\t// NOTE: build a map of elements that will belong to Info.\n\t\tfor _, elem := range screenplay.TitlePage {\n\t\t\tswitch strings.ToLower(elem.Name) {\n\t\t\tcase \"title\":\n\t\t\t\tdocument.Info.Title = elem.Content\n\t\t\t\tpara := new(Para)\n\t\t\t\tpara.Bookmark = \"Title\"\n\t\t\t\tpara.Text = StringToTextArray(elem.Content)\n\t\t\t\tdocument.TitlePage.Para = append(document.TitlePage.Para, para)\n\t\t\tcase \"credit\":\n\t\t\t\tdocument.Info.WrittenBy = elem.Content\n\t\t\t\tpara := new(Para)\n\t\t\t\tpara.Bookmark = \"Credits\"\n\t\t\t\tpara.Text = StringToTextArray(elem.Content)\n\t\t\t\tdocument.TitlePage.Para = append(document.TitlePage.Para, para)\n\t\t\tcase \"author\":\n\t\t\t\tdocument.Info.WrittenBy = elem.Content\n\t\t\t\tpara := new(Para)\n\t\t\t\tpara.Bookmark = \"Author\"\n\t\t\t\tpara.Text = StringToTextArray(elem.Content)\n\t\t\t\tdocument.TitlePage.Para = append(document.TitlePage.Para, para)\n\t\t\tcase \"copyright\":\n\t\t\t\tdocument.Info.Copyright = elem.Content\n\t\t\t\tpara := new(Para)\n\t\t\t\tpara.Bookmark = \"Copyright\"\n\t\t\t\tpara.Text = StringToTextArray(elem.Content)\n\t\t\t\tdocument.TitlePage.Para = append(document.TitlePage.Para, para)\n\t\t\tcase \"draft date\":\n\t\t\t\tdocument.Info.Drafts = elem.Content\n\t\t\t\tpara := new(Para)\n\t\t\t\tpara.Bookmark = \"Drafts\"\n\t\t\t\tpara.Text = StringToTextArray(elem.Content)\n\t\t\t\tdocument.TitlePage.Para = append(document.TitlePage.Para, para)\n\t\t\tcase \"contact\":\n\t\t\t\tdocument.Info.Contact = elem.Content\n\t\t\t\tpara := new(Para)\n\t\t\t\tpara.Bookmark = \"Contact\"\n\t\t\t\tpara.Text = StringToTextArray(elem.Content)\n\t\t\t\tdocument.TitlePage.Para = append(document.TitlePage.Para, para)\n\t\t\tcase \"source\":\n\t\t\t\tpara := new(Para)\n\t\t\t\tpara.Bookmark = \"Source\"\n\t\t\t\tpara.Text = StringToTextArray(elem.Content)\n\t\t\t\tdocument.TitlePage.Para = append(document.TitlePage.Para, para)\n\t\t\tcase \"story by\":\n\t\t\t\tpara := new(Para)\n\t\t\t\tpara.Bookmark = \"Story By\"\n\t\t\t\tpara.Text = StringToTextArray(elem.Content)\n\t\t\t\tdocument.TitlePage.Para = append(document.TitlePage.Para, para)\n\t\t\tcase \"uuid\":\n\t\t\t\tdocument.Info.UUID = elem.Content\n\t\t\tcase \"page_count\":\n\t\t\t\tdocument.Info.PageCount = elem.Content\n\t\t\tcase \"title_format\":\n\t\t\t\tdocument.Info.TitleFormat = elem.Content\n\t\t\t}\n\t\t}\n\t}\n\n\tif screenplay.Elements != nil {\n\t\t// Populate the Paragraphs array\n\t\tif document.Paragraphs == nil {\n\t\t\tdocument.Paragraphs = new(Paragraphs)\n\t\t}\n\t\tfor _, elem := range screenplay.Elements {\n\t\t\tpara := new(Para)\n\t\t\tpara.Bookmark = elem.TypeName()\n\t\t\tpara.Text = StringToTextArray(elem.Content)\n\t\t\tdocument.Paragraphs.Para = append(document.Paragraphs.Para, para)\n\t\t}\n\t}\n}", "func stage3() {\n\tlog.Println(\"stage 3\")\n\n\tminimal, err := pdf.Open(\"h7-minimal.pdf\")\n\tif err != nil {\n\t\tlog.Fatalln(errgo.Details(err))\n\t}\n\n\t// log.Println(\"minimal:\", minimal)\n\n\t// annotation array\n\tminimal.Add(pdf.IndirectObject{\n\t\tObjectReference: pdf.ObjectReference{ObjectNumber: 7},\n\t\tObject: pdf.Array{\n\t\t\tpdf.ObjectReference{ObjectNumber: 10},\n\t\t\tpdf.ObjectReference{ObjectNumber: 11},\n\t\t},\n\t})\n\n\tminimal.Free(8)\n\tminimal.Free(9)\n\n\terr = minimal.Save()\n\tif err != nil {\n\t\tlog.Fatalln(errgo.Details(err))\n\t}\n}", "func (LocalAPIs) Site4DatasetPct(dasquery dasql.DASQuery) []mongo.DASRecord {\n\n\tspec := dasquery.Spec\n\tinst := dasquery.Instance\n\t// DBS part, find total number of blocks and files for given dataset\n\tdataset := spec[\"dataset\"].(string)\n\tapi := \"filesummaries\"\n\tfurl := fmt.Sprintf(\"%s/%s?dataset=%s\", DBSUrl(inst), api, dataset)\n\tif strings.HasPrefix(inst, \"prod\") {\n\t\tfurl = fmt.Sprintf(\"%s/%s?dataset=%s&validFileOnly=1\", DBSUrl(inst), api, dataset)\n\t}\n\tclient := utils.HttpClient()\n\tresp := utils.FetchResponse(client, furl, \"\") // \"\" specify optional args\n\trecords := DBSUnmarshal(api, resp.Data)\n\tvar totblocks, totfiles int64\n\tif len(records) == 0 {\n\t\treturn []mongo.DASRecord{}\n\t}\n\ttotblocks = rec2num(records[0][\"num_block\"])\n\ttotfiles = rec2num(records[0][\"num_file\"])\n\n\t// to proceed with Rucio we need to know all blocks for a given dataset\n\t// we obtain this list from DBS\n\tapi = \"blocks\"\n\tfurl = fmt.Sprintf(\"%s/%s?dataset=%s\", DBSUrl(inst), api, dataset)\n\tresp = utils.FetchResponse(client, furl, \"\") // \"\" specify optional args\n\trecords = DBSUnmarshal(api, resp.Data)\n\tvar blocks []string\n\tfor _, rec := range records {\n\t\tbrec := rec[\"block_name\"]\n\t\tif brec != nil {\n\t\t\tblk := rec[\"block_name\"].(string)\n\t\t\tblocks = append(blocks, blk)\n\t\t}\n\t}\n\n\t// obtan Rucio information\n\tsiteInfo, _ := rucioInfo(dasquery, blocks)\n\n\t// construct final representation for sites\n\tvar pfiles, pblks string\n\tvar out []mongo.DASRecord\n\tfor key, val := range siteInfo {\n\t\trow := val.(mongo.DASRecord)\n\t\tnfiles := rec2num(row[\"files\"])\n\t\tif totfiles > 0 {\n\t\t\tpfiles = fmt.Sprintf(\"%5.2f%%\", 100*float64(nfiles)/float64(totfiles))\n\t\t} else {\n\t\t\tpfiles = \"N/A\"\n\t\t\tpblks = \"N/A\"\n\t\t}\n\t\tif totblocks > 0 {\n\t\t\tnblks := rec2num(row[\"blocks\"])\n\t\t\tpblks = fmt.Sprintf(\"%5.2f%%\", 100*float64(nblks)/float64(totblocks))\n\t\t} else {\n\t\t\tpfiles = \"N/A\"\n\t\t\tpblks = \"N/A\"\n\t\t}\n\t\tratio := float64(rec2num(row[\"block_present\"])) / float64(rec2num(row[\"blocks\"]))\n\t\tbc := fmt.Sprintf(\"%5.2f%%\", 100*ratio)\n\t\tif rec2num(row[\"block_file_count\"]) != 0 {\n\t\t\tratio = float64(rec2num(row[\"available_file_count\"])) / float64(rec2num(row[\"block_file_count\"]))\n\t\t} else {\n\t\t\tratio = 0\n\t\t}\n\t\trf := fmt.Sprintf(\"%5.2f%%\", 100*ratio)\n\t\tif utils.VERBOSE > 0 {\n\t\t\tif utils.WEBSERVER == 0 {\n\t\t\t\tfmt.Printf(\"site: %s siteInfo: %+v\\n\", key, row)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"site: %s siteInfo: %+v\\n\", key, row)\n\t\t\t}\n\t\t}\n\t\t// put into file das record, internal type must be list\n\t\trec := make(mongo.DASRecord)\n\t\trec[\"site\"] = []mongo.DASRecord{{\"name\": key,\n\t\t\t\"dataset_fraction\": pfiles, \"block_fraction\": pblks, \"block_completion\": bc,\n\t\t\t\"se\": row[\"se\"].(string), \"replica_fraction\": rf, \"kind\": row[\"kind\"].(string),\n\t\t\t\"nblocks\": rec2num(row[\"block_present\"]), \"nfiles\": rec2num(row[\"available_file_count\"]),\n\t\t\t\"total_blocks\": totblocks, \"total_files\": totfiles,\n\t\t}}\n\t\tout = append(out, rec)\n\t}\n\treturn out\n}", "func (pt *PathTracer) SampleSensorPath(\n\trng *rand.Rand, scene *Scene, sensor Sensor, x, y int,\n\tsensorBundle, tracerBundle SampleBundle, record *TracerRecord) {\n\t*record = TracerRecord{\n\t\tContributionType: TRACER_SENSOR_CONTRIBUTION,\n\t\tSensor: sensor,\n\t\tX: x,\n\t\tY: y,\n\t}\n\tif !pt.hasSomethingToDo() {\n\t\treturn\n\t}\n\n\tinitialRay, WeDivPdf, pdfSensor := sensor.SampleRay(x, y, sensorBundle)\n\tif WeDivPdf.IsBlack() || pdfSensor == 0 {\n\t\treturn\n\t}\n\n\tweightTracker := MakeTracerWeightTracker(pt.beta)\n\n\t// One for the point on the sensor, and one for the direction\n\t// to the next vertex (assuming there is one).\n\tswitch pt.weighingMethod {\n\tcase TRACER_UNIFORM_WEIGHTS:\n\t\tweightTracker.AddP(0, 1)\n\t\tweightTracker.AddP(1, 1)\n\tcase TRACER_POWER_WEIGHTS:\n\t\tweightTracker.AddP(0, 1)\n\t\t// The spatial component should technically be in the\n\t\t// first weight, but it doesn't affect anything to\n\t\t// have it lumped in with the directional component\n\t\t// here.\n\t\textent := sensor.GetExtent()\n\t\tpdfPixel := 1 / float32(extent.GetPixelCount())\n\t\tweightTracker.AddP(1, pdfPixel*pdfSensor)\n\t}\n\n\twiSamples := tracerBundle.Samples2D[0]\n\tray := initialRay\n\n\t// It's okay to leave n uninitialized for the first iteration\n\t// of the loop below since pt.computeEmittedLight() uses it\n\t// only when edgeCount > 1.\n\tvar n Normal3\n\n\t// alpha = We * T(path) / pdf.\n\talpha := WeDivPdf\n\talbedo := WeDivPdf\n\tvar t *Spectrum\n\tswitch pt.russianRouletteContribution {\n\tcase TRACER_RUSSIAN_ROULETTE_ALPHA:\n\t\tt = &alpha\n\tcase TRACER_RUSSIAN_ROULETTE_ALBEDO:\n\t\tt = &albedo\n\t}\n\tvar edgeCount int\n\tfor {\n\t\tpContinue := pt.russianRouletteState.GetContinueProbability(\n\t\t\tedgeCount, t)\n\t\tif pContinue <= 0 {\n\t\t\tbreak\n\t\t}\n\t\tif pContinue < 1 {\n\t\t\tif randFloat32(rng) > pContinue {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\talpha.ScaleInv(&alpha, pContinue)\n\t\t}\n\t\tvar intersection Intersection\n\t\tif !scene.Aggregate.Intersect(&ray, &intersection) {\n\t\t\tbreak\n\t\t}\n\t\t// The new edge is between ray.O and intersection.P.\n\t\tedgeCount++\n\n\t\tvar wo Vector3\n\t\two.Flip(&ray.D)\n\n\t\t// NOTE: If emitted light paths are turned off, then\n\t\t// no light will reach the sensor directly from the\n\t\t// light (since direct lighting doesn't handle the\n\t\t// first edge).\n\t\tif pt.pathTypes.HasPaths(TRACER_EMITTED_LIGHT_PATH) {\n\t\t\twLeAlpha := pt.computeEmittedLight(\n\t\t\t\tedgeCount, scene, sensor, x, y, &alpha,\n\t\t\t\tweightTracker, ray.O, ray.MinT, n,\n\t\t\t\tray.D, wo, &intersection,\n\t\t\t\t&record.DebugRecords)\n\t\t\tif !wLeAlpha.IsValid() {\n\t\t\t\tfmt.Printf(\"Invalid wLeAlpha %v returned for \"+\n\t\t\t\t\t\"intersection %v and wo %v\\n\",\n\t\t\t\t\twLeAlpha, intersection, wo)\n\t\t\t\twLeAlpha = Spectrum{}\n\t\t\t}\n\n\t\t\trecord.WeLiDivPdf.Add(&record.WeLiDivPdf, &wLeAlpha)\n\t\t}\n\n\t\tif edgeCount >= pt.maxEdgeCount {\n\t\t\tbreak\n\t\t}\n\n\t\t// Don't sample direct lighting for the last edge,\n\t\t// since the process adds an extra edge.\n\t\tif pt.pathTypes.HasPaths(TRACER_DIRECT_LIGHTING_PATH) {\n\t\t\twLeAlphaNext := pt.sampleDirectLighting(\n\t\t\t\tedgeCount, rng, scene, sensor, x, y,\n\t\t\t\ttracerBundle, &alpha, weightTracker, wo,\n\t\t\t\t&intersection, &record.DebugRecords)\n\t\t\tif !wLeAlphaNext.IsValid() {\n\t\t\t\tfmt.Printf(\"Invalid wLeAlphaNext %v returned \"+\n\t\t\t\t\t\"for intersection %v and wo %v\\n\",\n\t\t\t\t\twLeAlphaNext, intersection, wo)\n\t\t\t\twLeAlphaNext = Spectrum{}\n\t\t\t}\n\n\t\t\trecord.WeLiDivPdf.Add(&record.WeLiDivPdf, &wLeAlphaNext)\n\t\t}\n\n\t\tsampleIndex := edgeCount - 1\n\t\tu := wiSamples.GetSample(sampleIndex, rng)\n\t\twi, fDivPdf, pdf := intersection.Material.SampleWi(\n\t\t\tMATERIAL_LIGHT_TRANSPORT,\n\t\t\tu.U1, u.U2, wo, intersection.N)\n\t\tif fDivPdf.IsBlack() || pdf == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif !fDivPdf.IsValid() {\n\t\t\tfmt.Printf(\"Invalid fDivPdf %v returned for \"+\n\t\t\t\t\"intersection %v and wo %v\\n\",\n\t\t\t\tfDivPdf, intersection, wo)\n\t\t\tbreak\n\t\t}\n\n\t\tpt.updatePathWeight(\n\t\t\t&weightTracker, edgeCount, sensor, x, y, wo, wi,\n\t\t\t&intersection, pContinue, pdf)\n\n\t\tray = Ray{\n\t\t\tintersection.P, wi,\n\t\t\tintersection.PEpsilon, infFloat32(+1),\n\t\t}\n\t\tn = intersection.N\n\t\talpha.Mul(&alpha, &fDivPdf)\n\t\talbedo = fDivPdf\n\t}\n\n\tif pt.debugLevel >= 1 {\n\t\tn := float32(edgeCount) / float32(pt.maxEdgeCount)\n\t\tdebugRecord := TracerDebugRecord{\n\t\t\tTag: \"n\",\n\t\t\tS: MakeConstantSpectrum(n),\n\t\t}\n\t\trecord.DebugRecords = append(record.DebugRecords, debugRecord)\n\t}\n\n\tif !record.WeLiDivPdf.IsValid() {\n\t\tfmt.Printf(\"Invalid weighted Li %v for ray %v\\n\",\n\t\t\trecord.WeLiDivPdf, initialRay)\n\t}\n}", "func newAnalysis(b *Bucket, displayObjectCount int) *Analysis {\n\ta := Analysis{\n\t\tName: b.Name,\n\t\tDisplayObjectCount: displayObjectCount,\n\t\tCreationDate: b.CreationDate,\n\t\tSizePerOwnerID: make(map[string]int64, 0),\n\t\tObjects: make([]string, 0),\n\t}\n\treturn &a\n}", "func init() {\n\tf := GeneralMatrices\n\tfor level := 0; level < 2; level++ {\n\t\tmf := MutateFixtures(f, f)\n\t\tf = append(f, mf...)\n\t}\n\tTestFixtures = f\n\n}", "func processSample(name, samplePath, typ, vel string) error {\n\tlogrus.Infof(\"copying sample for preset '%s': %s\", name, samplePath)\n\t// Rimshots only have two samples - going to add them their own set and the 'all' set\n\tif strings.Contains(samplePath, \"Rim\") {\n\t\tdest := filepath.Join(\"export\", name, \"rim\")\n\t\tif err := copySampleFile(samplePath, getDestFilePath(dest, samplePath)); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tdest := filepath.Join(\"export\", name, vel)\n\t\tif err := copySampleFile(samplePath, getDestFilePath(dest, samplePath)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// add to the all directory as well\n\tdest := filepath.Join(\"export\", name, \"all\")\n\tif err := copySampleFile(samplePath, getDestFilePath(dest, samplePath)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (v VocalSystem) FormantsTrack() tracks.TrackSet {\n\treturn v.TrackSet[tracks.TrackID(\"Formants\")].(tracks.TrackSet)\n}" ]
[ "0.48447978", "0.47765958", "0.4695485", "0.46900222", "0.44679007", "0.44175565", "0.4406523", "0.4366745", "0.43615544", "0.42866498", "0.42866498", "0.42866498", "0.42866498", "0.42866498", "0.42866498", "0.42866498", "0.423736", "0.4231114", "0.4230045", "0.42229453", "0.4209855", "0.42066658", "0.41789192", "0.41717458", "0.4168601", "0.41661036", "0.4156746", "0.41362512", "0.41242582", "0.40978125", "0.4097806", "0.409089", "0.40778443", "0.40747258", "0.40656596", "0.40624216", "0.4061883", "0.4058627", "0.4029267", "0.40184698", "0.4016787", "0.40151185", "0.40002254", "0.3995809", "0.39850774", "0.3977785", "0.39776358", "0.39700165", "0.39692658", "0.39412165", "0.3938261", "0.39282116", "0.39267015", "0.39162752", "0.39095384", "0.39036134", "0.3902212", "0.38928118", "0.3891643", "0.38886666", "0.3883483", "0.38803297", "0.38795835", "0.38746458", "0.3874642", "0.38699567", "0.3869339", "0.3869216", "0.3868375", "0.38678047", "0.38556278", "0.38523787", "0.38429198", "0.38402584", "0.38399625", "0.38347965", "0.38337472", "0.3832336", "0.38305804", "0.38304037", "0.38301843", "0.38285914", "0.38282707", "0.38275683", "0.38267082", "0.38261327", "0.38253766", "0.38233528", "0.38219196", "0.38215062", "0.38213378", "0.38171506", "0.38138875", "0.38127315", "0.38076195", "0.3806556", "0.3800716", "0.37994277", "0.37933412", "0.3790487", "0.37894627" ]
0.0
-1
DoubleSliceCap doubles the capacity of a slice
func DoubleSliceCap(ba []byte) (newBa []byte) { newBa = make([]byte, len(ba), 2*cap(ba)) copy(newBa, ba) fmt.Printf("len: %v - newcap: %v <br>\n", len(newBa), cap(newBa)) return newBa }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func SliceCap(v any, c uint64) int {\n\tif int64(c) < 0 || c != uint64(int(c)) {\n\t\treturn -1\n\t}\n\ttyp := reflect.TypeOf(v)\n\tif typ.Kind() != reflect.Ptr {\n\t\tpanic(\"SliceCap called with non-pointer type\")\n\t}\n\tsize := uint64(typ.Elem().Size())\n\tif size > 0 && c > (1<<64-1)/size {\n\t\treturn -1\n\t}\n\tif c*size > chunk {\n\t\tc = uint64(chunk / size)\n\t\tif c == 0 {\n\t\t\tc = 1\n\t\t}\n\t}\n\treturn int(c)\n}", "func sliceTest02() {\n var list = make([]int, 1, 2)\n fmt.Println(\"original length\", len(list))\n list = list[:cap(list)]\n fmt.Println(\"after sliced\", len(list))\n\n defer func() {\n if err := recover(); err != nil {\n fmt.Printf(\"max slice length cannot be greater than the slice capicity!\\n\\t%T \\n\\t%s\\n\", err, err)\n }\n }()\n list = list[:cap(list) + 1]\n fmt.Println(\"after sliced\", len(list))\n}", "func SliceResize(pointToSlice interface{}, newCap int) {\n\tslice := reflect.ValueOf(pointToSlice).Elem()\n\tnewslice := reflect.MakeSlice(slice.Type(), newCap, newCap)\n\treflect.Copy(newslice, slice)\n\tslice.Set(newslice)\n}", "func growslice(et *_type, old slice, cap int) slice {\n\tif raceenabled {\n\t\tcallerpc := getcallerpc()\n\t\tracereadrangepc(old.array, uintptr(old.len*int(et.size)), callerpc, funcPC(growslice))\n\t}\n\tif msanenabled {\n\t\tmsanread(old.array, uintptr(old.len*int(et.size)))\n\t}\n\n\tif cap < old.cap {\n\t\tpanic(errorString(\"growslice: cap out of range\"))\n\t}\n\n\tif et.size == 0 {\n\t\t// append should not create a slice with nil pointer but non-zero len.\n\t\t// We assume that append doesn't need to preserve old.array in this case.\n\t\treturn slice{unsafe.Pointer(&zerobase), old.len, cap}\n\t}\n\n\tnewcap := old.cap\n\tdoublecap := newcap + newcap\n\tif cap > doublecap {\n\t\tnewcap = cap\n\t} else {\n\t\tif old.cap < 1024 {\n\t\t\tnewcap = doublecap\n\t\t} else {\n\t\t\t// Check 0 < newcap to detect overflow\n\t\t\t// and prevent an infinite loop.\n\t\t\tfor 0 < newcap && newcap < cap {\n\t\t\t\tnewcap += newcap / 4\n\t\t\t}\n\t\t\t// Set newcap to the requested cap when\n\t\t\t// the newcap calculation overflowed.\n\t\t\tif newcap <= 0 {\n\t\t\t\tnewcap = cap\n\t\t\t}\n\t\t}\n\t}\n\n\tvar overflow bool\n\tvar lenmem, newlenmem, capmem uintptr\n\t// Specialize for common values of et.size.\n\t// For 1 we don't need any division/multiplication.\n\t// For sys.PtrSize, compiler will optimize division/multiplication into a shift by a constant.\n\t// For powers of 2, use a variable shift.\n\tswitch {\n\tcase et.size == 1:\n\t\tlenmem = uintptr(old.len)\n\t\tnewlenmem = uintptr(cap)\n\t\tcapmem = roundupsize(uintptr(newcap))\n\t\toverflow = uintptr(newcap) > maxAlloc\n\t\tnewcap = int(capmem)\n\tcase et.size == sys.PtrSize:\n\t\tlenmem = uintptr(old.len) * sys.PtrSize\n\t\tnewlenmem = uintptr(cap) * sys.PtrSize\n\t\tcapmem = roundupsize(uintptr(newcap) * sys.PtrSize)\n\t\toverflow = uintptr(newcap) > maxAlloc/sys.PtrSize\n\t\tnewcap = int(capmem / sys.PtrSize)\n\tcase isPowerOfTwo(et.size):\n\t\tvar shift uintptr\n\t\tif sys.PtrSize == 8 {\n\t\t\t// Mask shift for better code generation.\n\t\t\tshift = uintptr(sys.Ctz64(uint64(et.size))) & 63\n\t\t} else {\n\t\t\tshift = uintptr(sys.Ctz32(uint32(et.size))) & 31\n\t\t}\n\t\tlenmem = uintptr(old.len) << shift\n\t\tnewlenmem = uintptr(cap) << shift\n\t\tcapmem = roundupsize(uintptr(newcap) << shift)\n\t\toverflow = uintptr(newcap) > (maxAlloc >> shift)\n\t\tnewcap = int(capmem >> shift)\n\tdefault:\n\t\tlenmem = uintptr(old.len) * et.size\n\t\tnewlenmem = uintptr(cap) * et.size\n\t\tcapmem, overflow = math.MulUintptr(et.size, uintptr(newcap))\n\t\tcapmem = roundupsize(capmem)\n\t\tnewcap = int(capmem / et.size)\n\t}\n\n\t// The check of overflow in addition to capmem > maxAlloc is needed\n\t// to prevent an overflow which can be used to trigger a segfault\n\t// on 32bit architectures with this example program:\n\t//\n\t// type T [1<<27 + 1]int64\n\t//\n\t// var d T\n\t// var s []T\n\t//\n\t// func main() {\n\t// s = append(s, d, d, d, d)\n\t// print(len(s), \"\\n\")\n\t// }\n\tif overflow || capmem > maxAlloc {\n\t\tpanic(errorString(\"growslice: cap out of range\"))\n\t}\n\n\tvar p unsafe.Pointer\n\tif et.ptrdata == 0 {\n\t\tp = mallocgc(capmem, nil, false)\n\t\t// The append() that calls growslice is going to overwrite from old.len to cap (which will be the new length).\n\t\t// Only clear the part that will not be overwritten.\n\t\tmemclrNoHeapPointers(add(p, newlenmem), capmem-newlenmem)\n\t} else {\n\t\t// Note: can't use rawmem (which avoids zeroing of memory), because then GC can scan uninitialized memory.\n\t\tp = mallocgc(capmem, et, true)\n\t\tif lenmem > 0 && writeBarrier.enabled {\n\t\t\t// Only shade the pointers in old.array since we know the destination slice p\n\t\t\t// only contains nil pointers because it has been cleared during alloc.\n\t\t\tbulkBarrierPreWriteSrcOnly(uintptr(p), uintptr(old.array), lenmem-et.size+et.ptrdata)\n\t\t}\n\t}\n\tmemmove(p, old.array, lenmem)\n\n\treturn slice{p, old.len, newcap}\n}", "func (ms Float64Slice) EnsureCapacity(newCap int) {\n\toldCap := cap(*ms.getOrig())\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]float64, len(*ms.getOrig()), newCap)\n\tcopy(newOrig, *ms.getOrig())\n\t*ms.getOrig() = newOrig\n}", "func TestSplitShareCapacity(t *testing.T) {\n\n\ta1 := []int{1,2,3,4,5}\n\n\ta2 := a1[1:2]\n\n\ta2[0] = 100\n\n\tt.Log(a1)\n\tt.Log(a2)\n\tt.Log(cap(a2))\n\n}", "func (m *metricMysqlDoubleWrites) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func sliceTest04() {\n list := make([]int, 1, 2)\n for i := 0; i < 65; i++ {\n list = append(list, i)\n fmt.Printf(\"length: %d, capacity %d\\n\", len(list), cap(list))\n }\n}", "func (s *slice) slice(start, stop int, elemsize uintptr) slice {\n\tif start >= s.cap_ || start < 0 || stop > s.cap_ || stop < 0 {\n\t\tpanic(\"cuda4/safe: slice index out of bounds\")\n\t}\n\tif start > stop {\n\t\tpanic(\"cuda4/safe: inverted slice range\")\n\t}\n\treturn slice{cu.DevicePtr(uintptr(s.ptr_) + uintptr(start)*elemsize), stop - start, s.cap_ - start}\n}", "func slicecap() {\n\n\tvar fruits = []string{\"apple\", \"grape\", \"banana\", \"melon\"}\n\tfmt.Println(\"index len is: \", len(fruits))\n\tfmt.Println(\"index cap is: \", cap(fruits))\n\n\tvar aFruits = fruits[0:3]\n\tfmt.Println(\"index len is: \", len(aFruits))\n\tfmt.Println(\"index cap is: \", cap(aFruits))\n\n\tvar bFruits = fruits[1:4]\n\tfmt.Println(\"index len is: \", len(bFruits))\n\tfmt.Println(\"index cap is: \", cap(bFruits))\n}", "func (q *queue) Double() {\n\tq.items = append(q.items, make([]item, q.len)...)\n\tq.capacity = len(q.items)\n\tq.head = 0\n\tq.tail = q.len\n}", "func GrowCap(oldCap, unit, num uint) (newCap uint) {\n\t// appendslice logic (if cap < 1024, *2, else *1.25):\n\t// leads to many copy calls, especially when copying bytes.\n\t// bytes.Buffer model (2*cap + n): much better for bytes.\n\t// smarter way is to take the byte-size of the appended element(type) into account\n\n\t// maintain 1 thresholds:\n\t// t1: if cap <= t1, newcap = 2x\n\t// else newcap = 1.5x\n\t//\n\t// t1 is always >= 1024.\n\t// This means that, if unit size >= 16, then always do 2x or 1.5x\n\t//\n\t// With this, appending for bytes increase by:\n\t// 100% up to 4K\n\t// 50% beyond that\n\n\t// unit can be 0 e.g. for struct{}{}; handle that appropriately\n\tmaxCap := num + (oldCap * 3 / 2)\n\tif unit == 0 || maxCap > MaxArrayLen || maxCap < oldCap { // handle wraparound, etc\n\t\treturn MaxArrayLen\n\t}\n\n\tconst baseThreshold = 1024\n\tconst cacheLineSize = 64\n\n\tvar t1 uint = baseThreshold // default thresholds for large values\n\tif unit <= 4 {\n\t\tt1 = 8 * baseThreshold\n\t} else if unit <= 16 {\n\t\tt1 = 2 * baseThreshold\n\t}\n\n\tif oldCap == 0 {\n\t\tnewCap = 2 + num\n\t} else if oldCap <= t1 { // [0,t1]\n\t\tnewCap = num + oldCap + oldCap // num+(oldCap*2)\n\t} else { // (t1,infinity]\n\t\tnewCap = maxCap\n\t}\n\n\t// ensure newCap takes multiples of a cache line (size is a multiple of cacheLineSize).\n\t// newcap*unit need not be divisible by the lowest common multiple of unit and cachelinesize.\n\tt1 = newCap * unit\n\tif t2 := t1 % cacheLineSize; t2 != 0 {\n\t\tnewCap = (t1 + cacheLineSize - t2) / unit\n\t}\n\n\treturn\n}", "func intArrayCapUp (old []int)(new []int) {\n new = make([]int, cap(old)+1)\n copy(new, old) //copy(dst,src)\n old = new\n return new\n}", "func main() {\n\n\tvar numbers = make([]int, 3, 5)\n\tprintSlice(numbers)\n\t// Before initial the slice, it is nil\n\tvar nums []int\n\tif nums == nil {\n\t\tfmt.Println(\"切片是空的\")\n\t}\n\tprintSlice(nums)\n\tnums = make([]int, 3, 10)\n\tif nums == nil {\n\t\tfmt.Println(\"切片是空的\")\n\t}\n\n\t//cut the slice with [lower-bound:upper-bound]\n\tnumbers2 := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}\n\tprintSlice(numbers2)\n\tfmt.Println(\"numbers2 ==\", numbers2)\n\tfmt.Println(\"numbers2[1:4] ==\", numbers2[1:4]) //print m to n (not include n)\n\tfmt.Println(\"numbers2[:3] ==\", numbers2[:3]) // print form 0 to n (not include n)\n\tfmt.Println(\"numbers2[4:] ==\", numbers2[4:]) // print form n to end (not include n)\n\n\t//add new element to slice with append\n\tnumbers2 = append(numbers2, 9, 10, 11)\n\tprintSlice(numbers2)\n\n\t//copy the slice\n\tnumbersCopy := make([]int, len(numbers2), (cap(numbers2))*2)\n\tcopy(numbersCopy, numbers2)\n\tprintSlice(numbers2)\n\tprintSlice(numbersCopy)\n\n}", "func (p *Pool) Make(len, cap, pad int) Slice {\n\tif pad%wordSize != 0 {\n\t\tpad = (1 + (pad / wordSize)) * wordSize\n\t}\n\n\tif blk := p.get(pad + cap + wordSize); blk != nil {\n\t\treturn realloc(*blk, len, cap, pad)\n\t}\n\n\treturn Make(len, cap, pad)\n}", "func main() {\n\t// A slice is a segment of an array.\n\t// Like arrays slices are indexable and have a length.\n\t// Unlike arrays this length is allowed to change\n\n\t//Examples on how to initialise Slices\n\tinitVariable := make([]float32,5)\n\tfmt.Println(\"value : \", initVariable)\n\tfmt.Println(\"length : \", len(initVariable))\n\tfmt.Println(\"Capacity : \", cap(initVariable))\n\n\tcapVariable := make([]float32,5,10)\n\tfmt.Println(\"value : \", capVariable)\n\tfmt.Println(\"length : \", len(capVariable))\n\tfmt.Println(\"Capacity : \", cap(capVariable))\n}", "func ensureCap(s []byte, n int) []byte {\n\tif n <= cap(s) {\n\t\treturn s\n\t}\n\t// logic adapted from appendslice1 in runtime\n\tm := cap(s)\n\tif m == 0 {\n\t\tm = n\n\t} else {\n\t\tfor {\n\t\t\tif m < 1024 {\n\t\t\t\tm += m\n\t\t\t} else {\n\t\t\t\tm += m / 4\n\t\t\t}\n\t\t\tif m >= n {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tt := make([]byte, len(s), m)\n\tcopy(t, s)\n\treturn t\n}", "func (mp *multiSizeSlicePool) RentSlice(desiredSize uint32) []byte {\n\tslotIndex, maxCapInSlot := getSlotInfo(desiredSize)\n\n\t// get the pool that most closely corresponds to the desired size\n\tpool := mp.poolsBySize[slotIndex]\n\n\t// try to get a pooled slice\n\tif typedSlice := pool.Get(); typedSlice != nil {\n\t\t// Capacity will be equal to maxCapInSlot.\n\t\t// Here we set len to the exact desired size that was requested\n\t\ttypedSlice = typedSlice[0:desiredSize]\n\t\t// We do not zero out the content of the slice, so it will still have the content it had\n\t\t// the previous time it was used (before it was returned to the pool)\n\t\t// Why don't we zero it out? Because there would be some performance cost to doing so.\n\t\t// So instead, we rely on the caller to user io.ReadFull or similar, to fully populate the\n\t\t// returned slice (up to its len) with their own data.\n\t\t// A possible alternative would be to change this to return bytes.Buffers instead of slices.\n\t\t// That would require changes to the usage of the returned objects too, since they are Readers/Writers not slices.\n\t\t// TODO: Question: are we happy with leaving this as it is?\n\t\treturn typedSlice\n\t}\n\n\t// make a new slice if nothing pooled\n\treturn make([]byte, desiredSize, maxCapInSlot)\n}", "func (q *Deque) Resize(newCap int) {\n\tif newCap != cap(q.values) {\n\t\tnewValues := make([]interface{}, newCap, newCap)\n\t\tvar j int = 0\n\t\tfor i := q.front; j < q.size && j < newCap; i, j = (i+1)%cap(q.values), j+1 {\n\t\t\tnewValues[j] = q.values[i]\n\t\t}\n\t\tq.values = newValues\n\t\tq.front = 0\n\t\tq.back = j\n\t}\n}", "func slicecopy(toPtr unsafe.Pointer, toLen int, fromPtr unsafe.Pointer, fromLen int, width uintptr) int {\n\tif fromLen == 0 || toLen == 0 {\n\t\treturn 0\n\t}\n\n\tn := fromLen\n\tif toLen < n {\n\t\tn = toLen\n\t}\n\n\tif width == 0 {\n\t\treturn n\n\t}\n\n\tsize := uintptr(n) * width\n\tif raceenabled {\n\t\tcallerpc := getcallerpc()\n\t\tpc := funcPC(slicecopy)\n\t\tracereadrangepc(fromPtr, size, callerpc, pc)\n\t\tracewriterangepc(toPtr, size, callerpc, pc)\n\t}\n\tif msanenabled {\n\t\tmsanread(fromPtr, size)\n\t\tmsanwrite(toPtr, size)\n\t}\n\n\tif size == 1 { // common case worth about 2x to do here\n\t\t// TODO: is this still worth it with new memmove impl?\n\t\t*(*byte)(toPtr) = *(*byte)(fromPtr) // known to be a byte pointer\n\t} else {\n\t\tmemmove(toPtr, fromPtr, size)\n\t}\n\treturn n\n}", "func (s *Slab) Cap() int {\n\treturn cap(s.entries)\n}", "func (es DoubleDataPointSlice) CopyTo(dest DoubleDataPointSlice) {\n\tnewLen := es.Len()\n\tif newLen == 0 {\n\t\t*dest.orig = []*otlpmetrics.DoubleDataPoint(nil)\n\t\treturn\n\t}\n\toldLen := dest.Len()\n\tif newLen <= oldLen {\n\t\t(*dest.orig) = (*dest.orig)[:newLen]\n\t\tfor i, el := range *es.orig {\n\t\t\tnewDoubleDataPoint(&el).CopyTo(newDoubleDataPoint(&(*dest.orig)[i]))\n\t\t}\n\t\treturn\n\t}\n\torigs := make([]otlpmetrics.DoubleDataPoint, newLen)\n\twrappers := make([]*otlpmetrics.DoubleDataPoint, newLen)\n\tfor i, el := range *es.orig {\n\t\twrappers[i] = &origs[i]\n\t\tnewDoubleDataPoint(&el).CopyTo(newDoubleDataPoint(&wrappers[i]))\n\t}\n\t*dest.orig = wrappers\n}", "func ensureLenAndDeref(dst interface{}, n int) interface{} {\n\t// De-reference pointer.\n\tval := reflect.ValueOf(dst).Elem()\n\tif val.Len() >= n {\n\t\treturn val.Slice(0, n).Interface()\n\t}\n\t// Not big enough, re-allocate.\n\tval.Set(reflect.MakeSlice(val.Type(), n, n))\n\treturn val.Interface()\n}", "func (s *internalPointSliceView) MakeWithCapacity(length int, capacity int) ([]Point, error) {\n\tif capacity < length {\n\t\treturn nil, arena.AllocationInvalidArgumentError\n\t}\n\tsliceHdr, allocErr := s.makeGoSlice(capacity)\n\tif allocErr != nil {\n\t\treturn nil, allocErr\n\t}\n\tsliceHdr.Len = length\n\treturn *(*[]Point)(unsafe.Pointer(sliceHdr)), nil\n}", "func boolArrayCapUp (old []bool)(new []bool) {\n new = make([]bool, cap(old)+1)\n copy(new, old)\n old = new\n return new\n}", "func addScaledSlice(y, x []float64, a float64)", "func GrowByDouble(pagesBefore, pagesNeeded int32, minSize uintptr) (pagesAdded int32, start, end uintptr) {\n\tif pagesBefore > pagesNeeded {\n\t\tpagesAdded = pagesBefore\n\t} else {\n\t\tpagesAdded = pagesNeeded\n\t}\n\tstart, end = growBy(pagesAdded)\n\tif start == 0 {\n\t\tpagesAdded = pagesNeeded\n\t\tstart, end = growBy(pagesAdded)\n\t\tif start == 0 {\n\t\t\treturn 0, 0, 0\n\t\t}\n\t}\n\treturn\n}", "func (d HostingDiffs) Cap() int {\n\treturn d.Size() + 3\n}", "func (iobuf *buf) slice(free, base, bound uint) *Slice {\n\tatomic.AddInt32(&iobuf.refcount, 1)\n\treturn &Slice{iobuf: iobuf, free: free, base: base, Contents: iobuf.Contents[base:bound]}\n}", "func main() {\n\n\tfmt.Println(\"---- Slices ------\")\n\n\t// init slice\n\tslice := make([]string, 3) // in C# it will be like List<string>\n\n\tfmt.Println(\"slice empty:\", slice)\n\n\t// different ways to add element in slice\n\tslice[0] = \"text1\"\n\n\tslice = append(slice, \"text2\")\n\tslice = append(slice, \"text3\")\n\tslice = append(slice, \"text4\")\n\n\tfmt.Println(\"slice added elements:\", slice)\n\n\t// change data by index\n\tslice[0] = \"some text\"\n\n\tfmt.Println(\"slice changed item:\", slice)\n\n\t// remove element from slice\n\tslice[0] = slice[len(slice)-1]\n\tslice = slice[:len(slice)-1]\n\n\tfmt.Println(\"slice removed item:\", slice)\n\n\t// copy slice\n\tslicecopy := make([]string, len(slice))\n\tcopy(slicecopy, slice)\n\n\tfmt.Println(\"slicecopy:\", slicecopy)\n\n\t// get length and capacity of slice\n\n\tfmt.Println(\"slice length :\", len(slice))\n\tfmt.Println(\"slice capacity :\", cap(slice))\n\n}", "func (c StringArrayCollection) Take(num int) Collection {\n\tvar d StringArrayCollection\n\tif num > c.length {\n\t\tpanic(\"not enough elements to take\")\n\t}\n\n\tif num >= 0 {\n\t\td.value = c.value[:num]\n\t\td.length = num\n\t} else {\n\t\td.value = c.value[len(c.value)+num:]\n\t\td.length = 0 - num\n\t}\n\n\treturn d\n}", "func makeslice(len_ int, elemsize int) slice {\n\tbytes := int64(len_) * int64(elemsize)\n\ts := slice{0, len_, len_}\n\tif bytes > 0 {\n\t\ts.ptr_ = cu.MemAlloc(bytes)\n\t\tcu.MemsetD8(s.ptr_, 0, bytes)\n\t\tcu.CtxSynchronize()\n\t}\n\treturn s\n}", "func (b *ByteBuffer) Cap() int {\n\treturn cap(b.B)\n}", "func (c *UnlimitedCache) Cap() int {\n\treturn math.MaxInt\n}", "func (s *f64) Cap() int {\n\treturn cap(s.buffer)\n}", "func (t *Slice) Size() int32 { return 4 }", "func MakingSlices() {\n\tvar slice1 = make([]int, 5)\n\tfmt.Println(len(slice1), cap(slice1))\n\n\tvar slice2 = make([]int, 1, 5)\n\tfmt.Println(len(slice2), cap(slice2))\n}", "func (vn *VecN) Cap() int {\n\treturn cap(vn.vec)\n}", "func (p *FixedSizePool) SetCapacity(newCap int) {}", "func Test(slice []int) {\n\tfmt.Printf(\"cap(the slice)=%d\\n\", cap(slice))\n\tslice = append(slice, 100)\n\n\tfmt.Println(\"inside Test:\", slice)\n\tfmt.Printf(\"cap(the slice)=%d\\n\", cap(slice))\n}", "func (p *Packed2DGenericTypeBuilder) Cap() int {\n\treturn len(p.buf)\n}", "func (es DoubleDataPointSlice) Len() int {\n\treturn len(*es.orig)\n}", "func (b *Buffer) Cap() int { return len(b.buf) }", "func (wpr *Wrapper) Cap() int64 {\n\treturn wpr.N\n}", "func makeslicecopy(et *_type, tolen int, fromlen int, from unsafe.Pointer) unsafe.Pointer {\n\tvar tomem, copymem uintptr\n\tif uintptr(tolen) > uintptr(fromlen) {\n\t\tvar overflow bool\n\t\ttomem, overflow = math.MulUintptr(et.size, uintptr(tolen))\n\t\tif overflow || tomem > maxAlloc || tolen < 0 {\n\t\t\tpanicmakeslicelen()\n\t\t}\n\t\tcopymem = et.size * uintptr(fromlen)\n\t} else {\n\t\t// fromlen is a known good length providing and equal or greater than tolen,\n\t\t// thereby making tolen a good slice length too as from and to slices have the\n\t\t// same element width.\n\t\ttomem = et.size * uintptr(tolen)\n\t\tcopymem = tomem\n\t}\n\n\tvar to unsafe.Pointer\n\tif et.ptrdata == 0 {\n\t\tto = mallocgc(tomem, nil, false)\n\t\tif copymem < tomem {\n\t\t\tmemclrNoHeapPointers(add(to, copymem), tomem-copymem)\n\t\t}\n\t} else {\n\t\t// Note: can't use rawmem (which avoids zeroing of memory), because then GC can scan uninitialized memory.\n\t\tto = mallocgc(tomem, et, true)\n\t\tif copymem > 0 && writeBarrier.enabled {\n\t\t\t// Only shade the pointers in old.array since we know the destination slice to\n\t\t\t// only contains nil pointers because it has been cleared during alloc.\n\t\t\tbulkBarrierPreWriteSrcOnly(uintptr(to), uintptr(from), copymem)\n\t\t}\n\t}\n\n\tif raceenabled {\n\t\tcallerpc := getcallerpc()\n\t\tpc := funcPC(makeslicecopy)\n\t\tracereadrangepc(from, copymem, callerpc, pc)\n\t}\n\tif msanenabled {\n\t\tmsanread(from, copymem)\n\t}\n\n\tmemmove(to, from, copymem)\n\n\treturn to\n}", "func MakeCap /*[T algo.Any]*/ (capacity int) *Queue /*[T]*/ {\n\treturn &Queue{\n\t\titems: make([]T, 0, capacity),\n\t}\n}", "func (j *Joint) SetCap(l uint64) error {\n\tchCap := uint64(j.readC.Cap() + j.writeC.Cap())\n\tmin := chCap + 1\n\tif l < min {\n\t\tif Debug {\n\t\t\tlog.Println(\"[joint] extend buffer size to\", min)\n\t\t}\n\t\tl = min\n\t}\n\tmax := uint64(math.MaxUint64 - 1)\n\tif l > max {\n\t\treturn fmt.Errorf(\"[joint] length should not greater than %v\", max)\n\t}\n\tmaxIn := atomic.LoadUint64(&j.maxIn)\n\tif maxIn != l-chCap && atomic.LoadInt32(&j.broken) == 0 && atomic.CompareAndSwapUint64(&j.maxIn, maxIn, l-chCap) {\n\t\tj.reloadC <- struct{}{}\n\t}\n\treturn nil\n}", "func unsafeSlice(slice, data unsafe.Pointer, len int) {\n\ts := (*reflect.SliceHeader)(slice)\n\ts.Data = uintptr(data)\n\ts.Cap = len\n\ts.Len = len\n}", "func (b *Ring) SetCapacity(capacity int) {\n\tb.lock.Lock()\n\tdefer b.lock.Unlock()\n\n\tif capacity < b.size {\n\t\tcapacity = b.size\n\t}\n\tif capacity == len(b.buf) { //nothing to be done\n\t\treturn\n\t}\n\n\tnbuf := make([]interface{}, capacity)\n\n\t// now that the new capacity is enough we just copy down the buffer\n\n\t//there are only two cases:\n\t// either the values are contiguous, then they goes from\n\t// tail to head\n\t// or there are splitted in two:\n\t// tail to buffer's end\n\t// 0 to head.\n\n\thead := b.head\n\ttail := Index(-1, head, b.size, len(b.buf))\n\n\t// we are not going to copy the buffer in the same state (absolute position of head and tail)\n\t// instead, we are going to select the simplest solution.\n\tif tail < head { //data is in one piece\n\t\tcopy(nbuf, b.buf[tail:head+1])\n\t} else { //two pieces\n\t\t//copy as much as possible to the end of the buf\n\t\tn := copy(nbuf, b.buf[tail:])\n\t\t//and then from the beginning\n\t\tcopy(nbuf[n:], b.buf[:head+1])\n\t}\n\tb.buf = nbuf\n\tb.head = b.size - 1\n\treturn\n}", "func (hm HashMap) Cap() int {\n\treturn cap(hm.arr)\n}", "func printSlice(s []int) {\n\tfmt.Printf(\"len=%d cap=%d %v\\n\", len(s), cap(s), s)\n}", "func sliceTest01() {\n var list []int\n pList := &list\n var rList = list\n for i := 0; i < 100; i++ {\n list = append(list, i)\n fmt.Printf(\n`Original Reference:\n length: %d, capacity: %d\nPointer:\n length: %d, capacity: %d\nReference:\n length: %d, capacity: %d\n\n`, len(rList), cap(rList), len(*pList), cap(*pList), len(list), cap(list))\n }\n}", "func (d PacketData) CapLength(length int) {\n\tif length < 0 {\n\t\tpanic(\"length < 0\")\n\t}\n\td.pk.buf.Truncate(int64(length + d.pk.dataOffset()))\n}", "func NewDoubleDataPointSlice() DoubleDataPointSlice {\n\torig := []*otlpmetrics.DoubleDataPoint(nil)\n\treturn DoubleDataPointSlice{&orig}\n}", "func MakeUnsafe(len int) []byte {\n\t// Although no planned function requires more than\n\t// RoundUpPow2(len+1, bytesPerVec) capacity, it is necessary to add\n\t// bytesPerVec instead to make subslicing safe.\n\treturn make([]byte, len, len+bytesPerVec)\n}", "func (_m *MockMutableSeriesIterators) Cap() int {\n\tret := _m.ctrl.Call(_m, \"Cap\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func RemakeUnsafe(bufptr *[]byte, len int) {\n\tminCap := len + bytesPerVec\n\tif minCap <= cap(*bufptr) {\n\t\tgunsafe.ExtendBytes(bufptr, len)\n\t\treturn\n\t}\n\t// This is likely to be called in an inner loop processing variable-size\n\t// inputs, so mild exponential growth is appropriate.\n\t*bufptr = make([]byte, len, RoundUpPow2(minCap+(minCap/8), bytesPerVec))\n}", "func Make(len, cap, pad int) Slice {\n\tif pad%wordSize != 0 {\n\t\tpad = (1 + (pad / wordSize)) * wordSize\n\t}\n\tpad += wordSize\n\n\tslice := make([]byte, pad+len, pad+cap)\n\tinitPadding(slice[:pad])\n\treturn slice[pad : pad+len : pad+cap]\n}", "func resizeSlice(s []interface{}, become int) []interface{} {\n\tswitch cur := len(s); {\n\tcase cur == become:\n\tcase cur < become:\n\t\t// Enlarged fields are set to nil.\n\t\ts = append(s, make([]interface{}, become-cur)...)\n\tcase cur > become:\n\t\ts = s[0:become]\n\t}\n\treturn s\n}", "func ResizeUnsafe(bufptr *[]byte, len int) {\n\tminCap := len + bytesPerVec\n\tif minCap <= cap(*bufptr) {\n\t\tgunsafe.ExtendBytes(bufptr, len)\n\t\treturn\n\t}\n\tdst := make([]byte, len, RoundUpPow2(minCap+(minCap/8), bytesPerVec))\n\tcopy(dst, *bufptr)\n\t*bufptr = dst\n}", "func (m *metricRedisClientsBlocked) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricMysqlBufferPoolDataPages) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func main(){\n\tnumslice:=[]int{1,2,3,4,5}\n\tnumslice2 := numslice[0:4] //4 is not the index but the total no. of elements\n\tfmt.Println(numslice2)\n\t// 5 is considered as 4 as the total no. of elements are 5(index from 0 to 4)\n\tfmt.Println(\"numslice2[1]=\",numslice2[1])\n\tfmt.Println(\"numslice3[:2]=\",numslice[:2]) //Starting from 0 to 1 (till 2 u want and not include 2)\n\tfmt.Println(\"numslice4[2:]=\",numslice[2:]) //After 2 all you want (include 2)\n\n\tnumslice3:=make([]int,5,10) //make a slice whose elements are not known where 5 is the size and 10 is the till what it can extend\n\tfmt.Println(numslice3) // prints the full array, no need of for loop\n\tcopy(numslice3,numslice) //copy of elements of numslice to numslice 3\n\tfmt.Println(numslice3[2])\n\tnumslice3=append(numslice3,0,-1) //adding two elements 0 and -1 in numslice 3 position after index4 and size 5\n\tfmt.Println(numslice3)\n\tfmt.Println(numslice3[6])\n}", "func slice1() {\n\tx := []float64{324234.23423, 232423.2342, 23423.2432, 23423.234, 23423.5556, 435634563.45634563456, 34564356.3456456}\n\n\t// this will check the type for the variable with \"%T\"\n\tfmt.Printf(\"%T \\n\", x)\n\n\t// this will start frm index value 2nd and show all the value prior to 4th place (excluding 4th place)\n\tfmt.Println(\"slicing the slice... by getting the values from index 2 to 4\", x[2:4])\n\n\t// printing the length of the slice, Slice is dynamic in memory allocation\n\tfmt.Println(len(x))\n\n}", "func (arr *ArrayList) resize(newCapacity uint32) {\n if newCapacity < MIN_CAPACITY {\n newCapacity = MIN_CAPACITY\n }\n if (newCapacity > arr.capacity) {\n var newData []ItemType = make([]ItemType, newCapacity)\n copy(newData, arr.data)\n arr.data = newData\n arr.capacity = newCapacity\n } else if newCapacity < arr.capacity {\n arr.data = arr.data[:newCapacity]\n arr.capacity = newCapacity\n }\n}", "func (m *metricRedisKeysEvicted) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricRedisSlavesConnected) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (b *loopBuffer) Cap() int { return cap(b.buf) }", "func CopySlice(slice []byte) []byte {\n\tcopy := append(slice[:0:0], slice...)\n\treturn copy\n}", "func (suite *FIFOTestSuite) TestGetCapSingleGR() {\n\t// initial capacity\n\tsuite.Equal(cap(suite.fifo.slice), suite.fifo.GetCap(), \"unexpected capacity\")\n\n\t// checking after adding 2 items\n\tsuite.fifo.Enqueue(1)\n\tsuite.fifo.Enqueue(2)\n\tsuite.Equal(cap(suite.fifo.slice), suite.fifo.GetCap(), \"unexpected capacity\")\n}", "func (s *internalPointBufferView) MakeWithCapacity(length int,\n\tcapacity int) (PointBuffer, error) {\n\tif capacity < length {\n\t\treturn PointBuffer{}, arena.AllocationInvalidArgumentError\n\t}\n\tsliceHdr, allocErr := s.state.makeSlice(capacity)\n\tif allocErr != nil {\n\t\treturn PointBuffer{}, allocErr\n\t}\n\tsliceHdr.len = length\n\treturn sliceHdr, nil\n}", "func (p *byteBufferPool) take(size int) *[]byte {\n\tslot := p.slot(size)\n\tif slot == errSlot {\n\t\tb := newBytes(size)\n\t\treturn &b\n\t}\n\tv := p.pool[slot].pool.Get()\n\tif v == nil {\n\t\tb := newBytes(p.pool[slot].defaultSize)\n\t\tb = b[0:size]\n\t\treturn &b\n\t}\n\tb := v.(*[]byte)\n\t*b = (*b)[0:size]\n\treturn b\n}", "func (m *metricActiveDirectoryDsBindRate) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricActiveDirectoryDsSuboperationRate) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (s PointBuffer) SubSlice(low int, high int) PointBuffer {\n\tinBounds := low >= 0 && low <= high && high <= s.cap\n\tif !inBounds {\n\t\tpanic(fmt.Errorf(\n\t\t\t\"runtime error: slice bounds out of range [%d:%d] with capacity %d\",\n\t\t\tlow, high, s.cap,\n\t\t))\n\t}\n\tvar tVar Point\n\ttSize := unsafe.Sizeof(tVar)\n\ttype internalPtr struct {\n\t\toffset uintptr\n\t\tbucketIdx uint8\n\t\tarenaMask uint16\n\t}\n\tcurrentPtr := *(*internalPtr)(unsafe.Pointer(&s.data))\n\tnewPtr := internalPtr{\n\t\toffset: currentPtr.offset + uintptr(low*int(tSize)),\n\t\tbucketIdx: currentPtr.bucketIdx,\n\t\tarenaMask: currentPtr.arenaMask,\n\t}\n\treturn PointBuffer{\n\t\tdata: *(*arena.Ptr)(unsafe.Pointer(&newPtr)),\n\t\tlen: high - low,\n\t\tcap: s.cap - low,\n\t}\n}", "func (m *metricMysqlSorts) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricMysqlBufferPoolPageFlushes) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func printSlice(s string, x []int) {\n\tfmt.Printf(\"%s len=%d cap=%d %v\\n\",\n\t\ts, len(x), cap(x), x)\n}", "func tcMakeSliceCopy(n *ir.MakeExpr) ir.Node {\n\t// Errors here are Fatalf instead of Errorf because only the compiler\n\t// can construct an OMAKESLICECOPY node.\n\t// Components used in OMAKESCLICECOPY that are supplied by parsed source code\n\t// have already been typechecked in OMAKE and OCOPY earlier.\n\tt := n.Type()\n\n\tif t == nil {\n\t\tbase.Fatalf(\"no type specified for OMAKESLICECOPY\")\n\t}\n\n\tif !t.IsSlice() {\n\t\tbase.Fatalf(\"invalid type %v for OMAKESLICECOPY\", n.Type())\n\t}\n\n\tif n.Len == nil {\n\t\tbase.Fatalf(\"missing len argument for OMAKESLICECOPY\")\n\t}\n\n\tif n.Cap == nil {\n\t\tbase.Fatalf(\"missing slice argument to copy for OMAKESLICECOPY\")\n\t}\n\n\tn.Len = Expr(n.Len)\n\tn.Cap = Expr(n.Cap)\n\n\tn.Len = DefaultLit(n.Len, types.Types[types.TINT])\n\n\tif !n.Len.Type().IsInteger() && n.Type().Kind() != types.TIDEAL {\n\t\tbase.Errorf(\"non-integer len argument in OMAKESLICECOPY\")\n\t}\n\n\tif ir.IsConst(n.Len, constant.Int) {\n\t\tif ir.ConstOverflow(n.Len.Val(), types.Types[types.TINT]) {\n\t\t\tbase.Fatalf(\"len for OMAKESLICECOPY too large\")\n\t\t}\n\t\tif constant.Sign(n.Len.Val()) < 0 {\n\t\t\tbase.Fatalf(\"len for OMAKESLICECOPY must be non-negative\")\n\t\t}\n\t}\n\treturn n\n}", "func (m *metricMysqlBufferPoolPages) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricActiveDirectoryDsReplicationObjectRate) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (mp *multiSizeSlicePool) ReturnSlice(slice []byte) {\n\tslotIndex, _ := getSlotInfo(uint32(cap(slice))) // be sure to use capacity, not length, here\n\n\t// get the pool that most closely corresponds to the desired size\n\tpool := mp.poolsBySize[slotIndex]\n\n\t// put the slice back into the pool\n\tpool.Put(slice)\n}", "func ReleaseDoubleArrayElements(env *C.JNIEnv, array C.jdoubleArray, elems *C.jdouble, mode C.jint) {\n\tC._GoJniReleaseDoubleArrayElements(env, array, elems, mode)\n}", "func cdivSlice(out, a []float64, c float64)", "func subSlice(out, a, b []float64)", "func (ins *Cache) releseCap(now time.Time) {\n\tif now.Sub(ins.released) < time.Duration(24)*time.Hour {\n\t\treturn\n\t}\n\tstorage := new(sync.Map)\n\tscanAll :=\n\t\tfunc(key, value interface{}) (continueIteration bool) {\n\t\t\tcontinueIteration = true\n\t\t\ti, ok := value.(*item)\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif i.expire.Before(now) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tstorage.Store(key, value)\n\t\t\treturn\n\t\t}\n\tins.storage.Range(scanAll)\n\tins.storage = storage\n\tins.released = now\n}", "func (items Float64Slice) SubSlice(i, j int) Interface { return items[i:j] }", "func Take(dst, src []float64, indices []int) []float64 {\n\n\tif len(indices) > len(src) {\n\t\tpanic(errLength)\n\t}\n\n\tif dst == nil {\n\t\tdst = make([]float64, len(indices))\n\t}\n\n\tif len(dst) != len(indices) {\n\t\tpanic(errLength)\n\t}\n\n\tif len(indices) == 0 {\n\t\treturn dst\n\t}\n\n\tdst[0] = src[indices[0]]\n\tfor i := 1; i < len(indices); i++ {\n\t\tv0 := indices[i-1]\n\t\tv1 := indices[i]\n\t\tswitch {\n\t\tcase v0 == v1:\n\t\t\tpanic(errDuplicateIndices)\n\t\tcase v0 > v1:\n\t\t\tpanic(errSortedIndices)\n\t\t}\n\t\tdst[i] = src[v1]\n\t}\n\n\treturn dst\n}", "func (m *metricActiveDirectoryDsReplicationPropertyRate) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricRedisKeyspaceMisses) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricBigipPoolPacketCount) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func slicesTest() {\n\tarr := [...]string{\"a\", \"b\", \"c\"}\n\ts1 := arr[1:3] // holds arr[1], arr[2]\n\tfmt.Printf(\"length, capacity of slice = %d,%d\\n\", len(s1), cap(s1))\n\ts1[0] = \"new\" //slices change the underlying array\n\tfmt.Println(arr[1])\n\n\ts2 := []int{1, 2, 3} //slice literal, creates underlying array\n\tfmt.Println(s2)\n}", "func main() {\n\ta := make([]int, 5)\n\tprintSlice(\"a\", a)\n\n\tb := make([]int, 0, 7)\n\tprintSlice(\"b\", b)\n\n\tc := b[:2]\n\tprintSlice(\"c\", c)\n\n\td := c[2:5]\n\tprintSlice(\"d\", d)\n\n\t//Slices can be composed into multi-dimensional data structures. The\n\t//length of the inner slices can vary, unlike with multi-dimensional\n\t//arrays.\n\ttwoD := make([][]int, 3)\n\tfor i := 0; i < 3; i++ {\n\t\tinnerLen := i + 1\n\t\ttwoD[i] = make([]int, innerLen)\n\t\tfor j := 0; j < innerLen; j++ {\n\t\t\ttwoD[i][j] = i + j\n\t\t}\n\t}\n\tfmt.Println(\"2d: \", twoD)\n}", "func (p *Pool) Cap() int {\n\treturn int(atomic.LoadInt32(&p.capacity))\n}", "func (m *metricRedisConnectionsRejected) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func copy2DSlice(sourceSlice [][]byte, destinationSlice [][]byte) {\n\tfor i := 0; i < len(sourceSlice); i++ {\n\t\tfor j := 0; j < len(sourceSlice[i]); j++ {\n\t\t\tdestinationSlice[i][j] = sourceSlice[i][j]\n\t\t}\n\t}\n}", "func (m *metricActiveDirectoryDsLdapBindRate) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricMysqlBufferPoolLimit) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricMysqlRowLocks) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (m *metricActiveDirectoryDsLdapSearchRate) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}" ]
[ "0.6515058", "0.58603746", "0.57400995", "0.5730556", "0.5695987", "0.5577184", "0.5510019", "0.54346704", "0.5266703", "0.5258881", "0.5249592", "0.5203409", "0.5164658", "0.5087734", "0.50720453", "0.5062025", "0.5043372", "0.50402814", "0.5031894", "0.4998711", "0.49762437", "0.49590856", "0.49492627", "0.4941919", "0.49266413", "0.49170104", "0.49008292", "0.4895789", "0.48918498", "0.48827738", "0.48759153", "0.48595163", "0.48394313", "0.48167613", "0.48150516", "0.48039666", "0.48033252", "0.48000672", "0.47947654", "0.4754607", "0.47508657", "0.47393492", "0.47168118", "0.4714805", "0.470983", "0.4707192", "0.4693256", "0.46805012", "0.46709067", "0.46585292", "0.46556705", "0.46396118", "0.46381035", "0.4635105", "0.46348572", "0.46079496", "0.460337", "0.4599486", "0.45906937", "0.45900458", "0.45846906", "0.45525718", "0.45498374", "0.45405045", "0.45387155", "0.4534576", "0.45316008", "0.45295012", "0.45249632", "0.45132256", "0.45042816", "0.45033777", "0.45032224", "0.4500544", "0.4500008", "0.44973266", "0.44909346", "0.44806713", "0.44738194", "0.44716558", "0.4470803", "0.4470522", "0.44698298", "0.44526005", "0.44521385", "0.44508082", "0.4412429", "0.4411352", "0.44111803", "0.4385628", "0.43830183", "0.438112", "0.4380038", "0.43759614", "0.43753955", "0.4372494", "0.43673888", "0.4366029", "0.43626451", "0.43553865" ]
0.82134825
0
When having multiple URL params of the same name,
func StringSliceToMapKeys(s []string) map[string]bool { ret := map[string]bool{} for _, v := range s { ret[v] = true } return ret }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *InboundRequest) QueryParamMultiple(key string) ([]string, bool) {\n value, ok := r.URL.Query()[key]\n\n return value, ok\n}", "func AppendParams(u *url.URL, nameValues ...string) *url.URL {\n\tlength := len(nameValues)\n\tif length%2 != 0 {\n\t\tpanic(\"nameValues must have even length.\")\n\t}\n\tresult := *u\n\tvalues := result.Query()\n\tfor i := 0; i < length; i += 2 {\n\t\tvalues.Add(nameValues[i], nameValues[i+1])\n\t}\n\tresult.RawQuery = values.Encode()\n\treturn &result\n}", "func URL(r *http.Request, data interface{}) error {\n\tq := r.URL.Query()\n\tv := reflect.ValueOf(data)\n\tt := v.Elem().Type()\n\tfor i := 0; i < v.Elem().NumField(); i++ {\n\t\tft := t.Field(i)\n\t\tfv := v.Elem().Field(i)\n\t\tif tv, exist := ft.Tag.Lookup(paramTag); exist {\n\t\t\tval := fmt.Sprintf(\"%v\", fv)\n\t\t\tif !(len(val) == 0 && strings.Contains(tv, omitEmpty)) {\n\t\t\t\tq.Add(strings.SplitN(tv, \",\", 2)[0], val)\n\t\t\t}\n\t\t}\n\t}\n\tr.URL.RawQuery = q.Encode()\n\treturn nil\n}", "func getURLParameters(u *url.URL, key string) []string {\n\tv, err := url.ParseQuery(u.RawQuery)\n\n\tif err != nil {\n\t\treturn []string{}\n\t}\n\n\treturn v[key]\n}", "func addQueryParams(values *url.Values, parameters map[string]string) {\n\tfor key, value := range parameters {\n\t\tvalues.Set(key, value)\n\t}\n}", "func parseParams(params map[string][]string) url.Values {\n\tv := url.Values{}\n\tfor key, values := range params {\n\t\tfor _, value := range values {\n\t\t\tv.Add(key, value)\n\t\t}\n\t}\n\treturn v\n}", "func WithParams(u *url.URL, nameValues ...string) *url.URL {\n\tlength := len(nameValues)\n\tif length%2 != 0 {\n\t\tpanic(\"nameValues must have even length.\")\n\t}\n\tresult := *u\n\tvalues := result.Query()\n\tfor i := 0; i < length; i += 2 {\n\t\tvalues.Set(nameValues[i], nameValues[i+1])\n\t}\n\tresult.RawQuery = values.Encode()\n\treturn &result\n}", "func QueryStringParamList(r *http.Request, param string) []string {\n\tvar results []string\n\tvalues := r.URL.Query()\n\n\tif _, found := values[param]; found {\n\t\tfor _, value := range values[param] {\n\t\t\tvalue = strings.TrimSpace(value)\n\t\t\tif value != \"\" {\n\t\t\t\tresults = append(results, value)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results\n}", "func getAllURLParameters(u *url.URL) map[string][]string {\n\tv, err := url.ParseQuery(u.RawQuery)\n\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn v\n}", "func (ctx *Context) QueryParams(key string) []string {\r\n\tif ctx.queryParams == nil {\r\n\t\tctx.queryParams = ctx.R.URL.Query()\r\n\t}\r\n\treturn ctx.queryParams[key]\r\n}", "func getSingleParam(r *Request) interface{} {\n\tvar params = r.groupedParams.PathParams\n\tif len(params) != 1 {\n\t\tparams = r.groupedParams.QueryParams\n\t}\n\n\tif len(params) == 1 {\n\t\tfor _, val := range params {\n\t\t\treturn val\n\t\t}\n\t}\n\treturn nil\n}", "func (r InboundRequest) QueryParams() map[string][]string {\n return r.URL.Query()\n}", "func collectParameters(r *http.Request, oauthParams map[string]string) map[string]string {\n\tparams := map[string]string{}\n\tfor key, value := range r.URL.Query() {\n\t\tparams[key] = value[0]\n\t}\n\tfor key, value := range oauthParams {\n\t\tparams[key] = value\n\t}\n\treturn params\n}", "func setQueryParams(req *http.Request, params map[string]interface{}) {\n\tquery := req.URL.Query()\n\tfor key, value := range params {\n\t\tquery.Add(key, fmt.Sprintf(\"%v\", value))\n\t}\n\treq.URL.RawQuery = query.Encode()\n}", "func addSWANParams(r *http.Request, q *url.Values, p []*swan.Pair) {\n\tif p != nil {\n\t\tfor _, i := range p {\n\t\t\tq.Set(i.Key, i.Value)\n\t\t}\n\t}\n}", "func AppendParams(u *url.URL, nameValues ...string) *url.URL {\n\treturn appendParams(u, nameValues)\n}", "func validQueryStringParams(metric string, params map[string][]string) map[string][]string {\n\tvalidParams := make(map[string][]string)\n\tfor key, value := range params {\n\t\tif util.SliceContains(statsQueryStringParams[metric], key) {\n\t\t\tvalidParams[key] = value\n\t\t}\n\t}\n\treturn validParams\n}", "func (r *request) setParams(params map[string]string) {\n\tfor k, v := range params {\n\t\tr.Parameters = append(r.Parameters, k+\"=\"+v)\n\t}\n}", "func getParams(req *http.Request, key string) (string, bool) {\n\tif req.Method != http.MethodGet {\n\t\treturn \"\", false\n\t}\n\n\tvalues := req.URL.Query()\n\tvalue := values.Get(key)\n\n\tif value == \"\" {\n\t\treturn \"\", false\n\t}\n\n\treturn value, true\n}", "func (ctx *Context) QueryParamAll() url.Values {\r\n\tif ctx.queryParams == nil {\r\n\t\tctx.queryParams = ctx.R.URL.Query()\r\n\t}\r\n\treturn ctx.queryParams\r\n}", "func addParamsList(params map[string]string, label string, ids []string) {\n\tfor i, id := range ids {\n\t\tparams[label+\".\"+strconv.Itoa(i+1)] = id\n\t}\n}", "func generateMultiInfoURL(args []string) string {\n\tna := make([]string, len(args))\n\tfor i, s := range args {\n\t\tna[i] = url.QueryEscape(s)\n\t}\n\treturn fmt.Sprintf(multiInfoURL, strings.Join(na, multiInfoArg))\n}", "func (r *Request) Params(names ...string) map[string]*validation.Value {\n\tif len(names) == 0 {\n\t\treturn r.Input\n\t}\n\tparams := map[string]*validation.Value{}\n\tfor _, n := range names {\n\t\tp, ok := r.Input[n]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tparams[n] = p\n\t}\n\treturn params\n}", "func RequestParam(URL *url.URL, key string, defaultValue interface{}) interface{} {\n\tswitch defaultValue.(type) {\n\tcase []string:\n\t\tkey = key + \"[]\"\n\t}\n\n\tvalue := URL.Query().Get(key)\n\tif value != \"\" {\n\t\tswitch defaultValue.(type) {\n\t\tcase string:\n\t\t\treturn value\n\t\tcase int:\n\t\t\tif intValue, err := strconv.Atoi(value); err != nil {\n\t\t\t\treturn defaultValue\n\t\t\t} else {\n\t\t\t\treturn intValue\n\t\t\t}\n\t\tcase int64:\n\t\t\tif int64Value, err := strconv.ParseInt(value, 10, 64); err != nil {\n\t\t\t\treturn int64Value\n\t\t\t} else {\n\t\t\t\treturn int64Value\n\t\t\t}\n\t\tcase []string:\n\t\t\treturn strings.Split(value, \",\")\n\t\t}\n\t}\n\treturn defaultValue\n}", "func mapValues(params map[string]string) url.Values {\n\tvalues := url.Values{}\n\tfor key, val := range params {\n\t\tvalues.Add(key, val)\n\t}\n\treturn values\n}", "func (icbc *IcbcClientUi) buildUrlQueryParams(params map[string]interface{} , urlQueryParams *map[string]interface{}, urlBodyParams *map[string]interface{}) {\n\tapiParamNames := make(map[string]bool)\n\tapiParamNames[SIGN] = true\n\tapiParamNames[APP_ID] = true\n\tapiParamNames[SIGN_TYPE] = true\n\tapiParamNames[CHARSET] = true\n\tapiParamNames[FORMAT] = true\n\tapiParamNames[ENCRYPT_TYPE] = true\n\tapiParamNames[TIMESTAMP] = true\n\tapiParamNames[MSG_ID] = true\n\tfor k,v := range params {\n\t\tif _,ok := apiParamNames[k];ok {\n\t\t\t(*urlQueryParams)[k] = v\n\t\t} else {\n\t\t\t(*urlBodyParams)[k] = v\n\t\t}\n\t}\n}", "func (*Handler) paginationParams(r *http.Request) (int, int) {\n\tq := r.URL.Query()\n\tpage, err := strconv.Atoi(q.Get(\"page\"))\n\tif err != nil {\n\t\tpage = 1\n\t}\n\tlimit, err := strconv.Atoi(q.Get(\"limit\"))\n\tif err != nil {\n\t\tlimit = 20\n\t}\n\treturn page*limit - limit, limit\n}", "func (b binder) setFromQueryParams() HTTPError {\n\tfor k, values := range b.req.URL.Query() {\n\t\tkey := k\n\t\t// Convention for array query params is key[]=val1&key[]=val2, which will be key: {val1, val2}\n\t\t// when parsed by Go. Remove the trailing []. We do this safely, if anyone is actually depending on\n\t\t// \"[]\" as part of a meaningful JSON key, they probably have a use case outside of apiparams.\n\t\tif strings.HasSuffix(key, \"[]\") {\n\t\t\tkey = strings.TrimSuffix(key, \"[]\")\n\t\t}\n\t\tfor _, v := range values {\n\t\t\tif err := b.setField(key, v, ParamSourceQuery); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func CheckParameters(r *rest.Request, needed_fields []string) (bool, map[string]string) {\n\tvar result map[string]string\n\tresult = make(map[string]string)\n\tfor _, field := range needed_fields {\n\t\tvalues, _ := r.URL.Query()[field]\n\t\tif len(values) < 1 {\n\t\t\treturn false, result\n\t\t}\n\t\tresult[field] = values[0]\n\t}\n\treturn true, result\n}", "func (t *RestURL) GetMany(w http.ResponseWriter, r *http.Request) {\n\tt.Log.Handle(w, r, nil, \"begin\", \"RestURL\", \"GetMany\")\n\n\txxRouteVars := mux.Vars(r)\n\n\txxURLValues := r.URL.Query()\n\tvar urlArg1 string\n\tif false {\n\t} else if _, ok := xxRouteVars[\"arg1\"]; ok {\n\t\txxTmpurlArg1 := xxRouteVars[\"arg1\"]\n\t\turlArg1 = xxTmpurlArg1\n\t} else if _, ok := xxURLValues[\"arg1\"]; ok {\n\t\txxTmpurlArg1 := xxURLValues.Get(\"arg1\")\n\t\turlArg1 = xxTmpurlArg1\n\t}\n\tvar urlArg2 string\n\tif false {\n\t} else if _, ok := xxRouteVars[\"arg2\"]; ok {\n\t\txxTmpurlArg2 := xxRouteVars[\"arg2\"]\n\t\turlArg2 = xxTmpurlArg2\n\t} else if _, ok := xxURLValues[\"arg2\"]; ok {\n\t\txxTmpurlArg2 := xxURLValues.Get(\"arg2\")\n\t\turlArg2 = xxTmpurlArg2\n\t}\n\n\tt.embed.GetMany(urlArg1, urlArg2)\n\n\tw.WriteHeader(200)\n\n\tt.Log.Handle(w, r, nil, \"end\", \"RestURL\", \"GetMany\")\n\n}", "func URLParamInt64Slice(request *http.Request, name string) ([]int64, IResponse) {\n\tvalues := []int64{}\n\n\tvalueStr := chi.URLParam(request, name)\n\tvalueStrParts := strings.Split(valueStr, \",\")\n\n\tfor i, valueStrPart := range valueStrParts {\n\t\tvalue, err := strconv.ParseInt(valueStrPart, 10, 64)\n\t\tif err != nil {\n\t\t\treturn []int64{}, BadRequest(request, \"Invalid url param %s (%d. value: '%s'): %s\", name, i+1, valueStrPart, err)\n\t\t}\n\t\tvalues = append(values, value)\n\t}\n\n\treturn values, nil\n}", "func getQueryParams(v interface{}, vals url.Values) error {\n\t// normalize all query string key/values\n\targs := make(map[string]string)\n\n\tfor k, v := range vals {\n\t\tif len(v) > 0 {\n\t\t\targs[k] = v[0]\n\t\t}\n\t}\n\n\tb, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(b, v)\n}", "func addParams(path string, params interface{}) (string, error) {\n\tv := reflect.ValueOf(params)\n\tif v.Kind() == reflect.Ptr && v.IsNil() {\n\t\treturn path, nil\n\t}\n\n\tpathURL, err := url.Parse(path)\n\tif err != nil {\n\t\treturn path, err\n\t}\n\n\tnewPath := pathURL.Query()\n\tnewParams, err := query.Values(params)\n\tif err != nil {\n\t\treturn path, err\n\t}\n\n\tfor k, v := range newParams {\n\t\tnewPath[k] = v\n\t}\n\n\tpathURL.RawQuery = newParams.Encode()\n\treturn pathURL.String(), nil\n}", "func checkParameter(parms [3]string, r *http.Request) (map[string]string, error){\n\tresult := make(map[string]string)\n\tfmt.Printf(\"==> \")\n for i := 0; i < len(parms); i++ {\n value, ok := r.URL.Query()[parms[i]]\n if !ok || len(value) < 1 {\n\n\t\t\treturn result, errors.New(fmt.Sprintf(\"==> Error %s not filled\", parms[i]))\n }\n fmt.Printf(\"%s=%s \", parms[i], value[0])\n result[parms[i]] = value[0]\n }\n\tfmt.Printf(\"\\n\")\n return result, nil\n\n}", "func ParamsValue(obj reflect.Value, params httprouter.Params) error {\n\tkind := obj.Type()\n\n\tfor i := 0; i < obj.NumField(); i++ {\n\t\tfield := obj.Field(i)\n\t\tif !field.CanSet() {\n\t\t\tcontinue\n\t\t}\n\n\t\ttField := kind.Field(i)\n\n\t\tkind := tField.Type.Kind()\n\t\t// switch is benchmarked as about 5x faster than using a slice\n\t\tswitch kind {\n\t\tcase reflect.Complex64, reflect.Complex128, reflect.Array, reflect.Chan,\n\t\t\treflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice,\n\t\t\treflect.Struct, reflect.UnsafePointer:\n\t\t\treturn fmt.Errorf(\"%q is not a supported type for a url parameter\", kind)\n\t\t}\n\n\t\tqueryKey := tField.Name\n\t\tif tag, ok := tField.Tag.Lookup(paramTagKey); ok {\n\t\t\tqueryKey = tag\n\t\t}\n\n\t\tif queryKey == \"-\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tval := params.ByName(queryKey)\n\t\tif len(val) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\terr := setSimpleField(field, tField.Name, kind, val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\treturn nil\n}", "func Params(r *http.Request) map[string]string {\n\tpreviousPathOffset, ok :=\n\t\tr.Context().Value(previousPathOffsetContextKey).(int)\n\tif !ok {\n\t\tpreviousPathOffset = 0\n\t}\n\troutePath, ok := r.Context().Value(pathContextKey).(string)\n\tif !ok {\n\t\troutePath = \"/\"\n\t}\n\trequestPathComponents :=\n\t\tstrings.Split(r.URL.Path[1:], \"/\")[previousPathOffset:]\n\troutePathComponents := strings.Split(routePath[1:], \"/\")\n\n\tresult := make(map[string]string)\n\tfor i := 0; i < len(routePathComponents); i++ {\n\t\tif routePathComponents[i][0] == ':' {\n\t\t\tresult[routePathComponents[i][1:]] = requestPathComponents[i]\n\t\t}\n\t}\n\n\treturn result\n}", "func (c *Ctx) Params(key string, defaultValue ...string) string {\n\tif key == \"*\" || key == \"+\" {\n\t\tkey += \"1\"\n\t}\n\tfor i := range c.route.Params {\n\t\tif len(key) != len(c.route.Params[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tif c.route.Params[i] == key {\n\t\t\t// in case values are not here\n\t\t\tif len(c.values) <= i || len(c.values[i]) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn c.values[i]\n\t\t}\n\t}\n\treturn defaultString(\"\", defaultValue)\n}", "func parseParams(header http.Header, key string) (params map[string]string) {\n\tparams = make(map[string]string)\n\tv := header.Get(key)\n\tp := strings.Split(v, \";\")\n\tre := regexp.MustCompile(\"([A-Za-z0-9-]*)[=\\\"]*([^\\\"]*)?\")\n\n\tfor _, s := range p {\n\t\ts = strings.TrimSpace(s)\n\t\tmatch := re.FindStringSubmatch(s)\n\t\tpk := strings.ToLower(match[1])\n\n\t\tpv := match[2]\n\t\tif params[pk] == \"\" {\n\t\t\tparams[pk] = pv\n\t\t} else {\n\t\t\tparams[pk] = params[pk] + \",\" + pv\n\t\t}\n\t}\n\n\treturn\n}", "func normalizeRequestParams(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvar urlParams, jsonBodyParams models.Relationship\n\n\t\t// parse the mux.vars into params\n\t\tif len(mux.Vars(r)) > 0 {\n\t\t\turlParams.UUIDSource = mux.Vars(r)[\"UUIDSource\"]\n\t\t\tif mux.Vars(r)[\"UUIDTarget\"] != \"\" {\n\t\t\t\turlParams.UUIDTarget = mux.Vars(r)[\"UUIDTarget\"]\n\t\t\t}\n\t\t\tif mux.Vars(r)[\"relationship\"] != \"\" {\n\t\t\t\turlParams.Relationship = mux.Vars(r)[\"relationship\"]\n\t\t\t}\n\n\t\t\ttlLog.Debug(\"parsed request URI into request context\")\n\t\t}\n\n\t\t// Decode the JSON body\n\t\terr := json.DecodeJSONBody(w, r, &jsonBodyParams)\n\t\tif err != nil && err.Error() != \"Request body is empty\" {\n\t\t\ttlLog.WithFields(logrus.Fields{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t}).Error(\"unable to parse request JSON body into params\")\n\t\t}\n\n\t\t// Merge the parameters specified in the JSON body and the URL.\n\t\t// In the case that a request defines a value for the same parameter in both\n\t\t// the URI /and/ the request body JSON, an error is produced. The client has to\n\t\t// choose one or the other; having both would require defining the behaviour\n\t\t// and if misunderstood could cause bad behaviour (overwriting/deleting data!)\n\t\tparams, err := urlParams.Merge(&jsonBodyParams)\n\t\tif err != nil {\n\t\t\ttlLog.WithFields(logrus.Fields{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t}).Error(\"unable to parse params, do you have conflicting values?\")\n\t\t}\n\t\tctx := context.WithValue(r.Context(), \"params\", params)\n\t\ttlLog.WithFields(logrus.Fields{\n\t\t\t\"url\": urlParams,\n\t\t\t\"json\": jsonBodyParams,\n\t\t\t\"rel\": params.Relationship,\n\t\t\t\"del\": params.Delta,\n\t\t\t\"uuids\": params.UUIDSource,\n\t\t\t\"uuidt\": params.UUIDTarget,\n\t\t}).Debug(\"parsed request parameters into request context\")\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}", "func addSwaggerParams(endpoint *stats.Endpoint, params map[string]spec.Parameter, definitions spec.Definitions) {\n\tfor _, param := range params {\n\t\tswitch param.In {\n\t\tcase \"body\":\n\t\t\tif param.Schema != nil {\n\t\t\t\textractBodyParams(param.Schema, definitions, endpoint.Body, endpoint.Body.Root)\n\t\t\t} else {\n\t\t\t\tendpoint.Params.Body.Add(param.Name, endpoint.Body.Root, true)\n\t\t\t}\n\t\tcase \"query\":\n\t\t\tendpoint.Params.Query.Add(param.Name, endpoint.Query.Root, true)\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func GetParams(name string, r *http.Request) []string {\n\tif params := r.Context().Value(ParamsKey); params != nil {\n\t\tparams := params.(Params)\n\t\tif name != \"*\" {\n\t\t\tname = \":\" + name\n\t\t}\n\t\tif param := params[name]; param != nil {\n\t\t\tswitch param := param.(type) {\n\t\t\tcase []string:\n\t\t\t\treturn param\n\t\t\tdefault:\n\t\t\t\treturn []string{param.(string)}\n\t\t\t}\n\t\t}\n\t}\n\treturn []string{}\n}", "func getSMAURLParams(values url.Values) (exchange string, interval string, market string, err error) {\n\tif _exchange, ok := values[\"exchange\"]; ok {\n\t\texchange = _exchange[0]\n\t} else {\n\t\terr = errors.New(\"missing URL param exchange\")\n\t\treturn\n\t}\n\n\tif _interval, ok := values[\"interval\"]; ok {\n\t\tinterval = _interval[0]\n\t} else {\n\t\terr = errors.New(\"missing URL param interval\")\n\t\treturn\n\t}\n\n\tif _market, ok := values[\"market\"]; ok {\n\t\tmarket = _market[0]\n\t} else {\n\t\terr = errors.New(\"missing URL param market\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (t *RestURL) GetAll2(w http.ResponseWriter, r *http.Request) {\n\tt.Log.Handle(w, r, nil, \"begin\", \"RestURL\", \"GetAll2\")\n\n\txxRouteVars := mux.Vars(r)\n\n\txxURLValues := r.URL.Query()\n\n\tvar urlValues map[string]string\n\t{\n\t\turlValues = map[string]string{}\n\t\txxTempValue := urlValues\n\n\t\tfor k, v := range xxRouteVars {\n\t\t\tif len(v) > 0 {\n\t\t\t\txxTempValue[k] = v\n\t\t\t}\n\t\t}\n\n\t\tfor k, v := range xxURLValues {\n\t\t\tif len(v) > 0 {\n\t\t\t\tif _, ok := xxTempValue[k]; ok {\n\t\t\t\t\tfor _, vv := range v {\n\t\t\t\t\t\tif len(vv) > 0 {\n\t\t\t\t\t\t\txxTempValue[k] = vv\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} else {\n\t\t\t\t\tfor _, vv := range v {\n\t\t\t\t\t\tif len(vv) > 0 {\n\t\t\t\t\t\t\txxTempValue[k] = vv\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}\n\t\t\t}\n\t\t}\n\t}\n\n\tt.embed.GetAll2(urlValues)\n\n\tw.WriteHeader(200)\n\n\tt.Log.Handle(w, r, nil, \"end\", \"RestURL\", \"GetAll2\")\n\n}", "func buildQueryParamUrl(reqURL *url.URL, queryStructs []interface{}, queryParams map[string]string) error {\n\turlValues, err := url.ParseQuery(reqURL.RawQuery)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// encodes query structs into a url.Values map and merges maps\n\tfor _, queryStruct := range queryStructs {\n\t\tqueryValues, err := goquery.Values(queryStruct)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor key, values := range queryValues {\n\t\t\tfor _, value := range values {\n\t\t\t\turlValues.Add(key, value)\n\t\t\t}\n\t\t}\n\t}\n\tfor k, v := range queryParams {\n\t\turlValues.Add(k, v)\n\t}\n\t// url.Values format to a sorted \"url encoded\" string, e.g. \"key=val&foo=bar\"\n\treqURL.RawQuery = urlValues.Encode()\n\treturn nil\n}", "func (sc SearchClient) QueryParams() url.Values {\n\tparams := url.Values{}\n\n\tif sc.FilterID > 0 {\n\t\tparams.Add(\"filter_id\", strconv.Itoa(sc.FilterID))\n\t}\n\n\tif sc.PerPage > 1 && sc.PerPage != 25 {\n\t\tparams.Add(\"per_page\", strconv.Itoa(sc.PerPage))\n\t}\n\n\tif len(sc.Key) > 0 {\n\t\tparams.Add(\"key\", sc.Key)\n\t}\n\n\tif len(sc.SortDirection) > 0 {\n\t\tparams.Add(\"sd\", sc.SortDirection)\n\t}\n\n\tif len(sc.SortField) > 0 {\n\t\tparams.Add(\"sf\", sc.SortField)\n\t}\n\n\treturn params\n}", "func addParamInURL(redirectTo *url.URL, param, value string) {\n\tq := redirectTo.Query()\n\tq.Add(param, value)\n\tredirectTo.RawQuery = q.Encode()\n}", "func (r *Request) QueryParams(params map[string]string) *Request {\n\tfor k, v := range params {\n\t\tr.query[k] = append(r.query[k], v)\n\t}\n\treturn r\n}", "func (r *InboundRequest) QueryParam(key string) (string, bool) {\n values, ok := r.URL.Query()[key]\n\n if !ok || len(values) == 0 {\n return \"\", false\n }\n\n return values[0], true\n}", "func (r *Request) MatchParams(params map[string]string) *Request {\n\tquery := r.URLStruct.Query()\n\tfor key, value := range params {\n\t\tquery.Set(key, value)\n\t}\n\tr.URLStruct.RawQuery = query.Encode()\n\treturn r\n}", "func ParamsMultiValueGet(params map[string][]string, key string) ([]string, error) {\n values := params[key]\n \n if values == nil || len(values) == 0 {\n return nil, errors.New(\"key not exist\")\n }\n\n return values, nil\n}", "func getParams(regEx, url string) (paramsMap map[string]string) {\n\n\tvar compRegEx = regexp.MustCompile(regEx)\n\tmatch := compRegEx.FindStringSubmatch(url)\n\n\tparamsMap = make(map[string]string)\n\tfor i, name := range compRegEx.SubexpNames() {\n\t\tif i > 0 && i <= len(match) {\n\t\t\tparamsMap[name] = match[i]\n\t\t}\n\t}\n\treturn\n}", "func (c *Client) multiURL(end endpoint, IDs []int, opts ...FuncOption) (string, error) {\n\tfor _, ID := range IDs {\n\t\tif ID < 0 {\n\t\t\treturn \"\", ErrNegativeID\n\t\t}\n\t}\n\n\topt, err := newOpt(opts...)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\turl := c.rootURL + string(end) + intsToCommaString(IDs)\n\turl = encodeURL(&opt.Values, url)\n\n\treturn url, nil\n}", "func (c MethodParams) ValidateParams(params url.Values) error {\n\tfor _, p := range c {\n\t\tif err := p.ValidateValue(params.Get(p.Name)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (this *gurl) urlWithParam() (err error) {\n\tif this.param == nil {\n\t\treturn\n\t}\n\n\tvar u *url.URL\n\tif u, err = url.Parse(this.url); err != nil {\n\t\treturn\n\t}\n\n\tq := u.Query()\n\tfor k, v := range this.param {\n\t\tq.Set(k, v)\n\t}\n\n\tu.RawQuery = q.Encode()\n\tthis.url = u.String()\n\n\treturn\n}", "func TestMultipleArgs(t *testing.T) {\n\tflagSet := pflag.NewFlagSet(\"\", pflag.PanicOnError)\n\tregisterParamsFlags(flagSet)\n\tassert.NoError(t, flagSet.Parse([]string{\"-p\", \"key1=1\", \"-p\", \"key2=2\"}))\n\tvalues, errors := getParamsFromFlags(flagSet)\n\tassert.Len(t, values, 2)\n\tassert.Len(t, errors, 0)\n}", "func (f Freckle) api(path string, ps Parameters) string {\n\tu := fmt.Sprintf(\"%s%s\", f.base, path)\n\tif ps != nil && len(ps) > 0 {\n\t\tvar v url.Values = make(url.Values)\n\t\tfor key, value := range ps {\n\t\t\tv.Set(key, value)\n\t\t}\n\t\tu = fmt.Sprintf(\"%s?%s\", u, v.Encode())\n\t}\n\treturn u\n}", "func (u *URL) QueryS(name string) []string {\n\tif u.query == nil {\n\t\tu.query = u.URL.Query()\n\t}\n\n\treturn u.query[name]\n}", "func makeQueryStringFromParam(params map[string][]string) string {\n\tif params == nil {\n\t\treturn \"\"\n\t}\n\tresult := \"\"\n\tfor key, array := range params {\n\t\tfor _, value := range array {\n\t\t\tkeyVal := fmt.Sprintf(\"%s-%s\", key, value)\n\t\t\tif result == \"\" {\n\t\t\t\tresult = \"?\" + keyVal\n\t\t\t} else {\n\t\t\t\tresult = result + \"&\" + keyVal\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func (req *request) Params() *EntrySet {\n return req.params\n}", "func queryPostsWithParameterHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t_, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0)\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// Default params\n\t\tparams := types.DefaultQueryPostsParams(page, limit)\n\n\t\tcliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\tif v := r.URL.Query().Get(RestSortBy); len(v) != 0 {\n\t\t\tparams.SortBy = v\n\t\t}\n\n\t\tif v := r.URL.Query().Get(RestSortOrder); len(v) != 0 {\n\t\t\tparams.SortOrder = v\n\t\t}\n\n\t\tif v := r.URL.Query().Get(RestParentID); len(v) != 0 {\n\t\t\tparentID := types.PostID(v)\n\t\t\tif !parentID.Valid() {\n\t\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf(\"invalid postID: %s\", parentID))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tparams.ParentID = &parentID\n\t\t}\n\n\t\tif v := r.URL.Query().Get(RestCreationTime); len(v) != 0 {\n\t\t\tparsedTime, err := time.Parse(time.RFC3339, v)\n\t\t\tif err != nil {\n\t\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tparams.CreationTime = &parsedTime\n\t\t}\n\n\t\tif v := r.URL.Query().Get(RestAllowsComments); len(v) != 0 {\n\t\t\tparsedAllowsComments, err := strconv.ParseBool(v)\n\t\t\tif err != nil {\n\t\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tparams.AllowsComments = &parsedAllowsComments\n\t\t}\n\n\t\tif v := r.URL.Query().Get(RestSubspace); len(v) != 0 {\n\t\t\tparams.Subspace = v\n\t\t}\n\n\t\tif v := r.URL.Query().Get(RestCreator); len(v) != 0 {\n\t\t\tcreatorAddr, err := sdk.AccAddressFromBech32(v)\n\t\t\tif err != nil {\n\t\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tparams.Creator = creatorAddr\n\t\t}\n\n\t\tif v := r.URL.Query().Get(RestHashtags); len(v) != 0 {\n\t\t\tparams.Hashtags = strings.Split(v, \",\")\n\t\t}\n\n\t\tbz, err := cliCtx.Codec.MarshalJSON(params)\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\troute := fmt.Sprintf(\"custom/%s/%s\", types.QuerierRoute, types.QueryPosts)\n\t\tres, height, err := cliCtx.QueryWithData(route, bz)\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tcliCtx = cliCtx.WithHeight(height)\n\t\trest.PostProcessResponse(w, cliCtx, res)\n\t}\n}", "func parseParams(pairs []string) Params {\n\tm := make(Params)\n\n\tfor _, p := range pairs {\n\t\tparts := strings.Split(p, \"=\")\n\t\tif len(parts) > 1 {\n\t\t\tm[parts[0]] = parts[1]\n\t\t} else {\n\t\t\tm[parts[0]] = true\n\t\t}\n\t}\n\n\treturn m\n}", "func validateParams(params map[string][]string) error {\n\tfor param, values := range params {\n\t\tswitch param {\n\t\tcase timeRangeQS:\n\t\t\tvalue := values[len(values)-1]\n\t\t\tif !validTimeRange(value) {\n\t\t\t\treturn errors.New(\"invalid time_range query string param\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func HasParam(values url.Values, param string) bool {\n\t_, ok := values[param]\n\treturn ok\n}", "func (c Consul) makeParams(opts KeyOptions) url.Values {\n\tv := url.Values{}\n\t// TODO(ashcrow): This is a hack to avoid colliding with int:0. Fix it.\n\tif opts.CASet != \"\" {\n\t\tv.Set(\"cas\", opts.CASet)\n\t}\n\treturn v\n}", "func (ø *MountedRouter) URL(rt *route, params ...string) (string, error) {\n\tif len(params)%2 != 0 {\n\t\tpanic(\"number of params must be even (pairs of key, value)\")\n\t}\n\tvars := map[string]string{}\n\tfor i := 0; i < len(params)/2; i += 2 {\n\t\tvars[params[i]] = params[i+1]\n\t}\n\n\treturn ø.URLMap(rt, vars)\n}", "func url_parser(url_string string) url.Values{\n\tparams, err := url.ParseQuery(url_string)\n\tif err != nil{\n\t\tfmt.Println(err)\n\t}\n\treturn params\n}", "func paramsForOtp(params *OtpParams) *url.Values {\n\turlParams := &url.Values{}\n\n\tif params == nil {\n\t\treturn urlParams\n\t}\n\n\tif params.Reference != \"\" {\n\t\turlParams.Set(\"reference\", params.Reference)\n\t}\n\tif params.Originator != \"\" {\n\t\turlParams.Set(\"originator\", params.Originator)\n\t}\n\tif params.Type != \"\" {\n\t\turlParams.Set(\"type\", params.Type)\n\t}\n\tif params.Template != \"\" {\n\t\turlParams.Set(\"template\", params.Template)\n\t}\n\n\tif params.DataCoding != \"\" {\n\t\turlParams.Set(\"datacoding\", params.DataCoding)\n\t}\n\n\t// Specific params for voice messages\n\tif params.Language != \"\" {\n\t\turlParams.Set(\"language\", params.Language)\n\t}\n\tif params.Voice != \"\" {\n\t\turlParams.Set(\"voice\", params.Voice)\n\t}\n\n\treturn urlParams\n}", "func (h *httpRouterExtended) paramsToMap(params jsRouter.Params, w http.ResponseWriter) map[string][]string {\n\trv := make(map[string][]string)\n\n\t// check if its a catch-all route\n\troute := params.MatchedRoutePath()\n\tcatchAllRoute := false\n\tif strings.Contains(route, \"*\") {\n\t\tcatchAllRoute = true\n\t}\n\n\tfor _, p := range params {\n\t\tif p.Key == jsRouter.MatchedRoutePathParam {\n\t\t\tcontinue\n\t\t}\n\n\t\tif p.Key == \"filepath\" {\n\t\t\trv[p.Key] = []string{p.Value}\n\t\t\tcontinue\n\t\t}\n\n\t\tif catchAllRoute {\n\t\t\turlParam := strings.Split(strings.Trim(p.Value, \"/\"), \"/\")\n\t\t\tfor i := 0; i < len(urlParam); i++ {\n\t\t\t\tif h.router.options.CatchAllKeyValuePair {\n\n\t\t\t\t\tif i+1 >= len(urlParam) {\n\t\t\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\t\t\t_, _ = w.Write([]byte(ErrKeyValuePair.Error()))\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\n\t\t\t\t\trv[urlParam[i]] = []string{urlParam[i+1]}\n\t\t\t\t\ti++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trv[strconv.Itoa(i)] = []string{urlParam[i]}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\trv[p.Key] = []string{p.Value}\n\t}\n\treturn rv\n}", "func PathParams(req *http.Request) (params map[string]string) {\n\tparams = req.Context().Value(paramsKey).(map[string]string)\n\n\treturn\n}", "func WithParams(u *url.URL, nameValues ...string) *url.URL {\n\treturn withParams(u, nameValues)\n}", "func (ctx *SimpleContext) QueryParams(typ interface{}) error {\n\tq := ctx.request.URL.Query()\n\terr := query.Unmarshal(q, typ)\n\tif nil != err {\n\t\treturn err\n\t}\n\treturn ctx.validate(typ)\n}", "func namedPqParams(numFields int, numEntities int) string {\n\tparamGroups := make([]string, 0, numEntities)\n\tparams := make([]string, 0, numFields)\n\tnumTotalParams := numEntities * numFields\n\n\tfor i := 0; i < numTotalParams; i++ {\n\t\tparams = append(params, fmt.Sprintf(\"$%v\", i+1))\n\n\t\t//when we reach the number of fields, group the params\n\t\tif (i+1)%numFields == 0 {\n\t\t\tparamGroup := fmt.Sprintf(\"(%s)\", strings.Join(params, \",\"))\n\t\t\tparamGroups = append(paramGroups, paramGroup)\n\t\t\tparams = make([]string, 0, numFields)\n\t\t}\n\t}\n\treturn strings.Join(paramGroups, \",\")\n}", "func mappingUrlKeystoValues(postback *Pbo) {\n\tmatchingIndexes := argumentPattern.FindStringIndex(postback.Url)\n\tfor matchingIndexes != nil {\n\t\tpatternMatch := argumentPattern.FindString(postback.Url)\n\t\tmatchString := patternMatch[1:(len(patternMatch) - 1)]\n\t\treplaceString, keyHasValue := postback.Data[matchString]\n\t\tif !keyHasValue {\n\t\t\treplaceString = MISMATCH_KEY_VALUE_URL\n\t\t\tpostback.Data[matchString] = MISMATCH_KEY_VALUE_URL\n\t\t}\n\t\tpostback.Url = postback.Url[:matchingIndexes[0]] + replaceString + postback.Url[matchingIndexes[1]:]\n\t\tmatchingIndexes = argumentPattern.FindStringIndex(postback.Url)\n\t}\n}", "func requestParamsFromRpc(rpc *specSpec.Rpc) []Qparams {\n\t// path params regexFindAll \"{[a-zA-Z]*}\" $method.deeplink.href 10\n\tregex := regexp.MustCompile(`{([^{]+)}`)\n\tmatches := regex.FindAllStringSubmatch(rpc.Deeplink.Href, 50)\n\tparams := []Qparams{}\n\ti := 1\n\tfor _, match := range matches {\n\t\tparams = append(params, Qparams{\n\t\t\tDescription: \"deeplink params for path segment {\" + match[1] + \"} of \" + rpc.Deeplink.Href,\n\t\t\tType: \"string\",\n\t\t\tName: match[1],\n\t\t\tFieldId: i,\n\t\t})\n\t\ti++\n\t}\n\n\t// request type\n\tif rpc.Data.Request != \"\" {\n\t\tparams = append(params, Qparams{\n\t\t\tDescription: \"request type \" + rpc.Data.Request,\n\t\t\tType: rpc.Data.Request,\n\t\t\tName: \"data\",\n\t\t\tFieldId: i,\n\t\t})\n\t\ti++\n\t}\n\n\t// query\n\tif rpc.Query != nil {\n\t\trpc.Query.Map(func(iKey interface{}, iValue interface{}) {\n\t\t\tp := iValue.(*specSpec.Queryparam)\n\t\t\tparams = append(params, Qparams{\n\t\t\t\tDescription: p.Description,\n\t\t\t\tType: p.Type,\n\t\t\t\tName: iKey.(string),\n\t\t\t\tFieldId: i,\n\t\t\t})\n\t\t\ti++\n\t\t})\n\t}\n\n\treturn params\n}", "func setParamInURL(redirectTo *url.URL, param, value string) {\n\tq := redirectTo.Query()\n\tq.Set(param, value)\n\tredirectTo.RawQuery = q.Encode()\n}", "func AddIndependentPropertyGeneratorsForUrlSigningParamIdentifier(gens map[string]gopter.Gen) {\n\tgens[\"ParamIndicator\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"ParamName\"] = gen.PtrOf(gen.AlphaString())\n}", "func TestParam(t *testing.T) {\n\tparamCode := \"123456\"\n\tparamFields := \"f1;f2;f3\"\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Form.Get(\"code\") != paramCode {\n\t\t\tt.Errorf(\"Expected 'code' == %s; got %v\", paramCode, r.Form.Get(\"code\"))\n\t\t}\n\n\t\tif r.Form.Get(\"fields\") != paramFields {\n\t\t\tt.Errorf(\"Expected 'fields' == %s; got %v\", paramFields, r.Form.Get(\"fields\"))\n\t\t}\n\t}))\n\n\tdefer ts.Close()\n\n\tNew().Get(ts.URL).\n\t\tParam(\"code\", paramCode).\n\t\tParam(\"fields\", paramFields)\n}", "func (p *SASQueryParameters) addToValues(v url.Values) url.Values {\n\tif p.version != \"\" {\n\t\tv.Add(\"sv\", p.version)\n\t}\n\tif p.services != \"\" {\n\t\tv.Add(\"ss\", p.services)\n\t}\n\tif p.resourceTypes != \"\" {\n\t\tv.Add(\"srt\", p.resourceTypes)\n\t}\n\tif p.protocol != \"\" {\n\t\tv.Add(\"spr\", string(p.protocol))\n\t}\n\tif !p.startTime.IsZero() {\n\t\tv.Add(\"st\", formatSASTime(&(p.startTime), p.stTimeFormat))\n\t}\n\tif !p.expiryTime.IsZero() {\n\t\tv.Add(\"se\", formatSASTime(&(p.expiryTime), p.seTimeFormat))\n\t}\n\tif len(p.ipRange.Start) > 0 {\n\t\tv.Add(\"sip\", p.ipRange.String())\n\t}\n\tif p.identifier != \"\" {\n\t\tv.Add(\"si\", p.identifier)\n\t}\n\tif p.resource != \"\" {\n\t\tv.Add(\"sr\", p.resource)\n\t}\n\tif p.permissions != \"\" {\n\t\tv.Add(\"sp\", p.permissions)\n\t}\n\tif p.signature != \"\" {\n\t\tv.Add(\"sig\", p.signature)\n\t}\n\tif p.tableName != \"\" {\n\t\tv.Add(\"tn\", p.tableName)\n\t}\n\tif p.startPk != \"\" {\n\t\tv.Add(\"spk\", p.startPk)\n\t}\n\tif p.endPk != \"\" {\n\t\tv.Add(\"epk\", p.endPk)\n\t}\n\tif p.startRk != \"\" {\n\t\tv.Add(\"srk\", p.startRk)\n\t}\n\tif p.endRk != \"\" {\n\t\tv.Add(\"erk\", p.endRk)\n\t}\n\treturn v\n}", "func printAddressParams(request *http.Request) {\n\tsource := request.FormValue(\"Source\")\n\tlog.Printf(\"Source: %s\", source)\n\n\tfor i := 1; i < maxDestinations; i++ {\n\t\tdest := request.FormValue(fmt.Sprintf(\"Destinations.member.%d\", i))\n\t\tif dest == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tlog.Printf(\"Destination [%d]: %s\", i, dest)\n\t}\n}", "func extractPathParameters(url string, pageUrl string, eventName string) []string {\n\t// validate\n\tif !strings.HasPrefix(url, pageUrl) {\n\t\tpanic(fmt.Sprintf(\"%v should has prefix %v\", url, pageUrl))\n\t}\n\n\t// parepare parameters\n\tparamsString := url[len(pageUrl):]\n\tif eventName != \"\" {\n\t\tindex := strings.Index(paramsString, \"/\")\n\t\tif index > 0 {\n\t\t\tparamsString = paramsString[index:]\n\t\t}\n\t}\n\tvar pathParams []string\n\tif len(paramsString) > 0 {\n\t\tif strings.HasPrefix(paramsString, \"/\") {\n\t\t\tparamsString = paramsString[1:]\n\t\t}\n\t\tpathParams = strings.Split(paramsString, \"/\")\n\t}\n\tdebug.Log(\"- - [injection] URL:%v, parameters:%v\", url, pathParams)\n\treturn pathParams\n}", "func (r *route) parsePatternParams(path string) string {\n pathParts := strings.Split(path, \"/\")\n patternParts := strings.Split(r.pattern, \"/\")\n params := \"\"\n for i, s := range patternParts {\n if strings.HasPrefix(s, \":\") {\n if params != \"\" {\n params += \"&\"\n }\n params += s[1:] + \"=\" + pathParts[i]\n }\n }\n return params\n}", "func String(r *http.Request, key string) string {\n\tv := chi.URLParam(r, key)\n\tif v == \"\" {\n\t\tv = r.URL.Query().Get(key)\n\t}\n\n\treturn v\n}", "func ValidateAndRegisterParams(mapName string, params []provider.QueryParameter) error {\n\tif len(params) == 0 {\n\t\treturn nil\n\t}\n\n\tusedNames := make(map[string]struct{})\n\tusedTokens := make(map[string]struct{})\n\n\tfor _, param := range params {\n\t\tif _, ok := provider.ParamTypeDecoders[param.Type]; !ok {\n\t\t\treturn ErrParamUnknownType{\n\t\t\t\tMapName: string(mapName),\n\t\t\t\tParameter: param,\n\t\t\t}\n\t\t}\n\n\t\tif len(param.DefaultSQL) > 0 && len(param.DefaultValue) > 0 {\n\t\t\treturn ErrParamTwoDefaults{\n\t\t\t\tMapName: string(mapName),\n\t\t\t\tParameter: param,\n\t\t\t}\n\t\t}\n\n\t\tif len(param.DefaultValue) > 0 {\n\t\t\tdecoderFn := provider.ParamTypeDecoders[param.Type]\n\t\t\tif _, err := decoderFn(param.DefaultValue); err != nil {\n\t\t\t\treturn ErrParamInvalidDefault{\n\t\t\t\t\tMapName: string(mapName),\n\t\t\t\t\tParameter: param,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif _, ok := ReservedTokens[param.Token]; ok {\n\t\t\treturn ErrParamTokenReserved{\n\t\t\t\tMapName: string(mapName),\n\t\t\t\tParameter: param,\n\t\t\t}\n\t\t}\n\n\t\tif !provider.ParameterTokenRegexp.MatchString(param.Token) {\n\t\t\treturn ErrParamBadTokenName{\n\t\t\t\tMapName: string(mapName),\n\t\t\t\tParameter: param,\n\t\t\t}\n\t\t}\n\n\t\tif _, ok := usedNames[param.Name]; ok {\n\t\t\treturn ErrParamDuplicateName{\n\t\t\t\tMapName: string(mapName),\n\t\t\t\tParameter: param,\n\t\t\t}\n\t\t}\n\n\t\tif _, ok := usedTokens[param.Token]; ok {\n\t\t\treturn ErrParamDuplicateToken{\n\t\t\t\tMapName: string(mapName),\n\t\t\t\tParameter: param,\n\t\t\t}\n\t\t}\n\n\t\tusedNames[param.Name] = struct{}{}\n\t\tusedTokens[param.Token] = struct{}{}\n\t}\n\n\t// Mark all used tokens as reserved\n\tfor token := range usedTokens {\n\t\tReservedTokens[token] = struct{}{}\n\t}\n\n\treturn nil\n}", "func addQueryParams(s string, queryParams interface{}) (string, error) {\n\tv := reflect.ValueOf(queryParams)\n\tif v.Kind() == reflect.Ptr && v.IsNil() {\n\t\treturn s, nil\n\t}\n\n\tu, err := url.Parse(s)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\n\tqs, err := query.Values(queryParams)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\n\tu.RawQuery = qs.Encode()\n\treturn u.String(), nil\n}", "func VerifyParameters(key string, qs map[string]interface{}) bool {\n\tparams := url.Values{}\n\n\tfor k, v := range qs {\n\t\ts, ok := v.(string)\n\t\tif ok {\n\t\t\tparams.Set(k, s)\n\t\t\tcontinue\n\t\t}\n\n\t\tl, ok := v.([]string)\n\t\tif ok {\n\t\t\tfor i := range l {\n\t\t\t\tparams.Add(k, l[i])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn VerifySign(key, params.Encode())\n}", "func positionalParams(paramList string, paramDefs []langutil.MethodParam) ([]langutil.MethodParam, error) {\n\tvar posParams []langutil.MethodParam\nLOOP:\n\tfor _, paramSpec := range strings.Split(paramList, \",\") {\n\t\tparamSpec = strings.TrimSpace(paramSpec)\n\n\t\t// ':' signifies a named parameter and '&' specifies a block. Both must come after all\n\t\t// positional parameters.\n\t\tif strings.ContainsAny(paramSpec, \":&\") {\n\t\t\tbreak\n\t\t}\n\n\t\tvar paramName string\n\t\tif p := strings.IndexFunc(paramSpec, func(r rune) bool {\n\t\t\treturn !unicode.IsLetter(r) && !unicode.IsNumber(r) && r != '_'\n\t\t}); p >= 0 {\n\t\t\tparamName = paramSpec[:p]\n\t\t} else {\n\t\t\tparamName = paramSpec\n\t\t}\n\n\t\tfor _, def := range paramDefs {\n\t\t\tif def.Name == paramName {\n\t\t\t\t// This is a simple heuristic that assumes any param whose type\n\t\t\t\t// contains \"::\" is a message, and therefore the request_body.\n\t\t\t\tif strings.Contains(def.Type, \"::\") {\n\t\t\t\t\tdef.Name = \"request_body\"\n\t\t\t\t}\n\t\t\t\tposParams = append(posParams, def)\n\t\t\t\tcontinue LOOP\n\t\t\t}\n\t\t}\n\t\treturn nil, fmt.Errorf(\"param used but not defined: %q\", paramName)\n\t}\n\treturn posParams, nil\n}", "func AddIndependentPropertyGeneratorsForUrlRewriteActionParameters(gens map[string]gopter.Gen) {\n\tgens[\"Destination\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"PreserveUnmatchedPath\"] = gen.PtrOf(gen.Bool())\n\tgens[\"SourcePattern\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"TypeName\"] = gen.PtrOf(gen.AlphaString())\n}", "func PathParams(r *http.Request) map[string]string {\n\treturn mux.Vars(r)\n}", "func (req *Request) ParamsBySource() (map[string]url.Values, error) {\n\tparams := map[string]url.Values{\n\t\t\"url\": req.MuxVariables(),\n\t\t\"query\": req.Request.URL.Query(),\n\t\t\"form\": url.Values{},\n\t}\n\n\tform, err := req.JSONBody()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tparams[\"form\"] = form\n\n\treturn params, nil\n}", "func newQueryParametersBag( //nolint:gocyclo\n\tvalues url.Values,\n\tdefaultRedirectTo string,\n\tmaxSources int,\n) (*queryParametersBag, error) {\n\tbag := &queryParametersBag{\n\t\t// Defaults:\n\t\tRedirectTo: defaultRedirectTo,\n\t\tFormat: \"routeros\",\n\t}\n\n\t// Extract `sources_urls` values\n\tif sourceUrls, ok := values[\"sources_urls\"]; ok {\n\t\t// Iterate query values slice\n\t\tfor _, value := range sourceUrls {\n\t\t\t// Explode value with URLs list (separated using `,`) into single URLs\n\t\t\tfor _, sourceURL := range strings.Split(value, \",\") {\n\t\t\t\t// Make URL validation, and if all is ok - append it into query parameters bag\n\t\t\t\tif _, err := url.ParseRequestURI(sourceURL); err == nil && len(sourceURL) <= 256 {\n\t\t\t\t\tbag.SourceUrls = append(bag.SourceUrls, sourceURL)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn nil, errors.New(\"required parameter `sources_urls` was not found\")\n\t}\n\n\t// Validate sources list size\n\tif len(bag.SourceUrls) < 1 {\n\t\treturn nil, errors.New(\"empty sources list\")\n\t}\n\n\t// remove duplicated sources\n\tbag.SourceUrls = bag.uniqueStringsSlice(bag.SourceUrls)\n\n\t// check for sources count\n\tif len(bag.SourceUrls) > maxSources {\n\t\treturn nil, fmt.Errorf(\"too much sources (only %d is allowed)\", maxSources)\n\t}\n\n\t// Extract `format` value\n\tif value, ok := values[\"format\"]; ok {\n\t\tif len(value) > 0 {\n\t\t\tbag.Format = value[0]\n\t\t}\n\t}\n\n\t// Extract `version` value\n\tif value, ok := values[\"version\"]; ok {\n\t\tif len(value) > 0 {\n\t\t\tbag.Version = value[0]\n\t\t}\n\t}\n\n\t// Extract `excluded_hosts` value\n\tif excludedHosts, ok := values[\"excluded_hosts\"]; ok {\n\t\t// Iterate query values slice\n\t\tfor _, value := range excludedHosts {\n\t\t\t// Explode value with host names list (separated using `,`) into single host names\n\t\t\tfor _, excludedHost := range strings.Split(value, \",\") {\n\t\t\t\t// Make basic checking, and if all is ok - append it into query parameters bag\n\t\t\t\tif excludedHost != \"\" {\n\t\t\t\t\tbag.ExcludedHosts = append(bag.ExcludedHosts, excludedHost)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// remove duplicated hosts\n\t\tbag.ExcludedHosts = bag.uniqueStringsSlice(bag.ExcludedHosts)\n\t\t// Validate excluded hosts list size\n\t\tif len(bag.ExcludedHosts) > 32 {\n\t\t\treturn nil, errors.New(\"too many excluded hosts (more then 32)\")\n\t\t}\n\t}\n\n\t// Extract `limit` value\n\tif value, ok := values[\"limit\"]; ok {\n\t\tif len(value) > 0 {\n\t\t\tif value, err := strconv.Atoi(value[0]); err == nil {\n\t\t\t\tif value <= 0 {\n\t\t\t\t\treturn nil, errors.New(\"wrong `limit` value (cannot be less then 1)\")\n\t\t\t\t}\n\t\t\t\tbag.Limit = value\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"wrong `limit` value (cannot be converted into integer)\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// Extract and validate `redirect_to` value\n\tif value, ok := values[\"redirect_to\"]; ok {\n\t\tif len(value) > 0 {\n\t\t\tif net.ParseIP(value[0]) == nil {\n\t\t\t\treturn nil, errors.New(\"wrong `redirect_to` value (invalid IP address)\")\n\t\t\t}\n\t\t\tbag.RedirectTo = value[0]\n\t\t}\n\t}\n\n\treturn bag, nil\n}", "func buildSearchParams(opts ...wowsearch.Opt) string {\n\tif len(opts) == 0 {\n\t\treturn \"\"\n\t}\n\n\tvar params []string\n\tfor _, opt := range opts {\n\t\topt.Apply(&params)\n\t}\n\n\treturn \"?\" + strings.Join(params, \"&\")\n}", "func buildSearchParams(opts ...wowsearch.Opt) string {\n\tif len(opts) == 0 {\n\t\treturn \"\"\n\t}\n\tvar params []string\n\tfor _, opt := range opts {\n\t\topt.Apply(&params)\n\t}\n\treturn \"?\" + strings.Join(params, \"&\")\n}", "func getVKParams(rawValues url.Values) string {\n\tvkPrefix := make(url.Values)\n\n\tfor key, values := range rawValues {\n\t\tif strings.HasPrefix(key, \"vk_\") {\n\t\t\tfor _, value := range values {\n\t\t\t\tvkPrefix.Add(key, value)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn vkPrefix.Encode() // sorted by key.\n}", "func (p *ByName) processParam(loc *location.L, paramParts []string) {\n\tif p.AttrIsSet(SetOnlyOnce) && p.HasBeenSet() {\n\t\tp.ps.AddErr(p.name,\n\t\t\tloc.Error(fmt.Sprintf(\n\t\t\t\t\"This may only be set once but has already been set at %s\",\n\t\t\t\tp.whereIsParamSet[0])))\n\t\treturn\n\t}\n\n\tif p.AttrIsSet(IsTerminalParam) {\n\t\tp.ps.terminalParamSeen = true\n\t}\n\n\tvar err error\n\n\tswitch len(paramParts) {\n\tcase 1:\n\t\terr = p.setter.Set(paramParts[0])\n\tcase 2:\n\t\terr = p.setter.SetWithVal(paramParts[0], paramParts[1])\n\tdefault:\n\t\terr = fmt.Errorf(\"bad parameter: %q\", paramParts)\n\t}\n\n\tif err != nil {\n\t\tp.ps.AddErr(p.name, loc.Error(err.Error()))\n\t\treturn\n\t}\n\n\tp.whereIsParamSet = append(p.whereIsParamSet, loc.String())\n\n\tfor _, action := range p.postAction {\n\t\terr = action(*loc, p, paramParts)\n\n\t\tif err != nil {\n\t\t\tp.ps.AddErr(p.name, loc.Error(err.Error()))\n\t\t}\n\t}\n}", "func ArgsURL(args []string) []string {\n\turls := args\n\n\tfirstArg := args[0]\n\tif firstArg == \"-parallel\" { // ignore first 2 if it's flag\n\t\turls = args[2:]\n\t}\n\n\tparsedURLs := []string{}\n\tfor _, u := range urls {\n\t\tparsed, err := parseURL(u)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"warn: invalid url %s\", u) // ignore invalid url\n\t\t\tcontinue\n\t\t}\n\t\tparsedURLs = append(parsedURLs, parsed)\n\t}\n\n\treturn parsedURLs\n}", "func (resp *PharosResponse) ParamsForNextPage() url.Values {\n\tif resp.HasNextPage() {\n\t\tnextUrl, _ := url.Parse(*resp.Next)\n\t\tif nextUrl != nil {\n\t\t\treturn nextUrl.Query()\n\t\t}\n\t}\n\treturn nil\n}", "func SignParams(key string, values url.Values) string {\n\tmac := hmac.New(sha1.New, []byte(key))\n\tmac.Write([]byte(values.Encode()))\n\treturn hex.EncodeToString(mac.Sum(nil))\n}", "func (t *RestURL) GetAll(w http.ResponseWriter, r *http.Request) {\n\tt.Log.Handle(w, r, nil, \"begin\", \"RestURL\", \"GetAll\")\n\n\txxRouteVars := mux.Vars(r)\n\n\txxURLValues := r.URL.Query()\n\n\tvar urlValues map[string][]string\n\t{\n\t\turlValues = map[string][]string{}\n\t\txxTempValue := urlValues\n\n\t\tfor k, v := range xxRouteVars {\n\t\t\tif _, ok := xxTempValue[k]; ok {\n\t\t\t\txxTempValue[k] = append(xxTempValue[k], v)\n\t\t\t} else {\n\t\t\t\txxTempValue[k] = []string{v}\n\t\t\t}\n\t\t}\n\n\t\tfor k, v := range xxURLValues {\n\t\t\tif _, ok := xxTempValue[k]; ok {\n\t\t\t\txxTempValue[k] = append(xxTempValue[k], v...)\n\t\t\t} else {\n\t\t\t\txxTempValue[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\tt.embed.GetAll(urlValues)\n\n\tw.WriteHeader(200)\n\n\tt.Log.Handle(w, r, nil, \"end\", \"RestURL\", \"GetAll\")\n\n}", "func (r *Request) Name(name ...string) *Request {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tfor _, n := range name {\n\t\tr.query.Add(\"name[]\", n)\n\t}\n\n\treturn r\n}", "func key(r *http.Request) string {\n\treturn r.URL.Query().Get(\"key\")\n}", "func AllowedParams() []string {\n\treturn []string{\"status\", \"email\", \"name\", \"role\"}\n}" ]
[ "0.7303993", "0.67703974", "0.6523088", "0.61336064", "0.61227006", "0.59929454", "0.5915242", "0.5845793", "0.58435327", "0.5837705", "0.58255464", "0.58133453", "0.5778155", "0.576003", "0.57238996", "0.56995887", "0.56993115", "0.56924534", "0.5681098", "0.5680045", "0.5674362", "0.56637174", "0.56417793", "0.564058", "0.5624973", "0.560486", "0.55171955", "0.55065244", "0.5477668", "0.54668444", "0.54641443", "0.54638934", "0.545979", "0.5452264", "0.54517955", "0.5446871", "0.5444302", "0.5440535", "0.5432461", "0.5429173", "0.54274017", "0.54250675", "0.54089695", "0.54078466", "0.53826624", "0.5380285", "0.53689116", "0.5365472", "0.5355693", "0.5354945", "0.53321505", "0.5330619", "0.53290546", "0.53026074", "0.5298985", "0.529645", "0.5289751", "0.52785045", "0.52759266", "0.5266071", "0.5260639", "0.5246695", "0.52359754", "0.52283674", "0.52238095", "0.5221391", "0.5219368", "0.52169484", "0.5213039", "0.520517", "0.5194032", "0.5193328", "0.51794004", "0.5176051", "0.51730037", "0.51727796", "0.517157", "0.51657873", "0.516374", "0.51538956", "0.5153435", "0.5152217", "0.5144315", "0.51311827", "0.5123973", "0.51157874", "0.51060796", "0.50989825", "0.5093014", "0.5091992", "0.5091049", "0.5088445", "0.5087434", "0.5082322", "0.5075032", "0.50744915", "0.50719696", "0.5067597", "0.50513923", "0.504895", "0.5047284" ]
0.0
-1
NewSupervisor creates new Supervisor.
func NewSupervisor(parent context.Context) *Supervisor { ctx, cancel := context.WithCancel(parent) return &Supervisor{ ctx: ctx, cancel: cancel, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewSupervisor(service string) *Supervisor {\n\treturn &Supervisor{\n\t\tname: \"/usr/bin/supervisorctl\",\n\t\tservice: service,\n\t}\n}", "func NewSupervisor(policyOptions ...PolicyOption) *Supervisor {\n\ts := &Supervisor{\n\t\tmux: sync.Mutex{},\n\t\tprocesses: make(map[string]process),\n\t\tpolicy: Policy{\n\t\t\tFailure: FailurePolicy{\n\t\t\t\tPolicy: shutdown,\n\t\t\t},\n\t\t\tRestart: RestartPolicy{\n\t\t\t\tPolicy: never,\n\t\t\t\tMaxAttempts: 1,\n\t\t\t},\n\t\t},\n\t\tlogger: defaultLogger,\n\t}\n\ts.shutdown = signal.OSShutdownSignal()\n\ts.policy.Reconfigure(policyOptions...)\n\n\treturn s\n}", "func NewSupervisor(ff FixtureFactory) *Supervisor {\n\treturn &Supervisor{\n\t\tfixtureFactory: ff,\n\t\tfixtures: map[string]*Runner{},\n\t}\n}", "func NewCrawlerSupervisor(c *Crawler) *CrawlerSupervisor {\n\treturn &CrawlerSupervisor{\n\t\tjobID: 1,\n\t\tpending: make(map[int]int),\n\t\tvisited: make(map[string]int),\n\t\tbuff: make([]*Job, 0),\n\t\tcrawler: c,\n\t}\n}", "func New(pipeName string, hnd daemon.Handler) *Server {\n\treturn nil\n}", "func NewEtcdSupervisor(client *clientv3.Client, h Handler) *EtcdSupervisor {\n\treturn &EtcdSupervisor{\n\t\tclient: client,\n\t\tfailureHandler: h,\n\t\terrorHandler: h,\n\t}\n}", "func New(\n\taddr string,\n\thandler Handler,\n\tlog *log.Logger,\n\tworkersCount uint8,\n) (srv *Server) {\n\tsrv = &Server{\n\t\taddr: addr,\n\t\thandler: handler,\n\t\tlog: log,\n\t\tClients: newClients(),\n\t\tchStop: make(chan bool, 1),\n\t\tchRequest: make(chan *tRequest, workersCount),\n\t}\n\n\treturn\n}", "func newSpawner(spawnerType SpawnerType) spawner {\n\tswitch spawnerType {\n\tcase NsEnter:\n\t\treturn &nsenter{}\n\tdefault:\n\t\treturn nil\n\t}\n}", "func New(staff repository.IStaffRepo, security security.ISecurity) *router {\n\treturn &router{\n\t\tstaff: staff,\n\t\tsecurity: security,\n\t}\n}", "func New(path string, host string, port int) *Server {\n\ts := &Server{\n\t\thost: host,\n\t\tport: port,\n\t\tpath: path,\n\t\t//\tfs: db.NewFs(),\n\t\trouter: mux.NewRouter(),\n\t\trecvQueryReqQ:make(chan *ServerRequestItem, 100000),\n\t\trecvUpdateReqQ:make(chan *ServerRequestItem, 100000),\n\t\tsendRespQ:make(chan *ServerResponceItem, 100000),\n\t}\n\ts.fs = db.NewFs(s.fsNotifyCb)\n\n\ts.facade = NewEventDispatcher(s)\n\ts.facade.AddEventListener(kEventLeaderChanged, s.eventListener)\n\n\tlog.Printf(\"filePath:%v\", filepath.Join(path, \"name\"))\n\t// Read existing name or generate a new one.\n\tif b, err := ioutil.ReadFile(filepath.Join(path, \"name\")); err == nil {\n\t\ts.name = string(b)\n\t} else {\n\t\ts.name = fmt.Sprintf(\"%07x\", rand.Int())[0:7]\n\t\tif err = ioutil.WriteFile(filepath.Join(path, \"name\"), []byte(s.name), 0644); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn s\n}", "func New(e *calc.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tDivideH: NewDivideHandler(e.Divide, uh),\n\t}\n}", "func CreateNewSSHAgent() (*SSHAgent, error) {\n\tcmd := exec.Command(\"ssh-agent\", \"-s\")\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresultSock := sockR.FindStringSubmatch(string(out))\n\tresultPID := pidR.FindStringSubmatch(string(out))\n\tif len(resultSock) != 2 || len(resultPID) != 2 {\n\t\treturn nil, fmt.Errorf(\"not a valid pid or agent sock, %v %v\", resultSock, resultPID)\n\t}\n\t// The second element is the raw value we want\n\trawPID := resultPID[1]\n\trawSock := resultSock[1]\n\n\tpid, err := strconv.Atoi(rawPID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error processing ssh agent pid %s: %w\", resultPID, err)\n\t}\n\ts := &SSHAgent{Socket: rawSock, PID: pid}\n\ts.Close = func() {\n\t\t_ = s.Kill()\n\t}\n\treturn s, nil\n}", "func NewSegment(concurrency int, descriptors []Descriptor) *Segment {\n\treturn &Segment{\n\t\tconcurrency: concurrency,\n\t\tdescriptors: descriptors,\n\t\tdescriptorErrorBehavior: ErrorBehaviorTerminate,\n\t\tprocessErrorBehavior: ErrorBehaviorCollect,\n\t}\n}", "func NewServer() *Server {}", "func newServer(ctx common.Context, self *replica, listener net.Listener, workers int) (net.Server, error) {\n\tserver := &rpcServer{ctx: ctx, logger: ctx.Logger(), self: self}\n\treturn net.NewServer(ctx, listener, serverInitHandler(server), workers)\n}", "func newPrometheusSpec(name, addr string) cap.SupervisorSpec {\n\treturn cap.NewSupervisorSpec(\n\t\tname,\n\t\t// this function builds an HTTP Server, this functionality requires more\n\t\t// than a goroutine given the only way to stop a http server is to call the\n\t\t// http.Shutdown function on a seperate goroutine\n\t\tfunc() ([]cap.Node, cap.CleanupResourcesFn, error) {\n\t\t\tserver := buildPrometheusHTTPServer(addr)\n\n\t\t\t// CAUTION: The order here matters, we need waitUntilDone to start last so\n\t\t\t// that it can terminate first, if this is not the case the\n\t\t\t// listenAndServeHTTPWorker child will never terminate.\n\t\t\t//\n\t\t\t// DISCLAIMER: The caution above _is not_ a capataz requirement, but a\n\t\t\t// requirement of net/https' API\n\t\t\tnodes := []cap.Node{\n\t\t\t\tlistenAndServeHTTPWorker(server),\n\t\t\t\twaitUntilDoneHTTPWorker(server),\n\t\t\t}\n\n\t\t\tcleanupServer := func() error {\n\t\t\t\treturn server.Close()\n\t\t\t}\n\n\t\t\treturn nodes, cleanupServer, nil\n\t\t},\n\t)\n}", "func main() {\n\n\t// The command line arguments. args[1] is the supervisor address,\n\t// args[2] is the port to run on\n\targs := os.Args\n\n\t// If the right number of arguments weren't passed, ask for them.\n\tif len(args) != 3 {\n\t\tfmt.Println(\"Please pass the hostname of the supervisor and the outgoing port.\" +\n\t\t\t\"eg. http://stu.cs.jmu.edu:4001 4031\")\n\t\tos.Exit(1)\n\t}\n\n\tresp, err := http.Post(args[1]+\"/register\", \"text/plain\", strings.NewReader(args[2]))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\n\t// This gives what the supervisor thinks the worker is, which is useful for debugging.\n\t_ = data.JsonToWorker(buf.Bytes())\n\n\t// Make a directory for this worker, to avoid IO errors from workers writing and reading to\n\t// the same file.\n\tworkerDirectory = args[2]\n\tif _, err = os.Stat(workerDirectory); os.IsNotExist(err) {\n\t\terr = os.Mkdir(args[2], 0777)\n\t\tcheck(err)\n\t}\n\n\t// If there is a request for /newjob,\n\t// the new_job routine will handle it.\n\thttp.HandleFunc(\"/newjob\", new_job)\n\n\t// Listen on a port.\n\tlog.Fatal(http.ListenAndServe(\":\"+args[2], nil))\n}", "func (s *Scene) NewRoutine(name string, args ...string) *Routine {\n\tr := NewRoutine(name, args...)\n\ts.AddRoutine(r)\n\treturn r\n}", "func NewCreateNewtrader(ctx *middleware.Context, handler CreateNewtraderHandler) *CreateNewtrader {\n\treturn &CreateNewtrader{Context: ctx, Handler: handler}\n}", "func newAgent(conf config.Agent) (*agent, error) {\n\t// Check that the agent's processor type is supported\n\tif _, ok := availableProcessorsFactory[conf.Type]; !ok {\n\t\treturn nil, fmt.Errorf(\"Processor %s not found\", conf.Type)\n\t}\n\n\t// Create a new Processor processor\n\tproc := availableProcessorsFactory[conf.Type]()\n\tif proc == nil {\n\t\treturn nil, fmt.Errorf(\"Can not start processor %s\", conf.Type)\n\t}\n\n\ta := &agent{\n\t\tpacketChan: make(chan *event, conf.Buffer),\n\t\toutputs: map[int][]chan *event{},\n\t\tprocessor: proc,\n\t\tDone: make(chan bool),\n\t\tconf: conf,\n\t}\n\n\t// Configure the agent (and its processor)\n\tif err := a.configure(&conf); err != nil {\n\t\treturn nil, fmt.Errorf(\"Can not configure agent %s : %s\", conf.Type, err)\n\t}\n\n\treturn a, nil\n}", "func New(cfg Config, logger log.Logger) (*Agent, error) {\n\treturn newAgent(cfg, logger, defaultInstanceFactory)\n}", "func New(w http.ResponseWriter, r *http.Request) {\n\tgetTemplates().ExecuteTemplate(w, \"New\", nil)\n}", "func (s *Store) SetSupervisor(stu string, t schema.Person) error {\n\treturn s.singleUpdate(updateSupervisor, schema.ErrUnknownInternship, t.Firstname, t.Lastname, t.Tel, t.Email, stu)\n}", "func New(path string, host string, port int) *Server {\r\n\ts := &Server{\r\n\t\thost: host,\r\n\t\tport: port,\r\n\t\tpath: path,\r\n\t\trouter: mux.NewRouter(),\r\n\t}\r\n\r\n\t// Read existing name or generate a new one.\r\n\tif b, err := ioutil.ReadFile(filepath.Join(path, \"name\")); err == nil {\r\n\t\ts.name = string(b)\r\n\t} else {\r\n\t\ts.name = fmt.Sprintf(\"%07x\", rand.Int())[0:7]\r\n\t\tif err = ioutil.WriteFile(filepath.Join(path, \"name\"), []byte(s.name), 0644); err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\t}\r\n\r\n\treturn s\r\n}", "func main() {\n\n\t// The command line arguments. args[1] is the supervisor address,\n\t// args[2] is the port to run on\n\targs := os.Args\n\n\t// If the right number of arguments weren't passed, ask for them.\n\tif len(args) != 3 {\n\t\tfmt.Println(\"Please pass the hostname of the supervisor and the outgoing port.\" +\n\t\t\t\"eg. http://stu.cs.jmu.edu:4001 4031\")\n\t\tos.Exit(1)\n\t}\n\n\tresp, err := http.Post(args[1]+\"/register\", \"text/plain\", strings.NewReader(args[2]))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\n\t// This gives what the supervisor thinks the worker is, which is useful for debugging.\n\t_ = data.JsonToWorker(buf.Bytes())\n\n\t// If there is a request for /newjob,\n\t// the new_job routine will handle it.\n\thttp.HandleFunc(\"/newjob\", new_job)\n\n\t// Listen on a port.\n\tlog.Fatal(http.ListenAndServe(\":\"+args[2], nil))\n}", "func New(config *Config, logger log.Logger) (*Agent, error) {\n\n\tconfig = DefaultConfig().Merge(config)\n\n\tif logger == nil {\n\t\treturn nil, errors.New(\"missing logger\")\n\t}\n\n\ta := &Agent{\n\t\tconfig: config,\n\t\tlogger: logger.WithName(\"agent\"),\n\t\tshutdownCh: make(chan struct{}),\n\t}\n\n\t// Setup Seashell client\n\tif err := a.setupClient(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a, nil\n}", "func (b *BananaPhone) NewProc(funcname string) BananaProcedure {\n\taddr, _ := b.GetFuncPtr(funcname) //yolo error handling\n\treturn BananaProcedure{address: uintptr(addr)}\n}", "func newProcBase(name, bin, serviceAddr string, loggers []Logger) *procBase {\n\tlog.Infof(\"%s has addr %s\", name, serviceAddr)\n\treturn &procBase{\n\t\tname: name,\n\t\tbin: bin,\n\t\tserviceAddr: serviceAddr,\n\t\tloggers: loggers,\n\t}\n}", "func New(addr string, host app.HostService, collector *metrics.Collector) app.Server {\n\treturn &server{\n\t\tsrv: telnet.Server{Addr: addr, Handler: nil},\n\t\thost: host,\n\t\tcollector: collector,\n\t}\n}", "func (a *acceptor) newInstance() {\n\ta.instanceID++\n\ta.initForNewPaxosInstance()\n}", "func New(e *goastarter.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t}\n}", "func (c *Client) VirtualServerCreate(name, address string, virtualPorts []string) error {\n\treturn virtualServerPost(c, \"slb.virtual_server.create\", name, address, virtualPorts)\n}", "func (s *Session) SetSupervisor(stu string, sup schema.Person) error {\n\tif s.Myself(stu) || s.Role().Level() >= schema.AdminLevel {\n\t\treturn s.store.SetSupervisor(stu, sup)\n\t}\n\treturn ErrPermission\n}", "func New() (*Serf, error) {\n\tserf := &Serf{\n\t\tshutdownCh: make(chan struct{}),\n\t}\n\n\treturn serf, nil\n}", "func ServeNew(w http.ResponseWriter, r *http.Request) {\n\tvar data newReq\n\n\tID, err := ulid.New(ulid.Now(), entropy)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\terr = json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tnewH := NewHMST(data.Resolution, data.MaxTime, data.Keys)\n\tregistry[ID.String()] = newH\n\tlog.Println(\"/new\", ID.String(), data, len(newH.Registers))\n\tfmt.Fprintf(w, \"%v\", ID)\n}", "func New(e *calc.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t}\n}", "func Supervise(d *Daemon) error {\n\t// start a new process\n\tp, err := d.Run(NewProcess(d.cfg))\n\tif err != nil {\n\t\treturn err\n\t}\n\tsupervisor := &Supervisor{\n\t\tdaemon: d,\n\t\tprocess: p,\n\t}\n\treturn supervisor.Start()\n}", "func New(middleware ...Handler) *Server {\n\tdebugPrintWARNINGNew()\n\tserv := &Server{\n\t\trouter: make(tree.Trees, 0, 9),\n\t\tnotFound: []Handler{default404Handler},\n\t\tnoMethod: []Handler{default405Handler},\n\t\tmiddleware: middleware,\n\t\tRedirectTrailingSlash: true,\n\t\tRedirectFixedPath: false,\n\t\tMaxMultipartMemory: defaultMultipartMemory,\n\t}\n\n\tserv.pool.New = func() interface{} {\n\t\treturn serv.allocateContext()\n\t}\n\treturn serv\n}", "func New(w http.ResponseWriter, r *http.Request) {\r\n\ttmpl.ExecuteTemplate(w, \"New\", nil)\r\n}", "func New(w http.ResponseWriter, r *http.Request) {\r\n\ttmpl.ExecuteTemplate(w, \"New\", nil)\r\n}", "func CreateChatsSupervisor() *Supervisor {\n\tchannels := &common.Channels{\n\t\tChatsChannel: make(chan common.ChatMessage),\n\t\tSuscriptionsChannel: make(chan common.SubscriptionMessage),\n\t}\n\treturn &Supervisor{\n\t\tchats: make(map[string]*Chat),\n\t\tChannels: channels,\n\t}\n}", "func New(listener net.Listener, httpServer *http.Server) goroutine.BackgroundRoutine {\n\treturn &server{\n\t\tserver: httpServer,\n\t\tmakeListener: func() (net.Listener, error) { return listener, nil },\n\t}\n}", "func New(ctx context.Context, address, masterAddress string) (*agent, error) {\n\t// Register with the master.\n\tvar conn *grpc.ClientConn\n\tfor {\n\t\tvar err error\n\t\tconn, err = grpc.Dial(masterAddress, grpc.WithInsecure(), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxSize)), grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(maxSize)))\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Agent %v unable to communicate with master, sleeping...\", address)\n\t\t\ttime.Sleep(idleWaitTime)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tdefer conn.Close()\n\tc := pb.NewMasterClient(conn)\n\treq := &pb.RegisterAgentRequest{Address: address}\n\t_, err := c.RegisterAgent(ctx, req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to register with master: %v\", err)\n\t}\n\n\tlog.Printf(\"Successfully registered agent %v with master %v\", address, masterAddress)\n\treturn &agent{}, nil\n}", "func New(s *service.Service) (svr *rpc.Server) {\n\tr := &RPC{s: s}\n\tsvr = rpc.NewServer(nil)\n\tif err := svr.Register(r); err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func New(\n\tlistenIP string,\n\tport int,\n\tconf gortsplib.ServerConf,\n\tparent Parent) (*Server, error) {\n\n\taddress := listenIP + \":\" + strconv.FormatInt(int64(port), 10)\n\tsrv, err := conf.Serve(address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := &Server{\n\t\tparent: parent,\n\t\tsrv: srv,\n\t\taccept: make(chan *gortsplib.ServerConn),\n\t\tdone: make(chan struct{}),\n\t}\n\n\tlabel := func() string {\n\t\tif conf.TLSConfig != nil {\n\t\t\treturn \"TCP/TLS/RTSPS\"\n\t\t}\n\t\treturn \"TCP/RTSP\"\n\t}()\n\n\tparent.Log(logger.Info, \"[%s listener] opened on %s\", label, address)\n\n\tgo s.run()\n\n\treturn s, nil\n}", "func New(name, group, address string) *Server {\n\ts := &Server{\n\t\tname: name,\n\t\tgroup: group,\n\t\taddress: address,\n\t}\n\n\treturn s\n}", "func CreateNewEmployee(id string, username string, pass string, fName string, lName string) Employee {\n\treturn Employee{id, username, pass, fName, lName}\n}", "func New(address string, branch string, secret string, logger *logrus.Logger) http.Handler {\n\tproto := \"tcp\"\n\taddr := address\n\tif strings.HasPrefix(addr, \"unix:\") {\n\t\tproto = \"unix\"\n\t\taddr = addr[5:]\n\t}\n\treturn &Server{\n\t\tproto: proto,\n\t\taddress: addr,\n\t\tbranch: branch,\n\t\tsecret: secret,\n\t\tlogger: logger,\n\t}\n}", "func NewCreateNewOffering(ctx *middleware.Context, handler CreateNewOfferingHandler) *CreateNewOffering {\n\treturn &CreateNewOffering{Context: ctx, Handler: handler}\n}", "func New(addr string, port int) *Server {\n\tctx, cancel := context.WithCancel(context.Background())\n\treturn &Server{\n\t\taddr: addr,\n\t\tport: port,\n\t\tctx: ctx,\n\t\tctxCancel: cancel,\n\t}\n}", "func New(config *configuration.Config, vs *library.Library, auth *auth.Manager) *Server {\n\treturn &Server{\n\t\tBase: subapp.NewBase(AppName),\n\t\tconfig: config,\n\t\tlibrary: vs,\n\t\tauthManager: auth,\n\t\trender: render.New(),\n\t}\n}", "func New(e *step.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tListH: NewListHandler(e.List, uh),\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t\tRemoveH: NewRemoveHandler(e.Remove, uh),\n\t\tUpdateH: NewUpdateHandler(e.Update, uh),\n\t}\n}", "func New(addr string) *Server {\n if addr == \"\" {\n addr = DefaultAddr\n }\n return &Server{\n addr: DefaultAddr,\n ds: newDataStore(),\n done: make(chan struct{}),\n }\n}", "func (c *VeterinarianClient) Create() *VeterinarianCreate {\n\tmutation := newVeterinarianMutation(c.config, OpCreate)\n\treturn &VeterinarianCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func NewVegeta(region string) Shooter {\n\treturn &Vegeta{\n\t\tName: fmt.Sprintf(\"Request from %s\", region),\n\t\tAttacker: vegeta.NewAttacker(),\n\t\tDuration: constants.DefaultWorkerDuration,\n\t\tTargeter: nil,\n\t\tRate: &vegeta.Rate{\n\t\t\tFreq: 0,\n\t\t\tPer: time.Second,\n\t\t},\n\t}\n}", "func New(GPIO int) (s *Servo) {\n\t// maxS is the maximun degrees/s for a tipical servo of speed\n\t// 0.19s/60degrees.\n\tconst maxS = 315.7\n\n\ts = &Servo{\n\t\tpin: gpio(GPIO),\n\t\tName: fmt.Sprintf(\"Servo%d\", GPIO),\n\t\tmaxStep: maxS,\n\t\tstep: maxS,\n\t\tMinPulse: 0.05,\n\t\tMaxPulse: 0.25,\n\n\t\tidle: true,\n\t\tfinished: sync.NewCond(&sync.Mutex{}),\n\t\tlock: new(sync.RWMutex),\n\t}\n\n\treturn s\n}", "func New(name string, leaderElectionClient kubernetes.Interface, recorder resourcelock.EventRecorder, callbacks leaderelection.LeaderCallbacks) (*leaderelection.LeaderElector, error) {\n\t// Identity used to distinguish between multiple controller manager instances\n\tid, err := os.Hostname()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting hostname: %s\", err.Error())\n\t}\n\n\t// Lock required for leader election\n\trl := resourcelock.EndpointsLock{\n\t\tEndpointsMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t},\n\t\tClient: leaderElectionClient.CoreV1(),\n\t\tLockConfig: resourcelock.ResourceLockConfig{\n\t\t\tIdentity: id + \"-\" + name,\n\t\t\tEventRecorder: recorder,\n\t\t},\n\t}\n\n\treturn leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{\n\t\tLock: &rl,\n\t\tLeaseDuration: leaseDuration,\n\t\tRenewDeadline: renewDeadline,\n\t\tRetryPeriod: retryPeriod,\n\t\tCallbacks: callbacks,\n\t})\n}", "func New(router *mux.Router, db db.PGManager) Server {\n\t// This creates a new *server struct instance. Notice the pointer (&): this means when\n\t// the server is returned it will be the same place in memory when used elsewhere (i.e.\n\t// the struct isn't copied).\n\tserver := &server{\n\t\tHandler: router,\n\t\tdb: db,\n\t}\n\t// We set up our routes as part of the constructor function.\n\tserver.routes(router)\n\treturn server\n}", "func New(c *conf.Config, s *service.Service) (svr *rpc.Server) {\n\tr := &RPC{s: s}\n\tsvr = rpc.NewServer(c.RPCServer)\n\tif err := svr.Register(r); err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func CreateNewFv(nodeID int, timeAfter string, remarks string, timeStart string, version string, verState int) (Fverinfo, error) {\n\tif nodeID == 0 || timeAfter == \"\" || remarks == \"\" || timeStart == \"\" || version == \"\" || verState == 0 {\n\t\treturn Fverinfo{}, errors.New(\"Not enough argument supplied\")\n\t}\n\treturn Fverinfo{\n\t\tNodeID: nodeID,\n\t\tEndDate: timeAfter,\n\t\tRemarks: remarks,\n\t\tStartDate: timeStart,\n\t\tVersion: version,\n\t\tVerState: verState,\n\t}, nil\n}", "func New(commandArgs common.CommandArgs) *Node {\n\n\tnode := Node{\n\t\tNodeCommon: common.NewNodeCommon(commandArgs, \"master\"),\n\t\t// FirstSlaveListenPort: 7500, // TODO(greg) make this an env parameter /TODO this is the *base* port that the new slave should try. incrementing if failing to get the port\n\t}\n\n\treturn &node\n}", "func NewSegment(p1, p2 Vector) Segment {\n\treturn Segment{p1, p2}\n}", "func New() *Server {\n\tr := gin.Default()\n\treturn &Server{Engine: r}\n}", "func NewBalancer(name string, handler EventHandler, configure *conf.BalancersConfiguration) (balancer *Balancer) {\n\n\tbalancer = new(Balancer)\n\tbalancer.name = name\n\tbalancer.handler = handler\n\tconfiguration := configure.GetBalancerConfiguration(name)\n\tbalancer.balancerType = configuration.BalancerType\n\tbalancer.initQueue(configuration)\n\tbalancer.aggregatorManager = initAggregatorManager(configuration.AggreagatorName, balancer, configuration.WorkAggregatorConfiguration)\n\tbalancer.poolManager = initRoutinePoolManager(name, balancer.balancerType, balancer, handler, configuration)\n\treturn balancer\n}", "func NewServerus(port string) *Serverus {\n\tport = getPort(port)\n\n\tlog.Println(\"Creating new serverus\")\n\treturn &Serverus{\n\t\tport: port,\n\t\tlis: getListener(port),\n\t}\n}", "func New(transport runtime.ClientTransport, formats strfmt.Registry) *Jasperserver {\n\tcli := new(Jasperserver)\n\tcli.Transport = transport\n\n\tcli.Operations = operations.New(transport, formats)\n\n\treturn cli\n}", "func New() *Server {\n\tsv := &Server{\n\t\tE: echo.New(),\n\t\tH: handlers.New(),\n\t}\n\tsv.routes()\n\treturn sv\n}", "func newServer() *negroni.Negroni {\n\tn := negroni.Classic()\n\tn.UseHandler(router())\n\treturn n\n}", "func (c *NurseClient) Create() *NurseCreate {\n\tmutation := newNurseMutation(c.config, OpCreate)\n\treturn &NurseCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func New(ctx context.Context) (*Controller, error) {\n\t// create user service\n\tuserSVC, err := service.New(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating service: %v\", err)\n\t}\n\n\treturn &Controller{\n\t\tuser: userSVC,\n\t}, nil\n}", "func NewVRF(name string) (*VRF, error) {\n\tif !vrfMgr.re.MatchString(name) {\n\t\treturn nil, fmt.Errorf(\"Invalid VRF name: '%v'\", name)\n\t}\n\n\tvrfMgr.mutex.Lock()\n\tdefer vrfMgr.mutex.Unlock()\n\n\tif _, exists := vrfMgr.byName[name]; exists {\n\t\treturn nil, fmt.Errorf(\"VRF %s already exists\", name)\n\t}\n\n\tvrf := &VRF{\n\t\tname: name,\n\t\tenabled: false,\n\t}\n\n\tif !vrfMgr.assignIndex(vrf) {\n\t\treturn nil, fmt.Errorf(\"No space left for new VRF\")\n\t}\n\n\tvifIndex, err := vifIdxMgr.allocVIFIndex(vrf)\n\tif err != nil {\n\t\tvrfMgr.releaseIndex(vrf)\n\t\treturn nil, fmt.Errorf(\"Can't assign VIFIndex: %v\", err)\n\t}\n\tvrf.vifIndex = vifIndex\n\n\t// Create an ICMP processor\n\tvar errMsg error\n\ttapName := name + \"-tap\"\n\tif tap, err := newInstance(tapModule, tapName, name); err != nil {\n\t\terrMsg = fmt.Errorf(\"ICMP handler instance creation failed: %v\", err)\n\t\tgoto error1\n\t} else {\n\t\tvrf.tap = tap\n\t}\n\n\t// Craete a router\n\tif router, err := newRouter(vrf, name); err != nil {\n\t\terrMsg = fmt.Errorf(\"Router instance creation failed: %v\", err)\n\t\tgoto error2\n\t} else {\n\t\tvrf.router = router\n\t}\n\n\t// Forward all IP packets to the ICMP processor\n\tif err := vrf.router.connect(vrf.tap.Input(), MatchIPv4DstSelf, nil); err != nil {\n\t\terrMsg = errors.New(\"Can't connect a router and an tap modules\")\n\t\tgoto error3\n\t}\n\n\tvrf.RoutingTable = newRoutingTable(vrf)\n\tvrf.devs = make(map[VIFIndex]OutputDevice)\n\tvrf.PBR = newPBR(vrf)\n\tvrfMgr.byName[name] = vrf\n\n\tnoti.Notify(notifier.Add, vrf, nil)\n\n\treturn vrf, nil\n\nerror3:\n\tvrf.router.free()\nerror2:\n\tvrf.tap.free()\nerror1:\n\tvrfMgr.releaseIndex(vrf)\n\treturn nil, errMsg\n}", "func Create(addr, Nickname, username, realname, password string) *Server {\n\tref := &Server{Server: addr, sendqueue: make(chan string),\n\t\tpassword: password, Nickname: Nickname, username: username, realname: realname,\n\t\tthrottle: 0, kill: make(chan bool)}\n\n\tdebug(\"Created: \", addr, \"\\n\")\n\treturn ref\n}", "func New(jobsession string) (*Tracker, error) {\n\tsingularityPath, err := exec.LookPath(\"singularity\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"singularity command is not found\")\n\t}\n\treturn &Tracker{\n\t\tprocessTracker: simpletracker.New(jobsession),\n\t\tsingularityPath: singularityPath,\n\t}, nil\n}", "func (l *listener) NewLeader(id string) {\n\tlog.Printf(\"[INFO] %s: new leader: %s\", hostname(), id)\n}", "func New(srv *cmutation.Server) *Server {\n\treturn &Server{srv}\n}", "func New() prov.Provisioner {\n\tx\n}", "func New(p Processor, e Exception, opt *Options) *Actor {\n\topt.configure()\n\n\tactor := &Actor{\n\t\tname: opt.Name,\n\t\tinbox: make(chan interface{}, opt.Worker),\n\t\toutbox: opt.Output,\n\t\tprocess: p,\n\t\texception: e,\n\n\t\texit: make(chan struct{}),\n\t\tworkgroup: &sync.WaitGroup{},\n\t\tinboxgroup: &sync.WaitGroup{},\n\t}\n\n\tactor.start(0, opt.Worker)\n\treturn actor\n}", "func New(cfg config.ServerConfig, db database.Database) *Server {\n\treturn &Server{\n\t\trouter: gin.Default(),\n\t\tport: cfg.Port,\n\t\tdb: db,\n\t}\n}", "func New(path, listen string) (*Server, error) {\n\tcs, err := transport.Encode(listen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsqlPath := filepath.Join(path, \"storage.sql\")\n\tutil.EnsureAbsent(sqlPath)\n\n\ts := &Server{\n\t\tpath: path,\n\t\tlisten: listen,\n\t\tsql: sql.NewSQL(sqlPath),\n\t\trouter: mux.NewRouter(),\n\t\tclient: transport.NewClient(),\n\t\tcluster: NewCluster(path, cs),\n\t}\n\n\treturn s, nil\n}", "func newSegment(segType uint8, flags uint16, streamID uint32, transID uint16, orderID uint16, message []byte) (*segment, error) {\n\tlength := len(message)\n\tif length > segmentBodyMaxSize {\n\t\treturn nil, errSegmentBodyTooLarge\n\t}\n\thdr := header(make([]byte, headerSize))\n\tif message == nil {\n\t\tmessage = []byte{} // FIXME!\n\t}\n\thdr.encode(segType, flags, streamID, transID, orderID, uint16(length))\n\treturn &segment{h: hdr, b: message}, nil\n}", "func NewStage(name string, e func(*Context) error) Stage {\n\treturn &baseStage{name: name, execFunc: e}\n}", "func New(h handlers.Handler, l *zap.SugaredLogger) Router {\n\tr := chi.NewRouter()\n\n\tr.Mount(\"/\", newIndexRouter(h))\n\n\tr.NotFound(h.NotFound)\n\tr.MethodNotAllowed(h.MethodNotAllowed)\n\n\trouter := &router{\n\t\tHandler: r,\n\t\tlogger: l,\n\t}\n\n\trouter.Handler = middleware.Log(router.Handler, router.logger)\n\n\treturn router\n}", "func NewVessel(id uuid.UUID, name, beam, loa, draft, status string) *Vessel {\n\treturn &Vessel{\n\t\tID: id,\n\t\tName: name,\n\t\tBeam: beam,\n\t\tLOA: loa,\n\t\tDraft: draft,\n\t\tStatus: status,\n\t}\n}", "func New(lms chan mysignals.LifeSignal) *Person {\n\t// create new Person\n\tp := Person{\n\t\tid: newPersonID(),\n\t\tage: Age{\n\t\t\tvalue: 15,\n\t\t\tlock: sync.Mutex{},\n\t\t\tmaxage: 40,\n\t\t},\n\t\tsmartphone: smartphone.New(),\n\t\tlifemsgs: lms,\n\t\tengaged: engaged{\n\t\t\tvalue: false,\n\t\t\tlock: sync.Mutex{},\n\t\t},\n\t\t// use &brain.Brain{}\n\t\t// instead of brain.Brain{}\n\t\t// because Brain implements the interface DecisionMaker{} using a pointer receiver\n\t\t// \t\t\t(b* Brain)Method(...)\n\t\t// instead of a value receiver\n\t\t// \t\t\t(b Brain)Method(...)\n\t\tbrain: &brain.Brain{},\n\t\t// sex is M or F\n\t\tsex: func() byte {\n\t\t\tif utils.NewRandomIntInRange(0, 1) == 0 {\n\t\t\t\treturn 'M'\n\t\t\t}\n\t\t\treturn 'F'\n\t\t}(),\n\t}\n\t// start listening for signals\n\tgo (&p).listenForSignals()\n\t// return Person information\n\treturn &p\n}", "func newLoadBalancer(ctx context.Context, frontend NetAddr, policy loadBalancerPolicy, backends ...NetAddr) (*LoadBalancer, error) {\n\tif ctx == nil {\n\t\treturn nil, trace.BadParameter(\"missing parameter context\")\n\t}\n\twaitCtx, waitCancel := context.WithCancel(ctx)\n\treturn &LoadBalancer{\n\t\tfrontend: frontend,\n\t\tctx: ctx,\n\t\tbackends: backends,\n\t\tpolicy: policy,\n\t\twaitCtx: waitCtx,\n\t\twaitCancel: waitCancel,\n\t\tEntry: log.WithFields(log.Fields{\n\t\t\ttrace.Component: \"loadbalancer\",\n\t\t\ttrace.ComponentFields: log.Fields{\n\t\t\t\t\"listen\": frontend.String(),\n\t\t\t},\n\t\t}),\n\t\tconnections: make(map[NetAddr]map[int64]net.Conn),\n\t}, nil\n}", "func New() *Pipeline {\n\treturn &Pipeline{}\n}", "func New(ctx context.Context, fs afs.Service, done OnDone, routines int) Service {\n\tsrv := &service{\n\t\tOnDone: done,\n\t\tWaitGroup: &sync.WaitGroup{},\n\t\terrChannel: make(chan error, 1),\n\t\tfs: fs,\n\t}\n\tsrv.init(ctx, routines)\n\treturn srv\n}", "func (zkts *Server) NewMasterParticipation(name, id string) (topo.MasterParticipation, error) {\n\telectionPath := path.Join(GlobalElectionPath, name)\n\n\t// create the toplevel directory, OK if it exists already.\n\t_, err := zk.CreateRecursive(zkts.zconn, electionPath, nil, 0, zookeeper.WorldACL(zookeeper.PermAll))\n\tif err != nil && err != zookeeper.ErrNodeExists {\n\t\treturn nil, convertError(err)\n\t}\n\n\treturn &zkMasterParticipation{\n\t\tzkts: zkts,\n\t\tname: name,\n\t\tid: []byte(id),\n\t\tstop: make(chan struct{}),\n\t\tdone: make(chan struct{}),\n\t}, nil\n}", "func New(voter vote.Voter, opnRetriever OpinionRetriever, bindAddr string, netRxEvent, netTxEvent, queryReceivedEvent *events.Event) *VoterServer {\n\treturn &VoterServer{\n\t\tvoter: voter,\n\t\topnRetriever: opnRetriever,\n\t\tbindAddr: bindAddr,\n\t\tgrpcServer: grpc.NewServer(),\n\t\tnetRxEvent: netRxEvent,\n\t\tnetTxEvent: netTxEvent,\n\t\tqueryReceivedEvent: queryReceivedEvent,\n\t}\n}", "func New(svcURL, location string, id, key string, crypto license.Crypto, validator license.Validator) license.Agent {\n\treturn &agent{\n\t\tsvcURL: svcURL,\n\t\tlocation: location,\n\t\tid: id,\n\t\tkey: key,\n\t\tcrypto: crypto,\n\t\tvalidator: validator,\n\t\tcommands: make(chan command),\n\t\terrs: make(chan error),\n\t}\n}", "func New(cfg *viper.Viper) *Server {\n\tsrv := &Server{cfg: cfg}\n\n\t// Create App Context\n\tsrv.runCtx, srv.runCancel = context.WithCancel(context.Background())\n\n\t// Initiate a new logger\n\tsrv.log = logrus.New()\n\tif srv.cfg.GetBool(\"debug\") {\n\t\tsrv.log.Level = logrus.DebugLevel\n\t\tsrv.log.Debug(\"Enabling Debug Logging\")\n\t}\n\tif srv.cfg.GetBool(\"trace\") {\n\t\tsrv.log.Level = logrus.TraceLevel\n\t\tsrv.log.Debug(\"Enabling Trace Logging\")\n\t}\n\tif srv.cfg.GetBool(\"disable_logging\") {\n\t\tsrv.log.Level = logrus.FatalLevel\n\t}\n\n\treturn srv\n\n}", "func Create(conf *config.Config, logger *logrus.Logger) (Runner, error) {\n\tvar srv Runner\n\n\tswitch conf.Server.Type {\n\tcase \"grpc\":\n\t\tsrv = grpc.NewRunner(conf,logger)\n\tdefault:\n\t\treturn nil, errors.New(\"InvalidServerTypeError(#{conf.Server.Type})\")\n\t}\n\treturn srv, nil\n}", "func NewVirtualEndpoint()(*VirtualEndpoint) {\n m := &VirtualEndpoint{\n Entity: *NewEntity(),\n }\n return m\n}", "func New() *Server {\n\treturn &Server{}\n}", "func New() *Server {\n\treturn &Server{}\n}", "func New(fetcherSvc *services.Fetcher, log *logrus.Entry) *Server {\n\treturn &Server{\n\t\tFetcherSvc: fetcherSvc,\n\t\tLog: log,\n\t}\n}", "func New(config *Config) *Server {\n\ts := &Server{\n\t\tconfig: config,\n\t\trouter: chi.NewRouter(),\n\t\tlogger: newLogger(config.LogDebug),\n\t}\n\n\treturn s\n}", "func newAgent() (agent.Agent, error) {\n\tsock := os.Getenv(\"SSH_AUTH_SOCK\")\n\tif sock == \"\" {\n\t\treturn nil, errors.New(\"Unable to connect to the ssh agent. Please, check that SSH_AUTH_SOCK is set and the ssh agent is running\")\n\t}\n\n\tconn, err := net.Dial(\"unix\", sock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn agent.NewClient(conn), nil\n}", "func New(sigs chan os.Signal) *Server {\n\ts := &Server{mux: http.NewServeMux(), sigs: sigs}\n\n\tif s.logger == nil {\n\t\ts.logger = log.New(os.Stdout, \"\", 0)\n\t}\n\n\ts.db = store.NewStore()\n\n\ts.mux.HandleFunc(\"/\", s.latencyMiddleware(s.index))\n\ts.mux.HandleFunc(\"/hash/\", s.latencyMiddleware(s.hash))\n\ts.mux.HandleFunc(\"/shutdown/\", s.latencyMiddleware(s.shutdown))\n\ts.mux.HandleFunc(\"/stats/\", s.stats)\n\n\treturn s\n}", "func New() (*VueLoader, error) {\n\treturn NewWithConfig(NewConfig())\n}" ]
[ "0.7386423", "0.72824174", "0.7207616", "0.5784553", "0.5330781", "0.53016263", "0.5257373", "0.51081926", "0.49982578", "0.49463803", "0.48996973", "0.4896564", "0.4884315", "0.48748294", "0.48615274", "0.4859745", "0.48468015", "0.48456034", "0.48424396", "0.48383132", "0.4830504", "0.48293838", "0.4805644", "0.48008716", "0.4799958", "0.47693995", "0.47476587", "0.4743213", "0.4738055", "0.47322628", "0.47296783", "0.47289056", "0.47277927", "0.4726457", "0.4712758", "0.47017962", "0.46956766", "0.46664315", "0.46286842", "0.46286842", "0.46252793", "0.46132502", "0.46098202", "0.45884064", "0.45818016", "0.45801565", "0.45798883", "0.45777294", "0.45749667", "0.45736033", "0.4563514", "0.45600632", "0.45585746", "0.45542774", "0.45474324", "0.45446083", "0.45389593", "0.4538647", "0.45363525", "0.45344052", "0.4517816", "0.45117223", "0.45108524", "0.4504962", "0.44999084", "0.44973227", "0.4491496", "0.44798493", "0.4476442", "0.44741186", "0.44487748", "0.44457555", "0.44438574", "0.44425908", "0.44419077", "0.44369537", "0.4436435", "0.4433629", "0.44327933", "0.44243148", "0.44219202", "0.44161525", "0.44109738", "0.44106284", "0.4407286", "0.44066182", "0.44065198", "0.4403374", "0.43996295", "0.43943882", "0.43934968", "0.43916667", "0.4387393", "0.43789795", "0.43789795", "0.43780038", "0.43759042", "0.4369831", "0.4367755", "0.43630016" ]
0.7562363
0
Go calls the given function in a new goroutine.
func (s *Supervisor) Go(task func(ctx context.Context) error) { s.wg.Add(1) go func() { defer s.wg.Done() if err := task(s.ctx); err != nil { if s.onError != nil { s.onError(err) } } }() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Go(ctx Context, f func(ctx Context)) {\n\tstate := getState(ctx)\n\tstate.dispatcher.newCoroutine(ctx, f)\n}", "func (wg *WaitGroup) Go(fn func(...interface{}), arg ...interface{}) {\n\twg.Wg.Add(1)\n\tgo func() {\n\t\tfn(arg...)\n\t\twg.Wg.Done()\n\t}()\n}", "func NewGoroutine(f func()) {\n\tdefer Recover()\n\tf()\n}", "func (dummyPool) Go(ctx context.Context, fn func()) error {\n\tgo fn()\n\treturn nil\n}", "func (p *GoroutinePool) Go(ctx context.Context, fn func()) error {\n\tselect {\n\tcase <-p.quitChan:\n\t\treturn ErrClosed\n\tdefault:\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase p.fnChan <- fn:\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tif err := p.startGoroutine(ctx, fn); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase p.fnChan <- fn:\n\t\t\t\treturn nil\n\t\t\tcase <-time.After(time.Millisecond):\n\t\t\t}\n\t\t}\n\t}\n}", "func (pool *Pool) Go(f func()) {\n\tg := pool.get()\n\tg.ch <- f\n}", "func (w *WaitGroup) Go(f func()) {\n\tw.wg.Add(1)\n\tgo w.do(f)\n}", "func (g *FuncGroup) Go(f func()) {\n\t(*sync.WaitGroup)(unsafe.Pointer(g)).Add(1)\n\tdefer (*sync.WaitGroup)(unsafe.Pointer(g)).Done()\n\tf()\n}", "func (p *Pool) Go(goroutine func(stop chan bool)) {\n\tp.lock.Lock()\n\tnewRoutine := routine{\n\t\tgoroutine: goroutine,\n\t\tstop: make(chan bool, 1),\n\t}\n\tp.routines = append(p.routines, newRoutine)\n\tp.waitGroup.Add(1)\n\tGo(func() {\n\t\tgoroutine(newRoutine.stop)\n\t\tp.waitGroup.Done()\n\t})\n\tp.lock.Unlock()\n}", "func CallOnUIGoroutine(f func()) {\n\tdriver.CallOnUIGoroutine(f)\n}", "func (s *StanServer) startGoRoutine(f func()) {\n\ts.mu.Lock()\n\tif !s.shutdown {\n\t\ts.wg.Add(1)\n\t\tgo f()\n\t}\n\ts.mu.Unlock()\n}", "func goroutineTest() {\n\tgo say(\"world\")\n\tsay(\"hello\")\n}", "func spawnInALoop() {\n\tfor i := 0; i < 10; i++ {\n\t\t// Our goroutine is a closure, and closures can\n\t\t// access variables in the outer scope, so we can\n\t\t// grab i here to give each goroutine an ID, right?\n\t\t// (Hint: wrong.)\n\t\tgo func() {\n\t\t\tfmt.Println(\"Goroutine\", i)\n\t\t}() // <- Don't forget to call () the closure\n\t}\n\ttime.Sleep(100 * time.Millisecond)\n}", "func newRoutine(wg *sync.WaitGroup) {\n\tfmt.Println(\"New Routine\")\n\twg.Done()\n}", "func Go(f func() error) chan error {\n\tch := make(chan error, 1)\n\tgo func() {\n\t\tch <- f()\n\t}()\n\treturn ch\n}", "func Go(goroutine func()) {\n\tGoWithRecover(goroutine, defaultRecoverGoroutine)\n}", "func Go(goroutine func()) {\n\tGoWithRecover(goroutine, defaultRecoverGoroutine)\n}", "func (g *Group) Go(f func(quit <-chan struct{}) error) {\n\tg.mu.Lock()\n\tif g.quit == nil {\n\t\tg.quit = make(chan struct{})\n\t}\n\tg.mu.Unlock()\n\n\tg.wg.Add(1)\n\tgo func() {\n\t\terr := f(g.quit)\n\t\tif err != nil {\n\t\t\tg.mu.Lock()\n\t\t\tif g.err == nil {\n\t\t\t\tg.err = err\n\t\t\t}\n\t\t\tg.mu.Unlock()\n\t\t\tg.Quit()\n\t\t}\n\t\tg.wg.Done()\n\t}()\n}", "func Go(f func() error) chan error {\n\tch := make(chan error)\n\tgo func() {\n\t\tch <- f()\n\t}()\n\treturn ch\n}", "func Go(f func() error) chan error {\n\tch := make(chan error)\n\tgo func() {\n\t\tch <- f()\n\t}()\n\treturn ch\n}", "func (g *Group) Go(f func()) {\n\tg.group.Add(1)\n\tgo func() { f(); g.group.Done() }()\n}", "func (e *Endpoint) Go(function string, args interface{}, reply interface{}, done chan *rpc.Call) *rpc.Call {\n\tcall := &rpc.Call{}\n\tcall.ServiceMethod = function\n\tcall.Args = args\n\tcall.Reply = reply\n\tif done == nil {\n\t\tdone = make(chan *rpc.Call, 10)\n\t} else {\n\t\tif cap(done) == 0 {\n\t\t\tlog.Panic(\"ws_rpc: done channel is unbuffered\")\n\t\t}\n\t}\n\tcall.Done = done\n\n\tmsg := &Message{\n\t\tFunc: function,\n\t\tArgs: args,\n\t}\n\n\te.client.mutex.Lock()\n\te.client.seq++\n\tmsg.ID = e.client.seq\n\te.client.pending[msg.ID] = call\n\te.client.mutex.Unlock()\n\n\t// put sending in a goroutine so a malicious client that\n\t// refuses to read cannot ever make a .Go call block\n\tgo e.send(msg)\n\treturn call\n}", "func (x Go) Go(f func()) error {\n\tvar started, funcDone chan struct{}\n\tif x.ensureStarted {\n\t\tstarted = make(chan struct{})\n\t}\n\tif x.timeout != 0 {\n\t\tfuncDone = make(chan struct{})\n\t}\n\tif x.wg != nil {\n\t\tx.wg.Add(1)\n\t}\n\n\tgo func() {\n\t\tif started != nil {\n\t\t\tclose(started)\n\t\t}\n\t\tif x.wg != nil {\n\t\t\tdefer x.wg.Done()\n\t\t}\n\t\tif funcDone != nil {\n\t\t\tdefer close(funcDone)\n\t\t}\n\t\tif x.recoverFunc != nil {\n\t\t\tdefer func() {\n\t\t\t\tif e := recover(); e != nil {\n\t\t\t\t\tx.recoverFunc(e)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tif x.before != nil {\n\t\t\tx.before()\n\t\t}\n\t\tif x.after != nil && x.deferAfter {\n\t\t\tdefer x.after()\n\t\t}\n\n\t\tf()\n\n\t\tif x.after != nil && !x.deferAfter {\n\t\t\tx.after()\n\t\t}\n\t}()\n\n\tif started != nil {\n\t\t<-started\n\t}\n\tif funcDone != nil {\n\t\tif x.timeout > 0 {\n\t\t\ttm := time.NewTimer(x.timeout)\n\t\t\tdefer func() {\n\t\t\t\tif !tm.Stop() {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-tm.C:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t\tselect {\n\t\t\tcase <-funcDone:\n\t\t\tcase <-tm.C:\n\t\t\t\treturn ErrTimeout\n\t\t\t}\n\t\t} else if x.timeout < 0 {\n\t\t\t<-funcDone\n\t\t}\n\t}\n\n\treturn nil\n}", "func (p *pool) Go(goroutine func(context.Context)) {\n\tp.waitGroup.Add(1)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tif p.recoverFunc != nil {\n\t\t\t\t\tp.recoverFunc(r)\n\t\t\t\t}\n\t\t\t}\n\t\t\tp.waitGroup.Done()\n\t\t}()\n\t\tgoroutine(p.ctx)\n\t}()\n}", "func runNaiveGoRoutine(gr g.Graph, poolSize int, debug int, c chan g.Graph) {\n\tc <- RunNaive(gr, poolSize, debug)\n}", "func Call(f func()) {\n\tdone := dPool.Get().(chan struct{})\n\tdefer dPool.Put(done)\n\tfq <- fun{fn: f, done: done}\n\t<-done\n}", "func main() {\n\tfor i:=0;i<10;i++ {\n\t\tgo myfunc(i) //this will call myfunc() as a goroutine\n\t}\n\tvar input string\n\tfmt.Scanln(&input) //waiting on user input so the goroutine finishes and program does not exit as this is the last line of the program.\n\t\n}", "func main() {\n\t// this is a blockin function, it will not process next line if this function isn't done processed\n\tf(\"non-goroutine\")\n\n\t// this is go routine, it will start thread and continue to next line\n\tgo f(\"goroutine1\")\n\ttime.Sleep(time.Second)\n\tgo f(\"goroutine2\")\n\n\t// if we dont make a wait group, after go routine started it will end the main program\n\ttime.Sleep(time.Second * 10)\n}", "func Call(f func()) {\n\tcheckRun()\n\tdone := make(chan struct{})\n\tcallQueue <- func() {\n\t\tf()\n\t\tdone <- struct{}{}\n\t}\n\t<-done\n}", "func (m *GoRoutines) Run(c context.Context, name string, fn func(ctx context.Context)) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tg := &GoRoutine{\n\t\tctx: c,\n\t\tName: name,\n\t\tFunc: fn,\n\t\tActive: true,\n\t\tRestart: false,\n\t}\n\tm.status = append(m.status, g)\n\tm.exec(g)\n}", "func BasicGoroutine(){\n\t// Starts a new go routine\n\tgo say(\"World\")\n\t//go say(\"test\")\n\tsay(\"Hello\")\n}", "func simplyRun(f func()) {\n\tgo f()\n}", "func (runner *suiteRunner) runFunc(method *reflect.FuncValue, kind funcKind,\n dispatcher func(c *C)) *C {\n c := runner.forkCall(method, kind, dispatcher)\n <-c.done\n return c\n}", "func Go(f func()) {\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tstack := debug.Stack()\n\t\t\t\tlog.Printf(\"goroutine panic: %v\\n%s\", err, stack)\n\t\t\t}\n\t\t}()\n\t\tf()\n\t}()\n}", "func (e *executor) call(fn func() error, format string, args ...interface{}) error {\n\treturn e.function(e.opts, fn, format, args...)\n}", "func Go(fn func()) {\n\tgo func() {\n\t\tdefer func() { Ignore(Recover()) }()\n\t\tfn()\n\t}()\n}", "func (g *Group) Go(\n\tfn func(context.Context) error,\n) error {\n\tselect {\n\tcase <-g.ctx.Done():\n\t\treturn g.ctx.Err()\n\tdefault:\n\t}\n\n\tg.wgM.RLock()\n\tdefer g.wgM.RUnlock()\n\n\tselect {\n\tcase <-g.ctx.Done():\n\t\treturn g.ctx.Err()\n\tdefault:\n\t\tg.wg.Add(1)\n\t\tgo g.execute(fn)\n\t\treturn nil\n\t}\n}", "func (p *GoroutinePool) Go(ctx context.Context, f func()) {\n\tif err := p.sem.Acquire(context.TODO(), 1); err != nil {\n\t\tlog.Errorf(ctx, \"[GoroutinePool] Go acquire failed %v\", err)\n\t\treturn\n\t}\n\tSentryGo(func() {\n\t\tdefer p.sem.Release(1)\n\t\tf()\n\t})\n}", "func main() {\n\tgo foo()\n\tgo bar()\n}", "func main() {\n\tgo foo()\n\tgo bar()\n}", "func Go(f func(), nsrefs ...Referrer) error {\n\tstarted := make(chan error)\n\tgo func() {\n\t\t// Lock, but never unlock the OS thread exclusively powering our Go\n\t\t// routine. This ensures that the Golang runtime will destroy the OS\n\t\t// thread and never attempts to reuse it.\n\t\truntime.LockOSThread()\n\t\t// Switch our highly exclusive OS thread into the specified\n\t\t// namespaces...\n\t\tfor _, nsref := range nsrefs {\n\t\t\t// Important: since nsref.Reference() returns a file descriptor\n\t\t\t// which potentially is derived from an open os.File, the latter\n\t\t\t// must not get garbage collected while we attempt to use the file\n\t\t\t// descriptor, as otherwise the os.File's finalizer will have closed\n\t\t\t// the fd prematurely. Luckily (hopefully not!) the (varargs) slice\n\t\t\t// won't be collectible until the iteration terminates, keeping its\n\t\t\t// slice elements and thus its os.Files (if any) alive. In\n\t\t\t// consequence, we don't need an explicit runtime.KeepAlive(...)\n\t\t\t// here.\n\t\t\tfd, close, err := nsref.Reference()\n\t\t\tif err != nil {\n\t\t\t\tstarted <- err\n\t\t\t\treturn // ex-terminate ;)\n\t\t\t}\n\t\t\terr = unix.Setns(fd, 0)\n\t\t\tif close {\n\t\t\t\t// Don't leak open file descriptors...\n\t\t\t\tunix.Close(int(fd))\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tstarted <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// Our preparations are finally done, so let's call the desired function and\n\t\t// then call it a day.\n\t\tstarted <- nil\n\t\tf()\n\t}()\n\t// Wait for the goroutine to have finished switching namespaces and about to\n\t// invoke the specified function. We're lazy and are never closing the\n\t// channel, but it will get garbage collected anyway.\n\treturn <-started\n}", "func Spawn(f func()) sync.Locker {\r\n\tdone := NewDone() // created in locked state\r\n\tgo func() {\r\n\t\tf()\r\n\t\tdone.Unlock()\r\n\t} ()\r\n\treturn done\r\n}", "func (c *Circuit) Go(ctx context.Context, runFunc func(context.Context) error, fallbackFunc func(context.Context, error) error) error {\n\tif c == nil {\n\t\tvar wrapper goroutineWrapper\n\t\treturn c.Execute(ctx, wrapper.run(runFunc), wrapper.fallback(fallbackFunc))\n\t}\n\treturn c.Execute(ctx, c.goroutineWrapper.run(runFunc), c.goroutineWrapper.fallback(fallbackFunc))\n}", "func main() { // runs in the main Goroutine\n\t// create new Goroutine - call return immediately -> does not wait for the Goroutine to finishing executing\n\t// next line of code + any return values from the Goroutine are ignored\n\t// main Goroutine termiantes -> programm will be terminated\n\tgo hello()\n\ttime.Sleep(1 * time.Second) // better using channels to block the main Goroutine until all other Goroutines finish their execution\n\tfmt.Println(\"main function\")\n}", "func (r *rpcClientService) Go(serviceMethod string, args interface{},\n reply interface{}, rspCh chan error) error {\n\n go func() {\n err := r.Call(serviceMethod, args, reply)\n rspCh <- err\n }()\n return nil\n}", "func callGreet() {\n\tc := make(chan string)\n\tgo Greet(c) //start new goroutine,ready state\n\tc <- \"zhang sir\"\n}", "func (g *Group) Go(f func() (interface{}, error)) {\n\tg.initOnce.Do(func() {\n\t\tg.init(context.Background())\n\t})\n\n\tatomic.AddInt64(&g.count, 1)\n\tgo func() {\n\t\tv, err := f()\n\t\tselect {\n\t\tcase g.ch <- result{value: v, err: err}:\n\t\tcase <-g.ctx.Done():\n\t\t}\n\t\tatomic.AddInt64(&g.count, -1)\n\t}()\n}", "func (sf JobFunc) Run() {\n\tsf()\n}", "func (m *Memberlist) triggerFunc(stagger time.Duration, C <-chan time.Time, stop <-chan struct{}, f func()) {\n\t// Use a random stagger to avoid syncronizing\n\trandStagger := time.Duration(uint64(rand.Int63()) % uint64(stagger))\n\tselect {\n\tcase <-time.After(randStagger):\n\tcase <-stop:\n\t\treturn\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-C:\n\t\t\tf()\n\t\tcase <-stop:\n\t\t\treturn\n\t\t}\n\t}\n}", "func GoNamed(ctx Context, name string, f func(ctx Context)) {\n\tstate := getState(ctx)\n\tstate.dispatcher.newNamedCoroutine(ctx, name, f)\n}", "func (g *Glimit) Run(f func()) {\n\tg.c <- struct{}{}\n\tgo func() {\n\t\tf()\n\t\t<-g.c\n\t}()\n}", "func (w *WaitGroup) MultiGo(n int, f func()) {\n\tif n <= 0 {\n\t\tpanic(\"WaitGroup.MultiGo(): n must be a positive integer\")\n\t}\n\n\tw.wg.Add(n)\n\tfor i := 0; i < n; i++ {\n\t\tgo w.do(f)\n\t}\n}", "func (cl ConcurrencyLimit) Exec(fn func()) {\n\tcl <- struct{}{}\n\tfn()\n\t<-cl\n}", "func (g *Group) Go(f func() error, index int) {\n\tg.wg.Add(1)\n\tgo func() {\n\t\tdefer g.wg.Done()\n\t\tif g.bucket != nil {\n\t\t\t// Wait for token\n\t\t\tselect {\n\t\t\tcase <-g.bucket:\n\t\t\t\tdefer func() {\n\t\t\t\t\t// Put back token..\n\t\t\t\t\tg.bucket <- struct{}{}\n\t\t\t\t}()\n\t\t\tcase <-g.ctxCancel:\n\t\t\t\tif len(g.errs) > index {\n\t\t\t\t\tatomic.CompareAndSwapInt64(&g.firstErr, -1, int64(index))\n\t\t\t\t\tg.errs[index] = g.ctxErr()\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err := f(); err != nil {\n\t\t\tif len(g.errs) > index {\n\t\t\t\tatomic.CompareAndSwapInt64(&g.firstErr, -1, int64(index))\n\t\t\t\tg.errs[index] = err\n\t\t\t}\n\t\t\tif g.cancel != nil {\n\t\t\t\tg.cancel()\n\t\t\t}\n\t\t}\n\t}()\n}", "func (c *Concurrent) Call(function interface{}, params ...interface{}) error {\n\n\tif c.HasError() {\n\t\treturn c.GetLastError()\n\t}\n\n\tif c.closeSignal {\n\t\treturn ErrVChanClosed\n\t}\n\n\tf := reflect.TypeOf(function)\n\n\t// fucntion callable validate\n\tif f.Kind() != reflect.Func {\n\t\treturn fmt.Errorf(\"Concurrent-handler must be a callable func\")\n\t}\n\n\tfin := f.NumIn()\n\tfout := f.NumOut()\n\n\t// params validate\n\tif fin > len(params) {\n\t\treturn fmt.Errorf(\"Call function <%s> with too few input arguments(%d), need %d\", function, len(params), fin)\n\t}\n\tin := make([]reflect.Value, len(params))\n\tfor i := 0; i < len(params); i++ {\n\t\tin[i] = reflect.ValueOf(params[i])\n\t}\n\n\t// allocate thread\n\tc.semaphore.P()\n\tgo func(ticket uint64) {\n\t\tdefer c.semaphore.V() // free thread\n\t\tvals := reflect.ValueOf(function).Call(in)\n\t\tif fout != len(vals) {\n\t\t\tc.AddError(fmt.Errorf(\"The number of return values does not match\"))\n\t\t\treturn\n\t\t}\n\t\trets := make([]interface{}, fout)\n\t\tfor i, v := range vals {\n\t\t\trets[i] = v.Interface()\n\t\t}\n\t\tif !c.orderSignal {\n\t\t\tc.values <- rets\n\t\t\treturn\n\t\t}\n\t\tc.cond.L.Lock()\n\t\tdefer func() {\n\t\t\tc.cond.L.Unlock()\n\t\t\tc.cond.Broadcast()\n\t\t}()\n\t\tfor ticket != c.finTicket {\n\t\t\tc.cond.Wait()\n\t\t}\n\t\tc.values <- rets\n\t\tc.finTicket++\n\t}(c.totalTicket)\n\tc.totalTicket++\n\treturn nil\n}", "func other_wait() {\r\n\t// variabel untuk waitgroup\r\n\tvar wait sync.WaitGroup\r\n\r\n\tgoRoutines := 5\r\n\r\n\t// tambah sejumlah 5 goroutine\r\n\twait.Add(goRoutines)\r\n\r\n\tfor i := 0; i < goRoutines; i++ {\r\n\t\tgo func(goRoutineID int) {\r\n\t\t\tfmt.Printf(\"ID:%d: Hello goroutines!\\n\", goRoutineID)\r\n\t\t\twait.Done()\r\n\t\t}(i) // parameter goRoutineID\r\n\t}\r\n\r\n\twait.Wait()\r\n}", "func (client *BaseClient) Go(\n\tname string,\n\targs []reflect.Value,\n\tsettings *InvokeSettings,\n\tcallback Callback) {\n\tgo func() {\n\t\tdefer client.fireErrorEvent(name, nil)\n\t\tcallback(client.Invoke(name, args, settings))\n\t}()\n}", "func (vm *ChaincodeVM) callFunction(funcnum int, debug Dumper, extraArgs ...Value) (Value, error) {\n\tvar retval Value\n\tif funcnum <= vm.infunc || funcnum >= len(vm.functions) {\n\t\treturn retval, vm.runtimeError(newRuntimeError(\"invalid function number (no recursion allowed)\"))\n\t}\n\n\tchildvm, err := vm.CreateForFunc(funcnum)\n\tif err != nil {\n\t\treturn retval, vm.runtimeError(err)\n\t}\n\tfor _, e := range extraArgs {\n\t\terr := childvm.stack.Push(e)\n\t\tif err != nil {\n\t\t\treturn retval, vm.runtimeError(err)\n\t\t}\n\t}\n\terr = childvm.Run(debug)\n\t// no matter what, we want the history\n\tvm.history = append(vm.history, childvm.history...)\n\tif err != nil {\n\t\treturn retval, vm.runtimeError(err)\n\t}\n\t// we've called the child function, now get back its return value\n\tretval, err = childvm.stack.Pop()\n\tif err != nil {\n\t\treturn retval, vm.runtimeError(err)\n\t}\n\treturn retval, nil\n}", "func main() {\n\tgo println(\"goroutine message\")\n\n\tprintln(\"main function message\")\n}", "func callMe(routine int, task *pooler.Task) {\n\tfmt.Printf(\"<< Goroutine %d is done with task %s\\n\", routine, task.ID())\n}", "func startPipelineFunction(numbers chan<- int) {\n\tfor i := 1; i <= 10; i++ {\n\t\tnumbers <- i\n\t}\n\tclose(numbers)\n}", "func main() {\n\n\t// Calling Goroutine\n\tgo display(\"Welcome\")\n\n\t// Calling normal function\n\tdisplay(\"Azures S/U/C\")\n\n\tfmt.Println(\"Welcome!! to Main function\")\n\n\t// Creating Anonymous Goroutine\n\tgo func() {\n\t\tfmt.Println(\"Welcome!! to Azures\")\n\t}()\n\n\ttime.Sleep(1 * time.Second) // let the other goroutine time for execute.\n\tfmt.Println(\"GoodBye!! to Main function\")\n}", "func testfunctions(){\n\t// Test Go Channels\n\tchannel_var := make(chan string)\n\t\n\t// Test GoRoutine\n\tgo mygoroutine(channel_var)\n\tfmt.Println(\"This is after calling goroutine.\")\n\ttime.Sleep(2*time.Second)\n\n\t//testdata := [...] string {\"rak\",\"raj\",\"ram\"}\n\t//channel_var <- \"Rakesh\" //testdata\n\t\n\t// Receive data from string channel\n\tchan_data:=<-channel_var\n\n\tfmt.Println(\"Got from Channel: \",chan_data)\n\n\t// Multiple return values from function\n\ta,b,c := multi_return()\n\tfmt.Println(\"Multi-Return-Values:\",a,b,c)\n}", "func parallelize(functions ...func()) {\n\n\t//New WaitGroup for handle goRoutines\n\tvar waitGroup sync.WaitGroup\n\n\t//Add length of goRoutines to run\n\twaitGroup.Add(len(functions))\n\n\t//End of Functions wait for goRoutines to finish=(functionsGoRoutines.length==0)\n\tdefer waitGroup.Wait()\n\n\t//Foreach of functions to execute in goRoutines\n\tfor _, function := range functions {\n\t\tgo func(copy func()) {\n\n\t\t\t//functionsGoRoutines.length -1\n\t\t\tdefer waitGroup.Done()\n\t\t\tcopy()\n\t\t}(function)\n\t}\n}", "func QueueFunctionCalls(c *net.Conn, rate int64, TTL time.Duration, main *sync.WaitGroup) {\n\tdefer main.Done()\n\n\tvar sub sync.WaitGroup\n\tdone := make(chan bool)\n\n\tticker := time.NewTicker(time.Duration(int64(time.Second) / rate))\n\tdefer ticker.Stop()\n\n\tgo func() {\n\t\ttime.Sleep(TTL)\n\t\tdone <- true\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\tticker.Stop()\n\t\t\tsub.Wait()\n\t\t\tlog.Println(\"[DEBUG] Closing connection...\")\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tselect {\n\t\t\tcase moduleID := <-moduleIDs:\n\t\t\t\tsub.Add(1)\n\t\t\t\tgo FunctionCall(c, &sub, moduleID)\n\t\t\t\tgo func() {\n\t\t\t\t\tmoduleIDs <- moduleID\n\t\t\t\t}()\n\t\t\t\t// fmt.Println(\"finished one fn call\")\n\t\t\tdefault:\n\t\t\t\t// fmt.Println(\"end of first loop\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func goroutine(c echo.Context) error {\n\tpprof.Handler(\"goroutine\").ServeHTTP(c.Response().Writer, c.Request())\n\treturn nil\n}", "func (g *Group) Go(fn func() error) {\n\tselect {\n\tcase <-g.ctx.Done():\n\t\treturn\n\tcase g.limiter <- struct{}{}:\n\t}\n\n\tg.parent.Go(func() error {\n\t\terr := fn()\n\n\t\tselect {\n\t\tcase <-g.limiter:\n\t\tcase <-g.ctx.Done():\n\t\t}\n\t\treturn err\n\t})\n}", "func goTest() {\n\t// nova goroutine-a se pravi sa go, prakticno thread novi, goroutine imaju isti adresni prostor\n\tgo pljuni(\"Go\")\n\tpljuni(\"Ne go\")\n}", "func (t TaskFunc) Run() { t() }", "func New(concurrency int) Async {\n\ta := &async{}\n\ta.funcs = make(chan func() error, concurrency)\n\ta.wg.Add(concurrency)\n\tfor i := 0; i < concurrency; i++ {\n\t\tgo func() {\n\t\t\tdefer a.wg.Done()\n\t\t\tfor f := range a.funcs {\n\t\t\t\tif err := f(); err != nil {\n\t\t\t\t\ta.mu.Lock()\n\t\t\t\t\ta.err = err\n\t\t\t\t\ta.mu.Unlock()\n\t\t\t\t\treturn // stopping processing if we get an error\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn a\n}", "func CallVal(f func() interface{}) interface{} {\n\tcheckRun()\n\trespChan := make(chan interface{})\n\tcallQueue <- func() {\n\t\trespChan <- f()\n\t}\n\treturn <-respChan\n}", "func New(callable func() error, duration time.Duration) (func(), <-chan error) {\n\tvar (\n\t\tcalled = make(chan struct{})\n\t\terrChan = make(chan error)\n\t)\n\n\tgo func() {\n\t\tt := time.NewTimer(duration)\n\t\tt.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-called:\n\t\t\t\tt.Reset(duration)\n\t\t\tcase <-t.C:\n\t\t\t\tgo func() {\n\t\t\t\t\tif err := callable(); err != nil {\n\t\t\t\t\t\terrChan <- err\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn func() { go func() { called <- struct{}{} }() }, errChan\n}", "func (o *Group) Go(f Grouper) {\n\to.wg().Add(1)\n\tgo func() {\n\t\tdefer o.wg().Done()\n\t\tf.Run(o)\n\t\to.Cancel()\n\t}()\n}", "func (g *Group) Go(f func() error) {\n\t// ...\n}", "func (f *Function) Invoke(msg *runtime.Message) (*runtime.Message, error) {\n\titem, err := f.pool.BorrowObject(context.Background())\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tfl := item.(*funclet)\n\tres, err := fl.handle(msg)\n\tif err != nil {\n\t\tf.log.WithError(err).Error(\"Failed to talk with function instance\")\n\t\terr1 := f.pool.InvalidateObject(context.Background(), item)\n\t\tif err1 != nil {\n\t\t\tfl.Close()\n\t\t\tf.log.WithError(err).Error(\"Failed to invalidate function instance\")\n\t\t}\n\t\treturn nil, errors.Trace(err)\n\t}\n\tf.pool.ReturnObject(context.Background(), item)\n\treturn res, nil\n\n}", "func (c *Client) Go(serviceMethod string, args, reply interface{}, done chan *Call) *Call {\n\tif done == nil {\n\t\tdone = make(chan *Call, 10)\n\t} else if cap(done) == 0 {\n\t\tlog.Panic(\"rpc client: done channel is unbuffered\")\n\t}\n\tcall := &Call{\n\t\tServiceMethod: serviceMethod,\n\t\tArgs: args,\n\t\tReply: reply,\n\t\tDone: done,\n\t}\n\tc.send(call)\n\treturn call\n}", "func (m *GoRoutines) RunWithRestart(c context.Context, name string, fn func(ctx context.Context)) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tg := &GoRoutine{\n\t\tctx: c,\n\t\tName: name,\n\t\tFunc: fn,\n\t\tActive: true,\n\t\tRestart: true,\n\t}\n\tm.status = append(m.status, g)\n\tm.exec(g)\n}", "func (g *Group) Go(runnable func() error) *Task {\n\ttask := &Task{\n\t\tgroup: g,\n\t\tdone: make(chan struct{}),\n\t}\n\ttask.start(runnable)\n\treturn task\n}", "func runInterchangebly(f1 func(), f2 func(), timer *time.Timer) {\n\tf1()\n\t<-timer.C\n\tf2()\n\tfmt.Println(\"session expired, for next iteration you need to start brand new session\")\n}", "func (p *Pipeline) Go(f func()) {\n\tp.wait.Add(1)\n\tgo func() {\n\t\tdefer p.wait.Done()\n\t\texc.Try(f).Catch(&exc.Exception{}, func(e exc.Throwable) {\n\t\t\tp.mut.Lock()\n\t\t\tdefer p.mut.Unlock()\n\t\t\tif p.err == nil {\n\t\t\t\tp.err = e\n\t\t\t\tclose(p.done)\n\t\t\t}\n\t\t}).Error()\n\t}()\n}", "func (j *Job) Do(jobFun interface{}, params ...interface{}) error {\n\tif j.err != nil {\n\t\treturn j.err\n\t}\n\n\ttyp := reflect.TypeOf(jobFun)\n\tif typ.Kind() != reflect.Func {\n\t\treturn ErrNotAFunction\n\t}\n\tfname := getFunctionName(jobFun)\n\tj.funcs[fname] = jobFun\n\tj.fparams[fname] = params\n\tj.jobFunc = fname\n\n\tnow := time.Now()\n\tif !j.from.IsZero() && j.from.After(now) {\n\t\tj.nextRun = j.from\n\t\treturn nil\n\t}\n\n\t// without Immediately()\n\tif j.nextRun.IsZero() {\n\t\tj.nextRun = now.Add(j.interval)\n\t}\n\n\treturn nil\n}", "func (e *Endpoint) Call(function string, args interface{}, reply interface{}) error {\n\tcall := <-e.Go(function, args, reply, make(chan *rpc.Call, 1)).Done\n\treturn call.Error\n}", "func main() {\n\tgodur, _ := time.ParseDuration(\"10ms\")\n\t// we are telling our application it can only use 2 processes\n\truntime.GOMAXPROCS(2)\n\n\t// anonamous function\n\tgo func() {\n\t\tfor i := 0; i < 100; i++ {\n\t\t\tprintln(\"Hello\")\n\t\t\ttime.Sleep(godur)\n\t\t}\n\t}()\n\n\t// anonamous function\n\tgo func() {\n\t\tfor i := 0; i < 100; i++ {\n\t\t\tprintln(\"World\")\n\t\t\ttime.Sleep(godur)\n\t\t}\n\t}()\n\n\t// without a sleep the function will close out before the go routines has a chance to finish\n\tdur, _ := time.ParseDuration(\"1s\")\n\ttime.Sleep(dur)\n}", "func RepeatFunc(ctx context.Context, fn func() interface{}) <-chan interface{} {\n\tstream := make(chan interface{})\n\n\tgo func() {\n\t\tdefer close(stream)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase stream <- fn():\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn stream\n}", "func main() {\n\tn := 10 // number of functions to spawn\n\tc := make(chan int) // unbuffered integer channel\n\tdone := make(chan bool) // semaphore channel\n\n\tfor i := 0; i < n; i++ {\n\t\tgo func(n int) {\n\t\t\tfor i := 0 + (n*10); i < 10 +(n*10); i++ {\n\t\t\t\tc <- i\n\t\t\t}\n\t\t\tdone <- true\n\t\t}(i)\n\t}\n\n\tgo func() {\n\t\tfor i := 0; i < n; i++ {\n\t\t\t<-done\n\t\t}\n\t\tclose(c)\n\t}()\n\n\tfor n := range c {\n\t\tfmt.Println(n)\n\t}\n}", "func (m *GoRoutines) Exec(c context.Context, name string, fn func(ctx context.Context)) {\n\tg := &GoRoutine{\n\t\tctx: c,\n\t\tName: name,\n\t\tFunc: fn,\n\t\tActive: true,\n\t\tRestart: false,\n\t}\n\tm.exec(g)\n}", "func (c *Client) Go(ctx context.Context, method string, result interface{}, done chan Call, args ...interface{}) Call {\n\tswitch {\n\tcase done == nil:\n\t\tdone = make(chan Call, 1)\n\tcase cap(done) == 0:\n\t\tpanic(\"wsrpc: done channel is unbuffered\")\n\t}\n\n\tcall := &call{\n\t\tdone: done,\n\t\tresult: result,\n\t}\n\tif ctx.Err() != nil {\n\t\tcall.err = ctx.Err()\n\t\tcall.finalize()\n\t\treturn call\n\t}\n\tid := atomic.AddUint32(&c.atomicSeq, 1)\n\tif id == 0 {\n\t\tid = atomic.AddUint32(&c.atomicSeq, 1)\n\t}\n\tc.callMu.Lock()\n\tif c.calls != nil {\n\t\tc.calls[id] = call\n\t} else {\n\t\tc.callMu.Unlock()\n\t\tcall.err = c.err\n\t\tcall.finalize()\n\t\treturn call\n\t}\n\tc.callMu.Unlock()\n\n\treq := &request{\n\t\tJSONRPC: \"2.0\",\n\t\tMethod: method,\n\t\tParams: args,\n\t\tID: id,\n\t\tctx: ctx,\n\t}\n\tvar err error\n\tselect {\n\tcase c.send <- req:\n\tcase <-ctx.Done():\n\t\terr = ctx.Err()\n\tcase <-c.errc:\n\t\terr = c.err\n\t}\n\tif err != nil {\n\t\tc.callMu.Lock()\n\t\tdelete(c.calls, id)\n\t\tc.callMu.Unlock()\n\t\t// call was not sent, safe to set and finalize error\n\t\tcall.err = err\n\t\tcall.finalize()\n\t}\n\treturn call\n}", "func safeCall(ctx context.Context, name string, timeout, gracePeriod time.Duration, ph panicHandler, f func(ctx context.Context)) error {\n\t// Two goroutines race for a token below.\n\t// The main goroutine attempts to take a token when it sees timeout\n\t// or context cancellation. If it successfully takes a token, safeCall\n\t// returns immediately without waiting for f to finish, and ph will\n\t// never be called.\n\t// A background goroutine attempts to take a token when it finishes\n\t// calling f. If it successfully takes a token, it calls recover and\n\t// ph (if it recovered from a panic). Until the goroutine finishes\n\t// safeCall will not return.\n\n\tvar token uintptr\n\t// takeToken returns true if it is called first time.\n\ttakeToken := func() bool {\n\t\treturn atomic.CompareAndSwapUintptr(&token, 0, 1)\n\t}\n\n\tdone := make(chan struct{}) // closed when the background goroutine finishes\n\n\t// Start a background goroutine that calls into the user code.\n\tgo func() {\n\t\tdefer close(done)\n\n\t\tdefer func() {\n\t\t\t// Always call recover to avoid crashing the process.\n\t\t\tval := recover()\n\n\t\t\t// If the main goroutine already returned from safeCall, do not call ph.\n\t\t\tif !takeToken() {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If we recovered from a panic, call ph. Note that we must call\n\t\t\t// ph on this goroutine to include the panic location in the\n\t\t\t// stack trace.\n\t\t\tif val != nil {\n\t\t\t\tph(val)\n\t\t\t}\n\t\t}()\n\n\t\tctx, cancel := context.WithTimeout(ctx, timeout)\n\t\tdefer cancel()\n\t\tf(ctx)\n\t}()\n\n\t// Block returning from safeCall if the background goroutine is still calling ph.\n\tdefer func() {\n\t\tif !takeToken() {\n\t\t\t<-done\n\t\t}\n\t}()\n\n\t// Allow f to clean up after timeout for gracePeriod.\n\ttm := time.NewTimer(timeout + gracePeriod)\n\tdefer tm.Stop()\n\n\tselect {\n\tcase <-done:\n\t\treturn nil\n\tcase <-tm.C:\n\t\treturn errors.Errorf(\"%s did not return on timeout\", name)\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func Exec(f func() error) error {\n\tdone := make(chan error, 1)\n\tgfxfunc <- func() {\n\t\tdone <- f()\n\t}\n\terr := <-done\n\treturn err\n}", "func (f EventHandlerFunc) Call(ctx context.Context, jobId string) error {\n\treturn f(ctx, jobId)\n}", "func verOne() {\n\tsleepyGopher := func(id int) {\n\t\t// sleep, to demonstrate the overhead of a routine that takes time. \n\t\ttime.Sleep(3 * time.Second)\n\t\tfmt.Printf(\"...%v snore...\\n\", id)\n\t}\n\n\tfmt.Println(\"Running code from listing 30.1-30.3\")\n\n\tfor i := 0; i < 5; i++ {\n\t\tgo sleepyGopher(i)\n\t}\n\t// Waiting 4 seconds for the goroutines to finish - obviously not the best.\n\ttime.Sleep(4 * time.Second)\n}", "func Go(name string, f func()) {\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif i := recover(); i != nil {\n\t\t\t\t// TODO(maruel): No allocation in recover handling.\n\t\t\t\tbuf := make([]byte, 2048)\n\t\t\t\tn := runtime.Stack(buf, false)\n\t\t\t\tif n != 0 {\n\t\t\t\t\tbuf = buf[:n-1]\n\t\t\t\t}\n\t\t\t\tgotPanic <- fmt.Errorf(\"%s panicked: %s\\nStack: %s\", name, i, buf)\n\t\t\t}\n\t\t}()\n\t\tf()\n\t}()\n}", "func GoroutineTest(s string) {\n\tfor i := 0; i < 3; i++ {\n\t\ttime.Sleep(time.Second)\n\t\tfmt.Println(s, i)\n\t}\n}", "func (c *OSContext) Go(t *testing.T, fn func()) {\n\tt.Helper()\n\terrCh := make(chan error, 1)\n\tgo func() {\n\t\tteardown, err := c.Set()\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\t\tdefer teardown(t)\n\t\tclose(errCh)\n\t\tfn()\n\t}()\n\n\tif err := <-errCh; err != nil {\n\t\tt.Fatalf(\"%+v\", err)\n\t}\n}", "func Run(routine func()) {\n\tdoRun(context.Background(), func(context.Context) {\n\t\troutine()\n\t})\n}", "func (f Func) Call(functionName string, payload []byte, contentType StoreContentType) (<-chan FuncResponse, error) {\n\n\tresponseChan := make(chan FuncResponse)\n\tgo f.parseRawFuncResponse(functionName, payload, contentType, responseChan)\n\treturn responseChan, nil\n\n}", "func generateGoroutines(done chan bool, numGoroutines int) {\n\tfor i := 0; i < numGoroutines; i++ {\n\t\tgo func(done chan bool) {\n\t\t\t<-done\n\t\t}(done)\n\t}\n}", "func repeatFn(done <-chan interface{}, fn func() interface{}) <-chan interface{} {\n\tvalueStream := make(chan interface{})\n\tgo func(){\n\t\tdefer close(valueStream)\n\t\t// defer log.Println(\"broek loop\")\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\tcase valueStream<-fn():\n\t\t\t}\n\t\t}\n\n\t}()\n\treturn valueStream\n}", "func (p *Proxy) do(fn doFunc) error {\n\tc, err := grpc.Dial(p.host, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Close()\n\trlc := services.NewReleaseServiceClient(c)\n\treturn fn(rlc)\n}", "func simulate(c echo.Context) error {\n\tsetInterval(func() {\n\n\t\ts1 := rand.NewSource(time.Now().UnixNano())\n\t\tr1 := rand.New(s1)\n\n\t\tnewVisitsData := visitsData{\n\t\t\tPages: r1.Intn(100),\n\t\t\tCount: r1.Intn(100),\n\t\t}\n\n\t\tclient.Trigger(\"visitorsCount\", \"addNumber\", newVisitsData)\n\n\t}, 2500, true)\n\n\treturn c.String(http.StatusOK, \"Simulation begun\")\n}" ]
[ "0.63778317", "0.6130507", "0.61002207", "0.60362846", "0.59871405", "0.58630985", "0.58374625", "0.5799728", "0.57535833", "0.56970245", "0.5635223", "0.5628486", "0.56167054", "0.5596828", "0.55732346", "0.55711", "0.55711", "0.55590457", "0.55224115", "0.55224115", "0.54937226", "0.5445255", "0.5432504", "0.5427438", "0.54227424", "0.54182905", "0.5366979", "0.536128", "0.5346385", "0.53274363", "0.5316976", "0.5291113", "0.52024925", "0.51940864", "0.5190845", "0.518569", "0.5177494", "0.51647145", "0.51609844", "0.51609844", "0.5157891", "0.51534176", "0.5134722", "0.51250756", "0.5112051", "0.5108706", "0.5097665", "0.5088253", "0.50759417", "0.5046672", "0.50420046", "0.50375044", "0.50364345", "0.50173235", "0.50171685", "0.5004342", "0.50007665", "0.4998963", "0.4983571", "0.498278", "0.49765164", "0.49667376", "0.49387258", "0.49254498", "0.49083775", "0.48928633", "0.48825255", "0.48604196", "0.48492745", "0.4808042", "0.47982493", "0.479678", "0.478303", "0.47704124", "0.4753267", "0.47524157", "0.47504085", "0.47319424", "0.47276643", "0.47230816", "0.47136745", "0.47046423", "0.47045273", "0.46961865", "0.46845022", "0.46806964", "0.46806353", "0.4674617", "0.46698368", "0.4666893", "0.46536702", "0.46467602", "0.46456757", "0.46412554", "0.4640806", "0.4635671", "0.46062455", "0.460175", "0.4590649", "0.45875856" ]
0.5199745
33
Cancel cancels all goroutines in group. Note: context cancellation error can be returned by Wait().
func (s *Supervisor) Cancel() { s.cancel() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *ServerGroup) Cancel() {\n\ts.ctxCancel()\n}", "func (g *LogGroup) Cancel() {\n\tg.group.Cancel()\n}", "func (g *Group) Cancel() {\n\tg.cancel()\n}", "func (g *Group) Cancel() {\n\tg.initOnce.Do(g.init)\n\tg.cancel()\n}", "func (segs *httpSubsegments) Cancel() {\n\tsegs.mu.Lock()\n\tdefer segs.mu.Unlock()\n\n\tif segs.dnsCtx != nil {\n\t\tsegs.dnsSeg.AddError(context.Canceled)\n\t\tsegs.dnsSeg.Close()\n\t\tsegs.dnsCtx, segs.dnsSeg = nil, nil\n\t}\n\tif segs.dialCtx != nil {\n\t\tsegs.dialSeg.AddError(context.Canceled)\n\t\tsegs.dialSeg.Close()\n\t\tsegs.dialCtx, segs.dialSeg = nil, nil\n\t}\n\tif segs.tlsCtx != nil {\n\t\tsegs.tlsSeg.AddError(context.Canceled)\n\t\tsegs.tlsSeg.Close()\n\t\tsegs.tlsCtx, segs.tlsSeg = nil, nil\n\t}\n\tif segs.connCtx != nil {\n\t\tsegs.connSeg.AddError(context.Canceled)\n\t\tsegs.connSeg.Close()\n\t\tsegs.connCtx, segs.connSeg = nil, nil\n\t}\n\tif segs.reqCtx != nil {\n\t\tsegs.reqSeg.AddError(context.Canceled)\n\t\tsegs.reqSeg.Close()\n\t\tsegs.reqCtx, segs.reqSeg = nil, nil\n\t}\n}", "func (p *unlimitedPool) Cancel() {\n\n\terr := &ErrCancelled{s: errCancelled}\n\tp.closeWithError(err)\n}", "func With_cancel(parent *Group) option {\n\treturn func(o *Group) {\n\t\tif o.Context != nil {\n\t\t\tpanic(\"context already set\")\n\t\t}\n\t\tif parent == nil {\n\t\t\tpanic(\"parent is nil\")\n\t\t}\n\t\to.Context, o.CancelFunc = context.WithCancel(parent)\n\t\to.parent = parent\n\t}\n}", "func CtxCancelIfCanceled(f context.CancelFunc, ctxCanceler context.Context) chan struct{} {\n\tquitCh := make(chan struct{})\n\tgo func() {\n\t\tselect {\n\t\tcase <-quitCh:\n\t\tcase <-ctxCanceler.Done():\n\t\t\tf()\n\t\t}\n\t}()\n\treturn quitCh\n}", "func (wp *Pool) Cancel(key string) {\n\twp.workersLock.RLock()\n\tdefer wp.workersLock.RUnlock()\n\tfor _, w := range wp.workers {\n\t\tw.worker.Cancel(key)\n\t}\n}", "func (c *Context) Cancel() {\n\tif c.cancel != nil {\n\t\tc.cancel()\n\t}\n}", "func (c *context) Cancel() {\n\tc.cancel()\n}", "func TestCancel(t *testing.T) {\n\tvar (\n\t\tmu ctxsync.Mutex\n\t\twg sync.WaitGroup\n\t\terrWaiter error\n\t)\n\trequire.NoError(t, mu.Lock(context.Background()))\n\tctx, cancel := context.WithCancel(context.Background())\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tif errWaiter = mu.Lock(ctx); errWaiter != nil {\n\t\t\treturn\n\t\t}\n\t\tmu.Unlock()\n\t}()\n\tcancel()\n\twg.Wait()\n\tmu.Unlock()\n\t// Verify that we can still lock and unlock after the canceled attempt.\n\tif assert.NoError(t, mu.Lock(context.Background())) {\n\t\tmu.Unlock()\n\t}\n\t// Verify that Lock returned the expected non-nil error from the canceled\n\t// attempt.\n\tassert.True(t, errors.Is(errors.Canceled, errWaiter), \"expected errors.Canceled\")\n}", "func With_cancel_nowait(ctx context.Context) option {\n\treturn func(o *Group) {\n\t\tif o.Context != nil {\n\t\t\tpanic(\"context already set\")\n\t\t}\n\t\tif ctx == nil {\n\t\t\to.Context, o.CancelFunc = context.WithCancel(context.Background())\n\t\t\treturn\n\t\t}\n\t\to.Context, o.CancelFunc = context.WithCancel(ctx)\n\t}\n}", "func (impl *Impl) Cancel(ctx context.Context, rs *state.RunState, reasons []string) (*Result, error) {\n\tswitch status := rs.Status; {\n\tcase status == run.Status_STATUS_UNSPECIFIED:\n\t\terr := errors.Reason(\"CRITICAL: can't cancel a Run with unspecified status\").Err()\n\t\tcommon.LogError(ctx, err)\n\t\tpanic(err)\n\tcase status == run.Status_SUBMITTING:\n\t\t// Can't cancel while submitting.\n\t\treturn &Result{State: rs, PreserveEvents: true}, nil\n\tcase run.IsEnded(status):\n\t\tlogging.Debugf(ctx, \"skipping cancellation because Run is %s\", status)\n\t\treturn &Result{State: rs}, nil\n\t}\n\tcg, err := prjcfg.GetConfigGroup(ctx, rs.ID.LUCIProject(), rs.ConfigGroupID)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"prjcfg.GetConfigGroup\").Err()\n\t}\n\trs = rs.ShallowCopy()\n\t// make sure reasons are unique and doesn't contain empty reasons.\n\tuniqueReasons := stringset.NewFromSlice(reasons...)\n\tuniqueReasons.Del(\"\")\n\trs.CancellationReasons = uniqueReasons.ToSortedSlice()\n\tse := impl.endRun(ctx, rs, run.Status_CANCELLED, cg)\n\n\treturn &Result{\n\t\tState: rs,\n\t\tSideEffectFn: se,\n\t}, nil\n}", "func (s serverImpl) Cancel(goCtx context.Context, req *ecocredit.MsgCancel) (*ecocredit.MsgCancelResponse, error) {\n\tctx := types.UnwrapSDKContext(goCtx)\n\tstore := ctx.KVStore(s.storeKey)\n\tholderAddr, err := sdk.AccAddressFromBech32(req.Holder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, credit := range req.Credits {\n\n\t\t// Check that the batch that were trying to cancel credits from\n\t\t// exists\n\t\tdenom := batchDenomT(credit.BatchDenom)\n\t\tif !s.batchInfoTable.Has(ctx, orm.RowID(denom)) {\n\t\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrapf(\"%s is not a valid credit batch denom\", denom)\n\t\t}\n\n\t\t// Remove the credits from the total_amount in the batch and add\n\t\t// them to amount_cancelled\n\t\tvar batchInfo ecocredit.BatchInfo\n\t\terr := s.batchInfoTable.GetOne(ctx, orm.RowID(denom), &batchInfo)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tclassInfo, err := s.getClassInfo(ctx, batchInfo.ClassId)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmaxDecimalPlaces := classInfo.CreditType.Precision\n\n\t\t// Parse the amount of credits to cancel, checking it conforms\n\t\t// to the precision\n\t\ttoCancel, err := math.NewPositiveFixedDecFromString(credit.Amount, maxDecimalPlaces)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Remove the credits from the balance of the holder and the\n\t\t// overall supply\n\t\terr = subtractTradableBalanceAndSupply(store, holderAddr, denom, toCancel)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttotalAmount, err := math.NewPositiveFixedDecFromString(batchInfo.TotalAmount, maxDecimalPlaces)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttotalAmount, err = math.SafeSubBalance(totalAmount, toCancel)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbatchInfo.TotalAmount = totalAmount.String()\n\n\t\tamountCancelled, err := math.NewNonNegativeFixedDecFromString(batchInfo.AmountCancelled, maxDecimalPlaces)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tamountCancelled, err = amountCancelled.Add(toCancel)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbatchInfo.AmountCancelled = amountCancelled.String()\n\n\t\tif err = s.batchInfoTable.Update(ctx, &batchInfo); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Emit the cancellation event\n\t\terr = ctx.EventManager().EmitTypedEvent(&ecocredit.EventCancel{\n\t\t\tCanceller: req.Holder,\n\t\t\tBatchDenom: string(denom),\n\t\t\tAmount: toCancel.String(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tctx.GasMeter().ConsumeGas(gasCostPerIteration, \"cancel ecocredits\")\n\t}\n\n\treturn &ecocredit.MsgCancelResponse{}, nil\n}", "func channelCancellation(stop <-chan struct{}) {\n\n\t// Create a cancel context for handling the stop signal.\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// If a signal is received on the stop channel, cancel the\n\t// context. This will propagate the cancel into the p.Run\n\t// function below.\n\tgo func() {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\tcancel()\n\t\tcase <-ctx.Done():\n\t\t}\n\t}()\n\n\t// Imagine a function that is performing an I/O operation that is\n\t// cancellable.\n\tfunc(ctx context.Context) error {\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, \"https://www.ardanlabs.com/blog/index.xml\", nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}(ctx)\n}", "func (b *Builder) Cancel(ctx context.Context, id string) error {\n\tb.mu.Lock()\n\tif j, ok := b.jobs[id]; ok && j.cancel != nil {\n\t\tj.cancel()\n\t}\n\tb.mu.Unlock()\n\treturn nil\n}", "func (k *xyzProvider) Cancel(context.Context, *pbempty.Empty) (*pbempty.Empty, error) {\n\t// TODO\n\treturn &pbempty.Empty{}, nil\n}", "func cancelworker(ctx context.Context, jobChan <-chan Job) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase job := <-jobChan:\n\t\t\tprocess(job)\n\t\t}\n\t}\n}", "func (c *canceler) Cancel(ctx context.Context, id string) error {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.cancelled[id] = time.Now().Add(5 * time.Minute)\n\tif sub, ok := c.subsciber[id]; ok {\n\t\tclose(sub)\n\t}\n\tc.clear()\n\treturn nil\n}", "func (i *Internal) CancelableCtx() context.Context {\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo func() {\n\t\tselect {\n\t\tcase <-*i.done:\n\t\tcase <-*i.Stopper:\n\t\t\tcancel()\n\t\t}\n\t}()\n\treturn ctx\n}", "func GracefulCancel(cancel func()) {\n\tquit := make(chan os.Signal, 1)\n\tsignal.Notify(quit, os.Interrupt)\n\t<-quit\n\n\tcancel()\n}", "func (c *Context) Cancel([]Node) (Status, error) {\n\tif c.cancel != nil {\n\t\tc.cancel()\n\t}\n\treturn Success, nil\n}", "func (j *Job) Cancel() {\n\tdefer j.recover()\n\n\tj.CancelFunc(j)\n\tj.tomb.Kill(nil)\n\tj.err = j.tomb.Wait()\n}", "func (c *MockedHTTPContext) Cancel(err error) {\n\tif c.MockedCancel != nil {\n\t\tc.MockedCancel(err)\n\t}\n}", "func (w *WaitTask) Cancel(_ *TaskContext) {\n\tw.cancelFunc()\n}", "func (i *inflight) Cancel() {\n\t// Lock after close to avoid deadlock\n\ti.Lock()\n\tdefer i.Unlock()\n\n\t// Clear the map\n\ti.operations = make(map[uint64]*logFuture)\n\n\t// Clear the list of committed\n\ti.committed = list.New()\n\n\t// Close the commmitCh\n\tclose(i.commitCh)\n\n\t// Reset indexes\n\ti.minCommit = 0\n\ti.maxCommit = 0\n}", "func (c *context) WithCancel() Context {\n\tcc, cancel := ctx.WithCancel(c)\n\n\treturn &context{\n\t\tcancel: cancel,\n\t\tparent: cc,\n\t\twaitGroup: c.waitGroup,\n\t}\n}", "func (p *googleCloudProvider) Cancel(context.Context, *empty.Empty) (*empty.Empty, error) {\n\treturn &empty.Empty{}, nil\n}", "func (p *googleCloudProvider) Cancel(context.Context, *empty.Empty) (*empty.Empty, error) {\n\treturn &empty.Empty{}, nil\n}", "func WithCancel(ctx Context) (Context, context.CancelFunc) {\n\tstdCtx, cancel := context.WithCancel(ctx.StdContext())\n\treturn withStdCancel(ctx, stdCtx), cancel\n}", "func (p *BoteaterServiceClient) CancelGroupInvitation(ctx context.Context, reqSeq int32, groupId string, contactIds []string) (err error) {\r\n var _args79 BoteaterServiceCancelGroupInvitationArgs\r\n _args79.ReqSeq = reqSeq\r\n _args79.GroupId = groupId\r\n _args79.ContactIds = contactIds\r\n var _result80 BoteaterServiceCancelGroupInvitationResult\r\n if err = p.Client_().Call(ctx, \"cancelGroupInvitation\", &_args79, &_result80); err != nil {\r\n return\r\n }\r\n switch {\r\n case _result80.E!= nil:\r\n return _result80.E\r\n }\r\n\r\n return nil\r\n}", "func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {\n\tctx, f := context.WithCancel(parent)\n\treturn ctx, f\n}", "func (p *Pipeline) Cancel() {\n\tp.cancel()\n}", "func (p *Pipeline) Cancel() {\n\tp.cancel()\n}", "func (t *Task) Cancel() {\n\tt.mutex.Lock()\n\tfor _, v := range t.cancelFns {\n\t\tv()\n\t}\n\tt.mutex.Unlock()\n}", "func (ci *CertificateIssuer) Cancel() {\n\tclose(ci.cancel)\n}", "func (c *Context) Canceled() <-chan struct{} {\n\tif c.Request == nil {\n\t\treturn nil\n\t}\n\treturn c.Request.Canceled()\n}", "func (c *canceler) Cancel() {\n\tc.cancel()\n}", "func (ctx *Context) ChildCancel() (Context, context.CancelFunc) {\n\tcopy := *ctx\n\tcancelCtx, cancel := context.WithCancel(ctx)\n\tcopy.Context = cancelCtx\n\treturn copy, cancel\n}", "func CancelOnExitContext() context.Context {\n\tctx, cancel := context.WithCancel(context.Background())\n\tOnCloseSignal(cancel)\n\treturn ctx\n}", "func (impl *Impl) Cancel(ctx context.Context, rs *state.RunState) (*Result, error) {\n\tswitch status := rs.Run.Status; {\n\tcase status == run.Status_STATUS_UNSPECIFIED:\n\t\terr := errors.Reason(\"CRITICAL: can't cancel a Run with unspecified status\").Err()\n\t\tcommon.LogError(ctx, err)\n\t\tpanic(err)\n\tcase status == run.Status_SUBMITTING:\n\t\tlogging.Debugf(ctx, \"Run cancellation can't be fulfilled at this time as Run is currently submitting.\")\n\t\t// Don't consume the events so that the RM executing the submission will\n\t\t// be able to read the Cancel events and attempt to cancel if the Run\n\t\t// failed to submit.\n\t\treturn &Result{State: rs, PreserveEvents: true}, nil\n\tcase run.IsEnded(status):\n\t\tlogging.Debugf(ctx, \"skip cancellation because Run has already ended.\")\n\t\treturn &Result{State: rs}, nil\n\t}\n\n\trs = rs.ShallowCopy()\n\tse := endRun(ctx, rs, run.Status_CANCELLED, impl.PM)\n\tif rs.Run.StartTime.IsZero() {\n\t\t// This run has never started but already gets a cancelled event.\n\t\trs.Run.StartTime = rs.Run.EndTime\n\t}\n\treturn &Result{\n\t\tState: rs,\n\t\tSideEffectFn: se,\n\t}, nil\n}", "func (s *Server) CtxCancel() {\n\tif s.ctxCancel != nil {\n\t\t(*s.ctxCancel)()\n\t}\n}", "func Cancel(w http.ResponseWriter, r *http.Request) {\n\terr := command.New(getFlags(r.URL.Query())).\n\t\tStopRunningCommand().\n\t\tError\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (oo *OmciCC) CancelRequestMonitoring(ctx context.Context) {\n\tlogger.Debugw(ctx, \"CancelRequestMonitoring entered\", log.Fields{\"device-id\": oo.deviceID})\n\too.mutexMonReq.RLock()\n\tfor k := range oo.monitoredRequests {\n\t\t//implement non-blocking channel send to avoid blocking on mutexMonReq later\n\t\tselect {\n\t\tcase oo.monitoredRequests[k].chSuccess <- false:\n\t\t\tlogger.Debugw(ctx, \"send cancellation on omciRespChannel\",\n\t\t\t\tlog.Fields{\"index\": k, \"device-id\": oo.deviceID})\n\t\tdefault:\n\t\t\tlogger.Debugw(ctx, \"cancellation could not be send on omciRespChannel (no receiver)\",\n\t\t\t\tlog.Fields{\"index\": k, \"device-id\": oo.deviceID})\n\t\t}\n\t}\n\too.mutexMonReq.RUnlock()\n}", "func cancelOnInterrupt(ctx context.Context, f context.CancelFunc) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tcase <-c:\n\t\t\tf()\n\t\t}\n\t}()\n}", "func cancelOnInterrupt(ctx context.Context, f context.CancelFunc) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tcase <-c:\n\t\t\tf()\n\t\t}\n\t}()\n}", "func CanceledContext() context.Context {\n\tdateline := time.Now().Add(time.Duration(1) * time.Millisecond)\n\tctx, cancel := context.WithDeadline(context.Background(), dateline)\n\tdefer cancel()\n\ttime.Sleep(time.Duration(2) * time.Millisecond)\n\treturn ctx\n}", "func (dc *Decompressor) Cancel(err error) {\n\tdc.pwr.CloseWithError(err)\n}", "func (b *Builder) Cancel() error {\n\t// acuire the lock\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\terr := kustomize.CleanDirectory(b.resourcesPath, b.action)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Stream) Cancel() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tif s.canceling {\n\t\treturn nil\n\t}\n\ts.canceling = true\n\tif err := s.performClose(true); err != nil {\n\t\ts.canceling = false\n\t\treturn err\n\t}\n\tif err := s.remove(); err != nil {\n\t\ts.canceling = false\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *CB) Cancel() error {\n\tif c.matchState(stCanceled) {\n\t\treturn errCanceled\n\t}\n\tif c.matchState(stFired) {\n\t\treturn errFired\n\t}\n\n\tc.setState(stCanceled)\n\treturn nil\n}", "func (_m *AsyncBR) Cancel() {\n\t_m.Called()\n}", "func (w *WithFunc[V]) Cancel() {\n\tw.mx.Lock()\n\tdefer w.mx.Unlock()\n\n\tif w.cancel == nil {\n\t\treturn\n\t}\n\n\tw._cancel()\n}", "func CICancel(pid interface{}, jobID int) (*gitlab.Job, error) {\n\tj, _, err := lab.Jobs.CancelJob(pid, jobID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn j, nil\n}", "func propagateCancellation(\n\tctx context.Context,\n\tallDone chan struct{},\n\tc CancellableRoundTripper,\n\treq *http.Request) {\n\t// If the context is not cancellable, there is nothing interesting we can do.\n\tcancelChan := ctx.Done()\n\tif cancelChan == nil {\n\t\treturn\n\t}\n\n\t// If the user closes allDone before the context is cancelled, we can return\n\t// immediately.\n\tselect {\n\tcase <-allDone:\n\t\treturn\n\n\tcase <-cancelChan:\n\t}\n\n\t// The context has been cancelled. Repeatedly cancel the HTTP request as\n\t// described above until the user closes allDone.\n\tfor {\n\t\tc.CancelRequest(req)\n\n\t\tselect {\n\t\tcase <-allDone:\n\t\t\treturn\n\n\t\tcase <-time.After(10 * time.Millisecond):\n\t\t}\n\t}\n}", "func (t *Task) Cancel() {\n log.Warnf(\"Cancelling task and all subsequent runs\")\n\n // Clear queue of subsequent runs\n t.runs.Clear()\n}", "func CancelWhenClosed(parent context.Context, w http.ResponseWriter) (context.Context, func()) {\n\tctx, cancel := context.WithCancel(parent)\n\n\tclose := w.(http.CloseNotifier).CloseNotify()\n\n\t// listen for the connection to close, trigger cancelation\n\tgo func() {\n\t\tselect {\n\t\tcase <-close:\n\t\t\tcancel()\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn ctx, cancel\n}", "func (drc *DummyRegistryClient) Cancel() {}", "func (ctx *RenderContext) Cancel() {\n\tif ctx == nil {\n\t\treturn\n\t}\n\tctx.ShaExistCache = map[string]bool{}\n\tif ctx.cancelFn == nil {\n\t\treturn\n\t}\n\tctx.cancelFn()\n}", "func (g *Group) Stop() {\n\tif g.Total > len(g.threads) {\n\t\tdefer close(g.chanStop)\n\t\tg.chanStop <- true\n\t}\n\n\tfor _, ok := range g.threads {\n\t\tok.Stop()\n\t}\n}", "func (this *service) CancelRequests() error {\n\tthis.log.Debug2(\"<grpc.service.mihome>CancelRequests{}\")\n\n\t// Cancel any streaming requests\n\tthis.Publisher.Emit(event.NullEvent)\n\n\t// Return success\n\treturn nil\n}", "func (s *ServerStatistics) cancel() {\n\ts.blacklisted.Store(false)\n\ts.backoffUntil.Store(time.Time{})\n\tselect {\n\tcase s.interrupt <- struct{}{}:\n\tdefault:\n\t}\n}", "func (w *FuncWaiter) Cancel() error {\n\tw.cancel <- struct{}{}\n\treturn nil\n}", "func (dhtm *dontHaveTimeoutMgr) CancelPending(ks []cid.Cid) {\n\tdhtm.lk.Lock()\n\tdefer dhtm.lk.Unlock()\n\n\t// Mark the wants as cancelled\n\tfor _, c := range ks {\n\t\tif pw, ok := dhtm.activeWants[c]; ok {\n\t\t\tpw.active = false\n\t\t\tdelete(dhtm.activeWants, c)\n\t\t}\n\t}\n}", "func propagateCancel(parent Context, child canceler) {\n\tif parent.Done() == nil {\n\t\treturn // parent is never canceled\n\t}\n\tif p, ok := parentCancelCtx(parent); ok {\n\t\tp.mu.Lock()\n\t\tif p.err != nil {\n\t\t\t// parent has already been canceled\n\t\t\tchild.cancel(false, p.err)\n\t\t} else {\n\t\t\tif p.children == nil {\n\t\t\t\tp.children = make(map[canceler]struct{})\n\t\t\t}\n\t\t\tp.children[child] = struct{}{}\n\t\t}\n\t\tp.mu.Unlock()\n\t} else {\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase <-parent.Done():\n\t\t\t\tchild.cancel(false, parent.Err())\n\t\t\tcase <-child.Done():\n\t\t\t}\n\t\t}()\n\t}\n}", "func (c *InspectOperationsCancelCall) Context(ctx context.Context) *InspectOperationsCancelCall {\n\tc.ctx_ = ctx\n\treturn c\n}", "func ContextWithCancel() (context.Context, context.CancelFunc) {\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tgo func() {\n\t\tstop := make(chan os.Signal, 1)\n\t\tsignal.Notify(stop, os.Interrupt, syscall.SIGTERM)\n\t\t<-stop\n\t\tlog.Print(\"[INFO] interrupt signal\")\n\t\tcancel()\n\t}()\n\n\treturn ctx, cancel\n}", "func (d *deferredErrGroupScheduler) Cancel(key string) error {\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\n\tif f, ok := d.m[key]; !ok {\n\t\treturn KeyNotFound\n\t} else {\n\t\tif f != nil {\n\t\t\tf()\n\t\t}\n\t}\n\n\tdelete(d.m, key)\n\treturn nil\n}", "func (e *Event) Cancel(err ...error) {\r\n\te.canceled = true\r\n\te.cancelFunc()\r\n\r\n\tif len(err) > 0 {\r\n\t\te.Err = fmt.Errorf(\"已取消:%w\", err[0])\r\n\t}\r\n}", "func (s *ServiceManager) cancelSignalers() {\n\t// We need to OnCancel all of the signalers to have them stop their routines and clean up\n\tfor _, value := range s.signalers {\n\t\t// This should not block. It's OK if it does, but it should not\n\t\tvalue.Cancel()\n\t}\n}", "func (r *Runtime) Cancel() { r.cancel() }", "func (c *Ctx) WithCancel() (cf context.CancelFunc) {\n\tc.netContext, cf = context.WithCancel(c.netContext)\n\treturn\n}", "func (c *Context) WithCancel(parent context.Context) *Context {\n\tc.parent = func() (context.Context, context.CancelFunc) { return context.WithCancel(parent) }\n\treturn c\n}", "func (s *FileSnapshotSink) Cancel() error {\n\t// Make sure close is idempotent\n\tif s.closed {\n\t\treturn nil\n\t}\n\ts.closed = true\n\n\t// Close the open handles\n\tif err := s.finalize(); err != nil {\n\t\ts.logger.Printf(\"[ERR] snapshot: Failed to finalize snapshot: %v\", err)\n\t\treturn err\n\t}\n\n\t// Attempt to remove all artifacts\n\treturn os.RemoveAll(s.dir)\n}", "func (w *watcher) waitForCancel() {\n\tselect {\n\tcase <-w.ctx.Done():\n\t\tw.Stop()\n\t}\n}", "func (c *Context) Terminate(err error) {\n\tif err == context.Canceled {\n\t\tc.Err <- nil // no errors, a legal cancel, already canceled\n\t\treturn\n\t}\n\tc.Err <- err\n\tc.Cancel()\n}", "func (s *supervisor) processKill() {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\t// Gather all context cancel functions.\n\tvar cancels []func()\n\tqueue := []*node{s.root}\n\tfor {\n\t\tif len(queue) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tcur := queue[0]\n\t\tqueue = queue[1:]\n\n\t\tcancels = append(cancels, cur.ctxC)\n\t\tfor _, c := range cur.children {\n\t\t\tqueue = append(queue, c)\n\t\t}\n\t}\n\n\t// Call all context cancels.\n\tfor _, c := range cancels {\n\t\tc()\n\t}\n}", "func (p *Pool) Stop() {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\tp.cancel()\n\tfor _, routine := range p.routines {\n\t\troutine.stop <- true\n\t}\n\tp.waitGroup.Wait()\n\tfor _, routine := range p.routines {\n\t\tclose(routine.stop)\n\t}\n}", "func (controller *playgroundController) Cancel(ctx context.Context, info *pb.CancelRequest) (*pb.CancelResponse, error) {\n\tpipelineId, err := uuid.Parse(info.PipelineUuid)\n\terrorMessage := \"Error during canceling the code processing\"\n\tif err != nil {\n\t\tlogger.Errorf(\"%s: Cancel(): pipelineId has incorrect value and couldn't be parsed as uuid value: %s\", info.PipelineUuid, err.Error())\n\t\treturn nil, cerrors.InvalidArgumentError(errorMessage, \"pipelineId has incorrect value and couldn't be parsed as uuid value: %s\", info.PipelineUuid)\n\t}\n\tif err := utils.SetToCache(controller.cacheService, pipelineId, cache.Canceled, true); err != nil {\n\t\treturn nil, cerrors.InternalError(errorMessage, \"Error during saving cancel flag value\")\n\t}\n\treturn &pb.CancelResponse{}, nil\n}", "func (eCtx *ExecutionContext) CancelTimer(repeating bool) {\n\tact := eCtx.currentStage().act\n\n\tstate := eCtx.pipeline.sm.GetState(eCtx.discriminator)\n\n\tif repeating {\n\t\tstate.RemoveTicker(act)\n\t} else {\n\t\tstate.RemoveTimer(act)\n\t}\n}", "func (s *CertificatesService) Cancel(id string) error {\n\t_, err := s.client.Post(\"/v1/certificates/\"+id+\"/cancel\", nil)\n\n\treturn err\n}", "func cancelCheck(ctx context.Context, pipelineId uuid.UUID, cancelChannel chan bool, cacheService cache.Cache) {\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tticker.Stop()\n\t\t\treturn\n\t\tcase _ = <-ticker.C:\n\t\t\tcancel, err := cacheService.GetValue(ctx, pipelineId, cache.Canceled)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif cancel.(bool) {\n\t\t\t\tcancelChannel <- true\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (p *pool) Stop() {\n\tp.cancel()\n\tp.waitGroup.Wait()\n}", "func (g *Group) Close() error {\n\tg.cancel()\n\tg.group.Wait()\n\treturn nil\n}", "func (manager *transportManager) cancelCtxCloseTransport() {\n\t// Grab the notification subscriber lock so new subscribers will not get added\n\t// without seeing the context cancel.\n\tmanager.notificationSubscriberLock.Lock()\n\n\t// Cancel the context the tryReconnect this closure will cause exits.\n\tmanager.cancelFunc()\n\n\t// Release the notification lock. Not doing so before we grab the livesOnce lock\n\t// can result in a deadlock if a redial is in process (since the redial needs to\n\t// grab the subscribers lock to notify them).\n\tmanager.notificationSubscriberLock.Unlock()\n\n\t// Take control of the connection lock to ensure all in-process operations have\n\t// completed.\n\tmanager.transportLock.Lock()\n\tdefer manager.transportLock.Unlock()\n\n\t// Close the current connection on exit\n\tdefer manager.transport.underlyingTransport().Close()\n}", "func (c *Context) WithCancel() *Context {\n\tnewCtx, cancel := context.WithCancel(c.ctx)\n\treturn &Context{ctx: newCtx, cancel: cancel}\n}", "func WaitForCancel() chan os.Signal {\n\tabort := make(chan os.Signal, 1)\n\tsignal.Notify(abort, syscall.SIGINT, syscall.SIGTERM)\n\treturn abort\n}", "func (g *GRPC) Stop() {\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\n\tif g == nil {\n\t\treturn\n\t}\n\n\tfor _, cancel := range g.cancelFuncs {\n\t\tcancel()\n\t}\n\n\tg.serv.GracefulStop()\n\n\tg.lis = nil\n}", "func (t *Transactions) Cancel(transactionKey string) {\n\tdefer t.lock.Unlock()\n\tt.lock.Lock()\n\tif t.closed {\n\t\treturn\n\t}\n\n\tresult, ok := t.pending[transactionKey]\n\tdelete(t.pending, transactionKey)\n\n\tif ok {\n\t\tclose(result)\n\t}\n}", "func (s *Stopper) WithCancelOnStop(ctx context.Context) (context.Context, func()) {\n\treturn s.withCancel(ctx, s.mu.sCancels, s.stopper)\n}", "func (r *ProjectsLocationsOperationsService) Cancel(name string, googlelongrunningcanceloperationrequest *GoogleLongrunningCancelOperationRequest) *ProjectsLocationsOperationsCancelCall {\n\tc := &ProjectsLocationsOperationsCancelCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\tc.googlelongrunningcanceloperationrequest = googlelongrunningcanceloperationrequest\n\treturn c\n}", "func (this *service) CancelRequests() error {\n\tthis.log.Debug2(\"<grpc.service.sensordb.CancelRequests>{}\")\n\n\t// Cancel any streaming requests\n\tthis.Publisher.Emit(event.NullEvent)\n\n\t// Return success\n\treturn nil\n}", "func (controller *playgroundController) Cancel(ctx context.Context, info *pb.CancelRequest) (*pb.CancelResponse, error) {\n\tpipelineId, err := uuid.Parse(info.PipelineUuid)\n\tif err != nil {\n\t\tlogger.Errorf(\"%s: Cancel(): pipelineId has incorrect value and couldn't be parsed as uuid value: %s\", info.PipelineUuid, err.Error())\n\t\treturn nil, errors.InvalidArgumentError(\"Cancel\", \"pipelineId has incorrect value and couldn't be parsed as uuid value: \"+info.PipelineUuid)\n\t}\n\tif err := utils.SetToCache(ctx, controller.cacheService, pipelineId, cache.Canceled, true); err != nil {\n\t\treturn nil, errors.InternalError(\"Cancel\", \"error during set cancel flag to cache\")\n\t}\n\treturn &pb.CancelResponse{}, nil\n}", "func (c *ProjectsGroupsDeleteCall) Context(ctx context.Context) *ProjectsGroupsDeleteCall {\n\tc.ctx_ = ctx\n\treturn c\n}", "func (g *ErrGroup) Go(f func(ctx context.Context) error) {\n\tif g.err != nil {\n\t\treturn\n\t}\n\n\tg.limit <- struct{}{}\n\tg.wg.Add(1)\n\tgo func() {\n\t\tdefer func() {\n\t\t\t<-g.limit\n\t\t\tg.wg.Done()\n\t\t}()\n\t\tif err := f(g.ctx); err != nil {\n\t\t\tg.cancel()\n\t\t\tg.errOnce.Do(func() {\n\t\t\t\tg.err = err\n\t\t\t\tg.cancel()\n\t\t\t})\n\t\t}\n\t}()\n}", "func (ae *attackEntry) Cancel() error {\n\tif ae.status == models.AttackResponseStatusCompleted || ae.status == models.AttackResponseStatusFailed {\n\t\treturn fmt.Errorf(\"cannot cancel attack %s with status %v\", ae.uuid, ae.status)\n\t}\n\t// Cancel the attack context\n\tae.ctx.cancelFn()\n\n\tlog.WithField(\"UUID\", ae.uuid).Info(\"Canceled\")\n\tae.status = models.AttackResponseStatusCanceled\n\treturn nil\n}", "func (req *Request) Cancel() {\n\treq.cancel()\n}", "func (c *Group) Watch(ctx context.Context, cancel context.CancelFunc) {\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tlog.Infof(\"Main %v, cancel other processes\", ctx.Err())\n\t\tc.Stop(cancel)\n\t}\n}", "func (sc *ServerConn) cancelRequests() {\n\tsc.respHandlersMtx.Lock()\n\tdefer sc.respHandlersMtx.Unlock()\n\tfor id, c := range sc.respHandlers {\n\t\tclose(c) // requester receives nil immediately\n\t\tdelete(sc.respHandlers, id)\n\t}\n}", "func (m *EventItemRequestBuilder) Cancel()(*i22b4abf5d21f46083e388fe3297f3a331d292876d79491e062ea21ab4d5d5d96.CancelRequestBuilder) {\n return i22b4abf5d21f46083e388fe3297f3a331d292876d79491e062ea21ab4d5d5d96.NewCancelRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}" ]
[ "0.67705494", "0.66169894", "0.6566277", "0.6501351", "0.6323341", "0.62263507", "0.618185", "0.6092547", "0.60669494", "0.60384965", "0.60297287", "0.59959096", "0.5934514", "0.5880945", "0.5767867", "0.57493836", "0.57120466", "0.5708042", "0.570287", "0.56803375", "0.565068", "0.56425226", "0.56309766", "0.5629785", "0.5617243", "0.5601737", "0.560078", "0.55995727", "0.5585381", "0.5585381", "0.55686367", "0.5567592", "0.5557146", "0.5555125", "0.5555125", "0.55526173", "0.5535314", "0.5527757", "0.55250275", "0.54951966", "0.5478674", "0.54750884", "0.5474373", "0.5473154", "0.5472175", "0.5471344", "0.5471344", "0.54712605", "0.54696256", "0.5450838", "0.54455894", "0.5443406", "0.5438989", "0.543211", "0.5422398", "0.54118896", "0.5366486", "0.5346996", "0.5345593", "0.5338165", "0.53326464", "0.53288376", "0.53257143", "0.53217673", "0.5309373", "0.5300375", "0.52933204", "0.5287569", "0.5278357", "0.5251311", "0.5250982", "0.5246187", "0.524561", "0.524535", "0.52421635", "0.5241206", "0.5239199", "0.523318", "0.52252597", "0.5225048", "0.5221867", "0.52147156", "0.52106595", "0.5208047", "0.5204094", "0.51949924", "0.518675", "0.517603", "0.5175686", "0.5172243", "0.5169629", "0.5168411", "0.51675403", "0.5165231", "0.516424", "0.5164069", "0.51625746", "0.51554257", "0.51522607", "0.5144888", "0.51298594" ]
0.0
-1
Wait blocks until all function calls from the Go method have returned, then returns the first nonnil error (if any) from them.
func (s *Supervisor) Wait() error { s.wg.Wait() return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 (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 (m *MockWorker) Wait() (interface{}, error) {\n\targs := m.MethodCalled(\"Wait\")\n\n\treturn args.Get(0), args.Error(1)\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 (res *errResult) Wait() error {\n\tif res == nil {\n\t\treturn nil\n\t}\n\tif res.listen != nil {\n\t\tres.err = <-res.listen\n\t\tres.listen = nil\n\t}\n\treturn res.err\n}", "func (bl *BuildLog) Wait() error {\n\tvar errors []error\n\tfor err := range bl.errCh {\n\t\terrors = append(errors, err)\n\t}\n\tif len(errors) > 0 {\n\t\treturn errors[0]\n\t}\n\treturn nil\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 (g *ErrGroup) Wait() *Errors {\n\t_ = g.Group.Wait()\n\treturn &g.err\n}", "func (b *Any) Wait() (errCount uint64, errs []error) {\n\t<-b.closedCh\n\n\treturn b.errCount, b.errs\n}", "func (wg *ErrorWaitGroup) Wait() (err error) {\n\tn := cap(wg.ch)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tfor {\n\t\tif resErr := <-wg.ch; resErr != nil && err == nil {\n\t\t\terr = resErr\n\t\t}\n\t\tif n--; n == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn err\n}", "func (g *Group) WaitErr() error {\n\tg.wg.Wait()\n\tif g.cancel != nil {\n\t\tg.cancel()\n\t}\n\tif g.firstErr >= 0 && len(g.errs) > int(g.firstErr) {\n\t\t// len(g.errs) > int(g.firstErr) is for then used uninitialized.\n\t\treturn g.errs[g.firstErr]\n\t}\n\treturn nil\n}", "func TryCall(f reflect.Value, args []reflect.Value) (results []reflect.Value, err error) {\n\t//defer func() {\n\t//\t// Recover from panic and set err.\n\t//\tif e := recover(); e != nil {\n\t//\t\tswitch e := e.(type) {\n\t//\t\tdefault:\n\t//\t\t\terr = errors.New(\"Invoking task caused a panic\")\n\t//\n\t//\t\tcase error:\n\t//\t\t\terr = e\n\t//\t\tcase string:\n\t//\t\t\terr = errors.New(e)\n\t//\t\t}\n\t//\t}\n\t//}()\n\n\tresults = f.Call(args)\n\n\tif len(results) < 2 {\n\t\tlog.Fatalln(fmt.Errorf(\"warning!!! wrong async func define\"))\n\t}\n\n\t// If an error was returned by the task func, propagate it\n\t// to the caller via err.\n\tif !results[len(results)-1].IsNil() {\n\t\treturn nil, results[1].Interface().(error)\n\t}\n\treturn\n}", "func (m *MockSerializer) Wait() interface{} {\n\targs := m.MethodCalled(\"Wait\")\n\n\treturn args.Get(0)\n}", "func (t *Transport) Wait() <-chan error {\n\tc := make(chan error, 1)\n\tc <- errors.New(\"TODO\")\n\treturn c\n}", "func (s *Servers) Wait() error {\n\tlog.Debug(\"Waiting\")\n\terr := <-s.errors\n\ts.Close()\n\treturn err\n}", "func (g *Group) Wait() []error {\n\tg.wg.Wait()\n\tif g.cancel != nil {\n\t\tg.cancel()\n\t}\n\treturn g.errs\n}", "func (f *FirstErrPromise) Err() error {\n\tf.wg.Wait()\n\treturn f.err\n}", "func (e *EventsIO) Wait() <-chan error {\n\tif e.waitChan == nil {\n\t\te.waitChan = make(chan error)\n\t\tgo func() {\n\t\t\terr := e.errGroup.Wait()\n\t\t\te.waitChan <- err\n\t\t\tclose(e.waitChan)\n\t\t}()\n\t}\n\treturn (<-chan error)(e.waitChan)\n}", "func (g *FuncGroup) Wait() { (*sync.WaitGroup)(unsafe.Pointer(g)).Wait() }", "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 (s *BindSync) Wait(ctx context.Context) (map[string]*Method, error) {\n\tif !s.wait.Wait(ctx) {\n\t\treturn nil, task.StopReason(ctx)\n\t}\n\treturn s.methods, s.err\n}", "func (e *Engine) GoWait() {\n\tif atomic.CompareAndSwapInt32(&e.running, 0, 1) {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"SEARCH_ERROR recovered: %v\", r))\n\t\t\t}\n\t\t}()\n\t\te.searchRoot(false)\n\t}\n}", "func (i *InvokeMotorBrake) Wait() error {\n\treturn i.Result(nil)\n}", "func (p *Processor) Wait() []error {\n\tclose(p.Input)\n\tp.wg.Wait()\n\tclose(p.output)\n\tp.hwg.Wait()\n\treturn p.herr\n}", "func (r *result) Wait() {\n\t<-r.done\n}", "func (promise *Promise) Await() (interface{}, error) {\n\tpromise.wg.Wait()\n\treturn promise.result, promise.err\n}", "func (w *FuncWaiter) WaitForCompletion() error {\n\tfor i := 0; ; i++ {\n\t\tlog.Infof(\"Waiting for completion ... attempted %v times, %v total\", i, w.MaxAttempts)\n\n\t\tif i >= w.MaxAttempts {\n\t\t\treturn errors.New(\"maximum attempts are reached\")\n\t\t}\n\n\t\tif ok, err := w.Checker(); ok || (!w.IgnoreError && err != nil) {\n\t\t\treturn err\n\t\t}\n\n\t\tselect {\n\t\tcase <-time.After(w.Interval):\n\t\t\tcontinue\n\t\tcase <-w.cancel:\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (s *Server) Wait(waitChan chan error) {\n\tif err := s.serveAPI(); err != nil {\n\t\tlogrus.Errorf(\"ServeAPI error: %v\", err)\n\t\twaitChan <- err\n\t\treturn\n\t}\n\twaitChan <- nil\n}", "func (f *FakeCmdRunner) Wait() error {\n\treturn f.Err\n}", "func WaitAll(futures []*Future) {\r\n\tfor _,future:= range futures {\r\n\t\tfuture.Join()\r\n\t}\r\n\tfor _,future:= range futures {\r\n\t\tif !future.Success() && !future.Cancelled() {\r\n\t\t\terr:= future.Error()\r\n\t\t\tif err != nil {\r\n\t\t\t\tpanic(err)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (g *errGroup) wait() error {\n\tg.wg.Wait()\n\tif g.cancel != nil {\n\t\tg.cancel()\n\t}\n\treturn g.err\n}", "func (g *Group) Wait() error", "func (mfs *MinFS) wait(path string) error {\n\t// check if the file is locked, and wait for max 5 seconds for the file to be\n\t// acquired\n\tfor i := 0; ; /* retries */ i++ {\n\t\tif !mfs.IsLocked(path) {\n\t\t\tbreak\n\t\t}\n\n\t\tif i > 25 /* max number of retries */ {\n\t\t\treturn fuse.EPERM\n\t\t}\n\n\t\ttime.Sleep(time.Millisecond * 200)\n\t}\n\n\treturn nil\n}", "func (p *Promise) Wait(out ...interface{}) error {\n\t// Check for slice special case\n\n\tsliceReturnType, isSliceReturn := validSliceReturn(p.resultType, out)\n\n\tif !isSliceReturn {\n\t\tif len(p.resultType) != len(out) {\n\t\t\tpanic(errors.Errorf(\"Promise returns %d values, Wait was asked to set %d values\", len(p.resultType), len(out)))\n\t\t}\n\t\tfor i := 0; i < len(out); i++ {\n\t\t\toutRv := reflect.ValueOf(out[i])\n\t\t\toutType := outRv.Type()\n\t\t\tif outType != reflect.PtrTo(p.resultType[i]) {\n\t\t\t\tpanic(errors.Errorf(\"for return value %d: expected pointer to %s got type %s\", i, p.resultType[i], outType))\n\t\t\t}\n\t\t}\n\t}\n\tp.cond.L.Lock()\n\tfor !p.complete {\n\t\tp.cond.Wait()\n\t}\n\tp.cond.L.Unlock()\n\n\tif p.err != nil {\n\t\treturn errors.Wrap(p.err, \"error during promise execution\")\n\t}\n\n\tvar outRvs []reflect.Value\n\n\tif isSliceReturn {\n\t\tslicePtr := reflect.ValueOf(out[0])\n\t\tnewSlice := reflect.MakeSlice(reflect.SliceOf(sliceReturnType), len(p.resultType), len(p.resultType))\n\t\tslicePtr.Elem().Set(newSlice)\n\t\tfor i := 0; i < len(p.results); i++ {\n\t\t\toutRv := newSlice.Index(i)\n\t\t\toutRvs = append(outRvs, outRv)\n\t\t}\n\t} else {\n\t\tfor i := 0; i < len(out); i++ {\n\t\t\toutRv := reflect.ValueOf(out[i])\n\t\t\toutRvs = append(outRvs, outRv.Elem())\n\t\t}\n\t}\n\n\tfor i := 0; i < len(p.results); i++ {\n\t\toutRv := outRvs[i]\n\t\tresult := p.results[i]\n\t\toutRv.Set(result)\n\t}\n\treturn nil\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 (r *Reader) _Wait() error {\n\t// Wait for our goroutine to finish\n\t<-r.done\n\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\treturn r.err\n}", "func (wg *WaitGroup) Wait() error {\n\twg.wg.Wait()\n\treturn wg.err\n}", "func waitForReadValue(requestChannel chan *Request, request *Request) (interface{}, error) {\n\trequestChannel <- request\n\tresponse := <-request.ResponseChannel\n\tif response.Error != \"\" {\n\t\treturn nil, errors.New(response.Error)\n\t}\n\treturn response.Value.Val, nil\n}", "func (a API) GetPeerInfoWait(cmd *None) (out *[]btcjson.GetPeerInfoResult, e error) {\n\tRPCHandlers[\"getpeerinfo\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetPeerInfoRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (a API) GetDifficultyWait(cmd *btcjson.GetDifficultyCmd) (out *float64, e error) {\n\tRPCHandlers[\"getdifficulty\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetDifficultyRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (c *qemuCmd) Wait() (int, error) {\n\terr := c.cmd.Wait()\n\n\texitStatus := -1\n\topAPI := c.cmd.Get()\n\tif opAPI.Metadata != nil {\n\t\texitStatusRaw, ok := opAPI.Metadata[\"return\"].(float64)\n\t\tif ok {\n\t\t\texitStatus = int(exitStatusRaw)\n\n\t\t\t// Convert special exit statuses into errors.\n\t\t\tswitch exitStatus {\n\t\t\tcase 127:\n\t\t\t\terr = ErrExecCommandNotFound\n\t\t\tcase 126:\n\t\t\t\terr = ErrExecCommandNotExecutable\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn exitStatus, err\n\t}\n\n\t<-c.dataDone\n\n\tif c.cleanupFunc != nil {\n\t\tdefer c.cleanupFunc()\n\t}\n\n\treturn exitStatus, nil\n}", "func (g *ErrGroup) Wait() error {\n\tg.wg.Wait()\n\tg.cancel()\n\treturn g.err\n}", "func wait() {\n\twaitImpl()\n}", "func (g *Group) Wait() error {\n\t<-g.done\n\n\tg.errM.RLock()\n\tdefer g.errM.RUnlock()\n\n\treturn g.err\n}", "func (e *Executor) Wait() { <-e.exit }", "func TestTryReturn(t *testing.T) {\n\tv, err := Try(func(throw Thrower) int {\n\t\treturn 1\n\t})\n\tassert.Nil(t, err)\n\tassert.Equal(t, 1, v, \"Result should be what was returned\")\n}", "func (i *InvokeMotorStart) Wait() error {\n\treturn i.Result(nil)\n}", "func (container *container) Wait() error {\r\n\terr := container.system.Wait()\r\n\tif err == nil {\r\n\t\terr = container.system.ExitError()\r\n\t}\r\n\treturn convertSystemError(err, container)\r\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 (d *Download) Wait() error {\r\n\tfor err := range d.done {\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (a API) GetInfoWait(cmd *None) (out *btcjson.InfoChainResult0, e error) {\n\tRPCHandlers[\"getinfo\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetInfoRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func WaitForPipeline(errs ...<-chan error) error {\n\terrc := MergeErrors(errs...)\n\tfor err := range errc {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *TaskChain) Wait() error {\n\treturn errors.EnsureStack(c.eg.Wait())\n}", "func (cmd *Command) Wait() error {\n\t// According to https://github.com/golang/go/issues/28461,\n\t// exec.Cmd#Wait is not thread-safe, so we need to implement\n\t// our own version.\n\tcmd.waitOnce.Do(func() {\n\t\tcmd.waitResult = cmd.c.Wait()\n\t\tclose(cmd.waitDoneCh)\n\t})\n\treturn cmd.waitResult\n}", "func (s *sshSessionExternal) Wait() error {\n\tif s.exited() {\n\t\treturn nil\n\t}\n\terr := s.cmd.Wait()\n\tif err == nil {\n\t\tfs.Debugf(s.f, \"ssh external: command exited OK\")\n\t} else {\n\t\tfs.Debugf(s.f, \"ssh external: command exited with error: %v\", err)\n\t}\n\treturn err\n}", "func (p *Pipeline) WaitThrow() {\n\tp.Stop()\n\tp.wait.Wait()\n\tif p.err != nil {\n\t\texc.Rethrow(p.err, exc.Errorf(\"pipeline failure\"))\n\t}\n}", "func (m *mware) Wait() error {\n\treturn m.cmd.Wait()\n}", "func (client *NativeClient) Wait() error {\n\terr := client.openSession.Wait()\n\t_ = client.openSession.Close()\n\tclient.openSession = nil\n\treturn err\n}", "func Go(f func() error) chan error {\n\tch := make(chan error)\n\tgo func() {\n\t\tch <- f()\n\t}()\n\treturn ch\n}", "func Go(f func() error) chan error {\n\tch := make(chan error)\n\tgo func() {\n\t\tch <- f()\n\t}()\n\treturn ch\n}", "func Go(f func() error) chan error {\n\tch := make(chan error, 1)\n\tgo func() {\n\t\tch <- f()\n\t}()\n\treturn ch\n}", "func (r SortedRunner) Wait() error {\n\treturn nil\n}", "func WaitFor(\n\tf func() (error),\n\ttimeout time.Duration) (bool, error) {\n\n\tvar (\n\t\terr error\n\n\t\tfc = make(chan bool, 1)\n\t)\n\n\tgo func() {\n\t\terr = f()\n\t\tfc <- true\n\t}()\n\ttc := time.After(timeout)\n\n\tselect {\n\tcase <-fc:\n\t\treturn true, err\n\tcase <-tc:\n\t\treturn false, nil\n\t}\n}", "func waitForURL(c *C, url string) error {\n\tclient := http.DefaultClient\n\tretries := 100\n\tfor retries > 0 {\n\t\tretries--\n\t\ttime.Sleep(200 * time.Millisecond)\n\t\tresp, err := client.Get(url)\n\t\tif err != nil {\n\t\t\tc.Logf(\"Got error, retries left: %d (error: %v)\", retries, err)\n\t\t\tcontinue\n\t\t}\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tc.Logf(\"Body is: %s\", body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tif resp.StatusCode == 200 {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}", "func WaitSuccessfulDial(address string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), waitDur)\n\tvar lastErr error\n\tdefer cancel()\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn multierr.Combine(ctx.Err(), lastErr)\n\t\tdefault:\n\t\t}\n\t\tvar conn net.Conn\n\t\tconn, lastErr = net.Dial(\"tcp\", address)\n\t\tif lastErr == nil {\n\t\t\treturn conn.Close()\n\t\t}\n\t\tlastErr = errors.Wrap(lastErr, 0)\n\t}\n}", "func (c *Connection) Wait() error {\n\tc.connection.Wait()\n\treturn nil\n}", "func (wsv *web) Wait() Interface { wsv.doCloseDone.Wait(); return wsv }", "func asyncTryWorkersUntilSuccess(config *Config, workerUris []string, startWorkerIndex int, responsesChannel chan *WorkerResponse,\n\trpcReqMethod string, reqBody []byte) {\n\tif len(workerUris) <= startWorkerIndex {\n\t\treturn\n\t}\n\tgo func() {\n\t\tres := useWorkerToProvideService(config, startWorkerIndex, workerUris[startWorkerIndex], rpcReqMethod, reqBody)\n\t\tif startWorkerIndex == (len(workerUris) - 1) {\n\t\t\tresponsesChannel <- res\n\t\t\treturn\n\t\t}\n\t\tif res.IsValidJSONRpcResult() {\n\t\t\tresponsesChannel <- res\n\t\t} else {\n\t\t\tasyncTryWorkersUntilSuccess(config, workerUris, startWorkerIndex+1, responsesChannel, rpcReqMethod, reqBody)\n\t\t}\n\t}()\n}", "func (wg *ErrorWaitGroup) WaitFor(timeout time.Duration) error {\n\tn := cap(wg.ch)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tfor {\n\t\tselect {\n\t\tcase err := <-wg.ch:\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-time.After(timeout):\n\t\t\treturn fmt.Errorf(\"timeout %s\", timeout)\n\t\t}\n\t\tif n--; n == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (g *Group) Wait() error {\n\tg.wg.Wait()\n\tg.cancel() // still cancel the context if all goroutines exit returning no errors\n\treturn g.err\n}", "func (e *endpoint) Wait() {\n\te.completed.Wait()\n}", "func (m *Module) Wait(ctx context.Context) error {\n\tselect {\n\tcase <-m.done:\n\t\tif m.err != nil {\n\t\t\treturn m.err\n\t\t}\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func (s *Stream) Wait() error {\n\treturn s.WaitTimeout(time.Duration(0))\n}", "func (a API) GetCurrentNetWait(cmd *None) (out *string, e error) {\n\tRPCHandlers[\"getcurrentnet\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetCurrentNetRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (async *async) wait() {\n\t<-async.done\n}", "func (j *Job) Wait(ctx context.Context) (*JobStatus, error) {\n\tif j.isQuery {\n\t\t// We can avoid polling for query jobs.\n\t\tif _, err := j.c.service.waitForQuery(ctx, j.projectID, j.jobID); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Note: extra RPC even if you just want to wait for the query to finish.\n\t\tjs, err := j.Status(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn js, nil\n\t}\n\t// Non-query jobs must poll.\n\tvar js *JobStatus\n\terr := internal.Retry(ctx, gax.Backoff{}, func() (stop bool, err error) {\n\t\tjs, err = j.Status(ctx)\n\t\tif err != nil {\n\t\t\treturn true, err\n\t\t}\n\t\tif js.Done() {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn js, nil\n}", "func wait1Second()string{\n\treturn \"\"\n}", "func (node *Node) Wait() error {\n\treturn node.httpAPIServer.Wait()\n}", "func (i *InvokeMotorStop) Wait() error {\n\treturn i.Result(nil)\n}", "func (e *errGroup) Go(goroutine func(context.Context) error) {\n\te.waitGroup.Add(1)\n\tgo func() {\n\t\tvar err error\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\terr = fmt.Errorf(\"%v.Stack:%s\", r, debug.Stack())\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\te.errOnce.Do(func() {\n\t\t\t\t\te.err = err\n\t\t\t\t\te.cancel()\n\t\t\t\t})\n\t\t\t}\n\t\t\te.waitGroup.Done()\n\t\t}()\n\t\terr = goroutine(e.ctx)\n\t}()\n}", "func (s *sshClientExternal) Wait() error {\n\tif s.session == nil {\n\t\treturn nil\n\t}\n\treturn s.session.Wait()\n}", "func (me Retrier) Try(fn func() error) (err error) {\n\tvar (\n\t\tn int\n\t)\n\n\tfor n < me.Loop {\n\t\terr := fn()\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tn++\n\t\ttime.Sleep(me.Delay())\n\t}\n\n\treturn\n}", "func (j *Job) Wait() { <-j.isDone }", "func (p *ResourcePool) getWait() (resource ResourceWrapper, err error) {\n\n\tstart := time.Now()\n\ttimeout := time.After(p.TimeoutTime)\n\n\tfor {\n\t\tr, e := p.getAvailable(timeout)\n\n\t\t//if the test failed try again\n\t\tif e == ResourceTestError {\n\t\t\ttime.Sleep(time.Microsecond)\n\t\t\tcontinue\n\t\t}\n\n\t\t//if we are at our max open try again after a short sleep\n\t\tif e == ResourceExhaustedError {\n\t\t\ttime.Sleep(time.Microsecond)\n\t\t\tcontinue\n\t\t}\n\n\t\t//if we failed to create a new resource, try agaig after a short sleep\n\t\tif e == ResourceCreationError {\n\t\t\ttime.Sleep(time.Microsecond)\n\t\t\tcontinue\n\t\t}\n\n\t\tp.Report()\n\t\tp.ReportWait(time.Now().Sub(start))\n\t\treturn r, e\n\t}\n\n}", "func (a API) GetBlockCountWait(cmd *None) (out *int64, e error) {\n\tRPCHandlers[\"getblockcount\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetBlockCountRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (a API) GetBlockHeaderWait(cmd *btcjson.GetBlockHeaderCmd) (out *btcjson.GetBlockHeaderVerboseResult, e error) {\n\tRPCHandlers[\"getblockheader\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetBlockHeaderRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (t *SyncTransport) Wait() {}", "func (a API) GetHashesPerSecWait(cmd *None) (out *float64, e error) {\n\tRPCHandlers[\"gethashespersec\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetHashesPerSecRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func Try(a func() error, max time.Duration, extra ...interface{}) {\n\tx, y := 0, 1\n\tfor {\n\t\terr := actual(a, extra...)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\tt := time.Duration(x) * time.Second\n\t\tif t < max {\n\t\t\tx, y = y, x+y\n\t\t}\n\t\ttime.Sleep(t)\n\t}\n}", "func (s *Session) Wait() error {\n\t<-s.exited\n\treturn s.exitErr\n}", "func (a API) GetNetworkHashPSWait(cmd *btcjson.GetNetworkHashPSCmd) (out *[]btcjson.GetPeerInfoResult, e error) {\n\tRPCHandlers[\"getnetworkhashps\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetNetworkHashPSRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func retryCall(times int, sleep int64, fn func() (interface{}, error)) (intf interface{}, err error) {\n\tfor i := 0; i < times; i++ {\n\t\tintf, err = fn()\n\t\tif err == nil {\n\t\t\treturn intf, nil\n\t\t}\n\t\ttime.Sleep(time.Millisecond * time.Duration(sleep))\n\t}\n\treturn nil, err\n}", "func (c *client) PingWait() error {\n\treturn wait.PollImmediate(PollInterval, RetryTimeout, c.Ping)\n}", "func CallErr(f func() error) error {\n\tcheckRun()\n\terrChan := make(chan error)\n\tcallQueue <- func() {\n\t\terrChan <- f()\n\t}\n\treturn <-errChan\n}", "func AwaitResult(c net.Conn) (*rmake.FinalBuildResult, error) {\n\tvar gobint interface{}\n\tvar fbr *rmake.FinalBuildResult\n\n\tdec := gob.NewDecoder(c)\n\n\t// Wait till we have what we want\n\tfor fbr == nil {\n\t\t// Decode some data\n\t\terr := dec.Decode(&gobint)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\t//return nil, err // I don't think we want to simply die...\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Found some data, grab the type...\n\t\tswitch message := gobint.(type) {\n\t\tcase *rmake.BuildStatus:\n\t\t\tfmt.Println(\"Build Status\")\n\t\t\tPrintBuildStatus(message) // Doesn't work for some reason\n\t\tcase *rmake.FinalBuildResult:\n\t\t\tfmt.Println(\"Final Build Result\")\n\t\t\tfbr = message\n\t\tcase *rmake.BuilderResult:\n\t\t\tfmt.Println(\"Got builder result.\")\n\t\t\tfmt.Printf(\"Got %d files back.\", len(message.Results))\n\t\tcase *rmake.JobFinishedMessage:\n\t\t\tfmt.Println(\"I SHOULDNT BE GETTING THIS.\")\n\t\t\tfmt.Println(message.Stdout)\n\t\tdefault:\n\t\t\tfmt.Println(\"Unknown Type.\")\n\t\t\tfmt.Println(reflect.TypeOf(message))\n\t\t}\n\t}\n\n\treturn fbr, nil\n}", "func waitForFile(fp string) ([]byte, error) {\n\tretries := 3\n\tfileExists := false\n\tvar err error\n\tfor i := 0; i < retries; i++ {\n\t\tif _, err = os.Stat(fp); os.IsNotExist(err) {\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t} else {\n\t\t\tfileExists = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !fileExists {\n\t\treturn nil, err\n\t}\n\n\tfile, err := ioutil.ReadFile(fp)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to open file: %s\", fp)\n\t}\n\treturn file, err\n}", "func (p *Pipeline) Wait() error {\n\tp.Stop()\n\tp.wait.Wait()\n\treturn p.err\n}", "func (e *engine) Wait(context.Context, *Spec, *Step) (*State, error) {\n\treturn nil, nil // no-op for bash implementation\n}", "func MultiCall(funs []func() error, timeout time.Duration) []error {\n\tresults := make([]error, len(funs))\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(funs))\n\n\tfor i, f := range funs {\n\t\tgo func(i int, f func() error) {\n\t\t\tdefer wg.Done()\n\t\t\tdone := make(chan error)\n\t\t\tgo func() {\n\t\t\t\tdone <- f()\n\t\t\t}()\n\t\t\tselect {\n\t\t\tcase err := <-done:\n\t\t\t\tresults[i] = err\n\t\t\tcase <-time.After(timeout):\n\t\t\t\tresults[i] = ErrTimeout\n\t\t\t}\n\t\t}(i, f)\n\t}\n\n\twg.Wait()\n\treturn results\n}", "func (a API) VersionWait(cmd *btcjson.VersionCmd) (out *map[string]btcjson.VersionResult, e error) {\n\tRPCHandlers[\"version\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan VersionRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (p *Pool) WaitAll() {\n\tdefer recover()\n\tp.wg.Wait()\n}" ]
[ "0.61228603", "0.6063529", "0.5848832", "0.5809065", "0.5668806", "0.557306", "0.5548479", "0.5540164", "0.5452004", "0.544528", "0.5429177", "0.53745997", "0.53048795", "0.52970463", "0.5241863", "0.51986533", "0.5172391", "0.5152442", "0.51371413", "0.5093955", "0.5086318", "0.5085114", "0.50742155", "0.5055976", "0.5031462", "0.5016837", "0.5007141", "0.50036395", "0.49620616", "0.49618724", "0.49542108", "0.49528888", "0.49344954", "0.4932006", "0.49204752", "0.48923633", "0.48913273", "0.48902488", "0.48889905", "0.4886561", "0.4880918", "0.48756886", "0.48725405", "0.4858461", "0.48439842", "0.4842378", "0.48422927", "0.48298565", "0.48150486", "0.48147005", "0.47926712", "0.47862494", "0.47854832", "0.47829363", "0.47785965", "0.4770418", "0.47674015", "0.47413012", "0.4726476", "0.4726476", "0.47260267", "0.472248", "0.47171307", "0.47153935", "0.47087604", "0.4703556", "0.47015226", "0.46945286", "0.4694191", "0.4691687", "0.46897084", "0.46746355", "0.46698958", "0.46659866", "0.46545914", "0.4651696", "0.46459183", "0.46436295", "0.46421507", "0.4629764", "0.46296084", "0.46255633", "0.46243674", "0.4615239", "0.46146235", "0.46116775", "0.4610066", "0.46094805", "0.46054304", "0.46031013", "0.46018565", "0.45987156", "0.45972264", "0.4595343", "0.45948058", "0.45903364", "0.45891258", "0.45843118", "0.45747963", "0.457474", "0.45714068" ]
0.0
-1
Shutdown gracefully shuts down the server without interrupting any connections. Shutdown works by first closing all open listeners, then fills closeCh on Serve method of Handler, and then waiting indefinitely for connections to exit Serve method of Handler and then close. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s). When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil. Make sure the program doesn't exit and waits instead for Shutdown to return.
func (srv *TCPServer) Shutdown(ctx context.Context) (err error) { err = srv.l.Close() select { case srv.closeCh <- struct{}{}: default: } srv.connsMu.RLock() for _, c := range srv.conns { select { case c.closeCh <- struct{}{}: default: } } srv.connsMu.RUnlock() for { select { case <-time.After(5 * time.Millisecond): srv.connsMu.RLock() if len(srv.conns) == 0 { srv.connsMu.RUnlock() return } srv.connsMu.RUnlock() case <-ctx.Done(): srv.connsMu.RLock() for _, c := range srv.conns { c.conn.Close() } srv.connsMu.RUnlock() err = ctx.Err() return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Server) Shutdown(ctx context.Context) error {\n\tif s.closing == nil {\n\t\t// Nothing to do\n\t\treturn nil\n\t}\n\tclose(s.closing)\n\n\t// Stops listening.\n\terr := s.closeListener()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\t// Forces closing of all actives connections.\n\t\t\ts.close()\n\t\t\treturn ctx.Err()\n\t\tcase <-s.closed:\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\tselect {\n\tcase <-s.done:\n\t\treturn ErrServerClosed\n\tdefault:\n\t\tclose(s.done)\n\t}\n\n\tvar err error\n\ts.locker.Lock()\n\tfor _, l := range s.listeners {\n\t\tif lerr := l.Close(); lerr != nil && err == nil {\n\t\t\terr = lerr\n\t\t}\n\t}\n\ts.locker.Unlock()\n\n\tconnDone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(connDone)\n\t\ts.wg.Wait()\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-connDone:\n\t\treturn err\n\t}\n}", "func (srv *Server) Shutdown(ctx context.Context) error {\n\tsrv.inShutdown.Store(true)\n\tsrv.mu.Lock()\n\tlnerr := srv.closeListenersLocked()\n\tsrv.closeDoneChanLocked()\n\n\tfor _, f := range srv.onShutdown {\n\t\tgo f()\n\t}\n\tsrv.mu.Unlock()\n\n\tticker := time.NewTicker(shutdownPollInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tif srv.closeIdleConns() {\n\t\t\treturn lnerr\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-ticker.C:\n\t\t}\n\t}\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\twg := &sync.WaitGroup{}\n\tc := make(chan struct{})\n\n\tgo func() {\n\t\tdefer close(c)\n\t\ts.GracefulStop()\n\t\twg.Wait()\n\t}()\n\n\tselect {\n\tcase <-c:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func (s *Server) Shutdown() error {\n\ts.ctxCancel()\n\treturn nil\n}", "func (r *Raft) Shutdown(ctx context.Context) error {\n\tr.doClose(ErrServerClosed)\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-r.closed:\n\t\treturn nil\n\t}\n}", "func (s *MuxServer) Shutdown(ctx context.Context) {\n\ts.HTTPServer.Shutdown(ctx)\n\ts.GRPCServer.Shutdown(ctx)\n}", "func (s *HTTPServer) Shutdown(ctx context.Context) error {\n\tglog.Infof(\"http server shutdown\")\n\treturn s.https.Shutdown(ctx)\n}", "func HandleShutdown(ctx context.Context) {\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tLogger.Info(\"Shutting down server\")\n\t\t\tdatastore.GetStore().Close()\n\t\t}\n\t}()\n}", "func (proxy *ProxyService) Shutdown(ctx context.Context) error {\n\tproxy.doTerminate()\n\tselect {\n\tcase <-proxy.doneCh:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn trace.Wrap(ctx.Err())\n\t}\n}", "func (srv *Server) Shutdown(ctx context.Context) error {\n\tif srv.Config.Stats != nil {\n\t\tif err := srv.Config.Stats.Shutdown(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err := srv.ssh.Shutdown(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn srv.http.Shutdown(ctx)\n}", "func (p *Proxy) Shutdown(ctx context.Context) error {\n\tif err := p.server.Shutdown(ctx); err != nil {\n\t\tp.logger.Error(\"Error shutting down HTTP server!\", zap.Error(err))\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\treturn s.e.Shutdown(ctx)\n}", "func (r *otlpReceiver) Shutdown(ctx context.Context) error {\n\tvar err error\n\n\tif r.serverHTTP != nil {\n\t\terr = r.serverHTTP.Shutdown(ctx)\n\t}\n\n\tif r.serverGRPC != nil {\n\t\tr.serverGRPC.GracefulStop()\n\t}\n\n\tr.shutdownWG.Wait()\n\treturn err\n}", "func (r *otlpReceiver) Shutdown(ctx context.Context) error {\n\tvar err error\n\n\tif r.serverHTTP != nil {\n\t\terr = r.serverHTTP.Shutdown(ctx)\n\t}\n\n\tif r.serverGRPC != nil {\n\t\tr.serverGRPC.GracefulStop()\n\t}\n\n\tr.shutdownWG.Wait()\n\treturn err\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\t// logInfo(\"%v %v Shutdown...\", s.Handler.LogTag(), s.Listener.Addr())\n\tdefer logInfo(\"%v %v Shutdown\", s.Handler.LogTag(), s.Listener.Addr())\n\ts.running = false\n\ts.Listener.Close()\n\tselect {\n\tcase <-s.chStop:\n\tcase <-ctx.Done():\n\t\treturn ErrTimeout\n\t}\n\treturn nil\n}", "func (m *cMux) Shutdown(ctx context.Context) error {\n\tm.mu.Lock()\n\tlnerr := m.closeListenersLocked()\n\tm.cancel()\n\n\tfor _, f := range m.onShutdown {\n\t\tgo f()\n\t}\n\tm.mu.Unlock()\n\n\tticker := time.NewTicker(shutdownPollInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tif m.closeIdleConns() {\n\t\t\treturn lnerr\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-ticker.C:\n\t\t}\n\t}\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\treturn s.callbackServer.Shutdown(ctx)\n}", "func (s *Server) Stop(ctx context.Context) {\n\ts.shutdownFuncsM.Lock()\n\tdefer s.shutdownFuncsM.Unlock()\n\ts.shutdownOnce.Do(func() {\n\t\tclose(s.shuttingDown)\n\t\t// Shut down the HTTP server in parallel to calling any custom shutdown functions\n\t\twg := sync.WaitGroup{}\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tif err := s.srv.Shutdown(ctx); err != nil {\n\t\t\t\tslog.Debug(ctx, \"Graceful shutdown failed; forcibly closing connections 👢\")\n\t\t\t\tif err := s.srv.Close(); err != nil {\n\t\t\t\t\tslog.Critical(ctx, \"Forceful shutdown failed, exiting 😱: %v\", err)\n\t\t\t\t\tpanic(err) // Something is super hosed here\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tfor _, f := range s.shutdownFuncs {\n\t\t\tf := f // capture range variable\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tf(ctx)\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t})\n}", "func Handle(ctx context.Context, server *http.Server, grpcServer *grpc.Server, closable ...Closable) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)\n\n\t// wait for signals or app context done\n\tselect {\n\tcase <-ctx.Done():\n\tcase <-c:\n\t}\n\tshutdown(server, grpcServer, closable...)\n}", "func (d *Driver) Shutdown(ctx context.Context) error {\n\treturn d.Server.Shutdown(ctx)\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\treturn s.Server.Shutdown(ctx)\n}", "func (zr *zipkinReceiver) Shutdown(context.Context) error {\n\tvar err error\n\tif zr.server != nil {\n\t\terr = zr.server.Close()\n\t}\n\tzr.shutdownWG.Wait()\n\treturn err\n}", "func (srv *Server) Shutdown(ctx context.Context, wg *sync.WaitGroup) error {\n\tdefer wg.Done()\n\treturn srv.Server.Shutdown(ctx)\n}", "func (t *TLSServer) Shutdown(ctx context.Context) error {\n\terrC := make(chan error, 2)\n\tgo func() {\n\t\terrC <- t.httpServer.Shutdown(ctx)\n\t}()\n\tgo func() {\n\t\tt.grpcServer.server.GracefulStop()\n\t\terrC <- nil\n\t}()\n\terrors := []error{}\n\tfor i := 0; i < 2; i++ {\n\t\terrors = append(errors, <-errC)\n\t}\n\treturn trace.NewAggregate(errors...)\n}", "func (dd *DefaultDriver) Shutdown(ctx context.Context) error {\n\treturn dd.Server.Shutdown(ctx)\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\treturn s.srv.Shutdown(ctx)\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\treturn s.server.Shutdown(ctx)\n}", "func (s *Server) Shutdown(ctx context.Context) {\n\ts.router.Shutdown(ctx)\n}", "func (p *Proxy) Shutdown() {\n\tlog.Info(\"Shutting down server gracefully\")\n\tclose(p.shutdown)\n\tgraceful.Shutdown()\n\tp.gRPCStop()\n}", "func (l *LocalSDKServer) Shutdown(context.Context, *sdk.Empty) (*sdk.Empty, error) {\n\tlogrus.Info(\"Shutdown request has been received!\")\n\treturn &sdk.Empty{}, nil\n}", "func Shutdown() error {\n\tif server != nil {\n\t\treturn server.Shutdown(context.Background())\n\t}\n\n\tserver = nil\n\treturn nil\n}", "func (sw *SimpleWebServer) Shutdown(ctx context.Context) error {\n\tif !sw.running {\n\t\treturn fmt.Errorf(\"not started\")\n\t}\n\tsw.running = false\n\treturn sw.Server.Shutdown(ctx)\n}", "func (o *OmahaServer) Shutdown(ctx context.Context) {\n\to.server.Shutdown(ctx)\n\tclose(o.shuttingDown)\n}", "func (s *Server) Shutdown() {\n\t// TODO(aditya) shut down workers and socket readers\n\ts.logger.Info(\"Shutting down server gracefully\")\n\tclose(s.shutdown)\n\tif s.FlushOnShutdown {\n\t\tctx, cancel := context.WithTimeout(context.Background(), s.Interval)\n\t\ts.Flush(ctx)\n\t\tcancel()\n\t}\n\tgraceful.Shutdown()\n\tfor _, source := range s.sources {\n\t\tsource.source.Stop()\n\t}\n\n\t// Close the gRPC connection for forwarding\n\tif s.grpcForwardConn != nil {\n\t\ts.grpcForwardConn.Close()\n\t}\n}", "func (s *server) shutdown(ctx context.Context) error {\n\treturn s.server.Shutdown(ctx)\n}", "func (svc *Service) Close(ctx context.Context) error {\n\ttimeout := svc.Config.GracefulShutdownTimeout\n\tlog.Event(ctx, \"commencing graceful shutdown\", log.Data{\"graceful_shutdown_timeout\": timeout}, log.INFO)\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\n\t// track shutown gracefully closes up\n\tvar hasShutdownError bool\n\n\tgo func() {\n\t\tdefer cancel()\n\n\t\t// stop healthcheck, as it depends on everything else\n\t\tif svc.ServiceList.HealthCheck {\n\t\t\tsvc.HealthCheck.Stop()\n\t\t}\n\n\t\t// stop any incoming requests before closing any outbound connections\n\t\tif err := svc.Server.Shutdown(ctx); err != nil {\n\t\t\tlog.Event(ctx, \"failed to shutdown http server\", log.Error(err), log.ERROR)\n\t\t\thasShutdownError = true\n\t\t}\n\n\t\t// TODO: Close other dependencies, in the expected order\n\t}()\n\n\t// wait for shutdown success (via cancel) or failure (timeout)\n\t<-ctx.Done()\n\n\t// timeout expired\n\tif ctx.Err() == context.DeadlineExceeded {\n\t\tlog.Event(ctx, \"shutdown timed out\", log.ERROR, log.Error(ctx.Err()))\n\t\treturn ctx.Err()\n\t}\n\n\t// other error\n\tif hasShutdownError {\n\t\terr := errors.New(\"failed to shutdown gracefully\")\n\t\tlog.Event(ctx, \"failed to shutdown gracefully \", log.ERROR, log.Error(err))\n\t\treturn err\n\t}\n\n\tlog.Event(ctx, \"graceful shutdown was successful\", log.INFO)\n\treturn nil\n}", "func (a *Application) Shutdown(ctx context.Context) error {\n\tif timeout, ok := ctx.Deadline(); ok {\n\t\tlevel.Debug(a.logger).Log(\n\t\t\t\"msg\", \"shutting down with timeout\",\n\t\t\t\"timeout\", math.Floor(timeout.Sub(time.Now()).Seconds()),\n\t\t)\n\t}\n\n\tfor _, hook := range a.lifecycle.hooks {\n\t\terr := invokeHook(hook.PreShutdown)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, hook := range a.lifecycle.hooks {\n\t\terr := invokeHookCtx(hook.OnShutdown, ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, hook := range a.lifecycle.hooks {\n\t\terr := invokeHook(hook.PostShutdown)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\treturn s.service.Stop(ctx)\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\tconst (\n\t\tminPollInterval = 10 * time.Millisecond\n\t\tmaxPollInterval = 500 * time.Millisecond\n\t)\n\n\ts.mutex.Lock()\n\n\tif s.shutdown != nil {\n\t\ts.shutdown()\n\t}\n\n\tfor l := range s.listeners {\n\t\tl.Close()\n\t}\n\n\ts.mutex.Unlock()\n\n\tfor i := 0; s.numberOfActors() != 0; i++ {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tcase <-time.After(backoff(i, minPollInterval, maxPollInterval)):\n\t\t}\n\t}\n\n\treturn ctx.Err()\n}", "func (s *SrvSession) Shutdown(ctx context.Context) {\n\tif s.srv != nil {\n\t\tif err := s.srv.Shutdown(ctx); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.Warningf(\"Shutdown for [%v] %v\", s.listenAddr, err)\n\t\t}\n\t}\n}", "func (s Server) Shutdown(ctx context.Context) error {\n\treturn s.Server.Shutdown(ctx)\n}", "func Shutdown() {\n\tlog.Println(\"http server is shutting down...\")\n\n\tctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)\n\tdefer cancel()\n\n\tif err := server.Shutdown(ctx); err != nil {\n\t\tlog.Fatalf(\"Could not gracefully shutdown http server: %v\\n\", err)\n\t}\n\t// wait for the go routine to clean up\n\twg.Wait()\n}", "func (srv *Server) Shutdown(ctx context.Context) error {\n\tsrv.inShutdown.setTrue()\n\n\tsrv.mu.Lock()\n\tlnerr := srv.closeListenersLocked()\n\tsrv.closeDoneChanLocked()\n\tfor _, f := range srv.onShutdown {\n\t\tgo f()\n\t}\n\tsrv.mu.Unlock()\n\n\tpollIntervalBase := time.Millisecond\n\tnextPollInterval := func() time.Duration {\n\t\t// Add 10% jitter.\n\t\tinterval := pollIntervalBase + time.Duration(rand.Intn(int(pollIntervalBase/10)))\n\t\t// Double and clamp for next time.\n\t\tpollIntervalBase *= 2\n\t\tif pollIntervalBase > shutdownPollIntervalMax {\n\t\t\tpollIntervalBase = shutdownPollIntervalMax\n\t\t}\n\t\treturn interval\n\t}\n\n\ttimer := time.NewTimer(nextPollInterval())\n\tdefer timer.Stop()\n\tfor {\n\t\tif srv.closeIdleConns() && srv.numListeners() == 0 {\n\t\t\treturn lnerr\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-timer.C:\n\t\t\ttimer.Reset(nextPollInterval())\n\t\t}\n\t}\n}", "func (sr *sapmReceiver) Shutdown(context.Context) error {\n\tif sr.server == nil {\n\t\treturn nil\n\t}\n\terr := sr.server.Close()\n\tsr.shutdownWG.Wait()\n\treturn err\n}", "func (s *Server) Serve(ctx context.Context) (err error) {\n\tch := make(chan error)\n\tdefer close(ch)\n\n\t// Start serving.\n\tgo s.serve(ch)\n\n\t// Wait on our context to be cancelled.\n\t<-ctx.Done()\n\n\t// Shutdown http within 5 seconds\n\tctxShutdown, cancel := context.WithTimeout(context.Background(), s.shutdownTimeout)\n\tdefer cancel()\n\n\tif err = suppressServerClosed(s.svr.Shutdown(ctxShutdown)); err == nil {\n\t\treturn suppressServerClosed(<-ch)\n\t}\n\n\tif chErr := suppressServerClosed(<-ch); chErr != nil {\n\t\treturn multierror.Append(err, chErr)\n\t}\n\n\treturn err\n}", "func (f *Fs) Shutdown(ctx context.Context) error {\n\treturn f.multithread(ctx, func(ctx context.Context, u *upstream) error {\n\t\tif do := u.f.Features().Shutdown; do != nil {\n\t\t\treturn do(ctx)\n\t\t}\n\t\treturn nil\n\t})\n}", "func OnShutdown() context.Context {\n\treturn shutdownCtx\n}", "func OnShutdown() context.Context {\n\treturn shutdownCtx\n}", "func RunContext(h http.Handler, ctx context.Context) {\n\tsrv := createServer(h)\n\tgo gracefullyShutDownOnSignal(srv, ctx)\n\tif err := srv.ListenAndServe(); err != http.ErrServerClosed {\n\t\tlog.Fatalf(\"Unable to to start server: %v\", err)\n\t}\n}", "func (m *Manager) Shutdown(ctx context.Context) error {\n\tinitShutdown := func() {\n\t\tctx, m.shutdownCancel = context.WithCancel(ctx)\n\t\tm.status <- StatusShutdown\n\t}\n\n\tvar isRunning bool\n\ts := <-m.status\n\tswitch s {\n\tcase StatusShutdown:\n\t\tm.status <- s\n\t\tselect {\n\t\tcase <-m.shutdownDone:\n\t\tcase <-ctx.Done():\n\t\t\t// if we timeout before the existing call, cancel it's context\n\t\t\tm.shutdownCancel()\n\t\t\t<-m.shutdownDone\n\t\t}\n\t\treturn m.shutdownErr\n\tcase StatusStarting:\n\t\tm.startupCancel()\n\t\tclose(m.pauseStart)\n\t\tinitShutdown()\n\t\t<-m.startupDone\n\tcase StatusUnknown:\n\t\tinitShutdown()\n\t\tclose(m.pauseStart)\n\t\tclose(m.shutdownDone)\n\t\treturn nil\n\tcase StatusPausing:\n\t\tisRunning = true\n\t\tm.pauseCancel()\n\t\tinitShutdown()\n\t\t<-m.pauseDone\n\tcase StatusReady:\n\t\tclose(m.pauseStart)\n\t\tfallthrough\n\tcase StatusPaused:\n\t\tisRunning = true\n\t\tinitShutdown()\n\t}\n\n\tdefer close(m.shutdownDone)\n\tdefer m.shutdownCancel()\n\n\terr := m.shutdownFunc(ctx)\n\n\tif isRunning {\n\t\tm.runCancel()\n\t\t<-m.runDone\n\t}\n\n\treturn err\n}", "func (cc *ClientConn) Shutdown(ctx context.Context) error {\n\tif err := cc.sendGoAway(); err != nil {\n\t\treturn err\n\t}\n\t// Wait for all in-flight streams to complete or connection to close\n\tdone := make(chan struct{})\n\tcancelled := false // guarded by cc.mu\n\tgo func() {\n\t\tcc.mu.Lock()\n\t\tdefer cc.mu.Unlock()\n\t\tfor {\n\t\t\tif len(cc.streams) == 0 || cc.closed {\n\t\t\t\tcc.closed = true\n\t\t\t\tclose(done)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif cancelled {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcc.cond.Wait()\n\t\t}\n\t}()\n\tshutdownEnterWaitStateHook()\n\tselect {\n\tcase <-done:\n\t\tcc.closeConn()\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\tcc.mu.Lock()\n\t\t// Free the goroutine above\n\t\tcancelled = true\n\t\tcc.cond.Broadcast()\n\t\tcc.mu.Unlock()\n\t\treturn ctx.Err()\n\t}\n}", "func (c *WSClient) Shutdown(ctx context.Context) error {\n\tclose(c.shutdown)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tc.conn.Close()\n\t\treturn errors.New(\"Failed to shutdown gracefully\")\n\tcase <-c.ok:\n\t\treturn nil\n\t}\n}", "func (c *client) Shutdown(ctx context.Context) error {\n\t// The otlpmetric.Exporter synchronizes access to client methods and\n\t// ensures this is called only once. The only thing that needs to be done\n\t// here is to release any computational resources the client holds.\n\n\tc.metadata = nil\n\tc.requestFunc = nil\n\tc.msc = nil\n\n\terr := ctx.Err()\n\tif c.ourConn {\n\t\tcloseErr := c.conn.Close()\n\t\t// A context timeout error takes precedence over this error.\n\t\tif err == nil && closeErr != nil {\n\t\t\terr = closeErr\n\t\t}\n\t}\n\tc.conn = nil\n\treturn err\n}", "func (srv *Server) Shutdown(ctx context.Context) error {\n\tif srv.driver == nil {\n\t\treturn nil\n\t}\n\treturn srv.driver.Shutdown(ctx)\n}", "func (h *handler) shutdown(ctx context.Context) {\n\tdefer func() {\n\t\tif h.onStopped != nil {\n\t\t\tgo h.onStopped()\n\t\t}\n\n\t\th.totalClosingTime = h.clock.Time().Sub(h.startClosingTime)\n\t\tclose(h.closed)\n\t}()\n\n\t// shutdown may be called during Start, so we populate the start closing\n\t// time here in case Stop was never called.\n\tif h.startClosingTime.IsZero() {\n\t\th.startClosingTime = h.clock.Time()\n\t}\n\n\tstate := h.ctx.State.Get()\n\tengine, ok := h.engineManager.Get(state.Type).Get(state.State)\n\tif !ok {\n\t\th.ctx.Log.Error(\"failed fetching current engine during shutdown\",\n\t\t\tzap.Stringer(\"type\", state.Type),\n\t\t\tzap.Stringer(\"state\", state.State),\n\t\t)\n\t\treturn\n\t}\n\n\tif err := engine.Shutdown(ctx); err != nil {\n\t\th.ctx.Log.Error(\"failed while shutting down the chain\",\n\t\t\tzap.Error(err),\n\t\t)\n\t}\n}", "func TestServer_ShutdownContextTimeoutExceeded(t *testing.T) {\n\tdone := make(chan struct{})\n\n\tmessage := &msg.Message{\n\t\tAttributes: msg.Attributes{},\n\t\tBody: bytes.NewBufferString(\"hello world!\"),\n\t}\n\n\tsrv := mem.NewServer(make(chan *msg.Message, 1), 1)\n\tdefer close(srv.C)\n\n\treceiver := msg.ReceiverFunc(func(ctx context.Context, m *msg.Message) error {\n\t\tdefer close(done)\n\n\t\t// set a fast timeout so srv doesn't have enough time to finish\n\t\tsctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\t\tdefer cancel()\n\n\t\tif err := srv.Shutdown(sctx); err == msg.ErrServerClosed {\n\t\t\tt.Fatal(\"expected context timeout\")\n\t\t}\n\t\treturn nil\n\t})\n\tsrv.C <- message\n\n\tif err := srv.Serve(receiver); err != msg.ErrServerClosed {\n\t\tt.Fatalf(\"expected %v, got %v\", msg.ErrServerClosed, err)\n\t}\n\n\t<-done\n}", "func (c *CleanupHTTP) Serve(timeout time.Duration) {\n\tquit := make(chan struct{})\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)\n\n\tgo c.handleSignal(interrupt, quit)\n\n\tgo func() {\n\t\tif err := c.Server.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.Printf(\"ListenAndServe failed: %s\", err.Error())\n\t\t}\n\n\t\tif atomic.CompareAndSwapInt32(&c.closing, 0, 1) {\n\t\t\tclose(quit)\n\t\t}\n\t}()\n\n\t<-quit\n\tc.preCleanup()\n\tdefer c.postCleanup()\n\n\tvar (\n\t\tctx context.Context\n\t\tcancel context.CancelFunc\n\t)\n\n\tif timeout > 0 {\n\t\tctx, cancel = context.WithTimeout(\n\t\t\tcontext.Background(),\n\t\t\ttimeout,\n\t\t)\n\t\tdefer cancel()\n\t} else {\n\t\tctx = context.Background()\n\t}\n\n\tif err := c.Server.Shutdown(ctx); err != nil {\n\t\tlog.Printf(\"Shutdown failed: %s\", err.Error())\n\t}\n}", "func (m *Manager) Shutdown(context.Context) error {\n\tclose(m.shutdownCh)\n\tm.shutdownWg.Wait()\n\treturn nil\n}", "func Shutdown(ctx context.Context, code int) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tcancelFn()\n\tif _, ok := ctx.Deadline(); ok {\n\t\t<-ctx.Done()\n\t}\n}", "func (i *Instance) Shutdown() {\n\t// Shutdown all dependencies\n\ti.Service.Shutdown()\n\n\t// Shutdown HTTP server\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\terr := i.httpServer.Shutdown(ctx)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"Failed to shutdown HTTP server gracefully\")\n\t\tos.Exit(1)\n\t}\n\n\tlogrus.Info(\"Shutdown HTTP server...\")\n\tos.Exit(0)\n}", "func (c *LspConn) Shutdown(ctx context.Context) error {\n\treturn c.Call(ctx, \"shutdown\", nil, nil)\n}", "func (ws *WebServer) Shutdown() error {\n\terr := ws.server.Shutdown(context.Background())\n\tws.server = nil\n\treturn err\n}", "func (mw *JWTMiddleware) Shutdown(_ context.Context) error {\n\treturn nil\n}", "func (c *client) Shutdown(ctx context.Context, goodbye bool) error {\n\tq := url.Values{}\n\tif goodbye {\n\t\tq.Set(\"mode\", \"goodbye\")\n\t}\n\turl := c.createURL(\"/shutdown\", q)\n\n\treq, err := http.NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn maskAny(err)\n\t}\n\tif ctx != nil {\n\t\treq = req.WithContext(ctx)\n\t}\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn maskAny(err)\n\t}\n\tif err := c.handleResponse(resp, \"POST\", url, nil); err != nil {\n\t\treturn maskAny(err)\n\t}\n\n\treturn nil\n}", "func (a *API) Shutdown(ctx context.Context) error {\n\tif err := a.Server.Shutdown(ctx); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\tif s.driver == nil {\n\t\treturn nil\n\t}\n\treturn s.driver.Shutdown(ctx)\n}", "func (f ServiceFunc) Shutdown(ctx context.Context) error {\n\treturn f.OnShutdown(ctx)\n}", "func (srv *Server) Close() error {\n\tdefer close(srv.closeChan)\n\tsrv.closeMu.Lock()\n\tdefer srv.closeMu.Unlock()\n\t// Stop accepting API requests.\n\terr := srv.apiServer.Shutdown(context.Background())\n\t// Wait for serve() to return and capture its error.\n\t<-srv.serveChan\n\tif !errors.Contains(srv.serveErr, http.ErrServerClosed) {\n\t\terr = errors.Compose(err, srv.serveErr)\n\t}\n\t// Shutdown modules.\n\tif srv.node != nil {\n\t\terr = errors.Compose(err, srv.node.Close())\n\t}\n\treturn errors.AddContext(err, \"error while closing server\")\n}", "func (as *apiServer) Shutdown(ctx context.Context) error {\n\treturn as.server.Shutdown(ctx)\n}", "func (e *Engine) Shutdown() error {\n\treturn e.server.Shutdown(context.TODO())\n}", "func (s *Server) Shutdown() error {\n\terr := s.httpListener.Shutdown(context.Background())\n\treturn err\n}", "func (srv *Server) Close() error {\n\tsrv.inShutdown.Store(true)\n\tsrv.mu.Lock()\n\tdefer srv.mu.Unlock()\n\tsrv.closeDoneChanLocked()\n\n\terr := srv.closeListenersLocked()\n\tfor c := range srv.activeConn {\n\t\tc.close()\n\t\tdelete(srv.activeConn, c)\n\t}\n\tif srv.Handler == nil {\n\t\tDefaultServeMux.Close()\n\t} else {\n\t\tif closer, ok := srv.Handler.(io.Closer); ok {\n\t\t\tcloser.Close()\n\t\t}\n\t}\n\treturn err\n}", "func (s *callbackServer) Shutdown() {\n\tif err := s.server.Shutdown(context.Background()); err != nil {\n\t\tlog.Printf(\"HTTP server Shutdown error: %v\", err)\n\t}\n}", "func (e *EntryPoint) Shutdown(ctx context.Context, code int) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tcancelFn()\n\tif _, ok := ctx.Deadline(); ok {\n\t\t<-ctx.Done()\n\t}\n\tos.Exit(code)\n}", "func (s *server) Close(ctx context.Context) error {\n\treturn s.server.Shutdown(ctx)\n}", "func (p *Processor) Shutdown(_ context.Context) error {\n\tp.Logger.Infof(\"attempting graceful shutdown\")\n\tif p.isStopped() {\n\t\treturn ErrStopped\n\t}\n\n\tp.mu.Lock()\n\tp.stopped = true\n\tp.mu.Unlock()\n\n\tp.Logger.Infof(\"waiting up to %v for inflight events to finish processing\", waitShutdown)\n\treturn errors.Wrap(p.wg.WaitTimeout(waitShutdown), \"shutdown\")\n}", "func (sc *serverConfig) Shutdown() {\n\tlog.Println(\"shutting down http server...\")\n\tsc.Shutdown()\n}", "func (httpAPI *HTTPAPIService) Shutdown(ctx context.Context) error {\n\tlog.Println(\"shutting down HTTP API service...\")\n\tif err := httpAPI.e.Shutdown(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (f *Fastglue) Shutdown(s *fasthttp.Server, shutdownComplete chan error) {\n\tshutdownComplete <- f.Server.Shutdown()\n}", "func (a *AbstractSSHConnectionHandler) OnShutdown(_ context.Context) {}", "func (s Server) Shutdown() {\n\ts.logger.Error(s.server.Shutdown(context.Background()))\n}", "func (server *Server) Shutdown() errors.Error {\n\t// graceful shutdown: https://github.com/gin-gonic/examples/blob/master/graceful-shutdown/graceful-shutdown/server.go\n\tcontext, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\treturn errors.Wrap(server.asyncServer.Shutdown(context))\n}", "func (s *Server) Close() error {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\t// Perform a best-effort final flush.\n\t\tif s.logtail != nil {\n\t\t\ts.logtail.Shutdown(ctx)\n\t\t}\n\t\tif s.logbuffer != nil {\n\t\t\ts.logbuffer.Close()\n\t\t}\n\t}()\n\n\tif _, isMemStore := s.Store.(*mem.Store); isMemStore && s.Ephemeral && s.lb != nil {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\t// Perform a best-effort logout.\n\t\t\ts.lb.LogoutSync(ctx)\n\t\t}()\n\t}\n\n\tif s.netstack != nil {\n\t\ts.netstack.Close()\n\t\ts.netstack = nil\n\t}\n\tif s.shutdownCancel != nil {\n\t\ts.shutdownCancel()\n\t}\n\tif s.lb != nil {\n\t\ts.lb.Shutdown()\n\t}\n\tif s.linkMon != nil {\n\t\ts.linkMon.Close()\n\t}\n\tif s.dialer != nil {\n\t\ts.dialer.Close()\n\t}\n\tif s.localAPIListener != nil {\n\t\ts.localAPIListener.Close()\n\t}\n\tif s.localAPITCPListener != nil {\n\t\ts.localAPITCPListener.Close()\n\t}\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, ln := range s.listeners {\n\t\tln.Close()\n\t}\n\ts.listeners = nil\n\n\twg.Wait()\n\treturn nil\n}", "func (e noop) Shutdown(ctx context.Context) error {\n\treturn nil\n}", "func (a *App) Shutdown() {\n\ta.Trace(\"lego.shutdown\", \"Gracefully shutting down...\")\n\ta.disco.Leave(a.appCtx)\n\tif !a.Drain() {\n\t\ta.Trace(\"lego.shutdown.abort\", \"Server already draining\")\n\t\treturn\n\t}\n\ta.close()\n}", "func (s *Server) Shutdown(graceful bool) {\n\ts.yorkieServiceCancel()\n\n\tif graceful {\n\t\ts.grpcServer.GracefulStop()\n\t} else {\n\t\ts.grpcServer.Stop()\n\t}\n}", "func (e *Etcd) Shutdown() error {\n\tetcdStopped := e.etcd.Server.StopNotify()\n\te.etcd.Close()\n\t<-etcdStopped\n\treturn nil\n}", "func Shutdown() {\n\tlog.Info().Msg(\"Shutting down HTTP server gracefully...\")\n\terr := E.Shutdown(nil)\n\tif err != nil {\n\t\tlog.Error().Msgf(\"Failed to shutdown HTTP server gracefully: %s\", err.Error())\n\t}\n}", "func (g *Manager) ShutdownContext() context.Context {\n\treturn g.shutdownCtx\n}", "func (s *Server) Shutdown() {\n\tclose(stop)\n}", "func (s *Server) Shutdown() {\n\ts.log.Info(\"shutting down server\", zap.Int(\"peers\", s.PeerCount()))\n\ts.transport.Close()\n\ts.discovery.Close()\n\ts.consensus.Shutdown()\n\tfor _, p := range s.getPeers(nil) {\n\t\tp.Disconnect(errServerShutdown)\n\t}\n\ts.bQueue.discard()\n\ts.bSyncQueue.discard()\n\tif s.StateRootCfg.Enabled {\n\t\ts.stateRoot.Shutdown()\n\t}\n\tif s.oracle != nil {\n\t\ts.oracle.Shutdown()\n\t}\n\tif s.notaryModule != nil {\n\t\ts.notaryModule.Stop()\n\t}\n\tif s.chain.P2PSigExtensionsEnabled() {\n\t\ts.notaryRequestPool.StopSubscriptions()\n\t}\n\tclose(s.quit)\n}", "func (s *Server) Close() error {\n\ts.mixerContext.Server.GracefulStop()\n\t<-s.shutdown\n\tclose(s.shutdown)\n\ts.mixerContext = nil\n\treturn nil\n}", "func (s *Rest) Shutdown() {\n\tlog.Print(\"[WARN] shutdown rest server\")\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\n\tdefer cancel()\n\n\ts.lock.Lock()\n\n\tif s.httpServer != nil {\n\t\tif err := s.httpServer.Shutdown(ctx); err != nil {\n\t\t\tlog.Printf(\"[DEBUG] rest shutdown error, %s\", err)\n\t\t}\n\t}\n\n\tlog.Print(\"[DEBUG] shutdown rest server completed\")\n\n\ts.lock.Unlock()\n}", "func (a *AbstractHandler) OnShutdown(_ context.Context) {\n}", "func (s *Rest) Shutdown() {\n\tlog.Print(\"[WARN] shutdown rest server\")\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\ts.lock.Lock()\n\tif err := s.httpServer.Shutdown(ctx); err != nil {\n\t\tlog.Printf(\"[DEBUG] rest shutdown error, %s\", err)\n\t}\n\tlog.Print(\"[DEBUG] shutdown rest server completed\")\n\ts.lock.Unlock()\n}", "func (a *AbstractNetworkConnectionHandler) OnShutdown(_ context.Context) {}", "func (s *Server) Shutdown() error {\n\ts.server.GracefulStop()\n\treturn nil\n}", "func (srv *Server) Shutdown() {\n\tsrv.opsLock.Lock()\n\tsrv.shutdown = true\n\t// Don't block if there's no currently processed operations\n\tif srv.currentOps < 1 {\n\t\treturn\n\t}\n\tsrv.opsLock.Unlock()\n\t<-srv.shutdownRdy\n}", "func (s *Server) Shutdown() {\n\tlog.Printf(\"server Shutdown 1\")\n\n\tif s.cancel != nil {\n\t\ts.cancel()\n\t}\n\n\t// Wait until interfaces shut down\n\ts.grpcStopped.Wait()\n\ts.restStopped.Wait()\n}" ]
[ "0.7094715", "0.70458925", "0.68298435", "0.6741759", "0.66677463", "0.66280496", "0.66003054", "0.6597964", "0.6582366", "0.6554484", "0.6533769", "0.6530384", "0.642576", "0.6360936", "0.6360936", "0.6354501", "0.6329415", "0.6311131", "0.6302091", "0.6264521", "0.62461084", "0.62369686", "0.6232691", "0.623039", "0.6226544", "0.6224457", "0.6216889", "0.62125933", "0.6204238", "0.6173548", "0.6150981", "0.6144927", "0.61439985", "0.61422354", "0.61344534", "0.6106832", "0.61060953", "0.60937256", "0.60864216", "0.608169", "0.6047764", "0.60447145", "0.6044559", "0.60325015", "0.603127", "0.602464", "0.6006222", "0.6003998", "0.6003998", "0.5988711", "0.59755605", "0.5971223", "0.59709", "0.59601545", "0.5958315", "0.59579146", "0.5957061", "0.595562", "0.59420794", "0.5939873", "0.5937449", "0.5935904", "0.59186655", "0.59164566", "0.5894775", "0.58882105", "0.5879834", "0.58740264", "0.5869915", "0.5866422", "0.58660334", "0.5842267", "0.5840389", "0.5836517", "0.5830997", "0.5802396", "0.57861954", "0.5781305", "0.57797056", "0.5773517", "0.5772727", "0.5759723", "0.5734398", "0.5723469", "0.57182664", "0.5711851", "0.5700919", "0.56986713", "0.56960076", "0.569386", "0.5690167", "0.5685471", "0.5680385", "0.56803054", "0.56751555", "0.5673346", "0.5635361", "0.5632903", "0.56320935", "0.5629961" ]
0.59859467
50
Close immediately closes all active net.Listeners and any connections. For a graceful shutdown, use Shutdown. Close returns any error returned from closing the Server's underlying Listener(s).
func (srv *TCPServer) Close() (err error) { err = srv.l.Close() select { case srv.closeCh <- struct{}{}: default: } srv.connsMu.RLock() for _, c := range srv.conns { select { case c.closeCh <- struct{}{}: default: } c.conn.Close() } srv.connsMu.RUnlock() return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Server) Close() error {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\t// Perform a best-effort final flush.\n\t\tif s.logtail != nil {\n\t\t\ts.logtail.Shutdown(ctx)\n\t\t}\n\t\tif s.logbuffer != nil {\n\t\t\ts.logbuffer.Close()\n\t\t}\n\t}()\n\n\tif _, isMemStore := s.Store.(*mem.Store); isMemStore && s.Ephemeral && s.lb != nil {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\t// Perform a best-effort logout.\n\t\t\ts.lb.LogoutSync(ctx)\n\t\t}()\n\t}\n\n\tif s.netstack != nil {\n\t\ts.netstack.Close()\n\t\ts.netstack = nil\n\t}\n\tif s.shutdownCancel != nil {\n\t\ts.shutdownCancel()\n\t}\n\tif s.lb != nil {\n\t\ts.lb.Shutdown()\n\t}\n\tif s.linkMon != nil {\n\t\ts.linkMon.Close()\n\t}\n\tif s.dialer != nil {\n\t\ts.dialer.Close()\n\t}\n\tif s.localAPIListener != nil {\n\t\ts.localAPIListener.Close()\n\t}\n\tif s.localAPITCPListener != nil {\n\t\ts.localAPITCPListener.Close()\n\t}\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, ln := range s.listeners {\n\t\tln.Close()\n\t}\n\ts.listeners = nil\n\n\twg.Wait()\n\treturn nil\n}", "func (s *Server) Close() error {\n\tvar err error\n\ts.mutex.Lock()\n\n\tif s.shutdown != nil {\n\t\ts.shutdown()\n\t}\n\n\tfor l := range s.listeners {\n\t\tif cerr := l.Close(); cerr != nil && err == nil {\n\t\t\terr = cerr\n\t\t}\n\t}\n\n\tfor c := range s.connections {\n\t\tc.Close()\n\t}\n\n\ts.mutex.Unlock()\n\treturn err\n}", "func (s *Server) Close() error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\ts.closed = true\n\n\tvar err error\n\tfor ln := range s.listeners {\n\t\tif cerr := (*ln).Close(); cerr != nil && err == nil {\n\t\t\terr = cerr\n\t\t}\n\t}\n\treturn err\n}", "func (s *Server) Close() error {\n\tselect {\n\tcase <-s.done:\n\t\treturn ErrServerClosed\n\tdefault:\n\t\tclose(s.done)\n\t}\n\n\tvar err error\n\ts.locker.Lock()\n\tfor _, l := range s.listeners {\n\t\tif lerr := l.Close(); lerr != nil && err == nil {\n\t\t\terr = lerr\n\t\t}\n\t}\n\n\tfor conn := range s.conns {\n\t\tconn.Close()\n\t}\n\ts.locker.Unlock()\n\n\treturn err\n}", "func (s *Server) Close() error {\n\tif s.Listener != nil {\n\t\terr := s.Listener.Close()\n\t\ts.Listener = nil\n\t\treturn err\n\t}\n\treturn nil\n}", "func (srv *Server) Close() error {\n\tsrv.inShutdown.Store(true)\n\tsrv.mu.Lock()\n\tdefer srv.mu.Unlock()\n\tsrv.closeDoneChanLocked()\n\n\terr := srv.closeListenersLocked()\n\tfor c := range srv.activeConn {\n\t\tc.close()\n\t\tdelete(srv.activeConn, c)\n\t}\n\tif srv.Handler == nil {\n\t\tDefaultServeMux.Close()\n\t} else {\n\t\tif closer, ok := srv.Handler.(io.Closer); ok {\n\t\t\tcloser.Close()\n\t\t}\n\t}\n\treturn err\n}", "func (srv *Server) Close() error {\n\tsrv.inShutdown.setTrue()\n\tsrv.mu.Lock()\n\tdefer srv.mu.Unlock()\n\tsrv.closeDoneChanLocked()\n\terr := srv.closeListenersLocked()\n\tfor c := range srv.activeConn {\n\t\tc.rwc.Close()\n\t\tdelete(srv.activeConn, c)\n\t}\n\treturn err\n}", "func (s *Server) Close() {\n\ts.mu.Lock()\n\tif !s.closed {\n\t\ts.closed = true\n\t\ts.Listener.Close()\n\t\tfor c, _ := range s.conns {\n\t\t\tc.Close()\n\t\t}\n\t}\n\ts.mu.Unlock()\n}", "func (s *server) Close() error {\n\treturn s.listener.Close()\n}", "func (server *SServer) Close() error {\n\tvar err error\n\tfor _, listener := range server.listeners {\n\t\tif err_ := listener.Close(); err_ != nil && err == nil {\n\t\t\terr = err_\n\t\t}\n\t}\n\treturn err\n}", "func (s *Server) Close() {\n\ts.rwlock.Lock()\n\tdefer s.rwlock.Unlock()\n\n\tif s.listener != nil {\n\t\terr := s.listener.Close()\n\t\tterror.Log(errors.Trace(err))\n\t\ts.listener = nil\n\t}\n\tmetrics.ServerEventCounter.WithLabelValues(metrics.EventClose).Inc()\n}", "func (s *Server) Close() error {\n\treturn s.listener.Close()\n}", "func (s *Server) Close() error {\n\treturn s.listener.Close()\n}", "func (l *Listener) Close() {\n\tclose(l.shutdownChan)\n\tl.tcpListener.Close()\n}", "func (l *Listener) Close() {\n\tclose(l.Shutdown)\n\tl.Shutdown = nil\n}", "func (s *Server) Close() {\n\ts.running = false\n\tif s.listener != nil {\n\t\ts.listener.Close()\n\t\ts.listener = nil\n\t}\n}", "func (server *Server) Close() {\n\tserver.Lock()\n\tserver.halting = true\n\tserver.Unlock()\n\n\tif len(server.tlsCertificate.Certificate) == 0 {\n\t\terr := server.netListener.Close()\n\t\tif err != nil {\n\t\t\tserver.logger.Printf(\"server.netListener.Close() returned err: %v\\n\", err)\n\t\t}\n\t} else {\n\t\terr := server.tlsListener.Close()\n\t\tif err != nil {\n\t\t\tserver.logger.Printf(\"server.tlsListener.Close() returned err: %v\\n\", err)\n\t\t}\n\t}\n\n\tserver.listenersWG.Wait()\n\n\tserver.goroutineWG.Wait()\n\n\t// Now close the client sockets to wakeup them up\n\tserver.closeClientConn()\n\n\tif !server.dontStartTrimmers {\n\t\tserver.completedLongTicker.Stop()\n\t\tserver.completedShortTicker.Stop()\n\t}\n\tserver.completedTickerDone <- true\n\tserver.completedDoneWG.Wait()\n\n\t// Cleanup bucketstats so that unit tests can run\n\tfor _, ci := range server.perClientInfo {\n\t\tci.Lock()\n\t\tci.unregsiterMethodStats(server)\n\t\tci.Unlock()\n\n\t}\n}", "func (s *Server) Close() error {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\treturn s.listener.Close()\n}", "func (s *Servers) Close() {\n\tfor _, srv := range s.listeners {\n\t\tif srv != nil {\n\t\t\tsrv.Close()\n\t\t}\n\t}\n}", "func (s *TCPServer) Close() {\n\ts.listener.Close()\n}", "func (server *TCPServer) Close() {\n\tif server.listener != nil {\n\t\tlistener := server.listener\n\t\tserver.listener = nil\n\t\tlistener.Close()\n\t}\n}", "func (s *Server) Close() error {\n\ts.cancelMx.Lock()\n\tif s.cancel != nil {\n\t\ts.cancel()\n\t}\n\ts.cancelMx.Unlock()\n\n\treturn s.listener.Close()\n}", "func (s *Server) Close() {\n\tgo func() {\n\t\tfor co := range s.accept {\n\t\t\tco.NConn.Close()\n\t\t}\n\t}()\n\ts.l.Close()\n\ts.wg.Wait()\n\tclose(s.accept)\n}", "func (s *TCPServer) Close() error {\n\treturn s.listener.Close()\n}", "func (s *Server) Close() {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tif s.closed {\n\t\treturn\n\t}\n\n\ts.closed = true\n\ts.Listener.Close()\n\ts.CloseClientConnections()\n}", "func (s *SimpleServer) Close() error {\n\tif s.Listener == nil {\n\t\treturn nil\n\t}\n\treturn s.Listener.Close()\n}", "func (s *Server) Close() error {\n\terrL := s.l.Close()\n\terrDB := s.db.Close()\n\tif errL != nil {\n\t\treturn errors.Wrap(errL, \"listener\")\n\t}\n\tif errDB != nil {\n\t\treturn errors.Wrap(errDB, \"DB\")\n\t}\n\treturn nil\n}", "func (l *Listener) Close() error {\n\treturn nil\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\tif s.closing == nil {\n\t\t// Nothing to do\n\t\treturn nil\n\t}\n\tclose(s.closing)\n\n\t// Stops listening.\n\terr := s.closeListener()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\t// Forces closing of all actives connections.\n\t\t\ts.close()\n\t\t\treturn ctx.Err()\n\t\tcase <-s.closed:\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (l *Listener) Close() error {\n\tremoveListener(l)\n\n\tl.Lock()\n\tdefer l.Unlock()\n\n\tif l.connections == nil {\n\t\treturn &net.OpError{\n\t\t\tOp: \"close\",\n\t\t\tNet: \"fake\",\n\t\t\tSource: l.Addr(),\n\t\t\tErr: fmt.Errorf(\"closed already\"),\n\t\t}\n\t}\n\n\tclose(l.connections)\n\tl.connections = nil\n\treturn nil\n}", "func (r *Listener) Close() error {\n\tr.portsLk.Lock()\n\tdefer r.portsLk.Unlock()\n\n\tfor n, port := range r.ports {\n\t\tif err := port.Close(); err != nil {\n\t\t\tr.ports = r.ports[n:] // drop any port that was successfully closed\n\t\t\treturn err\n\t\t}\n\t}\n\tr.ports = nil\n\treturn nil\n}", "func (s *Server) Close() {\n\tgo func() {\n\t\tfor co := range s.accept {\n\t\t\tco.Close()\n\t\t}\n\t}()\n\ts.srv.Close()\n\t<-s.done\n}", "func (s *Server) Close() {\n\ts.rtspListener.Close()\n\tclose(s.shutdown)\n}", "func (listener *Listener) Close() error {\n\tlistener.close()\n\n\tvar err error\n\tlistener.connections.Range(func(key, value interface{}) bool {\n\t\tconn := value.(*Conn)\n\t\tif closeErr := conn.Close(); err != nil {\n\t\t\terr = fmt.Errorf(\"error closing conn %v: %v\", conn.addr, closeErr)\n\t\t}\n\t\treturn true\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := listener.conn.Close(); err != nil {\n\t\treturn fmt.Errorf(\"error closing UDP listener: %v\", err)\n\t}\n\treturn nil\n}", "func (srv *Server) Close() error {\n\tdefer close(srv.closeChan)\n\tsrv.closeMu.Lock()\n\tdefer srv.closeMu.Unlock()\n\t// Stop accepting API requests.\n\terr := srv.apiServer.Shutdown(context.Background())\n\t// Wait for serve() to return and capture its error.\n\t<-srv.serveChan\n\tif !errors.Contains(srv.serveErr, http.ErrServerClosed) {\n\t\terr = errors.Compose(err, srv.serveErr)\n\t}\n\t// Shutdown modules.\n\tif srv.node != nil {\n\t\terr = errors.Compose(err, srv.node.Close())\n\t}\n\treturn errors.AddContext(err, \"error while closing server\")\n}", "func (s *Server) Close() (err error) {\n\treturn\n}", "func (ml *ManagedListener) Close() {\n\tif ml != nil {\n\t\tdefer trace.Tracer.ScopedTrace()()\n\t\tdefer ml.Monitor()()\n\t\tif ml.Canceled != nil {\n\t\t\tclose(ml.Canceled)\n\t\t\tml.Canceled = make(chan struct{})\n\t\t}\n\t\tif ml.Listener != nil {\n\t\t\tif err := ml.Listener.Close(); err != nil {\n\t\t\t\tlog.Println(\"Error closing listener\", ml.Listener)\n\t\t\t}\n\t\t\tvar pipes = []*pipe.Pipe{}\n\t\t\tfor pipe := range ml.Pipes {\n\t\t\t\tgo pipe.Close()\n\t\t\t\tpipes = append(pipes, pipe)\n\t\t\t}\n\t\t\tfor _, pipe := range pipes {\n\t\t\t\tdelete(ml.Pipes, pipe)\n\t\t\t}\n\t\t}\n\t\tml.RemoveExternalIP()\n\t}\n}", "func (s *Server) Close() error {\n if s.ln != nil {\n s.ln.Close()\n }\n return nil\n}", "func (s *Server) Close() error {\n\t// Notify other goroutines of shutdown.\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.conn == nil {\n\t\treturn errors.New(\"server already closed\")\n\t}\n\ts.conn.Close()\n\ts.conn = nil\n\n\t// Wait for all goroutines to shutdown.\n\ts.wg.Wait()\n\tlog.Printf(\"all waitgroups finished\")\n\n\treturn nil\n}", "func (s *Server) Close() error {\n\t// TODO(sajjadm): Determine if some pending connections were forcefully closed by s.cancel()\n\t// and report that as an error.\n\ts.cancel()\n\treturn s.ln.Close()\n}", "func (srv *Server) Close() error {\n\therr := srv.http.server.Close()\n\thherr := srv.http.health.Close()\n\tserr := srv.ssh.server.Close()\n\tif herr != nil || hherr != nil || serr != nil {\n\t\treturn fmt.Errorf(\"one or more servers had an error closing: %s %s %s\", herr, hherr, serr)\n\t}\n\terr := srv.Config.DB.Close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"db close error: %s\", err)\n\t}\n\tif srv.Config.Stats != nil {\n\t\tif err := srv.Config.Stats.Close(); err != nil {\n\t\t\treturn fmt.Errorf(\"db close error: %s\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Listener) Close() error {\n\treturn s.Listener.Close()\n}", "func Close() error {\n\treturn server.Close()\n}", "func (s *Server) Close() {\n\tfor _, srv := range s.servers {\n\t\tif err := srv.Close(); err != nil {\n\t\t\tlogrus.Error(err)\n\t\t}\n\t}\n}", "func (s *Server) Close() error {\n\tclose(s.stop)\n\t<-s.stopped\n\n\tvar closers []io.Closer\n\n\ts.webSocketsMutex.Lock()\n\tfor ws := range s.webSockets {\n\t\tclosers = append(closers, ws)\n\t}\n\ts.webSocketsMutex.Unlock()\n\n\tfor _, closer := range closers {\n\t\tcloser.Close()\n\t}\n\treturn nil\n}", "func (ln *Listener) Close() error {\n\treturn ln.tcpLn.Close()\n}", "func (l *Listener) Close() error {\n\treturn l.Listener.Close()\n}", "func (n *Node) Close() error {\n\tn.closing = true\n\tn.listener.Close()\n\tfor _, conn := range n.connections {\n\t\tconn.Close()\n\t}\n\treturn nil\n}", "func (s *Server) Close() error {\n\tif s.ln != nil {\n\t\ts.ln.Close()\n\t}\n\treturn nil\n}", "func Close() {\n\tif quit != nil {\n\t\t// must close quit first\n\t\tclose(quit)\n\t\tlistener.Close()\n\t\tlistener = nil\n\t}\n}", "func (s *Server) Close() error {\n\treturn s.ln.Close()\n}", "func (s *Server) Close() error {\n\treturn s.ln.Close()\n}", "func (s *Server) Close() {\n\tif !atomic.CompareAndSwapInt64(&s.closed, 0, 1) {\n\t\t// server is already closed\n\t\treturn\n\t}\n\n\tlog.Info(\"closing server\")\n\ts.closeAllConnections()\n\tif s.metricMeter != nil {\n\t\ts.metricMeter.Stop()\n\t}\n\tif s.l != nil {\n\t\ts.l.Close()\n\t}\n\ts.wg.Wait()\n\n\tlog.Info(\"close server\")\n}", "func (s *MockServer) Close() {\n\ts.Listener.Close()\n\ts.CloseClientConnections()\n}", "func (l *Listener) Close() error {\n\tif l.close() {\n\t\treturn nil\n\t}\n\treturn ErrClientClosed\n}", "func (p *Listener) Close() error { return p.Listener.Close() }", "func (serv *Server) Close() (e error) {\n log.Println(\"Shutting down server.\")\n\n if serv.logFile != nil {\n e = serv.logFile.Close()\n }\n\n if serv.db != nil {\n e = serv.db.Close()\n }\n\n return e\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\tselect {\n\tcase <-s.done:\n\t\treturn ErrServerClosed\n\tdefault:\n\t\tclose(s.done)\n\t}\n\n\tvar err error\n\ts.locker.Lock()\n\tfor _, l := range s.listeners {\n\t\tif lerr := l.Close(); lerr != nil && err == nil {\n\t\t\terr = lerr\n\t\t}\n\t}\n\ts.locker.Unlock()\n\n\tconnDone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(connDone)\n\t\ts.wg.Wait()\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-connDone:\n\t\treturn err\n\t}\n}", "func (i *invoker) Close() error {\n\ti.cancelPF()\n\n\t// Closing the local listener effectively closes the gRPC connection\n\tif err := i.listener.Close(); err != nil {\n\t\ti.conn.Close() // If we fail to close the listener, explicitly close the gRPC connection and ignore any error\n\t\treturn fmt.Errorf(\"failed to close local tcp port listener: %w\", err)\n\t}\n\n\treturn nil\n}", "func (l *listener) Close() error {\n\tvar err error\n\tl.doneOnce.Do(func() {\n\t\tl.accepting.Store(false)\n\t\tclose(l.doneCh)\n\n\t\tl.connLock.Lock()\n\t\t// Close unaccepted connections\n\tlclose:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase c := <-l.acceptCh:\n\t\t\t\tclose(c.doneCh)\n\t\t\t\t// If we have an alternate identifier, remove it from the connection\n\t\t\t\t// map.\n\t\t\t\tif id := c.id.Load(); id != nil {\n\t\t\t\t\tdelete(l.conns, id.(string)) //nolint:forcetypeassert\n\t\t\t\t}\n\t\t\t\t// If we haven't already removed the remote address, remove it\n\t\t\t\t// from the connection map.\n\t\t\t\tif !c.rmraddr.Load() {\n\t\t\t\t\tdelete(l.conns, c.raddr.String())\n\t\t\t\t\tc.rmraddr.Store(true)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak lclose\n\t\t\t}\n\t\t}\n\t\tnConns := len(l.conns)\n\t\tl.connLock.Unlock()\n\n\t\tl.connWG.Done()\n\n\t\tif nConns == 0 {\n\t\t\t// Wait if this is the final connection.\n\t\t\tl.readWG.Wait()\n\t\t\tif errClose, ok := l.errClose.Load().(error); ok {\n\t\t\t\terr = errClose\n\t\t\t}\n\t\t} else {\n\t\t\terr = nil\n\t\t}\n\t})\n\n\treturn err\n}", "func (v *vsockListener) Close() error {\n\t// Note this won't cause the Accept to unblock.\n\treturn unix.Close(v.fd)\n}", "func (s *Service) Close() error {\n\tdefer s.diag.StoppedService()\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\t// If server is not set we were never started\n\tif s.server == nil {\n\t\treturn nil\n\t}\n\t// First turn off KeepAlives so that new connections will not become idle\n\ts.server.SetKeepAlivesEnabled(false)\n\t// Signal to manage loop we are stopping\n\tstopping := make(chan struct{})\n\ts.stop <- stopping\n\n\t// Next close the listener so no new connections can be made\n\terr := s.ln.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t<-stopping\n\ts.wg.Wait()\n\ts.server = nil\n\treturn nil\n}", "func Close() {\n\tmainServer.Close()\n}", "func (l *listener) Close() error {\n\tl.L.Lock()\n\terr := l.err\n\tif err == nil {\n\t\tl.err = ErrListenerClosed\n\t}\n\tl.L.Unlock()\n\tl.Broadcast()\n\n\tif err == nil {\n\t\tl.stopListening()\n\t}\n\n\treturn errors.New(\"Not implemented\")\n}", "func (ln *StoppableListener) Close() error {\n\tfor _, v := range ln.listeners {\n\t\tif err := v.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Server) Close() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.ln == nil {\n\t\treturn errors.New(\"not serving\")\n\t}\n\ts.done = true\n\treturn s.ln.Close()\n}", "func (s *server) Close(ctx context.Context) error {\n\treturn s.server.Shutdown(ctx)\n}", "func (s *Server) Close() error {\n\ts.Server.Stop()\n\n\treturn nil\n}", "func (l *Listener) Close() error {\n\tdefer log.Debugf(\"trafficshape: closed read/write buckets and connection\")\n\n\tl.rb.Close()\n\tl.wb.Close()\n\n\treturn l.Listener.Close()\n}", "func (s *Server) Close() error {\n\treturn s.httpServer.Shutdown(context.Background())\n}", "func (listener *Listener) Close() error {\n\treturn listener.base.Close()\n}", "func (p *Listener) Close() error {\n\treturn p.Listener.Close()\n}", "func (l *Listener) Close() error {\n\tif err := l.lowerListener.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tl.endpoint = \"\"\n\tl.rcvBufSize = 0\n\tl.sndBufSize = 0\n\treturn nil\n}", "func (a *AgentServer) Close() error {\n\tvar errors []error\n\tif a.listener != nil {\n\t\tlog.Debugf(\"AgentServer(%v) is closing\", a.listener.Addr())\n\t\tif err := a.listener.Close(); err != nil {\n\t\t\terrors = append(errors, trace.ConvertSystemError(err))\n\t\t}\n\t}\n\tif a.Path != \"\" {\n\t\tif err := os.Remove(a.Path); err != nil {\n\t\t\terrors = append(errors, trace.ConvertSystemError(err))\n\t\t}\n\t}\n\tif a.Dir != \"\" {\n\t\tif err := os.RemoveAll(a.Dir); err != nil {\n\t\t\terrors = append(errors, trace.ConvertSystemError(err))\n\t\t}\n\t}\n\treturn trace.NewAggregate(errors...)\n}", "func (s *Server) Close() {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\n\tgo func(ctx context.Context) {\n\t\t<-ctx.Done()\n\t\tif errors.Is(ctx.Err(), context.Canceled) {\n\t\t\treturn\n\t\t} else if errors.Is(ctx.Err(), context.DeadlineExceeded) {\n\t\t\tpanic(\"Timeout while stopping traefik, killing instance ✝\")\n\t\t}\n\t}(ctx)\n\n\tstopMetricsClients()\n\n\ts.routinesPool.Stop()\n\n\tsignal.Stop(s.signals)\n\tclose(s.signals)\n\n\tclose(s.stopChan)\n\n\ts.chainBuilder.Close()\n\n\tcancel()\n}", "func (l *TCPListener) Close() error {\n\tif l == nil || l.fd == nil {\n\t\treturn syscall.EINVAL\n\t}\n\treturn l.fd.Close()\n}", "func (s *ListenerServerStream) Close() error {\n\tvar err error\n\tif s.conn == nil {\n\t\treturn nil\n\t}\n\tif err = s.conn.WriteControl(\n\t\twebsocket.CloseMessage,\n\t\twebsocket.FormatCloseMessage(websocket.CloseNormalClosure, \"server closing connection\"),\n\t\ttime.Now().Add(time.Second),\n\t); err != nil {\n\t\treturn err\n\t}\n\treturn s.conn.Close()\n}", "func (s *Server) Close() {\n\ts.serverUDP.Close()\n\tastilog.Debug(\"Stopping server\")\n}", "func (s *Server) Close() {\n\t// stop the server\n\ts.e.Close()\n}", "func (s *Server) Close() error {\n\ts.server.Stop()\n\treturn nil\n}", "func (l *listener) Close() error {\n\tl.cancel()\n\tl.host.RemoveStreamHandler(l.tag)\n\treturn nil\n}", "func (p *Proxy) Close() {\n\tlog.Println(\"[Server] Closing connections...\")\n\n\tp.closeMutex.Lock()\n\tp.closed = true\n\tp.closeMutex.Unlock()\n\n\tp.remote.Close()\n\tp.client.Close()\n\tp.listener.Close()\n}", "func (s *MaplAdapter) Close() error {\n\tif s.server != nil {\n\t\ts.server.GracefulStop()\n\t}\n\n\tif s.listener != nil {\n\t\t_ = s.listener.Close()\n\t}\n\n\treturn nil\n}", "func (g *Gateway) Close() error {\n\tlog.Infof(\"server at %s terminating...\", g.listener.Addr())\n\treturn g.listener.Close()\n}", "func (c *AuditClient) Close() error {\n\tvar err error\n\n\t// Only unregister and close the socket once.\n\tc.closeOnce.Do(func() {\n\t\tif c.clearPIDOnClose {\n\t\t\t// Unregister from the kernel for a clean exit.\n\t\t\tstatus := AuditStatus{\n\t\t\t\tMask: AuditStatusPID,\n\t\t\t\tPID: 0,\n\t\t\t}\n\t\t\terr = c.set(status, NoWait)\n\t\t}\n\n\t\terr = multierr.Append(err, c.Netlink.Close())\n\t})\n\n\treturn err\n}", "func (t *TLSServer) Close() error {\n\terrC := make(chan error, 2)\n\tgo func() {\n\t\terrC <- t.httpServer.Close()\n\t}()\n\tgo func() {\n\t\tt.grpcServer.server.Stop()\n\t\terrC <- nil\n\t}()\n\terrors := []error{}\n\tfor i := 0; i < 2; i++ {\n\t\terrors = append(errors, <-errC)\n\t}\n\terrors = append(errors, t.mux.Close())\n\treturn trace.NewAggregate(errors...)\n}", "func (p *PureProxy) Close() (err error) {\n\tatomic.StoreInt32(&p.inShutdown, 1)\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tp.closeDoneChanLocked()\n\tif p.listener != nil {\n\t\terr = (*p.listener).Close()\n\t\tp.listener = nil\n\t}\n\tfor c := range p.activeConn {\n\t\tc.rwc.Close()\n\t\tdelete(p.activeConn, c)\n\t}\n\treturn\n}", "func (s *Server) Close() error {\n\treturn s.srv.Close()\n}", "func (s *Server) Close() error {\n\treturn s.srv.Close()\n}", "func (s *Sockets) Close() {\n\ts.close <- struct{}{}\n}", "func (dg *App) Close() (err error) {\n\tdg.objsLock.Lock()\n\tdefer dg.objsLock.Unlock()\n\n\tchk := func(err_ error) {\n\t\tif err == nil {\n\t\t\terr = err_\n\t\t}\n\t}\n\n\t// stop consuming more request first\n\tchk(dg.b.StopAllListeners())\n\n\t// further reporter(s) should be reported to Reporter(s)\n\t// after workers/mappers shutdown\n\n\t// shutdown mappers\n\tchk(dg.mappers.Close())\n\n\t// shutdown workers\n\tchk(dg.workers.Close())\n\n\t// stop reporter/store\n\tfor _, v := range dg.objs {\n\t\ts, ok := v.obj.(Object)\n\t\tif ok {\n\t\t\tchk(s.Close())\n\t\t}\n\t}\n\n\tchk(dg.b.Close())\n\n\t// shutdown mux\n\tdg.eventMux.Close()\n\n\t// shutdown the monitor of error channels\n\tfunc() {\n\t\tdg.eventOutLock.Lock()\n\t\tdefer dg.eventOutLock.Unlock()\n\n\t\tm := dg.eventOut.Load().(map[int]*_eventListener)\n\t\tfor _, v := range m {\n\t\t\t// send channel-close event\n\t\t\tclose(v.events)\n\t\t}\n\t\tdg.eventOut.Store(make(map[int]*_eventListener))\n\t}()\n\n\treturn\n}", "func (s *Server) Close() error {\n\treturn s.server.Close()\n}", "func (s *Server) Shutdown() {\n\t// TODO(aditya) shut down workers and socket readers\n\ts.logger.Info(\"Shutting down server gracefully\")\n\tclose(s.shutdown)\n\tif s.FlushOnShutdown {\n\t\tctx, cancel := context.WithTimeout(context.Background(), s.Interval)\n\t\ts.Flush(ctx)\n\t\tcancel()\n\t}\n\tgraceful.Shutdown()\n\tfor _, source := range s.sources {\n\t\tsource.source.Stop()\n\t}\n\n\t// Close the gRPC connection for forwarding\n\tif s.grpcForwardConn != nil {\n\t\ts.grpcForwardConn.Close()\n\t}\n}", "func (p *TCPProxy) Close() error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tp.closed = true\n\tp.listener.Close()\n\tfor _, c := range p.conns {\n\t\tc.Close()\n\t}\n\treturn nil\n}", "func (s *Server) Shutdown(ctx context.Context) error {\n\tconst (\n\t\tminPollInterval = 10 * time.Millisecond\n\t\tmaxPollInterval = 500 * time.Millisecond\n\t)\n\n\ts.mutex.Lock()\n\n\tif s.shutdown != nil {\n\t\ts.shutdown()\n\t}\n\n\tfor l := range s.listeners {\n\t\tl.Close()\n\t}\n\n\ts.mutex.Unlock()\n\n\tfor i := 0; s.numberOfActors() != 0; i++ {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tcase <-time.After(backoff(i, minPollInterval, maxPollInterval)):\n\t\t}\n\t}\n\n\treturn ctx.Err()\n}", "func Close() {\n\tFlush()\n\n\tif traceListeners != nil {\n\t\tfor _, tl := range traceListeners {\n\t\t\t(*tl).Close()\n\t\t}\n\t}\n\n\ttraceListeners = nil\n}", "func (s *Server) Close() error {\n\treturn s.httpSrv.Close()\n}", "func (l *grpcListener) Close() error {\n\tl.listenerCtxCancel()\n\treturn nil\n}", "func (l *listener) Close() error {\n\tif l.unsubscribeLogs != nil {\n\t\tl.unsubscribeLogs()\n\t}\n\tl.runs.Range(func(key, runCloserChannelIf interface{}) bool {\n\t\trunCloserChannel, _ := runCloserChannelIf.(chan struct{})\n\t\tclose(runCloserChannel)\n\t\treturn true\n\t})\n\tl.runs = sync.Map{}\n\tl.shutdownWaitGroup.Wait()\n\treturn nil\n}", "func Close() {\n\tif serverOpened == true {\n\t\tgolnet.TcpServerHalt = true\n\t\tserverOpened = false\n\t}\n}" ]
[ "0.8096452", "0.7916411", "0.79162276", "0.7643262", "0.76239103", "0.76097476", "0.75901407", "0.7529573", "0.7472624", "0.7440782", "0.74403816", "0.74033844", "0.74033844", "0.73230445", "0.7242586", "0.72332895", "0.7227414", "0.719517", "0.7186884", "0.715775", "0.7137487", "0.7125228", "0.71199185", "0.7119555", "0.7119437", "0.71131265", "0.71117014", "0.7054391", "0.70465803", "0.6999314", "0.6998647", "0.699137", "0.6971729", "0.6967314", "0.69471407", "0.69216645", "0.69057673", "0.6905676", "0.6898214", "0.68753874", "0.6860822", "0.68500346", "0.68460333", "0.684596", "0.68425786", "0.6841839", "0.68284416", "0.682553", "0.682244", "0.67970777", "0.6791671", "0.6791671", "0.67851007", "0.6770536", "0.6760258", "0.67448044", "0.67428946", "0.67348444", "0.67281854", "0.6712826", "0.6698722", "0.66891795", "0.66845703", "0.6679599", "0.6662412", "0.6655195", "0.6647199", "0.66458184", "0.6640631", "0.6639978", "0.6631715", "0.6627891", "0.66076964", "0.6603652", "0.6599743", "0.6587481", "0.6585249", "0.6583262", "0.6576383", "0.6570792", "0.65591943", "0.6555853", "0.65530735", "0.6547951", "0.65467495", "0.65436256", "0.6537795", "0.6536909", "0.6536909", "0.6535646", "0.6533078", "0.6532306", "0.6527833", "0.6514513", "0.650331", "0.65025127", "0.6502507", "0.6499654", "0.64971316", "0.64926636" ]
0.65150917
93
ListenAndServe listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming connections. ListenAndServe returns a nil error after Close or Shutdown method called.
func (srv *TCPServer) ListenAndServe() error { addr := srv.Addr l, err := net.Listen("tcp", addr) if err != nil { return err } return srv.Serve(l) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (srv *Server) ListenAndServe() (err error) {\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":3000\"\n\t}\n\n\tgo srv.handleSignals()\n\n\tsrv.ln, err = srv.getListener(addr)\n\tif err != nil {\n\t\tlog.Println(os.Getpid(), err)\n\t\treturn err\n\t}\n\n\tif srv.isChild {\n\t\tprocess, err := os.FindProcess(os.Getppid())\n\t\tif err != nil {\n\t\t\tlog.Println(os.Getpid(), err)\n\t\t\treturn err\n\t\t}\n\t\terr = process.Signal(syscall.SIGTERM)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Listening for connections on %v, pid=%d\", srv.ln.Addr(), os.Getpid()))\n\n\treturn srv.Serve()\n}", "func (srv *Server) ListenAndServe() error {\n\tif srv.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":http\"\n\t}\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn srv.Serve(ln)\n}", "func (srv *Server) ListenAndServe(addr string) error {\n\tif srv.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\tif addr == \"\" {\n\t\taddr = \":tcp\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn srv.Serve(ln)\n}", "func (srv *Server) ListenAndServe() error {\n\taddr := srv.httpServer.Addr\n\tif addr == \"\" {\n\t\taddr = \":http\"\n\t}\n\n\tln, err := srv.getListener(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrv.listener = NewWebTcpListener(ln)\n\n\treturn srv.Serve()\n}", "func (srv *Server) ListenAndServe() error {\n\tif srv.TLSConfig != nil {\n\t\tl, err := tls.Listen(\"tcp\", srv.Addr, srv.TLSConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn srv.Serve(l)\n\t}\n\tl, err := net.Listen(\"tcp\", srv.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn srv.Serve(l)\n}", "func (svr *Server) ListenAndServe() error {\n\tutils.Logger.Info(\"ListenAndServe with addr %s\", svr.Addr)\n\taddr, err := ParseAddr(svr.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tutils.Logger.Info(\"net is %s and ipport %s\", addr.Network, addr.IPPort)\n\tif addr.Network == \"tcp\" {\n\t\tln, err := net.Listen(\"tcp\", addr.IPPort)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsvr.listenAndServeTCP(ln.(*net.TCPListener), addr.Kpal)\n\t}\n\treturn nil\n}", "func (srv *Server) ListenAndServe(handler Handler) error {\n\tsrv.init(handler)\n\n\treturn srv.Server.ListenAndServe()\n}", "func (srv *Server) ListenAndServe(addr string) error {\n\tsrv.init()\n\treturn srv.driver.ListenAndServe(addr, srv.wrappedHandler)\n}", "func ListenAndServe(addr string, handler Handler) error {\n\tsrv := New(addr)\n\n\treturn srv.ListenAndServe(handler)\n}", "func (s *Server) ListenAndServe() error {\n\tlistener, err := net.Listen(\"tcp\", s.Addr)\n\tlog.Printf(\"listening\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.serve(listener)\n}", "func (s *Server) ListenAndServe() error {\n\tif s.Addr == \"\" {\n\t\treturn errs.E(errs.Internal, \"Server Addr is empty\")\n\t}\n\tif s.router == nil {\n\t\treturn errs.E(errs.Internal, \"Server router is nil\")\n\t}\n\tif s.driver == nil {\n\t\treturn errs.E(errs.Internal, \"Server driver is nil\")\n\t}\n\treturn s.driver.ListenAndServe(s.Addr, s.router)\n}", "func (srv *Server) ListenAndServe(proto, addr string) error {\n\treturn nil\n}", "func (srv *TCPServer) ListenAndServe() error {\n\tvar err error\n\tlog.Printf(\"starting server on %v\\n\", srv.Addr)\n\tsrv.listener, err = net.Listen(\"tcp\", srv.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer srv.listener.Close()\n\tfor {\n\t\tif srv.inShutdown {\n\t\t\tbreak\n\t\t}\n\t\tconn, err := srv.listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error accepting connection %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"accepted connection from %v\", conn.RemoteAddr())\n\n\t\tsConn := NewSafeConn(conn, srv.IdleTimeout)\n\t\tsrv.trackConn(sConn)\n\n\t\tgo func() {\n\t\t\tsrv.HandleFunc(sConn)\n\t\t\tlog.Printf(\"closing connection from %v\", sConn.RemoteAddr())\n\t\t\tsConn.Close()\n\t\t\tsrv.deleteConn(sConn)\n\t\t}()\n\n\t}\n\treturn nil\n}", "func (s *Server) ListenAndServe() error {\n\treturn s.server.Serve(s.listener)\n}", "func ListenAndServe(addr string, handler http.Handler, logger *zap.Logger) error {\n\tl, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tserver := NewServer(handler, logger)\n\tserver.ListenForSignals(os.Interrupt, syscall.SIGTERM)\n\treturn server.Serve(l)\n}", "func ListenAndServe(addr string, handler Handler) error {\n\treturn (&Server{Addr: addr, Handler: handler}).ListenAndServe()\n}", "func ListenAndServe(addr string, handler Handler) error {\n\tserver := &Server{Addr: addr, Handler: handler}\n\treturn server.ListenAndServe()\n}", "func ListenAndServe(addr string, srcvr ...interface{}) {\n\terr := listen(addr, srcvr...)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Println(\"rpc server listen:\", addr)\n}", "func ListenAndServe(ctx context.Context, addr string, handler Handler) error {\n\tserver := New(ctx)\n\tserver.MatchAndGoServe(handler)\n\treturn server.ListenAndServe(addr)\n}", "func ListenAndServe(addr string, handler http.Handler) error {\n\tlog.Info(fmt.Sprintf(\"Starting service on %s\", addr))\n\n\t// channel for SIGINT and SIGTERM signals\n\tstopChan := make(chan os.Signal)\n\tsignal.Notify(stopChan, syscall.SIGINT, syscall.SIGTERM)\n\n\tsrv := &http.Server{\n\t\tAddr: addr,\n\t\tHandler: Trace(handler),\n\t}\n\n\tvar err error\n\tgo func() {\n\t\tif err = srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {\n\t\t\tlog.Error(\"Server error: \", err)\n\t\t\tclose(stopChan)\n\t\t}\n\t}()\n\n\t<-stopChan // wait for SIGINT\n\tlog.Info(\"Shutting down server gracefully...\")\n\n\tctx, _ := context.WithTimeout(context.Background(), 25*time.Second)\n\tsrv.Shutdown(ctx)\n\tlog.Info(\"Server gracefully stopped.\")\n\treturn err\n}", "func (s *Server) ListenAndServe() error {\n\t// TODO: Enable TLS\n\treturn s.httpSrv.ListenAndServe()\n}", "func (s *Service)ListenAndServe(port string, r http.Handler) {\n\t\tlog.Println(\"Starting Server!\")\n\t\ts.Server = &http.Server{Addr: port, Handler: r}\n\t\tif err := s.Server.ListenAndServe(); err != nil {\n\t\t\t\t// handle err\n\t\t}\n\n // Setting up signal capturing\n stop := make(chan os.Signal, 1)\n signal.Notify(stop, os.Interrupt)\n\n // Waiting for SIGINT (pkill -2)\n <-stop\n\t\tlog.Println(\"Received Server Stop!\")\n s.Stop()\n // Wait for ListenAndServe goroutine to close.\n}", "func (s *Service) ListenAndServe() error {\n\treturn s.server.ListenAndServe()\n}", "func (s *Server) ListenAndServe() {\n\tserver := &http.Server{\n\t\tAddr: s.addr,\n\t\tHandler: s.router,\n\t}\n\n\tdone := make(chan bool)\n\n\tgo func() {\n\t\t<-s.quit\n\t\tatomic.StoreInt32(&isHealthy, 0)\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\t\tdefer cancel()\n\n\t\tserver.SetKeepAlivesEnabled(false)\n\t\tif err := server.Shutdown(ctx); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tclose(done)\n\t}()\n\n\tatomic.StoreInt32(&isHealthy, 1)\n\tif err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\tlog.Fatal(err)\n\t}\n\n\t<-done\n}", "func ListenAndServe(v *viper.Viper) error {\n\tvar err error\n\ts := new(server)\n\ts.initConfig(v)\n\terr = s.initServices(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.runMonitoring(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.initHandler()\n\treturn http.ListenAndServe(s.config.Addr, s.handler)\n}", "func (p *Server) ListenAndServe() (err error) {\n\tes := &Server{}\n\n\tgnet.Serve(es, p.address)\n\treturn\n}", "func (srv *MonitorServer) ListenAndServe() error {\n\tlog.Logger.Info(\"Embeded web server start at port[%d]\", srv.port)\n\n\thttp.HandleFunc(\"/\", srv.webHandler)\n\n\tportStr := fmt.Sprintf(\":%d\", srv.port)\n\treturn http.ListenAndServe(portStr, nil)\n}", "func (s *Server) ListenAndServe() error {\n\treturn s.serveConn(s.TLSConfig, nil)\n}", "func (s *Server) ListenAndServe() error {\n\tnetwork := \"tcp\"\n\tif s.LMTP {\n\t\tnetwork = \"unix\"\n\t}\n\n\taddr := s.Addr\n\tif !s.LMTP && addr == \"\" {\n\t\taddr = \":smtp\"\n\t}\n\n\tl, err := net.Listen(network, addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.Serve(l)\n}", "func ListenAndServe(addr string, handler HandlerConn) error {\n\tserver := NewServer()\n\tserver.Handler = handler\n\treturn server.ListenAndServe(addr)\n}", "func (s *Server) ListenAndServe() error {\n\tctx, tx, err := s.txBuilder.BuildLazyTransactionContext(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.pluginManager.LoadPlugins(ctx)\n\n\ttx.CommitIfNeeded()\n\n\terr = s.startInternalServer()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taddr := net.JoinHostPort(\n\t\ts.startupConf.Server.Public.Host,\n\t\ts.startupConf.Server.Public.Port,\n\t)\n\ts.server = &http.Server{\n\t\tAddr: addr,\n\t\tHandler: *s.router,\n\t}\n\n\t// Listen\n\tlistener, err := net.Listen(\"tcp\", s.server.Addr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not listen on %s: %v\", s.server.Addr, err)\n\t}\n\n\tgo func() {\n\t\tif err = s.server.Serve(listener); err != nil {\n\t\t\ts.logger.Error(\"API Listen error\", \"error\", err, \"address\", s.server.Addr)\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\ts.logger.Info(\"Public Server Listening\", \"address\", s.server.Addr)\n\n\tgo s.walletPoller.Start()\n\n\treturn nil\n}", "func (s *Server) ListenAndServe() (err error) {\n\n\tvar (\n\t\tl net.Listener\n\t\tserver = &http.Server{\n\t\t\tAddr: s.host,\n\t\t\tHandler: s.dispatcher,\n\t\t}\n\t)\n\tif l, err = newListener(\"tcp\", s.host, s.tlsConfig); err != nil {\n\t\treturn\n\t}\n\n\tlog.Infof(\"Start API server at: %s\", s.host)\n\treturn server.Serve(l)\n}", "func (a *TCPAcceptor) ListenAndServe() {\n\tif a.hasTLSCertificates() {\n\t\ta.listenAndServeTLS()\n\t\treturn\n\t}\n\n\tlistener, err := net.Listen(\"tcp\", a.addr)\n\tif err != nil {\n\t\tlogger.Log.Fatalf(\"Failed to listen: %s\", err.Error())\n\t}\n\ta.listener = listener\n\ta.running = true\n\ta.serve()\n}", "func ListenAndServe(addr string) {\n\tsrv := &http.Server{Handler: router, Addr: addr}\n\tlog.Fatal(srv.ListenAndServe())\n}", "func (m *cMux) ListenAndServe(addr string) error {\n\tif m.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\tif addr == \"\" {\n\t\taddr = \":tcp\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.Serve(ln)\n}", "func (gss *Server) ListenAndServe() error {\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo func() {\n\t\tgss.server.Addr = gss.Addr\n\t\tif err := gss.server.ListenAndServe(); err != http.ErrServerClosed {\n\t\t\tgss.startErr = err\n\t\t\tcancel()\n\t\t}\n\t}()\n\treturn gss.waitForInterrupt(ctx)\n}", "func ListenAndServe(addr string, handler http.Handler) (err error) {\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\n\tl, err := kmsnet.NewTCPListenerNoShutdown(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts := &http.Server{Addr: l.Addr().String(), Handler: handler}\n\n\tserver := &serverConnState{\n\t\tServer: s,\n\t\tl: l,\n\t\tidleConns: make(map[net.Conn]struct{}),\n\t\tactive: make(chan net.Conn),\n\t\tidle: make(chan net.Conn),\n\t\tclosed: make(chan net.Conn),\n\t\tshutdown: make(chan struct{}),\n\t}\n\n\tserver.handleConnState()\n\n\terr = server.Serve(server.l)\n\n\t// wait for process shutdown to complete or timeout.\n\t<-kms.ShutdownComplete()\n\n\treturn err\n}", "func (app *App) ListenAndServe() error {\n\tif app.gracefulShutdown != nil {\n\t\treturn app.GracefulShutdown().ListenAndServe()\n\t}\n\n\treturn app.listenAndServe()\n}", "func (s *Server) ListenAndServe() error {\n\tif s.proxy == nil {\n\t\ts.proxy = newProxy()\n\t}\n\treturn http.ListenAndServe(s.Addr, s.proxy)\n\n}", "func (s *Server) ListenAndServe() error {\n\treturn s.ListenServeAndSignal(nil)\n}", "func ListenAndServe(addr string, handler http.Handler, shutdownTimeout time.Duration) {\n\tserver := startServer(handler, addr)\n\tshutdownServerGracefully(server, shutdownTimeout)\n}", "func ListenAndServe(addr string, handler http.Handler) error {\n\tif addr == \"\" {\n\t\taddr = \":80\"\n\t}\n\tvar err error\n\tserver, err = New(&http.Server{\n\t\tAddr: addr,\n\t\tHandler: handler,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn server.ListenAndServe()\n}", "func (s Server) ListenAndServe(addr string) {\n\tconn, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.Fatalf(\"listen failure: %v\", err)\n\t}\n\tg := grpc.NewServer()\n\tgabby.RegisterServerServer(g, s)\n\tif err := g.Serve(conn); err != nil {\n\t\tlog.Fatalf(\"serve failure: %v\", err)\n\t}\n}", "func (dd *DefaultDriver) ListenAndServe(addr string, h http.Handler) error {\n\tdd.Server.Addr = addr\n\tdd.Server.Handler = h\n\treturn dd.Server.ListenAndServe()\n}", "func (s *Server) ListenAndServe(ctx context.Context) error {\n\taddr := s.Addr\n\tif addr == \"\" {\n\t\taddr = \":domain\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := net.ListenPacket(\"udp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terrc := make(chan error, 1)\n\tgo func() { errc <- s.Serve(ctx, ln) }()\n\tgo func() { errc <- s.ServePacket(ctx, conn) }()\n\n\treturn <-errc\n}", "func (s *Server) ListenAndServe() (err error) {\n\ts.hookShutdownSignal()\n\n\t// Start the HTTP server\n\tgo func() {\n\t\ts.Log.Infof(\"server started\")\n\n\t\terr = s.HTTP.ListenAndServe()\n\t\tif err != nil && err != http.ErrServerClosed {\n\t\t\ts.Log.Errorf(\"error serving: %+v\", err)\n\t\t}\n\t\ts.Finished()\n\t}()\n\n\tselect {\n\tcase <-s.Context.Done():\n\t\ts.Log.Infof(\"server stopped\")\n\t}\n\n\treturn\n}", "func ListenAndServe(addr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n) error {\n\treturn ListenAndServeNetwork(\"tcp\", addr, handler, accept, closed)\n}", "func ListenAndServe(opts ...server.Option) {\n\n\td, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfp := filepath.Join(d, \"service.ini\")\n\tcfg, err := config.LoadIniConfig(fp)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsvr, err := server.NewServer(opts...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, section := range cfg.Sections() {\n\t\t// enable support for protocols\n\t\tok := strings.HasSuffix(section, \"-service\")\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tcodec := strings.TrimSuffix(section, \"-service\")\n\n\t\t// initialize tcp ServerModule\n\t\ttcpport := cfg.Int(section, \"tcp.port\", 0)\n\t\tif tcpport > 0 {\n\t\t\tmod, err := server.NewTcpServer(\"tcp4\", fmt.Sprintf(\":%d\", tcpport), codec)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tmod.Register(svr)\n\t\t}\n\n\t\t// initialize udp ServerModule\n\t\tudpport := cfg.Int(section, \"udp.port\", 0)\n\t\tif udpport > 0 {\n\t\t\tmod, err := server.NewTcpServer(\"udp4\", fmt.Sprintf(\":%d\", udpport), codec)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tmod.Register(svr)\n\t\t}\n\t}\n\n\tsvr.Start()\n}", "func (s *Server) ListenAndServe() error {\n\tif err := s.HTTPServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Server) ListenAndServe(addr string) error {\n\tif addr == \"\" {\n\t\taddr = \":http\"\n\t}\n\n\t// Assign ServeMux to Server.\n\thttpserver := &http.Server{\n\t\tAddr: addr,\n\t\tHandler: s.mux,\n\t}\n\n\treturn httpserver.ListenAndServe()\n}", "func (s *Server) ListenAndServe(addr string) error {\n\ts.server = &http.Server{Addr: addr, Handler: s.mux}\n\tif HandlerHook != nil {\n\t\ts.server.Handler = HandlerHook(s.mux)\n\t}\n\n\treturn s.server.ListenAndServe()\n}", "func (s *Server) ListenAndServe() error {\n\taddr := s.Addr\n\tif len(addr) == 0 {\n\t\taddr = \":6379\"\n\t}\n\n\tnetwork, address := splitNetworkAddress(addr)\n\tif len(network) == 0 {\n\t\tnetwork = \"tcp\"\n\t}\n\n\tl, err := net.Listen(network, address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.Serve(l)\n}", "func (d *Driver) ListenAndServe(addr string, h http.Handler) error {\n\td.Server.Addr = addr\n\td.Server.Handler = h\n\treturn d.Server.ListenAndServe()\n}", "func ListenAndServe(addr string) {\n\tDefaultMux.ListenAndServe(addr)\n}", "func (s *daemonServer) ListenAndServe() error {\n\tl, err := s.Listen()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.Serve(l)\n}", "func (s *Server) ListenAndServe() {\n\t// UDP\n\tgo s.serverUDP.ListenAndServe()\n\n\t// HTTP\n\tgo s.serverHTTP.ListenAndServe()\n}", "func ListenAndServe(\n\thost string, port int,\n\thandler func(conn *Conn, msg *Message, rd *AnyReaderWriter, w io.Writer) error,\n\topened func(conn *Conn),\n\tclosed func(conn *Conn),\n\tlnp *net.Listener,\n) error {\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", host, port))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif lnp != nil {\n\t\t*lnp = ln\n\t}\n\tlog.Printf(\"The server is now ready to accept connections on port %d\\n\", port)\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo handleConn(&Conn{Conn: conn}, handler, opened, closed)\n\t}\n}", "func (s *Server) ListenAndServe(network, addr string) error {\n\tl, err := net.Listen(network, addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"listening to %v\\n\", addr)\n\treturn s.Serve(l)\n}", "func (a *Api) ListenAndServe() error {\n\treturn a.httpserver.Serve(a.listener)\n}", "func (p *PureProxy) ListenAndServe(addr string) error {\n\tif p.shuttingDown() {\n\t\treturn errServerClosed\n\t}\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.serve(tcpKeepAliveListener{ln.(*net.TCPListener)})\n\treturn nil\n}", "func (s *Server) ListenAndServe(network, addr string) error {\n\tl, err := net.Listen(network, addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.Serve(l)\n}", "func (s *Server) ListenAndServe() error {\n\tlog.Printf(\"Starting server at %s\", s.httpServer.Addr)\n\treturn s.httpServer.ListenAndServe()\n}", "func (s *Server) ListenAndServe(addr string) error {\n\tsrv := http.Server{\n\t\tAddr: addr,\n\t\tHandler: s,\n\t}\n\n\treturn srv.ListenAndServe()\n}", "func (s *TLSServer) ListenAndServe() error {\n\treturn s.ListenServeAndSignal(nil)\n}", "func (c *Client) ListenAndServe(addr string) error {\n\tif c.handler == nil {\n\t\treg := prometheus.NewRegistry()\n\n\t\t// Register collectors.\n\t\tif c.EnableRuntime {\n\t\t\tregisterRuntime(c.ServiceName, &c.runtimeCollectors, c.ConstLabels)\n\t\t\treg.MustRegister(c.runtimeCollectors...)\n\t\t\tconstructs = append(constructs, updateRuntimeGuage)\n\n\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\tc.cancel = cancel\n\t\t\tgo updateRuntimeMemstats(ctx, c.UpdateMemStatsInterval)\n\t\t}\n\t\treg.MustRegister(c.collectors...)\n\n\t\tc.handler = decorateHandler(\n\t\t\tpromhttp.HandlerFor(reg, promhttp.HandlerOpts{}),\n\t\t)\n\t}\n\n\thttp.Handle(c.Path, c.handler)\n\tc.srv = &http.Server{\n\t\tAddr: addr,\n\t}\n\tif err := c.srv.ListenAndServe(); err != http.ErrServerClosed {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (wsv *web) ListenAndServe(addr string) Interface {\n\tvar conf *Configuration\n\n\tif conf, wsv.err = parseAddress(addr); wsv.err != nil {\n\t\treturn wsv\n\t}\n\treturn wsv.ListenAndServeWithConfig(conf)\n}", "func (srv *Server) ListenAndServe(addr string) error {\n\tmux := srv.GetMux()\n\tlog.Println(\"mog: listening on\", addr)\n\treturn http.ListenAndServe(addr, mux)\n}", "func ListenAndServe(n, addr string, rh Handler) error {\n\tuaddr, err := net.ResolveUDPAddr(n, addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := net.ListenUDP(n, uaddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn Serve(\n\t\t&Conn{conn: l},\n\t\trh,\n\t)\n}", "func ListenAndServe(svr *http.Server) (*RestServiceInfo, error) {\n\tlog.Printf(\"Entering ListenAndServe(%p)\", svr)\n\tif svr.Addr == \"\" {\n\t\tsvr.Addr = \":0\"\n\t}\n\tln, err := net.Listen(\"tcp\", svr.Addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trealAddr := ln.Addr().String()\n\tchannel := make(chan ServiceMessage)\n\tl := svr.ErrorLog\n\tif l == nil {\n\t\tl = log.New(os.Stdout, \"\", 0)\n\t}\n\tgo func() {\n\t\tchannel <- Starting\n\t\tl.Printf(\"ListenAndServe(%p): listening on %s (asked for %s) with configuration %v, handler %v\\n\", svr, realAddr, svr.Addr, svr, svr.Handler)\n\t\terr := svr.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"RestService: Fatal error %v\", err)\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\treturn &RestServiceInfo{Address: realAddr, Channel: channel}, nil\n}", "func ListenAndServe(addr string, mc *safehttp.ServeMuxConfig) error {\n\tmc.Intercept(hsts.Default())\n\tmc.Intercept(cors.Default())\n\tmc.Intercept(hostcheck.New(addr))\n\treturn http.ListenAndServe(addr, mc.Mux())\n}", "func ListenAndServe(chatCmd chat.CommandService, chatQuery chat.QueryService, chatHub chat.Hub, login chat.LoginService, conf *Config) error {\n\ts := NewServer(chatCmd, chatQuery, chatHub, login, conf)\n\tdefer s.Shutdown(context.Background())\n\treturn s.ListenAndServe()\n}", "func (s *server) listenAndServe() error {\n\tvar ln net.Listener\n\tvar err error\n\n\tif s.tlsCfg == nil {\n\t\ts.logger.Sugar().Debugf(\"tcp listener on address %s\", s.addr)\n\t\tln, err = net.Listen(\"tcp\", s.addr)\n\t} else {\n\t\ts.logger.Sugar().Debugf(\"tcp listener on address %s with tls config %+v\", s.addr, s.tlsCfg)\n\t\tln, err = tls.Listen(\"tcp\", s.addr, s.tlsCfg)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.ln = ln\n\treturn s.serve()\n}", "func (t *HTTPServer) ListenAndServe() error {\n\treturn http.ListenAndServe(t.options.ListenAddress, t.layers)\n}", "func (m *ServeMux) ListenAndServe(addr string) error {\n\tm.Prepare()\n\n\tserver := &http.Server{Addr: addr, Handler: m}\n\treturn server.ListenAndServe()\n}", "func (s *Server) ListenAndServe() error {\n\tif err := s.conf.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"server: config erorr: %v\", err)\n\t}\n\n\te := s.echo\n\n\t// show registered URLs\n\tif s.conf.ShowRoutes {\n\t\troutes := e.Routes()\n\t\tsort.Slice(routes, func(i, j int) bool {\n\t\t\tri, rj := routes[i], routes[j]\n\t\t\treturn len(ri.Path) < len(rj.Path)\n\t\t})\n\t\tfor _, url := range routes {\n\t\t\t// built-in routes are ignored\n\t\t\tif strings.Contains(url.Name, \"github.com/labstack/echo\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Printf(\"%8s : %-35s (%v)\\n\", url.Method, url.Path, url.Name)\n\t\t}\n\t}\n\n\t// start server\n\tserverURL := s.conf.HTTP\n\tlog.Println(\"server listen at \" + serverURL)\n\terr := e.Start(serverURL)\n\te.Logger.Error(err)\n\treturn err\n}", "func ListenAndServe(ctx context.Context, bin, address, port string) {\n\tfmt.Println(`\n\n███████╗███████╗██╗ ███████╗ ███████╗███████╗████████╗███████╗███████╗███╗ ███╗\n██╔════╝██╔════╝██║ ██╔════╝ ██╔════╝██╔════╝╚══██╔══╝██╔════╝██╔════╝████╗ ████║\n███████╗█████╗ ██║ █████╗█████╗█████╗ ███████╗ ██║ █████╗ █████╗ ██╔████╔██║\n╚════██║██╔══╝ ██║ ██╔══╝╚════╝██╔══╝ ╚════██║ ██║ ██╔══╝ ██╔══╝ ██║╚██╔╝██║\n███████║███████╗███████╗██║ ███████╗███████║ ██║ ███████╗███████╗██║ ╚═╝ ██║\n╚══════╝╚══════╝╚══════╝╚═╝ ╚══════╝╚══════╝ ╚═╝ ╚══════╝╚══════╝╚═╝ ╚═╝`)\n\tlog.Info(ctx, \"server listening\", \"bin\", bin, \"address\", address, \"port\", port)\n\thttp.ListenAndServe(fmt.Sprintf(\"%s:%s\", address, port), mux)\n}", "func (serv *Server) ListenAndServe() error {\n conf := serv.config\n e := make(chan error)\n\n log.Printf(\"Listening to HTTP requests on %s\", conf.HttpAddr)\n log.Printf(\"Listening to HTTPS requests on %s\", conf.HttpsAddr)\n\n // HTTP and TLS servers are bound to the socket addresses defined in the\n // Config structure, and respond to requests concurrently.\n // The responses are generated in the ServeHTTP function below.\n go func() {\n e <- http.ListenAndServe(conf.HttpAddr, http.Handler(serv))\n }()\n go func() {\n e <- serv.httpsServer.ListenAndServeTLS(conf.CertFile, conf.KeyFile)\n }()\n\n // Block execution until one of the functions returns with a critical error.\n // This may fail if you are trying to bind to a port that is in use, or if\n // you do not have proper permissions to bind to that port.\n err := <-e\n\n if err != nil {\n log.Println(err)\n }\n\n return err\n}", "func (h *Handler) ListenAndServe() error {\n\t// Setup a watcher.\n\tWatchMPD(h.ServerConfig[\"mpd_domain\"]+\":\"+h.ServerConfig[\"mpd_control_port\"], h)\n\n\tport := \":\" + h.ServerConfig[\"server_port\"]\n\tlog.Println(\"Starting server on \" + port)\n\treturn http.ListenAndServe(port, h)\n}", "func (p *Proxy) ListenAndServe() error {\n\tlistener, mux, err := p.listen()\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.Listener = listener\n\n\treturn rpcserver.Serve(\n\t\tlistener,\n\t\tmux,\n\t\tp.Logger,\n\t\tp.Config,\n\t)\n}", "func ListenAndServe() error {\n\treturn httpServer.ListenAndServe()\n}", "func (s *WebsocketServer) ListenAndServe(address string) (io.Closer, error) {\n\t// Call Listen separate from Serve to check for error listening.\n\tl, err := net.Listen(\"tcp\", address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Run service on configured port.\n\tserver := &http.Server{\n\t\tHandler: s,\n\t\tAddr: l.Addr().String(),\n\t}\n\tgo server.Serve(l)\n\treturn l, nil\n}", "func (s *tcpServerBase) ListenAndServe() error {\n\tlogCtx := log.WithFields(log.Fields{\"name\": s.name, \"listen-address\": s.address})\n\n\taddr, err := net.ResolveTCPAddr(\"tcp\", s.address)\n\tif err != nil {\n\t\tlogCtx.WithError(err).Fatal(\"failed to resolve tcp addr\")\n\t\treturn err\n\t}\n\n\ts.listener, err = net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tlogCtx.WithError(err).Fatal(\"failed to listen port\")\n\t\treturn err\n\t}\n\n\tlogCtx.Info(\"ready for connection\")\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-s.quit:\n\t\t\tlog.WithField(\"name\", s.name).Debug(\"quit\")\n\t\t\tbreak loop\n\t\tdefault:\n\t\t\tconn, err := s.listener.AcceptTCP()\n\t\t\tif opErr, ok := err.(*net.OpError); ok && opErr.Op == \"accept\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlogCtx.WithError(err).Warn(\"error while accepting connection\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\ts.wg.Add(1)\n\t\t\t\ts.connHandler(conn)\n\t\t\t\ts.wg.Done()\n\t\t\t}()\n\t\t}\n\t}\n\n\treturn nil\n}", "func (a *API) ListenAndServe(lAddr, pAddr, httpAddr string) error {\n\terrCh := make(chan error)\n\n\tdmsgLn, err := net.Listen(\"tcp\", lAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdmsgLis := &proxyproto.Listener{Listener: dmsgLn}\n\tdefer dmsgLis.Close() // nolint:errcheck\n\tgo func(l net.Listener, address string) {\n\t\tif err := a.dmsgServer.Serve(l, address); err != nil {\n\t\t\terrCh <- err\n\t\t}\n\t}(dmsgLis, pAddr)\n\n\tln, err := net.Listen(\"tcp\", httpAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlis := &proxyproto.Listener{Listener: ln}\n\tdefer lis.Close() // nolint:errcheck\n\tsrv := &http.Server{\n\t\tReadTimeout: 3 * time.Second,\n\t\tWriteTimeout: 3 * time.Second,\n\t\tIdleTimeout: 30 * time.Second,\n\t\tReadHeaderTimeout: 3 * time.Second,\n\t\t//Addr: lis,\n\t\tHandler: a.router,\n\t}\n\tif err := srv.Serve(lis); err != nil {\n\t\terrCh <- err\n\t}\n\n\treturn <-errCh\n}", "func ListenAndServe(host string, port uint16) {\n\taddr := tools.ToAddressString(host, port)\n\t// Listen to tcp addr\n\tlistener, err := net.Listen(\"tcp\", addr)\n\ttools.LogAndExitIfErr(err)\n\tlog.Printf(\"Start a Echo Server Success! on %s\\n\", addr)\n\t// Create a context\n\tctx := context.Background()\n\tfor {\n\t\t// Wait accept connection\n\t\tconn, err := listener.Accept()\n\t\ttools.LogAndExitIfErr(err)\n\t\tlog.Printf(\"Client %s connection success\\n\", conn.RemoteAddr().String())\n\t\t// Serve a client connection\n\t\tgo serve(ctx, conn)\n\t}\n}", "func ListenAndServe(s *http.Server, keepAlive time.Duration) error {\n\treturn s.ListenAndServe()\n}", "func (s *Server) ListenAndServe(addr string) error {\n\thttp.Handle(\"/\", s.handlerFunc(s.routesHandler))\n\n\thttp.HandleFunc(\"/script.js\", script)\n\thttp.HandleFunc(\"/favicon.png\", favicon)\n\thttp.HandleFunc(\"/favicon.ico\", favicon)\n\n\treturn http.ListenAndServe(addr, nil)\n}", "func ListenAndServe(addr string, handler http.Handler) error {\n\ts := http.Server{\n\t\tAddr: addr,\n\t\tHandler: handler,\n\t\tReadTimeout: 2 * time.Second,\n\t}\n\treturn s.ListenAndServe()\n}", "func (s Server) ListenAndServe() {\n\tgo func() {\n\t\ts.logger.Infof(\"Server is running on port :%d\", s.port)\n\t\ts.logger.Error(s.server.ListenAndServe())\n\t}()\n}", "func (s *TLSServer) ListenAndServe(addr string, handler http.Handler) {\n\n\tconfig, err := createServerConfig(s.Certspath)\n\tif err != nil {\n\t\tlog.Panic(logPrefix, \"create tls configuration failed: \", err.Error())\n\t}\n\n\ts.listener, err = tls.Listen(\"tcp\", addr, config)\n\tif err != nil {\n\t\tlog.Panic(logPrefix, \"listen failed: \", err.Error())\n\t}\n\n\tdefer s.listener.Close()\n\n\t(&http.Server{Handler: handler}).Serve(s.listener)\n}", "func (a *AgentServer) ListenAndServe(addr utils.NetAddr) error {\n\tl, err := net.Listen(addr.AddrNetwork, addr.Addr)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\ta.listener = l\n\treturn a.Serve()\n}", "func ListenAndServe(network string, laddr string) error {\n\treturn Default.ListenAndServe(network, laddr)\n}", "func (s *HTTPServer) ListenAndServe(host string, router http.Handler) error {\n\treturn http.ListenAndServe(host, router)\n}", "func (s *Server) ListenAndServe() error {\n\tln, err := net.Listen(\"tcp\", s.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Listening on %s\\n\", s.Addr)\n\tdefer ln.Close()\n\tid := 1\n\ts.rooms.create(\"lobby\")\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// log the RemoteAddr here because NewConn() stores it as a io.ReadWriteCloser\n\t\tlog.Printf(\"New connection id %d from %s\\n\", id, conn.RemoteAddr().String())\n\t\tc := s.NewConn(conn, id)\n\t\tif c == nil {\n\t\t\tconn.Close()\n\t\t\tcontinue\n\t\t}\n\t\tgo c.handleConnection()\n\t\tid++\n\t}\n}", "func (r *Router) ListenAndServe(port int) error {\n\t// Assign the router to the server handler\n\tr.Server.Handler = r.Router\n\tr.Server.Addr = \":\" + strconv.Itoa(port)\n\n\t// Begin listening for requests\n\treturn r.Server.ListenAndServe()\n}", "func (h *HTTP) ListenAndServe(ctx context.Context) error {\n\tlog.AddLoggerToHTTPServer(ctx, \"download\", h.server)\n\terrCh := make(chan error, 1)\n\tgo func() {\n\t\terrCh <- h.server.ListenAndServe()\n\t}()\n\tselect {\n\tcase <-ctx.Done():\n\t\tlog.Info(ctx, \"terminating download server\", zap.Error(context.Cause(ctx)))\n\t\treturn errors.EnsureStack(h.server.Shutdown(ctx))\n\tcase err := <-errCh:\n\t\treturn err\n\t}\n}", "func (s *Server) ListenAndServe() error {\n\tlog.Printf(\"dns server listening on %s [%s]\", s.Config.DNS.Listen, s.Config.DNS.Protocol)\n\treturn s.proxy.ListenAndServe(s.Config.DNS.Listen, s.Config.DNS.Protocol)\n}", "func ListenAndServe(port string, handler http.Handler) {\n\tfmt.Println(\"Listening on:\", port)\n\tif err := http.ListenAndServe(fmt.Sprintf(\":%s\", port), handler); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (g *Gonf) ListenAndServe(addr string, errChan chan error) {\n\terr := http.ListenAndServe(addr, &g.handler)\n\n\tif err != nil && errChan != nil {\n\t\terrChan <- err\n\t}\n}", "func (r *router) ListenAndServe() {\n\tsigCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)\n\n\tgo func() {\n\t\tif err := r.server.ListenAndServeTLS(\"\", \"\"); err != nil {\n\t\t\tlog.WithError(err).Fatal(\"Failed to listen and serve webhook server\")\n\t\t}\n\t}()\n\tlog.Info(\"NSE webhook injector has started\")\n\n\t<-sigCh\n}", "func (s Server) ListenAndServe(port int) {\n\ts.router.HandleFunc(\"/accounts/{accountID}\", s.retrieveAccountInfoHandler()).Methods(\"GET\")\n\ts.router.HandleFunc(\"/accounts\", s.createAccountHandler()).Methods(\"POST\")\n\ts.router.HandleFunc(\"/transactions\", s.createTransactionHandler()).Methods(\"POST\")\n\n\ts.logger.Println(`HTTP server listening on port`, port)\n\thttp.ListenAndServe(fmt.Sprintf(\":%d\", port), s.router)\n}" ]
[ "0.81201774", "0.80848074", "0.79041094", "0.7880685", "0.78403497", "0.77083457", "0.7631258", "0.7622403", "0.75918704", "0.7575086", "0.75674087", "0.75577086", "0.75408393", "0.7525587", "0.751776", "0.7497703", "0.74919134", "0.7471763", "0.7456875", "0.74443716", "0.7440863", "0.74222195", "0.74183214", "0.74039465", "0.7387839", "0.73727995", "0.7353218", "0.7337003", "0.7324175", "0.73023605", "0.7300567", "0.72991055", "0.7298257", "0.7296069", "0.72934425", "0.7291953", "0.72911835", "0.7282695", "0.7282684", "0.72777456", "0.7275808", "0.7270604", "0.7270072", "0.72559834", "0.72504157", "0.72458935", "0.72426265", "0.72407866", "0.72290385", "0.72209626", "0.7213947", "0.72126764", "0.7206867", "0.71883273", "0.7187769", "0.7181035", "0.71736354", "0.7170188", "0.71661115", "0.7164024", "0.7162572", "0.714996", "0.71450764", "0.7142698", "0.7136937", "0.71322864", "0.7132259", "0.7126317", "0.7118374", "0.7102211", "0.71020263", "0.70922345", "0.7077564", "0.70625466", "0.7056853", "0.70492816", "0.70350176", "0.70307386", "0.70270586", "0.7026644", "0.7015079", "0.6984549", "0.698073", "0.69776523", "0.69538283", "0.69526154", "0.6940478", "0.6924497", "0.69042003", "0.69006807", "0.68965757", "0.6895073", "0.68716305", "0.6848783", "0.68265176", "0.6826404", "0.6824052", "0.6817129", "0.6801355", "0.6772639" ]
0.758933
9
ListenAndServeTLS listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming TLS connections. Filenames containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.
func (srv *TCPServer) ListenAndServeTLS(certFile, keyFile string) error { addr := srv.Addr l, err := net.Listen("tcp", addr) if err != nil { return err } return srv.ServeTLS(l, certFile, keyFile) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\tsrv.isHttps = true\n\taddr := srv.httpServer.Addr\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tsrv.tlsConfig = &tls.Config{}\n\tif srv.httpServer.TLSConfig != nil {\n\t\t*srv.tlsConfig = *srv.httpServer.TLSConfig\n\t}\n\tif srv.tlsConfig.NextProtos == nil {\n\t\tsrv.tlsConfig.NextProtos = []string{\"http/1.1\"}\n\t}\n\n\tvar err error\n\tsrv.tlsConfig.Certificates = make([]tls.Certificate, 1)\n\tsrv.tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tln, err := srv.getListener(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrv.listener = NewWebTcpListener(ln)\n\n\treturn srv.Serve()\n}", "func (r *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {\n return http.ListenAndServeTLS(addr, certFile, keyFile, r.router)\n}", "func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\tif srv.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer ln.Close()\n\n\treturn srv.ServeTLS(ln, certFile, keyFile)\n}", "func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\tconfig := &tls.Config{}\n\tif s.server.TLSConfig != nil {\n\t\t*config = *s.server.TLSConfig\n\t}\n\tif config.NextProtos == nil {\n\t\tconfig.NextProtos = []string{\"http/1.1\"}\n\t}\n\n\tvar err error\n\tconfig.Certificates = make([]tls.Certificate, 1)\n\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsListener := tls.NewListener(s.listener, config)\n\treturn s.server.Serve(tlsListener)\n}", "func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\tvar err error\n\tcerts := make([]tls.Certificate, 1)\n\tcerts[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// We currently only use the cert-related stuff from tls.Config,\n\t// so we don't need to make a full copy.\n\tconfig := &tls.Config{\n\t\tCertificates: certs,\n\t}\n\treturn s.serveConn(config, nil)\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {\n\tserver := &Server{Addr: addr, Handler: handler}\n\treturn server.ListenAndServeTLS(certFile, keyFile)\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {\n\tserver := &Server{Addr: addr, Handler: handler}\n\treturn server.ListenAndServeTLS(certFile, keyFile)\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {\n\tsrv := New(addr)\n\n\treturn srv.ListenAndServeTLS(certFile, keyFile, handler)\n}", "func ListenAndServeTLS(addr string, handler http.Handler, crt Certifier) error {\n\tcerts := newCertCache(crt)\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\n\ts := http.Server{\n\t\tAddr: addr,\n\t\tHandler: handler,\n\t\tTLSConfig: &tls.Config{\n\t\t\tGetCertificate: func(h *tls.ClientHelloInfo) (c *tls.Certificate, err error) {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpromVPKICertError.With(prometheus.Labels{\"server_name\": h.ServerName}).Inc()\n\t\t\t\t\t}\n\t\t\t\t}()\n\n\t\t\t\tif h.ServerName == \"\" {\n\t\t\t\t\terr = fmt.Errorf(\"Cannot generate certs without TLS SNI (no server name was indicated)\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif crt, ok := crt.(SNICertifier); ok {\n\t\t\t\t\tc, err = crt.GetCertificate(h)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tc, err = certs.get(h.ServerName)\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t}\n\n\treturn s.ListenAndServeTLS(\"\", \"\")\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) error {\n\tvar err error\n\tserver, err = New(&http.Server{\n\t\tAddr: addr,\n\t\tHandler: handler,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn server.ListenAndServeTLS(certFile, keyFile)\n}", "func (srv *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {\n\t// Check if the driver implements the optional interface.\n\ttlsDriver, ok := srv.driver.(driver.TLSServer)\n\tif !ok {\n\t\treturn fmt.Errorf(\"driver %T does not support ListenAndServeTLS\", srv.driver)\n\t}\n\tsrv.init()\n\treturn tlsDriver.ListenAndServeTLS(addr, certFile, keyFile, srv.wrappedHandler)\n}", "func (srv *Server) ListenAndServeTLS(certFile, keyFile string, handler Handler) error {\n\tsrv.init(handler)\n\n\treturn srv.Server.ListenAndServeTLS(certFile, keyFile)\n}", "func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {\n\tif s.opts.HTTPRedirectPort != 0 {\n\t\tmux := http.NewServeMux()\n\t\tmux.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n\t\t\tp := req.URL.Path\n\t\t\tif p != \"\" && p[0] != '/' {\n\t\t\t\tp = \"/\" + p\n\t\t\t}\n\t\t\thttp.Redirect(w, req, s.opts.ServerURL+p, http.StatusTemporaryRedirect)\n\t\t})\n\t\tgo http.ListenAndServe(fmt.Sprintf(\":%d\", s.opts.HTTPRedirectPort), mux)\n\t}\n\tconfig := &tls.Config{MinVersion: tls.VersionTLS10}\n\thttpserver := &http.Server{\n\t\tAddr: addr,\n\t\tTLSConfig: config,\n\t\tHandler: s.mux,\n\t}\n\treturn httpserver.ListenAndServeTLS(certFile, keyFile)\n}", "func (s *Server) listenAndServe() (err error) {\n\n\tvar listener net.Listener\n\tvar clientAuth tls.ClientAuthType\n\tvar ok bool\n\n\tc := s.Config\n\n\t// Set default listening address and port\n\tif c.Address == \"\" {\n\t\tc.Address = DefaultServerAddr\n\t}\n\tif c.Port == 0 {\n\t\tc.Port = DefaultServerPort\n\t}\n\taddr := net.JoinHostPort(c.Address, strconv.Itoa(c.Port))\n\tvar addrStr string\n\n\tif c.TLS.Enabled {\n\t\tlog.Debug(\"TLS is enabled\")\n\t\taddrStr = fmt.Sprintf(\"https://%s\", addr)\n\n\t\t// If key file is specified and it does not exist or its corresponding certificate file does not exist\n\t\t// then need to return error and not start the server. The TLS key file is specified when the user\n\t\t// wants the server to use custom tls key and cert and don't want server to auto generate its own. So,\n\t\t// when the key file is specified, it must exist on the file system\n\t\tif c.TLS.KeyFile != \"\" {\n\t\t\tif !util.FileExists(c.TLS.KeyFile) {\n\t\t\t\treturn fmt.Errorf(\"File specified by 'tls.keyfile' does not exist: %s\", c.TLS.KeyFile)\n\t\t\t}\n\t\t\tif !util.FileExists(c.TLS.CertFile) {\n\t\t\t\treturn fmt.Errorf(\"File specified by 'tls.certfile' does not exist: %s\", c.TLS.CertFile)\n\t\t\t}\n\t\t\tlog.Debugf(\"TLS Certificate: %s, TLS Key: %s\", c.TLS.CertFile, c.TLS.KeyFile)\n\t\t} else if !util.FileExists(c.TLS.CertFile) {\n\t\t\t// TLS key file is not specified, generate TLS key and cert if they are not already generated\n\t\t\terr = s.autoGenerateTLSCertificateKey()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to automatically generate TLS certificate and key: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\tcer, err := util.LoadX509KeyPair(c.TLS.CertFile, c.TLS.KeyFile, s.csp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif c.TLS.ClientAuth.Type == \"\" {\n\t\t\tc.TLS.ClientAuth.Type = defaultClientAuth\n\t\t}\n\n\t\tlog.Debugf(\"Client authentication type requested: %s\", c.TLS.ClientAuth.Type)\n\n\t\tauthType := strings.ToLower(c.TLS.ClientAuth.Type)\n\t\tif clientAuth, ok = clientAuthTypes[authType]; !ok {\n\t\t\treturn errors.New(\"Invalid client auth type provided\")\n\t\t}\n\n\t\tvar certPool *x509.CertPool\n\t\tif authType != defaultClientAuth {\n\t\t\tcertPool, err = LoadPEMCertPool(c.TLS.ClientAuth.CertFiles)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tconfig := &tls.Config{\n\t\t\tCertificates: []tls.Certificate{*cer},\n\t\t\tClientAuth: clientAuth,\n\t\t\tClientCAs: certPool,\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tMaxVersion: tls.VersionTLS13,\n\t\t\tCipherSuites: stls.DefaultCipherSuites,\n\t\t}\n\n\t\tlistener, err = tls.Listen(\"tcp\", addr, config)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"TLS listen failed for %s\", addrStr)\n\t\t}\n\t} else {\n\t\taddrStr = fmt.Sprintf(\"http://%s\", addr)\n\t\tlistener, err = net.Listen(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"TCP listen failed for %s\", addrStr)\n\t\t}\n\t}\n\ts.listener = listener\n\tlog.Infof(\"Listening on %s\", addrStr)\n\n\terr = s.checkAndEnableProfiling()\n\tif err != nil {\n\t\ts.closeListener()\n\t\treturn errors.WithMessage(err, \"TCP listen for profiling failed\")\n\t}\n\n\t// Start serving requests, either blocking or non-blocking\n\tif s.BlockingStart {\n\t\treturn s.serve()\n\t}\n\ts.wait = make(chan bool)\n\tgo s.serve()\n\n\treturn nil\n}", "func ListenAndServeTLS(opt *Options, httpHandler http.Handler, grpcHandler *grpc.Server) error {\n\tif opt == nil {\n\t\topt = defaultOptions\n\t} else {\n\t\topt.applyDefaults()\n\t}\n\tvar cert *tls.Certificate\n\tvar err error\n\tif opt.Cert != \"\" && opt.Key != \"\" {\n\t\tcert, err = decodeCertificate(opt.Cert, opt.Key)\n\t} else {\n\t\tcert, err = readCertificateFile(opt.CertFile, opt.KeyFile)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: failed loading x509 certificate: %v\", err)\n\t}\n\tconfig, err := newDefaultTLSConfig(cert)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: setting up TLS config: %v\", err)\n\t}\n\tln, err := net.Listen(\"tcp\", opt.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tln = tls.NewListener(ln, config)\n\n\tvar h http.Handler\n\tif grpcHandler == nil {\n\t\th = httpHandler\n\t} else {\n\t\th = grpcHandlerFunc(grpcHandler, httpHandler)\n\t}\n\tsublogger := log.With().Str(\"addr\", opt.Addr).Logger()\n\n\t// Set up the main server.\n\tserver := &http.Server{\n\t\tReadHeaderTimeout: 10 * time.Second,\n\t\tReadTimeout: 30 * time.Second,\n\t\t// WriteTimeout is set to 0 for streaming replies\n\t\tWriteTimeout: 0,\n\t\tIdleTimeout: 5 * time.Minute,\n\t\tTLSConfig: config,\n\t\tHandler: h,\n\t\tErrorLog: stdlog.New(&log.StdLogWrapper{Logger: &sublogger}, \"\", 0),\n\t}\n\n\treturn server.Serve(ln)\n}", "func (gss *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo func() {\n\t\tif err := gss.server.ListenAndServeTLS(certFile, keyFile); err != http.ErrServerClosed {\n\t\t\tgss.startErr = err\n\t\t\tcancel()\n\t\t}\n\t}()\n\treturn gss.waitForInterrupt(ctx)\n}", "func (dd *DefaultDriver) ListenAndServeTLS(addr, certFile, keyFile string, h http.Handler) error {\n\tdd.Server.Addr = addr\n\tdd.Server.Handler = h\n\treturn dd.Server.ListenAndServeTLS(certFile, keyFile)\n}", "func ListenAndServeTLS(addr string, handler HandlerConn, tlsConfig *tls.Config, certFile, keyFile string) error {\n\tserver := NewServer()\n\tserver.Handler = handler\n\treturn server.ListenAndServeTLS(addr, tlsConfig, certFile, keyFile)\n}", "func (srv *Server) ListenAndServeTLS(addr string, tlsConfig *tls.Config, certFile, keyFile string) error {\n\tif srv.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer ln.Close()\n\n\treturn srv.ServeTLS(net_.TcpKeepAliveListener(ln.(*net.TCPListener), 3*time.Minute), tlsConfig, certFile, keyFile)\n}", "func (t *HTTPServer) ListenAndServeTLS() error {\n\tif t.options.Certificate == \"\" || t.options.CertificateKey == \"\" {\n\t\ttlsOptions := sslcert.DefaultOptions\n\t\ttlsOptions.Host = t.options.CertificateDomain\n\t\ttlsConfig, err := sslcert.NewTLSConfig(tlsOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpServer := &http.Server{\n\t\t\tAddr: t.options.ListenAddress,\n\t\t\tTLSConfig: tlsConfig,\n\t\t}\n\t\thttpServer.Handler = t.layers\n\t\treturn httpServer.ListenAndServeTLS(\"\", \"\")\n\t}\n\treturn http.ListenAndServeTLS(t.options.ListenAddress, t.options.Certificate, t.options.CertificateKey, t.layers)\n}", "func ListenAndServeTLS(ctx context.Context, addr string, handler Handler, tlsConfig *tls.Config, certFile, keyFile string) error {\n\tserver := New(ctx)\n\tserver.MatchAndGoServe(handler)\n\treturn server.ListenAndServeTLS(addr, tlsConfig, certFile, keyFile)\n}", "func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {\n\t// Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig\n\t// before we clone it and create the TLS Listener.\n\tif err := srv.setupHTTP2_ServeTLS(); err != nil {\n\t\treturn err\n\t}\n\n\tconfig := cloneTLSConfig(srv.TLSConfig)\n\tif !strSliceContains(config.NextProtos, \"http/1.1\") {\n\t\tconfig.NextProtos = append(config.NextProtos, \"http/1.1\")\n\t}\n\n\tconfigHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil\n\tif !configHasCert || certFile != \"\" || keyFile != \"\" {\n\t\tvar err error\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttlsListener := tls.NewListener(l, config)\n\treturn srv.Serve(tlsListener)\n}", "func (srv *Server) ServeTLS(l net.Listener, tLSConfig *tls.Config, certFile, keyFile string) error {\n\tconfig := http_.CloneTLSConfig(tLSConfig)\n\tif !strings.SliceContains(config.NextProtos, \"http/1.1\") {\n\t\tconfig.NextProtos = append(config.NextProtos, \"http/1.1\")\n\t}\n\n\tconfigHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil\n\tif !configHasCert || certFile != \"\" || keyFile != \"\" {\n\t\tvar err error\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttlsListener := tls.NewListener(l, config)\n\treturn srv.Serve(tlsListener)\n}", "func ListenTLS(how, addr string, certFile, keyFile string) (*Server, error) {\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ListenTLSCustom(how, addr, &tls.Config{\n\t\tRootCAs: TLSCertPool(),\n\t\tCertificates: []tls.Certificate{cert},\n\t})\n}", "func (srv *TCPServer) ServeTLS(l net.Listener, certFile, keyFile string) (err error) {\n\tconfig := srv.TLSConfig\n\tif config == nil {\n\t\tconfig = &tls.Config{}\n\t}\n\tconfigHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil\n\tif !configHasCert || certFile != \"\" || keyFile != \"\" {\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\ttlsListener := tls.NewListener(l, config)\n\treturn srv.Serve(tlsListener)\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) (err error) {\n\n\ttlsConfig := &tls.Config{\n\t\tNextProtos: []string{http2NextProtoTLS, http2Rev14, http11},\n\t\tCertificates: make([]tls.Certificate, 1),\n\t}\n\n\ttlsConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\n\tl, err := kmsnet.NewTCPListenerNoShutdown(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsListener := tls.NewListener(l, tlsConfig)\n\n\ts := &http.Server{Addr: tlsListener.Addr().String(), Handler: handler, TLSConfig: tlsConfig}\n\n\tserver := &serverConnState{\n\t\tServer: s,\n\t\tl: tlsListener,\n\t\tidleConns: make(map[net.Conn]struct{}),\n\t\tactive: make(chan net.Conn),\n\t\tidle: make(chan net.Conn),\n\t\tclosed: make(chan net.Conn),\n\t\tshutdown: make(chan struct{}),\n\t}\n\n\tserver.handleConnState()\n\n\terr = server.Serve(server.l)\n\n\t// wait for process shutdown to complete or timeout.\n\t<-kms.ShutdownComplete()\n\n\treturn err\n}", "func (p *Proxy) ListenAndServeTLS(certFile, keyFile string) error {\n\tlistener, mux, err := p.listen()\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.Listener = listener\n\n\treturn rpcserver.ServeTLS(\n\t\tlistener,\n\t\tmux,\n\t\tcertFile,\n\t\tkeyFile,\n\t\tp.Logger,\n\t\tp.Config,\n\t)\n}", "func (m *cMux) ListenAndServeTLS(addr string, tlsConfig *tls.Config, certFile, keyFile string) error {\n\tif m.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer ln.Close()\n\n\treturn m.ServeTLS(net_.TcpKeepAliveListener(ln.(*net.TCPListener), 3*time.Minute), tlsConfig, certFile, keyFile)\n}", "func (r *Router) ListenAndServeTLS(port int, certFile, keyFile string) error {\n\t// Assign the router to the server handler\n\tr.Server.Handler = r.Router\n\tr.Server.Addr = \":\" + strconv.Itoa(port)\n\n\t// Begin listening for TLS requests\n\treturn r.Server.ListenAndServeTLS(certFile, keyFile)\n}", "func ListenAndServeTLSKeyPair(addr string, cert tls.Certificate,\n\thandler http.Handler) error {\n\n\tif addr == \"\" {\n\t\treturn errors.New(\"Invalid address string\")\n\t}\n\n\tserver := &http.Server{Addr: addr, Handler: handler}\n\n\tconfig := &tls.Config{}\n\tconfig.NextProtos = []string{\"http/1.1\"}\n\tconfig.Certificates = make([]tls.Certificate, 1)\n\tconfig.Certificates[0] = cert\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)},\n\t\tconfig)\n\n\treturn server.Serve(tlsListener)\n}", "func (s *WebsocketServer) ListenAndServeTLS(address string, tlscfg *tls.Config, certFile, keyFile string) (io.Closer, error) { //nolint:lll\n\t// Load certificate here, instead of in ServeTLS, to check for error before\n\t// serving.\n\tvar hasCert bool\n\tif tlscfg == nil {\n\t\ttlscfg = &tls.Config{}\n\t} else if len(tlscfg.Certificates) > 0 || tlscfg.GetCertificate != nil {\n\t\thasCert = true\n\t}\n\n\tif !hasCert || certFile != \"\" || keyFile != \"\" {\n\t\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error loading X509 key pair: %w\", err)\n\t\t}\n\t\ttlscfg.Certificates = append(tlscfg.Certificates, cert)\n\t}\n\n\t// Call Listen separate from Serve to check for error listening.\n\tl, err := net.Listen(\"tcp\", address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Run service on configured port.\n\tserver := &http.Server{\n\t\tHandler: s,\n\t\tAddr: l.Addr().String(),\n\t\tTLSConfig: tlscfg,\n\t}\n\tgo server.ServeTLS(l, \"\", \"\")\n\treturn l, nil\n}", "func (m *cMux) ServeTLS(l net.Listener, tLSConfig *tls.Config, certFile, keyFile string) error {\n\tconfig := cloneTLSConfig(tLSConfig)\n\tif !strings.SliceContains(config.NextProtos, \"http/1.1\") {\n\t\tconfig.NextProtos = append(config.NextProtos, \"http/1.1\")\n\t}\n\n\tconfigHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil\n\tif !configHasCert || certFile != \"\" || keyFile != \"\" {\n\t\tvar err error\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttlsListener := tls.NewListener(l, config)\n\treturn m.Serve(tlsListener)\n}", "func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {\n\tsrv := &Server{Handler: handler}\n\treturn srv.ServeTLS(l, certFile, keyFile)\n}", "func (serv *Server) RunTLS(addr, certFile, keyFile string) (err error) {\n\tdebugPrint(\"Listening and serving HTTPS on %s\\n\", addr)\n\tdefer func() { debugPrintError(err) }()\n\n\terr = http.ListenAndServeTLS(addr, certFile, keyFile, serv)\n\treturn\n}", "func ServeTLS(reg *cookoo.Registry, router *cookoo.Router, cxt cookoo.Context, certFile, keyFile string) {\n\taddr := cxt.Get(\"server.Address\", \":4433\").(string)\n\n\tserver := &http.Server{Addr: addr}\n\tserver.Handler = NewCookooHandler(reg, router, cxt)\n\n\tgo handleSignals(router, cxt, server)\n\terr := server.ListenAndServeTLS(certFile, keyFile)\n\tif err != nil {\n\t\tcxt.Logf(\"error\", \"Caught error while serving: %s\", err)\n\t\tif router.HasRoute(\"@crash\") {\n\t\t\trouter.HandleRequest(\"@crash\", cxt, false)\n\t\t}\n\t}\n}", "func (a *TCPAcceptor) ListenAndServeTLS(cert, key string) {\n\tcrt, err := tls.LoadX509KeyPair(cert, key)\n\tif err != nil {\n\t\tlogger.Log.Fatalf(\"Failed to listen: %s\", err.Error())\n\t}\n\n\ta.certs = append(a.certs, crt)\n\n\ta.listenAndServeTLS()\n}", "func (lb *LB) ServeTLS(tlsConfig *tls.Config, certFile, keyFile string) error {\n\tlisner, err := net.Listen(\"tcp\", lb.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlb.TLSConfig = tlsConfig\n\n\tglg.Success(\"Load Balancer starting on \" + lb.Addr)\n\terr = lb.Server.ServeTLS(lisner, certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Server) ListenAndServeTLS(ctx context.Context) error {\n\taddr := s.Addr\n\tif addr == \"\" {\n\t\taddr = \":domain\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.ServeTLS(ctx, ln)\n}", "func (s *Server) RunTLS(addr string, certPairs []CertPair) error {\n\tcfg := tls.Config{RootCAs: x509.NewCertPool()}\n\tcfg.Certificates = make([]tls.Certificate, 0, len(certPairs))\n\n\tfor _, cp := range certPairs {\n\t\tcert, err := tls.LoadX509KeyPair(cp.CertFile, cp.KeyFile)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s: %v\", cp.CertFile, err)\n\t\t}\n\t\tcfg.Certificates = append(cfg.Certificates, cert)\n\t}\n\n\tcfg.BuildNameToCertificate()\n\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrv := s.newHTTPServer(ln.Addr().String())\n\tsrv.TLSConfig = &cfg\n\n\ts.serversMux.Lock()\n\ts.servers = append(s.servers, srv)\n\ts.serversMux.Unlock()\n\n\tif s.opts.KeepAlivePeriod == -1 {\n\t\treturn srv.ServeTLS(ln, \"\", \"\")\n\t}\n\n\treturn srv.ServeTLS(&tcpKeepAliveListener{ln.(*net.TCPListener), s.opts.KeepAlivePeriod}, \"\", \"\")\n}", "func (s *HTTPServer) ListenAndServe(host, certFile, keyFile string, router http.Handler) error {\n\tif certFile == \"\" || keyFile == \"\" {\n\t\treturn http.ListenAndServe(host, router) // nolint:wrapcheck // reduce cyclo\n\t}\n\n\treturn http.ListenAndServeTLS(host, certFile, keyFile, router) // nolint:wrapcheck // reduce cyclo\n}", "func (s *Server) RunTLS(addr, certFile, keyFile string) error {\n\tc, err := tlsConfig(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.listener, err = tls.Listen(network, addr, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.serve()\n}", "func (s *Server) ListenAndServeTLS() error {\n\tif s.LMTP {\n\t\treturn errTCPAndLMTP\n\t}\n\n\taddr := s.Addr\n\tif addr == \"\" {\n\t\taddr = \":smtps\"\n\t}\n\n\tl, err := tls.Listen(\"tcp\", addr, s.TLSConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.Serve(l)\n}", "func (s *Server) ServeOnListenerTLS(address string, port int, certFile, keyFile string, stopChan <-chan struct{}) error {\n\t// kubernetes build handler configuration\n\tserverConfig := server.NewConfig(serializer.NewCodecFactory(s.virtualManager.GetScheme()))\n\tserverConfig.RequestInfoResolver = &request.RequestInfoFactory{\n\t\tAPIPrefixes: sets.NewString(\"api\", \"apis\"),\n\t\tGrouplessAPIPrefixes: sets.NewString(\"api\"),\n\t}\n\n\tredirectAuthResources := []delegatingauthorizer.GroupVersionResourceVerb{\n\t\t{\n\t\t\tGroupVersionResource: corev1.SchemeGroupVersion.WithResource(\"services\"),\n\t\t\tVerb: \"create\",\n\t\t\tSubResource: \"\",\n\t\t},\n\t}\n\tredirectAuthResources = append(redirectAuthResources, s.redirectResources...)\n\tserverConfig.Authorization.Authorizer = union.New(kubeletauthorizer.New(s.localManager, s.virtualManager), delegatingauthorizer.New(s.virtualManager, redirectAuthResources, nil), impersonationauthorizer.New(s.virtualManager.GetClient()), allowall.New())\n\n\tsso := options.NewSecureServingOptions()\n\tsso.HTTP2MaxStreamsPerConnection = 1000\n\tsso.ServerCert.CertKey.CertFile = certFile\n\tsso.ServerCert.CertKey.KeyFile = keyFile\n\tsso.BindPort = port\n\tsso.BindAddress = net.ParseIP(address)\n\terr := sso.WithLoopback().ApplyTo(&serverConfig.SecureServing, &serverConfig.LoopbackClientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tauthOptions := options.NewDelegatingAuthenticationOptions()\n\tauthOptions.RemoteKubeConfigFileOptional = true\n\tauthOptions.SkipInClusterLookup = true\n\tauthOptions.RequestHeader.ClientCAFile = s.requestHeaderCaFile\n\tauthOptions.ClientCert.ClientCA = s.clientCaFile\n\terr = authOptions.ApplyTo(&serverConfig.Authentication, serverConfig.SecureServing, serverConfig.OpenAPIConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// make sure the tokens are correctly authenticated\n\tserverConfig.Authentication.Authenticator = unionauthentication.New(delegatingauthenticator.New(s.virtualManager.GetClient()), serverConfig.Authentication.Authenticator)\n\n\t// create server\n\tklog.Info(\"Starting tls proxy server at \" + address + \":\" + strconv.Itoa(port))\n\tstopped, err := serverConfig.SecureServing.Serve(s.buildHandlerChain(serverConfig), serverConfig.RequestTimeout, stopChan)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t<-stopped\n\treturn nil\n}", "func (s *TLSServer) ListenAndServe(addr string, handler http.Handler) {\n\n\tconfig, err := createServerConfig(s.Certspath)\n\tif err != nil {\n\t\tlog.Panic(logPrefix, \"create tls configuration failed: \", err.Error())\n\t}\n\n\ts.listener, err = tls.Listen(\"tcp\", addr, config)\n\tif err != nil {\n\t\tlog.Panic(logPrefix, \"listen failed: \", err.Error())\n\t}\n\n\tdefer s.listener.Close()\n\n\t(&http.Server{Handler: handler}).Serve(s.listener)\n}", "func ListenAndServe(addr, certFile, keyFile string, handler http.Handler) error {\n\t// Load certs\n\tvar err error\n\tcerts := make([]tls.Certificate, 1)\n\tcerts[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// We currently only use the cert-related stuff from tls.Config,\n\t// so we don't need to make a full copy.\n\tconfig := &tls.Config{\n\t\tCertificates: certs,\n\t}\n\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\t// Open the listeners\n\tudpAddr, err := net.ResolveUDPAddr(\"udp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tudpConn, err := net.ListenUDP(\"udp\", udpAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer udpConn.Close()\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\t// Start the servers\n\tquicServer := &Server{\n\t\tTLSConfig: config,\n\t\tHandler: handler,\n\t}\n\n\thErr := make(chan error)\n\tqErr := make(chan error)\n\tgo func() {\n\t\thErr <- http.ListenAndServeTLS(addr, certFile, keyFile, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tquicServer.SetQuicHeaders(w.Header())\n\t\t\thandler.ServeHTTP(w, r)\n\t\t}))\n\t}()\n\tgo func() {\n\t\tqErr <- quicServer.Serve(udpConn)\n\t}()\n\n\tselect {\n\tcase err := <-hErr:\n\t\tquicServer.Close()\n\t\treturn err\n\tcase err := <-qErr:\n\t\t// Cannot close the HTTP server or wait for requests to complete properly :/\n\t\treturn err\n\t}\n}", "func (gss *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo func() {\n\t\tif err := gss.server.ServeTLS(l, certFile, keyFile); err != nil {\n\t\t\tgss.startErr = err\n\t\t\tcancel()\n\t\t}\n\t}()\n\treturn gss.waitForInterrupt(ctx)\n}", "func (r *Router) RunTLS(addr, certFile, keyFile string) error {\n\treturn http.ListenAndServeTLS(addr, certFile, keyFile, r.chain())\n}", "func (r *Router) ListenAndServeFreeTLS(domain, certDir string) error {\n\t// Assign the router to the server handler\n\tr.Server.Handler = r.Router\n\tr.Server.Addr = \":https\"\n\n\t// Set up a cert manager that will retrieve configured SSL certs\n\t// for your domain\n\tcertManager := autocert.Manager{\n\t\tPrompt: autocert.AcceptTOS,\n\t\tHostPolicy: autocert.HostWhitelist(domain), // Your domain here\n\t\tCache: autocert.DirCache(\"certs\"), // Folder for storing certificates\n\t}\n\n\t// Set the GetCertificate func on the TLS config\n\tr.Server.TLSConfig = &tls.Config{\n\t\tGetCertificate: certManager.GetCertificate,\n\t}\n\n\t// HTTP needed for LetsEncrypt security issue. HTTP should however\n\t// redirect to HTTPS\n\tgo http.ListenAndServe(\":http\", certManager.HTTPHandler(nil))\n\n\t// Begin listening for TLS requests\n\treturn r.Server.ListenAndServeTLS(\"\", \"\")\n}", "func ListenAndServeTLS(addr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n\tconfig *tls.Config,\n) error {\n\treturn ListenAndServeNetworkTLS(\"tcp\", addr, handler, accept, closed, config)\n}", "func (s *httpServer) ListenAndServe(host, certFile, keyFile string, router http.Handler) error {\n\tif certFile != \"\" && keyFile != \"\" {\n\t\treturn http.ListenAndServeTLS(host, certFile, keyFile, router)\n\t}\n\n\treturn http.ListenAndServe(host, router)\n}", "func ListenAndServeTLSAsync(server *http.Server, certFile, keyFile string) error {\n\t// Start listening synchronously.\n\tlistener, err := net.Listen(tcpNetwork.Value, server.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Unlike ListenAndServeAsync we don't update the server's Addr when the\n\t// server.Addr ends with :0, because the resulting URL may or may not be\n\t// GET-able. In ipv6-only contexts it could be, for example, \"[::]:3232\", and\n\t// that URL can't be used for TLS because TLS needs a name or an explicit IP\n\t// and [::] doesn't qualify. It is unclear what the right thing to do is in\n\t// this situation, because names and IPs and TLS are suffciently complicated\n\t// that no one thing is the right thing in all situations, so we affirmatively\n\t// do nothing in an attempt to avoid making a bad situation worse.\n\n\t// Serve asynchronously.\n\tgo serveTLS(server, tcpKeepAliveListener{listener.(*net.TCPListener)}, certFile, keyFile)\n\treturn nil\n}", "func ListenAndServe(config Config, handler http.Handler) (srv *http.Server, err error) {\n\tserver := &http.Server{\n\t\tAddr: config.Endpoint,\n\t\tReadTimeout: config.ReadTimeout,\n\t\tReadHeaderTimeout: config.ReadHeaderTimeout,\n\t\tWriteTimeout: config.WriteTimeout,\n\t\tIdleTimeout: config.IdleTimeout,\n\t\tMaxHeaderBytes: config.MaxHeaderBytes,\n\t\tHandler: handler,\n\t}\n\n\tif len(config.ClientCerts) > 0 {\n\t\t// require client certificate\n\t\tcaCertPool := x509.NewCertPool()\n\n\t\tfor _, c := range config.ClientCerts {\n\t\t\tcaCert, err := ioutil.ReadFile(c)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif !caCertPool.AppendCertsFromPEM(caCert) {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to add CA from '%s' file\", c)\n\t\t\t}\n\t\t}\n\n\t\tserver.TLSConfig = &tls.Config{\n\t\t\tClientAuth: tls.RequireAndVerifyClientCert,\n\t\t\tClientCAs: caCertPool,\n\t\t}\n\t}\n\n\tln, err := net.Listen(\"tcp\", server.Addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl := tcpKeepAliveListener{ln.(*net.TCPListener)}\n\n\tgo func() {\n\t\tvar err error\n\t\tif config.UseHTTPS() {\n\t\t\t// if server certificate and key is configured use HTTPS\n\t\t\terr = server.ServeTLS(l, config.ServerCertfile, config.ServerKeyfile)\n\t\t} else {\n\t\t\terr = server.Serve(l)\n\t\t}\n\t\t// Serve always returns non-nil error\n\t\tlogging.Debugf(\"HTTP server Serve: %v\", err)\n\t}()\n\n\treturn server, nil\n}", "func (ts *TcpServer) StartTlsServer(port string) (err error) {\n\n\tbelogs.Debug(\"StartTlsServer(): tlsserver port:\", port)\n\tcert, err := tls.LoadX509KeyPair(ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver LoadX509KeyPair fail: port:\", port,\n\t\t\t\" tlsPublicCrtFileName, tlsPrivateKeyFileName:\", ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver cert:\", ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName)\n\n\trootCrtBytes, err := ioutil.ReadFile(ts.tlsRootCrtFileName)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver ReadFile tlsRootCrtFileName fail, port:\", port,\n\t\t\t\" tlsRootCrtFileName:\", ts.tlsRootCrtFileName, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver len(rootCrtBytes):\", len(rootCrtBytes), \" tlsRootCrtFileName:\", ts.tlsRootCrtFileName)\n\n\trootCertPool := x509.NewCertPool()\n\tok := rootCertPool.AppendCertsFromPEM(rootCrtBytes)\n\tif !ok {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver AppendCertsFromPEM tlsRootCrtFileName fail,port:\", port,\n\t\t\t\" tlsRootCrtFileName:\", ts.tlsRootCrtFileName, \" len(rootCrtBytes):\", len(rootCrtBytes), err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver AppendCertsFromPEM len(rootCrtBytes):\", len(rootCrtBytes), \" tlsRootCrtFileName:\", ts.tlsRootCrtFileName)\n\n\tclientAuthType := tls.NoClientCert\n\tif ts.tlsVerifyClient {\n\t\tclientAuthType = tls.RequireAndVerifyClientCert\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver clientAuthType:\", clientAuthType)\n\n\t// https://stackoverflow.com/questions/63676241/how-to-set-setkeepaliveperiod-on-a-tls-conn\n\tsetTCPKeepAlive := func(clientHello *tls.ClientHelloInfo) (*tls.Config, error) {\n\t\t// Check that the underlying connection really is TCP.\n\t\tif tcpConn, ok := clientHello.Conn.(*net.TCPConn); ok {\n\t\t\ttcpConn.SetKeepAlive(true)\n\t\t\ttcpConn.SetKeepAlivePeriod(time.Second * 300)\n\t\t\tbelogs.Debug(\"StartTlsServer(): tlsserver SetKeepAlive:\")\n\t\t}\n\t\t// Make sure to return nil, nil to let the caller fall back on the default behavior.\n\t\treturn nil, nil\n\t}\n\tconfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tClientAuth: clientAuthType,\n\t\tRootCAs: rootCertPool,\n\t\tInsecureSkipVerify: false,\n\t\tGetConfigForClient: setTCPKeepAlive,\n\t}\n\tlistener, err := tls.Listen(\"tcp\", \":\"+port, config)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver Listen fail, port:\", port, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): Listen ok, port:\", port)\n\n\t// get tcpListener\n\tts.tcpListener, err = NewFromTlsListener(listener)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver NewFromTlsListener fail, port: \", port, err)\n\t\treturn err\n\t}\n\tbelogs.Info(\"StartTlsServer(): tlsserver create server ok, port:\", port, \" will accept client\")\n\n\tgo ts.waitBusinessToConnMsg()\n\n\t// wait new conn\n\tts.acceptNewConn()\n\treturn nil\n}", "func (r *Router) RunTLS(addr, certFile, keyFile string) {\n\tr.server.Addr = addr\n\tr.server.Handler = r\n\tr.logger.Printf(\"listening tls on %s\", addr)\n\tr.logger.Fatal(r.server.ListenAndServeTLS(certFile, keyFile))\n}", "func ListenAndServeNetworkTLS(\n\tnet, laddr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n\tconfig *tls.Config,\n) error {\n\treturn NewServerNetworkTLS(net, laddr, handler, accept, closed, config).ListenAndServe()\n}", "func (s *Server) Listen(\n\taddr string,\n\tcertPath string,\n\tkeyPath string,\n) (err error) {\n\tlogger := logger.Logger()\n\tif err = s.init(); err != nil {\n\t\treturn\n\t}\n\n\topts := []grpc.ServerOption{}\n\ttlsFlag := false\n\n\tif certPath != \"\" && keyPath != \"\" {\n\t\tcreds, err := credentials.NewServerTLSFromFile(certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\topts = append(opts, grpc.Creds(creds))\n\t\ttlsFlag = true\n\t}\n\n\ts.grpcServer = grpc.NewServer(opts...)\n\tpb.RegisterEchoServer(s.grpcServer, s)\n\n\thttpMux := http.NewServeMux()\n\thttpMux.HandleFunc(\"/\", s.httpEchoPing)\n\n\trootMux := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.ProtoMajor == 2 && strings.Contains(req.Header.Get(\"Content-Type\"), \"application/grpc\") {\n\t\t\ts.grpcServer.ServeHTTP(w, req)\n\t\t} else {\n\t\t\thttpMux.ServeHTTP(w, req)\n\t\t}\n\t})\n\n\ts.httpServer = &http.Server{\n\t\tAddr: addr,\n\t\tHandler: h2c.NewHandler(rootMux, &http2.Server{}),\n\t}\n\n\tlogger.Printf(\"grpc listen address: %q tls: %v\", addr, tlsFlag)\n\tif tlsFlag {\n\t\treturn s.httpServer.ListenAndServeTLS(certPath, keyPath)\n\t}\n\treturn s.httpServer.ListenAndServe()\n}", "func (registry *Registry) ListenAndServe() error {\n\tconfig := registry.config\n\n\tln, err := listener.NewListener(config.HTTP.Net, config.HTTP.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif config.HTTP.TLS.Certificate != \"\" || config.HTTP.TLS.LetsEncrypt.CacheFile != \"\" {\n\t\tif config.HTTP.TLS.MinimumTLS == \"\" {\n\t\t\tconfig.HTTP.TLS.MinimumTLS = defaultTLSVersionStr\n\t\t}\n\t\ttlsMinVersion, ok := tlsVersions[config.HTTP.TLS.MinimumTLS]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown minimum TLS level '%s' specified for http.tls.minimumtls\", config.HTTP.TLS.MinimumTLS)\n\t\t}\n\t\tdcontext.GetLogger(registry.app).Infof(\"restricting TLS version to %s or higher\", config.HTTP.TLS.MinimumTLS)\n\n\t\tvar tlsCipherSuites []uint16\n\t\t// configuring cipher suites are no longer supported after the tls1.3.\n\t\t// (https://go.dev/blog/tls-cipher-suites)\n\t\tif tlsMinVersion > tls.VersionTLS12 {\n\t\t\tdcontext.GetLogger(registry.app).Warnf(\"restricting TLS cipher suites to empty. Because configuring cipher suites is no longer supported in %s\", config.HTTP.TLS.MinimumTLS)\n\t\t} else {\n\t\t\ttlsCipherSuites, err = getCipherSuites(config.HTTP.TLS.CipherSuites)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdcontext.GetLogger(registry.app).Infof(\"restricting TLS cipher suites to: %s\", strings.Join(getCipherSuiteNames(tlsCipherSuites), \",\"))\n\t\t}\n\n\t\ttlsConf := &tls.Config{\n\t\t\tClientAuth: tls.NoClientCert,\n\t\t\tNextProtos: nextProtos(config),\n\t\t\tMinVersion: tlsMinVersion,\n\t\t\tCipherSuites: tlsCipherSuites,\n\t\t}\n\n\t\tif config.HTTP.TLS.LetsEncrypt.CacheFile != \"\" {\n\t\t\tif config.HTTP.TLS.Certificate != \"\" {\n\t\t\t\treturn fmt.Errorf(\"cannot specify both certificate and Let's Encrypt\")\n\t\t\t}\n\t\t\tm := &autocert.Manager{\n\t\t\t\tHostPolicy: autocert.HostWhitelist(config.HTTP.TLS.LetsEncrypt.Hosts...),\n\t\t\t\tCache: autocert.DirCache(config.HTTP.TLS.LetsEncrypt.CacheFile),\n\t\t\t\tEmail: config.HTTP.TLS.LetsEncrypt.Email,\n\t\t\t\tPrompt: autocert.AcceptTOS,\n\t\t\t\tClient: setDirectoryURL(config.HTTP.TLS.LetsEncrypt.DirectoryURL),\n\t\t\t}\n\t\t\ttlsConf.GetCertificate = m.GetCertificate\n\t\t\ttlsConf.NextProtos = append(tlsConf.NextProtos, acme.ALPNProto)\n\t\t} else {\n\t\t\ttlsConf.Certificates = make([]tls.Certificate, 1)\n\t\t\ttlsConf.Certificates[0], err = tls.LoadX509KeyPair(config.HTTP.TLS.Certificate, config.HTTP.TLS.Key)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif len(config.HTTP.TLS.ClientCAs) != 0 {\n\t\t\tpool := x509.NewCertPool()\n\n\t\t\tfor _, ca := range config.HTTP.TLS.ClientCAs {\n\t\t\t\tcaPem, err := os.ReadFile(ca)\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 ok := pool.AppendCertsFromPEM(caPem); !ok {\n\t\t\t\t\treturn fmt.Errorf(\"could not add CA to pool\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, subj := range pool.Subjects() { //nolint:staticcheck // FIXME(thaJeztah): ignore SA1019: ac.(*accessController).rootCerts.Subjects has been deprecated since Go 1.18: if s was returned by SystemCertPool, Subjects will not include the system roots. (staticcheck)\n\t\t\t\tdcontext.GetLogger(registry.app).Debugf(\"CA Subject: %s\", string(subj))\n\t\t\t}\n\n\t\t\ttlsConf.ClientAuth = tls.RequireAndVerifyClientCert\n\t\t\ttlsConf.ClientCAs = pool\n\t\t}\n\n\t\tln = tls.NewListener(ln, tlsConf)\n\t\tdcontext.GetLogger(registry.app).Infof(\"listening on %v, tls\", ln.Addr())\n\t} else {\n\t\tdcontext.GetLogger(registry.app).Infof(\"listening on %v\", ln.Addr())\n\t}\n\n\tif config.HTTP.DrainTimeout == 0 {\n\t\treturn registry.server.Serve(ln)\n\t}\n\n\t// setup channel to get notified on SIGTERM signal\n\tsignal.Notify(quit, syscall.SIGTERM)\n\tserveErr := make(chan error)\n\n\t// Start serving in goroutine and listen for stop signal in main thread\n\tgo func() {\n\t\tserveErr <- registry.server.Serve(ln)\n\t}()\n\n\tselect {\n\tcase err := <-serveErr:\n\t\treturn err\n\tcase <-quit:\n\t\tdcontext.GetLogger(registry.app).Info(\"stopping server gracefully. Draining connections for \", config.HTTP.DrainTimeout)\n\t\t// shutdown the server with a grace period of configured timeout\n\t\tc, cancel := context.WithTimeout(context.Background(), config.HTTP.DrainTimeout)\n\t\tdefer cancel()\n\t\treturn registry.server.Shutdown(c)\n\t}\n}", "func (serv *Server) ListenAndServe() error {\n conf := serv.config\n e := make(chan error)\n\n log.Printf(\"Listening to HTTP requests on %s\", conf.HttpAddr)\n log.Printf(\"Listening to HTTPS requests on %s\", conf.HttpsAddr)\n\n // HTTP and TLS servers are bound to the socket addresses defined in the\n // Config structure, and respond to requests concurrently.\n // The responses are generated in the ServeHTTP function below.\n go func() {\n e <- http.ListenAndServe(conf.HttpAddr, http.Handler(serv))\n }()\n go func() {\n e <- serv.httpsServer.ListenAndServeTLS(conf.CertFile, conf.KeyFile)\n }()\n\n // Block execution until one of the functions returns with a critical error.\n // This may fail if you are trying to bind to a port that is in use, or if\n // you do not have proper permissions to bind to that port.\n err := <-e\n\n if err != nil {\n log.Println(err)\n }\n\n return err\n}", "func (a *TCPAcceptor) listenAndServeTLS() {\n\ttlsCfg := &tls.Config{Certificates: a.certs}\n\n\tlistener, err := tls.Listen(\"tcp\", a.addr, tlsCfg)\n\tif err != nil {\n\t\tlogger.Log.Fatalf(\"Failed to listen: %s\", err.Error())\n\t}\n\ta.listener = listener\n\ta.running = true\n\ta.serve()\n}", "func listen() error {\n\t// define https variable\n\taddress := config.Get(\"https\", \"address\")\n\tcertificate := config.Get(\"https\", \"certificate\")\n\tkey := config.Get(\"https\", \"key\")\n\n\t// return error\n\treturn http.ListenAndServeTLS(address, certificate, key, nil)\n}", "func (s *Server) ServeHTTPSWithCert(certFile, certKey string) error {\n\treturn s.router.RunTLS(fmt.Sprintf(\"%s:%d\", s.listen, s.port), certFile, certKey)\n}", "func LoadServerTLSConfig(sslCA, sslCert, sslCertKey string) (*tls.Config, error) {\n\tcertPEM, err := assetLoaderImpl.ReadFile(sslCert)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyPEM, err := assetLoaderImpl.ReadFile(sslCertKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcaPEM, err := assetLoaderImpl.ReadFile(sslCA)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newServerTLSConfig(certPEM, keyPEM, caPEM)\n}", "func (s *Server) ListenAndServeLetsencrypt() error {\n\treturn s.server.ListenAndServeTLS(\"\", \"\")\n}", "func SecureServe(addr string, certFile, keyFile, caFile string) {\n\tconfig := tls.Config{}\n\n\t// load the server cert / key\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\tconfig.Certificates = []tls.Certificate{cert}\n\n\t// load the ca if necessary\n\t// FIXME(alainjobart) this doesn't quite work yet, have\n\t// to investigate\n\tif caFile != \"\" {\n\t\tconfig.ClientCAs = x509.NewCertPool()\n\n\t\tpemCerts, err := ioutil.ReadFile(caFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"%s\", err)\n\t\t}\n\t\tif !config.ClientCAs.AppendCertsFromPEM(pemCerts) {\n\t\t\tlog.Fatalf(\"%s\", err)\n\t\t}\n\n\t\tconfig.ClientAuth = tls.RequireAndVerifyClientCert\n\t}\n\tl, err := tls.Listen(\"tcp\", addr, &config)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\tcl := proc.Published(l, \"SecureConns\", \"SecureAccepts\")\n\tgo http.Serve(cl, nil)\n}", "func ListenAndServeHTTPS(addr string, config *tls.Config, handler http.Handler) error {\n\tlis, err := ListenTLS(\"tcp\", addr, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn http.Serve(lis, handler)\n}", "func NewServer(\n\tctx context.Context,\n\taddr string,\n\tk8sAPI *k8s.API,\n\tgrpcTapServer pb.TapServer,\n\tdisableCommonNames bool,\n) (*Server, error) {\n\tupdateEvent := make(chan struct{})\n\terrEvent := make(chan error)\n\twatcher := pkgTls.NewFsCredsWatcher(pkgk8s.MountPathTLSBase, updateEvent, errEvent).\n\t\tWithFilePaths(pkgk8s.MountPathTLSCrtPEM, pkgk8s.MountPathTLSKeyPEM)\n\tgo func() {\n\t\tif err := watcher.StartWatching(ctx); err != nil {\n\t\t\tlog.Fatalf(\"Failed to start creds watcher: %s\", err)\n\t\t}\n\t}()\n\n\tclientCAPem, allowedNames, usernameHeader, groupHeader, err := serverAuth(ctx, k8sAPI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// for development\n\tif disableCommonNames {\n\t\tallowedNames = []string{}\n\t}\n\n\tlog := log.WithFields(log.Fields{\n\t\t\"component\": \"tap\",\n\t\t\"addr\": addr,\n\t})\n\n\tclientCertPool := x509.NewCertPool()\n\tclientCertPool.AppendCertsFromPEM([]byte(clientCAPem))\n\n\thttpServer := &http.Server{\n\t\tAddr: addr,\n\t\tReadHeaderTimeout: 15 * time.Second,\n\t\tTLSConfig: &tls.Config{\n\t\t\tClientAuth: tls.VerifyClientCertIfGiven,\n\t\t\tClientCAs: clientCertPool,\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t},\n\t}\n\n\tvar emptyCert atomic.Value\n\th := &handler{\n\t\tk8sAPI: k8sAPI,\n\t\tusernameHeader: usernameHeader,\n\t\tgroupHeader: groupHeader,\n\t\tgrpcTapServer: grpcTapServer,\n\t\tlog: log,\n\t}\n\n\tlis, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"net.Listen failed with: %w\", err)\n\t}\n\n\ts := &Server{\n\t\tServer: httpServer,\n\t\tlistener: lis,\n\t\trouter: initRouter(h),\n\t\tallowedNames: allowedNames,\n\t\tcertValue: &emptyCert,\n\t\tlog: log,\n\t}\n\ts.Handler = prometheus.WithTelemetry(s)\n\thttpServer.TLSConfig.GetCertificate = s.getCertificate\n\n\tif err := watcher.UpdateCert(s.certValue); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialized certificate: %w\", err)\n\t}\n\n\tgo watcher.ProcessEvents(log, s.certValue, updateEvent, errEvent)\n\n\treturn s, nil\n}", "func main() {\n\tr := &http.ServeMux{}\n\tr.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"A web page on HTTPS\"))\n\t})\n\n\thttp.ListenAndServeTLS(\":8080\", \"../cert/server.crt\", \"../cert/server.key\", r)\n}", "func FdListenAndServeTLS(fd int, addr, certFile, keyFile string, handler http.Handler) error {\n\tvar err error\n\tserver, err = FromFd(fd, &http.Server{\n\t\tAddr: addr,\n\t\tHandler: handler,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn server.ListenAndServeTLS(certFile, keyFile)\n}", "func main() {\n\thomeDir, err := os.UserHomeDir()\n\tif err != nil {\n\t\tlog.Fatal(\"error in getting home directory\")\n\t}\n\tsslCertDirArg := flag.String(\"d\", homeDir+\"/ssl-local-cert\", \"the directory of SSL cert\")\n\tsslCrtNameArg := flag.String(\"c\", \"test.iw.com.pem\", \"the filename of SSL cert\")\n\tsslKeyNameArg := flag.String(\"k\", \"test.iw.com-key.pem\", \"the filename of SSL key\")\n\tflag.Parse()\n\n\tif string((*sslCrtNameArg)[0]) != \"/\" {\n\t\t*sslCrtNameArg = \"/\" + *sslCrtNameArg\n\t}\n\tif string((*sslKeyNameArg)[0]) != \"/\" {\n\t\t*sslKeyNameArg = \"/\" + *sslKeyNameArg\n\t}\n\tsslCertCrtPath := *sslCertDirArg + *sslCrtNameArg\n\tsslCertKeyPath := *sslCertDirArg + *sslKeyNameArg\n\n\tfmt.Println(sslCertCrtPath)\n\tfmt.Println(sslCertKeyPath)\n\n\t// create file server handler serving current directory\n\tfs := http.FileServer(http.Dir(\".\"))\n\n\t// start HTTP server with `fs` as the default handler\n\tfmt.Println(\"server run with :9000 and :443\")\n\tlog.Fatal(http.ListenAndServeTLS(\":443\", sslCertCrtPath, sslCertKeyPath, fs))\n\tlog.Fatal(http.ListenAndServe(\":9000\", fs))\n\n}", "func (s *FrontendServer) Run(tls bool, certFile string,\n\tkeyFile string) error {\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", s.hostname, s.port))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\tvar lis2 net.Listener\n\tif (s.hostnameGw != \"\") && (s.portGw != 0) {\n\t\tlis2, err = net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", s.hostnameGw, s.portGw))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to listen on second address: %v\", err)\n\t\t}\n\t}\n\tvar opts []grpc.ServerOption\n\tif tls {\n\t\t// if caFile == \"\" {\n\t\t// \tset default caFile path\n\t\t// }\n\t\t// if keyFile == \"\" {\n\t\t// \tset default keyFile path\n\t\t// }\n\t\tcreds, err := credentials.NewServerTLSFromFile(certFile, keyFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to generate credentials %v\", err)\n\t\t}\n\t\topts = []grpc.ServerOption{grpc.Creds(creds)}\n\t}\n\tgrpcServer := grpc.NewServer(opts...)\n\tpb.RegisterFrontendServer(grpcServer, s)\n\tgo grpcServer.Serve(lis)\n\tif lis2 != nil {\n\t\tgo grpcServer.Serve(lis2)\n\t}\n\treturn nil\n}", "func (s *Server) ServeTLS(ctx context.Context, ln net.Listener) error {\n\tln = tls.NewListener(ln, s.TLSConfig.Clone())\n\tdefer ln.Close()\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tgo func(conn net.Conn) {\n\t\t\tif err := conn.(*tls.Conn).Handshake(); err != nil {\n\t\t\t\ts.logf(\"dns handshake: %s\", err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts.serveStream(ctx, conn)\n\t\t}(conn)\n\t}\n}", "func (r *Router) Serve() {\n\tvar err error\n\tif conf.Options.SSL.Cert != \"\" {\n\t\t// First, listen on the HTTP address with redirect\n\t\tgo func() {\n\t\t\terr := http.ListenAndServe(conf.Options.HTTPAddress, http.HandlerFunc(redirectToHTTPS))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}()\n\t\taddr := conf.Options.Address\n\t\tif addr == \"\" {\n\t\t\taddr = \":https\"\n\t\t}\n\t\tserver := &http.Server{Addr: conf.Options.Address, Handler: r}\n\t\tconfig := &tls.Config{NextProtos: []string{\"http/1.1\"}}\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.X509KeyPair([]byte(conf.Options.SSL.Cert), []byte(conf.Options.SSL.Key))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tln, err := net.Listen(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\ttlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, config)\n\t\terr = server.Serve(tlsListener)\n\t} else {\n\t\terr = http.ListenAndServe(conf.Options.Address, r)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func httpsServer(\n\tserverUsername string,\n\tserverPassword string,\n\ttlsCert string,\n\ttlsKey string,\n) (*httptest.Server, error) {\n\ts, err := testServer(serverUsername, serverPassword)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcert, err := tls.LoadX509KeyPair(tlsCert, tlsKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tMinVersion: tls.VersionTLS12,\n\t}\n\ts.TLS = config\n\n\ts.StartTLS()\n\treturn s, nil\n}", "func startHTTPSListener(service, certFile, keyFile string) error {\n\ts := http.Server{}\n\n\t// If certFile and/or keyFile are blank, generate a self-signed TLS cert\n\tif len(certFile) == 0 || len(keyFile) == 0 {\n\t\tselfSignedCert, err := privatetls.NewCert()\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ts.TLSConfig = &tls.Config{\n\t\t\tCertificates: []tls.Certificate{selfSignedCert},\n\t\t}\n\t}\n\n\ts.Addr = service\n\n\treturn s.ListenAndServeTLS(certFile, keyFile)\n}", "func (srv *Server) ListenAndServe() error {\n\tif srv.TLSConfig != nil {\n\t\tl, err := tls.Listen(\"tcp\", srv.Addr, srv.TLSConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn srv.Serve(l)\n\t}\n\tl, err := net.Listen(\"tcp\", srv.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn srv.Serve(l)\n}", "func (s *Server) ServeHTTPS(addr string, tlsConfig *tls.Config) error {\n\n\thttp.HandleFunc(\"/wsman/SubscriptionManager/WEC\",\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\ts.subscriptionManager(w, r)\n\t\t})\n\thttp.HandleFunc(\"/wsman/subscriptions/\",\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\ts.subscriptions(w, r)\n\t\t})\n\thttp.HandleFunc(\"/\",\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tdump, err := httputil.DumpRequest(r, true)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, fmt.Sprint(err), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Printf(\"Unhandled request:\\n%s\\n\", dump)\n\t\t\thttp.Error(w, \"Not implemented yet\", http.StatusNotImplemented)\n\t\t})\n\thttpd := &http.Server{\n\t\tAddr: addr,\n\t\tTLSConfig: tlsConfig,\n\t}\n\tlog.Printf(\"WEF HTTPS: listening at %s\\n\", addr)\n\treturn httpd.ListenAndServeTLS(\"\", \"\")\n}", "func NewServerTLS(addr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n\tconfig *tls.Config,\n) *TLSServer {\n\treturn NewServerNetworkTLS(\"tcp\", addr, handler, accept, closed, config)\n}", "func (s *HTTPServer) Run() error {\n\tif s.certFiles == \"\" {\n\t\tglog.Info(\"http server starting to listen on http://\", s.https.Addr)\n\t\treturn s.https.ListenAndServe()\n\t}\n\tglog.Info(\"http server starting to listen on https://\", s.https.Addr)\n\treturn s.https.ListenAndServeTLS(fmt.Sprint(s.certFiles, \".crt\"), fmt.Sprint(s.certFiles, \".key\"))\n}", "func (api *API) ListenAndServe(ctx context.Context, addr string, tlsConfig *TLSConfig) error {\n\tserver := &http.Server{\n\t\tAddr: addr,\n\t\tHandler: api.r,\n\t}\n\terrChan := make(chan error, 1)\n\tgo func() {\n\t\tif tlsConfig != nil {\n\t\t\t// configure TLS to override defaults\n\t\t\ttlsCfg := &tls.Config{\n\t\t\t\tCurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},\n\t\t\t\t//PreferServerCipherSuites: true,\n\t\t\t\tCipherSuites: []uint16{\n\t\t\t\t\t// http/2 mandated supported cipher\n\t\t\t\t\t// unforunately this is a less secure cipher\n\t\t\t\t\t// but specifying it first is the only way to accept\n\t\t\t\t\t// http/2 connections without go throwing an error\n\t\t\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\t\t\t// super duper secure ciphers\n\t\t\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\t\t\ttls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\t\t\ttls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t\t\t\t},\n\t\t\t\t// consider whether or not to fix to tls1.2\n\t\t\t\tMinVersion: tls.VersionTLS11,\n\t\t\t}\n\t\t\t// set tls configuration\n\t\t\tserver.TLSConfig = tlsCfg\n\t\t\terrChan <- server.ListenAndServeTLS(tlsConfig.CertFile, tlsConfig.KeyFile)\n\t\t\treturn\n\t\t}\n\t\terrChan <- server.ListenAndServe()\n\t\treturn\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase err := <-errChan:\n\t\t\treturn err\n\t\tcase <-ctx.Done():\n\t\t\treturn server.Close()\n\t\tcase msg := <-api.queues.cluster.ErrCh:\n\t\t\tqmCluster, err := api.handleQueueError(msg, api.cfg.RabbitMQ.URL, queue.IpfsClusterPinQueue, true)\n\t\t\tif err != nil {\n\t\t\t\treturn server.Close()\n\t\t\t}\n\t\t\tapi.queues.cluster = qmCluster\n\t\tcase msg := <-api.queues.dash.ErrCh:\n\t\t\tqmDash, err := api.handleQueueError(msg, api.cfg.RabbitMQ.URL, queue.DashPaymentConfirmationQueue, true)\n\t\t\tif err != nil {\n\t\t\t\treturn server.Close()\n\t\t\t}\n\t\t\tapi.queues.dash = qmDash\n\t\tcase msg := <-api.queues.email.ErrCh:\n\t\t\tqmEmail, err := api.handleQueueError(msg, api.cfg.RabbitMQ.URL, queue.EmailSendQueue, true)\n\t\t\tif err != nil {\n\t\t\t\treturn server.Close()\n\t\t\t}\n\t\t\tapi.queues.email = qmEmail\n\t\tcase msg := <-api.queues.ipns.ErrCh:\n\t\t\tqmIpns, err := api.handleQueueError(msg, api.cfg.RabbitMQ.URL, queue.IpnsEntryQueue, true)\n\t\t\tif err != nil {\n\t\t\t\treturn server.Close()\n\t\t\t}\n\t\t\tapi.queues.ipns = qmIpns\n\t\tcase msg := <-api.queues.key.ErrCh:\n\t\t\tqmKey, err := api.handleQueueError(msg, api.cfg.RabbitMQ.URL, queue.IpfsKeyCreationQueue, true)\n\t\t\tif err != nil {\n\t\t\t\treturn server.Close()\n\t\t\t}\n\t\t\tapi.queues.key = qmKey\n\t\tcase msg := <-api.queues.eth.ErrCh:\n\t\t\tqmEth, err := api.handleQueueError(msg, api.cfg.RabbitMQ.URL, queue.EthPaymentConfirmationQueue, true)\n\t\t\tif err != nil {\n\t\t\t\treturn server.Close()\n\t\t\t}\n\t\t\tapi.queues.eth = qmEth\n\t\tcase msg := <-api.queues.pin.ErrCh:\n\t\t\tqmPin, err := api.handleQueueError(msg, api.cfg.RabbitMQ.URL, queue.IpfsPinQueue, true)\n\t\t\tif err != nil {\n\t\t\t\treturn server.Close()\n\t\t\t}\n\t\t\tapi.queues.pin = qmPin\n\t\tcase msg := <-api.queues.bch.ErrCh:\n\t\t\tqmBch, err := api.handleQueueError(msg, api.cfg.RabbitMQ.URL, queue.BitcoinCashPaymentConfirmationQueue, true)\n\t\t\tif err != nil {\n\t\t\t\treturn server.Close()\n\t\t\t}\n\t\t\tapi.queues.bch = qmBch\n\t\t}\n\t}\n}", "func (s *WebhookServer) Start() error {\n\t// Load server certificate.\n\tkeyPair, err := tls.LoadX509KeyPair(\n\t\ts.Settings.ServerCertPath,\n\t\ts.Settings.ServerKeyPath,\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"load TLS certs: %v\", err)\n\t}\n\n\t// Construct a hostname for certificate.\n\thost := fmt.Sprintf(\"%s.%s\",\n\t\ts.Settings.ServiceName,\n\t\ts.Namespace,\n\t)\n\n\ttlsConf := &tls.Config{\n\t\tCertificates: []tls.Certificate{keyPair},\n\t\tServerName: host,\n\t}\n\n\t// Load client CA if defined\n\tif len(s.Settings.ClientCAPaths) > 0 {\n\t\troots := x509.NewCertPool()\n\n\t\tfor _, caPath := range s.Settings.ClientCAPaths {\n\t\t\tcaBytes, err := os.ReadFile(caPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"load client CA '%s': %v\", caPath, err)\n\t\t\t}\n\n\t\t\tok := roots.AppendCertsFromPEM(caBytes)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"parse client CA '%s': %v\", caPath, err)\n\t\t\t}\n\t\t}\n\n\t\ttlsConf.ClientAuth = tls.RequireAndVerifyClientCert\n\t\ttlsConf.ClientCAs = roots\n\t}\n\n\tlistenAddr := net.JoinHostPort(s.Settings.ListenAddr, s.Settings.ListenPort)\n\t// Check if port is available\n\tlistener, err := net.Listen(\"tcp\", listenAddr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"try listen on '%s': %v\", listenAddr, err)\n\t}\n\n\ttimeout := time.Duration(10) * time.Second\n\n\tsrv := &http.Server{\n\t\tHandler: s.Router,\n\t\tTLSConfig: tlsConf,\n\t\tAddr: listenAddr,\n\t\tIdleTimeout: timeout,\n\t\tReadTimeout: timeout,\n\t\tReadHeaderTimeout: timeout,\n\t}\n\n\tgo func() {\n\t\tlog.Infof(\"Webhook server listens on %s\", listenAddr)\n\t\terr := srv.ServeTLS(listener, \"\", \"\")\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error starting Webhook https server: %v\", err)\n\t\t\t// Stop process if server can't start.\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\treturn nil\n}", "func RunTLS() {\n\tApp.Init()\n\n\tif Config.String(\"cert\") == \"\" || Config.String(\"cert_key\") == \"\" {\n\t\tpanic(\"Invalid cert files or key. Please review your configuration.\")\n\t}\n\n\tif Config.String(\"address\") != \"\" {\n\t\tLog.Info(fmt.Sprintf(\"listening TLS on %s\", Config.String(\"address\")))\n\t\tLog.Error(http.ListenAndServeTLS(Config.String(\"address\"), Config.String(\"cert\"), Config.String(\"cert_key\"), App.Router))\n\t} else {\n\t\tLog.Info(fmt.Sprintf(\"listening TLS on port :%d\", Config.Int(\"port\")))\n\t\tLog.Error(http.ListenAndServeTLS(fmt.Sprintf(\":%d\", Config.Int(\"port\")), Config.String(\"cert\"), Config.String(\"cert_key\"), App.Router))\n\t}\n}", "func (server *Server) runServerTLS() {\n\tserver.G.Go(func() error {\n\t\tserver.API.log.Info(\"running server TLS %v\", server.config.Server.ListenAddr)\n\t\treturn http.ListenAndServeTLS(server.config.Server.HTTPSAddr, server.config.TLS.CertFile, server.config.TLS.KeyFile, server.Server.Handler)\n\t})\n}", "func TestFileTLS(t *testing.T) {\n\t// Create a temporary directory\n\tdir, err := ioutil.TempDir(\"\", \"gorilla_test\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\t// Setup TLS auth\n\tdownloadCfg.TLSAuth = true\n\tdownloadCfg.TLSClientCert = \"testdata/client.pem\"\n\tdownloadCfg.TLSClientKey = \"testdata/client.key\"\n\tdownloadCfg.TLSServerCert = \"testdata/server.pem\"\n\tserverKeyPath := \"testdata/server.key\"\n\tcaCertPath := \"testdata/rootCA.pem\"\n\n\t// Create a test server\n\tts := httptest.NewUnstartedServer(router())\n\n\t// Prepare server certs\n\tserverCert, _ := ioutil.ReadFile(downloadCfg.TLSServerCert)\n\tserverKey, _ := ioutil.ReadFile(serverKeyPath)\n\tcaCert, _ := ioutil.ReadFile(caCertPath)\n\n\tcertPool := x509.NewCertPool()\n\tcertPool.AppendCertsFromPEM(caCert)\n\n\tcert, err := tls.X509KeyPair(serverCert, serverKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Set TLS configuration\n\tts.TLS = &tls.Config{\n\t\tClientAuth: tls.RequireAndVerifyClientCert,\n\t\tClientCAs: certPool,\n\t\tCertificates: []tls.Certificate{cert},\n\t}\n\n\t// Start server\n\tts.StartTLS()\n\tdefer ts.Close()\n\n\t// Compile the url with hostname instead of ip address\n\tu, err := url.Parse(ts.URL)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttlsURL := \"https://localhost:\" + u.Port() + \"/tlsauth\"\n\n\t// Run the code\n\tfileErr := File(dir, tlsURL)\n\n\t// Check that we did not receive an error\n\tif fileErr != nil {\n\t\tt.Errorf(\"File download with TLS auth failed':\\n%v\", fileErr)\n\t}\n\n}", "func SMTPServerTLS(t *testing.T, addr string, fn ...SMTPServerConfigureFunc) (*tls.Config, *SMTPBackend, *smtp.Server) {\n\tt.Helper()\n\n\tcert, err := tls.X509KeyPair([]byte(testServerCert), []byte(testServerKey))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := tls.Listen(\"tcp\", addr, &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbe := new(SMTPBackend)\n\ts := smtp.NewServer(be)\n\ts.Domain = \"localhost\"\n\tfor _, f := range fn {\n\t\tf(s)\n\t}\n\n\tpool := x509.NewCertPool()\n\tpool.AppendCertsFromPEM([]byte(testServerCert))\n\n\tclientCfg := &tls.Config{\n\t\tServerName: \"127.0.0.1\",\n\t\tTime: func() time.Time {\n\t\t\treturn time.Date(2019, time.November, 18, 17, 59, 41, 0, time.UTC)\n\t\t},\n\t\tRootCAs: pool,\n\t}\n\n\tgo func() {\n\t\tif err := s.Serve(l); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\t// Dial it once it make sure Server completes its initialization before\n\t// we try to use it. Notably, if test fails before connecting to the server,\n\t// it will call Server.Close which will call Server.listener.Close with a\n\t// nil Server.listener (Serve sets it to a non-nil value, so it is racy and\n\t// happens only sometimes).\n\ttestConn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttestConn.Close()\n\n\treturn clientCfg, be, s\n}", "func (a *API) Serve(certPath, keyPath string) (err error) {\n\tm := http.NewServeMux()\n\tm.HandleFunc(\"/submit_cert\", a.submissionHandler)\n\tsrv := &http.Server{Addr: a.addr, Handler: m}\n\n\tif certPath != \"\" && keyPath != \"\" {\n\t\tcert, err := tls.LoadX509KeyPair(certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttlsConf := &tls.Config{\n\t\t\tCertificates: []tls.Certificate{cert},\n\t\t\tNextProtos: []string{\"http/1.1\"},\n\t\t}\n\t\tsrv.TLSConfig = tlsConf\n\t}\n\tl, err := net.Listen(\"tcp\", a.addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.listener = l\n\tdefer l.Close()\n\treturn srv.Serve(l)\n}", "func (self *Proxy) StartTLS(cert string, key string) error {\n\n\tself.srv = http.Server{\n\t\tAddr: self.Bind,\n\t\tHandler: self,\n\t}\n\n\tlog.Printf(\"Listening for HTTPs client request at %s.\\n\", self.Bind)\n\n\treturn self.srv.ListenAndServeTLS(cert, key)\n}", "func WithTLS(cert, key string) ServerOption {\n\treturn func(opt *ServerConfig) error {\n\t\topt.TLS = true\n\t\topt.certFile = cert\n\t\topt.keyFile = key\n\t\treturn nil\n\t}\n}", "func RunTLS(addr string, config *tls.Config) {\n\tmainServer.RunTLS(addr, config)\n}", "func NewServerTLSConfig(caCrtFile, certFile, keyFile string) (*tls.Config, error) {\n\ttc := &tls.Config{}\n\n\tpool := x509.NewCertPool()\n\tcaCertPath := caCrtFile\n\n\tcaCrt, err := ioutil.ReadFile(caCertPath)\n\tif err != nil {\n\t\tfmt.Println(\"ReadFile err:\", err)\n\t\treturn nil, err\n\t}\n\tpool.AppendCertsFromPEM(caCrt)\n\n\ttc.ClientCAs = pool\n\n\tif certFile != \"\" {\n\t\tcliCrt, err := tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttc.Certificates = []tls.Certificate{cliCrt}\n\t}\n\treturn tc, nil\n}", "func (srv *Server) Run() error {\n\tlog.Printf(\"Server listening on port %v\", srv.cfg.Port)\n\treturn http.ListenAndServeTLS(fmt.Sprintf(\":%v\", srv.cfg.Port), srv.cfg.CertFilePath, srv.cfg.KeyFilePath, srv.router)\n}", "func ListenAndServeHTTP(addr string, connLimit int, certFile *string, keyFile *string, handler http.Handler, readTimeout *int, writeTimeout *int, http2Enabled bool) error {\n\tvar config *tls.Config\n\tif certFile != nil {\n\t\tconfig = &tls.Config{}\n\t\tconfig.MinVersion = tls.VersionTLS10 // Disable SSLv3 due to POODLE vulnerability\n\t\tprotocolsEnabled := []string{\"http/1.1\"}\n\t\tif http2Enabled {\n\t\t\tprotocolsEnabled = []string{\"h2\", \"http/1.1\"}\n\t\t}\n\t\tconfig.NextProtos = protocolsEnabled\n\t\tLogTo(\"HTTP\", \"Protocols enabled: %v on %v\", config.NextProtos, addr)\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tvar err error\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(*certFile, *keyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tlistener, err := ThrottledListen(\"tcp\", addr, connLimit)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif config != nil {\n\t\tlistener = tls.NewListener(listener, config)\n\t}\n\tdefer listener.Close()\n\tserver := &http.Server{Addr: addr, Handler: handler}\n\tif readTimeout != nil {\n\t\tserver.ReadTimeout = time.Duration(*readTimeout) * time.Second\n\t}\n\tif writeTimeout != nil {\n\t\tserver.WriteTimeout = time.Duration(*writeTimeout) * time.Second\n\t}\n\n\treturn server.Serve(listener)\n}", "func (s *Server) Serve(lis net.Listener) {\n\thttpsrv := &http.Server{\n\t\tTLSConfig: s.opts.creds.Config,\n\t}\n\thttp.HandleFunc(\"/\", s.wshandler)\n\tgo httpsrv.ServeTLS(lis, \"\", \"\")\n\tdefer httpsrv.Close()\n\n\ts.httpsrv = httpsrv\n\n\t<-s.done.Done()\n}", "func TestServeContextCertificateHandling(t *testing.T) {\n\ttests := map[string]struct {\n\t\tserverCredentialsDir string\n\t\tclientCredentialsDir string\n\t\texpectedServerCert string\n\t\texpectError bool\n\t}{\n\t\t\"successful TLS connection established\": {\n\t\t\tserverCredentialsDir: \"testdata/1\",\n\t\t\tclientCredentialsDir: \"testdata/1\",\n\t\t\texpectedServerCert: \"testdata/1/contourcert.pem\",\n\t\t\texpectError: false,\n\t\t},\n\t\t\"rotating server credentials returns new server cert\": {\n\t\t\tserverCredentialsDir: \"testdata/2\",\n\t\t\tclientCredentialsDir: \"testdata/2\",\n\t\t\texpectedServerCert: \"testdata/2/contourcert.pem\",\n\t\t\texpectError: false,\n\t\t},\n\t\t\"rotating server credentials again to ensure rotation can be repeated\": {\n\t\t\tserverCredentialsDir: \"testdata/1\",\n\t\t\tclientCredentialsDir: \"testdata/1\",\n\t\t\texpectedServerCert: \"testdata/1/contourcert.pem\",\n\t\t\texpectError: false,\n\t\t},\n\t\t\"fail to connect with client certificate which is not signed by correct CA\": {\n\t\t\tserverCredentialsDir: \"testdata/2\",\n\t\t\tclientCredentialsDir: \"testdata/1\",\n\t\t\texpectedServerCert: \"testdata/2/contourcert.pem\",\n\t\t\texpectError: true,\n\t\t},\n\t}\n\n\t// Create temporary directory to store certificates and key for the server.\n\tconfigDir, err := ioutil.TempDir(\"\", \"contour-testdata-\")\n\tcheckFatalErr(t, err)\n\tdefer os.RemoveAll(configDir)\n\n\tcontourTLS := &contour_api_v1alpha1.TLS{\n\t\tCAFile: filepath.Join(configDir, \"CAcert.pem\"),\n\t\tCertFile: filepath.Join(configDir, \"contourcert.pem\"),\n\t\tKeyFile: filepath.Join(configDir, \"contourkey.pem\"),\n\t\tInsecure: false,\n\t}\n\n\t// Initial set of credentials must be linked into temp directory before\n\t// starting the tests to avoid error at server startup.\n\terr = linkFiles(\"testdata/1\", configDir)\n\tcheckFatalErr(t, err)\n\n\t// Start a dummy server.\n\tlog := fixture.NewTestLogger(t)\n\topts := grpcOptions(log, contourTLS)\n\tg := grpc.NewServer(opts...)\n\tif g == nil {\n\t\tt.Error(\"failed to create server\")\n\t}\n\n\taddress := \"localhost:8001\"\n\tl, err := net.Listen(\"tcp\", address)\n\tcheckFatalErr(t, err)\n\n\tgo func() {\n\t\terr := g.Serve(l)\n\t\tcheckFatalErr(t, err)\n\t}()\n\tdefer g.GracefulStop()\n\n\tfor name, tc := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t// Link certificates and key to temp dir used by serveContext.\n\t\t\terr = linkFiles(tc.serverCredentialsDir, configDir)\n\t\t\tcheckFatalErr(t, err)\n\t\t\treceivedCert, err := tryConnect(address, tc.clientCredentialsDir)\n\t\t\tgotError := err != nil\n\t\t\tif gotError != tc.expectError {\n\t\t\t\tt.Errorf(\"Unexpected result when connecting to the server: %s\", err)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\texpectedCert, err := loadCertificate(tc.expectedServerCert)\n\t\t\t\tcheckFatalErr(t, err)\n\t\t\t\tassert.Equal(t, receivedCert, expectedCert)\n\t\t\t}\n\t\t})\n\t}\n}", "func NewServerTLSConfig(certFile, keyFile string) (*tls.Config, error) {\n\ttlsCert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load keypair: %s\", err)\n\t}\n\n\ttlsConfig := NewTLSConfig()\n\n\ttlsConfig.Certificates = []tls.Certificate{tlsCert}\n\n\treturn tlsConfig, nil\n}", "func (s Server) Listen() error {\n\tlog.WithField(\"address\", s.opts.ListenAddress).Info(\"Now serving.\")\n\treturn http.ListenAndServeTLS(s.opts.ListenAddress, secrets.FilenameTLSCertificate, secrets.FilenameTLSKey, nil)\n}", "func SMTPServerSTARTTLS(t *testing.T, addr string, fn ...SMTPServerConfigureFunc) (*tls.Config, *SMTPBackend, *smtp.Server) {\n\tt.Helper()\n\n\tcert, err := tls.X509KeyPair([]byte(testServerCert), []byte(testServerKey))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbe := new(SMTPBackend)\n\ts := smtp.NewServer(be)\n\ts.Domain = \"localhost\"\n\ts.AllowInsecureAuth = true\n\ts.TLSConfig = &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t}\n\tfor _, f := range fn {\n\t\tf(s)\n\t}\n\n\tpool := x509.NewCertPool()\n\tpool.AppendCertsFromPEM([]byte(testServerCert))\n\n\tclientCfg := &tls.Config{\n\t\tServerName: \"127.0.0.1\",\n\t\tTime: func() time.Time {\n\t\t\treturn time.Date(2019, time.November, 18, 17, 59, 41, 0, time.UTC)\n\t\t},\n\t\tRootCAs: pool,\n\t}\n\n\tgo func() {\n\t\tif err := s.Serve(l); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\t// Dial it once it make sure Server completes its initialization before\n\t// we try to use it. Notably, if test fails before connecting to the server,\n\t// it will call Server.Close which will call Server.listener.Close with a\n\t// nil Server.listener (Serve sets it to a non-nil value, so it is racy and\n\t// happens only sometimes).\n\ttestConn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttestConn.Close()\n\n\treturn clientCfg, be, s\n}", "func Test_App_ListenTLS(t *testing.T) {\n\tt.Parallel()\n\tapp := New()\n\n\t// invalid port\n\tutils.AssertEqual(t, false, app.ListenTLS(\":99999\", \"./.github/testdata/ssl.pem\", \"./.github/testdata/ssl.key\") == nil)\n\t// missing perm/cert file\n\tutils.AssertEqual(t, false, app.ListenTLS(\":0\", \"\", \"./.github/testdata/ssl.key\") == nil)\n\n\tgo func() {\n\t\ttime.Sleep(1000 * time.Millisecond)\n\t\tutils.AssertEqual(t, nil, app.Shutdown())\n\t}()\n\n\tutils.AssertEqual(t, nil, app.ListenTLS(\":0\", \"./.github/testdata/ssl.pem\", \"./.github/testdata/ssl.key\"))\n}", "func (b *Baa) RunTLS(addr, certfile, keyfile string) {\n\tb.run(b.Server(addr), certfile, keyfile)\n}", "func ListenAndServe(serverSource string) error {\n\tlis, err := net.Listen(\"tcp\", serverSource)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to listen: %v\", err)\n\t}\n\n\tvar s *grpc.Server\n\tif env == \"prod\" {\n\t\t// Create the TLS credentials\n\t\tcred, err := credentials.NewServerTLSFromFile(crt, key)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not load TLS keys: %v\", err)\n\t\t}\n\n\t\t// Creates a new gRPC server\n\t\ts = grpc.NewServer(grpc.Creds(cred))\n\t} else {\n\t\t// Creates a new gRPC server\n\t\ts = grpc.NewServer()\n\t}\n\n\tstorage := database.Storage\n\tapi.RegisterFailMailServer(s, &server{storage: storage})\n\tfmt.Printf(\"Start listening on %s. Env: %s \\n\", serverSource, env)\n\treturn s.Serve(lis)\n}", "func (s *server) listenAndServe() error {\n\tvar ln net.Listener\n\tvar err error\n\n\tif s.tlsCfg == nil {\n\t\ts.logger.Sugar().Debugf(\"tcp listener on address %s\", s.addr)\n\t\tln, err = net.Listen(\"tcp\", s.addr)\n\t} else {\n\t\ts.logger.Sugar().Debugf(\"tcp listener on address %s with tls config %+v\", s.addr, s.tlsCfg)\n\t\tln, err = tls.Listen(\"tcp\", s.addr, s.tlsCfg)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.ln = ln\n\treturn s.serve()\n}" ]
[ "0.8036622", "0.7998496", "0.788779", "0.78385574", "0.7740059", "0.7738769", "0.7738769", "0.77262855", "0.7687477", "0.76723385", "0.7624732", "0.7623218", "0.76037407", "0.7594799", "0.754912", "0.75170785", "0.74853915", "0.74719095", "0.7444751", "0.74214697", "0.7414217", "0.74111354", "0.73683465", "0.73477995", "0.7339663", "0.72965264", "0.72192675", "0.72110885", "0.7131375", "0.70253205", "0.7023705", "0.6965003", "0.6953435", "0.6913052", "0.68934196", "0.6788097", "0.6776826", "0.67639273", "0.67614746", "0.6734583", "0.67142725", "0.67076504", "0.66836965", "0.6661866", "0.66390896", "0.6617839", "0.65811527", "0.654805", "0.65130275", "0.6470226", "0.6447478", "0.64437914", "0.6416723", "0.63845706", "0.6356241", "0.6348391", "0.6345496", "0.6340862", "0.6331002", "0.6287438", "0.6267735", "0.6243657", "0.62270784", "0.6188894", "0.6156324", "0.6149766", "0.61385274", "0.61278254", "0.61199427", "0.6078969", "0.6078106", "0.6070208", "0.6066267", "0.60612226", "0.60362417", "0.59995866", "0.59913653", "0.5969212", "0.5946425", "0.594475", "0.5943976", "0.59384036", "0.5930845", "0.5928178", "0.59250593", "0.59177554", "0.59099436", "0.5880425", "0.58738446", "0.58564734", "0.5842924", "0.583463", "0.58237493", "0.58221155", "0.58093303", "0.57703644", "0.5752389", "0.5746969", "0.5744837", "0.5742906" ]
0.7363671
23
Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.Handler to reply to them. Serve returns a nil error after Close or Shutdown method called.
func (srv *TCPServer) Serve(l net.Listener) (err error) { srv.l = l srv.conns = make(map[net.Conn]connContext) srv.closeCh = make(chan struct{}, 1) defer func() { srv.l.Close() }() for { var conn net.Conn conn, err = l.Accept() if err != nil { select { case <-srv.closeCh: err = nil return default: } if ne, ok := err.(net.Error); ok && ne.Temporary() { time.Sleep(5 * time.Millisecond) continue } return } go srv.serve(conn) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (srv *Server) Serve(l net.Listener) error {\n\tl = net_.OnceCloseListener(l)\n\tdefer l.Close()\n\n\tif srv.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\n\tif !srv.trackListener(&l, true) {\n\t\treturn ErrServerClosed\n\t}\n\tdefer srv.trackListener(&l, false)\n\n\tvar tempDelay time.Duration // how long to sleep on accept failure\n\tctx := context.WithValue(srv.Context(), ServerContextKey, srv)\n\n\tfor {\n\t\trw, err := l.Accept()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ErrServerClosed\n\t\t\tcase <-srv.getDoneChan():\n\t\t\t\treturn ErrServerClosed\n\t\t\tdefault:\n\t\t\t}\n\t\t\tif !srv.handleErr(err) {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif ne, ok := err.(net.Error); ok && ne.Temporary() {\n\t\t\t\tif tempDelay == 0 {\n\t\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\ttempDelay *= 2\n\t\t\t\t}\n\t\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\t\ttempDelay = max\n\t\t\t\t}\n\t\t\t\tsrv.logf(\"cmux: Accept error: %v; retrying in %v\", err, tempDelay)\n\t\t\t\ttime.Sleep(tempDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\ttempDelay = 0\n\n\t\tc := srv.newConn(rw)\n\t\tc.setState(c.muc, ConnStateNew) // before Serve can return\n\n\t\tgo c.serve(ctx)\n\n\t}\n}", "func (srv *server) Serve() {\n\tfor {\n\t\tcli, err := srv.l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Closing server:\", err)\n\t\t\tbreak // on srv.l.Close\n\t\t}\n\t\tgo srv.handle(newConn(cli))\n\t}\n}", "func (srv *Server) Serve(l net.Listener) error {\n\tdefer l.Close()\n\tsrv.MonitorChans = []chan string{}\n\n\tfor {\n\t\trw, err := l.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo srv.ServeClient(rw)\n\t}\n}", "func (srv *Server) Serve(l net.Listener) error {\n\tif fn := testHookServerServe; fn != nil {\n\t\tfn(srv, l) // call hook with unwrapped listener\n\t}\n\n\torigListener := l\n\tl = &onceCloseListener{Listener: l}\n\tdefer l.Close()\n\n\tif err := srv.setupHTTP2_Serve(); err != nil {\n\t\treturn err\n\t}\n\n\tif !srv.trackListener(&l, true) {\n\t\treturn ErrServerClosed\n\t}\n\tdefer srv.trackListener(&l, false)\n\n\tbaseCtx := context.Background()\n\tif srv.BaseContext != nil {\n\t\tbaseCtx = srv.BaseContext(origListener)\n\t\tif baseCtx == nil {\n\t\t\tpanic(\"BaseContext returned a nil context\")\n\t\t}\n\t}\n\n\tvar tempDelay time.Duration // how long to sleep on accept failure\n\n\tctx := context.WithValue(baseCtx, ServerContextKey, srv)\n\tfor {\n\t\trw, err := l.Accept()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-srv.getDoneChan():\n\t\t\t\treturn ErrServerClosed\n\t\t\tdefault:\n\t\t\t}\n\t\t\tif ne, ok := err.(net.Error); ok && ne.Temporary() {\n\t\t\t\tif tempDelay == 0 {\n\t\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\ttempDelay *= 2\n\t\t\t\t}\n\t\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\t\ttempDelay = max\n\t\t\t\t}\n\t\t\t\tsrv.logf(\"http: Accept error: %v; retrying in %v\", err, tempDelay)\n\t\t\t\ttime.Sleep(tempDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tconnCtx := ctx\n\t\tif cc := srv.ConnContext; cc != nil {\n\t\t\tconnCtx = cc(connCtx, rw)\n\t\t\tif connCtx == nil {\n\t\t\t\tpanic(\"ConnContext returned nil\")\n\t\t\t}\n\t\t}\n\t\ttempDelay = 0\n\t\tc := srv.newConn(rw)\n\t\tc.setState(c.rwc, StateNew, runHooks) // before Serve can return\n\t\tgo c.serve(connCtx)\n\t}\n}", "func (s *Server) Serve(l net.Listener) error {\n\ts.locker.Lock()\n\ts.listeners = append(s.listeners, l)\n\ts.locker.Unlock()\n\n\tvar tempDelay time.Duration // how long to sleep on accept failure\n\n\tfor {\n\t\tc, err := l.Accept()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-s.done:\n\t\t\t\t// we called Close()\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t}\n\t\t\tif ne, ok := err.(net.Error); ok && ne.Temporary() {\n\t\t\t\tif tempDelay == 0 {\n\t\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\ttempDelay *= 2\n\t\t\t\t}\n\t\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\t\ttempDelay = max\n\t\t\t\t}\n\t\t\t\ts.ErrorLog.Printf(\"accept error: %s; retrying in %s\", err, tempDelay)\n\t\t\t\ttime.Sleep(tempDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\ts.wg.Add(1)\n\t\tgo func() {\n\t\t\tdefer s.wg.Done()\n\n\t\t\terr := s.handleConn(newConn(c, s))\n\t\t\tif err != nil {\n\t\t\t\ts.ErrorLog.Printf(\"handler error: %s\", err)\n\t\t\t}\n\t\t}()\n\t}\n}", "func Serve(l net.Listener) error {\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo handleConn(conn)\n\t}\n}", "func (s *Server) Serve(l net.Listener) error {\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo func() {\n\t\t\terr2 := s.ServeConn(conn)\n\t\t\tif err2 != nil {\n\t\t\t\tlog.Println(\"s.ServeConn failed:\", err2)\n\t\t\t}\n\t\t}()\n\t}\n}", "func (s *Server) Serve(l net.Listener) error {\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo s.ServeConn(conn)\n\t}\n}", "func (m *cMux) Serve(l net.Listener) error {\n\tif m.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\n\tl = net_.OnceCloseListener(l)\n\tdefer l.Close()\n\n\tif !m.trackListener(&l, true) {\n\t\treturn ErrServerClosed\n\t}\n\tdefer m.trackListener(&l, false)\n\n\tvar tempDelay time.Duration // how long to sleep on accept failure\n\tctx := context.WithValue(m.Context(), ServerContextKey, m)\n\n\tfor {\n\t\trw, err := l.Accept()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ErrServerClosed\n\t\t\tdefault:\n\t\t\t}\n\t\t\tif !m.handleErr(err) {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif ne, ok := err.(net.Error); ok && ne.Temporary() {\n\t\t\t\tif tempDelay == 0 {\n\t\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\ttempDelay *= 2\n\t\t\t\t}\n\t\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\t\ttempDelay = max\n\t\t\t\t}\n\t\t\t\tm.logf(\"cmux: Accept error: %v; retrying in %v\", err, tempDelay)\n\t\t\t\ttime.Sleep(tempDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\ttempDelay = 0\n\n\t\tc := m.newConn(rw)\n\t\tc.setState(c.muc, ConnStateNew) // before Serve can return\n\n\t\tgo c.serve(ctx)\n\n\t}\n}", "func (s *Server) Serve(l net.Listener) error {\n\tdefer l.Close()\n\tfor {\n\t\trw, err := l.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo s.ServeClient(rw)\n\t}\n}", "func (s *Server) Serve(l net.Listener) error {\n\tconst (\n\t\tminBackoffDelay = 10 * time.Millisecond\n\t\tmaxBackoffDelay = 1000 * time.Millisecond\n\t)\n\n\tdefer l.Close()\n\tdefer s.untrackListener(l)\n\n\ts.trackListener(l)\n\n\tconfig := serverConfig{\n\t\tidleTimeout: s.IdleTimeout,\n\t\treadTimeout: s.ReadTimeout,\n\t\twriteTimeout: s.WriteTimeout,\n\t\tretryable: s.EnableRetry,\n\t}\n\n\tif config.idleTimeout == 0 {\n\t\tconfig.idleTimeout = config.readTimeout\n\t}\n\n\tattempt := 0\n\n\tfor {\n\t\tconn, err := l.Accept()\n\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\tcase <-s.context.Done():\n\t\t\t\treturn ErrServerClosed\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase isTimeout(err):\n\t\t\t\tcontinue\n\t\t\tcase isTemporary(err):\n\t\t\t\tattempt++\n\n\t\t\t\tselect {\n\t\t\t\tcase <-time.After(backoff(attempt, minBackoffDelay, maxBackoffDelay)):\n\t\t\t\tcase <-s.context.Done():\n\t\t\t\t\treturn ErrServerClosed\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tattempt = 0\n\t\tc := NewServerConn(conn)\n\t\ts.trackConnection(c)\n\t\tgo s.serveConnection(s.context, c, config)\n\t}\n}", "func (srv *Server) Serve(l net.Listener) error", "func (s *Server) Serve(l net.Listener) (err error) {\n\tdefer l.Close()\n\tfor {\n\t\tvar conn net.Conn\n\t\tconn, err = l.Accept()\n\t\tif err != nil {\n\t\t\tif netErr, ok := err.(net.Error); ok && netErr.Temporary() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tsession := s.newSession(conn)\n\t\tgo session.serve()\n\t}\n\treturn\n}", "func (s *Server) Serve(ctx context.Context, ln net.Listener) error {\n\tdefer ln.Close()\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tgo s.serveStream(ctx, conn)\n\t}\n}", "func (me *Server) Serve(l net.Listener) error {\n\tdefer l.Close()\n\n\td := 5 * time.Millisecond // How long to sleep on accept failure\n\tm := 1 * time.Second\n\n\tfor {\n\t\tc, err := l.Accept()\n\t\tif err != nil {\n\t\t\tif ne, ok := err.(net.Error); ok && ne.Temporary() {\n\t\t\t\tme.logger.Warnf(\"Accept error: %v; retrying in %dms\", err, d)\n\n\t\t\t\ttime.Sleep(d)\n\n\t\t\t\tif d *= 2; d > m {\n\t\t\t\t\td = m\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\n\t\t// TODO: whitelist & blacklist\n\n\t\tnc := new(NetConnection).Init(c, me, me.logger, me.factory)\n\t\tgo nc.serve()\n\t}\n}", "func (d *Dispatcher) Serve(l net.Listener) {\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlogrus.Fatalf(\"Accept error: %v\", err)\n\t\t}\n\t\tgo d.handleConn(conn)\n\t}\n}", "func (s *Service) Serve(listener *net.TCPListener) {\n\tdefer s.waitGroup.Done()\n\tfor {\n\t\tselect {\n\t\tcase <-s.ch:\n\t\t\tlog.Println(\"stopping listening on\", listener.Addr())\n\t\t\tlistener.Close()\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tlistener.SetDeadline(time.Now().Add(1e9))\n\t\tconn, err := listener.AcceptTCP()\n\n\t\tif nil != err {\n\t\t\tif opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tlog.Println(conn.RemoteAddr(), \"connected\")\n\t\ts.waitGroup.Add(1)\n\n\t\tgo s.serve(conn)\n\t}\n}", "func Serve(svc Service, l net.Listener) (*Server, error) {\n\ts := &Server{\n\t\tl: l,\n\t\tshuttingDown: make(chan struct{})}\n\tsvc = svc.Filter(func(req Request, svc Service) Response {\n\t\treq.server = s\n\t\treturn svc(req)\n\t})\n\ts.srv = &http.Server{\n\t\tHandler: HttpHandler(svc),\n\t\tMaxHeaderBytes: http.DefaultMaxHeaderBytes}\n\tgo func() {\n\t\terr := s.srv.Serve(l)\n\t\tif err != nil && err != http.ErrServerClosed {\n\t\t\tslog.Error(nil, \"HTTP server error: %v\", err)\n\t\t\t// Stopping with an already-closed context means we go immediately to \"forceful\" mode\n\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\tcancel()\n\t\t\ts.Stop(ctx)\n\t\t}\n\t}()\n\treturn s, nil\n}", "func (m *servingService) Serve(ln net.Listener, fn func(net.Conn)) {\n\tvar tempDelay time.Duration // how long to sleep on accept failure\n\n\tfor {\n\t\tc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tif ne, ok := err.(net.Error); ok && ne.Temporary() {\n\t\t\t\tif tempDelay == 0 {\n\t\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\ttempDelay *= 2\n\t\t\t\t}\n\n\t\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\t\ttempDelay = max\n\t\t\t\t}\n\n\t\t\t\ttime.Sleep(tempDelay)\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\ttempDelay = 0\n\n\t\tm.connections.Store(c, struct{}{})\n\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\tc.Close()\n\t\t\t\tm.connections.Delete(c)\n\t\t\t}()\n\t\t\tfn(c)\n\t\t}()\n\t}\n}", "func (s *Server) Serve(l net.Listener) error {\n\ts.m.Lock()\n\n\ts.server[tcp] = &dns.Server{Listener: l,\n\t\tNet: \"tcp\",\n\t\tTsigSecret: s.tsigSecret,\n\t\tMaxTCPQueries: tcpMaxQueries,\n\t\tReadTimeout: s.readTimeout,\n\t\tWriteTimeout: s.writeTimeout,\n\t\tIdleTimeout: func() time.Duration {\n\t\t\treturn s.idleTimeout\n\t\t},\n\t\tHandler: dns.HandlerFunc(func(w dns.ResponseWriter, r *dns.Msg) {\n\t\t\tctx := context.WithValue(context.Background(), Key{}, s)\n\t\t\tctx = context.WithValue(ctx, LoopKey{}, 0)\n\t\t\ts.ServeDNS(ctx, w, r)\n\t\t})}\n\n\ts.m.Unlock()\n\n\treturn s.server[tcp].ActivateAndServe()\n}", "func (p *Proxy) Serve() error {\n\tfor {\n\t\tconn, err := p.listener.Accept()\n\t\tstart := time.Now()\n\n\t\tif err != nil {\n\t\t\tif ne, ok := err.(net.Error); ok {\n\t\t\t\tif ne.Temporary() {\n\t\t\t\t\tp.logger.Warn(\"Failed to accept\", zap.Error(err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\t\tselect {\n\t\t\t\tcase <-p.done:\n\t\t\t\t\treturn ErrServerClosed\n\t\t\t\tdefault:\n\t\t\t\t\t// fallthrough\n\t\t\t\t}\n\t\t\t}\n\t\t\tp.logger.Error(\"Failed to accept\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\n\t\tp.wg.Add(1)\n\t\tgo func(c net.Conn) {\n\t\t\tdefer p.wg.Done()\n\t\t\tp.handleConn(c, start)\n\t\t}(conn)\n\t}\n}", "func (s *Server) Serve(l net.Listener) error {\n\tdefer l.Close()\n\n\tvar tempDelay time.Duration // how long to sleep on accept failure\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-s.closing():\n\t\t\t\treturn ErrServerClosed\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tif netErr, ok := err.(net.Error); ok && netErr.Temporary() {\n\t\t\t\tif tempDelay == 0 {\n\t\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\ttempDelay *= 2\n\t\t\t\t}\n\t\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\t\ttempDelay = max\n\t\t\t\t}\n\n\t\t\t\ttime.Sleep(tempDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\ttempDelay = 0\n\t\tgo s.OnAccept(conn)\n\t}\n}", "func (server *Server) Accept(lis net.Listener) {\n\tfor {\n\t\tconn, err := lis.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"rpc server: accept error:\", err)\n\t\t\treturn\n\t\t}\n\t\t// 每个connection使用一个goroutine来handle\n\t\tgo server.ServeConn(conn)\n\t}\n}", "func Serve(l net.Listener, handler http.Handler) (err error) {\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\n\ts := &http.Server{Handler: handler}\n\n\tvar lis net.Listener\n\n\tswitch l.(type) {\n\tcase *net.TCPListener:\n\t\tlis = kmsnet.NewTCPNoShutdown(l.(*net.TCPListener))\n\tcase *net.UnixListener:\n\t\tlis = kmsnet.NewUnixNoShutdown(l.(*net.UnixListener))\n\tdefault:\n\t\tpanic(\"unsupported listener type\")\n\t}\n\n\tserver := &serverConnState{\n\t\tServer: s,\n\t\tl: lis,\n\t\tidleConns: make(map[net.Conn]struct{}),\n\t\tactive: make(chan net.Conn),\n\t\tidle: make(chan net.Conn),\n\t\tclosed: make(chan net.Conn),\n\t\tshutdown: make(chan struct{}),\n\t}\n\n\tserver.handleConnState()\n\n\terr = server.Serve(server.l)\n\n\t// wait for process shutdown to complete or timeout.\n\t<-kms.ShutdownComplete()\n\n\treturn err\n}", "func (l *WebListener) Serve() error {\n\tfor {\n\t\tconn, err := l.cfg.Listener.Accept()\n\t\tif err != nil {\n\t\t\tif utils.IsUseOfClosedNetworkError(err) {\n\t\t\t\t<-l.context.Done()\n\t\t\t\treturn trace.Wrap(err, \"listener is closed\")\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-l.context.Done():\n\t\t\t\treturn trace.Wrap(net.ErrClosed, \"listener is closed\")\n\t\t\tcase <-time.After(5 * time.Second):\n\t\t\t\tl.log.WithError(err).Warn(\"Backoff on accept error.\")\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\ttlsConn, ok := conn.(*tls.Conn)\n\t\tif !ok {\n\t\t\tl.log.Errorf(\"Expected *tls.Conn, got %T.\", conn)\n\t\t\tconn.Close()\n\t\t\tcontinue\n\t\t}\n\n\t\tgo l.detectAndForward(tlsConn)\n\t}\n}", "func Accept(lis net.Listener) { DefaultServer.Accept(lis) }", "func Accept(lis net.Listener) { DefaultServer.Accept(lis) }", "func (h *handler) Serve(ctx context.Context, _ *sync.WaitGroup) error {\n\tln, err := net.Listen(\"tcp\", h.addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo h.stop(ctx, ln)\n\n\th.registerRoutes()\n\n\treturn h.server.Serve(ln)\n}", "func (srv *Server) Serve(ln net.Listener) error {\n\tdefer ln.Close()\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tif netError, ok := err.(net.Error); ok && netError.Temporary() {\n\t\t\t\tsrv.log.Printf(\"temporary accept error %s\", err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\ts := srv.newSession(conn)\n\t\tgo s.Serve()\n\t}\n}", "func (e *Engine) Serve(ln net.Listener) error {\n\tln = &onceCloseListener{Listener: ln}\n\tdefer ln.Close()\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\te.Stat.AddConn()\n\t\tc := newConn(e, conn)\n\t\te.Log().Printf(\"Accept a connect from %s\", c.remoteAddr)\n\t\te.Log().Print(e.Stat.String())\n\t\tgo c.server()\n\t}\n\n}", "func (l *Listener) Listen() {\n\tfor {\n\t\tvar client net.Conn\n\t\tvar err error\n\t\tif client, err = util.Accept(l); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Serve the first Handler which is attached to this listener\n\t\tif len(l.HandlerConfigs) > 0 {\n\t\t\toptions := plugin_v1.HandlerOptions{\n\t\t\t\tClientConnection: client,\n\t\t\t\tHandlerConfig: l.HandlerConfigs[0],\n\t\t\t\tEventNotifier: l.EventNotifier,\n\t\t\t\tResolver: l.Resolver,\n\t\t\t\tShutdownNotifier: func(handler plugin_v1.Handler) {},\n\t\t\t}\n\n\t\t\tl.RunHandlerFunc(\"example-handler\", options)\n\t\t} else {\n\t\t\tclient.Write([]byte(\"Error - no handlers were defined!\"))\n\t\t}\n\t}\n}", "func (s *Server) Serve(ctx context.Context, handler Handler) error {\n\ts.cancelMx.Lock()\n\ts.ctx, s.cancel = context.WithCancel(ctx)\n\ts.cancelMx.Unlock()\n\n\tfor {\n\t\tconn, err := s.listener.Accept()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\n\t\t\tcase <-s.ctx.Done():\n\t\t\t\t// If parent context is not done, so\n\t\t\t\t// server context is canceled by Close.\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tgo func() {\n\t\t\t_ = s.serveConn(s.ctx, handler, conn)\n\t\t}()\n\t}\n}", "func Serve(l net.Listener, handler Handler) error {\n\tsrv := &Server{Handler: handler}\n\treturn srv.Serve(l)\n}", "func (l *tcp) Serve() error {\n\n\t// accept is a channel to signal about next incoming connection Accept()\n\t// results.\n\taccept := make(chan error, 1)\n\n\tdefer close(accept)\n\n\tfor {\n\t\t// Try to accept incoming connection inside free pool worker.\n\t\t// If there no free workers for 1ms, do not accept anything and try later.\n\t\t// This will help us to prevent many self-ddos or out of resource limit cases.\n\t\terr := l.AcceptPool.ScheduleTimeout(time.Millisecond, func() {\n\t\t\tvar cn net.Conn\n\t\t\tvar er error\n\n\t\t\tdefer func() {\n\t\t\t\taccept <- er\n\t\t\t}()\n\n\t\t\tif cn, er = l.listener.Accept(); er == nil {\n\t\t\t\tselect {\n\t\t\t\tcase <-l.quit:\n\t\t\t\t\ter = types.ErrClosed\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\n\t\t\t\tif inConn, e := l.newConn(cn, l.Metric.Bytes()); e != nil {\n\t\t\t\t\tl.log.Error(\"create connection interface\", zap.Error(e))\n\t\t\t\t} else {\n\t\t\t\t\tl.handleConnection(inConn)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\t// We do not want to accept incoming connection when goroutine pool is\n\t\t// busy. So if there are no free goroutines during 1ms we want to\n\t\t// cooldown the server and do not receive connection for some short\n\t\t// time.\n\t\tif err != nil && err != types.ErrScheduleTimeout {\n\t\t\tbreak\n\t\t} else if err == types.ErrScheduleTimeout {\n\t\t\tcontinue\n\t\t}\n\n\t\terr = <-accept\n\n\t\tif err != nil {\n\t\t\tif ne, ok := err.(net.Error); ok && ne.Temporary() {\n\t\t\t\tdelay := 5 * time.Millisecond\n\t\t\t\ttime.Sleep(delay)\n\t\t\t} else {\n\t\t\t\t// unknown error stop listener\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func Serve() error {\n\tclientConnectionCount = metrics.RegisterGauge(\"client_connection_count\")\n\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"0.0.0.0:34601\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tlistener, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogrus.Infof(\"start server listen: %s\", listener.Addr())\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"connection accept: %s\", err)\n\t\t\tcontinue\n\t\t}\n\t\tclientConnectionCount.Inc()\n\t\t// TODO(wutao): add connections management\n\n\t\t// use one goroutine per connection\n\t\tgo serveConn(conn, conn.RemoteAddr().String())\n\t}\n}", "func (s *Server) ServeListener(ln QUICEarlyListener) error {\n\tif err := s.addListener(&ln); err != nil {\n\t\treturn err\n\t}\n\tdefer s.removeListener(&ln)\n\tfor {\n\t\tconn, err := ln.Accept(context.Background())\n\t\tif err == quic.ErrServerClosed {\n\t\t\treturn http.ErrServerClosed\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo func() {\n\t\t\tif err := s.handleConn(conn); err != nil {\n\t\t\t\ts.logger.Debugf(err.Error())\n\t\t\t}\n\t\t}()\n\t}\n}", "func (s *Server) Serve(listener net.Listener) {\n\tif listener == nil || s.ctx.Err() != nil {\n\t\treturn\n\t}\n\ts.wg.Add(1)\n\tgo func() {\n\t\tdefer s.wg.Done()\n\t\t<-s.ctx.Done()\n\t\tlistener.Close()\n\t}()\n\n\ts.wg.Add(1)\n\tdefer s.wg.Done()\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-s.ctx.Done():\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t}\n\t\t\tlogError(s.logger, \"Failed to accept connection:\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tremote := formatAddress(conn.RemoteAddr())\n\t\tlogInfo(s.logger, \"ACCEPTED\", remote, connectionID(conn))\n\n\t\tif err := s.broker.KeepConnection(conn); err != nil {\n\t\t\tlogError(s.logger, \"DROPPED\", remote, err)\n\t\t}\n\t}\n}", "func (gss *Server) Serve(l net.Listener) error {\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo func() {\n\t\tif err := gss.server.Serve(l); err != nil {\n\t\t\tgss.startErr = err\n\t\t\tcancel()\n\t\t}\n\t}()\n\treturn gss.waitForInterrupt(ctx)\n}", "func (sv *Server) Serve() {\n\tlog.Println(\"Server : Serve : Started\")\n\tdefer log.Println(\"Server : Serve : Completed\")\n\n\tfor {\n\t\t// Check if we should stop accepting connections and shutdown\n\t\tselect {\n\t\tcase <-sv.quit:\n\t\t\tlog.Println(\"Server : Serve : Shutting Down\")\n\t\t\tsv.Listener.Close()\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\t// Accept a new connection or timeout and loop again\n\t\tsv.Listener.SetDeadline(time.Now().Add(time.Second))\n\t\tconn, err := sv.Listener.AcceptTCP()\n\t\tif err != nil {\n\t\t\t// Loop if deadline expired\n\t\t\tif opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tlog.Println(\"Server: New connection from:\", conn.RemoteAddr())\n\t\t// Hand the connection off to PeerManager\n\t\tgo func() { sv.peerChans.conns <- conn }()\n\t}\n}", "func (s *Server) Serve(lis net.Listener) {\n\thttpsrv := &http.Server{\n\t\tTLSConfig: s.opts.creds.Config,\n\t}\n\thttp.HandleFunc(\"/\", s.wshandler)\n\tgo httpsrv.ServeTLS(lis, \"\", \"\")\n\tdefer httpsrv.Close()\n\n\ts.httpsrv = httpsrv\n\n\t<-s.done.Done()\n}", "func Serve(domain string, listener net.Listener, handler Handler) error {\n\tfor {\n\t\tvar c io.ReadWriteCloser\n\t\tc, err := listener.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tconn := &conn{\n\t\t\tdomain: domain,\n\t\t\tconn: c,\n\t\t\treader: newBufferedReader(c, MaxLineLength),\n\t\t\thandler: handler,\n\t\t}\n\t\tgo conn.handle()\n\t}\n}", "func (s *Server) Serve(ctx context.Context, l transport.AuthenticatedListener) {\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\ts.log.Debug(\"context done\")\n\t\tif err := l.Close(); err != nil {\n\t\t\ts.log.WithError(err).Error(\"cannot close listener\")\n\t\t}\n\t}()\n\tconns := make(chan *transport.AuthConn)\n\tgo func() {\n\t\tfor {\n\t\t\tconn, err := l.Accept(ctx)\n\t\t\tif err != nil {\n\t\t\t\tif ctx.Done() != nil {\n\t\t\t\t\ts.log.Debug(\"stop accepting after context is done\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ts.log.WithError(err).Error(\"accept error\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconns <- conn\n\t\t}\n\t}()\n\tfor conn := range conns {\n\t\tgo s.serveConn(conn)\n\t}\n}", "func Serve(l net.Listener) error {\n\tfor {\n\t\tc, err := l.Accept()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot accept connection: %s\", err)\n\t\t}\n\t\tif err := echoConn(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (server *Server) Accept(lis net.Listener) {\n\tfor {\n\t\tconn, err := lis.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"rpc server: accept error:\", err)\n\t\t\treturn\n\t\t}\n\t\tgo server.ServerCon(conn)\n\t}\n}", "func Serve(l net.Listener, handler Handler) error {\n\treturn (&Server{Handler: handler}).Serve(l)\n}", "func (s *Server) Serve(l net.Listener) error {\n\treturn s.server.Serve(l)\n}", "func Serve(ln net.Listener,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n) error {\n\ts := newServer()\n\ts.mu.Lock()\n\ts.net = ln.Addr().Network()\n\ts.laddr = ln.Addr().String()\n\ts.ln = ln\n\ts.handler = handler\n\ts.accept = accept\n\ts.closed = closed\n\ts.mu.Unlock()\n\treturn serve(s)\n}", "func (r *Ricochet) ServeListener(service RicochetService, ln net.Listener) {\n\tgo r.ProcessMessages(service)\n\tservice.OnReady()\n\tfor {\n\t\t// accept connection on port\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tgo r.processNewConnection(conn, service)\n\t}\n}", "func (srv *Server) Serve(l net.Listener) error {\n\treturn nil\n}", "func (s *Server) Serve(l net.Listener, gateway Gateway) error {\n\tdefer l.Close()\n\ts.listener = l\n\n\tfor {\n\t\ttcpConn := l.(*net.TCPListener)\n\t\ttcpConn.SetDeadline(time.Now().Add(300 * time.Millisecond))\n\n\t\tc, err := l.Accept()\n\t\t//Check for the channel being closed\n\t\tselect {\n\t\tcase <-s.quit:\n\t\t\tfmt.Println(\"finishing task\")\n\t\t\tfmt.Println(\"task done\")\n\t\t\ts.quit <- true\n\t\t\treturn nil\n\t\tdefault:\n\t\t\t//If the channel is still open, continue as normal\n\t\t}\n\t\tif err != nil {\n\t\t\tif nerr, ok := err.(net.Error); ok && nerr.Timeout() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t}\n\n\t\tgo s.handle(c, gateway)\n\n\t}\n}", "func (s *Server) Serve(listener net.Listener) error {\n\t// When we return, wait for all pending goroutines to finish.\n\tdefer s.wg.Wait()\n\n\tsignalCh, cancel := s.notifyOnSignals()\n\tdefer cancel()\n\n\terrCh := s.serve(listener)\n\tselect {\n\tcase err := <-errCh:\n\t\t// The server has failed and reported an error.\n\t\treturn err\n\tcase <-signalCh:\n\t\t// We have received an interrupt. Signal the shutdown process.\n\t\treturn s.shutdown(signalCh)\n\t}\n}", "func Accept(lis net.Listener) {\n\tDefaultServer.Accept(lis)\n}", "func (s *Server) Serve(ln net.Listener) error {\n\ts.ln = ln\n\tdefer s.ln.Close()\n\n\t// prepare built'n ack response server-only handler\n\ts.Handle(\"panda_ack\", func(req *Request) {\n\t\t// the ack will return the connection id which will be setted on the client side in order to be synchronized with the server's\n\t\t// this id is not changed\n\t\t// after this method the client can be served(this is done on client.go)\n\t\treq.Result(int(req.Conn.ID()))\n\t})\n\n\tfor {\n\t\tnetConn, err := s.ln.Accept()\n\t\tif err != nil {\n\t\t\ts.engine.logf(\"Connection error: %s\\n\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo func() {\n\t\t\tc := s.engine.acquireConn(netConn)\n\t\t\tgo s.emitConnected(c)\n\t\t\tc.serve() // serve blocks until connection stop reading\n\t\t\ts.engine.releaseConn(c)\n\t\t}()\n\t}\n}", "func (a *AgentServer) Serve() error {\n\tif a.listener == nil {\n\t\treturn trace.BadParameter(\"Serve needs a Listen call first\")\n\t}\n\tvar tempDelay time.Duration // how long to sleep on accept failure\n\tfor {\n\t\tconn, err := a.listener.Accept()\n\t\tif err != nil {\n\t\t\tneterr, ok := err.(net.Error)\n\t\t\tif !ok {\n\t\t\t\treturn trace.Wrap(err, \"unknown error\")\n\t\t\t}\n\t\t\tif utils.IsUseOfClosedNetworkError(neterr) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif !neterr.Timeout() {\n\t\t\t\tlog.WithError(err).Error(\"Got non-timeout error.\")\n\t\t\t\treturn trace.Wrap(err)\n\t\t\t}\n\t\t\tif tempDelay == 0 {\n\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t} else {\n\t\t\t\ttempDelay *= 2\n\t\t\t}\n\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\ttempDelay = max\n\t\t\t}\n\t\t\tlog.WithError(err).Errorf(\"Got timeout error (will sleep %v).\", tempDelay)\n\t\t\ttime.Sleep(tempDelay)\n\t\t\tcontinue\n\t\t}\n\t\ttempDelay = 0\n\n\t\t// get an agent instance for serving this conn\n\t\tinstance, err := a.getAgent()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Failed to get agent.\")\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\n\t\t// serve agent protocol against conn in a\n\t\t// separate goroutine.\n\t\tgo func() {\n\t\t\tdefer instance.Close()\n\t\t\tif err := agent.ServeAgent(instance, conn); err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n}", "func (s *Server) Serve(ln net.Listener) error {\n\ts.Listener = ln\n\ts.chStop = make(chan error)\n\tlogInfo(\"%v Running On: \\\"%v\\\"\", s.Handler.LogTag(), ln.Addr())\n\tdefer logInfo(\"%v Stopped\", s.Handler.LogTag())\n\treturn s.runLoop()\n}", "func (s *Service) serve() {\n\tfor {\n\t\t// Wait for next connection.\n\t\tconn, err := s.ln.Accept()\n\t\tif opErr, ok := err.(*net.OpError); ok && !opErr.Temporary() {\n\t\t\ts.Logger.Info(\"OpenTSDB TCP listener closed\")\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\ts.Logger.Info(\"Error accepting OpenTSDB\", zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle connection in separate goroutine.\n\t\tgo s.handleConn(conn)\n\t}\n}", "func Serve(eventHandler EventHandler, addr ...string) error {\n\tvar lns []*listener\n\tdefer func() {\n\t\tfor _, ln := range lns {\n\t\t\tln.close()\n\t\t}\n\t}()\n\tvar stdlib bool\n\tfor _, addr := range addr {\n\t\tvar ln listener\n\t\tvar stdlibt bool\n\t\tln.network, ln.addr, ln.reuseport, stdlibt = parseAddr(addr)\n\t\tif stdlibt {\n\t\t\tstdlib = true\n\t\t}\n\t\tif ln.network == \"unix\" {\n\t\t\tos.RemoveAll(ln.addr)\t//remove existed socket file for sockets' communication\n\t\t}\n\t\tvar err error\n\t\tif ln.network == \"udp\" {\n\t\t\tif ln.reuseport {\n\t\t\t\t//ln.pconn, err = reuse\n\t\t\t} else {\n\t\t\t\tln.pconn, err = net.ListenPacket(ln.network, ln.addr)\n\t\t\t}\n\t\t} else {\n\t\t\tif ln.reuseport {\n\t\t\t\t//operation for reuseport\n\t\t\t} else {\n\t\t\t\tln.ln, err = net.Listen(ln.network, ln.addr)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif ln.pconn != nil {\n\t\t\tln.lnaddr = ln.pconn.LocalAddr()\n\t\t} else {\n\t\t\tln.lnaddr = ln.ln.Addr()\n\t\t}\n\t\tif !stdlib {\n\t\t\tif err := ln.system(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tlns = append(lns, &ln)\n\t}\n\treturn serve(eventHandler, lns)\n}", "func (s *Server) serve(lis net.Listener) {\n\ts.wg.Add(1)\n\tgo func() {\n\t\tlog.Infof(\"Listening on %s\", lis.Addr())\n\t\terr := s.httpServer.Serve(lis)\n\t\tlog.Tracef(\"Finished serving RPC: %v\", err)\n\t\ts.wg.Done()\n\t}()\n}", "func (s *Server) Serve(ln net.Listener) error {\n\ts.mu.Lock()\n\ts.ln = ln\n\ts.net = ln.Addr().Network()\n\ts.laddr = ln.Addr().String()\n\ts.mu.Unlock()\n\treturn serve(s)\n}", "func (listener *Listener) Serve() <-chan error {\n\terrChan := make(chan error)\n\tgo func() {\n\t\tlistener.logger.Infow(\"serving\")\n\t\terr := listener.Server.Serve(listener.Listener)\n\t\terrChan <- err\n\t\tclose(errChan)\n\t}()\n\treturn errChan\n}", "func (s *Server) Serve() (err error) {\n\ts.serverListener, err = net.Listen(\"tcp\", fmt.Sprint(\":\", s.ServerPort))\n\tif err != nil {\n\t\ts.log(err)\n\t\treturn err\n\t}\n\ts.clientListener, err = net.Listen(\"tcp\", fmt.Sprint(\":\", s.ClientPort))\n\tif err != nil {\n\t\ts.log(err)\n\t\treturn err\n\t}\n\n\tgo s.handleConn(s.serverListener)\n\tgo s.handleConn(s.clientListener)\n\n\treturn nil\n}", "func (srv *Server) Serve(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsrv.ln = ln\n\tdefer srv.Close()\n\thandler := http.NewServeMux()\n\thandler.Handle(\"/\", srv)\n\thttp.Serve(ln, handler)\n\treturn nil\n}", "func Serve(ctx context.Context, serviceName string, options ...ServerOption) error {\n\tvar err error\n\n\t// Setup the server options\n\tserverOptions := &serverOptions{\n\t\tserviceName: serviceName,\n\t\tlog: log.WithField(\"service\", serviceName),\n\t}\n\n\toptions = append([]ServerOption{\n\t\tWithServerConfig(ServerConfig{\n\t\t\tBind: \"0.0.0.0\",\n\t\t\tListen: 5000,\n\t\t\tTLS: TLSConfig{},\n\t\t}),\n\t\tWithHealthCheck(nil),\n\t\tWithPrometheusMetrics(),\n\t}, options...)\n\n\t// Process all server options (which may override any of the above)\n\tfor _, option := range options {\n\t\terr = option.apply(ctx, serverOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\thandlers := &handlerHeap{}\n\theap.Init(handlers)\n\n\tfor _, option := range options {\n\t\terr = option.addHandler(ctx, serverOptions, handlers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Create the HTTP server\n\tmux := http.NewServeMux()\n\n\tfor handlers.Len() > 0 {\n\t\tpair := heap.Pop(handlers).(*handlerPair)\n\t\tserverOptions.log.WithField(\"endpoint\", pair.pattern).Info(\"adding handler\")\n\t\tmux.Handle(pair.pattern, pair.handler)\n\t}\n\n\tw := log.Writer()\n\tdefer w.Close()\n\n\t// Start listening\n\tserverOptions.log.Info(\"listening\")\n\tln, err := net.Listen(\"tcp\", serverOptions.addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Serve requests\n\tif serverOptions.config.GetTLS().GetEnabled() {\n\t\tserverOptions.log.Trace(\"loading server tls certs\")\n\t\tconfig, err := NewServerTLSConfig(serverOptions.config.GetTLS(), serverOptions.vault)\n\t\tif err != nil {\n\t\t\tln.Close()\n\n\t\t\treturn err\n\t\t}\n\n\t\tln = tls.NewListener(ln, config)\n\t}\n\n\tdefer ln.Close()\n\n\tserverOptions.log.Info(\"serving\")\n\tsrv := &http.Server{\n\t\tAddr: serverOptions.addr,\n\t\tHandler: mux,\n\t\tErrorLog: syslog.New(w, \"[http]\", 0),\n\t}\n\n\treturn srv.Serve(ln)\n}", "func (s *Server) listen(listener net.Listener) {\n\tfor {\n\t\t// Accept a connection\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tif s.shutdown {\n\t\t\t\treturn\n\t\t\t}\n\t\t\ts.logger.Printf(\"[ERR] consul.rpc: failed to accept RPC conn: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo s.handleConn(conn, false)\n\t\tmetrics.IncrCounter([]string{\"rpc\", \"accept_conn\"}, 1)\n\t}\n}", "func (s *daemonServer) Serve(l net.Listener) error {\n\treturn s.grpcServer.Serve(l)\n}", "func (s *Service) serve() {\n\tdefer s.wg.Done()\n\terr := s.server.Serve(s.ln)\n\t// The listener was closed so exit\n\t// See https://github.com/golang/go/issues/4373\n\tif !strings.Contains(err.Error(), \"closed\") {\n\t\ts.err <- fmt.Errorf(\"listener failed: addr=%s, err=%s\", s.Addr(), err)\n\t} else {\n\t\ts.err <- nil\n\t}\n}", "func (s *Server) ListenAndServe(h Handler) (err error) {\n\t// Listen given port.\n\ts.listener, err = net.Listen(\"tcp\", s.addr)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\t_ = s.listener.Close()\n\t}()\n\n\ts.Log(fmt.Sprintf(\"waiting for requests on %s\", s.addr))\n\n\t// Waiting for new connections.\n\tfor {\n\t\tif s.stop {\n\t\t\tbreak\n\t\t}\n\n\t\t// Accept new connection.\n\t\tconnRaw, err := s.listener.Accept()\n\t\tif err != nil {\n\t\t\ts.Log(err)\n\t\t\tcontinue\n\t\t}\n\t\ts.Log(fmt.Sprintf(\"connection accepted from %s\", connRaw.RemoteAddr()))\n\t\tconn := NewConn(&connRaw, s.idleTimeout, s.bytesLimit)\n\t\ts.addConn(conn)\n\n\t\t// Process each connection concurrently.\n\t\tgo func(conn *Conn) {\n\t\t\tdefer func(conn *Conn) {\n\t\t\t\ts.closeConn(conn)\n\t\t\t\ts.Log(\"connection closed\")\n\t\t\t}(conn)\n\n\t\t\tr := bufio.NewReader(conn)\n\t\t\tw := bufio.NewWriter(conn)\n\t\t\tcbuf := make(chan []byte)\n\t\t\ttimeout := time.After(s.idleTimeout)\n\t\t\tfor {\n\t\t\t\t// Waiting for reading from the connection.\n\t\t\t\tgo func(cbuf chan []byte, r *bufio.Reader) {\n\t\t\t\t\tbuf := make([]byte, BufSize)\n\t\t\t\t\t_, err := r.Read(buf)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\ts.Log(err)\n\t\t\t\t\t}\n\t\t\t\t\tbuf = bytes.Trim(buf, \"\\x00\")\n\t\t\t\t\tcbuf <- buf\n\t\t\t\t}(cbuf, r)\n\n\t\t\t\tselect {\n\t\t\t\tcase <-timeout:\n\t\t\t\t\t// Oops, we caught a timeout.\n\t\t\t\t\terr = io.EOF\n\t\t\t\t\treturn\n\t\t\t\tcase buf := <-cbuf:\n\t\t\t\t\t// Red buffer isn't empty, process the data.\n\t\t\t\t\tout, err := h.Handle(buf)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\ts.Log(err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// Write response to connection.\n\t\t\t\t\t_, err = w.Write(out)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\ts.Log(err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// Flush the connection.\n\t\t\t\t\terr = w.Flush()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\ts.Log(err)\n\t\t\t\t\t}\n\t\t\t\t\t// Update timeout,\n\t\t\t\t\ttimeout = time.After(s.idleTimeout)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}(conn)\n\t}\n\n\treturn\n}", "func (s *Server) Serve() (err error) {\n\terrors := make(chan error)\n\n\tfor i := range s.tcpServers {\n\t\tsrv := s.tcpServers[i]\n\t\tgo func() {\n\t\t\terrors <- srv.Serve()\n\t\t}()\n\t}\n\n\tif !s.Config.Passive {\n\t\tgo func() {\n\t\t\terrors <- s.runActiveServices()\n\t\t}()\n\t}\n\n\t// Block for the first error, then return.\n\terr = <-errors\n\treturn err\n}", "func (s *Server) Serve() (err error) {\n\t// Initialize the gRPC server\n\ts.srv = grpc.NewServer()\n\tpb.RegisterTRISADemoServer(s.srv, s)\n\tpb.RegisterTRISAIntegrationServer(s.srv, s)\n\n\t// Catch OS signals for graceful shutdowns\n\tquit := make(chan os.Signal, 1)\n\tsignal.Notify(quit, os.Interrupt)\n\tgo func() {\n\t\t<-quit\n\t\ts.echan <- s.Shutdown()\n\t}()\n\n\t// Run the TRISA service on the TRISABindAddr\n\tif err = s.trisa.Serve(); err != nil {\n\t\treturn err\n\t}\n\n\t// Listen for TCP requests on the specified address and port\n\tvar sock net.Listener\n\tif sock, err = net.Listen(\"tcp\", s.conf.BindAddr); err != nil {\n\t\treturn fmt.Errorf(\"could not listen on %q\", s.conf.BindAddr)\n\t}\n\tdefer sock.Close()\n\n\t// Run the server\n\tgo func() {\n\t\tlog.Info().\n\t\t\tStr(\"listen\", s.conf.BindAddr).\n\t\t\tStr(\"version\", pkg.Version()).\n\t\t\tStr(\"name\", s.vasp.Name).\n\t\t\tMsg(\"server started\")\n\n\t\tif err := s.srv.Serve(sock); err != nil {\n\t\t\ts.echan <- err\n\t\t}\n\t}()\n\n\t// Listen for any errors that might have occurred and wait for all go routines to finish\n\tif err = <-s.echan; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Server) Listen(\n\taddr string,\n\tcertPath string,\n\tkeyPath string,\n) (err error) {\n\tlogger := logger.Logger()\n\tif err = s.init(); err != nil {\n\t\treturn\n\t}\n\n\topts := []grpc.ServerOption{}\n\ttlsFlag := false\n\n\tif certPath != \"\" && keyPath != \"\" {\n\t\tcreds, err := credentials.NewServerTLSFromFile(certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\topts = append(opts, grpc.Creds(creds))\n\t\ttlsFlag = true\n\t}\n\n\ts.grpcServer = grpc.NewServer(opts...)\n\tpb.RegisterEchoServer(s.grpcServer, s)\n\n\thttpMux := http.NewServeMux()\n\thttpMux.HandleFunc(\"/\", s.httpEchoPing)\n\n\trootMux := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.ProtoMajor == 2 && strings.Contains(req.Header.Get(\"Content-Type\"), \"application/grpc\") {\n\t\t\ts.grpcServer.ServeHTTP(w, req)\n\t\t} else {\n\t\t\thttpMux.ServeHTTP(w, req)\n\t\t}\n\t})\n\n\ts.httpServer = &http.Server{\n\t\tAddr: addr,\n\t\tHandler: h2c.NewHandler(rootMux, &http2.Server{}),\n\t}\n\n\tlogger.Printf(\"grpc listen address: %q tls: %v\", addr, tlsFlag)\n\tif tlsFlag {\n\t\treturn s.httpServer.ListenAndServeTLS(certPath, keyPath)\n\t}\n\treturn s.httpServer.ListenAndServe()\n}", "func (p *Proxy) Serve(l net.Listener) error {\n\tp.logger.Info(\"Serving HTTP requests\", zap.String(\"address\", p.config.Addr.String()))\n\n\tif err := p.server.Serve(l); err != nil {\n\t\tif !errors.Is(err, http.ErrServerClosed) {\n\t\t\tp.logger.Error(\"Error while serving HTTP requests!\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Listen(addr string, handler Handler) error {\n\tlisten, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer listen.Close()\n\n\tfor {\n\t\tconn, err := listen.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf := make([]byte, types.MaxBufferSize)\n\t\tn, err := conn.Read(buf)\n\t\tif err != nil {\n\t\t\tlog.Logger.Tracef(\"Unable to read buf: %s\", err)\n\t\t\tcontinue\n\t\t}\n\t\tgo handler(conn, buf[:n])\n\t}\n}", "func (l *LoadBalancer) Serve() error {\n\tdefer l.waitCancel()\n\tfor {\n\t\tconn, err := l.listener.Accept()\n\t\tif err != nil {\n\t\t\tif IsUseOfClosedNetworkError(err) {\n\t\t\t\treturn trace.Wrap(err, \"listener is closed\")\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-l.ctx.Done():\n\t\t\t\treturn trace.Wrap(net.ErrClosed, \"context is closing\")\n\t\t\tcase <-time.After(5. * time.Second):\n\t\t\t\tl.Debugf(\"Backoff on network error.\")\n\t\t\t}\n\t\t} else {\n\t\t\tgo l.forwardConnection(conn)\n\t\t}\n\t}\n}", "func (ln *Listener) Listen(t string, addr string) {\n\n\t// Declare TCP listening server\n\tlis, err := net.Listen(t, addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Listening to %s-%s\\n\", t, addr)\n\n\t// Main loop\n\tfor {\n\t\t// Accept incoming connection\n\t\tc, err := lis.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t} else {\n\t\t\t// Connection accepted, create client and spawn associated goroutines\n\t\t\tclt := NewClient(c, ln.core)\n\t\t\tgo clt.jsonIn()\n\t\t\tgo clt.jsonOut()\n\t\t}\n\t}\n}", "func Serve(l net.Listener, h Handler, appname, hostname string) (err error) {\n\tserv := Server{\n\t\tAppname: appname,\n\t\tHostname: hostname,\n\t\tHandler: h,\n\t}\n\treturn serv.Serve(l)\n}", "func (s *HTTPServer) Serve() error {\n\treturn s.srv.Serve(s.l)\n}", "func Serve(ln net.Listener) error {\n\treturn Default.Serve(ln)\n}", "func (s Server) Listen() *ServerControl {\n\ts.init()\n\n\tstopHTTPServer := make(chan os.Signal, 1)\n\tsignal.Notify(stopHTTPServer, os.Interrupt)\n\n\tstatus := &serverStatus{\n\t\tlock: sync.RWMutex{},\n\t\tstatus: NotStarted,\n\t}\n\n\tsrv := &http.Server{Handler: s.Handler}\n\n\terrs := make(chan error, 1)\n\tgo func() {\n\t\tstatus.set(Starting)\n\t\thttpAddr := s.Address + \":\" + strconv.Itoa(s.Port)\n\t\tl, err := net.Listen(\"tcp\", httpAddr)\n\t\tif err != nil {\n\t\t\tstatus.set(Error)\n\t\t\terrs <- fmt.Errorf(\"listening to %s: %w\", httpAddr, err)\n\t\t\treturn\n\t\t}\n\n\t\tstatus.set(Listening)\n\n\t\tif err := srv.Serve(l); nil != err {\n\t\t\tif http.ErrServerClosed != err {\n\t\t\t\tstatus.set(Error)\n\t\t\t\terrs <- fmt.Errorf(\"serving on %s: %w\", httpAddr, err)\n\t\t\t\tclose(errs)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn &ServerControl{\n\t\tstatus: status,\n\t\tInterrupted: stopHTTPServer,\n\t\tErrors: errs,\n\t\tServer: srv,\n\t}\n}", "func (s *testDoQServer) Serve() {\n\tfor {\n\t\tconn, err := s.listener.Accept(context.Background())\n\t\tif err == quic.ErrServerClosed {\n\t\t\t// Finish serving on ErrServerClosed error.\n\t\t\treturn\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Debug(\"error while accepting a new connection: %v\", err)\n\t\t}\n\n\t\tgo s.handleQUICConnection(conn)\n\t}\n}", "func (f *HTTPFrontend) Serve(ctx context.Context, l *Listener, conn net.Conn) {\n\tif tcpConn, ok := conn.(*net.TCPConn); ok {\n\t\ttcpConn.SetKeepAlive(true)\n\t\ttcpConn.SetKeepAlivePeriod(5 * time.Second)\n\t}\n\tfeConn := newBufConn(conn)\n\tdefer feConn.Flush()\n\txlog.V(200).Debugf(\"connected client %q to listener %q on frontend %q\", feConn.RemoteAddr().String(), l.opts.Name, f.opts.Name)\n\tdefer xlog.V(200).Debugf(\"disconnected client %q from listener %q on frontend %q\", feConn.RemoteAddr().String(), l.opts.Name, f.opts.Name)\n\n\tpromLabels := prometheus.Labels{\n\t\t\"listener\": l.opts.Name,\n\t}\n\tf.promConnectionsTotal.With(promLabels).Inc()\n\n\tif f.opts.MaxConn > 0 && f.totalConnCount >= int64(f.opts.MaxConn) {\n\t\terr := errHTTPFrontendExhausted\n\t\txlog.V(100).Debugf(\"serve error on %s: %v\", (&httpReqDesc{\n\t\t\tleName: l.opts.Name,\n\t\t\tfeName: f.opts.Name,\n\t\t\tfeConn: feConn,\n\t\t}).FrontendSummary(), err)\n\t\te := err.(*httpError)\n\t\tpromLabels := prometheus.Labels{\n\t\t\t\"host\": \"\",\n\t\t\t\"path\": \"\",\n\t\t\t\"method\": \"\",\n\t\t\t\"backend\": \"\",\n\t\t\t\"server\": \"\",\n\t\t\t\"code\": \"\",\n\t\t\t\"listener\": l.opts.Name,\n\t\t\t\"error\": e.Group,\n\t\t}\n\t\tf.promRequestsTotal.With(promLabels).Inc()\n\t\treturn\n\t}\n\tatomic.AddInt64(&f.totalConnCount, 1)\n\tdefer atomic.AddInt64(&f.totalConnCount, -1)\n\n\tfor reqIdx, done := 0, false; !done; reqIdx++ {\n\t\tif reqIdx > 0 {\n\t\t\tatomic.AddInt64(&f.idleConnCount, 1)\n\t\t\tf.promIdleConnections.With(promLabels).Inc()\n\t\t} else {\n\t\t\tatomic.AddInt64(&f.waitingConnCount, 1)\n\t\t\tf.promWaitingConnections.With(promLabels).Inc()\n\t\t}\n\n\t\treadErrCh := make(chan error, 1)\n\t\tgo func(reqIdx int) {\n\t\t\tif reqIdx <= 0 && f.opts.RequestTimeout > 0 {\n\t\t\t\tfeConn.SetReadDeadline(time.Now().Add(f.opts.RequestTimeout))\n\t\t\t}\n\t\t\t_, e := feConn.Reader.Peek(1)\n\t\t\tif reqIdx > 0 {\n\t\t\t\tatomic.AddInt64(&f.idleConnCount, -1)\n\t\t\t\tf.promIdleConnections.With(promLabels).Dec()\n\t\t\t} else {\n\t\t\t\tatomic.AddInt64(&f.waitingConnCount, -1)\n\t\t\t\tf.promWaitingConnections.With(promLabels).Dec()\n\t\t\t}\n\t\t\treadErrCh <- e\n\t\t}(reqIdx)\n\n\t\tctx, ctxCancel := ctx, context.CancelFunc(func() { /* null function */ })\n\t\tif reqIdx > 0 && f.opts.KeepAliveTimeout > 0 {\n\t\t\tctx, ctxCancel = context.WithTimeout(ctx, f.opts.KeepAliveTimeout)\n\t\t}\n\n\t\tselect {\n\t\tcase err := <-readErrCh:\n\t\t\tif err != nil {\n\t\t\t\tif !errors.Is(err, io.EOF) {\n\t\t\t\t\tif e := (*net.OpError)(nil); reqIdx <= 0 && errors.As(err, &e) && e.Timeout() {\n\t\t\t\t\t\terr = wrapHTTPError(httpErrGroupRequestTimeout, err)\n\t\t\t\t\t\txlog.V(100).Debugf(\"serve error: read first byte from frontend: %v\", err)\n\t\t\t\t\t\tfeConn.Write([]byte(httpRequestTimeout))\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = wrapHTTPError(httpErrGroupCommunication, err)\n\t\t\t\t\t\txlog.V(100).Debugf(\"serve error: read first byte from frontend: %v\", err)\n\t\t\t\t\t}\n\t\t\t\t\te := err.(*httpError)\n\t\t\t\t\tpromLabels := prometheus.Labels{\n\t\t\t\t\t\t\"host\": \"\",\n\t\t\t\t\t\t\"path\": \"\",\n\t\t\t\t\t\t\"method\": \"\",\n\t\t\t\t\t\t\"backend\": \"\",\n\t\t\t\t\t\t\"server\": \"\",\n\t\t\t\t\t\t\"code\": \"\",\n\t\t\t\t\t\t\"listener\": l.opts.Name,\n\t\t\t\t\t\t\"error\": e.Group,\n\t\t\t\t\t}\n\t\t\t\t\tf.promRequestsTotal.With(promLabels).Inc()\n\t\t\t\t}\n\t\t\t\tdone = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tatomic.AddInt64(&f.activeConnCount, 1)\n\t\t\tf.promActiveConnections.With(promLabels).Inc()\n\t\t\treqDesc := &httpReqDesc{\n\t\t\t\treqIdx: reqIdx,\n\t\t\t\tleName: l.opts.Name,\n\t\t\t\tleTLS: l.opts.TLSConfig != nil,\n\t\t\t\tfeName: f.opts.Name,\n\t\t\t\tfeConn: feConn,\n\t\t\t}\n\t\t\treqDesc.leHost, reqDesc.lePort = splitHostPort(l.opts.Address)\n\t\t\tif e := f.serve(ctx, reqDesc); e != nil {\n\t\t\t\tdone = true\n\t\t\t}\n\t\t\tatomic.AddInt64(&f.activeConnCount, -1)\n\t\t\tf.promActiveConnections.With(promLabels).Dec()\n\t\t\tif (f.opts.MaxIdleConn > 0 && f.idleConnCount >= int64(f.opts.MaxIdleConn)) || (f.opts.MaxKeepAliveReqs >= 0 && reqIdx >= f.opts.MaxKeepAliveReqs) {\n\t\t\t\tdone = true\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tdone = true\n\t\t}\n\n\t\tctxCancel()\n\t}\n\n\treturn\n}", "func (srv *Server) Serve() (err error) {\n\tsrv.state = StateRunning\n\tdefer func() { srv.state = StateTerminate }()\n\n\t// 主动重启导致的错误为ErrReloadClose\n\tif err = srv.serve(); err != nil && err != ErrReloadClose {\n\t\tlog.Println(syscall.Getpid(), \"Server.Serve() error:\", err)\n\t\treturn err\n\t}\n\n\tlog.Println(syscall.Getpid(), srv.ln.Addr(), \"Listener closed.\")\n\t// wait for Shutdown to return\n\treturn <-srv.terminalChan\n}", "func (srv *Server) ListenAndServe() (err error) {\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":3000\"\n\t}\n\n\tgo srv.handleSignals()\n\n\tsrv.ln, err = srv.getListener(addr)\n\tif err != nil {\n\t\tlog.Println(os.Getpid(), err)\n\t\treturn err\n\t}\n\n\tif srv.isChild {\n\t\tprocess, err := os.FindProcess(os.Getppid())\n\t\tif err != nil {\n\t\t\tlog.Println(os.Getpid(), err)\n\t\t\treturn err\n\t\t}\n\t\terr = process.Signal(syscall.SIGTERM)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Listening for connections on %v, pid=%d\", srv.ln.Addr(), os.Getpid()))\n\n\treturn srv.Serve()\n}", "func (s *Server) Serve() error {\n\tif err := s.server.Serve(s.config.Listener); err != nil {\n\t\tif errors.Is(err, grpc.ErrServerStopped) ||\n\t\t\tutils.IsUseOfClosedNetworkError(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn trace.Wrap(err)\n\t}\n\treturn nil\n}", "func (svr *Server) Start() (err error) {\n\n\tfor {\n\t\tcliConn, err := svr.listener.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// save connection\n\t\tsvr.mtx.Lock()\n\t\tsvr.connList.PushBack(cliConn)\n\t\tsvr.mtx.Unlock()\n\n\t\tsvr.logger.Debug(\"Accept new connection\", \"RemoteAddr\", cliConn.RemoteAddr())\n\t\tgo svr.readRequest(cliConn)\n\t}\n}", "func (s *TCPServer) Serve(addr string) error {\n\t// Start TCP Server\n\tlistener, err := net.Listen(\"tcp4\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Bind to RPCBIND server\n\t_, port, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tportAsInt, err := strconv.Atoi(port)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.registerToPortmapper(Tcp, portAsInt); err != nil {\n\t\treturn err\n\t}\n\n\t// Handle incoming connections\n\tgo func() {\n\t\tfor {\n\t\t\tconn, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\ts.server.log.WithField(\"err\", err).Error(\"Unable to accept incoming connection. Ignoring\")\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ts.server.log.WithField(\"remote\", conn.RemoteAddr().String()).Debug(\"Client connected.\")\n\n\t\t\tgo s.handleCall(conn)\n\t\t}\n\t}()\n\n\treturn nil\n}", "func (srv *Server) Serve() error {\n\ts := srv.s\n\tif s == nil {\n\t\treturn fmt.Errorf(\"Serve() failed: not initialized\")\n\t}\n\treturn srv.s.Serve(srv.lis)\n}", "func (p *ConcurrentServer) Serve() error {\n\terr := p.Listen()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn p.AcceptLoop()\n}", "func Listen(lis net.Listener, grpcServer *grpc.Server) (clientChan chan *grpc.ClientConn, shutdownChan chan int, err error) {\n\t// create channels\n\tclientChan = make(chan *grpc.ClientConn)\n\tshutdownChan = make(chan int)\n\n\tgo func() {\n\t\t// start listenLoop - blocks until some error occurs\n\t\tlistenLoop(lis, grpcServer, clientChan)\n\t\tclose(shutdownChan)\n\t}()\n\n\treturn clientChan, shutdownChan, nil\n}", "func (ts *TCPServer) Listen() error {\n\tfor {\n\t\tconn, err := ts.listener.Accept()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot accept: %v\", err)\n\t\t}\n\t\tts.connections = append(ts.connections, conn)\n\t\tgo ts.handleConnection(conn)\n\t}\n}", "func (s *Server) Run() {\n\ts.Config.set()\n\tfor {\n\t\tconn, err := s.Listener.Accept()\n\t\tif err != nil {\n\t\t\ts.Config.ErrorLog(\"fail to accept new connection: %s\", err)\n\t\t}\n\t\tgo s.handleConn(conn)\n\t}\n}", "func (s *Server) Run() {\n\tfor {\n\t\tconn, err := s.l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Accept error: %v\\n\", err)\n\t\t} else {\n\t\t\tgo s.handlerConn(conn)\n\t\t}\n\t}\n}", "func (s *Service) Listen(ctx context.Context, address string, timeout time.Duration) error {\n\tvar wg sync.WaitGroup\n\tdefer func() { s.teardown(); wg.Wait() }()\n\n\terr := s.Bind(ctx, address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mutex.Lock()\n\ts.running = true\n\tl := s.listener\n\ts.mutex.Unlock()\n\n\tfor s.running {\n\t\tif timeout != 0 {\n\t\t\tif err := s.refreshTimeout(timeout); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tif err.(net.Error).Timeout() {\n\t\t\t\ts.mutex.Lock()\n\t\t\t\tif s.conncounter == 0 {\n\t\t\t\t\ts.mutex.Unlock()\n\t\t\t\t\treturn ServiceTimeoutError{}\n\t\t\t\t}\n\t\t\t\ts.mutex.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !s.running {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\ts.mutex.Lock()\n\t\ts.conncounter++\n\t\ts.mutex.Unlock()\n\t\twg.Add(1)\n\t\tgo s.handleConnection(ctx, conn, &wg)\n\t}\n\n\treturn nil\n}", "func (s *Service)ListenAndServe(port string, r http.Handler) {\n\t\tlog.Println(\"Starting Server!\")\n\t\ts.Server = &http.Server{Addr: port, Handler: r}\n\t\tif err := s.Server.ListenAndServe(); err != nil {\n\t\t\t\t// handle err\n\t\t}\n\n // Setting up signal capturing\n stop := make(chan os.Signal, 1)\n signal.Notify(stop, os.Interrupt)\n\n // Waiting for SIGINT (pkill -2)\n <-stop\n\t\tlog.Println(\"Received Server Stop!\")\n s.Stop()\n // Wait for ListenAndServe goroutine to close.\n}", "func ListenAndServe(opts ...server.Option) {\n\n\td, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfp := filepath.Join(d, \"service.ini\")\n\tcfg, err := config.LoadIniConfig(fp)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsvr, err := server.NewServer(opts...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, section := range cfg.Sections() {\n\t\t// enable support for protocols\n\t\tok := strings.HasSuffix(section, \"-service\")\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tcodec := strings.TrimSuffix(section, \"-service\")\n\n\t\t// initialize tcp ServerModule\n\t\ttcpport := cfg.Int(section, \"tcp.port\", 0)\n\t\tif tcpport > 0 {\n\t\t\tmod, err := server.NewTcpServer(\"tcp4\", fmt.Sprintf(\":%d\", tcpport), codec)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tmod.Register(svr)\n\t\t}\n\n\t\t// initialize udp ServerModule\n\t\tudpport := cfg.Int(section, \"udp.port\", 0)\n\t\tif udpport > 0 {\n\t\t\tmod, err := server.NewTcpServer(\"udp4\", fmt.Sprintf(\":%d\", udpport), codec)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tmod.Register(svr)\n\t\t}\n\t}\n\n\tsvr.Start()\n}", "func (s *Service) Listen() (err error) {\n\t// Initialize error channel\n\terrC := make(chan error, 2)\n\t// Listen to HTTP (if needed)\n\tgo s.listenHTTP(errC)\n\t// Listen to HTTPS (if needed)\n\tgo s.listenHTTPS(errC)\n\t// Return any error which may come down the error channel\n\treturn <-errC\n}", "func (s *Server) Serve(socketPath string, readyCh chan struct{}) error {\n\terr := syscall.Unlink(socketPath)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\ts.Lock()\n\ts.doneCh = make(chan struct{})\n\tdefer close(s.doneCh)\n\ts.ln, err = net.Listen(\"unix\", socketPath)\n\ts.Unlock()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer s.ln.Close()\n\tif readyCh != nil {\n\t\tclose(readyCh)\n\t}\n\tfor {\n\t\tvar tempDelay time.Duration // how long to sleep on accept failure\n\n\t\tfor {\n\t\t\tconn, err := s.ln.Accept()\n\t\t\tif err != nil {\n\t\t\t\tif ne, ok := err.(interface {\n\t\t\t\t\tTemporary() bool\n\t\t\t\t}); !ok || !ne.Temporary() {\n\t\t\t\t\tglog.V(1).Infof(\"done serving; Accept = %v\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif tempDelay == 0 {\n\t\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\ttempDelay *= 2\n\t\t\t\t}\n\t\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\t\ttempDelay = max\n\t\t\t\t}\n\t\t\t\tglog.Warningf(\"Accept error: %v; retrying in %v\", err, tempDelay)\n\t\t\t\t<-time.After(tempDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttempDelay = 0\n\n\t\t\tif err := s.dump(conn); err != nil {\n\t\t\t\tglog.Warningf(\"Error dumping diagnostics info: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n}", "func handleNewSlaves(port string, reqChan, rreqChan chan string) {\n\n\tln, err := net.Listen(\"tcp\", \":\"+port)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"Slave Master running on port: \" + port)\n\taddChan := make(chan Slave)\n\tmsgChan := make(chan Msg)\n\tgo handleSlaves(msgChan, addChan, reqChan, rreqChan)\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tgo handleSlaveConnection(conn, msgChan, addChan)\n\t}\n}", "func (s *Server) Run() {\n\tvar l net.Listener\n\tvar err error\n\thost := s.ip+\":\"+s.port\n\tl, err = net.Listen(\"tcp\", host)\n\tif err != nil {\n\t\tlog.Fatal(\"Listen: %v\", err)\n\t}\n\tif s.connLimit > 0 {\n\t\tl = netutil.LimitListener(l, s.connLimit)\n\t}\n\n\terr = http.Serve(l, s)\n\tif err != nil {\n\t\tlog.Fatal(\"http.listenAndServe failed: %s\", err.Error())\n\t}\n\ts.l = l\n\treturn\n}", "func (rcv *TCP) Listen(addr *net.TCPAddr) error {\n\treturn rcv.StartFunc(func() error {\n\n\t\ttcpListener, err := net.ListenTCP(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trcv.Go(func(exit chan struct{}) {\n\t\t\t<-exit\n\t\t\ttcpListener.Close()\n\t\t})\n\n\t\thandler := rcv.HandleConnection\n\n\t\trcv.Go(func(exit chan struct{}) {\n\t\t\tdefer tcpListener.Close()\n\n\t\t\tfor {\n\n\t\t\t\tconn, err := tcpListener.Accept()\n\t\t\t\tif err != nil {\n\t\t\t\t\tif strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\trcv.logger.Warn(\"failed to accept connection\", zap.Error(err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\trcv.Go(func(exit chan struct{}) {\n\t\t\t\t\thandler(conn)\n\t\t\t\t})\n\t\t\t}\n\n\t\t})\n\n\t\tfor i := 0; i < rcv.parseThreads; i++ {\n\t\t\trcv.Go(func(exit chan struct{}) {\n\t\t\t\tPlainParser(\n\t\t\t\t\texit,\n\t\t\t\t\trcv.parseChan,\n\t\t\t\t\trcv.writeChan,\n\t\t\t\t\t&rcv.stat.metricsReceived,\n\t\t\t\t\t&rcv.stat.errors,\n\t\t\t\t)\n\t\t\t})\n\t\t}\n\n\t\trcv.listener = tcpListener\n\n\t\treturn nil\n\t})\n}", "func (c *Core) Serve(args ...interface{}) error {\n\tvar (\n\t\taddr = \"8080\"\n\t\tln net.Listener\n\t\terr error\n\t\ttc *tls.Config\n\t)\n\n\tfor _, arg := range args {\n\t\tswitch a := arg.(type) {\n\t\tcase int:\n\t\t\taddr = strconv.Itoa(a)\n\t\tcase string:\n\t\t\taddr = a\n\t\tcase *tls.Config:\n\t\t\ttc = a\n\t\t}\n\t}\n\n\tif !strings.Contains(addr, \":\") {\n\t\taddr = \":\" + addr\n\t}\n\n\tif c.Prefork {\n\t\treturn c.prefork(addr, tc)\n\t}\n\n\tif ln, err = net.Listen(\"tcp\", addr); err != nil {\n\t\treturn err\n\t}\n\n\tif tc != nil {\n\t\tln = tls.NewListener(ln, tc)\n\t}\n\tLog.Info(\"Listen: %s\", addr)\n\treturn c.Server.Serve(ln)\n}" ]
[ "0.76736426", "0.75317055", "0.7455385", "0.74516284", "0.74438196", "0.7365043", "0.7327343", "0.7316645", "0.7296336", "0.72775364", "0.7251898", "0.72306645", "0.72092503", "0.71762687", "0.7172905", "0.71585333", "0.71043956", "0.70909613", "0.7074558", "0.7014645", "0.6938495", "0.6913426", "0.687756", "0.68492955", "0.6848619", "0.6831488", "0.6831488", "0.68297166", "0.68269604", "0.68061966", "0.67912954", "0.67797667", "0.6762346", "0.675365", "0.6751098", "0.67354035", "0.67334193", "0.67143625", "0.6703127", "0.669273", "0.669238", "0.6689304", "0.6681499", "0.66811055", "0.6680123", "0.6659357", "0.66285163", "0.661597", "0.6595158", "0.6545168", "0.6524841", "0.65054333", "0.6481336", "0.6470802", "0.64689", "0.6447174", "0.6443436", "0.6437811", "0.6434208", "0.6424629", "0.6418398", "0.6408678", "0.6383242", "0.63751537", "0.6358924", "0.6358924", "0.6352247", "0.63346356", "0.63198084", "0.62865907", "0.6272585", "0.62607855", "0.6255466", "0.6253117", "0.6252868", "0.624283", "0.6238339", "0.6236346", "0.62279063", "0.62212294", "0.62179923", "0.6210094", "0.62022066", "0.6180991", "0.6178867", "0.61662483", "0.61649406", "0.6158936", "0.6138123", "0.61186844", "0.61126435", "0.61093384", "0.60983247", "0.6095802", "0.60827416", "0.60687083", "0.6049409", "0.6046508", "0.60458463", "0.6022496" ]
0.74340755
5
ServeTLS accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.Handler to reply to them. ServeTLS returns a nil error after Close or Shutdown method called. Additionally, files containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated.. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.
func (srv *TCPServer) ServeTLS(l net.Listener, certFile, keyFile string) (err error) { config := srv.TLSConfig if config == nil { config = &tls.Config{} } configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil if !configHasCert || certFile != "" || keyFile != "" { config.Certificates = make([]tls.Certificate, 1) config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return } } tlsListener := tls.NewListener(l, config) return srv.Serve(tlsListener) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {\n\tsrv := &Server{Handler: handler}\n\treturn srv.ServeTLS(l, certFile, keyFile)\n}", "func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {\n\t// Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig\n\t// before we clone it and create the TLS Listener.\n\tif err := srv.setupHTTP2_ServeTLS(); err != nil {\n\t\treturn err\n\t}\n\n\tconfig := cloneTLSConfig(srv.TLSConfig)\n\tif !strSliceContains(config.NextProtos, \"http/1.1\") {\n\t\tconfig.NextProtos = append(config.NextProtos, \"http/1.1\")\n\t}\n\n\tconfigHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil\n\tif !configHasCert || certFile != \"\" || keyFile != \"\" {\n\t\tvar err error\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttlsListener := tls.NewListener(l, config)\n\treturn srv.Serve(tlsListener)\n}", "func ListenAndServeTLS(opt *Options, httpHandler http.Handler, grpcHandler *grpc.Server) error {\n\tif opt == nil {\n\t\topt = defaultOptions\n\t} else {\n\t\topt.applyDefaults()\n\t}\n\tvar cert *tls.Certificate\n\tvar err error\n\tif opt.Cert != \"\" && opt.Key != \"\" {\n\t\tcert, err = decodeCertificate(opt.Cert, opt.Key)\n\t} else {\n\t\tcert, err = readCertificateFile(opt.CertFile, opt.KeyFile)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: failed loading x509 certificate: %v\", err)\n\t}\n\tconfig, err := newDefaultTLSConfig(cert)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: setting up TLS config: %v\", err)\n\t}\n\tln, err := net.Listen(\"tcp\", opt.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tln = tls.NewListener(ln, config)\n\n\tvar h http.Handler\n\tif grpcHandler == nil {\n\t\th = httpHandler\n\t} else {\n\t\th = grpcHandlerFunc(grpcHandler, httpHandler)\n\t}\n\tsublogger := log.With().Str(\"addr\", opt.Addr).Logger()\n\n\t// Set up the main server.\n\tserver := &http.Server{\n\t\tReadHeaderTimeout: 10 * time.Second,\n\t\tReadTimeout: 30 * time.Second,\n\t\t// WriteTimeout is set to 0 for streaming replies\n\t\tWriteTimeout: 0,\n\t\tIdleTimeout: 5 * time.Minute,\n\t\tTLSConfig: config,\n\t\tHandler: h,\n\t\tErrorLog: stdlog.New(&log.StdLogWrapper{Logger: &sublogger}, \"\", 0),\n\t}\n\n\treturn server.Serve(ln)\n}", "func ListenTLS(how, addr string, certFile, keyFile string) (*Server, error) {\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ListenTLSCustom(how, addr, &tls.Config{\n\t\tRootCAs: TLSCertPool(),\n\t\tCertificates: []tls.Certificate{cert},\n\t})\n}", "func (gss *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo func() {\n\t\tif err := gss.server.ServeTLS(l, certFile, keyFile); err != nil {\n\t\t\tgss.startErr = err\n\t\t\tcancel()\n\t\t}\n\t}()\n\treturn gss.waitForInterrupt(ctx)\n}", "func (r *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {\n return http.ListenAndServeTLS(addr, certFile, keyFile, r.router)\n}", "func (srv *Server) ServeTLS(l net.Listener, tLSConfig *tls.Config, certFile, keyFile string) error {\n\tconfig := http_.CloneTLSConfig(tLSConfig)\n\tif !strings.SliceContains(config.NextProtos, \"http/1.1\") {\n\t\tconfig.NextProtos = append(config.NextProtos, \"http/1.1\")\n\t}\n\n\tconfigHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil\n\tif !configHasCert || certFile != \"\" || keyFile != \"\" {\n\t\tvar err error\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttlsListener := tls.NewListener(l, config)\n\treturn srv.Serve(tlsListener)\n}", "func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\tsrv.isHttps = true\n\taddr := srv.httpServer.Addr\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tsrv.tlsConfig = &tls.Config{}\n\tif srv.httpServer.TLSConfig != nil {\n\t\t*srv.tlsConfig = *srv.httpServer.TLSConfig\n\t}\n\tif srv.tlsConfig.NextProtos == nil {\n\t\tsrv.tlsConfig.NextProtos = []string{\"http/1.1\"}\n\t}\n\n\tvar err error\n\tsrv.tlsConfig.Certificates = make([]tls.Certificate, 1)\n\tsrv.tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tln, err := srv.getListener(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrv.listener = NewWebTcpListener(ln)\n\n\treturn srv.Serve()\n}", "func ListenAndServeTLS(addr string, handler http.Handler, crt Certifier) error {\n\tcerts := newCertCache(crt)\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\n\ts := http.Server{\n\t\tAddr: addr,\n\t\tHandler: handler,\n\t\tTLSConfig: &tls.Config{\n\t\t\tGetCertificate: func(h *tls.ClientHelloInfo) (c *tls.Certificate, err error) {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpromVPKICertError.With(prometheus.Labels{\"server_name\": h.ServerName}).Inc()\n\t\t\t\t\t}\n\t\t\t\t}()\n\n\t\t\t\tif h.ServerName == \"\" {\n\t\t\t\t\terr = fmt.Errorf(\"Cannot generate certs without TLS SNI (no server name was indicated)\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif crt, ok := crt.(SNICertifier); ok {\n\t\t\t\t\tc, err = crt.GetCertificate(h)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tc, err = certs.get(h.ServerName)\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t}\n\n\treturn s.ListenAndServeTLS(\"\", \"\")\n}", "func (m *cMux) ServeTLS(l net.Listener, tLSConfig *tls.Config, certFile, keyFile string) error {\n\tconfig := cloneTLSConfig(tLSConfig)\n\tif !strings.SliceContains(config.NextProtos, \"http/1.1\") {\n\t\tconfig.NextProtos = append(config.NextProtos, \"http/1.1\")\n\t}\n\n\tconfigHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil\n\tif !configHasCert || certFile != \"\" || keyFile != \"\" {\n\t\tvar err error\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttlsListener := tls.NewListener(l, config)\n\treturn m.Serve(tlsListener)\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) (err error) {\n\n\ttlsConfig := &tls.Config{\n\t\tNextProtos: []string{http2NextProtoTLS, http2Rev14, http11},\n\t\tCertificates: make([]tls.Certificate, 1),\n\t}\n\n\ttlsConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\n\tl, err := kmsnet.NewTCPListenerNoShutdown(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsListener := tls.NewListener(l, tlsConfig)\n\n\ts := &http.Server{Addr: tlsListener.Addr().String(), Handler: handler, TLSConfig: tlsConfig}\n\n\tserver := &serverConnState{\n\t\tServer: s,\n\t\tl: tlsListener,\n\t\tidleConns: make(map[net.Conn]struct{}),\n\t\tactive: make(chan net.Conn),\n\t\tidle: make(chan net.Conn),\n\t\tclosed: make(chan net.Conn),\n\t\tshutdown: make(chan struct{}),\n\t}\n\n\tserver.handleConnState()\n\n\terr = server.Serve(server.l)\n\n\t// wait for process shutdown to complete or timeout.\n\t<-kms.ShutdownComplete()\n\n\treturn err\n}", "func (gss *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo func() {\n\t\tif err := gss.server.ListenAndServeTLS(certFile, keyFile); err != http.ErrServerClosed {\n\t\t\tgss.startErr = err\n\t\t\tcancel()\n\t\t}\n\t}()\n\treturn gss.waitForInterrupt(ctx)\n}", "func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\tif srv.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer ln.Close()\n\n\treturn srv.ServeTLS(ln, certFile, keyFile)\n}", "func (s *Server) ServeOnListenerTLS(address string, port int, certFile, keyFile string, stopChan <-chan struct{}) error {\n\t// kubernetes build handler configuration\n\tserverConfig := server.NewConfig(serializer.NewCodecFactory(s.virtualManager.GetScheme()))\n\tserverConfig.RequestInfoResolver = &request.RequestInfoFactory{\n\t\tAPIPrefixes: sets.NewString(\"api\", \"apis\"),\n\t\tGrouplessAPIPrefixes: sets.NewString(\"api\"),\n\t}\n\n\tredirectAuthResources := []delegatingauthorizer.GroupVersionResourceVerb{\n\t\t{\n\t\t\tGroupVersionResource: corev1.SchemeGroupVersion.WithResource(\"services\"),\n\t\t\tVerb: \"create\",\n\t\t\tSubResource: \"\",\n\t\t},\n\t}\n\tredirectAuthResources = append(redirectAuthResources, s.redirectResources...)\n\tserverConfig.Authorization.Authorizer = union.New(kubeletauthorizer.New(s.localManager, s.virtualManager), delegatingauthorizer.New(s.virtualManager, redirectAuthResources, nil), impersonationauthorizer.New(s.virtualManager.GetClient()), allowall.New())\n\n\tsso := options.NewSecureServingOptions()\n\tsso.HTTP2MaxStreamsPerConnection = 1000\n\tsso.ServerCert.CertKey.CertFile = certFile\n\tsso.ServerCert.CertKey.KeyFile = keyFile\n\tsso.BindPort = port\n\tsso.BindAddress = net.ParseIP(address)\n\terr := sso.WithLoopback().ApplyTo(&serverConfig.SecureServing, &serverConfig.LoopbackClientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tauthOptions := options.NewDelegatingAuthenticationOptions()\n\tauthOptions.RemoteKubeConfigFileOptional = true\n\tauthOptions.SkipInClusterLookup = true\n\tauthOptions.RequestHeader.ClientCAFile = s.requestHeaderCaFile\n\tauthOptions.ClientCert.ClientCA = s.clientCaFile\n\terr = authOptions.ApplyTo(&serverConfig.Authentication, serverConfig.SecureServing, serverConfig.OpenAPIConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// make sure the tokens are correctly authenticated\n\tserverConfig.Authentication.Authenticator = unionauthentication.New(delegatingauthenticator.New(s.virtualManager.GetClient()), serverConfig.Authentication.Authenticator)\n\n\t// create server\n\tklog.Info(\"Starting tls proxy server at \" + address + \":\" + strconv.Itoa(port))\n\tstopped, err := serverConfig.SecureServing.Serve(s.buildHandlerChain(serverConfig), serverConfig.RequestTimeout, stopChan)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t<-stopped\n\treturn nil\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {\n\tserver := &Server{Addr: addr, Handler: handler}\n\treturn server.ListenAndServeTLS(certFile, keyFile)\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {\n\tserver := &Server{Addr: addr, Handler: handler}\n\treturn server.ListenAndServeTLS(certFile, keyFile)\n}", "func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\tconfig := &tls.Config{}\n\tif s.server.TLSConfig != nil {\n\t\t*config = *s.server.TLSConfig\n\t}\n\tif config.NextProtos == nil {\n\t\tconfig.NextProtos = []string{\"http/1.1\"}\n\t}\n\n\tvar err error\n\tconfig.Certificates = make([]tls.Certificate, 1)\n\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsListener := tls.NewListener(s.listener, config)\n\treturn s.server.Serve(tlsListener)\n}", "func (s *Server) ServeTLS(ctx context.Context, ln net.Listener) error {\n\tln = tls.NewListener(ln, s.TLSConfig.Clone())\n\tdefer ln.Close()\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tgo func(conn net.Conn) {\n\t\t\tif err := conn.(*tls.Conn).Handshake(); err != nil {\n\t\t\t\ts.logf(\"dns handshake: %s\", err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts.serveStream(ctx, conn)\n\t\t}(conn)\n\t}\n}", "func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\tvar err error\n\tcerts := make([]tls.Certificate, 1)\n\tcerts[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// We currently only use the cert-related stuff from tls.Config,\n\t// so we don't need to make a full copy.\n\tconfig := &tls.Config{\n\t\tCertificates: certs,\n\t}\n\treturn s.serveConn(config, nil)\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) error {\n\tvar err error\n\tserver, err = New(&http.Server{\n\t\tAddr: addr,\n\t\tHandler: handler,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn server.ListenAndServeTLS(certFile, keyFile)\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {\n\tsrv := New(addr)\n\n\treturn srv.ListenAndServeTLS(certFile, keyFile, handler)\n}", "func ListenAndServeTLS(addr string, handler HandlerConn, tlsConfig *tls.Config, certFile, keyFile string) error {\n\tserver := NewServer()\n\tserver.Handler = handler\n\treturn server.ListenAndServeTLS(addr, tlsConfig, certFile, keyFile)\n}", "func (srv *Server) ListenAndServeTLS(certFile, keyFile string, handler Handler) error {\n\tsrv.init(handler)\n\n\treturn srv.Server.ListenAndServeTLS(certFile, keyFile)\n}", "func (t *HTTPServer) ListenAndServeTLS() error {\n\tif t.options.Certificate == \"\" || t.options.CertificateKey == \"\" {\n\t\ttlsOptions := sslcert.DefaultOptions\n\t\ttlsOptions.Host = t.options.CertificateDomain\n\t\ttlsConfig, err := sslcert.NewTLSConfig(tlsOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpServer := &http.Server{\n\t\t\tAddr: t.options.ListenAddress,\n\t\t\tTLSConfig: tlsConfig,\n\t\t}\n\t\thttpServer.Handler = t.layers\n\t\treturn httpServer.ListenAndServeTLS(\"\", \"\")\n\t}\n\treturn http.ListenAndServeTLS(t.options.ListenAddress, t.options.Certificate, t.options.CertificateKey, t.layers)\n}", "func (serv *Server) RunTLS(addr, certFile, keyFile string) (err error) {\n\tdebugPrint(\"Listening and serving HTTPS on %s\\n\", addr)\n\tdefer func() { debugPrintError(err) }()\n\n\terr = http.ListenAndServeTLS(addr, certFile, keyFile, serv)\n\treturn\n}", "func ListenAndServeTLS(ctx context.Context, addr string, handler Handler, tlsConfig *tls.Config, certFile, keyFile string) error {\n\tserver := New(ctx)\n\tserver.MatchAndGoServe(handler)\n\treturn server.ListenAndServeTLS(addr, tlsConfig, certFile, keyFile)\n}", "func ServeTLS(reg *cookoo.Registry, router *cookoo.Router, cxt cookoo.Context, certFile, keyFile string) {\n\taddr := cxt.Get(\"server.Address\", \":4433\").(string)\n\n\tserver := &http.Server{Addr: addr}\n\tserver.Handler = NewCookooHandler(reg, router, cxt)\n\n\tgo handleSignals(router, cxt, server)\n\terr := server.ListenAndServeTLS(certFile, keyFile)\n\tif err != nil {\n\t\tcxt.Logf(\"error\", \"Caught error while serving: %s\", err)\n\t\tif router.HasRoute(\"@crash\") {\n\t\t\trouter.HandleRequest(\"@crash\", cxt, false)\n\t\t}\n\t}\n}", "func (s *Server) RunTLS(addr string, certPairs []CertPair) error {\n\tcfg := tls.Config{RootCAs: x509.NewCertPool()}\n\tcfg.Certificates = make([]tls.Certificate, 0, len(certPairs))\n\n\tfor _, cp := range certPairs {\n\t\tcert, err := tls.LoadX509KeyPair(cp.CertFile, cp.KeyFile)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s: %v\", cp.CertFile, err)\n\t\t}\n\t\tcfg.Certificates = append(cfg.Certificates, cert)\n\t}\n\n\tcfg.BuildNameToCertificate()\n\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrv := s.newHTTPServer(ln.Addr().String())\n\tsrv.TLSConfig = &cfg\n\n\ts.serversMux.Lock()\n\ts.servers = append(s.servers, srv)\n\ts.serversMux.Unlock()\n\n\tif s.opts.KeepAlivePeriod == -1 {\n\t\treturn srv.ServeTLS(ln, \"\", \"\")\n\t}\n\n\treturn srv.ServeTLS(&tcpKeepAliveListener{ln.(*net.TCPListener), s.opts.KeepAlivePeriod}, \"\", \"\")\n}", "func (srv *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {\n\t// Check if the driver implements the optional interface.\n\ttlsDriver, ok := srv.driver.(driver.TLSServer)\n\tif !ok {\n\t\treturn fmt.Errorf(\"driver %T does not support ListenAndServeTLS\", srv.driver)\n\t}\n\tsrv.init()\n\treturn tlsDriver.ListenAndServeTLS(addr, certFile, keyFile, srv.wrappedHandler)\n}", "func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {\n\tif s.opts.HTTPRedirectPort != 0 {\n\t\tmux := http.NewServeMux()\n\t\tmux.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n\t\t\tp := req.URL.Path\n\t\t\tif p != \"\" && p[0] != '/' {\n\t\t\t\tp = \"/\" + p\n\t\t\t}\n\t\t\thttp.Redirect(w, req, s.opts.ServerURL+p, http.StatusTemporaryRedirect)\n\t\t})\n\t\tgo http.ListenAndServe(fmt.Sprintf(\":%d\", s.opts.HTTPRedirectPort), mux)\n\t}\n\tconfig := &tls.Config{MinVersion: tls.VersionTLS10}\n\thttpserver := &http.Server{\n\t\tAddr: addr,\n\t\tTLSConfig: config,\n\t\tHandler: s.mux,\n\t}\n\treturn httpserver.ListenAndServeTLS(certFile, keyFile)\n}", "func (s *Server) RunTLS(addr, certFile, keyFile string) error {\n\tc, err := tlsConfig(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.listener, err = tls.Listen(network, addr, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.serve()\n}", "func ListenAndServeTLSKeyPair(addr string, cert tls.Certificate,\n\thandler http.Handler) error {\n\n\tif addr == \"\" {\n\t\treturn errors.New(\"Invalid address string\")\n\t}\n\n\tserver := &http.Server{Addr: addr, Handler: handler}\n\n\tconfig := &tls.Config{}\n\tconfig.NextProtos = []string{\"http/1.1\"}\n\tconfig.Certificates = make([]tls.Certificate, 1)\n\tconfig.Certificates[0] = cert\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)},\n\t\tconfig)\n\n\treturn server.Serve(tlsListener)\n}", "func (lb *LB) ServeTLS(tlsConfig *tls.Config, certFile, keyFile string) error {\n\tlisner, err := net.Listen(\"tcp\", lb.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlb.TLSConfig = tlsConfig\n\n\tglg.Success(\"Load Balancer starting on \" + lb.Addr)\n\terr = lb.Server.ServeTLS(lisner, certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (dd *DefaultDriver) ListenAndServeTLS(addr, certFile, keyFile string, h http.Handler) error {\n\tdd.Server.Addr = addr\n\tdd.Server.Handler = h\n\treturn dd.Server.ListenAndServeTLS(certFile, keyFile)\n}", "func (srv *Server) ListenAndServeTLS(addr string, tlsConfig *tls.Config, certFile, keyFile string) error {\n\tif srv.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer ln.Close()\n\n\treturn srv.ServeTLS(net_.TcpKeepAliveListener(ln.(*net.TCPListener), 3*time.Minute), tlsConfig, certFile, keyFile)\n}", "func (p *Proxy) ListenAndServeTLS(certFile, keyFile string) error {\n\tlistener, mux, err := p.listen()\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.Listener = listener\n\n\treturn rpcserver.ServeTLS(\n\t\tlistener,\n\t\tmux,\n\t\tcertFile,\n\t\tkeyFile,\n\t\tp.Logger,\n\t\tp.Config,\n\t)\n}", "func (s *Server) listenAndServe() (err error) {\n\n\tvar listener net.Listener\n\tvar clientAuth tls.ClientAuthType\n\tvar ok bool\n\n\tc := s.Config\n\n\t// Set default listening address and port\n\tif c.Address == \"\" {\n\t\tc.Address = DefaultServerAddr\n\t}\n\tif c.Port == 0 {\n\t\tc.Port = DefaultServerPort\n\t}\n\taddr := net.JoinHostPort(c.Address, strconv.Itoa(c.Port))\n\tvar addrStr string\n\n\tif c.TLS.Enabled {\n\t\tlog.Debug(\"TLS is enabled\")\n\t\taddrStr = fmt.Sprintf(\"https://%s\", addr)\n\n\t\t// If key file is specified and it does not exist or its corresponding certificate file does not exist\n\t\t// then need to return error and not start the server. The TLS key file is specified when the user\n\t\t// wants the server to use custom tls key and cert and don't want server to auto generate its own. So,\n\t\t// when the key file is specified, it must exist on the file system\n\t\tif c.TLS.KeyFile != \"\" {\n\t\t\tif !util.FileExists(c.TLS.KeyFile) {\n\t\t\t\treturn fmt.Errorf(\"File specified by 'tls.keyfile' does not exist: %s\", c.TLS.KeyFile)\n\t\t\t}\n\t\t\tif !util.FileExists(c.TLS.CertFile) {\n\t\t\t\treturn fmt.Errorf(\"File specified by 'tls.certfile' does not exist: %s\", c.TLS.CertFile)\n\t\t\t}\n\t\t\tlog.Debugf(\"TLS Certificate: %s, TLS Key: %s\", c.TLS.CertFile, c.TLS.KeyFile)\n\t\t} else if !util.FileExists(c.TLS.CertFile) {\n\t\t\t// TLS key file is not specified, generate TLS key and cert if they are not already generated\n\t\t\terr = s.autoGenerateTLSCertificateKey()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to automatically generate TLS certificate and key: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\tcer, err := util.LoadX509KeyPair(c.TLS.CertFile, c.TLS.KeyFile, s.csp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif c.TLS.ClientAuth.Type == \"\" {\n\t\t\tc.TLS.ClientAuth.Type = defaultClientAuth\n\t\t}\n\n\t\tlog.Debugf(\"Client authentication type requested: %s\", c.TLS.ClientAuth.Type)\n\n\t\tauthType := strings.ToLower(c.TLS.ClientAuth.Type)\n\t\tif clientAuth, ok = clientAuthTypes[authType]; !ok {\n\t\t\treturn errors.New(\"Invalid client auth type provided\")\n\t\t}\n\n\t\tvar certPool *x509.CertPool\n\t\tif authType != defaultClientAuth {\n\t\t\tcertPool, err = LoadPEMCertPool(c.TLS.ClientAuth.CertFiles)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tconfig := &tls.Config{\n\t\t\tCertificates: []tls.Certificate{*cer},\n\t\t\tClientAuth: clientAuth,\n\t\t\tClientCAs: certPool,\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tMaxVersion: tls.VersionTLS13,\n\t\t\tCipherSuites: stls.DefaultCipherSuites,\n\t\t}\n\n\t\tlistener, err = tls.Listen(\"tcp\", addr, config)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"TLS listen failed for %s\", addrStr)\n\t\t}\n\t} else {\n\t\taddrStr = fmt.Sprintf(\"http://%s\", addr)\n\t\tlistener, err = net.Listen(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"TCP listen failed for %s\", addrStr)\n\t\t}\n\t}\n\ts.listener = listener\n\tlog.Infof(\"Listening on %s\", addrStr)\n\n\terr = s.checkAndEnableProfiling()\n\tif err != nil {\n\t\ts.closeListener()\n\t\treturn errors.WithMessage(err, \"TCP listen for profiling failed\")\n\t}\n\n\t// Start serving requests, either blocking or non-blocking\n\tif s.BlockingStart {\n\t\treturn s.serve()\n\t}\n\ts.wait = make(chan bool)\n\tgo s.serve()\n\n\treturn nil\n}", "func (m *cMux) ListenAndServeTLS(addr string, tlsConfig *tls.Config, certFile, keyFile string) error {\n\tif m.shuttingDown() {\n\t\treturn ErrServerClosed\n\t}\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer ln.Close()\n\n\treturn m.ServeTLS(net_.TcpKeepAliveListener(ln.(*net.TCPListener), 3*time.Minute), tlsConfig, certFile, keyFile)\n}", "func (srv *TCPServer) ListenAndServeTLS(certFile, keyFile string) error {\n\taddr := srv.Addr\n\tl, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn srv.ServeTLS(l, certFile, keyFile)\n}", "func (self *Proxy) StartTLS(cert string, key string) error {\n\n\tself.srv = http.Server{\n\t\tAddr: self.Bind,\n\t\tHandler: self,\n\t}\n\n\tlog.Printf(\"Listening for HTTPs client request at %s.\\n\", self.Bind)\n\n\treturn self.srv.ListenAndServeTLS(cert, key)\n}", "func (r *Router) RunTLS(addr, certFile, keyFile string) error {\n\treturn http.ListenAndServeTLS(addr, certFile, keyFile, r.chain())\n}", "func (r *Router) ListenAndServeFreeTLS(domain, certDir string) error {\n\t// Assign the router to the server handler\n\tr.Server.Handler = r.Router\n\tr.Server.Addr = \":https\"\n\n\t// Set up a cert manager that will retrieve configured SSL certs\n\t// for your domain\n\tcertManager := autocert.Manager{\n\t\tPrompt: autocert.AcceptTOS,\n\t\tHostPolicy: autocert.HostWhitelist(domain), // Your domain here\n\t\tCache: autocert.DirCache(\"certs\"), // Folder for storing certificates\n\t}\n\n\t// Set the GetCertificate func on the TLS config\n\tr.Server.TLSConfig = &tls.Config{\n\t\tGetCertificate: certManager.GetCertificate,\n\t}\n\n\t// HTTP needed for LetsEncrypt security issue. HTTP should however\n\t// redirect to HTTPS\n\tgo http.ListenAndServe(\":http\", certManager.HTTPHandler(nil))\n\n\t// Begin listening for TLS requests\n\treturn r.Server.ListenAndServeTLS(\"\", \"\")\n}", "func (r *Router) RunTLS(addr, certFile, keyFile string) {\n\tr.server.Addr = addr\n\tr.server.Handler = r\n\tr.logger.Printf(\"listening tls on %s\", addr)\n\tr.logger.Fatal(r.server.ListenAndServeTLS(certFile, keyFile))\n}", "func (s *ProxyServer) serveGenericTLS(listener net.Listener, tlsConfig *tls.Config, dbName string) error {\n\ts.log.Debugf(\"Started %s proxy.\", dbName)\n\tdefer s.log.Debugf(\"%s proxy exited.\", dbName)\n\tfor {\n\t\tclientConn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tif utils.IsOKNetworkError(err) || trace.IsConnectionProblem(err) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\n\t\tgo func() {\n\t\t\tdefer clientConn.Close()\n\t\t\ttlsConn := tls.Server(clientConn, tlsConfig)\n\t\t\tif err := tlsConn.Handshake(); err != nil {\n\t\t\t\tif !utils.IsOKNetworkError(err) {\n\t\t\t\t\ts.log.WithError(err).Errorf(\"%s TLS handshake failed.\", dbName)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr := s.handleConnection(tlsConn)\n\t\t\tif err != nil {\n\t\t\t\ts.log.WithError(err).Errorf(\"Failed to handle %s client connection.\", dbName)\n\t\t\t}\n\t\t}()\n\t}\n}", "func (s *ProxyServer) ServeTLS(listener net.Listener) error {\n\ts.log.Debug(\"Started database TLS proxy.\")\n\tdefer s.log.Debug(\"Database TLS proxy exited.\")\n\tfor {\n\t\tclientConn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tif utils.IsOKNetworkError(err) || trace.IsConnectionProblem(err) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t\tgo func() {\n\t\t\tdefer clientConn.Close()\n\t\t\terr := s.handleConnection(clientConn)\n\t\t\tif err != nil {\n\t\t\t\ts.log.WithError(err).Error(\"Failed to handle database TLS connection.\")\n\t\t\t}\n\t\t}()\n\t}\n}", "func (r *Router) ListenAndServeTLS(port int, certFile, keyFile string) error {\n\t// Assign the router to the server handler\n\tr.Server.Handler = r.Router\n\tr.Server.Addr = \":\" + strconv.Itoa(port)\n\n\t// Begin listening for TLS requests\n\treturn r.Server.ListenAndServeTLS(certFile, keyFile)\n}", "func (s *WebsocketServer) ListenAndServeTLS(address string, tlscfg *tls.Config, certFile, keyFile string) (io.Closer, error) { //nolint:lll\n\t// Load certificate here, instead of in ServeTLS, to check for error before\n\t// serving.\n\tvar hasCert bool\n\tif tlscfg == nil {\n\t\ttlscfg = &tls.Config{}\n\t} else if len(tlscfg.Certificates) > 0 || tlscfg.GetCertificate != nil {\n\t\thasCert = true\n\t}\n\n\tif !hasCert || certFile != \"\" || keyFile != \"\" {\n\t\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error loading X509 key pair: %w\", err)\n\t\t}\n\t\ttlscfg.Certificates = append(tlscfg.Certificates, cert)\n\t}\n\n\t// Call Listen separate from Serve to check for error listening.\n\tl, err := net.Listen(\"tcp\", address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Run service on configured port.\n\tserver := &http.Server{\n\t\tHandler: s,\n\t\tAddr: l.Addr().String(),\n\t\tTLSConfig: tlscfg,\n\t}\n\tgo server.ServeTLS(l, \"\", \"\")\n\treturn l, nil\n}", "func (server *Server) runServerTLS() {\n\tserver.G.Go(func() error {\n\t\tserver.API.log.Info(\"running server TLS %v\", server.config.Server.ListenAddr)\n\t\treturn http.ListenAndServeTLS(server.config.Server.HTTPSAddr, server.config.TLS.CertFile, server.config.TLS.KeyFile, server.Server.Handler)\n\t})\n}", "func (s *Server) Serve(lis net.Listener) {\n\thttpsrv := &http.Server{\n\t\tTLSConfig: s.opts.creds.Config,\n\t}\n\thttp.HandleFunc(\"/\", s.wshandler)\n\tgo httpsrv.ServeTLS(lis, \"\", \"\")\n\tdefer httpsrv.Close()\n\n\ts.httpsrv = httpsrv\n\n\t<-s.done.Done()\n}", "func (s *Server) ListenAndServeTLS() error {\n\tif s.LMTP {\n\t\treturn errTCPAndLMTP\n\t}\n\n\taddr := s.Addr\n\tif addr == \"\" {\n\t\taddr = \":smtps\"\n\t}\n\n\tl, err := tls.Listen(\"tcp\", addr, s.TLSConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.Serve(l)\n}", "func (a *TCPAcceptor) ListenAndServeTLS(cert, key string) {\n\tcrt, err := tls.LoadX509KeyPair(cert, key)\n\tif err != nil {\n\t\tlogger.Log.Fatalf(\"Failed to listen: %s\", err.Error())\n\t}\n\n\ta.certs = append(a.certs, crt)\n\n\ta.listenAndServeTLS()\n}", "func NewServerTLS(addr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n\tconfig *tls.Config,\n) *TLSServer {\n\treturn NewServerNetworkTLS(\"tcp\", addr, handler, accept, closed, config)\n}", "func (s *Server) Start() error {\n\tif s.Handler == nil {\n\t\treturn errors.New(\"No server handler set\")\n\t}\n\n\tif s.listener != nil {\n\t\treturn errors.New(\"Server already started\")\n\t}\n\n\taddr := s.Addr\n\tif addr == \"\" {\n\t\taddr = \":http\"\n\t}\n\n\tlistener, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif s.secureConnection {\n\t\tlogger.RootLogger().Debug(\"Reading certificates\")\n\t\tprivateKey, err := s.decodeCertificate(s.serverKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tCACertificate, err := s.decodeCertificate(s.caCertificate)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttlsConfig := &tls.Config{}\n\t\tfinalCert, err := tls.X509KeyPair(CACertificate, privateKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttlsConfig.Certificates = []tls.Certificate{finalCert}\n\t\tlistener = tls.NewListener(listener, tlsConfig)\n\t}\n\n\thostname, _ := os.Hostname()\n\ts.serverInstanceID = fmt.Sprintf(\"%x\", md5.Sum([]byte(hostname+addr)))\n\n\ts.listener = listener\n\ts.serverGroup = &sync.WaitGroup{}\n\ts.clientsGroup = make(chan bool, 50000)\n\n\t//if s.ErrorLog == nil {\n\t// if r, ok := s.Handler.(ishttpwayrouter); ok {\n\t// s.ErrorLog = log.New(&internalServerLoggerWriter{r.(*Router).Logger}, \"\", 0)\n\t// }\n\t//}\n\t//\n\ts.Handler = &serverHandler{s.Handler, s.clientsGroup, s.serverInstanceID}\n\n\ts.serverGroup.Add(1)\n\tgo func() {\n\t\tdefer s.serverGroup.Done()\n\n\t\terr := s.Serve(listener)\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts.lastError = err\n\t\t}\n\t}()\n\n\treturn nil\n}", "func (s *Server) ListenAndServeTLS(ctx context.Context) error {\n\taddr := s.Addr\n\tif addr == \"\" {\n\t\taddr = \":domain\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.ServeTLS(ctx, ln)\n}", "func ListenAndServeTLS(addr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n\tconfig *tls.Config,\n) error {\n\treturn ListenAndServeNetworkTLS(\"tcp\", addr, handler, accept, closed, config)\n}", "func (a *TCPAcceptor) listenAndServeTLS() {\n\ttlsCfg := &tls.Config{Certificates: a.certs}\n\n\tlistener, err := tls.Listen(\"tcp\", a.addr, tlsCfg)\n\tif err != nil {\n\t\tlogger.Log.Fatalf(\"Failed to listen: %s\", err.Error())\n\t}\n\ta.listener = listener\n\ta.running = true\n\ta.serve()\n}", "func ListenAndServeTLSAsync(server *http.Server, certFile, keyFile string) error {\n\t// Start listening synchronously.\n\tlistener, err := net.Listen(tcpNetwork.Value, server.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Unlike ListenAndServeAsync we don't update the server's Addr when the\n\t// server.Addr ends with :0, because the resulting URL may or may not be\n\t// GET-able. In ipv6-only contexts it could be, for example, \"[::]:3232\", and\n\t// that URL can't be used for TLS because TLS needs a name or an explicit IP\n\t// and [::] doesn't qualify. It is unclear what the right thing to do is in\n\t// this situation, because names and IPs and TLS are suffciently complicated\n\t// that no one thing is the right thing in all situations, so we affirmatively\n\t// do nothing in an attempt to avoid making a bad situation worse.\n\n\t// Serve asynchronously.\n\tgo serveTLS(server, tcpKeepAliveListener{listener.(*net.TCPListener)}, certFile, keyFile)\n\treturn nil\n}", "func startHTTPSListener(service, certFile, keyFile string) error {\n\ts := http.Server{}\n\n\t// If certFile and/or keyFile are blank, generate a self-signed TLS cert\n\tif len(certFile) == 0 || len(keyFile) == 0 {\n\t\tselfSignedCert, err := privatetls.NewCert()\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ts.TLSConfig = &tls.Config{\n\t\t\tCertificates: []tls.Certificate{selfSignedCert},\n\t\t}\n\t}\n\n\ts.Addr = service\n\n\treturn s.ListenAndServeTLS(certFile, keyFile)\n}", "func (ts *TcpServer) StartTlsServer(port string) (err error) {\n\n\tbelogs.Debug(\"StartTlsServer(): tlsserver port:\", port)\n\tcert, err := tls.LoadX509KeyPair(ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver LoadX509KeyPair fail: port:\", port,\n\t\t\t\" tlsPublicCrtFileName, tlsPrivateKeyFileName:\", ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver cert:\", ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName)\n\n\trootCrtBytes, err := ioutil.ReadFile(ts.tlsRootCrtFileName)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver ReadFile tlsRootCrtFileName fail, port:\", port,\n\t\t\t\" tlsRootCrtFileName:\", ts.tlsRootCrtFileName, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver len(rootCrtBytes):\", len(rootCrtBytes), \" tlsRootCrtFileName:\", ts.tlsRootCrtFileName)\n\n\trootCertPool := x509.NewCertPool()\n\tok := rootCertPool.AppendCertsFromPEM(rootCrtBytes)\n\tif !ok {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver AppendCertsFromPEM tlsRootCrtFileName fail,port:\", port,\n\t\t\t\" tlsRootCrtFileName:\", ts.tlsRootCrtFileName, \" len(rootCrtBytes):\", len(rootCrtBytes), err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver AppendCertsFromPEM len(rootCrtBytes):\", len(rootCrtBytes), \" tlsRootCrtFileName:\", ts.tlsRootCrtFileName)\n\n\tclientAuthType := tls.NoClientCert\n\tif ts.tlsVerifyClient {\n\t\tclientAuthType = tls.RequireAndVerifyClientCert\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver clientAuthType:\", clientAuthType)\n\n\t// https://stackoverflow.com/questions/63676241/how-to-set-setkeepaliveperiod-on-a-tls-conn\n\tsetTCPKeepAlive := func(clientHello *tls.ClientHelloInfo) (*tls.Config, error) {\n\t\t// Check that the underlying connection really is TCP.\n\t\tif tcpConn, ok := clientHello.Conn.(*net.TCPConn); ok {\n\t\t\ttcpConn.SetKeepAlive(true)\n\t\t\ttcpConn.SetKeepAlivePeriod(time.Second * 300)\n\t\t\tbelogs.Debug(\"StartTlsServer(): tlsserver SetKeepAlive:\")\n\t\t}\n\t\t// Make sure to return nil, nil to let the caller fall back on the default behavior.\n\t\treturn nil, nil\n\t}\n\tconfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tClientAuth: clientAuthType,\n\t\tRootCAs: rootCertPool,\n\t\tInsecureSkipVerify: false,\n\t\tGetConfigForClient: setTCPKeepAlive,\n\t}\n\tlistener, err := tls.Listen(\"tcp\", \":\"+port, config)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver Listen fail, port:\", port, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): Listen ok, port:\", port)\n\n\t// get tcpListener\n\tts.tcpListener, err = NewFromTlsListener(listener)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver NewFromTlsListener fail, port: \", port, err)\n\t\treturn err\n\t}\n\tbelogs.Info(\"StartTlsServer(): tlsserver create server ok, port:\", port, \" will accept client\")\n\n\tgo ts.waitBusinessToConnMsg()\n\n\t// wait new conn\n\tts.acceptNewConn()\n\treturn nil\n}", "func (s *Server) Listen(\n\taddr string,\n\tcertPath string,\n\tkeyPath string,\n) (err error) {\n\tlogger := logger.Logger()\n\tif err = s.init(); err != nil {\n\t\treturn\n\t}\n\n\topts := []grpc.ServerOption{}\n\ttlsFlag := false\n\n\tif certPath != \"\" && keyPath != \"\" {\n\t\tcreds, err := credentials.NewServerTLSFromFile(certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\topts = append(opts, grpc.Creds(creds))\n\t\ttlsFlag = true\n\t}\n\n\ts.grpcServer = grpc.NewServer(opts...)\n\tpb.RegisterEchoServer(s.grpcServer, s)\n\n\thttpMux := http.NewServeMux()\n\thttpMux.HandleFunc(\"/\", s.httpEchoPing)\n\n\trootMux := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.ProtoMajor == 2 && strings.Contains(req.Header.Get(\"Content-Type\"), \"application/grpc\") {\n\t\t\ts.grpcServer.ServeHTTP(w, req)\n\t\t} else {\n\t\t\thttpMux.ServeHTTP(w, req)\n\t\t}\n\t})\n\n\ts.httpServer = &http.Server{\n\t\tAddr: addr,\n\t\tHandler: h2c.NewHandler(rootMux, &http2.Server{}),\n\t}\n\n\tlogger.Printf(\"grpc listen address: %q tls: %v\", addr, tlsFlag)\n\tif tlsFlag {\n\t\treturn s.httpServer.ListenAndServeTLS(certPath, keyPath)\n\t}\n\treturn s.httpServer.ListenAndServe()\n}", "func (s *Server) DispatchTLS(certFile, keyFile string) error {\n\thandler := cors.Default().Handler(s.router)\n\tlistener, err := net.Listen(\"tcp\", s.listenAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.log.Info(\"API server listening on %q\", s.listenAddress)\n\treturn http.ServeTLS(listener, handler, certFile, keyFile)\n}", "func ListenAndServeNetworkTLS(\n\tnet, laddr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n\tconfig *tls.Config,\n) error {\n\treturn NewServerNetworkTLS(net, laddr, handler, accept, closed, config).ListenAndServe()\n}", "func (s *WebhookServer) Start() error {\n\t// Load server certificate.\n\tkeyPair, err := tls.LoadX509KeyPair(\n\t\ts.Settings.ServerCertPath,\n\t\ts.Settings.ServerKeyPath,\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"load TLS certs: %v\", err)\n\t}\n\n\t// Construct a hostname for certificate.\n\thost := fmt.Sprintf(\"%s.%s\",\n\t\ts.Settings.ServiceName,\n\t\ts.Namespace,\n\t)\n\n\ttlsConf := &tls.Config{\n\t\tCertificates: []tls.Certificate{keyPair},\n\t\tServerName: host,\n\t}\n\n\t// Load client CA if defined\n\tif len(s.Settings.ClientCAPaths) > 0 {\n\t\troots := x509.NewCertPool()\n\n\t\tfor _, caPath := range s.Settings.ClientCAPaths {\n\t\t\tcaBytes, err := os.ReadFile(caPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"load client CA '%s': %v\", caPath, err)\n\t\t\t}\n\n\t\t\tok := roots.AppendCertsFromPEM(caBytes)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"parse client CA '%s': %v\", caPath, err)\n\t\t\t}\n\t\t}\n\n\t\ttlsConf.ClientAuth = tls.RequireAndVerifyClientCert\n\t\ttlsConf.ClientCAs = roots\n\t}\n\n\tlistenAddr := net.JoinHostPort(s.Settings.ListenAddr, s.Settings.ListenPort)\n\t// Check if port is available\n\tlistener, err := net.Listen(\"tcp\", listenAddr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"try listen on '%s': %v\", listenAddr, err)\n\t}\n\n\ttimeout := time.Duration(10) * time.Second\n\n\tsrv := &http.Server{\n\t\tHandler: s.Router,\n\t\tTLSConfig: tlsConf,\n\t\tAddr: listenAddr,\n\t\tIdleTimeout: timeout,\n\t\tReadTimeout: timeout,\n\t\tReadHeaderTimeout: timeout,\n\t}\n\n\tgo func() {\n\t\tlog.Infof(\"Webhook server listens on %s\", listenAddr)\n\t\terr := srv.ServeTLS(listener, \"\", \"\")\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error starting Webhook https server: %v\", err)\n\t\t\t// Stop process if server can't start.\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\treturn nil\n}", "func ListenAndServe(addr, certFile, keyFile string, handler http.Handler) error {\n\t// Load certs\n\tvar err error\n\tcerts := make([]tls.Certificate, 1)\n\tcerts[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// We currently only use the cert-related stuff from tls.Config,\n\t// so we don't need to make a full copy.\n\tconfig := &tls.Config{\n\t\tCertificates: certs,\n\t}\n\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\t// Open the listeners\n\tudpAddr, err := net.ResolveUDPAddr(\"udp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tudpConn, err := net.ListenUDP(\"udp\", udpAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer udpConn.Close()\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\t// Start the servers\n\tquicServer := &Server{\n\t\tTLSConfig: config,\n\t\tHandler: handler,\n\t}\n\n\thErr := make(chan error)\n\tqErr := make(chan error)\n\tgo func() {\n\t\thErr <- http.ListenAndServeTLS(addr, certFile, keyFile, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tquicServer.SetQuicHeaders(w.Header())\n\t\t\thandler.ServeHTTP(w, r)\n\t\t}))\n\t}()\n\tgo func() {\n\t\tqErr <- quicServer.Serve(udpConn)\n\t}()\n\n\tselect {\n\tcase err := <-hErr:\n\t\tquicServer.Close()\n\t\treturn err\n\tcase err := <-qErr:\n\t\t// Cannot close the HTTP server or wait for requests to complete properly :/\n\t\treturn err\n\t}\n}", "func (s *Server) StartTLS() {\n\tif s.URL != \"\" {\n\t\tpanic(\"Server already started\")\n\t}\n\tcert, err := tls.X509KeyPair(internal.LocalhostCert, internal.LocalhostKey)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"amqptest: NewTLSServer: %v\", err))\n\t}\n\n\texistingConfig := s.TLS\n\ts.TLS = new(tls.Config)\n\tif existingConfig != nil {\n\t\t*s.TLS = *existingConfig\n\t}\n\tif s.TLS.NextProtos == nil {\n\t\ts.TLS.NextProtos = []string{\"amqp/0-9-1\"}\n\t}\n\tif len(s.TLS.Certificates) == 0 {\n\t\ts.TLS.Certificates = []tls.Certificate{cert}\n\t}\n\ts.Listener = tls.NewListener(s.Listener, s.TLS)\n\ts.URL = \"amqps://\" + s.Listener.Addr().String()\n\ts.goServe()\n}", "func (s *Server) StartTLS() {\n\tif s.URL != \"\" {\n\t\tpanic(\"Server already started\")\n\t}\n\ts.setupTLS()\n\ts.Listener = tls.NewListener(s.Listener, s.Config.TLSConfig)\n\ts.URL = \"ftps://\" + s.Listener.Addr().String()\n\ts.goServe()\n}", "func (aps *ApiServer) RunTLS() error {\n\treturn aps.Engine.RunTLS(aps.ipAddr+\":\"+strconv.Itoa(aps.port), aps.certFile, aps.keyFile)\n}", "func (srv *Server) Serve(l net.Listener) error {\n\tif fn := testHookServerServe; fn != nil {\n\t\tfn(srv, l) // call hook with unwrapped listener\n\t}\n\n\torigListener := l\n\tl = &onceCloseListener{Listener: l}\n\tdefer l.Close()\n\n\tif err := srv.setupHTTP2_Serve(); err != nil {\n\t\treturn err\n\t}\n\n\tif !srv.trackListener(&l, true) {\n\t\treturn ErrServerClosed\n\t}\n\tdefer srv.trackListener(&l, false)\n\n\tbaseCtx := context.Background()\n\tif srv.BaseContext != nil {\n\t\tbaseCtx = srv.BaseContext(origListener)\n\t\tif baseCtx == nil {\n\t\t\tpanic(\"BaseContext returned a nil context\")\n\t\t}\n\t}\n\n\tvar tempDelay time.Duration // how long to sleep on accept failure\n\n\tctx := context.WithValue(baseCtx, ServerContextKey, srv)\n\tfor {\n\t\trw, err := l.Accept()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-srv.getDoneChan():\n\t\t\t\treturn ErrServerClosed\n\t\t\tdefault:\n\t\t\t}\n\t\t\tif ne, ok := err.(net.Error); ok && ne.Temporary() {\n\t\t\t\tif tempDelay == 0 {\n\t\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\ttempDelay *= 2\n\t\t\t\t}\n\t\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\t\ttempDelay = max\n\t\t\t\t}\n\t\t\t\tsrv.logf(\"http: Accept error: %v; retrying in %v\", err, tempDelay)\n\t\t\t\ttime.Sleep(tempDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tconnCtx := ctx\n\t\tif cc := srv.ConnContext; cc != nil {\n\t\t\tconnCtx = cc(connCtx, rw)\n\t\t\tif connCtx == nil {\n\t\t\t\tpanic(\"ConnContext returned nil\")\n\t\t\t}\n\t\t}\n\t\ttempDelay = 0\n\t\tc := srv.newConn(rw)\n\t\tc.setState(c.rwc, StateNew, runHooks) // before Serve can return\n\t\tgo c.serve(connCtx)\n\t}\n}", "func listen() error {\n\t// define https variable\n\taddress := config.Get(\"https\", \"address\")\n\tcertificate := config.Get(\"https\", \"certificate\")\n\tkey := config.Get(\"https\", \"key\")\n\n\t// return error\n\treturn http.ListenAndServeTLS(address, certificate, key, nil)\n}", "func RunTLS() {\n\tApp.Init()\n\n\tif Config.String(\"cert\") == \"\" || Config.String(\"cert_key\") == \"\" {\n\t\tpanic(\"Invalid cert files or key. Please review your configuration.\")\n\t}\n\n\tif Config.String(\"address\") != \"\" {\n\t\tLog.Info(fmt.Sprintf(\"listening TLS on %s\", Config.String(\"address\")))\n\t\tLog.Error(http.ListenAndServeTLS(Config.String(\"address\"), Config.String(\"cert\"), Config.String(\"cert_key\"), App.Router))\n\t} else {\n\t\tLog.Info(fmt.Sprintf(\"listening TLS on port :%d\", Config.Int(\"port\")))\n\t\tLog.Error(http.ListenAndServeTLS(fmt.Sprintf(\":%d\", Config.Int(\"port\")), Config.String(\"cert\"), Config.String(\"cert_key\"), App.Router))\n\t}\n}", "func RunTLS(addr string, config *tls.Config) {\n\tmainServer.RunTLS(addr, config)\n}", "func (s *PingServer) ServeTLS(port uint) error {\n\t// Initialize server variables\n\ts.sequence = make(map[string]int64)\n\taddr := fmt.Sprintf(\":%d\", port)\n\n\t// Create the TLS credentials\n\tcreds, err := credentials.NewServerTLSFromFile(ServerCert, ServerKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not load TLS keys: %s\", err)\n\t}\n\n\t// Create the gRPC server with the gredentials\n\ts.srv = grpc.NewServer(grpc.Creds(creds))\n\n\t// Register the handler object\n\tpb.RegisterSecurePingServer(s.srv, s)\n\n\t// Create the channel to listen on\n\tlis, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not listen on %s: %s\", addr, err)\n\t}\n\n\t// Serve and Listen\n\tif err := s.srv.Serve(lis); err != nil {\n\t\treturn fmt.Errorf(\"grpc serve error: %s\", err)\n\t}\n\n\treturn nil\n}", "func httpsServer(\n\tserverUsername string,\n\tserverPassword string,\n\ttlsCert string,\n\ttlsKey string,\n) (*httptest.Server, error) {\n\ts, err := testServer(serverUsername, serverPassword)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcert, err := tls.LoadX509KeyPair(tlsCert, tlsKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tMinVersion: tls.VersionTLS12,\n\t}\n\ts.TLS = config\n\n\ts.StartTLS()\n\treturn s, nil\n}", "func serveHTTPS(ech chan<- error, addr, cert, key string) {\n\tif \"\" == addr || NO == addr {\n\t\treturn\n\t}\n\t/* Listen */\n\tl, err := net.Listen(\"tcp\", addr)\n\tif nil != err {\n\t\tech <- err\n\t\treturn\n\t}\n\tlog.Printf(\"Serving HTTPS requests on %v\", l.Addr())\n\t/* Serve */\n\tech <- http.ServeTLS(l, nil, cert, key)\n}", "func (c *Client) InitTLS(certFile string) error {\n\tserverCert, err := ioutil.ReadFile(certFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tCA_Pool := x509.NewCertPool()\n\tCA_Pool.AppendCertsFromPEM(serverCert)\n\tc.mutex.Lock()\n\tc.rootCAs = CA_Pool\n\tc.mutex.Unlock()\n\tif c.agentProvider != nil {\n\t\treturn c.agentProvider.Refresh()\n\t}\n\treturn nil\n}", "func (s *Server) Listen() (cancel func()) {\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\terr := s.srv.ListenAndServeTLS(s.certPath, s.keyPath)\n\t\tif err != nil && err != http.ErrServerClosed {\n\t\t\ts.t.Fatalf(\"ListenFederationServer: ListenAndServeTLS failed: %s\", err)\n\t\t}\n\t}()\n\n\treturn func() {\n\t\terr := s.srv.Shutdown(context.Background())\n\t\tif err != nil {\n\t\t\ts.t.Fatalf(\"ListenFederationServer: failed to shutdown server: %s\", err)\n\t\t}\n\t\twg.Wait() // wait for the server to shutdown\n\t}\n}", "func SMTPServerTLS(t *testing.T, addr string, fn ...SMTPServerConfigureFunc) (*tls.Config, *SMTPBackend, *smtp.Server) {\n\tt.Helper()\n\n\tcert, err := tls.X509KeyPair([]byte(testServerCert), []byte(testServerKey))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := tls.Listen(\"tcp\", addr, &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbe := new(SMTPBackend)\n\ts := smtp.NewServer(be)\n\ts.Domain = \"localhost\"\n\tfor _, f := range fn {\n\t\tf(s)\n\t}\n\n\tpool := x509.NewCertPool()\n\tpool.AppendCertsFromPEM([]byte(testServerCert))\n\n\tclientCfg := &tls.Config{\n\t\tServerName: \"127.0.0.1\",\n\t\tTime: func() time.Time {\n\t\t\treturn time.Date(2019, time.November, 18, 17, 59, 41, 0, time.UTC)\n\t\t},\n\t\tRootCAs: pool,\n\t}\n\n\tgo func() {\n\t\tif err := s.Serve(l); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\t// Dial it once it make sure Server completes its initialization before\n\t// we try to use it. Notably, if test fails before connecting to the server,\n\t// it will call Server.Close which will call Server.listener.Close with a\n\t// nil Server.listener (Serve sets it to a non-nil value, so it is racy and\n\t// happens only sometimes).\n\ttestConn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttestConn.Close()\n\n\treturn clientCfg, be, s\n}", "func (s *Server) ServeHTTPS(addr string, tlsConfig *tls.Config) error {\n\n\thttp.HandleFunc(\"/wsman/SubscriptionManager/WEC\",\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\ts.subscriptionManager(w, r)\n\t\t})\n\thttp.HandleFunc(\"/wsman/subscriptions/\",\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\ts.subscriptions(w, r)\n\t\t})\n\thttp.HandleFunc(\"/\",\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tdump, err := httputil.DumpRequest(r, true)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, fmt.Sprint(err), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Printf(\"Unhandled request:\\n%s\\n\", dump)\n\t\t\thttp.Error(w, \"Not implemented yet\", http.StatusNotImplemented)\n\t\t})\n\thttpd := &http.Server{\n\t\tAddr: addr,\n\t\tTLSConfig: tlsConfig,\n\t}\n\tlog.Printf(\"WEF HTTPS: listening at %s\\n\", addr)\n\treturn httpd.ListenAndServeTLS(\"\", \"\")\n}", "func WithTLS(cert, key string) ServerOption {\n\treturn func(opt *ServerConfig) error {\n\t\topt.TLS = true\n\t\topt.certFile = cert\n\t\topt.keyFile = key\n\t\treturn nil\n\t}\n}", "func (c *Client) InitTLS(certFile string) error {\n\tserverCert, err := ioutil.ReadFile(certFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tCA_Pool := x509.NewCertPool()\n\tCA_Pool.AppendCertsFromPEM(serverCert)\n\tc.tlsConfig = &tls.Config{RootCAs: CA_Pool}\n\treturn nil\n}", "func LoadServerTLSConfig(sslCA, sslCert, sslCertKey string) (*tls.Config, error) {\n\tcertPEM, err := assetLoaderImpl.ReadFile(sslCert)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyPEM, err := assetLoaderImpl.ReadFile(sslCertKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcaPEM, err := assetLoaderImpl.ReadFile(sslCA)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newServerTLSConfig(certPEM, keyPEM, caPEM)\n}", "func ListenTLS(network, addr string, config *tls.Config) (net.Listener, error) {\n\tlis, err := tls.Listen(network, addr, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn WrapListener(lis), nil\n}", "func (r *Router) Serve() {\n\tvar err error\n\tif conf.Options.SSL.Cert != \"\" {\n\t\t// First, listen on the HTTP address with redirect\n\t\tgo func() {\n\t\t\terr := http.ListenAndServe(conf.Options.HTTPAddress, http.HandlerFunc(redirectToHTTPS))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}()\n\t\taddr := conf.Options.Address\n\t\tif addr == \"\" {\n\t\t\taddr = \":https\"\n\t\t}\n\t\tserver := &http.Server{Addr: conf.Options.Address, Handler: r}\n\t\tconfig := &tls.Config{NextProtos: []string{\"http/1.1\"}}\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.X509KeyPair([]byte(conf.Options.SSL.Cert), []byte(conf.Options.SSL.Key))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tln, err := net.Listen(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\ttlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, config)\n\t\terr = server.Serve(tlsListener)\n\t} else {\n\t\terr = http.ListenAndServe(conf.Options.Address, r)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\thomeDir, err := os.UserHomeDir()\n\tif err != nil {\n\t\tlog.Fatal(\"error in getting home directory\")\n\t}\n\tsslCertDirArg := flag.String(\"d\", homeDir+\"/ssl-local-cert\", \"the directory of SSL cert\")\n\tsslCrtNameArg := flag.String(\"c\", \"test.iw.com.pem\", \"the filename of SSL cert\")\n\tsslKeyNameArg := flag.String(\"k\", \"test.iw.com-key.pem\", \"the filename of SSL key\")\n\tflag.Parse()\n\n\tif string((*sslCrtNameArg)[0]) != \"/\" {\n\t\t*sslCrtNameArg = \"/\" + *sslCrtNameArg\n\t}\n\tif string((*sslKeyNameArg)[0]) != \"/\" {\n\t\t*sslKeyNameArg = \"/\" + *sslKeyNameArg\n\t}\n\tsslCertCrtPath := *sslCertDirArg + *sslCrtNameArg\n\tsslCertKeyPath := *sslCertDirArg + *sslKeyNameArg\n\n\tfmt.Println(sslCertCrtPath)\n\tfmt.Println(sslCertKeyPath)\n\n\t// create file server handler serving current directory\n\tfs := http.FileServer(http.Dir(\".\"))\n\n\t// start HTTP server with `fs` as the default handler\n\tfmt.Println(\"server run with :9000 and :443\")\n\tlog.Fatal(http.ListenAndServeTLS(\":443\", sslCertCrtPath, sslCertKeyPath, fs))\n\tlog.Fatal(http.ListenAndServe(\":9000\", fs))\n\n}", "func Listen(port string) error {\n\tlog.Info(fmt.Sprintf(\"secure listener started on port: %s\", port), log.AppLog, map[string]interface{}{})\n\n\tcer, err := tls.LoadX509KeyPair(\"server.crt\", \"server.key\")\n\tif err != nil {\n\t\tlog.Error(err.Error(), log.AppLog, map[string]interface{}{})\n\t\treturn err\n\t}\n\n\tcfg := &tls.Config{\n\t\tMinVersion: tls.VersionTLS12,\n\t\tCertificates: []tls.Certificate{cer},\n\t}\n\n\tlistener, err := tls.Listen(\"tcp\", fmt.Sprintf(\":%s\", port), cfg)\n\tif err != nil {\n\t\tlog.Error(err.Error(), log.AppLog, map[string]interface{}{})\n\t\treturn err\n\t}\n\tdefer listener.Close()\n\n\tfor {\n\t\tif conn, err := listener.Accept(); err != nil {\n\t\t\tlog.Error(err.Error(), log.AppLog, map[string]interface{}{})\n\t\t} else {\n\t\t\thandleConnection(conn)\n\t\t}\n\t}\n}", "func (s *FrontendServer) Run(tls bool, certFile string,\n\tkeyFile string) error {\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", s.hostname, s.port))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\tvar lis2 net.Listener\n\tif (s.hostnameGw != \"\") && (s.portGw != 0) {\n\t\tlis2, err = net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", s.hostnameGw, s.portGw))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to listen on second address: %v\", err)\n\t\t}\n\t}\n\tvar opts []grpc.ServerOption\n\tif tls {\n\t\t// if caFile == \"\" {\n\t\t// \tset default caFile path\n\t\t// }\n\t\t// if keyFile == \"\" {\n\t\t// \tset default keyFile path\n\t\t// }\n\t\tcreds, err := credentials.NewServerTLSFromFile(certFile, keyFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to generate credentials %v\", err)\n\t\t}\n\t\topts = []grpc.ServerOption{grpc.Creds(creds)}\n\t}\n\tgrpcServer := grpc.NewServer(opts...)\n\tpb.RegisterFrontendServer(grpcServer, s)\n\tgo grpcServer.Serve(lis)\n\tif lis2 != nil {\n\t\tgo grpcServer.Serve(lis2)\n\t}\n\treturn nil\n}", "func newServer(listenAddrs []string) (*server, error) {\n\tlogin := cfg.Username + \":\" + cfg.Password\n\tauth := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(login))\n\ts := server{\n\t\tauthsha: sha256.Sum256([]byte(auth)),\n\t}\n\n\t// Check for existence of cert file and key file\n\tif !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {\n\t\t// if both files do not exist, we generate them.\n\t\terr := genCertPair(cfg.RPCCert, cfg.RPCKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tkeypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig := tls.Config{\n\t\tCertificates: []tls.Certificate{keypair},\n\t}\n\n\tipv4ListenAddrs, ipv6ListenAddrs, err := parseListeners(listenAddrs)\n\tlisteners := make([]net.Listener, 0,\n\t\tlen(ipv6ListenAddrs)+len(ipv4ListenAddrs))\n\tfor _, addr := range ipv4ListenAddrs {\n\t\tlistener, err := tls.Listen(\"tcp4\", addr, &tlsConfig)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"RPCS: Can't listen on %s: %v\", addr,\n\t\t\t\terr)\n\t\t\tcontinue\n\t\t}\n\t\tlisteners = append(listeners, listener)\n\t}\n\n\tfor _, addr := range ipv6ListenAddrs {\n\t\tlistener, err := tls.Listen(\"tcp6\", addr, &tlsConfig)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"RPCS: Can't listen on %s: %v\", addr,\n\t\t\t\terr)\n\t\t\tcontinue\n\t\t}\n\t\tlisteners = append(listeners, listener)\n\t}\n\tif len(listeners) == 0 {\n\t\treturn nil, errors.New(\"no valid listen address\")\n\t}\n\n\ts.listeners = listeners\n\n\treturn &s, nil\n}", "func NewListenerTLS(network, addr, certFile, keyFile string, readTimeout, writeTimeout time.Duration) (net.Listener, error) {\n\tconfig := &tls.Config{}\n\tif config.NextProtos == nil {\n\t\tconfig.NextProtos = []string{\"http/1.1\"}\n\t}\n\n\tvar err error\n\tconfig.Certificates = make([]tls.Certificate, 1)\n\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := net.Listen(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttl := &Listener{\n\t\tListener: tls.NewListener(conn, config),\n\t\tReadTimeout: readTimeout,\n\t\tWriteTimeout: writeTimeout,\n\t}\n\treturn tl, nil\n}", "func SMTPServerSTARTTLS(t *testing.T, addr string, fn ...SMTPServerConfigureFunc) (*tls.Config, *SMTPBackend, *smtp.Server) {\n\tt.Helper()\n\n\tcert, err := tls.X509KeyPair([]byte(testServerCert), []byte(testServerKey))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbe := new(SMTPBackend)\n\ts := smtp.NewServer(be)\n\ts.Domain = \"localhost\"\n\ts.AllowInsecureAuth = true\n\ts.TLSConfig = &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t}\n\tfor _, f := range fn {\n\t\tf(s)\n\t}\n\n\tpool := x509.NewCertPool()\n\tpool.AppendCertsFromPEM([]byte(testServerCert))\n\n\tclientCfg := &tls.Config{\n\t\tServerName: \"127.0.0.1\",\n\t\tTime: func() time.Time {\n\t\t\treturn time.Date(2019, time.November, 18, 17, 59, 41, 0, time.UTC)\n\t\t},\n\t\tRootCAs: pool,\n\t}\n\n\tgo func() {\n\t\tif err := s.Serve(l); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\t// Dial it once it make sure Server completes its initialization before\n\t// we try to use it. Notably, if test fails before connecting to the server,\n\t// it will call Server.Close which will call Server.listener.Close with a\n\t// nil Server.listener (Serve sets it to a non-nil value, so it is racy and\n\t// happens only sometimes).\n\ttestConn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttestConn.Close()\n\n\treturn clientCfg, be, s\n}", "func ListenTLSCustom(how, addr string, config *tls.Config) (*Server, error) {\n\tl, err := net.Listen(how, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// must call wrapListener _before_ wrapping with tls.NewListener\n\tl = tls.NewListener(wrapListener(l), config)\n\ts := NewServer(DefaultHandlers, DefaultLimits, l)\n\treturn s, nil\n}", "func SecureServe(addr string, certFile, keyFile, caFile string) {\n\tconfig := tls.Config{}\n\n\t// load the server cert / key\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\tconfig.Certificates = []tls.Certificate{cert}\n\n\t// load the ca if necessary\n\t// FIXME(alainjobart) this doesn't quite work yet, have\n\t// to investigate\n\tif caFile != \"\" {\n\t\tconfig.ClientCAs = x509.NewCertPool()\n\n\t\tpemCerts, err := ioutil.ReadFile(caFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"%s\", err)\n\t\t}\n\t\tif !config.ClientCAs.AppendCertsFromPEM(pemCerts) {\n\t\t\tlog.Fatalf(\"%s\", err)\n\t\t}\n\n\t\tconfig.ClientAuth = tls.RequireAndVerifyClientCert\n\t}\n\tl, err := tls.Listen(\"tcp\", addr, &config)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\tcl := proc.Published(l, \"SecureConns\", \"SecureAccepts\")\n\tgo http.Serve(cl, nil)\n}", "func main() {\n\tr := &http.ServeMux{}\n\tr.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"A web page on HTTPS\"))\n\t})\n\n\thttp.ListenAndServeTLS(\":8080\", \"../cert/server.crt\", \"../cert/server.key\", r)\n}", "func TLSServer() {\n\tif _, err := os.Stat(Temp + tun.WWW); os.IsNotExist(err) {\n\t\terr = os.MkdirAll(Temp+tun.WWW, 0700)\n\t\tif err != nil {\n\t\t\tCliFatalError(\"TLSServer: %v\", err)\n\t\t}\n\t}\n\tr := mux.NewRouter()\n\n\t// Load CA\n\ttun.CACrt = []byte(RuntimeConfig.CAPEM)\n\n\t// handlers\n\tr.HandleFunc(fmt.Sprintf(\"/%s/{api}/{token}\", tun.WebRoot), dispatcher)\n\n\t// shutdown TLSServer if it's already running\n\tif EmpTLSServer != nil {\n\t\tEmpTLSServer.Shutdown(EmpTLSServerCtx)\n\t}\n\n\t// initialize EmpTLSServer\n\tEmpTLSServer = &http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", RuntimeConfig.CCPort), // C2 service port\n\t\tHandler: r, // use mux router\n\t}\n\tEmpTLSServerCtx, EmpTLSServerCancel = context.WithCancel(context.Background())\n\n\tCliPrintInfo(\"Starting C2 TLS service at port %s\", RuntimeConfig.CCPort)\n\t// emp3r0r.crt and emp3r0r.key is generated by build.sh\n\terr := EmpTLSServer.ListenAndServeTLS(EmpWorkSpace+\"/emp3r0r-cert.pem\", EmpWorkSpace+\"/emp3r0r-key.pem\")\n\tif err != nil {\n\t\tif err == http.ErrServerClosed {\n\t\t\tCliPrintWarning(\"C2 TLS service is shutdown\")\n\t\t\treturn\n\t\t}\n\t\tCliFatalError(\"Failed to start HTTPS server at *:%s\", RuntimeConfig.CCPort)\n\t}\n}", "func New(opts ...Option) (*Server, error) {\n\tcfg := options{\n\t\tlog: log.Base(),\n\t}\n\n\tvar srvOpts []grpc.ServerOption\n\n\tfor _, o := range opts {\n\t\to(&cfg)\n\t}\n\n\tif cfg.errored() {\n\t\treturn nil, fmt.Errorf(\"error during server setup: %v\", cfg.errs)\n\t}\n\n\tif !cfg.insecure {\n\t\tif (cfg.tlsCert == \"\" || cfg.tlsKey == \"\") && cfg.certificates == nil {\n\t\t\treturn nil, errors.New(\"either set insecure or define TLS certificates appropriately\")\n\t\t}\n\n\t\tif cfg.certificates == nil {\n\t\t\tcrt, err := tls.X509KeyPair(\n\t\t\t\t[]byte(cfg.tlsCert),\n\t\t\t\t[]byte(cfg.tlsKey),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcfg.certificates = append(cfg.certificates, crt)\n\t\t}\n\n\t\tcreds := credentials.NewTLS(serverTLS(&cfg))\n\t\tsrvOpts = append(srvOpts, grpc.Creds(creds))\n\t}\n\n\tif len(cfg.ssInterceptors) > 0 {\n\t\tc := middleware.ChainStreamServer(cfg.ssInterceptors...)\n\t\tsrvOpts = append(srvOpts, grpc.StreamInterceptor(c))\n\t}\n\n\tif len(cfg.usInterceptors) > 0 {\n\t\tc := middleware.ChainUnaryServer(cfg.usInterceptors...)\n\t\tsrvOpts = append(srvOpts, grpc.UnaryInterceptor(c))\n\t}\n\n\tsrv := Server{\n\t\tstate: Init,\n\t\ttransport: grpc.NewServer(srvOpts...),\n\t\tlog: cfg.log,\n\t\tnotifyChan: make(map[State][]chan<- State),\n\t}\n\n\tsrv.shutdown = srv.transport.GracefulStop\n\n\tif cfg.httpPassthrough || cfg.httpPassthroughInsecure {\n\t\tsrv.httpMux = grpc_runtime.NewServeMux(\n\t\t\tgrpc_runtime.WithMarshalerOption(\n\t\t\t\tgrpc_runtime.MIMEWildcard,\n\t\t\t\t&grpc_runtime.JSONPb{\n\t\t\t\t\tMarshalOptions: protojson.MarshalOptions{\n\t\t\t\t\t\tIndent: \"\",\n\t\t\t\t\t\tUseProtoNames: true,\n\t\t\t\t\t\tEmitUnpopulated: true,\n\t\t\t\t\t\tMultiline: true,\n\t\t\t\t\t},\n\t\t\t\t\tUnmarshalOptions: protojson.UnmarshalOptions{\n\t\t\t\t\t\tDiscardUnknown: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t),\n\t\t)\n\n\t\tmux := http.NewServeMux()\n\t\tmux.Handle(\"/\", srv.httpMux)\n\n\t\tif cfg.certificates != nil {\n\t\t\tsrv.httpConfig = &tls.Config{\n\t\t\t\tCertificates: cfg.certificates,\n\t\t\t\tNextProtos: []string{\"h2\"},\n\t\t\t\tClientCAs: cfg.mustGetCertPool(),\n\t\t\t\tClientAuth: cfg.clientAuth,\n\t\t\t\t//nolint -- the only way to make this proper is to have a SAN in the cert, which may expose\n\t\t\t\t// some of the internals. I could go either way on this one..\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t}\n\t\t}\n\n\t\tsrv.httpTransport = &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", cfg.port),\n\t\t\tHandler: grpcHandlerFunc(srv.Transport(), mux),\n\t\t\tTLSConfig: srv.httpConfig,\n\t\t\tIdleTimeout: time.Second * idletimeout,\n\t\t\tReadHeaderTimeout: time.Second * readheadertimeout,\n\t\t\tMaxHeaderBytes: maxheaderbytes,\n\t\t}\n\n\t\tvar err error\n\n\t\tswitch {\n\t\tcase cfg.httpPassthrough:\n\t\t\tsrv.httpListener, err = srv.getListener(cfg.port, cfg.certificates)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase cfg.httpPassthroughInsecure:\n\t\t\tsrv.httpListener, err = srv.getListener(cfg.port, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tsrv.listener, err = srv.getListener(internalServerPort, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\trpcLis, _ := srv.getListener(cfg.port, nil)\n\t\tsrv.listener = rpcLis\n\t}\n\n\tif cfg.reflect {\n\t\treflection.Register(srv.transport)\n\t}\n\n\treturn &srv, nil\n}", "func (s *MockServer) StartTLS() {\n\tcert, err := tls.X509KeyPair(localhostCert, localhostKey)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"NewTLSServer: %v\", err))\n\t}\n\n\t// init tls config and tls listener\n\tif s.TLS == nil {\n\t\ts.TLS = new(tls.Config)\n\t}\n\tif len(s.TLS.Certificates) == 0 {\n\t\ts.TLS.Certificates = []tls.Certificate{cert}\n\t}\n\ttlsListener := tls.NewListener(s.Listener, s.TLS)\n\ts.Listener = &historyListener{Listener: tlsListener}\n\n\t// start tls server\n\tgo s.Serve(s.Listener)\n}", "func FdListenAndServeTLS(fd int, addr, certFile, keyFile string, handler http.Handler) error {\n\tvar err error\n\tserver, err = FromFd(fd, &http.Server{\n\t\tAddr: addr,\n\t\tHandler: handler,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn server.ListenAndServeTLS(certFile, keyFile)\n}", "func (ts *TCPServer) Start() error {\n\t// check for conditions\n\tif ts.handler == nil {\n\t\treturn errorf(errTCPHandlerNotRegistered)\n\t}\n\t// listen\n\tvar ln net.Listener\n\tvar err error\n\tif ts.useTls {\n\t\t// if use tls, then load pem files and start server\n\t\tif *confCAFile == \"\" {\n\t\t\treturn errorf(errMissingFlag, FlagCAFile)\n\t\t}\n\t\tif *confKeyFile == \"\" {\n\t\t\treturn errorf(errMissingFlag, FlagKeyFile)\n\t\t}\n\n\t\t// process key files\n\t\tcert, err := tls.LoadX509KeyPair(*confCAFile, *confKeyFile)\n\t\tif err != nil {\n\t\t\treturn errorf(errLoadSecureKey, err.Error())\n\t\t}\n\n\t\t// config server with tls\n\t\tconfig := tls.Config{Certificates: []tls.Certificate{cert}}\n\n\t\t// listen for new connection\n\t\tln, err = tls.Listen(\"tcp\", ts.addr, &config)\n\n\t\tif err != nil {\n\t\t\treturn errorf(errListenFailed, ts.addr, err)\n\t\t}\n\n\t} else {\n\t\t// don't use tls, just listen\n\t\tln, err = net.Listen(\"tcp\", ts.addr)\n\t\tif err != nil {\n\t\t\treturn errorf(errListenFailed, ts.addr, err)\n\t\t}\n\t}\n\n\tLog.Infof(\"TCP Server Listen on %s, use tls: %v\", ts.addr, ts.useTls)\n\n\t// continously accept connections and serve, nonblock\n\tgo func() {\n\t\tfor {\n\t\t\tconn, err := ln.Accept()\n\t\t\tif err != nil {\n\t\t\t\tLog.Errorf(errNewConnection, err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tLog.Infof(\"accepting new connection %s\", conn.RemoteAddr())\n\t\t\tgo ts.handler.Handle(conn)\n\t\t}\n\t}()\n\n\treturn nil\n}", "func ParseServerTLS(configuration *viper.Viper, tlsRequired bool) (*tls.Config, error) {\n\t// unmarshalling into objects does not seem to pick up env vars\n\ttlsOpts := tlsconfig.Options{\n\t\tCertFile: GetPathRelativeToConfig(configuration, \"server.tls_cert_file\"),\n\t\tKeyFile: GetPathRelativeToConfig(configuration, \"server.tls_key_file\"),\n\t\tCAFile: GetPathRelativeToConfig(configuration, \"server.client_ca_file\"),\n\t}\n\tif tlsOpts.CAFile != \"\" {\n\t\ttlsOpts.ClientAuth = tls.RequireAndVerifyClientCert\n\t}\n\n\tif !tlsRequired {\n\t\tcert, key, ca := tlsOpts.CertFile, tlsOpts.KeyFile, tlsOpts.CAFile\n\t\tif cert == \"\" && key == \"\" && ca == \"\" {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tif (cert == \"\" && key != \"\") || (cert != \"\" && key == \"\") || (cert == \"\" && key == \"\" && ca != \"\") {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"either include both a cert and key file, or no TLS information at all to disable TLS\")\n\t\t}\n\t}\n\n\treturn tlsconfig.Server(tlsOpts)\n}", "func Server(conn net.Conn, config *Config) *Conn {\n\ttls := new(Conn);\n\ttls.Conn = conn;\n\n\twriteChan := make(chan []byte);\n\treadChan := make(chan []byte);\n\trequestChan := make(chan interface{});\n\n\ttls.writeChan = writeChan;\n\ttls.readChan = readChan;\n\ttls.requestChan = requestChan;\n\n\thandshakeWriterChan := make(chan interface{});\n\tprocessorHandshakeChan := make(chan interface{});\n\thandshakeProcessorChan := make(chan interface{});\n\treaderProcessorChan := make(chan *record);\n\n\tgo new(recordWriter).loop(conn, writeChan, handshakeWriterChan);\n\tgo recordReader(readerProcessorChan, conn);\n\tgo new(recordProcessor).loop(readChan, requestChan, handshakeProcessorChan, readerProcessorChan, processorHandshakeChan);\n\tgo new(serverHandshake).loop(handshakeWriterChan, handshakeProcessorChan, processorHandshakeChan, config);\n\n\treturn tls;\n}", "func NewServer(\n\tctx context.Context,\n\taddr string,\n\tk8sAPI *k8s.API,\n\tgrpcTapServer pb.TapServer,\n\tdisableCommonNames bool,\n) (*Server, error) {\n\tupdateEvent := make(chan struct{})\n\terrEvent := make(chan error)\n\twatcher := pkgTls.NewFsCredsWatcher(pkgk8s.MountPathTLSBase, updateEvent, errEvent).\n\t\tWithFilePaths(pkgk8s.MountPathTLSCrtPEM, pkgk8s.MountPathTLSKeyPEM)\n\tgo func() {\n\t\tif err := watcher.StartWatching(ctx); err != nil {\n\t\t\tlog.Fatalf(\"Failed to start creds watcher: %s\", err)\n\t\t}\n\t}()\n\n\tclientCAPem, allowedNames, usernameHeader, groupHeader, err := serverAuth(ctx, k8sAPI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// for development\n\tif disableCommonNames {\n\t\tallowedNames = []string{}\n\t}\n\n\tlog := log.WithFields(log.Fields{\n\t\t\"component\": \"tap\",\n\t\t\"addr\": addr,\n\t})\n\n\tclientCertPool := x509.NewCertPool()\n\tclientCertPool.AppendCertsFromPEM([]byte(clientCAPem))\n\n\thttpServer := &http.Server{\n\t\tAddr: addr,\n\t\tReadHeaderTimeout: 15 * time.Second,\n\t\tTLSConfig: &tls.Config{\n\t\t\tClientAuth: tls.VerifyClientCertIfGiven,\n\t\t\tClientCAs: clientCertPool,\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t},\n\t}\n\n\tvar emptyCert atomic.Value\n\th := &handler{\n\t\tk8sAPI: k8sAPI,\n\t\tusernameHeader: usernameHeader,\n\t\tgroupHeader: groupHeader,\n\t\tgrpcTapServer: grpcTapServer,\n\t\tlog: log,\n\t}\n\n\tlis, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"net.Listen failed with: %w\", err)\n\t}\n\n\ts := &Server{\n\t\tServer: httpServer,\n\t\tlistener: lis,\n\t\trouter: initRouter(h),\n\t\tallowedNames: allowedNames,\n\t\tcertValue: &emptyCert,\n\t\tlog: log,\n\t}\n\ts.Handler = prometheus.WithTelemetry(s)\n\thttpServer.TLSConfig.GetCertificate = s.getCertificate\n\n\tif err := watcher.UpdateCert(s.certValue); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialized certificate: %w\", err)\n\t}\n\n\tgo watcher.ProcessEvents(log, s.certValue, updateEvent, errEvent)\n\n\treturn s, nil\n}" ]
[ "0.7715989", "0.7664833", "0.76329964", "0.75620776", "0.75520676", "0.755003", "0.7523259", "0.74570715", "0.7444302", "0.7389253", "0.73218924", "0.7318289", "0.7289134", "0.72622293", "0.7257478", "0.7257478", "0.72479", "0.7235329", "0.7182851", "0.7138725", "0.7125067", "0.7122513", "0.71171254", "0.70866543", "0.70569104", "0.7047099", "0.70450866", "0.70435655", "0.7007318", "0.69059616", "0.69023067", "0.68671346", "0.68565804", "0.6830232", "0.6816793", "0.67919505", "0.67853266", "0.674149", "0.6706326", "0.67023855", "0.66975826", "0.6680983", "0.66118807", "0.66102165", "0.66032606", "0.6596258", "0.6531027", "0.6513254", "0.64860076", "0.6481447", "0.64322084", "0.64202505", "0.63861567", "0.6343713", "0.6341853", "0.63194394", "0.6311276", "0.6309099", "0.630475", "0.6302747", "0.6296504", "0.62642974", "0.6252838", "0.62122506", "0.61978424", "0.609981", "0.6091046", "0.6074851", "0.6074222", "0.60731703", "0.6066241", "0.6047899", "0.6042247", "0.6037652", "0.60366255", "0.60332376", "0.6029555", "0.6010259", "0.6008242", "0.5993495", "0.5983149", "0.5978481", "0.59366244", "0.5932003", "0.59298366", "0.59297013", "0.59138936", "0.5911515", "0.59108996", "0.58971745", "0.58966666", "0.58937657", "0.5887228", "0.5885978", "0.5875992", "0.58747286", "0.58704144", "0.5868363", "0.58653736", "0.5855563" ]
0.7643902
2
Index renders index page.
func (si ServeIndex) Index(w http.ResponseWriter, r *http.Request) { para := params.NewParams() data, _, err := Updates(r, para) if err != nil { if _, ok := err.(params.RenamedConstError); ok { http.Redirect(w, r, err.Error(), http.StatusFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } data["Distrib"] = si.StaticData.Distrib data["Exporting"] = exportingCopy() // from ./ws.go data["OstentUpgrade"] = OstentUpgrade.Get() data["OstentVersion"] = si.StaticData.OstentVersion data["TAGGEDbin"] = si.StaticData.TAGGEDbin si.IndexTemplate.Apply(w, struct{ Data IndexData }{Data: data}) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Index(w http.ResponseWriter, r *http.Request) {\n\t// Fill out the page data for index\n\tpd := PageData{\n\t\tTitle: \"Index Page\",\n\t\tBody: \"This is the body of the index page.\",\n\t}\n\n\t// Render a template with our page data\n\ttmpl, err := render(pd)\n\n\t// if we get an error, write it out and exit\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\t// All went well, so write out the template\n\tw.Write([]byte(tmpl))\n\n\t//fmt.Fprintf(w, \"Hello world from %q\", html.EscapeString(r.URL.Path))\n}", "func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tdata, err := newPageData(1)\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t}\n\terr = t.ExecuteTemplate(w, \"index\", data)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func index(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\terr := tpl.ExecuteTemplate(w, \"index.html\", nil)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tlog.Fatalln(err)\n\t}\n\tfmt.Println(\"HERE INDEX\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\t// @todo: check setup required\n\n\t// @todo: check user is logged in\n\n\trender.HTML(w, \"index.html\", struct{}{})\n}", "func Index(c echo.Context) error {\n\treturn c.Render(http.StatusOK, \"index\", echo.Map{})\n}", "func index(w http.ResponseWriter, r *http.Request){\n\terr := templ.ExecuteTemplate(w, \"index\", nil)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t}\n}", "func Index(w http.ResponseWriter, data *IndexData) {\n\trender(tpIndex, w, data)\n}", "func Index(w http.ResponseWriter, data *IndexData) {\n\trender(tpIndex, w, data)\n}", "func Index(w http.ResponseWriter, data interface{}) {\n\trender(tpIndex, w, data)\n}", "func index(w http.ResponseWriter, req *http.Request, ctx httputil.Context) (e *httputil.Error) {\n\tif req.URL.Path != \"/\" {\n\t\tnotFound(w, req)\n\t\treturn\n\t}\n\tm := newManager(ctx)\n\n\tres, err := m.Index()\n\tif err != nil {\n\t\te = httputil.Errorf(err, \"couldn't query for test results\")\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tif err := T(\"index/index.html\").Execute(w, res); err != nil {\n\t\te = httputil.Errorf(err, \"error executing index template\")\n\t}\n\treturn\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\t//shows 404 not found\n\tif r.URL.Path != \"/\" {\n\t\tNotFound(w, r)\n\t} else {\n\t\ttemplate, err := template.ParseFiles(\"../htmls/index.html\")\n\t\tif err != nil {\n\t\t\tlogger.ErrLogger(err)\n\t\t} else {\n\t\t\ttemplate.Execute(w, nil)\n\t\t}\n\t}\n}", "func (c App) Index() revel.Result {\n\treturn c.Render()\n}", "func (c App) Index() revel.Result {\n\treturn c.Render()\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tdata := &Index{\n\t\tTitle: \"Image gallery\",\n\t\tBody: \"Welcome to the image gallery.\",\n\t}\n\tfor name, img := range images {\n\t\tdata.Links = append(data.Links, Link{\n\t\t\tURL: \"/image/\" + name,\n\t\t\tTitle: img.Title,\n\t\t})\n\t}\n\tif err := indexTemplate.Execute(w, data); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func indexHandler(res http.ResponseWriter, req *http.Request) {\n\n\t// Execute the template and respond with the index page.\n\ttemplates.ExecuteTemplate(res, \"index\", nil)\n}", "func showIndex(c *gin.Context) {\n\trender(\n\t\tc,\n\t\tgin.H{\n\t\t\t\"title\": \"Home Page\",\n\t\t\t\"payload\": films,\n\t\t},\n\t\ttemplates.Index,\n\t)\n}", "func (app *Application) Index(w http.ResponseWriter, r *http.Request) {\n\tdata := struct {\n\t\tTime int64\n\t}{\n\t\tTime: time.Now().Unix(),\n\t}\n\n\tt, err := template.ParseFiles(\"views/index.tpl\")\n\n\tif err != nil {\n\t\tlog.Println(\"Template.Parse:\", err)\n\t\thttp.Error(w, \"Internal Server Error 0x0178\", http.StatusInternalServerError)\n\t}\n\n\tif err := t.Execute(w, data); err != nil {\n\t\tlog.Println(\"Template.Execute:\", err)\n\t\thttp.Error(w, \"Internal Server Error 0x0183\", http.StatusInternalServerError)\n\t}\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tdata := page{Title: \"School Database\", Header: \"Welcome, please select an option\"}\n\ttemplateInit(w, \"index.html\", data)\n\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tmessage := \"Welcome to Recipe Book!\"\n\tindexT.Execute(w, message)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\n\t// Render the \"Index.gtpl\"\n\tgoTmpl.ExecuteTemplate(w, \"Index\", nil)\n\n\t//name := r.FormValue(\"name\")\n\n\t// Logging the Action\n\tlog.Println(\"Render: Index.gtpl\")\n\n}", "func indexHandler(w http.ResponseWriter, req *http.Request) {\n\tlayout, err := template.ParseFile(PATH_PUBLIC + TEMPLATE_LAYOUT)\n\tif err != nil {\n\t\thttp.Error(w, ERROR_TEMPLATE_NOT_FOUND, http.StatusNotFound)\n\t\treturn\n\t}\n\tindex, err := template.ParseFile(PATH_PUBLIC + TEMPLATE_INDEX)\n\t//artical, err := template.ParseFile(PATH_PUBLIC + TEMPLATE_ARTICAL)\n\tif err != nil {\n\t\thttp.Error(w, ERROR_TEMPLATE_NOT_FOUND, http.StatusNotFound)\n\t\treturn\n\t}\n\tmapOutput := map[string]interface{}{\"Title\": \"炫酷的网站技术\" + TITLE, \"Keyword\": KEYWORD, \"Description\": DESCRIPTION, \"Base\": BASE_URL, \"Url\": BASE_URL, \"Carousel\": getAddition(PREFIX_INDEX), \"Script\": getAddition(PREFIX_SCRIPT), \"Items\": leveldb.GetRandomContents(20, &Filter{})}\n\tcontent := []byte(index.RenderInLayout(layout, mapOutput))\n\tw.Write(content)\n\tgo cacheFile(\"index\", content)\n}", "func (h *Handlers) Index(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tfile := path.Join(\"index.html\")\n\n\tdata := struct{ Host string }{Host: h.Host}\n\n\ttemp, _ := template.ParseFiles(file)\n\ttemp.Execute(w, &data)\n}", "func (app *App) RenderIndex(w http.ResponseWriter, r *http.Request) {\n\ttmplList := []string{\"./web/views/base.html\",\n\t\t\"./web/views/index.html\"}\n\tres, err := app.TplParser.ParseTemplate(tmplList, nil)\n\tif err != nil {\n\t\tapp.Log.Info(err)\n\t}\n\tio.WriteString(w, res)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hello from our index page\")\n}", "func IndexHandler(w http.ResponseWriter, r *http.Request) {\n page := &Data{Title:\"Home page\", Body:\"This is the home page.\"}\n\tt, _ := template.ParseFiles(\"templates/index.html\")\n t.Execute(w, page)\n}", "func showIndex(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tServeTemplateWithParams(res, req, \"index.html\", nil)\n}", "func index(res http.ResponseWriter, req *http.Request) {\n\ttpl, err := template.ParseFiles(\"index.html\")\n\tif err != nil { // if file does not exist, give user a error\n\t\tlog.Fatalln(err) // stops program if file does not exist\n\t}\n\ttpl.Execute(res, nil) // execute the html file\n}", "func IndexHandler(c *gin.Context) {\n\tc.HTML(200, \"index.tmpl\", nil)\n}", "func IndexHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\n\tt, err := template.ParseFiles(path.Join(\"templates\", \"index.html\"))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\tError.Printf(\"error parsing the template %v\", err)\n\t}\n\n\terr = t.Execute(w, nil)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\tError.Printf(\"error executing the template %v\", err)\n\t}\n}", "func index(w http.ResponseWriter, req *http.Request) {\n\thttp.ServeFile(w, req, \"./templates/index.html\")\n}", "func IndexHandler(c buffalo.Context) error {\n\treturn c.Render(200, r.HTML(\"index.html\"))\n}", "func getIndexPage(w http.ResponseWriter, r *http.Request) {\n\t// Get DB information\n\trows, err := model.GetAllUsers()\n\t\n\t// Error Handling\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Print(\"Error: Execute database query: \", err)\n\t\treturn\n\t}\n\t\n\tvar users []types.User\n\t\n\tfor rows.Next() {\n\t\tvar uid, name, email, username, photoUrl string\n\t\terr := rows.Scan(&uid, &name, &username, &email, &photoUrl)\n\t\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tusers = append(users, types.User{ username, uid, email, name, photoUrl })\n\t}\n\t\n\tPageData := SiteData{\n\t\tTitle: \"Test\",\n\t\tDescription: \"This is test for DB connection, read and write.\",\n\t\tPageTitle: \"Users\",\n\t\tReactFilePath: \"\",\n\t\tUsers: users,\n\t}\n\t\n\tt, err := template.ParseFiles(\"templates/index.html.tpl\")\n\t\n\tif err != nil {\n\t\tlog.Printf(\"Could not find template file: %v\", err)\n\t}\n\t\n\tif err := t.Execute(w, PageData); err != nil {\n\t\tlog.Printf(\"Failed to execute template: %v\", err)\n\t}\n\t\n}", "func indexHandler(res http.ResponseWriter, req *http.Request) {\n\tfmt.Println(\"website index\")\n\t//grab all partials\n\tpartials, err := loadPartials()\n\tif err != nil {\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\t//get template function based on index and execute to load page\n\tt, _ := template.ParseFiles(\"../index.html\")\n\tt.Execute(res, partials)\n}", "func IndexView(ctx *fiber.Ctx) error {\n\t// load records\n\tquery := bson.D{{}}\n\tcursor, queryError := Instance.Database.Collection(\"Todos\").Find(ctx.Context(), query)\n\tif queryError != nil {\n\t\treturn utilities.Response(utilities.ResponseParams{\n\t\t\tCtx: ctx,\n\t\t\tInfo: configuration.ResponseMessages.InternalServerError,\n\t\t\tStatus: fiber.StatusInternalServerError,\n\t\t})\n\t}\n\n\tvar todos []Todo = make([]Todo, 0)\n\n\t// iterate the cursor and decode each item into a Todo\n\tif err := cursor.All(ctx.Context(), &todos); err != nil {\n\t\treturn utilities.Response(utilities.ResponseParams{\n\t\t\tCtx: ctx,\n\t\t\tInfo: configuration.ResponseMessages.InternalServerError,\n\t\t\tStatus: fiber.StatusInternalServerError,\n\t\t})\n\t}\n\n\t// caclulate the latency\n\tinitial := ctx.Context().Time()\n\tlatency := utilities.MakeTimestamp() - (initial.UnixNano() / 1e6)\n\n\t// send response: render the page\n\treturn ctx.Render(\n\t\t\"index\",\n\t\tfiber.Map{\n\t\t\t\"Latency\": latency,\n\t\t\t\"Todos\": todos,\n\t\t},\n\t\t\"layouts/main\",\n\t)\n}", "func (c App) Index() revel.Result {\n\tusername, _ := c.Session.Get(\"user\")\n\tfulluser, _ := c.Session.Get(\"fulluser\")\n\treturn c.Render(username, fulluser)\n}", "func IndexHandler(w http.ResponseWriter, r *http.Request) {\n heading := \"Welcome to Hats for cats!\"\n text := \"On this page you can put funny hats on your cat pictures! Create an account and upload your favorite pictures of your (or someone else's) cat today. Get some inspiration from the latest cats below.\"\n\ttv := &TextView{heading, text}\n template.Must(template.ParseFiles(\"static/index.html\", \"static/templates/latestCats.tmp\")).Execute(w, tv)\n}", "func IndexHandler(w http.ResponseWriter, r *http.Request) {\n\tpage := Page{Title: Environ.Config.Title, Logo: Environ.Config.Logo}\n\n\t// Set the document root based on the type of interface that is to be served\n\tvar path []string\n\tif Environ.Config.Interface == InterfaceTypeAdmin {\n\t\tpath = []string{Environ.Config.DocRootAdmin, indexTemplate}\n\t} else {\n\t\tpath = []string{Environ.Config.DocRootUser, indexTemplate}\n\t}\n\n\tt, err := template.ParseFiles(strings.Join(path, \"\"))\n\tif err != nil {\n\t\tlog.Printf(\"Error loading the application template: %v\\n\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\terr = t.Execute(w, page)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func index(ctx *gin.Context) {\n\tctx.Header(\"Content-Type\", \"text/html\")\n\tctx.String(\n\t\thttp.StatusOK,\n\t\t\"<h1>Rasse Server</h1><p>Wel come to the api server.</p><p>%v</p>\",nil)\n}", "func (a *Ctl) Index(res http.ResponseWriter, req *http.Request) {\n\ttype pageData struct {\n\t\tUser User\n\t}\n\td := pageData{\n\t\tUser: a.getUser(res, req),\n\t}\n\ta.Template.ExecuteTemplate(res, \"index.html\", d)\n}", "func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n p, _ := loadPage(\"/src/github.com/mrgirlyman/watcher/frontman/build/index.html\")\n\n fmt.Fprintf(w, string(p.Body))\n // log.Fatal(err)\n\n // if (err != nil) {\n // fmt.Fprintf(w, string(p.Body))\n // } else {\n // fmt.Fprintf(w, \"Error reading index.html\")\n // }\n}", "func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tasset, err := Asset(\"static/templates/index.html\")\n\tif err != nil {\n\t\tlog.Panic(\"Unable to read file from bindata: \", err)\n\t}\n\tfmt.Fprint(w, string(asset))\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tt, _ := template.ParseFiles(\"templates/index.html\")\n\tt.Execute(w, mails)\n}", "func (c *AppController) Index() {\n\tdata := aah.Data{\n\t\t\"Greet\": models.Greet{\n\t\t\tMessage: \"Welcome to aah framework - Web Application\",\n\t\t},\n\t}\n\n\tc.Reply().Ok().HTML(data)\n}", "func (controller *BuoyController) Index() {\n\tbuoyStations, err := buoyService.AllStation(&controller.Service)\n\tif err != nil {\n\t\tcontroller.ServeError(err)\n\t\treturn\n\t}\n\n\tcontroller.Data[\"Stations\"] = buoyStations\n\tcontroller.Layout = \"shared/basic-layout.html\"\n\tcontroller.TplName = \"buoy/content.html\"\n\tcontroller.LayoutSections = map[string]string{}\n\tcontroller.LayoutSections[\"PageHead\"] = \"buoy/page-head.html\"\n\tcontroller.LayoutSections[\"Header\"] = \"shared/header.html\"\n\tcontroller.LayoutSections[\"Modal\"] = \"shared/modal.html\"\n}", "func Index(txn *cheshire.Txn) {\n\t//create a context map to be passed to the template\n\tcontext := make(map[string]interface{})\n\tcontext[\"services\"] = Servs.RouterTables()\n\tcheshire.RenderInLayout(txn, \"/index.html\", \"/template.html\", context)\n}", "func index(w http.ResponseWriter, req *http.Request) {\n\t// Get user and session state\n\tuserData, _ := getUserAndSession(w, req)\n\n\t// Redirect to login page if user is logged out\n\tif !userData.LoggedIn {\n\t\thttp.Redirect(w, req, \"/login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\ttpl.ExecuteTemplate(w, \"index.gohtml\", userData)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hola, este es el inicio\")\n}", "func indexHandler(c *fiber.Ctx) error {\n\treturn common.HandleTemplate(c, \"index\",\n\t\t\"me\", nil, 200)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tsession, _ := store.Get(r, \"session-name\")\n\n\tvar fname, lname, email string\n\tvar id int64\n\n\tif _, ok := session.Values[\"id\"].(int64); ok {\n\t\tfname = session.Values[\"fname\"].(string)\n\t\tlname = session.Values[\"lname\"].(string)\n\t\temail = session.Values[\"email\"].(string)\n\t\tid = session.Values[\"id\"].(int64)\n\t} else {\n\t\tfname = \"\"\n\t\tlname = \"\"\n\t\temail = \"\"\n\t\tid = 0\n\t}\n\tp1 := &Page{Title: \"index\", Body: []byte(\"\"), User: Researcher{ID: id, Email: email, Name: Name{First: fname, Last: lname}}}\n\n\tgenTemplate(w, \"index\", p1)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\t// validate the passed-in arguments\n\tvars, err := wdp.ValidateApiArgs(r)\n\tif err != nil {\n\t\tlog.Print(\"error validating API arguments: \", err)\n\t}\n\n\t// parse the template at index.html\n\t// NOTE: SWITCH WHICH OF THESE STATEMENTS IS COMMENTED OUT TO RUN ON CLOUD VPS VS LOCALLY\n\t// t, err := template.ParseFiles(\"templates/index.html\") // LOCAL\n\tt, err := template.ParseFiles(\"/etc/diff-privacy-beam/index.html\") // CLOUD VPS\n\tif err != nil {\n\t\tlog.Print(\"error parsing template index_go.html: \", err)\n\t}\n\n\t// execute the template to serve it back to the client\n\terr = t.Execute(w, vars)\n\tif err != nil {\n\t\tlog.Print(\"error executing template index_go.html: \", err)\n\t}\n}", "func IndexHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := \"Visualizing Wizard\"\n buttonContent := \"Sätt igång\"\n\tbt := &ButtonText{title, buttonContent}\n template.Must(template.ParseFiles(\"static/index.html\", \"static/templates/start.tmp\")).Execute(w, bt)\n}", "func Index(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func (t tApp) Index(w http.ResponseWriter, r *http.Request) {\n\tvar h http.Handler\n\tc := App.New(w, r, \"App\", \"Index\")\n\tdefer func() {\n\t\tif h != nil {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t}()\n\tdefer App.After(c, w, r)\n\tif res := App.Before(c, w, r); res != nil {\n\t\th = res\n\t\treturn\n\t}\n\tif res := c.Index(); res != nil {\n\t\th = res\n\t\treturn\n\t}\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\r\n t, _ := template.New(\"webpage\").Parse(indexPage) // parse embeded index page\r\n t.Execute(w, pd) // serve the index page (html template)\r\n}", "func (c *IndexController) IndexHandler(ctx *iris.Context) {\n\tif err := ctx.Render(\"index.html\", nil); err != nil {\n\t\tfmt.Println(err.Error())\n\t\tpanic(err)\n\t}\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"Hello World!\"))\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\t// Create a pagination instance with a max of 10 results.\n\tp := pagination.New(r, 10)\n\n\tarticles, _, err := article.ByUserIDPaginate(c.DB, c.UserID, p.PerPage, p.Offset)\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t\tarticles = []article.Article{}\n\t}\n\n\tcount, err := article.ByUserIDCount(c.DB, c.UserID)\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t}\n\n\t// Calculate the number of pages.\n\tp.CalculatePages(count)\n\n\tv := c.View.New(\"article/index\")\n\tv.Vars[\"articles\"] = articles\n\tv.Vars[\"pagination\"] = p\n\tv.Render(w, r)\n}", "func (s *Server) IndexHandler(w http.ResponseWriter, r *http.Request) {\n\t// Should we render the recent commits as an html fragment?\n\tfragmentParam := r.URL.Query().Get(\"fragment\")\n\tif fragmentParam == \"\" {\n\t\tfragmentParam = \"false\"\n\t}\n\tfragment, _ := strconv.ParseBool(fragmentParam)\n\n\t// Get recent commits.\n\tgroup := r.URL.Query().Get(\"group\")\n\tcommits, err := s.DB.RecentCommitsByGroup(group)\n\tif err != nil {\n\t\tsentry.CaptureException(err)\n\t\tfmt.Println(err)\n\t\thttp.Error(w, \"oopsie, something went horribly wrong\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Render the template.\n\tif fragment {\n\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\t\ts.Templates.ExecuteTemplate(w, \"commits\", commits)\n\t\treturn\n\t}\n\ts.Templates.ExecuteTemplate(w, \"index\", commits)\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tthreads, err := data.Threads()\n\tif err != nil {\n\t\tRedirectToErrorPage(w, r, \"Cannot get threads\")\n\t\treturn\n\t}\n\tif _, err := data.CheckSession(r); err == nil {\n\t\tgenerateHTML(w, threads, []string{\"layout\", \"private.navbar\", \"index\"})\n\t} else {\n\t\tgenerateHTML(w, threads, []string{\"layout\", \"public.navbar\", \"index\"})\n\t}\n}", "func Index(w http.ResponseWriter, r *http.Request) {\r\n\tfiles := []string{\"templates/layout.html\", \"templates/navbar.html\", \"templates/upload.index.html\"}\r\n\tt, err := template.ParseFiles(files...)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tt.ExecuteTemplate(w, \"layout\", \"\")\r\n}", "func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func (c Application) Index() revel.Result {\n\tif user := c.connected(); user != nil {\n\t\treturn c.Redirect(routes.Dashboard.Index())\n\t}\n\treturn c.Render()\n}", "func handleIndex(w http.ResponseWriter, r *http.Request) {\n\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tc := appengine.NewContext(r)\n\tlog.Infof(c, \"Serving main page.\")\n\n\ttmpl, _ := template.ParseFiles(\"web/tmpl/index.tmpl\")\n\n\ttmpl.Execute(w, time.Since(initTime))\n}", "func IndexHandler(w http.ResponseWriter, r *http.Request) {\n\tt, _ := template.ParseFiles(\"templates/index.html\")\n\tt.Execute(w, nil)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Welcome!\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome to this example API\\n\")\n}", "func HomeIndex(res http.ResponseWriter, req *http.Request) {\n\tvar article model.Article\n\tapp.DB.First(&article, 1)\n\tapp.Render.HTML(res, http.StatusOK, \"home\", article)\n}", "func IndexPage(w http.ResponseWriter, req *http.Request) {\n\tdashDir := getDashDir()\n\tif len(dashDir) != 0 {\n\t\t// Serve the index page from disk if the env variable is set.\n\t\thttp.ServeFile(w, req, path.Join(dashDir, \"index.html\"))\n\t} else {\n\t\t// Otherwise serve it from the compiled resources.\n\t\tb, _ := resources.Asset(\"index.html\")\n\t\thttp.ServeContent(w, req, \"index.html\", time.Time{}, bytes.NewReader(b))\n\t}\n\treturn\n}", "func (h *Root) Index(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\tif claims, err := auth.ClaimsFromContext(ctx); err == nil && claims.HasAuth() {\n\t\treturn h.indexDashboard(ctx, w, r, params)\n\t}\n\n\treturn h.indexDefault(ctx, w, r, params)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func (h *MovieHandler) index(w http.ResponseWriter, r *http.Request) {\n\t// Call GetMovies to retrieve all movies from the database.\n\tif movies, err := h.MovieService.GetMovies(); err != nil {\n\t\t// Render an error response and set status code.\n\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\tlog.Println(\"Error:\", err)\n\t} else {\n\t\t// Render a HTML response and set status code.\n\t\trender.HTML(w, http.StatusOK, \"movie/index.html\", movies)\n\t}\n}", "func (app *app) Index(w http.ResponseWriter, r *http.Request) {\n\tselDB, err := app.db.Query(\"select * from employee order by id desc\")\n\tif err != nil{\n\t\tpanic(err.Error())\n\t}\n\temp := Employee{}\n\tres := []Employee{}\n\tfor selDB.Next(){\n\t\tvar id uint\n\t\tvar name, city string\n\t\terr = selDB.Scan(&id, &name, &city)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\temp.Id=id\n\t\temp.Name=name\n\t\temp.City=city\n\t\tres = append(res,emp)\n\t}\n\ttmpl.ExecuteTemplate(w, \"Index\", res)\n\t// defer app.db.Close()\n}", "func IndexHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tif pusher, ok := w.(http.Pusher); ok {\n\t\tif err := pusher.Push(\"./web/css/app.css\", nil); err != nil {\n\t\t\tlog.Printf(\"Failed to push %v\\n\", err)\n\t\t}\n\t}\n\tt, err := template.ParseFiles(\"./web/html/index.html\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tt.Execute(w, nil)\n}", "func Index(w http.ResponseWriter, r *http.Request, us httprouter.Params) {\n\tfmt.Fprint(w, \"WELCOMEEE!\")\n}", "func (h *Root) indexDefault(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\treturn h.Renderer.Render(ctx, w, r, tmplLayoutSite, \"site-index.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, nil)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"s-senpai, please don't hurt me ;_;\\n\")\n}", "func indexHandler(w http.ResponseWriter, r *http.Request, s *Server) {\n\tif r.Method == \"GET\" {\n\t\t//create the source upload page with available languages and metrics\n\t\tpage := &Page{Config: s.Config, Extensions: s.Analyzer.Extensions(), Metrics: s.Analyzer.Metrics, Languages: s.Analyzer.Languages}\n\n\t\t//display the source upload page\n\t\ts.Template.ExecuteTemplate(w, \"index.html\", page)\n\t}\n}", "func Index() (int, error) {\n\t\tfmt.Println(\"Loading resources\")\n\t\terr := InitDB()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tcoursesHTML, _ := ioutil.ReadFile(config.Local.DefaultFN)\n\t\tdoc := soup.HTMLParse(string(coursesHTML))\n\t\ttables := doc.FindAll(\"table\", \"class\", \"datadisplaytable\")\n\t\tregistrar := start(tables)\n\t\tif config.CatSecret != nil {\n\t\t\t\tcat := handleCatalog()\n\t\t\t\tindexCatalog(cat, registrar)\n\t\t}\n\t\tCommit(registrar)\n\t\treturn 0, nil\n}", "func ExecuteIndex(user models.User, w http.ResponseWriter, r *http.Request) error {\n\taccess := 0\n\n\t// check if user is empty\n\tif user.ID != \"\" {\n\t\taccess = user.GetAccess()\n\t} else {\n\t\t// todo: normal auth page\n\t\tw.Header().Set(\"Content-Type\", \"\")\n\t\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n\t\treturn nil\n\t}\n\n\t// getting all required data\n\tvoiceTime := \"\"\n\tvtd, err := user.GetVoiceTime()\n\tif err == nil {\n\t\tvoiceTime = utils.FormatDuration(vtd)\n\t}\n\txbox := \"\"\n\txboxes, _ := user.GetXboxes()\n\tif len(xboxes) > 0 {\n\t\txbox = xboxes[0].Xbox\n\t}\n\tjoinedAtTime, err := user.GetGuildJoinDate()\n\tjoinedAt := \"\"\n\tif err == nil {\n\t\tdif := int(time.Now().Sub(joinedAtTime).Milliseconds()) / 1000 / 3600 / 24\n\t\tdays := utils.FormatUnit(dif, utils.Days)\n\t\tjoinedAt = fmt.Sprintf(\"%s (%s)\", utils.FormatDateTime(joinedAtTime), days)\n\t}\n\twarns, err := user.GetWarnings()\n\tif err != nil {\n\t\twarns = []models.Warning{}\n\t}\n\n\t// Preparing content and rendering\n\tcontent := IndexContent{\n\t\tUsername: user.Username,\n\t\tAvatar: user.AvatarURL,\n\t\tJoinedAt: joinedAt,\n\t\tXbox: xbox,\n\t\tVoiceTime: voiceTime,\n\t\tWarnsCount: len(warns),\n\t\tWarnings: PrepareWarnings(warns),\n\t}\n\n\ttmpl, err := template.ParseFiles(\"templates/layout.gohtml\", \"templates/index.gohtml\", \"templates/navbar.gohtml\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = tmpl.ExecuteTemplate(w, \"layout\", Layout{\n\t\tTitle: \"Главная страница\",\n\t\tPage: \"index\",\n\t\tAccess: access,\n\t\tContent: content,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (t tApp) Index(w http.ResponseWriter, r *http.Request) {\n\tvar h http.Handler\n\tc := App.newC(w, r, \"App\", \"Index\")\n\tdefer func() {\n\t\t// If one of the actions (Before, After or Index) returned\n\t\t// a handler, apply it.\n\t\tif h != nil {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t}()\n\tdefer App.after(c, w, r) // Call this at the very end, but before applying result.\n\tif res := App.before(c, w, r); res != nil {\n\t\th = res\n\t\treturn\n\t}\n\tif res := c.Index(); res != nil {\n\t\th = res\n\t\treturn\n\t}\n}", "func index() string {\n\tvar buffer bytes.Buffer\n\tvar id = 0\n\tvar class = 0\n\tbuffer.WriteString(indexTemplate)\n\tlock.Lock()\n\tfor folderName, folder := range folders {\n\t\tbuffer.WriteString(fmt.Sprintf(\"<h2>%s</h2>\", folderName))\n\t\tfor _, source := range folder {\n\t\t\tif !anyNonRead(source) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsort.Sort(source)\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"<h3>%s</h3>\", source.Title))\n\t\t\tbuffer.WriteString(fmt.Sprintf(`<button onClick=\"hideAll('source_%d'); return false\">Mark all as read</button>`, class))\n\t\t\tbuffer.WriteString(\"<ul>\")\n\n\t\t\tfor _, entry := range source.Entries {\n\t\t\t\tif entry.Read {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tbuffer.WriteString(fmt.Sprintf(`<li id=\"entry_%d\">`, id))\n\t\t\t\tbuffer.WriteString(fmt.Sprintf(`<button class=\"source_%d\" onClick=\"hide('entry_%d', '%s'); return false\">Mark Read</button> `, class, id, entry.Url))\n\t\t\t\tbuffer.WriteString(fmt.Sprintf(`<a href=\"%s\">%s</a>`, entry.Url, entry.Title))\n\t\t\t\tbuffer.WriteString(\"</li>\")\n\t\t\t\tid += 1\n\t\t\t}\n\t\t\tbuffer.WriteString(\"</ul>\")\n\t\t\tclass += 1\n\t\t}\n\t}\n\tlock.Unlock()\n\tbuffer.WriteString(\"</body></html>\")\n\treturn buffer.String()\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"index de uma função\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\ttodosOsProdutos := models.BuscaTodosOsProdutos()\n\t//EXECUTA NO TEMPLATE\n\ttemp.ExecuteTemplate(w, \"Index\", todosOsProdutos)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Welcome francis!\")\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\thttp.ServeFile(w, r, \"pages/main.html\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\t//index_routes := []string{\"providers\"}\n\tvar index_routes []string\n\tindex_routes = GetJobs()\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\tif err := json.NewEncoder(w).Encode(index_routes); err != nil {\n\t\tpanic(err)\n\t}\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tdb := dbConn()\n\tselDB, err := db.Query(\"SELECT * FROM Employee ORDER BY id DESC\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\temp := Employee{}\n\tres := []Employee{}\n\tfor selDB.Next() {\n\t\tvar id int\n\t\tvar name, city string\n\t\terr = selDB.Scan(&id, &name, &city)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\temp.Id = id\n\t\temp.Name = name\n\t\temp.City = city\n\t\tres = append(res, emp)\n\t}\n\tgetTemplates().ExecuteTemplate(w, \"Index\", res)\n\tdefer db.Close()\n}", "func (s *Server) indexHandler(w http.ResponseWriter, r *http.Request) {\n\tb, _ := s.static.Find(\"index.html\")\n\tw.Write(b)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\n\tfmt.Fprintln(w, \"Steve and Kyle Podcast: #api\")\n\tfmt.Fprintln(w, \"Number of episodes in database:\", EpCount())\n\tfmt.Fprintln(w, \"Created by Derek Slenk\")\n\tfmt.Println(\"Endpoint Hit: Index\")\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func Index(c *gin.Context) {\n\n\tw := c.Writer\n\tr := c.Request\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tp, lastMod, err := tools.ReadFileIfModified(time.Time{})\n\tif err != nil {\n\t\tp = []byte(err.Error())\n\t\tlastMod = time.Unix(0, 0)\n\t}\n\tvar v = struct {\n\t\tHost string\n\t\tData string\n\t\tLastMod string\n\t}{\n\t\tr.Host,\n\t\tstring(p),\n\t\tstrconv.FormatInt(lastMod.UnixNano(), 16),\n\t}\n\tindexTempl.Execute(w, &v)\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tInfo.Println(\"Received request: \", r) // logging\n\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\n\tfmt.Fprintf(w, \"Hello Gopher! <a href='static/static.html'>Static Page</a> <a href='static/'>Static Content</a>\")\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Whoa, Nice!\")\n}", "func (c *Controller) Index(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"listing users\"))\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\ta := \"hello from index router\"\n\tfmt.Fprintln(w, a)\n}", "func rootIndexHandler(w http.ResponseWriter, r *http.Request) {\n\tvar data map[string]*Record\n\tq := r.FormValue(\"q\")\n\tp := r.FormValue(\"p\")\n\n\tif q != \"\" { // GET /?q=query\n\t\tif len(q) >= 3 {\n\t\t\tdata = db.find(q)\n\t\t} else {\n\t\t\thttp.Error(w, http.StatusText(422), 422)\n\t\t\treturn\n\t\t}\n\t} else if p == \"1\" { // GET /?p=1\n\t\tdata = db.getPaused()\n\t}\n\n\ttotalCount, err := db.keyCount()\n\tif err != nil {\n\t\tlog.Printf(\"db.keyCount() Error: %s\\n\", err)\n\t\thttp.Error(w, http.StatusText(500), 500)\n\t\treturn\n\t}\n\n\ttmpl, err := template.New(\"index\").Parse(indexTmpl)\n\tif err != nil {\n\t\tlog.Printf(\"template.ParseFiles() Error: %s\\n\", err)\n\t\thttp.Error(w, http.StatusText(500), 500)\n\t\treturn\n\t}\n\n\tif err = tmpl.Execute(w, H{\"data\": data, \"isDisabled\": isDisabled, \"totalCount\": totalCount, \"q\": q, \"p\": p}); err != nil {\n\t\tlog.Printf(\"tmpl.Execute() Error: %s\\n\", err)\n\t\thttp.Error(w, http.StatusText(500), 500)\n\t}\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tif (!Auth(w, r)) {\n\t\treturn\n\t}\n\tfmt.Fprintln(w, \"Welcome to the REST Businesses API!\")\n\tfmt.Fprintln(w, \"Usage:\")\n\tfmt.Fprintln(w, `GET /businesses?page={number}&size={number}\nFetch list of businesses with pagination.`)\n\tfmt.Fprintln(w, \"\")\n\tfmt.Fprintln(w, `GET /business/{id}\nFetch a specific business as a JSON object`)\n}", "func (uc UserController) Index(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\n\tfmt.Fprintln(w, \"Welcome to Index!\")\n\n}", "func index(writer http.ResponseWriter, request *http.Request) {\n\tloggedin(writer, request)\n\tt := parseTemplateFiles(\"layout\", \"public.navbar\", \"index\")\n\tconversations, err := data.Conversations(); if err != nil {\n\t\terror_message(writer, request, \"Cannot get conversations\")\n\t} else {\n\t\tt.Execute(writer, conversations)\n\t}\n}", "func (a *App) Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\trawBankStatements, err := models.AllRawBankStatements(a.db)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, http.StatusText(500), 500)\n\t\treturn\n\t}\n\n\tdata, err := json.Marshal(rawBankStatements)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, http.StatusText(500), 500)\n\t\treturn\n\t}\n\tw.Write(data)\n\tfmt.Println(\"Index\")\n}", "func GetIndex(w http.ResponseWriter, req *http.Request, app *App) {\n\tscheme := \"http\"\n\tif req.TLS != nil {\n\t\tscheme = \"https\"\n\t}\n\tbase := []string{scheme, \"://\", req.Host, app.Config.General.Prefix}\n\trender(w, \"index\", map[string]interface{}{\"base\": strings.Join(base, \"\"), \"hideNav\": true}, app)\n}" ]
[ "0.80268294", "0.790578", "0.77338165", "0.7715898", "0.7689121", "0.7684665", "0.76702815", "0.76702815", "0.7656754", "0.7542163", "0.7517239", "0.7509632", "0.7509632", "0.75040925", "0.7436748", "0.74282384", "0.7349767", "0.73343587", "0.73327005", "0.7326263", "0.73177403", "0.7304866", "0.7275821", "0.72579914", "0.7216298", "0.7169393", "0.7164979", "0.7164468", "0.7141333", "0.7127708", "0.71245384", "0.710656", "0.7099273", "0.70555234", "0.7055481", "0.7039714", "0.7037446", "0.70371425", "0.7013888", "0.7012538", "0.70101404", "0.7007724", "0.7006772", "0.69973075", "0.69936067", "0.698247", "0.6967889", "0.6944416", "0.69417375", "0.6934144", "0.69246686", "0.6917409", "0.69160306", "0.691399", "0.69060457", "0.6903803", "0.68934405", "0.6875425", "0.68679684", "0.6866903", "0.6865839", "0.68557686", "0.68537176", "0.6831742", "0.6828569", "0.6825229", "0.6820908", "0.6820558", "0.68121725", "0.67961967", "0.6791418", "0.67848283", "0.6783686", "0.67785496", "0.67622095", "0.67572725", "0.67552716", "0.6752654", "0.6751508", "0.6740243", "0.6733264", "0.67287946", "0.67262775", "0.67190534", "0.6709589", "0.6707917", "0.6704465", "0.6701847", "0.6692577", "0.66899353", "0.6684525", "0.668016", "0.66731346", "0.6655969", "0.6643242", "0.66185", "0.6617404", "0.66122353", "0.6611395", "0.66108817", "0.6607039" ]
0.0
-1
ServeHTTP is a regular serve func except the first argument, passed as a copy, is unused. sse.Writer is there for writes.
func (sse *SSE) ServeHTTP(_ http.ResponseWriter, r *http.Request) { w := sse.Writer data, _, err := Updates(r, sse.Params) if err != nil { if _, ok := err.(params.RenamedConstError); ok { http.Redirect(w, r, err.Error(), http.StatusFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) } text, err := json.Marshal(data) if err != nil { sse.Errord = true // what would http.Error do if sse.SetHeader("Content-Type", "text/plain; charset=utf-8") { w.WriteHeader(http.StatusInternalServerError) } fmt.Fprintln(w, err.Error()) return } sse.SetHeader("Content-Type", "text/event-stream") if _, err := w.Write(append(append([]byte("data: "), text...), []byte("\n\n")...)); err != nil { sse.Errord = true } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mw *Stats) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tbeginning, recorder := mw.Begin(w)\n\n\tnext(recorder, r)\n\n\tmw.End(beginning, WithRecorder(recorder))\n}", "func (f MiddlewareFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, next func()) {\n\tf(w, r, next)\n}", "func (m middleware) serve(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tm.fn(w, r, ps, m.next.serve)\n}", "func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)", "func (k *Kite) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tk.muxer.ServeHTTP(w, req)\n}", "func (s prodAssetServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\touturl := *s.url\n\torigPath := req.URL.Path\n\tif !strings.HasPrefix(origPath, \"/static/\") {\n\t\t// redirect everything to the main entry point.\n\t\torigPath = \"index.html\"\n\t}\n\n\touturl.Path = path.Join(outurl.Path, origPath)\n\toutreq, err := http.NewRequest(\"GET\", outurl.String(), bytes.NewBuffer(nil))\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_, _ = w.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tcopyHeader(outreq.Header, req.Header)\n\toutres, err := http.DefaultClient.Do(outreq)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_, _ = w.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\t_ = outres.Body.Close()\n\t}()\n\n\tcopyHeader(w.Header(), outres.Header)\n\tw.WriteHeader(outres.StatusCode)\n\t_, _ = io.Copy(w, outres.Body)\n}", "func (sw *subware) serve(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tsw.middleware.serve(w, r, ps)\n}", "func (f HandlerFunc) ServeHttp(w ResponseWriter, r *Request){\n f(w, r)\n}", "func (s *ConcurrentServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.router.ServeHTTP(w, r)\n}", "func (w HandlerFuncWrapper) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tw(next)(rw, r)\n}", "func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.HTTP.Handler.ServeHTTP(w, r)\n}", "func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif h.Skip(r) {\n\t\th.Next.ServeHTTP(w, r)\n\t\treturn\n\t}\n\tvar written int64\n\tvar status = -1\n\n\twp := writerProxy{\n\t\th: func() http.Header {\n\t\t\treturn w.Header()\n\t\t},\n\t\tw: func(bytes []byte) (int, error) {\n\t\t\tbw, err := w.Write(bytes)\n\t\t\twritten += int64(bw)\n\t\t\treturn bw, err\n\t\t},\n\t\twh: func(code int) {\n\t\t\tstatus = code\n\t\t\tw.WriteHeader(code)\n\t\t},\n\t}\n\n\tstart := time.Now()\n\th.Next.ServeHTTP(wp, r)\n\tduration := time.Now().Sub(start)\n\n\t// Use default status.\n\tif status == -1 {\n\t\tstatus = 200\n\t}\n\n\th.Logger(r, status, written, duration)\n}", "func (rh *RandomHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t// Increment serveCounter every time we serve a page.\n\trh.serveCounter.Inc()\n\n\tn := rand.Float64()\n\t// Track the cumulative values served.\n\trh.valueCounter.Add(n)\n\n\tfmt.Fprintf(w, \"%v\", n)\n}", "func (s *Service) serveHTTP() {\n\thandler := &Handler{\n\t\tDatabase: s.Database,\n\t\tRetentionPolicy: s.RetentionPolicy,\n\t\tPointsWriter: s.PointsWriter,\n\t\tLogger: s.Logger,\n\t\tstats: s.stats,\n\t}\n\tsrv := &http.Server{Handler: handler}\n\tsrv.Serve(s.httpln)\n}", "func (t Telemetry) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tt.rCount.Mark(1)\n\tsw := MakeLogger(w)\n\n\tstart := time.Now()\n\tt.inner.ServeHTTP(sw, r)\n\tt.tmr.Update(int64(time.Since(start) / time.Millisecond))\n\n\tif sw.Status() >= 300 {\n\t\tt.fCount.Mark(1)\n\t} else {\n\t\tt.sCount.Mark(1)\n\t}\n\n}", "func (w HandlerWrapper) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tw(next).ServeHTTP(rw, r)\n}", "func (p *Proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tjob := p.stream.NewJob(\"proxy.serve\")\n\n\t// Add headers\n\tfor key, vals := range p.lastResponseHeaders {\n\t\tfor _, val := range vals {\n\t\t\tw.Header().Set(key, val)\n\t\t}\n\t}\n\tw.Header().Set(\"X-OpenBazaar\", \"Trade free!\")\n\n\t// Write body\n\t_, err := w.Write(p.lastResponseBody)\n\tif err != nil {\n\t\tjob.EventErr(\"write\", err)\n\t\tjob.Complete(health.Error)\n\t}\n\n\tjob.Complete(health.Success)\n}", "func (t *Timer) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tdefer t.UpdateSince(time.Now())\n\tt.handler.ServeHTTP(w, r)\n}", "func (s static) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.handler.ServeHTTP(w, r)\n}", "func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\th(context.TODO(), w, r)\n}", "func serveHTTP(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {\n\t// Checks if the URL contains the baseURL and strips it. Otherwise, it just\n\t// returns a 404 error because we're not supposed to be here!\n\tp := strings.TrimPrefix(r.URL.Path, c.FM.BaseURL)\n\n\tif len(p) >= len(r.URL.Path) && c.FM.BaseURL != \"\" {\n\t\treturn http.StatusNotFound, nil\n\t}\n\n\tr.URL.Path = p\n\n\t// Check if this request is made to the service worker. If so,\n\t// pass it through a template to add the needed variables.\n\tif r.URL.Path == \"/sw.js\" {\n\t\treturn renderFile(\n\t\t\tw,\n\t\t\tc.FM.assets.MustString(\"sw.js\"),\n\t\t\t\"application/javascript\",\n\t\t\tc,\n\t\t)\n\t}\n\n\t// Checks if this request is made to the static assets folder. If so, and\n\t// if it is a GET request, returns with the asset. Otherwise, returns\n\t// a status not implemented.\n\tif matchURL(r.URL.Path, \"/static\") {\n\t\tif r.Method != http.MethodGet {\n\t\t\treturn http.StatusNotImplemented, nil\n\t\t}\n\n\t\treturn staticHandler(c, w, r)\n\t}\n\n\t// Checks if this request is made to the API and directs to the\n\t// API handler if so.\n\tif matchURL(r.URL.Path, \"/api\") {\n\t\tr.URL.Path = strings.TrimPrefix(r.URL.Path, \"/api\")\n\t\treturn apiHandler(c, w, r)\n\t}\n\n\t// Any other request should show the index.html file.\n\tw.Header().Set(\"x-frame-options\", \"SAMEORIGIN\")\n\tw.Header().Set(\"x-content-type\", \"nosniff\")\n\tw.Header().Set(\"x-xss-protection\", \"1; mode=block\")\n\n\treturn renderFile(\n\t\tw,\n\t\tc.FM.assets.MustString(\"index.html\"),\n\t\t\"text/html\",\n\t\tc,\n\t)\n}", "func (h TestServerHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {\n\twriter.WriteHeader(h.StatusCode)\n\twriter.Header().Add(\"Content-Type\", \"text/plain\")\n\t_, _ = writer.Write([]byte(h.Content))\n}", "func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {\n\tf(w, r)\n}", "func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {\n\tf(w, r)\n}", "func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {\n\tf(w, r)\n}", "func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {\n\tf(w, r)\n}", "func (b *backend) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n}", "func (m hotdog) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Any code in this func\")\n}", "func (es *EventSource) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tvar startID int\n\tif start := r.Header.Get(\"Last-Event-ID\"); start != \"\" {\n\t\tif _, err := fmt.Sscanf(start, \"%d\", &startID); err != nil {\n\t\t\thttp.Error(w, \"bad Last-Event-ID\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tstartID++\n\t}\n\n\tw.Header().Set(\"Content-Type\", ContentType)\n\tw.Header().Set(\"Connection\", \"keep-alive\")\n\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\tw.Header().Set(\"Transfer-Encoding\", \"chunked\")\n\tw.WriteHeader(200)\n\n\tflusher, ok := w.(http.Flusher)\n\tif !ok {\n\t\tpanic(\"esource: ServeHTTP called without a Flusher\")\n\t}\n\n\tlog.Printf(\"esource: [%s] starting stream\", r.RemoteAddr)\n\n\told, events := es.Tee(startID)\n\tfor _, event := range old {\n\t\tif _, err := event.WriteTo(w); err != nil {\n\t\t\tlog.Printf(\"esource: [%s] failed to write backlogged event %+v\", r.RemoteAddr, event)\n\t\t\treturn\n\t\t}\n\t}\n\tflusher.Flush()\n\n\tfor event := range events {\n\t\tif _, err := event.WriteTo(w); err != nil {\n\t\t\tlog.Printf(\"esource: [%s] failed to write event %+v\", r.RemoteAddr, event)\n\t\t\tfmt.Fprintln(w, \"\\nretry: 0\\n\")\n\t\t\treturn\n\t\t}\n\t\tflusher.Flush()\n\t}\n\n\tlog.Printf(\"esource: [%s] complete\", r.RemoteAddr)\n}", "func (hw *CtxHandlerWraper) ServeHTTP(ctx context.Context, w http.ResponseWriter, req *http.Request) error {\n\treturn hw.Func(ctx, w, req)\n}", "func (s *ServeSeq) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ti := &intrespwriter{parent: w, written: false}\n\tfor idx, h := range s.handlers {\n\t\ti.canskip = (idx != len(s.handlers)-1)\n\t\ti.skip = false\n\t\th.ServeHTTP(i, r)\n\t\tif i.written {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (f HandlerFunc) ServeHTTP(ctx *Context) {\n\tf(ctx)\n}", "func (s *Server) ServeHTTP(res http.ResponseWriter, req *http.Request) {\n\ts.Handler.ServeHTTP(res, req)\n}", "func (ot *openTelemetryWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {\n\tn := &nextCall{\n\t\tnext: next,\n\t\terr: nil,\n\t}\n\tot.handler.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), nextCallCtxKey, n)))\n\n\treturn n.err\n}", "func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\ts.Router().ServeHTTP(context.Wrap(w), req)\n}", "func (ot *openTelemetryWrapper) serveHTTP(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tot.propagators.Inject(ctx, propagation.HeaderCarrier(r.Header))\n\tspanCtx := trace.SpanContextFromContext(ctx)\n\tif spanCtx.IsValid() {\n\t\tif extra, ok := ctx.Value(caddyhttp.ExtraLogFieldsCtxKey).(*caddyhttp.ExtraLogFields); ok {\n\t\t\textra.Add(zap.String(\"traceID\", spanCtx.TraceID().String()))\n\t\t}\n\t}\n\tnext := ctx.Value(nextCallCtxKey).(*nextCall)\n\tnext.err = next.next.ServeHTTP(w, r)\n}", "func (m *RegExpMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n}", "func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tfmt.Printf(\"%s %s %s\\n\", r.RemoteAddr, r.Method, r.URL.Path)\n\tt1 := time.Now()\n\thandler.store.ExpireSessions()\n\treq := newReqImpl(w, r, handler.store)\n\thandler.serve(req)\n\tif req.html != \"\" {\n\t\tio.WriteString(w, req.html)\n\t} else if req.template != \"\" {\n\t\tt := template.New(\"\").Funcs(handler.funcmap)\n\t\tt, err := t.ParseGlob(handler.templatePattern)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = t.ExecuteTemplate(w, req.template, req.model)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else if req.redirect != \"\" {\n\t\thttp.Redirect(w, r, req.redirect, http.StatusFound)\n\t} else if req.status != 0 {\n\t\tmsg := http.StatusText(req.status)\n\t\thttp.Error(w, msg, req.status)\n\t} else {\n\t\tio.WriteString(w, \"no result\")\n\t}\n\td := time.Since(t1)\n\tfmt.Printf(\"%s %s %s - %f s\\n\", r.RemoteAddr, r.Method, r.URL.Path, float64(d)/1e9)\n}", "func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tmx.ServeHTTPContext(w, r, nil)\n}", "func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tpanic(fmt.Sprintf(\"httpx: ServeHTTP called on %v\", h))\n}", "func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tpanic(fmt.Sprintf(\"httpx: ServeHTTP called on %v\", h))\n}", "func (f *Forwarder) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tif f.log.GetLevel() >= log.DebugLevel {\n\t\tlogEntry := f.log.WithField(\"Request\", utils.DumpHttpRequest(req))\n\t\tlogEntry.Debug(\"vulcand/oxy/forward: begin ServeHttp on request\")\n\t\tdefer logEntry.Debug(\"vulcand/oxy/forward: completed ServeHttp on request\")\n\t}\n\n\tif f.stateListener != nil {\n\t\tf.stateListener(req.URL, StateConnected)\n\t\tdefer f.stateListener(req.URL, StateDisconnected)\n\t}\n\tif IsWebsocketRequest(req) {\n\t\tf.httpForwarder.serveWebSocket(w, req, f.handlerContext)\n\t} else {\n\t\tf.httpForwarder.serveHTTP(w, req, f.handlerContext)\n\t}\n}", "func (serv *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tc := serv.pool.Get().(*Context)\n\tc.reset(w, req)\n\n\tserv.handleHTTPRequest(c)\n\n\tserv.pool.Put(c)\n}", "func (c *PingMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next traffic.NextMiddlewareFunc) (http.ResponseWriter, *http.Request) {\n if r.URL.Path == \"/ping\" {\n fmt.Fprint(w, \"pong\\n\")\n\n return w, r\n }\n\n if nextMiddleware := next(); nextMiddleware != nil {\n arw := w.(*traffic.AppResponseWriter)\n arw.SetVar(\"ping\", \"pong\")\n w, r = nextMiddleware.ServeHTTP(w, r, next)\n }\n\n return w, r\n}", "func (m *metricsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tm.Handler.ServeHTTP(w, r)\n}", "func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.mux.ServeHTTP(w, r)\n}", "func (h HttpHandlerPipe) ServeHttpPipe(w ResponseWriter, r *http.Request, f *Pipeline) {\n\th.ServeHTTP(w, r)\n\tf.Next(w, r)\n}", "func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tses := newSession(w, req)\n\ts.Sessions <- ses\n\t<-ses.end\n}", "func (p *Proxy) HTTPServe() {\n\tvar prf interface {\n\t\tStop()\n\t}\n\n\t// We want to make sure the profile is stopped\n\t// exactly once (and only once), even if the\n\t// shutdown pre-hook does not run (which it may not)\n\tprofileStopOnce := sync.Once{}\n\n\tif p.enableProfiling {\n\t\tprofileStartOnce.Do(func() {\n\t\t\tprf = profile.Start()\n\t\t})\n\n\t\tdefer func() {\n\t\t\tprofileStopOnce.Do(prf.Stop)\n\t\t}()\n\t}\n\thttpSocket := bind.Socket(p.HTTPAddr)\n\tgraceful.Timeout(10 * time.Second)\n\tgraceful.PreHook(func() {\n\n\t\tif prf != nil {\n\t\t\tprofileStopOnce.Do(prf.Stop)\n\t\t}\n\n\t\tlog.Info(\"Terminating HTTP listener\")\n\t})\n\n\t// Ensure that the server responds to SIGUSR2 even\n\t// when *not* running under einhorn.\n\tgraceful.AddSignal(syscall.SIGUSR2, syscall.SIGHUP)\n\tgraceful.HandleSignals()\n\tgracefulSocket := graceful.WrapListener(httpSocket)\n\tlog.WithField(\"address\", p.HTTPAddr).Info(\"HTTP server listening\")\n\n\t// Signal that the HTTP server is listening\n\tatomic.AddInt32(p.numListeningHTTP, 1)\n\tdefer atomic.AddInt32(p.numListeningHTTP, -1)\n\tbind.Ready()\n\n\tif err := http.Serve(gracefulSocket, p.Handler()); err != nil {\n\t\tlog.WithError(err).Error(\"HTTP server shut down due to error\")\n\t}\n\tlog.Info(\"Stopped HTTP server\")\n\n\tgraceful.Shutdown()\n}", "func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\ts.router.ServeHTTP(w, req)\n}", "func serveHTTP(ech chan<- error, addr string) {\n\tif \"\" == addr || NO == addr {\n\t\treturn\n\t}\n\t/* Listen */\n\tl, err := net.Listen(\"tcp\", addr)\n\tif nil != err {\n\t\tech <- err\n\t\treturn\n\t}\n\tlog.Printf(\"Serving HTTP requests on %v\", l.Addr())\n\t/* Serve */\n\tech <- http.Serve(l, nil)\n}", "func (m hotdog) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tfmt.Fprintln(w,\"My power code here!\")\n}", "func (a anything) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Any code you want in this func\")\n}", "func (e *Exporter) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\te.handler.ServeHTTP(w, r)\n}", "func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tc := engine.pool.Get().(*Context)\n\tc.writermem.reset(w)\n\tc.Request = r\n\tc.reset()\n\n\tengine.handleHTTPRequest(c)\n\n\tengine.pool.Put(c)\n}", "func (i indexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"You are all my minions, %v, beware %v, %v!\\n\", r.RemoteAddr, r.Method, r.URL)\n\tif r.URL.Path != \"/\" {\n\t\tlog.Printf(\"Sirree, this is a wrong URL path: %v!\\n\", r.URL.Path)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tfmt.Fprintf(w, i.pageNotFound)\n\t\treturn\n\t}\n\tif r.Method != \"GET\" {\n\t\tlog.Printf(\"Madam, the method thou art using is wrong: %v!\\n\", r.Method)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, i.pageBadRequest)\n\t\treturn\n\t}\n\tdata := pageData{\n\t\tTitle: \"Welcome\",\n\t\tVersion: fmt.Sprintf(\"This is version %v\", i.version),\n\t}\n\tif err := i.tmpl.Execute(w, data); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tt := time.Now()\n\tww := buildLoggingWriter(w)\n\tif h.serveHTTP(ww, r) {\n\t\tww.LogAccess(r, time.Now().Sub(t))\n\t}\n}", "func (s *SimpleStaticFilesServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif s.testMode && strings.HasPrefix(r.URL.String(), GOPATH_PREFIX) {\n\t\tGopathLookup(w, r, strings.TrimPrefix(r.URL.String(), GOPATH_PREFIX))\n\t\treturn\n\t}\n\tlog.Printf(\"[STATIC CONTENT (%s)]: %v\", s.staticDir, r.URL.String())\n\ts.fs.ServeHTTP(w, r)\n}", "func (a *Application) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\t// log all unhandled panic's\n\t// todo: check performance impact\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\ta.Emit(\"error\", r)\n\t\t\tpanic(r)\n\t\t}\n\t}()\n\n\tctx := makeCtx(req, w)\n\trequest := ctx.Req\n\tresponse := ctx.Res\n\n\tdefer response.flush()\n\n\t///////////////////////////////////////////////////////////////////\n\t// Catch Neo Assertions\n\t///////////////////////////////////////////////////////////////////\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr, ok := r.(*NeoAssertError)\n\n\t\t\tif ok {\n\t\t\t\tresponse.Raw(err.message, err.status)\n\t\t\t\ta.Emit(\"error\", r)\n\t\t\t} else {\n\t\t\t\t// bubble panic\n\t\t\t\tpanic(r)\n\t\t\t}\n\t\t}\n\t}()\n\n\t///////////////////////////////////////////////////////////////////\n\t// Static File Serving\n\t///////////////////////////////////////////////////////////////////\n\tif a.static != nil {\n\t\t// check if file can be served\n\t\tfile, err := a.static.match(req.URL.Path)\n\n\t\tif err == nil {\n\t\t\th := func(ctx *Ctx) {\n\t\t\t\tresponse.skipFlush()\n\t\t\t\tresponse.serveFile(file)\n\t\t\t}\n\n\t\t\tfn := compose(merge(a.middlewares, []appliable{handler(h)}))\n\t\t\tfn(ctx)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Debug(\"result not found in static\")\n\t}\n\n\t///////////////////////////////////////////////////////////////////\n\t// Route Matching\n\t///////////////////////////////////////////////////////////////////\n\troute, err := a.match(request)\n\n\tif err != nil {\n\t\tlog.Debugf(\"route %s not found\", req.URL.Path)\n\n\t\t// dummy route handler\n\t\th := func(ctx *Ctx) {\n\t\t\tresponse.Status = http.StatusNotFound\n\t\t}\n\n\t\tcompose(merge(a.middlewares, []appliable{handler(h)}))(ctx)\n\t} else {\n\t\troute.fnChain(ctx)\n\t}\n}", "func (s Thumbnails) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.mux.ServeHTTP(w, r)\n}", "func (h *Handler) ServeHTTP(ctx context.Context, event cloudevents.Event, resp *cloudevents.EventResponse) error {\n\t// Hand work off to the current multi channel fanout handler.\n\th.logger.Debug(\"ServeHTTP request received\")\n\treturn h.getMultiChannelFanoutHandler().ServeHTTP(ctx, event, resp)\n}", "func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.router.ServeHTTP(w, r)\n}", "func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.router.ServeHTTP(w, r)\n}", "func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.router.ServeHTTP(w, r)\n}", "func (m *Module) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\n\t// Create a context from the response and request\n\tctx := web.NewContext(w, r)\n\n\t// Serve the app using the new context\n\tm.Serve(ctx)\n}", "func (self *Direct) ServeHTTP(w http.ResponseWriter, r *http.Request) (err error) {\n\tif r.Method == \"CONNECT\" {\n\t\tglog.Println(\"this function can not handle CONNECT method\")\n\t\thttp.Error(w, r.Method, http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\tstart := time.Now()\n\n\t// Client.Do is different from DefaultTransport.RoundTrip ...\n\t// Client.Do will change some part of request as a new request of the server.\n\t// The underlying RoundTrip never changes anything of the request.\n\tresp, err := self.Tr.RoundTrip(r)\n\tif err != nil {\n\t\tif nerr, ok := err.(net.Error); ok && nerr.Timeout() {\n\t\t\tglog.Errorf(\"RoundTrip: %s, reproxy...\\n\", err.Error())\n\t\t\terr = ErrShouldProxy\n\t\t\treturn\n\t\t}\n\t\tglog.Errorf(\"RoundTrip: %s\\n\", err.Error())\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\t// please prepare header first and write them\n\tCopyHeader(w, resp)\n\tw.WriteHeader(resp.StatusCode)\n\n\tn, err := io.Copy(w, resp.Body)\n\tif err != nil {\n\t\tglog.Printf(\"Copy: %s\", err.Error())\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\td := BeautifyDuration(time.Since(start))\n\tndtos := BeautifySize(n)\n\tglog.Infof(\"RESPONSE %s %s in %s <-%s\", r.URL.Host, resp.Status, d, ndtos)\n\treturn\n}", "func (h httpHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tl := h.logger\n\tp := newPrinter(l)\n\tdefer p.flush()\n\n\tif hide := req.Context().Value(contextHide{}); hide != nil || p.checkFilter(req) {\n\t\th.next.ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\tif p.logger.Time {\n\t\tdefer p.printTimeRequest()()\n\t}\n\n\tif !p.logger.SkipRequestInfo {\n\t\tp.printRequestInfo(req)\n\t}\n\n\tif p.logger.TLS {\n\t\tp.printTLSInfo(req.TLS, true)\n\t\tp.printIncomingClientTLS(req.TLS)\n\t}\n\n\tp.printRequest(req)\n\n\trec := &responseRecorder{\n\t\tResponseWriter: w,\n\n\t\tstatusCode: http.StatusOK,\n\n\t\tmaxReadableBody: l.MaxResponseBody,\n\t\tbuf: &bytes.Buffer{},\n\t}\n\n\tdefer p.printServerResponse(req, rec)\n\th.next.ServeHTTP(rec, req)\n}", "func (h *SubscribeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tvar index, err = strconv.Atoi(r.Header.Get(\"Last-Event-ID\"))\n\tif r.Header.Get(\"Last-Event-ID\") != \"\" {\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tindex += 1\n\t}\n\n\t// Create a channel for subscribing to database updates.\n\tch := h.db.Subscribe(index)\n\tcloseNotifier := w.(http.CloseNotifier).CloseNotify()\n\n\t// Mark this as an SSE event stream.\n\tw.Header().Set(\"Content-Type\", \"text/event-stream\")\n\n\t// Continually stream updates as they come.\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-closeNotifier:\n\t\t\tbreak loop\n\n\t\tcase row := <-ch:\n\t\t\t// Encode row as JSON.\n\t\t\tb, err := json.Marshal(row)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\tbreak loop\n\t\t\t}\n\n\t\t\t// Send row as server-sent event.\n\t\t\tfmt.Fprintf(w, \"id: %d\\n\", row.Index())\n\t\t\tfmt.Fprintf(w, \"data: %s\\n\\n\", b)\n\t\t\tw.(http.Flusher).Flush()\n\t\t}\n\t}\n\n\t// Unsubscribe from the database when the connection is lost.\n\th.db.Unsubscribe(ch)\n}", "func (avd avocado) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"brought you by a handler\")\n}", "func (s *server) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\ts.router.ServeHTTP(rw, r)\n}", "func (t *Tunnel) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tt.proxy.ServeHTTP(w, r)\n}", "func (_m *MockHandler) ServeHTTP(_a0 http.ResponseWriter, _a1 *http.Request) {\n\t_m.Called(_a0, _a1)\n}", "func (con *Controller) ServeHTTP(res http.ResponseWriter, req *http.Request) {\n\tstartTime := time.Now()\n\n\tswitch con.Status {\n\tcase 0: // This will actually never show because this function won't run if the server is off\n\t\thttp.Error(res, \"The server is currently down and not serving requests.\", http.StatusServiceUnavailable)\n\t\treturn\n\tcase 1: // Normal\n\t\tbreak\n\tcase 2: // Maintenance mode\n\t\thttp.Error(res, \"The server is currently maintenance mode and not serving requests.\", http.StatusServiceUnavailable)\n\t\treturn\n\tcase 3: // This will actually never show because this function won't run if the server is off\n\t\thttp.Error(res, \"The server is currently restarting.\", http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\n\tpath := req.URL.Path[1:]\n\tif len(path) == 0 {\n\t\tpath = (con.DocumentRoot + \"index.html\")\n\t} else {\n\t\tpath = (con.DocumentRoot + path)\n\t}\n\n\tf, err := os.Open(path)\n\n\tif err != nil {\n\t\tcon.PublicLogger.Write(path + \"::\" + strconv.Itoa(http.StatusNotFound) + \"::\" + err.Error())\n\t\trouting.HttpThrowStatus(http.StatusNotFound, res)\n\t\treturn\n\t}\n\n\tcontentType, err := routing.GetContentType(path)\n\n\tif err != nil {\n\t\tcon.PublicLogger.Write(path + \"::\" + strconv.Itoa(http.StatusUnsupportedMediaType) + \"::\" + err.Error())\n\t\trouting.HttpThrowStatus(http.StatusUnsupportedMediaType, res)\n\t\treturn\n\t}\n\n\tres.Header().Add(\"Content-Type\", contentType)\n\t_, err = io.Copy(res, f)\n\n\tif err != nil {\n\t\tcon.PublicLogger.Write(path + \"::\" + strconv.Itoa(http.StatusInternalServerError) + \"::\" + err.Error())\n\t\trouting.HttpThrowStatus(http.StatusInternalServerError, res)\n\t\treturn\n\t}\n\n\telapsedTime := time.Since(startTime)\n\tcon.LoadTimeLogger.Write(path + \" rendered in \" + strconv.FormatFloat(elapsedTime.Seconds(), 'f', 6, 64) + \" seconds\")\n}", "func (b *Builder) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tb.mux.ServeHTTP(w, req)\n}", "func ServeHTTP(w http.ResponseWriter, r *http.Request, h HandlerFunc) error {\n\theaderSaver := saveHeaders(w.Header())\n\theaderHop := MakeHeaderHop()\n\n\theaderHop.Del(r.Header)\n\n\tlog.Printf(\"recv a requests to proxy to: %s\", r.RemoteAddr)\n\n\tif err := h(w, r); err != nil {\n\t\tlog.Printf(\"could not proxy: %v\\n\", err)\n\t\treturn err\n\t}\n\n\t// response to client\n\theaderHop.Del(w.Header())\n\theaderSaver.set(&r.Header)\n\n\treturn nil\n}", "func (m *Module) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\n\t// Create a context from the response and request\n\tctx := newContext(w, r)\n\n\t// Serve the app using the new context\n\tm.Serve(ctx)\n}", "func (s *StaticDataElement) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tfallthrough\n\tcase \"HEAD\":\n\t\tw.Header().Set(\"Last-Modified\", s.Time().UTC().Format(http.TimeFormat))\n\t\tif ims := r.Header.Get(\"If-Modified-Since\"); ims != \"\" {\n\t\t\tif t, e := time.Parse(http.TimeFormat, ims); e == nil && !t.Before(s.Time()) {\n\t\t\t\tw.WriteHeader(http.StatusNotModified)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif r.Method == \"GET\" {\n\t\t\tw.Header().Set(\"Content-type\", s.Mime)\n\t\t\t_, _ = w.Write(s.Data)\n\t\t}\n\t\treturn\n\tcase \"POST\":\n\t\tw.Header().Set(\"Allow\", \"Get\")\n\t\tw.Header().Add(\"Allow\", \"Head\")\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\tdefault:\n\t\tw.WriteHeader(http.StatusNotImplemented)\n\t\treturn\n\t}\n\treturn\n}", "func (s *Server) HTTPServe() {\n\tvar prf interface {\n\t\tStop()\n\t}\n\n\t// We want to make sure the profile is stopped\n\t// exactly once (and only once), even if the\n\t// shutdown pre-hook does not run (which it may not)\n\tprofileStopOnce := sync.Once{}\n\n\tif s.enableProfiling {\n\t\tprofileStartOnce.Do(func() {\n\t\t\tprf = profile.Start()\n\t\t})\n\n\t\tdefer func() {\n\t\t\tprofileStopOnce.Do(prf.Stop)\n\t\t}()\n\t}\n\thttpSocket := bind.Socket(s.HTTPAddr)\n\tgraceful.Timeout(10 * time.Second)\n\tgraceful.PreHook(func() {\n\n\t\tif prf != nil {\n\t\t\tprofileStopOnce.Do(prf.Stop)\n\t\t}\n\n\t\ts.logger.Info(\"Terminating HTTP listener\")\n\t})\n\n\t// Ensure that the server responds to SIGUSR2 even\n\t// when *not* running under einhorn.\n\tgraceful.AddSignal(syscall.SIGUSR2, syscall.SIGHUP)\n\tgraceful.HandleSignals()\n\tgracefulSocket := graceful.WrapListener(httpSocket)\n\ts.logger.WithField(\"address\", s.HTTPAddr).Info(\"HTTP server listening\")\n\n\t// Signal that the HTTP server is starting\n\tatomic.AddInt32(s.numListeningHTTP, 1)\n\tdefer atomic.AddInt32(s.numListeningHTTP, -1)\n\tbind.Ready()\n\n\tif err := http.Serve(gracefulSocket, s.Handler()); err != nil {\n\t\ts.logger.WithError(err).Error(\"HTTP server shut down due to error\")\n\t}\n\ts.logger.Info(\"Stopped HTTP server\")\n\n\tgraceful.Shutdown()\n}", "func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tengine.handleHTTPRequest(w, req)\n}", "func (s *RegistryServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.muxer.ServeHTTP(w, r)\n}", "func (h stubbingHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\tresponses := h.holder.responses\n\tif len(responses) > 0 {\n\t\tresp := responses[0]\n\t\tw.WriteHeader(resp.responseCode)\n\t\t_, err := w.Write([]byte(resp.body))\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Can't write the response: %v\", err)\n\t\t}\n\n\t\tswitch resp.times {\n\t\tcase 0:\n\t\t\tbreak\n\t\tcase 1:\n\t\t\tshortened := responses[1:]\n\t\t\th.holder.responses = shortened\n\t\tdefault:\n\t\t\tresp.times--\n\t\t}\n\t} else {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t}\n}", "func (m *Macross) ServeHTTP(ctx *fasthttp.RequestCtx) {\n\tc := m.AcquireContext()\n\tc.Reset(ctx)\n\tc.handlers, c.pnames = m.find(string(ctx.Method()), string(ctx.Path()), c.pvalues)\n\tif err := c.Next(); err != nil {\n\t\tm.HandleError(c, err)\n\t}\n\tm.ReleaseContext(c)\n}", "func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\n\tpath, err := filepath.Abs(r.URL.Path)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpath = filepath.Join(h.staticPath, r.URL.Path)\n\n\t_, err = os.Stat(path)\n\tif os.IsNotExist(err) {\n\t\thttp.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))\n\t\treturn\n\t} else if err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttp.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)\n}", "func (m *MockedNextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tm.hasBeenCalled = true\n\tm.request = r\n\tw.Write([]byte(\"Next handler has been called\"))\n\tw.WriteHeader(200)\n}", "func ServeSingleHTTP(w http.ResponseWriter, r *http.Request) {\n\tif !webMux.routesSetup {\n\t\tinitRoutes()\n\t}\n\n\t// Allow cross-origin resource sharing.\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\n\twebMux.ServeHTTP(w, r)\n}", "func (c *Controller) serveHTTP(w http.ResponseWriter, req *http.Request) {\n\tif strings.Contains(req.URL.Path, mutateWebHook) {\n\t\tc.processMutateRequest(w, req)\n\t} else {\n\t\thttp.Error(w, \"Unsupported request\", http.StatusNotFound)\n\t}\n}", "func (s *server) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\t// Get request and response from the pool.\n\n\treq := s.requestPool.Get().(*Request)\n\tres := s.responsePool.Get().(*Response)\n\n\t// Tie the request body and the standard request body together.\n\n\tr.Body = &requestBody{\n\t\tr: req,\n\t\thr: r,\n\t\trc: r.Body,\n\t}\n\n\t// Reset the request.\n\n\treq.Air = s.a\n\treq.SetHTTPRequest(r)\n\treq.res = res\n\treq.params = req.params[:0]\n\treq.routeParamNames = nil\n\treq.routeParamValues = nil\n\treq.parseRouteParamsOnce = &sync.Once{}\n\treq.parseOtherParamsOnce = &sync.Once{}\n\tfor key := range req.values {\n\t\tdelete(req.values, key)\n\t}\n\n\treq.localizedString = nil\n\n\t// Reset the response.\n\n\tres.Air = s.a\n\tres.SetHTTPResponseWriter(&responseWriter{\n\t\tr: res,\n\t\trw: rw,\n\t})\n\tres.Status = http.StatusOK\n\tres.ContentLength = -1\n\tres.Written = false\n\tres.Minified = false\n\tres.Gzipped = false\n\tres.req = req\n\tres.ohrw = rw\n\tres.servingContent = false\n\tres.serveContentError = nil\n\tres.reverseProxying = false\n\tres.deferredFuncs = res.deferredFuncs[:0]\n\n\t// Chain the gases stack.\n\n\th := func(req *Request, res *Response) error {\n\t\th := s.a.router.route(req)\n\t\tfor i := len(s.a.Gases) - 1; i >= 0; i-- {\n\t\t\th = s.a.Gases[i](h)\n\t\t}\n\n\t\treturn h(req, res)\n\t}\n\n\t// Chain the pregases stack.\n\n\tfor i := len(s.a.Pregases) - 1; i >= 0; i-- {\n\t\th = s.a.Pregases[i](h)\n\t}\n\n\t// Execute the chain.\n\n\tif err := h(req, res); err != nil {\n\t\tif !res.Written && res.Status < http.StatusBadRequest {\n\t\t\tres.Status = http.StatusInternalServerError\n\t\t}\n\n\t\ts.a.ErrorHandler(err, req, res)\n\t}\n\n\t// Execute the deferred functions.\n\n\tfor i := len(res.deferredFuncs) - 1; i >= 0; i-- {\n\t\tres.deferredFuncs[i]()\n\t}\n\n\t// Put the route param values back to the pool.\n\n\tif req.routeParamValues != nil {\n\t\ts.a.router.routeParamValuesPool.Put(req.routeParamValues)\n\t}\n\n\t// Put the request and response back to the pool.\n\n\ts.requestPool.Put(req)\n\ts.responsePool.Put(res)\n}", "func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t// Serve data with a method of http.ResponseWriter.\n\tw.Write([]byte(\"You learned Go in Y minutes!\"))\n}", "func (t *staticTemplateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif err := t.templ.Execute(w, t.data); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\tw.Header().Set(\"Vary\", \"Accept\")\n\n\tif !h.acceptable(r.Header.Get(\"Accept\")) {\n\t\tw.WriteHeader(http.StatusNotAcceptable)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/event-stream\")\n\tw.WriteHeader(http.StatusOK)\n\n\tvar stop <-chan bool\n\n\tif notifier, ok := w.(http.CloseNotifier); ok {\n\t\tstop = notifier.CloseNotify()\n\t}\n\n\th(r.Header.Get(\"Last-Event-Id\"), NewEncoder(w), stop)\n}", "func (srv *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tif srv.handler != nil {\n\t\tsrv.handler.ServeHTTP(w, req)\n\t\treturn\n\t}\n\tsrv.routes.ServeHTTP(w, req)\n}", "func (a *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tdefer func() {\n\t\tif x := recover(); x != nil {\n\t\t\terr = fmt.Errorf(\"ws: %v\", x)\n\t\t}\n\t\tfinally(w, err)\n\t}()\n\n\tpath := r.URL.Path\n\tif len(path) < 1 || path[0] != '/' {\n\t\tpath = \"/\" + path\n\t}\n\tif r.Method == http.MethodOptions && path == \"/*\" {\n\t\tw.Header().Add(\"Allow\", allAllow)\n\t\terr = Status(http.StatusOK, \"\")\n\t\treturn\n\t}\n\n\tctx := ctxPool.Get().(*Context)\n\tdefer ctxPool.Put(ctx)\n\tctx.Request = r\n\tctx.ResponseWriter = w\n\tctx.Path = path\n\tctx.code = 0\n\tctx.datas = make(map[string]interface{})\n\tctx.params = make(map[string]string)\n\tctx.querys = nil\n\tctx.router = a\n\tctx.index = -len(a.middlewares)\n\terr = ctx.Next()\n}", "func (handler ShortURLForwardingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close()\n\tif r.Method == http.MethodPut {\n\t\thandler.handleAddingNewShortURL(w, r)\n\t} else {\n\t\thandler.handleGettingShortURL(w, r)\n\t}\n}", "func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\n\tsession, state, err := m.initializeSession(r)\n\tif err != nil {\n\t\tm.Logger.Printf(\"couldn't initialise session: %+v\", err)\n\t\thttp.Error(w, \"couldn't initialise session\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tctx = context.WithValue(ctx, ctxStateKey, state)\n\tr = r.WithContext(ctx)\n\n\terr = m.setupAccessToken(ctx, w, r)\n\tif err != nil {\n\t\t// Access token is not set in request\n\t\tm.Logger.Printf(\"couldn't setup access token: %+v\", err)\n\t}\n\n\twriter := &sessionWriter{\n\t\tsessionStore: m.SessionStore,\n\t\tsession: session,\n\t\tstate: state,\n\t\tlogger: m.Logger,\n\t\tr: r,\n\t\tResponseWriter: w,\n\t}\n\tm.mux.ServeHTTP(writer, r)\n}", "func (l *httpHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {\n\turi := request.RequestURI\n\n\tif uri == \"\" || uri == \"/\" || uri == URIIndexPrefix {\n\t\tresponseServerList(response)\n\n\t\treturn\n\t}\n\n\tif strings.HasPrefix(uri, URIIndexPrefix+\"/\") {\n\t\tserverID := uri[len(URIIndexPrefix)+1:]\n\t\t_, ok := serverDB[serverID]\n\n\t\tif !ok {\n\t\t\tresponse.WriteHeader(http.StatusNotFound)\n\n\t\t\treturn\n\t\t}\n\n\t\trouteToServerIndex(response, serverID)\n\n\t\treturn\n\t}\n\n\ttailServerID := \"\"\n\tif uri == URITailPrefix {\n\t\ttailServerID = DefaultServerID\n\t} else if strings.HasPrefix(uri, URITailPrefix+\"/\") {\n\t\ttailServerID = uri[len(URITailPrefix)+1:]\n\t\tif _, ok := serverDB[tailServerID]; !ok {\n\t\t\tresponse.WriteHeader(http.StatusNotFound)\n\n\t\t\treturn\n\t\t}\n\t}\n\n\tif tailServerID != \"\" {\n\t\tstartWebsocketTransfer(response, request, tailServerID)\n\n\t\treturn\n\t}\n\n\tresponseServerList(response)\n}", "func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tr.HandleFunc(w, req)\n}", "func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n // get the absolute path to prevent directory traversal\n\tpath, err := filepath.Abs(r.URL.Path)\n\tif err != nil {\n // if we failed to get the absolute path respond with a 400 bad request\n // and stop\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n // prepend the path with the path to the static directory\n\tpath = filepath.Join(h.staticPath, path)\n\n // check whether a file exists at the given path\n\t_, err = os.Stat(path)\n\tif os.IsNotExist(err) {\n\t\t// file does not exist, serve index.html\n\t\thttp.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))\n\t\treturn\n\t} else if err != nil {\n // if we got an error (that wasn't that the file doesn't exist) stating the\n // file, return a 500 internal server error and stop\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n // otherwise, use http.FileServer to serve the static dir\n\thttp.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)\n}", "func serveHTTP(value interface{}, w http.ResponseWriter, r *http.Request) bool {\n\tswitch fn := value.(type) {\n\tcase func(http.ResponseWriter, *http.Request):\n\t\tfn(w, r)\n\t\treturn true\n\t}\n\treturn false\n}", "func (s Sample) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n fmt.Fprint(w, \"<h1>Welcome to Go.Land Server!</h1>\")\n}", "func (h *Handler) serveServers(w http.ResponseWriter, r *http.Request) {}" ]
[ "0.6951916", "0.6677218", "0.66611326", "0.6659163", "0.66036826", "0.65062517", "0.6490767", "0.6455201", "0.6432141", "0.64305204", "0.64240736", "0.6365968", "0.635253", "0.62759244", "0.6265223", "0.6240166", "0.62350315", "0.62345415", "0.6224378", "0.6202612", "0.6189022", "0.6154214", "0.61497366", "0.61497366", "0.61497366", "0.61497366", "0.6145679", "0.6140432", "0.613213", "0.61040795", "0.6095694", "0.6083812", "0.6083305", "0.6066852", "0.6065363", "0.60498524", "0.60442346", "0.6039158", "0.60377496", "0.60267794", "0.60267794", "0.6026457", "0.60190797", "0.60079604", "0.60056275", "0.59980524", "0.5989811", "0.5989404", "0.59852654", "0.59808105", "0.59793234", "0.5971335", "0.59678435", "0.596159", "0.5939658", "0.5930786", "0.5927288", "0.592442", "0.59237385", "0.5903532", "0.5899209", "0.58991826", "0.58991826", "0.58991826", "0.5897835", "0.58904666", "0.5885631", "0.5877298", "0.5877219", "0.58698004", "0.5869217", "0.5860292", "0.58547825", "0.58476716", "0.5846107", "0.5843574", "0.5842439", "0.5836007", "0.5827333", "0.58240193", "0.5818226", "0.5818002", "0.58137965", "0.5812305", "0.5806882", "0.580604", "0.5802835", "0.57985616", "0.57882124", "0.5787872", "0.57876706", "0.57865787", "0.5782738", "0.5781484", "0.5770537", "0.57643616", "0.57626075", "0.5762233", "0.57603776", "0.5757428" ]
0.6446284
8
IndexSSE serves SSE updates.
func (ss ServeSSE) IndexSSE(w http.ResponseWriter, r *http.Request) { sse := &SSE{Writer: w, Params: params.NewParams()} if LogHandler(ss.logRequests, sse).ServeHTTP(nil, r); sse.Errord { return } for { // loop is log-requests-free now := time.Now() time.Sleep(now.Truncate(time.Second).Add(time.Second).Sub(now)) // TODO redo with some channel to receive from, pushed in lastCopy by CollectLoop or something if sse.ServeHTTP(nil, r); sse.Errord { break } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (action *LedgerIndexAction) SSE(stream sse.Stream) {\n\taction.LoadRecords()\n\n\tif action.Err != nil {\n\t\tstream.Err(action.Err)\n\t\treturn\n\t}\n\n\trecords := action.Records[stream.SentCount():]\n\n\tfor _, record := range records {\n\t\tstream.Send(sse.Event{\n\t\t\tID: record.PagingToken(),\n\t\t\tData: NewLedgerResource(record),\n\t\t})\n\t}\n\n\tif stream.SentCount() >= int(action.Query.Limit) {\n\t\tstream.Done()\n\t}\n}", "func (action *TransactionIndexAction) SSE(stream sse.Stream) {\n\taction.Setup(\n\t\taction.EnsureHistoryFreshness,\n\t\taction.loadParams,\n\t\taction.checkAllowed,\n\t\taction.ValidateCursorWithinHistory,\n\t)\n\taction.Do(\n\t\tfunc() {\n\t\t\t// we will reuse this variable in sse, so re-initializing is required\n\t\t\taction.Records = []history.Transaction{}\n\t\t},\n\t\taction.loadRecords,\n\t\tfunc() {\n\t\t\trecords := action.Records[:]\n\n\t\t\tfor _, record := range records {\n\t\t\t\tres := resource.PopulateTransaction(record)\n\t\t\t\tstream.Send(sse.Event{\n\t\t\t\t\tID: res.PagingToken(),\n\t\t\t\t\tData: res,\n\t\t\t\t})\n\t\t\t\taction.PagingParams.Cursor = res.PagingToken()\n\t\t\t}\n\t\t},\n\t)\n}", "func (action *AccountIndexAction) SSE(stream sse.Stream) {\n\taction.Setup(action.LoadQuery)\n\taction.Do(\n\t\taction.LoadRecords,\n\t\tfunc() {\n\t\t\tstream.SetLimit(int(action.Query.Limit))\n\t\t\tvar res resource.HistoryAccount\n\t\t\tfor _, record := range action.Records[stream.SentCount():] {\n\t\t\t\tres.Populate(action.Ctx, record)\n\t\t\t\tstream.Send(sse.Event{ID: record.PagingToken(), Data: res})\n\t\t\t}\n\t\t},\n\t)\n}", "func (si ServeIndex) Index(w http.ResponseWriter, r *http.Request) {\n\tpara := params.NewParams()\n\tdata, _, err := Updates(r, para)\n\tif err != nil {\n\t\tif _, ok := err.(params.RenamedConstError); ok {\n\t\t\thttp.Redirect(w, r, err.Error(), http.StatusFound)\n\t\t\treturn\n\t\t}\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tdata[\"Distrib\"] = si.StaticData.Distrib\n\tdata[\"Exporting\"] = exportingCopy() // from ./ws.go\n\tdata[\"OstentUpgrade\"] = OstentUpgrade.Get()\n\tdata[\"OstentVersion\"] = si.StaticData.OstentVersion\n\tdata[\"TAGGEDbin\"] = si.StaticData.TAGGEDbin\n\n\tsi.IndexTemplate.Apply(w, struct{ Data IndexData }{Data: data})\n}", "func (sw ServeWS) IndexWS(w http.ResponseWriter, req *http.Request) {\n\t// Upgrader.Upgrade() has Origin check if .CheckOrigin is nil\n\tupgrader := &websocket.Upgrader{HandshakeTimeout: 5 * time.Second}\n\twsconn, err := upgrader.Upgrade(w, req, nil)\n\tif err != nil { // Upgrade() does http.Error() to the client\n\t\treturn\n\t}\n\n\tc := &conn{\n\t\tlogger: sw.logger,\n\t\tConn: wsconn,\n\n\t\tinitialRequest: req,\n\t\tlogRequests: sw.logRequests,\n\n\t\tpara: params.NewParams(),\n\t}\n\tconnections.reg(c)\n\tdefer func() {\n\t\tconnections.unreg(c)\n\t\tc.Conn.Close()\n\t}()\n\tfor {\n\t\trd := new(received)\n\t\tif err := c.Conn.ReadJSON(&rd); err != nil || !c.Process(rd, nil) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (action *AccountShowAction) SSE(stream sse.Stream) {\n\taction.Do(\n\t\taction.LoadQuery,\n\t\taction.LoadRecord,\n\t\taction.LoadResource,\n\t\tfunc() {\n\t\t\tstream.SetLimit(10)\n\t\t\tstream.Send(sse.Event{Data: action.Resource})\n\t\t},\n\t)\n}", "func (esHandler *ESHandler) Index(verses []Verse) error {\n\tctx := context.Background()\n\tserivce, err := esHandler.Client.BulkProcessor().Name(\"ScriptureProcessor\").Workers(2).BulkActions(1000).Do(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error initializing BulkProcessor\")\n\t}\n\tdefer serivce.Close()\n\n\tfor _, v := range verses {\n\t\tid := v.GetID()\n\t\tr := elastic.NewBulkIndexRequest().Index(esHandler.ESIndex).Type(\"Verse\").Id(id).Doc(v)\n\t\tserivce.Add(r)\n\t}\n\treturn nil\n}", "func (h *SubscribeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tvar index, err = strconv.Atoi(r.Header.Get(\"Last-Event-ID\"))\n\tif r.Header.Get(\"Last-Event-ID\") != \"\" {\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tindex += 1\n\t}\n\n\t// Create a channel for subscribing to database updates.\n\tch := h.db.Subscribe(index)\n\tcloseNotifier := w.(http.CloseNotifier).CloseNotify()\n\n\t// Mark this as an SSE event stream.\n\tw.Header().Set(\"Content-Type\", \"text/event-stream\")\n\n\t// Continually stream updates as they come.\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-closeNotifier:\n\t\t\tbreak loop\n\n\t\tcase row := <-ch:\n\t\t\t// Encode row as JSON.\n\t\t\tb, err := json.Marshal(row)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\tbreak loop\n\t\t\t}\n\n\t\t\t// Send row as server-sent event.\n\t\t\tfmt.Fprintf(w, \"id: %d\\n\", row.Index())\n\t\t\tfmt.Fprintf(w, \"data: %s\\n\\n\", b)\n\t\t\tw.(http.Flusher).Flush()\n\t\t}\n\t}\n\n\t// Unsubscribe from the database when the connection is lost.\n\th.db.Unsubscribe(ch)\n}", "func HandleSSE(handler func(http.ResponseWriter, *http.Request, *MessageFlusher, <-chan bool)) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tflusher, ok := makeNewMessageFlusher(w)\n\t\tif !ok {\n\t\t\thttp.Error(w, \"Streaming unsupported.\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"text/event-stream\")\n\t\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\t\tw.Header().Set(\"Connection\", \"keep-alive\")\n\t\tfmt.Println(\"opening connection\")\n\t\tcn, ok := w.(http.CloseNotifier)\n\t\tif !ok {\n\t\t\thttp.Error(w, \"Closing not supported\", http.StatusNotImplemented)\n\t\t\treturn\n\t\t}\n\t\tclose := cn.CloseNotify()\n\t\thandler(w, r, flusher, close)\n\t}\n}", "func (es *EventSource) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tvar startID int\n\tif start := r.Header.Get(\"Last-Event-ID\"); start != \"\" {\n\t\tif _, err := fmt.Sscanf(start, \"%d\", &startID); err != nil {\n\t\t\thttp.Error(w, \"bad Last-Event-ID\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tstartID++\n\t}\n\n\tw.Header().Set(\"Content-Type\", ContentType)\n\tw.Header().Set(\"Connection\", \"keep-alive\")\n\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\tw.Header().Set(\"Transfer-Encoding\", \"chunked\")\n\tw.WriteHeader(200)\n\n\tflusher, ok := w.(http.Flusher)\n\tif !ok {\n\t\tpanic(\"esource: ServeHTTP called without a Flusher\")\n\t}\n\n\tlog.Printf(\"esource: [%s] starting stream\", r.RemoteAddr)\n\n\told, events := es.Tee(startID)\n\tfor _, event := range old {\n\t\tif _, err := event.WriteTo(w); err != nil {\n\t\t\tlog.Printf(\"esource: [%s] failed to write backlogged event %+v\", r.RemoteAddr, event)\n\t\t\treturn\n\t\t}\n\t}\n\tflusher.Flush()\n\n\tfor event := range events {\n\t\tif _, err := event.WriteTo(w); err != nil {\n\t\t\tlog.Printf(\"esource: [%s] failed to write event %+v\", r.RemoteAddr, event)\n\t\t\tfmt.Fprintln(w, \"\\nretry: 0\\n\")\n\t\t\treturn\n\t\t}\n\t\tflusher.Flush()\n\t}\n\n\tlog.Printf(\"esource: [%s] complete\", r.RemoteAddr)\n}", "func (sse *SSE) ServeHTTP(_ http.ResponseWriter, r *http.Request) {\n\tw := sse.Writer\n\tdata, _, err := Updates(r, sse.Params)\n\tif err != nil {\n\t\tif _, ok := err.(params.RenamedConstError); ok {\n\t\t\thttp.Redirect(w, r, err.Error(), http.StatusFound)\n\t\t\treturn\n\t\t}\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\ttext, err := json.Marshal(data)\n\tif err != nil {\n\t\tsse.Errord = true\n\t\t// what would http.Error do\n\t\tif sse.SetHeader(\"Content-Type\", \"text/plain; charset=utf-8\") {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\tfmt.Fprintln(w, err.Error())\n\t\treturn\n\t}\n\tsse.SetHeader(\"Content-Type\", \"text/event-stream\")\n\tif _, err := w.Write(append(append([]byte(\"data: \"), text...), []byte(\"\\n\\n\")...)); err != nil {\n\t\tsse.Errord = true\n\t}\n}", "func (ms *MusicServer) Index(response http.ResponseWriter, request *http.Request) {\n\t// Always check addressMask. If no define, mask is 0.0.0.0 and nothing is accepted (except localhost)\n\tif !ms.checkRequester(request) {\n\t\treturn\n\t}\n\tif ms.musicFolder != \"\" {\n\t\ttextIndexer := music.IndexArtists(ms.folder)\n\t\tms.indexManager.UpdateIndexer(textIndexer)\n\t}\n}", "func Index(w http.ResponseWriter, data *IndexData) {\n\trender(tpIndex, w, data)\n}", "func Index(w http.ResponseWriter, data *IndexData) {\n\trender(tpIndex, w, data)\n}", "func (s *ChartStreamServer) IndexHandler(c *gin.Context) {\n\tindex, err := s.chartProvider.GetIndexFile()\n\tif err != nil {\n\t\tc.AbortWithError(500, err)\n\t}\n\n\tc.YAML(200, index)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request, s *Server) {\n\tif r.Method == \"GET\" {\n\t\t//create the source upload page with available languages and metrics\n\t\tpage := &Page{Config: s.Config, Extensions: s.Analyzer.Extensions(), Metrics: s.Analyzer.Metrics, Languages: s.Analyzer.Languages}\n\n\t\t//display the source upload page\n\t\ts.Template.ExecuteTemplate(w, \"index.html\", page)\n\t}\n}", "func (c *Connection) Index(idx []FileInfo) {\n\tc.Lock()\n\tvar msgType int\n\tif c.indexSent == nil {\n\t\t// This is the first time we send an index.\n\t\tmsgType = messageTypeIndex\n\n\t\tc.indexSent = make(map[string]int64)\n\t\tfor _, f := range idx {\n\t\t\tc.indexSent[f.Name] = f.Modified\n\t\t}\n\t} else {\n\t\t// We have sent one full index. Only send updates now.\n\t\tmsgType = messageTypeIndexUpdate\n\t\tvar diff []FileInfo\n\t\tfor _, f := range idx {\n\t\t\tif modified, ok := c.indexSent[f.Name]; !ok || f.Modified != modified {\n\t\t\t\tdiff = append(diff, f)\n\t\t\t\tc.indexSent[f.Name] = f.Modified\n\t\t\t}\n\t\t}\n\t\tidx = diff\n\t}\n\n\tc.mwriter.writeHeader(header{0, c.nextId, msgType})\n\tc.mwriter.writeIndex(idx)\n\terr := c.flush()\n\tc.nextId = (c.nextId + 1) & 0xfff\n\tc.hasSentIndex = true\n\tc.Unlock()\n\n\tif err != nil {\n\t\tc.Close(err)\n\t\treturn\n\t} else if c.mwriter.err != nil {\n\t\tc.Close(c.mwriter.err)\n\t\treturn\n\t}\n}", "func (siw *SindexWatcher) refresh(o *Observer, infoKeys []string, rawMetrics map[string]string, ch chan<- prometheus.Metric) error {\n\tif config.Aerospike.DisableSindexMetrics {\n\t\t// disabled\n\t\treturn nil\n\t}\n\n\tif siw.sindexMetrics == nil {\n\t\tsiw.sindexMetrics = make(map[string]AerospikeStat)\n\t}\n\n\tfor _, sindex := range infoKeys {\n\t\tsindexInfoKey := strings.ReplaceAll(sindex, \"sindex/\", \"\")\n\t\tsindexInfoKeySplit := strings.Split(sindexInfoKey, \"/\")\n\t\tnsName := sindexInfoKeySplit[0]\n\t\tsindexName := sindexInfoKeySplit[1]\n\t\tlog.Tracef(\"sindex-stats:%s:%s:%s\", nsName, sindexName, rawMetrics[sindex])\n\n\t\tstats := parseStats(rawMetrics[sindex], \";\")\n\t\tfor stat, value := range stats {\n\t\t\tpv, err := tryConvert(value)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tasMetric, exists := siw.sindexMetrics[stat]\n\n\t\t\tif !exists {\n\t\t\t\tasMetric = newAerospikeStat(CTX_SINDEX, stat)\n\t\t\t\tsiw.sindexMetrics[stat] = asMetric\n\t\t\t}\n\t\t\t// handle any panic from prometheus, this may occur when prom encounters a config/stat with special characters\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tlog.Tracef(\"sindex-stats: recovered from panic while handling stat %s in %s\", stat, sindexName)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tif asMetric.isAllowed {\n\t\t\t\tdesc, valueType := asMetric.makePromMetric(METRIC_LABEL_CLUSTER_NAME, METRIC_LABEL_SERVICE, METRIC_LABEL_NS, METRIC_LABEL_SINDEX)\n\t\t\t\tch <- prometheus.MustNewConstMetric(desc, valueType, pv, rawMetrics[ikClusterName], rawMetrics[ikService], nsName, sindexName)\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\n\tfmt.Fprintln(w, \"Steve and Kyle Podcast: #api\")\n\tfmt.Fprintln(w, \"Number of episodes in database:\", EpCount())\n\tfmt.Fprintln(w, \"Created by Derek Slenk\")\n\tfmt.Println(\"Endpoint Hit: Index\")\n}", "func Index(w http.ResponseWriter, data interface{}) {\n\trender(tpIndex, w, data)\n}", "func (c *rawConnection) Index(repo string, idx []FileInfo) {\n\tc.imut.Lock()\n\tvar msgType int\n\tif c.indexSent[repo] == nil {\n\t\t// This is the first time we send an index.\n\t\tmsgType = messageTypeIndex\n\n\t\tc.indexSent[repo] = make(map[string][2]int64)\n\t\tfor _, f := range idx {\n\t\t\tc.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}\n\t\t}\n\t} else {\n\t\t// We have sent one full index. Only send updates now.\n\t\tmsgType = messageTypeIndexUpdate\n\t\tvar diff []FileInfo\n\t\tfor _, f := range idx {\n\t\t\tif vs, ok := c.indexSent[repo][f.Name]; !ok || f.Modified != vs[0] || int64(f.Version) != vs[1] {\n\t\t\t\tdiff = append(diff, f)\n\t\t\t\tc.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}\n\t\t\t}\n\t\t}\n\t\tidx = diff\n\t}\n\tc.imut.Unlock()\n\n\tc.send(header{0, -1, msgType}, IndexMessage{repo, idx})\n}", "func Index(c *gin.Context) {\n\n\tw := c.Writer\n\tr := c.Request\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tp, lastMod, err := tools.ReadFileIfModified(time.Time{})\n\tif err != nil {\n\t\tp = []byte(err.Error())\n\t\tlastMod = time.Unix(0, 0)\n\t}\n\tvar v = struct {\n\t\tHost string\n\t\tData string\n\t\tLastMod string\n\t}{\n\t\tr.Host,\n\t\tstring(p),\n\t\tstrconv.FormatInt(lastMod.UnixNano(), 16),\n\t}\n\tindexTempl.Execute(w, &v)\n}", "func (handler StormWatchHandler) Index(c *gin.Context) {\n\tstormWatchs := []m.StormWatch{}\t\n\tvar query = handler.db\n\n\tstartParam,startParamExist := c.GetQuery(\"start\")\n\tlimitParam,limitParamExist := c.GetQuery(\"limit\")\n\n\t//start param exist\n\tif startParamExist {\n\t\tstart,_ := strconv.Atoi(startParam)\n\t\tif start != 0 {\n\t\t\tquery = query.Offset(start).Order(\"created_at asc\")\t\t\n\t\t} else {\n\t\t\tquery = query.Offset(0).Order(\"created_at desc\")\n\t\t}\n\t} \n\n\t//limit param exist\n\tif limitParamExist {\n\t\tlimit,_ := strconv.Atoi(limitParam)\n\t\tquery = query.Limit(limit)\n\t} else {\n\t\tquery = query.Limit(10)\n\t}\n\n\tquery.Order(\"created_at desc\").Find(&stormWatchs)\n\tc.JSON(http.StatusOK, stormWatchs)\n\treturn\n}", "func index(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\terr := tpl.ExecuteTemplate(w, \"index.html\", nil)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tlog.Fatalln(err)\n\t}\n\tfmt.Println(\"HERE INDEX\")\n}", "func indexHandler(w http.ResponseWriter, req *http.Request) {\n\tlayout, err := template.ParseFile(PATH_PUBLIC + TEMPLATE_LAYOUT)\n\tif err != nil {\n\t\thttp.Error(w, ERROR_TEMPLATE_NOT_FOUND, http.StatusNotFound)\n\t\treturn\n\t}\n\tindex, err := template.ParseFile(PATH_PUBLIC + TEMPLATE_INDEX)\n\t//artical, err := template.ParseFile(PATH_PUBLIC + TEMPLATE_ARTICAL)\n\tif err != nil {\n\t\thttp.Error(w, ERROR_TEMPLATE_NOT_FOUND, http.StatusNotFound)\n\t\treturn\n\t}\n\tmapOutput := map[string]interface{}{\"Title\": \"炫酷的网站技术\" + TITLE, \"Keyword\": KEYWORD, \"Description\": DESCRIPTION, \"Base\": BASE_URL, \"Url\": BASE_URL, \"Carousel\": getAddition(PREFIX_INDEX), \"Script\": getAddition(PREFIX_SCRIPT), \"Items\": leveldb.GetRandomContents(20, &Filter{})}\n\tcontent := []byte(index.RenderInLayout(layout, mapOutput))\n\tw.Write(content)\n\tgo cacheFile(\"index\", content)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"indexHandler is called\")\n\n\tw.WriteHeader(http.StatusOK)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"indexHandler is called\")\n\n\tw.WriteHeader(http.StatusOK)\n}", "func handleIndex(w http.ResponseWriter, r *http.Request) {\n\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tc := appengine.NewContext(r)\n\tlog.Infof(c, \"Serving main page.\")\n\n\ttmpl, _ := template.ParseFiles(\"web/tmpl/index.tmpl\")\n\n\ttmpl.Execute(w, time.Since(initTime))\n}", "func indexHandler(c *fiber.Ctx) error {\n\treturn common.HandleTemplate(c, \"index\",\n\t\t\"me\", nil, 200)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\r\n t, _ := template.New(\"webpage\").Parse(indexPage) // parse embeded index page\r\n t.Execute(w, pd) // serve the index page (html template)\r\n}", "func (s *Server) Index(w http.ResponseWriter, r *http.Request) {\n\tsession := s.getSessionFromCookie(r)\n\n\tif session.IsNew {\n\t\ts.newRandomInbox(session, w, r)\n\t\treturn\n\t}\n\n\ts.getInbox(session, w, r)\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"index de uma função\")\n}", "func index(w http.ResponseWriter, req *http.Request, ctx httputil.Context) (e *httputil.Error) {\n\tif req.URL.Path != \"/\" {\n\t\tnotFound(w, req)\n\t\treturn\n\t}\n\tm := newManager(ctx)\n\n\tres, err := m.Index()\n\tif err != nil {\n\t\te = httputil.Errorf(err, \"couldn't query for test results\")\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tif err := T(\"index/index.html\").Execute(w, res); err != nil {\n\t\te = httputil.Errorf(err, \"error executing index template\")\n\t}\n\treturn\n}", "func (db *DB) Index(ctx context.Context, i services.Consumable) error {\n\tvar (\n\t\terr error\n\t\tjob = db.stream.NewJob(\"index\")\n\t\tsess = db.db.NewSession(job)\n\t)\n\tjob.KeyValue(\"id\", i.ID())\n\tjob.KeyValue(\"chain_id\", i.ChainID())\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tjob.CompleteKv(health.Error, health.Kvs{\"err\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\tjob.Complete(health.Success)\n\t}()\n\n\t// Create db tx\n\tvar dbTx *dbr.Tx\n\tdbTx, err = sess.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dbTx.RollbackUnlessCommitted()\n\n\t// Ingest the tx and commit\n\terr = db.ingestTx(services.NewConsumerContext(ctx, job, dbTx, i.Timestamp()), i.Body())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = dbTx.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"s-senpai, please don't hurt me ;_;\\n\")\n}", "func (s *Server) IndexHandler(w http.ResponseWriter, r *http.Request) {\n\tworkouts, err := storage.GetWorkouts(s.DataRepository)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tout, err := json.Marshal(workouts)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, string(out))\n}", "func (s *Server) indexHandler(w http.ResponseWriter, r *http.Request) {\n\tb, _ := s.static.Find(\"index.html\")\n\tw.Write(b)\n}", "func Index(data []byte){\n\n api.Domain = \"localhost\"\n fmt.Println(\"Entered inside elasticgo file...lets do this\")\n response, _ := core.Index(\"scalegray_sample\", \"first_sampleset\", \"3\", nil, data)\n fmt.Println(response)\n fmt.Println(\"Done pushing the data into elastic search..woohoo!\")\n}", "func Serve(ctx context.Context, serveAddr string, db idb.IndexerDb, fetcherError error, log *log.Logger, options ExtraOptions) {\n\te := echo.New()\n\te.HideBanner = true\n\n\tif options.MetricsEndpoint {\n\t\tp := echo_contrib.NewPrometheus(\"indexer\", nil, nil)\n\t\tif options.MetricsEndpointVerbose {\n\t\t\tp.RequestCounterURLLabelMappingFunc = middlewares.PrometheusPathMapperVerbose\n\t\t} else {\n\t\t\tp.RequestCounterURLLabelMappingFunc = middlewares.PrometheusPathMapper404Sink\n\t\t}\n\t\t// This call installs the prometheus metrics collection middleware and\n\t\t// the \"/metrics\" handler.\n\t\tp.Use(e)\n\t}\n\n\te.Use(middlewares.MakeLogger(log))\n\te.Use(middleware.CORS())\n\n\tmiddleware := make([]echo.MiddlewareFunc, 0)\n\n\tmiddleware = append(middleware, middlewares.MakeMigrationMiddleware(db))\n\n\tif len(options.Tokens) > 0 {\n\t\tmiddleware = append(middleware, middlewares.MakeAuth(\"X-Indexer-API-Token\", options.Tokens))\n\t}\n\n\tapi := ServerImplementation{\n\t\tEnableAddressSearchRoundRewind: options.DeveloperMode,\n\t\tdb: db,\n\t\tfetcher: fetcherError,\n\t}\n\n\tgenerated.RegisterHandlers(e, &api, middleware...)\n\tcommon.RegisterHandlers(e, &api)\n\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgetctx := func(l net.Listener) context.Context {\n\t\treturn ctx\n\t}\n\ts := &http.Server{\n\t\tAddr: serveAddr,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t\tBaseContext: getctx,\n\t}\n\n\tlog.Fatal(e.StartServer(s))\n}", "func (app *Application) Index(w http.ResponseWriter, r *http.Request) {\n\tdata := struct {\n\t\tTime int64\n\t}{\n\t\tTime: time.Now().Unix(),\n\t}\n\n\tt, err := template.ParseFiles(\"views/index.tpl\")\n\n\tif err != nil {\n\t\tlog.Println(\"Template.Parse:\", err)\n\t\thttp.Error(w, \"Internal Server Error 0x0178\", http.StatusInternalServerError)\n\t}\n\n\tif err := t.Execute(w, data); err != nil {\n\t\tlog.Println(\"Template.Execute:\", err)\n\t\thttp.Error(w, \"Internal Server Error 0x0183\", http.StatusInternalServerError)\n\t}\n}", "func index(w http.ResponseWriter, r *http.Request){\n\terr := templ.ExecuteTemplate(w, \"index\", nil)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t}\n}", "func serveIndex(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\terr := serveAssets(w, r, \"index.html\")\n\tcheckError(err)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"indexHandler is called\")\n\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(indexHandlerResponse{Message: \"OK\"})\n}", "func index(c echo.Context) error {\n\tpprof.Index(c.Response().Writer, c.Request())\n\treturn nil\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tif err := json.NewEncoder(w).Encode(ResultIndex{Connect: true}); err != nil {\n\t\tpanic(err)\n\t}\n}", "func subscribeSSE(transport *HTTPTransport, statuschan chan ServerStatus, errorchan chan error, untilNextOnly bool) error {\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tevents := make(chan *sseclient.Event)\n\tcancelled := false\n\tgo func() {\n\t\tfor {\n\t\t\te := <-events\n\t\t\tif e == nil || e.Type == \"open\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstatus := ServerStatus(strings.Trim(string(e.Data), `\"`))\n\t\t\tstatuschan <- status\n\t\t\tif untilNextOnly || status.Finished() {\n\t\t\t\terrorchan <- nil\n\t\t\t\tcancelled = true\n\t\t\t\tcancel()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\terr := sseclient.Notify(ctx, transport.Server+\"statusevents\", true, events)\n\t// When sse was cancelled, an error is expected to be returned. The channels are already closed then.\n\tif cancelled {\n\t\treturn nil\n\t}\n\tclose(events)\n\treturn err\n}", "func Index(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tio.WriteString(w, \"Hello\")\n}", "func IndexHandeler(w http.ResponseWriter, r *http.Request) {\n\trespond.OK(w, map[string]interface{}{\n\t\t\"name\": \"hotstar-schedular\",\n\t\t\"version\": 1,\n\t})\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n}", "func showIndex(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tServeTemplateWithParams(res, req, \"index.html\", nil)\n}", "func HandleIndex(w http.ResponseWriter, r *http.Request) {\n\tresponse := info()\n\n\terr := utils.Respond(w, response)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: Failed to encode info response, %s\", err)\n\t}\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hola, este es el inicio\")\n}", "func (s *RefreshService) Index(index ...string) *RefreshService {\n\ts.index = append(s.index, index...)\n\treturn s\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\titems, _, err := summary.All(c.DB)\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t\titems = []summary.Item{}\n\t}\n\tdefaultFormat := \"Mon, 02-Jan-2006\"\n\n\tfor i := 0; i < len(items); i++ {\n\t\titems[i].SnapshotDate_Formatted = items[i].SnapshotDate.Time.Format(defaultFormat)\n\t\t//items[i].Details_Split = strings.Split(items[i].Details, \"|\")\n\t\titems[i].Cash_String = utilities.DisplayPrettyNullFloat64(items[i].Cash)\n\t\titems[i].Loads_String = utilities.DisplayPrettyNullFloat64(items[i].Loads)\n\t\titems[i].SmartMoney_String = utilities.DisplayPrettyNullFloat64(items[i].SmartMoney)\n\t\titems[i].Codes_String = utilities.DisplayPrettyNullFloat64(items[i].Codes)\n\t\titems[i].Total_String = utilities.DisplayPrettyNullFloat64(items[i].Total)\n\t}\n\n\tdaily_earnings, _, _ := summary.DailyEarnings(c.DB, \"7\")\n\n\tm := make(map[string]float64)\n\tn := make(map[string]float64)\n\n\tfor i := 0; i < len(daily_earnings); i++ {\n\t\tdaily_earnings[i].Trans_Datetime_Formatted = daily_earnings[i].Trans_Datetime.Time.Format(defaultFormat)\n\t\tdaily_earnings[i].Amount_String = utilities.DisplayPrettyNullFloat64(daily_earnings[i].Amount)\n\n\t\tm[daily_earnings[i].Trans_Datetime.Time.Format(\"2006-01-02\")] = m[daily_earnings[i].Trans_Datetime.Time.Format(\"2006-01-02\")] + daily_earnings[i].Amount.Float64\n\t\tn[daily_earnings[i].Trans_code] = n[daily_earnings[i].Trans_code] + daily_earnings[i].Amount.Float64\n\t}\n\n\t//fmt.Println(m)\n\n\t//prettysum := utilities.DisplayPrettyFloat(sum)\n\n\tpie := chart.PieChart{\n\t\tTitle: \"Summary\",\n\t\tWidth: 512,\n\t\tHeight: 512,\n\t\tValues: []chart.Value{\n\t\t\t{Value: items[0].Cash.Float64, Label: \"Cash\"},\n\t\t\t{Value: items[0].Loads.Float64, Label: \"Loads\"},\n\t\t\t{Value: items[0].SmartMoney.Float64, Label: \"SmartMoney\"},\n\t\t\t{Value: items[0].Codes.Float64, Label: \"Codes\"},\n\t\t},\n\t}\n\n\toutputfile := \"./asset/static/outputfile.png\"\n\n\tpie2 := chart.PieChart{\n\t\tTitle: \"Summary\",\n\t\tWidth: 512,\n\t\tHeight: 512,\n\t\tValues: []chart.Value{},\n\t}\n\n\t//outputfile := \"./asset/static/outputfile.png\"\n\n\t//buffer := []byte{}\n\n\tf, _ := os.Create(outputfile)\n\n\twriter := bufio.NewWriter(f)\n\n\tdefer f.Close()\n\n\t_ = pie.Render(chart.PNG, writer)\n\n\twriter.Flush()\n\n\tsbc := chart.BarChart{\n\t\tTitle: \"Daily Total Earnings\",\n\t\tTitleStyle: chart.StyleShow(),\n\t\tBackground: chart.Style{\n\t\t\tPadding: chart.Box{\n\t\t\t\tTop: 40,\n\t\t\t},\n\t\t},\n\t\tHeight: 512,\n\t\tBarWidth: 60,\n\t\tXAxis: chart.Style{\n\t\t\tShow: true,\n\t\t},\n\t\tYAxis: chart.YAxis{\n\t\t\tStyle: chart.Style{\n\t\t\t\tShow: true,\n\t\t\t},\n\t\t},\n\t\tBars: []chart.Value{},\n\t}\n\n\t//vBars := sbc.Bars\n\tidx := 0\n\t// fmt.Println(\"Length of m:\", len(m))\n\tslice := make([]chart.Value, len(m))\n\n\tslice1 := make([]summary.Earning, len(m))\n\t//fmt.Println(\"Arr:\", slice)\n\tfor k, v := range m {\n\n\t\t//\t\tfmt.Println(k, v)\n\t\t//fmt.Printf(\"type: %T\\n\", sbc.Bars)\n\t\tslice[idx].Label = k\n\t\tslice[idx].Value = v\n\n\t\tslice1[idx].Trans_Datetime_Formatted = k\n\t\tslice1[idx].Amount_String = utilities.DisplayPrettyFloat64(v)\n\n\t\tidx++\n\t}\n\n\tsort.Slice(slice, func(i, j int) bool { return slice[i].Label < slice[j].Label })\n\n\tsbc.Bars = slice\n\n\toutputfile2 := \"./asset/static/outputfile2.png\"\n\n\t//buffer := []byte{}\n\n\tf2, _ := os.Create(outputfile2)\n\n\twriter2 := bufio.NewWriter(f2)\n\n\tdefer f2.Close()\n\n\t_ = sbc.Render(chart.PNG, writer2)\n\n\twriter2.Flush()\n\n\tidx2 := 0\n\n\tslice2 := make([]chart.Value, len(n))\n\n\t//make([]summary.Earning, len(n))\n\n\tslice3 := make([]summary.Earning, len(n))\n\t//fmt.Println(\"Arr:\", slice)\n\tfor k, v := range n {\n\t\t//sbc.Bars[idx].Label = k\n\t\t//sbc.Bars[idx].Value = v\n\n\t\t//\t\tfmt.Println(k, v)\n\t\t//fmt.Printf(\"type: %T\\n\", sbc.Bars)\n\t\tslice2[idx2].Label = k\n\t\tslice2[idx2].Value = v\n\n\t\tslice3[idx2].Trans_code = k\n\t\tslice3[idx2].Amount_String = utilities.DisplayPrettyFloat64(v)\n\n\t\tidx2++\n\t}\n\n\tpie2.Values = slice2\n\n\toutputfile3 := \"./asset/static/outputfile3.png\"\n\n\tf3, _ := os.Create(outputfile3)\n\n\twriter3 := bufio.NewWriter(f3)\n\n\tdefer f3.Close()\n\n\t_ = pie2.Render(chart.PNG, writer3)\n\n\twriter3.Flush()\n\n\t//fmt.Println(n)\n\n\t//\tfmt.Println(daily_earnings)\n\t//\tfmt.Println(slice3)\n\n\tcurrentTime := time.Now()\n\n\tv := c.View.New(\"summary/index\")\n\tv.Vars[\"items\"] = items\n\tv.Vars[\"today\"] = currentTime.Format(defaultFormat)\n\t//fmt.Println(daily_earnings)\n\t//v.Vars[\"buf\"] = outputfile\n\t//v.Vars[\"daily_earnings\"] = daily_earnings\n\tv.Vars[\"daily_earnings\"] = slice1\n\tv.Vars[\"earnings_by_transcode\"] = slice3\n\tv.Render(w, r)\n}", "func IndexHandler() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tpprof.Index(c.Writer, c.Request)\n\t}\n}", "func indexHandler(res http.ResponseWriter, req *http.Request) {\n\n\t// Execute the template and respond with the index page.\n\ttemplates.ExecuteTemplate(res, \"index\", nil)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\titems, sum, cnt, _, err := code.All(c.DB)\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t\titems = []code.Item{}\n\t}\n\n\tdefaultFormat := \"Mon, 02-Jan-2006\"\n\n\tfor i := 0; i < len(items); i++ {\n\t\titems[i].Trans_Datetime_Formatted = items[i].Trans_Datetime.Time.Format(defaultFormat)\n\t\titems[i].Details_Split = strings.Split(items[i].Details, \"|\")\n\t\titems[i].Amount_String = u.DisplayPrettyNullFloat64(items[i].Amount)\n\t}\n\n\tprettysum := u.DisplayPrettyFloat(sum)\n\tprettycnt := u.DisplayPrettyFloat(cnt)\n\n\tv := c.View.New(\"code/index\")\n\tv.Vars[\"items\"] = items\n\tv.Vars[\"sum\"] = prettysum\n\tv.Vars[\"cnt\"] = prettycnt\n\tv.Render(w, r)\n}", "func IndexHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, \"http://sjsafranek.github.io/gospatial/\", 200)\n\treturn\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Whoa, Nice!\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tenv.Output.WriteChDebug(\"(ApiEngine::Index)\")\n\thttp.Redirect(w, r, \"/api/node\", http.StatusFound)\n}", "func index(ctx *gin.Context) {\n\tctx.Header(\"Content-Type\", \"text/html\")\n\tctx.String(\n\t\thttp.StatusOK,\n\t\t\"<h1>Rasse Server</h1><p>Wel come to the api server.</p><p>%v</p>\",nil)\n}", "func (ns *EsIndexer) Start(grpcClient types.AergoRPCServiceClient, reindex bool) error {\n\turl := ns.esURL\n\tif !strings.HasPrefix(url, \"http\") {\n\t\turl = fmt.Sprintf(\"http://%s\", url)\n\t}\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\thttpClient := &http.Client{Transport: tr}\n\tclient, err := elastic.NewClient(\n\t\telastic.SetHttpClient(httpClient),\n\t\telastic.SetURL(url),\n\t\telastic.SetHealthcheckTimeoutStartup(30*time.Second),\n\t\telastic.SetSniff(false),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tns.client = client\n\tns.grpcClient = grpcClient\n\n\tif reindex {\n\t\tns.log.Warn().Msg(\"Reindexing database. Will sync from scratch and replace index aliases when caught up\")\n\t\tns.reindexing = true\n\t}\n\n\tns.CreateIndexIfNotExists(\"tx\")\n\tns.CreateIndexIfNotExists(\"block\")\n\tns.CreateIndexIfNotExists(\"name\")\n\tns.UpdateLastBlockHeightFromDb()\n\tns.log.Info().Uint64(\"lastBlockHeight\", ns.lastBlockHeight).Msg(\"Started Elasticsearch Indexer\")\n\n\tgo ns.CheckConsistency()\n\n\treturn ns.StartStream()\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"%v\", \"Hello world\")\n}", "func IndexHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tif pusher, ok := w.(http.Pusher); ok {\n\t\tif err := pusher.Push(\"./web/css/app.css\", nil); err != nil {\n\t\t\tlog.Printf(\"Failed to push %v\\n\", err)\n\t\t}\n\t}\n\tt, err := template.ParseFiles(\"./web/html/index.html\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tt.Execute(w, nil)\n}", "func main() {\n\tapp := iris.New()\n\ts := sse.New()\n\t/*\n\t\tThis creates a new stream inside of the scheduler.\n\t\tSeeing as there are no consumers, publishing a message\n\t\tto this channel will do nothing.\n\t\tClients can connect to this stream once the iris handler is started\n\t\tby specifying stream as a url parameter, like so:\n\t\thttp://localhost:8080/events?stream=messages\n\t*/\n\ts.CreateStream(\"messages\")\n\n\tapp.Any(\"/events\", iris.FromStd(s))\n\n\tgo func() {\n\t\t// You design when to send messages to the client,\n\t\t// here we just wait 5 seconds to send the first message\n\t\t// in order to give u time to open a browser window...\n\t\ttime.Sleep(5 * time.Second)\n\t\t// Publish a payload to the stream.\n\t\ts.Publish(\"messages\", &sse.Event{\n\t\t\tData: []byte(\"ping\"),\n\t\t})\n\n\t\ttime.Sleep(3 * time.Second)\n\t\ts.Publish(\"messages\", &sse.Event{\n\t\t\tData: []byte(\"second message\"),\n\t\t})\n\t\ttime.Sleep(2 * time.Second)\n\t\ts.Publish(\"messages\", &sse.Event{\n\t\t\tData: []byte(\"third message\"),\n\t\t})\n\t}() // ...\n\n\tapp.Listen(\":8080\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hello from our index page\")\n}", "func run() {\n\tfor {\n\t\tselect {\n\t\tcase at, more := <-pump:\n\t\t\tlog.WithField(ctx, \"time\", at).Debug(\"sse pump\")\n\n\t\t\tprev := nextTick\n\t\t\tnextTick = make(chan struct{})\n\t\t\t// trigger all listeners by closing the nextTick channel\n\t\t\tclose(prev)\n\n\t\t\tif !more {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tpump = nil\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *Server) Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"[INDEX]: \", r.URL.Path[1:])\n\tu, ok := s.m[r.URL.Path[1:]]\n\tif !ok {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tfmt.Fprintf(w, \"not found\\n\")\n\t\treturn\n\t}\n\thttp.Redirect(w, r, u, http.StatusMovedPermanently)\n}", "func (c *Client) IndexUpdate(update io.Reader, opts IndexUpdateOptions) error {\n\tpopts := PostMultipartOptions{\n\t\tFiles: map[string]io.Reader{\n\t\t\t\"update\": update,\n\t\t},\n\t\tProgress: opts.Progress,\n\t}\n\n\treturn c.PostMultipart(\"/index/update\", popts, nil)\n}", "func (s *Service) HandleIndex(w http.ResponseWriter, r *http.Request) {\n\tpag, err := s.parsePagination(r)\n\tif err != nil {\n\t\ts.writer.Error(w, \"error during pagination parse\", err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err = pag.Valid(); err != nil {\n\t\ts.writer.Error(w, \"invalid pagination\", err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsubs, subsPag, err := s.subscriptionRepository.FindAll(\n\t\tr.Context(), pag, s.getResourceID(r),\n\t)\n\tif err != nil {\n\t\ts.writer.Error(w, \"error during subscriptions search\", err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\ts.writer.Response(w, &response{\n\t\tSubscriptions: transformSubscriptions(subs),\n\t\tPagination: transformPagination(subsPag),\n\t}, http.StatusOK, nil)\n}", "func (i *Index) Index(docs []index.Document, opts interface{}) error {\n blk := i.conn.Bulk()\n\tfor _, doc := range docs {\n //fmt.Println(\"indexing \", doc.Id)\n\t\treq := elastic.NewBulkIndexRequest().Index(i.name).Type(\"doc\").Id(doc.Id).Doc(doc.Properties)\n\t\tblk.Add(req)\n\t\t/*_, err := i.conn.Index().Index(i.name).Type(\"doc\").Id(doc.Id).BodyJson(doc.Properties).Do()\n if err != nil {\n // Handle error\n panic(err)\n }*/\n //fmt.Printf(\"Indexed tweet %s to index %s, type %s\\n\", put2.Id, put2.Index, put2.Type)\n\t}\n\t//_, err := blk.Refresh(true).Do()\n\t_, err := blk.Refresh(false).Do()\n if err != nil {\n panic(err)\n fmt.Println(\"Get Error during indexing\", err)\n }\n\treturn err\n\t//return nil\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tdata := &Index{\n\t\tTitle: \"Image gallery\",\n\t\tBody: \"Welcome to the image gallery.\",\n\t}\n\tfor name, img := range images {\n\t\tdata.Links = append(data.Links, Link{\n\t\t\tURL: \"/image/\" + name,\n\t\t\tTitle: img.Title,\n\t\t})\n\t}\n\tif err := indexTemplate.Execute(w, data); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (s *FieldStatsService) Index(index ...string) *FieldStatsService {\n\ts.index = append(s.index, index...)\n\treturn s\n}", "func HandleIndex(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tname := p.ByName(\"name\")\n\tresponse := snakes[name].Info\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\terr := json.NewEncoder(w).Encode(response)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: response write: \" + err.Error())\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfmt.Println(\"Index: \" + name)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tmessage := \"Welcome to Recipe Book!\"\n\tindexT.Execute(w, message)\n}", "func (tc *TransactionsController) Index(c *gin.Context, size, page, offset int) {\n\ttxs, count, err := tc.App.GetStore().Transactions(offset, size)\n\tptxs := make([]presenters.Tx, len(txs))\n\tfor i, tx := range txs {\n\t\tptxs[i] = presenters.NewTx(&tx)\n\t}\n\tpaginatedResponse(c, \"Transactions\", size, page, ptxs, count, err)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"Hello World!\"))\n}", "func BenchmarkIndexHandler(b *testing.B) {\n\tc, _ := loadTestYaml()\n\tcontext := &Context{Config: c}\n\tappHandler := &CtxWrapper{context, IndexHandler}\n\thandler := http.Handler(appHandler)\n\treq, _ := http.NewRequest(\"GET\", \"/z\", nil)\n\treq.Host = \"g\"\n\trr := httptest.NewRecorder()\n\tfor n := 0; n < b.N; n++ {\n\t\thandler.ServeHTTP(rr, req)\n\t}\n}", "func TestIndexHandler(t *testing.T) {\n\tslist := []Subscription{\n\t\tSubscription{\n\t\t\tEventType: \"test_type\",\n\t\t\tContext: \"test_context\",\n\t\t},\n\t}\n\n\th := Handler{\n\t\tdb: MockDatabase{slist: slist},\n\t}\n\treq, w := newReqParams(\"GET\")\n\n\th.Index(w, req, httprouter.Params{})\n\n\tcases := []struct {\n\t\tlabel, actual, expected interface{}\n\t}{\n\t\t{\"Response code\", w.Code, 200},\n\t\t{\"Response body contains context\", strings.Contains(w.Body.String(), slist[0].Context), true},\n\t\t{\"Response body contains event type\", strings.Contains(w.Body.String(), slist[0].EventType), true},\n\t}\n\n\ttestCases(t, cases)\n}", "func (s *IndicesStatsService) Index(indices ...string) *IndicesStatsService {\n\ts.index = append(s.index, indices...)\n\treturn s\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\ta := \"hello from index router\"\n\tfmt.Fprintln(w, a)\n}", "func (s *service) indexCore(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\treq := &indexRequest{\n\t\tindex: s.index,\n\t\tlog: s.logger,\n\t\tr: r,\n\t\tstore: s.store,\n\t}\n\treq.init()\n\treq.read()\n\treq.readCore()\n\tif req.req.IncludeExecutable {\n\t\treq.readExecutable()\n\t} else {\n\t\treq.computeExecutableSize()\n\t}\n\treq.indexCore()\n\treq.close()\n\n\tif req.err != nil {\n\t\ts.logger.Error(\"indexing\", \"uid\", req.uid, \"err\", req.err)\n\t\twriteError(w, http.StatusInternalServerError, req.err)\n\t\treturn\n\t}\n\n\ts.received.With(prometheus.Labels{\n\t\t\"hostname\": req.coredump.Hostname,\n\t\t\"executable\": req.coredump.Executable,\n\t}).Inc()\n\n\ts.receivedSizes.With(prometheus.Labels{\n\t\t\"hostname\": req.coredump.Hostname,\n\t\t\"executable\": req.coredump.Executable,\n\t}).Observe(datasize.ByteSize(req.coredump.Size).MBytes())\n\n\ts.analysisQueue <- req.coredump\n\n\twrite(w, http.StatusOK, map[string]interface{}{\"acknowledged\": true})\n}", "func (req MinRequest) Index(index interface{}) MinRequest {\n\treq.index = index\n\treturn req\n}", "func indexHandler() func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tt, err := template.New(\"index\").Parse(indexHTMLTemplate)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, \"parsing the HTML template failed: %+v\", err)\n\t\t}\n\n\t\tinfo := struct {\n\t\t\tPrefix string\n\t\t}{\n\t\t\tPrefix: rootPrefix,\n\t\t}\n\n\t\terr = t.Execute(w, info)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, \"error writting index template: %+v\", err)\n\t\t}\n\t}\n}", "func HandlerIndex(res http.ResponseWriter, req *http.Request) {\n\thttp.ServeFile(res, req, \"./static/index.html\")\n}", "func (h *handler) Serve() {\n\tdefer close(h.stopDone)\n\th.logger.Info(\"Running\")\n\th.updateChan <- addStreamUpdate{streamID: h.streamID}\n\tfor {\n\t\tselect {\n\t\tcase parsedBlock := <-h.ingressChan:\n\t\t\th.updateChan <- h.generator.Generate(h.streamID, false, parsedBlock)\n\t\tcase parsedBlock := <-h.egressChan:\n\t\t\th.updateChan <- h.generator.Generate(h.streamID, true, parsedBlock)\n\t\tcase <-h.stop:\n\t\t\th.logger.Info(\"Stopping...\")\n\t\t\th.updateChan <- removeStreamUpdate{streamID: h.streamID}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *server) handleIndex(FSS fs.FS) http.HandlerFunc {\n\ttype AppConfig struct {\n\t\tAvatarService string\n\t\tToastTimeout int\n\t\tAllowGuests bool\n\t\tAllowRegistration bool\n\t\tDefaultLocale string\n\t\tAuthMethod string\n\t\tAppVersion string\n\t\tCookieName string\n\t\tPathPrefix string\n\t\tAPIEnabled bool\n\t\tCleanupGuestsDaysOld int\n\t\tCleanupStoryboardsDaysOld int\n\t\tShowActiveCountries bool\n\t}\n\ttype UIConfig struct {\n\t\tAnalyticsEnabled bool\n\t\tAnalyticsID string\n\t\tAppConfig AppConfig\n\t\tActiveAlerts []interface{}\n\t}\n\n\ttmpl := s.getIndexTemplate(FSS)\n\n\tappConfig := AppConfig{\n\t\tAvatarService: viper.GetString(\"config.avatar_service\"),\n\t\tToastTimeout: viper.GetInt(\"config.toast_timeout\"),\n\t\tAllowGuests: viper.GetBool(\"config.allow_guests\"),\n\t\tAllowRegistration: viper.GetBool(\"config.allow_registration\") && viper.GetString(\"auth.method\") == \"normal\",\n\t\tDefaultLocale: viper.GetString(\"config.default_locale\"),\n\t\tAuthMethod: viper.GetString(\"auth.method\"),\n\t\tAPIEnabled: viper.GetBool(\"config.allow_external_api\"),\n\t\tAppVersion: s.config.Version,\n\t\tCookieName: s.config.FrontendCookieName,\n\t\tPathPrefix: s.config.PathPrefix,\n\t\tCleanupGuestsDaysOld: viper.GetInt(\"config.cleanup_guests_days_old\"),\n\t\tCleanupStoryboardsDaysOld: viper.GetInt(\"config.cleanup_storyboards_days_old\"),\n\t\tShowActiveCountries: viper.GetBool(\"config.show_active_countries\"),\n\t}\n\n\tActiveAlerts = s.database.GetActiveAlerts()\n\n\tdata := UIConfig{\n\t\tAnalyticsEnabled: s.config.AnalyticsEnabled,\n\t\tAnalyticsID: s.config.AnalyticsID,\n\t\tAppConfig: appConfig,\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdata.ActiveAlerts = ActiveAlerts // get latest alerts from memory\n\n\t\tif embedUseOS {\n\t\t\ttmpl = s.getIndexTemplate(FSS)\n\t\t}\n\n\t\ttmpl.Execute(w, data)\n\t}\n}", "func (h *MovieHandler) index(w http.ResponseWriter, r *http.Request) {\n\t// Call GetMovies to retrieve all movies from the database.\n\tif movies, err := h.MovieService.GetMovies(); err != nil {\n\t\t// Render an error response and set status code.\n\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\tlog.Println(\"Error:\", err)\n\t} else {\n\t\t// Render a HTML response and set status code.\n\t\trender.HTML(w, http.StatusOK, \"movie/index.html\", movies)\n\t}\n}", "func Index(w http.ResponseWriter, req *http.Request) {\n\tfmt.Fprint(w, \"El servidor esta funcionando\")\n\n\tmatriz := pedidosAnuales.BuscarNodo(2017).meses.searchByContent(04).data\n\tfmt.Println(matriz)\n\tmatriz.lst_h.print()\n\tmatriz.lst_v.print()\n\tfmt.Println(matriz.getGraphviz())\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\t_, p, err := conn.ReadMessage()\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\turi := string(p)\n\tarticleInfo := articleInfoFromUrl(uri)\n\tif articleInfo == nil {\n\t\tfmt.Printf(\"serveWs: didn't find article for uri %s\\n\", uri)\n\t\treturn\n\t}\n\n\tarticle := articleInfo.this\n\tfmt.Printf(\"serveWs: started watching %s for uri %s\\n\", article.Path, uri)\n\n\tc := AddWatch(article.Path)\n\tdefer RemoveWatch(c)\n\tdone := make(chan struct{})\n\n\tgo func() {\n\t\tfor {\n\t\t\t_, _, err := conn.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"serveWs: closing for %s\\n\", uri)\n\t\t\t\tclose(done)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-c:\n\t\t\treloadArticle(article)\n\t\t\terr := conn.WriteMessage(websocket.TextMessage, nil)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tbreak loop\n\t\t\t}\n\t\tcase <-done:\n\t\t\tbreak loop\n\t\t}\n\t}\n}", "func indexer() {\n\tfor {\n\t\tselect {\n\t\tcase file := <-feedCh:\n\t\t\treadFeed(file)\n\t\t}\n\t}\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Welcome to the DEM service!\")\n}", "func (e Manager) Send(envelope sunduq.Envelope) {\n\te.index.send(envelope)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"indexHandler is called\")\n\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(appResponse{Message: \"OK\"})\n}", "func (req *MinRequest) Index(index interface{}) *MinRequest {\n\treq.index = index\n\treturn req\n}", "func ReadIndex(output http.ResponseWriter, reader *http.Request) {\n\tfmt.Fprintln(output, \"ImageManagerAPI v1.0\")\n\tLog(\"info\", \"Endpoint Hit: ReadIndex\")\n}", "func Index(_ core.StorageClient) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"Hello World!\")\n\t}\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tmovies, err := service.GetMoviesData()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"getMoviesData: %v\", err)\n\t\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tjs, err := json.Marshal(movies)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(js)\n\n\tdefault:\n\t\thttp.Error(w, fmt.Sprintf(\"HTTP Method %s Not Allowed\", r.Method), http.StatusMethodNotAllowed)\n\t}\n}", "func (s *IndicesSyncedFlushService) Index(indices ...string) *IndicesSyncedFlushService {\n\ts.index = append(s.index, indices...)\n\treturn s\n}", "func TestIndexHandler(t *testing.T) {\n\telist := []Event{testEvent}\n\n\th := Handler{\n\t\tdb: MockDatabase{elist: elist},\n\t}\n\treq, w := newReqParams(\"GET\")\n\n\th.Index(w, req, httprouter.Params{})\n\n\tcases := []struct {\n\t\tlabel, actual, expected interface{}\n\t}{\n\t\t{\"Response code\", w.Code, 200},\n\t\t{\"Response body contains context\", strings.Contains(w.Body.String(), testEvent.Context), true},\n\t\t{\"Response body contains event type\", strings.Contains(w.Body.String(), testEvent.EventType), true},\n\t\t{\"Response body contains data\", strings.Contains(w.Body.String(), testEvent.Data), true},\n\t\t{\"Response body contains id\", strings.Contains(w.Body.String(), testEvent.ID.String()), true},\n\t\t{\"Response body contains account id\", strings.Contains(w.Body.String(), testEvent.OriginalAccountID.String()), true},\n\t}\n\n\ttestCases(t, cases)\n}" ]
[ "0.64418113", "0.6440549", "0.6064773", "0.59902114", "0.5585452", "0.5555484", "0.55490744", "0.5497935", "0.5477929", "0.54218686", "0.53964406", "0.5335342", "0.52755517", "0.52755517", "0.5224524", "0.52050734", "0.52000564", "0.51795226", "0.51668257", "0.5147979", "0.5136852", "0.5081622", "0.50739896", "0.50573564", "0.5041458", "0.49915555", "0.49915555", "0.49341318", "0.48991054", "0.4890557", "0.4887498", "0.4886702", "0.48864636", "0.48817533", "0.48815873", "0.4880548", "0.48498708", "0.4849382", "0.48401156", "0.48353982", "0.483534", "0.4826761", "0.4816217", "0.48150557", "0.4805371", "0.48008314", "0.47822547", "0.47801274", "0.47744912", "0.47602138", "0.47396624", "0.47385553", "0.47255158", "0.47233823", "0.47223297", "0.4721904", "0.47204095", "0.47072744", "0.47061688", "0.4696188", "0.46949178", "0.4692428", "0.46922588", "0.46909094", "0.468459", "0.4683208", "0.46810037", "0.46728665", "0.46692872", "0.466899", "0.46652973", "0.4663862", "0.465334", "0.46508166", "0.46455795", "0.46452323", "0.46441534", "0.46437255", "0.46377167", "0.46337038", "0.46257535", "0.46239504", "0.460884", "0.45916626", "0.458753", "0.45866403", "0.458661", "0.4584211", "0.45800608", "0.45796612", "0.4569796", "0.4561945", "0.45533648", "0.453393", "0.45302603", "0.45275682", "0.4522599", "0.45197058", "0.4518554", "0.45172453" ]
0.812101
0
problem statement : given a story generate html to show the story
func main() { stories, err := reader.ReadJsonStory("./static/story/default.json") if err != nil { log.Panicln(err) } web.Start(stories) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func story(Memories int) string {\n\tGamePlot := \"story.txt\"\n\tif len(plot) <= 0 {\n\t\tstory, err := os.Open(GamePlot)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"either incorrect format or associated with %s please rewrite.\\n\", err)\n\t\t} else {\n\t\t\tStoryReader := bio.NewScanner(story)\n\t\t\tStoryReader.Split(bio.ScanLines)\n\t\t\tdefer story.Close()\n\t\t\tfor StoryReader.Scan() {\n\t\t\t\tplot = append(plot, StoryReader.Text())\n\t\t\t}\n\t\t}\n\t}\n\treturn plot[Memories]\n}", "func getStory(w http.ResponseWriter, r *http.Request) {\n\t// read the id\n\tid := mux.Vars(r)[\"id\"]\n\t// format the url\n\tstoryURL := fmtURL(id)\n\t// Make request and get response body\n\tdata := fmtRes(storyURL)\n\tfmt.Println(\"data:\", data)\n\tw.Write([]byte(data))\n}", "func Source_() HTML {\n return Source(nil)\n}", "func (page *storyPage) playStoryMethod() {\n\tfor page != nil {\n\t\tfmt.Println(page.text)\n\t\tpage = page.nextPage\n\t}\n}", "func Embed_() HTML {\n return Embed(nil)\n}", "func getHTML(str string) template.HTML {\n\tmarkdown := string(blackfriday.Run([]byte(str)))\n\treturn template.HTML(markdown)\n}", "func (t toc) toHTMLStr() (htmlStr string) {\n\thtmlStr = `<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\" />\n<title>Redis in Action: Table Of Content</title>\n</head>\n<body>\n<h1 style=\"margin-top:20px; margin-left:30px; font-size:48px;\">Redis in Action</h1>\n`\n\n\thtmlStr += \"<div style=\\\"margin-left:auto; margin-right:auto; margin-top:80px; margin-bottom:40px;\\\">\\n<ul>\\n\"\n\tcurrentLevel := 1\n\tfor _, v := range t {\n\t\tif v.level > currentLevel {\n\t\t\thtmlStr += \"<ul>\\n\"\n\t\t\tcurrentLevel = v.level\n\t\t} else if v.level < currentLevel {\n\t\t\tfor i := v.level; i < currentLevel; i++ {\n\t\t\t\thtmlStr += \"</ul>\\n\"\n\t\t\t}\n\t\t\tcurrentLevel = v.level\n\t\t}\n\n\t\thtmlStr += fmt.Sprintf(\"<li><a href=\\\"./%03d.html\\\">%s</a></li>\\n\", v.value, v.title)\n\t}\n\thtmlStr += \"</ul>\\n</div>\\n</body>\\n</html>\"\n\treturn htmlStr\n}", "func playHtmlHandle(w http.ResponseWriter, r *http.Request) {\n\tplayTempl.Execute(w, Params)\n}", "func toHtml(fname string) string {\n\treturn strings.Replace(fname, \".md\", \".html\", -1)\n}", "func pagemain(w http.ResponseWriter, r *http.Request){\n w.Write([]byte( `\n <!doctype html>\n <title>Ciao</title>\n <h1>Come stai</h1>\n <img src=\"https://www.4gamehz.com/wp-content/uploads/2019/10/league-of-legends-4.jpg\">\n `))\n }", "func work(reader io.Reader, app_data AppData) string {\n content_markdown := ReaderToString(reader)\n content_title := \"\"\n \n //look for an H1 title, break it out for use in the HTML title tag\n first_newline := strings.Index(content_markdown, \"\\n\")\n if first_newline > -1{\n if strings.HasPrefix(content_markdown[0:first_newline], \"# \") {\n content_title = content_markdown[2:first_newline]\n content_markdown = content_markdown[first_newline:]\n }\n }\n\n //get the content\n var content_html string\n if app_data.Markdown {\n content_html = MarkdownToHTML(content_markdown)\n } else {\n content_html = content_markdown\n }\n\n //set up reporting time/date\n now := time.Now()\n formated_date := now.Format(\"2006-01-02 03:04 PM\")\n\n //expose data to template\n data := TemplateData{\n Title: content_title,\n Content: content_html,\n Date: formated_date,\n }\n \n //get template file\n template_file_path := FindTemplate(app_data.Template, app_data.Limit)\n var template_content string\n if template_file_path == \"\" {\n template_content = FILE_TEMPLATE\n } else {\n template_content = readFile(template_file_path)\n }\n \n return render(template_content, data)\n}", "func (server Server) Create_Open_Html() {\n\tlayernames := []string{}\n\tfor _,i := range server.Mbtiles {\n\t\tlayernames = append(layernames,Get_Vector_Layers(i)...)\n\t}\n\tfor _,i := range server.Geobufs {\n\t\tlayernames = append(layernames,i.Config_Dynamic.LayerName)\n\t}\n\n\tlayer_parts := []string{}\n\tfor _,layername := range layernames {\n\t\tlayer_parts = append(layer_parts,Get_Part_Layer(layername))\n\t}\n\tmiddle := strings.Join(layer_parts,\"\\n\")\n\tstart,end := Start_End()\n\n\ttotal := start + \"\\n\" + middle + \"\\n\" + end\n\n\tioutil.WriteFile(\"index.html\",[]byte(total),0677)\n\n\texec.Command(\"open\",\"index.html\").Run()\n\n}", "func TestHTML(t *testing.T) {\n\tm := MarkHub{}\n\terr := m.ParseString(\"# title 1\")\n\tif err != nil {\n\t\tt.Errorf(\"TestHTML(): got -> %v, want: nil\", err)\n\t}\n\thtml := m.HTML()\n\tif len(html) == 0 {\n\t\tt.Errorf(\"TestHTML(): got -> %v, want: length > 0\", len(html))\n\t}\n}", "func HTML(s string) got.HTML {\n\treturn got.HTML(s)\n}", "func execToHTML(_ int, p *gop.Context) {\n\targs := p.GetArgs(3)\n\tdoc.ToHTML(args[0].(io.Writer), args[1].(string), args[2].(map[string]string))\n}", "func (llp *LogLineParsed) HTML(vp viewerProvider) string {\n\tseconds := llp.StampSeconds\n\thour := seconds / (60 * 60)\n\tseconds -= hour * 60 * 60\n\tminute := seconds / 60\n\tseconds -= minute * 60\n\n\tcatStr := llp.Cat.FriendlyName()\n\tif llp.Msg == nil {\n\t\treturn fmt.Sprintf(ChatLogFormatHTML,\n\t\t\tcatStr,\n\t\t\thour, minute, seconds,\n\t\t\tllp.Body)\n\t}\n\n\tmsgContent := llp.Msg.Emotes.Replace(llp.Msg.Content)\n\n\t// Multiple Badges\n\tbadgeHTML := \"\"\n\n\t// Get Viewer Data\n\tv, err := vp.GetData(llp.Msg.UserID)\n\tif err != nil {\n\t\treturn fmt.Sprintf(ChatLogFormatMsgHTML,\n\t\t\tcatStr,\n\t\t\thour, minute, seconds,\n\t\t\tllp.Msg.UserID,\n\t\t\tbadgeHTML,\n\t\t\tllp.Msg.Nick,\n\t\t\tmsgContent)\n\t}\n\n\t// View Lock\n\tif v.Follower != nil {\n\t\tcatStr += \" follow\"\n\t}\n\n\tchatColor := \"#DDD\"\n\tif v.Chatter != nil {\n\t\tchatColor = v.Chatter.Color\n\n\t\tfor badgeID, ver := range v.Chatter.Badges {\n\t\t\tbadgeHTML += vp.Client().Badges.BadgeHTML(badgeID, ver)\n\t\t}\n\n\t\treturn llp.Body\n\t}\n\t//\n\n\treturn fmt.Sprintf(ChatLogFormatMsgExtraHTML,\n\t\tcatStr,\n\t\tchatColor,\n\t\thour, minute, seconds,\n\t\tllp.Msg.UserID,\n\t\tbadgeHTML,\n\t\tllp.Msg.Nick,\n\t\tmsgContent)\n}", "func _html(ns Nodes, outer bool) string {\n\tif len(ns) == 0 {\n\t\treturn \"\"\n\t}\n\twr := w{}\n\tif outer {\n\t\thtml.Render(&wr, ns[0].Node)\n\t} else {\n\t\tfor _, v := range ns[0].Node.Child {\n\t\t\thtml.Render(&wr, v)\n\t\t}\n\t}\n\treturn wr.s\n}", "func (o *OutputHandler) createBeautifulHTML() error {\n\terr := o.importFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.markdownToHTML()\n\n\terr = o.createFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func templateHTML(releases []models.HelmRelease, w io.Writer) error {\n\n\tsum := internalSummery{\n\t\tOutdatedReleases: make(map[string][]uiHelmRelease),\n\t\tDeprecatedReleases: make(map[string][]uiHelmRelease),\n\t\tGoodReleases: make(map[string][]uiHelmRelease),\n\t}\n\n\tfor _, c := range releases {\n\t\tuiC := uiHelmRelease{\n\t\t\tName: c.Name,\n\t\t\tNamespace: c.Namespace,\n\t\t\tDeprecated: c.Deprecated,\n\t\t\tInstalledVersion: c.InstalledVersion,\n\t\t\tLatestVersion: c.LatestVersion,\n\t\t\tOutdated: c.InstalledVersion != c.LatestVersion,\n\t\t}\n\n\t\tif uiC.Deprecated {\n\t\t\tsum.DeprecatedReleases[uiC.Namespace] = append(sum.DeprecatedReleases[uiC.Namespace], uiC)\n\t\t} else if uiC.Outdated {\n\t\t\tsum.OutdatedReleases[uiC.Namespace] = append(sum.OutdatedReleases[uiC.Namespace], uiC)\n\t\t} else {\n\t\t\tsum.GoodReleases[uiC.Namespace] = append(sum.GoodReleases[uiC.Namespace], uiC)\n\t\t}\n\t}\n\n\tfor i, v := range sum.DeprecatedReleases {\n\t\tsort.Sort(ByName(v))\n\t\tsum.DeprecatedReleases[i] = v\n\t}\n\n\tfor i, v := range sum.OutdatedReleases {\n\t\tsort.Sort(ByName(v))\n\t\tsum.OutdatedReleases[i] = v\n\t}\n\n\tfor i, v := range sum.GoodReleases {\n\t\tsort.Sort(ByName(v))\n\t\tsum.GoodReleases[i] = v\n\t}\n\n\tt := template.Must(template.New(\"index.html\").Funcs(getFunctions()).ParseFS(views, \"views/*\"))\n\terr := t.Execute(w, sum)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *Template) Html() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"html\"])\n}", "func page(content string) string {\n\treturn \"<html><body>\\n\" + content + \"\\n</body></html>\"\n}", "func (e *explorer) outputGoHTML(goSource, funcName string, lines [][2]int, step int, subStep string) error {\n\t// Get Chroma Go lexer.\n\tlexer := lexers.Get(\"go\")\n\tif lexer == nil {\n\t\tlexer = lexers.Fallback\n\t}\n\t//lexer = chroma.Coalesce(lexer)\n\t// Get Chrome style.\n\tstyle := styles.Get(e.style)\n\tif style == nil {\n\t\tstyle = styles.Fallback\n\t}\n\t// Get Chroma HTML formatter.\n\tformatter := html.New(\n\t\thtml.TabWidth(3),\n\t\thtml.WithLineNumbers(),\n\t\thtml.WithClasses(),\n\t\thtml.LineNumbersInTable(),\n\t\t//html.HighlightLines(lines),\n\t)\n\t// Generate syntax highlighted Go code.\n\titerator, err := lexer.Tokenise(nil, goSource)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tgoCode := &bytes.Buffer{}\n\tif err := formatter.Format(goCode, style, iterator); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\t// Generate Go HTML page.\n\thtmlContent := &bytes.Buffer{}\n\tdata := map[string]interface{}{\n\t\t\"FuncName\": funcName,\n\t\t\"Style\": e.style,\n\t\t\"GoCode\": template.HTML(goCode.String()),\n\t}\n\tif err := e.goTmpl.Execute(htmlContent, data); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\thtmlName := fmt.Sprintf(\"%s_step_%04d%s_go.html\", funcName, step, subStep)\n\thtmlPath := filepath.Join(e.outputDir, htmlName)\n\tdbg.Printf(\"creating file %q\", htmlPath)\n\tif err := ioutil.WriteFile(htmlPath, htmlContent.Bytes(), 0644); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func getStories(w http.ResponseWriter, r *http.Request) {\n\t// get all of the story id\n\tids := getNewsItems()\n\t// filter out anything that isn't a story\n\t// Not sure this is going to be a necessary step\n\tstories := filterStories(ids)\n\n\tvar s []map[string]interface{}\n\n\tfor i := 0; i < len(stories); i++ {\n\t\ts = append(s, stories[i])\n\t\t// fmt.Println(\"stories\", byt)\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tw.WriteHeader(http.StatusCreated)\n\t// json.NewEncoder(w).Encode(s)\n\tbyt, err := json.Marshal(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tw.Write(byt)\n}", "func viewPage(response http.ResponseWriter, request *http.Request) {\n\ttitle := request.URL.Path[len(\"/\"):]\n\tpage, err := loadPage(title)\n\tif err != nil {\n\t\thttp.Error(response, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tfmt.Fprintf(response, \"<div><h1>%s</h1></div><div><p>%s</p></div>\", page.Title, page.Body)\n}", "func Html(url string) ([]byte, error) {\n\trsp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not make request: %w\", err)\n\t}\n\tdefer rsp.Body.Close()\n\tbody, err := ioutil.ReadAll(rsp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not read response body: %w\", err)\n\t}\n\treturn body, nil\n}", "func (as *Action) HTML(u string, args ...interface{}) *httptest.Request {\n\treturn httptest.New(as.App).HTML(u, args...)\n}", "func main() {\n\t// We place each set of stories in a new buffer\n\thnStories := newHnStories()\n\tredditStories := newRedditStories()\n\t// And we need a buffer to contain all stories\n\tvar stories []Story\n\n\t// Now we check that each source actually did return some stories\n\tif hnStories != nil {\n\t\t// If so, we'll append those to the list\n\t\tstories = append(stories, hnStories...)\n\t}\n\tif redditStories != nil {\n\t\tstories = append(stories, redditStories...)\n\t}\n\n\t// Now let's write these stories to a file, stories.txt\n\t// First we open the file\n\tfile, err := os.Create(\"stories.txt\")\n\t// If there's a problem opening the file, abort\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\t// And we'll defer closing the file\n\tdefer file.Close()\n\t// Now we'll write the stories out to the file\n\tfor _, s := range stories {\n\t\tfmt.Fprintf(file, \"%s: %s\\nby %s on %s\\n\\n\", s.title, s.url, s.author, s.source)\n\t}\n\n\t// Finally, we'll print out all the stories we received\n\tfor _, s := range stories {\n\t\tfmt.Printf(\"%s: %s\\nby %s on %s\\n\\n\", s.title, s.url, s.author, s.source)\n\t}\n}", "func createHTMLNote(htmlFileName, mdFileName string) error {\n\tvar result error\n\tlog.Print(\"Generating HTML release note...\")\n\tcssFileName := \"/tmp/release_note_cssfile\"\n\tcssFile, err := os.Create(cssFileName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create css file %s: %v\", cssFileName, err)\n\t}\n\n\tcssFile.WriteString(\"<style type=text/css> \")\n\tcssFile.WriteString(\"table,th,tr,td {border: 1px solid gray; \")\n\tcssFile.WriteString(\"border-collapse: collapse;padding: 5px;} \")\n\tcssFile.WriteString(\"</style>\")\n\t// Here we manually close the css file instead of defer the close function,\n\t// because we need to use the css file for pandoc command below.\n\t// Writing to css file is a clear small logic so we don't separate it into\n\t// another function.\n\tif err = cssFile.Close(); err != nil {\n\t\treturn fmt.Errorf(\"failed to close file %s, %v\", cssFileName, err)\n\t}\n\n\thtmlStr, err := u.Shell(\"pandoc\", \"-H\", cssFileName, \"--from\", \"markdown_github\", \"--to\", \"html\", mdFileName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to generate html content: %v\", err)\n\t}\n\n\thtmlFile, err := os.Create(htmlFileName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create html file: %v\", err)\n\t}\n\tdefer func() {\n\t\tif err = htmlFile.Close(); err != nil {\n\t\t\tresult = fmt.Errorf(\"failed to close file %s, %v\", htmlFileName, err)\n\t\t}\n\t}()\n\n\thtmlFile.WriteString(htmlStr)\n\treturn result\n}", "func (e *explorer) outputLLVMHTML(f *ir.Func, lines [][2]int, step int) error {\n\t// Get Chroma LLVM IR lexer.\n\tlexer := lexers.Get(\"llvm\")\n\tif lexer == nil {\n\t\tlexer = lexers.Fallback\n\t}\n\t//lexer = chroma.Coalesce(lexer)\n\t// Get Chrome style.\n\tstyle := styles.Get(e.style)\n\tif style == nil {\n\t\tstyle = styles.Fallback\n\t}\n\t// Get Chroma HTML formatter.\n\tformatter := html.New(\n\t\thtml.TabWidth(3),\n\t\thtml.WithLineNumbers(),\n\t\thtml.WithClasses(),\n\t\thtml.LineNumbersInTable(),\n\t\thtml.HighlightLines(lines),\n\t)\n\t// Generate syntax highlighted LLVM IR assembly.\n\tllvmSource := f.LLString()\n\titerator, err := lexer.Tokenise(nil, llvmSource)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tllvmCode := &bytes.Buffer{}\n\tif err := formatter.Format(llvmCode, style, iterator); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\t// Generate LLVM IR HTML page.\n\thtmlContent := &bytes.Buffer{}\n\tfuncName := f.Name()\n\tdata := map[string]interface{}{\n\t\t\"FuncName\": funcName,\n\t\t\"Style\": e.style,\n\t\t\"LLVMCode\": template.HTML(llvmCode.String()),\n\t}\n\tif err := e.llvmTmpl.Execute(htmlContent, data); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\thtmlName := fmt.Sprintf(\"%s_step_%04d_llvm.html\", funcName, step)\n\thtmlPath := filepath.Join(e.outputDir, htmlName)\n\tdbg.Printf(\"creating file %q\", htmlPath)\n\tif err := ioutil.WriteFile(htmlPath, htmlContent.Bytes(), 0644); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func Track_() HTML {\n return Track(nil)\n}", "func HTML(c *slurp.C, data interface{}) slurp.Stage {\n\treturn func(in <-chan slurp.File, out chan<- slurp.File) {\n\n\t\ttemplates := html.New(\"\")\n\n\t\tvar wg sync.WaitGroup\n\t\tdefer wg.Wait() //Wait before all templates are executed.\n\n\t\tfor f := range in {\n\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\t_, err := buf.ReadFrom(f.Reader)\n\t\t\tf.Close()\n\t\t\tif err != nil {\n\t\t\t\tc.Println(err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ttemplate, err := templates.New(f.Stat.Name()).Parse(buf.String())\n\t\t\tif err != nil {\n\t\t\t\tc.Println(err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tf.Reader = NewTemplateReadCloser(c, wg, template, data)\n\n\t\t\tout <- f\n\t\t}\n\t}\n}", "func Start(story map[string]storyBuilder.Arc) {\n\tconst tpl = `\n\t\t<!DOCTYPE html>\n\t\t<html>\n\t\t\t<head>\n\t\t\t\t<meta charset=\"UTF-8\">\n\t\t\t\t<title>{{.Title}}</title>\n\t\t\t</head>\n\t\t\t<body>\n\t\t\t<h1>{{.Title}}</h1>\n\t\t\t{{range .Paragraphs}}\n\t\t\t\t<p>{{.}}</p>\n\t\t\t{{end}}\n\t\t\t\t{{range .Options}}\n\t\t\t\t\t<p>\n\t\t\t\t\t\t<a href=\"/{{.ArcLink}}\">{{.Text}}</a>\n\t\t\t\t\t</p>\n\t\t\t\t{{end}}\n\t\t\t</body>\n\t\t</html>`\n\n\ttemplate, err := template.New(\"story\").Parse(tpl)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\thandler := func(w http.ResponseWriter, req *http.Request) {\n\t\turl := strings.Replace(req.URL.Path, \"/\", \"\", 1)\n\t\tcurrentStory, found := story[url]\n\t\tif found {\n\t\t\ttemplate.Execute(w, currentStory)\n\t\t} else {\n\t\t\ttemplate.Execute(w, story[\"intro\"])\n\t\t}\n\n\t}\n\n\thttp.HandleFunc(\"/\", handler)\n\tfmt.Println(\"Server is listening on port 8080\")\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}", "func generateURLIssue(h string) string {\n\tconst (\n\t\ttitle = \"Move your ass\"\n\t\turlFormat = \"https://github.com/sjeandeaux/nexus-cli/issues/new?title=%s&body=%s\"\n\t\tbodyFormat = \"Could you add the hash %q lazy man?\\n%s\"\n\t)\n\tescapedTitle := url.QueryEscape(title)\n\tbody := fmt.Sprintf(bodyFormat, h, information.Print())\n\tescapedBody := url.QueryEscape(body)\n\turlIssue := fmt.Sprintf(urlFormat, escapedTitle, escapedBody)\n\treturn urlIssue\n}", "func viewHandler(w http.ResponseWriter, r *http.Request, title string) {\n\t// Special case for the root page.\n\tif title == rootTitle {\n\t\trootHandler(w, r, title)\n\t\treturn\n\t}\n\n\tp, err := loadPage(title)\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/edit/\"+title, http.StatusFound)\n\t\treturn\n\t}\n\n\tp.Ingredients = template.HTML(blackfriday.MarkdownCommon([]byte(p.Ingredients)))\n\tp.Instructions = template.HTML(blackfriday.MarkdownCommon([]byte(p.Instructions)))\n\tp.Ingredients = template.HTML(convertWikiMarkup([]byte(p.Ingredients)))\n\tp.Instructions = template.HTML(convertWikiMarkup([]byte(p.Instructions)))\n\trenderTemplate(w, \"view\", p)\n}", "func generateHTML(writer http.ResponseWriter, data interface{}, filenames ...string) {\n\n\tvar t *template.Template\n\tvar files []string\n\tfor _, file := range filenames {\n\t\tfiles = append(files, fmt.Sprintf(\"web/ui/template/HTMLLayouts/%s.html\", file))\n\t}\n\tt = template.Must(template.ParseFiles(files...))\n\tt.ExecuteTemplate(writer, \"layout\", data)\n}", "func (thread *Thread) HTML() string {\n\tif thread.html != \"\" {\n\t\treturn thread.html\n\t}\n\n\tthread.html = markdown.Render(thread.Text)\n\treturn thread.html\n}", "func (c *StoryController) Get() mvc.Result {\n\tstories, err := c.StoryUsecase.GetAll()\n\tif err != nil {\n\t\treturn mvc.View{\n\t\t\tName: \"index.html\",\n\t\t\tData: iris.Map{\"Title\": \"Stories\"},\n\t\t}\n\t}\n\n\treturn mvc.View{\n\t\tName: \"index.html\",\n\t\tData: iris.Map{\"Title\": \"Stories\", \"Stories\": stories},\n\t}\n}", "func main() {\n\tstory := flag.String(\"story\", \"\", \"select the story to play.\")\n\tflag.Parse()\n\n\troot := flag.Arg(0)\n\tif !stories.Select(*story) || root == \"\" {\n\t\tfmt.Println(\"Expected a story and a directory of files to serve.\")\n\t\tfmt.Println(\"ex. webapp -story sushi .\")\n\t\tfmt.Println(\"The following example stories are available:\")\n\t\tfor _, nick := range stories.List() {\n\t\t\tfmt.Println(\" \", nick)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"listening on http://localhost:8080\")\n\t\thandler := support.NewServeMux()\n\t\thandler.HandleFunc(\"/game/\", net.HandleResource(ess.GameResource(mem.NewSessions())))\n\t\thandler.HandleFilePatterns(root,\n\t\t\tsupport.Dir(\"/app/\"),\n\t\t\tsupport.Dir(\"/bower_components/\"),\n\t\t\tsupport.Dir(\"/media/\"))\n\t\tgo support.OpenBrowser(\"http://localhost:8080/app/\")\n\t\tlog.Fatal(http.ListenAndServe(\":8080\", handler))\n\t}\n}", "func publishShareInstructions(url string) {\n\tlog.Println(\"\\n\" + GrayStyle.Render(\" Share your GIF with Markdown:\"))\n\tlog.Println(CommandStyle.Render(\" ![Made with VHS]\") + URLStyle.Render(\"(\"+url+\")\"))\n\tlog.Println(GrayStyle.Render(\"\\n Or HTML (with badge):\"))\n\tlog.Println(CommandStyle.Render(\" <img \") + CommandStyle.Render(\"src=\") + URLStyle.Render(`\"`+url+`\"`) + CommandStyle.Render(\" alt=\") + URLStyle.Render(`\"Made with VHS\"`) + CommandStyle.Render(\">\"))\n\tlog.Println(CommandStyle.Render(\" <a \") + CommandStyle.Render(\"href=\") + URLStyle.Render(`\"https://vhs.charm.sh\"`) + CommandStyle.Render(\">\"))\n\tlog.Println(CommandStyle.Render(\" <img \") + CommandStyle.Render(\"src=\") + URLStyle.Render(`\"https://stuff.charm.sh/vhs/badge.svg\"`) + CommandStyle.Render(\">\"))\n\tlog.Println(CommandStyle.Render(\" </a>\"))\n\tlog.Println(GrayStyle.Render(\"\\n Or link to it:\"))\n}", "func CreateArticelePage(w http.ResponseWriter, r *http.Request) {\n\n\tvars := mux.Vars(r)\n\n\tmtitle := vars[\"mtitle\"]\n\n\tmongoDBDialInfo := &mgo.DialInfo{\n\n\t\tAddrs: []string{\"mymongo-controller\"},\n\t\tTimeout: 60 * time.Second,\n\t\tDatabase: \"admin\",\n\t\tUsername: mongodbuser,\n\t\tPassword: mongodbpass,\n\t\tMechanism: \"SCRAM-SHA-1\",\n\t}\n\n\tdbsession, err := mgo.DialWithInfo(mongoDBDialInfo)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer dbsession.Close()\n\n\tif mtitle == \"\" {\n\n\t\tlog.Println(\"no mtitle\")\n\n\t\tarticles := dbhandler.GetAllForStatic(*dbsession, \"kaukotyo.eu\")\n\t\tjson.NewEncoder(w).Encode(articles)\n\n\t} else {\n\n\t\tarticle := dbhandler.GetOneArticle(*dbsession, mtitle)\n\n\t\tjson.NewEncoder(w).Encode(article)\n\n\t}\n}", "func HTMLString(data interface{}, viewName string) string {\n\tvar html bytes.Buffer\n\ttemplateName := viewName\n\tt, err := Jet.GetTemplate(templateName)\n\tif err != nil {\n\t\tlog.Println(\"Failed to get tempalte \")\n\t}\n\tvars := make(jet.VarMap)\n\tif err = t.Execute(&html, vars, data); err != nil {\n\t\tlog.Println(\"Failed to execute view tepmlate \")\n\t}\n\treturn html.String()\n}", "func generateHTML(domain, pkg, source string) ([]byte, error) {\n\tvar (\n\t\tdir, file, redirect string\n\t\tb bytes.Buffer\n\t)\n\n\tif pkg != \"\" {\n\t\tredirect = \"https://pkg.go.dev/\" + domain + \"/\" + pkg\n\n\t\t// Add the URL scheme if not already present\n\t\tif !strings.HasPrefix(source, \"http\") {\n\t\t\tsource = \"https://\" + source\n\t\t}\n\n\t\t// Deduce go-source paths for the hosting\n\t\tswitch path := urlMustParse(source); path.Host {\n\t\tcase \"github.com\":\n\t\t\tdir = source + \"/tree/master/{dir}\"\n\t\t\tfile = source + \"/blob/master/{dir}/{file}#L{line}\"\n\t\tcase \"gitlab.com\":\n\t\t\tdir = source + \"/-/tree/master/{dir}\"\n\t\t\tfile = source + \"/-/blob/master/{dir}/{file}#L{line}\"\n\t\t}\n\t} else {\n\t\tredirect = \"https://\" + domain\n\t}\n\n\tt := template.Must(template.New(\"package\").Parse(templString))\n\terr := t.Execute(&b, &templValue{redirect, domain, pkg, source, dir, file})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b.Bytes(), nil\n}", "func htmlPageHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, `\n<html>\n\t<head><script type=\"text/javascript\"><!--\n\t\tfunction reloadpic()\n {\n\t\t\tdocument.images[\"gameBoard\"].src = \"image/test.png\";\n\t\t\tsetTimeout(reloadpic, 400);\n }\n setTimeout(reloadpic, 400)\n\t--></script></head>\n\t<body bgcolor=\"#888888\"><img id=\"gameBoard\" src=\"image/test.png\" height=\"910\" width=\"1360\"/></body>\n</html>`)\n\n}", "func main() {\n\twebview.Open(\"GoNotes\", \"file:///home/ubuntu/go/src/github.com/mattackard/project-0/cmd/GoNotesClient/client.html\", 600, 700, true)\n}", "func (bt *Hackerbeat) fetchStory(stories chan<- story, storyID uint) {\n\tstory := story{\n\t\tID: storyID,\n\t}\n\n\t// Generate getStoryURL from getItemURL and storyID\n\tgetStoryURL := strings.Replace(getItemURL, storyIDToken, strconv.FormatUint(uint64(storyID), 10), -1)\n\n\t// Get story from HackerNews API\n\tresp, err := bt.httpClient.Get(getStoryURL)\n\tif err != nil {\n\t\tbt.logger.Errorw(\n\t\t\t\"Failed to get story\",\n\t\t\t\"error\", err,\n\t\t)\n\t\treturn\n\t}\n\n\t// Read all bytes from response body\n\tstoryInfos, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tbt.logger.Errorw(\n\t\t\t\"Failed to parse story\",\n\t\t\t\"error\", err,\n\t\t)\n\t\treturn\n\t}\n\n\t// Unmarshal response body into our story data structure\n\terr = json.Unmarshal(storyInfos, &story)\n\tif err != nil {\n\t\tbt.logger.Errorw(\n\t\t\t\"Failed to unmarshal story\",\n\t\t\t\"error\", err,\n\t\t)\n\t\treturn\n\t}\n\n\t// Send story back to the main thread\n\tstories <- story\n}", "func RenderHTMLWithMetadata(actual string, settings ...configuration.Setting) (string, types.Metadata, error) {\n\tallSettings := append([]configuration.Setting{configuration.WithFilename(\"test.adoc\"), configuration.WithBackEnd(\"html5\")}, settings...)\n\tconfig := configuration.NewConfiguration(allSettings...)\n\tcontentReader := strings.NewReader(actual)\n\tresultWriter := bytes.NewBuffer(nil)\n\tmetadata, err := libasciidoc.Convert(contentReader, resultWriter, config)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn \"\", types.Metadata{}, err\n\t}\n\tif log.IsLevelEnabled(log.DebugLevel) {\n\t\tlog.Debug(resultWriter.String())\n\t}\n\treturn resultWriter.String(), metadata, nil\n}", "func getHTMLContent(articleContent *goquery.Selection) string {\n\thtml, err := articleContent.Html()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\thtml = ghtml.UnescapeString(html)\n\thtml = rxComments.ReplaceAllString(html, \"\")\n\thtml = rxKillBreaks.ReplaceAllString(html, \"<br />\")\n\thtml = rxSpaces.ReplaceAllString(html, \" \")\n\treturn html\n}", "func (r renderer) BlockHtml(out *bytes.Buffer, text []byte) {}", "func HTMLFromResults(script *Script, serverConfigs map[string]ServerConfig, scriptResults map[string]*ScriptResults) string {\n\t// sorted ID list\n\tvar sortedIDs []string\n\tfor id := range serverConfigs {\n\t\tsortedIDs = append(sortedIDs, id)\n\t}\n\tsort.Strings(sortedIDs)\n\n\t// tab buttons\n\tvar tabs string\n\tfor _, id := range sortedIDs {\n\t\ttabs += fmt.Sprintf(tabText, id, serverConfigs[id].DisplayName)\n\t}\n\n\t// css\n\tvar css string\n\thue := 150\n\tfor id := range script.Clients {\n\t\t// + 5 for ' <- ' or similar\n\t\tcss += fmt.Sprintf(cssPreTemplate, id, len(id)+5, hue)\n\t\thue += 40\n\t}\n\n\t// construct JSON blob used by the page\n\tblob := htmlJSONBlob{\n\t\tDefaultServer: sortedIDs[0],\n\t\tServerNames: make(map[string]string),\n\t\tServerLogs: make(map[string]serverBlob),\n\t}\n\tfor id, info := range serverConfigs {\n\t\tblob.ServerNames[id] = info.DisplayName\n\t}\n\tfor id, sr := range scriptResults {\n\t\tvar sBlob serverBlob\n\n\t\tvar actionIndex int\n\t\tfor _, srl := range sr.Lines {\n\t\t\tswitch srl.Type {\n\t\t\tcase ResultIRCMessage:\n\t\t\t\t// raw line\n\t\t\t\tlineRaw := lineBlob{\n\t\t\t\t\tClient: srl.Client,\n\t\t\t\t\tSentBy: \"s\",\n\t\t\t\t\tLine: strings.TrimSuffix(srl.RawLine, \"\\r\\n\"),\n\t\t\t\t}\n\t\t\t\tsBlob.Raw = append(sBlob.Raw, lineRaw)\n\n\t\t\t\t// sanitised line\n\t\t\t\tsanitisedLine := srl.RawLine\n\t\t\t\tfor orig, new := range serverConfigs[id].SanitisedReplacements {\n\t\t\t\t\tsanitisedLine = strings.Replace(sanitisedLine, orig, new, -1)\n\t\t\t\t}\n\t\t\t\tlineSanitised := lineBlob{\n\t\t\t\t\tClient: srl.Client,\n\t\t\t\t\tSentBy: \"s\",\n\t\t\t\t\tLine: strings.TrimSuffix(sanitisedLine, \"\\r\\n\"),\n\t\t\t\t}\n\t\t\t\tsBlob.Sanitised = append(sBlob.Sanitised, lineSanitised)\n\t\t\tcase ResultActionSync:\n\t\t\t\tthisAction := script.Actions[actionIndex]\n\t\t\t\tif thisAction.LineToSend != \"\" {\n\t\t\t\t\t// sent line always stays the same\n\t\t\t\t\tline := lineBlob{\n\t\t\t\t\t\tClient: thisAction.Client,\n\t\t\t\t\t\tSentBy: \"c\",\n\t\t\t\t\t\tLine: strings.TrimSuffix(thisAction.LineToSend, \"\\r\\n\"),\n\t\t\t\t\t}\n\t\t\t\t\tsBlob.Raw = append(sBlob.Raw, line)\n\t\t\t\t\tsBlob.Sanitised = append(sBlob.Sanitised, line)\n\t\t\t\t}\n\t\t\t\tactionIndex++\n\t\t\tcase ResultDisconnected:\n\t\t\t\tline := lineBlob{\n\t\t\t\t\tClient: srl.Client,\n\t\t\t\t\tError: fmt.Sprintf(\"%s was disconnected unexpectedly\", srl.Client),\n\t\t\t\t}\n\t\t\t\tsBlob.Raw = append(sBlob.Raw, line)\n\t\t\t\tsBlob.Sanitised = append(sBlob.Sanitised, line)\n\t\t\tcase ResultDisconnectedExpected:\n\t\t\t\tline := lineBlob{\n\t\t\t\t\tClient: srl.Client,\n\t\t\t\t\tError: fmt.Sprintf(\"%s was disconnected\", srl.Client),\n\t\t\t\t}\n\t\t\t\tsBlob.Raw = append(sBlob.Raw, line)\n\t\t\t\tsBlob.Sanitised = append(sBlob.Sanitised, line)\n\t\t\t}\n\t\t}\n\n\t\tblob.ServerLogs[id] = sBlob\n\t}\n\n\t// marshall json blob\n\tblobBytes, err := json.Marshal(blob)\n\tblobString := \"{'error': 1}\"\n\tif err == nil {\n\t\tblobString = string(blobBytes)\n\t}\n\n\t// assemble template\n\treturn fmt.Sprintf(htmlTemplate, script.Name, script.ShortDescription, tabs, blobString, css)\n}", "func (VS *Server) manuals(c *gin.Context) {\n\trender(c, gin.H{}, \"presentation-manuals.html\")\n}", "func (this *Asset) buildHTML() template.HTML {\n\tvar tag_fn func(string) template.HTML\n\tswitch this.assetType {\n\tcase ASSET_JAVASCRIPT:\n\t\ttag_fn = js_tag\n\tcase ASSET_STYLESHEET:\n\t\ttag_fn = css_tag\n\tdefault:\n\t\tError(\"Unknown asset type\")\n\t\treturn \"\"\n\t}\n\tvar result template.HTML\n\tfor _, assetFile := range this.result {\n\t\tresult += tag_fn(\"/\" + assetFile.Path)\n\t}\n\treturn result\n}", "func (service *StoriesService) getStories(codes []int, limit int64) ([]*handler.Story, error) {\n\n\t// concurrency is cool, but needs to be limited\n\tsemaphore := make(chan struct{}, 10)\n\n\t// how we know when all our goroutines are done\n\twg := sync.WaitGroup{}\n\n\t// somewhere to store all the stories when we're done\n\tstories := make([]*handler.Story, 0)\n\n\t// go over all the stories\n\tfor _, code := range codes {\n\n\t\t// stop when we have 30 stories\n\t\tif int64(len(stories)) >= limit {\n\t\t\tbreak\n\t\t}\n\n\t\t// in a goroutine with the story key\n\t\tgo func(code int) {\n\n\t\t\t// add one to the wait group\n\t\t\twg.Add(1)\n\n\t\t\t// add one to the semaphore\n\t\t\tsemaphore <- struct{}{}\n\n\t\t\t// make sure this gets fired\n\t\t\tdefer func() {\n\n\t\t\t\t// remove one from the wait group\n\t\t\t\twg.Done()\n\n\t\t\t\t// remove one from the semaphore\n\t\t\t\t<-semaphore\n\t\t\t}()\n\n\t\t\tp, err := service.hn.GetPost(code)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Error(\"error get stories\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// parse the url\n\t\t\tu, err := url.Parse(p.Url)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Error(\"error get stories\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// get the hostname from the url\n\t\t\th := u.Hostname()\n\n\t\t\t// check if it's from github or gitlab before adding to stories\n\t\t\tif strings.Contains(h, \"github\") || strings.Contains(h, \"gitlab\") {\n\t\t\t\tlog.Debugf(\"found url (%s)\", p.Url)\n\n\t\t\t\ts := &handler.Story{\n\t\t\t\t\tScore: p.Score,\n\t\t\t\t\tTitle: p.Title,\n\t\t\t\t\tUrl: p.Url,\n\t\t\t\t}\n\n\t\t\t\tif strings.Contains(h, \"github\") {\n\t\t\t\t\tvar err error\n\t\t\t\t\ts.Langauges, err = service.gh.GetDataBy(p.Url)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.WithError(err).Error(\"error get stories\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ts.DomainName = h\n\t\t\t\tstories = append(stories, s)\n\t\t\t}\n\n\t\t}(code)\n\t}\n\n\t// wait for all the goroutines\n\twg.Wait()\n\n\treturn stories, nil\n}", "func Html(resp http.ResponseWriter, content string, code int) error {\n\tresp.Header().Add(\"Content-Type\", \"text/html\")\n\tresp.WriteHeader(code)\n\t_, err := resp.Write([]byte(content))\n\treturn maskAny(err)\n}", "func (dt *Slick) HTMLTemplate() string {\n\treturn htmlTemplate\n}", "func (p *TestPager) GeneratePagerHtml() (string, error) {\n p.FixData()\n\n var buffer bytes.Buffer\n left := p.Total\n i := 1\n for left > 0 {\n // generate spliter before\n if i > 1 {\n buffer.WriteString(d_spliter)\n }\n\n // main page nubmer\n if p.PageItems*(i-1) < p.Current && p.Current <= p.PageItems*i {\n buffer.WriteString(d_curr1)\n buffer.WriteString(strconv.Itoa(i))\n buffer.WriteString(d_curr2)\n } else {\n buffer.WriteString(d_pagenumber1)\n buffer.WriteString(strconv.Itoa(i))\n buffer.WriteString(d_pagenumber2)\n }\n // prepare next loop\n i += 1\n left -= p.PageItems\n }\n\n return buffer.String(), nil\n}", "func render(src string, dst string) {\n\tdefer wg.Done()\n\tmd, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\tprintErr(err)\n\t\treturn\n\t}\n\thtml := renderHtml(md)\n\tif stylefile != \"\" {\n\t\thtml = addStyle(html, stylecont)\n\t} else {\n\t\thtml = addStyle(html, CSS)\n\t}\n\n\terr = ioutil.WriteFile(dst, []byte(html), 0644)\n\tif err != nil {\n\t\tprintErr(err)\n\t}\n}", "func TestToHTML(timestamp string, results [][]string) string {\n\tvar ti testResults\n\n\t// for each line in the test results\n\tfor i := 0; i < len(results); i++ {\n\t\t// transform line to HTML\n\t\tfor _, v := range results[i] {\n\t\t\tparseTestLine(v, &ti)\n\t\t}\n\t}\n\n\t// return the body as a string\n\treturn statHeader(ti.pass, ti.fail, timestamp) + strings.Join(ti.html, \"\")\n}", "func (c *Client) ReportStory(ctx context.Context, request *ReportStoryRequest) error {\n\tvar ok Ok\n\n\tif err := c.rpc.Invoke(ctx, request, &ok); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func writeHTML(domain, pkg, source, filename string) error {\n\tdata, err := generateHTML(domain, pkg, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.MkdirAll(filepath.Dir(filename), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(filename, data, 0666)\n}", "func Article_(children ...HTML) HTML {\n return Article(nil, children...)\n}", "func outHTML(config *MainConfig, fileFunc FileResultFunc) {\n\n\tindexPath := filepath.Join(config.Outpath, FILE_NAME_HTML_INDEX)\n\terr := SFFileManager.WirteFilepath(indexPath, []byte(assets.HTML_INDEX))\n\n\tif nil != err {\n\t\tfileFunc(indexPath, ResultFileOutFail, err)\n\t} else {\n\t\tfileFunc(indexPath, ResultFileSuccess, nil)\n\t}\n\n\tsrcPath := filepath.Join(config.Outpath, FILE_NAME_HTML_SRC)\n\terr = SFFileManager.WirteFilepath(srcPath, []byte(assets.HTML_SRC))\n\n\tif nil != err {\n\t\tfileFunc(srcPath, ResultFileOutFail, err)\n\t} else {\n\t\tfileFunc(srcPath, ResultFileSuccess, nil)\n\t}\n\n}", "func (account *Account) Stories() *StoryMedia {\r\n\tmedia := &StoryMedia{}\r\n\tmedia.uid = account.ID\r\n\tmedia.inst = account.inst\r\n\tmedia.endpoint = urlUserStories\r\n\treturn media\r\n}", "func (self templateEngine) genBoard(prefix, frontend, newsgroup, outdir string, db Database) {\n // get the board model\n board := self.obtainBoard(prefix, frontend, newsgroup, db)\n // update the entire board model\n board = board.UpdateAll(db)\n // save the model\n self.groups[newsgroup] = board\n updateLinkCache()\n \n pages := len(board)\n for page := 0 ; page < pages ; page ++ {\n outfile := filepath.Join(outdir, fmt.Sprintf(\"%s-%d.html\", newsgroup, page))\n wr, err := OpenFileWriter(outfile)\n if err == nil {\n board[page].RenderTo(wr)\n wr.Close()\n log.Println(\"wrote file\", outfile)\n } else {\n log.Println(\"error generating board page\", page, \"for\", newsgroup, err)\n }\n }\n}", "func (is *infosec) html(page *Page, els element) {\n\tis.Map.html(page, nil)\n\tels.setMeta(\"isInfosec\", true)\n\n\t// not in an infobox{}\n\t// FIXME: do not produce this warning if infosec{} is in a variable\n\tif is.parentBlock().blockType() != \"infobox\" {\n\t\tis.warn(is.openPosition(), \"infosec{} outside of infobox{} does nothing\")\n\t\treturn\n\t}\n\n\t// inject the title\n\tif is.blockName() != \"\" {\n\t\tis.mapList = append([]*mapListEntry{{\n\t\t\tkey: \"_infosec_title_\",\n\t\t\tmetas: map[string]bool{\"isTitle\": true},\n\t\t\tvalue: page.Fmt(is.blockName(), is.openPosition()),\n\t\t}}, is.mapList...)\n\t}\n\n\tinfoTableAddRows(is, els, page, is.mapList)\n}", "func toHTML(s string) template.HTML {\n\treturn template.HTML(s)\n}", "func HTML(opts ...ServerOption) {\n\tsrv, err := initServer(opts...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\thttp.HandleFunc(\"/\", renderTemplate(srv))\n\n\tlog.Println(\"Listening on :3000...\")\n\terr = http.ListenAndServe(\":3000\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (h *Home) SetHtmlFromPosts(html []byte, summ []byte, posts Posts) {\n var summaries []byte\n\n // Sort the Posts\n sort.Sort(posts)\n\n // Loop through Post collection\n for _, post := range posts {\n html := summ\n\n // Replace summary template variables\n html = bytes.Replace(html, []byte(\"{{ path }}\"), []byte(post.path), -1)\n html = bytes.Replace(html, []byte(\"{{ name }}\"), []byte(post.name), -1)\n\n summaries = append(summaries, html...)\n }\n\n // Replace base template variables\n html = bytes.Replace(html, []byte(\"{{ posts }}\"), summaries, -1)\n\n h.html = html\n}", "func (g *Generator) GenerateHTML(data *scraper.ScrapedData) error {\n\treturn g.template.ExecuteTemplate(g.writer, \"profile\", data)\n}", "func RenderHTMLFromFile(filename string, settings ...configuration.Setting) (string, types.Metadata, error) {\n\tinfo, err := os.Stat(filename)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn \"\", types.Metadata{}, err\n\t}\n\n\tallSettings := append([]configuration.Setting{\n\t\tconfiguration.WithLastUpdated(info.ModTime()),\n\t\tconfiguration.WithFilename(filename),\n\t\tconfiguration.WithBackEnd(\"html5\")},\n\t\tsettings...)\n\tconfig := configuration.NewConfiguration(allSettings...)\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn \"\", types.Metadata{}, err\n\t}\n\tdefer func() { f.Close() }()\n\tresultWriter := bytes.NewBuffer(nil)\n\tmetadata, err := libasciidoc.Convert(f, resultWriter, config)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn \"\", types.Metadata{}, err\n\t}\n\tif log.IsLevelEnabled(log.DebugLevel) {\n\t\tlog.Debug(resultWriter.String())\n\t}\n\treturn resultWriter.String(), metadata, nil\n}", "func (r *Recipe) parseHTML() (rerr error) {\n\tif r == nil {\n\t\tr = &Recipe{}\n\t}\n\tif r.FileContent == \"\" || r.FileName == \"\" {\n\t\trerr = fmt.Errorf(\"no file loaded\")\n\t\treturn\n\t}\n\n\tr.Lines, rerr = getIngredientLinesInHTML(r.FileContent)\n\treturn r.parseRecipe()\n\n}", "func (h *ImageProxyHandler) imagesHTML(w http.ResponseWriter, dataURLChan <-chan *dataurl.DataURL) {\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\tif err := imagesPageTmpl.Execute(w, dataURLChan); err != nil {\n\t\th.logger.Println(\"writing html response error:\", err)\n\t}\n}", "func (t *GoatsTemplate) genRenderContent(output io.Writer) string {\n\tvar headProcessor processors.Processor = processors.NewHeadProcessor()\n\n\tvar argProcessor processors.Processor = processors.NewArgProcessor(t.Args)\n\theadProcessor.SetNext(argProcessor)\n\n\tt.buildProcessorChain(argProcessor, t.RootNode)\n\n\tctx := processors.NewTagContext(t.Parser.PkgMgr, t.pkgRefs, t.Parser.Settings.OutputFormat)\n\tif t.NeedsDocType {\n\t\tdocTypeProcessor := processors.NewDocTypeProcessor(t.Parser.DocTypeTag, t.Parser.DocTypeAttrs)\n\t\tdocTypeProcessor.SetNext(headProcessor)\n\t\theadProcessor = docTypeProcessor\n\t}\n\n\tvar renderBuffer bytes.Buffer\n\theadProcessor.Process(&renderBuffer, ctx)\n\treturn renderBuffer.String()\n}", "func viewHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, err := loadPage(title)\n\tif err != nil {\n\t\thttp.Redirect(w, r, \"/edit/\"+title, http.StatusFound)// if there does not exist page:title, make a new page.\n\t\treturn\t\t\n\t}\n\trenderTemplate(w, \"view\", p)\n\t// t, _ := template.ParseFiles(\"view.html\")// return *template.Template, error\n\t// t.Execute(w,p)\n\t// fmt.Fprintf(w, \"<h1>%s</h1><div>%s</div>\", p.Title, p.Body)\n}", "func newHnStories() []Story {\n\t// First we need a buffer to hold stories\n\tvar stories []Story\n\t// We can use the GetChanges function to get all the most recent objects\n\t// from HackerNews. These will just be integer IDs, and we'll need to make requests\n\t// for each one.\n\tchanges, err := hackerNewsClient.GetChanges()\n\t// In case of an error, we'll print it and return nil\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil\n\t}\n\n\t// Now, we can loop over the IDs we got back and make a request for each one.\n\tfor _, id := range changes.Items {\n\t\t// The GetStory method will return a Story struct, or an error if the requested object wasn't\n\t\t// as story.\n\t\tstory, err := hackerNewsClient.GetStory(id)\n\t\t// In case it wasn't a story, just move on.\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\t// Now we can construct a Story struct and put it in the list\n\t\tnewStory := Story{\n\t\t\ttitle: story.Title,\n\t\t\turl: story.URL,\n\t\t\tauthor: story.By,\n\t\t\tsource: \"HackerNews\",\n\t\t}\n\t\tstories = append(stories, newStory)\n\t}\n\n\t// Finally, after the loop completes, we'll just return the stories\n\treturn stories\n}", "func (i Novel) HTMLContent(ctx context.Context, renderer ContentRenderer) (string, error) {\n\tif renderer == nil {\n\t\trenderer = SimpleContentRenderer{EmbeddedImages: i.EmbeddedImages}\n\t}\n\treturn HTMLContent(ctx, renderer, i.Content)\n}", "func (c *rstConverter) getRstContent(src []byte, ctx converter.DocumentContext) []byte {\n\tlogger := c.cfg.Logger\n\tpath := getRstExecPath()\n\n\tif path == \"\" {\n\t\tlogger.Println(\"rst2html / rst2html.py not found in $PATH: Please install.\\n\",\n\t\t\t\" Leaving reStructuredText content unrendered.\")\n\t\treturn src\n\t}\n\n\tlogger.Infoln(\"Rendering\", ctx.DocumentName, \"with\", path, \"...\")\n\n\tvar result []byte\n\t// certain *nix based OSs wrap executables in scripted launchers\n\t// invoking binaries on these OSs via python interpreter causes SyntaxError\n\t// invoke directly so that shebangs work as expected\n\t// handle Windows manually because it doesn't do shebangs\n\tif runtime.GOOS == \"windows\" {\n\t\tpython := internal.GetPythonExecPath()\n\t\targs := []string{path, \"--leave-comments\", \"--initial-header-level=2\"}\n\t\tresult = internal.ExternallyRenderContent(c.cfg, ctx, src, python, args)\n\t} else {\n\t\targs := []string{\"--leave-comments\", \"--initial-header-level=2\"}\n\t\tresult = internal.ExternallyRenderContent(c.cfg, ctx, src, path, args)\n\t}\n\t// TODO(bep) check if rst2html has a body only option.\n\tbodyStart := bytes.Index(result, []byte(\"<body>\\n\"))\n\tif bodyStart < 0 {\n\t\tbodyStart = -7 // compensate for length\n\t}\n\n\tbodyEnd := bytes.Index(result, []byte(\"\\n</body>\"))\n\tif bodyEnd < 0 || bodyEnd >= len(result) {\n\t\tbodyEnd = len(result) - 1\n\t\tif bodyEnd < 0 {\n\t\t\tbodyEnd = 0\n\t\t}\n\t}\n\n\treturn result[bodyStart+7 : bodyEnd]\n}", "func main() {\n\tp1 := &gowiki.Page{Title: \"TestPage\", Body: []byte(\"This is a sample Page.\")}\n\tp1.Save()\n\tp2, _ := gowiki.LoadPage(\"TestPage\")\n\tfmt.Println(string(p2.Body))\n}", "func ForHTMLTemplate(ts ...*template.Template) func(io.Writer) frameless.Presenter {\n\treturn (func(io.Writer) frameless.Presenter)(func(w io.Writer) frameless.Presenter {\n\t\treturn frameless.PresenterFunc(func(data interface{}) error {\n\n\t\t\tmostInnerTemplate := ts[len(ts)-1]\n\t\t\ttContent := bytes.NewBuffer([]byte{})\n\n\t\t\tif err := mostInnerTemplate.Execute(tContent, data); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\trest := ts[:len(ts)-1]\n\t\t\tcurrentContent := tContent.String()\n\n\t\t\tfor i := len(rest) - 1; i >= 0; i-- {\n\t\t\t\tt := rest[i]\n\t\t\t\tb := bytes.NewBuffer([]byte{})\n\n\t\t\t\tif err := t.Execute(b, template.HTML(currentContent)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tcurrentContent = b.String()\n\t\t\t}\n\n\t\t\tw.Write([]byte(currentContent))\n\n\t\t\treturn nil\n\n\t\t})\n\t})\n}", "func BuildPage(htmlTemplate string, bingoBoard BingoBoard) *bytes.Buffer {\n\tvar bodyBuffer bytes.Buffer\n\tt := template.New(\"template\")\n\tvar templates = template.Must(t.Parse(htmlTemplate))\n\ttemplates.Execute(&bodyBuffer, bingoBoard)\n\treturn &bodyBuffer\n}", "func (VS *Server) design(c *gin.Context) {\n\trender(c, gin.H{}, \"presentation-design.html\")\n}", "func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n p, _ := loadPage(\"/src/github.com/mrgirlyman/watcher/frontman/build/index.html\")\n\n fmt.Fprintf(w, string(p.Body))\n // log.Fatal(err)\n\n // if (err != nil) {\n // fmt.Fprintf(w, string(p.Body))\n // } else {\n // fmt.Fprintf(w, \"Error reading index.html\")\n // }\n}", "func TestPutSlidesDocumentFromHtmlInvalidhtml(t *testing.T) {\n request := createPutSlidesDocumentFromHtmlRequest()\n request.html = invalidizeTestParamValue(request.html, \"html\", \"string\").(string)\n e := initializeTest(\"PutSlidesDocumentFromHtml\", \"html\", request.html)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PutSlidesDocumentFromHtml(request)\n assertError(t, \"PutSlidesDocumentFromHtml\", \"html\", r.Code, e)\n}", "func markdownToHTML(s string) string {\n\ts = strings.Replace(s, \"_blank\", \"________\", -1)\n\ts = strings.Replace(s, \"\\\\kh\", \"( )\", -1)\n\ts = strings.Replace(s, \"~\", \" \", -1)\n\tresult := \"\"\n\troot := Parse(s)\n\tfor node := root.FirstChild; node != nil; node = node.NextSibling {\n\t\tif node.Type == NodePara {\n\t\t\tresult += fmt.Sprintf(\"<p> %s </p>\", node.Data)\n\t\t} else if node.Type == NodeImag {\n\t\t\tresult += fmt.Sprintf(\"<p> <img src=\\\"%s\\\" width=\\\"%s\\\" align=\\\"top\\\" /> </p>\", node.Data, node.Attr)\n\t\t} else if node.Type == NodeOl {\n\t\t\tresult += \"<ol>\"\n\t\t\tfor linode := node.FirstChild; linode != nil; linode = linode.NextSibling {\n\t\t\t\tresult += fmt.Sprintf(\"<li %s>\\n\", linode.Attr)\n\t\t\t\tfor p := linode.FirstChild; p != nil; p = p.NextSibling {\n\t\t\t\t\tif p.Type == NodePara {\n\t\t\t\t\t\tresult += fmt.Sprintf(\"<p>%s</p>\", p.Data)\n\t\t\t\t\t} else if p.Type == NodeImag {\n\t\t\t\t\t\tresult += fmt.Sprintf(\"<p> <img src=\\\"%s\\\" width=\\\"%s\\\" align=\\\"top\\\" /> </p>\", p.Data, p.Attr)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult += fmt.Sprintf(\"</li>\\n\")\n\t\t\t}\n\t\t\tresult += \"</ol>\"\n\t\t}\n\t}\n\treturn result\n}", "func htmlHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"<h1>Whoa, Nice!</h1>\")\n\tfmt.Fprint(w, \"<h3>Nice Go</h3>\")\n\tfmt.Fprint(w, \"<p>This is a paragraph</p>\")\n\t// Note Fprintf for formatting\n\tfmt.Fprintf(w, \"<p>You %s even add %s</p>\", \"can\", \"<strong>variables</strong>\")\n\t// Multiline print\n\tfmt.Fprintf(w, `<h1>Hi!</h1>\n<h3>This is also Go</h3>\n<p>Multiline</p>`)\n\n}", "func generateHTMLReport(c *gin.Context,scrapeID string){\n\tjsonFile, err := os.Open(\"data/\" + scrapeID + \"_report.json\")\n\tif err!=nil{\n\t\tc.HTML(\n\t\t\thttp.StatusBadRequest,\n\t\t\t\"error.tmpl\",\n\t\t\tgin.H{\n\t\t\t\t\"err\": \"no report found!\",\n\t\t\t},\n\t\t)\n\t\treturn\n\t}\n\n\tdefer jsonFile.Close()\n\treportInBytes, err := ioutil.ReadAll(jsonFile)\n\tif err!=nil{\n\t\tc.HTML(\n\t\t\thttp.StatusBadRequest,\n\t\t\t\"error.tmpl\",\n\t\t\tgin.H{\n\t\t\t\t\"err\": \"Error while reading report\",\n\t\t\t},\n\t\t)\n\t\treturn\n\t}\n\n\tvar finalReport scraper.Report\n\t_ = json.Unmarshal(reportInBytes, &finalReport)\n\n\tc.HTML(\n\t\thttp.StatusOK,\n\t\t\"index.tmpl\",\n\t\tgin.H{\n\t\t\t\"scrape_id\": finalReport.ScrapeID,\n\t\t\t\"project_id\":finalReport.ProjectID,\n\t\t\t\"folder_threshold\":finalReport.FolderThreshold,\n\t\t\t\"folder_examples_count\":finalReport.FolderExamplesCount,\n\t\t\t\"patterns\":finalReport.Patterns,\n\t\t\t\"details\": finalReport.DetailedReport,\n\t\t},\n\t)\n\treturn\n\n}", "func testTemplate(w http.ResponseWriter, r *http.Request) {\n\ttestpage := Page{\n\t\tID: \"urn:cts:tests:test1.test1:1\",\n\t\tText: template.HTML(\"This is a testing of the template\")}\n\n\trenderTemplate(w, \"view\", testpage)\n}", "func how(w http.ResponseWriter, req *http.Request, ctx httputil.Context) (e *httputil.Error) {\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\n\tif err := T(\"how/how.html\").Execute(w, nil); err != nil {\n\t\te = httputil.Errorf(err, \"error executing index template\")\n\t}\n\treturn\n}", "func PrettyPrints(print int) {\r\n\t/*this section is going to define all my big pretty printing and follow with a simple switch that chooses the particular graphic by its integer number associated with it.\r\n\tthe images come out distorted without modifying them here piece by piece so they look weird here but they look great in use.*/\r\n\r\n\t//this graphic and a few other presented weird so adjustments were made to achieve correct appearance\r\n\tvar pridePic string = `\r\n\t _____ _____ _____ _____\r\n\t| | | __| _ | | __|___ _____ ___ ___\r\n\t| | | |__ | | | | | .'| | -_|_ -|\r\n\t|_|___|_____|__|__| |_____|__,|_|_|_|___|___|\r\n\t _____ _\r\n\t\t| _ |___ ___ ___ ___ ___| |_ ___\r\n\t\t| __| _| -_|_ -| -_| | _|_ -|\r\n\t\t|__| |_| |___|___|___|_|_|_| |___|\r\n`\r\n\tvar titlePic string = `\r\n\t _____ _ _\r\n\t| _ |___ ___ |_|___ ___| |_\r\n\t| __| _| . | | | -_| _| _|\r\n\t|__| |_| |___|_| |___|___|_|\r\n\t\t |___|\r\n\t \t _ _\r\n\t\t _| | |_ ___\r\n\t |_ _| |_ |\r\n\t\t |_ _| | _|\r\n\t\t |_|_| |___|\r\n`\r\n\r\n\tvar spellPic string = `\r\n /\\\r\n / \\\r\n | |\r\n --:'''':--\r\n :'_' :\r\n _:\"\":\\___\r\n ' ' ____.' ::: '._\r\n . *=====<<=) \\ :\r\n . ' '-'-'\\_ /'._.'\r\n \\====:_ \"\"\r\n .' \\\\\r\n : :\r\n / : \\\r\n : . '.\r\n ,. _ : : : :\r\n '-' ). :__:-:__.;--'\r\n ( ' ) '-' '-'\r\n ( - .00. - _\r\n( .' O ) )\r\n'- ()_.\\,\\, -\r\n`\r\n\t//\r\n\tvar swordPic string = `\r\n /\r\nO===[====================-\r\n \\\r\n`\r\n\r\n\tvar shieldPic string = `\r\n\t\\_ _/\r\n\t] --__________-- [\r\n\t| || |\r\n\t\\ || /\r\n\t [ || ]\r\n\t |______||______|\r\n\t |------..------|\r\n\t ] || [\r\n\t \\ || /\r\n\t [ || ]\r\n\t \\ || /\r\n\t [ || ]\r\n\t \\__||__/\r\n\t --\r\n\t`\r\n\tvar winPic string = `\r\n\t __ __ _ _ _ __\r\n\t| | |___ _ _ | | | |___ ___| |\r\n\t|_ _| . | | | | | | | . | |__|\r\n\t |_| |___|___| |_____|___|_|_|__|\r\n\t`\r\n\r\n\tvar losePic string = `\r\n\t __ __ ____ _ _\r\n\t| | |___ _ _ | \\|_|___ _| |\r\n\t|_ _| . | | | | | | | -_| . |\r\n\t |_| |___|___| |____/|_|___|___|\r\n\t`\r\n\tvar tiePic string = `\r\n\t _____ _\r\n\t|_ _|_|___\r\n\t | | | | -_|\r\n\t |_| |_|___|\r\n\t`\r\n\tvar sssPic string = `\r\n\t _____ _\r\n\t| __|_ _ _ ___ ___ _| |\r\n\t|__ | | | | . | _| . |\r\n\t|_____|_____|___|_| |___|\r\n\t _____ _ _ _ _\r\n\t| __| |_|_|___| |_| |\r\n\t|__ | | | -_| | . |\r\n\t|_____|_|_|_|___|_|___|\r\n\t _____ _ _\r\n\t| __|___ ___| | |\r\n\t|__ | . | -_| | |\r\n\t|_____| _|___|_|_|\r\n\t\t|_|\r\n\t`\r\n\tswitch print {\r\n\tcase 1:\r\n\t\tfmt.Printf(\"%s\\n\", pridePic)\r\n\tcase 2:\r\n\t\tfmt.Printf(\"%s\\n\", titlePic)\r\n\tcase 3:\r\n\t\tfmt.Printf(\"%s\\n\", spellPic)\r\n\tcase 4:\r\n\t\tfmt.Printf(\"%s\\n\", swordPic)\r\n\tcase 5:\r\n\t\tfmt.Printf(\"%s\\n\", shieldPic)\r\n\tcase 6:\r\n\t\tfmt.Printf(\"%s\\n\", winPic)\r\n\tcase 7:\r\n\t\tfmt.Printf(\"%s\\n\", losePic)\r\n\tcase 8:\r\n\t\tfmt.Printf(\"%s\\n\", sssPic)\r\n\tcase 9:\r\n\t\tfmt.Printf(\"%s\\n\", tiePic)\r\n\r\n\t}\r\n}", "func main() {\n\tdomTarget := dom.GetWindow().Document().GetElementByID(\"app\")\n\n\tr.Render(container.Container(), domTarget)\n}", "func FullStory(ctx context.Context, client streamexp.ReadMyStoryServiceClient) error {\n\n}", "func getOneStory(id int, c hn.Client, channel chan item, counter int) {\r\n\t// defer wg.Done()\r\n\tvar i item\r\n\t// fmt.Printf(\"getting item %d inside getOneStory number %d\\n\", id, counter)\r\n\thnItem, err := c.GetItem(id)\r\n\tif err != nil {\r\n\t\tfmt.Println(err)\r\n\t\treturn\r\n\t}\r\n\tfmt.Printf(\"parsing item %d\\n\", id)\r\n\ti = parseHNItem(hnItem)\r\n\tif !isStoryLink(i) {\r\n\t\tgoroutine--\r\n\t\t// fmt.Printf(\"returning because item %d is not a story.\\n\", id)\r\n\t\treturn\r\n\t}\r\n\t// fmt.Printf(\"Adding item %d to channel.\\n\", id)\r\n\tchannel <- i\r\n}", "func helpHtmlHandle(w http.ResponseWriter, r *http.Request) {\n\thelpTempl.Execute(w, Params)\n}", "func descriptionContents(shuffledData *ClipJSON) string {\n\tcontents := `\\n\\n` // Start with new line to seperate message at top\n\tcurrentTime := 0\n\n\tfor _, clip := range shuffledData.Clips {\n\t\tcontents += fmt.Sprintf(\"Title: %s\\nVod: %s\\nTime: %s\\n\\n\", clip.Title, clip.Vod.URL, youtubeTimify(currentTime))\n\t\t// Convert clip.Duration to milliseconds, then round in to the nearest millisecond\n\t\tcurrentTime += int(math.Floor(clip.Duration + 0.5))\n\t}\n\n\treturn contents\n}", "func GenerateHTMLReport(totalTestTime, testDate string, testSummary []TestOverview, testSuiteDetails map[string]TestSuiteDetails) {\n\ttotalPassedTests := 0\n\ttotalFailedTests := 0\n\ttotalSkippedTests := 0\n\ttemplates := make([]template.HTML, 0)\n\tfor _, testSuite := range testSuiteDetails {\n\t\ttotalPassedTests = totalPassedTests + testSuite.PassedTests\n\t\ttotalFailedTests = totalFailedTests + testSuite.FailedTests\n\t\ttotalSkippedTests = totalSkippedTests + testSuite.SkippedTests\n\t\t// display testSuiteName\n\t\thtmlString := template.HTML(\"<div type=\\\"button\\\" class=\\\"collapsible\\\">\\n\")\n\t\tpackageInfoTemplateString := template.HTML(\"\")\n\n\t\tpackageInfoTemplateString = \"<div>{{.testsuiteName}}</div>\" + \"\\n\" + \"<div>Run Time: {{.elapsedTime}}m</div> \" + \"\\n\"\n\t\tpackageInfoTemplate, err := template.New(\"packageInfoTemplate\").Parse(string(packageInfoTemplateString))\n\t\tif err != nil {\n\t\t\tlog.Println(\"error parsing package info template\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tvar processedPackageTemplate bytes.Buffer\n\t\terr = packageInfoTemplate.Execute(&processedPackageTemplate, map[string]string{\n\t\t\t\"testsuiteName\": testSuite.TestSuiteName + \"_\" + OS,\n\t\t\t\"elapsedTime\": fmt.Sprintf(\"%.2f\", testSuite.ElapsedTime),\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Println(\"error applying package info template: \", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif testSuite.Status == \"pass\" {\n\t\t\tpackageInfoTemplateString = \"<div class=\\\"collapsibleHeading packageCardLayout successBackgroundColor \\\">\" +\n\t\t\t\ttemplate.HTML(processedPackageTemplate.Bytes()) + \"</div>\"\n\t\t} else if testSuite.Status == \"fail\" {\n\t\t\tpackageInfoTemplateString = \"<div class=\\\"collapsibleHeading packageCardLayout failBackgroundColor \\\">\" +\n\t\t\t\ttemplate.HTML(processedPackageTemplate.Bytes()) + \"</div>\"\n\t\t} else {\n\t\t\tpackageInfoTemplateString = \"<div class=\\\"collapsibleHeading packageCardLayout skipBackgroundColor \\\">\" +\n\t\t\t\ttemplate.HTML(processedPackageTemplate.Bytes()) + \"</div>\"\n\t\t}\n\n\t\thtmlString = htmlString + \"\\n\" + packageInfoTemplateString\n\t\ttestInfoTemplateString := template.HTML(\"\")\n\n\t\t// display testCases\n\t\tfor _, pt := range testSummary {\n\t\t\ttestHTMLTemplateString := template.HTML(\"\")\n\t\t\tif len(pt.TestCases) == 0 {\n\t\t\t\tlog.Println(\"Test run failed for \", pt.TestSuiteName, \"no testcases were executed\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif pt.TestSuiteName == testSuite.TestSuiteName {\n\t\t\t\tif testSuite.FailedTests == 0 {\n\t\t\t\t\ttestHTMLTemplateString = \"<div type=\\\"button\\\" class=\\\"collapsible \\\">\" +\n\t\t\t\t\t\t\"\\n\" + \"<div class=\\\"collapsibleHeading testCardLayout successBackgroundColor \\\">\" +\n\t\t\t\t\t\t\"<div>+ {{.testName}}</div>\" + \"\\n\" + \"<div>{{.elapsedTime}}</div>\" + \"\\n\" +\n\t\t\t\t\t\t\"</div>\" + \"\\n\" +\n\t\t\t\t\t\t\"<div class=\\\"collapsibleHeadingContent\\\">\"\n\t\t\t\t} else if testSuite.FailedTests > 0 {\n\t\t\t\t\ttestHTMLTemplateString = \"<div type=\\\"button\\\" class=\\\"collapsible \\\">\" +\n\t\t\t\t\t\t\"\\n\" + \"<div class=\\\"collapsibleHeading testCardLayout failBackgroundColor \\\">\" +\n\t\t\t\t\t\t\"<div>+ {{.testName}}</div>\" + \"\\n\" + \"<div>{{.elapsedTime}}</div>\" + \"\\n\" +\n\t\t\t\t\t\t\"</div>\" + \"\\n\" +\n\t\t\t\t\t\t\"<div class=\\\"collapsibleHeadingContent\\\">\"\n\t\t\t\t} else if testSuite.SkippedTests > 0 {\n\t\t\t\t\ttestHTMLTemplateString = \"<div type=\\\"button\\\" class=\\\"collapsible \\\">\" +\n\t\t\t\t\t\t\"\\n\" + \"<div class=\\\"collapsibleHeading testCardLayout skipBackgroundColor \\\">\" +\n\t\t\t\t\t\t\"<div>+ {{.testName}}</div>\" + \"\\n\" + \"<div>{{.elapsedTime}}</div>\" + \"\\n\" +\n\t\t\t\t\t\t\"</div>\" + \"\\n\" +\n\t\t\t\t\t\t\"<div class=\\\"collapsibleHeadingContent\\\">\"\n\t\t\t\t}\n\t\t\t\ttestTemplate, err := template.New(\"Test\").Parse(string(testHTMLTemplateString))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"error parsing tests template: \", err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t\tvar processedTestTemplate bytes.Buffer\n\t\t\t\terr = testTemplate.Execute(&processedTestTemplate, map[string]string{\n\t\t\t\t\t\"testName\": \"TestCases\",\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"error applying test template: \", err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\ttestHTMLTemplateString = template.HTML(processedTestTemplate.Bytes())\n\t\t\t\ttestCaseHTMLTemplateString := template.HTML(\"\")\n\n\t\t\t\tfor _, tC := range pt.TestCases {\n\t\t\t\t\ttestCaseHTMLTemplateString = \"<div>{{.testName}}</div>\" + \"\\n\" + \"<div>{{.elapsedTime}}m</div>\"\n\t\t\t\t\ttestCaseTemplate, err := template.New(\"testCase\").Parse(string(testCaseHTMLTemplateString))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Println(\"error parsing test case template: \", err)\n\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t}\n\n\t\t\t\t\tvar processedTestCaseTemplate bytes.Buffer\n\t\t\t\t\terr = testCaseTemplate.Execute(&processedTestCaseTemplate, map[string]string{\n\t\t\t\t\t\t\"testName\": tC.TestCaseName,\n\t\t\t\t\t\t\"elapsedTime\": fmt.Sprintf(\"%f\", tC.ElapsedTime),\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Println(\"error applying test case template: \", err)\n\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t}\n\n\t\t\t\t\tif tC.Status == \"passed\" {\n\t\t\t\t\t\ttestCaseHTMLTemplateString = \"<div class=\\\"testCardLayout successBackgroundColor \\\">\" + template.HTML(processedTestCaseTemplate.Bytes()) + \"</div>\"\n\n\t\t\t\t\t} else if tC.Status == \"failed\" {\n\t\t\t\t\t\ttestCaseHTMLTemplateString = \"<div class=\\\"testCardLayout failBackgroundColor \\\">\" + template.HTML(processedTestCaseTemplate.Bytes()) + \"</div>\"\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttestCaseHTMLTemplateString = \"<div class=\\\"testCardLayout skipBackgroundColor \\\">\" + template.HTML(processedTestCaseTemplate.Bytes()) + \"</div>\"\n\t\t\t\t\t}\n\t\t\t\t\ttestHTMLTemplateString = testHTMLTemplateString + \"\\n\" + testCaseHTMLTemplateString\n\t\t\t\t}\n\t\t\t\ttestHTMLTemplateString = testHTMLTemplateString + \"\\n\" + \"</div>\" + \"\\n\" + \"</div>\"\n\t\t\t\ttestInfoTemplateString = testInfoTemplateString + \"\\n\" + testHTMLTemplateString\n\t\t\t}\n\t\t}\n\t\thtmlString = htmlString + \"\\n\" + \"<div class=\\\"collapsibleHeadingContent\\\">\\n\" + testInfoTemplateString + \"\\n\" + \"</div>\"\n\t\thtmlString = htmlString + \"\\n\" + \"</div>\"\n\t\ttemplates = append(templates, htmlString)\n\t}\n\treportTemplate := template.New(\"report-template.html\")\n\treportTemplateData, err := Asset(\"report-template.html\")\n\tif err != nil {\n\t\tlog.Println(\"error retrieving report-template.html: \", err)\n\t\tos.Exit(1)\n\t}\n\n\treport, err := reportTemplate.Parse(string(reportTemplateData))\n\tif err != nil {\n\t\tlog.Println(\"error parsing report-template.html: \", err)\n\t\tos.Exit(1)\n\t}\n\n\tvar processedTemplate bytes.Buffer\n\ttype templateData struct {\n\t\tHTMLElements []template.HTML\n\t\tFailedTests int\n\t\tPassedTests int\n\t\tSkippedTests int\n\t\tTotalTestTime string\n\t\tTestDate string\n\t}\n\n\terr = report.Execute(&processedTemplate,\n\t\t&templateData{\n\t\t\tHTMLElements: templates,\n\t\t\tFailedTests: totalFailedTests,\n\t\t\tPassedTests: totalPassedTests,\n\t\t\tSkippedTests: totalSkippedTests,\n\t\t\tTotalTestTime: totalTestTime,\n\t\t\tTestDate: testDate,\n\t\t},\n\t)\n\tif err != nil {\n\t\tlog.Println(\"error applying report-template.html: \", err)\n\t\tos.Exit(1)\n\t}\n\thtmlReport = strings.Split(fileName, \".\")[0] + \"_results.html\"\n\tbucketName = strings.Split(htmlReport, \"_\")[0] + \"-results\"\n\tfmt.Println(bucketName)\n\terr = ioutil.WriteFile(htmlReport, processedTemplate.Bytes(), 0644)\n\tif err != nil {\n\t\tlog.Println(\"error writing report.html file: \", err)\n\t\tos.Exit(1)\n\t}\n}", "func outputHTML(w http.ResponseWriter, r *http.Request, filepath string) {\n\tfile, err := os.Open(filepath)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\thttp.ServeContent(w, r, file.Name(), time.Now(), file)\n}", "func generate(p *models.Project) string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(fmt.Sprintf(\"# %s\\n\", p.Name))\n\tplugins := []Plugin{description}\n\tif len(p.Badges) > 0 {\n\t\tplugins = append(plugins, addBadges)\n\t\tfor _, plugin := range plugins {\n\t\t\tplugin(&builder, p)\n\t\t}\n\t}\n\tbuilder.WriteString(fmt.Sprintf(\"### Author\\n\"))\n\tbuilder.WriteString(fmt.Sprintf(\"%s\\n\", p.Author))\n\tbuilder.WriteString(fmt.Sprintf(\"### LICENCE\\n\"))\n\treturn builder.String()\n}", "func handlerPreview(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tvar v = struct {\n\t\tHost string\n\t\tData string\n\t}{\n\t\tr.Host,\n\t\t\"Go ahead, save that markdown file.\",\n\t}\n\n\ttmpl.Execute(w, &v)\n}", "func Idea() string {\n\tresp, err := http.Get(\"http://itsthisforthat.com/api.php?json\")\n\tif err != nil {\n\t\treturn \"I had a problem...\"\n\t}\n\tdefer resp.Body.Close()\n\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\n\tvar concept idea\n\tjson.Unmarshal([]byte(bodyBytes), &concept)\n\treturn \"you should create \" + concept.This + \" for \" + concept.That\n}", "func handlerView(w http.ResponseWriter, r *http.Request, title string) {\r\n\tp2, err := loadPage(title)\r\n\tif err != nil {\r\n\t\t//thiswill redirect the cliebt to the edit page so the content may be created\r\n\t\t//the http.redirect fucntion adds an HTTP status code\r\n\t\t//of fttp.statusFound(302) and a location header to the http response\r\n\t\thttp.Redirect(w, r, \"/edit/\"+title, http.StatusFound)\r\n\t\tfmt.Println(err.Error())\r\n\t\tos.Exit(1)\r\n\t}\r\n\tfetchHTML(w, \"view\", p2)\r\n}", "func TestHandler_OEmbed(t *testing.T) {\n\th := NewTestHandler()\n\tdefer h.Close()\n\n\t// Create the gist in the database.\n\th.DB.Update(func(tx *gist.Tx) error {\n\t\treturn tx.SaveGist(&gist.Gist{ID: \"abc123\", UserID: 1000, Description: \"My Gist\"})\n\t})\n\n\t// Retrieve oEmbed.\n\tu, _ := url.Parse(h.Server.URL + \"/oembed.json\")\n\tu.RawQuery = (&url.Values{\"url\": {\"https://gist.exposed/benbjohnson/abc123\"}}).Encode()\n\tresp, err := http.Get(u.String())\n\tok(t, err)\n\tequals(t, 200, resp.StatusCode)\n\n\thtml, _ := json.Marshal(`<div class=\"gist-exposed\" style=\"position: relative; padding-bottom: 300; padding-top: 0px; height: 0; overflow: hidden;\"><iframe style=\"position: absolute; top:0; left: 0; width: 100%; height: 100%; border: none;\" src=\"https://gist.exposed/benbjohnson/abc123/\"></iframe></div>`)\n\tequals(t, `{\"version\":\"1.0\",\"type\":\"rich\",\"html\":`+string(html)+`,\"height\":300,\"title\":\"My Gist\",\"provider_name\":\"Gist Exposed!\",\"provider_url\":\"https://gist.exposed\"}`+\"\\n\", readall(resp.Body))\n}" ]
[ "0.5904224", "0.578877", "0.56078124", "0.55700314", "0.5567403", "0.554374", "0.5488931", "0.53688914", "0.5325711", "0.532188", "0.526886", "0.5257439", "0.5236609", "0.5176298", "0.5149505", "0.5146099", "0.5114756", "0.5097406", "0.5078993", "0.50427485", "0.50344986", "0.5019498", "0.5019177", "0.49961522", "0.49780497", "0.4975862", "0.4961908", "0.49614975", "0.49591345", "0.49493757", "0.49482626", "0.49473584", "0.49434146", "0.49307263", "0.4920825", "0.48889476", "0.48781717", "0.48753387", "0.48506093", "0.48249647", "0.48221233", "0.4816635", "0.48156294", "0.48145634", "0.4809513", "0.48005748", "0.47956198", "0.4774784", "0.47729695", "0.47700685", "0.47642386", "0.47567058", "0.4751701", "0.4747277", "0.474557", "0.47342852", "0.47337687", "0.47226277", "0.4701286", "0.46990013", "0.46911454", "0.4684466", "0.4681692", "0.46805358", "0.46780446", "0.46705112", "0.46684372", "0.46593276", "0.46550214", "0.463317", "0.46255726", "0.46148714", "0.46144423", "0.46049565", "0.45956522", "0.4586924", "0.4575458", "0.45742297", "0.4574036", "0.456465", "0.45582435", "0.45550835", "0.45504823", "0.4550298", "0.4537013", "0.45340636", "0.45241225", "0.45188797", "0.45117643", "0.45102054", "0.45049828", "0.4500267", "0.44960213", "0.44951433", "0.4484383", "0.44718808", "0.44659087", "0.44651255", "0.44606313", "0.44596946" ]
0.48855904
36
EvaluateEnv evaluates an env with jsonnet.
func EvaluateEnv(a app.App, sourcePath, paramsStr, envName string) (string, error) { libPath, err := a.LibPath(envName) if err != nil { return "", err } vm := jsonnet.NewVM() vm.JPaths = []string{ libPath, filepath.Join(a.Root(), "vendor"), } vm.ExtCode("__ksonnet/params", paramsStr) snippet, err := afero.ReadFile(a.Fs(), sourcePath) if err != nil { return "", err } return vm.EvaluateSnippet(sourcePath, string(snippet)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r RuleDefinition) EvaluateEnv(e map[string]string) bool {\n\t// Compile if needed\n\tif r.rule == nil {\n\t\tif err := r.Compile(); err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn r.rule.Env.Evaluate(e)\n}", "func (getEnvPropertyValueFn) Eval(params ...interface{}) (interface{}, error) {\n\tif getEnvPropertyValueFnLogger.DebugEnabled() {\n\t\tgetEnvPropertyValueFnLogger.Debugf(\"Entering function getEnvPropertyValue (eval) with param: [%+v]\", params[0])\n\t}\n\n\tinputParamValue := params[0]\n\tinputString := \"\"\n\tvar outputValue interface{}\n\tvar err error\n\n\tinputString, err = coerce.ToString(inputParamValue)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to coerece input value to a string. Value = [%+v].\", inputParamValue)\n\t}\n\n\tif getEnvPropertyValueFnLogger.DebugEnabled() {\n\t\tgetEnvPropertyValueFnLogger.Debugf(\"Input Parameter's string length is [%+v].\", len(inputString))\n\t}\n\n\tif len(inputString) <= 0 {\n\t\tgetEnvPropertyValueFnLogger.Debugf(\"Input Parameter is empty or nil. Returning nil.\")\n\t\treturn nil, nil\n\t}\n\n\toutputValue, exists := os.LookupEnv(inputString)\n\tif !exists {\n\t\tif getEnvPropertyValueFnLogger.DebugEnabled() {\n\t\t\tgetEnvPropertyValueFnLogger.Debugf(\"failed to resolve Env Property: '%s', ensure that property is configured in the application\", inputString)\n\t\t}\n\t\treturn nil, nil\n\t}\n\n\tif getEnvPropertyValueFnLogger.DebugEnabled() {\n\t\tgetEnvPropertyValueFnLogger.Debugf(\"Final output value = [%+v]\", outputValue)\n\t}\n\n\tif getEnvPropertyValueFnLogger.DebugEnabled() {\n\t\tgetEnvPropertyValueFnLogger.Debugf(\"Exiting function getEnvPropertyValue (eval)\")\n\t}\n\n\treturn outputValue, nil\n}", "func (rs RuleDefinitions) EvaluateEnv(e map[string]string) bool {\n\tfor _, r := range rs.Rules {\n\t\tif r.EvaluateEnv(e) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func EvalEnv(key string) bool {\n\treturn os.Getenv(key) == \"1\" || os.Getenv(key) == \"true\" || os.Getenv(key) == \"TRUE\"\n}", "func (gf *genericFramework) Env(key, value string) error {\n\tif gf.adam.Variables == nil {\n\t\tgf.adam.Variables = jsonutil.NewVariableMap(\"\", nil)\n\t}\n\tif _, ok := gf.adam.Variables.Get(key); ok {\n\t\treturn fmt.Errorf(\"%v has been defined\", key)\n\t}\n\tgf.adam.Variables.Set(key, jsonutil.NewStringVariable(key, value))\n\treturn nil\n}", "func Eval(input string, env interface{}) (interface{}, error) {\n\tif _, ok := env.(Option); ok {\n\t\treturn nil, fmt.Errorf(\"misused expr.Eval: second argument (env) should be passed without expr.Env\")\n\t}\n\n\ttree, err := parser.Parse(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := compiler.Compile(tree, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toutput, err := vm.Run(program, env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn output, nil\n}", "func (c config) EvalContext(env string, props map[string]interface{}) eval.Context {\n\tp, err := json.Marshal(props)\n\tif err != nil {\n\t\tsio.Warnln(\"unable to serialize env properties to JSON:\", err)\n\t}\n\treturn eval.Context{\n\t\tApp: c.App().Name(),\n\t\tTag: c.App().Tag(),\n\t\tEnv: env,\n\t\tEnvPropsJSON: string(p),\n\t\tDefaultNs: c.App().DefaultNamespace(env),\n\t\tVMConfig: c.vmConfig,\n\t\tVerbose: c.Verbosity() > 1,\n\t\tConcurrency: c.EvalConcurrency(),\n\t\tPostProcessFile: c.App().PostProcessor(),\n\t\tCleanMode: c.cleanEvalMode,\n\t}\n}", "func (e Env) MarshalJSON() ([]byte, error) {\n\tvar b []byte\n\tvar err error\n\tswitch e.Type {\n\tcase EnvValType:\n\t\tb, err = json.Marshal(UnparseEnvVal(*e.Val))\n\tcase EnvFromType:\n\t\tb, err = json.Marshal(e.From)\n\tdefault:\n\t\treturn []byte{}, util.InvalidInstanceError(e.Type)\n\t}\n\n\tif err != nil {\n\t\treturn nil, util.InvalidInstanceErrorf(e, \"couldn't marshal to JSON: %s\", err.Error())\n\t}\n\n\treturn b, nil\n}", "func (s) TestJSONEnvVarSet(t *testing.T) {\n\tconfigJSON := `{\n\t\t\"project_id\": \"fake\"\n\t}`\n\tcleanup, err := createTmpConfigInFileSystem(configJSON)\n\tdefer cleanup()\n\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create config in file system: %v\", err)\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\tdefer cancel()\n\tif err := Start(ctx); err != nil {\n\t\tt.Fatalf(\"error starting observability with valid config through file system: %v\", err)\n\t}\n\tdefer End()\n}", "func (e *ChefEnvironment) UpdateFromJSON(jsonEnv map[string]interface{}) util.Gerror {\n\tif e.Name != jsonEnv[\"name\"].(string) {\n\t\terr := util.Errorf(\"Environment name %s and %s from JSON do not match\", e.Name, jsonEnv[\"name\"].(string))\n\t\treturn err\n\t} else if e.Name == \"_default\" {\n\t\terr := util.Errorf(\"The '_default' environment cannot be modified.\")\n\t\terr.SetStatus(http.StatusMethodNotAllowed)\n\t\treturn err\n\t}\n\n\t/* Validations */\n\tvalidElements := []string{\"name\", \"chef_type\", \"json_class\", \"description\", \"default_attributes\", \"override_attributes\", \"cookbook_versions\"}\nValidElem:\n\tfor k := range jsonEnv {\n\t\tfor _, i := range validElements {\n\t\t\tif k == i {\n\t\t\t\tcontinue ValidElem\n\t\t\t}\n\t\t}\n\t\terr := util.Errorf(\"Invalid key %s in request body\", k)\n\t\treturn err\n\t}\n\n\tvar verr util.Gerror\n\n\tattrs := []string{\"default_attributes\", \"override_attributes\"}\n\tfor _, a := range attrs {\n\t\tjsonEnv[a], verr = util.ValidateAttributes(a, jsonEnv[a])\n\t\tif verr != nil {\n\t\t\treturn verr\n\t\t}\n\t}\n\n\tjsonEnv[\"json_class\"], verr = util.ValidateAsFieldString(jsonEnv[\"json_class\"])\n\tif verr != nil {\n\t\tif verr.Error() == \"Field 'name' nil\" {\n\t\t\tjsonEnv[\"json_class\"] = e.JSONClass\n\t\t} else {\n\t\t\treturn verr\n\t\t}\n\t} else {\n\t\tif jsonEnv[\"json_class\"].(string) != \"Chef::Environment\" {\n\t\t\tverr = util.Errorf(\"Field 'json_class' invalid\")\n\t\t\treturn verr\n\t\t}\n\t}\n\n\tjsonEnv[\"chef_type\"], verr = util.ValidateAsFieldString(jsonEnv[\"chef_type\"])\n\tif verr != nil {\n\t\tif verr.Error() == \"Field 'name' nil\" {\n\t\t\tjsonEnv[\"chef_type\"] = e.ChefType\n\t\t} else {\n\t\t\treturn verr\n\t\t}\n\t} else {\n\t\tif jsonEnv[\"chef_type\"].(string) != \"environment\" {\n\t\t\tverr = util.Errorf(\"Field 'chef_type' invalid\")\n\t\t\treturn verr\n\t\t}\n\t}\n\n\tjsonEnv[\"cookbook_versions\"], verr = util.ValidateAttributes(\"cookbook_versions\", jsonEnv[\"cookbook_versions\"])\n\tif verr != nil {\n\t\treturn verr\n\t}\n\tfor k, v := range jsonEnv[\"cookbook_versions\"].(map[string]interface{}) {\n\t\tif !util.ValidateEnvName(k) || k == \"\" {\n\t\t\tmerr := util.Errorf(\"Cookbook name %s invalid\", k)\n\t\t\tmerr.SetStatus(http.StatusBadRequest)\n\t\t\treturn merr\n\t\t}\n\n\t\tif v == nil {\n\t\t\tverr = util.Errorf(\"Invalid version number\")\n\t\t\treturn verr\n\t\t}\n\t\t_, verr = util.ValidateAsConstraint(v)\n\t\tif verr != nil {\n\t\t\t/* try validating as a version */\n\t\t\tv, verr = util.ValidateAsVersion(v)\n\t\t\tif verr != nil {\n\t\t\t\treturn verr\n\t\t\t}\n\t\t}\n\t}\n\n\tjsonEnv[\"description\"], verr = util.ValidateAsString(jsonEnv[\"description\"])\n\tif verr != nil {\n\t\tif verr.Error() == \"Field 'name' missing\" {\n\t\t\tjsonEnv[\"description\"] = \"\"\n\t\t} else {\n\t\t\treturn verr\n\t\t}\n\t}\n\n\te.ChefType = jsonEnv[\"chef_type\"].(string)\n\te.JSONClass = jsonEnv[\"json_class\"].(string)\n\te.Description = jsonEnv[\"description\"].(string)\n\te.Default = jsonEnv[\"default_attributes\"].(map[string]interface{})\n\te.Override = jsonEnv[\"override_attributes\"].(map[string]interface{})\n\t/* clear out, then loop over the cookbook versions */\n\te.CookbookVersions = make(map[string]string, len(jsonEnv[\"cookbook_versions\"].(map[string]interface{})))\n\tfor c, v := range jsonEnv[\"cookbook_versions\"].(map[string]interface{}) {\n\t\te.CookbookVersions[c] = v.(string)\n\t}\n\n\treturn nil\n}", "func Test(w http.ResponseWriter, r *http.Request) {\n\tres, err := json.Marshal(EnvVariablesModel{Vars: os.Environ(), A: \"b\", C: 123})\n\tif 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}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(res)\n}", "func (t envTemplate) Env(secrets map[string]string, sr tpl.SecretReader) (map[string]string, error) {\n\tresult := make(map[string]string)\n\tfor _, tpls := range t.envVars {\n\t\tkey, err := tpls.key.Evaluate(t.templateVarReader, secretReaderNotAllowed{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\terr = validation.ValidateEnvarName(key)\n\t\tif err != nil {\n\t\t\treturn nil, templateError(tpls.lineNo, err)\n\t\t}\n\n\t\tvalue, err := tpls.value.Evaluate(t.templateVarReader, sr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tresult[key] = value\n\t}\n\treturn result, nil\n}", "func Env(env string) (value []byte, err error) {\n\tvalue, err = exec.Command(\"go\", \"env\", env).Output()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvalue = bytes.TrimSpace(value)\n\n\tif len(value) == 0 {\n\t\terr = ErrEmptyEnv{env}\n\t}\n\n\treturn\n}", "func InitEnv() error {\n\tfile, err := ioutil.ReadFile(envPath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif errMarsh := codec.DecJson(file, &env); errMarsh != nil {\n\t\treturn fmt.Errorf(\"failed to parse %s. decode error: %v\", string(file), err)\n\t}\n\n\treturn nil\n}", "func LoadFromEnv(v interface{}, prefix string) (result []MarshalledEnvironmentVar) {\n\tpointerValue := reflect.ValueOf(v)\n\tstructValue := pointerValue.Elem()\n\tstructType := structValue.Type()\n\n\tfor i := 0; i < structValue.NumField(); i++ {\n\t\tstructField := structType.Field(i)\n\t\tfieldValue := structValue.Field(i)\n\n\t\tif fieldValue.CanSet() {\n\t\t\tenvKey := strings.ToUpper(prefix) + gocase.ToUpperSnake(structField.Name)\n\t\t\tenvVal := os.Getenv(envKey)\n\n\t\t\tif envVal != \"\" {\n\t\t\t\t// create a json blob with the env data\n\t\t\t\tjsonStr := \"\"\n\t\t\t\tif fieldValue.Kind() == reflect.String {\n\t\t\t\t\tjsonStr = fmt.Sprintf(`{\"%s\": \"%s\"}`, structField.Name, envVal)\n\t\t\t\t} else {\n\t\t\t\t\tjsonStr = fmt.Sprintf(`{\"%s\": %s}`, structField.Name, envVal)\n\t\t\t\t}\n\n\t\t\t\terr := json.Unmarshal([]byte(jsonStr), v)\n\t\t\t\tresult = append(result, MarshalledEnvironmentVar{envKey, envVal, structField.Name, err})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func (e *Env) UnmarshalJSON(value []byte) error {\n\tvar s string\n\terr := json.Unmarshal(value, &s)\n\tif err == nil {\n\t\tenvVal := ParseEnvVal(s)\n\t\te.SetVal(*envVal)\n\t\treturn nil\n\t}\n\n\tfrom := EnvFrom{}\n\terr = json.Unmarshal(value, &from)\n\tif err == nil {\n\t\te.SetFrom(from)\n\t\treturn nil\n\t}\n\n\treturn util.InvalidInstanceErrorf(e, \"couldn't parse from (%s)\", string(value))\n}", "func NewEnvironment(jsonData string) (*Environment, error) {\n\t// initialize env with input data\n\tenv := new(Environment)\n\terr := serialize.CopyFromJSON(jsonData, env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn env, nil\n}", "func (value *Env) Eval(ctx context.Context, env *Env, cont Cont) ReadyCont {\n\treturn cont.Call(value, nil)\n}", "func LoadTestEnv() *core.Engine {\n\tengine := new(core.Engine)\n\n\t_, dir, _, _ := runtime.Caller(0)\n\tconfigJSON := filepath.Join(filepath.Dir(dir), \"../..\", \"env\", \"tdd.json\")\n\n\tjsonFile, err := os.Open(configJSON)\n\n\tif err != nil {\n\t\tlog.Fatalln(err, \"can't open the config file\", dir+\"/regularenvs.json\")\n\t}\n\n\tdefer jsonFile.Close()\n\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\n\terr = json.Unmarshal(byteValue, &engine.Env)\n\tif err != nil {\n\t\tlog.Fatalln(err, \"error in unmarshal JSON\")\n\t}\n\n\tif engine.Env.MachineID, err = machineid.ProtectedID(\"SigmaMono\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn engine\n}", "func NewFromJSON(jsonEnv map[string]interface{}) (*ChefEnvironment, util.Gerror) {\n\tenv, err := New(jsonEnv[\"name\"].(string))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = env.UpdateFromJSON(jsonEnv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn env, nil\n}", "func (cx *Context) Eval(source string, result interface{}) (err error) {\n\tcx.do(func(ptr *C.JSAPIContext) {\n\t\t// alloc C-string\n\t\tcsource := C.CString(source)\n\t\tdefer C.free(unsafe.Pointer(csource))\n\t\tvar jsonData *C.char\n\t\tvar jsonLen C.int\n\t\tfilename := \"eval\"\n\t\tcfilename := C.CString(filename)\n\t\tdefer C.free(unsafe.Pointer(cfilename))\n\t\t// eval\n\t\tif C.JSAPI_EvalJSON(ptr, csource, cfilename, &jsonData, &jsonLen) != C.JSAPI_OK {\n\t\t\terr = cx.getError(filename)\n\t\t\treturn\n\t\t}\n\t\tdefer C.free(unsafe.Pointer(jsonData))\n\t\t// convert to go\n\t\tb := []byte(C.GoStringN(jsonData, jsonLen))\n\t\tif raw, ok := result.(*Raw); ok {\n\t\t\t*raw = Raw(string(b))\n\t\t} else {\n\t\t\terr = json.Unmarshal(b, result)\n\t\t}\n\t})\n\treturn err\n}", "func (o BuildRunStatusBuildSpecRuntimeOutput) Env() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v BuildRunStatusBuildSpecRuntime) map[string]string { return v.Env }).(pulumi.StringMapOutput)\n}", "func (o BuildSpecRuntimeOutput) Env() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v BuildSpecRuntime) map[string]string { return v.Env }).(pulumi.StringMapOutput)\n}", "func ReadEnv(c interface{}) {\r\n\tfor _, value := range os.Environ() {\r\n\t\tif strings.HasPrefix(value, \"ENV_\") {\r\n\t\t\tkv := strings.SplitN(value,\"=\",2)\r\n\t\t\tkv[0] = strings.ToLower(strings.Replace(kv[0],\"_\",\".\",-1))[4:]\r\n\t\t\tSetData(c,strings.Join(kv,\"=\"))\r\n\t\t}\r\n\t}\r\n}", "func buildEnvironment(env []string) (map[string]string, error) {\n result := make(map[string]string, len(env))\n for _, s := range env {\n // if value is empty, s is like \"K=\", not \"K\".\n if !strings.Contains(s, \"=\") {\n return result, errors.Errorf(\"unexpected environment %q\", s)\n }\n kv := strings.SplitN(s, \"=\", 2)\n result[kv[0]] = kv[1]\n }\n return result, nil\n}", "func (o StorageClusterSpecNodesOutput) Env() StorageClusterSpecNodesEnvArrayOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecNodes) []StorageClusterSpecNodesEnv { return v.Env }).(StorageClusterSpecNodesEnvArrayOutput)\n}", "func LoadEnvironment(object interface{}, metaDataKey string) error {\n\tvar values = func(key string) (string, bool) {\n\t\treturn os.LookupEnv(key)\n\t}\n\treturn commonLoad(values, object, metaDataKey)\n}", "func (b *taskBuilder) env(key, value string) {\n\tif b.Spec.Environment == nil {\n\t\tb.Spec.Environment = map[string]string{}\n\t}\n\tb.Spec.Environment[key] = value\n}", "func GetENV(experimentDetails *experimentTypes.ExperimentDetails) {\n\texperimentDetails.ExperimentName = Getenv(\"EXPERIMENT_NAME\", \"\")\n\texperimentDetails.AppNS = Getenv(\"APP_NS\", \"\")\n\texperimentDetails.TargetContainer = Getenv(\"APP_CONTAINER\", \"\")\n\texperimentDetails.TargetPods = Getenv(\"APP_POD\", \"\")\n\texperimentDetails.AppLabel = Getenv(\"APP_LABEL\", \"\")\n\texperimentDetails.ChaosDuration, _ = strconv.Atoi(Getenv(\"TOTAL_CHAOS_DURATION\", \"30\"))\n\texperimentDetails.ChaosNamespace = Getenv(\"CHAOS_NAMESPACE\", \"litmus\")\n\texperimentDetails.EngineName = Getenv(\"CHAOS_ENGINE\", \"\")\n\texperimentDetails.ChaosUID = clientTypes.UID(Getenv(\"CHAOS_UID\", \"\"))\n\texperimentDetails.ChaosPodName = Getenv(\"POD_NAME\", \"\")\n\texperimentDetails.ContainerRuntime = Getenv(\"CONTAINER_RUNTIME\", \"\")\n\texperimentDetails.NetworkInterface = Getenv(\"NETWORK_INTERFACE\", \"eth0\")\n\texperimentDetails.TargetIPs = Getenv(\"TARGET_IPs\", \"\")\n}", "func requireEnv(envVar string) string {\n\tval, _ := getEnv(envVar, true)\n\treturn val\n}", "func NewEnv(loader *ScriptLoader, debugging bool) *Env {\n\tenv := &Env{\n\t\tvm: otto.New(),\n\t\tloader: loader,\n\t\tdebugging: debugging,\n\t\tbuiltinModules: make(map[string]otto.Value),\n\t\tbuiltinModuleFactories: make(map[string]BuiltinModuleFactory),\n\t}\n\tenv.vm.Set(\"__getModulePath\", func(call otto.FunctionCall) otto.Value {\n\t\tvm := call.Otto\n\t\tvar cwd, moduleID string\n\t\tvar err error\n\t\tif cwd, err = call.Argument(0).ToString(); err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__getModulePath error\", err.Error()))\n\t\t}\n\t\tif moduleID, err = call.Argument(1).ToString(); err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__getModulePath error\", err.Error()))\n\t\t}\n\t\tif _, found := env.builtinModules[moduleID]; found {\n\t\t\tret, _ := otto.ToValue(moduleID)\n\t\t\treturn ret\n\t\t}\n\t\tif _, found := env.builtinModuleFactories[moduleID]; found {\n\t\t\tret, _ := otto.ToValue(moduleID)\n\t\t\treturn ret\n\t\t}\n\t\tif ap, err := env.loader.GetModuleAbs(cwd, moduleID); err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__getModulePath error\", err.Error()))\n\t\t} else {\n\t\t\tret, _ := otto.ToValue(ap)\n\t\t\treturn ret\n\t\t}\n\t})\n\tvar requireSrc string\n\tif env.debugging {\n\t\trequireSrc = debugRequireSrc\n\t} else {\n\t\trequireSrc = releaseRequireSrc\n\t}\n\tenv.vm.Set(\"__loadSource\", func(call otto.FunctionCall) otto.Value {\n\t\tvar mp string\n\t\tvar err error\n\t\tvm := call.Otto\n\t\t// reading arguments\n\t\tif mp, err = call.Argument(0).ToString(); err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__loadSource error\", err.Error()))\n\t\t}\n\t\t// finding built builtin modules\n\t\tif mod, found := env.builtinModules[mp]; found {\n\t\t\tretObj, _ := vm.Object(\"({isBuiltin: true})\")\n\t\t\tretObj.Set(\"builtin\", mod)\n\t\t\treturn retObj.Value()\n\t\t}\n\t\t// finding unbuilt builtin modules\n\t\tif mf, found := env.builtinModuleFactories[mp]; found {\n\t\t\tretObj, _ := vm.Object(\"({isBuiltin: true})\")\n\t\t\tmod := mf.CreateModule(vm)\n\t\t\tretObj.Set(\"builtin\", mod)\n\t\t\tenv.builtinModules[mp] = mod\n\t\t\treturn retObj.Value()\n\t\t}\n\t\t// loading module on file system\n\t\tsrc, err := env.loader.LoadScript(mp)\n\t\tif err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__loadSource error\", err.Error()))\n\t\t}\n\t\tscript, err := vm.Compile(mp, src)\n\t\tif err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__loadSource error\", err.Error()))\n\t\t}\n\t\tmodValue, err := vm.Run(script)\n\t\tif err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__loadSource error\", err.Error()))\n\t\t}\n\t\tretObj, _ := vm.Object(\"({})\")\n\t\tretObj.Set(\"src\", modValue)\n\t\tretObj.Set(\"filename\", path.Base(mp))\n\t\tretObj.Set(\"dirname\", path.Dir(mp))\n\t\treturn retObj.Value()\n\t})\n\t_, err := env.vm.Run(requireSrc)\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase *otto.Error:\n\t\t\tpanic(err.(otto.Error).String())\n\t\tdefault:\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn env\n}", "func (job *Job) DecodeEnv(src io.Reader) error {\n\treturn job.Env.Decode(src)\n}", "func SyncEnvVar(env interface{}) {\n\tbs, err := json.Marshal(&env)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tenvVar := map[string]string{}\n\terr = json.Unmarshal(bs, &envVar)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tviper.AutomaticEnv()\n\tfor k := range envVar {\n\t\tval := viper.GetString(k)\n\t\tif val != \"\" {\n\t\t\tenvVar[k] = val\n\t\t}\n\t}\n\n\tbs, err = json.Marshal(envVar)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = json.Unmarshal(bs, &env)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func envFun(args ...object.Object) object.Object {\n\n\tenv := os.Environ()\n\tnewHash := make(map[object.HashKey]object.HashPair)\n\n\t//\n\t// If we get a match then the output is an array\n\t// First entry is the match, any additional parts\n\t// are the capture-groups.\n\t//\n\tfor i := 1; i < len(env); i++ {\n\n\t\t// Capture groups start at index 0.\n\t\tk := &object.String{Value: env[i]}\n\t\tv := &object.String{Value: os.Getenv(env[i])}\n\n\t\tnewHashPair := object.HashPair{Key: k, Value: v}\n\t\tnewHash[k.HashKey()] = newHashPair\n\t}\n\n\treturn &object.Hash{Pairs: newHash}\n}", "func LookupEnv(key string) (string, bool)", "func Env(env Environ) func(*Runner) error {\n\treturn func(r *Runner) error {\n\t\tif env == nil {\n\t\t\tenv, _ = EnvFromList(os.Environ())\n\t\t}\n\t\tr.Env = env\n\t\treturn nil\n\t}\n}", "func (e *execution) parseEnvInputs() []apiv1.EnvVar {\n\tvar data []apiv1.EnvVar\n\n\tfor _, val := range e.envInputs {\n\t\ttmp := apiv1.EnvVar{Name: val.Name, Value: val.Value}\n\t\tdata = append(data, tmp)\n\t}\n\n\treturn data\n}", "func (o BuildRunStatusBuildSpecRuntimePtrOutput) Env() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *BuildRunStatusBuildSpecRuntime) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Env\n\t}).(pulumi.StringMapOutput)\n}", "func setEnv(d interface{}) {\n\tVCAP := os.Getenv(\"VCAP_SERVICES\")\n\tif VCAP == \"\" {\n\t\treturn // no environment found so use whatever DBURL is set to\n\t}\n\tb := []byte(VCAP)\n\terr := json.Unmarshal(b, d) \n\tif err != nil {\n\t\tfmt.Printf(\"dbhandler:setEnv:ERROR:%s\", err)\n\t}\n}", "func Getenv(key string) string", "func Eval(t testing.TestingT, options *EvalOptions, jsonFilePaths []string, resultQuery string) {\n\trequire.NoError(t, EvalE(t, options, jsonFilePaths, resultQuery))\n}", "func importEnv(e []string) *phpv.ZHashTable {\n\tzt := phpv.NewHashTable()\n\n\tfor _, s := range e {\n\t\tp := strings.IndexByte(s, '=')\n\t\tif p != -1 {\n\t\t\tzt.SetString(phpv.ZString(s[:p]), phpv.ZString(s[p+1:]).ZVal())\n\t\t}\n\t}\n\n\treturn zt\n}", "func (om *OpenMock) ParseEnv() {\n\terr := env.Parse(om)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func parseEnv(envs []string) map[string]string {\n\tout := make(map[string]string)\n\tfor _, v := range envs {\n\t\tp := strings.SplitN(v, \"=\", 2)\n\t\tout[p[0]] = p[1]\n\t}\n\treturn out\n}", "func RenderWithEnv(s string, ext map[string]string) string {\n\tmatches := regexpEnvironmentVar.FindAllString(s, -1)\n\tfor _, match := range matches {\n\t\tkey := match[1:]\n\t\tval := ext[key]\n\t\tif val == \"\" {\n\t\t\tval = os.Getenv(key)\n\t\t}\n\t\tif val != \"\" {\n\t\t\ts = strings.ReplaceAll(s, match, val)\n\t\t}\n\t}\n\treturn s\n}", "func AccessTokensFromEnvJSON(env string) []string {\n\taccessTokens := []string{}\n\tif len(env) == 0 {\n\t\treturn accessTokens\n\t}\n\terr := json.Unmarshal([]byte(env), &accessTokens)\n\tif err != nil {\n\t\tlog.Entry().Infof(\"Token json '%v' has wrong format.\", env)\n\t}\n\treturn accessTokens\n}", "func GetEnv(en []map[string]string, key string) string {\n\ts := \"\"\n\tfor _, e := range en {\n\t\tif v, ok := e[key]; ok {\n\t\t\ts = v\n\t\t}\n\t}\n\treturn s\n}", "func (hc ApplicationsController) EnvSet(w http.ResponseWriter, r *http.Request) APIErrors {\n\tctx := r.Context()\n\tlog := tracelog.Logger(ctx)\n\n\tparams := httprouter.ParamsFromContext(ctx)\n\torgName := params.ByName(\"org\")\n\tappName := params.ByName(\"app\")\n\n\tlog.Info(\"processing environment variable assignment\",\n\t\t\"org\", orgName, \"app\", appName)\n\n\tcluster, err := kubernetes.GetCluster(ctx)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\texists, err := organizations.Exists(ctx, cluster, orgName)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\tif !exists {\n\t\treturn OrgIsNotKnown(orgName)\n\t}\n\n\tapp := models.NewAppRef(appName, orgName)\n\n\texists, err = application.Exists(ctx, cluster, app)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\tif !exists {\n\t\treturn AppIsNotKnown(appName)\n\t}\n\n\tdefer r.Body.Close()\n\tbodyBytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\tvar setRequest models.EnvVariableList\n\terr = json.Unmarshal(bodyBytes, &setRequest)\n\tif err != nil {\n\t\treturn BadRequest(err)\n\t}\n\n\terr = application.EnvironmentSet(ctx, cluster, app, setRequest)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\treturn nil\n}", "func assertEnv(ctx context.Context, client client.Client, spec corev1.PodSpec, component, container, key, expectedValue string) error {\n\tvalue, err := getEnv(ctx, client, spec, component, container, key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif value != nil && strings.ToLower(*value) != expectedValue {\n\t\treturn ErrIncompatibleCluster{\n\t\t\terr: fmt.Sprintf(\"%s=%s is not supported\", key, *value),\n\t\t\tcomponent: component,\n\t\t\tfix: fmt.Sprintf(\"remove the %s env var or set it to '%s'\", key, expectedValue),\n\t\t}\n\t}\n\n\treturn nil\n}", "func env(key string, fallback string) string {\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\treturn fallback\n}", "func ExpandEnv(env map[string]string, otherEnv map[string]string) map[string]string {\n\tresult := make(map[string]string)\n\n\tfor k, v := range env {\n\t\texpandV := os.Expand(v, func (key string) string { return otherEnv[key] })\n\t\tresult[k] = expandV\n\t}\n\n\treturn result\n}", "func Env(def, key string, fallbacks ...string) string {\n\tif val, found := LookupEnv(key, fallbacks...); found {\n\t\treturn val\n\t}\n\treturn def\n}", "func TestEnvironmentGet(t *testing.T) {\n\tport := make(chan int, 1)\n\tdefer createTestServer(port, t).Close()\n\taddr := <-port\n\tresp, err := http.Get(fmt.Sprintf(\"http://localhost:%d/env/get\", addr))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\tbodyContent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif string(bodyContent) != \"Testing env.set function\" {\n\t\tt.Fatalf(\"Wrong env.get value. Expected 'Testing env.set function' but got '%s'\", string(bodyContent))\n\t}\n}", "func readEnviromentFile() *ServerEnv {\n\tvar serverEnv ServerEnv\n\tjsonFile, err := os.Open(\"dist/env.json\")\n\tif err != nil {\n\t\tfmt.Printf(\":0 PANIK , enviroment json not attempting local dir found\")\n\t\tjsonFile, err = os.Open(\"env.json\")\n\t\tif err != nil {\n\t\t\tpanic(\":0 PANIK , enviroment json not found\")\n\t\t}\n\t}\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\terr = json.Unmarshal(byteValue, &serverEnv)\n\tif err != nil {\n\t\tpanic(\":0 PANIK , enviroment json could not decode\")\n\t}\n\treturn &serverEnv\n}", "func (v LiteralValue) Eval(*Environment) (document.Value, error) {\n\treturn document.Value(v), nil\n}", "func getEnvFun(args ...object.Object) object.Object {\n\tif len(args) != 1 {\n\t\treturn newError(\"wrong number of arguments. got=%d, want=1\",\n\t\t\tlen(args))\n\t}\n\tif args[0].Type() != object.STRING_OBJ {\n\t\treturn newError(\"argument must be a string, got=%s\",\n\t\t\targs[0].Type())\n\t}\n\tinput := args[0].(*object.String).Value\n\treturn &object.String{Value: os.Getenv(input)}\n\n}", "func assertJSON(e *ptesting.Environment, out string, respObj interface{}) {\n\terr := json.Unmarshal([]byte(out), &respObj)\n\tif err != nil {\n\t\te.Errorf(\"unable to unmarshal %v\", out)\n\t}\n}", "func environ(envVars []*apiclient.EnvEntry) []string {\n\tvar environ []string\n\tfor _, item := range envVars {\n\t\tif item != nil && item.Name != \"\" && item.Value != \"\" {\n\t\t\tenviron = append(environ, fmt.Sprintf(\"%s=%s\", item.Name, item.Value))\n\t\t}\n\t}\n\treturn environ\n}", "func (ci MrbCallInfo) Env() REnv {\n\treturn REnv{C.mrb_vm_ci_env(ci.p), nil}\n}", "func Evaluate(expr string, contextVars map[string]logol.Match) bool {\n\tlogger.Debugf(\"Evaluate expression: %s\", expr)\n\n\tre := regexp.MustCompile(\"[$@#]+\\\\w+\")\n\tres := re.FindAllString(expr, -1)\n\t// msg, _ := json.Marshal(contextVars)\n\t// logger.Errorf(\"CONTEXT: %s\", msg)\n\tparameters := make(map[string]interface{}, 8)\n\tvarIndex := 0\n\tfor _, val := range res {\n\t\tt := strconv.Itoa(varIndex)\n\t\tvarName := \"VAR\" + t\n\t\tr := strings.NewReplacer(val, varName)\n\t\texpr = r.Replace(expr)\n\t\tvarIndex++\n\t\tcValue, cerr := getValueFromExpression(val, contextVars)\n\t\tif cerr {\n\t\t\tlogger.Debugf(\"Failed to get value from expression %s\", val)\n\t\t\treturn false\n\t\t}\n\t\tparameters[varName] = cValue\n\t}\n\tlogger.Debugf(\"New expr: %s with params %v\", expr, parameters)\n\n\texpression, err := govaluate.NewEvaluableExpression(expr)\n\tif err != nil {\n\t\tlogger.Errorf(\"Failed to evaluate expression %s\", expr)\n\t\treturn false\n\t}\n\tresult, _ := expression.Evaluate(parameters)\n\tif result == true {\n\t\treturn true\n\t}\n\treturn false\n}", "func (b *Executable) Env(arg, value string) *Executable {\n\tif b.Environment == nil {\n\t\tb.Environment = make(map[string]string)\n\t}\n\tb.Environment[arg] = value\n\treturn b\n}", "func parseEnv(name, defval string, parsefn func(string) error) {\n\tif envval := os.Getenv(name); envval != \"\" {\n\t\terr := parsefn(envval)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\tlog.Error(\"invalid environment %s=%q: %v, using default %q\", name, envval, err, defval)\n\t}\n\tif err := parsefn(defval); err != nil {\n\t\tlog.Error(\"invalid default %s=%q: %v\", name, defval, err)\n\t}\n}", "func evaluateENVBool(envVar string, defaultValue bool) bool {\n\tenvValue, isSet := os.LookupEnv(envVar)\n\n\tif isSet {\n\n\t\tswitch strings.ToLower(envValue) {\n\n\t\tcase \"false\", \"0\", \"no\", \"n\", \"f\":\n\t\t\tlog.Infof(\"%s is %t through environment variable\", envVar, false)\n\t\t\treturn false\n\t\t}\n\t\tlog.Infof(\"%s is %t through environment variable\", envVar, true)\n\t\treturn true\n\t}\n\tlog.Infof(\"%s is %t (defaulted) through environment variable\", envVar, defaultValue)\n\treturn defaultValue\n}", "func (c *Cli) ParseEnv() error {\n\tvar (\n\t\terr error\n\t\tu64 uint64\n\t)\n\tfor k, e := range c.env {\n\t\ts := strings.TrimSpace(os.Getenv(k))\n\t\t// NOTE: we only parse the environment if it is not an emprt string\n\t\tif s != \"\" {\n\t\t\tswitch e.Type {\n\t\t\tcase \"bool\":\n\t\t\t\te.BoolValue, err = strconv.ParseBool(s)\n\t\t\tcase \"int\":\n\t\t\t\te.IntValue, err = strconv.Atoi(s)\n\t\t\tcase \"int64\":\n\t\t\t\te.Int64Value, err = strconv.ParseInt(s, 10, 64)\n\t\t\tcase \"uint\":\n\t\t\t\tu64, err = strconv.ParseUint(s, 10, 32)\n\t\t\t\te.UintValue = uint(u64)\n\t\t\tcase \"uint64\":\n\t\t\t\te.Uint64Value, err = strconv.ParseUint(s, 10, 64)\n\t\t\tcase \"float64\":\n\t\t\t\te.Float64Value, err = strconv.ParseFloat(s, 64)\n\t\t\tcase \"time.Duration\":\n\t\t\t\te.DurationValue, err = time.ParseDuration(s)\n\t\t\tdefault:\n\t\t\t\te.StringValue = s\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%q should be type %q, %s\", e.Name, e.Type, err)\n\t\t\t}\n\t\t}\n\t\tc.env[k] = e\n\t}\n\treturn err\n}", "func addEnv(s *scope, arg pyObject, target *core.BuildTarget) {\n\tenvPy, ok := asDict(arg)\n\ts.Assert(ok, \"env must be a dict\")\n\n\tenv := make(map[string]string, len(envPy))\n\tfor name, val := range envPy {\n\t\tv, ok := val.(pyString)\n\t\ts.Assert(ok, \"Values of env must be strings, found %v at key %v\", val.Type(), name)\n\t\tenv[name] = string(v)\n\t}\n\n\ttarget.Env = env\n}", "func env() error {\n\t// regexp for TF_VAR_ terraform vars\n\ttfVar := regexp.MustCompile(`^TF_VAR_.*$`)\n\n\t// match terraform vars in environment\n\tfor _, e := range os.Environ() {\n\t\t// split on value\n\t\tpair := strings.SplitN(e, \"=\", 2)\n\n\t\t// match on TF_VAR_*\n\t\tif tfVar.MatchString(pair[0]) {\n\t\t\t// pull out the name\n\t\t\tname := strings.Split(pair[0], \"TF_VAR_\")\n\n\t\t\t// lower case the terraform variable\n\t\t\t// to accommodate cicd injection capitalization\n\t\t\terr := os.Setenv(fmt.Sprintf(\"TF_VAR_%s\",\n\t\t\t\tstrings.ToLower(name[1])), pair[1])\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}", "func validateEnv(vars []corev1.EnvVar, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i, ev := range vars {\n\t\tidxPath := fldPath.Index(i)\n\t\tif len(ev.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"name\"), \"\"))\n\t\t} else {\n\t\t\tfor _, msg := range validation.IsEnvVarName(ev.Name) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"name\"), ev.Name, msg))\n\t\t\t}\n\t\t}\n\t\tallErrs = append(allErrs, validateEnvVarValueFrom(ev, idxPath.Child(\"valueFrom\"))...)\n\t}\n\treturn allErrs\n}", "func UnmarshalFromEnv(c interface{}) {\n\ttopType := reflect.TypeOf(c).Elem()\n\ttopValue := reflect.ValueOf(c)\n\tfor i := 0; i < topType.NumField(); i++ {\n\t\tfield := topType.Field(i)\n\t\tif field.Tag.Get(\"env\") != \"\" {\n\t\t\tenvVar := os.Getenv(field.Tag.Get(\"env\"))\n\t\t\tif envVar == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch field.Type.Kind() {\n\t\t\tcase reflect.Bool:\n\t\t\t\tb, err := strconv.ParseBool(envVar)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"didn't set from \", field.Tag.Get(\"env\"), \" due to \", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tf := topValue.Elem().Field(i)\n\t\t\t\tf.SetBool(b)\n\t\t\tcase reflect.Int64:\n\t\t\t\tinteger, err := strconv.ParseInt(envVar, 0, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"didn't set from \", field.Tag.Get(\"env\"), \" due to \", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tf := topValue.Elem().Field(i)\n\t\t\t\tf.SetInt(integer)\n\t\t\tcase reflect.String:\n\t\t\t\tf := topValue.Elem().Field(i)\n\t\t\t\tf.SetString(envVar)\n\t\t\tcase reflect.Float64:\n\t\t\t\tfloat, err := strconv.ParseFloat(envVar, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"didn't set from \", field.Tag.Get(\"env\"), \" due to \", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tf := topValue.Elem().Field(i)\n\t\t\t\tf.SetFloat(float)\n\t\t\t}\n\t\t}\n\t}\n}", "func env(key string, defaultValue string) string {\n\tif value, exists := os.LookupEnv(key); exists {\n\t\treturn value\n\t}\n\treturn defaultValue\n}", "func NewJsonEnvironment() *JsonEnvironment {\n\tthis := JsonEnvironment{}\n\treturn &this\n}", "func RunJSONSerializationTestForHostingEnvironmentProfile(subject HostingEnvironmentProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual HostingEnvironmentProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func MatchEnv(k string) bool {\n\n\tkey := strings.TrimPrefix(k, \"/\")\n\tkeyEnv := strings.Split(key, \"/\")\n\tif len(keyEnv) > 3 {\n\t\tif (keyEnv[2] == os.Getenv(\"VINE_ENV\")) && (keyEnv[3] == \"routes\") {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (p RProc) Env() REnv {\n\tif !p.HasEnv() {\n\t\treturn REnv{nil, p.mrb}\n\t}\n\treturn REnv{C._MRB_PROC_ENV(p.p), p.mrb}\n}", "func parseIPEnvironment(envName, envValue string, version int) string {\n\t// To parse the environment (which could be an IP or a CIDR), convert\n\t// to a JSON string and use the UnmarshalJSON method on the IPNet\n\t// struct to parse the value.\n\tip := &cnet.IPNet{}\n\terr := ip.UnmarshalJSON([]byte(\"\\\"\" + envValue + \"\\\"\"))\n\tif err != nil || ip.Version() != version {\n\t\tlog.Warnf(\"Environment does not contain a valid IPv%d address: %s=%s\", version, envName, envValue)\n\t\tutils.Terminate()\n\t}\n\tlog.Infof(\"Using IPv%d address from environment: %s=%s\", ip.Version(), envName, envValue)\n\n\treturn ip.String()\n}", "func standardEnv() map[string]interface{} {\r\n env := make(map[string]interface{}, 0)\r\n env[\"false\"] = false\r\n env[\"true\"] = true\r\n env[\"+\"] = func(args []interface{}) interface{} {\r\n\tn, ok1 := args[0].(int)\r\n\tm, ok2 := args[1].(int)\r\n\tif !ok1 || !ok2 {\r\n\t panic(\"+ needs numbers\")\r\n\t}\r\n\treturn n + m\r\n }\r\n return env\r\n}", "func (b *builtinValuesJSONSig) evalJSON(_ chunk.Row) (types.BinaryJSON, bool, error) {\n\trow := b.ctx.GetSessionVars().CurrInsertValues\n\tif row.IsEmpty() {\n\t\treturn types.BinaryJSON{}, true, nil\n\t}\n\tif b.offset < row.Len() {\n\t\tif row.IsNull(b.offset) {\n\t\t\treturn types.BinaryJSON{}, true, nil\n\t\t}\n\t\treturn row.GetJSON(b.offset), false, nil\n\t}\n\treturn types.BinaryJSON{}, true, errors.Errorf(\"Session current insert values len %d and column's offset %v don't match\", row.Len(), b.offset)\n}", "func MakeEvalEnv() eval.Env {\n\tvar pkgs map[string] eval.Pkg = make(map[string] eval.Pkg)\n\tEvalEnvironment(pkgs)\n\n\tenv := eval.Env {\n\t\tName: \".\",\n\t\tVars: make(map[string] reflect.Value),\n\t\tConsts: make(map[string] reflect.Value),\n\t\tFuncs: make(map[string] reflect.Value),\n\t\tTypes: make(map[string] reflect.Type),\n\t\tPkgs: pkgs,\n\t}\n\treturn env\n}", "func (r *CheckedDaemonSet) assertEnv(ctx context.Context, client client.Client, container, key, expectedValue string) error {\n\tif err := assertEnv(ctx, client, r.Spec.Template.Spec, ComponentCalicoNode, container, key, expectedValue); err != nil {\n\t\treturn err\n\t}\n\tr.ignoreEnv(container, key)\n\treturn nil\n}", "func CheckEnv(lookupFunc func(key string) (string, bool)) (err error) {\n\tif lookupFunc == nil {\n\t\tlookupFunc = os.LookupEnv\n\t}\n\n\tenvVars := [4]string{\n\t\tEnvHueBridgeAddress,\n\t\tEnvHueBridgeUsername,\n\t\tEnvHueRemoteToken,\n\t\tEnvRedisURL,\n\t}\n\n\tfor _, v := range envVars {\n\t\tif _, ok := lookupFunc(v); !ok {\n\t\t\treturn models.NewMissingEnvError(v)\n\t\t}\n\t}\n\n\treturn nil\n}", "func toEnv(spec *engine.Spec, step *engine.Step) []v1.EnvVar {\n\tvar to []v1.EnvVar\n\tfor k, v := range step.Envs {\n\t\tto = append(to, v1.EnvVar{\n\t\t\tName: k,\n\t\t\tValue: v,\n\t\t})\n\t}\n\tto = append(to, v1.EnvVar{\n\t\tName: \"KUBERNETES_NODE\",\n\t\tValueFrom: &v1.EnvVarSource{\n\t\t\tFieldRef: &v1.ObjectFieldSelector{\n\t\t\t\tFieldPath: \"spec.nodeName\",\n\t\t\t},\n\t\t},\n\t})\n\tfor _, secret := range step.Secrets {\n\t\tsec, ok := engine.LookupSecret(spec, secret)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\toptional := true\n\t\tto = append(to, v1.EnvVar{\n\t\t\tName: secret.Env,\n\t\t\tValueFrom: &v1.EnvVarSource{\n\t\t\t\tSecretKeyRef: &v1.SecretKeySelector{\n\t\t\t\t\tLocalObjectReference: v1.LocalObjectReference{\n\t\t\t\t\t\tName: sec.Metadata.UID,\n\t\t\t\t\t},\n\t\t\t\t\tKey: sec.Metadata.UID,\n\t\t\t\t\tOptional: &optional,\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\treturn to\n}", "func Eval(node ast.Node, env *object.Environment) object.Object {\n\tswitch node := node.(type) {\n\n\t// Statements\n\tcase *ast.RootNode:\n\t\treturn evalRootNode(node, env)\n\n\tcase *ast.BlockStatement:\n\t\treturn evalBlockStmt(node, env)\n\n\tcase *ast.ExpressionStatement:\n\t\treturn Eval(node.Expression, env)\n\n\tcase *ast.ReturnStatement:\n\t\tval := Eval(node.ReturnValue, env)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\treturn &object.ReturnValue{Value: val}\n\n\tcase *ast.LetStatement:\n\t\tval := Eval(node.Value, env)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\tenv.Set(node.Name.Value, val)\n\n\tcase *ast.ConstStatement:\n\t\tval := Eval(node.Value, env)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\tenv.Set(node.Name.Value, val)\n\n\t// Expressions\n\tcase *ast.IntegerLiteral:\n\t\treturn &object.Integer{Value: node.Value}\n\n\tcase *ast.StringLiteral:\n\t\treturn &object.String{Value: node.Value}\n\n\tcase *ast.Boolean:\n\t\treturn nativeBoolToBooleanObj(node.Value)\n\n\tcase *ast.PrefixExpression:\n\t\tright := Eval(node.Right, env)\n\t\tif isError(right) {\n\t\t\treturn right\n\t\t}\n\t\treturn evalPrefixExpr(node.Operator, right, node.Token.Line)\n\n\tcase *ast.InfixExpression:\n\t\tleft := Eval(node.Left, env)\n\t\tif isError(left) {\n\t\t\treturn left\n\t\t}\n\t\tright := Eval(node.Right, env)\n\t\tif isError(right) {\n\t\t\treturn right\n\t\t}\n\t\treturn evalInfixExpr(node.Operator, left, right, node.Token.Line)\n\n\tcase *ast.PostfixExpression:\n\t\treturn evalPostfixExpr(env, node.Operator, node)\n\n\tcase *ast.IfExpression:\n\t\treturn evalIfExpr(node, env)\n\n\tcase *ast.Identifier:\n\t\treturn evalIdentifier(node, env)\n\n\tcase *ast.FunctionLiteral:\n\t\tparams := node.Parameters\n\t\tbody := node.Body\n\t\treturn &object.Function{\n\t\t\tParameters: params,\n\t\t\tBody: body,\n\t\t\tEnv: env,\n\t\t}\n\n\tcase *ast.CallExpression:\n\t\tfn := Eval(node.Function, env)\n\t\tif isError(fn) {\n\t\t\treturn fn\n\t\t}\n\t\targs := evalExprs(node.Arguments, env)\n\t\tif len(args) == 1 && isError(args[0]) {\n\t\t\treturn args[0]\n\t\t}\n\t\treturn applyFunction(fn, args, node.Token.Line)\n\n\tcase *ast.ArrayLiteral:\n\t\telements := evalExprs(node.Elements, env)\n\t\tif len(elements) == 1 && isError(elements[0]) {\n\t\t\treturn elements[0]\n\t\t}\n\t\treturn &object.Array{Elements: elements}\n\n\tcase *ast.IndexExpression:\n\t\tleft := Eval(node.Left, env)\n\t\tif isError(left) {\n\t\t\treturn left\n\t\t}\n\t\tindex := Eval(node.Index, env)\n\t\tif isError(index) {\n\t\t\treturn index\n\t\t}\n\t\treturn evalIndexExpr(left, index, node.Token.Line)\n\n\tcase *ast.HashLiteral:\n\t\treturn evalHashLiteral(node, env)\n\t}\n\n\treturn nil\n}", "func (o BuildSpecRuntimePtrOutput) Env() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *BuildSpecRuntime) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Env\n\t}).(pulumi.StringMapOutput)\n}", "func ExampleBind() {\n\t// Simple configuration struct\n\ttype config struct {\n\t\tHostName string `env:\"HOSTNAME\"` // default: HOST_NAME\n\t\tUserName string `env:\"USERNAME\"` // default: USER_NAME\n\t\tSSL bool `env:\"USE_SSL\"` // default: SSL\n\t\tPort int // leave as default (PORT)\n\t\tPingInterval time.Duration `env:\"PING\"` // default: PING_INTERVAL\n\t\tOnline bool `env:\"-\"` // ignore this field\n\t}\n\n\t// Set some values in the environment for test purposes\n\t_ = os.Setenv(\"HOSTNAME\", \"api.example.com\")\n\t_ = os.Setenv(\"USERNAME\", \"\") // empty\n\t_ = os.Setenv(\"PORT\", \"443\")\n\t_ = os.Setenv(\"USE_SSL\", \"1\")\n\t_ = os.Setenv(\"PING\", \"5m\")\n\t_ = os.Setenv(\"ONLINE\", \"1\") // will be ignored\n\n\t// Create a config and bind it to the environment\n\tc := &config{}\n\tif err := Bind(c); err != nil {\n\t\t// handle error...\n\t}\n\n\t// config struct now populated from the environment\n\tfmt.Println(c.HostName)\n\tfmt.Println(c.UserName)\n\tfmt.Printf(\"%d\\n\", c.Port)\n\tfmt.Printf(\"%v\\n\", c.SSL)\n\tfmt.Printf(\"%v\\n\", c.Online)\n\tfmt.Printf(\"%v\\n\", c.PingInterval*4) // it's not a string!\n\t// Output:\n\t// api.example.com\n\t//\n\t// 443\n\t// true\n\t// false\n\t// 20m0s\n\n\tos.Clearenv()\n}", "func EnvVarTest(resourceName string, sourceType string, envString string) {\n\n\tif sourceType == \"git\" {\n\t\t// checking the values of the env vars pairs in bc\n\t\tenvVars := runCmd(\"oc get bc \" + resourceName + \" -o go-template='{{range .spec.strategy.sourceStrategy.env}}{{.name}}{{.value}}{{end}}'\")\n\t\tExpect(envVars).To(Equal(envString))\n\t}\n\n\t// checking the values of the env vars pairs in dc\n\tenvVars := runCmd(\"oc get dc \" + resourceName + \" -o go-template='{{range .spec.template.spec.containers}}{{range .env}}{{.name}}{{.value}}{{end}}{{end}}'\")\n\tExpect(envVars).To(Equal(envString))\n}", "func (c *Env) MarshalJSON() ([]byte, error) {\n\tdata := map[string]interface{}{\n\t\t\"appID\": strconv.FormatUint(c.appID, 10),\n\t\t\"level\": c.level,\n\t\t\"status\": c.Status,\n\t\t\"frictionlessRequests\": c.FrictionlessRequests,\n\t\t\"signedRequest\": c.SignedRequest,\n\t\t\"viewMode\": c.ViewMode,\n\t\t\"init\": c.Init,\n\t}\n\tif c.isEmployee {\n\t\tdata[\"isEmployee\"] = true\n\t}\n\treturn json.Marshal(data)\n}", "func Evaluate(thing interface{}, env Environment) (error, Value, Environment) {\n\tswitch thing.(type) {\n\tcase Value:\n\t\treturn EvaluateValue(thing.(Value), env)\n\tcase SExpression:\n\t\tsexp := thing.(SExpression)\n\t\tif isSpecialForm(sexp.FormName.Contained) {\n\t\t\treturn EvaluateSpecialForm(sexp, env)\n\t\t} else {\n\t\t\treturn EvaluateSexp(thing.(SExpression), env)\n\t\t}\n\tdefault:\n\t\treturn errors.New(fmt.Sprintf(\"No way to evaluate %v\\n\", thing)), Value{}, env\n\t}\n}", "func (c *Client) EnvUpdate(ctx context.Context, req *EnvUpdateRequest) (*EnvUpdateResponse, error) {\n\tvar resp EnvUpdateResponse\n\tif err := c.client.Do(ctx, \"PATCH\", envURL, req, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Normalize()\n\treturn &resp, nil\n}", "func (config *Config) Get(key string, v interface{}) error {\n\tvar val interface{}\n\n\tenv, set := os.LookupEnv(key)\n\n\tif set {\n\t\tswitch v.(type) {\n\t\tcase *float64:\n\t\t\tval, err := strconv.ParseFloat(env, 64)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t*v.(*float64) = val\n\t\t\treturn nil\n\t\tcase *int:\n\t\t\tval, err := strconv.ParseInt(env, 10, 64)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t*v.(*int) = int(val)\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tval = env\n\t\t}\n\t} else if config.cache != nil {\n\t\tval = (*config.cache)[key]\n\t}\n\n\t// Cast JSON values\n\tswitch v.(type) {\n\tcase *string:\n\t\tif val == nil {\n\t\t\tval = \"\"\n\t\t}\n\n\t\tif b, ok := val.(bool); ok {\n\t\t\t*v.(*string) = strconv.FormatBool(b)\n\t\t} else if f, ok := val.(float64); ok {\n\t\t\t*v.(*string) = strconv.FormatFloat(f, 'f', -1, 64)\n\t\t} else {\n\t\t\t*v.(*string) = val.(string)\n\t\t}\n\tcase *bool:\n\t\tswitch val {\n\t\tcase nil, 0, false, \"\", \"0\", \"false\":\n\t\t\t// falsey\n\t\t\tval = false\n\t\tdefault:\n\t\t\t// truthy\n\t\t\tval = true\n\t\t}\n\n\t\t*v.(*bool) = val.(bool)\n\tcase *float64:\n\t\tif val == nil {\n\t\t\tval = float64(0)\n\t\t}\n\n\t\tif s, ok := val.(string); ok {\n\t\t\tpf, err := strconv.ParseFloat(s, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t*v.(*float64) = pf\n\t\t} else {\n\t\t\t*v.(*float64) = val.(float64)\n\t\t}\n\tcase *int:\n\t\tif val == nil {\n\t\t\tval = float64(0)\n\t\t}\n\n\t\t*v.(*int) = int(val.(float64))\n\tdefault:\n\t\treturn errors.New(\"Type not supported\")\n\t}\n\n\treturn nil\n}", "func (a *Client) ModifyRuntimeEnv(params *ModifyRuntimeEnvParams) (*ModifyRuntimeEnvOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewModifyRuntimeEnvParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ModifyRuntimeEnv\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/v1/runtime_envs\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &ModifyRuntimeEnvReader{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.(*ModifyRuntimeEnvOK), nil\n\n}", "func (environment *Environment) String() string {\n\tmarshaledVal, _ := json.MarshalIndent(*environment, \"\", \" \") // Marshal to JSON\n\n\treturn string(marshaledVal) // Return string value\n}", "func Getenv(key string, fallbacks ...string) (value string) {\n\tvalue, _ = LookupEnv(key, fallbacks...)\n\treturn\n}", "func (e *EnvironmentVariablesMapV0) UnmarshalJSON(data []byte) error {\n\tvar plain []string\n\tif err := json.Unmarshal(data, &plain); err == nil {\n\t\te.RawCPU = []string{}\n\t\te.RawGPU = []string{}\n\t\te.RawCPU = append(e.RawCPU, plain...)\n\t\te.RawGPU = append(e.RawGPU, plain...)\n\t\treturn nil\n\t}\n\ttype DefaultParser EnvironmentVariablesMapV0\n\tvar jsonItems DefaultParser\n\tif err := json.Unmarshal(data, &jsonItems); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to parse runtime items\")\n\t}\n\te.RawCPU = []string{}\n\te.RawGPU = []string{}\n\tif jsonItems.RawCPU != nil {\n\t\te.RawCPU = append(e.RawCPU, jsonItems.RawCPU...)\n\t}\n\tif jsonItems.RawGPU != nil {\n\t\te.RawGPU = append(e.RawGPU, jsonItems.RawGPU...)\n\t}\n\treturn nil\n}", "func eval(x interface{}, env map[string]interface{}) interface{} {\r\n if str, ok := isSymbol(x); ok { // variable reference\r\n\treturn env[str]\r\n }\r\n l, ok := isList(x)\r\n if !ok { // constant literal\r\n\treturn x\r\n }\r\n if len(l) == 0 {\r\n\tpanic(\"empty list\")\r\n }\r\n if str, ok := isSymbol(l[0]); ok {\r\n\tswitch (str) {\r\n\tcase \"quote\": // (quote exp)\r\n\t return l[1]\r\n\tcase \"if\": // (if test conseq alt)\r\n\t test := l[1]\r\n\t conseq := l[2]\r\n\t alt := l[3]\r\n\t r := eval(test, env)\r\n\t if b, ok := isFalse(r); ok && !b {\r\n\t\treturn eval(alt, env)\r\n\t } else {\r\n\t\treturn eval(conseq, env)\r\n\t }\r\n\tcase \"define\": // (define var exp)\r\n\t car := l[1]\r\n\t cdr := l[2]\r\n\t if str, ok = isSymbol(car); ok {\r\n\t\tenv[str] = eval(cdr, env)\r\n\t\treturn env[str]\r\n\t } else {\r\n\t\tpanic(\"define needs a symbol\")\r\n\t }\r\n\tdefault: // (proc arg...)\r\n\t car := eval(l[0], env)\r\n\t proc, ok := car.(func([]interface{})interface{})\r\n\t if !ok {\r\n\t\tpanic(\"not a procedure\")\r\n\t }\r\n args := makeArgs(l[1:], env)\r\n return proc(args)\r\n\t}\r\n }\r\n return nil\r\n}", "func evaluateAst(program *ast.RootNode) object.Object {\n\tenv := object.NewEnvironment()\n\treturn evaluator.Eval(program, env)\n}", "func ExpandEnv(x *X, env *envvar.Vars) {\n\te := env.ToMap()\n\trootEnv := \"${\" + RootEnv + \"}\"\n\tfor k, v := range e {\n\t\tn := strings.Replace(v, rootEnv, x.Root, -1)\n\t\tif n != v {\n\t\t\tenv.Set(k, n)\n\t\t}\n\t}\n}", "func (o StorageClusterSpecStorkOutput) Env() StorageClusterSpecStorkEnvArrayOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecStork) []StorageClusterSpecStorkEnv { return v.Env }).(StorageClusterSpecStorkEnvArrayOutput)\n}", "func init() {\n\tenvironments = make(map[string]string)\n\n\tfor _, e := range os.Environ() {\n\t\tspl := strings.SplitN(e, \"=\", 2)\n\t\tenvironments[spl[0]] = spl[1]\n\t}\n}", "func (session Runtime) evaluate(expression string, contextID int64, async, returnByValue bool) (*devtool.RemoteObject, error) {\n\tp := &devtool.EvaluatesExpression{\n\t\tExpression: expression,\n\t\tIncludeCommandLineAPI: true,\n\t\tContextID: contextID,\n\t\tAwaitPromise: !async,\n\t\tReturnByValue: returnByValue,\n\t}\n\tresult := new(devtool.EvaluatesResult)\n\tif err := session.call(\"Runtime.evaluate\", p, result); err != nil {\n\t\treturn nil, err\n\t}\n\tif result.ExceptionDetails != nil {\n\t\treturn nil, result.ExceptionDetails\n\t}\n\treturn result.Result, nil\n}", "func LoadEnv() {\n\tif err := env.Parse(&Env); err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func (config *configuration) getEnvVariables() error {\n\t// method 1: Decode json file\n\tfile, err := os.Open(confFile)\n\tif err != nil {\n\t\tpc, _, _, _ := runtime.Caller(0)\n\t\terrorWebLogger.ClientIP = \"ClientIP is NOT existed.\"\n\t\terrorWebLogger.FatalPrintln(getCurrentRPCmethod(pc), \"Open config file error.\", err)\n\t\treturn err\n\t}\n\tdecoder := json.NewDecoder(file)\n\tdecoderErr := decoder.Decode(&config)\n\tif decoderErr != nil {\n\t\tpc, _, _, _ := runtime.Caller(0)\n\t\terrorWebLogger.ClientIP = \"ClientIP is NOT existed.\"\n\t\terrorWebLogger.FatalPrintln(getCurrentRPCmethod(pc), \"Decode config file error.\", decoderErr)\n\t\treturn decoderErr\n\t}\n\n\t// method 2: Unmarshal json file\n\t// jsonData, err := ioutil.ReadFile(confFile)\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// unmarshalErr := json.Unmarshal(jsonData, &config)\n\t// if unmarshalErr != nil {\n\t// \treturn unmarshalErr\n\t// }\n\treturn nil\n}" ]
[ "0.6012806", "0.57397014", "0.5641687", "0.562627", "0.5615011", "0.5526408", "0.5431782", "0.53011316", "0.5275546", "0.52288705", "0.52123624", "0.5184238", "0.51708984", "0.51405346", "0.50925577", "0.5086788", "0.508465", "0.4974547", "0.49473223", "0.49283746", "0.49105817", "0.4858023", "0.4823975", "0.48168898", "0.47934678", "0.4780211", "0.47458574", "0.47359398", "0.47352475", "0.47280318", "0.47279152", "0.4725421", "0.47247875", "0.47198552", "0.46976775", "0.46925792", "0.46793276", "0.46762416", "0.46510607", "0.4642032", "0.46396163", "0.46392596", "0.4636361", "0.4623645", "0.4619046", "0.46121714", "0.46084854", "0.45997494", "0.45964465", "0.45959422", "0.45957252", "0.45936358", "0.45902616", "0.45837587", "0.45804453", "0.4572201", "0.45718783", "0.45715857", "0.45678344", "0.45673263", "0.45641345", "0.4556822", "0.455366", "0.4542691", "0.4542603", "0.4540475", "0.45363402", "0.45356238", "0.4524845", "0.45219144", "0.45195252", "0.45112938", "0.45072275", "0.4502684", "0.45025", "0.45017365", "0.44971296", "0.4493616", "0.44911042", "0.44865406", "0.44626948", "0.44613728", "0.44542572", "0.4453042", "0.4451882", "0.44499618", "0.4445243", "0.44431216", "0.44427878", "0.44415182", "0.44390374", "0.4438952", "0.4438583", "0.44378188", "0.44325697", "0.44271952", "0.4425578", "0.4424562", "0.4423951", "0.4422418" ]
0.7880987
0
EvaluateComponent evaluates a component with jsonnet using a path.
func EvaluateComponent(a app.App, sourcePath, paramsStr, envName string, useMemoryImporter bool) (string, error) { snippet, err := afero.ReadFile(a.Fs(), sourcePath) if err != nil { return "", err } return EvaluateComponentSnippet(a, string(snippet), paramsStr, envName, useMemoryImporter) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func EvaluateComponentSnippet(a app.App, snippet, paramsStr, envName string, useMemoryImporter bool) (string, error) {\n\tlibPath, err := a.LibPath(envName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvm := jsonnet.NewVM()\n\tif useMemoryImporter {\n\t\tvm.Fs = a.Fs()\n\t\tvm.UseMemoryImporter = true\n\t}\n\n\tvm.JPaths = []string{\n\t\tlibPath,\n\t\tfilepath.Join(a.Root(), \"vendor\"),\n\t}\n\tvm.ExtCode(\"__ksonnet/params\", paramsStr)\n\n\tenvDetails, err := a.Environment(envName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdest := map[string]string{\n\t\t\"server\": envDetails.Destination.Server,\n\t\t\"namespace\": envDetails.Destination.Namespace,\n\t}\n\n\tmarshalledDestination, err := json.Marshal(&dest)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvm.ExtCode(\"__ksonnet/environments\", string(marshalledDestination))\n\n\treturn vm.EvaluateSnippet(\"snippet\", snippet)\n}", "func EvaluateEnv(a app.App, sourcePath, paramsStr, envName string) (string, error) {\n\tlibPath, err := a.LibPath(envName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvm := jsonnet.NewVM()\n\n\tvm.JPaths = []string{\n\t\tlibPath,\n\t\tfilepath.Join(a.Root(), \"vendor\"),\n\t}\n\tvm.ExtCode(\"__ksonnet/params\", paramsStr)\n\n\tsnippet, err := afero.ReadFile(a.Fs(), sourcePath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn vm.EvaluateSnippet(sourcePath, string(snippet))\n}", "func (l *Loader) EvaluateDependencies(c *ComponentNode) {\n\ttracer := l.tracer.Tracer(\"\")\n\n\tl.mut.RLock()\n\tdefer l.mut.RUnlock()\n\n\tl.cm.controllerEvaluation.Set(1)\n\tdefer l.cm.controllerEvaluation.Set(0)\n\tstart := time.Now()\n\n\tspanCtx, span := tracer.Start(context.Background(), \"GraphEvaluatePartial\", trace.WithSpanKind(trace.SpanKindInternal))\n\tspan.SetAttributes(attribute.String(\"initiator\", c.NodeID()))\n\tdefer span.End()\n\n\tlogger := log.With(l.log, \"trace_id\", span.SpanContext().TraceID())\n\tlevel.Info(logger).Log(\"msg\", \"starting partial graph evaluation\")\n\tdefer func() {\n\t\tspan.SetStatus(codes.Ok, \"\")\n\n\t\tduration := time.Since(start)\n\t\tlevel.Info(logger).Log(\"msg\", \"finished partial graph evaluation\", \"duration\", duration)\n\t\tl.cm.componentEvaluationTime.Observe(duration.Seconds())\n\t}()\n\n\t// Make sure we're in-sync with the current exports of c.\n\tl.cache.CacheExports(c.ID(), c.Exports())\n\n\t_ = dag.WalkReverse(l.graph, []dag.Node{c}, func(n dag.Node) error {\n\t\tif n == c {\n\t\t\t// Skip over the starting component; the starting component passed to\n\t\t\t// EvaluateDependencies had its exports changed and none of its input\n\t\t\t// arguments will need re-evaluation.\n\t\t\treturn nil\n\t\t}\n\n\t\t_, span := tracer.Start(spanCtx, \"EvaluateNode\", trace.WithSpanKind(trace.SpanKindInternal))\n\t\tspan.SetAttributes(attribute.String(\"node_id\", n.NodeID()))\n\t\tdefer span.End()\n\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\tlevel.Info(logger).Log(\"msg\", \"finished node evaluation\", \"node_id\", n.NodeID(), \"duration\", time.Since(start))\n\t\t}()\n\n\t\tvar err error\n\n\t\tswitch n := n.(type) {\n\t\tcase BlockNode:\n\t\t\terr = l.evaluate(logger, n)\n\t\t\tif exp, ok := n.(*ExportConfigNode); ok {\n\t\t\t\tl.cache.CacheModuleExportValue(exp.Label(), exp.Value())\n\t\t\t}\n\t\t}\n\n\t\t// We only use the error for updating the span status; we don't return the\n\t\t// error because we want to evaluate as many nodes as we can.\n\t\tif err != nil {\n\t\t\tspan.SetStatus(codes.Error, err.Error())\n\t\t} else {\n\t\t\tspan.SetStatus(codes.Ok, \"\")\n\t\t}\n\t\treturn nil\n\t})\n\n\tif l.globals.OnExportsChange != nil && l.cache.ExportChangeIndex() != l.moduleExportIndex {\n\t\tl.globals.OnExportsChange(l.cache.CreateModuleExports())\n\t\tl.moduleExportIndex = l.cache.ExportChangeIndex()\n\t}\n}", "func ParseJSONPathExpr(pathExpr string) (PathExpression, error) {\n\tpeCache.mu.Lock()\n\tval, ok := peCache.cache.Get(pathExpressionKey(pathExpr))\n\tif ok {\n\t\tpeCache.mu.Unlock()\n\t\treturn val.(PathExpression), nil\n\t}\n\tpeCache.mu.Unlock()\n\n\tpathExpression, err := parseJSONPathExpr(pathExpr)\n\tif err == nil {\n\t\tpeCache.mu.Lock()\n\t\tpeCache.cache.Put(pathExpressionKey(pathExpr), kvcache.Value(pathExpression))\n\t\tpeCache.mu.Unlock()\n\t}\n\treturn pathExpression, err\n}", "func (ctx *TemplateContext) JSON(path string) (string, error) {\n\tdata := make(map[string]interface{})\n\tdec := json.NewDecoder(strings.NewReader(ctx.Payload))\n\terr := dec.Decode(&data)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tparts := strings.Split(path, \".\")\n\n\tquery := jsonq.NewQuery(data)\n\tvalue, err := query.Interface(parts...)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// converts int, float, bool, etc to string\n\treturn fmt.Sprintf(\"%v\", value), nil\n}", "func jsonizePath(mi *Model, path string) string {\n\texprs := strings.Split(path, ExprSep)\n\texprs = jsonizeExpr(mi, exprs)\n\treturn strings.Join(exprs, ExprSep)\n}", "func jsonizePath(mi *modelInfo, path string) string {\n\texprs := strings.Split(path, ExprSep)\n\texprs = jsonizeExpr(mi, exprs)\n\treturn strings.Join(exprs, ExprSep)\n}", "func (l *Loader) Apply(args map[string]any, componentBlocks []*ast.BlockStmt, configBlocks []*ast.BlockStmt) diag.Diagnostics {\n\tstart := time.Now()\n\tl.mut.Lock()\n\tdefer l.mut.Unlock()\n\tl.cm.controllerEvaluation.Set(1)\n\tdefer l.cm.controllerEvaluation.Set(0)\n\n\tfor key, value := range args {\n\t\tl.cache.CacheModuleArgument(key, value)\n\t}\n\tl.cache.SyncModuleArgs(args)\n\n\tnewGraph, diags := l.loadNewGraph(args, componentBlocks, configBlocks)\n\tif diags.HasErrors() {\n\t\treturn diags\n\t}\n\n\tvar (\n\t\tcomponents = make([]*ComponentNode, 0, len(componentBlocks))\n\t\tcomponentIDs = make([]ComponentID, 0, len(componentBlocks))\n\t\tservices = make([]*ServiceNode, 0, len(l.services))\n\t)\n\n\ttracer := l.tracer.Tracer(\"\")\n\tspanCtx, span := tracer.Start(context.Background(), \"GraphEvaluate\", trace.WithSpanKind(trace.SpanKindInternal))\n\tdefer span.End()\n\n\tlogger := log.With(l.log, \"trace_id\", span.SpanContext().TraceID())\n\tlevel.Info(logger).Log(\"msg\", \"starting complete graph evaluation\")\n\tdefer func() {\n\t\tspan.SetStatus(codes.Ok, \"\")\n\n\t\tduration := time.Since(start)\n\t\tlevel.Info(logger).Log(\"msg\", \"finished complete graph evaluation\", \"duration\", duration)\n\t\tl.cm.componentEvaluationTime.Observe(duration.Seconds())\n\t}()\n\n\tl.cache.ClearModuleExports()\n\n\t// Evaluate all the components.\n\t_ = dag.WalkTopological(&newGraph, newGraph.Leaves(), func(n dag.Node) error {\n\t\t_, span := tracer.Start(spanCtx, \"EvaluateNode\", trace.WithSpanKind(trace.SpanKindInternal))\n\t\tspan.SetAttributes(attribute.String(\"node_id\", n.NodeID()))\n\t\tdefer span.End()\n\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\tlevel.Info(logger).Log(\"msg\", \"finished node evaluation\", \"node_id\", n.NodeID(), \"duration\", time.Since(start))\n\t\t}()\n\n\t\tvar err error\n\n\t\tswitch n := n.(type) {\n\t\tcase *ComponentNode:\n\t\t\tcomponents = append(components, n)\n\t\t\tcomponentIDs = append(componentIDs, n.ID())\n\n\t\t\tif err = l.evaluate(logger, n); err != nil {\n\t\t\t\tvar evalDiags diag.Diagnostics\n\t\t\t\tif errors.As(err, &evalDiags) {\n\t\t\t\t\tdiags = append(diags, evalDiags...)\n\t\t\t\t} else {\n\t\t\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\t\t\tMessage: fmt.Sprintf(\"Failed to build component: %s\", err),\n\t\t\t\t\t\tStartPos: ast.StartPos(n.Block()).Position(),\n\t\t\t\t\t\tEndPos: ast.EndPos(n.Block()).Position(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase *ServiceNode:\n\t\t\tservices = append(services, n)\n\n\t\t\tif err = l.evaluate(logger, n); err != nil {\n\t\t\t\tvar evalDiags diag.Diagnostics\n\t\t\t\tif errors.As(err, &evalDiags) {\n\t\t\t\t\tdiags = append(diags, evalDiags...)\n\t\t\t\t} else {\n\t\t\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\t\t\tMessage: fmt.Sprintf(\"Failed to evaluate service: %s\", err),\n\t\t\t\t\t\tStartPos: ast.StartPos(n.Block()).Position(),\n\t\t\t\t\t\tEndPos: ast.EndPos(n.Block()).Position(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase BlockNode:\n\t\t\tif err = l.evaluate(logger, n); err != nil {\n\t\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\t\tMessage: fmt.Sprintf(\"Failed to evaluate node for config block: %s\", err),\n\t\t\t\t\tStartPos: ast.StartPos(n.Block()).Position(),\n\t\t\t\t\tEndPos: ast.EndPos(n.Block()).Position(),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif exp, ok := n.(*ExportConfigNode); ok {\n\t\t\t\tl.cache.CacheModuleExportValue(exp.Label(), exp.Value())\n\t\t\t}\n\t\t}\n\n\t\t// We only use the error for updating the span status; we don't return the\n\t\t// error because we want to evaluate as many nodes as we can.\n\t\tif err != nil {\n\t\t\tspan.SetStatus(codes.Error, err.Error())\n\t\t} else {\n\t\t\tspan.SetStatus(codes.Ok, \"\")\n\t\t}\n\t\treturn nil\n\t})\n\n\tl.componentNodes = components\n\tl.serviceNodes = services\n\tl.graph = &newGraph\n\tl.cache.SyncIDs(componentIDs)\n\tl.blocks = componentBlocks\n\tl.cm.componentEvaluationTime.Observe(time.Since(start).Seconds())\n\tif l.globals.OnExportsChange != nil && l.cache.ExportChangeIndex() != l.moduleExportIndex {\n\t\tl.moduleExportIndex = l.cache.ExportChangeIndex()\n\t\tl.globals.OnExportsChange(l.cache.CreateModuleExports())\n\t}\n\treturn diags\n}", "func (cx *Context) Eval(source string, result interface{}) (err error) {\n\tcx.do(func(ptr *C.JSAPIContext) {\n\t\t// alloc C-string\n\t\tcsource := C.CString(source)\n\t\tdefer C.free(unsafe.Pointer(csource))\n\t\tvar jsonData *C.char\n\t\tvar jsonLen C.int\n\t\tfilename := \"eval\"\n\t\tcfilename := C.CString(filename)\n\t\tdefer C.free(unsafe.Pointer(cfilename))\n\t\t// eval\n\t\tif C.JSAPI_EvalJSON(ptr, csource, cfilename, &jsonData, &jsonLen) != C.JSAPI_OK {\n\t\t\terr = cx.getError(filename)\n\t\t\treturn\n\t\t}\n\t\tdefer C.free(unsafe.Pointer(jsonData))\n\t\t// convert to go\n\t\tb := []byte(C.GoStringN(jsonData, jsonLen))\n\t\tif raw, ok := result.(*Raw); ok {\n\t\t\t*raw = Raw(string(b))\n\t\t} else {\n\t\t\terr = json.Unmarshal(b, result)\n\t\t}\n\t})\n\treturn err\n}", "func Get(path string, value interface{}) (interface{}, error) {\n\teval, err := lang.NewEvaluable(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn eval(context.Background(), value)\n}", "func LoadComponentFromPath(path string) (*Component, error) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdef, err := LoadComponent(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdef.Path = path\n\treturn def, nil\n}", "func (myjson *JSONModel) Get(nodePath string) (interface{}, error) {\n\tif len(nodePath) == 0 {\n\t\tpanic(\"The parameter \\\"nodePath\\\" is nil or empty\")\n\t}\n\tif e := myjson.toJSONObj(); e != nil {\n\t\treturn nil, e\n\t}\n\tif myjson.jsonObj == nil {\n\t\treturn nil, errors.New(\"Parse json to the type \\\"interface{}\\\" is nil \")\n\t}\n\n\tnodes := strings.Split(nodePath, \".\")\n\treturn adaptor(myjson.jsonObj, nodes)\n}", "func RunTemplate(template []byte, input []byte) (interface{}, error) {\n\n\tvar data interface{}\n\tjson.Unmarshal(input, &data)\n\n\tv, err := jsonfilter.FilterJsonFromTextWithFilterRunner(string(template), string(template), func(command string, value string) (string, error) {\n\t\tfilterval, _ := jsonpath.Read(data, value)\n\t\t// fmt.Println(filterval)\n\t\tret := fmt.Sprintf(\"%v\", filterval)\n\t\treturn ret, nil\n\t})\n\n\treturn v, err\n\n}", "func (r *NuxeoReconciler) getValueByPath(resource v1alpha1.BackingServiceResource, namespace string,\n\tfrom string) ([]byte, string, error) {\n\tif from == \"\" {\n\t\treturn nil, \"\", fmt.Errorf(\"no path provided in projection\")\n\t}\n\tu := unstructured.Unstructured{}\n\tgvk := schema.GroupVersionKind{\n\t\tGroup: resource.Group,\n\t\tVersion: resource.Version,\n\t\tKind: resource.Kind,\n\t}\n\tu.SetGroupVersionKind(gvk)\n\tif err := r.Get(context.TODO(), client.ObjectKey{Namespace: namespace, Name: resource.Name},\n\t\t&u); err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"unable to get resource: %v\", resource.Name)\n\t}\n\tresVer := \"\"\n\tif rv, rve := util.GetJsonPathValueU(u.Object, \"{.metadata.resourceVersion}\"); rve == nil && rv != nil {\n\t\tresVer = string(rv)\n\t} else if rve != nil {\n\t\treturn nil, \"\", rve\n\t} else if rv == nil {\n\t\treturn nil, \"\", fmt.Errorf(\"unable to get resource version from resource: %v\", resource.Name)\n\t}\n\tresVal, resErr := util.GetJsonPathValueU(u.Object, from)\n\treturn resVal, resVer, resErr\n}", "func RunJSONSerializationTestForUrlPathMatchConditionParameters(subject UrlPathMatchConditionParameters) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual UrlPathMatchConditionParameters\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (l *Loader) evaluate(logger log.Logger, bn BlockNode) error {\n\tectx := l.cache.BuildContext()\n\terr := bn.Evaluate(ectx)\n\n\tswitch c := bn.(type) {\n\tcase *ComponentNode:\n\t\t// Always update the cache both the arguments and exports, since both might\n\t\t// change when a component gets re-evaluated. We also want to cache the arguments and exports in case of an error\n\t\tl.cache.CacheArguments(c.ID(), c.Arguments())\n\t\tl.cache.CacheExports(c.ID(), c.Exports())\n\tcase *ArgumentConfigNode:\n\t\tif _, found := l.cache.moduleArguments[c.Label()]; !found {\n\t\t\tif c.Optional() {\n\t\t\t\tl.cache.CacheModuleArgument(c.Label(), c.Default())\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"missing required argument %q to module\", c.Label())\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tlevel.Error(logger).Log(\"msg\", \"failed to evaluate config\", \"node\", bn.NodeID(), \"err\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func loadSpec(cPath string) (spec *specs.Spec, err error) {\n\tcf, err := os.Open(cPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, fmt.Errorf(\"JSON specification file %s not found\", cPath)\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer cf.Close()\n\n\tif err = json.NewDecoder(cf).Decode(&spec); err != nil {\n\t\treturn nil, err\n\t}\n\t// return spec, validateProcessSpec(spec.Process)\n\treturn spec, nil\n}", "func jsonPathValue(yamlConfig string, jsonPath string) (interface{}, error) {\n\tu, err := k8sutil.YAMLToUnstructured([]byte(yamlConfig))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"YAML to unstructured object: %w\", err)\n\t}\n\n\tgot, err := valFromObject(jsonPath, u)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"JSON path value in YAML: %w\", err)\n\t}\n\n\tswitch got.Kind() { //nolint:exhaustive\n\tcase reflect.Interface:\n\t\t// TODO: Add type switch here for concrete types.\n\t\treturn got.Interface(), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"extracted object has an unknown type: %v\", got.Kind())\n\t}\n}", "func LoadComponentConfig(structConfig interface{}, configFile string) {\n\n\tif _, err := os.Stat(configFile); os.IsNotExist(err) {\n\t\tlog.Fatalln(configFile + \" file not found\")\n\t} else if err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n\n\tif _, err := toml.DecodeFile(configFile, structConfig); err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n\n}", "func TestCSharpCompat(t *testing.T) {\n\tjs := `{\n \"store\": {\n \"book\": [\n {\n \"category\": \"reference\",\n \"author\": \"Nigel Rees\",\n \"title\": \"Sayings of the Century\",\n \"price\": 8.95\n },\n {\n \"category\": \"fiction\",\n \"author\": \"Evelyn Waugh\",\n \"title\": \"Sword of Honour\",\n \"price\": 12.99\n },\n {\n \"category\": \"fiction\",\n \"author\": \"Herman Melville\",\n \"title\": \"Moby Dick\",\n \"isbn\": \"0-553-21311-3\",\n \"price\": 8.99\n },\n {\n \"category\": \"fiction\",\n \"author\": \"J. R. R. Tolkien\",\n \"title\": \"The Lord of the Rings\",\n \"isbn\": \"0-395-19395-8\",\n \"price\": null\n }\n ],\n \"bicycle\": {\n \"color\": \"red\",\n \"price\": 19.95\n }\n },\n \"expensive\": 10,\n \"data\": null\n}`\n\n\ttestCases := []pathTestCase{\n\t\t{\"$.store.book[*].author\", `[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]`},\n\t\t{\"$..author\", `[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]`},\n\t\t{\"$.store.*\", `[[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":null}],{\"color\":\"red\",\"price\":19.95}]`},\n\t\t{\"$.store..price\", `[19.95,8.95,12.99,8.99,null]`},\n\t\t{\"$..book[2]\", `[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]`},\n\t\t{\"$..book[-2]\", `[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]`},\n\t\t{\"$..book[0,1]\", `[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}]`},\n\t\t{\"$..book[:2]\", `[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}]`},\n\t\t{\"$..book[1:2]\", `[{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}]`},\n\t\t{\"$..book[-2:]\", `[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":null}]`},\n\t\t{\"$..book[2:]\", `[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":null}]`},\n\t\t{\"\", `[{\"store\":{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":null}],\"bicycle\":{\"color\":\"red\",\"price\":19.95}},\"expensive\":10,\"data\":null}]`},\n\t\t{\"$.*\", `[{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":null}],\"bicycle\":{\"color\":\"red\",\"price\":19.95}},10,null]`},\n\t\t{\"$..invalidfield\", `[]`},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.path, func(t *testing.T) {\n\t\t\ttc.testUnmarshalGet(t, js)\n\t\t})\n\t}\n\n\tt.Run(\"bad cases\", func(t *testing.T) {\n\t\t_, ok := unmarshalGet(t, js, `$..book[*].author\"`)\n\t\trequire.False(t, ok)\n\t})\n}", "func EvaluateBundle(ctx context.Context, bundle []byte) (rel.Value, error) {\n\tctx, err := WithBundleRun(ctx, bundle)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx, mainFileSource, path := GetMainBundleSource(ctx)\n\treturn EvaluateExpr(ctx, path, string(mainFileSource))\n}", "func (e *Implementation) Evaluate(template string) (string, error) {\n\tp := tmpl.Parameters{\n\t\tTestNamespace: e.TestNamespace,\n\t\tDependencyNamespace: e.DependencyNamespace,\n\t}\n\n\treturn tmpl.Evaluate(template, p)\n}", "func EvaluateComponents(iq IQ, components []Component, applicationID string) (*Evaluation, error) {\n\trequest, err := json.Marshal(iqEvaluationRequest{Components: components})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not build the request: %v\", err)\n\t}\n\n\trequestEndpoint := fmt.Sprintf(restEvaluation, applicationID)\n\tbody, _, err := iq.Post(requestEndpoint, bytes.NewBuffer(request))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"components not evaluated: %v\", err)\n\t}\n\n\tvar results iqEvaluationRequestResponse\n\tif err = json.Unmarshal(body, &results); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not parse evaluation response: %v\", err)\n\t}\n\n\tgetEvaluationResults := func() (*Evaluation, error) {\n\t\tbody, resp, e := iq.Get(results.ResultsURL)\n\t\tif e != nil {\n\t\t\tif resp.StatusCode != http.StatusNotFound {\n\t\t\t\treturn nil, fmt.Errorf(\"could not retrieve evaluation results: %v\", err)\n\t\t\t}\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tvar ev Evaluation\n\t\tif err = json.Unmarshal(body, &ev); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &ev, nil\n\t}\n\n\tvar eval *Evaluation\n\tticker := time.NewTicker(5 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif eval, err = getEvaluationResults(); eval != nil || err != nil {\n\t\t\t\tticker.Stop()\n\t\t\t\treturn eval, err\n\t\t\t}\n\t\tcase <-time.After(5 * time.Minute):\n\t\t\tticker.Stop()\n\t\t\treturn nil, errors.New(\"timed out waiting for valid evaluation results\")\n\t\t}\n\t}\n}", "func Eval(t testing.TestingT, options *EvalOptions, jsonFilePaths []string, resultQuery string) {\n\trequire.NoError(t, EvalE(t, options, jsonFilePaths, resultQuery))\n}", "func MarshalToJsonPathWrapper(expression string) OutputFormater {\n\texpr := expression\n\t// aka MarshalToJsonPath\n\treturn func(input interface{}) ([]byte, error) {\n\t\tjp := jsonpath.New(\"json-path\")\n\n\t\tif err := jp.Parse(expr); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to parse jsonpath expression: %v\", err)\n\t\t}\n\n\t\tvalues, err := jp.FindResults(input)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to execute jsonpath %s on input %s: %v \", expr, input, err)\n\t\t}\n\n\t\tif values == nil || len(values) == 0 || len(values[0]) == 0 {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Error parsing value from input %v using template %s: %v \", input, expr, err))\n\t\t}\n\n\t\tjson, err := MarshalToJson(values[0][0].Interface())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn unquote(json), err\n\t}\n}", "func RunJSONSerializationTestForExtendedLocation(subject ExtendedLocation) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ExtendedLocation\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForExtendedLocation(subject ExtendedLocation) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ExtendedLocation\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForExtendedLocation(subject ExtendedLocation) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ExtendedLocation\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (s *server) resolveComponent(dirPath, childQuery string, predicate func(os.FileInfo) bool) (string, error) {\n\tvar err error\n\tvar children []string\n\n\tkey := strings.ToLower(dirPath)\n\tif s.cache != nil && s.cache.Contains(key) {\n\t\tentry, _ := s.cache.Get(key)\n\t\tchildren = entry.([]string)\n\t} else {\n\t\tchildren, err = godirwalk.ReadDirnames(dirPath, nil)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tsort.Strings(children)\n\t\tif s.cache != nil {\n\t\t\ts.cache.Add(key, children)\n\t\t}\n\t}\n\n\tnormSegment := \"\"\n\tfor _, child := range children {\n\t\tif strings.EqualFold(child, childQuery) {\n\t\t\tchildPath := filepath.Join(dirPath, child)\n\t\t\tfi, err := os.Stat(childPath)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tif predicate(fi) {\n\t\t\t\tnormSegment = child\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif normSegment == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\treturn filepath.Join(dirPath, normSegment), nil\n}", "func (a *JSONDataDecouplerActivity) Eval(ctx activity.Context) (done bool, err error) {\n\n\toriginJSONObject := ctx.GetInput(input)\n\ttargetPath, targetPathElements, _ := a.getTarget(ctx)\n\ttarget := originJSONObject\n\tfor _, targetPathElement := range targetPathElements {\n\t\ttarget = target.(map[string]interface{})[targetPathElement]\n\t}\n\n\ttargetArray := target.([]interface{})\n\toutputArray := make([]interface{}, len(targetArray))\n\tfor index, targetElement := range targetArray {\n\t\toutputElement := make(map[string]interface{})\n\t\toutputElement[\"originJSONObject\"] = originJSONObject\n\t\toutputElement[fmt.Sprintf(\"%s.%s\", targetPath, \"Index\")] = index\n\t\toutputElement[fmt.Sprintf(\"%s.%s\", targetPath, \"Element\")] = targetElement\n\t\tif len(targetArray)-1 == index {\n\t\t\toutputElement[\"LastElement\"] = true\n\t\t} else {\n\t\t\toutputElement[\"LastElement\"] = false\n\t\t}\n\t}\n\n\tjsondata := &data.ComplexObject{Metadata: \"Data\", Value: outputArray}\n\n\tctx.SetOutput(output, jsondata)\n\n\treturn true, nil\n}", "func (session Runtime) evaluate(expression string, contextID int64, async, returnByValue bool) (*devtool.RemoteObject, error) {\n\tp := &devtool.EvaluatesExpression{\n\t\tExpression: expression,\n\t\tIncludeCommandLineAPI: true,\n\t\tContextID: contextID,\n\t\tAwaitPromise: !async,\n\t\tReturnByValue: returnByValue,\n\t}\n\tresult := new(devtool.EvaluatesResult)\n\tif err := session.call(\"Runtime.evaluate\", p, result); err != nil {\n\t\treturn nil, err\n\t}\n\tif result.ExceptionDetails != nil {\n\t\treturn nil, result.ExceptionDetails\n\t}\n\treturn result.Result, nil\n}", "func (p *Parser) Load(filename string) (string, error) {\n\tdirectory := filepath.Dir(filename)\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvm := jsonnet.MakeVM()\n\tvm.Importer(&jsonnet.FileImporter{\n\t\tJPaths: []string{directory},\n\t})\n\n\treturn vm.EvaluateAnonymousSnippet(filename, string(data))\n}", "func (this *Value) Path(path string) (*Value, error) {\n\t// aliases always have priority\n\n\tif this.alias != nil {\n\t\tresult, ok := this.alias[path]\n\t\tif ok {\n\t\t\treturn result, nil\n\t\t}\n\t}\n\t// next we already parsed, used that\n\tswitch parsedValue := this.parsedValue.(type) {\n\tcase map[string]*Value:\n\t\tresult, ok := parsedValue[path]\n\t\tif ok {\n\t\t\treturn result, nil\n\t\t}\n\t}\n\t// finally, consult the raw bytes\n\tif this.raw != nil {\n\t\tres, err := jsonpointer.Find(this.raw, \"/\"+path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif res != nil {\n\t\t\treturn NewValueFromBytes(res), nil\n\t\t}\n\t}\n\n\treturn nil, &Undefined{path}\n}", "func (a *Activity) Eval(ctx activity.Context) (done bool, err error) {\n\n\t//call neural network here\n ctx.Logger().Debugf(\"result of picking out a person: %s\", \"found\") //log is also dummy here\n\terr = nil //set if neural network go wrong\n\tif err != nil {\n\t\treturn true, err\n\t}\n//dummy json generation here\n\timgId:=215\n\timgPath:=\"/home/test.jpg/\"\n\tbboxid:=0\n\tx1:=1\n\ty1:=1\n\tx2:=3\n\ty2:=3\n\timgjson:=imgJson{\n\t\tImgid: imgId,\n\t\tImgpath: imgPath,\n\t\tBboxs:[]Bbox{\n\t\t\t Bbox{\n\t\t\t\tBoxid:bboxid,\n\t\t\t\tX1:x1,\n\t\t\t\tY1:y1,\n\t\t\t\tX2:x2,\n\t\t\t\tY2:y2,\n\t\t\t },\n\t\t\t},\t \n\t}\n\tif jsonString, err := json.Marshal(imgjson); err == nil {\n fmt.Println(\"================struct to json str==\")\n fmt.Println(string(jsonString))\n\t\toutput := &Output{Serial: string(jsonString)}\n\t\terr = ctx.SetOutputObject(output)\n\t if err != nil {\n\t\t return true, err\n\t }\n }\n\tif err != nil {\n\t\treturn true, err\n\t}\n\t\t\n\t//output := &Output{Serial: \"1\"}//should be serial of the record in the database\n\n\n\treturn true, nil\n}", "func parseJSON(jsonPath string, v interface{}) error {\n\tif !osutil.Exists(jsonPath) {\n\t\twarn.Printf(\"unable to locate JSON file %q\", jsonPath)\n\t\treturn nil\n\t}\n\treturn jsonutil.ParseFile(jsonPath, v)\n}", "func (o *Object) Path(path string) *Value {\n\topChain := o.chain.enter(\"Path(%q)\", path)\n\tdefer opChain.leave()\n\n\treturn jsonPath(opChain, o.value, path)\n}", "func (session Runtime) Evaluate(code string, async bool, returnByValue bool) (interface{}, error) {\n\tresult, err := session.evaluate(code, session.currentContext(), async, returnByValue)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn result.Value, nil\n}", "func (nc nameConfig) render(job, test string, metadatas ...map[string]string) string {\n\tparsed := make([]interface{}, len(nc.parts))\n\tfor i, p := range nc.parts {\n\t\tvar s string\n\t\tswitch p {\n\t\tcase jobName:\n\t\t\ts = job\n\t\tcase testsName:\n\t\t\ts = test\n\t\tdefault:\n\t\t\tfor _, metadata := range metadatas {\n\t\t\t\tv, present := metadata[p]\n\t\t\t\tif present {\n\t\t\t\t\ts = v\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tparsed[i] = s\n\t}\n\treturn fmt.Sprintf(nc.format, parsed...)\n}", "func (p *Path) Render(values map[string]string, usedValues map[string]struct{}) (string, error) {\n\tvar path string\n\n\tfor _, part := range p.parts {\n\t\tval, used, err := part.render(values, p.normalize)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tpath += `/` + val\n\t\tfor _, u := range used {\n\t\t\tusedValues[u] = struct{}{}\n\t\t}\n\t}\n\n\tif len(path) == 0 {\n\t\tpath = \"/\"\n\t} else if p.trailingSlash && !strings.HasSuffix(path, \"/\") {\n\t\tpath += \"/\"\n\t}\n\n\tquery := url.Values{}\n\tqueryUsed := false\n\tfor k, v := range values {\n\t\tif _, ok := usedValues[k]; !ok {\n\t\t\tqueryUsed = true\n\t\t\tquery.Set(k, v)\n\t\t}\n\t}\n\n\tif queryUsed {\n\t\treturn path + `?` + query.Encode(), nil\n\t}\n\treturn path, nil\n}", "func operatorPresentAtPath(jplan []byte, path string, operator string) error {\n\t// fmt.Printf(\"%s\\n\", string(jplan))\n\tv := interface{}(nil)\n\terr := json.Unmarshal(jplan, &v)\n\tif err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"expected '%s' to be present\", operator))\n\t}\n\n\tbuilder := gval.Full(jsonpath.PlaceholderExtension())\n\texpr, err := builder.NewEvaluable(path)\n\tif err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"expected '%s' to be present\", operator))\n\t}\n\teval, err := expr(context.Background(), v)\n\tif err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"expected '%s' to be present\", operator))\n\t}\n\ts, ok := eval.(string)\n\tif ok && strings.EqualFold(s, operator) {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"expected '%s' to be present\", operator)\n}", "func jsonPath(name string) string {\n\treturn path.Join(dataPath, fmt.Sprintf(\"rove-%s.json\", name))\n}", "func RunJSONSerializationTestForDeliveryRuleUrlPathCondition(subject DeliveryRuleUrlPathCondition) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual DeliveryRuleUrlPathCondition\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func Load (path string, unsafe...bool) (*Parser, error) {\n if j, e := gjson.Load(path, unsafe...); e == nil {\n return &Parser{j}, nil\n } else {\n return nil, e\n }\n}", "func fnEval(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) == 0 || len(params) > 2 {\n\t\tctx.Log().Error(\"error_type\", \"func_eval\", \"op\", \"eval\", \"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 eval function\"), \"eval\", params})\n\t\treturn \"\"\n\t} else if len(params) == 1 {\n\t\treturn doc.EvalPath(ctx, extractStringParam(params[0]))\n\t} else {\n\t\tldoc, err := NewJDocFromString(extractStringParam(params[1]))\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_eval\", \"op\", \"eval\", \"cause\", \"json_expected\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to eval function\"), \"eval\", params})\n\t\t\treturn \"\"\n\t\t}\n\t\treturn ldoc.EvalPath(ctx, extractStringParam(params[0]))\n\t}\n}", "func evaluate(node ast.Node, ext vmExtMap, tla vmExtMap, nativeFuncs map[string]*NativeFunction,\n\tmaxStack int, ic *importCache, traceOut io.Writer, stringOutputMode bool) (string, error) {\n\n\ti, err := buildInterpreter(ext, nativeFuncs, maxStack, ic, traceOut)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresult, err := evaluateAux(i, node, tla)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buf bytes.Buffer\n\ti.stack.setCurrentTrace(manifestationTrace())\n\tif stringOutputMode {\n\t\terr = i.manifestString(&buf, result)\n\t} else {\n\t\terr = i.manifestAndSerializeJSON(&buf, result, true, \"\")\n\t}\n\ti.stack.clearCurrentTrace()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf.WriteString(\"\\n\")\n\treturn buf.String(), nil\n}", "func (p PathParser) Value(raw string) ValueImpl {\n\tif len(raw) == 0 {\n\t\treturn ValueImpl{parser: p} // empty value\n\t}\n\n\tif p.AllowMultiple && strings.HasPrefix(raw, \"[\") {\n\t\t// parse as JSON\n\t\tvar rc = ValueImpl{parser: p}\n\n\t\tif err := json.Unmarshal([]byte(raw), &rc.values); err != nil {\n\t\t\treturn ValueImpl{err: fmt.Errorf(\"failed to parse JSON path: %s\", err.Error())}\n\t\t}\n\n\t\t// valid JSON list -> check each individual item\n\t\tfor _, value := range rc.values {\n\t\t\tif rc.err = p.validatePath(value); rc.err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn rc\n\t}\n\n\t// default behaviour: put it into the first slice\n\treturn ValueImpl{\n\t\tvalues: []string{raw},\n\t\terr: p.validatePath(raw),\n\t\tparser: p,\n\t}\n}", "func FetchPath(j JSON, path []string) (JSON, error) {\n\tvar next JSON\n\tvar err error\n\tfor _, v := range path {\n\t\tnext, err = j.FetchValKeyOrIdx(v)\n\t\tif next == nil {\n\t\t\treturn nil, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tj = next\n\t}\n\treturn j, nil\n}", "func (opa *client) EvaluatePolicy(policy string, input []byte) (*EvaluatePolicyResponse, error) {\n\tlog := opa.logger.Named(\"Evalute Policy\")\n\n\trequest, err := json.Marshal(&EvalutePolicyRequest{Input: input})\n\tif err != nil {\n\t\tlog.Error(\"failed to encode OPA input\", zap.Error(err), zap.String(\"input\", string(input)))\n\t\treturn nil, fmt.Errorf(\"failed to encode OPA input: %s\", err)\n\t}\n\n\thttpResponse, err := opa.httpClient.Post(opa.getDataQueryURL(getOpaPackagePath(policy)), \"application/json\", bytes.NewReader(request))\n\tif err != nil {\n\t\tlog.Error(\"http request to OPA failed\", zap.Error(err))\n\t\treturn nil, fmt.Errorf(\"http request to OPA failed: %s\", err)\n\t}\n\tif httpResponse.StatusCode != http.StatusOK {\n\t\tlog.Error(\"http response status from OPA not OK\", zap.Any(\"status\", httpResponse.Status))\n\t\treturn nil, fmt.Errorf(\"http response status not OK\")\n\t}\n\n\tresponse := &EvaluatePolicyResponse{}\n\terr = json.NewDecoder(httpResponse.Body).Decode(&response)\n\tif err != nil {\n\t\tlog.Error(\"failed to decode OPA result\", zap.Error(err))\n\t\treturn nil, fmt.Errorf(\"failed to decode OPA result: %s\", err)\n\t}\n\n\treturn response, nil\n}", "func evaluateAst(program *ast.RootNode) object.Object {\n\tenv := object.NewEnvironment()\n\treturn evaluator.Eval(program, env)\n}", "func (a *PipelineControllerApiService) EvaluateExpressionForExecutionUsingGET(ctx _context.Context, id string) apiEvaluateExpressionForExecutionUsingGETRequest {\n\treturn apiEvaluateExpressionForExecutionUsingGETRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func update(path []string, src string, params map[string]interface{}) (string, error) {\n\tobj, err := jsonnetParseFn(\"params.libsonnet\", src)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"parse jsonnet\")\n\t}\n\n\tparamsObject, err := nmKVFromMapFn(params)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"convert params to object\")\n\t}\n\n\tif err := jsonnetSetFn(obj, path, paramsObject.Node()); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"update params\")\n\t}\n\n\tvar buf bytes.Buffer\n\tif err := jsonnetPrinterFn(&buf, obj); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"rebuild params\")\n\t}\n\n\treturn buf.String(), nil\n}", "func (m *Map) traversePath(path string, updateValue interface{}, createPaths bool) (interface{}, error) {\n\tpath = strings.TrimPrefix(path, \"/\")\n\tcomponents := strings.Split(path, \"/\")\n\n\tLog.Debug.Printf(\"Traversing path %v with value %v\", path, updateValue)\n\n\tif len(components) == 1 && components[0] == \"\" && updateValue != nil {\n\t\t// Complete replacement of root map, updateValue must be a generic map\n\t\t*m = Map(updateValue.(map[string]interface{}))\n\t\treturn m, nil\n\t}\n\n\tvar lastIndex = len(components) - 1\n\n\tref := *m\n\tvar child interface{} = nil\n\n\tfor i, component := range components {\n\t\tvar ok bool\n\n\t\tif component == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"Empty component encountered in path %v\", path)\n\t\t}\n\n\t\tisUpdate := updateValue != nil\n\n\t\tif i == lastIndex && isUpdate {\n\t\t\tLog.Debug.Printf(\"Updating component %v value %+v\", component, updateValue)\n\n\t\t\tvar jsonUpdateValue = updateValue\n\t\t\tif updateValue == Nil {\n\t\t\t\tjsonUpdateValue = nil\n\t\t\t} else if updateValue == Remove {\n\t\t\t\tdelete(ref, component)\n\t\t\t\treturn Remove, nil\n\t\t\t}\n\n\t\t\tref[component] = jsonUpdateValue\n\t\t\treturn ref[component], nil\n\t\t} else {\n\t\t\tchild, ok = ref[component]\n\t\t\t// Error if this child is not found\n\t\t\tif !ok {\n\t\t\t\tif createPaths && isUpdate {\n\t\t\t\t\tLog.Debug.Printf(\"Creating path for component %v\", component)\n\t\t\t\t\tnewPath := map[string]interface{}{}\n\t\t\t\t\tref[component] = newPath\n\t\t\t\t\tref = newPath\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Child component %v of path %v not found\", component, path)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif i == lastIndex && !isUpdate {\n\t\t\t\t// Return the queried value\n\t\t\t\tLog.Debug.Printf(\"Returning query value %+v\", child)\n\t\t\t\treturn child, nil\n\t\t\t}\n\n\t\t\t// Keep going - child must be a map to enable further traversal\n\t\t\tref, ok = child.(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"Child component %v of path %v is not a map\", component, path)\n\t\t\t}\n\t\t}\n\t}\n\n\t// XXX Shouldn't get here\n\treturn nil, fmt.Errorf(\"Unexpected return from TraversePath %v\", path)\n}", "func (r *Rule) Eval(json []byte) (int, error) {\n\tjq := gojsonq.New().Reader(bytes.NewReader(json)).From(\"kind\")\n\tif jq.Error() != nil {\n\t\treturn 0, jq.Error()\n\t}\n\n\tkind := fmt.Sprintf(\"%s\", jq.Get())\n\n\tvar match bool\n\tfor _, k := range r.Kinds {\n\t\tif k == kind {\n\t\t\tmatch = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif match {\n\t\tcount := r.Predicate(json)\n\t\treturn count, nil\n\t} else {\n\t\treturn 0, &NotSupportedError{Kind: kind}\n\t}\n}", "func LoadConfig(path string, c interface{}) (err error) {\n\tvar jsonFile *os.File\n\tvar byteValue []byte\n\n\tfmt.Println(\"Path \", path)\n\t// Open our jsonFile\n\tjsonFile, err = os.Open(path)\n\t// if we os.Open returns an error then handle it\n\tif err != nil {\n\t\tfmt.Println(\"LoadConfig error \", err)\n\t\treturn\n\t}\n\tfmt.Println(\"Successfully Opened json\")\n\t// defer the closing of our jsonFile so that we can parse it later on\n\tdefer jsonFile.Close()\n\n\t// read our opened xmlFile as a byte array.\n\tbyteValue, err = ioutil.ReadAll(jsonFile)\n\tif err != nil {\n\t\tfmt.Println(\"ReadAll error \", err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(byteValue, &c)\n\tif err != nil {\n\t\tfmt.Println(\"Unmarshal error \", err)\n\t\treturn\n\t}\n\treturn\n}", "func LoadConfig(path string, c interface{}) (err error) {\n\tvar jsonFile *os.File\n\tvar byteValue []byte\n\n\tfmt.Println(\"Path \", path)\n\t// Open our jsonFile\n\tjsonFile, err = os.Open(path)\n\t// if we os.Open returns an error then handle it\n\tif err != nil {\n\t\tfmt.Println(\"LoadConfig error \", err)\n\t\treturn\n\t}\n\tfmt.Println(\"Successfully Opened json\")\n\t// defer the closing of our jsonFile so that we can parse it later on\n\tdefer jsonFile.Close()\n\n\t// read our opened xmlFile as a byte array.\n\tbyteValue, err = ioutil.ReadAll(jsonFile)\n\tif err != nil {\n\t\tfmt.Println(\"ReadAll error \", err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(byteValue, &c)\n\tif err != nil {\n\t\tfmt.Println(\"Unmarshal error \", err)\n\t\treturn\n\t}\n\treturn\n}", "func Load(path string, unsafe...bool) (*Parser, error) {\n if j, e := gjson.Load(path, unsafe...); e == nil {\n return &Parser{j}, nil\n } else {\n return nil, e\n }\n}", "func getJSONRaw(data []byte, path string, pathRequired bool) ([]byte, error) {\n\tobjectKeys := customSplit(path)\n\tfor element, k := range objectKeys {\n\t\t// check the object key to see if it also contains an array reference\n\t\tarrayRefs := jsonPathRe.FindAllStringSubmatch(k, -1)\n\t\tif arrayRefs != nil && len(arrayRefs) > 0 {\n\t\t\tarrayKeyStrs := jsonArrayRe.FindAllString(k, -1)\n\t\t\textracted := false\n\t\t\tobjKey := arrayRefs[0][1] // the key\n\t\t\tresults, newPath, err := getArrayResults(data, objectKeys, objKey, element)\n\t\t\tif err == jsonparser.KeyPathNotFoundError {\n\t\t\t\tif pathRequired {\n\t\t\t\t\treturn nil, NonExistentPath\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor _, arrayKeyStr := range arrayKeyStrs {\n\t\t\t\t// trim the square brackets\n\t\t\t\tarrayKeyStr = arrayKeyStr[1 : len(arrayKeyStr)-1]\n\t\t\t\terr = validateArrayKeyString(arrayKeyStr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\t// if there's a wildcard array reference\n\t\t\t\tif arrayKeyStr == \"*\" {\n\t\t\t\t\t// We won't filter anything with a wildcard\n\t\t\t\t\tcontinue\n\t\t\t\t} else if filterPattern := jsonFilterRe.FindString(arrayKeyStr); filterPattern != \"\" {\n\t\t\t\t\t// MODIFICATIONS --- FILTER SUPPORT\n\t\t\t\t\t// right now we only support filter expressions of the form ?(@.some.json.path Op \"someData\")\n\t\t\t\t\t// Op must be a boolean operator: '==', '<' are fine, '+', '%' are not. Spaces ARE required\n\n\t\t\t\t\t// get the filter jsonpath expression\n\t\t\t\t\tfilterPattern = filterPattern[2 : len(filterPattern)-1]\n\t\t\t\t\tfilterParts := strings.Split(filterPattern, \" \")\n\t\t\t\t\tvar filterPath string\n\t\t\t\t\tif len(filterParts[0]) > 2 {\n\t\t\t\t\t\tfilterPath = filterParts[0][2:]\n\t\t\t\t\t}\n\t\t\t\t\tvar filterObjs [][]byte\n\t\t\t\t\tvar filteredResults [][]byte\n\n\t\t\t\t\t// evaluate the jsonpath filter jsonpath for each index\n\t\t\t\t\tif newPath != \"\" {\n\t\t\t\t\t\t// we are filtering against a list of objects, lookup the data recursively\n\t\t\t\t\t\tfor _, v := range results {\n\t\t\t\t\t\t\tintermediate, err := getJSONRaw(v, filterPath, true)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tif err == NonExistentPath {\n\t\t\t\t\t\t\t\t\t// this is fine, we'll just filter these out\n\t\t\t\t\t\t\t\t\tfilterObjs = append(filterObjs, nil)\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tfilterObjs = append(filterObjs, intermediate)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if filterPath == \"\" {\n\t\t\t\t\t\t// we are filtering against a list of primitives - we won't match any non-empty filterPath\n\t\t\t\t\t\tfor _, v := range results {\n\t\t\t\t\t\t\tfilterObjs = append(filterObjs, v)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// evaluate the filter\n\t\t\t\t\tfor i, v := range filterObjs {\n\t\t\t\t\t\tif v != nil {\n\t\t\t\t\t\t\tfilterParts[0] = string(v)\n\t\t\t\t\t\t\texprString := strings.Join(filterParts, \" \")\n\t\t\t\t\t\t\t// filter the objects based on the results\n\t\t\t\t\t\t\texpr, err := govaluate.NewEvaluableExpression(exprString)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresult, err := expr.Evaluate(nil)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// We pass through the filter if the filter is a boolean expression\n\t\t\t\t\t\t\t// If the filter is not a boolean expression, just pass everything through\n\t\t\t\t\t\t\tif accepted, ok := result.(bool); accepted || !ok {\n\t\t\t\t\t\t\t\tfilteredResults = append(filteredResults, results[i])\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Set the results for the next pass\n\t\t\t\t\tresults = filteredResults\n\t\t\t\t} else {\n\t\t\t\t\tindex, err := strconv.ParseInt(arrayKeyStr, 10, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tif index < int64(len(results)) {\n\t\t\t\t\t\tresults = [][]byte{results[index]}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresults = [][]byte{}\n\t\t\t\t\t}\n\t\t\t\t\textracted = true\n\t\t\t\t}\n\t\t\t}\n\t\t\toutput, err := lookupAndWriteMulti(results, newPath, pathRequired)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// if we have access a specific index, we want to extract the value from the array\n\t\t\t// we just do this manually\n\t\t\tif extracted {\n\t\t\t\toutput = output[1 : len(output)-1]\n\t\t\t}\n\t\t\treturn output, nil\n\t\t} else {\n\t\t\t// no array reference, good to go\n\t\t\tcontinue\n\t\t}\n\t}\n\tresult, dataType, _, err := jsonparser.Get(data, objectKeys...)\n\n\t// jsonparser strips quotes from Strings\n\tif dataType == jsonparser.String {\n\t\t// bookend() is destructive to underlying slice, need to copy.\n\t\t// extra capacity saves an allocation and copy during bookend.\n\t\tresult = HandleUnquotedStrings(result, dataType)\n\t}\n\tif len(result) == 0 {\n\t\tresult = []byte(\"null\")\n\t}\n\tif err == jsonparser.KeyPathNotFoundError {\n\t\tif pathRequired {\n\t\t\treturn nil, NonExistentPath\n\t\t}\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}", "func (r *SourceResolver) Component(ctx context.Context, source *model.Source) (*model.Component, error) {\n\tresults, err := r.DataLoaders.SourceLoader(ctx).ComponentBySource(source.ID)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get component from loader\")\n\t}\n\treturn results, nil\n}", "func (p *prog) Eval(input any) (v ref.Val, det *EvalDetails, err error) {\n\t// Configure error recovery for unexpected panics during evaluation. Note, the use of named\n\t// return values makes it possible to modify the error response during the recovery\n\t// function.\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tswitch t := r.(type) {\n\t\t\tcase interpreter.EvalCancelledError:\n\t\t\t\terr = t\n\t\t\tdefault:\n\t\t\t\terr = fmt.Errorf(\"internal error: %v\", r)\n\t\t\t}\n\t\t}\n\t}()\n\t// Build a hierarchical activation if there are default vars set.\n\tvar vars interpreter.Activation\n\tswitch v := input.(type) {\n\tcase interpreter.Activation:\n\t\tvars = v\n\tcase map[string]any:\n\t\tvars = activationPool.Setup(v)\n\t\tdefer activationPool.Put(vars)\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"invalid input, wanted Activation or map[string]any, got: (%T)%v\", input, input)\n\t}\n\tif p.defaultVars != nil {\n\t\tvars = interpreter.NewHierarchicalActivation(p.defaultVars, vars)\n\t}\n\tv = p.interpretable.Eval(vars)\n\t// The output of an internal Eval may have a value (`v`) that is a types.Err. This step\n\t// translates the CEL value to a Go error response. This interface does not quite match the\n\t// RPC signature which allows for multiple errors to be returned, but should be sufficient.\n\tif types.IsError(v) {\n\t\terr = v.(*types.Err)\n\t}\n\treturn\n}", "func (t *TypeSystem) Evaluate(typename string, object interface{}, op string, value string) (bool, error) {\n\tswitch typename {\n\tcase String:\n\t\treturn t.stringts.Evaluate(object, op, value)\n\tcase Number:\n\t\treturn t.numberts.Evaluate(object, op, value)\n\tcase Boolean:\n\t\treturn t.boolts.Evaluate(object, op, value)\n\tcase Strings:\n\t\treturn t.stringsts.Evaluate(object, op, value)\n\tcase Date:\n\t\treturn t.datets.Evaluate(object, op, value)\n\tdefault:\n\t\treturn false, fmt.Errorf(\"type/golang/type.go: unsupport type, %s, %v, %s, %s\", typename, object, op, value)\n\t}\n}", "func Evaluate(expr string, contextVars map[string]logol.Match) bool {\n\tlogger.Debugf(\"Evaluate expression: %s\", expr)\n\n\tre := regexp.MustCompile(\"[$@#]+\\\\w+\")\n\tres := re.FindAllString(expr, -1)\n\t// msg, _ := json.Marshal(contextVars)\n\t// logger.Errorf(\"CONTEXT: %s\", msg)\n\tparameters := make(map[string]interface{}, 8)\n\tvarIndex := 0\n\tfor _, val := range res {\n\t\tt := strconv.Itoa(varIndex)\n\t\tvarName := \"VAR\" + t\n\t\tr := strings.NewReplacer(val, varName)\n\t\texpr = r.Replace(expr)\n\t\tvarIndex++\n\t\tcValue, cerr := getValueFromExpression(val, contextVars)\n\t\tif cerr {\n\t\t\tlogger.Debugf(\"Failed to get value from expression %s\", val)\n\t\t\treturn false\n\t\t}\n\t\tparameters[varName] = cValue\n\t}\n\tlogger.Debugf(\"New expr: %s with params %v\", expr, parameters)\n\n\texpression, err := govaluate.NewEvaluableExpression(expr)\n\tif err != nil {\n\t\tlogger.Errorf(\"Failed to evaluate expression %s\", expr)\n\t\treturn false\n\t}\n\tresult, _ := expression.Evaluate(parameters)\n\tif result == true {\n\t\treturn true\n\t}\n\treturn false\n}", "func jsonpt(data, key string) string {\n\tdatamap := make(map[string]interface{})\n\terr := json.Unmarshal([]byte(data), &datamap)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"%s cannot be parsed as json\", data)\n\t}\n\tres, err := jsonpath.JsonPathLookup(datamap, key)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"%q not found in data: %v\", key, err)\n\t}\n\treturn fmt.Sprintf(\"%s\", res)\n}", "func RunJSONSerializationTestForUrlFileExtensionMatchConditionParameters(subject UrlFileExtensionMatchConditionParameters) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual UrlFileExtensionMatchConditionParameters\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForResourceReference(subject ResourceReference) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ResourceReference\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForResourceReference(subject ResourceReference) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ResourceReference\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (j *Js) Getpath(args ...string) *Js {\n\td := j\n\tfor i := range args {\n\t\tm := d.Getdata()\n\n\t\tif val, ok := m[args[i]]; ok {\n\t\t\td.data = val\n\t\t} else {\n\t\t\td.data = nil\n\t\t\treturn d\n\t\t}\n\t}\n\treturn d\n}", "func renderValueTemplate(valueTemplate string, variables map[string]apiextensionsv1.JSON) (*apiextensionsv1.JSON, error) {\n\t// Parse the template.\n\ttpl, err := template.New(\"tpl\").Funcs(sprig.HermeticTxtFuncMap()).Parse(valueTemplate)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to parse template: %q\", valueTemplate)\n\t}\n\n\t// Convert the flat variables map in a nested map, so that variables can be\n\t// consumed in templates like this: `{{ .builtin.cluster.name }}`\n\t// NOTE: Variable values are also converted to their Go types as\n\t// they cannot be directly consumed as byte arrays.\n\tdata, err := calculateTemplateData(variables)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to calculate template data\")\n\t}\n\n\t// Render the template.\n\tvar buf bytes.Buffer\n\tif err := tpl.Execute(&buf, data); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to render template: %q\", valueTemplate)\n\t}\n\n\t// Unmarshal the rendered template.\n\t// NOTE: The YAML library is used for unmarshalling, to be able to handle YAML and JSON.\n\tvalue := apiextensionsv1.JSON{}\n\tif err := yaml.Unmarshal(buf.Bytes(), &value); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to unmarshal rendered template: %q\", buf.String())\n\t}\n\n\treturn &value, nil\n}", "func componentConfig(component *models.Component) (config map[string]interface{}, err error) {\n\n\t// fetch the env\n\tenv, err := models.FindEnvByID(component.EnvID)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to load env model: %s\", err.Error())\n\t\treturn\n\t}\n\n\tbox := boxfile.New([]byte(env.BuiltBoxfile))\n\tconfig = box.Node(component.Name).Node(\"config\").Parsed\n\n\tswitch component.Name {\n\tcase \"portal\", \"logvac\", \"hoarder\", \"mist\":\n\t\tconfig[\"token\"] = \"123\"\n\t}\n\treturn\n}", "func (r *Response) JSONPath(expression string, assert func(interface{})) *Response {\n\tr.jsonPathExpression = expression\n\tr.jsonPathAssert = assert\n\treturn r.apiTest.response\n}", "func Componentgen(nr, nl *Node) bool", "func LoadJSON(r io.Reader, filePath, urlPath string) (*Graph, error) {\n\tdec := json.NewDecoder(r)\n\tg := &Graph{\n\t\tFilePath: filePath,\n\t\tURLPath: urlPath,\n\t}\n\tif err := dec.Decode(g); err != nil {\n\t\treturn nil, err\n\t}\n\t// Each node and channel should cache it's own name.\n\tfor k, c := range g.Channels {\n\t\tc.Name = k\n\t}\n\tfor k, n := range g.Nodes {\n\t\tn.Name = k\n\t}\n\t// Finally, set up channel pin caches.\n\tg.RefreshChannelsPins()\n\treturn g, nil\n}", "func Evaluate(tpl string, data interface{}) (string, error) {\n\tt, err := Parse(tpl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn Execute(t, data)\n}", "func Get(json []byte, path ...string) ([]byte, error) {\n\tif len(path) == 0 {\n\t\treturn json, nil\n\t}\n\t_, start, end, err := core(json, false, path...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json[start:end], err\n}", "func RunJSONSerializationTestForComponent_STATUS_ARM(subject Component_STATUS_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual Component_STATUS_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForKubeletConfig(subject KubeletConfig) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual KubeletConfig\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForUrlFileNameMatchConditionParameters(subject UrlFileNameMatchConditionParameters) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual UrlFileNameMatchConditionParameters\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func ExampleJsonpath() {\n\tconst jsonString = `{\n\t \"firstName\": \"John\",\n\t \"lastName\" : \"doe\",\n\t \"age\" : 26,\n\t \"address\" : {\n\t\t\"streetAddress\": \"naist street\",\n\t\t\"city\" : \"Nara\",\n\t\t\"postalCode\" : \"630-0192\"\n\t },\n\t \"phoneNumbers\": [\n\t\t{\n\t\t \"type\" : \"iPhone\",\n\t\t \"number\": \"0123-4567-8888\"\n\t\t},\n\t\t{\n\t\t \"type\" : \"home\",\n\t\t \"number\": \"0123-4567-8910\"\n\t\t},\n\t\t{\n\t\t \"type\": \"mobile\",\n\t\t \"number\": \"0913-8532-8492\"\n\t\t}\n\t ]\n\t}`\n\n\tresult, err := Jsonpath([]byte(jsonString), \"$.phoneNumbers[*].type\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, item := range result {\n\t\tfmt.Println(item)\n\t}\n\t// Output:\n\t// iPhone\n\t// home\n\t// mobile\n}", "func (self *Map) JSONPath(query string, fallback ...interface{}) interface{} {\n\tif d, err := JSONPath(self.MapNative(), query); err == nil && d != nil {\n\t\treturn d\n\t}\n\n\treturn sliceutil.First(fallback)\n}", "func parseComponents(t *template.Template, dir string) (*template.Template, error) {\n\tcomponents, err := readComponents(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, c := range components {\n\t\tp := strings.TrimPrefix(c.Path, dir)\n\t\tp = strings.TrimPrefix(p, \"/\")\n\t\tfmt.Println(\"Parsing component\", p)\n\t\tt, err = t.New(p).Parse(c.Content)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn t, nil\n}", "func TestUpdateJsonFileWithString(t *testing.T) {\n\tfile := \"/tmp/testpathstring.json\"\n\tpaths := []string{\"testpathstring\"}\n\tui := &packer.BasicUi{\n\t\tReader: new(bytes.Buffer),\n\t\tWriter: new(bytes.Buffer),\n\t\tErrorWriter: new(bytes.Buffer),\n\t}\n\tvalue := \"simplevalue_string\"\n\t_ = UpdateJsonFile(file, paths, value, ui, true)\n}", "func RunJSONSerializationTestForRequestUriMatchConditionParameters(subject RequestUriMatchConditionParameters) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual RequestUriMatchConditionParameters\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func parse(input string) (output *js.Object, err error) {\n\tvar ast interface{}\n\terr = hcl.Unmarshal([]byte(input), &ast)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdata, err := json.MarshalIndent(ast, \"\", \" \")\n\tif err != nil {\n\t\treturn\n\t}\n\toutput = js.Global.Get(\"JSON\").Call(\"parse\", string(data))\n\treturn\n}", "func (d *Data) getValue(path string, source interface{}) interface{} {\n\ti := strings.Index(path, d.as+\".\")\n\tif i == 0 {\n\t\tpath = path[len(d.as)+1:]\n\t}\n\ttr, br := splitpath(path)\n\tif tr == \"\" {\n\t\treturn nil\n\t}\n\n\tv, ok := source.(reflect.Value)\n\tif !ok {\n\t\tv = reflect.ValueOf(source)\n\t}\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\n\tswitch v.Kind() {\n\tcase reflect.Map:\n\t\tv = v.MapIndex(reflect.ValueOf(tr))\n\tcase reflect.Struct:\n\t\tv = v.FieldByName(tr)\n\n\tdefault:\n\t\treturn nil\n\t}\n\n\tif !v.IsValid() {\n\t\treturn nil\n\t}\n\n\tvar inf interface{} = v\n\n\tif v.CanInterface() {\n\t\tinf = v.Interface()\n\t}\n\n\tif br != \"\" {\n\t\treturn d.getValue(br, inf)\n\t}\n\n\treturn inf\n}", "func (rt *importRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {\n\t_, err := rt.baseRuntime.Eval(vs, is, tid)\n\n\tif rt.erp.ImportLocator == nil {\n\t\terr = rt.erp.NewRuntimeError(util.ErrRuntimeError, \"No import locator was specified\", rt.node)\n\t}\n\n\tif err == nil {\n\n\t\tvar importPath interface{}\n\t\tif importPath, err = rt.node.Children[0].Runtime.Eval(vs, is, tid); err == nil {\n\n\t\t\tvar codeText string\n\t\t\tif codeText, err = rt.erp.ImportLocator.Resolve(fmt.Sprint(importPath)); err == nil {\n\t\t\t\tvar ast *parser.ASTNode\n\n\t\t\t\tif ast, err = parser.ParseWithRuntime(fmt.Sprint(importPath), codeText, rt.erp); err == nil {\n\t\t\t\t\tif err = ast.Runtime.Validate(); err == nil {\n\n\t\t\t\t\t\tivs := scope.NewScope(scope.GlobalScope)\n\t\t\t\t\t\tif _, err = ast.Runtime.Eval(ivs, make(map[string]interface{}), tid); err == nil {\n\t\t\t\t\t\t\tirt := rt.node.Children[1].Runtime.(*identifierRuntime)\n\t\t\t\t\t\t\tirt.Set(vs, is, tid, scope.ToObject(ivs))\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 nil, err\n}", "func (g *GraphiteProvider) RunQuery(query string) (float64, error) {\n\tquery = g.trimQuery(query)\n\tu, err := url.Parse(fmt.Sprintf(\"./render?%s\", query))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"url.Parse failed: %w\", err)\n\t}\n\n\tq := u.Query()\n\tq.Set(\"format\", \"json\")\n\tu.RawQuery = q.Encode()\n\n\tu.Path = path.Join(g.url.Path, u.Path)\n\tu = g.url.ResolveReference(u)\n\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"http.NewRequest failed: %w\", err)\n\t}\n\n\tif g.username != \"\" && g.password != \"\" {\n\t\treq.SetBasicAuth(g.username, g.password)\n\t}\n\n\tctx, cancel := context.WithTimeout(req.Context(), g.timeout)\n\tdefer cancel()\n\n\tr, err := g.client.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"request failed: %w\", err)\n\t}\n\tdefer r.Body.Close()\n\n\tb, err := io.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"error reading body: %w\", err)\n\t}\n\n\tif 400 <= r.StatusCode {\n\t\treturn 0, fmt.Errorf(\"error response: %s\", string(b))\n\t}\n\n\tvar result graphiteResponse\n\terr = json.Unmarshal(b, &result)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"error unmarshaling result: %w, '%s'\", err, string(b))\n\t}\n\n\tvar value *float64\n\tfor _, tr := range result {\n\t\tfor _, dp := range tr.DataPoints {\n\t\t\tif dp.Value != nil {\n\t\t\t\tvalue = dp.Value\n\t\t\t}\n\t\t}\n\t}\n\tif value == nil {\n\t\treturn 0, ErrNoValuesFound\n\t}\n\n\treturn *value, nil\n}", "func RunJSONSerializationTestForManagedClusters_AgentPool_Spec(subject ManagedClusters_AgentPool_Spec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusters_AgentPool_Spec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func renderCUETemplate(elem types.AddonElementFile, parameters string, args map[string]string) (*common2.ApplicationComponent, error) {\n\tbt, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar paramFile = cuemodel.ParameterFieldName + \": {}\"\n\tif string(bt) != \"null\" {\n\t\tparamFile = fmt.Sprintf(\"%s: %s\", cuemodel.ParameterFieldName, string(bt))\n\t}\n\tparam := fmt.Sprintf(\"%s\\n%s\", paramFile, parameters)\n\tv, err := value.NewValue(param, nil, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := v.LookupByScript(fmt.Sprintf(\"{%s}\", elem.Data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcompContent, err := out.LookupValue(\"output\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := cueyaml.Encode(compContent.CueValue())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcomp := common2.ApplicationComponent{\n\t\tName: strings.Join(append(elem.Path, elem.Name), \"-\"),\n\t}\n\terr = yaml.Unmarshal(b, &comp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &comp, err\n}", "func (gm *GraphicsManager) JsonCreate(id component.GOiD, compData []byte) error {\n\tobj := graphics.GraphicsComponent{}\n\terr := json.Unmarshal(compData, &obj)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal graphics component, error: %s\", err.Error())\n\t}\n\n\tgm.CreateComponent(id, obj)\n\n\treturn nil\n}", "func Jsonnet(service core.FileService, enabled bool) core.ConfigService {\n\treturn &jsonnetPlugin{\n\t\tenabled: enabled,\n\t\trepos: &repo{files: service},\n\t}\n}", "func ExprCmpDynamic(lzVars *base.Vars, labels base.Labels,\n\tparams []interface{}, path string, cmps []base.Val,\n\tcmpEQ base.Val, cmpEQOnly bool) (lzExprFunc base.ExprFunc) {\n\tcmpLT, cmpGT := cmps[0], cmps[1]\n\n\tvar lzCmpLT base.Val = cmpLT // <== varLift: lzCmpLT by path\n\tvar lzCmpEQ base.Val = cmpEQ // <== varLift: lzCmpEQ by path\n\tvar lzCmpGT base.Val = cmpGT // <== varLift: lzCmpGT by path\n\n\tbiExprFunc := func(lzA, lzB base.ExprFunc, lzVals base.Vals, lzYieldErr base.YieldErr) (lzVal base.Val) { // !lz\n\t\t_, _, _ = lzCmpLT, lzCmpEQ, lzCmpGT\n\n\t\tif LzScope {\n\t\t\tlzVal = lzA(lzVals, lzYieldErr) // <== emitCaptured: path \"A\"\n\n\t\t\tlzValA, lzTypeA := base.Parse(lzVal)\n\t\t\tif base.ParseTypeHasValue(lzTypeA) {\n\t\t\t\tlzVal = lzB(lzVals, lzYieldErr) // <== emitCaptured: path \"B\"\n\n\t\t\t\tlzValB, lzTypeB := base.Parse(lzVal)\n\t\t\t\tif base.ParseTypeHasValue(lzTypeB) {\n\t\t\t\t\tlzCmp := lzVars.Ctx.ValComparer.CompareWithType(\n\t\t\t\t\t\tlzValA, lzValB, lzTypeA, lzTypeB, 0)\n\t\t\t\t\tif lzCmp == 0 {\n\t\t\t\t\t\tlzVal = lzCmpEQ\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlzVal = lzCmpGT\n\t\t\t\t\t\tif !cmpEQOnly { // !lz\n\t\t\t\t\t\t\tif lzCmp < 0 {\n\t\t\t\t\t\t\t\tlzVal = lzCmpLT\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} // !lz\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lzVal\n\t} // !lz\n\n\tlzExprFunc =\n\t\tMakeBiExprFunc(lzVars, labels, params, path, biExprFunc) // !lz\n\n\treturn lzExprFunc\n}", "func marshalComponentRequestBodyToStorageComponent(v *ComponentRequestBody) *storage.Component {\n\tif v == nil {\n\t\treturn nil\n\t}\n\tres := &storage.Component{\n\t\tVarietal: v.Varietal,\n\t\tPercentage: v.Percentage,\n\t}\n\n\treturn res\n}", "func RunJSONSerializationTestForServers_VirtualNetworkRule_Spec(subject Servers_VirtualNetworkRule_Spec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual Servers_VirtualNetworkRule_Spec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (t *TestRuntime) GetDataWithInput(path string, input interface{}) ([]byte, error) {\n\tinputPayload := util.MustMarshalJSON(map[string]interface{}{\n\t\t\"input\": input,\n\t})\n\n\tpath = strings.TrimPrefix(path, \"/\")\n\tif !strings.HasPrefix(path, \"data\") {\n\t\tpath = \"data/\" + path\n\t}\n\n\tresp, err := t.GetDataWithRawInput(t.URL()+\"/v1/\"+path, bytes.NewReader(inputPayload))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := io.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected error reading response body: %s\", err)\n\t}\n\tresp.Close()\n\treturn body, nil\n}", "func renderRawComponent(elem types.AddonElementFile) (*common2.ApplicationComponent, error) {\n\tbaseRawComponent := common2.ApplicationComponent{\n\t\tType: \"raw\",\n\t\tName: strings.Join(append(elem.Path, elem.Name), \"-\"),\n\t}\n\tobj, err := renderObject(elem)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseRawComponent.Properties = util.Object2RawExtension(obj)\n\treturn &baseRawComponent, nil\n}", "func (*ConditionObjrefs) GetPath() string { return \"/api/objects/condition/objref/\" }", "func Read(vm *jsonnet.VM, path string) ([]runtime.Object, error) {\n\text := filepath.Ext(path)\n\tif ext == \".json\" {\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer f.Close()\n\t\treturn jsonReader(f)\n\t} else if ext == \".yaml\" {\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer f.Close()\n\t\treturn yamlReader(f)\n\t} else if ext == \".jsonnet\" {\n\t\treturn jsonnetReader(vm, path)\n\t}\n\n\treturn nil, fmt.Errorf(\"Unknown file extension: %s\", path)\n}", "func (r *Repository) ComponentsPath() string {\n\treturn dummyComponentPath\n}", "func JsonnetVM(cmd *cobra.Command) (*jsonnet.VM, error) {\n\tvm := jsonnet.Make()\n\tflags := cmd.Flags()\n\n\tjpath := os.Getenv(\"KUBECFG_JPATH\")\n\tfor _, p := range filepath.SplitList(jpath) {\n\t\tglog.V(2).Infoln(\"Adding jsonnet search path\", p)\n\t\tvm.JpathAdd(p)\n\t}\n\n\tjpath, err := flags.GetString(\"jpath\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, p := range filepath.SplitList(jpath) {\n\t\tglog.V(2).Infoln(\"Adding jsonnet search path\", p)\n\t\tvm.JpathAdd(p)\n\t}\n\n\treturn vm, nil\n}", "func Process(w http.ResponseWriter, r *http.Request, configPath string) {\n\tvar cr []aggregator.ComponentResponse\n\tvar components componentsList\n\n\tconfig := config.Parse(configPath)\n\tyaml.Unmarshal(config, &components)\n\n\tch = make(chan aggregator.ComponentResponse, len(components.Components))\n\n\tfor i, v := range components.Components {\n\t\twg.Add(1)\n\t\tgo getComponent(i, v)\n\t}\n\twg.Wait()\n\tclose(ch)\n\n\tfor component := range ch {\n\t\tcr = append(cr, component)\n\t}\n\n\tresponse, err := aggregator.Process(cr)\n\tif err != nil {\n\t\tfmt.Printf(\"There was an error aggregating a response: %s\", err.Error())\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(response)\n}", "func RunJSONSerializationTestForUrlPathMatchConditionParameters_STATUS(subject UrlPathMatchConditionParameters_STATUS) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual UrlPathMatchConditionParameters_STATUS\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}" ]
[ "0.6119853", "0.47705746", "0.47354072", "0.46243235", "0.45931298", "0.4567701", "0.45610455", "0.45374703", "0.45025703", "0.43760028", "0.4339587", "0.43366817", "0.42999598", "0.4297617", "0.4273561", "0.4254796", "0.42360145", "0.42228198", "0.42005682", "0.41736546", "0.41517466", "0.40808854", "0.4077454", "0.4072576", "0.40299582", "0.40055433", "0.40055433", "0.40055433", "0.40007722", "0.39933807", "0.3984514", "0.39804155", "0.39728805", "0.39343232", "0.3925781", "0.3920715", "0.3918482", "0.39163017", "0.3913441", "0.39131635", "0.39109868", "0.39079583", "0.39073348", "0.39042586", "0.38975018", "0.38962954", "0.38914463", "0.38901392", "0.38880306", "0.38805607", "0.38695878", "0.38599935", "0.38508764", "0.3847522", "0.3847522", "0.38472497", "0.38434973", "0.3842332", "0.38415912", "0.38380307", "0.38264036", "0.38229704", "0.38219035", "0.38201475", "0.38201475", "0.38167048", "0.38130802", "0.38108155", "0.38006306", "0.38000786", "0.37997362", "0.37987956", "0.37939638", "0.37936184", "0.3788396", "0.37867364", "0.37836084", "0.377424", "0.37652978", "0.3762576", "0.37606928", "0.3759514", "0.37502944", "0.37484947", "0.3747945", "0.37377465", "0.3735945", "0.37341788", "0.3728369", "0.37274444", "0.37210694", "0.3719959", "0.37158304", "0.37111482", "0.37110743", "0.37047973", "0.37017986", "0.37017548", "0.37005028", "0.36908263" ]
0.61542064
0
EvaluateComponentSnippet evaluates a component with jsonnet using a snippet.
func EvaluateComponentSnippet(a app.App, snippet, paramsStr, envName string, useMemoryImporter bool) (string, error) { libPath, err := a.LibPath(envName) if err != nil { return "", err } vm := jsonnet.NewVM() if useMemoryImporter { vm.Fs = a.Fs() vm.UseMemoryImporter = true } vm.JPaths = []string{ libPath, filepath.Join(a.Root(), "vendor"), } vm.ExtCode("__ksonnet/params", paramsStr) envDetails, err := a.Environment(envName) if err != nil { return "", err } dest := map[string]string{ "server": envDetails.Destination.Server, "namespace": envDetails.Destination.Namespace, } marshalledDestination, err := json.Marshal(&dest) if err != nil { return "", err } vm.ExtCode("__ksonnet/environments", string(marshalledDestination)) return vm.EvaluateSnippet("snippet", snippet) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func EvaluateComponent(a app.App, sourcePath, paramsStr, envName string, useMemoryImporter bool) (string, error) {\n\tsnippet, err := afero.ReadFile(a.Fs(), sourcePath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn EvaluateComponentSnippet(a, string(snippet), paramsStr, envName, useMemoryImporter)\n}", "func (vm *VM) EvaluateSnippet(filename string, snippet string) (json string, formattedErr error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tformattedErr = errors.New(vm.ef.format(fmt.Errorf(\"(CRASH) %v\\n%s\", r, debug.Stack())))\n\t\t}\n\t}()\n\tjson, err := vm.evaluateSnippet(filename, snippet)\n\tif err != nil {\n\t\treturn \"\", errors.New(vm.ef.format(err))\n\t}\n\treturn json, nil\n}", "func (cx *Context) Eval(source string, result interface{}) (err error) {\n\tcx.do(func(ptr *C.JSAPIContext) {\n\t\t// alloc C-string\n\t\tcsource := C.CString(source)\n\t\tdefer C.free(unsafe.Pointer(csource))\n\t\tvar jsonData *C.char\n\t\tvar jsonLen C.int\n\t\tfilename := \"eval\"\n\t\tcfilename := C.CString(filename)\n\t\tdefer C.free(unsafe.Pointer(cfilename))\n\t\t// eval\n\t\tif C.JSAPI_EvalJSON(ptr, csource, cfilename, &jsonData, &jsonLen) != C.JSAPI_OK {\n\t\t\terr = cx.getError(filename)\n\t\t\treturn\n\t\t}\n\t\tdefer C.free(unsafe.Pointer(jsonData))\n\t\t// convert to go\n\t\tb := []byte(C.GoStringN(jsonData, jsonLen))\n\t\tif raw, ok := result.(*Raw); ok {\n\t\t\t*raw = Raw(string(b))\n\t\t} else {\n\t\t\terr = json.Unmarshal(b, result)\n\t\t}\n\t})\n\treturn err\n}", "func jsonCodeBlock(value interface{}) string {\n\tblock, _ := json.MarshalIndent(value, \"\", \" \")\n\treturn fmt.Sprintf(\"```javascript\\n%s\\n```\", block)\n}", "func renderRawComponent(elem types.AddonElementFile) (*common2.ApplicationComponent, error) {\n\tbaseRawComponent := common2.ApplicationComponent{\n\t\tType: \"raw\",\n\t\tName: strings.Join(append(elem.Path, elem.Name), \"-\"),\n\t}\n\tobj, err := renderObject(elem)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseRawComponent.Properties = util.Object2RawExtension(obj)\n\treturn &baseRawComponent, nil\n}", "func RunJSONSerializationTestForManagedClusters_AgentPool_Spec(subject ManagedClusters_AgentPool_Spec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusters_AgentPool_Spec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func Snippet(value string) *SimpleElement { return newSEString(\"snippet\", value) }", "func RunJSONSerializationTestForLoadBalancers_InboundNatRule_Spec(subject LoadBalancers_InboundNatRule_Spec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual LoadBalancers_InboundNatRule_Spec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForAgentPoolNetworkProfile(subject AgentPoolNetworkProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual AgentPoolNetworkProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func EvaluateEnv(a app.App, sourcePath, paramsStr, envName string) (string, error) {\n\tlibPath, err := a.LibPath(envName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvm := jsonnet.NewVM()\n\n\tvm.JPaths = []string{\n\t\tlibPath,\n\t\tfilepath.Join(a.Root(), \"vendor\"),\n\t}\n\tvm.ExtCode(\"__ksonnet/params\", paramsStr)\n\n\tsnippet, err := afero.ReadFile(a.Fs(), sourcePath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn vm.EvaluateSnippet(sourcePath, string(snippet))\n}", "func Componentgen(nr, nl *Node) bool", "func (ecr *EnvComponentRemover) Remove(componentName, snippet string) (string, error) {\n\tif componentName == \"\" {\n\t\treturn \"\", errors.New(\"component name was blank\")\n\t}\n\n\tlogger := logrus.WithField(\"component-name\", componentName)\n\tlogger.Info(\"removing environment component\")\n\n\tn, err := jsonnet.ParseNode(\"params.libsonnet\", snippet)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tobj, err := componentParams(n, componentName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err = ecr.deleteEntry(obj, componentName); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"delete entry\")\n\t}\n\n\tvar buf bytes.Buffer\n\tif err = jsonnetPrinterFn(&buf, n); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to update snippet\")\n\t}\n\n\treturn buf.String(), nil\n}", "func RunJSONSerializationTestForExtendedLocation(subject ExtendedLocation) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ExtendedLocation\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForExtendedLocation(subject ExtendedLocation) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ExtendedLocation\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForExtendedLocation(subject ExtendedLocation) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ExtendedLocation\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForIpsecPolicy(subject IpsecPolicy) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual IpsecPolicy\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForContainerServiceNetworkProfile(subject ContainerServiceNetworkProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ContainerServiceNetworkProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForComponent_STATUS_ARM(subject Component_STATUS_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual Component_STATUS_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForNetworkProfile(subject NetworkProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual NetworkProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForKubeletConfig(subject KubeletConfig) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual KubeletConfig\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForInboundIpRule(subject InboundIpRule) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual InboundIpRule\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func renderCUETemplate(elem types.AddonElementFile, parameters string, args map[string]string) (*common2.ApplicationComponent, error) {\n\tbt, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar paramFile = cuemodel.ParameterFieldName + \": {}\"\n\tif string(bt) != \"null\" {\n\t\tparamFile = fmt.Sprintf(\"%s: %s\", cuemodel.ParameterFieldName, string(bt))\n\t}\n\tparam := fmt.Sprintf(\"%s\\n%s\", paramFile, parameters)\n\tv, err := value.NewValue(param, nil, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := v.LookupByScript(fmt.Sprintf(\"{%s}\", elem.Data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcompContent, err := out.LookupValue(\"output\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := cueyaml.Encode(compContent.CueValue())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcomp := common2.ApplicationComponent{\n\t\tName: strings.Join(append(elem.Path, elem.Name), \"-\"),\n\t}\n\terr = yaml.Unmarshal(b, &comp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &comp, err\n}", "func RunJSONSerializationTestForManagedCluster_Spec(subject ManagedCluster_Spec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedCluster_Spec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (l *Loader) EvaluateDependencies(c *ComponentNode) {\n\ttracer := l.tracer.Tracer(\"\")\n\n\tl.mut.RLock()\n\tdefer l.mut.RUnlock()\n\n\tl.cm.controllerEvaluation.Set(1)\n\tdefer l.cm.controllerEvaluation.Set(0)\n\tstart := time.Now()\n\n\tspanCtx, span := tracer.Start(context.Background(), \"GraphEvaluatePartial\", trace.WithSpanKind(trace.SpanKindInternal))\n\tspan.SetAttributes(attribute.String(\"initiator\", c.NodeID()))\n\tdefer span.End()\n\n\tlogger := log.With(l.log, \"trace_id\", span.SpanContext().TraceID())\n\tlevel.Info(logger).Log(\"msg\", \"starting partial graph evaluation\")\n\tdefer func() {\n\t\tspan.SetStatus(codes.Ok, \"\")\n\n\t\tduration := time.Since(start)\n\t\tlevel.Info(logger).Log(\"msg\", \"finished partial graph evaluation\", \"duration\", duration)\n\t\tl.cm.componentEvaluationTime.Observe(duration.Seconds())\n\t}()\n\n\t// Make sure we're in-sync with the current exports of c.\n\tl.cache.CacheExports(c.ID(), c.Exports())\n\n\t_ = dag.WalkReverse(l.graph, []dag.Node{c}, func(n dag.Node) error {\n\t\tif n == c {\n\t\t\t// Skip over the starting component; the starting component passed to\n\t\t\t// EvaluateDependencies had its exports changed and none of its input\n\t\t\t// arguments will need re-evaluation.\n\t\t\treturn nil\n\t\t}\n\n\t\t_, span := tracer.Start(spanCtx, \"EvaluateNode\", trace.WithSpanKind(trace.SpanKindInternal))\n\t\tspan.SetAttributes(attribute.String(\"node_id\", n.NodeID()))\n\t\tdefer span.End()\n\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\tlevel.Info(logger).Log(\"msg\", \"finished node evaluation\", \"node_id\", n.NodeID(), \"duration\", time.Since(start))\n\t\t}()\n\n\t\tvar err error\n\n\t\tswitch n := n.(type) {\n\t\tcase BlockNode:\n\t\t\terr = l.evaluate(logger, n)\n\t\t\tif exp, ok := n.(*ExportConfigNode); ok {\n\t\t\t\tl.cache.CacheModuleExportValue(exp.Label(), exp.Value())\n\t\t\t}\n\t\t}\n\n\t\t// We only use the error for updating the span status; we don't return the\n\t\t// error because we want to evaluate as many nodes as we can.\n\t\tif err != nil {\n\t\t\tspan.SetStatus(codes.Error, err.Error())\n\t\t} else {\n\t\t\tspan.SetStatus(codes.Ok, \"\")\n\t\t}\n\t\treturn nil\n\t})\n\n\tif l.globals.OnExportsChange != nil && l.cache.ExportChangeIndex() != l.moduleExportIndex {\n\t\tl.globals.OnExportsChange(l.cache.CreateModuleExports())\n\t\tl.moduleExportIndex = l.cache.ExportChangeIndex()\n\t}\n}", "func RunJSONSerializationTestForVaultCertificate(subject VaultCertificate) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual VaultCertificate\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForProfiles_Endpoint_Spec(subject Profiles_Endpoint_Spec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual Profiles_Endpoint_Spec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func EvaluateComponents(iq IQ, components []Component, applicationID string) (*Evaluation, error) {\n\trequest, err := json.Marshal(iqEvaluationRequest{Components: components})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not build the request: %v\", err)\n\t}\n\n\trequestEndpoint := fmt.Sprintf(restEvaluation, applicationID)\n\tbody, _, err := iq.Post(requestEndpoint, bytes.NewBuffer(request))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"components not evaluated: %v\", err)\n\t}\n\n\tvar results iqEvaluationRequestResponse\n\tif err = json.Unmarshal(body, &results); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not parse evaluation response: %v\", err)\n\t}\n\n\tgetEvaluationResults := func() (*Evaluation, error) {\n\t\tbody, resp, e := iq.Get(results.ResultsURL)\n\t\tif e != nil {\n\t\t\tif resp.StatusCode != http.StatusNotFound {\n\t\t\t\treturn nil, fmt.Errorf(\"could not retrieve evaluation results: %v\", err)\n\t\t\t}\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tvar ev Evaluation\n\t\tif err = json.Unmarshal(body, &ev); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &ev, nil\n\t}\n\n\tvar eval *Evaluation\n\tticker := time.NewTicker(5 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif eval, err = getEvaluationResults(); eval != nil || err != nil {\n\t\t\t\tticker.Stop()\n\t\t\t\treturn eval, err\n\t\t\t}\n\t\tcase <-time.After(5 * time.Minute):\n\t\t\tticker.Stop()\n\t\t\treturn nil, errors.New(\"timed out waiting for valid evaluation results\")\n\t\t}\n\t}\n}", "func RunTemplate(template []byte, input []byte) (interface{}, error) {\n\n\tvar data interface{}\n\tjson.Unmarshal(input, &data)\n\n\tv, err := jsonfilter.FilterJsonFromTextWithFilterRunner(string(template), string(template), func(command string, value string) (string, error) {\n\t\tfilterval, _ := jsonpath.Read(data, value)\n\t\t// fmt.Println(filterval)\n\t\tret := fmt.Sprintf(\"%v\", filterval)\n\t\treturn ret, nil\n\t})\n\n\treturn v, err\n\n}", "func RunJSONSerializationTestForManagedClusterAgentPoolProfile(subject ManagedClusterAgentPoolProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterAgentPoolProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForNatGateway_Spec_ARM(subject NatGateway_Spec_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual NatGateway_Spec_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (in *SampleIn) FetchComponent() *proIntegrator.Component {\n\tin.Component.Name = \"SampleIn\"\n\n\tmapParamIn := make(map[string]*proIntegrator.DataType)\n\tmapParamOut := make(map[string]*proIntegrator.DataType)\n\n\tmapParamIn[\"Param1\"] = &proIntegrator.DataType{Type: proIntegrator.DataType_STR}\n\tmapParamIn[\"Param2\"] = &proIntegrator.DataType{Type: proIntegrator.DataType_STR}\n\n\tmapParamOut[\"Param1\"] = &proIntegrator.DataType{Type: proIntegrator.DataType_STR}\n\tmapParamOut[\"Param2\"] = &proIntegrator.DataType{Type: proIntegrator.DataType_STR}\n\n\tin.Component.ParamsInput = mapParamIn\n\tin.Component.ParamsOutput = mapParamOut\n\treturn &in.Component\n}", "func RunJSONSerializationTestForManagedClusterNATGatewayProfile(subject ManagedClusterNATGatewayProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterNATGatewayProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForAdditionalUnattendContent(subject AdditionalUnattendContent) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual AdditionalUnattendContent\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForServers_VirtualNetworkRule_Spec(subject Servers_VirtualNetworkRule_Spec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual Servers_VirtualNetworkRule_Spec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForContainerServiceLinuxProfile(subject ContainerServiceLinuxProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ContainerServiceLinuxProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForCapability(subject Capability) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual Capability\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForAgentPoolWindowsProfile(subject AgentPoolWindowsProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual AgentPoolWindowsProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func templateFunctionSnippet(entry *registry.Entry) func(name string) (interface{}, error) {\n\treturn func(name string) (interface{}, error) {\n\t\tglog.V(log.LevelDebug).Infof(\"template: name '%s'\", name)\n\n\t\ttemplate, err := getTemplate(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttemplate, err = renderTemplate(template, entry, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar value interface{}\n\n\t\tif err := json.Unmarshal(template.Template.Raw, &value); err != nil {\n\t\t\treturn nil, errors.NewConfigurationError(\"template not JSON formatted: %v\", err)\n\t\t}\n\n\t\tglog.V(log.LevelDebug).Infof(\"template: value '%v'\", value)\n\n\t\treturn value, nil\n\t}\n}", "func RunJSONSerializationTestForDomain_Spec(subject Domain_Spec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual Domain_Spec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterSecurityProfileWorkloadIdentity(subject ManagedClusterSecurityProfileWorkloadIdentity) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterSecurityProfileWorkloadIdentity\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForUrlSigningParamIdentifier(subject UrlSigningParamIdentifier) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual UrlSigningParamIdentifier\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterAddonProfile(subject ManagedClusterAddonProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterAddonProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterOIDCIssuerProfile(subject ManagedClusterOIDCIssuerProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterOIDCIssuerProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func evaluate(node ast.Node, ext vmExtMap, tla vmExtMap, nativeFuncs map[string]*NativeFunction,\n\tmaxStack int, ic *importCache, traceOut io.Writer, stringOutputMode bool) (string, error) {\n\n\ti, err := buildInterpreter(ext, nativeFuncs, maxStack, ic, traceOut)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresult, err := evaluateAux(i, node, tla)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buf bytes.Buffer\n\ti.stack.setCurrentTrace(manifestationTrace())\n\tif stringOutputMode {\n\t\terr = i.manifestString(&buf, result)\n\t} else {\n\t\terr = i.manifestAndSerializeJSON(&buf, result, true, \"\")\n\t}\n\ti.stack.clearCurrentTrace()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf.WriteString(\"\\n\")\n\treturn buf.String(), nil\n}", "func RunJSONSerializationTestForManagedClusterOperatorSpec(subject ManagedClusterOperatorSpec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterOperatorSpec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (l *Loader) Apply(args map[string]any, componentBlocks []*ast.BlockStmt, configBlocks []*ast.BlockStmt) diag.Diagnostics {\n\tstart := time.Now()\n\tl.mut.Lock()\n\tdefer l.mut.Unlock()\n\tl.cm.controllerEvaluation.Set(1)\n\tdefer l.cm.controllerEvaluation.Set(0)\n\n\tfor key, value := range args {\n\t\tl.cache.CacheModuleArgument(key, value)\n\t}\n\tl.cache.SyncModuleArgs(args)\n\n\tnewGraph, diags := l.loadNewGraph(args, componentBlocks, configBlocks)\n\tif diags.HasErrors() {\n\t\treturn diags\n\t}\n\n\tvar (\n\t\tcomponents = make([]*ComponentNode, 0, len(componentBlocks))\n\t\tcomponentIDs = make([]ComponentID, 0, len(componentBlocks))\n\t\tservices = make([]*ServiceNode, 0, len(l.services))\n\t)\n\n\ttracer := l.tracer.Tracer(\"\")\n\tspanCtx, span := tracer.Start(context.Background(), \"GraphEvaluate\", trace.WithSpanKind(trace.SpanKindInternal))\n\tdefer span.End()\n\n\tlogger := log.With(l.log, \"trace_id\", span.SpanContext().TraceID())\n\tlevel.Info(logger).Log(\"msg\", \"starting complete graph evaluation\")\n\tdefer func() {\n\t\tspan.SetStatus(codes.Ok, \"\")\n\n\t\tduration := time.Since(start)\n\t\tlevel.Info(logger).Log(\"msg\", \"finished complete graph evaluation\", \"duration\", duration)\n\t\tl.cm.componentEvaluationTime.Observe(duration.Seconds())\n\t}()\n\n\tl.cache.ClearModuleExports()\n\n\t// Evaluate all the components.\n\t_ = dag.WalkTopological(&newGraph, newGraph.Leaves(), func(n dag.Node) error {\n\t\t_, span := tracer.Start(spanCtx, \"EvaluateNode\", trace.WithSpanKind(trace.SpanKindInternal))\n\t\tspan.SetAttributes(attribute.String(\"node_id\", n.NodeID()))\n\t\tdefer span.End()\n\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\tlevel.Info(logger).Log(\"msg\", \"finished node evaluation\", \"node_id\", n.NodeID(), \"duration\", time.Since(start))\n\t\t}()\n\n\t\tvar err error\n\n\t\tswitch n := n.(type) {\n\t\tcase *ComponentNode:\n\t\t\tcomponents = append(components, n)\n\t\t\tcomponentIDs = append(componentIDs, n.ID())\n\n\t\t\tif err = l.evaluate(logger, n); err != nil {\n\t\t\t\tvar evalDiags diag.Diagnostics\n\t\t\t\tif errors.As(err, &evalDiags) {\n\t\t\t\t\tdiags = append(diags, evalDiags...)\n\t\t\t\t} else {\n\t\t\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\t\t\tMessage: fmt.Sprintf(\"Failed to build component: %s\", err),\n\t\t\t\t\t\tStartPos: ast.StartPos(n.Block()).Position(),\n\t\t\t\t\t\tEndPos: ast.EndPos(n.Block()).Position(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase *ServiceNode:\n\t\t\tservices = append(services, n)\n\n\t\t\tif err = l.evaluate(logger, n); err != nil {\n\t\t\t\tvar evalDiags diag.Diagnostics\n\t\t\t\tif errors.As(err, &evalDiags) {\n\t\t\t\t\tdiags = append(diags, evalDiags...)\n\t\t\t\t} else {\n\t\t\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\t\t\tMessage: fmt.Sprintf(\"Failed to evaluate service: %s\", err),\n\t\t\t\t\t\tStartPos: ast.StartPos(n.Block()).Position(),\n\t\t\t\t\t\tEndPos: ast.EndPos(n.Block()).Position(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase BlockNode:\n\t\t\tif err = l.evaluate(logger, n); err != nil {\n\t\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\t\tMessage: fmt.Sprintf(\"Failed to evaluate node for config block: %s\", err),\n\t\t\t\t\tStartPos: ast.StartPos(n.Block()).Position(),\n\t\t\t\t\tEndPos: ast.EndPos(n.Block()).Position(),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif exp, ok := n.(*ExportConfigNode); ok {\n\t\t\t\tl.cache.CacheModuleExportValue(exp.Label(), exp.Value())\n\t\t\t}\n\t\t}\n\n\t\t// We only use the error for updating the span status; we don't return the\n\t\t// error because we want to evaluate as many nodes as we can.\n\t\tif err != nil {\n\t\t\tspan.SetStatus(codes.Error, err.Error())\n\t\t} else {\n\t\t\tspan.SetStatus(codes.Ok, \"\")\n\t\t}\n\t\treturn nil\n\t})\n\n\tl.componentNodes = components\n\tl.serviceNodes = services\n\tl.graph = &newGraph\n\tl.cache.SyncIDs(componentIDs)\n\tl.blocks = componentBlocks\n\tl.cm.componentEvaluationTime.Observe(time.Since(start).Seconds())\n\tif l.globals.OnExportsChange != nil && l.cache.ExportChangeIndex() != l.moduleExportIndex {\n\t\tl.moduleExportIndex = l.cache.ExportChangeIndex()\n\t\tl.globals.OnExportsChange(l.cache.CreateModuleExports())\n\t}\n\treturn diags\n}", "func TestRemoteComponent(t *testing.T) {\n\trunPolicyPackIntegrationTest(t, \"remote_component\", NodeJS, nil, []policyTestScenario{\n\t\t{\n\t\t\tWantErrors: []string{\n\t\t\t\t\"[advisory] remote-component-policy v0.0.1 resource-validation (random:index/randomString:RandomString: innerRandom)\",\n\t\t\t\t\"can't run policy 'resource-validation' during preview: string value at .keepers.hi can't be known during preview\",\n\t\t\t},\n\t\t\tAdvisory: true,\n\t\t},\n\t})\n}", "func RunJSONSerializationTestForLoadBalancersInboundNatRule(subject LoadBalancersInboundNatRule) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual LoadBalancersInboundNatRule\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForVirtualMachine_Spec(subject VirtualMachine_Spec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual VirtualMachine_Spec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForProfilesEndpoint(subject ProfilesEndpoint) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ProfilesEndpoint\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForNetwork_ARM(subject Network_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual Network_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForKeyVaultSecretReference(subject KeyVaultSecretReference) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual KeyVaultSecretReference\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClustersAgentPool(subject ManagedClustersAgentPool) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClustersAgentPool\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterStorageProfileSnapshotController(subject ManagedClusterStorageProfileSnapshotController) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterStorageProfileSnapshotController\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (s *Script) rawScriptSource(script string) (interface{}, error) {\n\tv := strings.TrimSpace(script)\n\tif !strings.HasPrefix(v, \"{\") && !strings.HasPrefix(v, `\"`) {\n\t\tv = fmt.Sprintf(\"%q\", v)\n\t}\n\traw := json.RawMessage(v)\n\treturn &raw, nil\n}", "func getComponentContent(name string, style string) string {\n\tstyleFile := fmt.Sprintf(\"%s.%s\", name, style)\n\tcomponentName := strings.ReplaceAll(name, \"-\", \" \")\n\tcomponentName = strings.Title(componentName)\n\tcomponentName = strings.ReplaceAll(componentName, \" \", \"\")\n\treturn fmt.Sprintf(\n\t\t`import React from \"react\";\nimport \"./%s\";\n\nconst %s = () => {\n\treturn <div className=\"%s\"></div>;\n}\n\nexport default %s;`, styleFile, componentName, name, componentName)\n}", "func RunJSONSerializationTestForNetworkInterface_Spec(subject NetworkInterface_Spec) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual NetworkInterface_Spec\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForIPTag(subject IPTag) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual IPTag\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForVpnClientRevokedCertificate(subject VpnClientRevokedCertificate) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual VpnClientRevokedCertificate\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForNatGatewayPropertiesFormat_ARM(subject NatGatewayPropertiesFormat_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual NatGatewayPropertiesFormat_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterStorageProfileFileCSIDriver(subject ManagedClusterStorageProfileFileCSIDriver) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterStorageProfileFileCSIDriver\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (c *Codegen) AddDefaultSnippets() {\n\t/* common props */\n\tc.AddSnippet(\"php\", \"<?php\")\n\tc.AddSnippet(\"path\", \"$_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__);\")\n\tc.AddSnippet(\"bxheader\", \"require_once($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_before.php');\")\n\n\t/* specially for iblock properties */\n\tc.AddSnippet(\"iblock\", \"\\\\Bitrix\\\\Main\\\\Loader::includeModule('iblock');\")\n\tc.AddSnippet(\"ibp_obj\", \"$ibp = new CIBlockProperty();\")\n\tc.AddSnippet(\"iblock_prop_st\", \"$prop = array(\")\n\tc.AddSnippet(\"iblock_prop_en\", \");\")\n\tc.AddSnippet(\"iblock_prop_run\", \"$r = $ibp->add($prop);\")\n\tc.AddSnippet(\"iblock_prop_check\", \"if ($r) { \"+c.LineBreak+c.Indent+\"echo 'Added prop with ID: ' . $r . PHP_EOL; \"+c.LineBreak+\"} else { \"+c.LineBreak+c.Indent+\"echo 'Error adding prop: ' . $ibp->LAST_ERROR . PHP_EOL; \"+c.LineBreak+\"}\")\n\n\t/* specially for user fields */\n\tc.AddSnippet(\"uf_obj\", \"$ufo = new CUserTypeEntity;\")\n\tc.AddSnippet(\"uf_data_st\", \"$uf = array(\")\n\tc.AddSnippet(\"uf_data_en\", \");\")\n\tc.AddSnippet(\"uf_data_run\", \"$r = $ufo->add($uf);\")\n\tc.AddSnippet(\"uf_data_check\", \"if ($r) { \"+c.LineBreak+c.Indent+\"echo 'Added UserField with ID: ' . $r . PHP_EOL; \"+c.LineBreak+\"} else { \"+c.LineBreak+c.Indent+\"echo 'Error adding UserField: ' . $ufo->LAST_ERROR . PHP_EOL; \"+c.LineBreak+\"}\")\n\t// TODO - no LAST_ERROR here, catch exception?\n\n\t/* specially for mail event/template */\n\tc.AddSnippet(\"mevent_obj\", \"$meo = new CEventType;\")\n\tc.AddSnippet(\"mevent_data_st\", \"$me = array(\")\n\tc.AddSnippet(\"mevent_data_en\", \");\")\n\tc.AddSnippet(\"mevent_run\", \"$r = $meo->add($me);\")\n\tc.AddSnippet(\"mevent_run_succ_wo_mm\", \"if ($r) { \"+c.LineBreak+c.Indent+\"echo 'Added MailEvent with ID: ' . $r . PHP_EOL; \"+c.LineBreak+\"} else { \"+c.LineBreak+c.Indent+\"echo 'Error adding MailEvent: ' . $meo->LAST_ERROR . PHP_EOL; \"+c.LineBreak+\"}\")\n\tc.AddSnippet(\"mevent_run_check\", \"if ($r) {\")\n\tc.AddSnippet(\"mevent_run_check_else\", \"} else {\"+c.LineBreak+c.Indent+\"echo 'Error adding MailEvent: ' . $meo->LAST_ERROR . PHP_EOL; \"+c.LineBreak+\"}\")\n\tc.AddSnippet(\"mevent_succ\", c.Indent+\"echo 'Added MailEvent with ID: ' . $r . PHP_EOL;\"+c.LineBreak)\n\n\tc.AddSnippet(\"mtpl_warn\", c.Indent+\"// TODO - set proper LID for template!\")\n\tc.AddSnippet(\"mtpl_obj\", \"$mmo = new CEventMessage;\")\n\tc.AddSnippet(\"mtpl_data_st\", \"$mm = array(\")\n\tc.AddSnippet(\"mtpl_data_en\", \");\")\n\tc.AddSnippet(\"mtpl_run\", \"$r = $mmo->add($mm);\")\n\tc.AddSnippet(\"mtpl_run_check\", c.Indent+\"if ($r) {\"+c.LineBreak+c.Indent+c.Indent+\"echo 'Added MailTemplate with ID: ' . $r . PHP_EOL;\"+c.LineBreak+c.Indent+\"} else {\"+c.LineBreak+c.Indent+c.Indent+\"echo 'Error adding MailTemplate: ' . $mmo->LAST_ERROR . PHP_EOL;\"+c.LineBreak+c.Indent+\"}\")\n\n\t/* common, group 2 */\n\tc.AddSnippet(\"done\", \"echo 'Done!' . PHP_EOL;\")\n}", "func (l *Loader) populateComponentNodes(g *dag.Graph, componentBlocks []*ast.BlockStmt) diag.Diagnostics {\n\tvar (\n\t\tdiags diag.Diagnostics\n\t\tblockMap = make(map[string]*ast.BlockStmt, len(componentBlocks))\n\t)\n\tfor _, block := range componentBlocks {\n\t\tvar c *ComponentNode\n\t\tid := BlockComponentID(block).String()\n\n\t\tif orig, redefined := blockMap[id]; redefined {\n\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\tMessage: fmt.Sprintf(\"Component %s already declared at %s\", id, ast.StartPos(orig).Position()),\n\t\t\t\tStartPos: block.NamePos.Position(),\n\t\t\t\tEndPos: block.NamePos.Add(len(id) - 1).Position(),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tblockMap[id] = block\n\n\t\t// Check the graph from the previous call to Load to see we can copy an\n\t\t// existing instance of ComponentNode.\n\t\tif exist := l.graph.GetByID(id); exist != nil {\n\t\t\tc = exist.(*ComponentNode)\n\t\t\tc.UpdateBlock(block)\n\t\t} else {\n\t\t\tcomponentName := block.GetBlockName()\n\t\t\tregistration, exists := l.componentReg.Get(componentName)\n\t\t\tif !exists {\n\t\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\t\tMessage: fmt.Sprintf(\"Unrecognized component name %q\", componentName),\n\t\t\t\t\tStartPos: block.NamePos.Position(),\n\t\t\t\t\tEndPos: block.NamePos.Add(len(componentName) - 1).Position(),\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif registration.Singleton && block.Label != \"\" {\n\t\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\t\tMessage: fmt.Sprintf(\"Component %q does not support labels\", componentName),\n\t\t\t\t\tStartPos: block.LabelPos.Position(),\n\t\t\t\t\tEndPos: block.LabelPos.Add(len(block.Label) + 1).Position(),\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !registration.Singleton && block.Label == \"\" {\n\t\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\t\tMessage: fmt.Sprintf(\"Component %q must have a label\", componentName),\n\t\t\t\t\tStartPos: block.NamePos.Position(),\n\t\t\t\t\tEndPos: block.NamePos.Add(len(componentName) - 1).Position(),\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif registration.Singleton && l.isModule() {\n\t\t\t\tdiags.Add(diag.Diagnostic{\n\t\t\t\t\tSeverity: diag.SeverityLevelError,\n\t\t\t\t\tMessage: fmt.Sprintf(\"Component %q is a singleton and unsupported inside a module\", componentName),\n\t\t\t\t\tStartPos: block.NamePos.Position(),\n\t\t\t\t\tEndPos: block.NamePos.Add(len(componentName) - 1).Position(),\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Create a new component\n\t\t\tc = NewComponentNode(l.globals, registration, block)\n\t\t}\n\n\t\tg.Add(c)\n\t}\n\n\treturn diags\n}", "func RunJSONSerializationTestForManagedClusterSKU(subject ManagedClusterSKU) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterSKU\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterWindowsProfile(subject ManagedClusterWindowsProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterWindowsProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForPowerState(subject PowerState) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual PowerState\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForResourceReference(subject ResourceReference) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ResourceReference\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForResourceReference(subject ResourceReference) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ResourceReference\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func ParseApplicationComponent(jsn string) (acomp v1alpha1.Component, err error) {\n\terr = json.Unmarshal([]byte(jsn), &acomp)\n\treturn\n}", "func Render(comp Component, container *js.Object) {\n\tcomp.Reconcile(nil)\n\tcontainer.Call(\"appendChild\", comp.Node())\n}", "func RunJSONSerializationTestForImageReference(subject ImageReference) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ImageReference\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForVpnClientConfiguration(subject VpnClientConfiguration) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual VpnClientConfiguration\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (opa *client) EvaluatePolicy(policy string, input []byte) (*EvaluatePolicyResponse, error) {\n\tlog := opa.logger.Named(\"Evalute Policy\")\n\n\trequest, err := json.Marshal(&EvalutePolicyRequest{Input: input})\n\tif err != nil {\n\t\tlog.Error(\"failed to encode OPA input\", zap.Error(err), zap.String(\"input\", string(input)))\n\t\treturn nil, fmt.Errorf(\"failed to encode OPA input: %s\", err)\n\t}\n\n\thttpResponse, err := opa.httpClient.Post(opa.getDataQueryURL(getOpaPackagePath(policy)), \"application/json\", bytes.NewReader(request))\n\tif err != nil {\n\t\tlog.Error(\"http request to OPA failed\", zap.Error(err))\n\t\treturn nil, fmt.Errorf(\"http request to OPA failed: %s\", err)\n\t}\n\tif httpResponse.StatusCode != http.StatusOK {\n\t\tlog.Error(\"http response status from OPA not OK\", zap.Any(\"status\", httpResponse.Status))\n\t\treturn nil, fmt.Errorf(\"http response status not OK\")\n\t}\n\n\tresponse := &EvaluatePolicyResponse{}\n\terr = json.NewDecoder(httpResponse.Body).Decode(&response)\n\tif err != nil {\n\t\tlog.Error(\"failed to decode OPA result\", zap.Error(err))\n\t\treturn nil, fmt.Errorf(\"failed to decode OPA result: %s\", err)\n\t}\n\n\treturn response, nil\n}", "func RunJSONSerializationTestForUrlSigningParamIdentifier_ARM(subject UrlSigningParamIdentifier_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual UrlSigningParamIdentifier_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterLoadBalancerProfile(subject ManagedClusterLoadBalancerProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterLoadBalancerProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForNetworkInterface_Spec_ARM(subject NetworkInterface_Spec_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual NetworkInterface_Spec_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func TestCSharpCompat(t *testing.T) {\n\tjs := `{\n \"store\": {\n \"book\": [\n {\n \"category\": \"reference\",\n \"author\": \"Nigel Rees\",\n \"title\": \"Sayings of the Century\",\n \"price\": 8.95\n },\n {\n \"category\": \"fiction\",\n \"author\": \"Evelyn Waugh\",\n \"title\": \"Sword of Honour\",\n \"price\": 12.99\n },\n {\n \"category\": \"fiction\",\n \"author\": \"Herman Melville\",\n \"title\": \"Moby Dick\",\n \"isbn\": \"0-553-21311-3\",\n \"price\": 8.99\n },\n {\n \"category\": \"fiction\",\n \"author\": \"J. R. R. Tolkien\",\n \"title\": \"The Lord of the Rings\",\n \"isbn\": \"0-395-19395-8\",\n \"price\": null\n }\n ],\n \"bicycle\": {\n \"color\": \"red\",\n \"price\": 19.95\n }\n },\n \"expensive\": 10,\n \"data\": null\n}`\n\n\ttestCases := []pathTestCase{\n\t\t{\"$.store.book[*].author\", `[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]`},\n\t\t{\"$..author\", `[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]`},\n\t\t{\"$.store.*\", `[[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":null}],{\"color\":\"red\",\"price\":19.95}]`},\n\t\t{\"$.store..price\", `[19.95,8.95,12.99,8.99,null]`},\n\t\t{\"$..book[2]\", `[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]`},\n\t\t{\"$..book[-2]\", `[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99}]`},\n\t\t{\"$..book[0,1]\", `[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}]`},\n\t\t{\"$..book[:2]\", `[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}]`},\n\t\t{\"$..book[1:2]\", `[{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}]`},\n\t\t{\"$..book[-2:]\", `[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":null}]`},\n\t\t{\"$..book[2:]\", `[{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":null}]`},\n\t\t{\"\", `[{\"store\":{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":null}],\"bicycle\":{\"color\":\"red\",\"price\":19.95}},\"expensive\":10,\"data\":null}]`},\n\t\t{\"$.*\", `[{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99},{\"category\":\"fiction\",\"author\":\"Herman Melville\",\"title\":\"Moby Dick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},{\"category\":\"fiction\",\"author\":\"J. R. R. Tolkien\",\"title\":\"The Lord of the Rings\",\"isbn\":\"0-395-19395-8\",\"price\":null}],\"bicycle\":{\"color\":\"red\",\"price\":19.95}},10,null]`},\n\t\t{\"$..invalidfield\", `[]`},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.path, func(t *testing.T) {\n\t\t\ttc.testUnmarshalGet(t, js)\n\t\t})\n\t}\n\n\tt.Run(\"bad cases\", func(t *testing.T) {\n\t\t_, ok := unmarshalGet(t, js, `$..book[*].author\"`)\n\t\trequire.False(t, ok)\n\t})\n}", "func RunJSONSerializationTestForManagedClusterPodIdentityProfile(subject ManagedClusterPodIdentityProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterPodIdentityProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterManagedOutboundIPProfile(subject ManagedClusterManagedOutboundIPProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterManagedOutboundIPProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForAgentPoolNetworkProfile_STATUS(subject AgentPoolNetworkProfile_STATUS) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual AgentPoolNetworkProfile_STATUS\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForApplicationInsightsComponentProperties_STATUS_ARM(subject ApplicationInsightsComponentProperties_STATUS_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ApplicationInsightsComponentProperties_STATUS_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterSecurityProfile(subject ManagedClusterSecurityProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterSecurityProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForProfiles_Endpoint_Spec_ARM(subject Profiles_Endpoint_Spec_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual Profiles_Endpoint_Spec_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func generatePerNodeConfigSnippet(pathStructName string, nodeData *ypathgen.NodeData, fakeRootTypeName, schemaStructPkgAccessor string, preferShadowPath bool) (GoPerNodeCodeSnippet, goTypeData, util.Errors) {\n\t// TODO: See if a float32 -> binary helper should be provided\n\t// for setting a float32 leaf.\n\tvar errs util.Errors\n\ts := struct {\n\t\tPathStructName string\n\t\tGoType goTypeData\n\t\tGoFieldName string\n\t\tGoStructTypeName string\n\t\tYANGPath string\n\t\tFakeRootTypeName string\n\t\tIsScalarField bool\n\t\tIsRoot bool\n\t\tSchemaStructPkgAccessor string\n\t\tWildcardSuffix string\n\t\tSpecialConversionFn string\n\t\tPreferShadowPath bool\n\t}{\n\t\tPathStructName: pathStructName,\n\t\tGoType: goTypeData{\n\t\t\tGoTypeName: nodeData.GoTypeName,\n\t\t\tTransformedGoTypeName: transformGoTypeName(nodeData),\n\t\t\tIsLeaf: nodeData.IsLeaf,\n\t\t\tHasDefault: nodeData.HasDefault,\n\t\t},\n\t\tGoFieldName: nodeData.GoFieldName,\n\t\tGoStructTypeName: nodeData.SubsumingGoStructName,\n\t\tYANGPath: nodeData.YANGPath,\n\t\tFakeRootTypeName: fakeRootTypeName,\n\t\tIsScalarField: nodeData.IsScalarField,\n\t\tIsRoot: nodeData.YANGPath == \"/\",\n\t\tWildcardSuffix: ypathgen.WildcardSuffix,\n\t\tSchemaStructPkgAccessor: schemaStructPkgAccessor,\n\t\tPreferShadowPath: preferShadowPath,\n\t}\n\tvar getMethod, replaceMethod, convertHelper strings.Builder\n\tif nodeData.IsLeaf {\n\t\t// Leaf types use their parent GoStruct to unmarshal, before\n\t\t// being retrieved out when returned to the user.\n\t\tif err := goLeafConvertTemplate.Execute(&convertHelper, s); err != nil {\n\t\t\tutil.AppendErr(errs, err)\n\t\t}\n\t}\n\tif err := goNodeSetTemplate.Execute(&replaceMethod, s); err != nil {\n\t\tutil.AppendErr(errs, err)\n\t}\n\tif err := goNodeGetTemplate.Execute(&getMethod, s); err != nil {\n\t\tutil.AppendErr(errs, err)\n\t}\n\n\treturn GoPerNodeCodeSnippet{\n\t\tPathStructName: pathStructName,\n\t\tGetMethod: getMethod.String(),\n\t\tConvertHelper: convertHelper.String(),\n\t\tReplaceMethod: replaceMethod.String(),\n\t}, s.GoType, errs\n}", "func RunJSONSerializationTestForEndpointProperties_ARM(subject EndpointProperties_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual EndpointProperties_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForVirtualMachineNetworkInterfaceIPConfiguration(subject VirtualMachineNetworkInterfaceIPConfiguration) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual VirtualMachineNetworkInterfaceIPConfiguration\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterWorkloadAutoScalerProfile(subject ManagedClusterWorkloadAutoScalerProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterWorkloadAutoScalerProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForProfile_Spec_ARM(subject Profile_Spec_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual Profile_Spec_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterLoadBalancerProfile_OutboundIPs(subject ManagedClusterLoadBalancerProfile_OutboundIPs) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterLoadBalancerProfile_OutboundIPs\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForAdditionalCapabilities(subject AdditionalCapabilities) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual AdditionalCapabilities\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForFailoverGroupReadOnlyEndpoint(subject FailoverGroupReadOnlyEndpoint) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual FailoverGroupReadOnlyEndpoint\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForSearchService_Spec_ARM(subject SearchService_Spec_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual SearchService_Spec_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForNetworkInterfacePropertiesFormat_ARM(subject NetworkInterfacePropertiesFormat_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual NetworkInterfacePropertiesFormat_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForManagedClusterOperatorSecrets(subject ManagedClusterOperatorSecrets) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagedClusterOperatorSecrets\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (p *Parser) Load(filename string) (string, error) {\n\tdirectory := filepath.Dir(filename)\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvm := jsonnet.MakeVM()\n\tvm.Importer(&jsonnet.FileImporter{\n\t\tJPaths: []string{directory},\n\t})\n\n\treturn vm.EvaluateAnonymousSnippet(filename, string(data))\n}", "func (c *Codegen) AddSnippet(key, value string) {\n\tc.phpSnippets[key] = value\n}", "func TestConstructPlainGo(t *testing.T) {\n\ttests := []struct {\n\t\tcomponentDir string\n\t\texpectedResourceCount int\n\t\tenv []string\n\t}{\n\t\t{\n\t\t\tcomponentDir: \"testcomponent\",\n\t\t\texpectedResourceCount: 9,\n\t\t\t// TODO[pulumi/pulumi#5455]: Dynamic providers fail to load when used from multi-lang components.\n\t\t\t// Until we've addressed this, set PULUMI_TEST_YARN_LINK_PULUMI, which tells the integration test\n\t\t\t// module to run `yarn install && yarn link @pulumi/pulumi` in the Go program's directory, allowing\n\t\t\t// the Node.js dynamic provider plugin to load.\n\t\t\t// When the underlying issue has been fixed, the use of this environment variable inside the integration\n\t\t\t// test module should be removed.\n\t\t\tenv: []string{\"PULUMI_TEST_YARN_LINK_PULUMI=true\"},\n\t\t},\n\t\t{\n\t\t\tcomponentDir: \"testcomponent-python\",\n\t\t\texpectedResourceCount: 9,\n\t\t\tenv: []string{pulumiRuntimeVirtualEnv(t, filepath.Join(\"..\", \"..\"))},\n\t\t},\n\t\t{\n\t\t\tcomponentDir: \"testcomponent-go\",\n\t\t\texpectedResourceCount: 8, // One less because no dynamic provider.\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.componentDir, func(t *testing.T) {\n\t\t\tpathEnv := pathEnv(t, filepath.Join(\"construct_component_plain\", test.componentDir))\n\t\t\tintegration.ProgramTest(t,\n\t\t\t\toptsForConstructPlainGo(t, test.expectedResourceCount, append(test.env, pathEnv)...))\n\t\t})\n\t}\n}", "func evaluateAst(program *ast.RootNode) object.Object {\n\tenv := object.NewEnvironment()\n\treturn evaluator.Eval(program, env)\n}", "func RunJSONSerializationTestForContainerServiceNetworkProfile_STATUS(subject ContainerServiceNetworkProfile_STATUS) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ContainerServiceNetworkProfile_STATUS\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func RunJSONSerializationTestForHardwareProfile(subject HardwareProfile) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual HardwareProfile\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}" ]
[ "0.6018792", "0.5632424", "0.448362", "0.4453841", "0.43523085", "0.43367103", "0.42906657", "0.42196247", "0.42056364", "0.419578", "0.41669178", "0.4136577", "0.4100212", "0.4100212", "0.4100212", "0.40901154", "0.40751195", "0.40624303", "0.40336677", "0.4032413", "0.40148476", "0.4005937", "0.40048996", "0.40017948", "0.39676642", "0.3966732", "0.39613116", "0.39562455", "0.39369887", "0.39339995", "0.39264905", "0.39227432", "0.39216796", "0.3915142", "0.390602", "0.38871023", "0.38829404", "0.38703528", "0.3870308", "0.38615695", "0.38598156", "0.38577735", "0.38569838", "0.38564745", "0.38560942", "0.38530016", "0.38443363", "0.3840074", "0.38186496", "0.38124526", "0.3807272", "0.37960362", "0.3789595", "0.37885532", "0.37860203", "0.3777633", "0.37747455", "0.3771837", "0.37686276", "0.37654698", "0.3762925", "0.3757735", "0.37542987", "0.37514305", "0.3741917", "0.37416518", "0.3738901", "0.3738901", "0.37358877", "0.37295392", "0.37287024", "0.37278968", "0.37262818", "0.37242624", "0.37215602", "0.37182292", "0.3717205", "0.37169397", "0.37115824", "0.3711554", "0.3702625", "0.3700985", "0.37000218", "0.36971915", "0.3695241", "0.36944655", "0.36940175", "0.36936027", "0.3691283", "0.36905685", "0.36877945", "0.3686932", "0.36793214", "0.36780158", "0.3673183", "0.36706612", "0.3661111", "0.36606506", "0.36542553", "0.36492112" ]
0.8140482
0
Get returns latest metrics from singleton
func Get() []Metric { singleton.mu.Lock() hosts := singleton.hosts singleton.mu.Unlock() return hosts }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *singleLhcNodeHarness) getMetrics() *metrics {\n\treturn &metrics{\n\t\ttimeSinceLastCommitMillis: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.TimeSinceLastCommit.Millis\").(*metric.Histogram),\n\t\ttimeSinceLastElectionMillis: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.TimeSinceLastElection.Millis\").(*metric.Histogram),\n\t\tcurrentElectionCount: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.CurrentElection.Number\").(*metric.Gauge),\n\t\tcurrentLeaderMemberId: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.CurrentLeaderMemberId.Number\").(*metric.Text),\n\t\tlastCommittedTime: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.LastCommitted.TimeNano\").(*metric.Gauge),\n\t}\n}", "func (s SolrPlugin) FetchMetrics() (map[string]interface{}, error) {\n\tstat := make(map[string]interface{})\n\tfor core, stats := range s.Stats {\n\t\tfor k, v := range stats {\n\t\t\tstat[core+\"_\"+k] = v\n\t\t}\n\t}\n\treturn stat, nil\n}", "func (e Entry) GetMetrics(timeout time.Duration, h heimdall.Doer, debug bool) (Metrics, error) {\n\tvar m Metrics\n\n\t// Let's set the stuff we know already.\n\tm.Address = e.Address\n\tm.Regexp = e.Regexp\n\tm.CapturedAt = time.Now().UTC()\n\n\t// Set a timeout.\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\t// Setup the request.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, e.Address, nil)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\tif debug {\n\t\tfmt.Printf(\"%#v\\n\", req)\n\t}\n\n\t// Let's do the request.\n\tstart := time.Now()\n\tres, err := h.Do(req)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\t// We don't need the body unless we've got a regexp.\n\tif e.Regexp != \"\" {\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\t// Do the regexp here and assign the value.\n\t\tmatch, _ := regexp.MatchString(e.Regexp, string(body))\n\t\tm.RegexpStatus = match\n\t}\n\ttook := time.Since(start)\n\n\t// Set the last few values\n\tm.StatusCode = res.StatusCode\n\tm.ResponseTime = took\n\n\tif debug {\n\t\tfmt.Printf(\"Result: %#v\\n\", res)\n\t\tfmt.Printf(\"Time Taken: %s\\n\", took)\n\t\tfmt.Printf(\"Metrics: %#v\\n\", m)\n\t}\n\n\tif ctx.Err() != nil {\n\t\treturn m, errors.New(\"context deadline exceeded\")\n\t}\n\treturn m, nil\n}", "func (ms *metricsStore) getMetricData(currentTime time.Time) pmetric.Metrics {\n\tms.RLock()\n\tdefer ms.RUnlock()\n\n\tout := pmetric.NewMetrics()\n\tfor _, mds := range ms.metricsCache {\n\t\tfor i := range mds {\n\t\t\t// Set datapoint timestamp to be time of retrieval from cache.\n\t\t\tapplyCurrentTime(mds[i].Metrics, currentTime)\n\t\t\tinternaldata.OCToMetrics(mds[i].Node, mds[i].Resource, mds[i].Metrics).ResourceMetrics().MoveAndAppendTo(out.ResourceMetrics())\n\t\t}\n\t}\n\n\treturn out\n}", "func (m Plugin) FetchMetrics() (map[string]float64, error) {\n\tresp, err := http.Get(fmt.Sprintf(\"http://%s/stats\", m.Target))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tstats := struct {\n\t\tConnections float64 `json:\"connections\"`\n\t\tTotalConnections float64 `json:\"total_connections\"`\n\t\tTotalMessages float64 `json:\"total_messages\"`\n\t\tConnectErrors float64 `json:\"connect_errors\"`\n\t\tMessageErrors float64 `json:\"message_errors\"`\n\t\tClosingConnections float64 `json:\"closing_connections\"`\n\t}{}\n\tif err := json.NewDecoder(resp.Body).Decode(&stats); err != nil {\n\t\treturn nil, err\n\t}\n\tret := make(map[string]float64, 6)\n\tret[\"conn_current\"] = stats.Connections\n\tret[\"conn_total\"] = stats.TotalConnections\n\tret[\"conn_errors\"] = stats.ConnectErrors\n\tret[\"conn_closing\"] = stats.ClosingConnections\n\tret[\"messages_total\"] = stats.TotalMessages\n\tret[\"messages_errors\"] = stats.MessageErrors\n\n\treturn ret, nil\n}", "func (m RedisPlugin) FetchMetrics() (map[string]interface{}, error) {\n\n\tpubClient := redis.NewClient(&m.PubRedisOpt)\n\tsubClient := redis.NewClient(&m.SubRedisOpt)\n\n\tsubscribe, err := subClient.Subscribe(m.ChannelName)\n\tif err != nil {\n\t\tlogger.Errorf(\"Failed to subscribe. %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer subscribe.Close()\n\tif _, err := pubClient.Publish(m.ChannelName, m.Message).Result(); err != nil {\n\t\tlogger.Errorf(\"Failed to publish. %s\", err)\n\t\treturn nil, err\n\t}\n\tstart := time.Now()\n\tif _, err := subscribe.ReceiveMessage(); err != nil {\n\t\tlogger.Infof(\"Failed to calculate capacity. (The cause may be that AWS Elasticache Redis has no `CONFIG` command.) Skip these metrics. %s\", err)\n\t\treturn nil, err\n\t}\n\tduration := time.Now().Sub(start)\n\n\treturn map[string]interface{}{m.metricName(): float64(duration) / float64(time.Microsecond)}, nil\n\n}", "func (s *Postgres) Get(filter Filter) ([]Metric, error) {\n\tmetrics := make([]Metric, 0)\n\n\terr := s.db.Model(&metrics).\n\t\tWhere(\"created_at >= ?\", filter.Since).\n\t\tWhere(\"name = ?\", filter.Name).\n\t\tSelect(&metrics)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get metrics %s\", filter)\n\t}\n\treturn metrics, nil\n}", "func (p ECachePlugin) FetchMetrics() (map[string]float64, error) {\n\tsess, err := session.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := aws.NewConfig()\n\tif p.AccessKeyID != \"\" && p.SecretAccessKey != \"\" {\n\t\tconfig = config.WithCredentials(credentials.NewStaticCredentials(p.AccessKeyID, p.SecretAccessKey, \"\"))\n\t}\n\tif p.Region != \"\" {\n\t\tconfig = config.WithRegion(p.Region)\n\t}\n\n\tcloudWatch := cloudwatch.New(sess, config)\n\n\tstat := make(map[string]float64)\n\n\tperInstances := []*cloudwatch.Dimension{\n\t\t{\n\t\t\tName: aws.String(\"CacheClusterId\"),\n\t\t\tValue: aws.String(p.CacheClusterID),\n\t\t},\n\t\t{\n\t\t\tName: aws.String(\"CacheNodeId\"),\n\t\t\tValue: aws.String(p.CacheNodeID),\n\t\t},\n\t}\n\n\tfor _, met := range p.CacheMetrics {\n\t\tv, err := getLastPoint(cloudWatch, perInstances, met)\n\t\tif err == nil {\n\t\t\tstat[met] = v\n\t\t} else {\n\t\t\tlog.Printf(\"%s: %s\", met, err)\n\t\t}\n\t}\n\n\treturn stat, nil\n}", "func getMetrics() []Metric {\n\tms := make([]Metric, 0)\n\treturn append(ms, &SimpleEapMetric{})\n}", "func (h *History) Compute() *Metrics {\n h.RLock()\n defer h.RUnlock()\n return h.compute()\n}", "func (c Configuration) metrics() (*pkg.Metrics, error) {\n\tMetricsInitialised.Once.Do(func() {\n\t\tlogger := zerolog.New(os.Stderr).Level(zerolog.DebugLevel)\n\t\tmetrics := &pkg.Metrics{\n\t\t\tGraphiteHost: c.MetricsConfig.GraphiteHost,\n\t\t\tNamespace: c.MetricsConfig.NameSpace,\n\t\t\tGraphiteMode: c.MetricsConfig.GraphiteMode,\n\t\t\tMetricsInterval: c.MetricsConfig.CollectionInterval,\n\t\t\tLogger: logger,\n\t\t}\n\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\tMetricsInitialised.metrics, MetricsInitialised.err = nil, err\n\t\t\treturn\n\t\t}\n\t\tmetrics.Hostname = hostname\n\n\t\t// determine server Role name\n\t\tif c.MetricsConfig.HostRolePath != \"\" {\n\t\t\tfile, err := os.Open(c.MetricsConfig.HostRolePath)\n\t\t\tif err != nil {\n\t\t\t\tMetricsInitialised.metrics, MetricsInitialised.err = nil, err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tscanner := bufio.NewScanner(file)\n\t\t\tfor scanner.Scan() {\n\t\t\t\ttokens := strings.Split(scanner.Text(), c.MetricsConfig.HostRoleToken)\n\t\t\t\tif len(tokens) < puppetFileColumnCount {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif tokens[0] == c.MetricsConfig.HostRoleKey {\n\t\t\t\t\tmetrics.RoleName = tokens[1]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err = file.Close(); err != nil {\n\t\t\t\tlogger.Error().Err(err)\n\t\t\t\tMetricsInitialised.metrics, MetricsInitialised.err = nil, err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tmetrics.EveryHourRegister = goMetrics.NewPrefixedRegistry(metrics.Namespace)\n\t\tmetrics.EveryMinuteRegister = goMetrics.NewPrefixedRegistry(metrics.Namespace)\n\n\t\tMetricsInitialised.metrics, MetricsInitialised.err = metrics, nil\n\t})\n\n\treturn MetricsInitialised.metrics, MetricsInitialised.err\n}", "func Metrics() (*statsd.Client, error) {\n\tonce.Do(func() {\n\t\tmetricsClientConf := config.Metrics()\n\t\tif !metricsClientConf.Enabled {\n\t\t\terr = errors.New(\"metrics collection has been disabled\")\n\t\t\tlog.Error(err)\n\t\t\tinstance = nil\n\t\t} else {\n\t\t\tconn := fmt.Sprintf(\"%s:%d\", metricsClientConf.Host, metricsClientConf.Port)\n\t\t\tinstance, err = statsd.New(conn)\n\t\t\tif err != nil {\n\t\t\t\tlog.Info(\"Unable to initialize statsd client.\")\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tinstance.Namespace = metricsClientConf.Prefix\n\t\t}\n\t})\n\treturn instance, err\n}", "func (c *Cache) Get(ctx context.Context, job, instance, metric string) (*Entry, error) {\n\tif md, ok := c.staticMetadata[metric]; ok {\n\t\treturn md, nil\n\t}\n\tmd, ok := c.metadata[metric]\n\tif !ok || md.shouldRefetch() {\n\t\t// If we are seeing the job for the first time, preemptively get a full\n\t\t// list of all metadata for the instance.\n\t\tif _, ok := c.seenJobs[job]; !ok {\n\t\t\tmds, err := c.fetchBatch(ctx, job, instance)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"fetch metadata for job %q\", job)\n\t\t\t}\n\t\t\tfor _, md := range mds {\n\t\t\t\t// Only set if we haven't seen the metric before. Changes to metadata\n\t\t\t\t// may need special handling in Stackdriver, which we do not provide\n\t\t\t\t// yet anyway.\n\t\t\t\tif _, ok := c.metadata[md.Metric]; !ok {\n\t\t\t\t\tc.metadata[md.Metric] = md\n\t\t\t\t}\n\t\t\t}\n\t\t\tc.seenJobs[job] = struct{}{}\n\t\t} else {\n\t\t\tmd, err := c.fetchMetric(ctx, job, instance, metric)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"fetch metric metadata \\\"%s/%s/%s\\\"\", job, instance, metric)\n\t\t\t}\n\t\t\tc.metadata[metric] = md\n\t\t}\n\t\tmd = c.metadata[metric]\n\t}\n\tif md != nil && md.found {\n\t\treturn md.Entry, nil\n\t}\n\t// The metric might also be produced by a recording rule, which by convention\n\t// contain at least one `:` character. In that case we can generally assume that\n\t// it is a gauge. We leave the help text empty.\n\tif strings.Contains(metric, \":\") {\n\t\tentry := &Entry{Metric: metric, MetricType: textparse.MetricTypeGauge}\n\t\treturn entry, nil\n\t}\n\treturn nil, nil\n}", "func (c *Client) getStatistics() *AllStats {\n\n\tvar status Status\n\tstatusURL := fmt.Sprintf(statusURLPattern, c.protocol, c.hostname, c.port)\n\tbody := c.MakeRequest(statusURL)\n\terr := json.Unmarshal(body, &status)\n\tif err != nil {\n\t\tlog.Println(\"Unable to unmarshal Adguard log statistics to log statistics struct model\", err)\n\t}\n\n\tvar stats Stats\n\tstatsURL := fmt.Sprintf(statsURLPattern, c.protocol, c.hostname, c.port)\n\tbody = c.MakeRequest(statsURL)\n\terr = json.Unmarshal(body, &stats)\n\tif err != nil {\n\t\tlog.Println(\"Unable to unmarshal Adguard statistics to statistics struct model\", err)\n\t}\n\n\tvar logstats LogStats\n\tlogstatsURL := fmt.Sprintf(logstatsURLPattern, c.protocol, c.hostname, c.port, c.logLimit)\n\tbody = c.MakeRequest(logstatsURL)\n\terr = json.Unmarshal(body, &logstats)\n\tif err != nil {\n\t\tlog.Println(\"Unable to unmarshal Adguard log statistics to log statistics struct model\", err)\n\t}\n\n\tvar allstats AllStats\n\tallstats.status = &status\n\tallstats.stats = &stats\n\tallstats.logStats = &logstats\n\n\treturn &allstats\n}", "func (c *MetricsCollector) Metrics() *InvocationMetrics {\n\tc.Lock()\n\tdefer c.Unlock()\n\treturn c.metrics\n}", "func (u UptimePlugin) FetchMetrics() (map[string]float64, error) {\n\tut, err := uptime.Get()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to fetch uptime metrics: %s\", err)\n\t}\n\treturn map[string]float64{\"seconds\": ut.Seconds()}, nil\n}", "func GetAll() map[Type]time.Duration {\n\tmutex.RLock()\n\tdefer mutex.RUnlock()\n\treturn GlobalStats\n}", "func (m *Manager) Get(base int64) *TimestampBuffering {\n\t// m.mutex.Lock()\n\t// defer m.mutex.Unlock()\n\n\t// get now\n\tindex := m.GetCurrentIndex(base)\n\tfmt.Printf(\"get current index :%d\\n\",index)\n\n\n\treturn m.targets[index]\n\n\t// return nil\n}", "func (p S3RequestsPlugin) FetchMetrics() (map[string]float64, error) {\n\tstats := make(map[string]float64)\n\n\tfor _, met := range s3RequestMetricsGroup {\n\t\tv, err := getLastPointFromCloudWatch(p.CloudWatch, p.BucketName, p.FilterID, met)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s: %s\", met, err)\n\t\t} else if v != nil {\n\t\t\tstats = mergeStatsFromDatapoint(stats, v, met)\n\t\t}\n\t}\n\treturn stats, nil\n}", "func (engine *DockerStatsEngine) GetInstanceMetrics() (*ecstcs.MetricsMetadata, []*ecstcs.TaskMetric, error) {\n\tvar taskMetrics []*ecstcs.TaskMetric\n\tidle := engine.isIdle()\n\tmetricsMetadata := &ecstcs.MetricsMetadata{\n\t\tCluster: aws.String(engine.cluster),\n\t\tContainerInstance: aws.String(engine.containerInstanceArn),\n\t\tIdle: aws.Bool(idle),\n\t\tMessageId: aws.String(uuid.NewRandom().String()),\n\t}\n\n\tif idle {\n\t\tlog.Debug(\"Instance is idle. No task metrics to report\")\n\t\tfin := true\n\t\tmetricsMetadata.Fin = &fin\n\t\treturn metricsMetadata, taskMetrics, nil\n\t}\n\n\tfor taskArn := range engine.tasksToContainers {\n\t\tcontainerMetrics, err := engine.getContainerMetricsForTask(taskArn)\n\t\tif err != nil {\n\t\t\tlog.Debug(\"Error getting container metrics for task\", \"err\", err, \"task\", taskArn)\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(containerMetrics) == 0 {\n\t\t\tlog.Debug(\"Empty containerMetrics for task, ignoring\", \"task\", taskArn)\n\t\t\tcontinue\n\t\t}\n\n\t\ttaskDef, exists := engine.tasksToDefinitions[taskArn]\n\t\tif !exists {\n\t\t\tlog.Debug(\"Could not map task to definition\", \"task\", taskArn)\n\t\t\tcontinue\n\t\t}\n\n\t\tmetricTaskArn := taskArn\n\t\ttaskMetric := &ecstcs.TaskMetric{\n\t\t\tTaskArn: &metricTaskArn,\n\t\t\tTaskDefinitionFamily: &taskDef.family,\n\t\t\tTaskDefinitionVersion: &taskDef.version,\n\t\t\tContainerMetrics: containerMetrics,\n\t\t}\n\t\ttaskMetrics = append(taskMetrics, taskMetric)\n\t}\n\n\tif len(taskMetrics) == 0 {\n\t\t// Not idle. Expect taskMetrics to be there.\n\t\treturn nil, nil, fmt.Errorf(\"No task metrics to report\")\n\t}\n\n\t// Reset current stats. Retaining older stats results in incorrect utilization stats\n\t// until they are removed from the queue.\n\tengine.resetStats()\n\treturn metricsMetadata, taskMetrics, nil\n}", "func (db *DB) Metrics() *Metrics {\n\treturn db.metrics\n}", "func Latest() StatusData {\n\tlog.Println(\"LatestStatusData\")\n\tr := rp.Get()\n\tdefer r.Close()\n\n\tresult := StatusData{Success: true, Timestamp: time.Now(), Realtime: make(map[string]int), Total: make(map[string]int)}\n\n\tr.Send(\"SMEMBERS\", \"domains\")\n\tr.Flush()\n\tresult.Domains, _ = redis.Strings(redis.MultiBulk(r.Receive()))\n\n\tfor _, d := range result.Domains {\n\t\tvar key = d + \"_\" + result.Timestamp.Format(\"20060102\")\n\t\tval, _ := redis.Int(r.Do(\"GET\", key))\n\t\tif val > 0 {\n\t\t\tresult.Total[d] = val\n\t\t}\n\t}\n\n\treply, err := redis.Values(r.Do(\"SCAN\", 0, \"MATCH\", \"*:*\", \"COUNT\", 1000000))\n\tif err != nil {\n\t\tlog.Println(\"redis.Values\", err)\n\t}\n\tif _, err := redis.Scan(reply, nil, &result.Idents); err != nil {\n\t\tlog.Println(\"redis.Scan\", err)\n\t}\n\tresult.Current = len(result.Idents)\n\n\tfor _, ident := range result.Idents {\n\t\ttmp := strings.Split(ident, \":\")\n\t\tif val, ok := result.Realtime[tmp[0]]; ok {\n\t\t\tresult.Realtime[tmp[0]] = val + 1\n\t\t} else {\n\t\t\tresult.Realtime[tmp[0]] = 1\n\t\t}\n\t}\n\n\treturn result\n}", "func (api *API) Get(k string) (MetricItem, bool) {\n\treturn api.metricItens.Get(k)\n}", "func (p CognitoIdpPlugin) FetchMetrics() (map[string]interface{}, error) {\n\tstat := make(map[string]interface{})\n\n\tfor _, met := range [...]metrics{\n\t\t{CloudWatchName: \"SignUpSuccesses\", MackerelName: \"SignUpSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"SignUpSuccesses\", MackerelName: \"SignUpParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"SignUpSuccesses\", MackerelName: \"SignUpSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"SignUpThrottles\", MackerelName: \"SignUpThrottles\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"SignInSuccesses\", MackerelName: \"SignInSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"SignInSuccesses\", MackerelName: \"SignInParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"SignInSuccesses\", MackerelName: \"SignInSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"SignInThrottles\", MackerelName: \"SignInThrottles\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"TokenRefreshSuccesses\", MackerelName: \"TokenRefreshSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"TokenRefreshSuccesses\", MackerelName: \"TokenRefreshParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"TokenRefreshSuccesses\", MackerelName: \"TokenRefreshSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"TokenRefreshThrottles\", MackerelName: \"TokenRefreshThrottles\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"FederationSuccesses\", MackerelName: \"FederationSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"FederationSuccesses\", MackerelName: \"FederationParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"FederationSuccesses\", MackerelName: \"FederationSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"FederationThrottles\", MackerelName: \"FederationThrottles\", Type: metricsTypeSum},\n\t} {\n\t\tv, err := p.getLastPoint(met)\n\t\tif err == nil {\n\t\t\tstat[met.MackerelName] = v\n\t\t} else {\n\t\t\tlog.Printf(\"%s: %s\", met, err)\n\t\t}\n\t}\n\treturn stat, nil\n}", "func (s *Stats) Get() Stats {\n\n\tout := Stats{\n\t\tEventsTotal: atomic.LoadUint64(&s.EventsTotal),\n\t\tEventsUpdate: atomic.LoadUint64(&s.EventsUpdate),\n\t\tEventsDestroy: atomic.LoadUint64(&s.EventsDestroy),\n\t}\n\n\t// Get Update source stats if present.\n\tif s.UpdateSourceStats != nil {\n\t\ts := s.UpdateSourceStats.Get()\n\t\tout.UpdateSourceStats = &s\n\t}\n\n\t// Get Destroy source stats if present.\n\tif s.DestroySourceStats != nil {\n\t\ts := s.DestroySourceStats.Get()\n\t\tout.DestroySourceStats = &s\n\t}\n\n\treturn out\n}", "func (m *MetricsCacheType) GetMetrics() ([]string, bool) {\n\tif m.IsAvailable() && !m.TimedOut() {\n\t\treturn m.metrics, true\n\t}\n\n\tif !m.updating {\n\t\tgo m.RefreshCache()\n\t}\n\treturn nil, false\n}", "func (c *ResourceCollector) Get(ch chan<- prometheus.Metric) (float64, error) {\n\n\tjsonResources, err := getResourceStats()\n\tif err != nil {\n\t\ttotalResourceErrors++\n\t\treturn totalResourceErrors, fmt.Errorf(\"cannot get resources: %s\", err)\n\t}\n\tif err := processResourceStats(ch, jsonResources); err != nil {\n\t\ttotalResourceErrors++\n\t\treturn totalResourceErrors, err\n\t}\n\treturn totalResourceErrors, nil\n\n}", "func (c *PromMetricsClient) GetMetrics() ([]*Metric, error) {\n\tres, err := http.Get(c.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, ErrUnexpectedHTTPStatusCode\n\t}\n\n\tdefer res.Body.Close()\n\treturn Parse(res.Body)\n}", "func (c *CAdvisor) GetMetrics() (*Metrics, error) {\n\tlog.Printf(\"[DEBUG] [cadvisor] Get metrics\")\n\tnodeSpec, err := c.Client.MachineInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive machine info : %#v\",\n\t\tnodeSpec)\n\tnodeInfo, err := c.Client.ContainerInfo(\"/\", c.Query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive container info : %#v\",\n\t\tnodeInfo)\n\tcontainersInfo, err := c.Client.AllDockerContainers(c.Query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive all docker containers : %#v\",\n\t\tcontainersInfo)\n\tmetrics := &Metrics{\n\t\tNodeSpec: nodeSpec,\n\t\tNodeInfo: nodeInfo,\n\t\tContainersInfo: containersInfo,\n\t}\n\t//log.Printf(\"[INFO] [cadvisor] Metrics: %#v\", metrics)\n\treturn metrics, nil\n}", "func (p RekognitionPlugin) FetchMetrics() (map[string]float64, error) {\n\tstat := make(map[string]float64)\n\n\tfor _, met := range [...]string{\n\t\t\"SuccessfulRequestCount\",\n\t\t\"ThrottledCount\",\n\t\t\"ResponseTime\",\n\t\t\"DetectedFaceCount\",\n\t\t\"DetectedLabelCount\",\n\t\t\"ServerErrorCount\",\n\t\t\"UserErrorCount\",\n\t} {\n\t\tv, err := p.getLastPoint(met)\n\t\tif err == nil {\n\t\t\tstat[met] = v\n\t\t} else {\n\t\t\tlog.Printf(\"%s: %s\", met, err)\n\t\t}\n\t}\n\n\treturn stat, nil\n}", "func (mw *Stats) Data() *Data {\n\tmw.mu.RLock()\n\n\tresponseCounts := make(map[string]int, len(mw.ResponseCounts))\n\ttotalResponseCounts := make(map[string]int, len(mw.TotalResponseCounts))\n\ttotalMetricsCounts := make(map[string]int, len(mw.MetricsCounts))\n\tmetricsCounts := make(map[string]float64, len(mw.MetricsCounts))\n\n\tnow := time.Now()\n\n\tuptime := now.Sub(mw.Uptime)\n\n\tcount := 0\n\tfor code, current := range mw.ResponseCounts {\n\t\tresponseCounts[code] = current\n\t\tcount += current\n\t}\n\n\ttotalCount := 0\n\tfor code, count := range mw.TotalResponseCounts {\n\t\ttotalResponseCounts[code] = count\n\t\ttotalCount += count\n\t}\n\n\ttotalResponseTime := mw.TotalResponseTime.Sub(time.Time{})\n\ttotalResponseSize := mw.TotalResponseSize\n\n\taverageResponseTime := time.Duration(0)\n\taverageResponseSize := int64(0)\n\tif totalCount > 0 {\n\t\tavgNs := int64(totalResponseTime) / int64(totalCount)\n\t\taverageResponseTime = time.Duration(avgNs)\n\t\taverageResponseSize = int64(totalResponseSize) / int64(totalCount)\n\t}\n\n\tfor key, count := range mw.MetricsCounts {\n\t\ttotalMetric := mw.MetricsTimers[key].Sub(time.Time{})\n\t\tavgNs := int64(totalMetric) / int64(count)\n\t\tmetricsCounts[key] = time.Duration(avgNs).Seconds()\n\t\ttotalMetricsCounts[key] = count\n\t}\n\n\tmw.mu.RUnlock()\n\n\tr := &Data{\n\t\tPid: mw.Pid,\n\t\tUpTime: uptime.String(),\n\t\tUpTimeSec: uptime.Seconds(),\n\t\tTime: now.String(),\n\t\tTimeUnix: now.Unix(),\n\t\tStatusCodeCount: responseCounts,\n\t\tTotalStatusCodeCount: totalResponseCounts,\n\t\tCount: count,\n\t\tTotalCount: totalCount,\n\t\tTotalResponseTime: totalResponseTime.String(),\n\t\tTotalResponseSize: totalResponseSize,\n\t\tTotalResponseTimeSec: totalResponseTime.Seconds(),\n\t\tTotalMetricsCounts: totalMetricsCounts,\n\t\tAverageResponseSize: averageResponseSize,\n\t\tAverageResponseTime: averageResponseTime.String(),\n\t\tAverageResponseTimeSec: averageResponseTime.Seconds(),\n\t\tAverageMetricsTimers: metricsCounts,\n\t}\n\n\treturn r\n}", "func (r IpvsPlugin) FetchMetrics() (map[string]float64, error) {\n file, err := os.Open(r.Target)\n if err != nil {\n return nil, err\n }\n defer file.Close()\n\n return Parse(file)\n}", "func (s *Store) Metrics() *StoreMetrics {\n\treturn s.metrics\n}", "func (s *inMemoryStore) Get(ctx context.Context, h types.Metric, resetTime time.Time, fieldVals []any) any {\n\tif resetTime.IsZero() {\n\t\tresetTime = clock.Now(ctx)\n\t}\n\n\tm := s.getOrCreateData(h)\n\tt := s.findTarget(ctx, m)\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\treturn m.get(fieldVals, t, resetTime).Value\n}", "func (c *MetricCollector) Get(ctx context.Context, namespace, name string) (*Metric, error) {\n\tc.collectionsMutex.RLock()\n\tdefer c.collectionsMutex.RUnlock()\n\n\tkey := NewMetricKey(namespace, name)\n\tcollector, ok := c.collections[key]\n\tif !ok {\n\t\treturn nil, k8serrors.NewNotFound(kpa.Resource(\"Deciders\"), key)\n\t}\n\n\treturn collector.metric.DeepCopy(), nil\n}", "func (sink *influxdbSink) GetMetric(metricName string, metricKeys []core.HistoricalKey, start, end time.Time) (map[core.HistoricalKey][]core.TimestampedMetricValue, error) {\n\tfor _, key := range metricKeys {\n\t\tif err := sink.checkSanitizedKey(&key); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := sink.checkSanitizedMetricName(metricName); err != nil {\n\t\treturn nil, err\n\t}\n\n\tquery := sink.composeRawQuery(metricName, nil, metricKeys, start, end)\n\n\tsink.RLock()\n\tdefer sink.RUnlock()\n\n\tresp, err := sink.runQuery(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := make(map[core.HistoricalKey][]core.TimestampedMetricValue, len(metricKeys))\n\tfor i, key := range metricKeys {\n\t\tif len(resp[i].Series) < 1 {\n\t\t\treturn nil, fmt.Errorf(\"No results for metric %q describing %q\", metricName, key.String())\n\t\t}\n\n\t\tvals, err := sink.parseRawQueryRow(resp[i].Series[0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres[key] = vals\n\t}\n\n\treturn res, nil\n}", "func setupMetrics() Metrics {\n\tm := Metrics{}\n\tm.LastBackupDuration = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_duration\",\n\t\tHelp: \"Backup duration in nanoseconds.\",\n\t})\n\tm.LastBackupSuccess = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_success\",\n\t\tHelp: \"Last backup success boolean: 0=failed, 1=success, 2=unknown.\",\n\t})\n\tm.LastBackupStart = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_start\",\n\t\tHelp: \"Last backup start timestamp.\",\n\t})\n\tm.LastBackupEnd = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_end\",\n\t\tHelp: \"Last backup end timestamp.\",\n\t})\n\tm.SuccessfulBackups = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"successful_backups\",\n\t\tHelp: \"Number of Successful Backups.\",\n\t})\n\tm.FailedBackups = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"failed_backups\",\n\t\tHelp: \"Number of Failed Backups.\",\n\t})\n\tprometheus.MustRegister(\n\t\tm.LastBackupDuration,\n\t\tm.LastBackupStart,\n\t\tm.LastBackupEnd,\n\t\tm.LastBackupSuccess,\n\t\tm.SuccessfulBackups,\n\t\tm.FailedBackups,\n\t)\n\tm.LastBackupSuccess.Set(2) // 0=failed, 1=success, 2=unknown\n\treturn m\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 (y *YarnMetrics) getMetrics() *NMMetrics {\n\tjmxResp := &JmxResp{}\n\terr := y.requestUrl(metricsSuffix, jmxResp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"request nodemanager metrics err: %v\", err)\n\t\treturn nil\n\t}\n\tif len(jmxResp.Beans) == 0 {\n\t\tklog.V(5).Infof(\"request nodemanager metrics, empty beans\")\n\t\treturn nil\n\t}\n\treturn &jmxResp.Beans[0]\n}", "func (self *Metric) GetTime() time.Time {\n\treturn time.Unix(self.Time, 0).UTC()\n}", "func (h *Handler) GetMetricSum(w http.ResponseWriter, r *http.Request) {\n\tvar b []byte\n\tkey := mux.Vars(r)[\"key\"]\n\n\tresp := response{}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tcachedVal, ok := h.MetricsCache.Get(key)\n\tif !ok {\n\t\tb, _ = json.Marshal(resp)\n\t\tw.Write(b)\n\t\treturn\n\t}\n\n\tcachedList := cachedVal.(*list.List)\n\tnewList := list.New()\n\n\tfor element := cachedList.Front(); element != nil; element = element.Next() {\n\t\tdata := element.Value.(metricData)\n\t\tmetricTime := data.time\n\t\tvalidMetricTime := metricTime.Add(h.InstrumentationTimeInSeconds * time.Second)\n\n\t\tif validMetricTime.After(time.Now()) {\n\t\t\tresp.Value = resp.Value + data.value\n\t\t\tdata := metricData{value: data.value, time: data.time}\n\n\t\t\tnewList.PushBack(data)\n\t\t} else {\n\t\t\th.MetricsCache.Set(key, newList, cache.NoExpiration)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tb, _ = json.Marshal(resp)\n\tw.Write(b)\n\n\treturn\n}", "func (r Virtual_Guest) GetRecentMetricData(time *uint) (resp []datatypes.Metric_Tracking_Object, err error) {\n\tparams := []interface{}{\n\t\ttime,\n\t}\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getRecentMetricData\", params, &r.Options, &resp)\n\treturn\n}", "func (c *client) getAllTicketMetrics(endpoint string, in interface{}) ([]TicketMetric, error) {\n\tresult := make([]TicketMetric, 0)\n\tpayload, err := marshall(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theaders := map[string]string{}\n\tif in != nil {\n\t\theaders[\"Content-Type\"] = \"application/json\"\n\t}\n\n\tres, err := c.request(\"GET\", endpoint, headers, bytes.NewReader(payload))\n\tdataPerPage := new(APIPayload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiV2 := \"/api/v2/\"\n\tfieldName := strings.Split(endpoint[len(apiV2):], \".\")[0]\n\tdefer res.Body.Close()\n\n\terr = unmarshall(res, dataPerPage)\n\n\tapiStartIndex := strings.Index(dataPerPage.NextPage, apiV2)\n\tcurrentPage := endpoint\n\n\tvar totalWaitTime int64\n\tfor currentPage != \"\" {\n\t\t// if too many requests(res.StatusCode == 429), delay sending request\n\t\tif res.StatusCode == 429 {\n\t\t\tafter, err := strconv.ParseInt(res.Header.Get(\"Retry-After\"), 10, 64)\n\t\t\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] too many requests. Wait for %v seconds\\n\", after)\n\t\t\ttotalWaitTime += after\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttime.Sleep(time.Duration(after) * time.Second)\n\t\t} else {\n\t\t\tif fieldName == \"ticket_metrics\" {\n\t\t\t\tresult = append(result, dataPerPage.TicketMetrics...)\n\t\t\t}\n\t\t\tcurrentPage = dataPerPage.NextPage\n\t\t}\n\t\tres, _ = c.request(\"GET\", dataPerPage.NextPage[apiStartIndex:], headers, bytes.NewReader(payload))\n\t\tdataPerPage = new(APIPayload)\n\t\terr = unmarshall(res, dataPerPage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] number of records pulled: %v\\n\", len(result))\n\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] total waiting time due to rate limit: %v\\n\", totalWaitTime)\n\n\treturn result, err\n}", "func (m *MetricSet) Fetch() (common.MapStr, error) {\n\n\thapc, err := haproxy.NewHaproxyClient(m.statsAddr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"HAProxy Client error: %s\", err)\n\t}\n\n\tres, err := hapc.GetInfo()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"HAProxy Client error fetching %s: %s\", statsMethod, err)\n\t}\n\n\tmappedEvent, err := eventMapping(res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mappedEvent, nil\n}", "func getGlobalMetrics(\n\tctx context.Context,\n\tcl kubeClient,\n\tnow time.Time,\n\tclusterName string,\n) ([]types.MetricPoint, error) {\n\tvar (\n\t\terr error\n\t\tmultiErr prometheus.MultiError\n\t\tcache kubeCache\n\t)\n\n\t// Add resources to the cache.\n\tcache.pods, err = cl.GetPODs(ctx, \"\")\n\tmultiErr.Append(err)\n\n\tcache.namespaces, err = cl.GetNamespaces(ctx)\n\tmultiErr.Append(err)\n\n\tcache.nodes, err = cl.GetNodes(ctx)\n\tmultiErr.Append(err)\n\n\treplicasets, err := cl.GetReplicasets(ctx)\n\tmultiErr.Append(err)\n\n\tcache.replicasetOwnerByUID = make(map[string]metav1.OwnerReference, len(replicasets))\n\n\tfor _, replicaset := range replicasets {\n\t\tif len(replicaset.OwnerReferences) > 0 {\n\t\t\tcache.replicasetOwnerByUID[string(replicaset.UID)] = replicaset.OwnerReferences[0]\n\t\t}\n\t}\n\n\t// Compute cluster metrics.\n\tvar points []types.MetricPoint\n\n\tmetricFunctions := []metricsFunc{podsCount, requestsAndLimits, namespacesCount, nodesCount, podsRestartCount}\n\n\tfor _, f := range metricFunctions {\n\t\tpoints = append(points, f(cache, now)...)\n\t}\n\n\t// Add the Kubernetes cluster meta label to global metrics, this is used to\n\t// replace the agent ID by the Kubernetes agent ID in the relabel hook.\n\tfor _, point := range points {\n\t\tpoint.Labels[types.LabelMetaKubernetesCluster] = clusterName\n\t}\n\n\treturn points, multiErr.MaybeUnwrap()\n}", "func (sm *SinkManager) LatestContainerMetrics(appID string) []*events.Envelope {\n\tif sink := sm.sinks.ContainerMetricsFor(appID); sink != nil {\n\t\treturn sink.GetLatest()\n\t}\n\treturn []*events.Envelope{}\n}", "func (xratesKit *XRatesKit) GetLatest(currencyCode string, coinCodes *CoinCodes) *XRates {\n\n\tdata, err := xratesKit.ipfsHandler.GetLatestXRates(currencyCode, coinCodes.toStringArray())\n\n\tif err != nil {\n\n\t\t// Get data from CoinPaprika\n\t\tdata, err = xratesKit.coinPaprika.GetLatestXRates(currencyCode, coinCodes.toStringArray())\n\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\t//---------- Cache Data -------------------\n\n\txratesKit.cacheService.SetLatest(data)\n\n\t//-----------------------------------------\n\n\tlog.Println(data)\n\n\tvar result = make([]XRate, len(data))\n\tfor i, xrate := range data {\n\t\tresult[i] = XRate(xrate)\n\t}\n\treturn &XRates{result}\n}", "func (s *Simulator) Stats() *Stats {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\telapsed := time.Since(s.now).Seconds()\n\tpThrough := float64(s.writtenN) / elapsed\n\trespMean := 0\n\tif len(s.latencyHistory) > 0 {\n\t\trespMean = int(s.totalLatency) / len(s.latencyHistory) / int(time.Millisecond)\n\t}\n\tstats := &Stats{\n\t\tTime: time.Unix(0, int64(time.Since(s.now))),\n\t\tTags: s.ReportTags,\n\t\tFields: models.Fields(map[string]interface{}{\n\t\t\t\"T\": int(elapsed),\n\t\t\t\"points_written\": s.writtenN,\n\t\t\t\"values_written\": s.writtenN * s.FieldsPerPoint,\n\t\t\t\"points_ps\": pThrough,\n\t\t\t\"values_ps\": pThrough * float64(s.FieldsPerPoint),\n\t\t\t\"write_error\": s.currentErrors,\n\t\t\t\"resp_wma\": int(s.wmaLatency),\n\t\t\t\"resp_mean\": respMean,\n\t\t\t\"resp_90\": int(s.quartileResponse(0.9) / time.Millisecond),\n\t\t\t\"resp_95\": int(s.quartileResponse(0.95) / time.Millisecond),\n\t\t\t\"resp_99\": int(s.quartileResponse(0.99) / time.Millisecond),\n\t\t}),\n\t}\n\n\tvar isCreating bool\n\tif s.writtenN < s.SeriesN() {\n\t\tisCreating = true\n\t}\n\tstats.Tags[\"creating_series\"] = fmt.Sprint(isCreating)\n\n\t// Reset error count for next reporting.\n\ts.currentErrors = 0\n\n\t// Add runtime stats for the remote instance.\n\tvar vars Vars\n\tresp, err := http.Get(strings.TrimSuffix(s.Host, \"/\") + \"/debug/vars\")\n\tif err != nil {\n\t\t// Don't log error as it can get spammy.\n\t\treturn stats\n\t}\n\tdefer resp.Body.Close()\n\n\tif err := json.NewDecoder(resp.Body).Decode(&vars); err != nil {\n\t\tfmt.Fprintln(s.Stderr, err)\n\t\treturn stats\n\t}\n\n\tstats.Fields[\"heap_alloc\"] = vars.Memstats.HeapAlloc\n\tstats.Fields[\"heap_in_use\"] = vars.Memstats.HeapInUse\n\tstats.Fields[\"heap_objects\"] = vars.Memstats.HeapObjects\n\treturn stats\n}", "func (m *MetricSet) Fetch(r mb.ReporterV2) {\n\tvar uptime sigar.Uptime\n\tif err := uptime.Get(); err != nil {\n\t\tr.Error(errors.Wrap(err, \"failed to get uptime\"))\n\t\treturn\n\t}\n\n\tr.Event(mb.Event{\n\t\tMetricSetFields: common.MapStr{\n\t\t\t\"duration\": common.MapStr{\n\t\t\t\t\"ms\": int64(uptime.Length * 1000),\n\t\t\t},\n\t\t},\n\t})\n}", "func Metrics(cl client.Client) (*v1.Metrics, error) {\n\n\t// Get metrics\n\treq, err := http.NewRequest(\"GET\", cl.MetronomeUrl()+\"/v1/metrics\", nil)\n\tres, err := cl.DoRequest(req)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to fetch metrics due to \" + err.Error())\n\t}\n\n\t// Parse metrics\n\tvar metrics v1.Metrics\n\tif err = json.Unmarshal(res, &metrics); err != nil {\n\t\treturn nil, errors.New(\"failed to unmarshal JSON data due to \" + err.Error())\n\t}\n\n\treturn &metrics, nil\n}", "func NewMetrics() *Metrics {\n\treturn &Metrics{items: make(map[string]*metric), rm: &sync.RWMutex{}}\n}", "func newMetrics() *metrics {\n\treturn new(metrics)\n}", "func (m *MetricSet) Fetch(reporter mb.ReporterV2) {\n\tvar err error\n\tvar rows *sql.Rows\n\trows, err = m.db.Query(`SELECT object_name, \n counter_name, \n instance_name, \n cntr_value \nFROM sys.dm_os_performance_counters \nWHERE counter_name = 'SQL Compilations/sec' \n OR counter_name = 'SQL Re-Compilations/sec' \n OR counter_name = 'User Connections' \n OR counter_name = 'Page splits/sec' \n OR ( counter_name = 'Lock Waits/sec' \n AND instance_name = '_Total' ) \n OR counter_name = 'Page splits/sec' \n OR ( object_name = 'SQLServer:Buffer Manager' \n AND counter_name = 'Page life expectancy' ) \n OR counter_name = 'Batch Requests/sec' \n OR ( counter_name = 'Buffer cache hit ratio' \n AND object_name = 'SQLServer:Buffer Manager' ) \n OR ( counter_name = 'Target pages' \n AND object_name = 'SQLServer:Buffer Manager' ) \n OR ( counter_name = 'Database pages' \n AND object_name = 'SQLServer:Buffer Manager' ) \n OR ( counter_name = 'Checkpoint pages/sec' \n AND object_name = 'SQLServer:Buffer Manager' ) \n OR ( counter_name = 'Lock Waits/sec' \n AND instance_name = '_Total' ) \n OR ( counter_name = 'Transactions' \n AND object_name = 'SQLServer:General Statistics' ) \n OR ( counter_name = 'Logins/sec' \n AND object_name = 'SQLServer:General Statistics' ) \n OR ( counter_name = 'Logouts/sec' \n AND object_name = 'SQLServer:General Statistics' ) \n OR ( counter_name = 'Connection Reset/sec' \n AND object_name = 'SQLServer:General Statistics' ) \n OR ( counter_name = 'Active Temp Tables' \n AND object_name = 'SQLServer:General Statistics' )`)\n\tif err != nil {\n\t\treporter.Error(errors.Wrapf(err, \"error closing rows\"))\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err := rows.Close(); err != nil {\n\t\t\tm.log.Error(\"error closing rows: %s\", err.Error())\n\t\t}\n\t}()\n\n\tmapStr := common.MapStr{}\n\tfor rows.Next() {\n\t\tvar row performanceCounter\n\t\tif err = rows.Scan(&row.objectName, &row.counterName, &row.instanceName, &row.counterValue); err != nil {\n\t\t\treporter.Error(errors.Wrap(err, \"error scanning rows\"))\n\t\t\tcontinue\n\t\t}\n\n\t\t//cell values contains spaces at the beginning and at the end of the 'actual' value. They must be removed.\n\t\trow.counterName = strings.TrimSpace(row.counterName)\n\t\trow.instanceName = strings.TrimSpace(row.instanceName)\n\t\trow.objectName = strings.TrimSpace(row.objectName)\n\n\t\tif row.counterName == \"Buffer cache hit ratio\" {\n\t\t\tmapStr[row.counterName] = fmt.Sprintf(\"%v\", float64(*row.counterValue)/100)\n\t\t} else {\n\t\t\tmapStr[row.counterName] = fmt.Sprintf(\"%v\", *row.counterValue)\n\t\t}\n\t}\n\n\tres, err := schema.Apply(mapStr)\n\tif err != nil {\n\t\tm.log.Error(errors.Wrap(err, \"error applying schema\"))\n\t\treturn\n\t}\n\n\tif isReported := reporter.Event(mb.Event{\n\t\tMetricSetFields: res,\n\t}); !isReported {\n\t\tm.log.Debug(\"event not reported\")\n\t}\n}", "func Get(key Type) time.Duration {\n\tif GlobalStats != nil {\n\t\tmutex.RLock()\n\t\tdefer mutex.RUnlock()\n\t\treturn GlobalStats[key]\n\t}\n\treturn 0\n}", "func NewMetrics() *MetricsHolder {\n\tm := &MetricsHolder{\n\t\tlines: make(map[string]*Reading),\n\t\tchannel: make(chan interface{}),\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tw, ok := <-m.channel\n\t\t\treading := w.(*Reading)\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif val, ok := m.lines[reading.Key]; ok {\n\t\t\t\tm.lines[reading.Key] = val.Accept(reading)\n\t\t\t} else {\n\t\t\t\tm.lines[reading.Key] = reading\n\t\t\t}\n\t\t}\n\t}()\n\treturn m\n}", "func (q AptCheckPlugin) FetchMetrics() (map[string]interface{}, error) {\n\tres, err := q.invokeAptCheck()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn map[string]interface{}{\n\t\t\"updates\": uint64(res.NumOfUpdates),\n\t\t\"security_updates\": uint64(res.NumOfSecurityUpdates),\n\t}, nil\n}", "func (m *metadataCache) get() *Metadata {\n\tm.mu.RLock()\n\tdefer m.mu.RUnlock()\n\treturn m.metadata\n}", "func (m *Metrics) Data() (*Data, error) {\n\tvar (\n\t\ttotalResponseTime float64\n\t\tmaxTime float64\n\t\tminTime = math.MaxFloat64\n\t\tbufsize = len(m.requests)\n\t\tpercentiledTime = make(percentiledTimeMap)\n\t)\n\tm.m.RLock()\n\tdefer m.m.RUnlock()\n\tfor _, v := range m.requests {\n\t\ttotalResponseTime += v\n\n\t\tif minTime > v {\n\t\t\tminTime = v\n\t\t}\n\t\tif maxTime < v {\n\t\t\tmaxTime = v\n\t\t}\n\t}\n\n\tfor _, p := range percents {\n\t\tvar err error\n\t\tpercentiledTime[p], err = m.requests.Percentile(float64(p))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tstatusCount := make(statusCountMap)\n\tfor _, status := range httpStatuses {\n\t\tstatusCount[status] = atomic.LoadInt64(&m.statusCount[status])\n\t}\n\n\treturn &Data{\n\t\tRequest: RequestData{\n\t\t\tCount: atomic.LoadInt64(&m.count),\n\t\t\tStatusCount: statusCount,\n\t\t},\n\t\tResponse: ResponseData{\n\t\t\tMaxTime: maxTime,\n\t\t\tMinTime: minTime,\n\t\t\tAverageTime: totalResponseTime / float64(bufsize),\n\t\t\tPercentiledTime: percentiledTime,\n\t\t},\n\t}, nil\n}", "func (u RackStatsPlugin) FetchMetrics() (stats map[string]interface{}, err error) {\n\tstats, err = u.parseStats()\n\treturn stats, err\n}", "func (c SslCertPlugin) FetchMetrics() (map[string]interface{}, error) {\n\tdays, err := getSslCertMetrics(c.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make(map[string]interface{})\n\tresult[\"days\"] = days\n\treturn result, nil\n}", "func (h CRConfigHistoryThreadsafe) Get() []CRConfigStat {\n\th.m.RLock()\n\tdefer h.m.RUnlock()\n\tif *h.length < *h.limit {\n\t\treturn CopyCRConfigStat((*h.hist)[:*h.length])\n\t}\n\tnewStats := make([]CRConfigStat, *h.limit)\n\tcopy(newStats, (*h.hist)[*h.pos:])\n\tcopy(newStats[*h.length-*h.pos:], (*h.hist)[:*h.pos])\n\treturn newStats\n}", "func (c *Cache) Metrics() CacheMetrics {\n\tif c == nil {\n\t\treturn CacheMetrics{}\n\t}\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.m.CacheMetrics\n}", "func fetchFloat64Metric(service *monitoring.Service, projectID string, resource *monitoring.MonitoredResource, metric *monitoring.Metric) (float64, error) {\n\tvar value float64\n\tbackoffPolicy := backoff.NewExponentialBackOff()\n\tbackoffPolicy.InitialInterval = 10 * time.Second\n\terr := backoff.Retry(\n\t\tfunc() error {\n\t\t\trequest := service.Projects.TimeSeries.\n\t\t\t\tList(fmt.Sprintf(\"projects/%s\", projectID)).\n\t\t\t\tFilter(fmt.Sprintf(\"resource.type=\\\"%s\\\" metric.type=\\\"%s\\\" %s %s\", resource.Type, metric.Type,\n\t\t\t\t\tbuildFilter(\"resource\", resource.Labels), buildFilter(\"metric\", metric.Labels))).\n\t\t\t\tAggregationAlignmentPeriod(\"300s\").\n\t\t\t\tAggregationPerSeriesAligner(\"ALIGN_NEXT_OLDER\").\n\t\t\t\tIntervalEndTime(time.Now().Format(time.RFC3339))\n\t\t\tlog.Printf(\"ListTimeSeriesRequest: %v\", request)\n\t\t\tresponse, err := request.Do()\n\t\t\tif err != nil {\n\t\t\t\t// TODO(jkohen): switch to gRPC and use error utils to get the response.\n\t\t\t\tif strings.Contains(err.Error(), \"Error 400\") {\n\t\t\t\t\t// The metric doesn't exist, but it may still show up.\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn backoff.Permanent(err)\n\t\t\t}\n\t\t\tlog.Printf(\"ListTimeSeriesResponse: %v\", response)\n\t\t\tif len(response.TimeSeries) > 1 {\n\t\t\t\treturn backoff.Permanent(fmt.Errorf(\"Expected 1 time series, got %v\", response.TimeSeries))\n\t\t\t}\n\t\t\tif len(response.TimeSeries) == 0 {\n\t\t\t\treturn fmt.Errorf(\"Waiting for 1 time series that matches the request, got %v\", response)\n\t\t\t}\n\t\t\ttimeSeries := response.TimeSeries[0]\n\t\t\tif len(timeSeries.Points) != 1 {\n\t\t\t\treturn fmt.Errorf(\"Expected 1 point, got %v\", timeSeries)\n\t\t\t}\n\t\t\tvalue = valueAsFloat64(timeSeries.Points[0].Value)\n\t\t\treturn nil\n\t\t}, backoffPolicy)\n\treturn value, err\n}", "func getMetric(c *gin.Context) {\n\tparams, err := parseMetricParams(c)\n\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\t// TODO: Allow string value comparisons as well!\n\tdocs, err := getDataOverRange(mongoSession, biModule.Rules[params.RuleIndex],\n\t\tparams.Granularity, params.Start, params.End, params.Value)\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tc.JSON(200, docs)\n}", "func (o *MetricsAllOf) GetMetrics() []Metric {\n\tif o == nil || o.Metrics == nil {\n\t\tvar ret []Metric\n\t\treturn ret\n\t}\n\treturn *o.Metrics\n}", "func (d *hdbDriver) Stats() *Stats { return d.metrics.stats() }", "func RegistryGet(humanName string) MX4JMetric {\n\treglock.RLock()\n\tdefer reglock.RUnlock()\n\n\treturn registry[humanName]\n}", "func (c *memoryExactMatcher) get(key string) (*event.SloClassification, error) {\n\ttimer := prometheus.NewTimer(matcherOperationDurationSeconds.WithLabelValues(\"get\", exactMatcherType))\n\tdefer timer.ObserveDuration()\n\tc.mtx.RLock()\n\tdefer c.mtx.RUnlock()\n\n\tvalue := c.exactMatches[key]\n\treturn value, nil\n}", "func GetStats(p *config.ProxyMonitorMetric, cfg *config.CCConfig, timeout time.Duration) *Stats {\n\tbytes := config.Encode(p)\n\tfmt.Println(string(bytes))\n\tvar ch = make(chan struct{})\n\tvar host = p.IP + \":\" + p.AdminPort\n\tfmt.Println(host)\n\tstats := &Stats{}\n\n\tgo func(host string) {\n\t\tdefer close(ch)\n\t\tstats.Host = host\n\t\terr := pingCheck(host, cfg.CCProxyServer.User, cfg.CCProxyServer.Password)\n\t\tif err != nil {\n\t\t\tstats.Error = err.Error()\n\t\t\tstats.Closed = true\n\t\t} else {\n\t\t\tstats.Closed = false\n\t\t}\n\t}(host)\n\n\tselect {\n\tcase <-ch:\n\t\treturn stats\n\tcase <-time.After(timeout):\n\t\treturn &Stats{Host: host, Timeout: true}\n\t}\n}", "func (m VarnishPlugin) FetchMetrics() (map[string]interface{}, error) {\n\tvar out []byte\n\tvar err error\n\n\tif m.VarnishName == \"\" {\n\t\tout, err = exec.Command(m.VarnishStatPath, \"-1\").CombinedOutput()\n\t} else {\n\t\tout, err = exec.Command(m.VarnishStatPath, \"-1\", \"-n\", m.VarnishName).CombinedOutput()\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %s\", err, out)\n\t}\n\n\tlineexp := regexp.MustCompile(`^([^ ]+) +(\\d+)`)\n\tsmaexp := regexp.MustCompile(`^SMA\\.([^\\.]+)\\.(.+)$`)\n\n\tstat := map[string]interface{}{\n\t\t\"requests\": float64(0),\n\t}\n\n\tvar tmpv float64\n\tfor _, line := range strings.Split(string(out), \"\\n\") {\n\t\tmatch := lineexp.FindStringSubmatch(line)\n\t\tif match == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\ttmpv, err = strconv.ParseFloat(match[2], 64)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch match[1] {\n\t\tcase \"cache_hit\", \"MAIN.cache_hit\":\n\t\t\tstat[\"cache_hits\"] = tmpv\n\t\t\tstat[\"requests\"] = stat[\"requests\"].(float64) + tmpv\n\t\tcase \"cache_miss\", \"MAIN.cache_miss\":\n\t\t\tstat[\"requests\"] = stat[\"requests\"].(float64) + tmpv\n\t\tcase \"cache_hitpass\", \"MAIN.cache_hitpass\":\n\t\t\tstat[\"requests\"] = stat[\"requests\"].(float64) + tmpv\n\t\tcase \"MAIN.backend_req\":\n\t\t\tstat[\"backend_req\"] = tmpv\n\t\tcase \"MAIN.backend_conn\":\n\t\t\tstat[\"backend_conn\"] = tmpv\n\t\tcase \"MAIN.backend_fail\":\n\t\t\tstat[\"backend_fail\"] = tmpv\n\t\tcase \"MAIN.backend_reuse\":\n\t\t\tstat[\"backend_reuse\"] = tmpv\n\t\tcase \"MAIN.backend_recycle\":\n\t\t\tstat[\"backend_recycle\"] = tmpv\n\t\tcase \"MAIN.n_object\":\n\t\t\tstat[\"n_object\"] = tmpv\n\t\tcase \"MAIN.n_objectcore\":\n\t\t\tstat[\"n_objectcore\"] = tmpv\n\t\tcase \"MAIN.n_expired\":\n\t\t\tstat[\"n_expired\"] = tmpv\n\t\tcase \"MAIN.n_objecthead\":\n\t\t\tstat[\"n_objecthead\"] = tmpv\n\t\tcase \"MAIN.busy_sleep\":\n\t\t\tstat[\"busy_sleep\"] = tmpv\n\t\tcase \"MAIN.busy_wakeup\":\n\t\t\tstat[\"busy_wakeup\"] = tmpv\n\t\tdefault:\n\t\t\tsmamatch := smaexp.FindStringSubmatch(match[1])\n\t\t\tif smamatch == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif smamatch[2] == \"g_alloc\" {\n\t\t\t\tstat[\"varnish.sma.g_alloc.\"+smamatch[1]+\".g_alloc\"] = tmpv\n\t\t\t} else if smamatch[2] == \"g_bytes\" {\n\t\t\t\tstat[\"varnish.sma.memory.\"+smamatch[1]+\".allocated\"] = tmpv\n\t\t\t} else if smamatch[2] == \"g_space\" {\n\t\t\t\tstat[\"varnish.sma.memory.\"+smamatch[1]+\".available\"] = tmpv\n\t\t\t}\n\t\t}\n\t}\n\n\treturn stat, err\n}", "func (m *MeterSnapshot) Snapshot() metrics.Meter { return m }", "func (h *Handler) GetAll(c echo.Context) error {\n\tid := c.Param(\"id\")\n\tdb := h.DB.Clone()\n\tdefer db.Close()\n\n\tvar results []*particleio.Result\n\tif err := db.DB(\"oxylus\").C(\"metrics\").Find(bson.M{\"uuid\": id}).Sort(\"time\").All(&results); err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn c.JSON(http.StatusOK, results)\n}", "func GetMetrics() []prometheus.Collector {\n\treturn []prometheus.Collector{\n\t\treqCounter,\n\t\treqDuration,\n\t\tconnDuration,\n\t}\n}", "func (r *GatewayConnectionStatsRegistry) Get(ctx context.Context, ids ttnpb.GatewayIdentifiers) (*ttnpb.GatewayConnectionStats, error) {\n\tuid := unique.ID(ctx, ids)\n\tresult := &ttnpb.GatewayConnectionStats{}\n\tstats := &ttnpb.GatewayConnectionStats{}\n\n\tretrieved, err := r.Redis.MGet(r.key(upKey, uid), r.key(downKey, uid), r.key(statusKey, uid)).Result()\n\tif err != nil {\n\t\treturn nil, ttnredis.ConvertError(err)\n\t}\n\n\tif retrieved[0] == nil && retrieved[1] == nil && retrieved[2] == nil {\n\t\treturn nil, errNotFound\n\t}\n\n\t// Retrieve uplink stats.\n\tif retrieved[0] != nil {\n\t\tif err = ttnredis.UnmarshalProto(retrieved[0].(string), stats); err != nil {\n\t\t\treturn nil, errInvalidStats.WithAttributes(\"type\", \"uplink\").WithCause(err)\n\t\t}\n\t\tresult.LastUplinkReceivedAt = stats.LastUplinkReceivedAt\n\t\tresult.UplinkCount = stats.UplinkCount\n\t}\n\n\t// Retrieve downlink stats.\n\tif retrieved[1] != nil {\n\t\tif err = ttnredis.UnmarshalProto(retrieved[1].(string), stats); err != nil {\n\t\t\treturn nil, errInvalidStats.WithAttributes(\"type\", \"downlink\").WithCause(err)\n\t\t}\n\t\tresult.LastDownlinkReceivedAt = stats.LastDownlinkReceivedAt\n\t\tresult.DownlinkCount = stats.DownlinkCount\n\t\tresult.RoundTripTimes = stats.RoundTripTimes\n\t}\n\n\t// Retrieve gateway status.\n\tif retrieved[2] != nil {\n\t\tif err = ttnredis.UnmarshalProto(retrieved[2].(string), stats); err != nil {\n\t\t\treturn nil, errInvalidStats.WithAttributes(\"type\", \"status\").WithCause(err)\n\t\t}\n\t\tresult.ConnectedAt = stats.ConnectedAt\n\t\tresult.Protocol = stats.Protocol\n\t\tresult.LastStatus = stats.LastStatus\n\t\tresult.LastStatusReceivedAt = stats.LastStatusReceivedAt\n\t}\n\n\treturn result, nil\n}", "func (e *Exporter) GetMetricsList() map[string]*QueryInstance {\n\tif e.allMetricMap == nil {\n\t\treturn nil\n\t}\n\treturn e.allMetricMap\n}", "func (Metrics) MetricStruct() {}", "func (c *HTTPClient) Metrics(timeout time.Duration) ([]string, error) {\n // temporary struct for parsing JSON response\n var respData struct {\n Names []string `json:\"results\"`\n }\n\n err := c.backend.Call(\"GET\", c.url+\"/api/v1/metricnames\", nil,\n timeout, http.StatusOK, &respData)\n if err != nil {\n return nil, err\n }\n\n glog.V(3).Infof(\"metric names: %+v\", respData.Names)\n return respData.Names, nil\n}", "func instrumentGet(inner func()) {\n\tTotalRequests.Add(1)\n\tPendingRequests.Add(1)\n\tdefer PendingRequests.Add(-1)\n\n\tstart := time.Now()\n\n\tinner()\n\n\t// Capture the histogram over 18 geometric buckets \n\tdelta := time.Since(start)\n\tswitch {\n\tcase delta < time.Millisecond:\n\t\tLatencies.Add(\"0ms\", 1)\n\tcase delta > 32768*time.Millisecond:\n\t\tLatencies.Add(\">32s\", 1)\n\tdefault:\n\t\tfor i := time.Millisecond; i < 32768*time.Millisecond; i *= 2 {\n\t\t\tif delta >= i && delta < i*2 {\n\t\t\t\tLatencies.Add(i.String(), 1)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func NewMetrics(scope tally.Scope) *Metrics {\n\tsuccessScope := scope.Tagged(map[string]string{\"result\": \"success\"})\n\tfailScope := scope.Tagged(map[string]string{\"result\": \"fail\"})\n\ttimeoutScope := scope.Tagged(map[string]string{\"result\": \"timeout\"})\n\tapiScope := scope.SubScope(\"api\")\n\tserverScope := scope.SubScope(\"server\")\n\tplacement := scope.SubScope(\"placement\")\n\trecovery := scope.SubScope(\"recovery\")\n\n\treturn &Metrics{\n\t\tAPIEnqueueGangs: apiScope.Counter(\"enqueue_gangs\"),\n\t\tEnqueueGangSuccess: successScope.Counter(\"enqueue_gang\"),\n\t\tEnqueueGangFail: failScope.Counter(\"enqueue_gang\"),\n\n\t\tAPIDequeueGangs: apiScope.Counter(\"dequeue_gangs\"),\n\t\tDequeueGangSuccess: successScope.Counter(\"dequeue_gangs\"),\n\t\tDequeueGangTimeout: timeoutScope.Counter(\"dequeue_gangs\"),\n\n\t\tAPIGetPreemptibleTasks: apiScope.Counter(\"get_preemptible_tasks\"),\n\t\tGetPreemptibleTasksSuccess: successScope.Counter(\"get_preemptible_tasks\"),\n\t\tGetPreemptibleTasksTimeout: timeoutScope.Counter(\"get_preemptible_tasks\"),\n\n\t\tAPISetPlacements: apiScope.Counter(\"set_placements\"),\n\t\tSetPlacementSuccess: successScope.Counter(\"set_placements\"),\n\t\tSetPlacementFail: failScope.Counter(\"set_placements\"),\n\n\t\tAPIGetPlacements: apiScope.Counter(\"get_placements\"),\n\t\tGetPlacementSuccess: successScope.Counter(\"get_placements\"),\n\t\tGetPlacementFail: failScope.Counter(\"get_placements\"),\n\n\t\tAPILaunchedTasks: apiScope.Counter(\"launched_tasks\"),\n\n\t\tRecoverySuccess: successScope.Counter(\"recovery\"),\n\t\tRecoveryFail: failScope.Counter(\"recovery\"),\n\t\tRecoveryRunningSuccessCount: successScope.Counter(\"task_count\"),\n\t\tRecoveryRunningFailCount: failScope.Counter(\"task_count\"),\n\t\tRecoveryEnqueueFailedCount: failScope.Counter(\"enqueue_task_count\"),\n\t\tRecoveryEnqueueSuccessCount: successScope.Counter(\"enqueue_task_count\"),\n\t\tRecoveryTimer: recovery.Timer(\"running_tasks\"),\n\n\t\tPlacementQueueLen: placement.Gauge(\"placement_queue_length\"),\n\t\tPlacementFailed: placement.Counter(\"fail\"),\n\n\t\tElected: serverScope.Gauge(\"elected\"),\n\t}\n}", "func (r *GoMetricsRegistry) GetAll() map[string]map[string]interface{} {\n\treturn r.shadow.GetAll()\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 (p HAProxyPlugin) FetchMetrics() (map[string]float64, error) {\n\tvar metrics map[string]float64\n\tvar err error\n\tif p.Socket == \"\" {\n\t\tmetrics, err = p.fetchMetricsFromTCP()\n\t} else {\n\t\tmetrics, err = p.fetchMetricsFromSocket()\n\t}\n\treturn metrics, err\n}", "func (tc *sklImpl) Metrics() Metrics {\n\treturn tc.metrics\n}", "func (p *StatsDParser) GetMetrics() pdata.Metrics {\n\tmetrics := pdata.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\n\tfor _, metric := range p.gauges {\n\t\trm.InstrumentationLibraryMetrics().Append(metric)\n\t}\n\n\tfor _, metric := range p.counters {\n\t\trm.InstrumentationLibraryMetrics().Append(metric)\n\t}\n\n\tfor _, metric := range p.timersAndDistributions {\n\t\trm.InstrumentationLibraryMetrics().Append(metric)\n\t}\n\n\tfor _, summaryMetric := range p.summaries {\n\t\tmetrics.ResourceMetrics().At(0).InstrumentationLibraryMetrics().Append(buildSummaryMetric(summaryMetric))\n\t}\n\n\tp.gauges = make(map[statsDMetricdescription]pdata.InstrumentationLibraryMetrics)\n\tp.counters = make(map[statsDMetricdescription]pdata.InstrumentationLibraryMetrics)\n\tp.timersAndDistributions = make([]pdata.InstrumentationLibraryMetrics, 0)\n\tp.summaries = make(map[statsDMetricdescription]summaryMetric)\n\treturn metrics\n}", "func (s *CacheService) Get(base string) *RatesStore {\n\t// Is our cache expired?\n\tif s.IsExpired(base) {\n\t\treturn nil\n\t}\n\n\t// Use stored results.\n\treturn cache[base]\n}", "func GetProxyMetrics(proxyName string) *ServerMetric {\n\tsmMutex.RLock()\n\tdefer smMutex.RUnlock()\n\tmetric, ok := ServerMetricInfoMap[proxyName]\n\tif ok {\n\t\tmetric.mutex.RLock()\n\t\ttmpMetric := metric.clone()\n\t\tmetric.mutex.RUnlock()\n\t\treturn tmpMetric\n\t} else {\n\t\treturn nil\n\t}\n}", "func GetStats(args *Args, format string) string {\n\tcfg := config.GetConfig(args.ConfigFile)\n\t// init statistic for record\n\tstatistic.InitStatistic(cfg.Statistic)\n\n\tallQueueStatistic := []*statistic.QueueStatistic{}\n\n\tfor _, cc := range cfg.Redis {\n\t\tfor _, queueConfig := range cc.Queues {\n\t\t\ts := &statistic.QueueStatistic{\n\t\t\t\tQueueName: queueConfig.QueueName,\n\t\t\t\tSourceType: \"Redis\",\n\t\t\t\tIsEnabled: queueConfig.IsEnabled,\n\t\t\t}\n\n\t\t\tqi := &redis.QueueInstance{\n\t\t\t\tSource: cc.Config,\n\t\t\t\tQueue: queueConfig,\n\t\t\t}\n\n\t\t\tif queueConfig.IsDelayQueue {\n\t\t\t\ts.Normal, _ = qi.DelayLength(queueConfig.QueueName)\n\t\t\t} else {\n\t\t\t\ts.Normal, _ = qi.Length(queueConfig.QueueName)\n\t\t\t}\n\n\t\t\tif len(queueConfig.DelayOnFailure) > 0 {\n\t\t\t\tqueueName := fmt.Sprintf(\"%s:delayed\", queueConfig.QueueName)\n\t\t\t\ts.Delayed, _ = qi.DelayLength(queueName)\n\t\t\t}\n\n\t\t\ts.Success, _ = statistic.GetCounter(fmt.Sprintf(\"%s:success\", queueConfig.QueueName))\n\t\t\ts.Failure, _ = statistic.GetCounter(fmt.Sprintf(\"%s:failure\", queueConfig.QueueName))\n\n\t\t\ts.Total = s.Normal + s.Delayed + s.Success + s.Failure\n\n\t\t\tallQueueStatistic = append(allQueueStatistic, s)\n\t\t}\n\t}\n\n\tfor _, cc := range cfg.RabbitMQ {\n\t\tfor _, queueConfig := range cc.Queues {\n\t\t\ts := &statistic.QueueStatistic{\n\t\t\t\tQueueName: queueConfig.QueueName,\n\t\t\t\tSourceType: \"RabbitMQ\",\n\t\t\t\tIsEnabled: queueConfig.IsEnabled,\n\t\t\t}\n\n\t\t\t// qi := &rabbitmq.QueueInstance{\n\t\t\t// \tSource: cc.Config,\n\t\t\t// \tQueue: queueConfig,\n\t\t\t// }\n\t\t\t// todo get queue length\n\n\t\t\ts.Normal = 0\n\t\t\ts.Delayed = 0\n\n\t\t\ts.Success, _ = statistic.GetCounter(fmt.Sprintf(\"%s:success\", queueConfig.QueueName))\n\t\t\ts.Failure, _ = statistic.GetCounter(fmt.Sprintf(\"%s:failure\", queueConfig.QueueName))\n\n\t\t\ts.Total = s.Normal + s.Delayed + s.Success + s.Failure\n\n\t\t\tallQueueStatistic = append(allQueueStatistic, s)\n\t\t}\n\t}\n\n\tif \"json\" == format {\n\t\toutput, err := json.Marshal(allQueueStatistic)\n\n\t\tif nil != err {\n\t\t\treturn \"\"\n\t\t}\n\n\t\treturn string(output)\n\t}\n\n\toutput := fmt.Sprintf(\"%s %s statistics information\\n\\n\", constant.APPNAME, constant.APPVERSION)\n\tfor _, s := range allQueueStatistic {\n\t\tstatus := \"disable\"\n\t\tif s.IsEnabled {\n\t\t\tstatus = \"enable\"\n\t\t}\n\t\toutput += fmt.Sprintf(\" > Type: %-8s Status: %-8s Name: %s\\n%10d Total\\n%10d Normal\\n%10d Delayed\\n%10d Success\\n%10d Failure\\n\\n\", s.SourceType, status, s.QueueName, s.Total, s.Normal, s.Delayed, s.Success, s.Failure)\n\t}\n\n\tif \"html\" == format {\n\t\tstrings.Replace(output, \"\\n\", \"<br />\", -1)\n\t}\n\n\treturn output\n}", "func (m *podMetrics) Get(ctx context.Context, name string, opts *metav1.GetOptions) (runtime.Object, error) {\n\tnamespace := genericapirequest.NamespaceValue(ctx)\n\n\tpod, err := m.podLister.ByNamespace(namespace).Get(name)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// return not-found errors directly\n\t\t\treturn &metrics.PodMetrics{}, err\n\t\t}\n\t\tklog.ErrorS(err, \"Failed getting pod\", \"pod\", klog.KRef(namespace, name))\n\t\treturn &metrics.PodMetrics{}, fmt.Errorf(\"failed getting pod: %w\", err)\n\t}\n\tif pod == nil {\n\t\treturn &metrics.PodMetrics{}, errors.NewNotFound(corev1.Resource(\"pods\"), fmt.Sprintf(\"%s/%s\", namespace, name))\n\t}\n\n\tms, err := m.getMetrics(pod)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed reading pod metrics\", \"pod\", klog.KRef(namespace, name))\n\t\treturn nil, fmt.Errorf(\"failed pod metrics: %w\", err)\n\t}\n\tif len(ms) == 0 {\n\t\treturn nil, errors.NewNotFound(m.groupResource, fmt.Sprintf(\"%s/%s\", namespace, name))\n\t}\n\treturn &ms[0], nil\n}", "func (core *Core) FetchMetricData() (*registry.MetricsData, error) {\n\tresp, err := http.Get(\"http://\" + core.master + \"/master/state.json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := new(registry.MetricsData)\n\tif err = json.NewDecoder(resp.Body).Decode(data); err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Body.Close()\n\treturn data, nil\n}", "func GetMetrics(ps datatypes.PerformanceSignature, ts []datatypes.Timestamps) (datatypes.ComparisonMetrics, error) {\n\tmetricString := createMetricString(ps.PSMetrics)\n\tlogging.LogDebug(datatypes.Logging{Message: fmt.Sprintf(\"Escaped safe metric names are: %v\", metricString)})\n\n\t// Get the metrics from the most recent Deployment Event\n\tmetricResponse, err := queryMetrics(ps.DTServer, ps.DTEnv, metricString, ts[0], ps)\n\tif err != nil {\n\t\treturn datatypes.ComparisonMetrics{}, fmt.Errorf(\"error querying current metrics from Dynatrace: %v\", err)\n\t}\n\n\t// If there were two Deployment Events, get the second set of metrics\n\tif len(ts) == 2 {\n\t\tpreviousMetricResponse, err := queryMetrics(ps.DTServer, ps.DTEnv, metricString, ts[1], ps)\n\t\tif err != nil {\n\t\t\treturn datatypes.ComparisonMetrics{}, fmt.Errorf(\"error querying previous metrics from Dynatrace: %v\", err)\n\t\t}\n\t\tvar bothMetricSets = datatypes.ComparisonMetrics{\n\t\t\tCurrentMetrics: metricResponse,\n\t\t\tPreviousMetrics: previousMetricResponse,\n\t\t}\n\n\t\treturn bothMetricSets, nil\n\t}\n\n\tvar metrics = datatypes.ComparisonMetrics{\n\t\tCurrentMetrics: metricResponse,\n\t}\n\n\treturn metrics, nil\n}", "func (b *gsDBBackup) getBackupMetrics(now time.Time) (time.Time, int64, error) {\n\tlastTime := time.Time{}\n\tvar count int64 = 0\n\tcountAfter := now.Add(-24 * time.Hour)\n\terr := gs.AllFilesInDir(b.gsClient, b.gsBucket, DB_BACKUP_DIR, func(item *storage.ObjectAttrs) {\n\t\tif item.Updated.After(lastTime) {\n\t\t\tlastTime = item.Updated\n\t\t}\n\t\tif item.Updated.After(countAfter) {\n\t\t\tcount++\n\t\t}\n\t})\n\treturn lastTime, count, err\n}", "func (c *ClusterScalingScheduleCollector) GetMetrics() ([]CollectedMetric, error) {\n\tclusterScalingScheduleInterface, exists, err := c.store.GetByKey(c.objectReference.Name)\n\tif !exists {\n\t\treturn nil, ErrClusterScalingScheduleNotFound\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected error retrieving the ClusterScalingSchedule: %s\", err.Error())\n\t}\n\n\t// The [cache.Store][0] returns the v1.ClusterScalingSchedule items as\n\t// a v1.ScalingSchedule when it first lists it. Once the objects are\n\t// updated/patched it asserts it correctly to the\n\t// v1.ClusterScalingSchedule type. It means we have to handle both\n\t// cases.\n\t// TODO(jonathanbeber): Identify why it happens and fix in the upstream.\n\t//\n\t// [0]: https://github.com/kubernetes/client-go/blob/v0.21.1/tools/cache/Store.go#L132-L140\n\tvar clusterScalingSchedule v1.ClusterScalingSchedule\n\tscalingSchedule, ok := clusterScalingScheduleInterface.(*v1.ScalingSchedule)\n\tif !ok {\n\t\tcss, ok := clusterScalingScheduleInterface.(*v1.ClusterScalingSchedule)\n\t\tif !ok {\n\t\t\treturn nil, ErrNotClusterScalingScheduleFound\n\t\t}\n\t\tclusterScalingSchedule = *css\n\t} else {\n\t\tclusterScalingSchedule = v1.ClusterScalingSchedule(*scalingSchedule)\n\t}\n\n\treturn calculateMetrics(clusterScalingSchedule.Spec, c.defaultScalingWindow, c.defaultTimeZone, c.rampSteps, c.now(), c.objectReference, c.metric)\n}", "func metricsUpdate() {\n metricsXml()\n}", "func (sr *scrutinyRepository) GetSummary(ctx context.Context) (map[string]*models.DeviceSummary, error) {\n\tdevices, err := sr.GetDevices(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsummaries := map[string]*models.DeviceSummary{}\n\n\tfor _, device := range devices {\n\t\tsummaries[device.WWN] = &models.DeviceSummary{Device: device}\n\t}\n\n\t// Get parser flux query result\n\t//appConfig.GetString(\"web.influxdb.bucket\")\n\tqueryStr := fmt.Sprintf(`\n \timport \"influxdata/influxdb/schema\"\n \tbucketBaseName = \"%s\"\n\n\tdailyData = from(bucket: bucketBaseName)\n\t|> range(start: -10y, stop: now())\n\t|> filter(fn: (r) => r[\"_measurement\"] == \"smart\" )\n\t|> filter(fn: (r) => r[\"_field\"] == \"temp\" or r[\"_field\"] == \"power_on_hours\" or r[\"_field\"] == \"date\")\n\t|> last()\n\t|> schema.fieldsAsCols()\n\t|> group(columns: [\"device_wwn\"])\n\t\n\tweeklyData = from(bucket: bucketBaseName + \"_weekly\")\n\t|> range(start: -10y, stop: now())\n\t|> filter(fn: (r) => r[\"_measurement\"] == \"smart\" )\n\t|> filter(fn: (r) => r[\"_field\"] == \"temp\" or r[\"_field\"] == \"power_on_hours\" or r[\"_field\"] == \"date\")\n\t|> last()\n\t|> schema.fieldsAsCols()\n\t|> group(columns: [\"device_wwn\"])\n\t\n\tmonthlyData = from(bucket: bucketBaseName + \"_monthly\")\n\t|> range(start: -10y, stop: now())\n\t|> filter(fn: (r) => r[\"_measurement\"] == \"smart\" )\n\t|> filter(fn: (r) => r[\"_field\"] == \"temp\" or r[\"_field\"] == \"power_on_hours\" or r[\"_field\"] == \"date\")\n\t|> last()\n\t|> schema.fieldsAsCols()\n\t|> group(columns: [\"device_wwn\"])\n\t\n\tyearlyData = from(bucket: bucketBaseName + \"_yearly\")\n\t|> range(start: -10y, stop: now())\n\t|> filter(fn: (r) => r[\"_measurement\"] == \"smart\" )\n\t|> filter(fn: (r) => r[\"_field\"] == \"temp\" or r[\"_field\"] == \"power_on_hours\" or r[\"_field\"] == \"date\")\n\t|> last()\n\t|> schema.fieldsAsCols()\n\t|> group(columns: [\"device_wwn\"])\n\t\n\tunion(tables: [dailyData, weeklyData, monthlyData, yearlyData])\n\t|> sort(columns: [\"_time\"], desc: false)\n\t|> group(columns: [\"device_wwn\"])\n\t|> last(column: \"device_wwn\")\n\t|> yield(name: \"last\")\n\t\t`,\n\t\tsr.appConfig.GetString(\"web.influxdb.bucket\"),\n\t)\n\n\tresult, err := sr.influxQueryApi.Query(ctx, queryStr)\n\tif err == nil {\n\t\t// Use Next() to iterate over query result lines\n\t\tfor result.Next() {\n\t\t\t// Observe when there is new grouping key producing new table\n\t\t\tif result.TableChanged() {\n\t\t\t\t//fmt.Printf(\"table: %s\\n\", result.TableMetadata().String())\n\t\t\t}\n\t\t\t// read result\n\n\t\t\t//get summary data from Influxdb.\n\t\t\t//result.Record().Values()\n\t\t\tif deviceWWN, ok := result.Record().Values()[\"device_wwn\"]; ok {\n\n\t\t\t\t//ensure summaries is intialized for this wwn\n\t\t\t\tif _, exists := summaries[deviceWWN.(string)]; !exists {\n\t\t\t\t\tsummaries[deviceWWN.(string)] = &models.DeviceSummary{}\n\t\t\t\t}\n\n\t\t\t\tsummaries[deviceWWN.(string)].SmartResults = &models.SmartSummary{\n\t\t\t\t\tTemp: result.Record().Values()[\"temp\"].(int64),\n\t\t\t\t\tPowerOnHours: result.Record().Values()[\"power_on_hours\"].(int64),\n\t\t\t\t\tCollectorDate: result.Record().Values()[\"_time\"].(time.Time),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif result.Err() != nil {\n\t\t\tfmt.Printf(\"Query error: %s\\n\", result.Err().Error())\n\t\t}\n\t} else {\n\t\treturn nil, err\n\t}\n\n\tdeviceTempHistory, err := sr.GetSmartTemperatureHistory(ctx, DURATION_KEY_FOREVER)\n\tif err != nil {\n\t\tsr.logger.Printf(\"========================>>>>>>>>======================\")\n\t\tsr.logger.Printf(\"========================>>>>>>>>======================\")\n\t\tsr.logger.Printf(\"========================>>>>>>>>======================\")\n\t\tsr.logger.Printf(\"========================>>>>>>>>======================\")\n\t\tsr.logger.Printf(\"========================>>>>>>>>======================\")\n\t\tsr.logger.Printf(\"Error: %v\", err)\n\t}\n\tfor wwn, tempHistory := range deviceTempHistory {\n\t\tsummaries[wwn].TempHistory = tempHistory\n\t}\n\n\treturn summaries, nil\n}", "func ServerMetrics() (*Metrics, error) {\n\t// Fetch total artists\n\tartists, err := data.DB.CountArtists()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Fetch total albums\n\talbums, err := data.DB.CountAlbums()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Fetch total songs\n\tsongs, err := data.DB.CountSongs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Fetch total folders\n\tfolders, err := data.DB.CountFolders()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Combine all metrics\n\treturn &Metrics{\n\t\tArtists: artists,\n\t\tAlbums: albums,\n\t\tSongs: songs,\n\t\tFolders: folders,\n\t}, nil\n}", "func (c *summaryCache) get() map[string]*eventsStatementsSummaryByDigest {\n\tc.rw.RLock()\n\tdefer c.rw.RUnlock()\n\n\tres := make(map[string]*eventsStatementsSummaryByDigest, len(c.items))\n\tfor k, v := range c.items {\n\t\tres[k] = v\n\t}\n\treturn res\n}", "func Read(\n\tctx context.Context,\n\tendpoint *url.URL,\n\ttp auth.TokenProvider,\n\tlabels []prompb.Label,\n\tago, latency time.Duration,\n\tm instr.Metrics,\n\tl log.Logger,\n\ttls options.TLS,\n) (int, error) {\n\tvar (\n\t\trt http.RoundTripper\n\t\terr error\n\t)\n\n\tif endpoint.Scheme == transport.HTTPS {\n\t\trt, err = transport.NewTLSTransport(l, tls)\n\t\tif err != nil {\n\t\t\treturn 0, errors.Wrap(err, \"create round tripper\")\n\t\t}\n\n\t\trt = auth.NewBearerTokenRoundTripper(l, tp, rt)\n\t} else {\n\t\trt = auth.NewBearerTokenRoundTripper(l, tp, nil)\n\t}\n\n\tclient, err := promapi.NewClient(promapi.Config{\n\t\tAddress: endpoint.String(),\n\t\tRoundTripper: rt,\n\t})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tlabelSelectors := make([]string, len(labels))\n\tfor i, label := range labels {\n\t\tlabelSelectors[i] = fmt.Sprintf(`%s=\"%s\"`, label.Name, label.Value)\n\t}\n\n\tquery := fmt.Sprintf(\"{%s}\", strings.Join(labelSelectors, \",\"))\n\tts := time.Now().Add(ago)\n\n\tvalue, httpCode, _, err := api.Query(ctx, client, query, ts, false)\n\tif err != nil {\n\t\treturn httpCode, errors.Wrap(err, \"query request failed\")\n\t}\n\n\tvec := value.(model.Vector)\n\tif len(vec) != 1 {\n\t\treturn httpCode, errors.Errorf(\"expected one metric, got %d\", len(vec))\n\t}\n\n\tt := time.Unix(int64(vec[0].Value/1000), 0)\n\n\tdiffSeconds := time.Since(t).Seconds()\n\n\tm.MetricValueDifference.Observe(diffSeconds)\n\n\tif diffSeconds > latency.Seconds() {\n\t\treturn httpCode, errors.Errorf(\"metric value is too old: %2.fs\", diffSeconds)\n\t}\n\n\treturn httpCode, nil\n}", "func getMetrics(_ string) []string {\n\tvar (\n\t\terr error\n\t\tsession *Session\n\t\tclient orchestrator.OrchestratorClient\n\t\tres *orchestrator.ListMetricsResponse\n\t)\n\n\tif session, err = ContinueSession(); err != nil {\n\t\tfmt.Printf(\"Error while retrieving the session. Please re-authenticate.\\n\")\n\t\treturn nil\n\t}\n\n\tclient = orchestrator.NewOrchestratorClient(session)\n\n\tif res, err = client.ListMetrics(context.Background(), &orchestrator.ListMetricsRequest{}); err != nil {\n\t\treturn []string{}\n\t}\n\n\tvar metrics []string\n\tfor _, v := range res.Metrics {\n\t\tmetrics = append(metrics, fmt.Sprintf(\"%s\\t%s: %s\", v.Id, v.Name, v.Description))\n\t}\n\n\treturn metrics\n}", "func (m Metrics) MetricStruct() {}", "func (h *StatsHandlers) getStats(c *gin.Context) {\n\tdb, ok := c.MustGet(\"databaseConn\").(*gorm.DB)\n\tif !ok {\n\t\treturn\n\t}\n\n\tvar stats []models.Stats\n\tdb.Limit(60 * 5).Order(\"created_date desc\").Find(&stats)\n\n\tSuccess(c, \"stats\", gin.H{\n\t\t\"title\": \"Stats\",\n\t\t\"stats\": stats})\n\n}" ]
[ "0.63227373", "0.5876255", "0.58494925", "0.58435", "0.5822314", "0.5772896", "0.5730107", "0.56519294", "0.56305707", "0.56088465", "0.5589029", "0.5588156", "0.5586257", "0.55593395", "0.55461884", "0.54866064", "0.54594845", "0.54443604", "0.5433243", "0.5426571", "0.5410528", "0.53490496", "0.5344679", "0.531531", "0.53000236", "0.5287589", "0.5275283", "0.5272943", "0.5268425", "0.5245843", "0.52366763", "0.52324414", "0.52313375", "0.5229259", "0.5218071", "0.5212275", "0.52122647", "0.52095604", "0.5207078", "0.52051544", "0.51929003", "0.5191632", "0.51883733", "0.51880074", "0.5172249", "0.51608557", "0.5158026", "0.51496845", "0.51483816", "0.51467407", "0.5137313", "0.5135146", "0.5127221", "0.5125391", "0.5125155", "0.5119823", "0.51148677", "0.51023525", "0.5099337", "0.50983155", "0.5093375", "0.5083848", "0.50821453", "0.5075079", "0.506536", "0.50622094", "0.50608796", "0.50552535", "0.5049605", "0.5047184", "0.50314313", "0.5027024", "0.50252265", "0.5023107", "0.50154036", "0.5012451", "0.5011658", "0.5009043", "0.50062954", "0.50032693", "0.50012875", "0.49996588", "0.49896225", "0.49834898", "0.49812722", "0.4980547", "0.49801648", "0.49771622", "0.49642426", "0.4962569", "0.4957777", "0.4957008", "0.49491656", "0.49477345", "0.4946963", "0.49464607", "0.49455923", "0.49450934", "0.49370977", "0.49330106" ]
0.62895125
1
Collect will process darkstats metrics locally and fill singleton with latest data
func Collect(ctx context.Context) error { if !singleton.enabled { return nil } if singleton.darkstatAddr == "" { return fmt.Errorf("Darkstat address is empty") } startTime := time.Now() inventoryHosts := inventory.Get() localAddr, err := network.DefaultLocalAddr() if err != nil { return err } // To label source traffic that we need to build dependency graph localHostgroup := localAddr.String() localDomain := localAddr.String() localInventory, ok := inventoryHosts[localAddr.String()] if ok { localHostgroup = localInventory.Hostgroup localDomain = localInventory.Domain } log.Debugf("Local address don't exist in inventory: %v", localAddr.String()) // Scrape darkstat prometheus endpoint for host_bytes_total var darkstatHostBytesTotal *prom2json.Family darkstatScrape, err := prometheus.Scrape(singleton.darkstatAddr) if err != nil { return err } for _, v := range darkstatScrape { if v.Name == "host_bytes_total" { darkstatHostBytesTotal = v break } } if darkstatHostBytesTotal == nil { return fmt.Errorf("Metric host_bytes_total doesn't exist") } // Extract relevant data out of host_bytes_total var hosts []Metric for _, m := range darkstatHostBytesTotal.Metrics { metric := m.(prom2json.Metric) ip := net.ParseIP(metric.Labels["ip"]) // Skip its own IP as we don't need it if ip.Equal(localAddr) { continue } inventoryHostInfo := inventoryHosts[metric.Labels["ip"]] bandwidth, err := strconv.ParseFloat(metric.Value, 64) if err != nil { log.Errorf("Failed to parse 'host_bytes_total' value: %v", err) continue } direction := "" // Reversed from netfilter perspective switch metric.Labels["dir"] { case "out": direction = "ingress" case "in": direction = "egress" } hosts = append(hosts, Metric{ LocalHostgroup: localHostgroup, RemoteHostgroup: inventoryHostInfo.Hostgroup, RemoteIPAddr: metric.Labels["ip"], LocalDomain: localDomain, RemoteDomain: inventoryHostInfo.Domain, Direction: direction, Bandwidth: bandwidth, }) } singleton.mu.Lock() singleton.hosts = hosts singleton.mu.Unlock() log.Debugf("taskdarkstat.Collect retrieved %v downstreams metrics", len(hosts)) log.Debugf("taskdarkstat.Collect process took %v", time.Since(startTime)) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tif err := e.scrape(); err != nil {\n\t\tlog.Error(err)\n\t\tnomad_up.Set(0)\n\t\tch <- nomad_up\n\t\treturn\n\t}\n\n\tch <- nomad_up\n\tch <- metric_uptime\n\tch <- metric_request_response_time_total\n\tch <- metric_request_response_time_avg\n\n\tfor _, metric := range metric_request_status_count_current {\n\t\tch <- metric\n\t}\n\tfor _, metric := range metric_request_status_count_total {\n\t\tch <- metric\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.scrape(ch); err != nil {\n\t\tlog.Printf(\"Error scraping nightscout url: %s\", err)\n\t}\n\n\te.statusNightscout.Collect(ch)\n\n\treturn\n}", "func (c *Collector) Collect(ch chan<- prometheus.Metric) {\n\tip := os.Getenv(\"DYNO_INSTANCE\")\n\tif ip == \"\" {\n\t\tlogg.Error(\"could not get ip address from env variable: DYNO_INSTANCE\")\n\t}\n\n\ttoken := os.Getenv(\"DYNO_TOKEN\")\n\tif token == \"\" {\n\t\tlogg.Error(\"could not get token from env variable: DYNO_TOKEN\")\n\t}\n\n\tvar rack, dc string\n\tir, err := c.dyno.Info()\n\tif err != nil {\n\t\tlogg.Error(err.Error())\n\t} else {\n\t\track = ir.Rack\n\t\tdc = ir.DC\n\n\t\tch <- c.uptime.mustNewConstMetric(float64(ir.Uptime), rack, dc, token, ip)\n\t\tch <- c.clientConnections.mustNewConstMetric(float64(ir.Pool.ClientConnections), rack, dc, token, ip)\n\t\tch <- c.clientReadRequests.mustNewConstMetric(float64(ir.Pool.ClientReadRequests), rack, dc, token, ip)\n\t\tch <- c.clientWriteRequests.mustNewConstMetric(float64(ir.Pool.ClientWriteRequests), rack, dc, token, ip)\n\t\tch <- c.clientDroppedRequests.mustNewConstMetric(float64(ir.Pool.ClientDroppedRequests), rack, dc, token, ip)\n\t}\n\n\tstateVal := 1 // until proven otherwise\n\tstateStr := \"unknown\" // always have a value for the state label\n\n\tstate, err := c.dyno.GetState()\n\tif err != nil {\n\t\tstateVal = 0\n\t\tlogg.Error(err.Error())\n\t} else {\n\t\tstateStr = string(state)\n\t}\n\n\tif state != Normal {\n\t\tstateVal = 0\n\t}\n\tch <- c.state.mustNewConstMetric(float64(stateVal), stateStr, rack, dc, token, ip)\n\n\tsize, err := c.dyno.Backend.DBSize()\n\tif err != nil {\n\t\tlogg.Error(err.Error())\n\t} else {\n\t\tch <- c.dbSize.mustNewConstMetric(float64(size), rack, dc, token, ip)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\t// Reset metrics.\n\tfor _, vec := range e.gauges {\n\t\tvec.Reset()\n\t}\n\n\tfor _, vec := range e.counters {\n\t\tvec.Reset()\n\t}\n\n\tresp, err := e.client.Get(e.URI)\n\tif err != nil {\n\t\te.up.Set(0)\n\t\tlog.Printf(\"Error while querying Elasticsearch: %v\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tlog.Printf(\"Failed to read ES response body: %v\", err)\n\t\te.up.Set(0)\n\t\treturn\n\t}\n\n\te.up.Set(1)\n\n\tvar all_stats NodeStatsResponse\n\terr = json.Unmarshal(body, &all_stats)\n\n\tif err != nil {\n\t\tlog.Printf(\"Failed to unmarshal JSON into struct: %v\", err)\n\t\treturn\n\t}\n\n\t// Regardless of whether we're querying the local host or the whole\n\t// cluster, here we can just iterate through all nodes found.\n\n\tfor node, stats := range all_stats.Nodes {\n\t\tlog.Printf(\"Processing node %v\", node)\n\t\t// GC Stats\n\t\tfor collector, gcstats := range stats.JVM.GC.Collectors {\n\t\t\te.counters[\"jvm_gc_collection_count\"].WithLabelValues(all_stats.ClusterName, stats.Name, collector).Set(float64(gcstats.CollectionCount))\n\t\t\te.counters[\"jvm_gc_collection_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name, collector).Set(float64(gcstats.CollectionTime))\n\t\t}\n\n\t\t// Breaker stats\n\t\tfor breaker, bstats := range stats.Breakers {\n\t\t\te.gauges[\"breakers_estimated_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name, breaker).Set(float64(bstats.EstimatedSize))\n\t\t\te.gauges[\"breakers_limit_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name, breaker).Set(float64(bstats.LimitSize))\n\t\t}\n\n\t\t// JVM Memory Stats\n\t\te.gauges[\"jvm_mem_heap_committed_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapCommitted))\n\t\te.gauges[\"jvm_mem_heap_used_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapUsed))\n\t\te.gauges[\"jvm_mem_heap_max_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapMax))\n\t\te.gauges[\"jvm_mem_non_heap_committed_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.NonHeapCommitted))\n\t\te.gauges[\"jvm_mem_non_heap_used_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.NonHeapUsed))\n\n\t\t// Indices Stats\n\t\te.gauges[\"indices_fielddata_evictions\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FieldData.Evictions))\n\t\te.gauges[\"indices_fielddata_memory_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FieldData.MemorySize))\n\t\te.gauges[\"indices_filter_cache_evictions\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FilterCache.Evictions))\n\t\te.gauges[\"indices_filter_cache_memory_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FilterCache.MemorySize))\n\n\t\te.gauges[\"indices_docs_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Docs.Count))\n\t\te.gauges[\"indices_docs_deleted\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Docs.Deleted))\n\n\t\te.gauges[\"indices_segments_memory_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Segments.Memory))\n\n\t\te.gauges[\"indices_store_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Store.Size))\n\t\te.counters[\"indices_store_throttle_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Store.ThrottleTime))\n\n\t\te.counters[\"indices_flush_total\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Flush.Total))\n\t\te.counters[\"indices_flush_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Flush.Time))\n\n\t\t// Transport Stats\n\t\te.counters[\"transport_rx_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.RxCount))\n\t\te.counters[\"transport_rx_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.RxSize))\n\t\te.counters[\"transport_tx_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.TxCount))\n\t\te.counters[\"transport_tx_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.TxSize))\n\t}\n\n\t// Report metrics.\n\tch <- e.up\n\n\tfor _, vec := range e.counters {\n\t\tvec.Collect(ch)\n\t}\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Collect(ch)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\t// Protect metrics from concurrent collects.\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\t// Scrape metrics from Tankerkoenig API.\n\tif err := e.scrape(ch); err != nil {\n\t\te.logger.Printf(\"error: cannot scrape tankerkoenig api: %v\", err)\n\t}\n\n\t// Collect metrics.\n\te.up.Collect(ch)\n\te.scrapeDuration.Collect(ch)\n\te.failedScrapes.Collect(ch)\n\te.totalScrapes.Collect(ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tup := e.scrape(ch)\n\n\tch <- prometheus.MustNewConstMetric(artifactoryUp, prometheus.GaugeValue, up)\n\tch <- e.totalScrapes\n\tch <- e.jsonParseFailures\n}", "func (c *MetricsCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, s := range c.status {\n\t\ts.RLock()\n\t\tdefer s.RUnlock()\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.verify,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(s.VerifyRestore),\n\t\t\t\"verify_restore\",\n\t\t\ts.BackupService,\n\t\t\ts.StorageService,\n\t\t)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.verify,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(s.VerifyDiff),\n\t\t\t\"verify_diff\",\n\t\t\ts.BackupService,\n\t\t\ts.StorageService,\n\t\t)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.verify,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(s.VerifyChecksum),\n\t\t\t\"verify_checksum\",\n\t\t\ts.BackupService,\n\t\t\ts.StorageService,\n\t\t)\n\t}\n\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tfor _, db := range e.dbs {\n\t\t// logger.Log(\"Scraping\", db.String())\n\t\tgo e.scrapeDatabase(db)\n\t}\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\te.cpuPercent.Collect(ch)\n\te.dataIO.Collect(ch)\n\te.logIO.Collect(ch)\n\te.memoryPercent.Collect(ch)\n\te.workPercent.Collect(ch)\n\te.sessionPercent.Collect(ch)\n\te.storagePercent.Collect(ch)\n\te.dbUp.Collect(ch)\n\te.up.Set(1)\n}", "func (sc *SlurmCollector) Collect(ch chan<- prometheus.Metric) {\n\tsc.mutex.Lock()\n\tdefer sc.mutex.Unlock()\n\n\tlog.Debugf(\"Time since last scrape: %f seconds\", time.Since(sc.lastScrape).Seconds())\n\tif time.Since(sc.lastScrape).Seconds() > float64(sc.scrapeInterval) {\n\t\tsc.updateDynamicJobIds()\n\t\tvar err error\n\t\tsc.sshClient, err = sc.sshConfig.NewClient()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Creating SSH client: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tdefer sc.sshClient.Close()\n\t\tlog.Infof(\"Collecting metrics from Slurm...\")\n\t\tsc.trackedJobs = make(map[string]bool)\n\t\tif sc.targetJobIds == \"\" {\n\t\t\t// sc.collectQueue()\n\t\t} else {\n\t\t\tsc.collectAcct()\n\t\t}\n\t\tif !sc.skipInfra {\n\t\t\tsc.collectInfo()\n\t\t}\n\t\tsc.lastScrape = time.Now()\n\t\tsc.delJobs()\n\n\t}\n\n\tsc.updateMetrics(ch)\n}", "func (c *Collector) Collect(ch chan<- prometheus.Metric) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tc.totalScrapes.Inc()\n\terr := c.getDadataBalance()\n\tif err != nil {\n\t\tc.failedBalanceScrapes.Inc()\n\t}\n\terr = c.getDadataStats()\n\tif err != nil {\n\t\tc.failedStatsScrapes.Inc()\n\t}\n\n\tch <- c.totalScrapes\n\tch <- c.failedBalanceScrapes\n\tch <- c.failedStatsScrapes\n\tch <- c.CurrentBalance\n\tch <- c.ServicesClean\n\tch <- c.ServicesMerging\n\tch <- c.ServicesSuggestions\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Reset()\n\t}\n\n\tdefer func() { ch <- e.up }()\n\n\t// If we fail at any point in retrieving GPU status, we fail 0\n\te.up.Set(1)\n\n\te.GetTelemetryFromNVML()\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Collect(ch)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tvar (\n\t\tdata *Data\n\t\terr error\n\t)\n\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\te.resetGaugeVecs() // Clean starting point\n\n\tvar endpointOfAPI []string\n\tif strings.HasSuffix(rancherURL, \"v3\") || strings.HasSuffix(rancherURL, \"v3/\") {\n\t\tendpointOfAPI = endpointsV3\n\t} else {\n\t\tendpointOfAPI = endpoints\n\t}\n\n\tcacheExpired := e.IsCacheExpired()\n\n\t// Range over the pre-configured endpoints array\n\tfor _, p := range endpointOfAPI {\n\t\tif cacheExpired {\n\t\t\tdata, err = e.gatherData(e.rancherURL, e.resourceLimit, e.accessKey, e.secretKey, p, ch)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error getting JSON from URL %s\", p)\n\t\t\t\treturn\n\t\t\t}\n\t\t\te.cache[p] = data\n\t\t} else {\n\t\t\td, ok := e.cache[p]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdata = d\n\t\t}\n\n\t\tif err := e.processMetrics(data, p, e.hideSys, ch); err != nil {\n\t\t\tlog.Errorf(\"Error scraping rancher url: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tlog.Infof(\"Metrics successfully processed for %s\", p)\n\t}\n\n\tif cacheExpired {\n\t\te.RenewCache()\n\t}\n\n\tfor _, m := range e.gaugeVecs {\n\t\tm.Collect(ch)\n\t}\n}", "func (collector *OpenweatherCollector) Collect(ch chan<- prometheus.Metric) {\n\t// Get Coords\n\tlatitude, longitude := geo.Get_coords(openstreetmap.Geocoder(), collector.Location)\n\n\t// Setup HTTP Client\n\tclient := &http.Client{\n\t\tTimeout: 1 * time.Second,\n\t}\n\n\t// Grab Metrics\n\tw, err := owm.NewCurrent(collector.DegreesUnit, collector.Language, collector.ApiKey, owm.WithHttpClient(client))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tlog.Infof(\"Collecting metrics from openweather API successful\")\n\t}\n\n\tw.CurrentByCoordinates(&owm.Coordinates{Longitude: longitude, Latitude: latitude})\n\n\t// Get Weather description out of Weather slice to pass as label\n\tvar weather_description string\n\tfor _, n := range w.Weather {\n\t\tweather_description = n.Description\n\t}\n\n\t//Write latest value for each metric in the prometheus metric channel.\n\t//Note that you can pass CounterValue, GaugeValue, or UntypedValue types here.\n\tch <- prometheus.MustNewConstMetric(collector.temperatureMetric, prometheus.GaugeValue, w.Main.Temp, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.humidity, prometheus.GaugeValue, float64(w.Main.Humidity), collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.feelslike, prometheus.GaugeValue, w.Main.FeelsLike, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.pressure, prometheus.GaugeValue, w.Main.Pressure, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.windspeed, prometheus.GaugeValue, w.Wind.Speed, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.rain1h, prometheus.GaugeValue, w.Rain.OneH, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.winddegree, prometheus.GaugeValue, w.Wind.Deg, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.cloudiness, prometheus.GaugeValue, float64(w.Clouds.All), collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.sunrise, prometheus.GaugeValue, float64(w.Sys.Sunrise), collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.sunset, prometheus.GaugeValue, float64(w.Sys.Sunset), collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.snow1h, prometheus.GaugeValue, w.Snow.OneH, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.currentconditions, prometheus.GaugeValue, 0, collector.Location, weather_description)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tvar up float64 = 1\n\n\tglobalMutex.Lock()\n\tdefer globalMutex.Unlock()\n\n\tif e.config.resetStats && !globalResetExecuted {\n\t\t// Its time to try to reset the stats\n\t\tif e.resetStatsSemp1() {\n\t\t\tlevel.Info(e.logger).Log(\"msg\", \"Statistics successfully reset\")\n\t\t\tglobalResetExecuted = true\n\t\t\tup = 1\n\t\t} else {\n\t\t\tup = 0\n\t\t}\n\t}\n\n\tif e.config.details {\n\t\tif up > 0 {\n\t\t\tup = e.getClientSemp1(ch)\n\t\t}\n\t\tif up > 0 {\n\t\t\tup = e.getQueueSemp1(ch)\n\t\t}\n\t\tif up > 0 && e.config.scrapeRates {\n\t\t\tup = e.getQueueRatesSemp1(ch)\n\t\t}\n\t} else { // Basic\n\t\tif up > 0 {\n\t\t\tup = e.getRedundancySemp1(ch)\n\t\t}\n\t\tif up > 0 {\n\t\t\tup = e.getSpoolSemp1(ch)\n\t\t}\n\t\tif up > 0 {\n\t\t\tup = e.getHealthSemp1(ch)\n\t\t}\n\t\tif up > 0 {\n\t\t\tup = e.getVpnSemp1(ch)\n\t\t}\n\t}\n\n\tch <- prometheus.MustNewConstMetric(solaceUp, prometheus.GaugeValue, up)\n}", "func (c *OrchestratorCollector) Collect(ch chan<- prometheus.Metric) {\n\tc.mutex.Lock() // To protect metrics from concurrent collects\n\tdefer c.mutex.Unlock()\n\n\tstats, err := c.orchestratorClient.GetMetrics()\n\tif err != nil {\n\t\tc.upMetric.Set(serviceDown)\n\t\tch <- c.upMetric\n\t\tlog.Printf(\"Error getting Orchestrator stats: %v\", err)\n\t\treturn\n\t}\n\n\tc.upMetric.Set(serviceUp)\n\tch <- c.upMetric\n\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"cluter_size\"],\n\t\tprometheus.GaugeValue, float64(len(stats.Status.Details.AvailableNodes)))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"is_active_node\"],\n\t\tprometheus.GaugeValue, boolToFloat64(stats.Status.Details.IsActiveNode))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"problems\"],\n\t\tprometheus.GaugeValue, float64(len(stats.Problems)))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"last_failover_id\"],\n\t\tprometheus.CounterValue, float64(stats.LastFailoverID))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"is_healthy\"],\n\t\tprometheus.GaugeValue, boolToFloat64(stats.Status.Details.Healthy))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"failed_seeds\"],\n\t\tprometheus.CounterValue, float64(stats.FailedSeeds))\n}", "func (k *KACollector) Collect(ch chan<- prometheus.Metric) {\n\tk.mutex.Lock()\n\tdefer k.mutex.Unlock()\n\n\tvar err error\n\tvar kaStats []KAStats\n\n\tif k.useJSON {\n\t\tkaStats, err = k.json()\n\t\tif err != nil {\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_up\"], prometheus.GaugeValue, 0)\n\t\t\tlog.Printf(\"keepalived_exporter: %v\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tkaStats, err = k.text()\n\t\tif err != nil {\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_up\"], prometheus.GaugeValue, 0)\n\t\t\tlog.Printf(\"keepalived_exporter: %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_up\"], prometheus.GaugeValue, 1)\n\n\tfor _, st := range kaStats {\n\t\tstate := \"\"\n\t\tif _, ok := state2string[st.Data.State]; ok {\n\t\t\tstate = state2string[st.Data.State]\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_advert_rcvd\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AdvertRcvd), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_advert_sent\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AdvertSent), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_become_master\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.BecomeMaster), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_release_master\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.ReleaseMaster), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_packet_len_err\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.PacketLenErr), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_advert_interval_err\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AdvertIntervalErr), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_ip_ttl_err\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AdvertIntervalErr), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_invalid_type_rcvd\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.InvalidTypeRcvd), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_addr_list_err\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AddrListErr), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_invalid_authtype\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.InvalidAuthtype), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_authtype_mismatch\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AuthtypeMismatch), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_auth_failure\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AuthFailure), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_pri_zero_rcvd\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.PriZeroRcvd), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_pri_zero_sent\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.PriZeroSent), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t}\n\n\tif k.handle == nil {\n\t\treturn\n\t}\n\n\tsvcs, err := k.handle.GetServices()\n\tif err != nil {\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_up\"], prometheus.GaugeValue, 0)\n\t\tlog.Printf(\"keepalived_exporter: services: %v\", err)\n\t\treturn\n\t}\n\n\tfor _, s := range svcs {\n\t\tdsts, err := k.handle.GetDestinations(s)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"keepalived_exporter: destinations: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\taddr := s.Address.String() + \":\" + strconv.Itoa(int(s.Port))\n\t\tproto := strconv.Itoa(int(s.Protocol))\n\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_vip_in_packets\"], prometheus.CounterValue,\n\t\t\tfloat64(s.Stats.PacketsIn), addr, proto)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_vip_out_packets\"], prometheus.CounterValue,\n\t\t\tfloat64(s.Stats.PacketsOut), addr, proto)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_vip_in_bytes\"], prometheus.CounterValue,\n\t\t\tfloat64(s.Stats.BytesIn), addr, proto)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_vip_out_bytes\"], prometheus.CounterValue,\n\t\t\tfloat64(s.Stats.BytesOut), addr, proto)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_vip_conn\"], prometheus.CounterValue,\n\t\t\tfloat64(s.Stats.Connections), addr, proto)\n\n\t\tfor _, d := range dsts {\n\t\t\taddr := d.Address.String() + \":\" + strconv.Itoa(int(d.Port))\n\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_rs_in_packets\"], prometheus.CounterValue,\n\t\t\t\tfloat64(d.Stats.PacketsIn), addr, proto)\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_rs_out_packets\"], prometheus.CounterValue,\n\t\t\t\tfloat64(d.Stats.PacketsOut), addr, proto)\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_rs_in_bytes\"], prometheus.CounterValue,\n\t\t\t\tfloat64(d.Stats.BytesIn), addr, proto)\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_rs_out_bytes\"], prometheus.CounterValue,\n\t\t\t\tfloat64(d.Stats.BytesOut), addr, proto)\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_rs_conn\"], prometheus.CounterValue,\n\t\t\t\tfloat64(d.Stats.Connections), addr, proto)\n\t\t}\n\t}\n}", "func (c *solarCollector) Collect(ch chan<- prometheus.Metric) {\n\tc.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer c.mutex.Unlock()\n\tif err := c.collect(ch); err != nil {\n\t\tlog.Printf(\"Error getting solar controller data: %s\", err)\n\t\tc.scrapeFailures.Inc()\n\t\tc.scrapeFailures.Collect(ch)\n\t}\n\treturn\n}", "func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) {\n\toomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState()\n\tfor host, oomCount := range oomCountByHost {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.OOMCountDesc,\n\t\t\tprometheus.CounterValue,\n\t\t\tfloat64(oomCount),\n\t\t\thost,\n\t\t)\n\t}\n\tfor host, ramUsage := range ramUsageByHost {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.RAMUsageDesc,\n\t\t\tprometheus.GaugeValue,\n\t\t\tramUsage,\n\t\t\thost,\n\t\t)\n\t}\n}", "func (e *UwsgiExporter) Collect(ch chan<- prometheus.Metric) {\n\tstartTime := time.Now()\n\terr := e.execute(ch)\n\td := time.Since(startTime).Seconds()\n\n\tif err != nil {\n\t\tlog.Errorf(\"ERROR: scrape failed after %fs: %s\", d, err)\n\t\te.uwsgiUp.Set(0)\n\t\te.scrapeDurations.WithLabelValues(\"error\").Observe(d)\n\t} else {\n\t\tlog.Debugf(\"OK: scrape successful after %fs.\", d)\n\t\te.uwsgiUp.Set(1)\n\t\te.scrapeDurations.WithLabelValues(\"success\").Observe(d)\n\t}\n\n\te.uwsgiUp.Collect(ch)\n\te.scrapeDurations.Collect(ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tignore := strings.Split(*flagStatsIgnore, \",\")\n\tif len(ignore) == 1 && ignore[0] == \"\" {\n\t\tignore = []string{}\n\t}\n\tnicks := strings.Split(*flagStatsNicks, \",\")\n\tif len(nicks) == 1 && nicks[0] == \"\" {\n\t\tnicks = []string{}\n\t}\n\tres := e.client.Stats(irc.StatsRequest{\n\t\tLocal: *flagStatsLocal,\n\t\tTimeout: *flagStatsTimeout,\n\t\tIgnoreServers: ignore,\n\t\tNicks: nicks,\n\t})\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tconnected, prometheus.GaugeValue, boolToFloat[e.client.Server != \"\"])\n\n\t_, ok := res.Servers[e.client.Server]\n\tif res.Timeout && !ok {\n\t\t// Timeout, no data at all\n\t\tif e.client.Server != \"\" {\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tup, prometheus.GaugeValue, 0.0, e.client.Server)\n\t\t}\n\t} else {\n\t\t// Global state\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tchannels, prometheus.GaugeValue, float64(res.Channels))\n\n\t\tfor nick, nickIson := range res.Nicks {\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tison, prometheus.GaugeValue, boolToFloat[nickIson], nick)\n\t\t}\n\n\t\t// Per server state\n\t\tfor server, stats := range res.Servers {\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tdistance, prometheus.GaugeValue, float64(stats.Distance), server)\n\n\t\t\tif *flagStatsLocal && e.client.Server != server {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tup, prometheus.GaugeValue, boolToFloat[stats.Up], server)\n\n\t\t\tif stats.Up {\n\t\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\t\tusers, prometheus.GaugeValue, float64(stats.Users), server)\n\n\t\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\t\tlatency, prometheus.GaugeValue, float64(stats.ResponseTime.Sub(stats.RequestTime))/float64(time.Second), server)\n\t\t\t}\n\t\t}\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n if err := e.scrape(ch); err != nil {\n\t\tlog.Infof(\"Error scraping tinystats: %s\", err)\n\t}\n e.ipv4QueryA.Collect(ch)\n e.ipv4QueryNS.Collect(ch)\n e.ipv4QueryCNAME.Collect(ch)\n e.ipv4QuerySOA.Collect(ch)\n e.ipv4QueryPTR.Collect(ch)\n e.ipv4QueryHINFO.Collect(ch)\n e.ipv4QueryMX.Collect(ch)\n e.ipv4QueryTXT.Collect(ch)\n e.ipv4QueryRP.Collect(ch)\n e.ipv4QuerySIG.Collect(ch)\n e.ipv4QueryKEY.Collect(ch)\n e.ipv4QueryAAAA.Collect(ch)\n e.ipv4QueryAXFR.Collect(ch)\n e.ipv4QueryANY.Collect(ch)\n e.ipv4QueryTOTAL.Collect(ch)\n e.ipv4QueryOTHER.Collect(ch)\n e.ipv4QueryNOTAUTH.Collect(ch)\n e.ipv4QueryNOTIMPL.Collect(ch)\n e.ipv4QueryBADCLASS.Collect(ch)\n e.ipv4QueryNOQUERY.Collect(ch)\n\n e.ipv6QueryA.Collect(ch)\n e.ipv6QueryNS.Collect(ch)\n e.ipv6QueryCNAME.Collect(ch)\n e.ipv6QuerySOA.Collect(ch)\n e.ipv6QueryPTR.Collect(ch)\n e.ipv6QueryHINFO.Collect(ch)\n e.ipv6QueryMX.Collect(ch)\n e.ipv6QueryTXT.Collect(ch)\n e.ipv6QueryRP.Collect(ch)\n e.ipv6QuerySIG.Collect(ch)\n e.ipv6QueryKEY.Collect(ch)\n e.ipv6QueryAAAA.Collect(ch)\n e.ipv6QueryAXFR.Collect(ch)\n e.ipv6QueryANY.Collect(ch)\n e.ipv6QueryTOTAL.Collect(ch)\n e.ipv6QueryOTHER.Collect(ch)\n e.ipv6QueryNOTAUTH.Collect(ch)\n e.ipv6QueryNOTIMPL.Collect(ch)\n e.ipv6QueryBADCLASS.Collect(ch)\n e.ipv6QueryNOQUERY.Collect(ch)\n\n\treturn\n}", "func (r *RGWCollector) Collect(ch chan<- prometheus.Metric, version *Version) {\n\tif !r.background {\n\t\tr.logger.WithField(\"background\", r.background).Debug(\"collecting RGW GC stats\")\n\t\terr := r.collect()\n\t\tif err != nil {\n\t\t\tr.logger.WithField(\"background\", r.background).WithError(err).Error(\"error collecting RGW GC stats\")\n\t\t}\n\t}\n\n\tfor _, metric := range r.collectorList() {\n\t\tmetric.Collect(ch)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tup, result := e.scrape(ch)\n\n\tch <- e.totalScrapes\n\tch <- e.jsonParseFailures\n\tch <- prometheus.MustNewConstMetric(iqAirUp, prometheus.GaugeValue, up)\n\tch <- prometheus.MustNewConstMetric(iqAirCO2, prometheus.GaugeValue, float64(result.CO2))\n\tch <- prometheus.MustNewConstMetric(iqAirP25, prometheus.GaugeValue, float64(result.P25))\n\tch <- prometheus.MustNewConstMetric(iqAirP10, prometheus.GaugeValue, float64(result.P10))\n\tch <- prometheus.MustNewConstMetric(iqAirTemp, prometheus.GaugeValue, float64(result.Temperature))\n\tch <- prometheus.MustNewConstMetric(iqAirHumidity, prometheus.GaugeValue, float64(result.Humidity))\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tlog.Infof(\"Syno exporter starting\")\n\tif e.Client == nil {\n\t\tlog.Errorf(\"Syno client not configured.\")\n\t\treturn\n\t}\n\terr := e.Client.Connect()\n\tif err != nil {\n\t\tlog.Errorln(\"Can't connect to Synology for SNMP: %s\", err)\n\t\treturn\n\t}\n\tdefer e.Client.SNMP.Conn.Close()\n\n\te.collectSystemMetrics(ch)\n\te.collectCPUMetrics(ch)\n\te.collectLoadMetrics(ch)\n\te.collectMemoryMetrics(ch)\n\te.collectNetworkMetrics(ch)\n\te.collectDiskMetrics(ch)\n\n\tlog.Infof(\"Syno exporter finished\")\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\te.zpool.getStatus()\n\te.poolUsage.Set(float64(e.zpool.capacity))\n\te.providersOnline.Set(float64(e.zpool.online))\n\te.providersFaulted.Set(float64(e.zpool.faulted))\n\n\tch <- e.poolUsage\n\tch <- e.providersOnline\n\tch <- e.providersFaulted\n}", "func Collect(metrics []Metric, c CloudWatchService, namespace string) {\n\tid, err := GetInstanceID()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, metric := range metrics {\n\t\tmetric.Collect(id, c, namespace)\n\t}\n}", "func (p *Collector) Collect(c chan<- prometheus.Metric) {\n\tp.Sink.mu.Lock()\n\tdefer p.Sink.mu.Unlock()\n\n\texpire := p.Sink.expiration != 0\n\tnow := time.Now()\n\tfor k, v := range p.Sink.gauges {\n\t\tlast := p.Sink.updates[k]\n\t\tif expire && last.Add(p.Sink.expiration).Before(now) {\n\t\t\tdelete(p.Sink.updates, k)\n\t\t\tdelete(p.Sink.gauges, k)\n\t\t} else {\n\t\t\tv.Collect(c)\n\t\t}\n\t}\n\tfor k, v := range p.Sink.summaries {\n\t\tlast := p.Sink.updates[k]\n\t\tif expire && last.Add(p.Sink.expiration).Before(now) {\n\t\t\tdelete(p.Sink.updates, k)\n\t\t\tdelete(p.Sink.summaries, k)\n\t\t} else {\n\t\t\tv.Collect(c)\n\t\t}\n\t}\n\tfor k, v := range p.Sink.counters {\n\t\tlast := p.Sink.updates[k]\n\t\tif expire && last.Add(p.Sink.expiration).Before(now) {\n\t\t\tdelete(p.Sink.updates, k)\n\t\t\tdelete(p.Sink.counters, k)\n\t\t} else {\n\t\t\tv.Collect(c)\n\t\t}\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tresp, err := e.Pihole.GetMetrics()\n\tif err != nil {\n\t\tlog.Errorf(\"Pihole error: %s\", err.Error())\n\t\treturn\n\t}\n\tlog.Debugf(\"PiHole metrics: %#v\", resp)\n\tch <- prometheus.MustNewConstMetric(\n\t\tdomainsBeingBlocked, prometheus.CounterValue, float64(resp.DomainsBeingBlocked))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tdnsQueries, prometheus.CounterValue, float64(resp.DNSQueriesToday))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tadsBlocked, prometheus.CounterValue, float64(resp.AdsBlockedToday))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tadsPercentage, prometheus.CounterValue, float64(resp.AdsPercentageToday))\n\n\tfor k, v := range resp.Querytypes {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tqueryTypes, prometheus.CounterValue, v, k)\n\t}\n\tfor k, v := range resp.TopQueries {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopQueries, prometheus.CounterValue, float64(v), k)\n\t}\n\tfor k, v := range resp.TopAds {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopAds, prometheus.CounterValue, float64(v), k)\n\n\t}\n\tfor k, v := range resp.TopSources {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopSources, prometheus.CounterValue, float64(v), k)\n\t}\n}", "func (collector *MetricsCollector) Collect(ch chan<- prometheus.Metric) {\n\tfilterMetricsByKind := func(kind string, orgMetrics []constMetric) (filteredMetrics []constMetric) {\n\t\tfor _, metric := range orgMetrics {\n\t\t\tif metric.kind == kind {\n\t\t\t\tfilteredMetrics = append(filteredMetrics, metric)\n\t\t\t}\n\t\t}\n\t\treturn filteredMetrics\n\t}\n\tcollector.defMetrics.reset()\n\tfor k := range collector.metrics {\n\t\tcounters := filterMetricsByKind(config.KeyMetricTypeCounter, collector.metrics[k])\n\t\tgauges := filterMetricsByKind(config.KeyMetricTypeGauge, collector.metrics[k])\n\t\thistograms := filterMetricsByKind(config.KeyMetricTypeHistogram, collector.metrics[k])\n\t\tcollectCounters(counters, collector.defMetrics, ch)\n\t\tcollectGauges(gauges, collector.defMetrics, ch)\n\t\tcollectHistograms(histograms, collector.defMetrics, ch)\n\t\tcollector.cache.Reset()\n\t}\n\tcollector.defMetrics.collectDefaultMetrics(ch)\n}", "func (collector *Collector) Collect(ch chan<- prometheus.Metric) {\n\tch <- prometheus.MustNewConstMetric(collector.incidentsCreatedCount, prometheus.CounterValue, collector.storage.GetIncidentsCreatedCount())\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tjunosTotalScrapeCount++\n\tch <- prometheus.MustNewConstMetric(junosDesc[\"ScrapesTotal\"], prometheus.CounterValue, junosTotalScrapeCount)\n\n\twg := &sync.WaitGroup{}\n\tfor _, collector := range e.Collectors {\n\t\twg.Add(1)\n\t\tgo e.runCollector(ch, collector, wg)\n\t}\n\twg.Wait()\n}", "func (c *auditdCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (o *OSDCollector) Collect(ch chan<- prometheus.Metric, version *Version) {\n\t// Reset daemon specific metrics; daemons can leave the cluster\n\to.CrushWeight.Reset()\n\to.Depth.Reset()\n\to.Reweight.Reset()\n\to.Bytes.Reset()\n\to.UsedBytes.Reset()\n\to.AvailBytes.Reset()\n\to.Utilization.Reset()\n\to.Variance.Reset()\n\to.Pgs.Reset()\n\to.CommitLatency.Reset()\n\to.ApplyLatency.Reset()\n\to.OSDIn.Reset()\n\to.OSDUp.Reset()\n\to.OSDMetadata.Reset()\n\to.buildOSDLabelCache()\n\n\tlocalWg := &sync.WaitGroup{}\n\n\tlocalWg.Add(1)\n\tgo func() {\n\t\tdefer localWg.Done()\n\t\tif err := o.collectOSDPerf(); err != nil {\n\t\t\to.logger.WithError(err).Error(\"error collecting OSD perf metrics\")\n\t\t}\n\t}()\n\n\tlocalWg.Add(1)\n\tgo func() {\n\t\tdefer localWg.Done()\n\t\tif err := o.collectOSDMetadata(); err != nil {\n\t\t\to.logger.WithError(err).Error(\"error collecting OSD metadata metrics\")\n\t\t}\n\t}()\n\n\tlocalWg.Add(1)\n\tgo func() {\n\t\tdefer localWg.Done()\n\t\tif err := o.collectOSDDump(); err != nil {\n\t\t\to.logger.WithError(err).Error(\"error collecting OSD dump metrics\")\n\t\t}\n\t}()\n\n\tlocalWg.Add(1)\n\tgo func() {\n\t\tdefer localWg.Done()\n\t\tif err := o.collectOSDDF(); err != nil {\n\t\t\to.logger.WithError(err).Error(\"error collecting OSD df metrics\")\n\t\t}\n\t}()\n\n\tlocalWg.Add(1)\n\tgo func() {\n\t\tdefer localWg.Done()\n\t\tif err := o.collectOSDTreeDown(ch); err != nil {\n\t\t\to.logger.WithError(err).Error(\"error collecting OSD tree down metrics\")\n\t\t}\n\t}()\n\n\tlocalWg.Add(1)\n\tgo func() {\n\t\tdefer localWg.Done()\n\t\tif err := o.collectOSDScrubState(ch); err != nil {\n\t\t\to.logger.WithError(err).Error(\"error collecting OSD scrub metrics\")\n\t\t}\n\t}()\n\n\tlocalWg.Wait()\n\n\tfor _, metric := range o.collectorList() {\n\t\tmetric.Collect(ch)\n\t}\n}", "func (c *metricbeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tif ch == nil {\n\t\tglog.Info(\"Prometheus channel is closed. Skipping\")\n\t\treturn\n\t}\n\n\te.mutex.Lock()\n\tdefer func() {\n\t\te.mutex.Unlock()\n\t\te.cleanup.Range(func(key, value interface{}) bool {\n\t\t\tswitch chiName := key.(type) {\n\t\t\tcase string:\n\t\t\t\te.cleanup.Delete(key)\n\t\t\t\te.removeInstallationReference(chiName)\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}()\n\n\tglog.Info(\"Starting Collect\")\n\tvar wg = sync.WaitGroup{}\n\t// Getting hostnames of Pods and requesting the metrics data from ClickHouse instances within\n\tfor chiName := range e.chInstallations {\n\t\t// Loop over all hostnames of this installation\n\t\tglog.Infof(\"Collecting metrics for %s\\n\", chiName)\n\t\tfor _, hostname := range e.chInstallations[chiName].hostnames {\n\t\t\twg.Add(1)\n\t\t\tgo func(name, hostname string, c chan<- prometheus.Metric) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tglog.Infof(\"Querying metrics for %s\\n\", hostname)\n\t\t\t\tmetricsData := make([][]string, 0)\n\t\t\t\tfetcher := e.newFetcher(hostname)\n\t\t\t\tif err := fetcher.clickHouseQueryMetrics(&metricsData); err != nil {\n\t\t\t\t\t// In case of an error fetching data from clickhouse store CHI name in e.cleanup\n\t\t\t\t\tglog.Infof(\"Error querying metrics for %s: %s\\n\", hostname, err)\n\t\t\t\t\te.cleanup.Store(name, struct{}{})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tglog.Infof(\"Extracted %d metrics for %s\\n\", len(metricsData), hostname)\n\t\t\t\twriteMetricsDataToPrometheus(c, metricsData, name, hostname)\n\n\t\t\t\tglog.Infof(\"Querying table sizes for %s\\n\", hostname)\n\t\t\t\ttableSizes := make([][]string, 0)\n\t\t\t\tif err := fetcher.clickHouseQueryTableSizes(&tableSizes); err != nil {\n\t\t\t\t\t// In case of an error fetching data from clickhouse store CHI name in e.cleanup\n\t\t\t\t\tglog.Infof(\"Error querying table sizes for %s: %s\\n\", hostname, err)\n\t\t\t\t\te.cleanup.Store(name, struct{}{})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tglog.Infof(\"Extracted %d table sizes for %s\\n\", len(tableSizes), hostname)\n\t\t\t\twriteTableSizesDataToPrometheus(c, tableSizes, name, hostname)\n\n\t\t\t}(chiName, hostname, ch)\n\t\t}\n\t}\n\twg.Wait()\n\tglog.Info(\"Finished Collect\")\n}", "func (collector *atlassianUPMCollector) Collect(ch chan<- prometheus.Metric) {\n\tstartTime := time.Now()\n\tlog.Debug(\"Collect start\")\n\n\tlog.Debug(\"create request object\")\n\treq, err := http.NewRequest(\"GET\", baseURL, nil)\n\tif err != nil {\n\t\tlog.Error(\"http.NewRequest returned an error:\", err)\n\t}\n\n\tlog.Debug(\"create Basic auth string from argument passed\")\n\tbearer = \"Basic \" + *token\n\n\tlog.Debug(\"add authorization header to the request\")\n\treq.Header.Add(\"Authorization\", bearer)\n\n\tlog.Debug(\"add content type to the request\")\n\treq.Header.Add(\"content-type\", \"application/json\")\n\n\tlog.Debug(\"make request... get back a response\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Debug(\"set metric atlassian_upm_rest_url_up\")\n\t\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMUpMetric, prometheus.GaugeValue, 0, *fqdn)\n\t\tlog.Warn(\"http.DefaultClient.Do returned an error:\", err, \" return from Collect\")\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\tlog.Debug(\"response status code: \", resp.StatusCode)\n\t}\n\n\tlog.Debug(\"set metric atlassian_upm_rest_url_up\")\n\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMUpMetric, prometheus.GaugeValue, 1, *fqdn)\n\n\tvar allPlugins restPlugins\n\tif resp.StatusCode == 200 {\n\t\tlog.Debug(\"get all plugins\")\n\t\tallPlugins = plugins(resp)\n\n\t\t// return user-installed plugins if argument passed\n\t\tif *userInstalled {\n\t\t\tlog.Debug(\"-user-installed found\")\n\t\t\tallPlugins = userInstalledPlugins(allPlugins)\n\t\t}\n\n\t\t// plugins have the ability to be installed, but disabled, this will remove them if disabled\n\t\tif *dropDisabled {\n\t\t\tlog.Debug(\"-drop-disabled found\")\n\t\t\tallPlugins = dropDisabledPlugins(allPlugins)\n\t\t}\n\n\t\t// Jira specific\n\t\t// some plugins maintained by Jira have an additional element, this gives the option to drop those plugins\n\t\tif *dropJiraSoftware {\n\t\t\tlog.Debug(\"-drop-jira-software found\")\n\t\t\tallPlugins = dropJiraSoftwarePlugins(allPlugins)\n\t\t}\n\n\t\tlog.Debug(\"range over values in response, add each as metric with labels\")\n\t\tfor _, plugin := range allPlugins.Plugins {\n\n\t\t\tlog.Debug(\"creating plugin metric for: \" + plugin.Name)\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tcollector.atlassianUPMPlugins,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\t0,\n\t\t\t\tstrconv.FormatBool(plugin.Enabled), // convert bool to string for the 'enabled' value in the labels\n\t\t\t\tstring(plugin.Name),\n\t\t\t\tstring(plugin.Key),\n\t\t\t\tstring(plugin.Version),\n\t\t\t\tstrconv.FormatBool(plugin.UserInstalled),\n\t\t\t\t*fqdn,\n\t\t\t)\n\t\t}\n\t}\n\n\tif resp.StatusCode == 200 && *checkUpdates {\n\t\tlog.Debug(\"get remaining plugins available info\")\n\t\tavailablePluginsMap := getAvailablePluginInfo(allPlugins)\n\n\t\tlog.Debug(\"range over values in response, add each as metric with labels\")\n\t\tfor _, plugin := range availablePluginsMap {\n\t\t\tavailableUpdate := false\n\n\t\t\tverInstalled, err := version.NewVersion(plugin.InstalledVersion)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"error turning plugin installed into version object\")\n\t\t\t}\n\n\t\t\tverAvailable, err := version.NewVersion(plugin.Version)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"error turning available plugin into version object\")\n\t\t\t}\n\n\t\t\tif verInstalled.LessThan(verAvailable) {\n\t\t\t\tlog.Debug(\"plugin: \", plugin.Name, \", is currently running: \", plugin.InstalledVersion, \", and can be upgraded to: \", plugin.Version)\n\t\t\t\tavailableUpdate = true\n\t\t\t}\n\n\t\t\tlog.Debug(\"creating plugin version metric for: \", plugin.Name, \", with Key: \", plugin.Key)\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tcollector.atlassianUPMVersionsMetric,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\tboolToFloat(availableUpdate),\n\t\t\t\tstring(plugin.Name),\n\t\t\t\tstring(plugin.Key),\n\t\t\t\tstring(plugin.Version),\n\t\t\t\tstring(plugin.InstalledVersion),\n\t\t\t\tstrconv.FormatBool(plugin.Enabled), // convert bool to string for the 'enabled' value in the labels\n\t\t\t\tstrconv.FormatBool(plugin.UserInstalled),\n\t\t\t\t*fqdn,\n\t\t\t)\n\t\t}\n\t}\n\n\tfinishTime := time.Now()\n\telapsedTime := finishTime.Sub(startTime)\n\tlog.Debug(\"set the duration metric\")\n\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMTimeMetric, prometheus.GaugeValue, elapsedTime.Seconds(), *fqdn)\n\n\tlog.Debug(\"Collect finished\")\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tok := e.collectPeersMetric(ch)\n\tok = e.collectLeaderMetric(ch) && ok\n\tok = e.collectNodesMetric(ch) && ok\n\tok = e.collectMembersMetric(ch) && ok\n\tok = e.collectMembersWanMetric(ch) && ok\n\tok = e.collectServicesMetric(ch) && ok\n\tok = e.collectHealthStateMetric(ch) && ok\n\tok = e.collectKeyValues(ch) && ok\n\n\tif ok {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tup, prometheus.GaugeValue, 1.0,\n\t\t)\n\t} else {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tup, prometheus.GaugeValue, 0.0,\n\t\t)\n\t}\n}", "func (c *prometheusCollector) Collect(ch chan<- prometheus.Metric) {\n\tvar stats = c.db.Stats()\n\n\tch <- prometheus.MustNewConstMetric(c.maxOpenConnections, prometheus.GaugeValue, float64(stats.MaxOpenConnections))\n\tch <- prometheus.MustNewConstMetric(c.openConnections, prometheus.GaugeValue, float64(stats.OpenConnections))\n\tch <- prometheus.MustNewConstMetric(c.inUse, prometheus.GaugeValue, float64(stats.InUse))\n\tch <- prometheus.MustNewConstMetric(c.idle, prometheus.GaugeValue, float64(stats.Idle))\n\tch <- prometheus.MustNewConstMetric(c.waitCount, prometheus.CounterValue, float64(stats.WaitCount))\n\tch <- prometheus.MustNewConstMetric(c.waitDuration, prometheus.CounterValue, float64(stats.WaitDuration))\n\tch <- prometheus.MustNewConstMetric(c.maxIdleClosed, prometheus.CounterValue, float64(stats.MaxIdleClosed))\n\tch <- prometheus.MustNewConstMetric(c.maxIdleTimeClosed, prometheus.CounterValue, float64(stats.MaxIdleTimeClosed))\n\tch <- prometheus.MustNewConstMetric(c.maxLifetimeClosed, prometheus.CounterValue, float64(stats.MaxLifetimeClosed))\n}", "func (c *filebeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func CollectAllMetrics(client *statsd.Client, log *li.StandardLogger) {\n\n\tvar metrics []metric\n\tmetrics = append(metrics, metric{name: \"gpu.temperature\", cmd: \"vcgencmd measure_temp | egrep -o '[0-9]*\\\\.[0-9]*'\"})\n\tmetrics = append(metrics, metric{name: \"cpu.temperature\", cmd: \"cat /sys/class/thermal/thermal_zone0/temp | awk 'END {print $1/1000}'\"})\n\tmetrics = append(metrics, metric{name: \"threads\", cmd: \"ps -eo nlwp | tail -n +2 | awk '{ num_threads += $1 } END { print num_threads }'\"})\n\tmetrics = append(metrics, metric{name: \"processes\", cmd: \"ps axu | wc -l\"})\n\n\tfor range time.Tick(15 * time.Second) {\n\t\tlog.Info(\"Starting metric collection\")\n\t\tfor _, m := range metrics {\n\t\t\terr := collectMetric(m, client, log)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tlog.Errorf(\"Error scraping: %s\", err)\n\t}\n\treturn\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\te.scrape()\n\n\te.up.Collect(ch)\n\te.totalScrapes.Collect(ch)\n\te.exchangeStatus.Collect(ch)\n\te.ltp.Collect(ch)\n\te.bestBid.Collect(ch)\n\te.bestAsk.Collect(ch)\n\te.bestBidSize.Collect(ch)\n\te.bestAskSize.Collect(ch)\n\te.totalBidDepth.Collect(ch)\n\te.totalAskDepth.Collect(ch)\n\te.volume.Collect(ch)\n\te.volumeByProduct.Collect(ch)\n}", "func (c *VMCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, m := range c.getMetrics() {\n\t\tch <- m\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tlog.Errorf(\"Error scraping ingestor: %s\", err)\n\t}\n\treturn\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tglog.Error(fmt.Sprintf(\"Error collecting stats: %s\", err))\n\t}\n\treturn\n}", "func (*noOpConntracker) Collect(ch chan<- prometheus.Metric) {}", "func (o *OSDCollector) Collect(ch chan<- prometheus.Metric) {\n\tif err := o.collectOSDPerf(); err != nil {\n\t\tlog.Println(\"failed collecting osd perf stats:\", err)\n\t}\n\n\tif err := o.collectOSDDump(); err != nil {\n\t\tlog.Println(\"failed collecting osd dump:\", err)\n\t}\n\n\tif err := o.collectOSDDF(); err != nil {\n\t\tlog.Println(\"failed collecting osd metrics:\", err)\n\t}\n\n\tif err := o.collectOSDTreeDown(ch); err != nil {\n\t\tlog.Println(\"failed collecting osd metrics:\", err)\n\t}\n\n\tfor _, metric := range o.collectorList() {\n\t\tmetric.Collect(ch)\n\t}\n\n\tif err := o.collectOSDScrubState(ch); err != nil {\n\t\tlog.Println(\"failed collecting osd scrub state:\", err)\n\t}\n}", "func (c *beatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (m httpReferenceDiscoveryMetrics) Collect(metrics chan<- prometheus.Metric) {\n\tm.firstPacket.Collect(metrics)\n\tm.totalTime.Collect(metrics)\n\tm.advertisedRefs.Collect(metrics)\n}", "func CollectProcessMetrics(refresh time.Duration) {\n\t// Short circuit if the metics system is disabled\n\tif !Enabled {\n\t\treturn\n\t}\n\t// Create the various data collectors\n\tmemstates := make([]*runtime.MemStats, 2)\n\tdiskstates := make([]*DiskStats, 2)\n\tfor i := 0; i < len(memstates); i++ {\n\t\tmemstates[i] = new(runtime.MemStats)\n\t\tdiskstates[i] = new(DiskStats)\n\t}\n\t// Define the various metics to collect\n\tmemAllocs := metics.GetOrRegisterMeter(\"system/memory/allocs\", metics.DefaultRegistry)\n\tmemFrees := metics.GetOrRegisterMeter(\"system/memory/frees\", metics.DefaultRegistry)\n\tmemInuse := metics.GetOrRegisterMeter(\"system/memory/inuse\", metics.DefaultRegistry)\n\tmemPauses := metics.GetOrRegisterMeter(\"system/memory/pauses\", metics.DefaultRegistry)\n\n\tvar diskReads, diskReadBytes, diskWrites, diskWriteBytes metics.Meter\n\tif err := ReadDiskStats(diskstates[0]); err == nil {\n\t\tdiskReads = metics.GetOrRegisterMeter(\"system/disk/readcount\", metics.DefaultRegistry)\n\t\tdiskReadBytes = metics.GetOrRegisterMeter(\"system/disk/readdata\", metics.DefaultRegistry)\n\t\tdiskWrites = metics.GetOrRegisterMeter(\"system/disk/writecount\", metics.DefaultRegistry)\n\t\tdiskWriteBytes = metics.GetOrRegisterMeter(\"system/disk/writedata\", metics.DefaultRegistry)\n\t} else {\n\t\tbgmlogs.Debug(\"Failed to read disk metics\", \"err\", err)\n\t}\n\t// Iterate loading the different states and updating the meters\n\tfor i := 1; ; i++ {\n\t\truntime.ReadMemStats(memstates[i%2])\n\t\tmemAllocs.Mark(int64(memstates[i%2].Mallocs - memstates[(i-1)%2].Mallocs))\n\t\tmemFrees.Mark(int64(memstates[i%2].Frees - memstates[(i-1)%2].Frees))\n\t\tmemInuse.Mark(int64(memstates[i%2].Alloc - memstates[(i-1)%2].Alloc))\n\t\tmemPauses.Mark(int64(memstates[i%2].PauseTotalNs - memstates[(i-1)%2].PauseTotalNs))\n\n\t\tif ReadDiskStats(diskstates[i%2]) == nil {\n\t\t\tdiskReads.Mark(diskstates[i%2].ReadCount - diskstates[(i-1)%2].ReadCount)\n\t\t\tdiskReadBytes.Mark(diskstates[i%2].ReadBytes - diskstates[(i-1)%2].ReadBytes)\n\t\t\tdiskWrites.Mark(diskstates[i%2].WriteCount - diskstates[(i-1)%2].WriteCount)\n\t\t\tdiskWriteBytes.Mark(diskstates[i%2].WriteBytes - diskstates[(i-1)%2].WriteBytes)\n\t\t}\n\t\ttime.Sleep(refresh)\n\t}\n}", "func (t *TimestampCollector) Collect(ch chan<- prometheus.Metric) {\n\t// New map to dedup filenames.\n\tuniqueFiles := make(map[string]float64)\n\tt.lock.RLock()\n\tfor fileSD := range t.discoverers {\n\t\tfileSD.lock.RLock()\n\t\tfor filename, timestamp := range fileSD.timestamps {\n\t\t\tuniqueFiles[filename] = timestamp\n\t\t}\n\t\tfileSD.lock.RUnlock()\n\t}\n\tt.lock.RUnlock()\n\tfor filename, timestamp := range uniqueFiles {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tt.Description,\n\t\t\tprometheus.GaugeValue,\n\t\t\ttimestamp,\n\t\t\tfilename,\n\t\t)\n\t}\n}", "func (m *Client) Collect(ch chan<- prometheus.Metric) {\n\tm.storeMu.Lock()\n\tdefer m.storeMu.Unlock()\n\n\tch <- prometheus.MustNewConstMetric(m.storeValuesDesc, prometheus.GaugeValue, float64(len(m.store)))\n\n\tfor k, v := range m.store {\n\t\tch <- prometheus.MustNewConstMetric(m.storeSizesDesc, prometheus.GaugeValue, float64(len(v.value)), k)\n\t}\n}", "func (c *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tfor _, cc := range c.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (c *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tfor _, cc := range c.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tc.m.Lock()\n\tfor _, m := range c.metrics {\n\t\tch <- m.metric\n\t}\n\tc.m.Unlock()\n}", "func (a *AttunityCollector) Collect(ch chan<- prometheus.Metric) {\n\n\t// Collect information on what servers are active\n\tservers, err := a.servers()\n\tif err != nil {\n\n\t\t// If the error is because the session_id expired, attempt to get a new one and collect info again\n\t\t// else, just fail with an invalid metric containing the error\n\t\tif strings.Contains(err.Error(), \"INVALID_SESSION_ID\") {\n\t\t\ta.SessionID = getSessionID(a.httpClient, a.APIURL, a.auth)\n\n\t\t\tservers, err = a.servers()\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Error(err)\n\t\t\t\tch <- prometheus.NewInvalidMetric(prometheus.NewDesc(\"attunity_error\", \"Error scraping target\", nil, nil), err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t} else {\n\t\t\tlogrus.Error(err)\n\t\t\tch <- prometheus.NewInvalidMetric(prometheus.NewDesc(\"attunity_error\", \"Error scraping target\", nil, nil), err)\n\t\t\treturn\n\t\t}\n\n\t} // end error handling for a.servers()\n\n\tfor _, s := range servers {\n\t\tch <- prometheus.MustNewConstMetric(serverDesc, prometheus.GaugeValue, 1.0, s.Name, s.State, s.Platform, s.Host)\n\t}\n\n\t// For each server, concurrently collect detailed information on\n\t// the tasks that are running on them.\n\twg := sync.WaitGroup{}\n\twg.Add(len(servers))\n\tfor _, s := range servers {\n\t\t// If the Server is not monitored, then it will not have any tasks so we can skip this bit.\n\t\tif s.State != \"MONITORED\" {\n\t\t\twg.Done()\n\t\t\tcontinue\n\t\t}\n\t\tgo func(s server) {\n\t\t\ttaskStates, err := a.taskStates(s.Name)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Error(err)\n\t\t\t} else {\n\t\t\t\tfor _, t := range taskStates {\n\t\t\t\t\t// inspired by: https://github.com/prometheus/node_exporter/blob/v0.18.1/collector/systemd_linux.go#L222\n\t\t\t\t\tfor _, tsn := range taskStateNames {\n\t\t\t\t\t\tvalue := 0.0\n\t\t\t\t\t\tif t.State == tsn {\n\t\t\t\t\t\t\tvalue = 1.0\n\t\t\t\t\t\t}\n\t\t\t\t\t\tch <- prometheus.MustNewConstMetric(taskStateDesc, prometheus.GaugeValue, value, s.Name, t.Name, tsn)\n\t\t\t\t\t}\n\n\t\t\t\t\t// Get details on each of the tasks and send them to the channel, too\n\t\t\t\t\tt.details(s.Name, a, ch)\n\t\t\t\t}\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(s)\n\t}\n\n\t// For each server, collect high level details such as\n\t// how many tasks are in each state on them and\n\t// how many days until license expiration\n\twg.Add(len(servers))\n\tfor _, s := range servers {\n\t\tgo func(s server) {\n\t\t\tserverDeets, err := a.serverDetails(s.Name)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Error(err)\n\t\t\t} else {\n\t\t\t\t// Create metrics for task totals by state\n\t\t\t\t// These counts will not be affected by included/excluded task in the config file\n\t\t\t\tch <- prometheus.MustNewConstMetric(serverTasksDesc, prometheus.GaugeValue, float64(serverDeets.TaskSummary.Running), s.Name, \"RUNNING\")\n\t\t\t\tch <- prometheus.MustNewConstMetric(serverTasksDesc, prometheus.GaugeValue, float64(serverDeets.TaskSummary.Stopped), s.Name, \"STOPPED\")\n\t\t\t\tch <- prometheus.MustNewConstMetric(serverTasksDesc, prometheus.GaugeValue, float64(serverDeets.TaskSummary.Error), s.Name, \"ERROR\")\n\t\t\t\tch <- prometheus.MustNewConstMetric(serverTasksDesc, prometheus.GaugeValue, float64(serverDeets.TaskSummary.Recovering), s.Name, \"RECOVERING\")\n\n\t\t\t\t// Create metric for license expiration\n\t\t\t\tch <- prometheus.MustNewConstMetric(serverLicenseExpirationDesc, prometheus.GaugeValue, float64(serverDeets.License.DaysToExpiration), s.Name)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(s)\n\t}\n\twg.Wait()\n}", "func (collector *Metrics) Collect(ch chan<- prometheus.Metric) {\n\n\tcollectedIssues, err := fetchJiraIssues()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\tfor _, issue := range collectedIssues.Issues {\n\t\tcreatedTimestamp := convertToUnixTime(issue.Fields.Created)\n\t\tch <- prometheus.MustNewConstMetric(collector.issue, prometheus.CounterValue, createdTimestamp, issue.Fields.Status.Name, issue.Fields.Project.Name, issue.Key, issue.Fields.Assignee.Name, issue.Fields.Location.Name, issue.Fields.Priority.Name, issue.Fields.Level.Name, issue.Fields.RequestType.Name, issue.Fields.Feedback, issue.Fields.Urgency.Name, issue.Fields.IssueType.Name, issue.Fields.Reporter.Name, issue.Fields.Satisfaction)\n\t}\n}", "func (c collector) Collect(ch chan<- prometheus.Metric) {\n\tvar wg sync.WaitGroup\n\n\t// We don't bail out on errors because those can happen if there is a race condition between\n\t// the destruction of a container and us getting to read the cgroup data. We just don't report\n\t// the values we don't get.\n\n\tcollectors := []func(string, *regexp.Regexp){\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\tnuma, err := cgroups.GetNumaStats(cgroupPath(\"memory\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateNumaStatMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], numa)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect NUMA stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\tmemory, err := cgroups.GetMemoryUsage(cgroupPath(\"memory\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateMemoryUsageMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], memory)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect memory usage stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\tmigrate, err := cgroups.GetCPUSetMemoryMigrate(cgroupPath(\"cpuset\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateMemoryMigrateMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], migrate)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect memory migration stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\tcpuAcctUsage, err := cgroups.GetCPUAcctStats(cgroupPath(\"cpuacct\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateCPUAcctUsageMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], cpuAcctUsage)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect CPU accounting stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\thugeTlbUsage, err := cgroups.GetHugetlbUsage(cgroupPath(\"hugetlb\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateHugeTlbUsageMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], hugeTlbUsage)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect hugetlb stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\tblkioDeviceUsage, err := cgroups.GetBlkioThrottleBytes(cgroupPath(\"blkio\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateBlkioDeviceUsageMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], blkioDeviceUsage)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect blkio stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t}\n\n\tcontainerIDRegexp := regexp.MustCompile(`[a-z0-9]{64}`)\n\n\tfor _, path := range walkCgroups() {\n\t\twg.Add(len(collectors))\n\t\tfor _, fn := range collectors {\n\t\t\tgo fn(path, containerIDRegexp)\n\t\t}\n\t}\n\n\t// We need to wait so that the response channel doesn't get closed.\n\twg.Wait()\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\n\tfor _, cc := range e.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (c *CephExporter) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tfor _, cc := range c.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (n LXCCollector) Collect(ch chan<- prometheus.Metric) {\n\twg := sync.WaitGroup{}\n\twg.Add(len(n.collectors))\n\tfor name, c := range n.collectors {\n\t\tgo func(name string, c collector.Collector) {\n\t\t\texecute(name, c, ch)\n\t\t\twg.Done()\n\t\t}(name, c)\n\t}\n\twg.Wait()\n\tscrapeDurations.Collect(ch)\n}", "func (c *Collector) Collect(ch chan<- prometheus.Metric) {\n\tsess, err := sessions.CreateAWSSession()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\t// Init WaitGroup. Without a WaitGroup the channel we write\n\t// results to will close before the goroutines finish\n\tvar wg sync.WaitGroup\n\twg.Add(len(c.Scrapers))\n\n\t// Iterate through all scrapers and invoke the scrape\n\tfor _, scraper := range c.Scrapers {\n\t\t// Wrape the scrape invocation in a goroutine, but we need to pass\n\t\t// the scraper into the function explicitly to re-scope the variable\n\t\t// the goroutine accesses. If we don't do this, we can sometimes hit\n\t\t// a case where the scraper reports results twice and the collector panics\n\t\tgo func(scraper *Scraper) {\n\t\t\t// Done call deferred until end of the scrape\n\t\t\tdefer wg.Done()\n\n\t\t\tlog.Debugf(\"Running scrape: %s\", scraper.ID)\n\t\t\tscrapeResults := scraper.Scrape(sess)\n\n\t\t\t// Iterate through scrape results and send the metric\n\t\t\tfor key, results := range scrapeResults {\n\t\t\t\tfor _, result := range results {\n\t\t\t\t\tch <- prometheus.MustNewConstMetric(scraper.Metrics[key].metric, result.Type, result.Value, result.Labels...)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Debugf(\"Scrape completed: %s\", scraper.ID)\n\t\t}(scraper)\n\t}\n\t// Wait\n\twg.Wait()\n}", "func (e *Exporter) collect(ch chan<- prometheus.Metric) error {\n\tvar mempct, memtot, memfree float64\n\tif v, e := mem.VirtualMemory(); e == nil {\n\t\tmempct = v.UsedPercent\n\t\tmemtot = float64(v.Total)\n\t\tmemfree = float64(v.Free)\n\t}\n\tvar swappct, swaptot, swapfree float64\n\tif v, e := mem.SwapMemory(); e == nil {\n\t\tswappct = v.UsedPercent\n\t\tswaptot = float64(v.Total)\n\t\tswapfree = float64(v.Free)\n\t}\n\tvar cpupct float64\n\tif c, e := cpu.Percent(time.Millisecond, false); e == nil {\n\t\tcpupct = c[0] // one value since we didn't ask per cpu\n\t}\n\tvar load1, load5, load15 float64\n\tif l, e := load.Avg(); e == nil {\n\t\tload1 = l.Load1\n\t\tload5 = l.Load5\n\t\tload15 = l.Load15\n\t}\n\n\tvar cpuTotal, vsize, rss, openFDs, maxFDs, maxVsize float64\n\tif proc, err := procfs.NewProc(int(*pid)); err == nil {\n\t\tif stat, err := proc.NewStat(); err == nil {\n\t\t\tcpuTotal = float64(stat.CPUTime())\n\t\t\tvsize = float64(stat.VirtualMemory())\n\t\t\trss = float64(stat.ResidentMemory())\n\t\t}\n\t\tif fds, err := proc.FileDescriptorsLen(); err == nil {\n\t\t\topenFDs = float64(fds)\n\t\t}\n\t\tif limits, err := proc.NewLimits(); err == nil {\n\t\t\tmaxFDs = float64(limits.OpenFiles)\n\t\t\tmaxVsize = float64(limits.AddressSpace)\n\t\t}\n\t}\n\n\tvar procCpu, procMem float64\n\tvar estCon, lisCon, othCon, totCon, closeCon, timeCon, openFiles float64\n\tvar nThreads float64\n\tif proc, err := process.NewProcess(int32(*pid)); err == nil {\n\t\tif v, e := proc.CPUPercent(); e == nil {\n\t\t\tprocCpu = float64(v)\n\t\t}\n\t\tif v, e := proc.MemoryPercent(); e == nil {\n\t\t\tprocMem = float64(v)\n\t\t}\n\n\t\tif v, e := proc.NumThreads(); e == nil {\n\t\t\tnThreads = float64(v)\n\t\t}\n\t\tif connections, e := proc.Connections(); e == nil {\n\t\t\tfor _, v := range connections {\n\t\t\t\tif v.Status == \"LISTEN\" {\n\t\t\t\t\tlisCon += 1\n\t\t\t\t} else if v.Status == \"ESTABLISHED\" {\n\t\t\t\t\testCon += 1\n\t\t\t\t} else if v.Status == \"TIME_WAIT\" {\n\t\t\t\t\ttimeCon += 1\n\t\t\t\t} else if v.Status == \"CLOSE_WAIT\" {\n\t\t\t\t\tcloseCon += 1\n\t\t\t\t} else {\n\t\t\t\t\tothCon += 1\n\t\t\t\t}\n\t\t\t}\n\t\t\ttotCon = lisCon + estCon + timeCon + closeCon + othCon\n\t\t}\n\t\tif oFiles, e := proc.OpenFiles(); e == nil {\n\t\t\topenFiles = float64(len(oFiles))\n\t\t}\n\t}\n\n\t// metrics from process collector\n\tch <- prometheus.MustNewConstMetric(e.cpuTotal, prometheus.CounterValue, cpuTotal)\n\tch <- prometheus.MustNewConstMetric(e.openFDs, prometheus.CounterValue, openFDs)\n\tch <- prometheus.MustNewConstMetric(e.maxFDs, prometheus.CounterValue, maxFDs)\n\tch <- prometheus.MustNewConstMetric(e.vsize, prometheus.CounterValue, vsize)\n\tch <- prometheus.MustNewConstMetric(e.maxVsize, prometheus.CounterValue, maxVsize)\n\tch <- prometheus.MustNewConstMetric(e.rss, prometheus.CounterValue, rss)\n\t// node specific metrics\n\tch <- prometheus.MustNewConstMetric(e.memPercent, prometheus.CounterValue, mempct)\n\tch <- prometheus.MustNewConstMetric(e.memTotal, prometheus.CounterValue, memtot)\n\tch <- prometheus.MustNewConstMetric(e.memFree, prometheus.CounterValue, memfree)\n\tch <- prometheus.MustNewConstMetric(e.swapPercent, prometheus.CounterValue, swappct)\n\tch <- prometheus.MustNewConstMetric(e.swapTotal, prometheus.CounterValue, swaptot)\n\tch <- prometheus.MustNewConstMetric(e.swapFree, prometheus.CounterValue, swapfree)\n\tch <- prometheus.MustNewConstMetric(e.numCpus, prometheus.CounterValue, float64(runtime.NumCPU()))\n\tch <- prometheus.MustNewConstMetric(e.load1, prometheus.CounterValue, load1)\n\tch <- prometheus.MustNewConstMetric(e.load5, prometheus.CounterValue, load5)\n\tch <- prometheus.MustNewConstMetric(e.load15, prometheus.CounterValue, load15)\n\t// process specific metrics\n\tch <- prometheus.MustNewConstMetric(e.procCpu, prometheus.CounterValue, procCpu)\n\tch <- prometheus.MustNewConstMetric(e.procMem, prometheus.CounterValue, procMem)\n\tch <- prometheus.MustNewConstMetric(e.numThreads, prometheus.CounterValue, nThreads)\n\tch <- prometheus.MustNewConstMetric(e.cpuPercent, prometheus.CounterValue, cpupct)\n\tch <- prometheus.MustNewConstMetric(e.openFiles, prometheus.CounterValue, openFiles)\n\tch <- prometheus.MustNewConstMetric(e.totCon, prometheus.CounterValue, totCon)\n\tch <- prometheus.MustNewConstMetric(e.lisCon, prometheus.CounterValue, lisCon)\n\tch <- prometheus.MustNewConstMetric(e.estCon, prometheus.CounterValue, estCon)\n\tch <- prometheus.MustNewConstMetric(e.closeCon, prometheus.CounterValue, closeCon)\n\tch <- prometheus.MustNewConstMetric(e.timeCon, prometheus.CounterValue, timeCon)\n\treturn nil\n}", "func (o *requestMetrics) Collect(ch chan<- prometheus.Metric) {\n\tmetricFamilies, err := o.stStore.GetPromDirectMetrics()\n\tif err != nil {\n\t\tklog.Errorf(\"fetch prometheus metrics failed: %v\", err)\n\t\treturn\n\t}\n\to.handleMetrics(metricFamilies, ch)\n}", "func (e *ebpfConntracker) Collect(ch chan<- prometheus.Metric) {\n\tebpfTelemetry := &netebpf.ConntrackTelemetry{}\n\tif err := e.telemetryMap.Lookup(unsafe.Pointer(&zero), unsafe.Pointer(ebpfTelemetry)); err != nil {\n\t\tlog.Tracef(\"error retrieving the telemetry struct: %s\", err)\n\t} else {\n\t\tdelta := ebpfTelemetry.Registers - conntrackerTelemetry.lastRegisters\n\t\tconntrackerTelemetry.lastRegisters = ebpfTelemetry.Registers\n\t\tch <- prometheus.MustNewConstMetric(conntrackerTelemetry.registersTotal, prometheus.CounterValue, float64(delta))\n\t}\n}", "func (c *MSCluster_ClusterCollector) Collect(ctx *ScrapeContext, ch chan<- prometheus.Metric) error {\n\tvar dst []MSCluster_Cluster\n\tq := queryAll(&dst, c.logger)\n\tif err := wmi.QueryNamespace(q, &dst, \"root/MSCluster\"); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, v := range dst {\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.AddEvictDelay,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.AddEvictDelay),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.AdminAccessPoint,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.AdminAccessPoint),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.AutoAssignNodeSite,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.AutoAssignNodeSite),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.AutoBalancerLevel,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.AutoBalancerLevel),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.AutoBalancerMode,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.AutoBalancerMode),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.BackupInProgress,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.BackupInProgress),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.BlockCacheSize,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.BlockCacheSize),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusSvcHangTimeout,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusSvcHangTimeout),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusSvcRegroupOpeningTimeout,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusSvcRegroupOpeningTimeout),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusSvcRegroupPruningTimeout,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusSvcRegroupPruningTimeout),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusSvcRegroupStageTimeout,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusSvcRegroupStageTimeout),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusSvcRegroupTickInMilliseconds,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusSvcRegroupTickInMilliseconds),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusterEnforcedAntiAffinity,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusterEnforcedAntiAffinity),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusterFunctionalLevel,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusterFunctionalLevel),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusterGroupWaitDelay,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusterGroupWaitDelay),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusterLogLevel,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusterLogLevel),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusterLogSize,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusterLogSize),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ClusterUpgradeVersion,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ClusterUpgradeVersion),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.CrossSiteDelay,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.CrossSiteDelay),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.CrossSiteThreshold,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.CrossSiteThreshold),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.CrossSubnetDelay,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.CrossSubnetDelay),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.CrossSubnetThreshold,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.CrossSubnetThreshold),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.CsvBalancer,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.CsvBalancer),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.DatabaseReadWriteMode,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.DatabaseReadWriteMode),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.DefaultNetworkRole,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.DefaultNetworkRole),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.DetectedCloudPlatform,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.DetectedCloudPlatform),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.DetectManagedEvents,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.DetectManagedEvents),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.DetectManagedEventsThreshold,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.DetectManagedEventsThreshold),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.DisableGroupPreferredOwnerRandomization,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.DisableGroupPreferredOwnerRandomization),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.DrainOnShutdown,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.DrainOnShutdown),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.DynamicQuorumEnabled,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.DynamicQuorumEnabled),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.EnableSharedVolumes,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.EnableSharedVolumes),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.FixQuorum,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.FixQuorum),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.GracePeriodEnabled,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.GracePeriodEnabled),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.GracePeriodTimeout,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.GracePeriodTimeout),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.GroupDependencyTimeout,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.GroupDependencyTimeout),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.HangRecoveryAction,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.HangRecoveryAction),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.IgnorePersistentStateOnStartup,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.IgnorePersistentStateOnStartup),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.LogResourceControls,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.LogResourceControls),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.LowerQuorumPriorityNodeId,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.LowerQuorumPriorityNodeId),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.MaxNumberOfNodes,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.MaxNumberOfNodes),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.MessageBufferLength,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.MessageBufferLength),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.MinimumNeverPreemptPriority,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.MinimumNeverPreemptPriority),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.MinimumPreemptorPriority,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.MinimumPreemptorPriority),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.NetftIPSecEnabled,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.NetftIPSecEnabled),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.PlacementOptions,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.PlacementOptions),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.PlumbAllCrossSubnetRoutes,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.PlumbAllCrossSubnetRoutes),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.PreventQuorum,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.PreventQuorum),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.QuarantineDuration,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.QuarantineDuration),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.QuarantineThreshold,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.QuarantineThreshold),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.QuorumArbitrationTimeMax,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.QuorumArbitrationTimeMax),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.QuorumArbitrationTimeMin,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.QuorumArbitrationTimeMin),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.QuorumLogFileSize,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.QuorumLogFileSize),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.QuorumTypeValue,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.QuorumTypeValue),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.RequestReplyTimeout,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.RequestReplyTimeout),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ResiliencyDefaultPeriod,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ResiliencyDefaultPeriod),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ResiliencyLevel,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ResiliencyLevel),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ResourceDllDeadlockPeriod,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ResourceDllDeadlockPeriod),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.RootMemoryReserved,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.RootMemoryReserved),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.RouteHistoryLength,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.RouteHistoryLength),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.S2DBusTypes,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.S2DBusTypes),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.S2DCacheDesiredState,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.S2DCacheDesiredState),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.S2DCacheFlashReservePercent,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.S2DCacheFlashReservePercent),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.S2DCachePageSizeKBytes,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.S2DCachePageSizeKBytes),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.S2DEnabled,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.S2DEnabled),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.S2DIOLatencyThreshold,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.S2DIOLatencyThreshold),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.S2DOptimizations,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.S2DOptimizations),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.SameSubnetDelay,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.SameSubnetDelay),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.SameSubnetThreshold,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.SameSubnetThreshold),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.SecurityLevel,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.SecurityLevel),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.SecurityLevelForStorage,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.SecurityLevelForStorage),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.SharedVolumeVssWriterOperationTimeout,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.SharedVolumeVssWriterOperationTimeout),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ShutdownTimeoutInMinutes,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.ShutdownTimeoutInMinutes),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.UseClientAccessNetworksForSharedVolumes,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.UseClientAccessNetworksForSharedVolumes),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.WitnessDatabaseWriteTimeout,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.WitnessDatabaseWriteTimeout),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.WitnessDynamicWeight,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.WitnessDynamicWeight),\n\t\t\tv.Name,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.WitnessRestartInterval,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(v.WitnessRestartInterval),\n\t\t\tv.Name,\n\t\t)\n\n\t}\n\n\treturn nil\n}", "func (c *TeamsCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tteams := getTotalTeams()\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.totalTeamsGaugeDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(teams),\n\t)\n}", "func (p *plug) Collect(ch chan<- prometheus.Metric) {\n\tp.doStats(ch, doMetric)\n}", "func (p *ProcMetrics) Collect() {\n\tif m, err := CollectProcInfo(p.pid); err == nil {\n\t\tnow := time.Now()\n\n\t\tif !p.lastTime.IsZero() {\n\t\t\tratio := 1.0\n\t\t\tswitch {\n\t\t\tcase m.CPU.Period > 0 && m.CPU.Quota > 0:\n\t\t\t\tratio = float64(m.CPU.Quota) / float64(m.CPU.Period)\n\t\t\tcase m.CPU.Shares > 0:\n\t\t\t\tratio = float64(m.CPU.Shares) / 1024\n\t\t\tdefault:\n\t\t\t\tratio = 1 / float64(runtime.NumCPU())\n\t\t\t}\n\n\t\t\tinterval := ratio * float64(now.Sub(p.lastTime))\n\n\t\t\tp.cpu.user.time = m.CPU.User - p.last.CPU.User\n\t\t\tp.cpu.user.percent = 100 * float64(p.cpu.user.time) / interval\n\n\t\t\tp.cpu.system.time = m.CPU.Sys - p.last.CPU.Sys\n\t\t\tp.cpu.system.percent = 100 * float64(p.cpu.system.time) / interval\n\n\t\t\tp.cpu.total.time = (m.CPU.User + m.CPU.Sys) - (p.last.CPU.User + p.last.CPU.Sys)\n\t\t\tp.cpu.total.percent = 100 * float64(p.cpu.total.time) / interval\n\t\t}\n\n\t\tp.memory.available = m.Memory.Available\n\t\tp.memory.size = m.Memory.Size\n\t\tp.memory.resident.usage = m.Memory.Resident\n\t\tp.memory.resident.percent = 100 * float64(p.memory.resident.usage) / float64(p.memory.available)\n\t\tp.memory.shared.usage = m.Memory.Shared\n\t\tp.memory.text.usage = m.Memory.Text\n\t\tp.memory.data.usage = m.Memory.Data\n\t\tp.memory.pagefault.major.count = m.Memory.MajorPageFaults - p.last.Memory.MajorPageFaults\n\t\tp.memory.pagefault.minor.count = m.Memory.MinorPageFaults - p.last.Memory.MinorPageFaults\n\n\t\tp.files.open = m.Files.Open\n\t\tp.files.max = m.Files.Max\n\n\t\tp.threads.num = m.Threads.Num\n\t\tp.threads.switches.voluntary.count = m.Threads.VoluntaryContextSwitches - p.last.Threads.VoluntaryContextSwitches\n\t\tp.threads.switches.involuntary.count = m.Threads.InvoluntaryContextSwitches - p.last.Threads.InvoluntaryContextSwitches\n\n\t\tp.last = m\n\t\tp.lastTime = now\n\t\tp.engine.Report(p)\n\t}\n}", "func (b *EBPFTelemetry) Collect(ch chan<- prometheus.Metric) {\n\tb.getHelpersTelemetry(ch)\n\tb.getMapsTelemetry(ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.withCollectors(func(cs []prometheus.Collector) {\n\t\tfor _, c := range cs {\n\t\t\tc.Collect(ch)\n\t\t}\n\t})\n}", "func (dc *daemonsetCollector) Collect(ch chan<- prometheus.Metric) {\n\tdss, err := dc.store.List()\n\tif err != nil {\n\t\tScrapeErrorTotalMetric.With(prometheus.Labels{\"resource\": \"daemonset\"}).Inc()\n\t\tglog.Errorf(\"listing daemonsets failed: %s\", err)\n\t\treturn\n\t}\n\tScrapeErrorTotalMetric.With(prometheus.Labels{\"resource\": \"daemonset\"}).Add(0)\n\n\tResourcesPerScrapeMetric.With(prometheus.Labels{\"resource\": \"daemonset\"}).Observe(float64(len(dss)))\n\tfor _, d := range dss {\n\t\tdc.collectDaemonSet(ch, d)\n\t}\n\n\tglog.V(4).Infof(\"collected %d daemonsets\", len(dss))\n}", "func (h *Metrics) Collect(in chan<- prometheus.Metric) {\n\th.duration.Collect(in)\n\th.totalRequests.Collect(in)\n\th.requestSize.Collect(in)\n\th.responseSize.Collect(in)\n\th.handlerStatuses.Collect(in)\n\th.responseTime.Collect(in)\n}", "func (coll WmiCollector) Collect(ch chan<- prometheus.Metric) {\n\tdefer trace()()\n\twg := sync.WaitGroup{}\n\twg.Add(len(coll.collectors))\n\tfor name, c := range coll.collectors {\n\t\tgo func(name string, c collector.Collector) {\n\t\t\texecute(name, c, ch)\n\t\t\twg.Done()\n\t\t}(name, c)\n\t}\n\twg.Wait()\n\tscrapeDurations.Collect(ch)\n}", "func (e *exporter) Collect(ch chan<- prometheus.Metric) {\n\twg := sync.WaitGroup{}\n\twg.Add(len(e.Collectors))\n\tfor name, c := range e.Collectors {\n\t\tgo func(name string, c Collector) {\n\t\t\texecute(name, c, ch)\n\t\t\twg.Done()\n\t\t}(name, c)\n\t}\n\twg.Wait()\n}", "func (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tstart := time.Now()\n\n\tp := \"Chassis/1\"\n\terr := power.Collect(p, c.cl, ch)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n\n\terr = thermal.Collect(p, c.cl, ch)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n\n\tduration := time.Now().Sub(start).Seconds()\n\tch <- prometheus.MustNewConstMetric(scrapeDurationDesc, prometheus.GaugeValue, duration, c.cl.HostName())\n}", "func (t *File_summary_by_instance) Collect(dbh *sql.DB) {\n\tstart := time.Now()\n\t// UPDATE current from db handle\n\tt.current = merge_by_table_name(select_fsbi_rows(dbh), t.global_variables)\n\n\t// copy in initial data if it was not there\n\tif len(t.initial) == 0 && len(t.current) > 0 {\n\t\tt.initial = make(file_summary_by_instance_rows, len(t.current))\n\t\tcopy(t.initial, t.current)\n\t}\n\n\t// check for reload initial characteristics\n\tif t.initial.needs_refresh(t.current) {\n\t\tt.initial = make(file_summary_by_instance_rows, len(t.current))\n\t\tcopy(t.initial, t.current)\n\t}\n\n\t// update results to current value\n\tt.results = make(file_summary_by_instance_rows, len(t.current))\n\tcopy(t.results, t.current)\n\n\t// make relative if need be\n\tif t.WantRelativeStats() {\n\t\tt.results.subtract(t.initial)\n\t}\n\n\t// sort the results\n\tt.results.sort()\n\n\t// setup the totals\n\tt.totals = t.results.totals()\n\tlib.Logger.Println(\"File_summary_by_instance.Collect() took:\", time.Duration(time.Since(start)).String())\n}", "func (n NodeCollector) Collect(ch chan<- prometheus.Metric) {\n\twg := sync.WaitGroup{}\n\twg.Add(len(n.collectors))\n\tfor name, c := range n.collectors {\n\t\tgo func(name string, c collector.Collector) {\n\t\t\texecute(name, c, ch)\n\t\t\twg.Done()\n\t\t}(name, c)\n\t}\n\twg.Wait()\n\tscrapeDurations.Collect(ch)\n}", "func (c *StatsCollector) Collect(metricChannel chan<- prometheus.Metric) {\n\t// read all stats from Kamailio\n\tif completeStatMap, err := c.fetchStats(); err == nil {\n\t\t// and produce various prometheus.Metric for well-known stats\n\t\tproduceMetrics(completeStatMap, metricChannel)\n\t\t// produce prometheus.Metric objects for scripted stats (if any)\n\t\tconvertScriptedMetrics(completeStatMap, metricChannel)\n\t} else {\n\t\t// something went wrong\n\t\t// TODO: add a error metric\n\t\tlog.Error(\"Could not fetch values from kamailio\", err)\n\t}\n}", "func (c *ImageCollector) Collect(ch chan<- prometheus.Metric) {\n\tctx, cancel := context.WithTimeout(context.Background(), c.config.Timeout)\n\tdefer cancel()\n\n\tnow := time.Now()\n\timages, err := c.client.Image.All(ctx)\n\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\n\t\t\t\"msg\", \"Failed to fetch images\",\n\t\t\t\"err\", err,\n\t\t)\n\n\t\tc.failures.WithLabelValues(\"image\").Inc()\n\t\treturn\n\t}\n\n\tlevel.Debug(c.logger).Log(\n\t\t\"msg\", \"Fetched images\",\n\t\t\"count\", len(images),\n\t)\n\n\tfor _, image := range images {\n\t\tvar (\n\t\t\tactive float64\n\t\t\tname string\n\t\t\tdeprecated float64\n\t\t)\n\n\t\tif image.CreatedFrom != nil {\n\t\t\tname = image.CreatedFrom.Name\n\t\t}\n\n\t\tif image.BoundTo != nil && image.BoundTo.Name != \"\" {\n\t\t\tactive = 1.0\n\t\t\tname = image.BoundTo.Name\n\t\t}\n\n\t\tlabels := []string{\n\t\t\tstrconv.FormatInt(image.ID, 10),\n\t\t\timage.Name,\n\t\t\tstring(image.Type),\n\t\t\tname,\n\t\t\timage.OSFlavor,\n\t\t\timage.OSVersion,\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.Active,\n\t\t\tprometheus.GaugeValue,\n\t\t\tactive,\n\t\t\tlabels...,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.ImageSize,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(image.ImageSize*1024*1024),\n\t\t\tlabels...,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.DiskSize,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(image.DiskSize*1024*1024),\n\t\t\tlabels...,\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.Created,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(image.Created.Unix()),\n\t\t\tlabels...,\n\t\t)\n\n\t\tif !image.Deprecated.IsZero() {\n\t\t\tdeprecated = float64(image.Deprecated.Unix())\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.Deprecated,\n\t\t\tprometheus.GaugeValue,\n\t\t\tdeprecated,\n\t\t\tlabels...,\n\t\t)\n\t}\n\n\tlevel.Debug(c.logger).Log(\n\t\t\"msg\", \"Processed image collector\",\n\t\t\"duration\", time.Since(now),\n\t)\n\n\tc.duration.WithLabelValues(\"image\").Observe(time.Since(now).Seconds())\n}", "func (c *grpcClientManagerCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, con := range c.cm.Metrics().Connections {\n\t\tl := []string{con.Target}\n\t\tch <- prometheus.MustNewConstMetric(connectionStateDesc, prometheus.GaugeValue, float64(con.State), l...)\n\t}\n}", "func (c *SchedulerController) CollectMetrics(ch chan<- prometheus.Metric) {\n\tmetric, err := prometheus.NewConstMetric(scheduler.ControllerWorkerSum, prometheus.GaugeValue, float64(c.RunningWorkers()), \"seed\")\n\tif err != nil {\n\t\tscheduler.ScrapeFailures.With(prometheus.Labels{\"kind\": \"gardener-shoot-scheduler\"}).Inc()\n\t\treturn\n\t}\n\tch <- metric\n}", "func (pc *PBSCollector) Collect(ch chan<- prometheus.Metric) {\n\tpc.mutex.Lock()\n\tdefer pc.mutex.Unlock()\n\tlog.Debugf(\"Time since last scrape: %f seconds\", time.Since(pc.lastScrape).Seconds())\n\n\tif time.Since(pc.lastScrape).Seconds() > float64(pc.scrapeInterval) {\n\t\tpc.updateDynamicJobIds()\n\t\tvar err error\n\t\tpc.sshClient, err = pc.sshConfig.NewClient()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Creating SSH client: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tdefer pc.sshClient.Close()\n\t\tlog.Infof(\"Collecting metrics from PBS...\")\n\t\tpc.trackedJobs = make(map[string]bool)\n\t\tif pc.targetJobIds != \"\" {\n\t\t\tpc.collectJobs(ch)\n\t\t}\n\t\tif !pc.skipInfra {\n\t\t\tpc.collectQueues(ch)\n\t\t}\n\t\tpc.lastScrape = time.Now()\n\t}\n\tpc.updateMetrics(ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tupValue := 1\n\n\tif err := e.collect(ch); err != nil {\n\t\tlog.Printf(\"Error scraping clickhouse: %s\", err)\n\t\te.scrapeFailures.Inc()\n\t\te.scrapeFailures.Collect(ch)\n\n\t\tupValue = 0\n\t}\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tprometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, \"\", \"up\"),\n\t\t\t\"Was the last query of ClickHouse successful.\",\n\t\t\tnil, nil,\n\t\t),\n\t\tprometheus.GaugeValue, float64(upValue),\n\t)\n\n}", "func (cpuCollector *CPUCollector) Collect() {\n\tcpuCollector.cpuStats.GetCPUStats()\n\n\tcpuCollector.cpuMetrics.cpuTotal.Set(float64(cpuCollector.cpuStats.Total))\n\tcpuCollector.cpuMetrics.cupIdle.Set(float64(cpuCollector.cpuStats.Idle))\n\tcpuCollector.cpuMetrics.cpuUtilization.Set(cpuCollector.cpuStats.Utilization)\n}", "func (e Exporter) Collect(ch chan<- prometheus.Metric) {\n\tctx := context.Background()\n\n\tcontainerService, err := container.NewService(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcloudresourcemanagerService, err := cloudresourcemanager.NewService(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tprojectsListResponse, err := cloudresourcemanagerService.Projects.List().Filter(\"lifecycleState:ACTIVE\").Context(ctx).Do()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Infof(\"Found %d projects\", len(projectsListResponse.Projects))\n\n\tvar mutex = &sync.Mutex{}\n\tvar wg sync.WaitGroup\n\twg.Add(len(projectsListResponse.Projects))\n\n\tvalidMasterVersions := map[string][]string{}\n\tmasterVersionCount := map[string]float64{}\n\n\tfor _, p := range projectsListResponse.Projects {\n\t\tgo func(p *cloudresourcemanager.Project) {\n\t\t\tdefer wg.Done()\n\t\t\tresp, err := containerService.Projects.Locations.Clusters.List(\"projects/\" + p.ProjectId + \"/locations/-\").Context(ctx).Do()\n\t\t\tif err != nil {\n\t\t\t\tif ae, ok := err.(*googleapi.Error); ok && ae.Code == http.StatusForbidden {\n\t\t\t\t\tlog.Warnf(\"Missing roles/container.clusterViewer on %s (%s)\", p.Name, p.ProjectId)\n\t\t\t\t\treturn\n\t\t\t\t} else if ae, ok := err.(*googleapi.Error); ok && ae.Code == http.StatusTooManyRequests {\n\t\t\t\t\tlog.Warn(\"Quota exceeded\")\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, c := range resp.Clusters {\n\t\t\t\tmutex.Lock()\n\t\t\t\tif _, ok := validMasterVersions[c.Location]; !ok {\n\t\t\t\t\tlog.Infof(\"Pulling server configs for location %s\", c.Location)\n\t\t\t\t\tserverConfig, err := containerService.Projects.Locations.GetServerConfig(\"projects/\" + p.ProjectId + \"/locations/\" + c.Location).Do()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif ae, ok := err.(*googleapi.Error); ok && ae.Code == http.StatusTooManyRequests {\n\t\t\t\t\t\t\tlog.Warn(\"Quota exceeded\")\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tvalidMasterVersions[c.Location] = serverConfig.ValidMasterVersions\n\t\t\t\t}\n\n\t\t\t\tif _, ok := masterVersionCount[c.CurrentMasterVersion]; !ok {\n\t\t\t\t\tmasterVersionCount[c.CurrentMasterVersion] = 1\n\t\t\t\t} else {\n\t\t\t\t\tmasterVersionCount[c.CurrentMasterVersion]++\n\t\t\t\t}\n\t\t\t\tmutex.Unlock()\n\n\t\t\t\tif !contains(c.CurrentMasterVersion, validMasterVersions[c.Location]) {\n\t\t\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\t\t\te.Metrics[\"gkeUnsupportedMasterVersion\"],\n\t\t\t\t\t\tprometheus.CounterValue,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\tc.CurrentMasterVersion,\n\t\t\t\t\t\t\tp.ProjectId,\n\t\t\t\t\t\t\tp.Name,\n\t\t\t\t\t\t\tc.Name,\n\t\t\t\t\t\t\tc.Location,\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}(p)\n\t}\n\n\twg.Wait()\n\n\tfor version, cnt := range masterVersionCount {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\te.Metrics[\"gkeMasterVersion\"],\n\t\t\tprometheus.CounterValue,\n\t\t\tcnt,\n\t\t\t[]string{\n\t\t\t\tversion,\n\t\t\t}...,\n\t\t)\n\t}\n\n\tlog.Info(\"Done\")\n}", "func (o *observer) Collect(ch chan<- prometheus.Metric) {\n\to.updateError.Collect(ch)\n\to.verifyError.Collect(ch)\n\to.expiration.Collect(ch)\n}", "func collectMetrics(db *sql.DB, populaterWg *sync.WaitGroup, i *integration.Integration, instanceLookUp map[string]string) {\n\tdefer populaterWg.Done()\n\n\tvar collectorWg sync.WaitGroup\n\tmetricChan := make(chan newrelicMetricSender, 100) // large buffer for speed\n\n\t// Create a goroutine for each of the metric groups to collect\n\tcollectorWg.Add(5)\n\tgo oracleReadWriteMetrics.Collect(db, &collectorWg, metricChan)\n\tgo oraclePgaMetrics.Collect(db, &collectorWg, metricChan)\n\tgo oracleSysMetrics.Collect(db, &collectorWg, metricChan)\n\tgo globalNameInstanceMetric.Collect(db, &collectorWg, metricChan)\n\tgo dbIDInstanceMetric.Collect(db, &collectorWg, metricChan)\n\n\t// Separate logic is needed to see if we should even collect tablespaces\n\tcollectTableSpaces(db, &collectorWg, metricChan)\n\n\t// When the metric groups are finished collecting, close the channel\n\tgo func() {\n\t\tcollectorWg.Wait()\n\t\tclose(metricChan)\n\t}()\n\n\t// Create a goroutine to read from the metric channel and insert the metrics\n\tpopulateMetrics(metricChan, i, instanceLookUp)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tfor _, pool := range *e.zpools {\n\t\tpool.getStatus()\n\n\t\tpoolUsage := prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tName: \"zpool_capacity_percentage\",\n\t\t\tHelp: \"Current zpool capacity level\",\n\t\t\tConstLabels: prometheus.Labels{\n\t\t\t\t\"name\": pool.name,\n\t\t\t},\n\t\t})\n\t\tpoolUsage.Set(float64(pool.capacity))\n\t\tch <- poolUsage\n\n\t\tprovidersOnline := prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tName: \"zpool_online_providers_count\",\n\t\t\tHelp: \"Number of ONLINE zpool providers (disks)\",\n\t\t\tConstLabels: prometheus.Labels{\n\t\t\t\t\"name\": pool.name,\n\t\t\t},\n\t\t})\n\t\tprovidersOnline.Set(float64(pool.online))\n\t\tch <- providersOnline\n\n\t\tprovidersFaulted := prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tName: \"zpool_faulted_providers_count\",\n\t\t\tHelp: \"Number of FAULTED/UNAVAIL zpool providers (disks)\",\n\t\t\tConstLabels: prometheus.Labels{\n\t\t\t\t\"name\": pool.name,\n\t\t\t},\n\t\t})\n\t\tprovidersFaulted.Set(float64(pool.faulted))\n\t\tch <- providersFaulted\n\t}\n\n}", "func (c *solarCollector) collect(ch chan<- prometheus.Metric) error {\n\t// fetch the status of the controller\n\ttracer, err := gotracer.Status(\"/dev/ttyUSB0\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/*\n\t * report the collected data\n\t */\n\n\t// store boolean values as a float (1 == true, 0 == false)\n\tvar loadIsActive float64\n\t// Panel array\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.panelVoltage,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.ArrayVoltage),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.panelCurrent,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.ArrayCurrent),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.panelPower,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.ArrayPower),\n\t)\n\n\t// Batteries\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batteryCurrent,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatteryCurrent),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batteryVoltage,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatteryVoltage),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batterySOC,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatterySOC),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batteryTemp,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatteryTemp),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batteryMinVoltage,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatteryMinVoltage),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batteryMaxVoltage,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatteryMaxVoltage),\n\t)\n\n\t// Load output\n\tif tracer.Load {\n\t\tloadIsActive = 1\n\t}\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.loadActive,\n\t\tprometheus.GaugeValue,\n\t\tloadIsActive,\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.loadVoltage,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.LoadVoltage),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.loadCurrent,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.LoadCurrent),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.loadPower,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.LoadPower),\n\t)\n\n\t// controller infos\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.deviceTemp,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.DeviceTemp),\n\t)\n\n\t// energy consumed\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyConsumedDaily,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyConsumedDaily),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyConsumedMonthly,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyConsumedMonthly),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyConsumedAnnual,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyConsumedAnnual),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyConsumedTotal,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyConsumedTotal),\n\t)\n\t// energy generated\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyGeneratedDaily,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyGeneratedDaily),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyGeneratedMonthly,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyGeneratedMonthly),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyGeneratedAnnual,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyGeneratedAnnual),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyGeneratedTotal,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyGeneratedTotal),\n\t)\n\n\treturn nil\n}", "func (e *PostfixExporter) Collect(ch chan<- prometheus.Metric) {\n\terr := CollectShowqFromSocket(e.showqPath, ch)\n\tif err == nil {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tpostfixUpDesc,\n\t\t\tprometheus.GaugeValue,\n\t\t\t1.0,\n\t\t\te.showqPath)\n\t} else {\n\t\tlog.Printf(\"Failed to scrape showq socket: %s\", err)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tpostfixUpDesc,\n\t\t\tprometheus.GaugeValue,\n\t\t\t0.0,\n\t\t\te.showqPath)\n\t}\n\n\terr = e.CollectLogfileFromFile(e.logfilePath)\n\tif err == nil {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tpostfixUpDesc,\n\t\t\tprometheus.GaugeValue,\n\t\t\t1.0,\n\t\t\te.logfilePath)\n\t} else {\n\t\tlog.Printf(\"Failed to scrape logfile: %s\", err)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tpostfixUpDesc,\n\t\t\tprometheus.GaugeValue,\n\t\t\t0.0,\n\t\t\te.logfilePath)\n\t}\n\n\tch <- e.cleanupProcesses\n\tch <- e.cleanupRejects\n\te.lmtpDelays.Collect(ch)\n\te.pipeDelays.Collect(ch)\n\tch <- e.qmgrInsertsNrcpt\n\tch <- e.qmgrInsertsSize\n\tch <- e.qmgrRemoves\n\te.smtpDelays.Collect(ch)\n\te.smtpTLSConnects.Collect(ch)\n\tch <- e.smtpdConnects\n\tch <- e.smtpdDisconnects\n\tch <- e.smtpdFCrDNSErrors\n\te.smtpdLostConnections.Collect(ch)\n\te.smtpdProcesses.Collect(ch)\n\te.smtpdRejects.Collect(ch)\n\tch <- e.smtpdSASLAuthenticationFailures\n\te.smtpdTLSConnects.Collect(ch)\n\te.unsupportedLogEntries.Collect(ch)\n}", "func (coll WmiCollector) Collect(ch chan<- prometheus.Metric) {\n\texecute(coll.collector, ch)\n}", "func (m *MeterImpl) collect(ctx context.Context, labels []attribute.KeyValue, measurements []Measurement) {\n\tm.provider.addMeasurement(Batch{\n\t\tCtx: ctx,\n\t\tLabels: labels,\n\t\tMeasurements: measurements,\n\t\tLibrary: m.library,\n\t})\n}", "func (c *libbeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n\t// output.type with dynamic label\n\tch <- prometheus.MustNewConstMetric(libbeatOutputType, prometheus.CounterValue, float64(1), c.stats.LibBeat.Output.Type)\n\n}", "func (c *Client) Collect(ch chan<- prometheus.Metric) {\n\tc.metrics.functionInvocation.Collect(ch)\n\tc.metrics.functionsHistogram.Collect(ch)\n\tc.metrics.queueHistogram.Collect(ch)\n\tc.metrics.functionInvocationStarted.Collect(ch)\n\tc.metrics.serviceReplicasGauge.Reset()\n\tfor _, service := range c.services {\n\t\tvar serviceName string\n\t\tif len(service.Namespace) > 0 {\n\t\t\tserviceName = fmt.Sprintf(\"%s.%s\", service.Name, service.Namespace)\n\t\t} else {\n\t\t\tserviceName = service.Name\n\t\t}\n\t\tc.metrics.serviceReplicasGauge.\n\t\t\tWithLabelValues(serviceName).\n\t\t\tSet(float64(service.Replicas))\n\t}\n\tc.metrics.serviceReplicasGauge.Collect(ch)\n}", "func appStatsCollect(ctx *zedrouterContext) {\n\tlog.Infof(\"appStatsCollect: containerStats, started\")\n\tappStatsCollectTimer := time.NewTimer(time.Duration(ctx.appStatsInterval) * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-appStatsCollectTimer.C:\n\t\t\titems, stopped := checkAppStopStatsCollect(ctx)\n\t\t\tif stopped {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcollectTime := time.Now() // all apps collection assign the same timestamp\n\t\t\tfor _, st := range items {\n\t\t\t\tstatus := st.(types.AppNetworkStatus)\n\t\t\t\tif status.GetStatsIPAddr != nil {\n\t\t\t\t\tacMetrics, err := appContainerGetStats(status.GetStatsIPAddr)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"appStatsCollect: can't get App %s Container Metrics on %s, %v\",\n\t\t\t\t\t\t\tstatus.UUIDandVersion.UUID.String(), status.GetStatsIPAddr.String(), err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tacMetrics.UUIDandVersion = status.UUIDandVersion\n\t\t\t\t\tacMetrics.CollectTime = collectTime\n\t\t\t\t\tctx.pubAppContainerMetrics.Publish(acMetrics.Key(), acMetrics)\n\t\t\t\t}\n\t\t\t}\n\t\t\tappStatsCollectTimer = time.NewTimer(time.Duration(ctx.appStatsInterval) * time.Second)\n\t\t}\n\t}\n}", "func (c *SVCResponse) Collect(ch chan<- prometheus.Metric) {\n\tvar err error\n\tc.totalScrapes.Inc()\n\tdefer func() {\n\t\tch <- c.up\n\t\tch <- c.totalScrapes\n\t\tch <- c.jsonParseFailures\n\t}()\n\n\tSVCResp, err := c.fetchDataAndDecode()\n\tif err != nil {\n\t\tc.up.Set(0)\n\t\t_ = level.Warn(*c.logger).Log(\n\t\t\t\"msg\", \"failed to fetch and decode data\",\n\t\t\t\"err\", err,\n\t\t)\n\t\treturn\n\t}\n\tc.up.Set(1)\n\n\tfor _, metric := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tmetric.Desc,\n\t\t\tmetric.Type,\n\t\t\tmetric.Value(&SVCResp),\n\t\t)\n\t}\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.data.Desc,\n\t\tc.data.Type,\n\t\tc.data.Value(&SVCResp),\n\t\tSVCResp.UniqueID, SVCResp.Version, SVCResp.LongVersion, SVCResp.Platform,\n\t)\n}", "func (s *stats) collect() {\n\truntime.GC()\n\truntime.Gosched()\n\n\tm := new(runtime.MemStats)\n\truntime.ReadMemStats(m)\n\n\tg := runtime.NumGoroutine()\n\tp := player.PlayerList.Length()\n\n\t// Calculate difference in resources since last run\n\tΔa := int64(m.Alloc - s.Alloc)\n\tΔh := int(m.HeapObjects - s.HeapObjects)\n\tΔg := g - s.Goroutines\n\n\t// Calculate max players\n\tmaxPlayers := s.MaxPlayers\n\tif s.MaxPlayers < p {\n\t\tmaxPlayers = p\n\t}\n\n\t// Calculate scaled numeric and prefix parts of Alloc and Alloc difference\n\tan, ap := uscale(m.Alloc)\n\tΔan, Δap := scale(Δa)\n\n\tlog.Printf(\"A[%4d%-2s %+5d%-2s] HO[%14d %+9d] GO[%6d %+6d] PL %d/%d\",\n\t\tan, ap, Δan, Δap, m.HeapObjects, Δh, g, Δg, p, maxPlayers,\n\t)\n\n\t// Save current stats\n\ts.Alloc = m.Alloc\n\ts.HeapObjects = m.HeapObjects\n\ts.Goroutines = g\n\ts.MaxPlayers = maxPlayers\n}", "func (c *ledCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, led := range c.leds {\n\t\tn := name(led.Name())\n\t\tbrightness, err := led.Brightness()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.brightness,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(brightness),\n\t\t\tn,\n\t\t)\n\t\tmaxBrightness, err := led.MaxBrightness()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.maxBrightness,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(maxBrightness),\n\t\t\tn,\n\t\t)\n\t}\n}", "func (a collectorAdapter) Collect(ch chan<- prometheus.Metric) {\n\tif err := a.Update(ch); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to update collector: %v\", err))\n\t}\n}" ]
[ "0.7183592", "0.71742594", "0.7162346", "0.70565355", "0.70360357", "0.69982564", "0.6949635", "0.6914864", "0.6885865", "0.6879976", "0.68548733", "0.68540335", "0.6808158", "0.68029076", "0.68007356", "0.67698246", "0.67640656", "0.67620915", "0.6753656", "0.6752293", "0.6744237", "0.6739006", "0.67390007", "0.67380345", "0.6727125", "0.6726372", "0.67184454", "0.671359", "0.6706968", "0.67049974", "0.6698012", "0.6693244", "0.66925627", "0.6678655", "0.666336", "0.6661282", "0.66609734", "0.666035", "0.6656762", "0.6652841", "0.66519517", "0.66454893", "0.6627886", "0.66224986", "0.6615926", "0.660144", "0.658763", "0.657078", "0.6568967", "0.65557", "0.65522474", "0.65458155", "0.65399355", "0.65399355", "0.65392137", "0.6536364", "0.6521162", "0.651431", "0.6498718", "0.6489084", "0.64823884", "0.6482232", "0.64529246", "0.64494044", "0.64492226", "0.6437596", "0.6432558", "0.6420688", "0.64153194", "0.64046174", "0.638546", "0.6368604", "0.6366169", "0.63609284", "0.63548523", "0.63504416", "0.6345726", "0.63364065", "0.6330194", "0.63286954", "0.6309989", "0.6309755", "0.62939787", "0.62667626", "0.6266644", "0.6260426", "0.62584746", "0.6253893", "0.6250315", "0.6233216", "0.6231679", "0.6228766", "0.6226484", "0.6220888", "0.6218559", "0.6217337", "0.621059", "0.6208171", "0.6202584", "0.6197745" ]
0.7495119
0
NewCustomLambda creates a new lambda that has a custom command
func NewCustomLambda(name, command string) *CustomLambda { return &CustomLambda{ name: name, command: command, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewLambda(vs []Argument, u bool, as []Argument, e Expression, t types.Type) Lambda {\n\treturn Lambda{as, e, t, vs, u}\n}", "func NewLambda(label string, t Term, body Term) Lambda {\n\treturn Lambda{\n\t\tLabel: label,\n\t\tType: t,\n\t\tBody: body,\n\t}\n}", "func New(cfg *config.Config) *Lambda {\n\n\treturn &Lambda{\n\t\tConfig: cfg,\n\t\tService: service.New(cfg),\n\t\tFileTransfer: filetransfer.New(cfg),\n\t}\n}", "func NewCmd(o *Options) *cobra.Command {\n\tc := command{\n\t\tCommand: cli.Command{Options: o.Options},\n\t\topts: o,\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"new-lambda\",\n\t\tShort: \"New local Lambda Function\",\n\t\tLong: `Creates a new local lambda function setup to start development`,\n\t\tRunE: func(_ *cobra.Command, args []string) error { return c.Run(args) },\n\t}\n\n\tcmd.Args = cobra.ExactArgs(1)\n\n\tcmd.Flags().StringVarP(&o.Namespace, \"namespace\", \"n\", \"default\", \"Namespace to bind\")\n\tcmd.Flags().BoolVar(&o.Expose, \"expose\", false, \"Create the namespace if not existing\")\n\tcmd.Flags().StringVar(&o.ClusterDomain, \"cluster-domain\", \"\", \"Cluster Domain of your cluster\")\n\n\treturn cmd\n}", "func createLambdaFunction(ctx *pulumi.Context, role *iam.Role, logPolicy *iam.RolePolicy, route APIRoute, method string) (*lambda.Function, error) {\n\t// Determine the language of the function.\n\tlambdaFilePath := path.Join(route.PathToFiles, method)\n\tlambdaLanguage, err := detectLambdaLanguage(lambdaFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Determine the Lambda runtime to use.\n\tvar lambdaRuntime string\n\tvar handlerName string\n\tvar handlerZipFile string\n\tswitch lambdaLanguage {\n\tcase \"typescript\":\n\t\tlambdaRuntime = \"nodejs12.x\"\n\t\thandlerName = fmt.Sprintf(\"%s-%s-handler.%sHandler\", route.Name, method, method)\n\t\thandlerZipFile, err = PackageTypeScriptLambda(tmpDirName, route.Name, method)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbreak\n\tcase \"go\":\n\t\tlambdaRuntime = \"go1.x\"\n\t\thandlerName = fmt.Sprintf(\"%s-%s-handler\", route.Name, method)\n\t\thandlerZipFile, err = PackageGoLambda(tmpDirName, route.Name, method)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase \"dotnet\":\n\t\tlambdaRuntime = \"dotnetcore3.1\"\n\t\thandlerName = fmt.Sprintf(\"app::app.Functions::%s\", utils.DashCaseToSentenceCase(method))\n\t\thandlerZipFile, err = PackageDotNetLambda(tmpDirName, route.Name, method)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unsupported runtime detected.\")\n\t}\n\n\tcurrentWorkingDirectory, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thandlerFileName := path.Join(currentWorkingDirectory, handlerZipFile)\n\targs := &lambda.FunctionArgs{\n\t\tHandler: pulumi.String(handlerName),\n\t\tRole: role.Arn,\n\t\tRuntime: pulumi.String(lambdaRuntime),\n\t\tCode: pulumi.NewFileArchive(handlerFileName),\n\t}\n\n\t// Create the lambda using the args.\n\tfunction, err := lambda.NewFunction(\n\t\tctx,\n\t\tfmt.Sprintf(\"%s-%s-lambda-function\", route.Name, method),\n\t\targs,\n\t\tpulumi.DependsOn([]pulumi.Resource{logPolicy}),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error updating lambda for file [%s]: %v\", handlerFileName, err)\n\t}\n\n\treturn function, nil\n}", "func NewLambdaFromJSON(json jsoniter.Any) (*Lambda, error) {\n\tif json.Get(\"type\").ToUint() != TypeLambda {\n\t\treturn nil, ErrInvalidJSON\n\t}\n\n\tvar jsonParameters []jsoniter.Any\n\tjson.Get(\"parameters\").ToVal(&jsonParameters)\n\n\tparameters := make([]*ID, len(jsonParameters))\n\tfor i, json := range jsonParameters {\n\t\tp, err := NewIDFromJSON(json)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tparameters[i] = p\n\t}\n\n\texpression, err := NewExpressionFromJSON(json.Get(\"expression\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Lambda{\n\t\tParameters: parameters,\n\t\tExpression: expression,\n\t}, nil\n}", "func New(h HandlerFunc) lambda.Handler {\n\treturn NewWithConfig(Config{}, h)\n}", "func (c *Client) NewCreateLambdaRequest(ctx context.Context, path string, payload *LambdaPayload, contentType string) (*http.Request, error) {\n\tvar body bytes.Buffer\n\tif contentType == \"\" {\n\t\tcontentType = \"*/*\" // Use default encoder\n\t}\n\terr := c.Encoder.Encode(payload, &body, contentType)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\tif contentType == \"*/*\" {\n\t\theader.Set(\"Content-Type\", \"application/json\")\n\t} else {\n\t\theader.Set(\"Content-Type\", contentType)\n\t}\n\treturn req, nil\n}", "func main() {\n\tlambda.Start(handler)\n}", "func main() {\n\tlambda.Start(handler)\n}", "func createNewPythonProxyEntry(lambdaInfo *LambdaAWSInfo, logger *logrus.Logger) string {\n\tlogger.WithFields(logrus.Fields{\n\t\t\"FunctionName\": lambdaInfo.lambdaFunctionName(),\n\t\t\"ScriptName\": lambdaInfo.scriptExportHandlerName(),\n\t}).Info(\"Registering Sparta Python function\")\n\n\tprimaryEntry := fmt.Sprintf(`def %s(event, context):\n\t\treturn lambda_handler(%s, event, context)\n\t`,\n\t\tlambdaInfo.scriptExportHandlerName(),\n\t\tlambdaInfo.lambdaFunctionName())\n\treturn primaryEntry\n}", "func NewLambdaInvocationMetricEvaluator(queries []awsv2CWTypes.MetricDataQuery,\n\tmetricEvaluator MetricEvaluator) CloudEvaluator {\n\tnowTime := time.Now()\n\n\t// We won't get initialized before the trigger function is called, so ensure there's\n\t// enough buffer for a lower bound\n\taddDuration, _ := time.ParseDuration(\"2s\")\n\treturn &lambdaInvocationMetricEvaluator{\n\t\tinitTime: nowTime.Add(-addDuration),\n\t\tqueries: queries,\n\t\tmetricEvaluator: metricEvaluator,\n\t}\n}", "func (l *CustomLambda) Execute(stdin io.Reader, args []string) (string, error) {\n\targsStr := strings.TrimSpace(strings.Join(args, \" \"))\n\tif argsStr != \"\" {\n\t\targsStr = \" \" + argsStr\n\t}\n\n\tcmd := exec.Command(\"bash\", \"-c\", l.command+argsStr)\n\n\t// pass through some stdin goodness\n\tcmd.Stdin = stdin\n\n\t// for those who are about to rock, I salute you.\n\tstdoutStderr, err := cmd.CombinedOutput()\n\n\tif err == nil {\n\t\t// noiiiice!\n\t\tlog.WithFields(log.Fields{\"name\": l.Name(), \"command\": l.command}).Info(\"Lambda Execution\")\n\t\treturn strings.TrimSpace(string(stdoutStderr)), nil\n\t}\n\n\t// *sigh*\n\tlog.WithFields(log.Fields{\"name\": l.Name(), \"command\": l.command}).Error(\"Lambda Execution\")\n\treturn string(stdoutStderr), errors.New(\"Error running command\")\n}", "func main() {\n\n\t// Test code\n\t// p := InputParameters{\n\t// \tStackID: \"MaxEdge-ddc65b40-5d03-4827-8bf9-2957903600ca-test-2m\",\n\t// \tSourceIP: \"EC2AMAZ-5EEVEUI\",\n\t// \tSourcePort: \"5450\",\n\t// \tDestinationIP: \"10.0.4.53\",\n\t// \tDestinationPort: \"5450\",\n\t// \tPiList: []string{\"tag1\", \"tag2\", \"tag3\", \"tag4\", \"tag5\", \"tag6\", \"endTag117\"},\n\t// }\n\t//LambdaHandler(p)\n\n\tlambda.Start(LambdaHandler)\n}", "func TestLambda(t *testing.T) {\n\tctx := context.Background()\n\n\tconst functionName = \"TestFunctionName\"\n\tt.Setenv(awsLambdaFunctionNameEnvVar, functionName)\n\n\t// Call Lambda Resource detector to detect resources\n\tlambdaDetector, err := NewDetector(processortest.NewNopCreateSettings(), CreateDefaultConfig())\n\trequire.NoError(t, err)\n\tres, _, err := lambdaDetector.Detect(ctx)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, res)\n\n\tassert.Equal(t, map[string]interface{}{\n\t\tconventions.AttributeCloudProvider: conventions.AttributeCloudProviderAWS,\n\t\tconventions.AttributeCloudPlatform: conventions.AttributeCloudPlatformAWSLambda,\n\t\tconventions.AttributeFaaSName: functionName,\n\t}, res.Attributes().AsRaw(), \"Resource object returned is incorrect\")\n}", "func resourceAwsLambdaFunctionCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lambdaconn\n\n\tfunctionName := d.Get(\"function_name\").(string)\n\treservedConcurrentExecutions := d.Get(\"reserved_concurrent_executions\").(int)\n\tiamRole := d.Get(\"role\").(string)\n\n\tlog.Printf(\"[DEBUG] Creating Lambda Function %s with role %s\", functionName, iamRole)\n\n\tfilename, hasFilename := d.GetOk(\"filename\")\n\ts3Bucket, bucketOk := d.GetOk(\"s3_bucket\")\n\ts3Key, keyOk := d.GetOk(\"s3_key\")\n\ts3ObjectVersion, versionOk := d.GetOk(\"s3_object_version\")\n\n\tif !hasFilename && !bucketOk && !keyOk && !versionOk {\n\t\treturn errors.New(\"filename or s3_* attributes must be set\")\n\t}\n\n\tvar functionCode *lambda.FunctionCode\n\tif hasFilename {\n\t\t// Grab an exclusive lock so that we're only reading one function into\n\t\t// memory at a time.\n\t\t// See https://github.com/hashicorp/terraform/issues/9364\n\t\tawsMutexKV.Lock(awsMutexLambdaKey)\n\t\tdefer awsMutexKV.Unlock(awsMutexLambdaKey)\n\t\tfile, err := loadFileContent(filename.(string))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to load %q: %s\", filename.(string), err)\n\t\t}\n\t\tfunctionCode = &lambda.FunctionCode{\n\t\t\tZipFile: file,\n\t\t}\n\t} else {\n\t\tif !bucketOk || !keyOk {\n\t\t\treturn errors.New(\"s3_bucket and s3_key must all be set while using S3 code source\")\n\t\t}\n\t\tfunctionCode = &lambda.FunctionCode{\n\t\t\tS3Bucket: aws.String(s3Bucket.(string)),\n\t\t\tS3Key: aws.String(s3Key.(string)),\n\t\t}\n\t\tif versionOk {\n\t\t\tfunctionCode.S3ObjectVersion = aws.String(s3ObjectVersion.(string))\n\t\t}\n\t}\n\n\tparams := &lambda.CreateFunctionInput{\n\t\tCode: functionCode,\n\t\tDescription: aws.String(d.Get(\"description\").(string)),\n\t\tFunctionName: aws.String(functionName),\n\t\tHandler: aws.String(d.Get(\"handler\").(string)),\n\t\tMemorySize: aws.Int64(int64(d.Get(\"memory_size\").(int))),\n\t\tRole: aws.String(iamRole),\n\t\tRuntime: aws.String(d.Get(\"runtime\").(string)),\n\t\tTimeout: aws.Int64(int64(d.Get(\"timeout\").(int))),\n\t\tPublish: aws.Bool(d.Get(\"publish\").(bool)),\n\t}\n\n\tif v, ok := d.GetOk(\"dead_letter_config\"); ok {\n\t\tdlcMaps := v.([]interface{})\n\t\tif len(dlcMaps) == 1 { // Schema guarantees either 0 or 1\n\t\t\t// Prevent panic on nil dead_letter_config. See GH-14961\n\t\t\tif dlcMaps[0] == nil {\n\t\t\t\treturn fmt.Errorf(\"Nil dead_letter_config supplied for function: %s\", functionName)\n\t\t\t}\n\t\t\tdlcMap := dlcMaps[0].(map[string]interface{})\n\t\t\tparams.DeadLetterConfig = &lambda.DeadLetterConfig{\n\t\t\t\tTargetArn: aws.String(dlcMap[\"target_arn\"].(string)),\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"vpc_config\"); ok {\n\n\t\tconfigs := v.([]interface{})\n\t\tconfig, ok := configs[0].(map[string]interface{})\n\n\t\tif !ok {\n\t\t\treturn errors.New(\"vpc_config is <nil>\")\n\t\t}\n\n\t\tif config != nil {\n\t\t\tvar subnetIds []*string\n\t\t\tfor _, id := range config[\"subnet_ids\"].(*schema.Set).List() {\n\t\t\t\tsubnetIds = append(subnetIds, aws.String(id.(string)))\n\t\t\t}\n\n\t\t\tvar securityGroupIds []*string\n\t\t\tfor _, id := range config[\"security_group_ids\"].(*schema.Set).List() {\n\t\t\t\tsecurityGroupIds = append(securityGroupIds, aws.String(id.(string)))\n\t\t\t}\n\n\t\t\tparams.VpcConfig = &lambda.VpcConfig{\n\t\t\t\tSubnetIds: subnetIds,\n\t\t\t\tSecurityGroupIds: securityGroupIds,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"tracing_config\"); ok {\n\t\ttracingConfig := v.([]interface{})\n\t\ttracing := tracingConfig[0].(map[string]interface{})\n\t\tparams.TracingConfig = &lambda.TracingConfig{\n\t\t\tMode: aws.String(tracing[\"mode\"].(string)),\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"environment\"); ok {\n\t\tenvironments := v.([]interface{})\n\t\tenvironment, ok := environments[0].(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn errors.New(\"At least one field is expected inside environment\")\n\t\t}\n\n\t\tif environmentVariables, ok := environment[\"variables\"]; ok {\n\t\t\tvariables := readEnvironmentVariables(environmentVariables.(map[string]interface{}))\n\n\t\t\tparams.Environment = &lambda.Environment{\n\t\t\t\tVariables: aws.StringMap(variables),\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"kms_key_arn\"); ok {\n\t\tparams.KMSKeyArn = aws.String(v.(string))\n\t}\n\n\tif v, exists := d.GetOk(\"tags\"); exists {\n\t\tparams.Tags = tagsFromMapGeneric(v.(map[string]interface{}))\n\t}\n\n\t// IAM profiles can take ~10 seconds to propagate in AWS:\n\t// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console\n\t// Error creating Lambda function: InvalidParameterValueException: The role defined for the task cannot be assumed by Lambda.\n\terr := resource.Retry(10*time.Minute, func() *resource.RetryError {\n\t\t_, err := conn.CreateFunction(params)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[DEBUG] Error creating Lambda Function: %s\", err)\n\n\t\t\tif isAWSErr(err, \"InvalidParameterValueException\", \"The role defined for the function cannot be assumed by Lambda\") {\n\t\t\t\tlog.Printf(\"[DEBUG] Received %s, retrying CreateFunction\", err)\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t\tif isAWSErr(err, \"InvalidParameterValueException\", \"The provided execution role does not have permissions\") {\n\t\t\t\tlog.Printf(\"[DEBUG] Received %s, retrying CreateFunction\", err)\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t\tif isAWSErr(err, \"InvalidParameterValueException\", \"Your request has been throttled by EC2\") {\n\t\t\t\tlog.Printf(\"[DEBUG] Received %s, retrying CreateFunction\", err)\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\n\t\t\treturn resource.NonRetryableError(err)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Lambda function: %s\", err)\n\t}\n\n\tif reservedConcurrentExecutions > 0 {\n\n\t\tlog.Printf(\"[DEBUG] Setting Concurrency to %d for the Lambda Function %s\", reservedConcurrentExecutions, functionName)\n\n\t\tconcurrencyParams := &lambda.PutFunctionConcurrencyInput{\n\t\t\tFunctionName: aws.String(functionName),\n\t\t\tReservedConcurrentExecutions: aws.Int64(int64(reservedConcurrentExecutions)),\n\t\t}\n\n\t\t_, err := conn.PutFunctionConcurrency(concurrencyParams)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error setting concurrency for Lambda %s: %s\", functionName, err)\n\t\t}\n\t}\n\n\td.SetId(d.Get(\"function_name\").(string))\n\n\treturn resourceAwsLambdaFunctionRead(d, meta)\n}", "func (c *Client) NewCodeLambdaRequest(ctx context.Context, path string) (*http.Request, error) {\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func execNewFunc(_ int, p *gop.Context) {\n\targs := p.GetArgs(4)\n\tret := types.NewFunc(token.Pos(args[0].(int)), args[1].(*types.Package), args[2].(string), args[3].(*types.Signature))\n\tp.Ret(4, ret)\n}", "func CreateLambdaPath() string {\n\n\treturn fmt.Sprintf(\"/p7/lambdas\")\n}", "func NewCustomExecutor(commandMap stringmap.StringMap) *CustomExecutor {\n\treturn &CustomExecutor{commandMap: commandMap}\n}", "func main() {\n\tlambda.Start(wflambda.Wrapper(handler))\n}", "func main() {\n\tlambda.Start(wflambda.Wrapper(handler))\n}", "func main() {\n\tlambda.Start(wflambda.Wrapper(handler))\n}", "func main() {\n\t/* Run shellscript: `$ sh create-lambda.sh` for docker deploy */\n\tlambda.Start(HandleRequest)\n\t// HandleRequest() // \ttesting:\n}", "func (c *Client) NewRunLambdaRequest(ctx context.Context, path string) (*http.Request, error) {\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func NewAdd(f func(string, string) (proto.Message, error)) *cobra.Command {\n\tvar (\n\t\trole string\n\t\tuser string\n\t)\n\n\tcmd := template.NewArg0Proto(\"add\", \"Add a new role binding\", func(cmd *cobra.Command) (proto.Message, error) {\n\t\treturn f(role, user)\n\t})\n\n\tcmd.Flags().StringVar(&role, \"role\", \"\", \"role name\")\n\tcmd.Flags().StringVar(&user, \"user\", \"\", \"user name\")\n\n\treturn cmd\n}", "func main() {\n\n\tlambda.Start(LambdaHandler)\n}", "func NewMessageFromLambda(content []byte, origin *Origin, status string, utcTime time.Time, ARN, reqID string, ingestionTimestamp int64) *Message {\n\treturn &Message{\n\t\tContent: content,\n\t\tOrigin: origin,\n\t\tStatus: status,\n\t\tIngestionTimestamp: ingestionTimestamp,\n\t\tServerlessExtra: ServerlessExtra{\n\t\t\tTimestamp: utcTime,\n\t\t\tLambda: &Lambda{\n\t\t\t\tARN: ARN,\n\t\t\t\tRequestID: reqID,\n\t\t\t},\n\t\t},\n\t}\n}", "func (machine *Dishwasher) RunCustomCommand(custom string) {\r\n machine.Append(func() (string, error) {\r\n var output string = \"\"\r\n var oops error = nil\r\n\r\n custom = strings.TrimSpace(custom)\r\n if custom[len(custom)-1] == '$' {\r\n go RunCommand(custom)\r\n } else {\r\n output, oops = RunCommand(custom)\r\n machine.SideEffect(output, oops)\r\n }\r\n\r\n return output, oops\r\n })\r\n}", "func (t *LambdaFactory) New(config *trigger.Config) (trigger.Trigger, error) {\n\n\tif singleton == nil {\n\t\tsingleton = &LambdaTrigger{}\n\t\treturn singleton, nil\n\t}\n\n\tlog.RootLogger().Warn(\"Only one lambda trigger instance can be instantiated\")\n\n\treturn nil, nil\n}", "func NewLambdaAlias(properties LambdaAliasProperties, deps ...interface{}) LambdaAlias {\n\treturn LambdaAlias{\n\t\tType: \"AWS::Lambda::Alias\",\n\t\tProperties: properties,\n\t\tDependsOn: deps,\n\t}\n}", "func (c *Client) CodeLambda(ctx context.Context, path string) (*http.Response, error) {\n\treq, err := c.NewCodeLambdaRequest(ctx, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Client.Do(ctx, req)\n}", "func LambdaApplication_FromLambdaApplicationName(scope constructs.Construct, id *string, lambdaApplicationName *string) ILambdaApplication {\n\t_init_.Initialize()\n\n\tvar returns ILambdaApplication\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_codedeploy.LambdaApplication\",\n\t\t\"fromLambdaApplicationName\",\n\t\t[]interface{}{scope, id, lambdaApplicationName},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (a *QueryLambdasApiService) CreateQueryLambdaExecute(r ApiCreateQueryLambdaRequest) (*QueryLambdaVersionResponse, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *QueryLambdaVersionResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"QueryLambdasApiService.CreateQueryLambda\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/orgs/self/ws/{workspace}/lambdas\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"workspace\"+\"}\", url.PathEscape(parameterValueToString(r.workspace, \"workspace\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\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 = r.body\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := io.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody))\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 == 400 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 405 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 406 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 408 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 415 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 429 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 501 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 502 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 503 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\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 createNewNodeJSProxyEntry(lambdaInfo *LambdaAWSInfo, logger *logrus.Logger) string {\n\tlogger.WithFields(logrus.Fields{\n\t\t\"FunctionName\": lambdaInfo.lambdaFunctionName(),\n\t\t\"ScriptName\": lambdaInfo.scriptExportHandlerName(),\n\t}).Info(\"Registering Sparta JS function\")\n\n\t// We do know the CF resource name here - could write this into\n\t// index.js and expose a GET localhost:9000/lambdaMetadata\n\t// which wraps up DescribeStackResource for the running\n\t// lambda function\n\tprimaryEntry := fmt.Sprintf(\"exports[\\\"%s\\\"] = createForwarder(\\\"/%s\\\");\\n\",\n\t\tlambdaInfo.scriptExportHandlerName(),\n\t\tlambdaInfo.lambdaFunctionName())\n\treturn primaryEntry\n}", "func (s *BaseBundListener) EnterLambda_term(ctx *Lambda_termContext) {}", "func (l *LambdaClient) createFunction(function *FunctionConfig, code []byte) error {\n\tfuncCode := &lambda.FunctionCode{\n\t\tZipFile: code,\n\t}\n\n\tcreateArgs := &lambda.CreateFunctionInput{\n\t\tCode: funcCode,\n\t\tFunctionName: aws.String(function.Name),\n\t\tHandler: aws.String(\"main\"),\n\t\tRuntime: aws.String(lambda.RuntimeGo1X),\n\t\tRole: aws.String(function.RoleARN),\n\t\tTimeout: aws.Int64(function.Timeout),\n\t\tMemorySize: aws.Int64(function.MemorySize),\n\t}\n\n\t_, err := l.Client.CreateFunction(createArgs)\n\treturn err\n}", "func NewCustom(fieldName string, fullPath bool) logrus.Hook {\n\treturn &customCallerHook{fieldName: fieldName, fullPath: fullPath}\n}", "func (l *CustomLambda) Name() string {\n\treturn l.name\n}", "func lambdaHandler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t// Validate RPC request\n\treq := json.GetRPCRequestFromJSON(request.Body)\n\tif method := request.QueryStringParameters[ParamFuncName]; method != \"\" {\n\t\treq.Method = method\n\t} else if method := request.PathParameters[ParamFuncName]; method != \"\" {\n\t\treq.Method = method\n\t}\n\n\trespBody, statusCode := handler(req)\n\treturn events.APIGatewayProxyResponse{Headers: lambdaHeaders, Body: respBody, StatusCode: statusCode}, nil\n}", "func main() {\n\tlambda.Start(handleRequest)\n}", "func createCommand(t *runner.Task, actionFunc func(*cli.Context) error) *cli.Command {\n\tcommand := &cli.Command{\n\t\tName: t.Name,\n\t\tUsage: strings.TrimSpace(t.Usage),\n\t\tDescription: strings.TrimSpace(t.Description),\n\t\tAction: actionFunc,\n\t}\n\n\tfor _, arg := range t.Args {\n\t\tcommand.ArgsUsage += fmt.Sprintf(\"<%s> \", arg.Name)\n\t}\n\n\tcommand.CustomHelpTemplate = createCommandHelp(t)\n\n\treturn command\n}", "func execNewNamed(_ int, p *gop.Context) {\n\targs := p.GetArgs(3)\n\tret := types.NewNamed(args[0].(*types.TypeName), args[1].(types.Type), args[2].([]*types.Func))\n\tp.Ret(3, ret)\n}", "func (c *Client) NewDeleteLambdaRequest(ctx context.Context, path string) (*http.Request, error) {\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"DELETE\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func createIAMLambdaRole(ctx *pulumi.Context, name string) (*iam.Role, error) {\n\troleName := fmt.Sprintf(\"%s-task-exec-role\", name)\n\n\trole, err := iam.NewRole(ctx, roleName, &iam.RoleArgs{\n\t\tAssumeRolePolicy: pulumi.String(`{\n\t\t\t\"Version\": \"2012-10-17\",\n\t\t\t\"Statement\": [{\n\t\t\t\t\"Sid\": \"\",\n\t\t\t\t\"Effect\": \"Allow\",\n\t\t\t\t\"Principal\": {\n\t\t\t\t\t\"Service\": \"lambda.amazonaws.com\"\n\t\t\t\t},\n\t\t\t\t\"Action\": \"sts:AssumeRole\"\n\t\t\t}]\n\t\t}`),\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error create IAM role for %s: %v\", name, err)\n\t}\n\n\treturn role, nil\n}", "func (a *QueryLambdasApiService) CreateQueryLambda(ctx context.Context, workspace string) ApiCreateQueryLambdaRequest {\n\treturn ApiCreateQueryLambdaRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tworkspace: workspace,\n\t}\n}", "func GenerateNewLambdaRoleName(region, name *string) string {\n\treturn fmt.Sprintf(\"%s-%s-%s\", constants.CommonNamePrefix, *name, *region)\n}", "func new_(e interface{}) func() Event {\n\ttyp := reflect.TypeOf(e)\n\treturn func() Event {\n\t\treturn reflect.New(typ).Interface().(Event)\n\t}\n}", "func newLogClosure(c func() string) logClosure {\n\treturn logClosure(c)\n}", "func main() {\n // Initialize a session\n sess := session.Must(session.NewSessionWithOptions(session.Options{\n SharedConfigState: session.SharedConfigEnable,\n }))\n\n // Create Lambda service client\n svc := lambda.New(sess, &aws.Config{Region: aws.String(\"us-west-2\")})\n\n result, err := svc.ListFunctions(nil)\n if err != nil {\n fmt.Println(\"Cannot list functions\")\n os.Exit(0)\n }\n\n fmt.Println(\"Functions:\")\n\n for _, f := range result.Functions {\n fmt.Println(\"Name: \" + aws.StringValue(f.FunctionName))\n fmt.Println(\"Description: \" + aws.StringValue(f.Description))\n fmt.Println(\"\")\n }\n}", "func newPipelineCommandHandler(repository eventstore.Repository) *pipelineCommandHandler {\n\treturn &pipelineCommandHandler{\n\t\trepository: repository,\n\t}\n}", "func NewExternalCmd(name string) Callable {\n\treturn externalCmd{name}\n}", "func NewProfile(name string) {\n\tpath := name\n\tif !IsLambdaDir() {\n\t\tpath = \"lambdas/\" + name + \".json\"\n\t}\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR Creating file \", err)\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\tl := Lambda{\n\t\tName: name,\n\t\tTriggers: []string{\"api\", \"event\", \"invoke\", \"sns\", \"sqs\"},\n\t\tStages: []string{\"dev\", \"qa\", \"uat\", \"prod\"},\n\t}\n\tprfl := Folder{\n\t\tLambda: l,\n\t}\n\n\tjs, err := json.Marshal(prfl)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR Marshalling \", err)\n\t\treturn\n\t}\n\n\t_, err = f.Write(pretty.Pretty(js))\n\tif err != nil {\n\t\tfmt.Println(\"ERROR Writing file \", err)\n\t}\n}", "func CreatePrintFunction(custom string) Printer {\n\treturn func(s string) {\n\t\tfmt.Println(s + custom)\n\t}\n}", "func (c *Client) NewShowLambdaRequest(ctx context.Context, path string) (*http.Request, error) {\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func NewFunctionCreateCommand(c cli.Interface) *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"create FUNCTION IMAGE\",\n\t\tShort: \"Create function\",\n\t\tPreRunE: cli.ExactArgs(2),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topts := &createFunctionOpts{}\n\t\t\topts.name = args[0]\n\t\t\topts.image = args[1]\n\t\t\treturn createFunction(c, opts)\n\t\t},\n\t}\n}", "func createPackageStep() workflowStep {\n\n\treturn func(ctx *workflowContext) (workflowStep, error) {\n\t\t// Compile the source to linux...\n\t\tsanitizedServiceName := sanitizedName(ctx.serviceName)\n\t\texecutableOutput := fmt.Sprintf(\"%s.lambda.amd64\", sanitizedServiceName)\n\t\tcmd := exec.Command(\"go\", \"build\", \"-o\", executableOutput, \"-tags\", \"lambdabinary\", \".\")\n\t\tctx.logger.Debug(\"Building application binary: \", cmd.Args)\n\t\tcmd.Env = os.Environ()\n\t\tcmd.Env = append(cmd.Env, \"GOOS=linux\", \"GOARCH=amd64\", \"GO15VENDOREXPERIMENT=1\")\n\t\tctx.logger.Info(\"Compiling binary: \", executableOutput)\n\n\t\toutputWriter := ctx.logger.Writer()\n\t\tdefer outputWriter.Close()\n\t\tcmd.Stdout = outputWriter\n\t\tcmd.Stderr = outputWriter\n\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer os.Remove(executableOutput)\n\n\t\t// Binary size\n\t\tstat, err := os.Stat(executableOutput)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Failed to stat build output\")\n\t\t}\n\t\t// Minimum hello world size is 2.3M\n\t\t// Minimum HTTP hello world is 6.3M\n\t\tctx.logger.Info(\"Executable binary size (MB): \", stat.Size()/(1024*1024))\n\n\t\tworkingDir, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Failed to retrieve working directory\")\n\t\t}\n\t\ttmpFile, err := ioutil.TempFile(workingDir, sanitizedServiceName)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Failed to create temporary file\")\n\t\t}\n\n\t\tdefer func() {\n\t\t\ttmpFile.Close()\n\t\t}()\n\n\t\tctx.logger.Info(\"Creating ZIP archive for upload: \", tmpFile.Name())\n\t\tlambdaArchive := zip.NewWriter(tmpFile)\n\t\tdefer lambdaArchive.Close()\n\n\t\t// File info for the binary executable\n\t\tbinaryWriter, err := lambdaArchive.Create(filepath.Base(executableOutput))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to create ZIP entry: %s\", filepath.Base(executableOutput))\n\t\t}\n\t\treader, err := os.Open(executableOutput)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to open file: %s\", executableOutput)\n\t\t}\n\t\tdefer reader.Close()\n\t\tio.Copy(binaryWriter, reader)\n\n\t\t// Add the string literal adapter, which requires us to add exported\n\t\t// functions to the end of index.js\n\t\tnodeJSWriter, err := lambdaArchive.Create(\"index.js\")\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Failed to create ZIP entry: index.js\")\n\t\t}\n\t\tnodeJSSource := _escFSMustString(false, \"/resources/index.js\")\n\t\tnodeJSSource += \"\\n// DO NOT EDIT - CONTENT UNTIL EOF IS AUTOMATICALLY GENERATED\\n\"\n\t\tfor _, eachLambda := range ctx.lambdaAWSInfos {\n\t\t\tnodeJSSource += createNewNodeJSProxyEntry(eachLambda, ctx.logger)\n\t\t}\n\t\t// Finally, replace\n\t\t// \tSPARTA_BINARY_NAME = 'Sparta.lambda.amd64';\n\t\t// with the service binary name\n\t\tnodeJSSource += fmt.Sprintf(\"SPARTA_BINARY_NAME='%s';\\n\", executableOutput)\n\t\tctx.logger.Debug(\"Dynamically generated NodeJS adapter:\\n\", nodeJSSource)\n\t\tstringReader := strings.NewReader(nodeJSSource)\n\t\tio.Copy(nodeJSWriter, stringReader)\n\n\t\t// Also embed the custom resource creation scripts\n\t\tfor _, eachName := range customResourceScripts {\n\t\t\tresourceName := fmt.Sprintf(\"/resources/provision/%s\", eachName)\n\t\t\tresourceContent := _escFSMustString(false, resourceName)\n\t\t\tstringReader := strings.NewReader(resourceContent)\n\t\t\tembedWriter, err := lambdaArchive.Create(eachName)\n\t\t\tif nil != err {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tctx.logger.Info(\"Embedding CustomResource script: \", eachName)\n\t\t\tio.Copy(embedWriter, stringReader)\n\t\t}\n\n\t\t// And finally, if there is a node_modules.zip file, then include it.\n\t\tnodeModuleBytes, err := _escFSByte(false, \"/resources/provision/node_modules.zip\")\n\t\tif nil == err {\n\t\t\tnodeModuleReader, err := zip.NewReader(bytes.NewReader(nodeModuleBytes), int64(len(nodeModuleBytes)))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor _, zipFile := range nodeModuleReader.File {\n\t\t\t\tembedWriter, err := lambdaArchive.Create(zipFile.Name)\n\t\t\t\tif nil != err {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tctx.logger.Debug(\"Copying node_module file: \", zipFile.Name)\n\t\t\t\tsourceReader, err := zipFile.Open()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tio.Copy(embedWriter, sourceReader)\n\t\t\t}\n\t\t} else {\n\t\t\tctx.logger.Warn(\"Failed to load /resources/provision/node_modules.zip for embedding\", err)\n\t\t}\n\t\treturn createUploadStep(tmpFile.Name()), nil\n\t}\n}", "func newLogClosure(\n\tc func() string) logClosure {\n\treturn logClosure(c)\n}", "func main() {\n\tf := GetFlags()\n\tif f.Test {\n\t\tif err := RunTest(f); err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tlambda.Start(HandleRequest)\n}", "func CommandFunc(f func(args []string) error) flags.Commander {\n\treturn &funcCommand{fn: f}\n}", "func NewLambdaFunctionMetricQuery(invocationMetricName MetricName) *awsv2CWTypes.MetricDataQuery {\n\treturn &awsv2CWTypes.MetricDataQuery{\n\t\tId: awsv2.String(strings.ToLower(string(invocationMetricName))),\n\t\tMetricStat: &awsv2CWTypes.MetricStat{\n\t\t\tPeriod: awsv2.Int32(30),\n\t\t\tStat: awsv2.String(string(awsv2CWTypes.StatisticSum)),\n\t\t\tUnit: awsv2CWTypes.StandardUnitCount,\n\t\t\tMetric: &awsv2CWTypes.Metric{\n\t\t\t\tNamespace: awsv2.String(\"AWS/Lambda\"),\n\t\t\t\tMetricName: awsv2.String(string(invocationMetricName)),\n\t\t\t\tDimensions: []awsv2CWTypes.Dimension{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: awsv2.String(\"FunctionName\"),\n\t\t\t\t\t\tValue: nil,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func NewTask(f func(int64)) *StdTask {\n t := new(StdTask)\n t.F = f\n return t\n}", "func NewPluginCommand(cmd *cobra.Command, dockerCli *client.DockerCli) {\n}", "func NewCfnCustomResource(scope constructs.Construct, id *string, props *CfnCustomResourceProps) CfnCustomResource {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnCustomResource{}\n\n\t_jsii_.Create(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnCustomResource\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func main() {\n\tcfg, err := config.Load()\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to load config: %v\\n\", err)\n\t}\n\n\tdb, err := database.SetUp(cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to connect to database: %v\\n\", err)\n\t}\n\n\tjwtManager, err := auth.NewJWTManager(cfg.SecretKey, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create JWT manager: %v\\n\", err)\n\t}\n\n\ts := services.SetUp(db, jwtManager)\n\tr := router.SetUp(s, cfg)\n\tl = chiadapter.New(r)\n\n\tlambda.Start(lambdaHandler)\n}", "func New(spec *Spec) Function {\n\tf := Function{\n\t\tspec: spec,\n\t}\n\treturn f\n}", "func NewCmdCreateEventHandler(f cmdutil.Factory, out io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"handler\",\n\t\tShort: \"Create event handler\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tRunCreateEventHandler(f, out, cmd)\n\t\t},\n\t}\n\tcmd.Flags().StringP(\"source\", \"s\", \"\", \"File containing event handler source code\")\n\tcmd.Flags().StringP(\"frontend\", \"f\", \"\", \"Event handler frontend\")\n\tcmd.Flags().StringP(\"url\", \"u\", \"\", \"URL of event handler source code\")\n\tcmd.Flags().StringP(\"version\", \"v\", \"1.0\", \"Event handler version\")\n\tcmd.Flags().StringP(\"dependencies-file\", \"d\", \"\", \"File containing event handler dependencies\")\n\tcmd.Flags().StringP(\"dependencies-url\", \"l\", \"\", \"URL of event handler source dependencies\")\n\n\treturn cmd\n}", "func myPrintFunction(custom string) myPrintType{\nreturn func(s string){\nfmt.Println(s +custom)\n}\n}", "func spartaCustomResourceForwarder(event *json.RawMessage,\n\tcontext *LambdaContext,\n\tw http.ResponseWriter,\n\tlogger *logrus.Logger) {\n\n\tvar rawProps map[string]interface{}\n\tjson.Unmarshal([]byte(*event), &rawProps)\n\n\tvar lambdaEvent cloudformationresources.CloudFormationLambdaEvent\n\tjsonErr := json.Unmarshal([]byte(*event), &lambdaEvent)\n\tif jsonErr != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"RawEvent\": rawProps,\n\t\t\t\"UnmarshalError\": jsonErr,\n\t\t}).Warn(\"Raw event data\")\n\t\thttp.Error(w, jsonErr.Error(), http.StatusInternalServerError)\n\t}\n\n\tlogger.WithFields(logrus.Fields{\n\t\t\"LambdaEvent\": lambdaEvent,\n\t}).Debug(\"CloudFormation Lambda event\")\n\n\t// Setup the request and send it off\n\tcustomResourceRequest := &cloudformationresources.CustomResourceRequest{}\n\tcustomResourceRequest.RequestType = lambdaEvent.RequestType\n\tcustomResourceRequest.ResponseURL = lambdaEvent.ResponseURL\n\tcustomResourceRequest.StackID = lambdaEvent.StackID\n\tcustomResourceRequest.RequestID = lambdaEvent.RequestID\n\tcustomResourceRequest.LogicalResourceID = lambdaEvent.LogicalResourceID\n\tcustomResourceRequest.PhysicalResourceID = lambdaEvent.PhysicalResourceID\n\tcustomResourceRequest.LogGroupName = context.LogGroupName\n\tcustomResourceRequest.LogStreamName = context.LogStreamName\n\tcustomResourceRequest.ResourceProperties = lambdaEvent.ResourceProperties\n\tif \"\" == customResourceRequest.PhysicalResourceID {\n\t\tcustomResourceRequest.PhysicalResourceID = fmt.Sprintf(\"LogStreamName: %s\", context.LogStreamName)\n\t}\n\n\trequestErr := cloudformationresources.Handle(customResourceRequest, logger)\n\tif requestErr != nil {\n\t\thttp.Error(w, requestErr.Error(), http.StatusInternalServerError)\n\t} else {\n\t\tfmt.Fprint(w, \"CustomResource handled: \"+lambdaEvent.LogicalResourceID)\n\t}\n}", "func TestNotLambda(t *testing.T) {\n\tctx := context.Background()\n\tlambdaDetector, err := NewDetector(processortest.NewNopCreateSettings(), CreateDefaultConfig())\n\trequire.NoError(t, err)\n\tres, _, err := lambdaDetector.Detect(ctx)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, res)\n\n\tassert.Equal(t, 0, res.Attributes().Len(), \"Resource object should be empty\")\n}", "func NewCustomAccessPackageWorkflowExtension()(*CustomAccessPackageWorkflowExtension) {\n m := &CustomAccessPackageWorkflowExtension{\n CustomCalloutExtension: *NewCustomCalloutExtension(),\n }\n odataTypeValue := \"#microsoft.graph.customAccessPackageWorkflowExtension\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func CodeLambdaPath(lambdaID int) string {\n\tparam0 := strconv.Itoa(lambdaID)\n\n\treturn fmt.Sprintf(\"/p7/lambdas/%s/actions/code\", param0)\n}", "func NewCustomParser(commandMap stringmap.StringMap) *CustomParser {\n\treturn &CustomParser{\n\t\tcommandMap: commandMap,\n\t}\n}", "func CustomGenerateTagFunc(name, typ, tag string) string {\n\treturn fmt.Sprintf(\"json:\\\"%s\\\"\", tag)\n}", "func LambdaHandler(functionName string,\n\tlogLevel string,\n\teventJSON string,\n\tawsCredentials *credentials.Credentials) ([]byte, http.Header, error) {\n\tstartTime := time.Now()\n\n\treadableBody := bytes.NewReader([]byte(eventJSON))\n\treadbleBodyCloser := ioutil.NopCloser(readableBody)\n\t// Update the credentials\n\tmuCredentials.Lock()\n\tvalue, valueErr := awsCredentials.Get()\n\tif nil != valueErr {\n\t\tmuCredentials.Unlock()\n\t\treturn nil, nil, valueErr\n\t}\n\tpythonCredentialsValue.AccessKeyID = value.AccessKeyID\n\tpythonCredentialsValue.SecretAccessKey = value.SecretAccessKey\n\tpythonCredentialsValue.SessionToken = value.SessionToken\n\tpythonCredentialsValue.ProviderName = \"PythonCGO\"\n\tmuCredentials.Unlock()\n\n\t// Unpack the JSON request, turn it into a proto here and pass it\n\t// into the handler...\n\n\t// Update the credentials in the HTTP handler\n\t// in case we're ultimately forwarding to a custom\n\t// resource provider\n\tcgoLambdaHTTPAdapter.lambdaHTTPHandlerInstance.Credentials(pythonCredentialsValue)\n\tlogrusLevel, logrusLevelErr := logrus.ParseLevel(logLevel)\n\tif logrusLevelErr == nil {\n\t\tcgoLambdaHTTPAdapter.logger.SetLevel(logrusLevel)\n\t}\n\tcgoLambdaHTTPAdapter.logger.WithFields(logrus.Fields{\n\t\t\"Resource\": functionName,\n\t\t\"Request\": eventJSON,\n\t}).Debug(\"Making request\")\n\n\t// Make the request...\n\tresponse, header, err := makeRequest(functionName, readbleBodyCloser, int64(len(eventJSON)))\n\n\t// TODO: Consider go routine\n\tpostMetrics(awsCredentials, functionName, len(response), time.Since(startTime))\n\n\tcgoLambdaHTTPAdapter.logger.WithFields(logrus.Fields{\n\t\t\"Header\": header,\n\t\t\"Error\": err,\n\t}).Debug(\"Request response\")\n\n\treturn response, header, err\n}", "func NewCustomEvent(userID, sessionID, context string) CustomEvent {\n\treturn CustomEvent{\n\t\tEventMeta: logger.NewEventMeta(logger.Flag(\"custom_event\")),\n\t\tUserID: userID,\n\t\tSessionID: sessionID,\n\t\tContext: context,\n\t}\n}", "func NewCommandFromPayload(contract string, payload []byte) (domain.Command, error) {\n\tswitch contract {\n\tcase RegisterUserWithEmail:\n\t\tcommand := RegisterWithEmail{}\n\t\tif err := json.Unmarshal(payload, &command); err != nil {\n\t\t\treturn command, apperrors.Wrap(err)\n\t\t}\n\n\t\treturn command, nil\n\tcase RegisterUserWithGoogle:\n\t\tcommand := RegisterWithGoogle{}\n\t\tif err := json.Unmarshal(payload, &command); err != nil {\n\t\t\treturn command, apperrors.Wrap(err)\n\t\t}\n\n\t\treturn command, nil\n\tcase RegisterUserWithFacebook:\n\t\tcommand := RegisterWithFacebook{}\n\t\tif err := json.Unmarshal(payload, &command); err != nil {\n\t\t\treturn command, apperrors.Wrap(err)\n\t\t}\n\n\t\treturn command, nil\n\tcase ChangeUserEmailAddress:\n\t\tcommand := ChangeEmailAddress{}\n\t\tif err := json.Unmarshal(payload, &command); err != nil {\n\t\t\treturn command, apperrors.Wrap(err)\n\t\t}\n\n\t\treturn command, nil\n\tdefault:\n\t\treturn nil, apperrors.Wrap(fmt.Errorf(\"invalid command contract: %s\", contract))\n\t}\n}", "func NewCustomServer(c func() Codec, listener net.Listener) *Server {\n\treturn &Server{\n\t\tcodec: c,\n\t\tlistener: &onceCloseListener{Listener: listener},\n\t}\n}", "func HandleLambdaEvent(event MyEvent) (MyResponse, error) {\n\tfmt.Printf(\"event argument: %#v\", event)\n\treturn MyResponse{Message: fmt.Sprintf(\"%s is %d years old!\", event.Name, event.Age)}, nil\n}", "func LambdaHandler(user string) (ResponseData, error) {\n\n\tvar res ResponseData\n\tvar accessSecret secretParameters\n\n\t// Connection information\n\tsess := session.Must(session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t}))\n\n\tvuser, e := createUser(sess, user)\n\n\tif e != nil {\n\t\tfmt.Println(e.Error())\n\t\treturn res, e\n\t}\n\n\tres.ResponseMessage = fmt.Sprintln(\"User created:\", user)\n\n\tif _, e := createAccessKey(sess, vuser); e != nil {\n\t\tfmt.Println(e.Error())\n\t\treturn res, e\n\t}\n\n\tres.ResponseMessage = fmt.Sprintln(\"Access Key created:\", accessSecret.AccessKey)\n\n\treturn res, nil\n\n}", "func (c *Client) RunLambda(ctx context.Context, path string) (*http.Response, error) {\n\treq, err := c.NewRunLambdaRequest(ctx, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Client.Do(ctx, req)\n}", "func New(repo eventsource.Repository, preprocessors ...Preprocessor) Dispatcher {\n\treturn dispatchFunc(func(ctx context.Context, cmd Interface) error {\n\t\tfor _, p := range preprocessors {\n\t\t\terr := p.Before(ctx, cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn eventsource.NewError(err, CodePreprocessorErr, \"processor failed on command, %#v\", cmd)\n\t\t\t}\n\t\t}\n\n\t\tvar aggregate eventsource.Aggregate\n\t\tif v, ok := cmd.(Constructor); ok && v.New() {\n\t\t\taggregate = repo.New()\n\n\t\t} else {\n\t\t\taggregateID := cmd.AggregateID()\n\t\t\tv, err := repo.Load(ctx, aggregateID)\n\t\t\tif err != nil {\n\t\t\t\treturn eventsource.NewError(err, CodeEventLoadErr, \"Unable to load %v [%v]\", typeOf(repo.New()), aggregateID)\n\t\t\t}\n\t\t\taggregate = v\n\t\t}\n\n\t\thandler, ok := aggregate.(Handler)\n\t\tif !ok {\n\t\t\treturn eventsource.NewError(nil, CodeAggregateNotCommandHandler, \"%#v does not implement command.Handler\", typeOf(aggregate))\n\t\t}\n\n\t\tevents, err := handler.Apply(ctx, cmd)\n\t\tif err != nil {\n\t\t\treturn eventsource.NewError(err, CodeHandlerErr, \"Failed to apply command, %v, to aggregate, %v\", typeOf(cmd), typeOf(aggregate))\n\t\t}\n\n\t\terr = repo.Save(ctx, events...)\n\t\tif err != nil {\n\t\t\treturn eventsource.NewError(err, CodeSaveErr, \"Failed to save events for %v, %v\", typeOf(aggregate), cmd.AggregateID())\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func NewSDKActor(execute func(string) string) SDKActor {\n sdkActor := SDKActor{}\n sdkActor.connector = newConnector()\n sdkActor.execute = execute\n return sdkActor\n}", "func addCloudformationLambdaFunctions(template *cloudformation.Template, functions map[string]cloudformation.AWSServerlessFunction) {\n\t// convert all lambda functions to serverless functions so that invoke works for them\n\tfor n, f := range template.GetAllAWSLambdaFunctionResources() {\n\t\tif _, found := functions[n]; !found {\n\t\t\tfunctions[n] = lambdaToServerless(f)\n\t\t}\n\t}\n}", "func NewCreate(f func(string, string, []string) (proto.Message, error)) *cobra.Command {\n\tvar (\n\t\tdisplayName string\n\t\tpermissionIDs []string\n\t)\n\n\tcmd := template.NewArg1Proto(\"create ROLE_ID\", \"Create a new role\", func(cmd *cobra.Command, arg string) (proto.Message, error) {\n\t\tvar names []string\n\t\tfor _, p := range permissionIDs {\n\t\t\tnames = append(names, fmt.Sprintf(\"permissions/%s\", p))\n\t\t}\n\t\treturn f(arg, displayName, names)\n\t})\n\n\tcmd.Flags().StringVar(&displayName, \"display-name\", \"\", \"display name\")\n\tcmd.Flags().StringSliceVar(&permissionIDs, \"permission-ids\", nil, \"permission ids\")\n\n\treturn cmd\n}", "func NewCustom(executor executor.Executor) executor.Launcher {\n\treturn New(executor, fmt.Sprintf(\"stress-ng-custom %s\", StressngCustomArguments.Value()), StressngCustomArguments.Value())\n}", "func NewFunction(ctx *pulumi.Context,\n\tname string, args *FunctionArgs, opts ...pulumi.ResourceOption) (*Function, error) {\n\tif args == nil {\n\t\targs = &FunctionArgs{}\n\t}\n\n\treplaceOnChanges := pulumi.ReplaceOnChanges([]string{\n\t\t\"location\",\n\t\t\"project\",\n\t})\n\topts = append(opts, replaceOnChanges)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Function\n\terr := ctx.RegisterResource(\"google-native:cloudfunctions/v2:Function\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func toFunc(commandName string) (Command, error) {\n\tswitch strings.ToLower(commandName) {\n\tdefault:\n\t\treturn nil, errors.New(\"invalid command.\")\n\tcase \".quit\":\n\t\treturn Quit, nil\n\tcase \".kick\":\n\t\treturn KickOut, nil\n\tcase \".dm\":\n\t\treturn DM, nil\n\tcase \".list\":\n\t\treturn ListMembers, nil\n\tcase \".msg\":\n\t\treturn Message, nil\n\t}\n}", "func NewLambdaClient(opt Options) *lambdaClient {\n\treturn &lambdaClient{\n\t\topt: opt,\n\t}\n}", "func NewInvokeRequestWithoutParam() *InvokeRequest {\n\n return &InvokeRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/regions/{regionId}/functions/{functionName}/versions/{versionName}:invoke\",\n Method: \"POST\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}", "func CreateLambdaCloudwatchAlarm(region string, functionName string, metricName string, namespace string, threshold float64, action string) bool {\n\tawsSession, _ := InitAwsSession(region)\n\tsvc := cloudwatch.New(awsSession)\n\tinput := &cloudwatch.PutMetricAlarmInput{\n\t\tAlarmName: aws.String(fmt.Sprintf(\"%v on %v\", metricName, functionName)),\n\t\tComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanOrEqualToThreshold),\n\t\tEvaluationPeriods: aws.Int64(1),\n\t\tMetricName: aws.String(metricName),\n\t\tNamespace: aws.String(namespace),\n\t\tPeriod: aws.Int64(60),\n\t\tStatistic: aws.String(cloudwatch.StatisticSum),\n\t\tThreshold: aws.Float64(threshold),\n\t\tActionsEnabled: aws.Bool(true),\n\t\tAlarmDescription: aws.String(fmt.Sprintf(\"%v on %v greater than %v\", metricName, functionName, threshold)),\n\n\t\tDimensions: []*cloudwatch.Dimension{\n\t\t\t{\n\t\t\t\tName: aws.String(\"FunctionName\"),\n\t\t\t\tValue: aws.String(functionName),\n\t\t\t},\n\t\t},\n\n\t\tAlarmActions: []*string{\n\t\t\taws.String(action),\n\t\t},\n\t}\n\n\t// Debug input\n\t// fmt.Println(input)\n\n\t_, err := svc.PutMetricAlarm(input)\n\tif err != nil {\n\t\tfmt.Println(\"Error\", err)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func lambdaToServerless(lambda cloudformation.AWSLambdaFunction) (serverless cloudformation.AWSServerlessFunction) {\n\t// serverless policies are not needed because lambdas have a role\n\tserverless.Policies = nil\n\n\t// no events are associated with the function\n\tserverless.Events = nil\n\n\t// codeUri is set to nil in order to get the code locally and not from a remote source\n\tserverless.CodeUri = nil\n\n\tserverless.FunctionName = lambda.FunctionName\n\tserverless.Description = lambda.Description\n\tserverless.Handler = lambda.Handler\n\tserverless.Timeout = lambda.Timeout\n\tserverless.KmsKeyArn = lambda.KmsKeyArn\n\tserverless.Role = lambda.Role\n\tserverless.Runtime = lambda.Runtime\n\tserverless.MemorySize = lambda.MemorySize\n\n\tif lambda.DeadLetterConfig != nil {\n\t\tdlqType := \"SQS\"\n\t\tmatch := dlqTypeEx.FindAllStringSubmatch(lambda.DeadLetterConfig.TargetArn, -1)\n\t\tif len(match) > 0 {\n\t\t\tdlqType = match[0][1]\n\t\t}\n\n\t\tserverless.DeadLetterQueue = &cloudformation.AWSServerlessFunction_DeadLetterQueue{\n\t\t\tTargetArn: lambda.DeadLetterConfig.TargetArn,\n\t\t\tType: strings.ToUpper(dlqType),\n\t\t}\n\t}\n\n\tif len(lambda.Tags) > 0 {\n\t\ttags := make(map[string]string)\n\t\tfor _, t := range lambda.Tags {\n\t\t\ttags[t.Key] = t.Value\n\t\t}\n\t\tserverless.Tags = tags\n\t}\n\n\tif lambda.TracingConfig != nil {\n\t\tserverless.Tracing = lambda.TracingConfig.Mode\n\t}\n\n\tif lambda.Environment != nil {\n\t\tserverless.Environment = &cloudformation.AWSServerlessFunction_FunctionEnvironment{\n\t\t\tVariables: lambda.Environment.Variables,\n\t\t}\n\t}\n\n\tif lambda.VpcConfig != nil {\n\t\tserverless.VpcConfig = &cloudformation.AWSServerlessFunction_VpcConfig{\n\t\t\tSecurityGroupIds: lambda.VpcConfig.SecurityGroupIds,\n\t\t\tSubnetIds: lambda.VpcConfig.SubnetIds,\n\t\t}\n\t}\n\n\treturn\n}", "func newEventHandler(fn interface{}, configurators []EventConfigurator) *eventHandler {\n\te := &eventHandler{\n\t\tcallBack: reflect.ValueOf(fn),\n\t\tMutex: sync.Mutex{},\n\t}\n\t// config\n\tfor i := range configurators {\n\t\tconfigurators[i](e)\n\t}\n\treturn e\n}", "func ClosureNew(f interface{}) *C.GClosure {\n\tclosure := C._g_closure_new()\n\tclosures.Lock()\n\tclosures.m[closure] = reflect.ValueOf(f)\n\tclosures.Unlock()\n\treturn closure\n}", "func newSshNativeTask(host string, cmd string, opt Options) func() (interface{}, error) {\n\tstate := &sshNativeTask{\n\t\tHost: host,\n\t\tCmd: cmd,\n\t\tOpts: opt,\n\t}\n\treturn state.run\n}", "func (c *Client) NewListLambdaRequest(ctx context.Context, path string) (*http.Request, error) {\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func (s *SimilarityLMJelinekMercer) Lambda(lambda float32) *SimilarityLMJelinekMercer {\n\ts.lambda = &lambda\n\treturn s\n}", "func NewQueryLambdaSql(query string) *QueryLambdaSql {\n\tthis := QueryLambdaSql{}\n\tthis.Query = query\n\treturn &this\n}", "func NewUrl(ctx *pulumi.Context,\n\tname string, args *UrlArgs, opts ...pulumi.ResourceOption) (*Url, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.AuthType == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'AuthType'\")\n\t}\n\tif args.TargetFunctionArn == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TargetFunctionArn'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Url\n\terr := ctx.RegisterResource(\"aws-native:lambda:Url\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func LambdaHref(lambdaID interface{}) string {\n\tparamlambdaID := strings.TrimLeftFunc(fmt.Sprintf(\"%v\", lambdaID), func(r rune) bool { return r == '/' })\n\treturn fmt.Sprintf(\"/p7/lambdas/%v\", paramlambdaID)\n}" ]
[ "0.6809891", "0.6555737", "0.6116072", "0.60545045", "0.5895499", "0.5475411", "0.5467674", "0.5454632", "0.5418645", "0.5418645", "0.538186", "0.53744304", "0.5372076", "0.536581", "0.5345117", "0.53066945", "0.5267985", "0.52672946", "0.5256035", "0.5200754", "0.5184864", "0.5184864", "0.5184864", "0.51721776", "0.51703125", "0.51580137", "0.51187295", "0.50939065", "0.506364", "0.49800122", "0.49760208", "0.49675593", "0.49281847", "0.48972243", "0.4870489", "0.4867049", "0.4863693", "0.48613295", "0.485114", "0.4850815", "0.48295268", "0.48227012", "0.48200744", "0.48112348", "0.4787294", "0.47851422", "0.47829318", "0.47767264", "0.47541043", "0.47314", "0.47302604", "0.47238705", "0.47221518", "0.47174153", "0.46917486", "0.46753088", "0.46611547", "0.4649559", "0.46482468", "0.46479818", "0.4639956", "0.4621591", "0.46049756", "0.4593627", "0.45899028", "0.45727336", "0.45695084", "0.45656455", "0.45638037", "0.45586723", "0.45384824", "0.45354882", "0.45279256", "0.4519368", "0.4516676", "0.45063096", "0.44951943", "0.44897914", "0.4486728", "0.44761276", "0.44690752", "0.4468953", "0.4456732", "0.4453384", "0.44310603", "0.44280532", "0.44229728", "0.44188035", "0.44161516", "0.44130284", "0.4410222", "0.44100836", "0.44069695", "0.44022852", "0.43979096", "0.43900245", "0.43812287", "0.4378663", "0.43775675", "0.4374682" ]
0.8538253
0
Name returns the custom lambda's name
func (l *CustomLambda) Name() string { return l.name }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Name(ctx context.Context) string {\n\tf, ok := ctx.Value(stateKey).(*Func)\n\tif !ok {\n\t\treturn \"<Undefined>\"\n\t}\n\tname := runtime.FuncForPC(reflect.ValueOf(*f).Pointer()).Name()\n\treturn strings.TrimRight(nameRe.FindStringSubmatch(name)[1], \")\")\n}", "func (m Function) Name() string {\n\treturn m.name\n}", "func (n *BindFnNode) Name() string { return n.name }", "func (t *Test) Name() string {\n\treturn t.callable.Name()\n}", "func (f *Function) Name() string {\n\treturn \"\"\n}", "func (o FunctionOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Function) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (f *Function) Name() string {\n\treturn f.name\n}", "func (v *Function) GetName() (o string) {\n\tif v != nil {\n\t\to = v.Name\n\t}\n\treturn\n}", "func (r *AwsCloudwatchLogGroupLambdaRetentionRule) Name() string {\n\treturn \"aws_cloudwatch_log_group_lambda_retention\"\n}", "func (n *FnInvNode) Name() string {\n\treturn n.name\n}", "func (mg MessageHandler) Name() string {\n\treturn nameFromFunc(mg)\n}", "func (f LetFunction) Name() string {\n\treturn f.name\n}", "func (oe *OraErr) FunName() string { return oe.funName }", "func (fnGet) Name() string {\n\treturn \"get\"\n}", "func (x InfrastructureAwsLambdaFunctionEntity) GetName() string {\n\treturn x.Name\n}", "func (m Method) Name() string {\n\treturn m.function.name\n}", "func (c criterionFunc) Name() string {\n\treturn c.name\n}", "func (dlmg RawMessageHandler) Name() string {\n\treturn nameFromFunc(dlmg)\n}", "func FuncName(i interface{}) string {\n\treturn runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()\n}", "func NewCustomLambda(name, command string) *CustomLambda {\n\treturn &CustomLambda{\n\t\tname: name,\n\t\tcommand: command,\n\t}\n}", "func (maxFn) Name() string {\n\treturn \"max\"\n}", "func (p *PropertyGenerator) getFnName(i int) string {\n\tif len(p.Kinds) == 1 {\n\t\treturn getMethod\n\t}\n\treturn fmt.Sprintf(\"%s%s\", getMethod, p.kindCamelName(i))\n}", "func (*FunctionLength) Name() string {\n\treturn \"function-length\"\n}", "func (o RegistryTaskSourceTriggerOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RegistryTaskSourceTrigger) string { return v.Name }).(pulumi.StringOutput)\n}", "func (n *ExceptionNamer) Name(t *types.Type) string {\n\tkey := n.KeyFunc(t)\n\tif exception, ok := n.Exceptions[key]; ok {\n\t\treturn exception\n\t}\n\treturn n.Delegate.Name(t)\n}", "func (f Function) GetName() string {\n\treturn f.ident.String()\n}", "func (o AzureFunctionOutputDataSourceOutput) FunctionName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AzureFunctionOutputDataSource) *string { return v.FunctionName }).(pulumi.StringPtrOutput)\n}", "func (DetectedAWSLambda) TableName() string {\n\treturn \"aws_lambda\"\n}", "func (fva *FunctionVisibilityAnalyzer) Name() string {\n\treturn \"function visibility\"\n}", "func (collector *CollectorV2[T]) Name() string {\n\treturn collector.name\n}", "func (o RegistryTaskTimerTriggerOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RegistryTaskTimerTrigger) string { return v.Name }).(pulumi.StringOutput)\n}", "func NameFunc(name string, fn func(ctx context.Context) error) NamedRunner {\n\treturn Name(name, RunnerFunc(fn))\n}", "func Name(v interface{}) string {\n\treturn New(v).Name()\n}", "func (o AzureFunctionOutputDataSourceResponseOutput) FunctionName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AzureFunctionOutputDataSourceResponse) *string { return v.FunctionName }).(pulumi.StringPtrOutput)\n}", "func (f *Function) Name() string {\n\tcstr := C.EnvGetDeffunctionName(f.env.env, f.fptr)\n\treturn C.GoString(cstr)\n}", "func (a *RedisAction) Name() string {\n\treturn a.name\n}", "func (p *FuncInfo) Name() string {\n\treturn p.name\n}", "func funcName(f interface{}) string {\n\tfi := ess.GetFunctionInfo(f)\n\treturn fi.Name\n}", "func (c *Event) Name() string {\n\treturn c.name\n}", "func (d *Decoder) NameFunc(n func(field string, locations []int) string) {\n\td.cache.nameFunc = n\n}", "func (o *CreateEventPayloadActions) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (action *scheduleRoutineAction) Name() string {\n\treturn \"schedule-routine\"\n}", "func (action *scheduleRoutineAction) Name() string {\n\treturn \"schedule-routine\"\n}", "func (e *BasicEvent) Name() string {\n\treturn e.name\n}", "func (sqs *SQS) Name() string {\n\treturn strings.Split(sqs.Arn, \":\")[5]\n}", "func (l *littr) GetFuncName(i int) string {\n\treturn l.code[i+5 : i+strings.Index(l.code[i:], \"(\")]\n}", "func (f frame) name() string {\n\tfn := runtime.FuncForPC(f.pc())\n\tif fn == nil {\n\t\treturn \"unknown\"\n\t}\n\treturn fn.Name()\n}", "func functionName(i func(int, int) (int, error)) string {\n\treturn runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()\n}", "func (getEnvPropertyValueFn) Name() string {\n\treturn \"getEnvPropertyValue\"\n}", "func (_FCToken *FCTokenCaller) Name(opts *bind.CallOpts) (string, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"name\")\n\n\tif err != nil {\n\t\treturn *new(string), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(string)).(*string)\n\n\treturn out0, err\n\n}", "func (x InfrastructureAwsLambdaFunctionEntityOutline) GetName() string {\n\treturn x.Name\n}", "func (e *binaryExprEvaluator) name() string { return \"\" }", "func (Functions) NameOf(obj interface{}) string {\n\treturn nameOf(obj)\n}", "func (g Generator) InvocationName() string {\n\treturn \"action\"\n}", "func (_ EventFilterAliases) Name(p graphql.ResolveParams) (string, error) {\n\tval, err := graphql.DefaultResolver(p.Source, p.Info.FieldName)\n\tret, ok := val.(string)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tif !ok {\n\t\treturn ret, errors.New(\"unable to coerce value for field 'name'\")\n\t}\n\treturn ret, err\n}", "func (d *ActionRename) Name() string {\n\treturn renameAction\n}", "func (o TriggerOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Trigger) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (t Type) Name() string {\n\treturn schemas[t%EvCount].Name\n}", "func (s *NamespaceWebhook) Name() string { return WebhookName }", "func (e *EDNS) Name() string { return name }", "func (o MethodOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Method) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (f nullFunc) name() name {\n\treturn null\n}", "func (c *withNameAndCode) Name() string {\n\treturn c.name\n}", "func (f *NamedFunction) NameString() string {\n\treturn f.Name.String()\n}", "func (s *StopEvent) Name() string {\n\treturn s.name\n}", "func (t *LogProviderHandler) Name() string {\n\treturn LogProvider\n}", "func (e *Executor) Name() string {\n\treturn OperationName\n}", "func (handler *ConsoleLogHandler) Name() string {\r\n return \"console\"\r\n}", "func nameOfFunction(f interface{}) string {\n\tfun := runtime.FuncForPC(reflect.ValueOf(f).Pointer())\n\ttokenized := strings.Split(fun.Name(), \".\")\n\tlast := tokenized[len(tokenized)-1]\n\tlast = strings.TrimSuffix(last, \")·fm\") // < Go 1.5\n\tlast = strings.TrimSuffix(last, \")-fm\") // Go 1.5\n\tlast = strings.TrimSuffix(last, \"·fm\") // < Go 1.5\n\tlast = strings.TrimSuffix(last, \"-fm\") // Go 1.5\n\tif last == \"func1\" { // this could mean conflicts in API docs\n\t\tval := atomic.AddInt32(&anonymousFuncCount, 1)\n\t\tlast = \"func\" + fmt.Sprintf(\"%d\", val)\n\t\tatomic.StoreInt32(&anonymousFuncCount, val)\n\t}\n\treturn last\n}", "func (n *SQSNotify) Name() string {\n\treturn n.name\n}", "func (m *MockJob) Name() string {\n\tr0 := m.NameFunc.nextHook()()\n\tm.NameFunc.appendCall(JobNameFuncCall{r0})\n\treturn r0\n}", "func (o *EventTypeIn) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (_ElvToken *ElvTokenCaller) Name(opts *bind.CallOpts) (string, error) {\n\tvar out []interface{}\n\terr := _ElvToken.contract.Call(opts, &out, \"name\")\n\n\tif err != nil {\n\t\treturn *new(string), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(string)).(*string)\n\n\treturn out0, err\n\n}", "func NameOfEvent(t uint32) string {\n\tswitch t {\n\tcase SessionCreate:\n\t\treturn \"SessionCreate\"\n\tcase SessionDestroy:\n\t\treturn \"SessionDestroy\"\n\tcase TopicPublish:\n\t\treturn \"TopicPublish\"\n\tcase TopicSubscribe:\n\t\treturn \"TopicSubscribe\"\n\tcase TopicUnsubscribe:\n\t\treturn \"TopicUnsubscribe\"\n\tcase QutoChange:\n\t\treturn \"QutoChange\"\n\tcase SessionResume:\n\t\treturn \"SessionResume\"\n\tcase AuthChange:\n\t\treturn \"AuthChange\"\n\tdefault:\n\t\treturn \"Unknown\"\n\t}\n}", "func (app *App) Name(name func(string) string) *App {\n\tapp.name = name\n\treturn app\n}", "func (ext *GetExtendedResourcesFunction) Name() string {\n\treturn \"GetExtendedResources\"\n}", "func (t EventType) GetName() string {\n\treturn C.GoString((*C.char)(C.gst_event_type_get_name(C.GstEventType(t))))\n}", "func (f Frame) name() string {\n\tfn := runtime.FuncForPC(f.pc())\n\tif fn == nil {\n\t\treturn \"unknown\"\n\t}\n\treturn fn.Name()\n}", "func (o OrganizationJobTriggerOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *OrganizationJobTrigger) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (fn *Func) FuncName() string {\n\treturn fn.fnName\n}", "func (method *Method) GetName() string { return method.Name }", "func (g Generator) Name() string {\n\treturn \"buffalo/generate-action\"\n}", "func (o TriggerGithubOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerGithub) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (ctx *Context) HandlerName() string {\n\treturn nameOfFunction(ctx.handlers.last())\n}", "func (p *PropertyGenerator) deserializeFnName() string {\n\tif p.asIterator {\n\t\treturn fmt.Sprintf(\"%s%s\", deserializeIteratorMethod, p.Name.CamelName)\n\t}\n\treturn fmt.Sprintf(\"%s%sProperty\", deserializeMethod, p.Name.CamelName)\n}", "func (_ZKOnacci *ZKOnacciCaller) Name(opts *bind.CallOpts) (string, error) {\n\tvar out []interface{}\n\terr := _ZKOnacci.contract.Call(opts, &out, \"name\")\n\n\tif err != nil {\n\t\treturn *new(string), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(string)).(*string)\n\n\treturn out0, err\n\n}", "func name(obj, eventType, eventSource string) string {\n\t// Pod names need to be lowercase. We might have an eventType as Any, that is why we lowercase them.\n\tif eventType == \"\" {\n\t\teventType = \"testany\"\n\t}\n\tif eventSource == \"\" {\n\t\teventSource = \"testany\"\n\t}\n\treturn strings.ToLower(fmt.Sprintf(\"%s-%s-%s\", obj, eventType, eventSource))\n}", "func (t Scalar) Name() string {\n\treturn strings.Title(t.Type)\n}", "func (o EventIntegrationOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EventIntegration) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (p *PropertyGenerator) serializeFnName() string {\n\tif p.asIterator {\n\t\treturn serializeIteratorMethod\n\t}\n\treturn serializeMethod\n}", "func (v ValidationFilter) Name() string {\r\n\treturn FilterValidation\r\n}", "func (*unifinames) Name() string { return \"unifi-names\" }", "func (pc *HTTPProxyClient) GetFunctionName(r *http.Request) string {\n\tvars := mux.Vars(r)\n\treturn vars[\"name\"]\n}", "func (o LookupListenerResultOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupListenerResult) string { return v.Name }).(pulumi.StringOutput)\n}", "func (s *Instruction) FuncName() string {\n\tif name, ok := protoNameToFuncName[s.Protobuf.TypeName]; ok {\n\t\treturn name\n\t}\n\treturn \"?\"\n}", "func (Functions) CommandName(obj interface{}) string {\n\treturn nameOptions{}.convert(nameOf(obj))\n}", "func (e *ChainEncryptor) Name() string {\n\treturn e.name\n}", "func FuncName(frame *govulncheck.StackFrame) string {\n\tswitch {\n\tcase frame.Receiver != \"\":\n\t\treturn fmt.Sprintf(\"%s.%s\", strings.TrimPrefix(frame.Receiver, \"*\"), frame.Function)\n\tcase frame.Package != \"\":\n\t\treturn fmt.Sprintf(\"%s.%s\", frame.Package, frame.Function)\n\tdefault:\n\t\treturn frame.Function\n\t}\n}", "func (c Code) Name() string {\n\treturn codeName[c]\n}", "func (of OperatorFactory) Name() string {\n\treturn operatorName\n}" ]
[ "0.6796825", "0.6480836", "0.64511144", "0.6372886", "0.634839", "0.6304672", "0.6254236", "0.6149269", "0.61243826", "0.61201745", "0.6118296", "0.6099602", "0.60856926", "0.60603654", "0.60352004", "0.5990408", "0.5978422", "0.5950406", "0.59426147", "0.59111196", "0.58902586", "0.5882737", "0.5870252", "0.5851591", "0.58515304", "0.5845814", "0.5795807", "0.57876956", "0.5781971", "0.5765038", "0.5753295", "0.57274544", "0.5719827", "0.5709263", "0.5698399", "0.5698169", "0.56962085", "0.56902117", "0.5680151", "0.56630594", "0.5653816", "0.56482834", "0.56482834", "0.5642264", "0.56355757", "0.563449", "0.563033", "0.5625635", "0.5623006", "0.5605839", "0.5603614", "0.5597817", "0.55963653", "0.5579961", "0.5577877", "0.5572013", "0.5559147", "0.5553601", "0.55510265", "0.5540461", "0.55336654", "0.55315393", "0.55162746", "0.55139023", "0.5510225", "0.5507841", "0.5505278", "0.5498224", "0.5494786", "0.5489895", "0.548717", "0.5485834", "0.5482287", "0.5482223", "0.5481784", "0.5470104", "0.54659325", "0.54625463", "0.5461361", "0.545628", "0.5451694", "0.54310024", "0.5430077", "0.54255646", "0.542518", "0.5423737", "0.54219913", "0.5420114", "0.5418339", "0.5418298", "0.5417198", "0.5414539", "0.54127324", "0.5410634", "0.5408961", "0.540808", "0.54013073", "0.54006517", "0.539913", "0.5392102" ]
0.83328086
0
Execute executes the custom lambda command
func (l *CustomLambda) Execute(stdin io.Reader, args []string) (string, error) { argsStr := strings.TrimSpace(strings.Join(args, " ")) if argsStr != "" { argsStr = " " + argsStr } cmd := exec.Command("bash", "-c", l.command+argsStr) // pass through some stdin goodness cmd.Stdin = stdin // for those who are about to rock, I salute you. stdoutStderr, err := cmd.CombinedOutput() if err == nil { // noiiiice! log.WithFields(log.Fields{"name": l.Name(), "command": l.command}).Info("Lambda Execution") return strings.TrimSpace(string(stdoutStderr)), nil } // *sigh* log.WithFields(log.Fields{"name": l.Name(), "command": l.command}).Error("Lambda Execution") return string(stdoutStderr), errors.New("Error running command") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_Vault *VaultTransactor) Execute(opts *bind.TransactOpts, token common.Address, amount *big.Int, recipientToken common.Address, exchangeAddress common.Address, callData []byte, timestamp []byte, signData []byte) (*types.Transaction, error) {\n\treturn _Vault.contract.Transact(opts, \"execute\", token, amount, recipientToken, exchangeAddress, callData, timestamp, signData)\n}", "func Execute(ctx context.Context, version string) {\n\tvar rootCmd = &cobra.Command{\n\t\tUse: \"act [event name to run]\",\n\t\tShort: \"Run Github actions locally by specifying the event name (e.g. `push`) or an action name directly.\",\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tRunE: newRunAction(ctx),\n\t\tVersion: version,\n\t\tSilenceUsage: true,\n\t}\n\trootCmd.Flags().BoolVarP(&list, \"list\", \"l\", false, \"list actions\")\n\trootCmd.Flags().StringVarP(&actionName, \"action\", \"a\", \"\", \"run action\")\n\trootCmd.Flags().StringVarP(&eventPath, \"event\", \"e\", \"\", \"path to event JSON file\")\n\trootCmd.PersistentFlags().BoolVarP(&dryrun, \"dryrun\", \"n\", false, \"dryrun mode\")\n\trootCmd.PersistentFlags().BoolVarP(&verbose, \"verbose\", \"v\", false, \"verbose output\")\n\trootCmd.PersistentFlags().StringVarP(&workflowPath, \"file\", \"f\", \"./.github/main.workflow\", \"path to workflow file\")\n\trootCmd.PersistentFlags().StringVarP(&workingDir, \"directory\", \"C\", \".\", \"working directory\")\n\tif err := rootCmd.Execute(); err != nil {\n\t\tos.Exit(1)\n\t}\n\n}", "func (e *EvaluatedFunctionExpression) Execute(ctx *Context, args *Values) Value {\n\tctx.SetParent(e.this) // this is how closure works\n\treturn e.fn.Execute(ctx, args)\n}", "func Execute(lambdaAWSInfos []*LambdaAWSInfo, port int, parentProcessPID int, logger *logrus.Logger) error {\n\tif port <= 0 {\n\t\tport = defaultHTTPPort\n\t}\n\tlogger.Info(\"Execute!\")\n\n\tlookupMap := make(dispatchMap, 0)\n\tfor _, eachLambdaInfo := range lambdaAWSInfos {\n\t\tlookupMap[eachLambdaInfo.lambdaFnName] = eachLambdaInfo\n\t}\n\tserver := &http.Server{\n\t\tAddr: fmt.Sprintf(\":%d\", port),\n\t\tHandler: &lambdaHandler{lookupMap, logger},\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t}\n\tif 0 != parentProcessPID {\n\t\tlogger.Debug(\"Sending SIGUSR2 to parent process: \", parentProcessPID)\n\t\tsyscall.Kill(parentProcessPID, syscall.SIGUSR2)\n\t}\n\tlogger.Debug(\"Binding to port: \", port)\n\terr := server.ListenAndServe()\n\tif err != nil {\n\t\tlogger.Error(\"FAILURE: \" + err.Error())\n\t\treturn err\n\t}\n\tlogger.Debug(\"Server available at: \", port)\n\treturn nil\n}", "func (c *Command) Execute(user string, msg string, args []string) {\n}", "func (_SimpleMultiSig *SimpleMultiSigTransactor) Execute(opts *bind.TransactOpts, bucketIdx uint16, expireTime *big.Int, sigV []uint8, sigR [][32]byte, sigS [][32]byte, destination common.Address, value *big.Int, data []byte, executor common.Address, gasLimit *big.Int) (*types.Transaction, error) {\n\treturn _SimpleMultiSig.contract.Transact(opts, \"execute\", bucketIdx, expireTime, sigV, sigR, sigS, destination, value, data, executor, gasLimit)\n}", "func (p *Plugin) Execute(config contracts.Configuration, cancelFlag task.CancelFlag, output iohandler.IOHandler) {\n\tp.execute(config, cancelFlag, output)\n\treturn\n}", "func (e *CustomExecutor) Execute(s api.DiscordSession, channel model.Snowflake, command *model.Command) {\n\tif command.Custom == nil {\n\t\tlog.Fatal(\"Incorrectly generated learn command\", errors.New(\"wat\"))\n\t}\n\n\thas, err := e.commandMap.Has(command.Custom.Call)\n\tif err != nil {\n\t\tlog.Fatal(\"Error testing custom feature\", err)\n\t}\n\tif !has {\n\t\tlog.Fatal(\"Accidentally found a mismatched call/response pair\", errors.New(\"call response mismatch\"))\n\t}\n\n\tresponse, err := e.commandMap.Get(command.Custom.Call)\n\tif err != nil {\n\t\tlog.Fatal(\"Error reading custom response\", err)\n\t}\n\n\t// Perform command substitutions.\n\tif strings.Contains(response, \"$1\") {\n\t\tif command.Custom.Args == \"\" {\n\t\t\tresponse = MsgCustomNeedsArgs\n\t\t} else {\n\t\t\tresponse = strings.Replace(response, \"$1\", command.Custom.Args, 4)\n\t\t}\n\t} else if matches := giphyRegexp.FindStringSubmatch(response); len(matches) > 2 {\n\t\turl := matches[2]\n\t\tresponse = fmt.Sprintf(MsgGiphyLink, url)\n\t}\n\n\ts.ChannelMessageSend(channel.Format(), response)\n}", "func (h *Handler) Execute(name string, args []string) {\n\tlog.Warn(\"generic doesn't support command execution\")\n}", "func (command SimpleCommandTestCommand) execute(notification interfaces.INotification) {\n\tvar vo = notification.Body().(*SimpleCommandTestVO)\n\n\t//Fabricate a result\n\tvo.Result = 2 * vo.Input\n}", "func (s *fnSignature) Execute(ctx context.Context) ([]reflect.Value, error) {\n\tglobalBackendStatsClient().TaskExecutionCount().Inc(1)\n\ttargetArgs := make([]reflect.Value, 0, len(s.Args)+1)\n\ttargetArgs = append(targetArgs, reflect.ValueOf(ctx))\n\tfor _, arg := range s.Args {\n\t\ttargetArgs = append(targetArgs, reflect.ValueOf(arg))\n\t}\n\tif fn, ok := fnLookup.getFn(s.FnName); ok {\n\t\tfnValue := reflect.ValueOf(fn)\n\t\treturn fnValue.Call(targetArgs), nil\n\t}\n\treturn nil, fmt.Errorf(\"function: %q not found. Did you forget to register?\", s.FnName)\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (vm *EVM) Execute(st acmstate.ReaderWriter, blockchain engine.Blockchain, eventSink exec.EventSink,\n\tparams engine.CallParams, code []byte) ([]byte, error) {\n\n\t// Make it appear as if natives are stored in state\n\tst = native.NewState(vm.options.Natives, st)\n\n\tstate := engine.State{\n\t\tCallFrame: engine.NewCallFrame(st).WithMaxCallStackDepth(vm.options.CallStackMaxDepth),\n\t\tBlockchain: blockchain,\n\t\tEventSink: eventSink,\n\t}\n\n\toutput, err := vm.Contract(code).Call(state, params)\n\tif err == nil {\n\t\t// Only sync back when there was no exception\n\t\terr = state.CallFrame.Sync()\n\t}\n\t// Always return output - we may have a reverted exception for which the return is meaningful\n\treturn output, err\n}", "func (pon *DmiTransceiverPlugIn) Execute(args []string) error {\n\tclient, conn := dmiEventGrpcClient()\n\tdefer conn.Close()\n\n\tctx, cancel := context.WithTimeout(context.Background(), config.GlobalConfig.Grpc.Timeout)\n\tdefer cancel()\n\n\treq := pb.TransceiverRequest{\n\t\tTransceiverId: uint32(pon.Args.TransceiverId),\n\t}\n\n\tres, err := client.PlugInTransceiver(ctx, &req)\n\tif err != nil {\n\t\tlog.Errorf(\"Cannot plug in PON transceiver: %v\", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(fmt.Sprintf(\"[Status: %d] %s\", res.StatusCode, res.Message))\n\treturn nil\n}", "func (c *cmdVoteInv) Execute(args []string) error {\n\t_, err := voteInv(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (lambda *Lambda) Execute(reconciliationMetaData *models.ReconciliationMetaData) error {\n\tif reconciliationMetaData.ReconciliationDate == \"\" {\n\n\t\treconciliationDateTime := time.Now()\n\t\treconciliationMetaData.ReconciliationDate = reconciliationDateTime.Format(dateFormat)\n\n\t\tstartTime := reconciliationDateTime.Truncate(24 * time.Hour)\n\t\treconciliationMetaData.StartTime = startTime\n\t\treconciliationMetaData.EndTime = startTime.Add(24 * time.Hour)\n\t} else {\n\n\t\tstartTime, err := time.Parse(dateFormat, reconciliationMetaData.ReconciliationDate)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\treconciliationMetaData.StartTime = startTime\n\t\treconciliationMetaData.EndTime = startTime.Add(24 * time.Hour)\n\t}\n\n\tlog.Info(\"LFP error reporting lambda executing. Getting penalties with e5 errors for date: \" + reconciliationMetaData.ReconciliationDate + \". Creating lfp CSV.\")\n\n\tlfpCSV, err := lambda.Service.GetLFPCSV(reconciliationMetaData)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\tlog.Info(\"LFP CSV constructed.\")\n\tlog.Trace(\"LFP CSV\", log.Data{\"lfp_csv\": lfpCSV})\n\n\terr = lambda.FileTransfer.UploadCSVFiles([]models.CSV{lfpCSV})\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\tlog.Info(\"CSV's successfully uploaded. Lambda execution finished.\")\n\n\treturn nil\n}", "func (ft *CustomTask) Exec(t *f.TaskNode, p *f.Params, out *io.PipeWriter) {\n\tglog.Info(\"executing custom task \", p.Complete)\n\n\tft.customFunc(t, p, out)\n\n\treturn\n}", "func (_Vault *VaultTransactorSession) Execute(token common.Address, amount *big.Int, recipientToken common.Address, exchangeAddress common.Address, callData []byte, timestamp []byte, signData []byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.Execute(&_Vault.TransactOpts, token, amount, recipientToken, exchangeAddress, callData, timestamp, signData)\n}", "func (c *Command) Execute(ctx context.Context) error {\n\n\tpctx := &commandContext{\n\t\tdependencyResolver: pipeline.NewDependencyRecorder[*commandContext](),\n\t\tContext: ctx,\n\t}\n\n\tp := pipeline.NewPipeline[*commandContext]().WithBeforeHooks(pipe.DebugLogger[*commandContext](c.Log), pctx.dependencyResolver.Record)\n\tp.WithSteps(\n\t\tp.NewStep(\"create client\", c.createClient),\n\t\tp.NewStep(\"fetch task\", c.fetchTask),\n\t\tp.NewStep(\"list intermediary files\", c.listIntermediaryFiles),\n\t\tp.NewStep(\"delete intermediary files\", c.deleteFiles),\n\t\tp.NewStep(\"delete source file\", c.deleteSourceFile),\n\t)\n\n\treturn p.RunWithContext(pctx)\n}", "func (c *CLI) Execute() {\n\tc.LoadCredentials()\n\twr := &workflow.WorkflowResult{}\n\texecHandler := workflow.GetExecutorHandler()\n\texec, err := execHandler.Add(c.Workflow, wr.Callback)\n\tc.exitOnError(err)\n\texec.SetLogListener(c.logListener)\n\tstart := time.Now()\n\texec, err = execHandler.Execute(c.Workflow.WorkflowID)\n\tc.exitOnError(err)\n\tchecks := 0\n\toperation := \"\"\n\tif c.Params.InstallRequest != nil {\n\t\tif c.Params.AppCluster {\n\t\t\toperation = \"Installing application cluster\"\n\t\t} else {\n\t\t\toperation = \"Installing management cluster\"\n\t\t}\n\t} else if c.Params.UninstallRequest != nil {\n\t\tif c.Params.AppCluster {\n\t\t\toperation = \"Uninstalling application cluster\"\n\t\t} else {\n\t\t\toperation = \"Uninstalling management cluster\"\n\t\t}\n\t}\n\tfor !wr.Called {\n\t\ttime.Sleep(time.Second * 15)\n\t\tif checks%4 == 0 {\n\t\t\tfmt.Println(operation, string(exec.State), \"-\", time.Since(start).String())\n\t\t}\n\t\tchecks++\n\t}\n\telapsed := time.Since(start)\n\tfmt.Println(\"Operation took \", elapsed)\n\tif wr.Error != nil {\n\t\tfmt.Println(\"Operation failed due to \", wr.Error.Error())\n\t\tlog.Fatal().Str(\"error\", wr.Error.DebugReport()).Msg(fmt.Sprintf(\"%s failed\", operation))\n\t}\n}", "func (p *ContextPlugin) Execute(event *types.Event) *types.Event {\n\tif event.Time == 0 {\n\t\tevent.Time = time.Now().UnixMilli()\n\t}\n\n\tif event.InsertID == \"\" {\n\t\tevent.InsertID = uuid.NewString()\n\t}\n\n\tevent.Library = p.contextString\n\n\treturn event\n}", "func (e *EventEmitter) execute(listener *Listener, event *Event) {\n\tdefer e.gracefulWait.Done()\n\n\tfor _, filterFunc := range e.filterFuncs {\n\t\tif !filterFunc(event) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar (\n\t\tdata Data\n\t\texecutionTags []string\n\t)\n\n\tif e.mapFunc != nil {\n\t\tdata = e.mapFunc(event)\n\t} else if err := event.Data(&data); err != nil {\n\t\te.app.log.Println(errDecodingEventData{err})\n\t\treturn\n\t}\n\n\tif e.executionTagsFunc != nil {\n\t\texecutionTags = e.executionTagsFunc(event)\n\t}\n\n\tif _, err := e.app.execute(e.taskServiceID, e.taskKey, data, executionTags); err != nil {\n\t\te.app.log.Println(executionError{e.taskKey, err})\n\t}\n}", "func (l *Labeler) Execute() error {\n\terr := l.checkPreconditions()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"executing with owner=%s repo=%s event=%s\", *l.Owner, *l.Repo, *l.Event)\n\n\tc, err := l.retrieveConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.config = c\n\n\tswitch *l.Event {\n\tcase issue:\n\t\terr = l.processIssue()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase pullRequestTarget, pullRequest:\n\t\terr = l.processPullRequest()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Execute(ctx context.Context) error {\n\treturn rootCmd.ExecuteContext(ctx)\n}", "func Execute(ctx context.Context, command Command, aggregate Aggregate, metadata Metadata) (Event, error) {\n\ttx := DB.Begin()\n\n\tevent, err := ExecuteTx(ctx, tx, command, aggregate, metadata)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn Event{}, err\n\t}\n\n\tif err = tx.Commit().Error; err != nil {\n\t\ttx.Rollback()\n\t\treturn Event{}, err\n\t}\n\n\treturn event, nil\n}", "func (_ERC725 *ERC725Transactor) Execute(opts *bind.TransactOpts, _data []byte) (*types.Transaction, error) {\n\treturn _ERC725.contract.Transact(opts, \"execute\", _data)\n}", "func (cmd *command) Execute(ch io.ReadWriter) (err error) {\n\tif cmd.Flags.Source {\n\t\terr = cmd.serveSource(ch)\n\t} else {\n\t\terr = cmd.serveSink(ch)\n\t}\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\treturn nil\n}", "func (pon *DmiTransceiverPlugOut) Execute(args []string) error {\n\tclient, conn := dmiEventGrpcClient()\n\tdefer conn.Close()\n\n\tctx, cancel := context.WithTimeout(context.Background(), config.GlobalConfig.Grpc.Timeout)\n\tdefer cancel()\n\n\treq := pb.TransceiverRequest{\n\t\tTransceiverId: uint32(pon.Args.TransceiverId),\n\t}\n\n\tres, err := client.PlugOutTransceiver(ctx, &req)\n\tif err != nil {\n\t\tlog.Errorf(\"Cannot plug out PON transceiver: %v\", err)\n\t\treturn err\n\t}\n\n\tfmt.Println(fmt.Sprintf(\"[Status: %d] %s\", res.StatusCode, res.Message))\n\treturn nil\n}", "func executeAction(fn command) cli.ActionFunc {\n\tusername := os.Getenv(\"VOIPMS_USERNAME\")\n\tpassword := os.Getenv(\"VOIPMS_PASSWORD\")\n\tclient := api.NewClient(username, password)\n\treturn func(c *cli.Context) error {\n\t\treturn fn(client, c)\n\t}\n}", "func Execute() {\n\tinitHelp()\n\tcontext := InitializeContext()\n\n\tprintLogoWithVersion(os.Stdout)\n\n\tif context.config.trustAll {\n\t\tif !context.config.quiet {\n\t\t\tfmt.Println(\"WARNING: Configured to trust all - means unnown service certificate is accepted. Don't use this in production!\")\n\t\t}\n\t}\n\taction := context.config.action\n\tif action == ActionExecuteSynchron {\n\t\tcommonWayToApprove(context)\n\t\twaitForSecHubJobDoneAndFailOnTrafficLight(context)\n\t\tos.Exit(ExitCodeOK)\n\n\t} else if action == ActionExecuteAsynchron {\n\t\tcommonWayToApprove(context)\n\t\tfmt.Println(context.config.secHubJobUUID)\n\t\tos.Exit(ExitCodeOK)\n\t} else if action == ActionExecuteGetStatus {\n\t\tstate := getSecHubJobState(context, true, false, false)\n\t\tfmt.Println(state)\n\t\tos.Exit(ExitCodeOK)\n\n\t} else if action == ActionExecuteGetReport {\n\t\treport := getSecHubJobReport(context)\n\t\tfmt.Println(report)\n\t\tos.Exit(ExitCodeOK)\n\t}\n\tfmt.Printf(\"Unknown action '%s'\", context.config.action)\n\tos.Exit(ExitCodeIllegalAction)\n}", "func Execute() error {\n\treturn cmd.Execute()\n}", "func (_Trebuchet *TrebuchetTransactor) Execute(opts *bind.TransactOpts, _data [][]byte) (*types.Transaction, error) {\n\treturn _Trebuchet.contract.Transact(opts, \"execute\", _data)\n}", "func (scs *SubCommandStruct) Execute(ctx context.Context, in io.Reader, out, outErr io.Writer) error {\n\tif scs.ExecuteValue != nil {\n\t\treturn scs.ExecuteValue(ctx, in, out, outErr)\n\t}\n\treturn nil\n}", "func (e *ldapExecutor) Execute(ctx context.Context, config *ldapconf.Config) error {\n\treturn nil\n}", "func (f *FunctionExpression) Execute(ctx *Context, args *Values) Value {\n\tf.params.BindArguments(ctx, args.values...)\n\tf.body.Execute(ctx)\n\tif ctx.hasret {\n\t\treturn ctx.retval\n\t}\n\treturn ValueFromNil()\n}", "func Execute(ctx context.OrionContext, action *Base, fn ExecuteFn) errors.Error {\n\t// ctx.StartAction()\n\tevalCtx := ctx.EvalContext()\n\twhen, err := helper.GetExpressionValueAsBool(evalCtx, action.when, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !when {\n\t\treturn nil\n\t}\n\tif action.count != nil && !action.count.Range().Empty() {\n\t\treturn doCount(ctx, action, fn)\n\t}\n\tif action.while != nil && !action.while.Range().Empty() {\n\t\treturn doWhile(ctx, action, fn)\n\t}\n\treturn fn(ctx)\n}", "func (ctrl *PGCtrl) Execute(q string) error {\n\t_, err := ctrl.conn.Exec(q)\n\treturn err\n}", "func (_Vault *VaultSession) Execute(token common.Address, amount *big.Int, recipientToken common.Address, exchangeAddress common.Address, callData []byte, timestamp []byte, signData []byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.Execute(&_Vault.TransactOpts, token, amount, recipientToken, exchangeAddress, callData, timestamp, signData)\n}", "func (_m *WorkerHandlerOptionFunc) Execute(_a0 *types.WorkerHandler) {\n\t_m.Called(_a0)\n}", "func (r Describe) Execute(name string, out io.Writer, args []string) error {\n\twrap := types.Executor{Name: name, Command: r}\n\tctx := context.WithValue(context.Background(), global.RefRoot, wrap)\n\tcmd := r.NewCommand(ctx, name)\n\tcmd.SetOut(out)\n\tcmd.SetArgs(args)\n\tif err := cmd.Execute(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *PrintCommand) Execute(_ engine.Handler) {\n\tfmt.Println(p.Arg)\n}", "func (tx *Hello) Execute(p types.Process, ctw *types.ContextWrapper, index uint16) error {\n\tsp := p.(*HelloWorld)\n\n\treturn sp.vault.WithFee(p, ctw, tx, func() error {\n\t\tif err := sp.AddHelloCount(ctw, tx.To); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (player *Player) ExecAs(commandLine string, callback func(statusCode int)) {\n\tplayer.Exec(fmt.Sprintf(\"execute %v ~ ~ ~ %v\", player.name, commandLine), func(response map[string]interface{}) {\n\t\tcodeInterface, exists := response[\"statusCode\"]\n\t\tif !exists {\n\t\t\tlog.Printf(\"exec as: invalid response JSON\")\n\t\t\treturn\n\t\t}\n\t\tcode, _ := codeInterface.(int)\n\t\tif callback != nil {\n\t\t\tcallback(code)\n\t\t}\n\t})\n}", "func (e *Execution) Execute(ctx context.Context) error {\n\n\tvar err error\n\tswitch strings.ToLower(e.Operation.Name) {\n\tcase installOperation, \"standard.create\":\n\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\"Creating Job %q\", e.NodeName)\n\t\terr = e.createJob(ctx)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\t\"Failed to create Job %q, error %s\", e.NodeName, err.Error())\n\n\t\t}\n\tcase uninstallOperation, \"standard.delete\":\n\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\"Deleting Job %q\", e.NodeName)\n\t\terr = e.deleteJob(ctx)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\t\"Failed to delete Job %q, error %s\", e.NodeName, err.Error())\n\n\t\t}\n\tcase enableFileTransferOperation:\n\t\terr = e.enableFileTransfer(ctx)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\t\"Failed to enable file transfer for Job %q, error %s\", e.NodeName, err.Error())\n\n\t\t}\n\tcase disableFileTransferOperation:\n\t\terr = e.disableFileTransfer(ctx)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\t\"Failed to disable file transfer for Job %q, error %s\", e.NodeName, err.Error())\n\n\t\t}\n\tcase listChangedFilesOperation:\n\t\terr = e.listChangedFiles(ctx)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\t\"Failed to list changed files for Job %q, error %s\", e.NodeName, err.Error())\n\n\t\t}\n\tcase tosca.RunnableSubmitOperationName:\n\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\"Submitting Job %q\", e.NodeName)\n\t\terr = e.submitJob(ctx)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\t\"Failed to submit Job %q, error %s\", e.NodeName, err.Error())\n\n\t\t}\n\tcase tosca.RunnableCancelOperationName:\n\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\"Canceling Job %q\", e.NodeName)\n\t\terr = e.cancelJob(ctx)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(\n\t\t\t\t\"Failed to cancel Job %q, error %s\", e.NodeName, err.Error())\n\n\t\t}\n\tdefault:\n\t\terr = errors.Errorf(\"Unsupported operation %q\", e.Operation.Name)\n\t}\n\n\treturn err\n}", "func OnExecute(c *grumble.Context) error {\n\tplanID := c.Flags.Int(\"plan\")\n\tif len(config.AppConfig.Plans) < planID {\n\t\tfmt.Println(\"No plan with ID\", planID, \"exists. Use the command \\\"list\\\" to get a list of available plans.\")\n\t\treturn nil\n\t}\n\tplan := config.AppConfig.Plans[planID-1]\n\n\tfor _, task := range plan.Tasks {\n\t\tresult := task.Execute()\n\n\t\tif result.IsSuccessful {\n\n\t\t\tfmt.Println(result.Message)\n\t\t} else {\n\t\t\tfmt.Println(\"Error:\", result.Message)\n\t\t}\n\t}\n\n\treturn nil\n}", "func Execute(contID container.ContainerID, r *scheduledRequest) error {\n\t//log.Printf(\"[%s] Executing on container: %v\", r, contID)\n\n\tvar req executor.InvocationRequest\n\tif r.Fun.Runtime == container.CUSTOM_RUNTIME {\n\t\treq = executor.InvocationRequest{\n\t\t\tParams: r.Params,\n\t\t}\n\t} else {\n\t\tcmd := container.RuntimeToInfo[r.Fun.Runtime].InvocationCmd\n\t\treq = executor.InvocationRequest{\n\t\t\tcmd,\n\t\t\tr.Params,\n\t\t\tr.Fun.Handler,\n\t\t\tHANDLER_DIR,\n\t\t}\n\t}\n\n\tt0 := time.Now()\n\n\tresponse, invocationWait, err := container.Execute(contID, &req)\n\tif err != nil {\n\t\t// notify scheduler\n\t\tcompletions <- &completion{scheduledRequest: r, contID: contID}\n\t\treturn fmt.Errorf(\"[%s] Execution failed: %v\", r, err)\n\t}\n\n\tif !response.Success {\n\t\t// notify scheduler\n\t\tcompletions <- &completion{scheduledRequest: r, contID: contID}\n\t\treturn fmt.Errorf(\"Function execution failed\")\n\t}\n\n\tr.ExecReport.Result = response.Result\n\tr.ExecReport.Duration = time.Now().Sub(t0).Seconds() - invocationWait.Seconds()\n\tr.ExecReport.ResponseTime = time.Now().Sub(r.Arrival).Seconds()\n\n\t// initializing containers may require invocation retries, adding\n\t// latency\n\tr.ExecReport.InitTime += invocationWait.Seconds()\n\n\t// notify scheduler\n\tcompletions <- &completion{scheduledRequest: r, contID: contID}\n\n\treturn nil\n}", "func Execute() {\n\tAddCommands()\n\tIpvanishCmd.Execute()\n\t//\tutils.StopOnErr(IpvanishCmd.Execute())\n}", "func (self *Controller) ExecuteCommand(notification interfaces.INotification) {\n\tself.commandMapMutex.RLock()\n\tdefer self.commandMapMutex.RUnlock()\n\n\tvar commandFunc = self.commandMap[notification.Name()]\n\tif commandFunc == nil {\n\t\treturn\n\t}\n\tcommandInstance := commandFunc()\n\tcommandInstance.InitializeNotifier(self.Key)\n\tcommandInstance.Execute(notification)\n}", "func (i service) Execute(ctx context.Context, to common.Address, contractAbi, methodName string, args ...interface{}) error {\n\tabi, err := abi.JSON(strings.NewReader(contractAbi))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Pack encodes the parameters and additionally checks if the method and arguments are defined correctly\n\tdata, err := abi.Pack(methodName, args...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn i.RawExecute(ctx, to, data)\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, args := stub.GetFunctionAndParameters()\n\tif function == \"makeStatement\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"Incorrect number of arguments: \" + string(len(args)))\n\t\t}\n\t\tstatement := args[0]\n\t\tts, _ := stub.GetTxTimestamp()\n\t\ttxtime := time.Unix(ts.Seconds, int64(ts.Nanos))\n\t\tevent := Event{\n\t\t\tStatement: statement,\n\t\t\tEventTime: txtime,\n\t\t\tTxID: stub.GetTxID(),\n\t\t}\n\t\tevtJson, _ := json.Marshal(event)\n\t\tstub.PutState(stub.GetTxID(), evtJson)\n\t\treturn shim.Success(evtJson)\n\t}\n\tlogger.Errorf(\"invoke did not find func: %s\", function)\n\treturn shim.Error(\"Received unknown function invocation\")\n}", "func Execute() {\n\tmainCmd.Execute()\n}", "func (f Function) Execute(i Instruction, e Environment, dryRun bool) error {\n\tif err := f.Check(i); err != nil {\n\t\treturn err\n\t}\n\treturn f.Func(i, e, dryRun)\n}", "func Execute(context *cli.Context) error {\n\tmanager, err := createManager(context)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmanager.WithTimeout(context.Int(\"timeout\"))\n\n\tfilename := context.Args().First()\n\tif filename == \"\" {\n\t\treturn cli.NewExitError(\"filename argument is required\", 1)\n\t}\n\n\tname := context.String(\"name\")\n\tif name == \"\" {\n\t\tname = strings.TrimSuffix(path.Base(filename), filepath.Ext(filename))\n\t}\n\n\tscript, err := manager.CreateFromFile(name, filename)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create script %s from %s\", name, filename)\n\t}\n\n\tvar result string\n\tfilePayload := context.String(\"file-payload\")\n\tpayload := context.String(\"payload\")\n\n\tif filePayload != \"\" && payload != \"\" {\n\t\treturn cli.NewExitError(\"only one of the parameters can be used: payload or file-payload\", 2)\n\t}\n\n\tif filePayload != \"\" {\n\t\tresult, err = script.ExecuteWithFilePayload(filePayload)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"execution of script %s with filePayload %s failed\", filename, filePayload)\n\t\t}\n\t} else if payload != \"\" {\n\t\tresult, err = script.ExecuteWithStringPayload(payload)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"execution of script %s failed\", filename)\n\t\t}\n\t} else {\n\t\tresult, err = script.ExecuteWithoutPayload()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"execution of script %s failed\", filename)\n\t\t}\n\t}\n\n\tfmt.Println(result)\n\n\treturn nil\n}", "func (mo *MenuOption) ExecuteCommand(ev chan UIEvent) {\n\tev <- mo.Command()\n}", "func Execute() {\n\tif err := RootCommand.Execute(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"aws-helper error: %s\\n\", err)\n\t\tRootCommand.Usage()\n\t\tos.Exit(1)\n\t}\n}", "func Execute(\n\tctx context.Context,\n\tpayload gapir.Payload,\n\thandlePost builder.PostDataHandler,\n\thandleNotification builder.NotificationHandler,\n\tconnection *gapir.Connection,\n\tmemoryLayout *device.MemoryLayout,\n\tos *device.OS) error {\n\n\tctx = status.Start(ctx, \"Execute\")\n\tdefer status.Finish(ctx)\n\n\t// The memoryLayout is specific to the ABI of the requested capture,\n\t// while the OS is not. Thus a device.Configuration is not applicable here.\n\treturn executor{\n\t\tpayload: payload,\n\t\thandlePost: handlePost,\n\t\thandleNotification: handleNotification,\n\t\tmemoryLayout: memoryLayout,\n\t\tOS: os,\n\t}.execute(ctx, connection)\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (execution *Execution) Execute() (err error) {\n\terr = execution.moveFromPendingToInProgress()\n\tif err != nil {\n\t\treturn\n\t}\n\texecution.ExecutedAt = time.Now()\n\tlog.Println(\"[PROCESSING]\", execution.Task)\n\n\tchannel := execution.Service.TaskSubscriptionChannel()\n\n\tgo pubsub.Publish(channel, execution)\n\treturn\n}", "func (_Transactable *TransactableTransactor) Execute(opts *bind.TransactOpts, _guarantor common.Address, _v uint8, _r [32]byte, _s [32]byte, _dest common.Address, _value *big.Int, _ts *big.Int) (*types.Transaction, error) {\n\treturn _Transactable.contract.Transact(opts, \"execute\", _guarantor, _v, _r, _s, _dest, _value, _ts)\n}", "func (e *executor) Execute() error {\n\tif len(e.executables) < 1 {\n\t\treturn errors.New(\"nothing to Work\")\n\t}\n\n\tlog(e.id).Infof(\"processing %d item(s)\", len(e.executables))\n\treturn nil\n}", "func (t *PulsarTrigger) Execute(ctx context.Context, events map[string]*v1alpha1.Event, resource interface{}) (interface{}, error) {\n\ttrigger, ok := resource.(*v1alpha1.PulsarTrigger)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to interpret the trigger resource\")\n\t}\n\n\tif trigger.Payload == nil {\n\t\treturn nil, fmt.Errorf(\"payload parameters are not specified\")\n\t}\n\n\tpayload, err := triggers.ConstructPayload(events, trigger.Payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = t.Producer.Send(ctx, &pulsar.ProducerMessage{\n\t\tPayload: payload,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to send message to pulsar, %w\", err)\n\t}\n\n\tt.Logger.Infow(\"successfully produced a message\", zap.Any(\"topic\", trigger.Topic))\n\n\treturn nil, nil\n}", "func (_SimpleMultiSig *SimpleMultiSigTransactorSession) Execute(bucketIdx uint16, expireTime *big.Int, sigV []uint8, sigR [][32]byte, sigS [][32]byte, destination common.Address, value *big.Int, data []byte, executor common.Address, gasLimit *big.Int) (*types.Transaction, error) {\n\treturn _SimpleMultiSig.Contract.Execute(&_SimpleMultiSig.TransactOpts, bucketIdx, expireTime, sigV, sigR, sigS, destination, value, data, executor, gasLimit)\n}", "func (app *App) Execute(input io.Reader, output io.Writer) error {\n\tdecoder := yaml.NewDecoder(input)\n\tvar data map[string]interface{}\n\tif err := decoder.Decode(&data); err != nil {\n\t\treturn errors.Wrap(err, \"yaml decode\")\n\t}\n\treturn errors.Wrap(app.t.Execute(output, data), \"transform execute\")\n}", "func (tasks *TaskFile) Execute(cmd, name, dir string) (out string, err error) {\n\tcommand, err := templates.Expand(cmd, tasks.TemplateVars.Functions)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif tasks.Options.LogLevel {\n\t\tlogger.Info(name, command)\n\t}\n\n\treturn templates.Run(templates.CommandOptions{\n\t\tCmd: command,\n\t\tDir: dir,\n\t\tUseStdOut: true,\n\t})\n}", "func (_SimpleMultiSig *SimpleMultiSigFilterer) FilterExecute(opts *bind.FilterOpts) (*SimpleMultiSigExecuteIterator, error) {\n\n\tlogs, sub, err := _SimpleMultiSig.contract.FilterLogs(opts, \"Execute\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SimpleMultiSigExecuteIterator{contract: _SimpleMultiSig.contract, event: \"Execute\", logs: logs, sub: sub}, nil\n}", "func (p *powerEventWatcher) Execute() error {\n\t<-p.interrupt\n\treturn nil\n}", "func Execute() {\n\tzk.Execute()\n}", "func (c *cmdProposalInv) Execute(args []string) error {\n\t_, err := proposalInv(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Execute() {\n\t// rootCmd.GenZshCompletionFile(\"./_clk\")\n\tcobra.CheckErr(rootCmd.Execute())\n}", "func Execute(args []string) (err error) {\n\treturn Cmd.Execute(args)\n}", "func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"invoke is running \" + function)\n\n\t// Handle different functions\n\tif function == \"init\" {\t\t\t\t\t\t\t\t\t\t\t\t\t//initialize the chaincode state, used as reset\n\t\treturn t.Init(stub, \"init\", args)\n\t}else if function == \"create_event\" {\n return t.create_event(stub, args)\n\t}else if function == \"ping\" {\n return t.ping(stub)\n }\n\t\n\treturn nil, errors.New(\"Received unknown function invocation: \" + function)\n}", "func Run(evt event.Event) error {\n\tenvs := env.GetEnvs()\n\tif len(evt.LogLevel) == 0 {\n\t\tevt.LogLevel = constants.DefaultWorkerLogLevel\n\t}\n\n\tif len(envs.Region) == 0 {\n\t\treturn fmt.Errorf(\"region is not specified. please check environment variables\")\n\t}\n\tlogrus.Infof(\"this is lambda function in %s\", envs.Region)\n\n\tswitch envs.Mode {\n\tcase constants.ManagerMode:\n\t\treturn workermanager.New().Run(envs)\n\tcase constants.WorkerMode:\n\t\treturn worker.NewWorker().Run(envs, evt)\n\t}\n\n\treturn nil\n}", "func (c *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\tfun, args := stub.GetFunctionAndParameters()\n\n\tfmt.Println(\"Executing => \"+fun)\n\n\tswitch fun{\n\tcase \"AddCpu\":\n\t\treturn c.AddCpu(stub,args)\n\tcase \"GetUsage\":\n\t\treturn c.GetUsage(stub,args)\n\tdefault:\n\t\treturn shim.Error(\"Not a vaild function\")\t\n\t}\n}", "func (r *Repository) Execute(command string, args ...interface{}) (middleware.Result, error) {\n\tconn, err := r.Database.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr = conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"alert DASRepo.Execute(): close database connection failed.\\n%s\", err.Error())\n\t\t}\n\t}()\n\n\treturn conn.Execute(command, args...)\n}", "func (c *ConsoleOutput) Execute() {\n\tfmt.Println(c.message)\n}", "func (t *TaskChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, args := stub.GetFunctionAndParameters()\n\tfmt.Println(\"invoke is running \" + function)\n\n\tif function == \"regist\" {\n\t\treturn t.regist(stub, args)\n\t} else if function == \"pay\" {\n\t\treturn t.pay(stub, args)\n\t} else if function == \"pendingPay\" {\n\t\treturn t.pendingPay(stub, args)\n } else if function == \"confirmPay\" {\n\t\treturn t.confirmPay(stub, args)\n } else if function == \"getBalance\" {\n\t\treturn t.getBalance(stub, args)\n\t} else if function == \"queryPayTxByTaskId\" {\n\t\treturn t.queryPayTxByTaskId(stub, args)\n\t} else if function == \"queryPayTxByPayer\" {\n\t\treturn t.queryPayTxByPayer(stub, args)\n\t} else if function == \"queryPayTxByPayee\" {\n\t\treturn t.queryPayTxByPayee(stub, args)\n\t} else if function == \"queryMembers\" {\n\t\treturn t.queryMembers(stub)\n\t} else {\n\t\treturn shim.Error(\"Function \" + function + \" doesn't exits, make sure function is right!\")\n\t}\n}", "func Execute(cfn ConfigFunc) error {\n\trootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) {\n\t\tcfn(rootCmd.PersistentFlags())\n\t}\n\n\treturn rootCmd.Execute()\n}", "func (t TaskFunc) Execute() { t() }", "func (_SimpleMultiSig *SimpleMultiSigFilterer) WatchExecute(opts *bind.WatchOpts, sink chan<- *SimpleMultiSigExecute) (event.Subscription, error) {\n\n\tlogs, sub, err := _SimpleMultiSig.contract.WatchLogs(opts, \"Execute\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(SimpleMultiSigExecute)\n\t\t\t\tif err := _SimpleMultiSig.contract.UnpackLog(event, \"Execute\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (e *ExecutableInvoker) Invoke(ctx context.Context, m *Manifest, cfg *InvokerConfig) error {\n\texecPath := path.Join(e.PluginDir, path.Join(m.Command...), m.Exec)\n\tcmd := execCommandContext(ctx, execPath, cfg.Args...)\n\tcmd.Env = append(cmd.Env, cfg.Env...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\treturn cmd.Run()\n}", "func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tswitch function {\n\n\tcase \"execute\":\n\n\t\tif len(args) < 1 {\n\t\t\treturn nil, errors.New(\"execute operation must include single argument, the base64 encoded form of a bitcoin transaction\")\n\t\t}\n\t\ttxDataBase64 := args[0]\n\t\ttxData, err := base64.StdEncoding.DecodeString(txDataBase64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error decoding TX as base64: %s\", err)\n\t\t}\n\n\t\tutxo := util.MakeUTXO(MakeChaincodeStore(stub))\n\t\texecResult, err := utxo.Execute(txData)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error executing TX: %s\", err)\n\t\t}\n\n\t\tfmt.Printf(\"\\nExecResult: Coinbase: %t, SumInputs %d, SumOutputs %d\\n\\n\", execResult.IsCoinbase, execResult.SumPriorOutputs, execResult.SumCurrentOutputs)\n\n\t\tif execResult.IsCoinbase == false {\n\t\t\tif execResult.SumCurrentOutputs > execResult.SumPriorOutputs {\n\t\t\t\treturn nil, fmt.Errorf(\"sumOfCurrentOutputs > sumOfPriorOutputs: sumOfCurrentOutputs = %d, sumOfPriorOutputs = %d\", execResult.SumCurrentOutputs, execResult.SumPriorOutputs)\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\n\tdefault:\n\t\treturn nil, errors.New(\"Unsupported operation\")\n\t}\n\n}", "func (t *AssetManagementChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\n if function == \"create\" {\n // create asset\n return t.create(stub, args)\n } else if function == \"update\" {\n // update asset (transfer ownership etc)\n return t.update(stub, args)\n }\n\n return nil, errors.New(\"Received unknown function invocation\")\n}", "func (machine *Dishwasher) RunCustomCommand(custom string) {\r\n machine.Append(func() (string, error) {\r\n var output string = \"\"\r\n var oops error = nil\r\n\r\n custom = strings.TrimSpace(custom)\r\n if custom[len(custom)-1] == '$' {\r\n go RunCommand(custom)\r\n } else {\r\n output, oops = RunCommand(custom)\r\n machine.SideEffect(output, oops)\r\n }\r\n\r\n return output, oops\r\n })\r\n}", "func (t *SimpleChaincode) Run(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n fmt.Printf(\" ############ KIRK ############# chaincode run\") \n fmt.Println(\"run is running \" + function)\n\n // Handle different functions\n if function == \"init\" { //initialize the chaincode state, used as reset\n return t.init(stub, args)\n } else if function == \"delete\" { //deletes an entity from its state\n return t.Delete(stub, args)\n } else if function == \"write\" { //writes a value to the chaincode state\n return t.Write(stub, args)\n } else if function == \"init_term\" { //create a new search term\n return t.init_term(stub, args)\n } else if function == \"set_user\" { //change owner of a search term\n return t.set_user(stub, args)\n }\n fmt.Println(\"run did not find func: \" + function) //error\n\n return nil, errors.New(\"Received unknown function invocation\")\n}", "func (m *MockFinder) Execute(ctx context.Context, config *config.Config, query string, from int64, until int64, stat *FinderStat) (err error) {\n\tm.query = query\n\treturn\n}", "func Execute(config ManagerConfig) error {\n\treturn execute(config)\n}", "func (e *EventEmitter) Execute(serviceID, taskKey string) (*Listener, error) {\n\te.taskServiceID = serviceID\n\te.taskKey = taskKey\n\tlistener := newListener(e.app, e.gracefulWait)\n\tif err := e.app.startServices(e.eventServiceID, serviceID); err != nil {\n\t\treturn nil, err\n\t}\n\tcancel, err := e.listen(listener)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlistener.cancel = cancel\n\te.app.addListener(listener)\n\treturn listener, nil\n}", "func (n *scalarNode) Execute(ctx context.Context) error {\n\tbounds := n.timespec.Bounds()\n\n\tblock := block.NewScalar(n.op.val, bounds)\n\tif n.debug {\n\t\t// Ignore any errors\n\t\titer, _ := block.StepIter()\n\t\tif iter != nil {\n\t\t\tlogging.WithContext(ctx).Info(\"scalar node\", zap.Any(\"meta\", iter.Meta()))\n\t\t}\n\t}\n\n\tif err := n.controller.Process(block); err != nil {\n\t\tblock.Close()\n\t\t// Fail on first error\n\t\treturn err\n\t}\n\n\tblock.Close()\n\treturn nil\n}", "func (t *evidence_management) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, args := stub.GetFunctionAndParameters()\n\tfmt.Println(\"function is ==> :\" + function)\n\taction := args[0]\n\tfmt.Println(\" action is ==> :\" + action)\n\tfmt.Println(args)\n\n\tif action == \"queryAsset\" {\n\t\treturn t.queryAsset(stub, args)\n\t} else if action == \"queryAllAsset\" {\n\t\treturn t.queryAllAsset(stub, args)\n\t} else if action == \"getHistoryForRecord\" {\n\t\treturn t.getHistoryForRecord(stub, args)\n\t} else if action == \"createCase\" {\n\t\treturn t.createCase(stub, args)\n\t} else if action == \"updateCase\" {\n\t\treturn t.updateCase(stub, args)\n\t} else if action == \"updateCaseStatus\" {\n\t\treturn t.updateCaseStatus(stub, args)\n\t} else if action == \"createFIR\" {\n\t\treturn t.createFIR(stub, args)\n\t} else if action == \"createDoc\" {\n\t\treturn t.createDoc(stub, args)\n\t} else if action == \"putPrivateData\" {\n\t\treturn t.putPrivateData(stub, args)\n\t} else if action == \"getPrivateData\" {\n\t\treturn t.getPrivateData(stub, args)\n\t} else if action == \"addAccused\" {\n\t\treturn t.addAccused(stub, args)\n\t} else if action == \"addSuspect\" {\n\t\treturn t.addSuspect(stub, args)\n\t} else if action == \"addVictim\" {\n\t\treturn t.addVictim(stub, args)\n\t}\n\n\tfmt.Println(\"invoke did not find func: \" + action) //error\n\n\treturn shim.Error(\"Received unknown function\")\n}", "func (_SimpleMultiSig *SimpleMultiSigSession) Execute(bucketIdx uint16, expireTime *big.Int, sigV []uint8, sigR [][32]byte, sigS [][32]byte, destination common.Address, value *big.Int, data []byte, executor common.Address, gasLimit *big.Int) (*types.Transaction, error) {\n\treturn _SimpleMultiSig.Contract.Execute(&_SimpleMultiSig.TransactOpts, bucketIdx, expireTime, sigV, sigR, sigS, destination, value, data, executor, gasLimit)\n}", "func Execute(runnable RunnableFn) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}()\n\n\tif runnable != nil {\n\t\trunnable()\n\t}\n}", "func (sb *ServerChangeBean) Execute(stringArgs []string, env *map[string]interface{}) error{\n\tif len(stringArgs) != 7 {\n\t\treturn fmt.Errorf(\"arguement error\")\n\t}\n\titerId, _ := strconv.Atoi(stringArgs[4])\n\tst, _ := strconv.Atoi(stringArgs[5])\n\tserverType := db.ServerType(st)\n\treturn sb.change(stringArgs[0], stringArgs[1], stringArgs[2], stringArgs[3], int64(iterId), serverType, env)\n}", "func (cli *OpsGenieAlertV2Client) ExecuteCustomAction(req alertsv2.ExecuteCustomActionRequest) (*AsyncRequestResponse, error) {\n\treturn cli.sendAsyncPostRequest(&req)\n}", "func Execute() {\n\tctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)\n\tdefer cancel()\n\n\tcobra.OnInitialize(initLogging, initConfig, initSSHFromConfig)\n\n\tif err := rootCommand().ExecuteContext(ctx); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"run is running \" + function)\n\n\t// Handle different functions\n\t// if function == \"init\" { //initialize the chaincode state\n\t// \treturn t.Init(stub, args)\n\t// } else\n\tif function == \"submitTransaction\" { //create a transaction\n\t\treturn t.submitTransaction(stub, args)\n\t} else if function == \"createFinancialInstitution\" { //create a new FinancialInst in ledger\n\t\treturn t.createFinancialInstitution(stub, args)\n\t}\n\n\tfmt.Println(\"run did not find func: \" + function) //error\n\n\treturn nil, errors.New(\"Received unknown function invocation\")\n}", "func (c *Command) Execute() {\n\targs := os.Args[1:]\n\tswitch argsLen := len(args); {\n\tcase argsLen == 1:\n\t\tc.Run(args)\n\tdefault:\n\t\tlog.Println(\"our service currently handle 1 command only\")\n\t}\n}", "func Execute() {\n\tcmd := arrangeCommands()\n\n\tif err := cmd.Execute(); err != nil {\n\t\tlog.LogError(err)\n\t\tos.Exit(1)\n\t}\n}", "func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n if function == \"createAsset\" {\n return t.createAsset(stub, args)\n } else if function == \"updateAsset\" {\n return t.updateAsset(stub, args)\n } else if function == \"deleteAsset\" {\n return t.deleteAsset(stub, args)\n } else if function == \"deleteAllAssets\" {\n return t.deleteAllAssets(stub, args)\n } else if function == \"deletePropertiesFromAsset\" {\n return t.deletePropertiesFromAsset(stub, args)\n } else if function == \"setLoggingLevel\" {\n return nil, t.setLoggingLevel(stub, args)\n } else if function == \"setCreateOnUpdate\" {\n return nil, t.setCreateOnUpdate(stub, args)\n }\n err := fmt.Errorf(\"Invoke received unknown invocation: %s\", function)\n log.Warning(err)\n return nil, err\n}", "func Execute(client ioctl.Client,\n\tcmd *cobra.Command,\n\tcontract string,\n\tamount *big.Int,\n\tbytecode []byte,\n\tgasPrice, signer, password string,\n\tnonce, gasLimit uint64,\n\tassumeYes bool,\n) error {\n\tif len(contract) == 0 && len(bytecode) == 0 {\n\t\treturn errors.New(\"failed to deploy contract with empty bytecode\")\n\t}\n\tgasPriceRau, err := gasPriceInRau(client, gasPrice)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get gas price\")\n\t}\n\tsender, err := Signer(client, signer)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get signer address\")\n\t}\n\tnonce, err = checkNonce(client, nonce, sender)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get nonce\")\n\t}\n\ttx, err := action.NewExecution(contract, nonce, amount, gasLimit, gasPriceRau, bytecode)\n\tif err != nil || tx == nil {\n\t\treturn errors.Wrap(err, \"failed to make a Execution instance\")\n\t}\n\tif gasLimit == 0 {\n\t\ttx, err = fixGasLimit(client, sender, tx)\n\t\tif err != nil || tx == nil {\n\t\t\treturn errors.Wrap(err, \"failed to fix Execution gas limit\")\n\t\t}\n\t\tgasLimit = tx.GasLimit()\n\t}\n\treturn SendAction(\n\t\tclient,\n\t\tcmd,\n\t\t(&action.EnvelopeBuilder{}).\n\t\t\tSetNonce(nonce).\n\t\t\tSetGasPrice(gasPriceRau).\n\t\t\tSetGasLimit(gasLimit).\n\t\t\tSetAction(tx).Build(),\n\t\tsender,\n\t\tpassword,\n\t\tnonce,\n\t\tassumeYes,\n\t)\n}" ]
[ "0.61757225", "0.60558516", "0.600172", "0.594281", "0.591137", "0.58878464", "0.5868138", "0.5838943", "0.5834418", "0.5796378", "0.57638127", "0.569484", "0.5669228", "0.5649975", "0.564762", "0.5629406", "0.5627392", "0.56055653", "0.5603532", "0.55984074", "0.5563326", "0.55606407", "0.5555603", "0.5548418", "0.5535985", "0.553183", "0.5523572", "0.5517329", "0.55156636", "0.55133724", "0.5511207", "0.5510714", "0.55082387", "0.54857856", "0.54826003", "0.5474606", "0.5474267", "0.5469845", "0.5464968", "0.54635686", "0.5463147", "0.5455342", "0.54509574", "0.54505885", "0.5435515", "0.5435158", "0.54202163", "0.5416637", "0.5412667", "0.54078513", "0.5407324", "0.54051954", "0.5402855", "0.5401248", "0.54000413", "0.5397939", "0.5393137", "0.53803754", "0.5380362", "0.5373192", "0.53716344", "0.5359982", "0.53577924", "0.5350144", "0.5345346", "0.5343468", "0.5341455", "0.5335112", "0.53207666", "0.5316344", "0.5292418", "0.52886266", "0.52874786", "0.52856416", "0.52820134", "0.5277574", "0.5274891", "0.52729183", "0.52664673", "0.52635044", "0.52630085", "0.5259118", "0.525069", "0.52491015", "0.52483374", "0.5247853", "0.52466536", "0.5243585", "0.5238571", "0.52345806", "0.5233941", "0.5232364", "0.5226131", "0.52223474", "0.5219134", "0.5217894", "0.5214131", "0.52138543", "0.5209799", "0.52058154" ]
0.7164371
0
FromBOM returns the charset declared in the BOM of content.
func FromBOM(content []byte) string { for _, b := range boms { if bytes.HasPrefix(content, b.bom) { return b.enc } } return "" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *Font) GetCharset() string { return f.charset }", "func (lf *localFile) ContentEncoding() string {\n\tif lf.matcher == nil {\n\t\treturn \"\"\n\t}\n\tif lf.matcher.Gzip {\n\t\treturn \"gzip\"\n\t}\n\treturn lf.matcher.ContentEncoding\n}", "func BOMReader(ir io.Reader) io.Reader {\n\tr := bufio.NewReader(ir)\n\tb, err := r.Peek(3)\n\tif err != nil {\n\t\treturn r\n\t}\n\tif b[0] == bom0 && b[1] == bom1 && b[2] == bom2 {\n\t\tr.Discard(3)\n\t}\n\treturn r\n}", "func (b *Blueprint) GetCharset() string {\n\treturn b.charset\n}", "func (ctx *ProxyCtx) Charset() string {\n\tcharsets := charsetFinder.FindStringSubmatch(ctx.Resp.Header.Get(\"Content-Type\"))\n\tif charsets == nil {\n\t\treturn \"\"\n\t}\n\treturn charsets[1]\n}", "func (ft *FieldType) GetCharset() string {\n\treturn ft.charset\n}", "func (*XMLDocument) Charset() (charset string) {\n\tmacro.Rewrite(\"$_.charset\")\n\treturn charset\n}", "func DetectCharset(body []byte, contentType string) (string, error) {\n\t// 1. Use charset.DetermineEncoding\n\t_, name, certain := charset.DetermineEncoding(body, contentType)\n\tif certain {\n\t\treturn name, nil\n\t}\n\n\t// Handle uncertain cases\n\t// 2. Use chardet.Detector.DetectBest\n\tr, err := chardet.NewHtmlDetector().DetectBest(body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif r.Confidence == 100 {\n\t\treturn strings.ToLower(r.Charset), nil\n\t}\n\n\t// 3. Parse meta tag for Content-Type\n\troot, err := html.Parse(bytes.NewReader(body))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdoc := goquery.NewDocumentFromNode(root)\n\tvar csFromMeta string\n\tdoc.Find(\"meta\").EachWithBreak(func(i int, s *goquery.Selection) bool {\n\t\t// <meta http-equiv=\"Content-Type\" content=\"text/html; charset=MS949\"/>\n\t\tif c, exists := s.Attr(\"content\"); exists && strings.Contains(c, \"charset\") {\n\t\t\tif _, params, err := mime.ParseMediaType(c); err == nil {\n\t\t\t\tif cs, ok := params[\"charset\"]; ok {\n\t\t\t\t\tcsFromMeta = strings.ToLower(cs)\n\t\t\t\t\t// Handle Korean charsets.\n\t\t\t\t\tif csFromMeta == \"ms949\" || csFromMeta == \"cp949\" {\n\t\t\t\t\t\tcsFromMeta = \"euc-kr\"\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\n\t\t// <meta charset=\"utf-8\"/>\n\t\tif c, exists := s.Attr(\"charset\"); exists {\n\t\t\tcsFromMeta = c\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t})\n\n\tif csFromMeta == \"\" {\n\t\treturn \"\", fmt.Errorf(\"failed to detect charset\")\n\t}\n\n\treturn csFromMeta, nil\n}", "func ClearBOM(r io.Reader) io.Reader {\n\tbuf := bufio.NewReader(r)\n\tb, err := buf.Peek(3)\n\tif err != nil {\n\t\t// not enough bytes\n\t\treturn buf\n\t}\n\tif b[0] == 0xef && b[1] == 0xbb && b[2] == 0xbf {\n\t\tbuf.Discard(3)\n\t}\n\treturn buf\n}", "func FileGuessEncoding(bytes []byte) string {\n\tstrQ := fmt.Sprintf(\"%+q\", bytes)\n\n\t// Clean double quote at the begining & at the end\n\tif strQ[0] == '\"' {\n\t\tstrQ = strQ[1:]\n\t}\n\n\tif strQ[len(strQ)-1] == '\"' {\n\t\tstrQ = strQ[0 : len(strQ)-1]\n\t}\n\n\t// If utf-8-bom, it must start with \\ufeff\n\tre := regexp.MustCompile(`^\\\\ufeff`)\n\n\tfound := re.MatchString(strQ)\n\tif found {\n\t\treturn \"utf-8bom\"\n\t}\n\n\t// If utf-8, it must contain \\uxxxx\n\tre = regexp.MustCompile(`\\\\u[a-z0-9]{4}`)\n\n\tfound = re.MatchString(strQ)\n\tif found {\n\t\treturn \"utf-8\"\n\t}\n\n\t// utf-32be\n\tre = regexp.MustCompile(`^\\\\x00\\\\x00\\\\xfe\\\\xff`)\n\n\tfound = re.MatchString(strQ)\n\tif found {\n\t\treturn \"utf-32be\"\n\t}\n\n\t// utf-32le\n\tre = regexp.MustCompile(`^\\\\xff\\\\xfe\\\\x00\\\\x00`)\n\n\tfound = re.MatchString(strQ)\n\tif found {\n\t\treturn \"utf-32le\"\n\t}\n\n\t// utf-16be\n\tre = regexp.MustCompile(`^\\\\xff\\\\xff`)\n\n\tfound = re.MatchString(strQ)\n\tif found {\n\t\treturn \"utf-16be\"\n\t}\n\n\t// utf-16le\n\tre = regexp.MustCompile(`^\\\\xff\\\\xfe`)\n\n\tfound = re.MatchString(strQ)\n\tif found {\n\t\treturn \"utf-16le\"\n\t}\n\n\t// Check if 0x8{0-F} or 0x9{0-F} is present\n\tre = regexp.MustCompile(`(\\\\x8[0-9a-f]{1}|\\\\x9[0-9a-f]{1})`)\n\n\tfound = re.MatchString(strQ)\n\tif found {\n\t\t// It might be windows-1252 or mac-roman\n\t\t// But at this moment, do not have mean to distinguish both. So fallback to windows-1252\n\t\treturn \"windows-1252\"\n\t}\n\n\t// No 0x8{0-F} or 0x9{0-F} found, it might be iso-8859-xx\n\t// We tried to detect whether it is iso-8859-1 or iso-8859-15\n\t// Check if 0x8{0-F} or 0x9{0-F} is present\n\t//re = regexp.MustCompile(`(\\\\xa[4|6|8]{1}|\\\\xb[4|8|c|d|e]{1})`)\n\n\t//loc := re.FindStringIndex(strQ)\n\t//if loc != nil {\n\t//c := strQ[loc[0]:loc[1]]\n\t//fmt.Printf(\"char %s\\n\", c)\n\t//if enc, err := BytesConvertToUTF8(bytes, \"iso-8859-15\"); err == nil {\n\t//fmt.Println(\"converted bytes\", enc)\n\t//fmt.Printf(\"converted %+q\\n\", enc)\n\t//}\n\n\t// At this moment, we can not detect the difference between iso-8859-x.\n\t// So just return a fallback iso-8859-1\n\treturn \"iso-8859-1\"\n}", "func GetBOMByTKRName(ctx context.Context, c client.Client, tkrName string) (*bomtypes.Bom, error) {\n\tconfigMapList := &corev1.ConfigMapList{}\n\tvar bomConfigMap *corev1.ConfigMap\n\tif err := c.List(ctx, configMapList, client.InNamespace(constants.TKGBomNamespace), client.MatchingLabels{constants.TKRLabel: tkrName}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(configMapList.Items) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tbomConfigMap = &configMapList.Items[0]\n\tbomData, ok := bomConfigMap.BinaryData[constants.TKGBomContent]\n\tif !ok {\n\t\tbomDataString, ok := bomConfigMap.Data[constants.TKGBomContent]\n\t\tif !ok {\n\t\t\treturn nil, nil\n\t\t}\n\t\tbomData = []byte(bomDataString)\n\t}\n\n\tbom, err := bomtypes.NewBom(bomData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &bom, nil\n}", "func findCharset(content string) string {\n\tif pos := strings.LastIndex(content, \"charset=\"); pos != -1 {\n\t\treturn content[pos+len(\"charset=\"):]\n\t}\n\treturn \"\"\n}", "func (downloader *HTTPDownloader) changeCharsetEncodingAuto(contentTypeStr string, sor io.ReadCloser) string {\r\n\tvar err error\r\n\tdestReader, err := charset.NewReader(sor, contentTypeStr)\r\n\r\n\tif err != nil {\r\n\t\tmlog.LogInst().LogError(err.Error())\r\n\t\tdestReader = sor\r\n\t}\r\n\r\n\tvar sorbody []byte\r\n\tif sorbody, err = ioutil.ReadAll(destReader); err != nil {\r\n\t\tmlog.LogInst().LogError(err.Error())\r\n\t\t// For gb2312, an error will be returned.\r\n\t\t// Error like: simplifiedchinese: invalid GBK encoding\r\n\t\t// return \"\"\r\n\t}\r\n\t//e,name,certain := charset.DetermineEncoding(sorbody,contentTypeStr)\r\n\tbodystr := string(sorbody)\r\n\r\n\treturn bodystr\r\n}", "func SkipBOM(r *bufio.Reader) *bufio.Reader {\n\trr, _, err := r.ReadRune()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif rr != '\\uFEFF' {\n\t\tr.UnreadRune() // Not a BOM -- put the rune back\n\t}\n\n\treturn r\n}", "func (h *RequestHeader) ContentEncoding() []byte {\n\treturn peekArgBytes(h.h, strContentEncoding)\n}", "func hasBom(in []byte) bool {\n\treturn bytes.HasPrefix(in, utf8bom)\n}", "func DecodeAutoDetect(src []byte) (string, error) {\n\tfor _, enc := range encodings {\n\t\te, _ := charset.Lookup(enc)\n\t\tif e == nil {\n\t\t\tcontinue\n\t\t}\n\t\tvar buf bytes.Buffer\n\t\tr := transform.NewWriter(&buf, e.NewDecoder())\n\t\t_, err := r.Write(src)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\terr = r.Close()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tf := buf.Bytes()\n\t\tif isInvalidRune(f) {\n\t\t\tcontinue\n\t\t}\n\t\tif utf8.Valid(f) {\n\t\t\tif hasBom(f) {\n\t\t\t\tf = stripBom(f)\n\t\t\t}\n\t\t\treturn string(f), nil\n\t\t}\n\t}\n\treturn string(src), errors.New(\"could not determine character code\")\n}", "func (cs *CsvStructure) checkForConvertToUtf8(textBytes []byte) (outBytes []byte) {\n\tvar strByte []byte\n\tvar err error\n\toutBytes = make([]byte, len(textBytes))\n\tcopy(outBytes, textBytes)\n\t_, cs.Charset, _ = charset.DetermineEncoding(textBytes, \"\")\n\t// fmt.Println(cs.Charset)\n\tif cs.Charset != \"utf-8\" { // convert to UTF-8\n\t\tif reader, err := charset.NewReader(strings.NewReader(string(textBytes)), cs.Charset); err == nil {\n\t\t\tif strByte, err = ioutil.ReadAll(reader); err == nil {\n\t\t\t\toutBytes = make([]byte, len(strByte))\n\t\t\t\tcopy(outBytes, strByte)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tfmt.Println(\"Error while trying to convert %s to utf-8: \", cs.Charset)\n\t}\n\treturn outBytes\n}", "func DefaultCharsetForType(tp byte) (defaultCharset string, defaultCollation string) {\n\tswitch tp {\n\tcase mysql.TypeVarString, mysql.TypeString, mysql.TypeVarchar:\n\t\t// Default charset for string types is utf8mb4.\n\t\treturn mysql.DefaultCharset, mysql.DefaultCollationName\n\t}\n\treturn charset.CharsetBin, charset.CollationBin\n}", "func (o *S3UploadOpts) GetContentEncoding() *string {\n\treturn getStrPtr(o.ContentEncoding)\n}", "func (p *Parser) CharsetReader(c string, i io.Reader) (r io.Reader, e error) {\n\tswitch c {\n\tcase \"windows-1251\":\n\t\tr = decodeWin1251(i)\n\t}\n\treturn\n}", "func (dr downloadResponse) ContentEncoding() string {\n\treturn dr.rawResponse.Header.Get(\"Content-Encoding\")\n}", "func (bgpr BlobsGetPropertiesResponse) ContentEncoding() string {\n\treturn bgpr.rawResponse.Header.Get(\"Content-Encoding\")\n}", "func (oie *ObjectInfoExtension) ContentEncoding() string {\n\treturn oie.ObjectInfo.Metadata.Get(\"Content-Encoding\")\n}", "func (rpr ReadPathResponse) ContentEncoding() string {\n\treturn rpr.rawResponse.Header.Get(\"Content-Encoding\")\n}", "func fromgb(in []byte) string {\n\tout := make([]byte, len(in)*4)\n\n\t_, _, err := iconv.Convert(in, out, \"gb2312\", \"utf-8\")\n\tcheck(err)\n\treturn strings.Trim(string(out), \" \\n\\r\\x00\")\n}", "func ConvertToUTF8(source, charset string) (string, error) {\n\tswitch {\n\tcase strings.EqualFold(\"utf-8\", charset):\n\t\treturn source, nil\n\tcase strings.EqualFold(\"iso-8859-1\", charset):\n\t\treturn source, nil\n\tcase strings.EqualFold(\"us-ascii\", charset):\n\t\treturn source, nil\n\tdefault:\n\t\tenc, err := htmlindex.Get(charset)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tin := bytes.NewReader([]byte(source))\n\t\tout := transform.NewReader(in, enc.NewDecoder())\n\t\tresult, err := ioutil.ReadAll(out)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn string(result), nil\n\t}\n}", "func (dr DownloadResponse) ContentEncoding() string {\n\treturn dr.dr.ContentEncoding()\n}", "func (h *ResponseHeader) ContentEncoding() []byte {\n\treturn h.contentEncoding\n}", "func correctEncodingToUtf8(text []byte) []byte {\n\tr, err := charset.NewReader(bytes.NewBuffer(text), \"application/xml\")\n\tif err != nil {\n\t\tfmt.Println(\"Error converting encoding:\", err)\n\t\treturn nil\n\t}\n\ttext, _ = ioutil.ReadAll(r)\n\treturn text\n}", "func checkBomSkip(fileJob *FileJob) int {\n\t// UTF-8 BOM which if detected we should skip the BOM as we can then count correctly\n\t// []byte is UTF-8 BOM taken from https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding\n\tif bytes.HasPrefix(fileJob.Content, []byte{239, 187, 191}) {\n\t\tif Verbose {\n\t\t\tprintWarn(fmt.Sprintf(\"UTF-8 BOM found for file %s skipping 3 bytes\", fileJob.Filename))\n\t\t}\n\t\treturn 3\n\t}\n\n\t// If we have one of the other BOM then we might not be able to count correctly so if verbose let the user know\n\tif Verbose {\n\t\tfor _, v := range ByteOrderMarks {\n\t\t\tif bytes.HasPrefix(fileJob.Content, v) {\n\t\t\t\tprintWarn(fmt.Sprintf(\"BOM found for file %s indicating it is not ASCII/UTF-8 and may be counted incorrectly or ignored as a binary file\", fileJob.Filename))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0\n}", "func (c *ColumnChunkMetaData) Encodings() []parquet.Encoding { return c.encodings }", "func detectCharEncode(body []byte) CharEncode {\n\tdet := chardet.NewTextDetector()\n\tres, err := det.DetectBest(body)\n\tif err != nil {\n\t\treturn CharUnknown\n\t}\n\treturn typeOfCharEncode(res.Charset)\n}", "func (this *SIPMessage) GetContentEncoding() header.ContentEncodingHeader {\n\treturn this.GetHeader(core.SIPHeaderNames_CONTENT_ENCODING).(header.ContentEncodingHeader)\n}", "func GetUTF8Body(body []byte, contentType string,\n\tignoreInvalidUTF8Chars bool) (string, error) {\n\t// Detect charset.\n\tcs, err := DetectCharset(body, contentType)\n\tif err != nil {\n\t\tif !ignoreInvalidUTF8Chars {\n\t\t\treturn \"\", err\n\t\t}\n\t\tcs = \"utf-8\"\n\t}\n\n\t// Remove utf8.RuneError if ignoreInvalidUTF8Chars is true.\n\tbs := string(body)\n\tif ignoreInvalidUTF8Chars {\n\t\tif !utf8.ValidString(bs) {\n\t\t\tv := make([]rune, 0, len(bs))\n\t\t\tfor i, r := range bs {\n\t\t\t\tif r == utf8.RuneError {\n\t\t\t\t\t_, size := utf8.DecodeRuneInString(bs[i:])\n\t\t\t\t\tif size == 1 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tv = append(v, r)\n\t\t\t}\n\t\t\tbs = string(v)\n\t\t}\n\t}\n\n\t// Convert body.\n\tconverted, err := iconv.ConvertString(bs, cs, \"utf-8\")\n\tif err != nil && !strings.Contains(converted, \"</head>\") {\n\t\treturn \"\", err\n\t}\n\n\treturn converted, nil\n}", "func CodepageDetect(r io.Reader) (IDCodePage, error) {\n\tif r == nil {\n\t\treturn ASCII, nil\n\t}\n\tbuf, err := bufio.NewReader(r).Peek(ReadBufSize)\n\tif (err != nil) && (err != io.EOF) {\n\t\treturn ASCII, err\n\t}\n\t//match code page from BOM, support: utf-8, utf-16le, utf-16be, utf-32le or utf-32be\n\tif idCodePage, ok := CheckBOM(buf); ok {\n\t\treturn idCodePage, nil\n\t}\n\tif ValidUTF8(buf) {\n\t\treturn UTF8, nil\n\t}\n\treturn CodepageAutoDetect(buf), nil\n}", "func StringFromCharset(length int, charset string) (string, error) {\n\tresult := make([]byte, length) // Random string to return\n\tcharsetlen := big.NewInt(int64(len(charset)))\n\n\tfor i := 0; i < length; i++ {\n\t\tb, err := rand.Int(rand.Reader, charsetlen)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tr := int(b.Int64())\n\t\tresult[i] = charset[r]\n\t}\n\n\treturn string(result), nil\n}", "func (e *HTTPResponseEvent) ContentEncoding() string {\n\treturn e.contentEncoding\n}", "func DetectEncoding(b []byte) ([]byte, Encoding) {\n\tif !utf8.Valid(b) {\n\t\treturn b, UnknownEncoding\n\t}\n\n\ts := strings.TrimSpace(string(b))\n\n\ttyp := UnknownEncoding\n\n\tif _, err := ParseID(s); err == nil {\n\t\ttyp = IDEncoding\n\t} else if len(s) < 100 && (strings.HasPrefix(s, \"kex1\") || strings.HasPrefix(s, \"kbx1\")) {\n\t\ttyp = IDEncoding\n\t} else if strings.Contains(s, \"BEGIN \") && strings.Contains(s, \" MESSAGE\") {\n\t\ttyp = SaltpackEncoding\n\t} else if strings.HasPrefix(s, \"-----BEGIN \") {\n\t\ttyp = SSHEncoding\n\t} else if strings.HasPrefix(s, \"ssh-\") {\n\t\ttyp = SSHEncoding\n\t}\n\n\treturn []byte(s), typ\n\n}", "func FromPlain(content []byte) string {\n\tif len(content) == 0 {\n\t\treturn \"\"\n\t}\n\tif cset := FromBOM(content); cset != \"\" {\n\t\treturn cset\n\t}\n\torigContent := content\n\t// Try to detect UTF-8.\n\t// First eliminate any partial rune at the end.\n\tfor i := len(content) - 1; i >= 0 && i > len(content)-4; i-- {\n\t\tb := content[i]\n\t\tif b < 0x80 {\n\t\t\tbreak\n\t\t}\n\t\tif utf8.RuneStart(b) {\n\t\t\tcontent = content[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\thasHighBit := false\n\tfor _, c := range content {\n\t\tif c >= 0x80 {\n\t\t\thasHighBit = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif hasHighBit && utf8.Valid(content) {\n\t\treturn \"utf-8\"\n\t}\n\n\t// ASCII is a subset of UTF8. Follow W3C recommendation and replace with UTF8.\n\tif ascii(origContent) {\n\t\treturn \"utf-8\"\n\t}\n\n\treturn latin(origContent)\n}", "func (*XMLDocument) InputEncoding() (inputEncoding string) {\n\tmacro.Rewrite(\"$_.inputEncoding\")\n\treturn inputEncoding\n}", "func (UTF8Decoder) Name() string { return \"utf-8\" }", "func Info(name string) *Charset {\n\tfor _, f := range factories {\n\t\tif info := f.Info(name); info != nil {\n\t\t\treturn info\n\t\t}\n\t}\n\treturn nil\n}", "func (gppr GetPathPropertiesResponse) ContentEncoding() string {\n\treturn gppr.rawResponse.Header.Get(\"Content-Encoding\")\n}", "func (upr UpdatePathResponse) ContentEncoding() string {\n\treturn upr.rawResponse.Header.Get(\"Content-Encoding\")\n}", "func ISO8859_1toUTF8(in string) (out string, err error) {\n\t// create a Reader using the input string as Reader and ISO8859 decoder\n\tdecoded := transform.NewReader(strings.NewReader(in), charmap.ISO8859_1.NewDecoder())\n\tdecodedBytes, err := ioutil.ReadAll(decoded)\n\tif err != nil {\n\t\treturn\n\t}\n\tout = string(decodedBytes)\n\treturn\n}", "func (r *RepositoryContent) GetEncoding() string {\n\tif r == nil || r.Encoding == nil {\n\t\treturn \"\"\n\t}\n\treturn *r.Encoding\n}", "func HasCharset(ft *FieldType) bool {\n\tswitch ft.GetType() {\n\tcase mysql.TypeVarchar, mysql.TypeString, mysql.TypeVarString, mysql.TypeBlob,\n\t\tmysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob:\n\t\treturn !mysql.HasBinaryFlag(ft.flag)\n\tcase mysql.TypeEnum, mysql.TypeSet:\n\t\treturn true\n\t}\n\treturn false\n}", "func UTF82GBK(src string) ([]byte, error) {\n\tGB18030 := simplifiedchinese.All[0]\n\treturn ioutil.ReadAll(transform.NewReader(bytes.NewReader([]byte(src)), GB18030.NewEncoder()))\n}", "func (b *Blob) GetEncoding() string {\n\tif b == nil || b.Encoding == nil {\n\t\treturn \"\"\n\t}\n\treturn *b.Encoding\n}", "func SystemCodePageToUtf8(text string) (s string, e error) {\r\n\te = ErrInvalidEncoding\r\n\tstr := C.CString(text)\r\n\tdefer C.free(unsafe.Pointer(str)) // #nosec\r\n\r\n\tif wcACPStr, err := mbToWide(C.CP_ACP, str); err == nil {\r\n\t\tif utf8Str, err := wideToMB(C.CP_UTF8, wcACPStr); err == nil {\r\n\t\t\ts, e = utf8Str, nil\r\n\t\t}\r\n\t}\r\n\r\n\treturn\r\n}", "func convertCP(in string) (out string) {\n\tbuf := new(bytes.Buffer)\n\tw, err := charset.NewWriter(\"windows-1252\", buf)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Fprintf(w, in)\n\tw.Close()\n\n\tout = fmt.Sprintf(\"%s\", buf)\n\treturn out\n}", "func NewReader(r io.Reader, cpn ...string) (io.Reader, error) {\n\tif r == nil {\n\t\treturn r, errInputIsNil\n\t}\n\ttmpReader := bufio.NewReader(r)\n\tvar err error\n\tcp := ASCII\n\tif len(cpn) > 0 {\n\t\tcp = codepageByName(cpn[0])\n\t}\n\tif cp == ASCII {\n\t\tcp, err = CodepageDetect(tmpReader)\n\t}\n\t//TODO внимательно нужно посмотреть что может вернуть CodepageDetect()\n\t//эти случаи обработать, например через func unsupportedCodepageToDecode(cp)\n\tswitch {\n\tcase (cp == UTF32) || (cp == UTF32BE) || (cp == UTF32LE):\n\t\treturn r, errUnsupportedCodepage\n\tcase cp == ASCII: // кодировку определить не удалось, неизвестную кодировку возвращаем как есть\n\t\treturn r, errUnknown\n\tcase err != nil: // и если ошибка при чтении, то возвращаем как есть\n\t\treturn r, err\n\t}\n\n\tif checkBomExist(tmpReader) {\n\t\t//ошибку не обрабатываем, если мы здесь, то эти байты мы уже читали\n\t\ttmpReader.Read(make([]byte, cp.BomLen())) // считываем в никуда количество байт занимаемых BOM этой кодировки\n\t}\n\tif cp == UTF8 {\n\t\treturn tmpReader, nil // когда удалили BOM тогда можно вернуть UTF-8, ведь его конвертировать не нужно\n\t}\n\t//ошибку не обрабатываем, htmlindex.Get() возвращает ошибку только если не найдена кодировка, здесь это уже невозможно\n\t//здесь cp может содержать только кодировки имеющиеся в htmlindex\n\te, _ := htmlindex.Get(cp.String())\n\tr = transform.NewReader(tmpReader, e.NewDecoder())\n\treturn r, nil\n}", "func toUtf(input string) string {\n\tsr := strings.NewReader(input)\n\ttr := transform.NewReader(sr, charmap.Windows1251.NewDecoder())\n\tbuf, err := ioutil.ReadAll(tr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ts := string(buf)\n\n\treturn s\n}", "func _escFSMustByte(useLocal bool, name string) []byte {\n\tb, err := _escFSByte(useLocal, name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func _escFSMustByte(useLocal bool, name string) []byte {\n\tb, err := _escFSByte(useLocal, name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func _escFSMustByte(useLocal bool, name string) []byte {\n\tb, err := _escFSByte(useLocal, name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func _escFSMustByte(useLocal bool, name string) []byte {\n\tb, err := _escFSByte(useLocal, name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func readUtf8(dis *bytes.Buffer) error {\n\n\treturn nil\n}", "func (o CsvSerializationOutput) Encoding() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v CsvSerialization) *string { return v.Encoding }).(pulumi.StringPtrOutput)\n}", "func (x *Message) getCodec() (encoding.Codec, error) {\n\tv, ok := x.Header[ContentType]\n\tif !ok || v == \"\" {\n\t\treturn encoding.GetCodec(encoding.ContentTypeJSON), nil\n\t}\n\tcts := strings.Split(v, \";\")\n\tct := strings.Split(cts[0], \"/\")\n\tc := ct[0] // in case of codec name\n\tif len(ct) == 2 {\n\t\tc = ct[1] // in case of full content type.\n\t}\n\tcodec := encoding.GetCodec(c)\n\tif codec == nil {\n\t\treturn nil, status.Unimplemented(\"unregistered codec for content-type: %s\", x.GetContentType())\n\t}\n\treturn codec, nil\n}", "func (this *Tidy) CharEncoding(val int) (bool, error) {\n\tswitch val {\n\tcase Raw, Ascii, Latin0, Latin1, Utf8, Iso2022, Mac, Win1252, Ibm858, Utf16le, Utf16be, Utf16, Big5, Shiftjis:\n\t\treturn this.optSetInt(C.TidyCharEncoding, (C.ulong)(val))\n\t}\n\treturn false, errors.New(\"Argument val int is out of range (0-13)\")\n}", "func Utf8ToSystemCodePage(text string) (s string, e error) {\r\n\te = ErrInvalidEncoding\r\n\tstr := C.CString(text)\r\n\tdefer C.free(unsafe.Pointer(str)) // #nosec\r\n\r\n\tif wcACPStr, err := mbToWide(C.CP_UTF8, str); err == nil {\r\n\t\tif utf8Str, err := wideToMB(C.CP_ACP, wcACPStr); err == nil {\r\n\t\t\ts, e = utf8Str, nil\r\n\t\t}\r\n\t}\r\n\r\n\treturn\r\n}", "func readModUTF8(b []byte) rune {\n\tvar res rune\n\tc := b[0] >> 4\n\tif len(b) == 1 {\n\t\tres = rune(c >> 4)\n\t} else if len(b) == 2 {\n\t\tres = rune(((c & 0x1F) << 6) | (b[1] & 0x3F))\n\t} else if len(b) == 3 {\n\t\tfmt.Println(\"case3\")\n\t\t//var j uint16 = ((c & 0x0f) << 12)\n\t\tres = rune(((c & 0x0F) << 12) |\n\t\t\t((b[1] & 0x3F) << 6) |\n\t\t\t((b[2] & 0x3F) << 0))\n\t}\n\treturn res\n}", "func (o *Metadata) GetEncoding() string {\n\tif o == nil || o.Encoding == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Encoding\n}", "func ContentEncoding(value string) Option {\n\treturn setHeader(\"Content-Encoding\", value)\n}", "func decodeMUTF8(bytearr []byte) string {\n\tutflen := len(bytearr)\n\tchararr := make([]uint16, utflen)\n\n\tvar c, char2, char3 uint16\n\tcount := 0\n\tchararr_count := 0\n\n\tfor count < utflen {\n\t\tc = uint16(bytearr[count])\n\t\tif c > 127 {\n\t\t\tbreak\n\t\t}\n\t\tcount++\n\t\tchararr[chararr_count] = c\n\t\tchararr_count++\n\t}\n\n\tfor count < utflen {\n\t\tc = uint16(bytearr[count])\n\t\tswitch c >> 4 {\n\t\tcase 0, 1, 2, 3, 4, 5, 6, 7:\n\t\t\t/* 0xxxxxxx*/\n\t\t\tcount++\n\t\t\tchararr[chararr_count] = c\n\t\t\tchararr_count++\n\t\tcase 12, 13:\n\t\t\t/* 110x xxxx 10xx xxxx*/\n\t\t\tcount += 2\n\t\t\tif count > utflen {\n\t\t\t\tpanic(\"malformed input: partial character at end\")\n\t\t\t}\n\t\t\tchar2 = uint16(bytearr[count-1])\n\t\t\tif char2&0xC0 != 0x80 {\n\t\t\t\tpanic(fmt.Errorf(\"malformed input around byte %v\", count))\n\t\t\t}\n\t\t\tchararr[chararr_count] = c&0x1F<<6 | char2&0x3F\n\t\t\tchararr_count++\n\t\tcase 14:\n\t\t\t/* 1110 xxxx 10xx xxxx 10xx xxxx*/\n\t\t\tcount += 3\n\t\t\tif count > utflen {\n\t\t\t\tpanic(\"malformed input: partial character at end\")\n\t\t\t}\n\t\t\tchar2 = uint16(bytearr[count-2])\n\t\t\tchar3 = uint16(bytearr[count-1])\n\t\t\tif char2&0xC0 != 0x80 || char3&0xC0 != 0x80 {\n\t\t\t\tpanic(fmt.Errorf(\"malformed input around byte %v\", (count - 1)))\n\t\t\t}\n\t\t\tchararr[chararr_count] = c&0x0F<<12 | char2&0x3F<<6 | char3&0x3F<<0\n\t\t\tchararr_count++\n\t\tdefault:\n\t\t\t/* 10xx xxxx, 1111 xxxx */\n\t\t\tpanic(fmt.Errorf(\"malformed input around byte %v\", count))\n\t\t}\n\t}\n\t// The number of chars produced may be less than utflen\n\tchararr = chararr[0:chararr_count]\n\trunes := utf16.Decode(chararr)\n\treturn string(runes)\n}", "func correctEncodingField(text []byte) []byte {\n\tbuf := bytes.NewBuffer(make([]byte, 0, len(text)))\n\n\tfor i := 0; i < len(text); i++ {\n\t\tbuf.WriteByte(text[i])\n\n\t\t// If found an encoding field.\n\t\tif text[i] == '=' && i >= 8 && string(text[i-8:i+1]) == \"encoding=\" {\n\t\t\tbuf.WriteString(\"\\\"utf-8\\\"\")\n\n\t\t\t// Advance to after end of field.\n\t\t\ti += 2\n\t\t\tfor text[i] != '\"' {\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn buf.Bytes()\n}", "func (dw *DrawingWand) GetTextEncoding() string {\n\tcstr := C.MagickDrawGetTextEncoding(dw.dw)\n\tdefer C.MagickRelinquishMemory(unsafe.Pointer(cstr))\n\treturn C.GoString(cstr)\n}", "func (f MLFindFileStructure) WithCharset(v string) func(*MLFindFileStructureRequest) {\n\treturn func(r *MLFindFileStructureRequest) {\n\t\tr.Charset = v\n\t}\n}", "func (o *VolumeLanguageAttributesType) OemCharacterSet() string {\n\tvar r string\n\tif o.OemCharacterSetPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.OemCharacterSetPtr\n\treturn r\n}", "func _escFSByte(useLocal bool, name string) ([]byte, error) {\n\tif useLocal {\n\t\tf, err := _escLocal.Open(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb, err := ioutil.ReadAll(f)\n\t\tf.Close()\n\t\treturn b, err\n\t}\n\tf, err := _escStatic.prepare(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.data, nil\n}", "func Bech32Decode(bech string) (string, []byte, error) {\n\tfor _, c := range bech {\n\t\tif c < 33 || c > 126 {\n\t\t\treturn \"\", nil, merry.Errorf(\"bech decode: character '%c' not in charset\", c)\n\t\t}\n\t}\n\tbech = strings.ToLower(bech)\n\tpos := strings.LastIndex(bech, \"1\")\n\tif pos < 1 || pos+7 > len(bech) || len(bech) > 90 {\n\t\treturn \"\", nil, merry.Errorf(\"bech decode: invalid hrp end index %d\", pos)\n\t}\n\thrp := bech[:pos]\n\tdataStr := bech[pos+1:]\n\tdata := make([]byte, len(dataStr))\n\tfor i, c := range dataStr {\n\t\tvar ok bool\n\t\tdata[i], ok = CHARSET_MAP[c]\n\t\tif !ok {\n\t\t\treturn \"\", nil, merry.Errorf(\"bech decode: character '%c' not in charset\", c)\n\t\t}\n\t}\n\tif !bech32VerifyChecksum(hrp, data) {\n\t\treturn \"\", nil, merry.Errorf(\"bech decode: checksum mismatch\")\n\t}\n\treturn hrp, data[:len(data)-6], nil\n}", "func GbToUtf8(s []byte, encoding string) ([]byte, error) {\n\tvar t transform.Transformer\n\tswitch encoding {\n\tcase \"gbk\":\n\t\tt = simplifiedchinese.GBK.NewDecoder()\n\tcase \"gb18030\":\n\t\tt = simplifiedchinese.GB18030.NewDecoder()\n\t}\n\treader := transform.NewReader(bytes.NewReader(s), t)\n\td, e := ioutil.ReadAll(reader)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn d, nil\n}", "func _escFSByte(useLocal bool, name string) ([]byte, error) {\n\tif useLocal {\n\t\tf, err := _escLocal.Open(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb, err := ioutil.ReadAll(f)\n\t\t_ = f.Close()\n\t\treturn b, err\n\t}\n\tf, err := _escStatic.prepare(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.data, nil\n}", "func _escFSByte(useLocal bool, name string) ([]byte, error) {\n\tif useLocal {\n\t\tf, err := _escLocal.Open(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb, err := ioutil.ReadAll(f)\n\t\t_ = f.Close()\n\t\treturn b, err\n\t}\n\tf, err := _escStatic.prepare(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.data, nil\n}", "func _escFSByte(useLocal bool, name string) ([]byte, error) {\n\tif useLocal {\n\t\tf, err := _escLocal.Open(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb, err := ioutil.ReadAll(f)\n\t\t_ = f.Close()\n\t\treturn b, err\n\t}\n\tf, err := _escStatic.prepare(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.data, nil\n}", "func (a *App) ProcessUTF16be(ctx context.Context, r io.Reader, name, archive string) error {\n\tr = transform.NewReader(r, unicode.UTF16(unicode.BigEndian, unicode.UseBOM).NewDecoder())\n\treturn a.ProcessUTF8(ctx, r, name, archive)\n}", "func (r *Response) ContentEncoding(encoding ...string) *Response {\n\topChain := r.chain.enter(\"ContentEncoding()\")\n\tdefer opChain.leave()\n\n\tif opChain.failed() {\n\t\treturn r\n\t}\n\n\tr.checkEqual(opChain, `\"Content-Encoding\" header`,\n\t\tencoding,\n\t\tr.httpResp.Header[\"Content-Encoding\"])\n\n\treturn r\n}", "func (m *Gzip) GetContentType() []string {\n\tif m != nil {\n\t\treturn m.ContentType\n\t}\n\treturn nil\n}", "func DumpBomAsText(bm *BomMeta, b *Bom, out io.Writer) {\n\tfmt.Fprintln(out)\n\tfmt.Fprintf(out, \"Name:\\t\\t%s\\n\", bm.Name)\n\tfmt.Fprintf(out, \"Version:\\t%s\\n\", b.Version)\n\tfmt.Fprintf(out, \"Creator:\\t%s\\n\", bm.Owner)\n\tfmt.Fprintf(out, \"Timestamp:\\t%s\\n\", b.Created)\n\tif bm.Homepage != \"\" {\n\t\tfmt.Fprintf(out, \"Homepage:\\t%s\\n\", bm.Homepage)\n\t}\n\tif b.Progeny != \"\" {\n\t\tfmt.Fprintf(out, \"Source:\\t\\t%s\\n\", b.Progeny)\n\t}\n\tif bm.Description != \"\" {\n\t\tfmt.Fprintf(out, \"Description:\\t%s\\n\", bm.Description)\n\t}\n\tfmt.Println()\n\ttabWriter := tabwriter.NewWriter(out, 2, 4, 1, ' ', 0)\n\t// \"by line item\", not \"by element\"\n\tfmt.Fprintf(tabWriter, \"qty\\ttag\\tmanufacturer\\tmpn\\t\\tfunction\\t\\tcomment\\n\")\n\tfor _, li := range b.LineItems {\n\t\tfmt.Fprintf(tabWriter, \"%d\\t%s\\t%s\\t%s\\t\\t%s\\t\\t%s\\n\",\n\t\t\tlen(li.Elements),\n\t\t\tli.Tag,\n\t\t\tli.Manufacturer,\n\t\t\tli.Mpn,\n\t\t\tli.Description,\n\t\t\tli.Comment)\n\t}\n\ttabWriter.Flush()\n}", "func (o TableExternalDataConfigurationCsvOptionsPtrOutput) Encoding() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TableExternalDataConfigurationCsvOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Encoding\n\t}).(pulumi.StringPtrOutput)\n}", "func (sct *ContentSniffer) ContentType() (string, bool) {\n\tif sct.sniffed {\n\t\treturn sct.ctype, sct.ctype != \"\"\n\t}\n\tsct.sniffed = true\n\t// If ReadAll hits EOF, it returns err==nil.\n\tsct.start, sct.err = ioutil.ReadAll(io.LimitReader(sct.r, sniffBuffSize))\n\n\t// Don't try to detect the content type based on possibly incomplete data.\n\tif sct.err != nil {\n\t\treturn \"\", false\n\t}\n\n\tsct.ctype = http.DetectContentType(sct.start)\n\treturn sct.ctype, true\n}", "func ContentTransferEncoding(encoding encoding.ContentTransferType) (string, string) {\n\treturn \"Content-Transfer-Encoding\", string(encoding)\n}", "func (this *Tidy) OutputBom(val int) (bool, error) {\n\treturn this.optSetAutoBool(C.TidyOutputBOM, (C.ulong)(val))\n}", "func (ft *FieldType) SetCharset(charset string) {\n\tft.charset = charset\n}", "func GetTKRNameFromBOMConfigMap(bomConfigMap *corev1.ConfigMap) string {\n\treturn bomConfigMap.Labels[constants.TKRLabel]\n}", "func (ft *FieldType) GetCollate() string {\n\treturn ft.collate\n}", "func (h *RequestHeader) ContentType() []byte {\n\tif h.disableSpecialHeader {\n\t\treturn peekArgBytes(h.h, []byte(HeaderContentType))\n\t}\n\treturn h.contentType\n}", "func (e CharacterEncoding) String() string {\n\tswitch e {\n\tcase EncodingASCII:\n\t\treturn \"ASCII\"\n\tcase EncodingUTF8:\n\t\treturn \"UTF-8\"\n\tcase EncodingUnknown:\n\t\tfallthrough\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}", "func WithCharset(nli int) CharsetOption {\n\treturn CharsetOption{nli}\n}", "func getCiliumVersionString(epCHeaderFilePath string) ([]byte, error) {\n\tf, err := os.Open(epCHeaderFilePath)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tbr := bufio.NewReader(f)\n\tdefer f.Close()\n\tfor {\n\t\tb, err := br.ReadBytes('\\n')\n\t\tif errors.Is(err, io.EOF) {\n\t\t\treturn []byte{}, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tif bytes.Contains(b, []byte(ciliumCHeaderPrefix)) {\n\t\t\treturn b, nil\n\t\t}\n\t}\n}", "func (o TableExternalDataConfigurationCsvOptionsOutput) Encoding() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TableExternalDataConfigurationCsvOptions) *string { return v.Encoding }).(pulumi.StringPtrOutput)\n}", "func FileConvertToUTF8(file io.Reader, charset string) (io.Reader, error) {\n\tencoding, err := getEncoding(charset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn encoding.NewDecoder().Reader(file), nil\n}", "func (h *ResponseHeader) ContentType() []byte {\n\tcontentType := h.contentType\n\tif !h.noDefaultContentType && len(h.contentType) == 0 {\n\t\tcontentType = defaultContentType\n\t}\n\treturn contentType\n}", "func getCE(meth string, ce string) string {\n\tif !(meth == \"POST\" || meth == \"PATCH\" || meth == \"PUT\") {\n\t\treturn \"\"\n\t}\n\t_, ce = split(strings.ToLower(ce), \";\")\n\t_, ce = split(ce, \"charset=\")\n\tce, _ = split(ce, \";\")\n\treturn ce\n}", "func (d Decoder) WithCharset(set charset.Decoder) Decoder {\n\td.set = set\n\treturn d\n}", "func (j *Env) GetUTF8String() *ObjectRef {\n\tif utf8 == nil {\n\t\tstr, err := j.NewObject(\"java/lang/String\", []byte(\"UTF-8\"))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tglobal := j.NewGlobalRef(str)\n\t\tj.DeleteLocalRef(str)\n\t\tutf8 = global\n\t}\n\n\treturn utf8\n}", "func GetEncoding(r *http.Request, offers []string) (string, error) {\n\tacceptEncoding := r.Header[AcceptEncodingHeaderKey]\n\n\tif len(acceptEncoding) == 0 {\n\t\treturn \"\", ErrResponseNotCompressed\n\t}\n\n\tencoding := negotiateAcceptHeader(acceptEncoding, offers, IDENTITY)\n\tif encoding == \"\" {\n\t\treturn \"\", fmt.Errorf(\"%w: %s\", ErrNotSupportedCompression, encoding)\n\t}\n\n\treturn encoding, nil\n}", "func Reader(charset string, input io.Reader) (io.Reader, error) {\n\tcharset = strings.ToLower(charset)\n\t// \"ascii\" is not in the spec but is common\n\tif charset == \"utf-8\" || charset == \"us-ascii\" || charset == \"ascii\" {\n\t\treturn input, nil\n\t}\n\tif enc, ok := charsets[charset]; ok {\n\t\treturn enc.NewDecoder().Reader(input), nil\n\t}\n\treturn nil, fmt.Errorf(\"unhandled charset %q\", charset)\n}" ]
[ "0.62555885", "0.5955372", "0.59179115", "0.58235437", "0.5750309", "0.5729708", "0.5658097", "0.5573649", "0.55022633", "0.5491252", "0.5472508", "0.54424894", "0.5424224", "0.5221963", "0.5099995", "0.50891393", "0.5028969", "0.49343708", "0.48285758", "0.47922873", "0.47917458", "0.47826916", "0.47747797", "0.47706518", "0.47669125", "0.47379306", "0.4710506", "0.47085384", "0.4668222", "0.4664772", "0.46549657", "0.46532995", "0.45682552", "0.45119137", "0.45072418", "0.4464518", "0.445596", "0.44345504", "0.44195205", "0.44178945", "0.44139856", "0.44080818", "0.4377532", "0.4353478", "0.43497998", "0.43241233", "0.4319483", "0.4318673", "0.43096623", "0.42973256", "0.42612612", "0.42586645", "0.42569834", "0.4255403", "0.42285556", "0.42285556", "0.42285556", "0.42285556", "0.4226552", "0.42237476", "0.4191453", "0.419092", "0.41668385", "0.41599143", "0.41452268", "0.41408226", "0.41219363", "0.40927705", "0.40818524", "0.40616468", "0.40600422", "0.40599367", "0.40582088", "0.40535718", "0.40534085", "0.40534085", "0.40534085", "0.40489474", "0.40222353", "0.40030396", "0.4001778", "0.39990863", "0.399247", "0.3992375", "0.39877763", "0.3982326", "0.39769134", "0.39654213", "0.39571244", "0.3957038", "0.39556602", "0.39531678", "0.39513907", "0.39381146", "0.39308843", "0.39305586", "0.3929666", "0.3928891", "0.39150962", "0.39099082" ]
0.75923693
0
FromPlain returns the charset of a plain text. It relies on BOM presence and it falls back on checking each byte in content.
func FromPlain(content []byte) string { if len(content) == 0 { return "" } if cset := FromBOM(content); cset != "" { return cset } origContent := content // Try to detect UTF-8. // First eliminate any partial rune at the end. for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- { b := content[i] if b < 0x80 { break } if utf8.RuneStart(b) { content = content[:i] break } } hasHighBit := false for _, c := range content { if c >= 0x80 { hasHighBit = true break } } if hasHighBit && utf8.Valid(content) { return "utf-8" } // ASCII is a subset of UTF8. Follow W3C recommendation and replace with UTF8. if ascii(origContent) { return "utf-8" } return latin(origContent) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ReadPlainBytes(b []byte) ByteReadScanner {\n\treturn bytes.NewReader(b)\n}", "func FromHTML(content []byte) string {\n\tif cset := FromBOM(content); cset != \"\" {\n\t\treturn cset\n\t}\n\tif cset := fromHTML(content); cset != \"\" {\n\t\treturn cset\n\t}\n\treturn FromPlain(content)\n}", "func CreatePlainMessage(t string) Message {\n\treturn Message{\n\t\tPayload: string(t),\n\t\tType: 0,\n\t}\n}", "func (cs *CsvStructure) checkForConvertToUtf8(textBytes []byte) (outBytes []byte) {\n\tvar strByte []byte\n\tvar err error\n\toutBytes = make([]byte, len(textBytes))\n\tcopy(outBytes, textBytes)\n\t_, cs.Charset, _ = charset.DetermineEncoding(textBytes, \"\")\n\t// fmt.Println(cs.Charset)\n\tif cs.Charset != \"utf-8\" { // convert to UTF-8\n\t\tif reader, err := charset.NewReader(strings.NewReader(string(textBytes)), cs.Charset); err == nil {\n\t\t\tif strByte, err = ioutil.ReadAll(reader); err == nil {\n\t\t\t\toutBytes = make([]byte, len(strByte))\n\t\t\t\tcopy(outBytes, strByte)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tfmt.Println(\"Error while trying to convert %s to utf-8: \", cs.Charset)\n\t}\n\treturn outBytes\n}", "func AcceptPlain(pw string) (EncodedPasswd, error) {\n\treturn &plainPassword{pw}, nil\n}", "func (text *Text) Plain(content string) *Text {\n\ttext.Spans = append(text.Spans, Span{\n\t\tContent: content,\n\t})\n\treturn text\n}", "func Text(raw []byte, limit uint32) bool {\n\t// First look for BOM.\n\tif cset := charset.FromBOM(raw); cset != \"\" {\n\t\treturn true\n\t}\n\t// Binary data bytes as defined here: https://mimesniff.spec.whatwg.org/#binary-data-byte\n\tfor _, b := range raw {\n\t\tif b <= 0x08 ||\n\t\t\tb == 0x0B ||\n\t\t\t0x0E <= b && b <= 0x1A ||\n\t\t\t0x1C <= b && b <= 0x1F {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func correctEncodingToUtf8(text []byte) []byte {\n\tr, err := charset.NewReader(bytes.NewBuffer(text), \"application/xml\")\n\tif err != nil {\n\t\tfmt.Println(\"Error converting encoding:\", err)\n\t\treturn nil\n\t}\n\ttext, _ = ioutil.ReadAll(r)\n\treturn text\n}", "func (be *ContentEnc) PlainBS() uint64 {\n\treturn be.plainBS\n}", "func (in *ActionMailTemplateTranslationUpdateInput) SetTextPlain(value string) *ActionMailTemplateTranslationUpdateInput {\n\tin.TextPlain = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"TextPlain\"] = nil\n\treturn in\n}", "func (w *Wallet) GetPlain() (psw, content string, err error) {\n\tbase64Decoded, err := base64.StdEncoding.DecodeString(w.CipherContent)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcontentBytes, err := crypto.AESDecrypt(base64Decoded, passWd)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcontent = util.String(contentBytes)\n\n\tbase64Decoded, err = base64.StdEncoding.DecodeString(w.CipherPSW)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpswBytes, err := crypto.AESDecrypt(base64Decoded, passWd)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpsw = util.String(pswBytes)\n\treturn\n}", "func New(cc *cryptocore.CryptoCore, plainBS uint64, forceDecode bool) *ContentEnc {\n\tcipherBS := plainBS + uint64(cc.IVLen) + cryptocore.AuthTagLen\n\n\treturn &ContentEnc{\n\t\tcryptoCore: cc,\n\t\tplainBS: plainBS,\n\t\tcipherBS: cipherBS,\n\t\tallZeroBlock: make([]byte, cipherBS),\n\t\tallZeroNonce: make([]byte, cc.IVLen),\n\t\tforceDecode: forceDecode,\n\t}\n}", "func NewDataFrameFromTextMessage(msg string, mask bool) (*DataFrame, error) {\n\tdf := &DataFrame{\n\t\tpayload: []byte(msg),\n\t\tmask: mask,\n\t\tfin: true,\n\t\tOpCode: OpCodeText,\n\t\tpayloadLen: len(msg),\n\t}\n\treturn df, nil\n}", "func PlainText(s string) Response {\n\treturn stringResponse{s}\n}", "func TestText(t *testing.T) {\n\tinput := \"Hello world!\"\n\tresult := Text(input)\n\n\tif !strings.EqualFold(input, result) {\n\t\tt.Errorf(\"Should have same content except capitalisation: \\\"%s\\\" - \\\"%s\\\"\", input, result)\n\t}\n}", "func fromTextPb(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar ctor starlark.Value\n\tvar text starlark.String\n\tif err := starlark.UnpackArgs(\"from_textpb\", args, kwargs, \"ctor\", &ctor, \"text\", &text); err != nil {\n\t\treturn nil, err\n\t}\n\n\tc, ok := ctor.(*messageCtor)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"from_textpb: got %s, expecting a proto message constructor\", ctor.Type())\n\t}\n\ttyp := c.typ\n\n\tprotoMsg := typ.NewProtoMessage().Interface().(proto.Message)\n\tif err := proto.UnmarshalText(text.GoString(), protoMsg); err != nil {\n\t\treturn nil, fmt.Errorf(\"from_textpb: %s\", err)\n\t}\n\n\tmsg := NewMessage(typ)\n\tif err := msg.FromProto(protoMsg); err != nil {\n\t\treturn nil, fmt.Errorf(\"from_textpb: %s\", err)\n\t}\n\treturn msg, nil\n}", "func NewTextMail(msg *mail.Message) (*TextMailMessage, error) {\n\t_, params, err := mime.ParseMediaType(msg.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata, err := DecodeText(msg.Body, params[\"charset\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &TextMailMessage{\n\t\tbody: msg.Body,\n\t\theader: msg.Header,\n\t\ttext: data,\n\t}\n\treturn t, nil\n}", "func (ckms *CKMS) DecryptRaw(cipherText []byte) ([]byte, error) {\n\n\tresult, err := ckms.svc.Decrypt(&kms.DecryptInput{CiphertextBlob: cipherText})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result.Plaintext, nil\n}", "func FromBOM(content []byte) string {\n\tfor _, b := range boms {\n\t\tif bytes.HasPrefix(content, b.bom) {\n\t\t\treturn b.enc\n\t\t}\n\t}\n\treturn \"\"\n}", "func GetUTF8Body(body []byte, contentType string,\n\tignoreInvalidUTF8Chars bool) (string, error) {\n\t// Detect charset.\n\tcs, err := DetectCharset(body, contentType)\n\tif err != nil {\n\t\tif !ignoreInvalidUTF8Chars {\n\t\t\treturn \"\", err\n\t\t}\n\t\tcs = \"utf-8\"\n\t}\n\n\t// Remove utf8.RuneError if ignoreInvalidUTF8Chars is true.\n\tbs := string(body)\n\tif ignoreInvalidUTF8Chars {\n\t\tif !utf8.ValidString(bs) {\n\t\t\tv := make([]rune, 0, len(bs))\n\t\t\tfor i, r := range bs {\n\t\t\t\tif r == utf8.RuneError {\n\t\t\t\t\t_, size := utf8.DecodeRuneInString(bs[i:])\n\t\t\t\t\tif size == 1 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tv = append(v, r)\n\t\t\t}\n\t\t\tbs = string(v)\n\t\t}\n\t}\n\n\t// Convert body.\n\tconverted, err := iconv.ConvertString(bs, cs, \"utf-8\")\n\tif err != nil && !strings.Contains(converted, \"</head>\") {\n\t\treturn \"\", err\n\t}\n\n\treturn converted, nil\n}", "func (sc *serverConn) authPlain() error {\n\tm := &msg{\n\t\theader: header{\n\t\t\tOp: opAuthStart,\n\t\t},\n\n\t\tkey: \"PLAIN\",\n\t\tval: fmt.Sprintf(\"\\x00%s\\x00%s\", sc.username, sc.password),\n\t}\n\n\treturn sc.sendRecv(m)\n}", "func TestLoadedSimpleFontEncoding(t *testing.T) {\n\trawpdf := `\n59 0 obj\n<</BaseFont /Helvetica/Encoding 60 0 R/Name /Helv/Subtype /Type1/Type /Font>>\nendobj\n60 0 obj\n<</Differences [24 /breve /caron /circumflex /dotaccent /hungarumlaut /ogonek /ring /tilde 39 /quotesingle 96 /grave 128 /bullet /dagger /daggerdbl /ellipsis /emdash /endash /florin /fraction /guilsinglleft /guilsinglright /minus /perthousand /quotedblbase /quotedblleft /quotedblright /quoteleft /quoteright /quotesinglbase /trademark /fi /fl /Lslash /OE /Scaron /Ydieresis /Zcaron /dotlessi /lslash /oe /scaron /zcaron 160 /Euro 164 /currency 166 /brokenbar 168 /dieresis /copyright /ordfeminine 172 /logicalnot /.notdef /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu 183 /periodcentered /cedilla /onesuperior /ordmasculine 188 /onequarter /onehalf /threequarters 192 /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis]/Type /Encoding>>\nendobj\n`\n\n\tobjects, err := testutils.ParseIndirectObjects(rawpdf)\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %v\", err)\n\t}\n\n\tfont, err := model.NewPdfFontFromPdfObject(objects[59])\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// The expected encoding is StandardEncoding with the applied differences.\n\tbaseEncoding := newStandandTextEncoder(t)\n\n\tdifferencesMap := map[textencoding.CharCode]rune{\n\t\t24: '˘',\n\t\t25: 'ˇ',\n\t\t26: 'ˆ',\n\t\t27: '˙',\n\t\t28: '˝',\n\t\t29: '˛',\n\t\t30: '˚',\n\t\t31: '˜',\n\t\t39: '\\'',\n\t\t96: '`',\n\t\t128: '•',\n\t\t129: '†',\n\t\t130: '‡',\n\t\t131: '…',\n\t\t132: '—',\n\t\t133: '–',\n\t\t134: 'ƒ',\n\t\t135: '⁄',\n\t\t136: '‹',\n\t\t137: '›',\n\t\t138: '−',\n\t\t139: '‰',\n\t\t140: '„',\n\t\t141: '“',\n\t\t142: '”',\n\t\t143: '‘',\n\t\t144: '’',\n\t\t145: '‚',\n\t\t146: '™',\n\t\t147: 'fi',\n\t\t148: 'fl',\n\t\t149: 'Ł',\n\t\t150: 'Œ',\n\t\t151: 'Š',\n\t\t152: 'Ÿ',\n\t\t153: 'Ž',\n\t\t154: 'ı',\n\t\t155: 'ł',\n\t\t156: 'œ',\n\t\t157: 'š',\n\t\t158: 'ž',\n\t\t160: '€',\n\t\t164: '¤',\n\t\t166: '¦',\n\t\t168: '¨',\n\t\t169: '©',\n\t\t170: 'ª',\n\t\t172: '¬',\n\t\t173: '�',\n\t\t174: '®',\n\t\t175: '¯',\n\t\t176: '°',\n\t\t177: '±',\n\t\t178: '²',\n\t\t179: '³',\n\t\t180: '´',\n\t\t181: 'µ',\n\t\t183: '·',\n\t\t184: '¸',\n\t\t185: '¹',\n\t\t186: 'º',\n\t\t188: '¼',\n\t\t189: '½',\n\t\t190: '¾',\n\t\t192: 'À',\n\t\t193: 'Á',\n\t\t194: 'Â',\n\t\t195: 'Ã',\n\t\t196: 'Ä',\n\t\t197: 'Å',\n\t\t198: 'Æ',\n\t\t199: 'Ç',\n\t\t200: 'È',\n\t\t201: 'É',\n\t\t202: 'Ê',\n\t\t203: 'Ë',\n\t\t204: 'Ì',\n\t\t205: 'Í',\n\t\t206: 'Î',\n\t\t207: 'Ï',\n\t\t208: 'Ð',\n\t\t209: 'Ñ',\n\t\t210: 'Ò',\n\t\t211: 'Ó',\n\t\t212: 'Ô',\n\t\t213: 'Õ',\n\t\t214: 'Ö',\n\t\t215: '×',\n\t\t216: 'Ø',\n\t\t217: 'Ù',\n\t\t218: 'Ú',\n\t\t219: 'Û',\n\t\t220: 'Ü',\n\t\t221: 'Ý',\n\t\t222: 'Þ',\n\t\t223: 'ß',\n\t\t224: 'à',\n\t\t225: 'á',\n\t\t226: 'â',\n\t\t227: 'ã',\n\t\t228: 'ä',\n\t\t229: 'å',\n\t\t230: 'æ',\n\t\t231: 'ç',\n\t\t232: 'è',\n\t\t233: 'é',\n\t\t234: 'ê',\n\t\t235: 'ë',\n\t\t236: 'ì',\n\t\t237: 'í',\n\t\t238: 'î',\n\t\t239: 'ï',\n\t\t240: 'ð',\n\t\t241: 'ñ',\n\t\t242: 'ò',\n\t\t243: 'ó',\n\t\t244: 'ô',\n\t\t245: 'õ',\n\t\t246: 'ö',\n\t\t247: '÷',\n\t\t248: 'ø',\n\t\t249: 'ù',\n\t\t250: 'ú',\n\t\t251: 'û',\n\t\t252: 'ü',\n\t\t253: 'ý',\n\t\t254: 'þ',\n\t\t255: 'ÿ',\n\t}\n\n\tenc := font.Encoder()\n\tfor code := textencoding.CharCode(32); code < 255; code++ {\n\t\tfontrune, has := enc.CharcodeToRune(code)\n\t\tif !has {\n\t\t\tbaserune, bad := baseEncoding.CharcodeToRune(code)\n\t\t\tif bad {\n\t\t\t\tt.Fatalf(\"font not having glyph for char code %d - whereas base encoding had %q\", code, baserune)\n\t\t\t}\n\t\t}\n\n\t\t// Check if in differencesmap first.\n\t\trune, has := differencesMap[code]\n\t\tif has {\n\t\t\tif rune != fontrune {\n\t\t\t\tt.Fatalf(\"Mismatch for char code %d, font has: %q and expected is: %q (differences)\", code, fontrune, rune)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// If not in differences, should be according to StandardEncoding (base).\n\t\trune, has = baseEncoding.CharcodeToRune(code)\n\t\tif has && rune != fontrune {\n\t\t\tt.Fatalf(\"Mismatch for char code %d (%X), font has: %q and expected is: %q (StandardEncoding)\", code, code, fontrune, rune)\n\t\t}\n\t}\n}", "func plainText(h http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Add(\"Content-Type\", \"text/plain; charset=utf-8\")\n\t\th(w, r)\n\t}\n}", "func (c *Cell) PlainText(b *bytes.Buffer) string {\n\tn := len(c.P)\n\tif n == 1 {\n\t\treturn c.P[0].PlainText(b)\n\t}\n\n\tb.Reset()\n\tfor i := range c.P {\n\t\tif i != n-1 {\n\t\t\tc.P[i].writePlainText(b)\n\t\t\tb.WriteByte('\\n')\n\t\t} else {\n\t\t\tc.P[i].writePlainText(b)\n\t\t}\n\t}\n\treturn b.String()\n}", "func DetectCharset(body []byte, contentType string) (string, error) {\n\t// 1. Use charset.DetermineEncoding\n\t_, name, certain := charset.DetermineEncoding(body, contentType)\n\tif certain {\n\t\treturn name, nil\n\t}\n\n\t// Handle uncertain cases\n\t// 2. Use chardet.Detector.DetectBest\n\tr, err := chardet.NewHtmlDetector().DetectBest(body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif r.Confidence == 100 {\n\t\treturn strings.ToLower(r.Charset), nil\n\t}\n\n\t// 3. Parse meta tag for Content-Type\n\troot, err := html.Parse(bytes.NewReader(body))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdoc := goquery.NewDocumentFromNode(root)\n\tvar csFromMeta string\n\tdoc.Find(\"meta\").EachWithBreak(func(i int, s *goquery.Selection) bool {\n\t\t// <meta http-equiv=\"Content-Type\" content=\"text/html; charset=MS949\"/>\n\t\tif c, exists := s.Attr(\"content\"); exists && strings.Contains(c, \"charset\") {\n\t\t\tif _, params, err := mime.ParseMediaType(c); err == nil {\n\t\t\t\tif cs, ok := params[\"charset\"]; ok {\n\t\t\t\t\tcsFromMeta = strings.ToLower(cs)\n\t\t\t\t\t// Handle Korean charsets.\n\t\t\t\t\tif csFromMeta == \"ms949\" || csFromMeta == \"cp949\" {\n\t\t\t\t\t\tcsFromMeta = \"euc-kr\"\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\n\t\t// <meta charset=\"utf-8\"/>\n\t\tif c, exists := s.Attr(\"charset\"); exists {\n\t\t\tcsFromMeta = c\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t})\n\n\tif csFromMeta == \"\" {\n\t\treturn \"\", fmt.Errorf(\"failed to detect charset\")\n\t}\n\n\treturn csFromMeta, nil\n}", "func NewDummyCipher(b []byte, k int) (Cipher, error) {\n\treturn &DummyCipher{}, nil\n}", "func (w *Wallet) SetPlain(psw, content string) (err error) {\n\n\taesBytes, err := crypto.AESEncrypt(util.Slice(content), passWd)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tw.CipherContent = base64.StdEncoding.EncodeToString(aesBytes)\n\n\taesBytes, err = crypto.AESEncrypt(util.Slice(psw), passWd)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tw.CipherPSW = base64.StdEncoding.EncodeToString(aesBytes)\n\treturn\n}", "func Body(body, contentType, transferEncoding string, opt Options) (string, error) {\n\t// attempt to do some base64-decoding anyway\n\tif decoded, err := base64.URLEncoding.DecodeString(body); err == nil {\n\t\tbody = string(decoded)\n\t}\n\tif decoded, err := base64.StdEncoding.DecodeString(body); err == nil {\n\t\tbody = string(decoded)\n\t}\n\n\tif strings.ToLower(transferEncoding) == \"quoted-printable\" {\n\t\tb, err := ioutil.ReadAll(quotedprintable.NewReader(strings.NewReader(body)))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tbody = string(b)\n\t}\n\n\tct := strings.ToLower(contentType)\n\tif strings.Contains(ct, \"multipart/\") {\n\t\treturn parseMultipart(body, contentType, opt)\n\t}\n\n\tif !opt.SkipHTML && strings.Contains(ct, \"text/html\") {\n\t\tbody = stripHTML(body, opt)\n\t}\n\n\tbody = stripEmbedded(body, opt)\n\tif opt.LineLimit > 0 || opt.ColLimit > 0 {\n\t\tlines := strings.Split(body, \"\\n\")\n\t\tif len(lines) > opt.LineLimit {\n\t\t\tlines = lines[:opt.LineLimit]\n\t\t}\n\t\tfor kk, l := range lines {\n\t\t\tif len(l) > opt.ColLimit {\n\t\t\t\tlines[kk] = l[:opt.ColLimit]\n\t\t\t}\n\t\t}\n\t\tbody = strings.Join(lines, \"\\n\")\n\t}\n\treturn body, nil\n}", "func PlainText(h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\th.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func FromMultipart(body []byte, boundary string) Mimes {\n\tmi := make(Mimes, 0, 10)\n\tsr := bytes.NewReader(body)\n\tmr := multipart.NewReader(sr, boundary)\n\tfor {\n\t\tp, err := mr.NextPart()\n\t\tif err == io.EOF {\n\t\t\treturn mi\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Printf(\"mimedata.IsMultipart: malformed multipart MIME: %v\\n\", err)\n\t\t\treturn mi\n\t\t}\n\t\tb, err := ioutil.ReadAll(p)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"mimedata.IsMultipart: bad ReadAll of multipart MIME: %v\\n\", err)\n\t\t\treturn mi\n\t\t}\n\t\td := Data{}\n\t\td.Type = p.Header.Get(ContentType)\n\t\tcte := p.Header.Get(ContentTransferEncoding)\n\t\tif cte != \"\" {\n\t\t\tswitch cte {\n\t\t\tcase \"base64\":\n\t\t\t\teb := make([]byte, base64.StdEncoding.DecodedLen(len(b)))\n\t\t\t\tbase64.StdEncoding.Decode(eb, b)\n\t\t\t\tb = eb\n\t\t\t}\n\t\t}\n\t\td.Data = b\n\t\tmi = append(mi, &d)\n\t}\n\treturn mi\n}", "func NewPlain(section string, operation *MetricOperation, success, uniDecode bool) *Plain {\n\toperationSanitized := make([]string, cap(operation.operations))\n\tfor k, v := range operation.operations {\n\t\toperationSanitized[k] = SanitizeMetricName(v, uniDecode)\n\t}\n\treturn &Plain{SanitizeMetricName(section, uniDecode), strings.Join(operationSanitized, \".\"), success}\n}", "func New(in []byte) (*SecurityTxt, error) {\n\tmsg, err := NewSignedMessage(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxt := &SecurityTxt{\n\t\tsigned: msg.Signed(),\n\t}\n\n\t// Note: try and collect as many fields as possible and as many errors as possible\n\t// Output should be human-readable error report.\n\n\terr = Parse(msg.Message(), txt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Caller should deal with parsing errors\n\treturn txt, nil\n}", "func (b *Builder) AddTextPlain(text []byte) {\n\tb.AddTextPart(text)\n}", "func PlainParser(r io.Reader, set func(name, value string) error) error {\n\ts := bufio.NewScanner(r)\n\tfor s.Scan() {\n\t\tline := strings.TrimSpace(s.Text())\n\t\tif line == \"\" {\n\t\t\tcontinue // skip empties\n\t\t}\n\n\t\tif line[0] == '#' {\n\t\t\tcontinue // skip comments\n\t\t}\n\n\t\tvar (\n\t\t\tname string\n\t\t\tvalue string\n\t\t\tindex = strings.IndexRune(line, ' ')\n\t\t)\n\t\tif index < 0 {\n\t\t\tname, value = line, \"true\" // boolean option\n\t\t} else {\n\t\t\tname, value = line[:index], strings.TrimSpace(line[index:])\n\t\t}\n\n\t\tif i := strings.Index(value, \" #\"); i >= 0 {\n\t\t\tvalue = strings.TrimSpace(value[:i])\n\t\t}\n\n\t\tif err := set(name, value); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func PlainParser(r io.Reader, set func(name, value string) error) error {\n\ts := bufio.NewScanner(r)\n\tfor s.Scan() {\n\t\tline := strings.TrimSpace(s.Text())\n\t\tif line == \"\" {\n\t\t\tcontinue // skip empties\n\t\t}\n\n\t\tif line[0] == '#' {\n\t\t\tcontinue // skip comments\n\t\t}\n\n\t\tvar (\n\t\t\tname string\n\t\t\tvalue string\n\t\t\tindex = strings.IndexRune(line, ' ')\n\t\t)\n\t\tif index < 0 {\n\t\t\tname, value = line, \"true\" // boolean option\n\t\t} else {\n\t\t\tname, value = line[:index], strings.TrimSpace(line[index:])\n\t\t}\n\n\t\tif i := strings.Index(value, \" #\"); i >= 0 {\n\t\t\tvalue = strings.TrimSpace(value[:i])\n\t\t}\n\n\t\tif err := set(name, value); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn s.Err()\n}", "func NewCorrupter(w io.Writer) *Corrupter {\n\treturn &Corrupter{w: w, b: make([]byte, utf8.MaxRune)}\n}", "func (p *Plain) Parse(data []byte) (T, error) {\n\tt := newPlainT(p.archetypes)\n\n\t//convert to string and remove spaces according to unicode\n\tstr := strings.TrimRightFunc(string(data), unicode.IsSpace)\n\n\t//creat element\n\te := NewElement(str)\n\n\t//set it as single table value\n\tt.Set(\".0\", e)\n\n\treturn t, nil\n}", "func From(s string) *Buffer {\n\treturn &Buffer{b: []byte(s)}\n}", "func FromXML(content []byte) string {\n\tif cset := fromXML(content); cset != \"\" {\n\t\treturn cset\n\t}\n\treturn FromPlain(content)\n}", "func FromBytes(content []byte, pkg string, w io.Writer) error {\n\tbundle := i18n.NewBundle(language.English)\n\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\n\t// Load source language\n\tmessageFile, err := bundle.ParseMessageFileBytes(content, \"en.json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn generate(messageFile, pkg, w)\n}", "func StringFromCharset(length int, charset string) (string, error) {\n\tresult := make([]byte, length) // Random string to return\n\tcharsetlen := big.NewInt(int64(len(charset)))\n\n\tfor i := 0; i < length; i++ {\n\t\tb, err := rand.Int(rand.Reader, charsetlen)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tr := int(b.Int64())\n\t\tresult[i] = charset[r]\n\t}\n\n\treturn string(result), nil\n}", "func (p Piece) GetPlain() Piece {\n\treturn p & 0xf\n}", "func RejectPlain(pw string) (EncodedPasswd, error) {\n\treturn nil, fmt.Errorf(\"plain password rejected: %s\", pw)\n}", "func (b *Builder) Plain(s string) *Builder {\n\tb.message.WriteString(s)\n\treturn b\n}", "func NewBuffer(data string) Buffer {\n\tif len(data) == 0 {\n\t\treturn nilBuffer\n\t}\n\tvar (\n\t\tidx = 0\n\t\tbuf8 = make([]byte, 0, len(data))\n\t\tbuf16 []uint16\n\t\tbuf32 []rune\n\t)\n\tfor idx < len(data) {\n\t\tr, s := utf8.DecodeRuneInString(data[idx:])\n\t\tidx += s\n\t\tif r < utf8.RuneSelf {\n\t\t\tbuf8 = append(buf8, byte(r))\n\t\t\tcontinue\n\t\t}\n\t\tif r <= 0xffff {\n\t\t\tbuf16 = make([]uint16, len(buf8), len(data))\n\t\t\tfor i, v := range buf8 {\n\t\t\t\tbuf16[i] = uint16(v)\n\t\t\t}\n\t\t\tbuf8 = nil\n\t\t\tbuf16 = append(buf16, uint16(r))\n\t\t\tgoto copy16\n\t\t}\n\t\tbuf32 = make([]rune, len(buf8), len(data))\n\t\tfor i, v := range buf8 {\n\t\t\tbuf32[i] = rune(uint32(v))\n\t\t}\n\t\tbuf8 = nil\n\t\tbuf32 = append(buf32, r)\n\t\tgoto copy32\n\t}\n\treturn &asciiBuffer{\n\t\tarr: buf8,\n\t}\ncopy16:\n\tfor idx < len(data) {\n\t\tr, s := utf8.DecodeRuneInString(data[idx:])\n\t\tidx += s\n\t\tif r <= 0xffff {\n\t\t\tbuf16 = append(buf16, uint16(r))\n\t\t\tcontinue\n\t\t}\n\t\tbuf32 = make([]rune, len(buf16), len(data))\n\t\tfor i, v := range buf16 {\n\t\t\tbuf32[i] = rune(uint32(v))\n\t\t}\n\t\tbuf16 = nil\n\t\tbuf32 = append(buf32, r)\n\t\tgoto copy32\n\t}\n\treturn &basicBuffer{\n\t\tarr: buf16,\n\t}\ncopy32:\n\tfor idx < len(data) {\n\t\tr, s := utf8.DecodeRuneInString(data[idx:])\n\t\tidx += s\n\t\tbuf32 = append(buf32, r)\n\t}\n\treturn &supplementalBuffer{\n\t\tarr: buf32,\n\t}\n}", "func NewTextData(text string) *Data {\n\treturn &Data{TextPlain, []byte(text)}\n}", "func (m MAC) PlainString() string {\n\tconst hexDigit = \"0123456789abcdef\"\n\tbuf := make([]byte, 0, len(m)*2)\n\tfor _, b := range m {\n\t\tbuf = append(buf, hexDigit[b>>4])\n\t\tbuf = append(buf, hexDigit[b&0xF])\n\t}\n\treturn string(buf)\n}", "func TestLoadStandardFontEncodings(t *testing.T) {\n\traw := `\n\t1 0 obj\n\t<< /Type /Font\n\t\t/BaseFont /Courier\n\t\t/Subtype /Type1\n\t>>\n\tendobj\n\t`\n\n\tr := model.NewReaderForText(raw)\n\n\terr := r.ParseIndObjSeries()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed loading indirect object series: %v\", err)\n\t}\n\n\t// Load the field from object number 1.\n\tobj, err := r.GetIndirectObjectByNumber(1)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to parse indirect obj (%s)\", err)\n\t}\n\n\tfont, err := model.NewPdfFontFromPdfObject(obj)\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %v\", err)\n\t}\n\n\tstr := \"Aabcdefg0123456790*\"\n\tfor _, r := range str {\n\t\t_, has := font.GetRuneMetrics(r)\n\t\tif !has {\n\t\t\tt.Fatalf(\"Loaded simple font not having glyph char metrics for %v\", r)\n\t\t}\n\t}\n}", "func PlainText(s string) ([]store.Measurement, error) {\n\tnow := time.Now()\n\tret := []store.Measurement{}\n\tlines := strings.Split(s, \"\\n\")\n\tfor _, l := range lines {\n\t\tparts := strings.Split(l, \" \")\n\t\tif len(parts) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"Invalid input line format: %q\", l)\n\t\t}\n\t\tkey := parts[0]\n\t\tvalue, err := strconv.ParseInt(parts[1], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid value format: %q\", l)\n\t\t}\n\t\tret = append(ret, store.Measurement{\n\t\t\tKey: key,\n\t\t\tPoint: ts.Point{\n\t\t\t\tTimestamp: now.Unix(),\n\t\t\t\tValue: value,\n\t\t\t},\n\t\t})\n\t}\n\treturn ret, nil\n}", "func PlainText(content string) TextLit {\n\treturn TextLit{Suffix: content}\n}", "func NewText(text string) Mimes {\n\tmd := NewTextData(text)\n\tmi := make(Mimes, 1)\n\tmi[0] = md\n\treturn mi\n}", "func NewReaderFromText(name string, text string) *Reader {\n\tnoExternalNewlines := strings.Trim(text, \"\\n\")\n\treturn &Reader{\n\t\tname: &name,\n\t\tlines: strings.Split(noExternalNewlines, \"\\n\"),\n\t\tlock: &sync.Mutex{},\n\t}\n}", "func (downloader *HTTPDownloader) changeCharsetEncodingAuto(contentTypeStr string, sor io.ReadCloser) string {\r\n\tvar err error\r\n\tdestReader, err := charset.NewReader(sor, contentTypeStr)\r\n\r\n\tif err != nil {\r\n\t\tmlog.LogInst().LogError(err.Error())\r\n\t\tdestReader = sor\r\n\t}\r\n\r\n\tvar sorbody []byte\r\n\tif sorbody, err = ioutil.ReadAll(destReader); err != nil {\r\n\t\tmlog.LogInst().LogError(err.Error())\r\n\t\t// For gb2312, an error will be returned.\r\n\t\t// Error like: simplifiedchinese: invalid GBK encoding\r\n\t\t// return \"\"\r\n\t}\r\n\t//e,name,certain := charset.DetermineEncoding(sorbody,contentTypeStr)\r\n\tbodystr := string(sorbody)\r\n\r\n\treturn bodystr\r\n}", "func Test_fromNetASCII(t *testing.T) {\n\tvar tests = []struct {\n\t\tin []byte\n\t\tout []byte\n\t}{\n\t\t{\n\t\t\tin: nil,\n\t\t\tout: nil,\n\t\t},\n\t\t{\n\t\t\tin: []byte{'a', 'b', 'c'},\n\t\t\tout: []byte{'a', 'b', 'c'},\n\t\t},\n\t\t{\n\t\t\tin: []byte{'a', '\\r', '\\n', 'b', '\\r', '\\n', 'c'},\n\t\t\tout: []byte{'a', '\\n', 'b', '\\n', 'c'},\n\t\t},\n\t\t{\n\t\t\tin: []byte{'a', '\\r', 0, 'b', '\\r', 0, 'c'},\n\t\t\tout: []byte{'a', '\\r', 'b', '\\r', 'c'},\n\t\t},\n\t\t{\n\t\t\tin: []byte{'a', '\\r', 0, 'b', '\\r', '\\n', 'c'},\n\t\t\tout: []byte{'a', '\\r', 'b', '\\n', 'c'},\n\t\t},\n\t\t// TODO(mdlayher): determine if it possible for a carriage return to\n\t\t// be the last character in a buffer. For the time being, we perform\n\t\t// no conversion if this is the case.\n\t\t{\n\t\t\tin: []byte{'a', '\\r'},\n\t\t\tout: []byte{'a', '\\r'},\n\t\t},\n\t}\n\n\tfor i, tt := range tests {\n\t\tif want, got := tt.out, fromNetASCII(tt.in); !bytes.Equal(want, got) {\n\t\t\tt.Fatalf(\"[%02d] unexpected fromNetASCII conversion:\\n- want: %v\\n- got: %v\",\n\t\t\t\ti, want, got)\n\t\t}\n\t}\n}", "func NewReader(r io.Reader, cpn ...string) (io.Reader, error) {\n\tif r == nil {\n\t\treturn r, errInputIsNil\n\t}\n\ttmpReader := bufio.NewReader(r)\n\tvar err error\n\tcp := ASCII\n\tif len(cpn) > 0 {\n\t\tcp = codepageByName(cpn[0])\n\t}\n\tif cp == ASCII {\n\t\tcp, err = CodepageDetect(tmpReader)\n\t}\n\t//TODO внимательно нужно посмотреть что может вернуть CodepageDetect()\n\t//эти случаи обработать, например через func unsupportedCodepageToDecode(cp)\n\tswitch {\n\tcase (cp == UTF32) || (cp == UTF32BE) || (cp == UTF32LE):\n\t\treturn r, errUnsupportedCodepage\n\tcase cp == ASCII: // кодировку определить не удалось, неизвестную кодировку возвращаем как есть\n\t\treturn r, errUnknown\n\tcase err != nil: // и если ошибка при чтении, то возвращаем как есть\n\t\treturn r, err\n\t}\n\n\tif checkBomExist(tmpReader) {\n\t\t//ошибку не обрабатываем, если мы здесь, то эти байты мы уже читали\n\t\ttmpReader.Read(make([]byte, cp.BomLen())) // считываем в никуда количество байт занимаемых BOM этой кодировки\n\t}\n\tif cp == UTF8 {\n\t\treturn tmpReader, nil // когда удалили BOM тогда можно вернуть UTF-8, ведь его конвертировать не нужно\n\t}\n\t//ошибку не обрабатываем, htmlindex.Get() возвращает ошибку только если не найдена кодировка, здесь это уже невозможно\n\t//здесь cp может содержать только кодировки имеющиеся в htmlindex\n\te, _ := htmlindex.Get(cp.String())\n\tr = transform.NewReader(tmpReader, e.NewDecoder())\n\treturn r, nil\n}", "func Plain() Spiff {\n\treturn &spiff{\n\t\tkey: \"\",\n\t\tmode: MODE_DEFAULT,\n\t\tfeatures: features.FeatureFlags{},\n\t\tregistry: dynaml.DefaultRegistry(),\n\t}\n}", "func parseText(strBytes []byte) (string, error) {\n\tif len(strBytes) == 0 {\n\t\treturn \"\", errors.New(\"empty id3 frame\")\n\t}\n\tif len(strBytes) < 2 {\n\t\t// Not an error according to the spec (because at least 1 byte big)\n\t\treturn \"\", nil\n\t}\n\tencoding, strBytes := strBytes[0], strBytes[1:]\n\n\tswitch encoding {\n\tcase 0: // ISO-8859-1 text.\n\t\treturn parseIso8859(strBytes), nil\n\n\tcase 1: // UTF-16 with BOM.\n\t\treturn parseUtf16WithBOM(strBytes)\n\n\tcase 2: // UTF-16BE without BOM.\n\t\treturn parseUtf16(strBytes, binary.BigEndian)\n\n\tcase 3: // UTF-8 text.\n\t\treturn parseUtf8(strBytes)\n\n\tdefault:\n\t\treturn \"\", id3v24Err(\"invalid encoding byte %x\", encoding)\n\t}\n}", "func UnmarshalText(text []byte) (f *Filter, err error) {\n\tr := bytes.NewBuffer(text)\n\tk, n, m, err := unmarshalTextHeader(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeys, err := newKeysBlank(k)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = unmarshalTextKeys(r, keys)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbits, err := newBits(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = unmarshalTextBits(r, bits)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf, err = newWithKeysAndBits(m, keys, bits, n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = unmarshalAndCheckTextHash(r, f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f, nil\n}", "func DefaultCharsetForType(tp byte) (defaultCharset string, defaultCollation string) {\n\tswitch tp {\n\tcase mysql.TypeVarString, mysql.TypeString, mysql.TypeVarchar:\n\t\t// Default charset for string types is utf8mb4.\n\t\treturn mysql.DefaultCharset, mysql.DefaultCollationName\n\t}\n\treturn charset.CharsetBin, charset.CollationBin\n}", "func fromgb(in []byte) string {\n\tout := make([]byte, len(in)*4)\n\n\t_, _, err := iconv.Convert(in, out, \"gb2312\", \"utf-8\")\n\tcheck(err)\n\treturn strings.Trim(string(out), \" \\n\\r\\x00\")\n}", "func NewTextMessageFromString(payload string) Message {\n\treturn NewTextMessage([]byte(payload))\n}", "func testTxtData(t *testing.T) {\n\ttxtData = discovery.TxtData{\n\t\tID: clientCluster.clusterId.GetClusterID(),\n\t\tNamespace: \"default\",\n\t\tApiUrl: \"https://\" + serverCluster.cfg.Host,\n\t\tAllowUntrustedCA: true,\n\t}\n\ttxt, err := txtData.Encode()\n\tassert.NilError(t, err, \"Error encoding txtData to DNS format\")\n\n\ttxtData2, err := discovery.Decode(\"127.0.0.1\", strings.Split(serverCluster.cfg.Host, \":\")[1], txt)\n\tassert.NilError(t, err, \"Error decoding txtData from DNS format\")\n\tassert.Equal(t, txtData, *txtData2, \"TxtData before and after encoding doesn't match\")\n}", "func NewSimpleTextEncoder(baseName string, differences map[CharCode]GlyphName) (SimpleEncoder, error) {\n\tfnc, ok := simple[baseName]\n\tif !ok {\n\t\tcommon.Log.Debug(\"ERROR: NewSimpleTextEncoder. Unknown encoding %q\", baseName)\n\t\treturn nil, errors.New(\"unsupported font encoding\")\n\t}\n\tenc := fnc()\n\tif len(differences) != 0 {\n\t\tenc = ApplyDifferences(enc, differences)\n\t}\n\treturn enc, nil\n}", "func New(beginToken, endToken, separator string, metaTemplates []string) (TemplateEngine, error) {\n\tif len(beginToken) == 0 || len(endToken) == 0 || len(separator) == 0 || len(metaTemplates) == 0 {\n\t\treturn DummyTemplate{}, fmt.Errorf(\"invalid input, beingToken %s, endToken %s, separator = %s , metaTempaltes %v\",\n\t\t\tbeginToken, endToken, separator, metaTemplates)\n\t}\n\tt := &TextTemplate{\n\t\tbeginToken: beginToken,\n\t\tendToken: endToken,\n\t\tseparator: separator,\n\t\tmetaTemplates: metaTemplates,\n\t\tdict: map[string]interface{}{},\n\t}\n\n\tif err := t.buildTemplateTree(); err != nil {\n\t\treturn DummyTemplate{}, err\n\t}\n\n\treturn t, nil\n}", "func NewText(pathname string, name dns.Name) *Text {\n\treturn &Text{\n\t\tMemory: NewMemory(),\n\t\tname: name,\n\t\tpathname: pathname,\n\t}\n}", "func detectCharEncode(body []byte) CharEncode {\n\tdet := chardet.NewTextDetector()\n\tres, err := det.DetectBest(body)\n\tif err != nil {\n\t\treturn CharUnknown\n\t}\n\treturn typeOfCharEncode(res.Charset)\n}", "func Parse(src []byte) (*Font, error) {\n\tface, err := truetype.Parse(bytes.NewReader(src))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed parsing truetype font: %w\", err)\n\t}\n\treturn &Font{\n\t\tfont: face,\n\t}, nil\n}", "func CreatePlainCrypt() *PlainCrypt {\n\treturn &PlainCrypt{}\n}", "func TestEncodeAndDecode(t *testing.T) {\n\tt.Parallel()\n\n\tcases := []struct {\n\t\tname string\n\t\tin string\n\t\tencoding Scheme\n\t\tout string\n\t}{\n\t\t{\n\t\t\tname: \"F1F2F3 v1\",\n\t\t\tin: \"\\xF1\\xF2\\xF3\",\n\t\t\tencoding: V1,\n\t\t\tout: \"wUAn\",\n\t\t},\n\t\t{\n\t\t\tname: \"F1F2F3 v2\",\n\t\t\tin: \"\\xF1\\xF2\\xF3\",\n\t\t\tencoding: V2,\n\t\t\tout: \"wUAn\",\n\t\t},\n\t\t{\n\t\t\tname: \"empty string v1\",\n\t\t\tin: \"\",\n\t\t\tencoding: V1,\n\t\t\tout: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"empty string v2\",\n\t\t\tin: \"\",\n\t\t\tencoding: V1,\n\t\t\tout: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"single char v1\",\n\t\t\tin: \"\\x00\",\n\t\t\tencoding: V1,\n\t\t\tout: \"00\",\n\t\t},\n\t\t{\n\t\t\tname: \"single char v2\",\n\t\t\tin: \"\\x00\",\n\t\t\tencoding: V2,\n\t\t\tout: \"..\",\n\t\t},\n\t\t{\n\t\t\tname: \"random string v1\",\n\t\t\tin: \"\\x67\\x9a\\x5c\\x48\\xbe\\x97\\x27\\x75\\xdf\\x6a\",\n\t\t\tencoding: V1,\n\t\t\tout: \"OtdRHAuM9rMUPV\",\n\t\t},\n\t\t{\n\t\t\tname: \"random string v2\",\n\t\t\tin: \"\\x67\\x9a\\x5c\\x48\\xbe\\x97\\x27\\x75\\xdf\\x6a\",\n\t\t\tencoding: V2,\n\t\t\tout: \"OtdRHAuM8rMUPV\",\n\t\t},\n\t}\n\n\tfor _, tt := range cases {\n\t\ttt := tt\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\tencoding := encodings[tt.encoding]\n\n\t\t\tin := []byte(tt.in)\n\t\t\tactual, err := Encode(encoding, in)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"unexpected error for subtest %q: %s\", tt.name, err)\n\t\t\t}\n\t\t\texpected := tt.out\n\n\t\t\tif diff := cmp.Diff(expected, actual); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected diff during encoding for subtest %q (-want +got): %s\", tt.name, diff)\n\t\t\t}\n\t\t})\n\t}\n}", "func NewFzText() *FzText {\n\treturn (*FzText)(allocFzTextMemory(1))\n}", "func NewTextDataBytes(text []byte) *Data {\n\treturn &Data{TextPlain, text}\n}", "func FromStringUnsafe(s string) []byte {\n\tvar b []byte\n\tpb := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n\tps := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\tpb.Data = ps.Data\n\tpb.Len = ps.Len\n\tpb.Cap = ps.Len\n\treturn b\n}", "func (be *CryptFS) PlainBS() uint64 {\n\treturn be.plainBS\n}", "func (iv *InitialValueMode) UnmarshalText(in []byte) error {\n\tswitch mode := InitialValueMode(in); mode {\n\tcase InitialValueModeAuto,\n\t\tInitialValueModeDrop,\n\t\tInitialValueModeKeep:\n\t\t*iv = mode\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid initial value mode %q\", mode)\n\t}\n}", "func FromLocal(fn string) ([]byte, error) {\n\tlog.Print(\"Reading from file\")\n\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to open file: %s\\n\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tdefer cleanup(f)\n\tr := bufio.NewScanner(f)\n\n\treturn r.Bytes(), nil\n}", "func (t *TopicType) UnmarshalText(input []byte) error {\n\treturn hexutil.UnmarshalFixedText(\"Topic\", input, t[:])\n}", "func TestParseText(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\ttext string\n\t\texpected *Digest\n\t\texpectedErr error\n\t}{\n\t\t// Strings.\n\n\t\t{\n\t\t\tname: \"short and long strings\",\n\t\t\ttext: \"\\\"short string\\\"\\n'''long'''\\n'''string'''\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tString{text: []byte(\"short string\")},\n\t\t\t\tString{text: []byte(\"longstring\")},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"escaped strings\",\n\t\t\ttext: `\"H\\x48\\u0048\\U00000048\" '''h\\x68\\u0068\\U00000068'''`,\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tString{text: []byte(\"HHHH\")},\n\t\t\t\tString{text: []byte(\"hhhh\")},\n\t\t\t}},\n\t\t},\n\n\t\t// Symbols\n\n\t\t{\n\t\t\tname: \"symbol\",\n\t\t\ttext: \"'short symbol'\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tSymbol{text: []byte(\"short symbol\")},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"escaped symbols\",\n\t\t\ttext: `'H\\x48\\u0048\\U00000048'`,\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tSymbol{text: []byte(\"HHHH\")},\n\t\t\t}},\n\t\t},\n\n\t\t// Numeric\n\n\t\t{\n\t\t\tname: \"infinity\",\n\t\t\ttext: \"inf +inf -inf\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\t// \"inf\" must have a plus or minus on it to be considered a number.\n\t\t\t\tSymbol{text: []byte(\"inf\")},\n\t\t\t\tFloat{isSet: true, text: []byte(\"+inf\")},\n\t\t\t\tFloat{isSet: true, text: []byte(\"-inf\")},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"integers\",\n\t\t\ttext: \"0 -1 1_2_3 0xFf -0xFf 0Xe_d 0b10 -0b10 0B1_0\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tInt{isSet: true, text: []byte(\"0\")},\n\t\t\t\tInt{isSet: true, isNegative: true, text: []byte(\"-1\")},\n\t\t\t\tInt{isSet: true, text: []byte(\"1_2_3\")},\n\t\t\t\tInt{isSet: true, base: intBase16, text: []byte(\"0xFf\")},\n\t\t\t\tInt{isSet: true, isNegative: true, base: intBase16, text: []byte(\"-0xFf\")},\n\t\t\t\tInt{isSet: true, base: intBase16, text: []byte(\"0Xe_d\")},\n\t\t\t\tInt{isSet: true, base: intBase2, text: []byte(\"0b10\")},\n\t\t\t\tInt{isSet: true, isNegative: true, base: intBase2, text: []byte(\"-0b10\")},\n\t\t\t\tInt{isSet: true, base: intBase2, text: []byte(\"0B1_0\")},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"decimals\",\n\t\t\ttext: \"0. 0.123 -0.12d4 0D-0 0d+0 12_34.56_78\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tDecimal{isSet: true, text: []byte(\"0.\")},\n\t\t\t\tDecimal{isSet: true, text: []byte(\"0.123\")},\n\t\t\t\tDecimal{isSet: true, text: []byte(\"-0.12d4\")},\n\t\t\t\tDecimal{isSet: true, text: []byte(\"0D-0\")},\n\t\t\t\tDecimal{isSet: true, text: []byte(\"0d+0\")},\n\t\t\t\tDecimal{isSet: true, text: []byte(\"12_34.56_78\")},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"floats\",\n\t\t\ttext: \"0E0 0.12e-4 -0e+0\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tFloat{isSet: true, text: []byte(\"0E0\")},\n\t\t\t\tFloat{isSet: true, text: []byte(\"0.12e-4\")},\n\t\t\t\tFloat{isSet: true, text: []byte(\"-0e+0\")},\n\t\t\t}},\n\t\t},\n\n\t\t{\n\t\t\tname: \"dates\",\n\t\t\ttext: \"2019T 2019-10T 2019-10-30 2019-10-30T\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tTimestamp{precision: TimestampPrecisionYear, text: []byte(\"2019T\")},\n\t\t\t\tTimestamp{precision: TimestampPrecisionMonth, text: []byte(\"2019-10T\")},\n\t\t\t\tTimestamp{precision: TimestampPrecisionDay, text: []byte(\"2019-10-30\")},\n\t\t\t\tTimestamp{precision: TimestampPrecisionDay, text: []byte(\"2019-10-30T\")},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"times\",\n\t\t\ttext: \"2019-10-30T22:30Z 2019-10-30T12:30:59+02:30 2019-10-30T12:30:59.999-02:30\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tTimestamp{precision: TimestampPrecisionMinute, text: []byte(\"2019-10-30T22:30Z\")},\n\t\t\t\tTimestamp{precision: TimestampPrecisionSecond, text: []byte(\"2019-10-30T12:30:59+02:30\")},\n\t\t\t\tTimestamp{precision: TimestampPrecisionMillisecond3, text: []byte(\"2019-10-30T12:30:59.999-02:30\")},\n\t\t\t}},\n\t\t},\n\n\t\t// Binary.\n\n\t\t{\n\t\t\tname: \"short blob\",\n\t\t\ttext: \"{{+AB/}}\",\n\t\t\texpected: &Digest{values: []Value{Blob{text: []byte(\"+AB/\")}}},\n\t\t},\n\t\t{\n\t\t\tname: \"padded blob with whitespace\",\n\t\t\ttext: \"{{ + A\\nB\\t/abc= }}\",\n\t\t\texpected: &Digest{values: []Value{Blob{text: []byte(\"+AB/abc=\")}}},\n\t\t},\n\t\t{\n\t\t\tname: \"short clob\",\n\t\t\ttext: `{{ \"A\\n\" }}`,\n\t\t\texpected: &Digest{values: []Value{Clob{text: []byte(\"A\\n\")}}},\n\t\t},\n\t\t{\n\t\t\tname: \"long clob\",\n\t\t\ttext: \"{{ '''+AB/''' }}\",\n\t\t\texpected: &Digest{values: []Value{Clob{text: []byte(\"+AB/\")}}},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple long clobs\",\n\t\t\ttext: \"{{ '''A\\\\nB'''\\n'''foo''' }}\",\n\t\t\texpected: &Digest{values: []Value{Clob{text: []byte(\"A\\nBfoo\")}}},\n\t\t},\n\t\t{\n\t\t\tname: \"escaped clobs\",\n\t\t\ttext: `{{\"H\\x48\\x48H\"}} {{'''h\\x68\\x68h'''}}`,\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tClob{text: []byte(\"HHHH\")},\n\t\t\t\tClob{text: []byte(\"hhhh\")},\n\t\t\t}},\n\t\t},\n\n\t\t// Containers\n\n\t\t{\n\t\t\tname: \"struct with symbol to symbol\",\n\t\t\ttext: `{symbol1: 'symbol', 'symbol2': symbol}`,\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tStruct{fields: []StructField{\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"symbol1\")}, Value: Symbol{quoted: true, text: []byte(\"symbol\")}},\n\t\t\t\t\t{Symbol: Symbol{quoted: true, text: []byte(\"symbol2\")}, Value: Symbol{text: []byte(\"symbol\")}},\n\t\t\t\t}},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"struct with annotated field\",\n\t\t\ttext: `{symbol1: ann::'symbol'}`,\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tStruct{fields: []StructField{\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"symbol1\")}, Value: Symbol{annotations: []Symbol{{text: []byte(\"ann\")}}, quoted: true, text: []byte(\"symbol\")}},\n\t\t\t\t}},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"struct with doubly-annotated field\",\n\t\t\ttext: `{symbol1: ann1::ann2::'symbol'}`,\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tStruct{fields: []StructField{\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"symbol1\")}, Value: Symbol{annotations: []Symbol{{text: []byte(\"ann1\")}, {text: []byte(\"ann2\")}}, quoted: true, text: []byte(\"symbol\")}},\n\t\t\t\t}},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"struct with comments between symbol and value\",\n\t\t\ttext: \"{abc : // Line\\n/* Block */ {{ \\\"A\\\\n\\\" }}}\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tStruct{fields: []StructField{\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"abc\")}, Value: Clob{text: []byte(\"A\\n\")}},\n\t\t\t\t}},\n\t\t\t}},\n\t\t},\n\n\t\t{\n\t\t\tname: \"struct with empty list, struct, and sexp\",\n\t\t\ttext: \"{a:[], b:{}, c:()}\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tStruct{fields: []StructField{\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"a\")}, Value: List{}},\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"b\")}, Value: Struct{}},\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"c\")}, Value: SExp{}},\n\t\t\t\t}},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"list with empty list, struct, and sexp\",\n\t\t\ttext: \"[[], {}, ()]\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tList{values: []Value{List{}, Struct{}, SExp{}}},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"list of things\",\n\t\t\ttext: \"[a, 1, ' ', {}, () /* comment */ ]\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tList{values: []Value{\n\t\t\t\t\tSymbol{text: []byte(\"a\")},\n\t\t\t\t\tInt{isSet: true, text: []byte(\"1\")},\n\t\t\t\t\tSymbol{text: []byte(\" \")},\n\t\t\t\t\tStruct{},\n\t\t\t\t\tSExp{},\n\t\t\t\t}},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"struct of things\",\n\t\t\ttext: \"{'a' : 1 , s:'', 'st': {}, \\n/* comment */lst:[],\\\"sexp\\\":()}\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tStruct{fields: []StructField{\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"a\")}, Value: Int{isSet: true, text: []byte(\"1\")}},\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"s\")}, Value: Symbol{text: []byte(\"\")}},\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"st\")}, Value: Struct{}},\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"lst\")}, Value: List{}},\n\t\t\t\t\t{Symbol: Symbol{text: []byte(\"sexp\")}, Value: SExp{}},\n\t\t\t\t}},\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"s-expression of things\",\n\t\t\ttext: \"(a+b/c<( j * k))\",\n\t\t\texpected: &Digest{values: []Value{\n\t\t\t\tSExp{values: []Value{\n\t\t\t\t\tSymbol{text: []byte(\"a\")},\n\t\t\t\t\tSymbol{text: []byte(\"+\")},\n\t\t\t\t\tSymbol{text: []byte(\"b\")},\n\t\t\t\t\tSymbol{text: []byte(\"/\")},\n\t\t\t\t\tSymbol{text: []byte(\"c\")},\n\t\t\t\t\tSymbol{text: []byte(\"<\")},\n\t\t\t\t\tSExp{values: []Value{\n\t\t\t\t\t\tSymbol{text: []byte(\"j\")},\n\t\t\t\t\t\tSymbol{text: []byte(\"*\")},\n\t\t\t\t\t\tSymbol{text: []byte(\"k\")},\n\t\t\t\t\t}},\n\t\t\t\t}},\n\t\t\t}},\n\t\t},\n\n\t\t// Error cases\n\n\t\t{\n\t\t\tname: \"list starts with comma\",\n\t\t\ttext: \"[, [], {}, ()]\",\n\t\t\texpectedErr: errors.New(\"parsing line 1 - list may not start with a comma\"),\n\t\t},\n\t\t{\n\t\t\tname: \"struct starts with comma\",\n\t\t\ttext: \"{, a:1}\",\n\t\t\texpectedErr: errors.New(\"parsing line 1 - struct may not start with a comma\"),\n\t\t},\n\t\t{\n\t\t\tname: \"list without commas\",\n\t\t\ttext: \"[[] {} ()]\",\n\t\t\texpectedErr: errors.New(\"parsing line 1 - list items must be separated by commas\"),\n\t\t},\n\t\t{\n\t\t\tname: \"struct without commas\",\n\t\t\ttext: \"{a:1 b:2}\",\n\t\t\texpectedErr: errors.New(\"parsing line 1 - struct fields must be separated by commas\"),\n\t\t},\n\t}\n\tfor _, tst := range tests {\n\t\ttest := tst\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tdigest, err := ParseText(strings.NewReader(test.text))\n\t\t\tif diff := cmpDigests(test.expected, digest); diff != \"\" {\n\t\t\t\tt.Logf(\"expected: %#v\", test.expected)\n\t\t\t\tt.Logf(\"found: %#v\", digest)\n\t\t\t\tt.Error(\"(-expected, +found)\", diff)\n\t\t\t}\n\t\t\tif diff := cmpErrs(test.expectedErr, err); diff != \"\" {\n\t\t\t\tt.Error(\"err: (-expected, +found)\", diff)\n\t\t\t}\n\t\t})\n\t}\n}", "func New() *Text {\n\treturn &Text{}\n}", "func textEncoderDummy(w io.Writer, props properties, text []byte) (textEncoder, error) {\n\t_, err := w.Write(text)\n\treturn textEncoderDummy, err\n}", "func NewColouredTextTypeChunk(text string, face font.Face, colour uint32) TypeChunk {\n\trunes := []rune{}\n\tfor _, r := range text {\n\t\trunes = append(runes, r)\n\t}\n\treturn fyTextTypeChunk{\n\t\trunes,\n\t\tface,\n\t\tcolour,\n\t}\n}", "func ISO8859_1toUTF8(in string) (out string, err error) {\n\t// create a Reader using the input string as Reader and ISO8859 decoder\n\tdecoded := transform.NewReader(strings.NewReader(in), charmap.ISO8859_1.NewDecoder())\n\tdecodedBytes, err := ioutil.ReadAll(decoded)\n\tif err != nil {\n\t\treturn\n\t}\n\tout = string(decodedBytes)\n\treturn\n}", "func PlainText(w http.ResponseWriter, r *http.Request, v string) {\n\trender.PlainText(w, r, v)\n}", "func NewFromCSV(headers, columns []string) types.Document {\n\tfb := NewFieldBuffer()\n\tfor i, h := range headers {\n\t\tif i >= len(columns) {\n\t\t\tbreak\n\t\t}\n\n\t\tfb.Add(h, types.NewTextValue(columns[i]))\n\t}\n\n\treturn fb\n}", "func (c *Plain) Safe() bool {\n\treturn true\n}", "func isText(s []byte) bool {\n\tconst max = 1024 // at least utf8.UTFMax\n\tif len(s) > max {\n\t\ts = s[0:max]\n\t}\n\tfor i, c := range string(s) {\n\t\tif i+utf8.UTFMax > len(s) {\n\t\t\t// last char may be incomplete - ignore\n\t\t\tbreak\n\t\t}\n\t\tif c == 0xFFFD || c < ' ' && c != '\\n' && c != '\\t' && c != '\\f' {\n\t\t\t// decoding error or control character - not a text file\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func convertCP(in string) (out string) {\n\tbuf := new(bytes.Buffer)\n\tw, err := charset.NewWriter(\"windows-1252\", buf)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Fprintf(w, in)\n\tw.Close()\n\n\tout = fmt.Sprintf(\"%s\", buf)\n\treturn out\n}", "func (self *CommitMessagePanelDriver) InitialText(expected *TextMatcher) *CommitMessagePanelDriver {\n\treturn self.Content(expected)\n}", "func (sm *CumulativeMonotonicSumMode) UnmarshalText(in []byte) error {\n\tswitch mode := CumulativeMonotonicSumMode(in); mode {\n\tcase CumulativeMonotonicSumModeToDelta,\n\t\tCumulativeMonotonicSumModeRawValue:\n\t\t*sm = mode\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid cumulative monotonic sum mode %q\", mode)\n\t}\n}", "func (text *Text) Plainf(format string, a ...interface{}) *Text {\n\treturn text.Plain(fmt.Sprintf(format, a...))\n}", "func FormatBytes(src []byte, invalid []byte, invalidWidth int, isJSON, isRaw bool, sep, quote rune) *Value {\n\tres := &Value{\n\t\tTabs: make([][][2]int, 1),\n\t}\n\tvar tmp [4]byte\n\tvar r rune\n\tvar l, w int\n\tfor ; len(src) > 0; src = src[w:] {\n\t\tr, w = rune(src[0]), 1\n\t\t// lazy decode\n\t\tif r >= utf8.RuneSelf {\n\t\t\tr, w = utf8.DecodeRune(src)\n\t\t}\n\t\t// invalid rune decoded\n\t\tif w == 1 && r == utf8.RuneError {\n\t\t\t// replace with invalid (if set), otherwise hex encode\n\t\t\tif invalid != nil {\n\t\t\t\tres.Buf = append(res.Buf, invalid...)\n\t\t\t\tres.Width += invalidWidth\n\t\t\t\tres.Quoted = true\n\t\t\t} else {\n\t\t\t\tres.Buf = append(res.Buf, '\\\\', 'x', lowerhex[src[0]>>4], lowerhex[src[0]&0xf])\n\t\t\t\tres.Width += 4\n\t\t\t\tres.Quoted = true\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// handle json encoding\n\t\tif isJSON {\n\t\t\tswitch r {\n\t\t\tcase '\\t':\n\t\t\t\tres.Buf = append(res.Buf, '\\\\', 't')\n\t\t\t\tres.Width += 2\n\t\t\t\tcontinue\n\t\t\tcase '\\n':\n\t\t\t\tres.Buf = append(res.Buf, '\\\\', 'n')\n\t\t\t\tres.Width += 2\n\t\t\t\tcontinue\n\t\t\tcase '\\\\':\n\t\t\t\tres.Buf = append(res.Buf, '\\\\', '\\\\')\n\t\t\t\tres.Width += 2\n\t\t\t\tcontinue\n\t\t\tcase '\"':\n\t\t\t\tres.Buf = append(res.Buf, '\\\\', '\"')\n\t\t\t\tres.Width += 2\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// handle raw encoding\n\t\tif isRaw {\n\t\t\tn := utf8.EncodeRune(tmp[:], r)\n\t\t\tres.Buf = append(res.Buf, tmp[:n]...)\n\t\t\tres.Width += runewidth.RuneWidth(r)\n\t\t\tswitch {\n\t\t\tcase r == sep:\n\t\t\t\tres.Quoted = true\n\t\t\tcase r == quote && quote != 0:\n\t\t\t\tres.Buf = append(res.Buf, tmp[:n]...)\n\t\t\t\tres.Width += runewidth.RuneWidth(r)\n\t\t\t\tres.Quoted = true\n\t\t\tdefault:\n\t\t\t\tres.Quoted = res.Quoted || unicode.IsSpace(r)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// printable character\n\t\tif strconv.IsGraphic(r) {\n\t\t\tn := utf8.EncodeRune(tmp[:], r)\n\t\t\tres.Buf = append(res.Buf, tmp[:n]...)\n\t\t\tres.Width += runewidth.RuneWidth(r)\n\t\t\tcontinue\n\t\t}\n\t\tswitch r {\n\t\t// escape \\a \\b \\f \\r \\v (Go special characters)\n\t\tcase '\\a':\n\t\t\tres.Buf = append(res.Buf, '\\\\', 'a')\n\t\t\tres.Width += 2\n\t\tcase '\\b':\n\t\t\tres.Buf = append(res.Buf, '\\\\', 'b')\n\t\t\tres.Width += 2\n\t\tcase '\\f':\n\t\t\tres.Buf = append(res.Buf, '\\\\', 'f')\n\t\t\tres.Width += 2\n\t\tcase '\\r':\n\t\t\tres.Buf = append(res.Buf, '\\\\', 'r')\n\t\t\tres.Width += 2\n\t\tcase '\\v':\n\t\t\tres.Buf = append(res.Buf, '\\\\', 'v')\n\t\t\tres.Width += 2\n\t\tcase '\\t':\n\t\t\t// save position\n\t\t\tres.Tabs[l] = append(res.Tabs[l], [2]int{len(res.Buf), res.Width})\n\t\t\tres.Buf = append(res.Buf, '\\t')\n\t\t\tres.Width = 0\n\t\tcase '\\n':\n\t\t\t// save position\n\t\t\tres.Newlines = append(res.Newlines, [2]int{len(res.Buf), res.Width})\n\t\t\tres.Buf = append(res.Buf, '\\n')\n\t\t\tres.Width = 0\n\t\t\t// increase line count\n\t\t\tres.Tabs = append(res.Tabs, nil)\n\t\t\tl++\n\t\tdefault:\n\t\t\tswitch {\n\t\t\t// escape as \\x00\n\t\t\tcase r < ' ':\n\t\t\t\tres.Buf = append(res.Buf, '\\\\', 'x', lowerhex[byte(r)>>4], lowerhex[byte(r)&0xf])\n\t\t\t\tres.Width += 4\n\t\t\t// escape as \\u0000\n\t\t\tcase r > utf8.MaxRune:\n\t\t\t\tr = 0xfffd\n\t\t\t\tfallthrough\n\t\t\tcase r < 0x10000:\n\t\t\t\tres.Buf = append(res.Buf, '\\\\', 'u')\n\t\t\t\tfor s := 12; s >= 0; s -= 4 {\n\t\t\t\t\tres.Buf = append(res.Buf, lowerhex[r>>uint(s)&0xf])\n\t\t\t\t}\n\t\t\t\tres.Width += 6\n\t\t\t// escape as \\U00000000\n\t\t\tdefault:\n\t\t\t\tres.Buf = append(res.Buf, '\\\\', 'U')\n\t\t\t\tfor s := 28; s >= 0; s -= 4 {\n\t\t\t\t\tres.Buf = append(res.Buf, lowerhex[r>>uint(s)&0xf])\n\t\t\t\t}\n\t\t\t\tres.Width += 10\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func (p *TOMLParser) FromBytes(byteData []byte) (interface{}, error) {\n\tvar data interface{}\n\tif err := toml.Unmarshal(byteData, &data); err != nil {\n\t\treturn data, fmt.Errorf(\"could not unmarshal data: %w\", err)\n\t}\n\treturn &BasicSingleDocument{\n\t\tValue: data,\n\t}, nil\n}", "func sanitizeText(str string) string {\n\t// count bytes in output & check whether modification is required\n\tnlen := 0\n\tmustmod := false\n\tfor _, r := range []rune(str) {\n\t\toutrune := cleanRune(r)\n\t\tif outrune != '\\000' {\n\t\t\tnlen++\n\t\t}\n\t\tif outrune != r {\n\t\t\tmustmod = true\n\t\t}\n\t}\n\n\t// if no modification is required, use the original string\n\tif !mustmod {\n\t\treturn str\n\t}\n\n\t// build new string\n\tnstr := make([]byte, nlen)\n\ti := 0\n\tfor _, r := range []rune(str) {\n\t\toutrune := cleanRune(r)\n\t\tif outrune != '\\000' {\n\t\t\tnstr[i] = byte(outrune)\n\t\t\ti++\n\t\t}\n\t}\n\n\t// unsafe convert byte slice to string\n\treturn *(*string)(unsafe.Pointer(&reflect.StringHeader{\n\t\tData: uintptr(unsafe.Pointer(&nstr[0])),\n\t\tLen: len(nstr),\n\t}))\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func NewFzTextRef(ref unsafe.Pointer) *FzText {\n\treturn (*FzText)(ref)\n}", "func DefaultStrConv() (ret *StrConv) {\n\tvar (\n\t\tb []byte\n\t\tr []rune\n\t)\n\n\treturn &StrConv{\n\t\tByType: map[reflect.Type]ConvFunc{\n\t\t\treflect.TypeOf(b): StringConverter,\n\t\t\treflect.TypeOf(r): StringConverter,\n\t\t},\n\t\tByKind: map[reflect.Kind]ConvFunc{\n\t\t\treflect.Bool: BoolConverter,\n\t\t\treflect.Int: IntDecConverter,\n\t\t\treflect.Int8: IntDecConverter,\n\t\t\treflect.Int16: IntDecConverter,\n\t\t\treflect.Int32: IntDecConverter,\n\t\t\treflect.Int64: IntDecConverter,\n\t\t\treflect.Uint: UintDecConverter,\n\t\t\treflect.Uint8: UintDecConverter,\n\t\t\treflect.Uint16: UintDecConverter,\n\t\t\treflect.Uint32: UintDecConverter,\n\t\t\treflect.Uint64: UintDecConverter,\n\t\t\treflect.Float32: FloatConverter,\n\t\t\treflect.Float64: FloatConverter,\n\t\t\treflect.String: StringConverter,\n\t\t},\n\t}\n}" ]
[ "0.49815226", "0.4444452", "0.43660194", "0.42840382", "0.4256527", "0.4245073", "0.42352146", "0.4208308", "0.4181139", "0.4091659", "0.40825537", "0.40743327", "0.40652514", "0.40333664", "0.402485", "0.40085512", "0.40047", "0.4001616", "0.39838123", "0.397401", "0.39643714", "0.39590704", "0.3948951", "0.3943882", "0.39404306", "0.39037493", "0.3861112", "0.38376728", "0.3834697", "0.38189304", "0.38154003", "0.3801105", "0.37847874", "0.37708223", "0.37605503", "0.37559214", "0.37442333", "0.3740616", "0.3737156", "0.37318963", "0.37235552", "0.3708758", "0.3706139", "0.36910698", "0.36827815", "0.36712673", "0.36699018", "0.3660626", "0.3608667", "0.36083558", "0.36041987", "0.359827", "0.3585674", "0.35673976", "0.3559286", "0.35560548", "0.3552995", "0.35494402", "0.35467237", "0.3540503", "0.35388517", "0.35372156", "0.35287634", "0.3521024", "0.3519376", "0.35130724", "0.3504963", "0.35017723", "0.35008246", "0.34936494", "0.3491794", "0.34874058", "0.34821793", "0.34810925", "0.34794986", "0.34772497", "0.3475225", "0.34636915", "0.34587243", "0.34557298", "0.3455063", "0.34495175", "0.3447693", "0.3442875", "0.34428236", "0.34412608", "0.3437017", "0.34240735", "0.34232157", "0.34207687", "0.34203565", "0.3415874", "0.34152782", "0.34152782", "0.34152782", "0.34152782", "0.34152782", "0.34152782", "0.3413884", "0.34113973" ]
0.78827673
0
FromXML returns the charset of an XML document. It relies on the XML header and falls back on the plain text content.
func FromXML(content []byte) string { if cset := fromXML(content); cset != "" { return cset } return FromPlain(content) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Charset) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for Charset has been passed, got [%s]\", v)\n\t}\n}", "func (*XMLDocument) Charset() (charset string) {\n\tmacro.Rewrite(\"$_.charset\")\n\treturn charset\n}", "func (conn *IRODSConnection) PreprocessXML(in []byte) (out []byte, err error) {\n\tbuf := in\n\n\tfor len(buf) > 0 {\n\t\tswitch {\n\t\t// turn &#34; into &quot;\n\t\tcase bytes.HasPrefix(buf, escQuot):\n\t\t\tout = append(out, irodsEscQuot...)\n\t\t\tbuf = buf[len(escQuot):]\n\n\t\t// turn &#39 into &apos; or '\n\t\tcase bytes.HasPrefix(buf, escApos):\n\t\t\tif conn.talksCorrectXML() {\n\t\t\t\tout = append(out, irodsEscApos...)\n\t\t\t} else {\n\t\t\t\tout = append(out, '\\'')\n\t\t\t}\n\t\t\tbuf = buf[len(escApos):]\n\n\t\t// irods does not decode encoded tabs\n\t\tcase bytes.HasPrefix(buf, escTab):\n\t\t\tout = append(out, '\\t')\n\t\t\tbuf = buf[len(escTab):]\n\n\t\t// irods does not decode encoded carriage returns\n\t\tcase bytes.HasPrefix(buf, escCR):\n\t\t\tout = append(out, '\\r')\n\t\t\tbuf = buf[len(escCR):]\n\n\t\t// irods does not decode encoded newlines\n\t\tcase bytes.HasPrefix(buf, escNL):\n\t\t\tout = append(out, '\\n')\n\t\t\tbuf = buf[len(escNL):]\n\n\t\t// turn ` into &apos;\n\t\tcase buf[0] == '`' && !conn.talksCorrectXML():\n\t\t\tout = append(out, irodsEscApos...)\n\t\t\tbuf = buf[1:]\n\n\t\t// pass utf8 characters\n\t\tdefault:\n\t\t\tr, size := utf8.DecodeRune(buf)\n\n\t\t\tif r == utf8.RuneError && size == 1 {\n\t\t\t\terr = ErrInvalidUTF8\n\t\t\t\tout = in\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tout = append(out, buf[:size]...)\n\t\t\tbuf = buf[size:]\n\t\t}\n\t}\n\n\treturn\n}", "func correctXml(text []byte) []byte {\n\ttext = correctEncodingToUtf8(text)\n\ttext = correctGibberish(text)\n\ttext = correctUnquotedAttrs(text)\n\ttext = correctEncodingField(text)\n\ttext = correctAmpersands(text)\n\n\treturn text\n}", "func (c *CopyrightType) 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 // Text or image copyright (normally indicated by the © symbol). The default if no <CopyrightType> is specified\n case \"C\":\n\t\tc.Body = `Copyright`\n\n // Phonogram copyright or neighbouring right (normally indicated by the ℗ symbol)\n case \"P\":\n\t\tc.Body = `Phonogram right`\n\n // Sui generis database right\n case \"D\":\n\t\tc.Body = `Database right`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for CopyrightType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *DefaultLanguageOfText) 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 // Afar\n case \"aar\":\n\t\tc.Body = `Afar`\n\n // Abkhaz\n case \"abk\":\n\t\tc.Body = `Abkhaz`\n\n // Achinese\n case \"ace\":\n\t\tc.Body = `Achinese`\n\n // Acoli\n case \"ach\":\n\t\tc.Body = `Acoli`\n\n // Adangme\n case \"ada\":\n\t\tc.Body = `Adangme`\n\n // Adygei\n case \"ady\":\n\t\tc.Body = `Adygei`\n\n // Collective name\n case \"afa\":\n\t\tc.Body = `Afro-Asiatic languages`\n\n // Artificial language\n case \"afh\":\n\t\tc.Body = `Afrihili`\n\n // Afrikaans\n case \"afr\":\n\t\tc.Body = `Afrikaans`\n\n // Ainu\n case \"ain\":\n\t\tc.Body = `Ainu`\n\n // Macrolanguage\n case \"aka\":\n\t\tc.Body = `Akan`\n\n // Akkadian\n case \"akk\":\n\t\tc.Body = `Akkadian`\n\n // Macrolanguage\n case \"alb\":\n\t\tc.Body = `Albanian`\n\n // Aleut\n case \"ale\":\n\t\tc.Body = `Aleut`\n\n // Collective name\n case \"alg\":\n\t\tc.Body = `Algonquian languages`\n\n // Southern Altai\n case \"alt\":\n\t\tc.Body = `Southern Altai`\n\n // Amharic\n case \"amh\":\n\t\tc.Body = `Amharic`\n\n // English, Old (ca. 450-1100)\n case \"ang\":\n\t\tc.Body = `English, Old (ca. 450-1100)`\n\n // Angika\n case \"anp\":\n\t\tc.Body = `Angika`\n\n // Collective name\n case \"apa\":\n\t\tc.Body = `Apache languages`\n\n // Macrolanguage\n case \"ara\":\n\t\tc.Body = `Arabic`\n\n // Official Aramaic; Imperial Aramaic (700-300 BCE)\n case \"arc\":\n\t\tc.Body = `Official Aramaic; Imperial Aramaic (700-300 BCE)`\n\n // Aragonese\n case \"arg\":\n\t\tc.Body = `Aragonese`\n\n // Armenian\n case \"arm\":\n\t\tc.Body = `Armenian`\n\n // Mapudungun; Mapuche\n case \"arn\":\n\t\tc.Body = `Mapudungun; Mapuche`\n\n // Arapaho\n case \"arp\":\n\t\tc.Body = `Arapaho`\n\n // Collective name\n case \"art\":\n\t\tc.Body = `Artificial languages`\n\n // Arawak\n case \"arw\":\n\t\tc.Body = `Arawak`\n\n // Assamese\n case \"asm\":\n\t\tc.Body = `Assamese`\n\n // Asturian; Bable; Leonese; Asturleonese\n case \"ast\":\n\t\tc.Body = `Asturian; Bable; Leonese; Asturleonese`\n\n // Collective name\n case \"ath\":\n\t\tc.Body = `Athapascan languages`\n\n // Collective name\n case \"aus\":\n\t\tc.Body = `Australian languages`\n\n // Avaric\n case \"ava\":\n\t\tc.Body = `Avaric`\n\n // Avestan\n case \"ave\":\n\t\tc.Body = `Avestan`\n\n // Awadhi\n case \"awa\":\n\t\tc.Body = `Awadhi`\n\n // Macrolanguage\n case \"aym\":\n\t\tc.Body = `Aymara`\n\n // Macrolanguage\n case \"aze\":\n\t\tc.Body = `Azerbaijani`\n\n // Collective name\n case \"bad\":\n\t\tc.Body = `Banda languages`\n\n // Collective name\n case \"bai\":\n\t\tc.Body = `Bamileke languages`\n\n // Bashkir\n case \"bak\":\n\t\tc.Body = `Bashkir`\n\n // Macrolanguage\n case \"bal\":\n\t\tc.Body = `Baluchi`\n\n // Bambara\n case \"bam\":\n\t\tc.Body = `Bambara`\n\n // Balinese\n case \"ban\":\n\t\tc.Body = `Balinese`\n\n // Basque\n case \"baq\":\n\t\tc.Body = `Basque`\n\n // Basa\n case \"bas\":\n\t\tc.Body = `Basa`\n\n // Collective name\n case \"bat\":\n\t\tc.Body = `Baltic languages`\n\n // Beja; Bedawiyet\n case \"bej\":\n\t\tc.Body = `Beja; Bedawiyet`\n\n // Belarusian\n case \"bel\":\n\t\tc.Body = `Belarusian`\n\n // Bemba\n case \"bem\":\n\t\tc.Body = `Bemba`\n\n // Bengali\n case \"ben\":\n\t\tc.Body = `Bengali`\n\n // Collective name\n case \"ber\":\n\t\tc.Body = `Berber languages`\n\n // Bhojpuri\n case \"bho\":\n\t\tc.Body = `Bhojpuri`\n\n // Collective name\n case \"bih\":\n\t\tc.Body = `Bihari languages`\n\n // Macrolanguage\n case \"bik\":\n\t\tc.Body = `Bikol`\n\n // Bini; Edo\n case \"bin\":\n\t\tc.Body = `Bini; Edo`\n\n // Bislama\n case \"bis\":\n\t\tc.Body = `Bislama`\n\n // Siksika\n case \"bla\":\n\t\tc.Body = `Siksika`\n\n // Collective name\n case \"bnt\":\n\t\tc.Body = `Bantu languages`\n\n // Bosnian\n case \"bos\":\n\t\tc.Body = `Bosnian`\n\n // Braj\n case \"bra\":\n\t\tc.Body = `Braj`\n\n // Breton\n case \"bre\":\n\t\tc.Body = `Breton`\n\n // Collective name\n case \"btk\":\n\t\tc.Body = `Batak languages`\n\n // Macrolanguage\n case \"bua\":\n\t\tc.Body = `Buriat`\n\n // Buginese\n case \"bug\":\n\t\tc.Body = `Buginese`\n\n // Bulgarian\n case \"bul\":\n\t\tc.Body = `Bulgarian`\n\n // Burmese\n case \"bur\":\n\t\tc.Body = `Burmese`\n\n // Blin; Bilin\n case \"byn\":\n\t\tc.Body = `Blin; Bilin`\n\n // Caddo\n case \"cad\":\n\t\tc.Body = `Caddo`\n\n // Collective name\n case \"cai\":\n\t\tc.Body = `Central American Indian languages`\n\n // Galibi Carib\n case \"car\":\n\t\tc.Body = `Galibi Carib`\n\n // Catalan\n case \"cat\":\n\t\tc.Body = `Catalan`\n\n // Collective name\n case \"cau\":\n\t\tc.Body = `Caucasian languages`\n\n // Cebuano\n case \"ceb\":\n\t\tc.Body = `Cebuano`\n\n // Collective name\n case \"cel\":\n\t\tc.Body = `Celtic languages`\n\n // Chamorro\n case \"cha\":\n\t\tc.Body = `Chamorro`\n\n // Chibcha\n case \"chb\":\n\t\tc.Body = `Chibcha`\n\n // Chechen\n case \"che\":\n\t\tc.Body = `Chechen`\n\n // Chagatai\n case \"chg\":\n\t\tc.Body = `Chagatai`\n\n // Macrolanguage\n case \"chi\":\n\t\tc.Body = `Chinese`\n\n // Chuukese (Truk)\n case \"chk\":\n\t\tc.Body = `Chuukese (Truk)`\n\n // Macrolanguage\n case \"chm\":\n\t\tc.Body = `Mari`\n\n // Chinook jargon\n case \"chn\":\n\t\tc.Body = `Chinook jargon`\n\n // Choctaw\n case \"cho\":\n\t\tc.Body = `Choctaw`\n\n // Chipewyan; Dene Suline\n case \"chp\":\n\t\tc.Body = `Chipewyan; Dene Suline`\n\n // Cherokee\n case \"chr\":\n\t\tc.Body = `Cherokee`\n\n // Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic\n case \"chu\":\n\t\tc.Body = `Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic`\n\n // Chuvash\n case \"chv\":\n\t\tc.Body = `Chuvash`\n\n // Cheyenne\n case \"chy\":\n\t\tc.Body = `Cheyenne`\n\n // ONIX local code, equivalent to ckb in ISO 639-3. For use in ONIX 3.0 only\n case \"ckb\":\n\t\tc.Body = `Central Kurdish (Sorani)`\n\n // Collective name\n case \"cmc\":\n\t\tc.Body = `Chamic languages`\n\n // ONIX local code, equivalent to cmn in ISO 639-3\n case \"cmn\":\n\t\tc.Body = `Mandarin`\n\n // For use in ONIX 3.0 only\n case \"cnr\":\n\t\tc.Body = `Montenegrin`\n\n // Coptic\n case \"cop\":\n\t\tc.Body = `Coptic`\n\n // Cornish\n case \"cor\":\n\t\tc.Body = `Cornish`\n\n // Corsican\n case \"cos\":\n\t\tc.Body = `Corsican`\n\n // Collective name\n case \"cpe\":\n\t\tc.Body = `Creoles and pidgins, English-based`\n\n // Collective name\n case \"cpf\":\n\t\tc.Body = `Creoles and pidgins, French-based`\n\n // Collective name\n case \"cpp\":\n\t\tc.Body = `Creoles and pidgins, Portuguese-based`\n\n // Macrolanguage\n case \"cre\":\n\t\tc.Body = `Cree`\n\n // Crimean Turkish; Crimean Tatar\n case \"crh\":\n\t\tc.Body = `Crimean Turkish; Crimean Tatar`\n\n // Collective name\n case \"crp\":\n\t\tc.Body = `Creoles and pidgins`\n\n // Kashubian\n case \"csb\":\n\t\tc.Body = `Kashubian`\n\n // Collective name\n case \"cus\":\n\t\tc.Body = `Cushitic languages`\n\n // Czech\n case \"cze\":\n\t\tc.Body = `Czech`\n\n // Dakota\n case \"dak\":\n\t\tc.Body = `Dakota`\n\n // Danish\n case \"dan\":\n\t\tc.Body = `Danish`\n\n // Dargwa\n case \"dar\":\n\t\tc.Body = `Dargwa`\n\n // Collective name\n case \"day\":\n\t\tc.Body = `Land Dayak languages`\n\n // Macrolanguage\n case \"del\":\n\t\tc.Body = `Delaware`\n\n // Macrolanguage\n case \"den\":\n\t\tc.Body = `Slave (Athapascan)`\n\n // Dogrib\n case \"dgr\":\n\t\tc.Body = `Dogrib`\n\n // Macrolanguage\n case \"din\":\n\t\tc.Body = `Dinka`\n\n // Divehi; Dhivehi; Maldivian\n case \"div\":\n\t\tc.Body = `Divehi; Dhivehi; Maldivian`\n\n // Macrolanguage\n case \"doi\":\n\t\tc.Body = `Dogri`\n\n // Collective name\n case \"dra\":\n\t\tc.Body = `Dravidian languages`\n\n // Lower Sorbian\n case \"dsb\":\n\t\tc.Body = `Lower Sorbian`\n\n // Duala\n case \"dua\":\n\t\tc.Body = `Duala`\n\n // Dutch, Middle (ca. 1050-1350)\n case \"dum\":\n\t\tc.Body = `Dutch, Middle (ca. 1050-1350)`\n\n // Dutch; Flemish\n case \"dut\":\n\t\tc.Body = `Dutch; Flemish`\n\n // Dyula\n case \"dyu\":\n\t\tc.Body = `Dyula`\n\n // Dzongkha\n case \"dzo\":\n\t\tc.Body = `Dzongkha`\n\n // Efik\n case \"efi\":\n\t\tc.Body = `Efik`\n\n // ONIX local code for Italian dialect, equivalent to egl in ISO 639-3. For use in ONIX 3.0 only\n case \"egl\":\n\t\tc.Body = `Emilian`\n\n // Egyptian (Ancient)\n case \"egy\":\n\t\tc.Body = `Egyptian (Ancient)`\n\n // Ekajuk\n case \"eka\":\n\t\tc.Body = `Ekajuk`\n\n // Elamite\n case \"elx\":\n\t\tc.Body = `Elamite`\n\n // English\n case \"eng\":\n\t\tc.Body = `English`\n\n // English, Middle (1100-1500)\n case \"enm\":\n\t\tc.Body = `English, Middle (1100-1500)`\n\n // Artificial language\n case \"epo\":\n\t\tc.Body = `Esperanto`\n\n // Macrolanguage\n case \"est\":\n\t\tc.Body = `Estonian`\n\n // Ewe\n case \"ewe\":\n\t\tc.Body = `Ewe`\n\n // Ewondo\n case \"ewo\":\n\t\tc.Body = `Ewondo`\n\n // Fang\n case \"fan\":\n\t\tc.Body = `Fang`\n\n // Faroese\n case \"fao\":\n\t\tc.Body = `Faroese`\n\n // Fanti\n case \"fat\":\n\t\tc.Body = `Fanti`\n\n // Fijian\n case \"fij\":\n\t\tc.Body = `Fijian`\n\n // Filipino; Pilipino\n case \"fil\":\n\t\tc.Body = `Filipino; Pilipino`\n\n // Finnish\n case \"fin\":\n\t\tc.Body = `Finnish`\n\n // ONIX local code, equivalent to fit in ISO 639-3\n case \"fit\":\n\t\tc.Body = `Meänkieli / Tornedalen Finnish`\n\n // Collective name\n case \"fiu\":\n\t\tc.Body = `Finno-Ugrian languages`\n\n // ONIX local code, equivalent to fkv in ISO 639-3\n case \"fkv\":\n\t\tc.Body = `Kvensk`\n\n // Fon\n case \"fon\":\n\t\tc.Body = `Fon`\n\n // French\n case \"fre\":\n\t\tc.Body = `French`\n\n // French, Middle (ca. 1400-1600)\n case \"frm\":\n\t\tc.Body = `French, Middle (ca. 1400-1600)`\n\n // French, Old (ca. 842-1400)\n case \"fro\":\n\t\tc.Body = `French, Old (ca. 842-1400)`\n\n // Northern Frisian\n case \"frr\":\n\t\tc.Body = `Northern Frisian`\n\n // Eastern Frisian\n case \"frs\":\n\t\tc.Body = `Eastern Frisian`\n\n // Western Frisian\n case \"fry\":\n\t\tc.Body = `Western Frisian`\n\n // Fulah\n case \"ful\":\n\t\tc.Body = `Fulah`\n\n // Friulian\n case \"fur\":\n\t\tc.Body = `Friulian`\n\n // Gã\n case \"gaa\":\n\t\tc.Body = `Gã`\n\n // Gayo\n case \"gay\":\n\t\tc.Body = `Gayo`\n\n // Macrolanguage\n case \"gba\":\n\t\tc.Body = `Gbaya`\n\n // Collective name\n case \"gem\":\n\t\tc.Body = `Germanic languages`\n\n // Georgian\n case \"geo\":\n\t\tc.Body = `Georgian`\n\n // German\n case \"ger\":\n\t\tc.Body = `German`\n\n // Ethiopic (Ge’ez)\n case \"gez\":\n\t\tc.Body = `Ethiopic (Ge’ez)`\n\n // Gilbertese\n case \"gil\":\n\t\tc.Body = `Gilbertese`\n\n // Scottish Gaelic\n case \"gla\":\n\t\tc.Body = `Scottish Gaelic`\n\n // Irish\n case \"gle\":\n\t\tc.Body = `Irish`\n\n // Galician\n case \"glg\":\n\t\tc.Body = `Galician`\n\n // Manx\n case \"glv\":\n\t\tc.Body = `Manx`\n\n // German, Middle High (ca. 1050-1500)\n case \"gmh\":\n\t\tc.Body = `German, Middle High (ca. 1050-1500)`\n\n // German, Old High (ca. 750-1050)\n case \"goh\":\n\t\tc.Body = `German, Old High (ca. 750-1050)`\n\n // Macrolanguage\n case \"gon\":\n\t\tc.Body = `Gondi`\n\n // Gorontalo\n case \"gor\":\n\t\tc.Body = `Gorontalo`\n\n // Gothic\n case \"got\":\n\t\tc.Body = `Gothic`\n\n // Macrolanguage\n case \"grb\":\n\t\tc.Body = `Grebo`\n\n // Greek, Ancient (to 1453)\n case \"grc\":\n\t\tc.Body = `Greek, Ancient (to 1453)`\n\n // Greek, Modern (1453-)\n case \"gre\":\n\t\tc.Body = `Greek, Modern (1453-)`\n\n // Macrolanguage\n case \"grn\":\n\t\tc.Body = `Guarani`\n\n // ONIX local code, equivalent to grt in ISO 639-3\n case \"grt\":\n\t\tc.Body = `Garo`\n\n // Swiss German; Alemannic\n case \"gsw\":\n\t\tc.Body = `Swiss German; Alemannic`\n\n // Gujarati\n case \"guj\":\n\t\tc.Body = `Gujarati`\n\n // Gwich’in\n case \"gwi\":\n\t\tc.Body = `Gwich’in`\n\n // Macrolanguage\n case \"hai\":\n\t\tc.Body = `Haida`\n\n // Haitian French Creole\n case \"hat\":\n\t\tc.Body = `Haitian French Creole`\n\n // Hausa\n case \"hau\":\n\t\tc.Body = `Hausa`\n\n // Hawaiian\n case \"haw\":\n\t\tc.Body = `Hawaiian`\n\n // Hebrew\n case \"heb\":\n\t\tc.Body = `Hebrew`\n\n // Herero\n case \"her\":\n\t\tc.Body = `Herero`\n\n // Hiligaynon\n case \"hil\":\n\t\tc.Body = `Hiligaynon`\n\n // Collective name\n case \"him\":\n\t\tc.Body = `Himachali languages; Western Pahari languages`\n\n // Hindi\n case \"hin\":\n\t\tc.Body = `Hindi`\n\n // Hittite\n case \"hit\":\n\t\tc.Body = `Hittite`\n\n // Macrolanguage\n case \"hmn\":\n\t\tc.Body = `Hmong; Mong`\n\n // Hiri Motu\n case \"hmo\":\n\t\tc.Body = `Hiri Motu`\n\n // Croatian\n case \"hrv\":\n\t\tc.Body = `Croatian`\n\n // Upper Sorbian\n case \"hsb\":\n\t\tc.Body = `Upper Sorbian`\n\n // Hungarian\n case \"hun\":\n\t\tc.Body = `Hungarian`\n\n // Hupa\n case \"hup\":\n\t\tc.Body = `Hupa`\n\n // Iban\n case \"iba\":\n\t\tc.Body = `Iban`\n\n // Igbo\n case \"ibo\":\n\t\tc.Body = `Igbo`\n\n // Icelandic\n case \"ice\":\n\t\tc.Body = `Icelandic`\n\n // Artificial language\n case \"ido\":\n\t\tc.Body = `Ido`\n\n // Sichuan Yi; Nuosu\n case \"iii\":\n\t\tc.Body = `Sichuan Yi; Nuosu`\n\n // Collective name\n case \"ijo\":\n\t\tc.Body = `Ijo languages`\n\n // Macrolanguage\n case \"iku\":\n\t\tc.Body = `Inuktitut`\n\n // Artificial language\n case \"ile\":\n\t\tc.Body = `Interlingue; Occidental`\n\n // Iloko\n case \"ilo\":\n\t\tc.Body = `Iloko`\n\n // Artificial language\n case \"ina\":\n\t\tc.Body = `Interlingua (International Auxiliary Language Association)`\n\n // Collective name\n case \"inc\":\n\t\tc.Body = `Indic languages`\n\n // Indonesian\n case \"ind\":\n\t\tc.Body = `Indonesian`\n\n // Collective name\n case \"ine\":\n\t\tc.Body = `Indo-European languages`\n\n // Ingush\n case \"inh\":\n\t\tc.Body = `Ingush`\n\n // Macrolanguage\n case \"ipk\":\n\t\tc.Body = `Inupiaq`\n\n // Collective name\n case \"ira\":\n\t\tc.Body = `Iranian languages`\n\n // Collective name\n case \"iro\":\n\t\tc.Body = `Iroquoian languages`\n\n // Italian\n case \"ita\":\n\t\tc.Body = `Italian`\n\n // Javanese\n case \"jav\":\n\t\tc.Body = `Javanese`\n\n // Lojban\n case \"jbo\":\n\t\tc.Body = `Lojban`\n\n // Japanese\n case \"jpn\":\n\t\tc.Body = `Japanese`\n\n // Judeo-Persian\n case \"jpr\":\n\t\tc.Body = `Judeo-Persian`\n\n // Macrolanguage\n case \"jrb\":\n\t\tc.Body = `Judeo-Arabic`\n\n // Kara-Kalpak\n case \"kaa\":\n\t\tc.Body = `Kara-Kalpak`\n\n // Kabyle\n case \"kab\":\n\t\tc.Body = `Kabyle`\n\n // Kachin; Jingpho\n case \"kac\":\n\t\tc.Body = `Kachin; Jingpho`\n\n // Kalâtdlisut; Greenlandic\n case \"kal\":\n\t\tc.Body = `Kalâtdlisut; Greenlandic`\n\n // Kamba\n case \"kam\":\n\t\tc.Body = `Kamba`\n\n // Kannada\n case \"kan\":\n\t\tc.Body = `Kannada`\n\n // Collective name\n case \"kar\":\n\t\tc.Body = `Karen languages`\n\n // Kashmiri\n case \"kas\":\n\t\tc.Body = `Kashmiri`\n\n // Macrolanguage\n case \"kau\":\n\t\tc.Body = `Kanuri`\n\n // Kawi\n case \"kaw\":\n\t\tc.Body = `Kawi`\n\n // Kazakh\n case \"kaz\":\n\t\tc.Body = `Kazakh`\n\n // Kabardian (Circassian)\n case \"kbd\":\n\t\tc.Body = `Kabardian (Circassian)`\n\n // ONIX local code, equivalent to kdr in ISO 639-3\n case \"kdr\":\n\t\tc.Body = `Karaim`\n\n // Khasi\n case \"kha\":\n\t\tc.Body = `Khasi`\n\n // Collective name\n case \"khi\":\n\t\tc.Body = `Khoisan languages`\n\n // Central Khmer\n case \"khm\":\n\t\tc.Body = `Central Khmer`\n\n // Khotanese; Sakan\n case \"kho\":\n\t\tc.Body = `Khotanese; Sakan`\n\n // Kikuyu; Gikuyu\n case \"kik\":\n\t\tc.Body = `Kikuyu; Gikuyu`\n\n // Kinyarwanda\n case \"kin\":\n\t\tc.Body = `Kinyarwanda`\n\n // Kirghiz; Kyrgyz\n case \"kir\":\n\t\tc.Body = `Kirghiz; Kyrgyz`\n\n // Kimbundu\n case \"kmb\":\n\t\tc.Body = `Kimbundu`\n\n // Macrolanguage\n case \"kok\":\n\t\tc.Body = `Konkani`\n\n // Macrolanguage\n case \"kom\":\n\t\tc.Body = `Komi`\n\n // Macrolanguage\n case \"kon\":\n\t\tc.Body = `Kongo`\n\n // Korean\n case \"kor\":\n\t\tc.Body = `Korean`\n\n // Kusaiean (Caroline Islands)\n case \"kos\":\n\t\tc.Body = `Kusaiean (Caroline Islands)`\n\n // Macrolanguage\n case \"kpe\":\n\t\tc.Body = `Kpelle`\n\n // Karachay-Balkar\n case \"krc\":\n\t\tc.Body = `Karachay-Balkar`\n\n // Karelian\n case \"krl\":\n\t\tc.Body = `Karelian`\n\n // Collective name\n case \"kro\":\n\t\tc.Body = `Kru languages`\n\n // Kurukh\n case \"kru\":\n\t\tc.Body = `Kurukh`\n\n // Kuanyama\n case \"kua\":\n\t\tc.Body = `Kuanyama`\n\n // Kumyk\n case \"kum\":\n\t\tc.Body = `Kumyk`\n\n // Macrolanguage\n case \"kur\":\n\t\tc.Body = `Kurdish`\n\n // Kutenai\n case \"kut\":\n\t\tc.Body = `Kutenai`\n\n // Ladino\n case \"lad\":\n\t\tc.Body = `Ladino`\n\n // Macrolanguage\n case \"lah\":\n\t\tc.Body = `Lahnda`\n\n // Lamba\n case \"lam\":\n\t\tc.Body = `Lamba`\n\n // Lao\n case \"lao\":\n\t\tc.Body = `Lao`\n\n // Latin\n case \"lat\":\n\t\tc.Body = `Latin`\n\n // Macrolanguage\n case \"lav\":\n\t\tc.Body = `Latvian`\n\n // Lezgian\n case \"lez\":\n\t\tc.Body = `Lezgian`\n\n // ONIX local code for Italian dialect, equivalent to lij in ISO 639-3. For use in ONIX 3.0 only\n case \"lij\":\n\t\tc.Body = `Ligurian`\n\n // Limburgish\n case \"lim\":\n\t\tc.Body = `Limburgish`\n\n // Lingala\n case \"lin\":\n\t\tc.Body = `Lingala`\n\n // Lithuanian\n case \"lit\":\n\t\tc.Body = `Lithuanian`\n\n // ONIX local code for Italian dialect, equivalent to lmo in ISO 639-3. For use in ONIX 3.0 only\n case \"lmo\":\n\t\tc.Body = `Lombard`\n\n // Mongo-Nkundu\n case \"lol\":\n\t\tc.Body = `Mongo-Nkundu`\n\n // Lozi\n case \"loz\":\n\t\tc.Body = `Lozi`\n\n // Luxembourgish; Letzeburgesch\n case \"ltz\":\n\t\tc.Body = `Luxembourgish; Letzeburgesch`\n\n // Luba-Lulua\n case \"lua\":\n\t\tc.Body = `Luba-Lulua`\n\n // Luba-Katanga\n case \"lub\":\n\t\tc.Body = `Luba-Katanga`\n\n // Ganda\n case \"lug\":\n\t\tc.Body = `Ganda`\n\n // Luiseño\n case \"lui\":\n\t\tc.Body = `Luiseño`\n\n // Lunda\n case \"lun\":\n\t\tc.Body = `Lunda`\n\n // Luo (Kenya and Tanzania)\n case \"luo\":\n\t\tc.Body = `Luo (Kenya and Tanzania)`\n\n // Lushai\n case \"lus\":\n\t\tc.Body = `Lushai`\n\n // Macedonian\n case \"mac\":\n\t\tc.Body = `Macedonian`\n\n // Madurese\n case \"mad\":\n\t\tc.Body = `Madurese`\n\n // Magahi\n case \"mag\":\n\t\tc.Body = `Magahi`\n\n // Marshallese\n case \"mah\":\n\t\tc.Body = `Marshallese`\n\n // Maithili\n case \"mai\":\n\t\tc.Body = `Maithili`\n\n // Makasar\n case \"mak\":\n\t\tc.Body = `Makasar`\n\n // Malayalam\n case \"mal\":\n\t\tc.Body = `Malayalam`\n\n // Macrolanguage\n case \"man\":\n\t\tc.Body = `Mandingo`\n\n // Maori\n case \"mao\":\n\t\tc.Body = `Maori`\n\n // Collective name\n case \"map\":\n\t\tc.Body = `Austronesian languages`\n\n // Marathi\n case \"mar\":\n\t\tc.Body = `Marathi`\n\n // Masai\n case \"mas\":\n\t\tc.Body = `Masai`\n\n // Macrolanguage\n case \"may\":\n\t\tc.Body = `Malay`\n\n // Moksha\n case \"mdf\":\n\t\tc.Body = `Moksha`\n\n // Mandar\n case \"mdr\":\n\t\tc.Body = `Mandar`\n\n // Mende\n case \"men\":\n\t\tc.Body = `Mende`\n\n // Irish, Middle (ca. 1100-1550)\n case \"mga\":\n\t\tc.Body = `Irish, Middle (ca. 1100-1550)`\n\n // Mi’kmaq; Micmac\n case \"mic\":\n\t\tc.Body = `Mi’kmaq; Micmac`\n\n // Minangkabau\n case \"min\":\n\t\tc.Body = `Minangkabau`\n\n // Use where no suitable code is available\n case \"mis\":\n\t\tc.Body = `Uncoded languages`\n\n // Collective name\n case \"mkh\":\n\t\tc.Body = `Mon-Khmer languages`\n\n // Macrolanguage\n case \"mlg\":\n\t\tc.Body = `Malagasy`\n\n // Maltese\n case \"mlt\":\n\t\tc.Body = `Maltese`\n\n // Manchu\n case \"mnc\":\n\t\tc.Body = `Manchu`\n\n // Manipuri\n case \"mni\":\n\t\tc.Body = `Manipuri`\n\n // Collective name\n case \"mno\":\n\t\tc.Body = `Manobo languages`\n\n // Mohawk\n case \"moh\":\n\t\tc.Body = `Mohawk`\n\n // DEPRECATED – use rum\n case \"mol\":\n\t\tc.Body = `Moldavian; Moldovan`\n\n // Macrolanguage\n case \"mon\":\n\t\tc.Body = `Mongolian`\n\n // Mooré; Mossi\n case \"mos\":\n\t\tc.Body = `Mooré; Mossi`\n\n // Multiple languages\n case \"mul\":\n\t\tc.Body = `Multiple languages`\n\n // Collective name\n case \"mun\":\n\t\tc.Body = `Munda languages`\n\n // Creek\n case \"mus\":\n\t\tc.Body = `Creek`\n\n // ONIX local code, equivalent to mwf in ISO 639-3. For use in ONIX 3.0 only\n case \"mwf\":\n\t\tc.Body = `Murrinh-Patha`\n\n // Mirandese\n case \"mwl\":\n\t\tc.Body = `Mirandese`\n\n // Macrolanguage\n case \"mwr\":\n\t\tc.Body = `Marwari`\n\n // Collective name\n case \"myn\":\n\t\tc.Body = `Mayan languages`\n\n // Erzya\n case \"myv\":\n\t\tc.Body = `Erzya`\n\n // Collective name\n case \"nah\":\n\t\tc.Body = `Nahuatl languages`\n\n // Collective name\n case \"nai\":\n\t\tc.Body = `North American Indian languages`\n\n // Neapolitan\n case \"nap\":\n\t\tc.Body = `Neapolitan`\n\n // Nauruan\n case \"nau\":\n\t\tc.Body = `Nauruan`\n\n // Navajo\n case \"nav\":\n\t\tc.Body = `Navajo`\n\n // Ndebele, South\n case \"nbl\":\n\t\tc.Body = `Ndebele, South`\n\n // Ndebele, North\n case \"nde\":\n\t\tc.Body = `Ndebele, North`\n\n // Ndonga\n case \"ndo\":\n\t\tc.Body = `Ndonga`\n\n // Low German; Low Saxon\n case \"nds\":\n\t\tc.Body = `Low German; Low Saxon`\n\n // Macrolanguage\n case \"nep\":\n\t\tc.Body = `Nepali`\n\n // Newari; Nepal Bhasa\n case \"new\":\n\t\tc.Body = `Newari; Nepal Bhasa`\n\n // Nias\n case \"nia\":\n\t\tc.Body = `Nias`\n\n // Collective name\n case \"nic\":\n\t\tc.Body = `Niger-Kordofanian languages`\n\n // Niuean\n case \"niu\":\n\t\tc.Body = `Niuean`\n\n // Norwegian Nynorsk\n case \"nno\":\n\t\tc.Body = `Norwegian Nynorsk`\n\n // Norwegian Bokmål\n case \"nob\":\n\t\tc.Body = `Norwegian Bokmål`\n\n // Nogai\n case \"nog\":\n\t\tc.Body = `Nogai`\n\n // Old Norse\n case \"non\":\n\t\tc.Body = `Old Norse`\n\n // Macrolanguage\n case \"nor\":\n\t\tc.Body = `Norwegian`\n\n // N’Ko\n case \"nqo\":\n\t\tc.Body = `N’Ko`\n\n // ONIX local code, equivalent to nrf in ISO 639-3. For use in ONIX 3.0 only\n case \"nrf\":\n\t\tc.Body = `Guernésiais, Jèrriais`\n\n // Pedi; Sepedi; Northern Sotho\n case \"nso\":\n\t\tc.Body = `Pedi; Sepedi; Northern Sotho`\n\n // Collective name\n case \"nub\":\n\t\tc.Body = `Nubian languages`\n\n // Classical Newari; Old Newari; Classical Nepal Bhasa\n case \"nwc\":\n\t\tc.Body = `Classical Newari; Old Newari; Classical Nepal Bhasa`\n\n // Chichewa; Chewa; Nyanja\n case \"nya\":\n\t\tc.Body = `Chichewa; Chewa; Nyanja`\n\n // Nyamwezi\n case \"nym\":\n\t\tc.Body = `Nyamwezi`\n\n // Nyankole\n case \"nyn\":\n\t\tc.Body = `Nyankole`\n\n // Nyoro\n case \"nyo\":\n\t\tc.Body = `Nyoro`\n\n // Nzima\n case \"nzi\":\n\t\tc.Body = `Nzima`\n\n // Occitan (post 1500)\n case \"oci\":\n\t\tc.Body = `Occitan (post 1500)`\n\n // ONIX local code, equivalent to odt in ISO 639-3\n case \"odt\":\n\t\tc.Body = `Old Dutch / Old Low Franconian (ca. 400–1050)`\n\n // Macrolanguage\n case \"oji\":\n\t\tc.Body = `Ojibwa`\n\n // ONIX local code, equivalent to omq in ISO 639-5. Collective name\n case \"omq\":\n\t\tc.Body = `Oto-Manguean languages`\n\n // Macrolanguage\n case \"ori\":\n\t\tc.Body = `Oriya`\n\n // Macrolanguage\n case \"orm\":\n\t\tc.Body = `Oromo`\n\n // Osage\n case \"osa\":\n\t\tc.Body = `Osage`\n\n // Ossetian; Ossetic\n case \"oss\":\n\t\tc.Body = `Ossetian; Ossetic`\n\n // Turkish, Ottoman\n case \"ota\":\n\t\tc.Body = `Turkish, Ottoman`\n\n // Collective name\n case \"oto\":\n\t\tc.Body = `Otomian languages`\n\n // Collective name\n case \"paa\":\n\t\tc.Body = `Papuan languages`\n\n // Pangasinan\n case \"pag\":\n\t\tc.Body = `Pangasinan`\n\n // Pahlavi\n case \"pal\":\n\t\tc.Body = `Pahlavi`\n\n // Pampanga; Kapampangan\n case \"pam\":\n\t\tc.Body = `Pampanga; Kapampangan`\n\n // Panjabi\n case \"pan\":\n\t\tc.Body = `Panjabi`\n\n // Papiamento\n case \"pap\":\n\t\tc.Body = `Papiamento`\n\n // Palauan\n case \"pau\":\n\t\tc.Body = `Palauan`\n\n // Old Persian (ca. 600-400 B.C.)\n case \"peo\":\n\t\tc.Body = `Old Persian (ca. 600-400 B.C.)`\n\n // Macrolanguage\n case \"per\":\n\t\tc.Body = `Persian; Farsi`\n\n // ONIX local code, equivalent to pes in ISO 639-3. For use in ONIX 3.0 only\n case \"pes\":\n\t\tc.Body = `Iranian Persian; Parsi`\n\n // Collective name\n case \"phi\":\n\t\tc.Body = `Philippine languages`\n\n // Phoenician\n case \"phn\":\n\t\tc.Body = `Phoenician`\n\n // Pali\n case \"pli\":\n\t\tc.Body = `Pali`\n\n // ONIX local code for Italian dialect, equivalent to pms in ISO 639-3. For use in ONIX 3.0 only\n case \"pms\":\n\t\tc.Body = `Piedmontese`\n\n // Polish\n case \"pol\":\n\t\tc.Body = `Polish`\n\n // Ponapeian\n case \"pon\":\n\t\tc.Body = `Ponapeian`\n\n // Portuguese\n case \"por\":\n\t\tc.Body = `Portuguese`\n\n // Collective name\n case \"pra\":\n\t\tc.Body = `Prakrit languages`\n\n // Provençal, Old (to 1500); Occitan, Old (to 1500)\n case \"pro\":\n\t\tc.Body = `Provençal, Old (to 1500); Occitan, Old (to 1500)`\n\n // ONIX local code, equivalent to prs in ISO 639-3. For use in ONIX 3.0 only\n case \"prs\":\n\t\tc.Body = `Dari; Afghan Persian`\n\n // Macrolanguage\n case \"pus\":\n\t\tc.Body = `Pushto; Pashto`\n\n // ONIX local code, distinct dialect of Occitan (not distinguished from oci by ISO 639-3)\n case \"qar\":\n\t\tc.Body = `Aranés`\n\n // ONIX local code, distinct dialect of Catalan (not distinguished from cat by ISO 639-3)\n case \"qav\":\n\t\tc.Body = `Valencian`\n\n // ONIX local code, distinct variant of langue d’oïl (old northern French) (not distinguished from fro, or from frm, fre, nrf by ISO 639-3). For use in ONIX 3.0 only\n case \"qgl\":\n\t\tc.Body = `Gallo`\n\n // ONIX local code, distinct dialect of of Rusyn (not distinguished from rue by ISO 639-3). For use in ONIX 3.0 only\n case \"qlk\":\n\t\tc.Body = `Lemko`\n\n // ONIX local code, distinct and exclusively spoken variation of Spanish, not distinguished from spa (Spanish, Castilian) by ISO 639-3. Neutral Latin American Spanish should be considered a ‘shorthand’ for spa plus a ‘country code’ for Latin America – but prefer spa plus the relevant country code for specifically Mexican Spanish, Argentine (Rioplatense) Spanish, Puerto Rican Spanish etc. Neutral Latin American Spanish must only be used with audio material (including the audio tracks of TV, video and film) to indicate use of accent, vocabulary and construction suitable for broad use across Latin America. For use in ONIX 3.0 only\n case \"qls\":\n\t\tc.Body = `Neutral Latin American Spanish`\n\n // Macrolanguage\n case \"que\":\n\t\tc.Body = `Quechua`\n\n // Macrolanguage\n case \"raj\":\n\t\tc.Body = `Rajasthani`\n\n // Rapanui\n case \"rap\":\n\t\tc.Body = `Rapanui`\n\n // Rarotongan; Cook Islands Maori\n case \"rar\":\n\t\tc.Body = `Rarotongan; Cook Islands Maori`\n\n // ONIX local code, equivalent to rcf in ISO 639-3. For use in ONIX 3.0 only\n case \"rcf\":\n\t\tc.Body = `Réunion Creole French`\n\n // ONIX local code for Italian dialect, equivalent to rgl in ISO 639-3. For use in ONIX 3.0 only\n case \"rgn\":\n\t\tc.Body = `Romagnol`\n\n // Collective name\n case \"roa\":\n\t\tc.Body = `Romance languages`\n\n // Romansh\n case \"roh\":\n\t\tc.Body = `Romansh`\n\n // Macrolanguage\n case \"rom\":\n\t\tc.Body = `Romany`\n\n // Romanian\n case \"rum\":\n\t\tc.Body = `Romanian`\n\n // Rundi\n case \"run\":\n\t\tc.Body = `Rundi`\n\n // Aromanian; Arumanian; Macedo-Romanian\n case \"rup\":\n\t\tc.Body = `Aromanian; Arumanian; Macedo-Romanian`\n\n // Russian\n case \"rus\":\n\t\tc.Body = `Russian`\n\n // Sandawe\n case \"sad\":\n\t\tc.Body = `Sandawe`\n\n // Sango\n case \"sag\":\n\t\tc.Body = `Sango`\n\n // Yakut\n case \"sah\":\n\t\tc.Body = `Yakut`\n\n // Collective name\n case \"sai\":\n\t\tc.Body = `South American Indian languages`\n\n // Collective name\n case \"sal\":\n\t\tc.Body = `Salishan languages`\n\n // Samaritan Aramaic\n case \"sam\":\n\t\tc.Body = `Samaritan Aramaic`\n\n // Sanskrit\n case \"san\":\n\t\tc.Body = `Sanskrit`\n\n // Sasak\n case \"sas\":\n\t\tc.Body = `Sasak`\n\n // Santali\n case \"sat\":\n\t\tc.Body = `Santali`\n\n // DEPRECATED – use srp\n case \"scc\":\n\t\tc.Body = `Serbian`\n\n // Sicilian\n case \"scn\":\n\t\tc.Body = `Sicilian`\n\n // Scots\n case \"sco\":\n\t\tc.Body = `Scots`\n\n // DEPRECATED – use hrv\n case \"scr\":\n\t\tc.Body = `Croatian`\n\n // ONIX local code for Sardinian dialect, equivalent to sdc in ISO 639-3. For use in ONIX 3.0 only\n case \"sdc\":\n\t\tc.Body = `Sassarese`\n\n // ONIX local code for Sardinian dialect, equivalent to sdn in ISO 639-3. For use in ONIX 3.0 only\n case \"sdn\":\n\t\tc.Body = `Gallurese`\n\n // Selkup\n case \"sel\":\n\t\tc.Body = `Selkup`\n\n // Collective name\n case \"sem\":\n\t\tc.Body = `Semitic languages`\n\n // Irish, Old (to 1100)\n case \"sga\":\n\t\tc.Body = `Irish, Old (to 1100)`\n\n // Collective name\n case \"sgn\":\n\t\tc.Body = `Sign languages`\n\n // Shan\n case \"shn\":\n\t\tc.Body = `Shan`\n\n // Sidamo\n case \"sid\":\n\t\tc.Body = `Sidamo`\n\n // Sinhala; Sinhalese\n case \"sin\":\n\t\tc.Body = `Sinhala; Sinhalese`\n\n // Collective name\n case \"sio\":\n\t\tc.Body = `Siouan languages`\n\n // Collective name\n case \"sit\":\n\t\tc.Body = `Sino-Tibetan languages`\n\n // Collective name\n case \"sla\":\n\t\tc.Body = `Slavic languages`\n\n // Slovak\n case \"slo\":\n\t\tc.Body = `Slovak`\n\n // Slovenian\n case \"slv\":\n\t\tc.Body = `Slovenian`\n\n // Southern Sami\n case \"sma\":\n\t\tc.Body = `Southern Sami`\n\n // Northern Sami\n case \"sme\":\n\t\tc.Body = `Northern Sami`\n\n // Collective name\n case \"smi\":\n\t\tc.Body = `Sami languages`\n\n // Lule Sami\n case \"smj\":\n\t\tc.Body = `Lule Sami`\n\n // Inari Sami\n case \"smn\":\n\t\tc.Body = `Inari Sami`\n\n // Samoan\n case \"smo\":\n\t\tc.Body = `Samoan`\n\n // Skolt Sami\n case \"sms\":\n\t\tc.Body = `Skolt Sami`\n\n // Shona\n case \"sna\":\n\t\tc.Body = `Shona`\n\n // Sindhi\n case \"snd\":\n\t\tc.Body = `Sindhi`\n\n // Soninke\n case \"snk\":\n\t\tc.Body = `Soninke`\n\n // Sogdian\n case \"sog\":\n\t\tc.Body = `Sogdian`\n\n // Somali\n case \"som\":\n\t\tc.Body = `Somali`\n\n // Collective name\n case \"son\":\n\t\tc.Body = `Songhai languages`\n\n // Sotho; Sesotho\n case \"sot\":\n\t\tc.Body = `Sotho; Sesotho`\n\n // Spanish\n case \"spa\":\n\t\tc.Body = `Spanish`\n\n // Macrolanguage\n case \"srd\":\n\t\tc.Body = `Sardinian`\n\n // Sranan Tongo\n case \"srn\":\n\t\tc.Body = `Sranan Tongo`\n\n // ONIX local code for Sardinian dialect, equivalent to sro in ISO 639-3. For use in ONIX 3.0 only\n case \"sro\":\n\t\tc.Body = `Campidanese`\n\n // Serbian\n case \"srp\":\n\t\tc.Body = `Serbian`\n\n // Serer\n case \"srr\":\n\t\tc.Body = `Serer`\n\n // Collective name\n case \"ssa\":\n\t\tc.Body = `Nilo-Saharan languages`\n\n // Swazi; Swati\n case \"ssw\":\n\t\tc.Body = `Swazi; Swati`\n\n // Sukuma\n case \"suk\":\n\t\tc.Body = `Sukuma`\n\n // Sundanese\n case \"sun\":\n\t\tc.Body = `Sundanese`\n\n // Susu\n case \"sus\":\n\t\tc.Body = `Susu`\n\n // Sumerian\n case \"sux\":\n\t\tc.Body = `Sumerian`\n\n // Macrolanguage\n case \"swa\":\n\t\tc.Body = `Swahili`\n\n // Swedish\n case \"swe\":\n\t\tc.Body = `Swedish`\n\n // Classical Syriac\n case \"syc\":\n\t\tc.Body = `Classical Syriac`\n\n // Macrolanguage\n case \"syr\":\n\t\tc.Body = `Syriac`\n\n // Tahitian\n case \"tah\":\n\t\tc.Body = `Tahitian`\n\n // Collective name\n case \"tai\":\n\t\tc.Body = `Tai languages`\n\n // Tamil\n case \"tam\":\n\t\tc.Body = `Tamil`\n\n // Tatar\n case \"tat\":\n\t\tc.Body = `Tatar`\n\n // Telugu\n case \"tel\":\n\t\tc.Body = `Telugu`\n\n // Temne; Time\n case \"tem\":\n\t\tc.Body = `Temne; Time`\n\n // Terena\n case \"ter\":\n\t\tc.Body = `Terena`\n\n // Tetum\n case \"tet\":\n\t\tc.Body = `Tetum`\n\n // Tajik; Tajiki Persian\n case \"tgk\":\n\t\tc.Body = `Tajik; Tajiki Persian`\n\n // Tagalog\n case \"tgl\":\n\t\tc.Body = `Tagalog`\n\n // Thai\n case \"tha\":\n\t\tc.Body = `Thai`\n\n // Tibetan\n case \"tib\":\n\t\tc.Body = `Tibetan`\n\n // Tigré\n case \"tig\":\n\t\tc.Body = `Tigré`\n\n // Tigrinya\n case \"tir\":\n\t\tc.Body = `Tigrinya`\n\n // Tiv\n case \"tiv\":\n\t\tc.Body = `Tiv`\n\n // Tokelauan\n case \"tkl\":\n\t\tc.Body = `Tokelauan`\n\n // Artificial language\n case \"tlh\":\n\t\tc.Body = `Klingon; tlhIngan-Hol`\n\n // Tlingit\n case \"tli\":\n\t\tc.Body = `Tlingit`\n\n // Macrolanguage\n case \"tmh\":\n\t\tc.Body = `Tamashek`\n\n // Tonga (Nyasa)\n case \"tog\":\n\t\tc.Body = `Tonga (Nyasa)`\n\n // Tongan\n case \"ton\":\n\t\tc.Body = `Tongan`\n\n // Tok Pisin\n case \"tpi\":\n\t\tc.Body = `Tok Pisin`\n\n // Tsimshian\n case \"tsi\":\n\t\tc.Body = `Tsimshian`\n\n // AKA Setswana\n case \"tsn\":\n\t\tc.Body = `Tswana`\n\n // Tsonga\n case \"tso\":\n\t\tc.Body = `Tsonga`\n\n // Turkmen\n case \"tuk\":\n\t\tc.Body = `Turkmen`\n\n // Tumbuka\n case \"tum\":\n\t\tc.Body = `Tumbuka`\n\n // Collective name\n case \"tup\":\n\t\tc.Body = `Tupi languages`\n\n // Turkish\n case \"tur\":\n\t\tc.Body = `Turkish`\n\n // Altaic languages\n case \"tut\":\n\t\tc.Body = `Altaic languages`\n\n // Tuvaluan\n case \"tvl\":\n\t\tc.Body = `Tuvaluan`\n\n // Twi\n case \"twi\":\n\t\tc.Body = `Twi`\n\n // Tuvinian\n case \"tyv\":\n\t\tc.Body = `Tuvinian`\n\n // ONIX local code, equivalent to tzo in ISO 639-3\n case \"tzo\":\n\t\tc.Body = `Tzotzil`\n\n // Udmurt\n case \"udm\":\n\t\tc.Body = `Udmurt`\n\n // Ugaritic\n case \"uga\":\n\t\tc.Body = `Ugaritic`\n\n // Uighur; Uyghur\n case \"uig\":\n\t\tc.Body = `Uighur; Uyghur`\n\n // Ukrainian\n case \"ukr\":\n\t\tc.Body = `Ukrainian`\n\n // Umbundu\n case \"umb\":\n\t\tc.Body = `Umbundu`\n\n // Undetermined language\n case \"und\":\n\t\tc.Body = `Undetermined language`\n\n // Urdu\n case \"urd\":\n\t\tc.Body = `Urdu`\n\n // Macrolanguage\n case \"uzb\":\n\t\tc.Body = `Uzbek`\n\n // Vai\n case \"vai\":\n\t\tc.Body = `Vai`\n\n // ONIX local code for Italian dialect, equivalent to vec in ISO 639-3. For use in ONIX 3.0 only\n case \"vec\":\n\t\tc.Body = `Venetian/Venetan`\n\n // Venda\n case \"ven\":\n\t\tc.Body = `Venda`\n\n // Vietnamese\n case \"vie\":\n\t\tc.Body = `Vietnamese`\n\n // Artificial language\n case \"vol\":\n\t\tc.Body = `Volapük`\n\n // Votic\n case \"vot\":\n\t\tc.Body = `Votic`\n\n // Collective name\n case \"wak\":\n\t\tc.Body = `Wakashan languages`\n\n // Wolaitta; Wolaytta\n case \"wal\":\n\t\tc.Body = `Wolaitta; Wolaytta`\n\n // Waray\n case \"war\":\n\t\tc.Body = `Waray`\n\n // Washo\n case \"was\":\n\t\tc.Body = `Washo`\n\n // Welsh\n case \"wel\":\n\t\tc.Body = `Welsh`\n\n // Collective name\n case \"wen\":\n\t\tc.Body = `Sorbian languages`\n\n // Walloon\n case \"wln\":\n\t\tc.Body = `Walloon`\n\n // Wolof\n case \"wol\":\n\t\tc.Body = `Wolof`\n\n // Kalmyk\n case \"xal\":\n\t\tc.Body = `Kalmyk`\n\n // Xhosa\n case \"xho\":\n\t\tc.Body = `Xhosa`\n\n // ONIX local code, equivalent to xuu in ISO 639-3. For use in ONIX 3.0 only\n case \"xuu\":\n\t\tc.Body = `Khwedam, Kxoe`\n\n // Yao\n case \"yao\":\n\t\tc.Body = `Yao`\n\n // Yapese\n case \"yap\":\n\t\tc.Body = `Yapese`\n\n // Macrolanguage\n case \"yid\":\n\t\tc.Body = `Yiddish`\n\n // Yoruba\n case \"yor\":\n\t\tc.Body = `Yoruba`\n\n // Collective name\n case \"ypk\":\n\t\tc.Body = `Yupik languages`\n\n // ONIX local code, equivalent to yue in ISO 639-3\n case \"yue\":\n\t\tc.Body = `Cantonese`\n\n // Macrolanguage\n case \"zap\":\n\t\tc.Body = `Zapotec`\n\n // Artificial language\n case \"zbl\":\n\t\tc.Body = `Blissymbols; Blissymbolics; Bliss`\n\n // Zenaga\n case \"zen\":\n\t\tc.Body = `Zenaga`\n\n // Standard Moroccan Tamazight\n case \"zgh\":\n\t\tc.Body = `Standard Moroccan Tamazight`\n\n // Macrolanguage\n case \"zha\":\n\t\tc.Body = `Zhuang; Chuang`\n\n // Collective name\n case \"znd\":\n\t\tc.Body = `Zande languages`\n\n // Zulu\n case \"zul\":\n\t\tc.Body = `Zulu`\n\n // Zuni\n case \"zun\":\n\t\tc.Body = `Zuni`\n\n // No linguistic content\n case \"zxx\":\n\t\tc.Body = `No linguistic content`\n\n // Macrolanguage\n case \"zza\":\n\t\tc.Body = `Zaza; Dimili; Dimli; Kirdki; Kirmanjki; Zazaki`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for DefaultLanguageOfText has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func correctEncodingToUtf8(text []byte) []byte {\n\tr, err := charset.NewReader(bytes.NewBuffer(text), \"application/xml\")\n\tif err != nil {\n\t\tfmt.Println(\"Error converting encoding:\", err)\n\t\treturn nil\n\t}\n\ttext, _ = ioutil.ReadAll(r)\n\treturn text\n}", "func (c *TextCaseCode) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for TextCaseCode has been passed, got [%s]\", v)\n\t}\n}", "func FromPlain(content []byte) string {\n\tif len(content) == 0 {\n\t\treturn \"\"\n\t}\n\tif cset := FromBOM(content); cset != \"\" {\n\t\treturn cset\n\t}\n\torigContent := content\n\t// Try to detect UTF-8.\n\t// First eliminate any partial rune at the end.\n\tfor i := len(content) - 1; i >= 0 && i > len(content)-4; i-- {\n\t\tb := content[i]\n\t\tif b < 0x80 {\n\t\t\tbreak\n\t\t}\n\t\tif utf8.RuneStart(b) {\n\t\t\tcontent = content[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\thasHighBit := false\n\tfor _, c := range content {\n\t\tif c >= 0x80 {\n\t\t\thasHighBit = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif hasHighBit && utf8.Valid(content) {\n\t\treturn \"utf-8\"\n\t}\n\n\t// ASCII is a subset of UTF8. Follow W3C recommendation and replace with UTF8.\n\tif ascii(origContent) {\n\t\treturn \"utf-8\"\n\t}\n\n\treturn latin(origContent)\n}", "func (c *Character) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for Character has been passed, got [%s]\", v)\n\t}\n}", "func (c *TextType) 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 // To be used only in circumstances where the parties to an exchange have agreed to include text which (a) is not for general distribution, and (b) cannot be coded elsewhere. If more than one type of text is sent, it must be identified by tagging within the text itself\n case \"01\":\n\t\tc.Body = `Sender-defined text`\n\n // Limited to a maximum of 350 characters\n case \"02\":\n\t\tc.Body = `Short description/annotation`\n\n // Length unrestricted\n case \"03\":\n\t\tc.Body = `Description`\n\n // Used for a table of contents sent as a single text field, which may or may not carry structure expressed using XHTML\n case \"04\":\n\t\tc.Body = `Table of contents`\n\n // Primary descriptive blurb usually taken from the back cover or jacket, or occasionally from the cover/jacket flaps. See also code 27\n case \"05\":\n\t\tc.Body = `Primary cover copy`\n\n // A quote taken from a review of the product or of the work in question where there is no need to take account of different editions\n case \"06\":\n\t\tc.Body = `Review quote`\n\n // A quote taken from a review of a previous edition of the work\n case \"07\":\n\t\tc.Body = `Review quote: previous edition`\n\n // A quote taken from a review of a previous work by the same author(s) or in the same series\n case \"08\":\n\t\tc.Body = `Review quote: previous work`\n\n // A quote usually provided by a celebrity or another author to promote a new book, not from a review\n case \"09\":\n\t\tc.Body = `Endorsement`\n\n // A promotional phrase which is intended to headline a description of the product\n case \"10\":\n\t\tc.Body = `Promotional headline`\n\n // Text describing a feature of a product to which the publisher wishes to draw attention for promotional purposes. Each separate feature should be described by a separate repeat, so that formatting can be applied at the discretion of the receiver of the ONIX record, or multiple features can be described using appropriate XHTML markup\n case \"11\":\n\t\tc.Body = `Feature`\n\n // A note referring to all contributors to a product – NOT linked to a single contributor\n case \"12\":\n\t\tc.Body = `Biographical note`\n\n // A statement included by a publisher in fulfillment of contractual obligations, such as a disclaimer, sponsor statement, or legal notice of any sort. Note that the inclusion of such a notice cannot and does not imply that a user of the ONIX record is obliged to reproduce it\n case \"13\":\n\t\tc.Body = `Publisher’s notice`\n\n // A short excerpt from the main text of the work\n case \"14\":\n\t\tc.Body = `Excerpt`\n\n // Used for an index sent as a single text field, which may be structured using XHTML\n case \"15\":\n\t\tc.Body = `Index`\n\n // (of which the product is a part.) Limited to a maximum of 350 characters\n case \"16\":\n\t\tc.Body = `Short description/annotation for collection`\n\n // (of which the product is a part.) Length unrestricted\n case \"17\":\n\t\tc.Body = `Description for collection`\n\n // As code 11 but used for a new feature of this edition or version\n case \"18\":\n\t\tc.Body = `New feature`\n\n // Version history\n case \"19\":\n\t\tc.Body = `Version history`\n\n // Short summary statement of open access status and any related conditions (eg ‘Open access – no commercial use’), primarily for marketing purposes. Should always be accompanied by a link to the complete license (see <EpubLicense> or code 99 in List 158)\n case \"20\":\n\t\tc.Body = `Open access statement`\n\n // Short summary statement that the product is available only in digital formats (eg ‘Digital exclusive’). If a non-digital version is planned, <ContentDate> should be used to specify the date when exclusivity will end (use content date role code 15). If a non-digital version is available, the statement should not be included\n case \"21\":\n\t\tc.Body = `Digital exclusivity statement`\n\n // For example a recommendation or approval provided by a ministry of education or other official body. Use <Text> to provide details and ideally use <TextSourceCorporate> to name the approver\n case \"22\":\n\t\tc.Body = `Official recommendation`\n\n // Short description in format specified by Japanese Book Publishers Association\n case \"23\":\n\t\tc.Body = `JBPA description`\n\n // JSON-LD snippet suitable for use within an HTML <script type=\"application/ld+json\"> tag, containing structured metadata suitable for use with schema.org\n case \"24\":\n\t\tc.Body = `schema.org snippet`\n\n // Errata\n case \"25\":\n\t\tc.Body = `Errata`\n\n // Introduction, preface or the text of other preliminary material, sent as a single text field, which may be structured using XHTML\n case \"26\":\n\t\tc.Body = `Introduction`\n\n // Secondary descriptive blurb taken from the cover/jacket flaps, or occasionally from the back cover or jacket, used only when there are two separate texts and the primary text is included using code 05\n case \"27\":\n\t\tc.Body = `Secondary cover copy`\n\n // For use with dramatized audiobooks, filmed entertainment etc, for a cast list sent as a single text field, which may or may not carry structure expressed using XHTML\n case \"28\":\n\t\tc.Body = `Full cast and credit list`\n\n // Complete list of books by the author(s), supplied as a single text field, which may be structured using (X)HTML\n case \"29\":\n\t\tc.Body = `Bibliography`\n\n // Formal summary of content (normally used with academic and scholarly content only)\n case \"30\":\n\t\tc.Body = `Abstract`\n\n // Eg for a game, kit\n case \"31\":\n\t\tc.Body = `Rules or instructions`\n\n // Eg for a game, kit. Note: use code 04 for a Table of Contents of a book\n case \"32\":\n\t\tc.Body = `List of contents`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for TextType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c Collation) processXML(p RuleProcessor) (err error) {\n\t// Collation is generated and defined in xml.go.\n\tvar v string\n\tfor _, r := range c.Rules.Any {\n\t\tswitch r.XMLName.Local {\n\t\tcase \"reset\":\n\t\t\tlevel := 0\n\t\t\tswitch r.Before {\n\t\t\tcase \"primary\", \"1\":\n\t\t\t\tlevel = 1\n\t\t\tcase \"secondary\", \"2\":\n\t\t\t\tlevel = 2\n\t\t\tcase \"tertiary\", \"3\":\n\t\t\t\tlevel = 3\n\t\t\tcase \"\":\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"cldr: unknown level %q\", r.Before)\n\t\t\t}\n\t\t\tv, err = r.value()\n\t\t\tif err == nil {\n\t\t\t\terr = p.Reset(v, level)\n\t\t\t}\n\t\tcase \"x\":\n\t\t\tvar context, extend string\n\t\t\tfor _, r1 := range r.Any {\n\t\t\t\tv, err = r1.value()\n\t\t\t\tswitch r1.XMLName.Local {\n\t\t\t\tcase \"context\":\n\t\t\t\t\tcontext = v\n\t\t\t\tcase \"extend\":\n\t\t\t\t\textend = v\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, r1 := range r.Any {\n\t\t\t\tif t := r1.XMLName.Local; t == \"context\" || t == \"extend\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tr1.rule.process(p, r1.XMLName.Local, context, extend)\n\t\t\t}\n\t\tdefault:\n\t\t\terr = r.rule.process(p, r.XMLName.Local, \"\", \"\")\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func NewDecoder(data io.Reader) *xml.Decoder {\n\tdecoder := xml.NewDecoder(data)\n\tdecoder.Entity = xml.HTMLEntity\n\tdecoder.Strict = false\n\tdecoder.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {\n\t\tutf8Reader, err := encoding.CharsetReader(charset, input)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trawData, err := ioutil.ReadAll(utf8Reader)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to read data: %q\", err)\n\t\t}\n\t\tfilteredBytes := bytes.Map(filterValidXMLChar, rawData)\n\t\treturn bytes.NewReader(filteredBytes), nil\n\t}\n\n\treturn decoder\n}", "func (conn *IRODSConnection) PostprocessXML(in []byte) (out []byte, err error) {\n\tbuf := in\n\n\tfor len(buf) > 0 {\n\t\tswitch {\n\t\t// turn &quot; into `\n\t\tcase bytes.HasPrefix(buf, irodsEscQuot) && !conn.talksCorrectXML():\n\t\t\tout = append(out, '`')\n\t\t\tbuf = buf[len(irodsEscQuot):]\n\n\t\t// turn ' into &quot;\n\t\tcase buf[0] == '\\'' && !conn.talksCorrectXML():\n\t\t\tout = append(out, escQuot...)\n\t\t\tbuf = buf[1:]\n\n\t\t// check utf8 characters for validity\n\t\tdefault:\n\t\t\tr, size := utf8.DecodeRune(buf)\n\n\t\t\tif r == utf8.RuneError && size == 1 {\n\t\t\t\terr = ErrInvalidUTF8\n\t\t\t\tout = in\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif isValidChar(r) {\n\t\t\t\tout = append(out, buf[:size]...)\n\t\t\t} else {\n\t\t\t\tout = append(out, escFFFD...)\n\t\t\t}\n\n\t\t\tbuf = buf[size:]\n\t\t}\n\t}\n\n\treturn\n}", "func (c *CountryOfManufacture) 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\tcodes := strings.Split(v, \" \")\n\ttmpeCodes := []string{}\n\tfor _, code := range codes {\n\t\tswitch code {\n\n\t\t// Andorra\n\t\tcase \"AD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Andorra`)\n\n\t\t// United Arab Emirates\n\t\tcase \"AE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United Arab Emirates`)\n\n\t\t// Afghanistan\n\t\tcase \"AF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Afghanistan`)\n\n\t\t// Antigua and Barbuda\n\t\tcase \"AG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Antigua and Barbuda`)\n\n\t\t// Anguilla\n\t\tcase \"AI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Anguilla`)\n\n\t\t// Albania\n\t\tcase \"AL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Albania`)\n\n\t\t// Armenia\n\t\tcase \"AM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Armenia`)\n\n\t\t// Deprecated – use BQ, CW and SX as appropriate\n\t\tcase \"AN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Netherlands Antilles`)\n\n\t\t// Angola\n\t\tcase \"AO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Angola`)\n\n\t\t// Antarctica\n\t\tcase \"AQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Antarctica`)\n\n\t\t// Argentina\n\t\tcase \"AR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Argentina`)\n\n\t\t// American Samoa\n\t\tcase \"AS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `American Samoa`)\n\n\t\t// Austria\n\t\tcase \"AT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Austria`)\n\n\t\t// Australia\n\t\tcase \"AU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Australia`)\n\n\t\t// Aruba\n\t\tcase \"AW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Aruba`)\n\n\t\t// Åland Islands\n\t\tcase \"AX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Åland Islands`)\n\n\t\t// Azerbaijan\n\t\tcase \"AZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Azerbaijan`)\n\n\t\t// Bosnia and Herzegovina\n\t\tcase \"BA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bosnia and Herzegovina`)\n\n\t\t// Barbados\n\t\tcase \"BB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Barbados`)\n\n\t\t// Bangladesh\n\t\tcase \"BD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bangladesh`)\n\n\t\t// Belgium\n\t\tcase \"BE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belgium`)\n\n\t\t// Burkina Faso\n\t\tcase \"BF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Burkina Faso`)\n\n\t\t// Bulgaria\n\t\tcase \"BG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bulgaria`)\n\n\t\t// Bahrain\n\t\tcase \"BH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bahrain`)\n\n\t\t// Burundi\n\t\tcase \"BI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Burundi`)\n\n\t\t// Benin\n\t\tcase \"BJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Benin`)\n\n\t\t// Saint Barthélemy\n\t\tcase \"BL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Barthélemy`)\n\n\t\t// Bermuda\n\t\tcase \"BM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bermuda`)\n\n\t\t// Brunei Darussalam\n\t\tcase \"BN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Brunei Darussalam`)\n\n\t\t// Bolivia, Plurinational State of\n\t\tcase \"BO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bolivia, Plurinational State of`)\n\n\t\t// Bonaire, Sint Eustatius and Saba\n\t\tcase \"BQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bonaire, Sint Eustatius and Saba`)\n\n\t\t// Brazil\n\t\tcase \"BR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Brazil`)\n\n\t\t// Bahamas\n\t\tcase \"BS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bahamas`)\n\n\t\t// Bhutan\n\t\tcase \"BT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bhutan`)\n\n\t\t// Bouvet Island\n\t\tcase \"BV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bouvet Island`)\n\n\t\t// Botswana\n\t\tcase \"BW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Botswana`)\n\n\t\t// Belarus\n\t\tcase \"BY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belarus`)\n\n\t\t// Belize\n\t\tcase \"BZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belize`)\n\n\t\t// Canada\n\t\tcase \"CA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Canada`)\n\n\t\t// Cocos (Keeling) Islands\n\t\tcase \"CC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cocos (Keeling) Islands`)\n\n\t\t// Congo, Democratic Republic of the\n\t\tcase \"CD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Congo, Democratic Republic of the`)\n\n\t\t// Central African Republic\n\t\tcase \"CF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Central African Republic`)\n\n\t\t// Congo\n\t\tcase \"CG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Congo`)\n\n\t\t// Switzerland\n\t\tcase \"CH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Switzerland`)\n\n\t\t// Cote d’Ivoire\n\t\tcase \"CI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cote d’Ivoire`)\n\n\t\t// Cook Islands\n\t\tcase \"CK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cook Islands`)\n\n\t\t// Chile\n\t\tcase \"CL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Chile`)\n\n\t\t// Cameroon\n\t\tcase \"CM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cameroon`)\n\n\t\t// China\n\t\tcase \"CN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `China`)\n\n\t\t// Colombia\n\t\tcase \"CO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Colombia`)\n\n\t\t// Costa Rica\n\t\tcase \"CR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Costa Rica`)\n\n\t\t// DEPRECATED, replaced by ME – Montenegro and RS – Serbia\n\t\tcase \"CS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Serbia and Montenegro`)\n\n\t\t// Cuba\n\t\tcase \"CU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cuba`)\n\n\t\t// Cabo Verde\n\t\tcase \"CV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cabo Verde`)\n\n\t\t// Curaçao\n\t\tcase \"CW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Curaçao`)\n\n\t\t// Christmas Island\n\t\tcase \"CX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Christmas Island`)\n\n\t\t// Cyprus\n\t\tcase \"CY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cyprus`)\n\n\t\t// Formerly Czech Republic\n\t\tcase \"CZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Czechia`)\n\n\t\t// Germany\n\t\tcase \"DE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Germany`)\n\n\t\t// Djibouti\n\t\tcase \"DJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Djibouti`)\n\n\t\t// Denmark\n\t\tcase \"DK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Denmark`)\n\n\t\t// Dominica\n\t\tcase \"DM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Dominica`)\n\n\t\t// Dominican Republic\n\t\tcase \"DO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Dominican Republic`)\n\n\t\t// Algeria\n\t\tcase \"DZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Algeria`)\n\n\t\t// Ecuador\n\t\tcase \"EC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ecuador`)\n\n\t\t// Estonia\n\t\tcase \"EE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Estonia`)\n\n\t\t// Egypt\n\t\tcase \"EG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Egypt`)\n\n\t\t// Western Sahara\n\t\tcase \"EH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Western Sahara`)\n\n\t\t// Eritrea\n\t\tcase \"ER\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Eritrea`)\n\n\t\t// Spain\n\t\tcase \"ES\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Spain`)\n\n\t\t// Ethiopia\n\t\tcase \"ET\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ethiopia`)\n\n\t\t// Finland\n\t\tcase \"FI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Finland`)\n\n\t\t// Fiji\n\t\tcase \"FJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Fiji`)\n\n\t\t// Falkland Islands (Malvinas)\n\t\tcase \"FK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Falkland Islands (Malvinas)`)\n\n\t\t// Micronesia, Federated States of\n\t\tcase \"FM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Micronesia, Federated States of`)\n\n\t\t// Faroe Islands\n\t\tcase \"FO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Faroe Islands`)\n\n\t\t// France\n\t\tcase \"FR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `France`)\n\n\t\t// Gabon\n\t\tcase \"GA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gabon`)\n\n\t\t// United Kingdom\n\t\tcase \"GB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United Kingdom`)\n\n\t\t// Grenada\n\t\tcase \"GD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Grenada`)\n\n\t\t// Georgia\n\t\tcase \"GE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Georgia`)\n\n\t\t// French Guiana\n\t\tcase \"GF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Guiana`)\n\n\t\t// Guernsey\n\t\tcase \"GG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guernsey`)\n\n\t\t// Ghana\n\t\tcase \"GH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ghana`)\n\n\t\t// Gibraltar\n\t\tcase \"GI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gibraltar`)\n\n\t\t// Greenland\n\t\tcase \"GL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Greenland`)\n\n\t\t// Gambia\n\t\tcase \"GM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gambia`)\n\n\t\t// Guinea\n\t\tcase \"GN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guinea`)\n\n\t\t// Guadeloupe\n\t\tcase \"GP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guadeloupe`)\n\n\t\t// Equatorial Guinea\n\t\tcase \"GQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Equatorial Guinea`)\n\n\t\t// Greece\n\t\tcase \"GR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Greece`)\n\n\t\t// South Georgia and the South Sandwich Islands\n\t\tcase \"GS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Georgia and the South Sandwich Islands`)\n\n\t\t// Guatemala\n\t\tcase \"GT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guatemala`)\n\n\t\t// Guam\n\t\tcase \"GU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guam`)\n\n\t\t// Guinea-Bissau\n\t\tcase \"GW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guinea-Bissau`)\n\n\t\t// Guyana\n\t\tcase \"GY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guyana`)\n\n\t\t// Hong Kong\n\t\tcase \"HK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Hong Kong`)\n\n\t\t// Heard Island and McDonald Islands\n\t\tcase \"HM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Heard Island and McDonald Islands`)\n\n\t\t// Honduras\n\t\tcase \"HN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Honduras`)\n\n\t\t// Croatia\n\t\tcase \"HR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Croatia`)\n\n\t\t// Haiti\n\t\tcase \"HT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Haiti`)\n\n\t\t// Hungary\n\t\tcase \"HU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Hungary`)\n\n\t\t// Indonesia\n\t\tcase \"ID\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Indonesia`)\n\n\t\t// Ireland\n\t\tcase \"IE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ireland`)\n\n\t\t// Israel\n\t\tcase \"IL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Israel`)\n\n\t\t// Isle of Man\n\t\tcase \"IM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Isle of Man`)\n\n\t\t// India\n\t\tcase \"IN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `India`)\n\n\t\t// British Indian Ocean Territory\n\t\tcase \"IO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `British Indian Ocean Territory`)\n\n\t\t// Iraq\n\t\tcase \"IQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iraq`)\n\n\t\t// Iran, Islamic Republic of\n\t\tcase \"IR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iran, Islamic Republic of`)\n\n\t\t// Iceland\n\t\tcase \"IS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iceland`)\n\n\t\t// Italy\n\t\tcase \"IT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Italy`)\n\n\t\t// Jersey\n\t\tcase \"JE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jersey`)\n\n\t\t// Jamaica\n\t\tcase \"JM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jamaica`)\n\n\t\t// Jordan\n\t\tcase \"JO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jordan`)\n\n\t\t// Japan\n\t\tcase \"JP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Japan`)\n\n\t\t// Kenya\n\t\tcase \"KE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kenya`)\n\n\t\t// Kyrgyzstan\n\t\tcase \"KG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kyrgyzstan`)\n\n\t\t// Cambodia\n\t\tcase \"KH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cambodia`)\n\n\t\t// Kiribati\n\t\tcase \"KI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kiribati`)\n\n\t\t// Comoros\n\t\tcase \"KM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Comoros`)\n\n\t\t// Saint Kitts and Nevis\n\t\tcase \"KN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Kitts and Nevis`)\n\n\t\t// Korea, Democratic People’s Republic of\n\t\tcase \"KP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Korea, Democratic People’s Republic of`)\n\n\t\t// Korea, Republic of\n\t\tcase \"KR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Korea, Republic of`)\n\n\t\t// Kuwait\n\t\tcase \"KW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kuwait`)\n\n\t\t// Cayman Islands\n\t\tcase \"KY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cayman Islands`)\n\n\t\t// Kazakhstan\n\t\tcase \"KZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kazakhstan`)\n\n\t\t// Lao People’s Democratic Republic\n\t\tcase \"LA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lao People’s Democratic Republic`)\n\n\t\t// Lebanon\n\t\tcase \"LB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lebanon`)\n\n\t\t// Saint Lucia\n\t\tcase \"LC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Lucia`)\n\n\t\t// Liechtenstein\n\t\tcase \"LI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Liechtenstein`)\n\n\t\t// Sri Lanka\n\t\tcase \"LK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sri Lanka`)\n\n\t\t// Liberia\n\t\tcase \"LR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Liberia`)\n\n\t\t// Lesotho\n\t\tcase \"LS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lesotho`)\n\n\t\t// Lithuania\n\t\tcase \"LT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lithuania`)\n\n\t\t// Luxembourg\n\t\tcase \"LU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Luxembourg`)\n\n\t\t// Latvia\n\t\tcase \"LV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Latvia`)\n\n\t\t// Libya\n\t\tcase \"LY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Libya`)\n\n\t\t// Morocco\n\t\tcase \"MA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Morocco`)\n\n\t\t// Monaco\n\t\tcase \"MC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Monaco`)\n\n\t\t// Moldova, Republic of\n\t\tcase \"MD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Moldova, Republic of`)\n\n\t\t// Montenegro\n\t\tcase \"ME\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Montenegro`)\n\n\t\t// Saint Martin (French part)\n\t\tcase \"MF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Martin (French part)`)\n\n\t\t// Madagascar\n\t\tcase \"MG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Madagascar`)\n\n\t\t// Marshall Islands\n\t\tcase \"MH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Marshall Islands`)\n\n\t\t// Formerly FYR Macedonia\n\t\tcase \"MK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `North Macedonia`)\n\n\t\t// Mali\n\t\tcase \"ML\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mali`)\n\n\t\t// Myanmar\n\t\tcase \"MM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Myanmar`)\n\n\t\t// Mongolia\n\t\tcase \"MN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mongolia`)\n\n\t\t// Macao\n\t\tcase \"MO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Macao`)\n\n\t\t// Northern Mariana Islands\n\t\tcase \"MP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Northern Mariana Islands`)\n\n\t\t// Martinique\n\t\tcase \"MQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Martinique`)\n\n\t\t// Mauritania\n\t\tcase \"MR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mauritania`)\n\n\t\t// Montserrat\n\t\tcase \"MS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Montserrat`)\n\n\t\t// Malta\n\t\tcase \"MT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malta`)\n\n\t\t// Mauritius\n\t\tcase \"MU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mauritius`)\n\n\t\t// Maldives\n\t\tcase \"MV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Maldives`)\n\n\t\t// Malawi\n\t\tcase \"MW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malawi`)\n\n\t\t// Mexico\n\t\tcase \"MX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mexico`)\n\n\t\t// Malaysia\n\t\tcase \"MY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malaysia`)\n\n\t\t// Mozambique\n\t\tcase \"MZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mozambique`)\n\n\t\t// Namibia\n\t\tcase \"NA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Namibia`)\n\n\t\t// New Caledonia\n\t\tcase \"NC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `New Caledonia`)\n\n\t\t// Niger\n\t\tcase \"NE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Niger`)\n\n\t\t// Norfolk Island\n\t\tcase \"NF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Norfolk Island`)\n\n\t\t// Nigeria\n\t\tcase \"NG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nigeria`)\n\n\t\t// Nicaragua\n\t\tcase \"NI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nicaragua`)\n\n\t\t// Netherlands\n\t\tcase \"NL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Netherlands`)\n\n\t\t// Norway\n\t\tcase \"NO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Norway`)\n\n\t\t// Nepal\n\t\tcase \"NP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nepal`)\n\n\t\t// Nauru\n\t\tcase \"NR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nauru`)\n\n\t\t// Niue\n\t\tcase \"NU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Niue`)\n\n\t\t// New Zealand\n\t\tcase \"NZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `New Zealand`)\n\n\t\t// Oman\n\t\tcase \"OM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Oman`)\n\n\t\t// Panama\n\t\tcase \"PA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Panama`)\n\n\t\t// Peru\n\t\tcase \"PE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Peru`)\n\n\t\t// French Polynesia\n\t\tcase \"PF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Polynesia`)\n\n\t\t// Papua New Guinea\n\t\tcase \"PG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Papua New Guinea`)\n\n\t\t// Philippines\n\t\tcase \"PH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Philippines`)\n\n\t\t// Pakistan\n\t\tcase \"PK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Pakistan`)\n\n\t\t// Poland\n\t\tcase \"PL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Poland`)\n\n\t\t// Saint Pierre and Miquelon\n\t\tcase \"PM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Pierre and Miquelon`)\n\n\t\t// Pitcairn\n\t\tcase \"PN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Pitcairn`)\n\n\t\t// Puerto Rico\n\t\tcase \"PR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Puerto Rico`)\n\n\t\t// Palestine, State of\n\t\tcase \"PS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Palestine, State of`)\n\n\t\t// Portugal\n\t\tcase \"PT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Portugal`)\n\n\t\t// Palau\n\t\tcase \"PW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Palau`)\n\n\t\t// Paraguay\n\t\tcase \"PY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Paraguay`)\n\n\t\t// Qatar\n\t\tcase \"QA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Qatar`)\n\n\t\t// Réunion\n\t\tcase \"RE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Réunion`)\n\n\t\t// Romania\n\t\tcase \"RO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Romania`)\n\n\t\t// Serbia\n\t\tcase \"RS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Serbia`)\n\n\t\t// Russian Federation\n\t\tcase \"RU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Russian Federation`)\n\n\t\t// Rwanda\n\t\tcase \"RW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Rwanda`)\n\n\t\t// Saudi Arabia\n\t\tcase \"SA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saudi Arabia`)\n\n\t\t// Solomon Islands\n\t\tcase \"SB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Solomon Islands`)\n\n\t\t// Seychelles\n\t\tcase \"SC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Seychelles`)\n\n\t\t// Sudan\n\t\tcase \"SD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sudan`)\n\n\t\t// Sweden\n\t\tcase \"SE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sweden`)\n\n\t\t// Singapore\n\t\tcase \"SG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Singapore`)\n\n\t\t// Saint Helena, Ascension and Tristan da Cunha\n\t\tcase \"SH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Helena, Ascension and Tristan da Cunha`)\n\n\t\t// Slovenia\n\t\tcase \"SI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Slovenia`)\n\n\t\t// Svalbard and Jan Mayen\n\t\tcase \"SJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Svalbard and Jan Mayen`)\n\n\t\t// Slovakia\n\t\tcase \"SK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Slovakia`)\n\n\t\t// Sierra Leone\n\t\tcase \"SL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sierra Leone`)\n\n\t\t// San Marino\n\t\tcase \"SM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `San Marino`)\n\n\t\t// Senegal\n\t\tcase \"SN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Senegal`)\n\n\t\t// Somalia\n\t\tcase \"SO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Somalia`)\n\n\t\t// Suriname\n\t\tcase \"SR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Suriname`)\n\n\t\t// South Sudan\n\t\tcase \"SS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Sudan`)\n\n\t\t// Sao Tome and Principe\n\t\tcase \"ST\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sao Tome and Principe`)\n\n\t\t// El Salvador\n\t\tcase \"SV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `El Salvador`)\n\n\t\t// Sint Maarten (Dutch part)\n\t\tcase \"SX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sint Maarten (Dutch part)`)\n\n\t\t// Syrian Arab Republic\n\t\tcase \"SY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Syrian Arab Republic`)\n\n\t\t// Formerly known as Swaziland\n\t\tcase \"SZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Eswatini`)\n\n\t\t// Turks and Caicos Islands\n\t\tcase \"TC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turks and Caicos Islands`)\n\n\t\t// Chad\n\t\tcase \"TD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Chad`)\n\n\t\t// French Southern Territories\n\t\tcase \"TF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Southern Territories`)\n\n\t\t// Togo\n\t\tcase \"TG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Togo`)\n\n\t\t// Thailand\n\t\tcase \"TH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Thailand`)\n\n\t\t// Tajikistan\n\t\tcase \"TJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tajikistan`)\n\n\t\t// Tokelau\n\t\tcase \"TK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tokelau`)\n\n\t\t// Timor-Leste\n\t\tcase \"TL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Timor-Leste`)\n\n\t\t// Turkmenistan\n\t\tcase \"TM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turkmenistan`)\n\n\t\t// Tunisia\n\t\tcase \"TN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tunisia`)\n\n\t\t// Tonga\n\t\tcase \"TO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tonga`)\n\n\t\t// Turkey\n\t\tcase \"TR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turkey`)\n\n\t\t// Trinidad and Tobago\n\t\tcase \"TT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Trinidad and Tobago`)\n\n\t\t// Tuvalu\n\t\tcase \"TV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tuvalu`)\n\n\t\t// Taiwan, Province of China\n\t\tcase \"TW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Taiwan, Province of China`)\n\n\t\t// Tanzania, United Republic of\n\t\tcase \"TZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tanzania, United Republic of`)\n\n\t\t// Ukraine\n\t\tcase \"UA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ukraine`)\n\n\t\t// Uganda\n\t\tcase \"UG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uganda`)\n\n\t\t// United States Minor Outlying Islands\n\t\tcase \"UM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United States Minor Outlying Islands`)\n\n\t\t// United States\n\t\tcase \"US\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United States`)\n\n\t\t// Uruguay\n\t\tcase \"UY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uruguay`)\n\n\t\t// Uzbekistan\n\t\tcase \"UZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uzbekistan`)\n\n\t\t// Holy See (Vatican City State)\n\t\tcase \"VA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Holy See (Vatican City State)`)\n\n\t\t// Saint Vincent and the Grenadines\n\t\tcase \"VC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Vincent and the Grenadines`)\n\n\t\t// Venezuela, Bolivarian Republic of\n\t\tcase \"VE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Venezuela, Bolivarian Republic of`)\n\n\t\t// Virgin Islands, British\n\t\tcase \"VG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Virgin Islands, British`)\n\n\t\t// Virgin Islands, US\n\t\tcase \"VI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Virgin Islands, US`)\n\n\t\t// Viet Nam\n\t\tcase \"VN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Viet Nam`)\n\n\t\t// Vanuatu\n\t\tcase \"VU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Vanuatu`)\n\n\t\t// Wallis and Futuna\n\t\tcase \"WF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Wallis and Futuna`)\n\n\t\t// Samoa\n\t\tcase \"WS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Samoa`)\n\n\t\t// Yemen\n\t\tcase \"YE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Yemen`)\n\n\t\t// Mayotte\n\t\tcase \"YT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mayotte`)\n\n\t\t// DEPRECATED, replaced by ME – Montenegro and RS – Serbia\n\t\tcase \"YU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Yugoslavia`)\n\n\t\t// South Africa\n\t\tcase \"ZA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Africa`)\n\n\t\t// Zambia\n\t\tcase \"ZM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Zambia`)\n\n\t\t// Zimbabwe\n\t\tcase \"ZW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Zimbabwe`)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"undefined code for CountryOfManufacture has been passed, got [%s]\", v)\n\t\t}\n\t}\n\tc.Body = tmpeCodes\n\treturn nil\n}", "func (service *RssService) rssArticleFromXML(xmlArticle *models.XMLArticle) models.Articles {\n\trssArticle := models.Articles{\n\t\tBody: xmlArticle.Description,\n\t\tTitle: xmlArticle.Title,\n\t\tLink: xmlArticle.Link,\n\t\tDate: time.Now().Unix(),\n\t\tIsRead: false,\n\t}\n\n\treturn rssArticle\n}", "func (c *CountryCode) 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\tcodes := strings.Split(v, \" \")\n\ttmpeCodes := []string{}\n\tfor _, code := range codes {\n\t\tswitch code {\n\n\t\t// Andorra\n\t\tcase \"AD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Andorra`)\n\n\t\t// United Arab Emirates\n\t\tcase \"AE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United Arab Emirates`)\n\n\t\t// Afghanistan\n\t\tcase \"AF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Afghanistan`)\n\n\t\t// Antigua and Barbuda\n\t\tcase \"AG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Antigua and Barbuda`)\n\n\t\t// Anguilla\n\t\tcase \"AI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Anguilla`)\n\n\t\t// Albania\n\t\tcase \"AL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Albania`)\n\n\t\t// Armenia\n\t\tcase \"AM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Armenia`)\n\n\t\t// Deprecated – use BQ, CW and SX as appropriate\n\t\tcase \"AN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Netherlands Antilles`)\n\n\t\t// Angola\n\t\tcase \"AO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Angola`)\n\n\t\t// Antarctica\n\t\tcase \"AQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Antarctica`)\n\n\t\t// Argentina\n\t\tcase \"AR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Argentina`)\n\n\t\t// American Samoa\n\t\tcase \"AS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `American Samoa`)\n\n\t\t// Austria\n\t\tcase \"AT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Austria`)\n\n\t\t// Australia\n\t\tcase \"AU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Australia`)\n\n\t\t// Aruba\n\t\tcase \"AW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Aruba`)\n\n\t\t// Åland Islands\n\t\tcase \"AX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Åland Islands`)\n\n\t\t// Azerbaijan\n\t\tcase \"AZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Azerbaijan`)\n\n\t\t// Bosnia and Herzegovina\n\t\tcase \"BA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bosnia and Herzegovina`)\n\n\t\t// Barbados\n\t\tcase \"BB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Barbados`)\n\n\t\t// Bangladesh\n\t\tcase \"BD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bangladesh`)\n\n\t\t// Belgium\n\t\tcase \"BE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belgium`)\n\n\t\t// Burkina Faso\n\t\tcase \"BF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Burkina Faso`)\n\n\t\t// Bulgaria\n\t\tcase \"BG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bulgaria`)\n\n\t\t// Bahrain\n\t\tcase \"BH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bahrain`)\n\n\t\t// Burundi\n\t\tcase \"BI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Burundi`)\n\n\t\t// Benin\n\t\tcase \"BJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Benin`)\n\n\t\t// Saint Barthélemy\n\t\tcase \"BL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Barthélemy`)\n\n\t\t// Bermuda\n\t\tcase \"BM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bermuda`)\n\n\t\t// Brunei Darussalam\n\t\tcase \"BN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Brunei Darussalam`)\n\n\t\t// Bolivia, Plurinational State of\n\t\tcase \"BO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bolivia, Plurinational State of`)\n\n\t\t// Bonaire, Sint Eustatius and Saba\n\t\tcase \"BQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bonaire, Sint Eustatius and Saba`)\n\n\t\t// Brazil\n\t\tcase \"BR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Brazil`)\n\n\t\t// Bahamas\n\t\tcase \"BS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bahamas`)\n\n\t\t// Bhutan\n\t\tcase \"BT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bhutan`)\n\n\t\t// Bouvet Island\n\t\tcase \"BV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bouvet Island`)\n\n\t\t// Botswana\n\t\tcase \"BW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Botswana`)\n\n\t\t// Belarus\n\t\tcase \"BY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belarus`)\n\n\t\t// Belize\n\t\tcase \"BZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belize`)\n\n\t\t// Canada\n\t\tcase \"CA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Canada`)\n\n\t\t// Cocos (Keeling) Islands\n\t\tcase \"CC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cocos (Keeling) Islands`)\n\n\t\t// Congo, Democratic Republic of the\n\t\tcase \"CD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Congo, Democratic Republic of the`)\n\n\t\t// Central African Republic\n\t\tcase \"CF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Central African Republic`)\n\n\t\t// Congo\n\t\tcase \"CG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Congo`)\n\n\t\t// Switzerland\n\t\tcase \"CH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Switzerland`)\n\n\t\t// Cote d’Ivoire\n\t\tcase \"CI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cote d’Ivoire`)\n\n\t\t// Cook Islands\n\t\tcase \"CK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cook Islands`)\n\n\t\t// Chile\n\t\tcase \"CL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Chile`)\n\n\t\t// Cameroon\n\t\tcase \"CM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cameroon`)\n\n\t\t// China\n\t\tcase \"CN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `China`)\n\n\t\t// Colombia\n\t\tcase \"CO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Colombia`)\n\n\t\t// Costa Rica\n\t\tcase \"CR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Costa Rica`)\n\n\t\t// DEPRECATED, replaced by ME – Montenegro and RS – Serbia\n\t\tcase \"CS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Serbia and Montenegro`)\n\n\t\t// Cuba\n\t\tcase \"CU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cuba`)\n\n\t\t// Cabo Verde\n\t\tcase \"CV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cabo Verde`)\n\n\t\t// Curaçao\n\t\tcase \"CW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Curaçao`)\n\n\t\t// Christmas Island\n\t\tcase \"CX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Christmas Island`)\n\n\t\t// Cyprus\n\t\tcase \"CY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cyprus`)\n\n\t\t// Formerly Czech Republic\n\t\tcase \"CZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Czechia`)\n\n\t\t// Germany\n\t\tcase \"DE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Germany`)\n\n\t\t// Djibouti\n\t\tcase \"DJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Djibouti`)\n\n\t\t// Denmark\n\t\tcase \"DK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Denmark`)\n\n\t\t// Dominica\n\t\tcase \"DM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Dominica`)\n\n\t\t// Dominican Republic\n\t\tcase \"DO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Dominican Republic`)\n\n\t\t// Algeria\n\t\tcase \"DZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Algeria`)\n\n\t\t// Ecuador\n\t\tcase \"EC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ecuador`)\n\n\t\t// Estonia\n\t\tcase \"EE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Estonia`)\n\n\t\t// Egypt\n\t\tcase \"EG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Egypt`)\n\n\t\t// Western Sahara\n\t\tcase \"EH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Western Sahara`)\n\n\t\t// Eritrea\n\t\tcase \"ER\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Eritrea`)\n\n\t\t// Spain\n\t\tcase \"ES\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Spain`)\n\n\t\t// Ethiopia\n\t\tcase \"ET\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ethiopia`)\n\n\t\t// Finland\n\t\tcase \"FI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Finland`)\n\n\t\t// Fiji\n\t\tcase \"FJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Fiji`)\n\n\t\t// Falkland Islands (Malvinas)\n\t\tcase \"FK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Falkland Islands (Malvinas)`)\n\n\t\t// Micronesia, Federated States of\n\t\tcase \"FM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Micronesia, Federated States of`)\n\n\t\t// Faroe Islands\n\t\tcase \"FO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Faroe Islands`)\n\n\t\t// France\n\t\tcase \"FR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `France`)\n\n\t\t// Gabon\n\t\tcase \"GA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gabon`)\n\n\t\t// United Kingdom\n\t\tcase \"GB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United Kingdom`)\n\n\t\t// Grenada\n\t\tcase \"GD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Grenada`)\n\n\t\t// Georgia\n\t\tcase \"GE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Georgia`)\n\n\t\t// French Guiana\n\t\tcase \"GF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Guiana`)\n\n\t\t// Guernsey\n\t\tcase \"GG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guernsey`)\n\n\t\t// Ghana\n\t\tcase \"GH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ghana`)\n\n\t\t// Gibraltar\n\t\tcase \"GI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gibraltar`)\n\n\t\t// Greenland\n\t\tcase \"GL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Greenland`)\n\n\t\t// Gambia\n\t\tcase \"GM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gambia`)\n\n\t\t// Guinea\n\t\tcase \"GN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guinea`)\n\n\t\t// Guadeloupe\n\t\tcase \"GP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guadeloupe`)\n\n\t\t// Equatorial Guinea\n\t\tcase \"GQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Equatorial Guinea`)\n\n\t\t// Greece\n\t\tcase \"GR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Greece`)\n\n\t\t// South Georgia and the South Sandwich Islands\n\t\tcase \"GS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Georgia and the South Sandwich Islands`)\n\n\t\t// Guatemala\n\t\tcase \"GT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guatemala`)\n\n\t\t// Guam\n\t\tcase \"GU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guam`)\n\n\t\t// Guinea-Bissau\n\t\tcase \"GW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guinea-Bissau`)\n\n\t\t// Guyana\n\t\tcase \"GY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guyana`)\n\n\t\t// Hong Kong\n\t\tcase \"HK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Hong Kong`)\n\n\t\t// Heard Island and McDonald Islands\n\t\tcase \"HM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Heard Island and McDonald Islands`)\n\n\t\t// Honduras\n\t\tcase \"HN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Honduras`)\n\n\t\t// Croatia\n\t\tcase \"HR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Croatia`)\n\n\t\t// Haiti\n\t\tcase \"HT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Haiti`)\n\n\t\t// Hungary\n\t\tcase \"HU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Hungary`)\n\n\t\t// Indonesia\n\t\tcase \"ID\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Indonesia`)\n\n\t\t// Ireland\n\t\tcase \"IE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ireland`)\n\n\t\t// Israel\n\t\tcase \"IL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Israel`)\n\n\t\t// Isle of Man\n\t\tcase \"IM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Isle of Man`)\n\n\t\t// India\n\t\tcase \"IN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `India`)\n\n\t\t// British Indian Ocean Territory\n\t\tcase \"IO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `British Indian Ocean Territory`)\n\n\t\t// Iraq\n\t\tcase \"IQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iraq`)\n\n\t\t// Iran, Islamic Republic of\n\t\tcase \"IR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iran, Islamic Republic of`)\n\n\t\t// Iceland\n\t\tcase \"IS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iceland`)\n\n\t\t// Italy\n\t\tcase \"IT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Italy`)\n\n\t\t// Jersey\n\t\tcase \"JE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jersey`)\n\n\t\t// Jamaica\n\t\tcase \"JM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jamaica`)\n\n\t\t// Jordan\n\t\tcase \"JO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jordan`)\n\n\t\t// Japan\n\t\tcase \"JP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Japan`)\n\n\t\t// Kenya\n\t\tcase \"KE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kenya`)\n\n\t\t// Kyrgyzstan\n\t\tcase \"KG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kyrgyzstan`)\n\n\t\t// Cambodia\n\t\tcase \"KH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cambodia`)\n\n\t\t// Kiribati\n\t\tcase \"KI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kiribati`)\n\n\t\t// Comoros\n\t\tcase \"KM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Comoros`)\n\n\t\t// Saint Kitts and Nevis\n\t\tcase \"KN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Kitts and Nevis`)\n\n\t\t// Korea, Democratic People’s Republic of\n\t\tcase \"KP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Korea, Democratic People’s Republic of`)\n\n\t\t// Korea, Republic of\n\t\tcase \"KR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Korea, Republic of`)\n\n\t\t// Kuwait\n\t\tcase \"KW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kuwait`)\n\n\t\t// Cayman Islands\n\t\tcase \"KY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cayman Islands`)\n\n\t\t// Kazakhstan\n\t\tcase \"KZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kazakhstan`)\n\n\t\t// Lao People’s Democratic Republic\n\t\tcase \"LA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lao People’s Democratic Republic`)\n\n\t\t// Lebanon\n\t\tcase \"LB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lebanon`)\n\n\t\t// Saint Lucia\n\t\tcase \"LC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Lucia`)\n\n\t\t// Liechtenstein\n\t\tcase \"LI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Liechtenstein`)\n\n\t\t// Sri Lanka\n\t\tcase \"LK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sri Lanka`)\n\n\t\t// Liberia\n\t\tcase \"LR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Liberia`)\n\n\t\t// Lesotho\n\t\tcase \"LS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lesotho`)\n\n\t\t// Lithuania\n\t\tcase \"LT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lithuania`)\n\n\t\t// Luxembourg\n\t\tcase \"LU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Luxembourg`)\n\n\t\t// Latvia\n\t\tcase \"LV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Latvia`)\n\n\t\t// Libya\n\t\tcase \"LY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Libya`)\n\n\t\t// Morocco\n\t\tcase \"MA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Morocco`)\n\n\t\t// Monaco\n\t\tcase \"MC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Monaco`)\n\n\t\t// Moldova, Republic of\n\t\tcase \"MD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Moldova, Republic of`)\n\n\t\t// Montenegro\n\t\tcase \"ME\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Montenegro`)\n\n\t\t// Saint Martin (French part)\n\t\tcase \"MF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Martin (French part)`)\n\n\t\t// Madagascar\n\t\tcase \"MG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Madagascar`)\n\n\t\t// Marshall Islands\n\t\tcase \"MH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Marshall Islands`)\n\n\t\t// Formerly FYR Macedonia\n\t\tcase \"MK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `North Macedonia`)\n\n\t\t// Mali\n\t\tcase \"ML\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mali`)\n\n\t\t// Myanmar\n\t\tcase \"MM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Myanmar`)\n\n\t\t// Mongolia\n\t\tcase \"MN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mongolia`)\n\n\t\t// Macao\n\t\tcase \"MO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Macao`)\n\n\t\t// Northern Mariana Islands\n\t\tcase \"MP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Northern Mariana Islands`)\n\n\t\t// Martinique\n\t\tcase \"MQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Martinique`)\n\n\t\t// Mauritania\n\t\tcase \"MR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mauritania`)\n\n\t\t// Montserrat\n\t\tcase \"MS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Montserrat`)\n\n\t\t// Malta\n\t\tcase \"MT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malta`)\n\n\t\t// Mauritius\n\t\tcase \"MU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mauritius`)\n\n\t\t// Maldives\n\t\tcase \"MV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Maldives`)\n\n\t\t// Malawi\n\t\tcase \"MW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malawi`)\n\n\t\t// Mexico\n\t\tcase \"MX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mexico`)\n\n\t\t// Malaysia\n\t\tcase \"MY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malaysia`)\n\n\t\t// Mozambique\n\t\tcase \"MZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mozambique`)\n\n\t\t// Namibia\n\t\tcase \"NA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Namibia`)\n\n\t\t// New Caledonia\n\t\tcase \"NC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `New Caledonia`)\n\n\t\t// Niger\n\t\tcase \"NE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Niger`)\n\n\t\t// Norfolk Island\n\t\tcase \"NF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Norfolk Island`)\n\n\t\t// Nigeria\n\t\tcase \"NG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nigeria`)\n\n\t\t// Nicaragua\n\t\tcase \"NI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nicaragua`)\n\n\t\t// Netherlands\n\t\tcase \"NL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Netherlands`)\n\n\t\t// Norway\n\t\tcase \"NO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Norway`)\n\n\t\t// Nepal\n\t\tcase \"NP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nepal`)\n\n\t\t// Nauru\n\t\tcase \"NR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nauru`)\n\n\t\t// Niue\n\t\tcase \"NU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Niue`)\n\n\t\t// New Zealand\n\t\tcase \"NZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `New Zealand`)\n\n\t\t// Oman\n\t\tcase \"OM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Oman`)\n\n\t\t// Panama\n\t\tcase \"PA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Panama`)\n\n\t\t// Peru\n\t\tcase \"PE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Peru`)\n\n\t\t// French Polynesia\n\t\tcase \"PF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Polynesia`)\n\n\t\t// Papua New Guinea\n\t\tcase \"PG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Papua New Guinea`)\n\n\t\t// Philippines\n\t\tcase \"PH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Philippines`)\n\n\t\t// Pakistan\n\t\tcase \"PK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Pakistan`)\n\n\t\t// Poland\n\t\tcase \"PL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Poland`)\n\n\t\t// Saint Pierre and Miquelon\n\t\tcase \"PM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Pierre and Miquelon`)\n\n\t\t// Pitcairn\n\t\tcase \"PN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Pitcairn`)\n\n\t\t// Puerto Rico\n\t\tcase \"PR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Puerto Rico`)\n\n\t\t// Palestine, State of\n\t\tcase \"PS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Palestine, State of`)\n\n\t\t// Portugal\n\t\tcase \"PT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Portugal`)\n\n\t\t// Palau\n\t\tcase \"PW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Palau`)\n\n\t\t// Paraguay\n\t\tcase \"PY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Paraguay`)\n\n\t\t// Qatar\n\t\tcase \"QA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Qatar`)\n\n\t\t// Réunion\n\t\tcase \"RE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Réunion`)\n\n\t\t// Romania\n\t\tcase \"RO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Romania`)\n\n\t\t// Serbia\n\t\tcase \"RS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Serbia`)\n\n\t\t// Russian Federation\n\t\tcase \"RU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Russian Federation`)\n\n\t\t// Rwanda\n\t\tcase \"RW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Rwanda`)\n\n\t\t// Saudi Arabia\n\t\tcase \"SA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saudi Arabia`)\n\n\t\t// Solomon Islands\n\t\tcase \"SB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Solomon Islands`)\n\n\t\t// Seychelles\n\t\tcase \"SC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Seychelles`)\n\n\t\t// Sudan\n\t\tcase \"SD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sudan`)\n\n\t\t// Sweden\n\t\tcase \"SE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sweden`)\n\n\t\t// Singapore\n\t\tcase \"SG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Singapore`)\n\n\t\t// Saint Helena, Ascension and Tristan da Cunha\n\t\tcase \"SH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Helena, Ascension and Tristan da Cunha`)\n\n\t\t// Slovenia\n\t\tcase \"SI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Slovenia`)\n\n\t\t// Svalbard and Jan Mayen\n\t\tcase \"SJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Svalbard and Jan Mayen`)\n\n\t\t// Slovakia\n\t\tcase \"SK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Slovakia`)\n\n\t\t// Sierra Leone\n\t\tcase \"SL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sierra Leone`)\n\n\t\t// San Marino\n\t\tcase \"SM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `San Marino`)\n\n\t\t// Senegal\n\t\tcase \"SN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Senegal`)\n\n\t\t// Somalia\n\t\tcase \"SO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Somalia`)\n\n\t\t// Suriname\n\t\tcase \"SR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Suriname`)\n\n\t\t// South Sudan\n\t\tcase \"SS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Sudan`)\n\n\t\t// Sao Tome and Principe\n\t\tcase \"ST\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sao Tome and Principe`)\n\n\t\t// El Salvador\n\t\tcase \"SV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `El Salvador`)\n\n\t\t// Sint Maarten (Dutch part)\n\t\tcase \"SX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sint Maarten (Dutch part)`)\n\n\t\t// Syrian Arab Republic\n\t\tcase \"SY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Syrian Arab Republic`)\n\n\t\t// Formerly known as Swaziland\n\t\tcase \"SZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Eswatini`)\n\n\t\t// Turks and Caicos Islands\n\t\tcase \"TC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turks and Caicos Islands`)\n\n\t\t// Chad\n\t\tcase \"TD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Chad`)\n\n\t\t// French Southern Territories\n\t\tcase \"TF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Southern Territories`)\n\n\t\t// Togo\n\t\tcase \"TG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Togo`)\n\n\t\t// Thailand\n\t\tcase \"TH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Thailand`)\n\n\t\t// Tajikistan\n\t\tcase \"TJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tajikistan`)\n\n\t\t// Tokelau\n\t\tcase \"TK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tokelau`)\n\n\t\t// Timor-Leste\n\t\tcase \"TL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Timor-Leste`)\n\n\t\t// Turkmenistan\n\t\tcase \"TM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turkmenistan`)\n\n\t\t// Tunisia\n\t\tcase \"TN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tunisia`)\n\n\t\t// Tonga\n\t\tcase \"TO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tonga`)\n\n\t\t// Turkey\n\t\tcase \"TR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turkey`)\n\n\t\t// Trinidad and Tobago\n\t\tcase \"TT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Trinidad and Tobago`)\n\n\t\t// Tuvalu\n\t\tcase \"TV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tuvalu`)\n\n\t\t// Taiwan, Province of China\n\t\tcase \"TW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Taiwan, Province of China`)\n\n\t\t// Tanzania, United Republic of\n\t\tcase \"TZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tanzania, United Republic of`)\n\n\t\t// Ukraine\n\t\tcase \"UA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ukraine`)\n\n\t\t// Uganda\n\t\tcase \"UG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uganda`)\n\n\t\t// United States Minor Outlying Islands\n\t\tcase \"UM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United States Minor Outlying Islands`)\n\n\t\t// United States\n\t\tcase \"US\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United States`)\n\n\t\t// Uruguay\n\t\tcase \"UY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uruguay`)\n\n\t\t// Uzbekistan\n\t\tcase \"UZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uzbekistan`)\n\n\t\t// Holy See (Vatican City State)\n\t\tcase \"VA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Holy See (Vatican City State)`)\n\n\t\t// Saint Vincent and the Grenadines\n\t\tcase \"VC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Vincent and the Grenadines`)\n\n\t\t// Venezuela, Bolivarian Republic of\n\t\tcase \"VE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Venezuela, Bolivarian Republic of`)\n\n\t\t// Virgin Islands, British\n\t\tcase \"VG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Virgin Islands, British`)\n\n\t\t// Virgin Islands, US\n\t\tcase \"VI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Virgin Islands, US`)\n\n\t\t// Viet Nam\n\t\tcase \"VN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Viet Nam`)\n\n\t\t// Vanuatu\n\t\tcase \"VU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Vanuatu`)\n\n\t\t// Wallis and Futuna\n\t\tcase \"WF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Wallis and Futuna`)\n\n\t\t// Samoa\n\t\tcase \"WS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Samoa`)\n\n\t\t// Yemen\n\t\tcase \"YE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Yemen`)\n\n\t\t// Mayotte\n\t\tcase \"YT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mayotte`)\n\n\t\t// DEPRECATED, replaced by ME – Montenegro and RS – Serbia\n\t\tcase \"YU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Yugoslavia`)\n\n\t\t// South Africa\n\t\tcase \"ZA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Africa`)\n\n\t\t// Zambia\n\t\tcase \"ZM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Zambia`)\n\n\t\t// Zimbabwe\n\t\tcase \"ZW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Zimbabwe`)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"undefined code for CountryCode has been passed, got [%s]\", v)\n\t\t}\n\t}\n\tc.Body = tmpeCodes\n\treturn nil\n}", "func (r *Response) XML(userStruct interface{}, charsetReader XMLCharDecoder) error {\n\n\tif r.Error != nil {\n\t\treturn r.Error\n\t}\n\n\txmlDecoder := xml.NewDecoder(r.getInternalReader())\n\n\tif charsetReader != nil {\n\t\txmlDecoder.CharsetReader = charsetReader\n\t}\n\n\tdefer r.Close()\n\n\tif err := xmlDecoder.Decode(&userStruct); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Conf) InitFromBytes(content []byte) error {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.content = content\n\txmlDecoder := xml.NewDecoder(bytes.NewReader(c.content))\n\tvar nodeStack []*elem\n\tnodeStack = append(nodeStack, c.root)\n\tfor {\n\t\tcurrNode := nodeStack[len(nodeStack)-1]\n\t\ttoken, _ := xmlDecoder.Token()\n\t\tif token == nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch t := token.(type) {\n\t\tcase xml.CharData:\n\t\t\tlineDecoder := bufio.NewScanner(bytes.NewReader(t))\n\t\t\tlineDecoder.Split(bufio.ScanLines)\n\t\t\tfor lineDecoder.Scan() {\n\t\t\t\tline := strings.Trim(lineDecoder.Text(), whiteSpaceChars)\n\t\t\t\tif (len(line) > 0 && line[0] == '#') || line == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// add Line data\n\t\t\t\tcurrNode.addLine(line)\n\t\t\t\tkv := strings.SplitN(line, \"=\", 2)\n\t\t\t\tk, v := strings.Trim(kv[0], whiteSpaceChars), \"\"\n\t\t\t\tif k == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif len(kv) == 2 {\n\t\t\t\t\tv = strings.Trim(kv[1], whiteSpaceChars)\n\t\t\t\t}\n\t\t\t\tleaf := newElem(Leaf, k)\n\t\t\t\tleaf.setValue(v)\n\t\t\t\tcurrNode.addChild(k, leaf)\n\t\t\t}\n\t\tcase xml.StartElement:\n\t\t\tnodeName := t.Name.Local\n\t\t\tnode, ok := currNode.findChild(nodeName)\n\t\t\tif !ok {\n\t\t\t\tnode = newElem(Node, nodeName)\n\t\t\t\tcurrNode.addChild(nodeName, node)\n\t\t\t}\n\t\t\tnodeStack = append(nodeStack, node)\n\t\tcase xml.EndElement:\n\t\t\tnodeName := t.Name.Local\n\t\t\tif currNode.name != nodeName {\n\t\t\t\treturn fmt.Errorf(\"xml end not match :%s\", nodeName)\n\t\t\t}\n\t\t\tnodeStack = nodeStack[:len(nodeStack)-1]\n\t\t}\n\t}\n\treturn nil\n}", "func DecodeAndInflateString(data string) ([]byte, error) {\n\tcompressedXML, err := DecodeString(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbXML := util.Decompress(compressedXML)\n\treturn bXML, nil\n}", "func (c *PrimaryContentType) 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 // Readable text of the main work: this value is required, together with applicable <ProductForm> and <ProductFormDetail> values, to designate an e-book or other digital or physical product whose primary content is eye-readable text\n case \"10\":\n\t\tc.Body = `Text (eye-readable)`\n\n // E-publication contains a significant number of actionable cross-references, hyperlinked notes and annotations, or with other actionable links between largely textual elements (eg quiz/test questions, ‘choose your own ending’ etc)\n case \"15\":\n\t\tc.Body = `Extensive links between internal content`\n\n // E-publication contains a significant number of actionable (clickable) web links\n case \"14\":\n\t\tc.Body = `Extensive links to external content`\n\n // Publication contains additional textual content such as interview, feature article, essay, bibliography, quiz/test, other background material or text that is not included in a primary or ‘unenhanced’ version\n case \"16\":\n\t\tc.Body = `Additional eye-readable text not part of main work`\n\n // Publication contains a significant number of web links (printed URLs, QR codes etc). For use in ONIX 3.0 only\n case \"41\":\n\t\tc.Body = `Additional eye-readable links to external content`\n\n // eg Teaser chapter\n case \"17\":\n\t\tc.Body = `Promotional text for other book product`\n\n // Musical notation\n case \"11\":\n\t\tc.Body = `Musical notation`\n\n // Use only when no more detailed specification is provided\n case \"07\":\n\t\tc.Body = `Still images / graphics`\n\n // Whether in a plate section / insert, or not\n case \"18\":\n\t\tc.Body = `Photographs`\n\n // Including other ‘mechanical’ (ie non-photographic) illustrations\n case \"19\":\n\t\tc.Body = `Figures, diagrams, charts, graphs`\n\n // Publication is enhanced with additional images or graphical content such as supplementary photographs that are not included in a primary or ‘unenhanced’ version\n case \"20\":\n\t\tc.Body = `Additional images / graphics not part of main work`\n\n // Maps and/or other cartographic content\n case \"12\":\n\t\tc.Body = `Maps and/or other cartographic content`\n\n // eg Questions or student exercises, problems, quizzes or tests (as an integral part of the work). For use in ONIX 3.0 only\n case \"42\":\n\t\tc.Body = `Assessment material`\n\n // Audio recording of a reading of a book or other text\n case \"01\":\n\t\tc.Body = `Audiobook`\n\n // Audio recording of a drama or other spoken word performance\n case \"02\":\n\t\tc.Body = `Performance – spoken word`\n\n // eg an interview, speech, lecture or discussion, not a ‘reading’ or ‘performance’)\n case \"13\":\n\t\tc.Body = `Other speech content`\n\n // Audio recording of a music performance, including musical drama and opera\n case \"03\":\n\t\tc.Body = `Music recording`\n\n // Audio recording of other sound, eg birdsong\n case \"04\":\n\t\tc.Body = `Other audio`\n\n // Audio recording of a reading, performance or dramatization of part of the work\n case \"21\":\n\t\tc.Body = `Partial performance – spoken word`\n\n // Product is enhanced with audio recording of full or partial reading, performance, dramatization, interview, background documentary or other audio content not included in the primary or ‘unenhanced’ version\n case \"22\":\n\t\tc.Body = `Additional audio content not part of main work`\n\n // eg Reading of teaser chapter\n case \"23\":\n\t\tc.Body = `Promotional audio for other book product`\n\n // Includes Film, video, animation etc. Use only when no more detailed specification is provided. Formerly ‘Moving images’\n case \"06\":\n\t\tc.Body = `Video`\n\n // Video recording of a reading\n case \"26\":\n\t\tc.Body = `Video recording of a reading`\n\n // Video recording of a drama or other performance, including musical performance\n case \"27\":\n\t\tc.Body = `Performance – visual`\n\n // eg animated diagrams, charts, graphs or other illustrations\n case \"24\":\n\t\tc.Body = `Animated / interactive illustrations`\n\n // eg cartoon, animatic or CGI animation\n case \"25\":\n\t\tc.Body = `Narrative animation`\n\n // Other video content eg interview, not a reading or performance\n case \"28\":\n\t\tc.Body = `Other video`\n\n // Video recording of a reading, performance or dramatization of part of the work\n case \"29\":\n\t\tc.Body = `Partial performance – video`\n\n // E-publication is enhanced with video recording of full or partial reading, performance, dramatization, interview, background documentary or other content not included in the primary or ‘unenhanced’ version\n case \"30\":\n\t\tc.Body = `Additional video content not part of main work`\n\n // eg Book trailer\n case \"31\":\n\t\tc.Body = `Promotional video for other book product`\n\n // No multi-user functionality. Formerly just ‘Game’\n case \"05\":\n\t\tc.Body = `Game / Puzzle`\n\n // Includes some degree of multi-user functionality\n case \"32\":\n\t\tc.Body = `Contest`\n\n // Largely ‘content free’\n case \"08\":\n\t\tc.Body = `Software`\n\n // Data files\n case \"09\":\n\t\tc.Body = `Data`\n\n // Data set plus software\n case \"33\":\n\t\tc.Body = `Data set plus software`\n\n // Entire pages or blank spaces, forms, boxes etc, intended to be filled in by the reader\n case \"34\":\n\t\tc.Body = `Blank pages or spaces`\n\n // Use only where type of advertising content is not stated\n case \"35\":\n\t\tc.Body = `Advertising content`\n\n // ‘Back ads’ – promotional pages for other books (that do not include sample content, cf codes 17, 23)\n case \"37\":\n\t\tc.Body = `Advertising – first party`\n\n // Eg to obtain discounts on other products\n case \"36\":\n\t\tc.Body = `Advertising – coupons`\n\n // Advertising – third party display\n case \"38\":\n\t\tc.Body = `Advertising – third party display`\n\n // Advertising – third party textual\n case \"39\":\n\t\tc.Body = `Advertising – third party textual`\n\n // E-publication contains microprograms written (eg) in Javascript and executed within the reading system. For use in ONIX 3.0 only\n case \"40\":\n\t\tc.Body = `Scripting`\n\n // E-publication contains pop-ups or other functionality offering (eg) term definitions, cross-links or glossary entries [Note this should not include (eg) dictionary funcionality that is part of the reading system.] For use in ONIX 3.0 only\n case \"43\":\n\t\tc.Body = `Scripted pop-ups`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for PrimaryContentType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *BibleTextFeature) 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 // Words spoken by Christ are printed in red\n case \"RL\":\n\t\tc.Body = `Red letter`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for BibleTextFeature has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *CitedContentType) 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 // The full text of a review in a third-party publication in any medium\n case \"01\":\n\t\tc.Body = `Review`\n\n // Bestseller list\n case \"02\":\n\t\tc.Body = `Bestseller list`\n\n // Other than a review\n case \"03\":\n\t\tc.Body = `Media mention`\n\n // (North America) Inclusion in a program such as ‘Chicago Reads’, ‘Seattle Reads’\n case \"04\":\n\t\tc.Body = `‘One locality, one book’ program`\n\n // For example a ‘best books of the year’ or ‘25 books you should have read’ list, without regard to their bestseller status\n case \"05\":\n\t\tc.Body = `Curated list`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for CitedContentType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *TextFormatCode) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for TextFormatCode has been passed, got [%s]\", v)\n\t}\n}", "func (c *LanguageCode) 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 // Afar\n case \"aar\":\n\t\tc.Body = `Afar`\n\n // Abkhaz\n case \"abk\":\n\t\tc.Body = `Abkhaz`\n\n // Achinese\n case \"ace\":\n\t\tc.Body = `Achinese`\n\n // Acoli\n case \"ach\":\n\t\tc.Body = `Acoli`\n\n // Adangme\n case \"ada\":\n\t\tc.Body = `Adangme`\n\n // Adygei\n case \"ady\":\n\t\tc.Body = `Adygei`\n\n // Collective name\n case \"afa\":\n\t\tc.Body = `Afro-Asiatic languages`\n\n // Artificial language\n case \"afh\":\n\t\tc.Body = `Afrihili`\n\n // Afrikaans\n case \"afr\":\n\t\tc.Body = `Afrikaans`\n\n // Ainu\n case \"ain\":\n\t\tc.Body = `Ainu`\n\n // Macrolanguage\n case \"aka\":\n\t\tc.Body = `Akan`\n\n // Akkadian\n case \"akk\":\n\t\tc.Body = `Akkadian`\n\n // Macrolanguage\n case \"alb\":\n\t\tc.Body = `Albanian`\n\n // Aleut\n case \"ale\":\n\t\tc.Body = `Aleut`\n\n // Collective name\n case \"alg\":\n\t\tc.Body = `Algonquian languages`\n\n // Southern Altai\n case \"alt\":\n\t\tc.Body = `Southern Altai`\n\n // Amharic\n case \"amh\":\n\t\tc.Body = `Amharic`\n\n // English, Old (ca. 450-1100)\n case \"ang\":\n\t\tc.Body = `English, Old (ca. 450-1100)`\n\n // Angika\n case \"anp\":\n\t\tc.Body = `Angika`\n\n // Collective name\n case \"apa\":\n\t\tc.Body = `Apache languages`\n\n // Macrolanguage\n case \"ara\":\n\t\tc.Body = `Arabic`\n\n // Official Aramaic; Imperial Aramaic (700-300 BCE)\n case \"arc\":\n\t\tc.Body = `Official Aramaic; Imperial Aramaic (700-300 BCE)`\n\n // Aragonese\n case \"arg\":\n\t\tc.Body = `Aragonese`\n\n // Armenian\n case \"arm\":\n\t\tc.Body = `Armenian`\n\n // Mapudungun; Mapuche\n case \"arn\":\n\t\tc.Body = `Mapudungun; Mapuche`\n\n // Arapaho\n case \"arp\":\n\t\tc.Body = `Arapaho`\n\n // Collective name\n case \"art\":\n\t\tc.Body = `Artificial languages`\n\n // Arawak\n case \"arw\":\n\t\tc.Body = `Arawak`\n\n // Assamese\n case \"asm\":\n\t\tc.Body = `Assamese`\n\n // Asturian; Bable; Leonese; Asturleonese\n case \"ast\":\n\t\tc.Body = `Asturian; Bable; Leonese; Asturleonese`\n\n // Collective name\n case \"ath\":\n\t\tc.Body = `Athapascan languages`\n\n // Collective name\n case \"aus\":\n\t\tc.Body = `Australian languages`\n\n // Avaric\n case \"ava\":\n\t\tc.Body = `Avaric`\n\n // Avestan\n case \"ave\":\n\t\tc.Body = `Avestan`\n\n // Awadhi\n case \"awa\":\n\t\tc.Body = `Awadhi`\n\n // Macrolanguage\n case \"aym\":\n\t\tc.Body = `Aymara`\n\n // Macrolanguage\n case \"aze\":\n\t\tc.Body = `Azerbaijani`\n\n // Collective name\n case \"bad\":\n\t\tc.Body = `Banda languages`\n\n // Collective name\n case \"bai\":\n\t\tc.Body = `Bamileke languages`\n\n // Bashkir\n case \"bak\":\n\t\tc.Body = `Bashkir`\n\n // Macrolanguage\n case \"bal\":\n\t\tc.Body = `Baluchi`\n\n // Bambara\n case \"bam\":\n\t\tc.Body = `Bambara`\n\n // Balinese\n case \"ban\":\n\t\tc.Body = `Balinese`\n\n // Basque\n case \"baq\":\n\t\tc.Body = `Basque`\n\n // Basa\n case \"bas\":\n\t\tc.Body = `Basa`\n\n // Collective name\n case \"bat\":\n\t\tc.Body = `Baltic languages`\n\n // Beja; Bedawiyet\n case \"bej\":\n\t\tc.Body = `Beja; Bedawiyet`\n\n // Belarusian\n case \"bel\":\n\t\tc.Body = `Belarusian`\n\n // Bemba\n case \"bem\":\n\t\tc.Body = `Bemba`\n\n // Bengali\n case \"ben\":\n\t\tc.Body = `Bengali`\n\n // Collective name\n case \"ber\":\n\t\tc.Body = `Berber languages`\n\n // Bhojpuri\n case \"bho\":\n\t\tc.Body = `Bhojpuri`\n\n // Collective name\n case \"bih\":\n\t\tc.Body = `Bihari languages`\n\n // Macrolanguage\n case \"bik\":\n\t\tc.Body = `Bikol`\n\n // Bini; Edo\n case \"bin\":\n\t\tc.Body = `Bini; Edo`\n\n // Bislama\n case \"bis\":\n\t\tc.Body = `Bislama`\n\n // Siksika\n case \"bla\":\n\t\tc.Body = `Siksika`\n\n // Collective name\n case \"bnt\":\n\t\tc.Body = `Bantu languages`\n\n // Bosnian\n case \"bos\":\n\t\tc.Body = `Bosnian`\n\n // Braj\n case \"bra\":\n\t\tc.Body = `Braj`\n\n // Breton\n case \"bre\":\n\t\tc.Body = `Breton`\n\n // Collective name\n case \"btk\":\n\t\tc.Body = `Batak languages`\n\n // Macrolanguage\n case \"bua\":\n\t\tc.Body = `Buriat`\n\n // Buginese\n case \"bug\":\n\t\tc.Body = `Buginese`\n\n // Bulgarian\n case \"bul\":\n\t\tc.Body = `Bulgarian`\n\n // Burmese\n case \"bur\":\n\t\tc.Body = `Burmese`\n\n // Blin; Bilin\n case \"byn\":\n\t\tc.Body = `Blin; Bilin`\n\n // Caddo\n case \"cad\":\n\t\tc.Body = `Caddo`\n\n // Collective name\n case \"cai\":\n\t\tc.Body = `Central American Indian languages`\n\n // Galibi Carib\n case \"car\":\n\t\tc.Body = `Galibi Carib`\n\n // Catalan\n case \"cat\":\n\t\tc.Body = `Catalan`\n\n // Collective name\n case \"cau\":\n\t\tc.Body = `Caucasian languages`\n\n // Cebuano\n case \"ceb\":\n\t\tc.Body = `Cebuano`\n\n // Collective name\n case \"cel\":\n\t\tc.Body = `Celtic languages`\n\n // Chamorro\n case \"cha\":\n\t\tc.Body = `Chamorro`\n\n // Chibcha\n case \"chb\":\n\t\tc.Body = `Chibcha`\n\n // Chechen\n case \"che\":\n\t\tc.Body = `Chechen`\n\n // Chagatai\n case \"chg\":\n\t\tc.Body = `Chagatai`\n\n // Macrolanguage\n case \"chi\":\n\t\tc.Body = `Chinese`\n\n // Chuukese (Truk)\n case \"chk\":\n\t\tc.Body = `Chuukese (Truk)`\n\n // Macrolanguage\n case \"chm\":\n\t\tc.Body = `Mari`\n\n // Chinook jargon\n case \"chn\":\n\t\tc.Body = `Chinook jargon`\n\n // Choctaw\n case \"cho\":\n\t\tc.Body = `Choctaw`\n\n // Chipewyan; Dene Suline\n case \"chp\":\n\t\tc.Body = `Chipewyan; Dene Suline`\n\n // Cherokee\n case \"chr\":\n\t\tc.Body = `Cherokee`\n\n // Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic\n case \"chu\":\n\t\tc.Body = `Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic`\n\n // Chuvash\n case \"chv\":\n\t\tc.Body = `Chuvash`\n\n // Cheyenne\n case \"chy\":\n\t\tc.Body = `Cheyenne`\n\n // ONIX local code, equivalent to ckb in ISO 639-3. For use in ONIX 3.0 only\n case \"ckb\":\n\t\tc.Body = `Central Kurdish (Sorani)`\n\n // Collective name\n case \"cmc\":\n\t\tc.Body = `Chamic languages`\n\n // ONIX local code, equivalent to cmn in ISO 639-3\n case \"cmn\":\n\t\tc.Body = `Mandarin`\n\n // For use in ONIX 3.0 only\n case \"cnr\":\n\t\tc.Body = `Montenegrin`\n\n // Coptic\n case \"cop\":\n\t\tc.Body = `Coptic`\n\n // Cornish\n case \"cor\":\n\t\tc.Body = `Cornish`\n\n // Corsican\n case \"cos\":\n\t\tc.Body = `Corsican`\n\n // Collective name\n case \"cpe\":\n\t\tc.Body = `Creoles and pidgins, English-based`\n\n // Collective name\n case \"cpf\":\n\t\tc.Body = `Creoles and pidgins, French-based`\n\n // Collective name\n case \"cpp\":\n\t\tc.Body = `Creoles and pidgins, Portuguese-based`\n\n // Macrolanguage\n case \"cre\":\n\t\tc.Body = `Cree`\n\n // Crimean Turkish; Crimean Tatar\n case \"crh\":\n\t\tc.Body = `Crimean Turkish; Crimean Tatar`\n\n // Collective name\n case \"crp\":\n\t\tc.Body = `Creoles and pidgins`\n\n // Kashubian\n case \"csb\":\n\t\tc.Body = `Kashubian`\n\n // Collective name\n case \"cus\":\n\t\tc.Body = `Cushitic languages`\n\n // Czech\n case \"cze\":\n\t\tc.Body = `Czech`\n\n // Dakota\n case \"dak\":\n\t\tc.Body = `Dakota`\n\n // Danish\n case \"dan\":\n\t\tc.Body = `Danish`\n\n // Dargwa\n case \"dar\":\n\t\tc.Body = `Dargwa`\n\n // Collective name\n case \"day\":\n\t\tc.Body = `Land Dayak languages`\n\n // Macrolanguage\n case \"del\":\n\t\tc.Body = `Delaware`\n\n // Macrolanguage\n case \"den\":\n\t\tc.Body = `Slave (Athapascan)`\n\n // Dogrib\n case \"dgr\":\n\t\tc.Body = `Dogrib`\n\n // Macrolanguage\n case \"din\":\n\t\tc.Body = `Dinka`\n\n // Divehi; Dhivehi; Maldivian\n case \"div\":\n\t\tc.Body = `Divehi; Dhivehi; Maldivian`\n\n // Macrolanguage\n case \"doi\":\n\t\tc.Body = `Dogri`\n\n // Collective name\n case \"dra\":\n\t\tc.Body = `Dravidian languages`\n\n // Lower Sorbian\n case \"dsb\":\n\t\tc.Body = `Lower Sorbian`\n\n // Duala\n case \"dua\":\n\t\tc.Body = `Duala`\n\n // Dutch, Middle (ca. 1050-1350)\n case \"dum\":\n\t\tc.Body = `Dutch, Middle (ca. 1050-1350)`\n\n // Dutch; Flemish\n case \"dut\":\n\t\tc.Body = `Dutch; Flemish`\n\n // Dyula\n case \"dyu\":\n\t\tc.Body = `Dyula`\n\n // Dzongkha\n case \"dzo\":\n\t\tc.Body = `Dzongkha`\n\n // Efik\n case \"efi\":\n\t\tc.Body = `Efik`\n\n // ONIX local code for Italian dialect, equivalent to egl in ISO 639-3. For use in ONIX 3.0 only\n case \"egl\":\n\t\tc.Body = `Emilian`\n\n // Egyptian (Ancient)\n case \"egy\":\n\t\tc.Body = `Egyptian (Ancient)`\n\n // Ekajuk\n case \"eka\":\n\t\tc.Body = `Ekajuk`\n\n // Elamite\n case \"elx\":\n\t\tc.Body = `Elamite`\n\n // English\n case \"eng\":\n\t\tc.Body = `English`\n\n // English, Middle (1100-1500)\n case \"enm\":\n\t\tc.Body = `English, Middle (1100-1500)`\n\n // Artificial language\n case \"epo\":\n\t\tc.Body = `Esperanto`\n\n // Macrolanguage\n case \"est\":\n\t\tc.Body = `Estonian`\n\n // Ewe\n case \"ewe\":\n\t\tc.Body = `Ewe`\n\n // Ewondo\n case \"ewo\":\n\t\tc.Body = `Ewondo`\n\n // Fang\n case \"fan\":\n\t\tc.Body = `Fang`\n\n // Faroese\n case \"fao\":\n\t\tc.Body = `Faroese`\n\n // Fanti\n case \"fat\":\n\t\tc.Body = `Fanti`\n\n // Fijian\n case \"fij\":\n\t\tc.Body = `Fijian`\n\n // Filipino; Pilipino\n case \"fil\":\n\t\tc.Body = `Filipino; Pilipino`\n\n // Finnish\n case \"fin\":\n\t\tc.Body = `Finnish`\n\n // ONIX local code, equivalent to fit in ISO 639-3\n case \"fit\":\n\t\tc.Body = `Meänkieli / Tornedalen Finnish`\n\n // Collective name\n case \"fiu\":\n\t\tc.Body = `Finno-Ugrian languages`\n\n // ONIX local code, equivalent to fkv in ISO 639-3\n case \"fkv\":\n\t\tc.Body = `Kvensk`\n\n // Fon\n case \"fon\":\n\t\tc.Body = `Fon`\n\n // French\n case \"fre\":\n\t\tc.Body = `French`\n\n // French, Middle (ca. 1400-1600)\n case \"frm\":\n\t\tc.Body = `French, Middle (ca. 1400-1600)`\n\n // French, Old (ca. 842-1400)\n case \"fro\":\n\t\tc.Body = `French, Old (ca. 842-1400)`\n\n // Northern Frisian\n case \"frr\":\n\t\tc.Body = `Northern Frisian`\n\n // Eastern Frisian\n case \"frs\":\n\t\tc.Body = `Eastern Frisian`\n\n // Western Frisian\n case \"fry\":\n\t\tc.Body = `Western Frisian`\n\n // Fulah\n case \"ful\":\n\t\tc.Body = `Fulah`\n\n // Friulian\n case \"fur\":\n\t\tc.Body = `Friulian`\n\n // Gã\n case \"gaa\":\n\t\tc.Body = `Gã`\n\n // Gayo\n case \"gay\":\n\t\tc.Body = `Gayo`\n\n // Macrolanguage\n case \"gba\":\n\t\tc.Body = `Gbaya`\n\n // Collective name\n case \"gem\":\n\t\tc.Body = `Germanic languages`\n\n // Georgian\n case \"geo\":\n\t\tc.Body = `Georgian`\n\n // German\n case \"ger\":\n\t\tc.Body = `German`\n\n // Ethiopic (Ge’ez)\n case \"gez\":\n\t\tc.Body = `Ethiopic (Ge’ez)`\n\n // Gilbertese\n case \"gil\":\n\t\tc.Body = `Gilbertese`\n\n // Scottish Gaelic\n case \"gla\":\n\t\tc.Body = `Scottish Gaelic`\n\n // Irish\n case \"gle\":\n\t\tc.Body = `Irish`\n\n // Galician\n case \"glg\":\n\t\tc.Body = `Galician`\n\n // Manx\n case \"glv\":\n\t\tc.Body = `Manx`\n\n // German, Middle High (ca. 1050-1500)\n case \"gmh\":\n\t\tc.Body = `German, Middle High (ca. 1050-1500)`\n\n // German, Old High (ca. 750-1050)\n case \"goh\":\n\t\tc.Body = `German, Old High (ca. 750-1050)`\n\n // Macrolanguage\n case \"gon\":\n\t\tc.Body = `Gondi`\n\n // Gorontalo\n case \"gor\":\n\t\tc.Body = `Gorontalo`\n\n // Gothic\n case \"got\":\n\t\tc.Body = `Gothic`\n\n // Macrolanguage\n case \"grb\":\n\t\tc.Body = `Grebo`\n\n // Greek, Ancient (to 1453)\n case \"grc\":\n\t\tc.Body = `Greek, Ancient (to 1453)`\n\n // Greek, Modern (1453-)\n case \"gre\":\n\t\tc.Body = `Greek, Modern (1453-)`\n\n // Macrolanguage\n case \"grn\":\n\t\tc.Body = `Guarani`\n\n // ONIX local code, equivalent to grt in ISO 639-3\n case \"grt\":\n\t\tc.Body = `Garo`\n\n // Swiss German; Alemannic\n case \"gsw\":\n\t\tc.Body = `Swiss German; Alemannic`\n\n // Gujarati\n case \"guj\":\n\t\tc.Body = `Gujarati`\n\n // Gwich’in\n case \"gwi\":\n\t\tc.Body = `Gwich’in`\n\n // Macrolanguage\n case \"hai\":\n\t\tc.Body = `Haida`\n\n // Haitian French Creole\n case \"hat\":\n\t\tc.Body = `Haitian French Creole`\n\n // Hausa\n case \"hau\":\n\t\tc.Body = `Hausa`\n\n // Hawaiian\n case \"haw\":\n\t\tc.Body = `Hawaiian`\n\n // Hebrew\n case \"heb\":\n\t\tc.Body = `Hebrew`\n\n // Herero\n case \"her\":\n\t\tc.Body = `Herero`\n\n // Hiligaynon\n case \"hil\":\n\t\tc.Body = `Hiligaynon`\n\n // Collective name\n case \"him\":\n\t\tc.Body = `Himachali languages; Western Pahari languages`\n\n // Hindi\n case \"hin\":\n\t\tc.Body = `Hindi`\n\n // Hittite\n case \"hit\":\n\t\tc.Body = `Hittite`\n\n // Macrolanguage\n case \"hmn\":\n\t\tc.Body = `Hmong; Mong`\n\n // Hiri Motu\n case \"hmo\":\n\t\tc.Body = `Hiri Motu`\n\n // Croatian\n case \"hrv\":\n\t\tc.Body = `Croatian`\n\n // Upper Sorbian\n case \"hsb\":\n\t\tc.Body = `Upper Sorbian`\n\n // Hungarian\n case \"hun\":\n\t\tc.Body = `Hungarian`\n\n // Hupa\n case \"hup\":\n\t\tc.Body = `Hupa`\n\n // Iban\n case \"iba\":\n\t\tc.Body = `Iban`\n\n // Igbo\n case \"ibo\":\n\t\tc.Body = `Igbo`\n\n // Icelandic\n case \"ice\":\n\t\tc.Body = `Icelandic`\n\n // Artificial language\n case \"ido\":\n\t\tc.Body = `Ido`\n\n // Sichuan Yi; Nuosu\n case \"iii\":\n\t\tc.Body = `Sichuan Yi; Nuosu`\n\n // Collective name\n case \"ijo\":\n\t\tc.Body = `Ijo languages`\n\n // Macrolanguage\n case \"iku\":\n\t\tc.Body = `Inuktitut`\n\n // Artificial language\n case \"ile\":\n\t\tc.Body = `Interlingue; Occidental`\n\n // Iloko\n case \"ilo\":\n\t\tc.Body = `Iloko`\n\n // Artificial language\n case \"ina\":\n\t\tc.Body = `Interlingua (International Auxiliary Language Association)`\n\n // Collective name\n case \"inc\":\n\t\tc.Body = `Indic languages`\n\n // Indonesian\n case \"ind\":\n\t\tc.Body = `Indonesian`\n\n // Collective name\n case \"ine\":\n\t\tc.Body = `Indo-European languages`\n\n // Ingush\n case \"inh\":\n\t\tc.Body = `Ingush`\n\n // Macrolanguage\n case \"ipk\":\n\t\tc.Body = `Inupiaq`\n\n // Collective name\n case \"ira\":\n\t\tc.Body = `Iranian languages`\n\n // Collective name\n case \"iro\":\n\t\tc.Body = `Iroquoian languages`\n\n // Italian\n case \"ita\":\n\t\tc.Body = `Italian`\n\n // Javanese\n case \"jav\":\n\t\tc.Body = `Javanese`\n\n // Lojban\n case \"jbo\":\n\t\tc.Body = `Lojban`\n\n // Japanese\n case \"jpn\":\n\t\tc.Body = `Japanese`\n\n // Judeo-Persian\n case \"jpr\":\n\t\tc.Body = `Judeo-Persian`\n\n // Macrolanguage\n case \"jrb\":\n\t\tc.Body = `Judeo-Arabic`\n\n // Kara-Kalpak\n case \"kaa\":\n\t\tc.Body = `Kara-Kalpak`\n\n // Kabyle\n case \"kab\":\n\t\tc.Body = `Kabyle`\n\n // Kachin; Jingpho\n case \"kac\":\n\t\tc.Body = `Kachin; Jingpho`\n\n // Kalâtdlisut; Greenlandic\n case \"kal\":\n\t\tc.Body = `Kalâtdlisut; Greenlandic`\n\n // Kamba\n case \"kam\":\n\t\tc.Body = `Kamba`\n\n // Kannada\n case \"kan\":\n\t\tc.Body = `Kannada`\n\n // Collective name\n case \"kar\":\n\t\tc.Body = `Karen languages`\n\n // Kashmiri\n case \"kas\":\n\t\tc.Body = `Kashmiri`\n\n // Macrolanguage\n case \"kau\":\n\t\tc.Body = `Kanuri`\n\n // Kawi\n case \"kaw\":\n\t\tc.Body = `Kawi`\n\n // Kazakh\n case \"kaz\":\n\t\tc.Body = `Kazakh`\n\n // Kabardian (Circassian)\n case \"kbd\":\n\t\tc.Body = `Kabardian (Circassian)`\n\n // ONIX local code, equivalent to kdr in ISO 639-3\n case \"kdr\":\n\t\tc.Body = `Karaim`\n\n // Khasi\n case \"kha\":\n\t\tc.Body = `Khasi`\n\n // Collective name\n case \"khi\":\n\t\tc.Body = `Khoisan languages`\n\n // Central Khmer\n case \"khm\":\n\t\tc.Body = `Central Khmer`\n\n // Khotanese; Sakan\n case \"kho\":\n\t\tc.Body = `Khotanese; Sakan`\n\n // Kikuyu; Gikuyu\n case \"kik\":\n\t\tc.Body = `Kikuyu; Gikuyu`\n\n // Kinyarwanda\n case \"kin\":\n\t\tc.Body = `Kinyarwanda`\n\n // Kirghiz; Kyrgyz\n case \"kir\":\n\t\tc.Body = `Kirghiz; Kyrgyz`\n\n // Kimbundu\n case \"kmb\":\n\t\tc.Body = `Kimbundu`\n\n // Macrolanguage\n case \"kok\":\n\t\tc.Body = `Konkani`\n\n // Macrolanguage\n case \"kom\":\n\t\tc.Body = `Komi`\n\n // Macrolanguage\n case \"kon\":\n\t\tc.Body = `Kongo`\n\n // Korean\n case \"kor\":\n\t\tc.Body = `Korean`\n\n // Kusaiean (Caroline Islands)\n case \"kos\":\n\t\tc.Body = `Kusaiean (Caroline Islands)`\n\n // Macrolanguage\n case \"kpe\":\n\t\tc.Body = `Kpelle`\n\n // Karachay-Balkar\n case \"krc\":\n\t\tc.Body = `Karachay-Balkar`\n\n // Karelian\n case \"krl\":\n\t\tc.Body = `Karelian`\n\n // Collective name\n case \"kro\":\n\t\tc.Body = `Kru languages`\n\n // Kurukh\n case \"kru\":\n\t\tc.Body = `Kurukh`\n\n // Kuanyama\n case \"kua\":\n\t\tc.Body = `Kuanyama`\n\n // Kumyk\n case \"kum\":\n\t\tc.Body = `Kumyk`\n\n // Macrolanguage\n case \"kur\":\n\t\tc.Body = `Kurdish`\n\n // Kutenai\n case \"kut\":\n\t\tc.Body = `Kutenai`\n\n // Ladino\n case \"lad\":\n\t\tc.Body = `Ladino`\n\n // Macrolanguage\n case \"lah\":\n\t\tc.Body = `Lahnda`\n\n // Lamba\n case \"lam\":\n\t\tc.Body = `Lamba`\n\n // Lao\n case \"lao\":\n\t\tc.Body = `Lao`\n\n // Latin\n case \"lat\":\n\t\tc.Body = `Latin`\n\n // Macrolanguage\n case \"lav\":\n\t\tc.Body = `Latvian`\n\n // Lezgian\n case \"lez\":\n\t\tc.Body = `Lezgian`\n\n // ONIX local code for Italian dialect, equivalent to lij in ISO 639-3. For use in ONIX 3.0 only\n case \"lij\":\n\t\tc.Body = `Ligurian`\n\n // Limburgish\n case \"lim\":\n\t\tc.Body = `Limburgish`\n\n // Lingala\n case \"lin\":\n\t\tc.Body = `Lingala`\n\n // Lithuanian\n case \"lit\":\n\t\tc.Body = `Lithuanian`\n\n // ONIX local code for Italian dialect, equivalent to lmo in ISO 639-3. For use in ONIX 3.0 only\n case \"lmo\":\n\t\tc.Body = `Lombard`\n\n // Mongo-Nkundu\n case \"lol\":\n\t\tc.Body = `Mongo-Nkundu`\n\n // Lozi\n case \"loz\":\n\t\tc.Body = `Lozi`\n\n // Luxembourgish; Letzeburgesch\n case \"ltz\":\n\t\tc.Body = `Luxembourgish; Letzeburgesch`\n\n // Luba-Lulua\n case \"lua\":\n\t\tc.Body = `Luba-Lulua`\n\n // Luba-Katanga\n case \"lub\":\n\t\tc.Body = `Luba-Katanga`\n\n // Ganda\n case \"lug\":\n\t\tc.Body = `Ganda`\n\n // Luiseño\n case \"lui\":\n\t\tc.Body = `Luiseño`\n\n // Lunda\n case \"lun\":\n\t\tc.Body = `Lunda`\n\n // Luo (Kenya and Tanzania)\n case \"luo\":\n\t\tc.Body = `Luo (Kenya and Tanzania)`\n\n // Lushai\n case \"lus\":\n\t\tc.Body = `Lushai`\n\n // Macedonian\n case \"mac\":\n\t\tc.Body = `Macedonian`\n\n // Madurese\n case \"mad\":\n\t\tc.Body = `Madurese`\n\n // Magahi\n case \"mag\":\n\t\tc.Body = `Magahi`\n\n // Marshallese\n case \"mah\":\n\t\tc.Body = `Marshallese`\n\n // Maithili\n case \"mai\":\n\t\tc.Body = `Maithili`\n\n // Makasar\n case \"mak\":\n\t\tc.Body = `Makasar`\n\n // Malayalam\n case \"mal\":\n\t\tc.Body = `Malayalam`\n\n // Macrolanguage\n case \"man\":\n\t\tc.Body = `Mandingo`\n\n // Maori\n case \"mao\":\n\t\tc.Body = `Maori`\n\n // Collective name\n case \"map\":\n\t\tc.Body = `Austronesian languages`\n\n // Marathi\n case \"mar\":\n\t\tc.Body = `Marathi`\n\n // Masai\n case \"mas\":\n\t\tc.Body = `Masai`\n\n // Macrolanguage\n case \"may\":\n\t\tc.Body = `Malay`\n\n // Moksha\n case \"mdf\":\n\t\tc.Body = `Moksha`\n\n // Mandar\n case \"mdr\":\n\t\tc.Body = `Mandar`\n\n // Mende\n case \"men\":\n\t\tc.Body = `Mende`\n\n // Irish, Middle (ca. 1100-1550)\n case \"mga\":\n\t\tc.Body = `Irish, Middle (ca. 1100-1550)`\n\n // Mi’kmaq; Micmac\n case \"mic\":\n\t\tc.Body = `Mi’kmaq; Micmac`\n\n // Minangkabau\n case \"min\":\n\t\tc.Body = `Minangkabau`\n\n // Use where no suitable code is available\n case \"mis\":\n\t\tc.Body = `Uncoded languages`\n\n // Collective name\n case \"mkh\":\n\t\tc.Body = `Mon-Khmer languages`\n\n // Macrolanguage\n case \"mlg\":\n\t\tc.Body = `Malagasy`\n\n // Maltese\n case \"mlt\":\n\t\tc.Body = `Maltese`\n\n // Manchu\n case \"mnc\":\n\t\tc.Body = `Manchu`\n\n // Manipuri\n case \"mni\":\n\t\tc.Body = `Manipuri`\n\n // Collective name\n case \"mno\":\n\t\tc.Body = `Manobo languages`\n\n // Mohawk\n case \"moh\":\n\t\tc.Body = `Mohawk`\n\n // DEPRECATED – use rum\n case \"mol\":\n\t\tc.Body = `Moldavian; Moldovan`\n\n // Macrolanguage\n case \"mon\":\n\t\tc.Body = `Mongolian`\n\n // Mooré; Mossi\n case \"mos\":\n\t\tc.Body = `Mooré; Mossi`\n\n // Multiple languages\n case \"mul\":\n\t\tc.Body = `Multiple languages`\n\n // Collective name\n case \"mun\":\n\t\tc.Body = `Munda languages`\n\n // Creek\n case \"mus\":\n\t\tc.Body = `Creek`\n\n // ONIX local code, equivalent to mwf in ISO 639-3. For use in ONIX 3.0 only\n case \"mwf\":\n\t\tc.Body = `Murrinh-Patha`\n\n // Mirandese\n case \"mwl\":\n\t\tc.Body = `Mirandese`\n\n // Macrolanguage\n case \"mwr\":\n\t\tc.Body = `Marwari`\n\n // Collective name\n case \"myn\":\n\t\tc.Body = `Mayan languages`\n\n // Erzya\n case \"myv\":\n\t\tc.Body = `Erzya`\n\n // Collective name\n case \"nah\":\n\t\tc.Body = `Nahuatl languages`\n\n // Collective name\n case \"nai\":\n\t\tc.Body = `North American Indian languages`\n\n // Neapolitan\n case \"nap\":\n\t\tc.Body = `Neapolitan`\n\n // Nauruan\n case \"nau\":\n\t\tc.Body = `Nauruan`\n\n // Navajo\n case \"nav\":\n\t\tc.Body = `Navajo`\n\n // Ndebele, South\n case \"nbl\":\n\t\tc.Body = `Ndebele, South`\n\n // Ndebele, North\n case \"nde\":\n\t\tc.Body = `Ndebele, North`\n\n // Ndonga\n case \"ndo\":\n\t\tc.Body = `Ndonga`\n\n // Low German; Low Saxon\n case \"nds\":\n\t\tc.Body = `Low German; Low Saxon`\n\n // Macrolanguage\n case \"nep\":\n\t\tc.Body = `Nepali`\n\n // Newari; Nepal Bhasa\n case \"new\":\n\t\tc.Body = `Newari; Nepal Bhasa`\n\n // Nias\n case \"nia\":\n\t\tc.Body = `Nias`\n\n // Collective name\n case \"nic\":\n\t\tc.Body = `Niger-Kordofanian languages`\n\n // Niuean\n case \"niu\":\n\t\tc.Body = `Niuean`\n\n // Norwegian Nynorsk\n case \"nno\":\n\t\tc.Body = `Norwegian Nynorsk`\n\n // Norwegian Bokmål\n case \"nob\":\n\t\tc.Body = `Norwegian Bokmål`\n\n // Nogai\n case \"nog\":\n\t\tc.Body = `Nogai`\n\n // Old Norse\n case \"non\":\n\t\tc.Body = `Old Norse`\n\n // Macrolanguage\n case \"nor\":\n\t\tc.Body = `Norwegian`\n\n // N’Ko\n case \"nqo\":\n\t\tc.Body = `N’Ko`\n\n // ONIX local code, equivalent to nrf in ISO 639-3. For use in ONIX 3.0 only\n case \"nrf\":\n\t\tc.Body = `Guernésiais, Jèrriais`\n\n // Pedi; Sepedi; Northern Sotho\n case \"nso\":\n\t\tc.Body = `Pedi; Sepedi; Northern Sotho`\n\n // Collective name\n case \"nub\":\n\t\tc.Body = `Nubian languages`\n\n // Classical Newari; Old Newari; Classical Nepal Bhasa\n case \"nwc\":\n\t\tc.Body = `Classical Newari; Old Newari; Classical Nepal Bhasa`\n\n // Chichewa; Chewa; Nyanja\n case \"nya\":\n\t\tc.Body = `Chichewa; Chewa; Nyanja`\n\n // Nyamwezi\n case \"nym\":\n\t\tc.Body = `Nyamwezi`\n\n // Nyankole\n case \"nyn\":\n\t\tc.Body = `Nyankole`\n\n // Nyoro\n case \"nyo\":\n\t\tc.Body = `Nyoro`\n\n // Nzima\n case \"nzi\":\n\t\tc.Body = `Nzima`\n\n // Occitan (post 1500)\n case \"oci\":\n\t\tc.Body = `Occitan (post 1500)`\n\n // ONIX local code, equivalent to odt in ISO 639-3\n case \"odt\":\n\t\tc.Body = `Old Dutch / Old Low Franconian (ca. 400–1050)`\n\n // Macrolanguage\n case \"oji\":\n\t\tc.Body = `Ojibwa`\n\n // ONIX local code, equivalent to omq in ISO 639-5. Collective name\n case \"omq\":\n\t\tc.Body = `Oto-Manguean languages`\n\n // Macrolanguage\n case \"ori\":\n\t\tc.Body = `Oriya`\n\n // Macrolanguage\n case \"orm\":\n\t\tc.Body = `Oromo`\n\n // Osage\n case \"osa\":\n\t\tc.Body = `Osage`\n\n // Ossetian; Ossetic\n case \"oss\":\n\t\tc.Body = `Ossetian; Ossetic`\n\n // Turkish, Ottoman\n case \"ota\":\n\t\tc.Body = `Turkish, Ottoman`\n\n // Collective name\n case \"oto\":\n\t\tc.Body = `Otomian languages`\n\n // Collective name\n case \"paa\":\n\t\tc.Body = `Papuan languages`\n\n // Pangasinan\n case \"pag\":\n\t\tc.Body = `Pangasinan`\n\n // Pahlavi\n case \"pal\":\n\t\tc.Body = `Pahlavi`\n\n // Pampanga; Kapampangan\n case \"pam\":\n\t\tc.Body = `Pampanga; Kapampangan`\n\n // Panjabi\n case \"pan\":\n\t\tc.Body = `Panjabi`\n\n // Papiamento\n case \"pap\":\n\t\tc.Body = `Papiamento`\n\n // Palauan\n case \"pau\":\n\t\tc.Body = `Palauan`\n\n // Old Persian (ca. 600-400 B.C.)\n case \"peo\":\n\t\tc.Body = `Old Persian (ca. 600-400 B.C.)`\n\n // Macrolanguage\n case \"per\":\n\t\tc.Body = `Persian; Farsi`\n\n // ONIX local code, equivalent to pes in ISO 639-3. For use in ONIX 3.0 only\n case \"pes\":\n\t\tc.Body = `Iranian Persian; Parsi`\n\n // Collective name\n case \"phi\":\n\t\tc.Body = `Philippine languages`\n\n // Phoenician\n case \"phn\":\n\t\tc.Body = `Phoenician`\n\n // Pali\n case \"pli\":\n\t\tc.Body = `Pali`\n\n // ONIX local code for Italian dialect, equivalent to pms in ISO 639-3. For use in ONIX 3.0 only\n case \"pms\":\n\t\tc.Body = `Piedmontese`\n\n // Polish\n case \"pol\":\n\t\tc.Body = `Polish`\n\n // Ponapeian\n case \"pon\":\n\t\tc.Body = `Ponapeian`\n\n // Portuguese\n case \"por\":\n\t\tc.Body = `Portuguese`\n\n // Collective name\n case \"pra\":\n\t\tc.Body = `Prakrit languages`\n\n // Provençal, Old (to 1500); Occitan, Old (to 1500)\n case \"pro\":\n\t\tc.Body = `Provençal, Old (to 1500); Occitan, Old (to 1500)`\n\n // ONIX local code, equivalent to prs in ISO 639-3. For use in ONIX 3.0 only\n case \"prs\":\n\t\tc.Body = `Dari; Afghan Persian`\n\n // Macrolanguage\n case \"pus\":\n\t\tc.Body = `Pushto; Pashto`\n\n // ONIX local code, distinct dialect of Occitan (not distinguished from oci by ISO 639-3)\n case \"qar\":\n\t\tc.Body = `Aranés`\n\n // ONIX local code, distinct dialect of Catalan (not distinguished from cat by ISO 639-3)\n case \"qav\":\n\t\tc.Body = `Valencian`\n\n // ONIX local code, distinct variant of langue d’oïl (old northern French) (not distinguished from fro, or from frm, fre, nrf by ISO 639-3). For use in ONIX 3.0 only\n case \"qgl\":\n\t\tc.Body = `Gallo`\n\n // ONIX local code, distinct dialect of of Rusyn (not distinguished from rue by ISO 639-3). For use in ONIX 3.0 only\n case \"qlk\":\n\t\tc.Body = `Lemko`\n\n // ONIX local code, distinct and exclusively spoken variation of Spanish, not distinguished from spa (Spanish, Castilian) by ISO 639-3. Neutral Latin American Spanish should be considered a ‘shorthand’ for spa plus a ‘country code’ for Latin America – but prefer spa plus the relevant country code for specifically Mexican Spanish, Argentine (Rioplatense) Spanish, Puerto Rican Spanish etc. Neutral Latin American Spanish must only be used with audio material (including the audio tracks of TV, video and film) to indicate use of accent, vocabulary and construction suitable for broad use across Latin America. For use in ONIX 3.0 only\n case \"qls\":\n\t\tc.Body = `Neutral Latin American Spanish`\n\n // Macrolanguage\n case \"que\":\n\t\tc.Body = `Quechua`\n\n // Macrolanguage\n case \"raj\":\n\t\tc.Body = `Rajasthani`\n\n // Rapanui\n case \"rap\":\n\t\tc.Body = `Rapanui`\n\n // Rarotongan; Cook Islands Maori\n case \"rar\":\n\t\tc.Body = `Rarotongan; Cook Islands Maori`\n\n // ONIX local code, equivalent to rcf in ISO 639-3. For use in ONIX 3.0 only\n case \"rcf\":\n\t\tc.Body = `Réunion Creole French`\n\n // ONIX local code for Italian dialect, equivalent to rgl in ISO 639-3. For use in ONIX 3.0 only\n case \"rgn\":\n\t\tc.Body = `Romagnol`\n\n // Collective name\n case \"roa\":\n\t\tc.Body = `Romance languages`\n\n // Romansh\n case \"roh\":\n\t\tc.Body = `Romansh`\n\n // Macrolanguage\n case \"rom\":\n\t\tc.Body = `Romany`\n\n // Romanian\n case \"rum\":\n\t\tc.Body = `Romanian`\n\n // Rundi\n case \"run\":\n\t\tc.Body = `Rundi`\n\n // Aromanian; Arumanian; Macedo-Romanian\n case \"rup\":\n\t\tc.Body = `Aromanian; Arumanian; Macedo-Romanian`\n\n // Russian\n case \"rus\":\n\t\tc.Body = `Russian`\n\n // Sandawe\n case \"sad\":\n\t\tc.Body = `Sandawe`\n\n // Sango\n case \"sag\":\n\t\tc.Body = `Sango`\n\n // Yakut\n case \"sah\":\n\t\tc.Body = `Yakut`\n\n // Collective name\n case \"sai\":\n\t\tc.Body = `South American Indian languages`\n\n // Collective name\n case \"sal\":\n\t\tc.Body = `Salishan languages`\n\n // Samaritan Aramaic\n case \"sam\":\n\t\tc.Body = `Samaritan Aramaic`\n\n // Sanskrit\n case \"san\":\n\t\tc.Body = `Sanskrit`\n\n // Sasak\n case \"sas\":\n\t\tc.Body = `Sasak`\n\n // Santali\n case \"sat\":\n\t\tc.Body = `Santali`\n\n // DEPRECATED – use srp\n case \"scc\":\n\t\tc.Body = `Serbian`\n\n // Sicilian\n case \"scn\":\n\t\tc.Body = `Sicilian`\n\n // Scots\n case \"sco\":\n\t\tc.Body = `Scots`\n\n // DEPRECATED – use hrv\n case \"scr\":\n\t\tc.Body = `Croatian`\n\n // ONIX local code for Sardinian dialect, equivalent to sdc in ISO 639-3. For use in ONIX 3.0 only\n case \"sdc\":\n\t\tc.Body = `Sassarese`\n\n // ONIX local code for Sardinian dialect, equivalent to sdn in ISO 639-3. For use in ONIX 3.0 only\n case \"sdn\":\n\t\tc.Body = `Gallurese`\n\n // Selkup\n case \"sel\":\n\t\tc.Body = `Selkup`\n\n // Collective name\n case \"sem\":\n\t\tc.Body = `Semitic languages`\n\n // Irish, Old (to 1100)\n case \"sga\":\n\t\tc.Body = `Irish, Old (to 1100)`\n\n // Collective name\n case \"sgn\":\n\t\tc.Body = `Sign languages`\n\n // Shan\n case \"shn\":\n\t\tc.Body = `Shan`\n\n // Sidamo\n case \"sid\":\n\t\tc.Body = `Sidamo`\n\n // Sinhala; Sinhalese\n case \"sin\":\n\t\tc.Body = `Sinhala; Sinhalese`\n\n // Collective name\n case \"sio\":\n\t\tc.Body = `Siouan languages`\n\n // Collective name\n case \"sit\":\n\t\tc.Body = `Sino-Tibetan languages`\n\n // Collective name\n case \"sla\":\n\t\tc.Body = `Slavic languages`\n\n // Slovak\n case \"slo\":\n\t\tc.Body = `Slovak`\n\n // Slovenian\n case \"slv\":\n\t\tc.Body = `Slovenian`\n\n // Southern Sami\n case \"sma\":\n\t\tc.Body = `Southern Sami`\n\n // Northern Sami\n case \"sme\":\n\t\tc.Body = `Northern Sami`\n\n // Collective name\n case \"smi\":\n\t\tc.Body = `Sami languages`\n\n // Lule Sami\n case \"smj\":\n\t\tc.Body = `Lule Sami`\n\n // Inari Sami\n case \"smn\":\n\t\tc.Body = `Inari Sami`\n\n // Samoan\n case \"smo\":\n\t\tc.Body = `Samoan`\n\n // Skolt Sami\n case \"sms\":\n\t\tc.Body = `Skolt Sami`\n\n // Shona\n case \"sna\":\n\t\tc.Body = `Shona`\n\n // Sindhi\n case \"snd\":\n\t\tc.Body = `Sindhi`\n\n // Soninke\n case \"snk\":\n\t\tc.Body = `Soninke`\n\n // Sogdian\n case \"sog\":\n\t\tc.Body = `Sogdian`\n\n // Somali\n case \"som\":\n\t\tc.Body = `Somali`\n\n // Collective name\n case \"son\":\n\t\tc.Body = `Songhai languages`\n\n // Sotho; Sesotho\n case \"sot\":\n\t\tc.Body = `Sotho; Sesotho`\n\n // Spanish\n case \"spa\":\n\t\tc.Body = `Spanish`\n\n // Macrolanguage\n case \"srd\":\n\t\tc.Body = `Sardinian`\n\n // Sranan Tongo\n case \"srn\":\n\t\tc.Body = `Sranan Tongo`\n\n // ONIX local code for Sardinian dialect, equivalent to sro in ISO 639-3. For use in ONIX 3.0 only\n case \"sro\":\n\t\tc.Body = `Campidanese`\n\n // Serbian\n case \"srp\":\n\t\tc.Body = `Serbian`\n\n // Serer\n case \"srr\":\n\t\tc.Body = `Serer`\n\n // Collective name\n case \"ssa\":\n\t\tc.Body = `Nilo-Saharan languages`\n\n // Swazi; Swati\n case \"ssw\":\n\t\tc.Body = `Swazi; Swati`\n\n // Sukuma\n case \"suk\":\n\t\tc.Body = `Sukuma`\n\n // Sundanese\n case \"sun\":\n\t\tc.Body = `Sundanese`\n\n // Susu\n case \"sus\":\n\t\tc.Body = `Susu`\n\n // Sumerian\n case \"sux\":\n\t\tc.Body = `Sumerian`\n\n // Macrolanguage\n case \"swa\":\n\t\tc.Body = `Swahili`\n\n // Swedish\n case \"swe\":\n\t\tc.Body = `Swedish`\n\n // Classical Syriac\n case \"syc\":\n\t\tc.Body = `Classical Syriac`\n\n // Macrolanguage\n case \"syr\":\n\t\tc.Body = `Syriac`\n\n // Tahitian\n case \"tah\":\n\t\tc.Body = `Tahitian`\n\n // Collective name\n case \"tai\":\n\t\tc.Body = `Tai languages`\n\n // Tamil\n case \"tam\":\n\t\tc.Body = `Tamil`\n\n // Tatar\n case \"tat\":\n\t\tc.Body = `Tatar`\n\n // Telugu\n case \"tel\":\n\t\tc.Body = `Telugu`\n\n // Temne; Time\n case \"tem\":\n\t\tc.Body = `Temne; Time`\n\n // Terena\n case \"ter\":\n\t\tc.Body = `Terena`\n\n // Tetum\n case \"tet\":\n\t\tc.Body = `Tetum`\n\n // Tajik; Tajiki Persian\n case \"tgk\":\n\t\tc.Body = `Tajik; Tajiki Persian`\n\n // Tagalog\n case \"tgl\":\n\t\tc.Body = `Tagalog`\n\n // Thai\n case \"tha\":\n\t\tc.Body = `Thai`\n\n // Tibetan\n case \"tib\":\n\t\tc.Body = `Tibetan`\n\n // Tigré\n case \"tig\":\n\t\tc.Body = `Tigré`\n\n // Tigrinya\n case \"tir\":\n\t\tc.Body = `Tigrinya`\n\n // Tiv\n case \"tiv\":\n\t\tc.Body = `Tiv`\n\n // Tokelauan\n case \"tkl\":\n\t\tc.Body = `Tokelauan`\n\n // Artificial language\n case \"tlh\":\n\t\tc.Body = `Klingon; tlhIngan-Hol`\n\n // Tlingit\n case \"tli\":\n\t\tc.Body = `Tlingit`\n\n // Macrolanguage\n case \"tmh\":\n\t\tc.Body = `Tamashek`\n\n // Tonga (Nyasa)\n case \"tog\":\n\t\tc.Body = `Tonga (Nyasa)`\n\n // Tongan\n case \"ton\":\n\t\tc.Body = `Tongan`\n\n // Tok Pisin\n case \"tpi\":\n\t\tc.Body = `Tok Pisin`\n\n // Tsimshian\n case \"tsi\":\n\t\tc.Body = `Tsimshian`\n\n // AKA Setswana\n case \"tsn\":\n\t\tc.Body = `Tswana`\n\n // Tsonga\n case \"tso\":\n\t\tc.Body = `Tsonga`\n\n // Turkmen\n case \"tuk\":\n\t\tc.Body = `Turkmen`\n\n // Tumbuka\n case \"tum\":\n\t\tc.Body = `Tumbuka`\n\n // Collective name\n case \"tup\":\n\t\tc.Body = `Tupi languages`\n\n // Turkish\n case \"tur\":\n\t\tc.Body = `Turkish`\n\n // Altaic languages\n case \"tut\":\n\t\tc.Body = `Altaic languages`\n\n // Tuvaluan\n case \"tvl\":\n\t\tc.Body = `Tuvaluan`\n\n // Twi\n case \"twi\":\n\t\tc.Body = `Twi`\n\n // Tuvinian\n case \"tyv\":\n\t\tc.Body = `Tuvinian`\n\n // ONIX local code, equivalent to tzo in ISO 639-3\n case \"tzo\":\n\t\tc.Body = `Tzotzil`\n\n // Udmurt\n case \"udm\":\n\t\tc.Body = `Udmurt`\n\n // Ugaritic\n case \"uga\":\n\t\tc.Body = `Ugaritic`\n\n // Uighur; Uyghur\n case \"uig\":\n\t\tc.Body = `Uighur; Uyghur`\n\n // Ukrainian\n case \"ukr\":\n\t\tc.Body = `Ukrainian`\n\n // Umbundu\n case \"umb\":\n\t\tc.Body = `Umbundu`\n\n // Undetermined language\n case \"und\":\n\t\tc.Body = `Undetermined language`\n\n // Urdu\n case \"urd\":\n\t\tc.Body = `Urdu`\n\n // Macrolanguage\n case \"uzb\":\n\t\tc.Body = `Uzbek`\n\n // Vai\n case \"vai\":\n\t\tc.Body = `Vai`\n\n // ONIX local code for Italian dialect, equivalent to vec in ISO 639-3. For use in ONIX 3.0 only\n case \"vec\":\n\t\tc.Body = `Venetian/Venetan`\n\n // Venda\n case \"ven\":\n\t\tc.Body = `Venda`\n\n // Vietnamese\n case \"vie\":\n\t\tc.Body = `Vietnamese`\n\n // Artificial language\n case \"vol\":\n\t\tc.Body = `Volapük`\n\n // Votic\n case \"vot\":\n\t\tc.Body = `Votic`\n\n // Collective name\n case \"wak\":\n\t\tc.Body = `Wakashan languages`\n\n // Wolaitta; Wolaytta\n case \"wal\":\n\t\tc.Body = `Wolaitta; Wolaytta`\n\n // Waray\n case \"war\":\n\t\tc.Body = `Waray`\n\n // Washo\n case \"was\":\n\t\tc.Body = `Washo`\n\n // Welsh\n case \"wel\":\n\t\tc.Body = `Welsh`\n\n // Collective name\n case \"wen\":\n\t\tc.Body = `Sorbian languages`\n\n // Walloon\n case \"wln\":\n\t\tc.Body = `Walloon`\n\n // Wolof\n case \"wol\":\n\t\tc.Body = `Wolof`\n\n // Kalmyk\n case \"xal\":\n\t\tc.Body = `Kalmyk`\n\n // Xhosa\n case \"xho\":\n\t\tc.Body = `Xhosa`\n\n // ONIX local code, equivalent to xuu in ISO 639-3. For use in ONIX 3.0 only\n case \"xuu\":\n\t\tc.Body = `Khwedam, Kxoe`\n\n // Yao\n case \"yao\":\n\t\tc.Body = `Yao`\n\n // Yapese\n case \"yap\":\n\t\tc.Body = `Yapese`\n\n // Macrolanguage\n case \"yid\":\n\t\tc.Body = `Yiddish`\n\n // Yoruba\n case \"yor\":\n\t\tc.Body = `Yoruba`\n\n // Collective name\n case \"ypk\":\n\t\tc.Body = `Yupik languages`\n\n // ONIX local code, equivalent to yue in ISO 639-3\n case \"yue\":\n\t\tc.Body = `Cantonese`\n\n // Macrolanguage\n case \"zap\":\n\t\tc.Body = `Zapotec`\n\n // Artificial language\n case \"zbl\":\n\t\tc.Body = `Blissymbols; Blissymbolics; Bliss`\n\n // Zenaga\n case \"zen\":\n\t\tc.Body = `Zenaga`\n\n // Standard Moroccan Tamazight\n case \"zgh\":\n\t\tc.Body = `Standard Moroccan Tamazight`\n\n // Macrolanguage\n case \"zha\":\n\t\tc.Body = `Zhuang; Chuang`\n\n // Collective name\n case \"znd\":\n\t\tc.Body = `Zande languages`\n\n // Zulu\n case \"zul\":\n\t\tc.Body = `Zulu`\n\n // Zuni\n case \"zun\":\n\t\tc.Body = `Zuni`\n\n // No linguistic content\n case \"zxx\":\n\t\tc.Body = `No linguistic content`\n\n // Macrolanguage\n case \"zza\":\n\t\tc.Body = `Zaza; Dimili; Dimli; Kirdki; Kirmanjki; Zazaki`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for LanguageCode has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *CountryOfPublication) 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\tcodes := strings.Split(v, \" \")\n\ttmpeCodes := []string{}\n\tfor _, code := range codes {\n\t\tswitch code {\n\n\t\t// Andorra\n\t\tcase \"AD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Andorra`)\n\n\t\t// United Arab Emirates\n\t\tcase \"AE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United Arab Emirates`)\n\n\t\t// Afghanistan\n\t\tcase \"AF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Afghanistan`)\n\n\t\t// Antigua and Barbuda\n\t\tcase \"AG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Antigua and Barbuda`)\n\n\t\t// Anguilla\n\t\tcase \"AI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Anguilla`)\n\n\t\t// Albania\n\t\tcase \"AL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Albania`)\n\n\t\t// Armenia\n\t\tcase \"AM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Armenia`)\n\n\t\t// Deprecated – use BQ, CW and SX as appropriate\n\t\tcase \"AN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Netherlands Antilles`)\n\n\t\t// Angola\n\t\tcase \"AO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Angola`)\n\n\t\t// Antarctica\n\t\tcase \"AQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Antarctica`)\n\n\t\t// Argentina\n\t\tcase \"AR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Argentina`)\n\n\t\t// American Samoa\n\t\tcase \"AS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `American Samoa`)\n\n\t\t// Austria\n\t\tcase \"AT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Austria`)\n\n\t\t// Australia\n\t\tcase \"AU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Australia`)\n\n\t\t// Aruba\n\t\tcase \"AW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Aruba`)\n\n\t\t// Åland Islands\n\t\tcase \"AX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Åland Islands`)\n\n\t\t// Azerbaijan\n\t\tcase \"AZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Azerbaijan`)\n\n\t\t// Bosnia and Herzegovina\n\t\tcase \"BA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bosnia and Herzegovina`)\n\n\t\t// Barbados\n\t\tcase \"BB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Barbados`)\n\n\t\t// Bangladesh\n\t\tcase \"BD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bangladesh`)\n\n\t\t// Belgium\n\t\tcase \"BE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belgium`)\n\n\t\t// Burkina Faso\n\t\tcase \"BF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Burkina Faso`)\n\n\t\t// Bulgaria\n\t\tcase \"BG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bulgaria`)\n\n\t\t// Bahrain\n\t\tcase \"BH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bahrain`)\n\n\t\t// Burundi\n\t\tcase \"BI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Burundi`)\n\n\t\t// Benin\n\t\tcase \"BJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Benin`)\n\n\t\t// Saint Barthélemy\n\t\tcase \"BL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Barthélemy`)\n\n\t\t// Bermuda\n\t\tcase \"BM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bermuda`)\n\n\t\t// Brunei Darussalam\n\t\tcase \"BN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Brunei Darussalam`)\n\n\t\t// Bolivia, Plurinational State of\n\t\tcase \"BO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bolivia, Plurinational State of`)\n\n\t\t// Bonaire, Sint Eustatius and Saba\n\t\tcase \"BQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bonaire, Sint Eustatius and Saba`)\n\n\t\t// Brazil\n\t\tcase \"BR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Brazil`)\n\n\t\t// Bahamas\n\t\tcase \"BS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bahamas`)\n\n\t\t// Bhutan\n\t\tcase \"BT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bhutan`)\n\n\t\t// Bouvet Island\n\t\tcase \"BV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bouvet Island`)\n\n\t\t// Botswana\n\t\tcase \"BW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Botswana`)\n\n\t\t// Belarus\n\t\tcase \"BY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belarus`)\n\n\t\t// Belize\n\t\tcase \"BZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belize`)\n\n\t\t// Canada\n\t\tcase \"CA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Canada`)\n\n\t\t// Cocos (Keeling) Islands\n\t\tcase \"CC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cocos (Keeling) Islands`)\n\n\t\t// Congo, Democratic Republic of the\n\t\tcase \"CD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Congo, Democratic Republic of the`)\n\n\t\t// Central African Republic\n\t\tcase \"CF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Central African Republic`)\n\n\t\t// Congo\n\t\tcase \"CG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Congo`)\n\n\t\t// Switzerland\n\t\tcase \"CH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Switzerland`)\n\n\t\t// Cote d’Ivoire\n\t\tcase \"CI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cote d’Ivoire`)\n\n\t\t// Cook Islands\n\t\tcase \"CK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cook Islands`)\n\n\t\t// Chile\n\t\tcase \"CL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Chile`)\n\n\t\t// Cameroon\n\t\tcase \"CM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cameroon`)\n\n\t\t// China\n\t\tcase \"CN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `China`)\n\n\t\t// Colombia\n\t\tcase \"CO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Colombia`)\n\n\t\t// Costa Rica\n\t\tcase \"CR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Costa Rica`)\n\n\t\t// DEPRECATED, replaced by ME – Montenegro and RS – Serbia\n\t\tcase \"CS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Serbia and Montenegro`)\n\n\t\t// Cuba\n\t\tcase \"CU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cuba`)\n\n\t\t// Cabo Verde\n\t\tcase \"CV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cabo Verde`)\n\n\t\t// Curaçao\n\t\tcase \"CW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Curaçao`)\n\n\t\t// Christmas Island\n\t\tcase \"CX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Christmas Island`)\n\n\t\t// Cyprus\n\t\tcase \"CY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cyprus`)\n\n\t\t// Formerly Czech Republic\n\t\tcase \"CZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Czechia`)\n\n\t\t// Germany\n\t\tcase \"DE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Germany`)\n\n\t\t// Djibouti\n\t\tcase \"DJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Djibouti`)\n\n\t\t// Denmark\n\t\tcase \"DK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Denmark`)\n\n\t\t// Dominica\n\t\tcase \"DM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Dominica`)\n\n\t\t// Dominican Republic\n\t\tcase \"DO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Dominican Republic`)\n\n\t\t// Algeria\n\t\tcase \"DZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Algeria`)\n\n\t\t// Ecuador\n\t\tcase \"EC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ecuador`)\n\n\t\t// Estonia\n\t\tcase \"EE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Estonia`)\n\n\t\t// Egypt\n\t\tcase \"EG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Egypt`)\n\n\t\t// Western Sahara\n\t\tcase \"EH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Western Sahara`)\n\n\t\t// Eritrea\n\t\tcase \"ER\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Eritrea`)\n\n\t\t// Spain\n\t\tcase \"ES\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Spain`)\n\n\t\t// Ethiopia\n\t\tcase \"ET\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ethiopia`)\n\n\t\t// Finland\n\t\tcase \"FI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Finland`)\n\n\t\t// Fiji\n\t\tcase \"FJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Fiji`)\n\n\t\t// Falkland Islands (Malvinas)\n\t\tcase \"FK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Falkland Islands (Malvinas)`)\n\n\t\t// Micronesia, Federated States of\n\t\tcase \"FM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Micronesia, Federated States of`)\n\n\t\t// Faroe Islands\n\t\tcase \"FO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Faroe Islands`)\n\n\t\t// France\n\t\tcase \"FR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `France`)\n\n\t\t// Gabon\n\t\tcase \"GA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gabon`)\n\n\t\t// United Kingdom\n\t\tcase \"GB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United Kingdom`)\n\n\t\t// Grenada\n\t\tcase \"GD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Grenada`)\n\n\t\t// Georgia\n\t\tcase \"GE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Georgia`)\n\n\t\t// French Guiana\n\t\tcase \"GF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Guiana`)\n\n\t\t// Guernsey\n\t\tcase \"GG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guernsey`)\n\n\t\t// Ghana\n\t\tcase \"GH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ghana`)\n\n\t\t// Gibraltar\n\t\tcase \"GI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gibraltar`)\n\n\t\t// Greenland\n\t\tcase \"GL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Greenland`)\n\n\t\t// Gambia\n\t\tcase \"GM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gambia`)\n\n\t\t// Guinea\n\t\tcase \"GN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guinea`)\n\n\t\t// Guadeloupe\n\t\tcase \"GP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guadeloupe`)\n\n\t\t// Equatorial Guinea\n\t\tcase \"GQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Equatorial Guinea`)\n\n\t\t// Greece\n\t\tcase \"GR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Greece`)\n\n\t\t// South Georgia and the South Sandwich Islands\n\t\tcase \"GS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Georgia and the South Sandwich Islands`)\n\n\t\t// Guatemala\n\t\tcase \"GT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guatemala`)\n\n\t\t// Guam\n\t\tcase \"GU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guam`)\n\n\t\t// Guinea-Bissau\n\t\tcase \"GW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guinea-Bissau`)\n\n\t\t// Guyana\n\t\tcase \"GY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guyana`)\n\n\t\t// Hong Kong\n\t\tcase \"HK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Hong Kong`)\n\n\t\t// Heard Island and McDonald Islands\n\t\tcase \"HM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Heard Island and McDonald Islands`)\n\n\t\t// Honduras\n\t\tcase \"HN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Honduras`)\n\n\t\t// Croatia\n\t\tcase \"HR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Croatia`)\n\n\t\t// Haiti\n\t\tcase \"HT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Haiti`)\n\n\t\t// Hungary\n\t\tcase \"HU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Hungary`)\n\n\t\t// Indonesia\n\t\tcase \"ID\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Indonesia`)\n\n\t\t// Ireland\n\t\tcase \"IE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ireland`)\n\n\t\t// Israel\n\t\tcase \"IL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Israel`)\n\n\t\t// Isle of Man\n\t\tcase \"IM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Isle of Man`)\n\n\t\t// India\n\t\tcase \"IN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `India`)\n\n\t\t// British Indian Ocean Territory\n\t\tcase \"IO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `British Indian Ocean Territory`)\n\n\t\t// Iraq\n\t\tcase \"IQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iraq`)\n\n\t\t// Iran, Islamic Republic of\n\t\tcase \"IR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iran, Islamic Republic of`)\n\n\t\t// Iceland\n\t\tcase \"IS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iceland`)\n\n\t\t// Italy\n\t\tcase \"IT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Italy`)\n\n\t\t// Jersey\n\t\tcase \"JE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jersey`)\n\n\t\t// Jamaica\n\t\tcase \"JM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jamaica`)\n\n\t\t// Jordan\n\t\tcase \"JO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jordan`)\n\n\t\t// Japan\n\t\tcase \"JP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Japan`)\n\n\t\t// Kenya\n\t\tcase \"KE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kenya`)\n\n\t\t// Kyrgyzstan\n\t\tcase \"KG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kyrgyzstan`)\n\n\t\t// Cambodia\n\t\tcase \"KH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cambodia`)\n\n\t\t// Kiribati\n\t\tcase \"KI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kiribati`)\n\n\t\t// Comoros\n\t\tcase \"KM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Comoros`)\n\n\t\t// Saint Kitts and Nevis\n\t\tcase \"KN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Kitts and Nevis`)\n\n\t\t// Korea, Democratic People’s Republic of\n\t\tcase \"KP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Korea, Democratic People’s Republic of`)\n\n\t\t// Korea, Republic of\n\t\tcase \"KR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Korea, Republic of`)\n\n\t\t// Kuwait\n\t\tcase \"KW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kuwait`)\n\n\t\t// Cayman Islands\n\t\tcase \"KY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cayman Islands`)\n\n\t\t// Kazakhstan\n\t\tcase \"KZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kazakhstan`)\n\n\t\t// Lao People’s Democratic Republic\n\t\tcase \"LA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lao People’s Democratic Republic`)\n\n\t\t// Lebanon\n\t\tcase \"LB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lebanon`)\n\n\t\t// Saint Lucia\n\t\tcase \"LC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Lucia`)\n\n\t\t// Liechtenstein\n\t\tcase \"LI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Liechtenstein`)\n\n\t\t// Sri Lanka\n\t\tcase \"LK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sri Lanka`)\n\n\t\t// Liberia\n\t\tcase \"LR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Liberia`)\n\n\t\t// Lesotho\n\t\tcase \"LS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lesotho`)\n\n\t\t// Lithuania\n\t\tcase \"LT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lithuania`)\n\n\t\t// Luxembourg\n\t\tcase \"LU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Luxembourg`)\n\n\t\t// Latvia\n\t\tcase \"LV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Latvia`)\n\n\t\t// Libya\n\t\tcase \"LY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Libya`)\n\n\t\t// Morocco\n\t\tcase \"MA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Morocco`)\n\n\t\t// Monaco\n\t\tcase \"MC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Monaco`)\n\n\t\t// Moldova, Republic of\n\t\tcase \"MD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Moldova, Republic of`)\n\n\t\t// Montenegro\n\t\tcase \"ME\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Montenegro`)\n\n\t\t// Saint Martin (French part)\n\t\tcase \"MF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Martin (French part)`)\n\n\t\t// Madagascar\n\t\tcase \"MG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Madagascar`)\n\n\t\t// Marshall Islands\n\t\tcase \"MH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Marshall Islands`)\n\n\t\t// Formerly FYR Macedonia\n\t\tcase \"MK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `North Macedonia`)\n\n\t\t// Mali\n\t\tcase \"ML\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mali`)\n\n\t\t// Myanmar\n\t\tcase \"MM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Myanmar`)\n\n\t\t// Mongolia\n\t\tcase \"MN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mongolia`)\n\n\t\t// Macao\n\t\tcase \"MO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Macao`)\n\n\t\t// Northern Mariana Islands\n\t\tcase \"MP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Northern Mariana Islands`)\n\n\t\t// Martinique\n\t\tcase \"MQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Martinique`)\n\n\t\t// Mauritania\n\t\tcase \"MR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mauritania`)\n\n\t\t// Montserrat\n\t\tcase \"MS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Montserrat`)\n\n\t\t// Malta\n\t\tcase \"MT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malta`)\n\n\t\t// Mauritius\n\t\tcase \"MU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mauritius`)\n\n\t\t// Maldives\n\t\tcase \"MV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Maldives`)\n\n\t\t// Malawi\n\t\tcase \"MW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malawi`)\n\n\t\t// Mexico\n\t\tcase \"MX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mexico`)\n\n\t\t// Malaysia\n\t\tcase \"MY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malaysia`)\n\n\t\t// Mozambique\n\t\tcase \"MZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mozambique`)\n\n\t\t// Namibia\n\t\tcase \"NA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Namibia`)\n\n\t\t// New Caledonia\n\t\tcase \"NC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `New Caledonia`)\n\n\t\t// Niger\n\t\tcase \"NE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Niger`)\n\n\t\t// Norfolk Island\n\t\tcase \"NF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Norfolk Island`)\n\n\t\t// Nigeria\n\t\tcase \"NG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nigeria`)\n\n\t\t// Nicaragua\n\t\tcase \"NI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nicaragua`)\n\n\t\t// Netherlands\n\t\tcase \"NL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Netherlands`)\n\n\t\t// Norway\n\t\tcase \"NO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Norway`)\n\n\t\t// Nepal\n\t\tcase \"NP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nepal`)\n\n\t\t// Nauru\n\t\tcase \"NR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nauru`)\n\n\t\t// Niue\n\t\tcase \"NU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Niue`)\n\n\t\t// New Zealand\n\t\tcase \"NZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `New Zealand`)\n\n\t\t// Oman\n\t\tcase \"OM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Oman`)\n\n\t\t// Panama\n\t\tcase \"PA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Panama`)\n\n\t\t// Peru\n\t\tcase \"PE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Peru`)\n\n\t\t// French Polynesia\n\t\tcase \"PF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Polynesia`)\n\n\t\t// Papua New Guinea\n\t\tcase \"PG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Papua New Guinea`)\n\n\t\t// Philippines\n\t\tcase \"PH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Philippines`)\n\n\t\t// Pakistan\n\t\tcase \"PK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Pakistan`)\n\n\t\t// Poland\n\t\tcase \"PL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Poland`)\n\n\t\t// Saint Pierre and Miquelon\n\t\tcase \"PM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Pierre and Miquelon`)\n\n\t\t// Pitcairn\n\t\tcase \"PN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Pitcairn`)\n\n\t\t// Puerto Rico\n\t\tcase \"PR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Puerto Rico`)\n\n\t\t// Palestine, State of\n\t\tcase \"PS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Palestine, State of`)\n\n\t\t// Portugal\n\t\tcase \"PT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Portugal`)\n\n\t\t// Palau\n\t\tcase \"PW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Palau`)\n\n\t\t// Paraguay\n\t\tcase \"PY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Paraguay`)\n\n\t\t// Qatar\n\t\tcase \"QA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Qatar`)\n\n\t\t// Réunion\n\t\tcase \"RE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Réunion`)\n\n\t\t// Romania\n\t\tcase \"RO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Romania`)\n\n\t\t// Serbia\n\t\tcase \"RS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Serbia`)\n\n\t\t// Russian Federation\n\t\tcase \"RU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Russian Federation`)\n\n\t\t// Rwanda\n\t\tcase \"RW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Rwanda`)\n\n\t\t// Saudi Arabia\n\t\tcase \"SA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saudi Arabia`)\n\n\t\t// Solomon Islands\n\t\tcase \"SB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Solomon Islands`)\n\n\t\t// Seychelles\n\t\tcase \"SC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Seychelles`)\n\n\t\t// Sudan\n\t\tcase \"SD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sudan`)\n\n\t\t// Sweden\n\t\tcase \"SE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sweden`)\n\n\t\t// Singapore\n\t\tcase \"SG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Singapore`)\n\n\t\t// Saint Helena, Ascension and Tristan da Cunha\n\t\tcase \"SH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Helena, Ascension and Tristan da Cunha`)\n\n\t\t// Slovenia\n\t\tcase \"SI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Slovenia`)\n\n\t\t// Svalbard and Jan Mayen\n\t\tcase \"SJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Svalbard and Jan Mayen`)\n\n\t\t// Slovakia\n\t\tcase \"SK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Slovakia`)\n\n\t\t// Sierra Leone\n\t\tcase \"SL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sierra Leone`)\n\n\t\t// San Marino\n\t\tcase \"SM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `San Marino`)\n\n\t\t// Senegal\n\t\tcase \"SN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Senegal`)\n\n\t\t// Somalia\n\t\tcase \"SO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Somalia`)\n\n\t\t// Suriname\n\t\tcase \"SR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Suriname`)\n\n\t\t// South Sudan\n\t\tcase \"SS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Sudan`)\n\n\t\t// Sao Tome and Principe\n\t\tcase \"ST\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sao Tome and Principe`)\n\n\t\t// El Salvador\n\t\tcase \"SV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `El Salvador`)\n\n\t\t// Sint Maarten (Dutch part)\n\t\tcase \"SX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sint Maarten (Dutch part)`)\n\n\t\t// Syrian Arab Republic\n\t\tcase \"SY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Syrian Arab Republic`)\n\n\t\t// Formerly known as Swaziland\n\t\tcase \"SZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Eswatini`)\n\n\t\t// Turks and Caicos Islands\n\t\tcase \"TC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turks and Caicos Islands`)\n\n\t\t// Chad\n\t\tcase \"TD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Chad`)\n\n\t\t// French Southern Territories\n\t\tcase \"TF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Southern Territories`)\n\n\t\t// Togo\n\t\tcase \"TG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Togo`)\n\n\t\t// Thailand\n\t\tcase \"TH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Thailand`)\n\n\t\t// Tajikistan\n\t\tcase \"TJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tajikistan`)\n\n\t\t// Tokelau\n\t\tcase \"TK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tokelau`)\n\n\t\t// Timor-Leste\n\t\tcase \"TL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Timor-Leste`)\n\n\t\t// Turkmenistan\n\t\tcase \"TM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turkmenistan`)\n\n\t\t// Tunisia\n\t\tcase \"TN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tunisia`)\n\n\t\t// Tonga\n\t\tcase \"TO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tonga`)\n\n\t\t// Turkey\n\t\tcase \"TR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turkey`)\n\n\t\t// Trinidad and Tobago\n\t\tcase \"TT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Trinidad and Tobago`)\n\n\t\t// Tuvalu\n\t\tcase \"TV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tuvalu`)\n\n\t\t// Taiwan, Province of China\n\t\tcase \"TW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Taiwan, Province of China`)\n\n\t\t// Tanzania, United Republic of\n\t\tcase \"TZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tanzania, United Republic of`)\n\n\t\t// Ukraine\n\t\tcase \"UA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ukraine`)\n\n\t\t// Uganda\n\t\tcase \"UG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uganda`)\n\n\t\t// United States Minor Outlying Islands\n\t\tcase \"UM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United States Minor Outlying Islands`)\n\n\t\t// United States\n\t\tcase \"US\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United States`)\n\n\t\t// Uruguay\n\t\tcase \"UY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uruguay`)\n\n\t\t// Uzbekistan\n\t\tcase \"UZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uzbekistan`)\n\n\t\t// Holy See (Vatican City State)\n\t\tcase \"VA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Holy See (Vatican City State)`)\n\n\t\t// Saint Vincent and the Grenadines\n\t\tcase \"VC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Vincent and the Grenadines`)\n\n\t\t// Venezuela, Bolivarian Republic of\n\t\tcase \"VE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Venezuela, Bolivarian Republic of`)\n\n\t\t// Virgin Islands, British\n\t\tcase \"VG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Virgin Islands, British`)\n\n\t\t// Virgin Islands, US\n\t\tcase \"VI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Virgin Islands, US`)\n\n\t\t// Viet Nam\n\t\tcase \"VN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Viet Nam`)\n\n\t\t// Vanuatu\n\t\tcase \"VU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Vanuatu`)\n\n\t\t// Wallis and Futuna\n\t\tcase \"WF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Wallis and Futuna`)\n\n\t\t// Samoa\n\t\tcase \"WS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Samoa`)\n\n\t\t// Yemen\n\t\tcase \"YE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Yemen`)\n\n\t\t// Mayotte\n\t\tcase \"YT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mayotte`)\n\n\t\t// DEPRECATED, replaced by ME – Montenegro and RS – Serbia\n\t\tcase \"YU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Yugoslavia`)\n\n\t\t// South Africa\n\t\tcase \"ZA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Africa`)\n\n\t\t// Zambia\n\t\tcase \"ZM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Zambia`)\n\n\t\t// Zimbabwe\n\t\tcase \"ZW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Zimbabwe`)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"undefined code for CountryOfPublication has been passed, got [%s]\", v)\n\t\t}\n\t}\n\tc.Body = tmpeCodes\n\treturn nil\n}", "func readXML(r io.Reader) (*Root, error) {\n\troot := Root{}\n\n\tdec := xml.NewDecoder(r)\n\tif err := dec.Decode(&root); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &root, nil\n}", "func readXML(r io.Reader) (*Root, error) {\n\troot := Root{}\n\n\tdec := xml.NewDecoder(r)\n\tif err := dec.Decode(&root); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &root, nil\n}", "func (c *Type) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\n // \n case \"1\":\n\t\t*c = ``\n\n // \n case \"A\":\n\t\t*c = ``\n\n // \n case \"a\":\n\t\t*c = ``\n\n // \n case \"I\":\n\t\t*c = ``\n\n // \n case \"i\":\n\t\t*c = ``\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for Type has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *XHTMLText) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for XHTMLText has been passed, got [%s]\", v)\n\t}\n}", "func DecodeXMLCharData(d *xml.Decoder) (val string, err error) {\n\tfor {\n\t\tvar t xml.Token\n\t\tt, err = d.Token()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"ki.DecodeXMLCharData err %v\\n\", err)\n\t\t\treturn\n\t\t}\n\t\tswitch tv := t.(type) {\n\t\tcase xml.CharData:\n\t\t\tval = string([]byte(tv))\n\t\t\treturn\n\t\tcase xml.StartElement:\n\t\t\terr = fmt.Errorf(\"ki.DecodeXMLCharData: got unexpected StartElement: %v\", tv.Name)\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\tcase xml.EndElement:\n\t\t\terr = fmt.Errorf(\"ki.DecodeXMLCharData: got unexpected EndElement: %v\", tv.Name)\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func ConvXml(file string) func(pathTag string, tag string) string {\n\txmlFile, err := ioutil.ReadFile(file)\n\tCheckErr(err)\n\treturn func(pathTag string, tag string) string {\n\t\tnfe, errOpenXml := mxj.NewMapXml(xmlFile)\n\t\tCheckErr(errOpenXml)\n\t\tpathDest := nfe.PathsForKey(pathTag)\n\t\tif len(pathDest) > 0 {\n\t\t\tdest, err := nfe.ValuesForPath(pathDest[0])\n\t\t\tCheckErr(err)\n\t\t\tmv := mxj.Map(dest[0].(map[string]interface{}))\n\t\t\tif mv[tag] == nil {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\tif tag == \"dhEmi\" {\n\t\t\t\tmv2 := strings.Split(mv[tag].(string), \"T\")\n\t\t\t\treturn mv2[0]\n\t\t\t} else {\n\t\t\t\treturn mv[tag].(string)\n\t\t\t}\n\t\t}\n\t\treturn \"\"\n\t}\n}", "func (c *CurrencyCode) 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 // United Arab Emirates\n case \"AED\":\n\t\tc.Body = `UAE Dirham`\n\n // Afghanistan. DEPRECATED, replaced by AFN\n case \"AFA\":\n\t\tc.Body = `Afghani`\n\n // Afghanistan (prices normally quoted as integers)\n case \"AFN\":\n\t\tc.Body = `Afghani`\n\n // Albania (prices normally quoted as integers)\n case \"ALL\":\n\t\tc.Body = `Lek`\n\n // Armenia (prices normally quoted as integers)\n case \"AMD\":\n\t\tc.Body = `Armenian Dram`\n\n // Curaçao, Sint Maarten\n case \"ANG\":\n\t\tc.Body = `Netherlands Antillian Guilder`\n\n // Angola\n case \"AOA\":\n\t\tc.Body = `Kwanza`\n\n // Argentina\n case \"ARS\":\n\t\tc.Body = `Argentine Peso`\n\n // Austria. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"ATS\":\n\t\tc.Body = `Schilling`\n\n // Australia, Christmas Island, Cocos (Keeling) Islands, Heard Island and McDonald Islands, Kiribati, Nauru, Norfolk Island, Tuvalu\n case \"AUD\":\n\t\tc.Body = `Australian Dollar`\n\n // Aruba\n case \"AWG\":\n\t\tc.Body = `Aruban Florin`\n\n // Azerbaijan\n case \"AZN\":\n\t\tc.Body = `Azerbaijan Manat`\n\n // Bosnia and Herzegovina\n case \"BAM\":\n\t\tc.Body = `Convertible Marks`\n\n // Barbados\n case \"BBD\":\n\t\tc.Body = `Barbados Dollar`\n\n // Bangladesh\n case \"BDT\":\n\t\tc.Body = `Taka`\n\n // Belgium. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"BEF\":\n\t\tc.Body = `Belgian Franc`\n\n // DEPRECATED, replaced by BGN\n case \"BGL\":\n\t\tc.Body = `Bulgarian Lev`\n\n // Bulgaria\n case \"BGN\":\n\t\tc.Body = `Bulgarian Lev`\n\n // Bahrain (prices normally quoted with 3 decimal places)\n case \"BHD\":\n\t\tc.Body = `Bahraini Dinar`\n\n // Burundi (prices normally quoted as integers)\n case \"BIF\":\n\t\tc.Body = `Burundi Franc`\n\n // Bermuda\n case \"BMD\":\n\t\tc.Body = `Bermudian Dollar`\n\n // Brunei Darussalam\n case \"BND\":\n\t\tc.Body = `Brunei Dollar`\n\n // Bolivia\n case \"BOB\":\n\t\tc.Body = `Boliviano`\n\n // Brazil\n case \"BRL\":\n\t\tc.Body = `Brazilian Real`\n\n // Bahamas\n case \"BSD\":\n\t\tc.Body = `Bahamian Dollar`\n\n // Bhutan\n case \"BTN\":\n\t\tc.Body = `Ngultrun`\n\n // Botswana\n case \"BWP\":\n\t\tc.Body = `Pula`\n\n // Belarus (prices normally quoted as integers). Deprecated – now replaced by new Belarussian Ruble (BYN): use only for historical prices that pre-date the introduction of the new Belarussian Ruble\n case \"BYR\":\n\t\tc.Body = `(Old) Belarussian Ruble`\n\n // Belarus\n case \"BYN\":\n\t\tc.Body = `Belarussian Ruble`\n\n // Belize\n case \"BZD\":\n\t\tc.Body = `Belize Dollar`\n\n // Canada\n case \"CAD\":\n\t\tc.Body = `Canadian Dollar`\n\n // Congo (Democratic Republic of the)\n case \"CDF\":\n\t\tc.Body = `Franc Congolais`\n\n // Switzerland, Liechtenstein\n case \"CHF\":\n\t\tc.Body = `Swiss Franc`\n\n // Chile (prices normally quoted as integers)\n case \"CLP\":\n\t\tc.Body = `Chilean Peso`\n\n // China\n case \"CNY\":\n\t\tc.Body = `Yuan Renminbi`\n\n // Colombia (prices normally quoted as integers)\n case \"COP\":\n\t\tc.Body = `Colombian Peso`\n\n // Costa Rica (prices normally quoted as integers)\n case \"CRC\":\n\t\tc.Body = `Costa Rican Colon`\n\n // Deprecated, replaced by RSD\n case \"CSD\":\n\t\tc.Body = `Serbian Dinar`\n\n // Cuba (alternative currency)\n case \"CUC\":\n\t\tc.Body = `Cuban Convertible Peso`\n\n // Cuba\n case \"CUP\":\n\t\tc.Body = `Cuban Peso`\n\n // Cabo Verde (prices normally quoted as integers)\n case \"CVE\":\n\t\tc.Body = `Cabo Verde Escudo`\n\n // Cyprus. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"CYP\":\n\t\tc.Body = `Cyprus Pound`\n\n // Czechia\n case \"CZK\":\n\t\tc.Body = `Czech Koruna`\n\n // Germany. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"DEM\":\n\t\tc.Body = `Mark`\n\n // Djibouti (prices normally quoted as integers)\n case \"DJF\":\n\t\tc.Body = `Djibouti Franc`\n\n // Denmark, Faroe Islands, Greenland\n case \"DKK\":\n\t\tc.Body = `Danish Krone`\n\n // Dominican Republic\n case \"DOP\":\n\t\tc.Body = `Dominican Peso`\n\n // Algeria\n case \"DZD\":\n\t\tc.Body = `Algerian Dinar`\n\n // Estonia.Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"EEK\":\n\t\tc.Body = `Kroon`\n\n // Egypt\n case \"EGP\":\n\t\tc.Body = `Egyptian Pound`\n\n // Eritrea\n case \"ERN\":\n\t\tc.Body = `Nakfa`\n\n // Spain. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro (prices normally quoted as integers)\n case \"ESP\":\n\t\tc.Body = `Peseta`\n\n // Ethiopia\n case \"ETB\":\n\t\tc.Body = `Ethiopian Birr`\n\n // Eurozone: Andorra, Austria, Belgium, Cyprus, Estonia, Finland, France, Fr Guiana, Fr S Territories, Germany, Greece, Guadeloupe, Holy See (Vatican City), Ireland, Italy, Latvia, Lithuania, Luxembourg, Martinique, Malta, Mayotte, Monaco, Montenegro, Netherlands, Portugal, Réunion, St Barthelemy, St Martin, St Pierre and Miquelon, San Marino, Slovakia, Slovenia, Spain\n case \"EUR\":\n\t\tc.Body = `Euro`\n\n // Finland. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"FIM\":\n\t\tc.Body = `Markka`\n\n // Fiji\n case \"FJD\":\n\t\tc.Body = `Fiji Dollar`\n\n // Falkland Islands (Malvinas)\n case \"FKP\":\n\t\tc.Body = `Falkland Islands Pound`\n\n // France. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"FRF\":\n\t\tc.Body = `Franc`\n\n // United Kingdom, Isle of Man, Channel Islands, South Georgia, South Sandwich Islands, British Indian Ocean Territory (de jure)\n case \"GBP\":\n\t\tc.Body = `Pound Sterling`\n\n // Georgia\n case \"GEL\":\n\t\tc.Body = `Lari`\n\n // Deprecated, replaced by GHS\n case \"GHC\":\n\t\tc.Body = `Ghana Cedi`\n\n // Ghana\n case \"GHS\":\n\t\tc.Body = `Ghana Cedi`\n\n // Gibraltar\n case \"GIP\":\n\t\tc.Body = `Gibraltar Pound`\n\n // Gambia\n case \"GMD\":\n\t\tc.Body = `Dalasi`\n\n // Guinea (prices normally quoted as integers)\n case \"GNF\":\n\t\tc.Body = `Guinean Franc`\n\n // Greece. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"GRD\":\n\t\tc.Body = `Drachma`\n\n // Guatemala\n case \"GTQ\":\n\t\tc.Body = `Quetzal`\n\n // Now replaced by the CFA Franc BCEAO XOF use only for historical prices that pre-date use of the CFA Franc\n case \"GWP\":\n\t\tc.Body = `Guinea-Bissau Peso`\n\n // Guyana (prices normally quoted as integers)\n case \"GYD\":\n\t\tc.Body = `Guyana Dollar`\n\n // Hong Kong\n case \"HKD\":\n\t\tc.Body = `Hong Kong Dollar`\n\n // Honduras\n case \"HNL\":\n\t\tc.Body = `Lempira`\n\n // Croatia\n case \"HRK\":\n\t\tc.Body = `Kuna`\n\n // Haiti\n case \"HTG\":\n\t\tc.Body = `Gourde`\n\n // Hungary (prices normally quoted as integers)\n case \"HUF\":\n\t\tc.Body = `Forint`\n\n // Indonesia (prices normally quoted as integers)\n case \"IDR\":\n\t\tc.Body = `Rupiah`\n\n // Ireland. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"IEP\":\n\t\tc.Body = `Punt`\n\n // Israel\n case \"ILS\":\n\t\tc.Body = `New Israeli Sheqel`\n\n // India, Bhutan (prices normally quoted as integers)\n case \"INR\":\n\t\tc.Body = `Indian Rupee`\n\n // Iraq (prices normally quoted as integers)\n case \"IQD\":\n\t\tc.Body = `Iraqi Dinar`\n\n // Iran (Islamic Republic of) (prices normally quoted as integers)\n case \"IRR\":\n\t\tc.Body = `Iranian Rial`\n\n // Iceland (prices normally quoted as integers)\n case \"ISK\":\n\t\tc.Body = `Iceland Krona`\n\n // Italy. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro (prices normally quoted as integers)\n case \"ITL\":\n\t\tc.Body = `Lira`\n\n // Jamaica\n case \"JMD\":\n\t\tc.Body = `Jamaican Dollar`\n\n // Jordan (prices normally quoted with 3 decimal places)\n case \"JOD\":\n\t\tc.Body = `Jordanian Dinar`\n\n // Japan (prices normally quoted as integers)\n case \"JPY\":\n\t\tc.Body = `Yen`\n\n // Kenya\n case \"KES\":\n\t\tc.Body = `Kenyan Shilling`\n\n // Kyrgyzstan\n case \"KGS\":\n\t\tc.Body = `Som`\n\n // Cambodia\n case \"KHR\":\n\t\tc.Body = `Riel`\n\n // Comoros (prices normally quoted as integers)\n case \"KMF\":\n\t\tc.Body = `Comorian Franc`\n\n // Korea (Democratic People’s Republic of) (prices normally quoted as integers)\n case \"KPW\":\n\t\tc.Body = `North Korean Won`\n\n // Korea (Republic of) (prices normally quoted as integers)\n case \"KRW\":\n\t\tc.Body = `Won`\n\n // Kuwait (prices normally quoted with 3 decimal places)\n case \"KWD\":\n\t\tc.Body = `Kuwaiti Dinar`\n\n // Cayman Islands\n case \"KYD\":\n\t\tc.Body = `Cayman Islands Dollar`\n\n // Kazakstan\n case \"KZT\":\n\t\tc.Body = `Tenge`\n\n // Lao People’s Democratic Republic (prices normally quoted as integers)\n case \"LAK\":\n\t\tc.Body = `Lao Kip`\n\n // Lebanon (prices normally quoted as integers)\n case \"LBP\":\n\t\tc.Body = `Lebanese Pound`\n\n // Sri Lanka\n case \"LKR\":\n\t\tc.Body = `Sri Lanka Rupee`\n\n // Liberia\n case \"LRD\":\n\t\tc.Body = `Liberian Dollar`\n\n // Lesotho\n case \"LSL\":\n\t\tc.Body = `Loti`\n\n // Lithuania. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"LTL\":\n\t\tc.Body = `Litus`\n\n // Luxembourg. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro (prices normally quoted as integers)\n case \"LUF\":\n\t\tc.Body = `Luxembourg Franc`\n\n // Latvia. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"LVL\":\n\t\tc.Body = `Latvian Lats`\n\n // Libyan Arab Jamahiriya (prices normally quoted with 3 decimal places)\n case \"LYD\":\n\t\tc.Body = `Libyan Dinar`\n\n // Morocco, Western Sahara\n case \"MAD\":\n\t\tc.Body = `Moroccan Dirham`\n\n // Moldova, Republic of\n case \"MDL\":\n\t\tc.Body = `Moldovan Leu`\n\n // Madagascar (prices normally quoted with 0 or 1 decimal place – 1 iraimbilanja = Ar0.2)\n case \"MGA\":\n\t\tc.Body = `Malagasy Ariary`\n\n // Now replaced by the Ariary (MGA) (prices normally quoted as integers)\n case \"MGF\":\n\t\tc.Body = `Malagasy Franc`\n\n // North Macedonia (formerly FYR Macedonia)\n case \"MKD\":\n\t\tc.Body = `Denar`\n\n // Myanmar (prices normally quoted as integers)\n case \"MMK\":\n\t\tc.Body = `Kyat`\n\n // Mongolia (prices normally quoted as integers)\n case \"MNT\":\n\t\tc.Body = `Tugrik`\n\n // Macau\n case \"MOP\":\n\t\tc.Body = `Pataca`\n\n // Mauritania (prices normally quoted with 0 or 1 decimal place – 1 khoums = UM0.2). Was interchangeable with MRU (New) Ouguiya at rate of 10:1 until June 2018. DEPRECATED, use MRU instead\n case \"MRO\":\n\t\tc.Body = `(Old) Ouguiya`\n\n // Mauritania (prices normally quoted with 0 or 1 decimal place – 1 khoums = UM0.2). Replaced MRO (old) Ouguiya at rate of 10:1 in June 2018. For use in ONIX 3.0 only\n case \"MRU\":\n\t\tc.Body = `Ouguiya`\n\n // Malta. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"MTL\":\n\t\tc.Body = `Maltese Lira`\n\n // Mauritius (prices normally quoted as integers)\n case \"MUR\":\n\t\tc.Body = `Mauritius Rupee`\n\n // Maldives\n case \"MVR\":\n\t\tc.Body = `Rufiyaa`\n\n // Malawi\n case \"MWK\":\n\t\tc.Body = `Malawi Kwacha`\n\n // Mexico\n case \"MXN\":\n\t\tc.Body = `Mexican Peso`\n\n // Malaysia\n case \"MYR\":\n\t\tc.Body = `Malaysian Ringgit`\n\n // Mozambique\n case \"MZN\":\n\t\tc.Body = `Mozambique Metical`\n\n // Namibia\n case \"NAD\":\n\t\tc.Body = `Namibia Dollar`\n\n // Nigeria\n case \"NGN\":\n\t\tc.Body = `Naira`\n\n // Nicaragua\n case \"NIO\":\n\t\tc.Body = `Cordoba Oro`\n\n // Netherlands. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"NLG\":\n\t\tc.Body = `Guilder`\n\n // Norway, Bouvet Island, Svalbard and Jan Mayen\n case \"NOK\":\n\t\tc.Body = `Norwegian Krone`\n\n // Nepal\n case \"NPR\":\n\t\tc.Body = `Nepalese Rupee`\n\n // New Zealand, Cook Islands, Niue, Pitcairn, Tokelau\n case \"NZD\":\n\t\tc.Body = `New Zealand Dollar`\n\n // Oman (prices normally quoted with 3 decimal places)\n case \"OMR\":\n\t\tc.Body = `Rial Omani`\n\n // Panama\n case \"PAB\":\n\t\tc.Body = `Balboa`\n\n // Peru (formerly Nuevo Sol)\n case \"PEN\":\n\t\tc.Body = `Sol`\n\n // Papua New Guinea\n case \"PGK\":\n\t\tc.Body = `Kina`\n\n // Philippines\n case \"PHP\":\n\t\tc.Body = `Philippine Peso`\n\n // Pakistan (prices normally quoted as integers)\n case \"PKR\":\n\t\tc.Body = `Pakistan Rupee`\n\n // Poland\n case \"PLN\":\n\t\tc.Body = `Złoty`\n\n // Portugal. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"PTE\":\n\t\tc.Body = `Escudo`\n\n // Paraguay (prices normally quoted as integers)\n case \"PYG\":\n\t\tc.Body = `Guarani`\n\n // Qatar\n case \"QAR\":\n\t\tc.Body = `Qatari Rial`\n\n // Deprecated, replaced by RON\n case \"ROL\":\n\t\tc.Body = `Romanian Old Leu`\n\n // Romania\n case \"RON\":\n\t\tc.Body = `Romanian Leu`\n\n // Serbia (prices normally quoted as integers)\n case \"RSD\":\n\t\tc.Body = `Serbian Dinar`\n\n // Russian Federation\n case \"RUB\":\n\t\tc.Body = `Russian Ruble`\n\n // DEPRECATED, replaced by RUB\n case \"RUR\":\n\t\tc.Body = `Russian Ruble`\n\n // Rwanda (prices normally quoted as integers)\n case \"RWF\":\n\t\tc.Body = `Rwanda Franc`\n\n // Saudi Arabia\n case \"SAR\":\n\t\tc.Body = `Saudi Riyal`\n\n // Solomon Islands\n case \"SBD\":\n\t\tc.Body = `Solomon Islands Dollar`\n\n // Seychelles\n case \"SCR\":\n\t\tc.Body = `Seychelles Rupee`\n\n // Now replaced by the Sudanese Pound (SDG)\n case \"SDD\":\n\t\tc.Body = `Sudanese Dinar`\n\n // Sudan\n case \"SDG\":\n\t\tc.Body = `Sudanese Pound`\n\n // Sweden\n case \"SEK\":\n\t\tc.Body = `Swedish Krona`\n\n // Singapore\n case \"SGD\":\n\t\tc.Body = `Singapore Dollar`\n\n // Saint Helena\n case \"SHP\":\n\t\tc.Body = `Saint Helena Pound`\n\n // Slovenia. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"SIT\":\n\t\tc.Body = `Tolar`\n\n // Slovakia. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"SKK\":\n\t\tc.Body = `Slovak Koruna`\n\n // Sierra Leone (prices normally quoted as integers)\n case \"SLL\":\n\t\tc.Body = `Leone`\n\n // Somalia (prices normally quoted as integers)\n case \"SOS\":\n\t\tc.Body = `Somali Shilling`\n\n // Suriname\n case \"SRD\":\n\t\tc.Body = `Surinam Dollar`\n\n // DEPRECATED, replaced by SRD\n case \"SRG\":\n\t\tc.Body = `Suriname Guilder`\n\n // São Tome and Principe (prices normally quoted as integers). Was interchangeable with STN (New) Dobra at rate of 1000:1 until June 2018. DEPRECATED, use STN instead\n case \"STD\":\n\t\tc.Body = `(Old) Dobra`\n\n // São Tome and Principe. Replaced STD (old) Dobra at rate of 1000:1 in June 2018. For use in ONIX 3.0 only\n case \"STN\":\n\t\tc.Body = `Dobra`\n\n // El Salvador\n case \"SVC\":\n\t\tc.Body = `El Salvador Colon`\n\n // Syrian Arab Republic (prices normally quoted as integers)\n case \"SYP\":\n\t\tc.Body = `Syrian Pound`\n\n // Eswatini (formerly known as Swaziland)\n case \"SZL\":\n\t\tc.Body = `Lilangeni`\n\n // Thailand\n case \"THB\":\n\t\tc.Body = `Baht`\n\n // Tajikistan\n case \"TJS\":\n\t\tc.Body = `Somoni`\n\n // Deprecated, replaced by TMT (prices normally quoted as integers)\n case \"TMM\":\n\t\tc.Body = `Turkmenistan Manat`\n\n // Turkmenistan\n case \"TMT\":\n\t\tc.Body = `Turkmenistan New Manat`\n\n // Tunisia (prices normally quoted with 3 decimal places)\n case \"TND\":\n\t\tc.Body = `Tunisian Dinar`\n\n // Tonga\n case \"TOP\":\n\t\tc.Body = `Pa’anga`\n\n // Deprecated. Timor-Leste now uses the US Dollar\n case \"TPE\":\n\t\tc.Body = `Timor Escudo`\n\n // Deprecated, replaced by TRY (prices normally quoted as integers)\n case \"TRL\":\n\t\tc.Body = `Turkish Lira (old)`\n\n // Turkey, from 1 January 2005\n case \"TRY\":\n\t\tc.Body = `Turkish Lira`\n\n // Trinidad and Tobago\n case \"TTD\":\n\t\tc.Body = `Trinidad and Tobago Dollar`\n\n // Taiwan (Province of China)\n case \"TWD\":\n\t\tc.Body = `New Taiwan Dollar`\n\n // Tanzania (United Republic of) (prices normally quoted as integers)\n case \"TZS\":\n\t\tc.Body = `Tanzanian Shilling`\n\n // Ukraine\n case \"UAH\":\n\t\tc.Body = `Hryvnia`\n\n // Uganda (prices normally quoted as integers)\n case \"UGX\":\n\t\tc.Body = `Uganda Shilling`\n\n // United States, American Samoa, Bonaire, Sint Eustatius and Saba, British Indian Ocean Territory, Ecuador, El Salvador, Guam, Haiti, Marshall Is, Micronesia (Federated States of), Northern Mariana Is, Palau, Panama, Puerto Rico, Timor-Leste, Turks and Caicos Is, US Minor Outlying Is, Virgin Is (British), Virgin Is (US)\n case \"USD\":\n\t\tc.Body = `US Dollar`\n\n // Uruguay\n case \"UYU\":\n\t\tc.Body = `Peso Uruguayo`\n\n // Uzbekistan (prices normally quoted as integers)\n case \"UZS\":\n\t\tc.Body = `Uzbekistan Sum`\n\n // Deprecated, replaced by VEF\n case \"VEB\":\n\t\tc.Body = `Bolívar`\n\n // Venezuela (formerly Bolívar fuerte). Deprecated, replaced by VES\n case \"VEF\":\n\t\tc.Body = `Bolívar`\n\n // Venezuela (replaced VEF from August 2018 at rate of 100,000:1). For use in ONIX 3.0 only\n case \"VES\":\n\t\tc.Body = `Bolívar Soberano`\n\n // Viet Nam (prices normally quoted as integers)\n case \"VND\":\n\t\tc.Body = `Dong`\n\n // Vanuatu (prices normally quoted as integers)\n case \"VUV\":\n\t\tc.Body = `Vatu`\n\n // Samoa\n case \"WST\":\n\t\tc.Body = `Tala`\n\n // Cameroon, Central African Republic, Chad, Congo, Equatorial Guinea, Gabon (prices normally quoted as integers)\n case \"XAF\":\n\t\tc.Body = `CFA Franc BEAC`\n\n // Anguilla, Antigua and Barbuda, Dominica, Grenada, Montserrat, Saint Kitts and Nevis, Saint Lucia, Saint Vincent and the Grenadines\n case \"XCD\":\n\t\tc.Body = `East Caribbean Dollar`\n\n // Benin, Burkina Faso, Côte D’Ivoire, Guinea-Bissau, Mali, Niger, Senegal, Togo (prices normally quoted as integers)\n case \"XOF\":\n\t\tc.Body = `CFA Franc BCEAO`\n\n // French Polynesia, New Caledonia, Wallis and Futuna (prices normally quoted as integers)\n case \"XPF\":\n\t\tc.Body = `CFP Franc`\n\n // Yemen (prices normally quoted as integers)\n case \"YER\":\n\t\tc.Body = `Yemeni Rial`\n\n // DEPRECATED, replaced by CSD\n case \"YUM\":\n\t\tc.Body = `Yugoslavian Dinar`\n\n // South Africa, Namibia, Lesotho\n case \"ZAR\":\n\t\tc.Body = `Rand`\n\n // Zambia. Deprecated, replaced with ZMW (prices normally quoted as integers)\n case \"ZMK\":\n\t\tc.Body = `Kwacha`\n\n // Zambia\n case \"ZMW\":\n\t\tc.Body = `Zambian Kwacha`\n\n // Deprecated, replaced with ZWL (prices normally quoted as integers)\n case \"ZWD\":\n\t\tc.Body = `Zimbabwe Dollar`\n\n // Zimbabwe\n case \"ZWL\":\n\t\tc.Body = `Zimbabwe Dollar`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for CurrencyCode has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func DetectCharset(body []byte, contentType string) (string, error) {\n\t// 1. Use charset.DetermineEncoding\n\t_, name, certain := charset.DetermineEncoding(body, contentType)\n\tif certain {\n\t\treturn name, nil\n\t}\n\n\t// Handle uncertain cases\n\t// 2. Use chardet.Detector.DetectBest\n\tr, err := chardet.NewHtmlDetector().DetectBest(body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif r.Confidence == 100 {\n\t\treturn strings.ToLower(r.Charset), nil\n\t}\n\n\t// 3. Parse meta tag for Content-Type\n\troot, err := html.Parse(bytes.NewReader(body))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdoc := goquery.NewDocumentFromNode(root)\n\tvar csFromMeta string\n\tdoc.Find(\"meta\").EachWithBreak(func(i int, s *goquery.Selection) bool {\n\t\t// <meta http-equiv=\"Content-Type\" content=\"text/html; charset=MS949\"/>\n\t\tif c, exists := s.Attr(\"content\"); exists && strings.Contains(c, \"charset\") {\n\t\t\tif _, params, err := mime.ParseMediaType(c); err == nil {\n\t\t\t\tif cs, ok := params[\"charset\"]; ok {\n\t\t\t\t\tcsFromMeta = strings.ToLower(cs)\n\t\t\t\t\t// Handle Korean charsets.\n\t\t\t\t\tif csFromMeta == \"ms949\" || csFromMeta == \"cp949\" {\n\t\t\t\t\t\tcsFromMeta = \"euc-kr\"\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\n\t\t// <meta charset=\"utf-8\"/>\n\t\tif c, exists := s.Attr(\"charset\"); exists {\n\t\t\tcsFromMeta = c\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t})\n\n\tif csFromMeta == \"\" {\n\t\treturn \"\", fmt.Errorf(\"failed to detect charset\")\n\t}\n\n\treturn csFromMeta, nil\n}", "func (c *FromLanguage) 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 // Afar\n case \"aar\":\n\t\tc.Body = `Afar`\n\n // Abkhaz\n case \"abk\":\n\t\tc.Body = `Abkhaz`\n\n // Achinese\n case \"ace\":\n\t\tc.Body = `Achinese`\n\n // Acoli\n case \"ach\":\n\t\tc.Body = `Acoli`\n\n // Adangme\n case \"ada\":\n\t\tc.Body = `Adangme`\n\n // Adygei\n case \"ady\":\n\t\tc.Body = `Adygei`\n\n // Collective name\n case \"afa\":\n\t\tc.Body = `Afro-Asiatic languages`\n\n // Artificial language\n case \"afh\":\n\t\tc.Body = `Afrihili`\n\n // Afrikaans\n case \"afr\":\n\t\tc.Body = `Afrikaans`\n\n // Ainu\n case \"ain\":\n\t\tc.Body = `Ainu`\n\n // Macrolanguage\n case \"aka\":\n\t\tc.Body = `Akan`\n\n // Akkadian\n case \"akk\":\n\t\tc.Body = `Akkadian`\n\n // Macrolanguage\n case \"alb\":\n\t\tc.Body = `Albanian`\n\n // Aleut\n case \"ale\":\n\t\tc.Body = `Aleut`\n\n // Collective name\n case \"alg\":\n\t\tc.Body = `Algonquian languages`\n\n // Southern Altai\n case \"alt\":\n\t\tc.Body = `Southern Altai`\n\n // Amharic\n case \"amh\":\n\t\tc.Body = `Amharic`\n\n // English, Old (ca. 450-1100)\n case \"ang\":\n\t\tc.Body = `English, Old (ca. 450-1100)`\n\n // Angika\n case \"anp\":\n\t\tc.Body = `Angika`\n\n // Collective name\n case \"apa\":\n\t\tc.Body = `Apache languages`\n\n // Macrolanguage\n case \"ara\":\n\t\tc.Body = `Arabic`\n\n // Official Aramaic; Imperial Aramaic (700-300 BCE)\n case \"arc\":\n\t\tc.Body = `Official Aramaic; Imperial Aramaic (700-300 BCE)`\n\n // Aragonese\n case \"arg\":\n\t\tc.Body = `Aragonese`\n\n // Armenian\n case \"arm\":\n\t\tc.Body = `Armenian`\n\n // Mapudungun; Mapuche\n case \"arn\":\n\t\tc.Body = `Mapudungun; Mapuche`\n\n // Arapaho\n case \"arp\":\n\t\tc.Body = `Arapaho`\n\n // Collective name\n case \"art\":\n\t\tc.Body = `Artificial languages`\n\n // Arawak\n case \"arw\":\n\t\tc.Body = `Arawak`\n\n // Assamese\n case \"asm\":\n\t\tc.Body = `Assamese`\n\n // Asturian; Bable; Leonese; Asturleonese\n case \"ast\":\n\t\tc.Body = `Asturian; Bable; Leonese; Asturleonese`\n\n // Collective name\n case \"ath\":\n\t\tc.Body = `Athapascan languages`\n\n // Collective name\n case \"aus\":\n\t\tc.Body = `Australian languages`\n\n // Avaric\n case \"ava\":\n\t\tc.Body = `Avaric`\n\n // Avestan\n case \"ave\":\n\t\tc.Body = `Avestan`\n\n // Awadhi\n case \"awa\":\n\t\tc.Body = `Awadhi`\n\n // Macrolanguage\n case \"aym\":\n\t\tc.Body = `Aymara`\n\n // Macrolanguage\n case \"aze\":\n\t\tc.Body = `Azerbaijani`\n\n // Collective name\n case \"bad\":\n\t\tc.Body = `Banda languages`\n\n // Collective name\n case \"bai\":\n\t\tc.Body = `Bamileke languages`\n\n // Bashkir\n case \"bak\":\n\t\tc.Body = `Bashkir`\n\n // Macrolanguage\n case \"bal\":\n\t\tc.Body = `Baluchi`\n\n // Bambara\n case \"bam\":\n\t\tc.Body = `Bambara`\n\n // Balinese\n case \"ban\":\n\t\tc.Body = `Balinese`\n\n // Basque\n case \"baq\":\n\t\tc.Body = `Basque`\n\n // Basa\n case \"bas\":\n\t\tc.Body = `Basa`\n\n // Collective name\n case \"bat\":\n\t\tc.Body = `Baltic languages`\n\n // Beja; Bedawiyet\n case \"bej\":\n\t\tc.Body = `Beja; Bedawiyet`\n\n // Belarusian\n case \"bel\":\n\t\tc.Body = `Belarusian`\n\n // Bemba\n case \"bem\":\n\t\tc.Body = `Bemba`\n\n // Bengali\n case \"ben\":\n\t\tc.Body = `Bengali`\n\n // Collective name\n case \"ber\":\n\t\tc.Body = `Berber languages`\n\n // Bhojpuri\n case \"bho\":\n\t\tc.Body = `Bhojpuri`\n\n // Collective name\n case \"bih\":\n\t\tc.Body = `Bihari languages`\n\n // Macrolanguage\n case \"bik\":\n\t\tc.Body = `Bikol`\n\n // Bini; Edo\n case \"bin\":\n\t\tc.Body = `Bini; Edo`\n\n // Bislama\n case \"bis\":\n\t\tc.Body = `Bislama`\n\n // Siksika\n case \"bla\":\n\t\tc.Body = `Siksika`\n\n // Collective name\n case \"bnt\":\n\t\tc.Body = `Bantu languages`\n\n // Bosnian\n case \"bos\":\n\t\tc.Body = `Bosnian`\n\n // Braj\n case \"bra\":\n\t\tc.Body = `Braj`\n\n // Breton\n case \"bre\":\n\t\tc.Body = `Breton`\n\n // Collective name\n case \"btk\":\n\t\tc.Body = `Batak languages`\n\n // Macrolanguage\n case \"bua\":\n\t\tc.Body = `Buriat`\n\n // Buginese\n case \"bug\":\n\t\tc.Body = `Buginese`\n\n // Bulgarian\n case \"bul\":\n\t\tc.Body = `Bulgarian`\n\n // Burmese\n case \"bur\":\n\t\tc.Body = `Burmese`\n\n // Blin; Bilin\n case \"byn\":\n\t\tc.Body = `Blin; Bilin`\n\n // Caddo\n case \"cad\":\n\t\tc.Body = `Caddo`\n\n // Collective name\n case \"cai\":\n\t\tc.Body = `Central American Indian languages`\n\n // Galibi Carib\n case \"car\":\n\t\tc.Body = `Galibi Carib`\n\n // Catalan\n case \"cat\":\n\t\tc.Body = `Catalan`\n\n // Collective name\n case \"cau\":\n\t\tc.Body = `Caucasian languages`\n\n // Cebuano\n case \"ceb\":\n\t\tc.Body = `Cebuano`\n\n // Collective name\n case \"cel\":\n\t\tc.Body = `Celtic languages`\n\n // Chamorro\n case \"cha\":\n\t\tc.Body = `Chamorro`\n\n // Chibcha\n case \"chb\":\n\t\tc.Body = `Chibcha`\n\n // Chechen\n case \"che\":\n\t\tc.Body = `Chechen`\n\n // Chagatai\n case \"chg\":\n\t\tc.Body = `Chagatai`\n\n // Macrolanguage\n case \"chi\":\n\t\tc.Body = `Chinese`\n\n // Chuukese (Truk)\n case \"chk\":\n\t\tc.Body = `Chuukese (Truk)`\n\n // Macrolanguage\n case \"chm\":\n\t\tc.Body = `Mari`\n\n // Chinook jargon\n case \"chn\":\n\t\tc.Body = `Chinook jargon`\n\n // Choctaw\n case \"cho\":\n\t\tc.Body = `Choctaw`\n\n // Chipewyan; Dene Suline\n case \"chp\":\n\t\tc.Body = `Chipewyan; Dene Suline`\n\n // Cherokee\n case \"chr\":\n\t\tc.Body = `Cherokee`\n\n // Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic\n case \"chu\":\n\t\tc.Body = `Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic`\n\n // Chuvash\n case \"chv\":\n\t\tc.Body = `Chuvash`\n\n // Cheyenne\n case \"chy\":\n\t\tc.Body = `Cheyenne`\n\n // ONIX local code, equivalent to ckb in ISO 639-3. For use in ONIX 3.0 only\n case \"ckb\":\n\t\tc.Body = `Central Kurdish (Sorani)`\n\n // Collective name\n case \"cmc\":\n\t\tc.Body = `Chamic languages`\n\n // ONIX local code, equivalent to cmn in ISO 639-3\n case \"cmn\":\n\t\tc.Body = `Mandarin`\n\n // For use in ONIX 3.0 only\n case \"cnr\":\n\t\tc.Body = `Montenegrin`\n\n // Coptic\n case \"cop\":\n\t\tc.Body = `Coptic`\n\n // Cornish\n case \"cor\":\n\t\tc.Body = `Cornish`\n\n // Corsican\n case \"cos\":\n\t\tc.Body = `Corsican`\n\n // Collective name\n case \"cpe\":\n\t\tc.Body = `Creoles and pidgins, English-based`\n\n // Collective name\n case \"cpf\":\n\t\tc.Body = `Creoles and pidgins, French-based`\n\n // Collective name\n case \"cpp\":\n\t\tc.Body = `Creoles and pidgins, Portuguese-based`\n\n // Macrolanguage\n case \"cre\":\n\t\tc.Body = `Cree`\n\n // Crimean Turkish; Crimean Tatar\n case \"crh\":\n\t\tc.Body = `Crimean Turkish; Crimean Tatar`\n\n // Collective name\n case \"crp\":\n\t\tc.Body = `Creoles and pidgins`\n\n // Kashubian\n case \"csb\":\n\t\tc.Body = `Kashubian`\n\n // Collective name\n case \"cus\":\n\t\tc.Body = `Cushitic languages`\n\n // Czech\n case \"cze\":\n\t\tc.Body = `Czech`\n\n // Dakota\n case \"dak\":\n\t\tc.Body = `Dakota`\n\n // Danish\n case \"dan\":\n\t\tc.Body = `Danish`\n\n // Dargwa\n case \"dar\":\n\t\tc.Body = `Dargwa`\n\n // Collective name\n case \"day\":\n\t\tc.Body = `Land Dayak languages`\n\n // Macrolanguage\n case \"del\":\n\t\tc.Body = `Delaware`\n\n // Macrolanguage\n case \"den\":\n\t\tc.Body = `Slave (Athapascan)`\n\n // Dogrib\n case \"dgr\":\n\t\tc.Body = `Dogrib`\n\n // Macrolanguage\n case \"din\":\n\t\tc.Body = `Dinka`\n\n // Divehi; Dhivehi; Maldivian\n case \"div\":\n\t\tc.Body = `Divehi; Dhivehi; Maldivian`\n\n // Macrolanguage\n case \"doi\":\n\t\tc.Body = `Dogri`\n\n // Collective name\n case \"dra\":\n\t\tc.Body = `Dravidian languages`\n\n // Lower Sorbian\n case \"dsb\":\n\t\tc.Body = `Lower Sorbian`\n\n // Duala\n case \"dua\":\n\t\tc.Body = `Duala`\n\n // Dutch, Middle (ca. 1050-1350)\n case \"dum\":\n\t\tc.Body = `Dutch, Middle (ca. 1050-1350)`\n\n // Dutch; Flemish\n case \"dut\":\n\t\tc.Body = `Dutch; Flemish`\n\n // Dyula\n case \"dyu\":\n\t\tc.Body = `Dyula`\n\n // Dzongkha\n case \"dzo\":\n\t\tc.Body = `Dzongkha`\n\n // Efik\n case \"efi\":\n\t\tc.Body = `Efik`\n\n // ONIX local code for Italian dialect, equivalent to egl in ISO 639-3. For use in ONIX 3.0 only\n case \"egl\":\n\t\tc.Body = `Emilian`\n\n // Egyptian (Ancient)\n case \"egy\":\n\t\tc.Body = `Egyptian (Ancient)`\n\n // Ekajuk\n case \"eka\":\n\t\tc.Body = `Ekajuk`\n\n // Elamite\n case \"elx\":\n\t\tc.Body = `Elamite`\n\n // English\n case \"eng\":\n\t\tc.Body = `English`\n\n // English, Middle (1100-1500)\n case \"enm\":\n\t\tc.Body = `English, Middle (1100-1500)`\n\n // Artificial language\n case \"epo\":\n\t\tc.Body = `Esperanto`\n\n // Macrolanguage\n case \"est\":\n\t\tc.Body = `Estonian`\n\n // Ewe\n case \"ewe\":\n\t\tc.Body = `Ewe`\n\n // Ewondo\n case \"ewo\":\n\t\tc.Body = `Ewondo`\n\n // Fang\n case \"fan\":\n\t\tc.Body = `Fang`\n\n // Faroese\n case \"fao\":\n\t\tc.Body = `Faroese`\n\n // Fanti\n case \"fat\":\n\t\tc.Body = `Fanti`\n\n // Fijian\n case \"fij\":\n\t\tc.Body = `Fijian`\n\n // Filipino; Pilipino\n case \"fil\":\n\t\tc.Body = `Filipino; Pilipino`\n\n // Finnish\n case \"fin\":\n\t\tc.Body = `Finnish`\n\n // ONIX local code, equivalent to fit in ISO 639-3\n case \"fit\":\n\t\tc.Body = `Meänkieli / Tornedalen Finnish`\n\n // Collective name\n case \"fiu\":\n\t\tc.Body = `Finno-Ugrian languages`\n\n // ONIX local code, equivalent to fkv in ISO 639-3\n case \"fkv\":\n\t\tc.Body = `Kvensk`\n\n // Fon\n case \"fon\":\n\t\tc.Body = `Fon`\n\n // French\n case \"fre\":\n\t\tc.Body = `French`\n\n // French, Middle (ca. 1400-1600)\n case \"frm\":\n\t\tc.Body = `French, Middle (ca. 1400-1600)`\n\n // French, Old (ca. 842-1400)\n case \"fro\":\n\t\tc.Body = `French, Old (ca. 842-1400)`\n\n // Northern Frisian\n case \"frr\":\n\t\tc.Body = `Northern Frisian`\n\n // Eastern Frisian\n case \"frs\":\n\t\tc.Body = `Eastern Frisian`\n\n // Western Frisian\n case \"fry\":\n\t\tc.Body = `Western Frisian`\n\n // Fulah\n case \"ful\":\n\t\tc.Body = `Fulah`\n\n // Friulian\n case \"fur\":\n\t\tc.Body = `Friulian`\n\n // Gã\n case \"gaa\":\n\t\tc.Body = `Gã`\n\n // Gayo\n case \"gay\":\n\t\tc.Body = `Gayo`\n\n // Macrolanguage\n case \"gba\":\n\t\tc.Body = `Gbaya`\n\n // Collective name\n case \"gem\":\n\t\tc.Body = `Germanic languages`\n\n // Georgian\n case \"geo\":\n\t\tc.Body = `Georgian`\n\n // German\n case \"ger\":\n\t\tc.Body = `German`\n\n // Ethiopic (Ge’ez)\n case \"gez\":\n\t\tc.Body = `Ethiopic (Ge’ez)`\n\n // Gilbertese\n case \"gil\":\n\t\tc.Body = `Gilbertese`\n\n // Scottish Gaelic\n case \"gla\":\n\t\tc.Body = `Scottish Gaelic`\n\n // Irish\n case \"gle\":\n\t\tc.Body = `Irish`\n\n // Galician\n case \"glg\":\n\t\tc.Body = `Galician`\n\n // Manx\n case \"glv\":\n\t\tc.Body = `Manx`\n\n // German, Middle High (ca. 1050-1500)\n case \"gmh\":\n\t\tc.Body = `German, Middle High (ca. 1050-1500)`\n\n // German, Old High (ca. 750-1050)\n case \"goh\":\n\t\tc.Body = `German, Old High (ca. 750-1050)`\n\n // Macrolanguage\n case \"gon\":\n\t\tc.Body = `Gondi`\n\n // Gorontalo\n case \"gor\":\n\t\tc.Body = `Gorontalo`\n\n // Gothic\n case \"got\":\n\t\tc.Body = `Gothic`\n\n // Macrolanguage\n case \"grb\":\n\t\tc.Body = `Grebo`\n\n // Greek, Ancient (to 1453)\n case \"grc\":\n\t\tc.Body = `Greek, Ancient (to 1453)`\n\n // Greek, Modern (1453-)\n case \"gre\":\n\t\tc.Body = `Greek, Modern (1453-)`\n\n // Macrolanguage\n case \"grn\":\n\t\tc.Body = `Guarani`\n\n // ONIX local code, equivalent to grt in ISO 639-3\n case \"grt\":\n\t\tc.Body = `Garo`\n\n // Swiss German; Alemannic\n case \"gsw\":\n\t\tc.Body = `Swiss German; Alemannic`\n\n // Gujarati\n case \"guj\":\n\t\tc.Body = `Gujarati`\n\n // Gwich’in\n case \"gwi\":\n\t\tc.Body = `Gwich’in`\n\n // Macrolanguage\n case \"hai\":\n\t\tc.Body = `Haida`\n\n // Haitian French Creole\n case \"hat\":\n\t\tc.Body = `Haitian French Creole`\n\n // Hausa\n case \"hau\":\n\t\tc.Body = `Hausa`\n\n // Hawaiian\n case \"haw\":\n\t\tc.Body = `Hawaiian`\n\n // Hebrew\n case \"heb\":\n\t\tc.Body = `Hebrew`\n\n // Herero\n case \"her\":\n\t\tc.Body = `Herero`\n\n // Hiligaynon\n case \"hil\":\n\t\tc.Body = `Hiligaynon`\n\n // Collective name\n case \"him\":\n\t\tc.Body = `Himachali languages; Western Pahari languages`\n\n // Hindi\n case \"hin\":\n\t\tc.Body = `Hindi`\n\n // Hittite\n case \"hit\":\n\t\tc.Body = `Hittite`\n\n // Macrolanguage\n case \"hmn\":\n\t\tc.Body = `Hmong; Mong`\n\n // Hiri Motu\n case \"hmo\":\n\t\tc.Body = `Hiri Motu`\n\n // Croatian\n case \"hrv\":\n\t\tc.Body = `Croatian`\n\n // Upper Sorbian\n case \"hsb\":\n\t\tc.Body = `Upper Sorbian`\n\n // Hungarian\n case \"hun\":\n\t\tc.Body = `Hungarian`\n\n // Hupa\n case \"hup\":\n\t\tc.Body = `Hupa`\n\n // Iban\n case \"iba\":\n\t\tc.Body = `Iban`\n\n // Igbo\n case \"ibo\":\n\t\tc.Body = `Igbo`\n\n // Icelandic\n case \"ice\":\n\t\tc.Body = `Icelandic`\n\n // Artificial language\n case \"ido\":\n\t\tc.Body = `Ido`\n\n // Sichuan Yi; Nuosu\n case \"iii\":\n\t\tc.Body = `Sichuan Yi; Nuosu`\n\n // Collective name\n case \"ijo\":\n\t\tc.Body = `Ijo languages`\n\n // Macrolanguage\n case \"iku\":\n\t\tc.Body = `Inuktitut`\n\n // Artificial language\n case \"ile\":\n\t\tc.Body = `Interlingue; Occidental`\n\n // Iloko\n case \"ilo\":\n\t\tc.Body = `Iloko`\n\n // Artificial language\n case \"ina\":\n\t\tc.Body = `Interlingua (International Auxiliary Language Association)`\n\n // Collective name\n case \"inc\":\n\t\tc.Body = `Indic languages`\n\n // Indonesian\n case \"ind\":\n\t\tc.Body = `Indonesian`\n\n // Collective name\n case \"ine\":\n\t\tc.Body = `Indo-European languages`\n\n // Ingush\n case \"inh\":\n\t\tc.Body = `Ingush`\n\n // Macrolanguage\n case \"ipk\":\n\t\tc.Body = `Inupiaq`\n\n // Collective name\n case \"ira\":\n\t\tc.Body = `Iranian languages`\n\n // Collective name\n case \"iro\":\n\t\tc.Body = `Iroquoian languages`\n\n // Italian\n case \"ita\":\n\t\tc.Body = `Italian`\n\n // Javanese\n case \"jav\":\n\t\tc.Body = `Javanese`\n\n // Lojban\n case \"jbo\":\n\t\tc.Body = `Lojban`\n\n // Japanese\n case \"jpn\":\n\t\tc.Body = `Japanese`\n\n // Judeo-Persian\n case \"jpr\":\n\t\tc.Body = `Judeo-Persian`\n\n // Macrolanguage\n case \"jrb\":\n\t\tc.Body = `Judeo-Arabic`\n\n // Kara-Kalpak\n case \"kaa\":\n\t\tc.Body = `Kara-Kalpak`\n\n // Kabyle\n case \"kab\":\n\t\tc.Body = `Kabyle`\n\n // Kachin; Jingpho\n case \"kac\":\n\t\tc.Body = `Kachin; Jingpho`\n\n // Kalâtdlisut; Greenlandic\n case \"kal\":\n\t\tc.Body = `Kalâtdlisut; Greenlandic`\n\n // Kamba\n case \"kam\":\n\t\tc.Body = `Kamba`\n\n // Kannada\n case \"kan\":\n\t\tc.Body = `Kannada`\n\n // Collective name\n case \"kar\":\n\t\tc.Body = `Karen languages`\n\n // Kashmiri\n case \"kas\":\n\t\tc.Body = `Kashmiri`\n\n // Macrolanguage\n case \"kau\":\n\t\tc.Body = `Kanuri`\n\n // Kawi\n case \"kaw\":\n\t\tc.Body = `Kawi`\n\n // Kazakh\n case \"kaz\":\n\t\tc.Body = `Kazakh`\n\n // Kabardian (Circassian)\n case \"kbd\":\n\t\tc.Body = `Kabardian (Circassian)`\n\n // ONIX local code, equivalent to kdr in ISO 639-3\n case \"kdr\":\n\t\tc.Body = `Karaim`\n\n // Khasi\n case \"kha\":\n\t\tc.Body = `Khasi`\n\n // Collective name\n case \"khi\":\n\t\tc.Body = `Khoisan languages`\n\n // Central Khmer\n case \"khm\":\n\t\tc.Body = `Central Khmer`\n\n // Khotanese; Sakan\n case \"kho\":\n\t\tc.Body = `Khotanese; Sakan`\n\n // Kikuyu; Gikuyu\n case \"kik\":\n\t\tc.Body = `Kikuyu; Gikuyu`\n\n // Kinyarwanda\n case \"kin\":\n\t\tc.Body = `Kinyarwanda`\n\n // Kirghiz; Kyrgyz\n case \"kir\":\n\t\tc.Body = `Kirghiz; Kyrgyz`\n\n // Kimbundu\n case \"kmb\":\n\t\tc.Body = `Kimbundu`\n\n // Macrolanguage\n case \"kok\":\n\t\tc.Body = `Konkani`\n\n // Macrolanguage\n case \"kom\":\n\t\tc.Body = `Komi`\n\n // Macrolanguage\n case \"kon\":\n\t\tc.Body = `Kongo`\n\n // Korean\n case \"kor\":\n\t\tc.Body = `Korean`\n\n // Kusaiean (Caroline Islands)\n case \"kos\":\n\t\tc.Body = `Kusaiean (Caroline Islands)`\n\n // Macrolanguage\n case \"kpe\":\n\t\tc.Body = `Kpelle`\n\n // Karachay-Balkar\n case \"krc\":\n\t\tc.Body = `Karachay-Balkar`\n\n // Karelian\n case \"krl\":\n\t\tc.Body = `Karelian`\n\n // Collective name\n case \"kro\":\n\t\tc.Body = `Kru languages`\n\n // Kurukh\n case \"kru\":\n\t\tc.Body = `Kurukh`\n\n // Kuanyama\n case \"kua\":\n\t\tc.Body = `Kuanyama`\n\n // Kumyk\n case \"kum\":\n\t\tc.Body = `Kumyk`\n\n // Macrolanguage\n case \"kur\":\n\t\tc.Body = `Kurdish`\n\n // Kutenai\n case \"kut\":\n\t\tc.Body = `Kutenai`\n\n // Ladino\n case \"lad\":\n\t\tc.Body = `Ladino`\n\n // Macrolanguage\n case \"lah\":\n\t\tc.Body = `Lahnda`\n\n // Lamba\n case \"lam\":\n\t\tc.Body = `Lamba`\n\n // Lao\n case \"lao\":\n\t\tc.Body = `Lao`\n\n // Latin\n case \"lat\":\n\t\tc.Body = `Latin`\n\n // Macrolanguage\n case \"lav\":\n\t\tc.Body = `Latvian`\n\n // Lezgian\n case \"lez\":\n\t\tc.Body = `Lezgian`\n\n // ONIX local code for Italian dialect, equivalent to lij in ISO 639-3. For use in ONIX 3.0 only\n case \"lij\":\n\t\tc.Body = `Ligurian`\n\n // Limburgish\n case \"lim\":\n\t\tc.Body = `Limburgish`\n\n // Lingala\n case \"lin\":\n\t\tc.Body = `Lingala`\n\n // Lithuanian\n case \"lit\":\n\t\tc.Body = `Lithuanian`\n\n // ONIX local code for Italian dialect, equivalent to lmo in ISO 639-3. For use in ONIX 3.0 only\n case \"lmo\":\n\t\tc.Body = `Lombard`\n\n // Mongo-Nkundu\n case \"lol\":\n\t\tc.Body = `Mongo-Nkundu`\n\n // Lozi\n case \"loz\":\n\t\tc.Body = `Lozi`\n\n // Luxembourgish; Letzeburgesch\n case \"ltz\":\n\t\tc.Body = `Luxembourgish; Letzeburgesch`\n\n // Luba-Lulua\n case \"lua\":\n\t\tc.Body = `Luba-Lulua`\n\n // Luba-Katanga\n case \"lub\":\n\t\tc.Body = `Luba-Katanga`\n\n // Ganda\n case \"lug\":\n\t\tc.Body = `Ganda`\n\n // Luiseño\n case \"lui\":\n\t\tc.Body = `Luiseño`\n\n // Lunda\n case \"lun\":\n\t\tc.Body = `Lunda`\n\n // Luo (Kenya and Tanzania)\n case \"luo\":\n\t\tc.Body = `Luo (Kenya and Tanzania)`\n\n // Lushai\n case \"lus\":\n\t\tc.Body = `Lushai`\n\n // Macedonian\n case \"mac\":\n\t\tc.Body = `Macedonian`\n\n // Madurese\n case \"mad\":\n\t\tc.Body = `Madurese`\n\n // Magahi\n case \"mag\":\n\t\tc.Body = `Magahi`\n\n // Marshallese\n case \"mah\":\n\t\tc.Body = `Marshallese`\n\n // Maithili\n case \"mai\":\n\t\tc.Body = `Maithili`\n\n // Makasar\n case \"mak\":\n\t\tc.Body = `Makasar`\n\n // Malayalam\n case \"mal\":\n\t\tc.Body = `Malayalam`\n\n // Macrolanguage\n case \"man\":\n\t\tc.Body = `Mandingo`\n\n // Maori\n case \"mao\":\n\t\tc.Body = `Maori`\n\n // Collective name\n case \"map\":\n\t\tc.Body = `Austronesian languages`\n\n // Marathi\n case \"mar\":\n\t\tc.Body = `Marathi`\n\n // Masai\n case \"mas\":\n\t\tc.Body = `Masai`\n\n // Macrolanguage\n case \"may\":\n\t\tc.Body = `Malay`\n\n // Moksha\n case \"mdf\":\n\t\tc.Body = `Moksha`\n\n // Mandar\n case \"mdr\":\n\t\tc.Body = `Mandar`\n\n // Mende\n case \"men\":\n\t\tc.Body = `Mende`\n\n // Irish, Middle (ca. 1100-1550)\n case \"mga\":\n\t\tc.Body = `Irish, Middle (ca. 1100-1550)`\n\n // Mi’kmaq; Micmac\n case \"mic\":\n\t\tc.Body = `Mi’kmaq; Micmac`\n\n // Minangkabau\n case \"min\":\n\t\tc.Body = `Minangkabau`\n\n // Use where no suitable code is available\n case \"mis\":\n\t\tc.Body = `Uncoded languages`\n\n // Collective name\n case \"mkh\":\n\t\tc.Body = `Mon-Khmer languages`\n\n // Macrolanguage\n case \"mlg\":\n\t\tc.Body = `Malagasy`\n\n // Maltese\n case \"mlt\":\n\t\tc.Body = `Maltese`\n\n // Manchu\n case \"mnc\":\n\t\tc.Body = `Manchu`\n\n // Manipuri\n case \"mni\":\n\t\tc.Body = `Manipuri`\n\n // Collective name\n case \"mno\":\n\t\tc.Body = `Manobo languages`\n\n // Mohawk\n case \"moh\":\n\t\tc.Body = `Mohawk`\n\n // DEPRECATED – use rum\n case \"mol\":\n\t\tc.Body = `Moldavian; Moldovan`\n\n // Macrolanguage\n case \"mon\":\n\t\tc.Body = `Mongolian`\n\n // Mooré; Mossi\n case \"mos\":\n\t\tc.Body = `Mooré; Mossi`\n\n // Multiple languages\n case \"mul\":\n\t\tc.Body = `Multiple languages`\n\n // Collective name\n case \"mun\":\n\t\tc.Body = `Munda languages`\n\n // Creek\n case \"mus\":\n\t\tc.Body = `Creek`\n\n // ONIX local code, equivalent to mwf in ISO 639-3. For use in ONIX 3.0 only\n case \"mwf\":\n\t\tc.Body = `Murrinh-Patha`\n\n // Mirandese\n case \"mwl\":\n\t\tc.Body = `Mirandese`\n\n // Macrolanguage\n case \"mwr\":\n\t\tc.Body = `Marwari`\n\n // Collective name\n case \"myn\":\n\t\tc.Body = `Mayan languages`\n\n // Erzya\n case \"myv\":\n\t\tc.Body = `Erzya`\n\n // Collective name\n case \"nah\":\n\t\tc.Body = `Nahuatl languages`\n\n // Collective name\n case \"nai\":\n\t\tc.Body = `North American Indian languages`\n\n // Neapolitan\n case \"nap\":\n\t\tc.Body = `Neapolitan`\n\n // Nauruan\n case \"nau\":\n\t\tc.Body = `Nauruan`\n\n // Navajo\n case \"nav\":\n\t\tc.Body = `Navajo`\n\n // Ndebele, South\n case \"nbl\":\n\t\tc.Body = `Ndebele, South`\n\n // Ndebele, North\n case \"nde\":\n\t\tc.Body = `Ndebele, North`\n\n // Ndonga\n case \"ndo\":\n\t\tc.Body = `Ndonga`\n\n // Low German; Low Saxon\n case \"nds\":\n\t\tc.Body = `Low German; Low Saxon`\n\n // Macrolanguage\n case \"nep\":\n\t\tc.Body = `Nepali`\n\n // Newari; Nepal Bhasa\n case \"new\":\n\t\tc.Body = `Newari; Nepal Bhasa`\n\n // Nias\n case \"nia\":\n\t\tc.Body = `Nias`\n\n // Collective name\n case \"nic\":\n\t\tc.Body = `Niger-Kordofanian languages`\n\n // Niuean\n case \"niu\":\n\t\tc.Body = `Niuean`\n\n // Norwegian Nynorsk\n case \"nno\":\n\t\tc.Body = `Norwegian Nynorsk`\n\n // Norwegian Bokmål\n case \"nob\":\n\t\tc.Body = `Norwegian Bokmål`\n\n // Nogai\n case \"nog\":\n\t\tc.Body = `Nogai`\n\n // Old Norse\n case \"non\":\n\t\tc.Body = `Old Norse`\n\n // Macrolanguage\n case \"nor\":\n\t\tc.Body = `Norwegian`\n\n // N’Ko\n case \"nqo\":\n\t\tc.Body = `N’Ko`\n\n // ONIX local code, equivalent to nrf in ISO 639-3. For use in ONIX 3.0 only\n case \"nrf\":\n\t\tc.Body = `Guernésiais, Jèrriais`\n\n // Pedi; Sepedi; Northern Sotho\n case \"nso\":\n\t\tc.Body = `Pedi; Sepedi; Northern Sotho`\n\n // Collective name\n case \"nub\":\n\t\tc.Body = `Nubian languages`\n\n // Classical Newari; Old Newari; Classical Nepal Bhasa\n case \"nwc\":\n\t\tc.Body = `Classical Newari; Old Newari; Classical Nepal Bhasa`\n\n // Chichewa; Chewa; Nyanja\n case \"nya\":\n\t\tc.Body = `Chichewa; Chewa; Nyanja`\n\n // Nyamwezi\n case \"nym\":\n\t\tc.Body = `Nyamwezi`\n\n // Nyankole\n case \"nyn\":\n\t\tc.Body = `Nyankole`\n\n // Nyoro\n case \"nyo\":\n\t\tc.Body = `Nyoro`\n\n // Nzima\n case \"nzi\":\n\t\tc.Body = `Nzima`\n\n // Occitan (post 1500)\n case \"oci\":\n\t\tc.Body = `Occitan (post 1500)`\n\n // ONIX local code, equivalent to odt in ISO 639-3\n case \"odt\":\n\t\tc.Body = `Old Dutch / Old Low Franconian (ca. 400–1050)`\n\n // Macrolanguage\n case \"oji\":\n\t\tc.Body = `Ojibwa`\n\n // ONIX local code, equivalent to omq in ISO 639-5. Collective name\n case \"omq\":\n\t\tc.Body = `Oto-Manguean languages`\n\n // Macrolanguage\n case \"ori\":\n\t\tc.Body = `Oriya`\n\n // Macrolanguage\n case \"orm\":\n\t\tc.Body = `Oromo`\n\n // Osage\n case \"osa\":\n\t\tc.Body = `Osage`\n\n // Ossetian; Ossetic\n case \"oss\":\n\t\tc.Body = `Ossetian; Ossetic`\n\n // Turkish, Ottoman\n case \"ota\":\n\t\tc.Body = `Turkish, Ottoman`\n\n // Collective name\n case \"oto\":\n\t\tc.Body = `Otomian languages`\n\n // Collective name\n case \"paa\":\n\t\tc.Body = `Papuan languages`\n\n // Pangasinan\n case \"pag\":\n\t\tc.Body = `Pangasinan`\n\n // Pahlavi\n case \"pal\":\n\t\tc.Body = `Pahlavi`\n\n // Pampanga; Kapampangan\n case \"pam\":\n\t\tc.Body = `Pampanga; Kapampangan`\n\n // Panjabi\n case \"pan\":\n\t\tc.Body = `Panjabi`\n\n // Papiamento\n case \"pap\":\n\t\tc.Body = `Papiamento`\n\n // Palauan\n case \"pau\":\n\t\tc.Body = `Palauan`\n\n // Old Persian (ca. 600-400 B.C.)\n case \"peo\":\n\t\tc.Body = `Old Persian (ca. 600-400 B.C.)`\n\n // Macrolanguage\n case \"per\":\n\t\tc.Body = `Persian; Farsi`\n\n // ONIX local code, equivalent to pes in ISO 639-3. For use in ONIX 3.0 only\n case \"pes\":\n\t\tc.Body = `Iranian Persian; Parsi`\n\n // Collective name\n case \"phi\":\n\t\tc.Body = `Philippine languages`\n\n // Phoenician\n case \"phn\":\n\t\tc.Body = `Phoenician`\n\n // Pali\n case \"pli\":\n\t\tc.Body = `Pali`\n\n // ONIX local code for Italian dialect, equivalent to pms in ISO 639-3. For use in ONIX 3.0 only\n case \"pms\":\n\t\tc.Body = `Piedmontese`\n\n // Polish\n case \"pol\":\n\t\tc.Body = `Polish`\n\n // Ponapeian\n case \"pon\":\n\t\tc.Body = `Ponapeian`\n\n // Portuguese\n case \"por\":\n\t\tc.Body = `Portuguese`\n\n // Collective name\n case \"pra\":\n\t\tc.Body = `Prakrit languages`\n\n // Provençal, Old (to 1500); Occitan, Old (to 1500)\n case \"pro\":\n\t\tc.Body = `Provençal, Old (to 1500); Occitan, Old (to 1500)`\n\n // ONIX local code, equivalent to prs in ISO 639-3. For use in ONIX 3.0 only\n case \"prs\":\n\t\tc.Body = `Dari; Afghan Persian`\n\n // Macrolanguage\n case \"pus\":\n\t\tc.Body = `Pushto; Pashto`\n\n // ONIX local code, distinct dialect of Occitan (not distinguished from oci by ISO 639-3)\n case \"qar\":\n\t\tc.Body = `Aranés`\n\n // ONIX local code, distinct dialect of Catalan (not distinguished from cat by ISO 639-3)\n case \"qav\":\n\t\tc.Body = `Valencian`\n\n // ONIX local code, distinct variant of langue d’oïl (old northern French) (not distinguished from fro, or from frm, fre, nrf by ISO 639-3). For use in ONIX 3.0 only\n case \"qgl\":\n\t\tc.Body = `Gallo`\n\n // ONIX local code, distinct dialect of of Rusyn (not distinguished from rue by ISO 639-3). For use in ONIX 3.0 only\n case \"qlk\":\n\t\tc.Body = `Lemko`\n\n // ONIX local code, distinct and exclusively spoken variation of Spanish, not distinguished from spa (Spanish, Castilian) by ISO 639-3. Neutral Latin American Spanish should be considered a ‘shorthand’ for spa plus a ‘country code’ for Latin America – but prefer spa plus the relevant country code for specifically Mexican Spanish, Argentine (Rioplatense) Spanish, Puerto Rican Spanish etc. Neutral Latin American Spanish must only be used with audio material (including the audio tracks of TV, video and film) to indicate use of accent, vocabulary and construction suitable for broad use across Latin America. For use in ONIX 3.0 only\n case \"qls\":\n\t\tc.Body = `Neutral Latin American Spanish`\n\n // Macrolanguage\n case \"que\":\n\t\tc.Body = `Quechua`\n\n // Macrolanguage\n case \"raj\":\n\t\tc.Body = `Rajasthani`\n\n // Rapanui\n case \"rap\":\n\t\tc.Body = `Rapanui`\n\n // Rarotongan; Cook Islands Maori\n case \"rar\":\n\t\tc.Body = `Rarotongan; Cook Islands Maori`\n\n // ONIX local code, equivalent to rcf in ISO 639-3. For use in ONIX 3.0 only\n case \"rcf\":\n\t\tc.Body = `Réunion Creole French`\n\n // ONIX local code for Italian dialect, equivalent to rgl in ISO 639-3. For use in ONIX 3.0 only\n case \"rgn\":\n\t\tc.Body = `Romagnol`\n\n // Collective name\n case \"roa\":\n\t\tc.Body = `Romance languages`\n\n // Romansh\n case \"roh\":\n\t\tc.Body = `Romansh`\n\n // Macrolanguage\n case \"rom\":\n\t\tc.Body = `Romany`\n\n // Romanian\n case \"rum\":\n\t\tc.Body = `Romanian`\n\n // Rundi\n case \"run\":\n\t\tc.Body = `Rundi`\n\n // Aromanian; Arumanian; Macedo-Romanian\n case \"rup\":\n\t\tc.Body = `Aromanian; Arumanian; Macedo-Romanian`\n\n // Russian\n case \"rus\":\n\t\tc.Body = `Russian`\n\n // Sandawe\n case \"sad\":\n\t\tc.Body = `Sandawe`\n\n // Sango\n case \"sag\":\n\t\tc.Body = `Sango`\n\n // Yakut\n case \"sah\":\n\t\tc.Body = `Yakut`\n\n // Collective name\n case \"sai\":\n\t\tc.Body = `South American Indian languages`\n\n // Collective name\n case \"sal\":\n\t\tc.Body = `Salishan languages`\n\n // Samaritan Aramaic\n case \"sam\":\n\t\tc.Body = `Samaritan Aramaic`\n\n // Sanskrit\n case \"san\":\n\t\tc.Body = `Sanskrit`\n\n // Sasak\n case \"sas\":\n\t\tc.Body = `Sasak`\n\n // Santali\n case \"sat\":\n\t\tc.Body = `Santali`\n\n // DEPRECATED – use srp\n case \"scc\":\n\t\tc.Body = `Serbian`\n\n // Sicilian\n case \"scn\":\n\t\tc.Body = `Sicilian`\n\n // Scots\n case \"sco\":\n\t\tc.Body = `Scots`\n\n // DEPRECATED – use hrv\n case \"scr\":\n\t\tc.Body = `Croatian`\n\n // ONIX local code for Sardinian dialect, equivalent to sdc in ISO 639-3. For use in ONIX 3.0 only\n case \"sdc\":\n\t\tc.Body = `Sassarese`\n\n // ONIX local code for Sardinian dialect, equivalent to sdn in ISO 639-3. For use in ONIX 3.0 only\n case \"sdn\":\n\t\tc.Body = `Gallurese`\n\n // Selkup\n case \"sel\":\n\t\tc.Body = `Selkup`\n\n // Collective name\n case \"sem\":\n\t\tc.Body = `Semitic languages`\n\n // Irish, Old (to 1100)\n case \"sga\":\n\t\tc.Body = `Irish, Old (to 1100)`\n\n // Collective name\n case \"sgn\":\n\t\tc.Body = `Sign languages`\n\n // Shan\n case \"shn\":\n\t\tc.Body = `Shan`\n\n // Sidamo\n case \"sid\":\n\t\tc.Body = `Sidamo`\n\n // Sinhala; Sinhalese\n case \"sin\":\n\t\tc.Body = `Sinhala; Sinhalese`\n\n // Collective name\n case \"sio\":\n\t\tc.Body = `Siouan languages`\n\n // Collective name\n case \"sit\":\n\t\tc.Body = `Sino-Tibetan languages`\n\n // Collective name\n case \"sla\":\n\t\tc.Body = `Slavic languages`\n\n // Slovak\n case \"slo\":\n\t\tc.Body = `Slovak`\n\n // Slovenian\n case \"slv\":\n\t\tc.Body = `Slovenian`\n\n // Southern Sami\n case \"sma\":\n\t\tc.Body = `Southern Sami`\n\n // Northern Sami\n case \"sme\":\n\t\tc.Body = `Northern Sami`\n\n // Collective name\n case \"smi\":\n\t\tc.Body = `Sami languages`\n\n // Lule Sami\n case \"smj\":\n\t\tc.Body = `Lule Sami`\n\n // Inari Sami\n case \"smn\":\n\t\tc.Body = `Inari Sami`\n\n // Samoan\n case \"smo\":\n\t\tc.Body = `Samoan`\n\n // Skolt Sami\n case \"sms\":\n\t\tc.Body = `Skolt Sami`\n\n // Shona\n case \"sna\":\n\t\tc.Body = `Shona`\n\n // Sindhi\n case \"snd\":\n\t\tc.Body = `Sindhi`\n\n // Soninke\n case \"snk\":\n\t\tc.Body = `Soninke`\n\n // Sogdian\n case \"sog\":\n\t\tc.Body = `Sogdian`\n\n // Somali\n case \"som\":\n\t\tc.Body = `Somali`\n\n // Collective name\n case \"son\":\n\t\tc.Body = `Songhai languages`\n\n // Sotho; Sesotho\n case \"sot\":\n\t\tc.Body = `Sotho; Sesotho`\n\n // Spanish\n case \"spa\":\n\t\tc.Body = `Spanish`\n\n // Macrolanguage\n case \"srd\":\n\t\tc.Body = `Sardinian`\n\n // Sranan Tongo\n case \"srn\":\n\t\tc.Body = `Sranan Tongo`\n\n // ONIX local code for Sardinian dialect, equivalent to sro in ISO 639-3. For use in ONIX 3.0 only\n case \"sro\":\n\t\tc.Body = `Campidanese`\n\n // Serbian\n case \"srp\":\n\t\tc.Body = `Serbian`\n\n // Serer\n case \"srr\":\n\t\tc.Body = `Serer`\n\n // Collective name\n case \"ssa\":\n\t\tc.Body = `Nilo-Saharan languages`\n\n // Swazi; Swati\n case \"ssw\":\n\t\tc.Body = `Swazi; Swati`\n\n // Sukuma\n case \"suk\":\n\t\tc.Body = `Sukuma`\n\n // Sundanese\n case \"sun\":\n\t\tc.Body = `Sundanese`\n\n // Susu\n case \"sus\":\n\t\tc.Body = `Susu`\n\n // Sumerian\n case \"sux\":\n\t\tc.Body = `Sumerian`\n\n // Macrolanguage\n case \"swa\":\n\t\tc.Body = `Swahili`\n\n // Swedish\n case \"swe\":\n\t\tc.Body = `Swedish`\n\n // Classical Syriac\n case \"syc\":\n\t\tc.Body = `Classical Syriac`\n\n // Macrolanguage\n case \"syr\":\n\t\tc.Body = `Syriac`\n\n // Tahitian\n case \"tah\":\n\t\tc.Body = `Tahitian`\n\n // Collective name\n case \"tai\":\n\t\tc.Body = `Tai languages`\n\n // Tamil\n case \"tam\":\n\t\tc.Body = `Tamil`\n\n // Tatar\n case \"tat\":\n\t\tc.Body = `Tatar`\n\n // Telugu\n case \"tel\":\n\t\tc.Body = `Telugu`\n\n // Temne; Time\n case \"tem\":\n\t\tc.Body = `Temne; Time`\n\n // Terena\n case \"ter\":\n\t\tc.Body = `Terena`\n\n // Tetum\n case \"tet\":\n\t\tc.Body = `Tetum`\n\n // Tajik; Tajiki Persian\n case \"tgk\":\n\t\tc.Body = `Tajik; Tajiki Persian`\n\n // Tagalog\n case \"tgl\":\n\t\tc.Body = `Tagalog`\n\n // Thai\n case \"tha\":\n\t\tc.Body = `Thai`\n\n // Tibetan\n case \"tib\":\n\t\tc.Body = `Tibetan`\n\n // Tigré\n case \"tig\":\n\t\tc.Body = `Tigré`\n\n // Tigrinya\n case \"tir\":\n\t\tc.Body = `Tigrinya`\n\n // Tiv\n case \"tiv\":\n\t\tc.Body = `Tiv`\n\n // Tokelauan\n case \"tkl\":\n\t\tc.Body = `Tokelauan`\n\n // Artificial language\n case \"tlh\":\n\t\tc.Body = `Klingon; tlhIngan-Hol`\n\n // Tlingit\n case \"tli\":\n\t\tc.Body = `Tlingit`\n\n // Macrolanguage\n case \"tmh\":\n\t\tc.Body = `Tamashek`\n\n // Tonga (Nyasa)\n case \"tog\":\n\t\tc.Body = `Tonga (Nyasa)`\n\n // Tongan\n case \"ton\":\n\t\tc.Body = `Tongan`\n\n // Tok Pisin\n case \"tpi\":\n\t\tc.Body = `Tok Pisin`\n\n // Tsimshian\n case \"tsi\":\n\t\tc.Body = `Tsimshian`\n\n // AKA Setswana\n case \"tsn\":\n\t\tc.Body = `Tswana`\n\n // Tsonga\n case \"tso\":\n\t\tc.Body = `Tsonga`\n\n // Turkmen\n case \"tuk\":\n\t\tc.Body = `Turkmen`\n\n // Tumbuka\n case \"tum\":\n\t\tc.Body = `Tumbuka`\n\n // Collective name\n case \"tup\":\n\t\tc.Body = `Tupi languages`\n\n // Turkish\n case \"tur\":\n\t\tc.Body = `Turkish`\n\n // Altaic languages\n case \"tut\":\n\t\tc.Body = `Altaic languages`\n\n // Tuvaluan\n case \"tvl\":\n\t\tc.Body = `Tuvaluan`\n\n // Twi\n case \"twi\":\n\t\tc.Body = `Twi`\n\n // Tuvinian\n case \"tyv\":\n\t\tc.Body = `Tuvinian`\n\n // ONIX local code, equivalent to tzo in ISO 639-3\n case \"tzo\":\n\t\tc.Body = `Tzotzil`\n\n // Udmurt\n case \"udm\":\n\t\tc.Body = `Udmurt`\n\n // Ugaritic\n case \"uga\":\n\t\tc.Body = `Ugaritic`\n\n // Uighur; Uyghur\n case \"uig\":\n\t\tc.Body = `Uighur; Uyghur`\n\n // Ukrainian\n case \"ukr\":\n\t\tc.Body = `Ukrainian`\n\n // Umbundu\n case \"umb\":\n\t\tc.Body = `Umbundu`\n\n // Undetermined language\n case \"und\":\n\t\tc.Body = `Undetermined language`\n\n // Urdu\n case \"urd\":\n\t\tc.Body = `Urdu`\n\n // Macrolanguage\n case \"uzb\":\n\t\tc.Body = `Uzbek`\n\n // Vai\n case \"vai\":\n\t\tc.Body = `Vai`\n\n // ONIX local code for Italian dialect, equivalent to vec in ISO 639-3. For use in ONIX 3.0 only\n case \"vec\":\n\t\tc.Body = `Venetian/Venetan`\n\n // Venda\n case \"ven\":\n\t\tc.Body = `Venda`\n\n // Vietnamese\n case \"vie\":\n\t\tc.Body = `Vietnamese`\n\n // Artificial language\n case \"vol\":\n\t\tc.Body = `Volapük`\n\n // Votic\n case \"vot\":\n\t\tc.Body = `Votic`\n\n // Collective name\n case \"wak\":\n\t\tc.Body = `Wakashan languages`\n\n // Wolaitta; Wolaytta\n case \"wal\":\n\t\tc.Body = `Wolaitta; Wolaytta`\n\n // Waray\n case \"war\":\n\t\tc.Body = `Waray`\n\n // Washo\n case \"was\":\n\t\tc.Body = `Washo`\n\n // Welsh\n case \"wel\":\n\t\tc.Body = `Welsh`\n\n // Collective name\n case \"wen\":\n\t\tc.Body = `Sorbian languages`\n\n // Walloon\n case \"wln\":\n\t\tc.Body = `Walloon`\n\n // Wolof\n case \"wol\":\n\t\tc.Body = `Wolof`\n\n // Kalmyk\n case \"xal\":\n\t\tc.Body = `Kalmyk`\n\n // Xhosa\n case \"xho\":\n\t\tc.Body = `Xhosa`\n\n // ONIX local code, equivalent to xuu in ISO 639-3. For use in ONIX 3.0 only\n case \"xuu\":\n\t\tc.Body = `Khwedam, Kxoe`\n\n // Yao\n case \"yao\":\n\t\tc.Body = `Yao`\n\n // Yapese\n case \"yap\":\n\t\tc.Body = `Yapese`\n\n // Macrolanguage\n case \"yid\":\n\t\tc.Body = `Yiddish`\n\n // Yoruba\n case \"yor\":\n\t\tc.Body = `Yoruba`\n\n // Collective name\n case \"ypk\":\n\t\tc.Body = `Yupik languages`\n\n // ONIX local code, equivalent to yue in ISO 639-3\n case \"yue\":\n\t\tc.Body = `Cantonese`\n\n // Macrolanguage\n case \"zap\":\n\t\tc.Body = `Zapotec`\n\n // Artificial language\n case \"zbl\":\n\t\tc.Body = `Blissymbols; Blissymbolics; Bliss`\n\n // Zenaga\n case \"zen\":\n\t\tc.Body = `Zenaga`\n\n // Standard Moroccan Tamazight\n case \"zgh\":\n\t\tc.Body = `Standard Moroccan Tamazight`\n\n // Macrolanguage\n case \"zha\":\n\t\tc.Body = `Zhuang; Chuang`\n\n // Collective name\n case \"znd\":\n\t\tc.Body = `Zande languages`\n\n // Zulu\n case \"zul\":\n\t\tc.Body = `Zulu`\n\n // Zuni\n case \"zun\":\n\t\tc.Body = `Zuni`\n\n // No linguistic content\n case \"zxx\":\n\t\tc.Body = `No linguistic content`\n\n // Macrolanguage\n case \"zza\":\n\t\tc.Body = `Zaza; Dimili; Dimli; Kirdki; Kirmanjki; Zazaki`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for FromLanguage has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *ProductContentType) 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 // Readable text of the main work: this value is required, together with applicable <ProductForm> and <ProductFormDetail> values, to designate an e-book or other digital or physical product whose primary content is eye-readable text\n case \"10\":\n\t\tc.Body = `Text (eye-readable)`\n\n // E-publication contains a significant number of actionable cross-references, hyperlinked notes and annotations, or with other actionable links between largely textual elements (eg quiz/test questions, ‘choose your own ending’ etc)\n case \"15\":\n\t\tc.Body = `Extensive links between internal content`\n\n // E-publication contains a significant number of actionable (clickable) web links\n case \"14\":\n\t\tc.Body = `Extensive links to external content`\n\n // Publication contains additional textual content such as interview, feature article, essay, bibliography, quiz/test, other background material or text that is not included in a primary or ‘unenhanced’ version\n case \"16\":\n\t\tc.Body = `Additional eye-readable text not part of main work`\n\n // Publication contains a significant number of web links (printed URLs, QR codes etc). For use in ONIX 3.0 only\n case \"41\":\n\t\tc.Body = `Additional eye-readable links to external content`\n\n // eg Teaser chapter\n case \"17\":\n\t\tc.Body = `Promotional text for other book product`\n\n // Musical notation\n case \"11\":\n\t\tc.Body = `Musical notation`\n\n // Use only when no more detailed specification is provided\n case \"07\":\n\t\tc.Body = `Still images / graphics`\n\n // Whether in a plate section / insert, or not\n case \"18\":\n\t\tc.Body = `Photographs`\n\n // Including other ‘mechanical’ (ie non-photographic) illustrations\n case \"19\":\n\t\tc.Body = `Figures, diagrams, charts, graphs`\n\n // Publication is enhanced with additional images or graphical content such as supplementary photographs that are not included in a primary or ‘unenhanced’ version\n case \"20\":\n\t\tc.Body = `Additional images / graphics not part of main work`\n\n // Maps and/or other cartographic content\n case \"12\":\n\t\tc.Body = `Maps and/or other cartographic content`\n\n // eg Questions or student exercises, problems, quizzes or tests (as an integral part of the work). For use in ONIX 3.0 only\n case \"42\":\n\t\tc.Body = `Assessment material`\n\n // Audio recording of a reading of a book or other text\n case \"01\":\n\t\tc.Body = `Audiobook`\n\n // Audio recording of a drama or other spoken word performance\n case \"02\":\n\t\tc.Body = `Performance – spoken word`\n\n // eg an interview, speech, lecture or discussion, not a ‘reading’ or ‘performance’)\n case \"13\":\n\t\tc.Body = `Other speech content`\n\n // Audio recording of a music performance, including musical drama and opera\n case \"03\":\n\t\tc.Body = `Music recording`\n\n // Audio recording of other sound, eg birdsong\n case \"04\":\n\t\tc.Body = `Other audio`\n\n // Audio recording of a reading, performance or dramatization of part of the work\n case \"21\":\n\t\tc.Body = `Partial performance – spoken word`\n\n // Product is enhanced with audio recording of full or partial reading, performance, dramatization, interview, background documentary or other audio content not included in the primary or ‘unenhanced’ version\n case \"22\":\n\t\tc.Body = `Additional audio content not part of main work`\n\n // eg Reading of teaser chapter\n case \"23\":\n\t\tc.Body = `Promotional audio for other book product`\n\n // Includes Film, video, animation etc. Use only when no more detailed specification is provided. Formerly ‘Moving images’\n case \"06\":\n\t\tc.Body = `Video`\n\n // Video recording of a reading\n case \"26\":\n\t\tc.Body = `Video recording of a reading`\n\n // Video recording of a drama or other performance, including musical performance\n case \"27\":\n\t\tc.Body = `Performance – visual`\n\n // eg animated diagrams, charts, graphs or other illustrations\n case \"24\":\n\t\tc.Body = `Animated / interactive illustrations`\n\n // eg cartoon, animatic or CGI animation\n case \"25\":\n\t\tc.Body = `Narrative animation`\n\n // Other video content eg interview, not a reading or performance\n case \"28\":\n\t\tc.Body = `Other video`\n\n // Video recording of a reading, performance or dramatization of part of the work\n case \"29\":\n\t\tc.Body = `Partial performance – video`\n\n // E-publication is enhanced with video recording of full or partial reading, performance, dramatization, interview, background documentary or other content not included in the primary or ‘unenhanced’ version\n case \"30\":\n\t\tc.Body = `Additional video content not part of main work`\n\n // eg Book trailer\n case \"31\":\n\t\tc.Body = `Promotional video for other book product`\n\n // No multi-user functionality. Formerly just ‘Game’\n case \"05\":\n\t\tc.Body = `Game / Puzzle`\n\n // Includes some degree of multi-user functionality\n case \"32\":\n\t\tc.Body = `Contest`\n\n // Largely ‘content free’\n case \"08\":\n\t\tc.Body = `Software`\n\n // Data files\n case \"09\":\n\t\tc.Body = `Data`\n\n // Data set plus software\n case \"33\":\n\t\tc.Body = `Data set plus software`\n\n // Entire pages or blank spaces, forms, boxes etc, intended to be filled in by the reader\n case \"34\":\n\t\tc.Body = `Blank pages or spaces`\n\n // Use only where type of advertising content is not stated\n case \"35\":\n\t\tc.Body = `Advertising content`\n\n // ‘Back ads’ – promotional pages for other books (that do not include sample content, cf codes 17, 23)\n case \"37\":\n\t\tc.Body = `Advertising – first party`\n\n // Eg to obtain discounts on other products\n case \"36\":\n\t\tc.Body = `Advertising – coupons`\n\n // Advertising – third party display\n case \"38\":\n\t\tc.Body = `Advertising – third party display`\n\n // Advertising – third party textual\n case \"39\":\n\t\tc.Body = `Advertising – third party textual`\n\n // E-publication contains microprograms written (eg) in Javascript and executed within the reading system. For use in ONIX 3.0 only\n case \"40\":\n\t\tc.Body = `Scripting`\n\n // E-publication contains pop-ups or other functionality offering (eg) term definitions, cross-links or glossary entries [Note this should not include (eg) dictionary funcionality that is part of the reading system.] For use in ONIX 3.0 only\n case \"43\":\n\t\tc.Body = `Scripted pop-ups`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for ProductContentType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *TitleType) 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 // Undefined\n case \"00\":\n\t\tc.Body = `Undefined`\n\n // The full text of the distinctive title of the item, without abbreviation or abridgement. For books, where the title alone is not distinctive, elements may be taken from a set or series title and part number etc to create a distinctive title. Where the item is an omnibus edition containing two or more works by the same author, and there is no separate combined title, a distinctive title may be constructed by concatenating the individual titles, with suitable punctuation, as in ‘Pride and prejudice / Sense and sensibility / Northanger Abbey’\n case \"01\":\n\t\tc.Body = `Distinctive title (book); Cover title (serial); Title on item (serial content item or reviewed resource)`\n\n // Serials only\n case \"02\":\n\t\tc.Body = `ISSN key title of serial`\n\n // Where the subject of the ONIX record is a translated item\n case \"03\":\n\t\tc.Body = `Title in original language`\n\n // For serials: an acronym or initialism of Title Type 01, eg ‘JAMA’, ‘JACM’\n case \"04\":\n\t\tc.Body = `Title acronym or initialism`\n\n // An abbreviated form of Title Type 01\n case \"05\":\n\t\tc.Body = `Abbreviated title`\n\n // A translation of Title Type 01 into another language\n case \"06\":\n\t\tc.Body = `Title in other language`\n\n // Serials only: when a journal issue is explicitly devoted to a specified topic\n case \"07\":\n\t\tc.Body = `Thematic title of journal issue`\n\n // Books or serials: when an item was previously published under another title\n case \"08\":\n\t\tc.Body = `Former title`\n\n // For books: the title carried in a book distributor’s title file: frequently incomplete, and may include elements not properly part of the title\n case \"10\":\n\t\tc.Body = `Distributor’s title`\n\n // An alternative title that appears on the cover of a book\n case \"11\":\n\t\tc.Body = `Alternative title on cover`\n\n // An alternative title that appears on the back of a book\n case \"12\":\n\t\tc.Body = `Alternative title on back`\n\n // An expanded form of the title, eg the title of a school text book with grade and type and other details added to make the title meaningful, where otherwise it would comprise only the curriculum subject. This title type is required for submissions to the Spanish ISBN Agency\n case \"13\":\n\t\tc.Body = `Expanded title`\n\n // An alternative title that the book is widely known by, whether it appears on the book or not\n case \"14\":\n\t\tc.Body = `Alternative title`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for TitleType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func XML() (ret httprpc.Codec) {\n\treturn Danger(\n\t\tfunc(w io.Writer) DangerEncoder {\n\t\t\treturn xml.NewEncoder(w)\n\t\t},\n\t\tfunc(r io.Reader) DangerDecoder {\n\t\t\treturn xml.NewDecoder(r)\n\t\t},\n\t)\n}", "func (c *XHTMLContentType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for XHTMLContentType has been passed, got [%s]\", v)\n\t}\n}", "func (c *DateFormat) 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 // Common Era year, month and day (default for most dates)\n case \"00\":\n\t\tc.Body = `YYYYMMDD`\n\n // Year and month\n case \"01\":\n\t\tc.Body = `YYYYMM`\n\n // Year and week number\n case \"02\":\n\t\tc.Body = `YYYYWW`\n\n // Year and quarter (Q = 1, 2, 3, 4, with 1 = Jan to Mar)\n case \"03\":\n\t\tc.Body = `YYYYQ`\n\n // Year and season (S = 1, 2, 3, 4, with 1 = ‘Spring’)\n case \"04\":\n\t\tc.Body = `YYYYS`\n\n // Year (default for some dates)\n case \"05\":\n\t\tc.Body = `YYYY`\n\n // Spread of exact dates\n case \"06\":\n\t\tc.Body = `YYYYMMDDYYYYMMDD`\n\n // Spread of months\n case \"07\":\n\t\tc.Body = `YYYYMMYYYYMM`\n\n // Spread of week numbers\n case \"08\":\n\t\tc.Body = `YYYYWWYYYYWW`\n\n // Spread of quarters\n case \"09\":\n\t\tc.Body = `YYYYQYYYYQ`\n\n // Spread of seasons\n case \"10\":\n\t\tc.Body = `YYYYSYYYYS`\n\n // Spread of years\n case \"11\":\n\t\tc.Body = `YYYYYYYY`\n\n // For complex, approximate or uncertain dates, or dates BCE\n case \"12\":\n\t\tc.Body = `Text string`\n\n // Exact time. Use ONLY when exact times with hour/minute precision are relevant. By default, time is local. Alternatively, the time may be suffixed with an optional ‘Z’ for UTC times, or with ‘+’ or ‘-’ and an hhmm timezone offset from UTC. Times without a timezone are ‘rolling’ local times, times qualified with a timezone (using Z, + or -) specify a particular instant in time\n case \"13\":\n\t\tc.Body = `YYYYMMDDThhmm`\n\n // Exact time. Use ONLY when exact times with second precision are relevant. By default, time is local. Alternatively, the time may be suffixed with an optional ‘Z’ for UTC times, or with ‘+’ or ‘-’ and an hhmm timezone offset from UTC. Times without a timezone are ‘rolling’ local times, times qualified with a timezone (using Z, + or -) specify a particular instant in time\n case \"14\":\n\t\tc.Body = `YYYYMMDDThhmmss`\n\n // Year month day (Hijri calendar)\n case \"20\":\n\t\tc.Body = `YYYYMMDD (H)`\n\n // Year and month (Hijri calendar)\n case \"21\":\n\t\tc.Body = `YYYYMM (H)`\n\n // Year (Hijri calendar)\n case \"25\":\n\t\tc.Body = `YYYY (H)`\n\n // For complex, approximate or uncertain dates (Hijri calendar), text would usually be in Arabic script\n case \"32\":\n\t\tc.Body = `Text string (H)`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for DateFormat has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (*XMLDocument) SetCharset(charset string) {\n\tmacro.Rewrite(\"$_.charset = $1\", charset)\n}", "func (c *XHTMLLanguageCode) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for XHTMLLanguageCode has been passed, got [%s]\", v)\n\t}\n}", "func (c *PrizeCountry) 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\tcodes := strings.Split(v, \" \")\n\ttmpeCodes := []string{}\n\tfor _, code := range codes {\n\t\tswitch code {\n\n\t\t// Andorra\n\t\tcase \"AD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Andorra`)\n\n\t\t// United Arab Emirates\n\t\tcase \"AE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United Arab Emirates`)\n\n\t\t// Afghanistan\n\t\tcase \"AF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Afghanistan`)\n\n\t\t// Antigua and Barbuda\n\t\tcase \"AG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Antigua and Barbuda`)\n\n\t\t// Anguilla\n\t\tcase \"AI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Anguilla`)\n\n\t\t// Albania\n\t\tcase \"AL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Albania`)\n\n\t\t// Armenia\n\t\tcase \"AM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Armenia`)\n\n\t\t// Deprecated – use BQ, CW and SX as appropriate\n\t\tcase \"AN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Netherlands Antilles`)\n\n\t\t// Angola\n\t\tcase \"AO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Angola`)\n\n\t\t// Antarctica\n\t\tcase \"AQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Antarctica`)\n\n\t\t// Argentina\n\t\tcase \"AR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Argentina`)\n\n\t\t// American Samoa\n\t\tcase \"AS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `American Samoa`)\n\n\t\t// Austria\n\t\tcase \"AT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Austria`)\n\n\t\t// Australia\n\t\tcase \"AU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Australia`)\n\n\t\t// Aruba\n\t\tcase \"AW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Aruba`)\n\n\t\t// Åland Islands\n\t\tcase \"AX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Åland Islands`)\n\n\t\t// Azerbaijan\n\t\tcase \"AZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Azerbaijan`)\n\n\t\t// Bosnia and Herzegovina\n\t\tcase \"BA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bosnia and Herzegovina`)\n\n\t\t// Barbados\n\t\tcase \"BB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Barbados`)\n\n\t\t// Bangladesh\n\t\tcase \"BD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bangladesh`)\n\n\t\t// Belgium\n\t\tcase \"BE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belgium`)\n\n\t\t// Burkina Faso\n\t\tcase \"BF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Burkina Faso`)\n\n\t\t// Bulgaria\n\t\tcase \"BG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bulgaria`)\n\n\t\t// Bahrain\n\t\tcase \"BH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bahrain`)\n\n\t\t// Burundi\n\t\tcase \"BI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Burundi`)\n\n\t\t// Benin\n\t\tcase \"BJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Benin`)\n\n\t\t// Saint Barthélemy\n\t\tcase \"BL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Barthélemy`)\n\n\t\t// Bermuda\n\t\tcase \"BM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bermuda`)\n\n\t\t// Brunei Darussalam\n\t\tcase \"BN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Brunei Darussalam`)\n\n\t\t// Bolivia, Plurinational State of\n\t\tcase \"BO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bolivia, Plurinational State of`)\n\n\t\t// Bonaire, Sint Eustatius and Saba\n\t\tcase \"BQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bonaire, Sint Eustatius and Saba`)\n\n\t\t// Brazil\n\t\tcase \"BR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Brazil`)\n\n\t\t// Bahamas\n\t\tcase \"BS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bahamas`)\n\n\t\t// Bhutan\n\t\tcase \"BT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bhutan`)\n\n\t\t// Bouvet Island\n\t\tcase \"BV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Bouvet Island`)\n\n\t\t// Botswana\n\t\tcase \"BW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Botswana`)\n\n\t\t// Belarus\n\t\tcase \"BY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belarus`)\n\n\t\t// Belize\n\t\tcase \"BZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Belize`)\n\n\t\t// Canada\n\t\tcase \"CA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Canada`)\n\n\t\t// Cocos (Keeling) Islands\n\t\tcase \"CC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cocos (Keeling) Islands`)\n\n\t\t// Congo, Democratic Republic of the\n\t\tcase \"CD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Congo, Democratic Republic of the`)\n\n\t\t// Central African Republic\n\t\tcase \"CF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Central African Republic`)\n\n\t\t// Congo\n\t\tcase \"CG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Congo`)\n\n\t\t// Switzerland\n\t\tcase \"CH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Switzerland`)\n\n\t\t// Cote d’Ivoire\n\t\tcase \"CI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cote d’Ivoire`)\n\n\t\t// Cook Islands\n\t\tcase \"CK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cook Islands`)\n\n\t\t// Chile\n\t\tcase \"CL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Chile`)\n\n\t\t// Cameroon\n\t\tcase \"CM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cameroon`)\n\n\t\t// China\n\t\tcase \"CN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `China`)\n\n\t\t// Colombia\n\t\tcase \"CO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Colombia`)\n\n\t\t// Costa Rica\n\t\tcase \"CR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Costa Rica`)\n\n\t\t// DEPRECATED, replaced by ME – Montenegro and RS – Serbia\n\t\tcase \"CS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Serbia and Montenegro`)\n\n\t\t// Cuba\n\t\tcase \"CU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cuba`)\n\n\t\t// Cabo Verde\n\t\tcase \"CV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cabo Verde`)\n\n\t\t// Curaçao\n\t\tcase \"CW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Curaçao`)\n\n\t\t// Christmas Island\n\t\tcase \"CX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Christmas Island`)\n\n\t\t// Cyprus\n\t\tcase \"CY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cyprus`)\n\n\t\t// Formerly Czech Republic\n\t\tcase \"CZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Czechia`)\n\n\t\t// Germany\n\t\tcase \"DE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Germany`)\n\n\t\t// Djibouti\n\t\tcase \"DJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Djibouti`)\n\n\t\t// Denmark\n\t\tcase \"DK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Denmark`)\n\n\t\t// Dominica\n\t\tcase \"DM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Dominica`)\n\n\t\t// Dominican Republic\n\t\tcase \"DO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Dominican Republic`)\n\n\t\t// Algeria\n\t\tcase \"DZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Algeria`)\n\n\t\t// Ecuador\n\t\tcase \"EC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ecuador`)\n\n\t\t// Estonia\n\t\tcase \"EE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Estonia`)\n\n\t\t// Egypt\n\t\tcase \"EG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Egypt`)\n\n\t\t// Western Sahara\n\t\tcase \"EH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Western Sahara`)\n\n\t\t// Eritrea\n\t\tcase \"ER\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Eritrea`)\n\n\t\t// Spain\n\t\tcase \"ES\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Spain`)\n\n\t\t// Ethiopia\n\t\tcase \"ET\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ethiopia`)\n\n\t\t// Finland\n\t\tcase \"FI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Finland`)\n\n\t\t// Fiji\n\t\tcase \"FJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Fiji`)\n\n\t\t// Falkland Islands (Malvinas)\n\t\tcase \"FK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Falkland Islands (Malvinas)`)\n\n\t\t// Micronesia, Federated States of\n\t\tcase \"FM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Micronesia, Federated States of`)\n\n\t\t// Faroe Islands\n\t\tcase \"FO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Faroe Islands`)\n\n\t\t// France\n\t\tcase \"FR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `France`)\n\n\t\t// Gabon\n\t\tcase \"GA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gabon`)\n\n\t\t// United Kingdom\n\t\tcase \"GB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United Kingdom`)\n\n\t\t// Grenada\n\t\tcase \"GD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Grenada`)\n\n\t\t// Georgia\n\t\tcase \"GE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Georgia`)\n\n\t\t// French Guiana\n\t\tcase \"GF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Guiana`)\n\n\t\t// Guernsey\n\t\tcase \"GG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guernsey`)\n\n\t\t// Ghana\n\t\tcase \"GH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ghana`)\n\n\t\t// Gibraltar\n\t\tcase \"GI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gibraltar`)\n\n\t\t// Greenland\n\t\tcase \"GL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Greenland`)\n\n\t\t// Gambia\n\t\tcase \"GM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Gambia`)\n\n\t\t// Guinea\n\t\tcase \"GN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guinea`)\n\n\t\t// Guadeloupe\n\t\tcase \"GP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guadeloupe`)\n\n\t\t// Equatorial Guinea\n\t\tcase \"GQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Equatorial Guinea`)\n\n\t\t// Greece\n\t\tcase \"GR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Greece`)\n\n\t\t// South Georgia and the South Sandwich Islands\n\t\tcase \"GS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Georgia and the South Sandwich Islands`)\n\n\t\t// Guatemala\n\t\tcase \"GT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guatemala`)\n\n\t\t// Guam\n\t\tcase \"GU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guam`)\n\n\t\t// Guinea-Bissau\n\t\tcase \"GW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guinea-Bissau`)\n\n\t\t// Guyana\n\t\tcase \"GY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Guyana`)\n\n\t\t// Hong Kong\n\t\tcase \"HK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Hong Kong`)\n\n\t\t// Heard Island and McDonald Islands\n\t\tcase \"HM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Heard Island and McDonald Islands`)\n\n\t\t// Honduras\n\t\tcase \"HN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Honduras`)\n\n\t\t// Croatia\n\t\tcase \"HR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Croatia`)\n\n\t\t// Haiti\n\t\tcase \"HT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Haiti`)\n\n\t\t// Hungary\n\t\tcase \"HU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Hungary`)\n\n\t\t// Indonesia\n\t\tcase \"ID\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Indonesia`)\n\n\t\t// Ireland\n\t\tcase \"IE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ireland`)\n\n\t\t// Israel\n\t\tcase \"IL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Israel`)\n\n\t\t// Isle of Man\n\t\tcase \"IM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Isle of Man`)\n\n\t\t// India\n\t\tcase \"IN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `India`)\n\n\t\t// British Indian Ocean Territory\n\t\tcase \"IO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `British Indian Ocean Territory`)\n\n\t\t// Iraq\n\t\tcase \"IQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iraq`)\n\n\t\t// Iran, Islamic Republic of\n\t\tcase \"IR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iran, Islamic Republic of`)\n\n\t\t// Iceland\n\t\tcase \"IS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Iceland`)\n\n\t\t// Italy\n\t\tcase \"IT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Italy`)\n\n\t\t// Jersey\n\t\tcase \"JE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jersey`)\n\n\t\t// Jamaica\n\t\tcase \"JM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jamaica`)\n\n\t\t// Jordan\n\t\tcase \"JO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Jordan`)\n\n\t\t// Japan\n\t\tcase \"JP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Japan`)\n\n\t\t// Kenya\n\t\tcase \"KE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kenya`)\n\n\t\t// Kyrgyzstan\n\t\tcase \"KG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kyrgyzstan`)\n\n\t\t// Cambodia\n\t\tcase \"KH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cambodia`)\n\n\t\t// Kiribati\n\t\tcase \"KI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kiribati`)\n\n\t\t// Comoros\n\t\tcase \"KM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Comoros`)\n\n\t\t// Saint Kitts and Nevis\n\t\tcase \"KN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Kitts and Nevis`)\n\n\t\t// Korea, Democratic People’s Republic of\n\t\tcase \"KP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Korea, Democratic People’s Republic of`)\n\n\t\t// Korea, Republic of\n\t\tcase \"KR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Korea, Republic of`)\n\n\t\t// Kuwait\n\t\tcase \"KW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kuwait`)\n\n\t\t// Cayman Islands\n\t\tcase \"KY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Cayman Islands`)\n\n\t\t// Kazakhstan\n\t\tcase \"KZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Kazakhstan`)\n\n\t\t// Lao People’s Democratic Republic\n\t\tcase \"LA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lao People’s Democratic Republic`)\n\n\t\t// Lebanon\n\t\tcase \"LB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lebanon`)\n\n\t\t// Saint Lucia\n\t\tcase \"LC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Lucia`)\n\n\t\t// Liechtenstein\n\t\tcase \"LI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Liechtenstein`)\n\n\t\t// Sri Lanka\n\t\tcase \"LK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sri Lanka`)\n\n\t\t// Liberia\n\t\tcase \"LR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Liberia`)\n\n\t\t// Lesotho\n\t\tcase \"LS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lesotho`)\n\n\t\t// Lithuania\n\t\tcase \"LT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Lithuania`)\n\n\t\t// Luxembourg\n\t\tcase \"LU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Luxembourg`)\n\n\t\t// Latvia\n\t\tcase \"LV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Latvia`)\n\n\t\t// Libya\n\t\tcase \"LY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Libya`)\n\n\t\t// Morocco\n\t\tcase \"MA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Morocco`)\n\n\t\t// Monaco\n\t\tcase \"MC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Monaco`)\n\n\t\t// Moldova, Republic of\n\t\tcase \"MD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Moldova, Republic of`)\n\n\t\t// Montenegro\n\t\tcase \"ME\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Montenegro`)\n\n\t\t// Saint Martin (French part)\n\t\tcase \"MF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Martin (French part)`)\n\n\t\t// Madagascar\n\t\tcase \"MG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Madagascar`)\n\n\t\t// Marshall Islands\n\t\tcase \"MH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Marshall Islands`)\n\n\t\t// Formerly FYR Macedonia\n\t\tcase \"MK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `North Macedonia`)\n\n\t\t// Mali\n\t\tcase \"ML\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mali`)\n\n\t\t// Myanmar\n\t\tcase \"MM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Myanmar`)\n\n\t\t// Mongolia\n\t\tcase \"MN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mongolia`)\n\n\t\t// Macao\n\t\tcase \"MO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Macao`)\n\n\t\t// Northern Mariana Islands\n\t\tcase \"MP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Northern Mariana Islands`)\n\n\t\t// Martinique\n\t\tcase \"MQ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Martinique`)\n\n\t\t// Mauritania\n\t\tcase \"MR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mauritania`)\n\n\t\t// Montserrat\n\t\tcase \"MS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Montserrat`)\n\n\t\t// Malta\n\t\tcase \"MT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malta`)\n\n\t\t// Mauritius\n\t\tcase \"MU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mauritius`)\n\n\t\t// Maldives\n\t\tcase \"MV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Maldives`)\n\n\t\t// Malawi\n\t\tcase \"MW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malawi`)\n\n\t\t// Mexico\n\t\tcase \"MX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mexico`)\n\n\t\t// Malaysia\n\t\tcase \"MY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Malaysia`)\n\n\t\t// Mozambique\n\t\tcase \"MZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mozambique`)\n\n\t\t// Namibia\n\t\tcase \"NA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Namibia`)\n\n\t\t// New Caledonia\n\t\tcase \"NC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `New Caledonia`)\n\n\t\t// Niger\n\t\tcase \"NE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Niger`)\n\n\t\t// Norfolk Island\n\t\tcase \"NF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Norfolk Island`)\n\n\t\t// Nigeria\n\t\tcase \"NG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nigeria`)\n\n\t\t// Nicaragua\n\t\tcase \"NI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nicaragua`)\n\n\t\t// Netherlands\n\t\tcase \"NL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Netherlands`)\n\n\t\t// Norway\n\t\tcase \"NO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Norway`)\n\n\t\t// Nepal\n\t\tcase \"NP\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nepal`)\n\n\t\t// Nauru\n\t\tcase \"NR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Nauru`)\n\n\t\t// Niue\n\t\tcase \"NU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Niue`)\n\n\t\t// New Zealand\n\t\tcase \"NZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `New Zealand`)\n\n\t\t// Oman\n\t\tcase \"OM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Oman`)\n\n\t\t// Panama\n\t\tcase \"PA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Panama`)\n\n\t\t// Peru\n\t\tcase \"PE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Peru`)\n\n\t\t// French Polynesia\n\t\tcase \"PF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Polynesia`)\n\n\t\t// Papua New Guinea\n\t\tcase \"PG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Papua New Guinea`)\n\n\t\t// Philippines\n\t\tcase \"PH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Philippines`)\n\n\t\t// Pakistan\n\t\tcase \"PK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Pakistan`)\n\n\t\t// Poland\n\t\tcase \"PL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Poland`)\n\n\t\t// Saint Pierre and Miquelon\n\t\tcase \"PM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Pierre and Miquelon`)\n\n\t\t// Pitcairn\n\t\tcase \"PN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Pitcairn`)\n\n\t\t// Puerto Rico\n\t\tcase \"PR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Puerto Rico`)\n\n\t\t// Palestine, State of\n\t\tcase \"PS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Palestine, State of`)\n\n\t\t// Portugal\n\t\tcase \"PT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Portugal`)\n\n\t\t// Palau\n\t\tcase \"PW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Palau`)\n\n\t\t// Paraguay\n\t\tcase \"PY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Paraguay`)\n\n\t\t// Qatar\n\t\tcase \"QA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Qatar`)\n\n\t\t// Réunion\n\t\tcase \"RE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Réunion`)\n\n\t\t// Romania\n\t\tcase \"RO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Romania`)\n\n\t\t// Serbia\n\t\tcase \"RS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Serbia`)\n\n\t\t// Russian Federation\n\t\tcase \"RU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Russian Federation`)\n\n\t\t// Rwanda\n\t\tcase \"RW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Rwanda`)\n\n\t\t// Saudi Arabia\n\t\tcase \"SA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saudi Arabia`)\n\n\t\t// Solomon Islands\n\t\tcase \"SB\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Solomon Islands`)\n\n\t\t// Seychelles\n\t\tcase \"SC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Seychelles`)\n\n\t\t// Sudan\n\t\tcase \"SD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sudan`)\n\n\t\t// Sweden\n\t\tcase \"SE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sweden`)\n\n\t\t// Singapore\n\t\tcase \"SG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Singapore`)\n\n\t\t// Saint Helena, Ascension and Tristan da Cunha\n\t\tcase \"SH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Helena, Ascension and Tristan da Cunha`)\n\n\t\t// Slovenia\n\t\tcase \"SI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Slovenia`)\n\n\t\t// Svalbard and Jan Mayen\n\t\tcase \"SJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Svalbard and Jan Mayen`)\n\n\t\t// Slovakia\n\t\tcase \"SK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Slovakia`)\n\n\t\t// Sierra Leone\n\t\tcase \"SL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sierra Leone`)\n\n\t\t// San Marino\n\t\tcase \"SM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `San Marino`)\n\n\t\t// Senegal\n\t\tcase \"SN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Senegal`)\n\n\t\t// Somalia\n\t\tcase \"SO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Somalia`)\n\n\t\t// Suriname\n\t\tcase \"SR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Suriname`)\n\n\t\t// South Sudan\n\t\tcase \"SS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Sudan`)\n\n\t\t// Sao Tome and Principe\n\t\tcase \"ST\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sao Tome and Principe`)\n\n\t\t// El Salvador\n\t\tcase \"SV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `El Salvador`)\n\n\t\t// Sint Maarten (Dutch part)\n\t\tcase \"SX\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Sint Maarten (Dutch part)`)\n\n\t\t// Syrian Arab Republic\n\t\tcase \"SY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Syrian Arab Republic`)\n\n\t\t// Formerly known as Swaziland\n\t\tcase \"SZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Eswatini`)\n\n\t\t// Turks and Caicos Islands\n\t\tcase \"TC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turks and Caicos Islands`)\n\n\t\t// Chad\n\t\tcase \"TD\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Chad`)\n\n\t\t// French Southern Territories\n\t\tcase \"TF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `French Southern Territories`)\n\n\t\t// Togo\n\t\tcase \"TG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Togo`)\n\n\t\t// Thailand\n\t\tcase \"TH\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Thailand`)\n\n\t\t// Tajikistan\n\t\tcase \"TJ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tajikistan`)\n\n\t\t// Tokelau\n\t\tcase \"TK\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tokelau`)\n\n\t\t// Timor-Leste\n\t\tcase \"TL\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Timor-Leste`)\n\n\t\t// Turkmenistan\n\t\tcase \"TM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turkmenistan`)\n\n\t\t// Tunisia\n\t\tcase \"TN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tunisia`)\n\n\t\t// Tonga\n\t\tcase \"TO\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tonga`)\n\n\t\t// Turkey\n\t\tcase \"TR\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Turkey`)\n\n\t\t// Trinidad and Tobago\n\t\tcase \"TT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Trinidad and Tobago`)\n\n\t\t// Tuvalu\n\t\tcase \"TV\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tuvalu`)\n\n\t\t// Taiwan, Province of China\n\t\tcase \"TW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Taiwan, Province of China`)\n\n\t\t// Tanzania, United Republic of\n\t\tcase \"TZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Tanzania, United Republic of`)\n\n\t\t// Ukraine\n\t\tcase \"UA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Ukraine`)\n\n\t\t// Uganda\n\t\tcase \"UG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uganda`)\n\n\t\t// United States Minor Outlying Islands\n\t\tcase \"UM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United States Minor Outlying Islands`)\n\n\t\t// United States\n\t\tcase \"US\":\n\t\t\ttmpeCodes = append(tmpeCodes, `United States`)\n\n\t\t// Uruguay\n\t\tcase \"UY\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uruguay`)\n\n\t\t// Uzbekistan\n\t\tcase \"UZ\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Uzbekistan`)\n\n\t\t// Holy See (Vatican City State)\n\t\tcase \"VA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Holy See (Vatican City State)`)\n\n\t\t// Saint Vincent and the Grenadines\n\t\tcase \"VC\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Saint Vincent and the Grenadines`)\n\n\t\t// Venezuela, Bolivarian Republic of\n\t\tcase \"VE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Venezuela, Bolivarian Republic of`)\n\n\t\t// Virgin Islands, British\n\t\tcase \"VG\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Virgin Islands, British`)\n\n\t\t// Virgin Islands, US\n\t\tcase \"VI\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Virgin Islands, US`)\n\n\t\t// Viet Nam\n\t\tcase \"VN\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Viet Nam`)\n\n\t\t// Vanuatu\n\t\tcase \"VU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Vanuatu`)\n\n\t\t// Wallis and Futuna\n\t\tcase \"WF\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Wallis and Futuna`)\n\n\t\t// Samoa\n\t\tcase \"WS\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Samoa`)\n\n\t\t// Yemen\n\t\tcase \"YE\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Yemen`)\n\n\t\t// Mayotte\n\t\tcase \"YT\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Mayotte`)\n\n\t\t// DEPRECATED, replaced by ME – Montenegro and RS – Serbia\n\t\tcase \"YU\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Yugoslavia`)\n\n\t\t// South Africa\n\t\tcase \"ZA\":\n\t\t\ttmpeCodes = append(tmpeCodes, `South Africa`)\n\n\t\t// Zambia\n\t\tcase \"ZM\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Zambia`)\n\n\t\t// Zimbabwe\n\t\tcase \"ZW\":\n\t\t\ttmpeCodes = append(tmpeCodes, `Zimbabwe`)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"undefined code for PrizeCountry has been passed, got [%s]\", v)\n\t\t}\n\t}\n\tc.Body = tmpeCodes\n\treturn nil\n}", "func (d *Document) XMLExtractText() XMLDocMacroData {\n\tvar doc XMLDocMacroData\n\tfile, err := d.Doc.Open()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\n\tdata, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := xml.Unmarshal(data, &doc); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn doc\n}", "func parseXmlMem(inXml []byte, options Options) (C.xmlDocPtr, error) {\n\n\tstrXml := C.CString(string(inXml))\n\tdefer C.free(unsafe.Pointer(strXml))\n\tpRes, err := C.cParseDoc(strXml, C.int(len(inXml)), C.short(options))\n\n\tdefer C.free(unsafe.Pointer(pRes.errorStr))\n\tif err != nil {\n\t\trStr := C.GoString(pRes.errorStr)\n\t\treturn nil, errors.New(\"Xml parser error:\\n\" + strings.Trim(rStr, \"\\n\"))\n\t}\n\treturn pRes.docPtr, nil\n}", "func (c *TradeCategory) 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 // An edition from a UK publisher sold only in territories where exclusive rights are not held. Rights details should be carried in PR.21 (ONIX 2.1) OR P.21 (ONIX 3.0) as usual\n case \"01\":\n\t\tc.Body = `UK open market edition`\n\n // In UK, an edition intended primarily for airside sales in UK airports, though it may be available for sale in other territories where exclusive rights are not held. Rights details should be carried in PR.21 (ONIX 2.1) OR P.21 (ONIX 3.0) as usual\n case \"02\":\n\t\tc.Body = `Airport edition`\n\n // In Germany, a special printing sold at a lower price than the regular hardback\n case \"03\":\n\t\tc.Body = `Sonderausgabe`\n\n // In countries where recognised as a distinct trade category, eg France « livre de poche », Germany ,Taschenbuch‘, Italy «tascabile», Spain «libro de bolsillo»\n case \"04\":\n\t\tc.Body = `Pocket book`\n\n // Edition produced solely for sale in designated export markets\n case \"05\":\n\t\tc.Body = `International edition (US)`\n\n // Audio product sold in special durable packaging and with a replacement guarantee for the contained cassettes or CDs for a specified shelf-life\n case \"06\":\n\t\tc.Body = `Library audio edition`\n\n // An edition from a US publisher sold only in territories where exclusive rights are not held. Rights details should be carried in PR.21 (ONIX 2.1) OR P.21 (ONIX 3.0) as usual\n case \"07\":\n\t\tc.Body = `US open market edition`\n\n // In France, a category of book that has a particular legal status, claimed by the publisher\n case \"08\":\n\t\tc.Body = `Livre scolaire, déclaré par l’éditeur`\n\n // In France, a category of book that has a particular legal status, designated independently of the publisher\n case \"09\":\n\t\tc.Body = `Livre scolaire (non spécifié)`\n\n // Edition published for sale only with a newspaper or periodical\n case \"10\":\n\t\tc.Body = `Supplement to newspaper`\n\n // In Spain, a school textbook for which there is no fixed or suggested retail price and which is supplied by the publisher on terms individually agreed with the bookseller\n case \"11\":\n\t\tc.Body = `Precio libre textbook`\n\n // For editions sold only through newsstands/newsagents\n case \"12\":\n\t\tc.Body = `News outlet edition`\n\n // In the US and Canada, a book that is published primarily for use by students in school or college education as a basis for study. Textbooks published for the elementary and secondary school markets are generally purchased by school districts for the use of students. Textbooks published for the higher education market are generally adopted for use in particular classes by the instructors of those classes. Textbooks are usually not marketed to the general public, which distinguishes them from trade books. Note that trade books adopted for course use are not considered to be textbooks (though a specific education edition of a trade title may be)\n case \"13\":\n\t\tc.Body = `US textbook`\n\n // ‘Short’ e-book (sometimes also called a ‘single’), typically containing a single short story, an essay or piece of long-form journalism\n case \"14\":\n\t\tc.Body = `E-book short`\n\n // In countries where recognised as a distinct trade category, eg Italy «supertascabile». For use in ONIX 3.0 only\n case \"15\":\n\t\tc.Body = `Superpocket book`\n\n // Category of books, usually hardcover and of a large format (A4 or larger) and printed on high-quality paper, where the primary features are illustrations, and these are more important than text. Sometimes called ‘coffee-table books’ or ‘art books’ in English. For use in ONIX 3.0 only\n case \"16\":\n\t\tc.Body = `Beau-livre`\n\n // Category of audio products typically distinguished by being free of charge (but which may be monetised through advertising content) and episodic. For use in ONIX 3.0 only\n case \"17\":\n\t\tc.Body = `Podcast`\n\n // Category of books or e-books which are single issues of a periodical publication, sold as independent products. For use in ONIX 3.0 only\n case \"18\":\n\t\tc.Body = `Periodical`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for TradeCategory has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *ToLanguage) 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 // Afar\n case \"aar\":\n\t\tc.Body = `Afar`\n\n // Abkhaz\n case \"abk\":\n\t\tc.Body = `Abkhaz`\n\n // Achinese\n case \"ace\":\n\t\tc.Body = `Achinese`\n\n // Acoli\n case \"ach\":\n\t\tc.Body = `Acoli`\n\n // Adangme\n case \"ada\":\n\t\tc.Body = `Adangme`\n\n // Adygei\n case \"ady\":\n\t\tc.Body = `Adygei`\n\n // Collective name\n case \"afa\":\n\t\tc.Body = `Afro-Asiatic languages`\n\n // Artificial language\n case \"afh\":\n\t\tc.Body = `Afrihili`\n\n // Afrikaans\n case \"afr\":\n\t\tc.Body = `Afrikaans`\n\n // Ainu\n case \"ain\":\n\t\tc.Body = `Ainu`\n\n // Macrolanguage\n case \"aka\":\n\t\tc.Body = `Akan`\n\n // Akkadian\n case \"akk\":\n\t\tc.Body = `Akkadian`\n\n // Macrolanguage\n case \"alb\":\n\t\tc.Body = `Albanian`\n\n // Aleut\n case \"ale\":\n\t\tc.Body = `Aleut`\n\n // Collective name\n case \"alg\":\n\t\tc.Body = `Algonquian languages`\n\n // Southern Altai\n case \"alt\":\n\t\tc.Body = `Southern Altai`\n\n // Amharic\n case \"amh\":\n\t\tc.Body = `Amharic`\n\n // English, Old (ca. 450-1100)\n case \"ang\":\n\t\tc.Body = `English, Old (ca. 450-1100)`\n\n // Angika\n case \"anp\":\n\t\tc.Body = `Angika`\n\n // Collective name\n case \"apa\":\n\t\tc.Body = `Apache languages`\n\n // Macrolanguage\n case \"ara\":\n\t\tc.Body = `Arabic`\n\n // Official Aramaic; Imperial Aramaic (700-300 BCE)\n case \"arc\":\n\t\tc.Body = `Official Aramaic; Imperial Aramaic (700-300 BCE)`\n\n // Aragonese\n case \"arg\":\n\t\tc.Body = `Aragonese`\n\n // Armenian\n case \"arm\":\n\t\tc.Body = `Armenian`\n\n // Mapudungun; Mapuche\n case \"arn\":\n\t\tc.Body = `Mapudungun; Mapuche`\n\n // Arapaho\n case \"arp\":\n\t\tc.Body = `Arapaho`\n\n // Collective name\n case \"art\":\n\t\tc.Body = `Artificial languages`\n\n // Arawak\n case \"arw\":\n\t\tc.Body = `Arawak`\n\n // Assamese\n case \"asm\":\n\t\tc.Body = `Assamese`\n\n // Asturian; Bable; Leonese; Asturleonese\n case \"ast\":\n\t\tc.Body = `Asturian; Bable; Leonese; Asturleonese`\n\n // Collective name\n case \"ath\":\n\t\tc.Body = `Athapascan languages`\n\n // Collective name\n case \"aus\":\n\t\tc.Body = `Australian languages`\n\n // Avaric\n case \"ava\":\n\t\tc.Body = `Avaric`\n\n // Avestan\n case \"ave\":\n\t\tc.Body = `Avestan`\n\n // Awadhi\n case \"awa\":\n\t\tc.Body = `Awadhi`\n\n // Macrolanguage\n case \"aym\":\n\t\tc.Body = `Aymara`\n\n // Macrolanguage\n case \"aze\":\n\t\tc.Body = `Azerbaijani`\n\n // Collective name\n case \"bad\":\n\t\tc.Body = `Banda languages`\n\n // Collective name\n case \"bai\":\n\t\tc.Body = `Bamileke languages`\n\n // Bashkir\n case \"bak\":\n\t\tc.Body = `Bashkir`\n\n // Macrolanguage\n case \"bal\":\n\t\tc.Body = `Baluchi`\n\n // Bambara\n case \"bam\":\n\t\tc.Body = `Bambara`\n\n // Balinese\n case \"ban\":\n\t\tc.Body = `Balinese`\n\n // Basque\n case \"baq\":\n\t\tc.Body = `Basque`\n\n // Basa\n case \"bas\":\n\t\tc.Body = `Basa`\n\n // Collective name\n case \"bat\":\n\t\tc.Body = `Baltic languages`\n\n // Beja; Bedawiyet\n case \"bej\":\n\t\tc.Body = `Beja; Bedawiyet`\n\n // Belarusian\n case \"bel\":\n\t\tc.Body = `Belarusian`\n\n // Bemba\n case \"bem\":\n\t\tc.Body = `Bemba`\n\n // Bengali\n case \"ben\":\n\t\tc.Body = `Bengali`\n\n // Collective name\n case \"ber\":\n\t\tc.Body = `Berber languages`\n\n // Bhojpuri\n case \"bho\":\n\t\tc.Body = `Bhojpuri`\n\n // Collective name\n case \"bih\":\n\t\tc.Body = `Bihari languages`\n\n // Macrolanguage\n case \"bik\":\n\t\tc.Body = `Bikol`\n\n // Bini; Edo\n case \"bin\":\n\t\tc.Body = `Bini; Edo`\n\n // Bislama\n case \"bis\":\n\t\tc.Body = `Bislama`\n\n // Siksika\n case \"bla\":\n\t\tc.Body = `Siksika`\n\n // Collective name\n case \"bnt\":\n\t\tc.Body = `Bantu languages`\n\n // Bosnian\n case \"bos\":\n\t\tc.Body = `Bosnian`\n\n // Braj\n case \"bra\":\n\t\tc.Body = `Braj`\n\n // Breton\n case \"bre\":\n\t\tc.Body = `Breton`\n\n // Collective name\n case \"btk\":\n\t\tc.Body = `Batak languages`\n\n // Macrolanguage\n case \"bua\":\n\t\tc.Body = `Buriat`\n\n // Buginese\n case \"bug\":\n\t\tc.Body = `Buginese`\n\n // Bulgarian\n case \"bul\":\n\t\tc.Body = `Bulgarian`\n\n // Burmese\n case \"bur\":\n\t\tc.Body = `Burmese`\n\n // Blin; Bilin\n case \"byn\":\n\t\tc.Body = `Blin; Bilin`\n\n // Caddo\n case \"cad\":\n\t\tc.Body = `Caddo`\n\n // Collective name\n case \"cai\":\n\t\tc.Body = `Central American Indian languages`\n\n // Galibi Carib\n case \"car\":\n\t\tc.Body = `Galibi Carib`\n\n // Catalan\n case \"cat\":\n\t\tc.Body = `Catalan`\n\n // Collective name\n case \"cau\":\n\t\tc.Body = `Caucasian languages`\n\n // Cebuano\n case \"ceb\":\n\t\tc.Body = `Cebuano`\n\n // Collective name\n case \"cel\":\n\t\tc.Body = `Celtic languages`\n\n // Chamorro\n case \"cha\":\n\t\tc.Body = `Chamorro`\n\n // Chibcha\n case \"chb\":\n\t\tc.Body = `Chibcha`\n\n // Chechen\n case \"che\":\n\t\tc.Body = `Chechen`\n\n // Chagatai\n case \"chg\":\n\t\tc.Body = `Chagatai`\n\n // Macrolanguage\n case \"chi\":\n\t\tc.Body = `Chinese`\n\n // Chuukese (Truk)\n case \"chk\":\n\t\tc.Body = `Chuukese (Truk)`\n\n // Macrolanguage\n case \"chm\":\n\t\tc.Body = `Mari`\n\n // Chinook jargon\n case \"chn\":\n\t\tc.Body = `Chinook jargon`\n\n // Choctaw\n case \"cho\":\n\t\tc.Body = `Choctaw`\n\n // Chipewyan; Dene Suline\n case \"chp\":\n\t\tc.Body = `Chipewyan; Dene Suline`\n\n // Cherokee\n case \"chr\":\n\t\tc.Body = `Cherokee`\n\n // Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic\n case \"chu\":\n\t\tc.Body = `Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic`\n\n // Chuvash\n case \"chv\":\n\t\tc.Body = `Chuvash`\n\n // Cheyenne\n case \"chy\":\n\t\tc.Body = `Cheyenne`\n\n // ONIX local code, equivalent to ckb in ISO 639-3. For use in ONIX 3.0 only\n case \"ckb\":\n\t\tc.Body = `Central Kurdish (Sorani)`\n\n // Collective name\n case \"cmc\":\n\t\tc.Body = `Chamic languages`\n\n // ONIX local code, equivalent to cmn in ISO 639-3\n case \"cmn\":\n\t\tc.Body = `Mandarin`\n\n // For use in ONIX 3.0 only\n case \"cnr\":\n\t\tc.Body = `Montenegrin`\n\n // Coptic\n case \"cop\":\n\t\tc.Body = `Coptic`\n\n // Cornish\n case \"cor\":\n\t\tc.Body = `Cornish`\n\n // Corsican\n case \"cos\":\n\t\tc.Body = `Corsican`\n\n // Collective name\n case \"cpe\":\n\t\tc.Body = `Creoles and pidgins, English-based`\n\n // Collective name\n case \"cpf\":\n\t\tc.Body = `Creoles and pidgins, French-based`\n\n // Collective name\n case \"cpp\":\n\t\tc.Body = `Creoles and pidgins, Portuguese-based`\n\n // Macrolanguage\n case \"cre\":\n\t\tc.Body = `Cree`\n\n // Crimean Turkish; Crimean Tatar\n case \"crh\":\n\t\tc.Body = `Crimean Turkish; Crimean Tatar`\n\n // Collective name\n case \"crp\":\n\t\tc.Body = `Creoles and pidgins`\n\n // Kashubian\n case \"csb\":\n\t\tc.Body = `Kashubian`\n\n // Collective name\n case \"cus\":\n\t\tc.Body = `Cushitic languages`\n\n // Czech\n case \"cze\":\n\t\tc.Body = `Czech`\n\n // Dakota\n case \"dak\":\n\t\tc.Body = `Dakota`\n\n // Danish\n case \"dan\":\n\t\tc.Body = `Danish`\n\n // Dargwa\n case \"dar\":\n\t\tc.Body = `Dargwa`\n\n // Collective name\n case \"day\":\n\t\tc.Body = `Land Dayak languages`\n\n // Macrolanguage\n case \"del\":\n\t\tc.Body = `Delaware`\n\n // Macrolanguage\n case \"den\":\n\t\tc.Body = `Slave (Athapascan)`\n\n // Dogrib\n case \"dgr\":\n\t\tc.Body = `Dogrib`\n\n // Macrolanguage\n case \"din\":\n\t\tc.Body = `Dinka`\n\n // Divehi; Dhivehi; Maldivian\n case \"div\":\n\t\tc.Body = `Divehi; Dhivehi; Maldivian`\n\n // Macrolanguage\n case \"doi\":\n\t\tc.Body = `Dogri`\n\n // Collective name\n case \"dra\":\n\t\tc.Body = `Dravidian languages`\n\n // Lower Sorbian\n case \"dsb\":\n\t\tc.Body = `Lower Sorbian`\n\n // Duala\n case \"dua\":\n\t\tc.Body = `Duala`\n\n // Dutch, Middle (ca. 1050-1350)\n case \"dum\":\n\t\tc.Body = `Dutch, Middle (ca. 1050-1350)`\n\n // Dutch; Flemish\n case \"dut\":\n\t\tc.Body = `Dutch; Flemish`\n\n // Dyula\n case \"dyu\":\n\t\tc.Body = `Dyula`\n\n // Dzongkha\n case \"dzo\":\n\t\tc.Body = `Dzongkha`\n\n // Efik\n case \"efi\":\n\t\tc.Body = `Efik`\n\n // ONIX local code for Italian dialect, equivalent to egl in ISO 639-3. For use in ONIX 3.0 only\n case \"egl\":\n\t\tc.Body = `Emilian`\n\n // Egyptian (Ancient)\n case \"egy\":\n\t\tc.Body = `Egyptian (Ancient)`\n\n // Ekajuk\n case \"eka\":\n\t\tc.Body = `Ekajuk`\n\n // Elamite\n case \"elx\":\n\t\tc.Body = `Elamite`\n\n // English\n case \"eng\":\n\t\tc.Body = `English`\n\n // English, Middle (1100-1500)\n case \"enm\":\n\t\tc.Body = `English, Middle (1100-1500)`\n\n // Artificial language\n case \"epo\":\n\t\tc.Body = `Esperanto`\n\n // Macrolanguage\n case \"est\":\n\t\tc.Body = `Estonian`\n\n // Ewe\n case \"ewe\":\n\t\tc.Body = `Ewe`\n\n // Ewondo\n case \"ewo\":\n\t\tc.Body = `Ewondo`\n\n // Fang\n case \"fan\":\n\t\tc.Body = `Fang`\n\n // Faroese\n case \"fao\":\n\t\tc.Body = `Faroese`\n\n // Fanti\n case \"fat\":\n\t\tc.Body = `Fanti`\n\n // Fijian\n case \"fij\":\n\t\tc.Body = `Fijian`\n\n // Filipino; Pilipino\n case \"fil\":\n\t\tc.Body = `Filipino; Pilipino`\n\n // Finnish\n case \"fin\":\n\t\tc.Body = `Finnish`\n\n // ONIX local code, equivalent to fit in ISO 639-3\n case \"fit\":\n\t\tc.Body = `Meänkieli / Tornedalen Finnish`\n\n // Collective name\n case \"fiu\":\n\t\tc.Body = `Finno-Ugrian languages`\n\n // ONIX local code, equivalent to fkv in ISO 639-3\n case \"fkv\":\n\t\tc.Body = `Kvensk`\n\n // Fon\n case \"fon\":\n\t\tc.Body = `Fon`\n\n // French\n case \"fre\":\n\t\tc.Body = `French`\n\n // French, Middle (ca. 1400-1600)\n case \"frm\":\n\t\tc.Body = `French, Middle (ca. 1400-1600)`\n\n // French, Old (ca. 842-1400)\n case \"fro\":\n\t\tc.Body = `French, Old (ca. 842-1400)`\n\n // Northern Frisian\n case \"frr\":\n\t\tc.Body = `Northern Frisian`\n\n // Eastern Frisian\n case \"frs\":\n\t\tc.Body = `Eastern Frisian`\n\n // Western Frisian\n case \"fry\":\n\t\tc.Body = `Western Frisian`\n\n // Fulah\n case \"ful\":\n\t\tc.Body = `Fulah`\n\n // Friulian\n case \"fur\":\n\t\tc.Body = `Friulian`\n\n // Gã\n case \"gaa\":\n\t\tc.Body = `Gã`\n\n // Gayo\n case \"gay\":\n\t\tc.Body = `Gayo`\n\n // Macrolanguage\n case \"gba\":\n\t\tc.Body = `Gbaya`\n\n // Collective name\n case \"gem\":\n\t\tc.Body = `Germanic languages`\n\n // Georgian\n case \"geo\":\n\t\tc.Body = `Georgian`\n\n // German\n case \"ger\":\n\t\tc.Body = `German`\n\n // Ethiopic (Ge’ez)\n case \"gez\":\n\t\tc.Body = `Ethiopic (Ge’ez)`\n\n // Gilbertese\n case \"gil\":\n\t\tc.Body = `Gilbertese`\n\n // Scottish Gaelic\n case \"gla\":\n\t\tc.Body = `Scottish Gaelic`\n\n // Irish\n case \"gle\":\n\t\tc.Body = `Irish`\n\n // Galician\n case \"glg\":\n\t\tc.Body = `Galician`\n\n // Manx\n case \"glv\":\n\t\tc.Body = `Manx`\n\n // German, Middle High (ca. 1050-1500)\n case \"gmh\":\n\t\tc.Body = `German, Middle High (ca. 1050-1500)`\n\n // German, Old High (ca. 750-1050)\n case \"goh\":\n\t\tc.Body = `German, Old High (ca. 750-1050)`\n\n // Macrolanguage\n case \"gon\":\n\t\tc.Body = `Gondi`\n\n // Gorontalo\n case \"gor\":\n\t\tc.Body = `Gorontalo`\n\n // Gothic\n case \"got\":\n\t\tc.Body = `Gothic`\n\n // Macrolanguage\n case \"grb\":\n\t\tc.Body = `Grebo`\n\n // Greek, Ancient (to 1453)\n case \"grc\":\n\t\tc.Body = `Greek, Ancient (to 1453)`\n\n // Greek, Modern (1453-)\n case \"gre\":\n\t\tc.Body = `Greek, Modern (1453-)`\n\n // Macrolanguage\n case \"grn\":\n\t\tc.Body = `Guarani`\n\n // ONIX local code, equivalent to grt in ISO 639-3\n case \"grt\":\n\t\tc.Body = `Garo`\n\n // Swiss German; Alemannic\n case \"gsw\":\n\t\tc.Body = `Swiss German; Alemannic`\n\n // Gujarati\n case \"guj\":\n\t\tc.Body = `Gujarati`\n\n // Gwich’in\n case \"gwi\":\n\t\tc.Body = `Gwich’in`\n\n // Macrolanguage\n case \"hai\":\n\t\tc.Body = `Haida`\n\n // Haitian French Creole\n case \"hat\":\n\t\tc.Body = `Haitian French Creole`\n\n // Hausa\n case \"hau\":\n\t\tc.Body = `Hausa`\n\n // Hawaiian\n case \"haw\":\n\t\tc.Body = `Hawaiian`\n\n // Hebrew\n case \"heb\":\n\t\tc.Body = `Hebrew`\n\n // Herero\n case \"her\":\n\t\tc.Body = `Herero`\n\n // Hiligaynon\n case \"hil\":\n\t\tc.Body = `Hiligaynon`\n\n // Collective name\n case \"him\":\n\t\tc.Body = `Himachali languages; Western Pahari languages`\n\n // Hindi\n case \"hin\":\n\t\tc.Body = `Hindi`\n\n // Hittite\n case \"hit\":\n\t\tc.Body = `Hittite`\n\n // Macrolanguage\n case \"hmn\":\n\t\tc.Body = `Hmong; Mong`\n\n // Hiri Motu\n case \"hmo\":\n\t\tc.Body = `Hiri Motu`\n\n // Croatian\n case \"hrv\":\n\t\tc.Body = `Croatian`\n\n // Upper Sorbian\n case \"hsb\":\n\t\tc.Body = `Upper Sorbian`\n\n // Hungarian\n case \"hun\":\n\t\tc.Body = `Hungarian`\n\n // Hupa\n case \"hup\":\n\t\tc.Body = `Hupa`\n\n // Iban\n case \"iba\":\n\t\tc.Body = `Iban`\n\n // Igbo\n case \"ibo\":\n\t\tc.Body = `Igbo`\n\n // Icelandic\n case \"ice\":\n\t\tc.Body = `Icelandic`\n\n // Artificial language\n case \"ido\":\n\t\tc.Body = `Ido`\n\n // Sichuan Yi; Nuosu\n case \"iii\":\n\t\tc.Body = `Sichuan Yi; Nuosu`\n\n // Collective name\n case \"ijo\":\n\t\tc.Body = `Ijo languages`\n\n // Macrolanguage\n case \"iku\":\n\t\tc.Body = `Inuktitut`\n\n // Artificial language\n case \"ile\":\n\t\tc.Body = `Interlingue; Occidental`\n\n // Iloko\n case \"ilo\":\n\t\tc.Body = `Iloko`\n\n // Artificial language\n case \"ina\":\n\t\tc.Body = `Interlingua (International Auxiliary Language Association)`\n\n // Collective name\n case \"inc\":\n\t\tc.Body = `Indic languages`\n\n // Indonesian\n case \"ind\":\n\t\tc.Body = `Indonesian`\n\n // Collective name\n case \"ine\":\n\t\tc.Body = `Indo-European languages`\n\n // Ingush\n case \"inh\":\n\t\tc.Body = `Ingush`\n\n // Macrolanguage\n case \"ipk\":\n\t\tc.Body = `Inupiaq`\n\n // Collective name\n case \"ira\":\n\t\tc.Body = `Iranian languages`\n\n // Collective name\n case \"iro\":\n\t\tc.Body = `Iroquoian languages`\n\n // Italian\n case \"ita\":\n\t\tc.Body = `Italian`\n\n // Javanese\n case \"jav\":\n\t\tc.Body = `Javanese`\n\n // Lojban\n case \"jbo\":\n\t\tc.Body = `Lojban`\n\n // Japanese\n case \"jpn\":\n\t\tc.Body = `Japanese`\n\n // Judeo-Persian\n case \"jpr\":\n\t\tc.Body = `Judeo-Persian`\n\n // Macrolanguage\n case \"jrb\":\n\t\tc.Body = `Judeo-Arabic`\n\n // Kara-Kalpak\n case \"kaa\":\n\t\tc.Body = `Kara-Kalpak`\n\n // Kabyle\n case \"kab\":\n\t\tc.Body = `Kabyle`\n\n // Kachin; Jingpho\n case \"kac\":\n\t\tc.Body = `Kachin; Jingpho`\n\n // Kalâtdlisut; Greenlandic\n case \"kal\":\n\t\tc.Body = `Kalâtdlisut; Greenlandic`\n\n // Kamba\n case \"kam\":\n\t\tc.Body = `Kamba`\n\n // Kannada\n case \"kan\":\n\t\tc.Body = `Kannada`\n\n // Collective name\n case \"kar\":\n\t\tc.Body = `Karen languages`\n\n // Kashmiri\n case \"kas\":\n\t\tc.Body = `Kashmiri`\n\n // Macrolanguage\n case \"kau\":\n\t\tc.Body = `Kanuri`\n\n // Kawi\n case \"kaw\":\n\t\tc.Body = `Kawi`\n\n // Kazakh\n case \"kaz\":\n\t\tc.Body = `Kazakh`\n\n // Kabardian (Circassian)\n case \"kbd\":\n\t\tc.Body = `Kabardian (Circassian)`\n\n // ONIX local code, equivalent to kdr in ISO 639-3\n case \"kdr\":\n\t\tc.Body = `Karaim`\n\n // Khasi\n case \"kha\":\n\t\tc.Body = `Khasi`\n\n // Collective name\n case \"khi\":\n\t\tc.Body = `Khoisan languages`\n\n // Central Khmer\n case \"khm\":\n\t\tc.Body = `Central Khmer`\n\n // Khotanese; Sakan\n case \"kho\":\n\t\tc.Body = `Khotanese; Sakan`\n\n // Kikuyu; Gikuyu\n case \"kik\":\n\t\tc.Body = `Kikuyu; Gikuyu`\n\n // Kinyarwanda\n case \"kin\":\n\t\tc.Body = `Kinyarwanda`\n\n // Kirghiz; Kyrgyz\n case \"kir\":\n\t\tc.Body = `Kirghiz; Kyrgyz`\n\n // Kimbundu\n case \"kmb\":\n\t\tc.Body = `Kimbundu`\n\n // Macrolanguage\n case \"kok\":\n\t\tc.Body = `Konkani`\n\n // Macrolanguage\n case \"kom\":\n\t\tc.Body = `Komi`\n\n // Macrolanguage\n case \"kon\":\n\t\tc.Body = `Kongo`\n\n // Korean\n case \"kor\":\n\t\tc.Body = `Korean`\n\n // Kusaiean (Caroline Islands)\n case \"kos\":\n\t\tc.Body = `Kusaiean (Caroline Islands)`\n\n // Macrolanguage\n case \"kpe\":\n\t\tc.Body = `Kpelle`\n\n // Karachay-Balkar\n case \"krc\":\n\t\tc.Body = `Karachay-Balkar`\n\n // Karelian\n case \"krl\":\n\t\tc.Body = `Karelian`\n\n // Collective name\n case \"kro\":\n\t\tc.Body = `Kru languages`\n\n // Kurukh\n case \"kru\":\n\t\tc.Body = `Kurukh`\n\n // Kuanyama\n case \"kua\":\n\t\tc.Body = `Kuanyama`\n\n // Kumyk\n case \"kum\":\n\t\tc.Body = `Kumyk`\n\n // Macrolanguage\n case \"kur\":\n\t\tc.Body = `Kurdish`\n\n // Kutenai\n case \"kut\":\n\t\tc.Body = `Kutenai`\n\n // Ladino\n case \"lad\":\n\t\tc.Body = `Ladino`\n\n // Macrolanguage\n case \"lah\":\n\t\tc.Body = `Lahnda`\n\n // Lamba\n case \"lam\":\n\t\tc.Body = `Lamba`\n\n // Lao\n case \"lao\":\n\t\tc.Body = `Lao`\n\n // Latin\n case \"lat\":\n\t\tc.Body = `Latin`\n\n // Macrolanguage\n case \"lav\":\n\t\tc.Body = `Latvian`\n\n // Lezgian\n case \"lez\":\n\t\tc.Body = `Lezgian`\n\n // ONIX local code for Italian dialect, equivalent to lij in ISO 639-3. For use in ONIX 3.0 only\n case \"lij\":\n\t\tc.Body = `Ligurian`\n\n // Limburgish\n case \"lim\":\n\t\tc.Body = `Limburgish`\n\n // Lingala\n case \"lin\":\n\t\tc.Body = `Lingala`\n\n // Lithuanian\n case \"lit\":\n\t\tc.Body = `Lithuanian`\n\n // ONIX local code for Italian dialect, equivalent to lmo in ISO 639-3. For use in ONIX 3.0 only\n case \"lmo\":\n\t\tc.Body = `Lombard`\n\n // Mongo-Nkundu\n case \"lol\":\n\t\tc.Body = `Mongo-Nkundu`\n\n // Lozi\n case \"loz\":\n\t\tc.Body = `Lozi`\n\n // Luxembourgish; Letzeburgesch\n case \"ltz\":\n\t\tc.Body = `Luxembourgish; Letzeburgesch`\n\n // Luba-Lulua\n case \"lua\":\n\t\tc.Body = `Luba-Lulua`\n\n // Luba-Katanga\n case \"lub\":\n\t\tc.Body = `Luba-Katanga`\n\n // Ganda\n case \"lug\":\n\t\tc.Body = `Ganda`\n\n // Luiseño\n case \"lui\":\n\t\tc.Body = `Luiseño`\n\n // Lunda\n case \"lun\":\n\t\tc.Body = `Lunda`\n\n // Luo (Kenya and Tanzania)\n case \"luo\":\n\t\tc.Body = `Luo (Kenya and Tanzania)`\n\n // Lushai\n case \"lus\":\n\t\tc.Body = `Lushai`\n\n // Macedonian\n case \"mac\":\n\t\tc.Body = `Macedonian`\n\n // Madurese\n case \"mad\":\n\t\tc.Body = `Madurese`\n\n // Magahi\n case \"mag\":\n\t\tc.Body = `Magahi`\n\n // Marshallese\n case \"mah\":\n\t\tc.Body = `Marshallese`\n\n // Maithili\n case \"mai\":\n\t\tc.Body = `Maithili`\n\n // Makasar\n case \"mak\":\n\t\tc.Body = `Makasar`\n\n // Malayalam\n case \"mal\":\n\t\tc.Body = `Malayalam`\n\n // Macrolanguage\n case \"man\":\n\t\tc.Body = `Mandingo`\n\n // Maori\n case \"mao\":\n\t\tc.Body = `Maori`\n\n // Collective name\n case \"map\":\n\t\tc.Body = `Austronesian languages`\n\n // Marathi\n case \"mar\":\n\t\tc.Body = `Marathi`\n\n // Masai\n case \"mas\":\n\t\tc.Body = `Masai`\n\n // Macrolanguage\n case \"may\":\n\t\tc.Body = `Malay`\n\n // Moksha\n case \"mdf\":\n\t\tc.Body = `Moksha`\n\n // Mandar\n case \"mdr\":\n\t\tc.Body = `Mandar`\n\n // Mende\n case \"men\":\n\t\tc.Body = `Mende`\n\n // Irish, Middle (ca. 1100-1550)\n case \"mga\":\n\t\tc.Body = `Irish, Middle (ca. 1100-1550)`\n\n // Mi’kmaq; Micmac\n case \"mic\":\n\t\tc.Body = `Mi’kmaq; Micmac`\n\n // Minangkabau\n case \"min\":\n\t\tc.Body = `Minangkabau`\n\n // Use where no suitable code is available\n case \"mis\":\n\t\tc.Body = `Uncoded languages`\n\n // Collective name\n case \"mkh\":\n\t\tc.Body = `Mon-Khmer languages`\n\n // Macrolanguage\n case \"mlg\":\n\t\tc.Body = `Malagasy`\n\n // Maltese\n case \"mlt\":\n\t\tc.Body = `Maltese`\n\n // Manchu\n case \"mnc\":\n\t\tc.Body = `Manchu`\n\n // Manipuri\n case \"mni\":\n\t\tc.Body = `Manipuri`\n\n // Collective name\n case \"mno\":\n\t\tc.Body = `Manobo languages`\n\n // Mohawk\n case \"moh\":\n\t\tc.Body = `Mohawk`\n\n // DEPRECATED – use rum\n case \"mol\":\n\t\tc.Body = `Moldavian; Moldovan`\n\n // Macrolanguage\n case \"mon\":\n\t\tc.Body = `Mongolian`\n\n // Mooré; Mossi\n case \"mos\":\n\t\tc.Body = `Mooré; Mossi`\n\n // Multiple languages\n case \"mul\":\n\t\tc.Body = `Multiple languages`\n\n // Collective name\n case \"mun\":\n\t\tc.Body = `Munda languages`\n\n // Creek\n case \"mus\":\n\t\tc.Body = `Creek`\n\n // ONIX local code, equivalent to mwf in ISO 639-3. For use in ONIX 3.0 only\n case \"mwf\":\n\t\tc.Body = `Murrinh-Patha`\n\n // Mirandese\n case \"mwl\":\n\t\tc.Body = `Mirandese`\n\n // Macrolanguage\n case \"mwr\":\n\t\tc.Body = `Marwari`\n\n // Collective name\n case \"myn\":\n\t\tc.Body = `Mayan languages`\n\n // Erzya\n case \"myv\":\n\t\tc.Body = `Erzya`\n\n // Collective name\n case \"nah\":\n\t\tc.Body = `Nahuatl languages`\n\n // Collective name\n case \"nai\":\n\t\tc.Body = `North American Indian languages`\n\n // Neapolitan\n case \"nap\":\n\t\tc.Body = `Neapolitan`\n\n // Nauruan\n case \"nau\":\n\t\tc.Body = `Nauruan`\n\n // Navajo\n case \"nav\":\n\t\tc.Body = `Navajo`\n\n // Ndebele, South\n case \"nbl\":\n\t\tc.Body = `Ndebele, South`\n\n // Ndebele, North\n case \"nde\":\n\t\tc.Body = `Ndebele, North`\n\n // Ndonga\n case \"ndo\":\n\t\tc.Body = `Ndonga`\n\n // Low German; Low Saxon\n case \"nds\":\n\t\tc.Body = `Low German; Low Saxon`\n\n // Macrolanguage\n case \"nep\":\n\t\tc.Body = `Nepali`\n\n // Newari; Nepal Bhasa\n case \"new\":\n\t\tc.Body = `Newari; Nepal Bhasa`\n\n // Nias\n case \"nia\":\n\t\tc.Body = `Nias`\n\n // Collective name\n case \"nic\":\n\t\tc.Body = `Niger-Kordofanian languages`\n\n // Niuean\n case \"niu\":\n\t\tc.Body = `Niuean`\n\n // Norwegian Nynorsk\n case \"nno\":\n\t\tc.Body = `Norwegian Nynorsk`\n\n // Norwegian Bokmål\n case \"nob\":\n\t\tc.Body = `Norwegian Bokmål`\n\n // Nogai\n case \"nog\":\n\t\tc.Body = `Nogai`\n\n // Old Norse\n case \"non\":\n\t\tc.Body = `Old Norse`\n\n // Macrolanguage\n case \"nor\":\n\t\tc.Body = `Norwegian`\n\n // N’Ko\n case \"nqo\":\n\t\tc.Body = `N’Ko`\n\n // ONIX local code, equivalent to nrf in ISO 639-3. For use in ONIX 3.0 only\n case \"nrf\":\n\t\tc.Body = `Guernésiais, Jèrriais`\n\n // Pedi; Sepedi; Northern Sotho\n case \"nso\":\n\t\tc.Body = `Pedi; Sepedi; Northern Sotho`\n\n // Collective name\n case \"nub\":\n\t\tc.Body = `Nubian languages`\n\n // Classical Newari; Old Newari; Classical Nepal Bhasa\n case \"nwc\":\n\t\tc.Body = `Classical Newari; Old Newari; Classical Nepal Bhasa`\n\n // Chichewa; Chewa; Nyanja\n case \"nya\":\n\t\tc.Body = `Chichewa; Chewa; Nyanja`\n\n // Nyamwezi\n case \"nym\":\n\t\tc.Body = `Nyamwezi`\n\n // Nyankole\n case \"nyn\":\n\t\tc.Body = `Nyankole`\n\n // Nyoro\n case \"nyo\":\n\t\tc.Body = `Nyoro`\n\n // Nzima\n case \"nzi\":\n\t\tc.Body = `Nzima`\n\n // Occitan (post 1500)\n case \"oci\":\n\t\tc.Body = `Occitan (post 1500)`\n\n // ONIX local code, equivalent to odt in ISO 639-3\n case \"odt\":\n\t\tc.Body = `Old Dutch / Old Low Franconian (ca. 400–1050)`\n\n // Macrolanguage\n case \"oji\":\n\t\tc.Body = `Ojibwa`\n\n // ONIX local code, equivalent to omq in ISO 639-5. Collective name\n case \"omq\":\n\t\tc.Body = `Oto-Manguean languages`\n\n // Macrolanguage\n case \"ori\":\n\t\tc.Body = `Oriya`\n\n // Macrolanguage\n case \"orm\":\n\t\tc.Body = `Oromo`\n\n // Osage\n case \"osa\":\n\t\tc.Body = `Osage`\n\n // Ossetian; Ossetic\n case \"oss\":\n\t\tc.Body = `Ossetian; Ossetic`\n\n // Turkish, Ottoman\n case \"ota\":\n\t\tc.Body = `Turkish, Ottoman`\n\n // Collective name\n case \"oto\":\n\t\tc.Body = `Otomian languages`\n\n // Collective name\n case \"paa\":\n\t\tc.Body = `Papuan languages`\n\n // Pangasinan\n case \"pag\":\n\t\tc.Body = `Pangasinan`\n\n // Pahlavi\n case \"pal\":\n\t\tc.Body = `Pahlavi`\n\n // Pampanga; Kapampangan\n case \"pam\":\n\t\tc.Body = `Pampanga; Kapampangan`\n\n // Panjabi\n case \"pan\":\n\t\tc.Body = `Panjabi`\n\n // Papiamento\n case \"pap\":\n\t\tc.Body = `Papiamento`\n\n // Palauan\n case \"pau\":\n\t\tc.Body = `Palauan`\n\n // Old Persian (ca. 600-400 B.C.)\n case \"peo\":\n\t\tc.Body = `Old Persian (ca. 600-400 B.C.)`\n\n // Macrolanguage\n case \"per\":\n\t\tc.Body = `Persian; Farsi`\n\n // ONIX local code, equivalent to pes in ISO 639-3. For use in ONIX 3.0 only\n case \"pes\":\n\t\tc.Body = `Iranian Persian; Parsi`\n\n // Collective name\n case \"phi\":\n\t\tc.Body = `Philippine languages`\n\n // Phoenician\n case \"phn\":\n\t\tc.Body = `Phoenician`\n\n // Pali\n case \"pli\":\n\t\tc.Body = `Pali`\n\n // ONIX local code for Italian dialect, equivalent to pms in ISO 639-3. For use in ONIX 3.0 only\n case \"pms\":\n\t\tc.Body = `Piedmontese`\n\n // Polish\n case \"pol\":\n\t\tc.Body = `Polish`\n\n // Ponapeian\n case \"pon\":\n\t\tc.Body = `Ponapeian`\n\n // Portuguese\n case \"por\":\n\t\tc.Body = `Portuguese`\n\n // Collective name\n case \"pra\":\n\t\tc.Body = `Prakrit languages`\n\n // Provençal, Old (to 1500); Occitan, Old (to 1500)\n case \"pro\":\n\t\tc.Body = `Provençal, Old (to 1500); Occitan, Old (to 1500)`\n\n // ONIX local code, equivalent to prs in ISO 639-3. For use in ONIX 3.0 only\n case \"prs\":\n\t\tc.Body = `Dari; Afghan Persian`\n\n // Macrolanguage\n case \"pus\":\n\t\tc.Body = `Pushto; Pashto`\n\n // ONIX local code, distinct dialect of Occitan (not distinguished from oci by ISO 639-3)\n case \"qar\":\n\t\tc.Body = `Aranés`\n\n // ONIX local code, distinct dialect of Catalan (not distinguished from cat by ISO 639-3)\n case \"qav\":\n\t\tc.Body = `Valencian`\n\n // ONIX local code, distinct variant of langue d’oïl (old northern French) (not distinguished from fro, or from frm, fre, nrf by ISO 639-3). For use in ONIX 3.0 only\n case \"qgl\":\n\t\tc.Body = `Gallo`\n\n // ONIX local code, distinct dialect of of Rusyn (not distinguished from rue by ISO 639-3). For use in ONIX 3.0 only\n case \"qlk\":\n\t\tc.Body = `Lemko`\n\n // ONIX local code, distinct and exclusively spoken variation of Spanish, not distinguished from spa (Spanish, Castilian) by ISO 639-3. Neutral Latin American Spanish should be considered a ‘shorthand’ for spa plus a ‘country code’ for Latin America – but prefer spa plus the relevant country code for specifically Mexican Spanish, Argentine (Rioplatense) Spanish, Puerto Rican Spanish etc. Neutral Latin American Spanish must only be used with audio material (including the audio tracks of TV, video and film) to indicate use of accent, vocabulary and construction suitable for broad use across Latin America. For use in ONIX 3.0 only\n case \"qls\":\n\t\tc.Body = `Neutral Latin American Spanish`\n\n // Macrolanguage\n case \"que\":\n\t\tc.Body = `Quechua`\n\n // Macrolanguage\n case \"raj\":\n\t\tc.Body = `Rajasthani`\n\n // Rapanui\n case \"rap\":\n\t\tc.Body = `Rapanui`\n\n // Rarotongan; Cook Islands Maori\n case \"rar\":\n\t\tc.Body = `Rarotongan; Cook Islands Maori`\n\n // ONIX local code, equivalent to rcf in ISO 639-3. For use in ONIX 3.0 only\n case \"rcf\":\n\t\tc.Body = `Réunion Creole French`\n\n // ONIX local code for Italian dialect, equivalent to rgl in ISO 639-3. For use in ONIX 3.0 only\n case \"rgn\":\n\t\tc.Body = `Romagnol`\n\n // Collective name\n case \"roa\":\n\t\tc.Body = `Romance languages`\n\n // Romansh\n case \"roh\":\n\t\tc.Body = `Romansh`\n\n // Macrolanguage\n case \"rom\":\n\t\tc.Body = `Romany`\n\n // Romanian\n case \"rum\":\n\t\tc.Body = `Romanian`\n\n // Rundi\n case \"run\":\n\t\tc.Body = `Rundi`\n\n // Aromanian; Arumanian; Macedo-Romanian\n case \"rup\":\n\t\tc.Body = `Aromanian; Arumanian; Macedo-Romanian`\n\n // Russian\n case \"rus\":\n\t\tc.Body = `Russian`\n\n // Sandawe\n case \"sad\":\n\t\tc.Body = `Sandawe`\n\n // Sango\n case \"sag\":\n\t\tc.Body = `Sango`\n\n // Yakut\n case \"sah\":\n\t\tc.Body = `Yakut`\n\n // Collective name\n case \"sai\":\n\t\tc.Body = `South American Indian languages`\n\n // Collective name\n case \"sal\":\n\t\tc.Body = `Salishan languages`\n\n // Samaritan Aramaic\n case \"sam\":\n\t\tc.Body = `Samaritan Aramaic`\n\n // Sanskrit\n case \"san\":\n\t\tc.Body = `Sanskrit`\n\n // Sasak\n case \"sas\":\n\t\tc.Body = `Sasak`\n\n // Santali\n case \"sat\":\n\t\tc.Body = `Santali`\n\n // DEPRECATED – use srp\n case \"scc\":\n\t\tc.Body = `Serbian`\n\n // Sicilian\n case \"scn\":\n\t\tc.Body = `Sicilian`\n\n // Scots\n case \"sco\":\n\t\tc.Body = `Scots`\n\n // DEPRECATED – use hrv\n case \"scr\":\n\t\tc.Body = `Croatian`\n\n // ONIX local code for Sardinian dialect, equivalent to sdc in ISO 639-3. For use in ONIX 3.0 only\n case \"sdc\":\n\t\tc.Body = `Sassarese`\n\n // ONIX local code for Sardinian dialect, equivalent to sdn in ISO 639-3. For use in ONIX 3.0 only\n case \"sdn\":\n\t\tc.Body = `Gallurese`\n\n // Selkup\n case \"sel\":\n\t\tc.Body = `Selkup`\n\n // Collective name\n case \"sem\":\n\t\tc.Body = `Semitic languages`\n\n // Irish, Old (to 1100)\n case \"sga\":\n\t\tc.Body = `Irish, Old (to 1100)`\n\n // Collective name\n case \"sgn\":\n\t\tc.Body = `Sign languages`\n\n // Shan\n case \"shn\":\n\t\tc.Body = `Shan`\n\n // Sidamo\n case \"sid\":\n\t\tc.Body = `Sidamo`\n\n // Sinhala; Sinhalese\n case \"sin\":\n\t\tc.Body = `Sinhala; Sinhalese`\n\n // Collective name\n case \"sio\":\n\t\tc.Body = `Siouan languages`\n\n // Collective name\n case \"sit\":\n\t\tc.Body = `Sino-Tibetan languages`\n\n // Collective name\n case \"sla\":\n\t\tc.Body = `Slavic languages`\n\n // Slovak\n case \"slo\":\n\t\tc.Body = `Slovak`\n\n // Slovenian\n case \"slv\":\n\t\tc.Body = `Slovenian`\n\n // Southern Sami\n case \"sma\":\n\t\tc.Body = `Southern Sami`\n\n // Northern Sami\n case \"sme\":\n\t\tc.Body = `Northern Sami`\n\n // Collective name\n case \"smi\":\n\t\tc.Body = `Sami languages`\n\n // Lule Sami\n case \"smj\":\n\t\tc.Body = `Lule Sami`\n\n // Inari Sami\n case \"smn\":\n\t\tc.Body = `Inari Sami`\n\n // Samoan\n case \"smo\":\n\t\tc.Body = `Samoan`\n\n // Skolt Sami\n case \"sms\":\n\t\tc.Body = `Skolt Sami`\n\n // Shona\n case \"sna\":\n\t\tc.Body = `Shona`\n\n // Sindhi\n case \"snd\":\n\t\tc.Body = `Sindhi`\n\n // Soninke\n case \"snk\":\n\t\tc.Body = `Soninke`\n\n // Sogdian\n case \"sog\":\n\t\tc.Body = `Sogdian`\n\n // Somali\n case \"som\":\n\t\tc.Body = `Somali`\n\n // Collective name\n case \"son\":\n\t\tc.Body = `Songhai languages`\n\n // Sotho; Sesotho\n case \"sot\":\n\t\tc.Body = `Sotho; Sesotho`\n\n // Spanish\n case \"spa\":\n\t\tc.Body = `Spanish`\n\n // Macrolanguage\n case \"srd\":\n\t\tc.Body = `Sardinian`\n\n // Sranan Tongo\n case \"srn\":\n\t\tc.Body = `Sranan Tongo`\n\n // ONIX local code for Sardinian dialect, equivalent to sro in ISO 639-3. For use in ONIX 3.0 only\n case \"sro\":\n\t\tc.Body = `Campidanese`\n\n // Serbian\n case \"srp\":\n\t\tc.Body = `Serbian`\n\n // Serer\n case \"srr\":\n\t\tc.Body = `Serer`\n\n // Collective name\n case \"ssa\":\n\t\tc.Body = `Nilo-Saharan languages`\n\n // Swazi; Swati\n case \"ssw\":\n\t\tc.Body = `Swazi; Swati`\n\n // Sukuma\n case \"suk\":\n\t\tc.Body = `Sukuma`\n\n // Sundanese\n case \"sun\":\n\t\tc.Body = `Sundanese`\n\n // Susu\n case \"sus\":\n\t\tc.Body = `Susu`\n\n // Sumerian\n case \"sux\":\n\t\tc.Body = `Sumerian`\n\n // Macrolanguage\n case \"swa\":\n\t\tc.Body = `Swahili`\n\n // Swedish\n case \"swe\":\n\t\tc.Body = `Swedish`\n\n // Classical Syriac\n case \"syc\":\n\t\tc.Body = `Classical Syriac`\n\n // Macrolanguage\n case \"syr\":\n\t\tc.Body = `Syriac`\n\n // Tahitian\n case \"tah\":\n\t\tc.Body = `Tahitian`\n\n // Collective name\n case \"tai\":\n\t\tc.Body = `Tai languages`\n\n // Tamil\n case \"tam\":\n\t\tc.Body = `Tamil`\n\n // Tatar\n case \"tat\":\n\t\tc.Body = `Tatar`\n\n // Telugu\n case \"tel\":\n\t\tc.Body = `Telugu`\n\n // Temne; Time\n case \"tem\":\n\t\tc.Body = `Temne; Time`\n\n // Terena\n case \"ter\":\n\t\tc.Body = `Terena`\n\n // Tetum\n case \"tet\":\n\t\tc.Body = `Tetum`\n\n // Tajik; Tajiki Persian\n case \"tgk\":\n\t\tc.Body = `Tajik; Tajiki Persian`\n\n // Tagalog\n case \"tgl\":\n\t\tc.Body = `Tagalog`\n\n // Thai\n case \"tha\":\n\t\tc.Body = `Thai`\n\n // Tibetan\n case \"tib\":\n\t\tc.Body = `Tibetan`\n\n // Tigré\n case \"tig\":\n\t\tc.Body = `Tigré`\n\n // Tigrinya\n case \"tir\":\n\t\tc.Body = `Tigrinya`\n\n // Tiv\n case \"tiv\":\n\t\tc.Body = `Tiv`\n\n // Tokelauan\n case \"tkl\":\n\t\tc.Body = `Tokelauan`\n\n // Artificial language\n case \"tlh\":\n\t\tc.Body = `Klingon; tlhIngan-Hol`\n\n // Tlingit\n case \"tli\":\n\t\tc.Body = `Tlingit`\n\n // Macrolanguage\n case \"tmh\":\n\t\tc.Body = `Tamashek`\n\n // Tonga (Nyasa)\n case \"tog\":\n\t\tc.Body = `Tonga (Nyasa)`\n\n // Tongan\n case \"ton\":\n\t\tc.Body = `Tongan`\n\n // Tok Pisin\n case \"tpi\":\n\t\tc.Body = `Tok Pisin`\n\n // Tsimshian\n case \"tsi\":\n\t\tc.Body = `Tsimshian`\n\n // AKA Setswana\n case \"tsn\":\n\t\tc.Body = `Tswana`\n\n // Tsonga\n case \"tso\":\n\t\tc.Body = `Tsonga`\n\n // Turkmen\n case \"tuk\":\n\t\tc.Body = `Turkmen`\n\n // Tumbuka\n case \"tum\":\n\t\tc.Body = `Tumbuka`\n\n // Collective name\n case \"tup\":\n\t\tc.Body = `Tupi languages`\n\n // Turkish\n case \"tur\":\n\t\tc.Body = `Turkish`\n\n // Altaic languages\n case \"tut\":\n\t\tc.Body = `Altaic languages`\n\n // Tuvaluan\n case \"tvl\":\n\t\tc.Body = `Tuvaluan`\n\n // Twi\n case \"twi\":\n\t\tc.Body = `Twi`\n\n // Tuvinian\n case \"tyv\":\n\t\tc.Body = `Tuvinian`\n\n // ONIX local code, equivalent to tzo in ISO 639-3\n case \"tzo\":\n\t\tc.Body = `Tzotzil`\n\n // Udmurt\n case \"udm\":\n\t\tc.Body = `Udmurt`\n\n // Ugaritic\n case \"uga\":\n\t\tc.Body = `Ugaritic`\n\n // Uighur; Uyghur\n case \"uig\":\n\t\tc.Body = `Uighur; Uyghur`\n\n // Ukrainian\n case \"ukr\":\n\t\tc.Body = `Ukrainian`\n\n // Umbundu\n case \"umb\":\n\t\tc.Body = `Umbundu`\n\n // Undetermined language\n case \"und\":\n\t\tc.Body = `Undetermined language`\n\n // Urdu\n case \"urd\":\n\t\tc.Body = `Urdu`\n\n // Macrolanguage\n case \"uzb\":\n\t\tc.Body = `Uzbek`\n\n // Vai\n case \"vai\":\n\t\tc.Body = `Vai`\n\n // ONIX local code for Italian dialect, equivalent to vec in ISO 639-3. For use in ONIX 3.0 only\n case \"vec\":\n\t\tc.Body = `Venetian/Venetan`\n\n // Venda\n case \"ven\":\n\t\tc.Body = `Venda`\n\n // Vietnamese\n case \"vie\":\n\t\tc.Body = `Vietnamese`\n\n // Artificial language\n case \"vol\":\n\t\tc.Body = `Volapük`\n\n // Votic\n case \"vot\":\n\t\tc.Body = `Votic`\n\n // Collective name\n case \"wak\":\n\t\tc.Body = `Wakashan languages`\n\n // Wolaitta; Wolaytta\n case \"wal\":\n\t\tc.Body = `Wolaitta; Wolaytta`\n\n // Waray\n case \"war\":\n\t\tc.Body = `Waray`\n\n // Washo\n case \"was\":\n\t\tc.Body = `Washo`\n\n // Welsh\n case \"wel\":\n\t\tc.Body = `Welsh`\n\n // Collective name\n case \"wen\":\n\t\tc.Body = `Sorbian languages`\n\n // Walloon\n case \"wln\":\n\t\tc.Body = `Walloon`\n\n // Wolof\n case \"wol\":\n\t\tc.Body = `Wolof`\n\n // Kalmyk\n case \"xal\":\n\t\tc.Body = `Kalmyk`\n\n // Xhosa\n case \"xho\":\n\t\tc.Body = `Xhosa`\n\n // ONIX local code, equivalent to xuu in ISO 639-3. For use in ONIX 3.0 only\n case \"xuu\":\n\t\tc.Body = `Khwedam, Kxoe`\n\n // Yao\n case \"yao\":\n\t\tc.Body = `Yao`\n\n // Yapese\n case \"yap\":\n\t\tc.Body = `Yapese`\n\n // Macrolanguage\n case \"yid\":\n\t\tc.Body = `Yiddish`\n\n // Yoruba\n case \"yor\":\n\t\tc.Body = `Yoruba`\n\n // Collective name\n case \"ypk\":\n\t\tc.Body = `Yupik languages`\n\n // ONIX local code, equivalent to yue in ISO 639-3\n case \"yue\":\n\t\tc.Body = `Cantonese`\n\n // Macrolanguage\n case \"zap\":\n\t\tc.Body = `Zapotec`\n\n // Artificial language\n case \"zbl\":\n\t\tc.Body = `Blissymbols; Blissymbolics; Bliss`\n\n // Zenaga\n case \"zen\":\n\t\tc.Body = `Zenaga`\n\n // Standard Moroccan Tamazight\n case \"zgh\":\n\t\tc.Body = `Standard Moroccan Tamazight`\n\n // Macrolanguage\n case \"zha\":\n\t\tc.Body = `Zhuang; Chuang`\n\n // Collective name\n case \"znd\":\n\t\tc.Body = `Zande languages`\n\n // Zulu\n case \"zul\":\n\t\tc.Body = `Zulu`\n\n // Zuni\n case \"zun\":\n\t\tc.Body = `Zuni`\n\n // No linguistic content\n case \"zxx\":\n\t\tc.Body = `No linguistic content`\n\n // Macrolanguage\n case \"zza\":\n\t\tc.Body = `Zaza; Dimili; Dimli; Kirdki; Kirmanjki; Zazaki`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for ToLanguage has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func XmlCtxtReadFile(ctxt *XmlParserCtxt, filename string, encoding string, options int) (g_ret *XmlDoc, err error) {\n\tvar c_ctxt C.xmlParserCtxtPtr = nil\n\tif ctxt != nil {\n\t\tc_ctxt = (C.xmlParserCtxtPtr)(ctxt.handler)\n\t}\n\tc_filename := (*C.char)(unsafe.Pointer(C.CString(filename)))\n\tdefer C.free(unsafe.Pointer(c_filename))\n\tc_encoding := (*C.char)(unsafe.Pointer(C.CString(encoding)))\n\tdefer C.free(unsafe.Pointer(c_encoding))\n\tc_options := C.int(options)\n\n\tc_ret := C.xmlCtxtReadFile(c_ctxt, c_filename, c_encoding, c_options)\n\n\tif c_ret == nil {\n\t\terr = fmt.Errorf(\"xmlCtxtReadFile errno %d\", c_ret)\n\t} else {\n\t\tg_ret = &XmlDoc{handler: (C.xmlDocPtr)(c_ret)}\n\t}\n\treturn\n}", "func (c *ResourceContentType) 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 // 2D\n case \"01\":\n\t\tc.Body = `Front cover`\n\n // 2D\n case \"02\":\n\t\tc.Body = `Back cover`\n\n // Not limited to front or back, including 3D perspective\n case \"03\":\n\t\tc.Body = `Cover / pack`\n\n // Photograph or portrait of contributor(s)\n case \"04\":\n\t\tc.Body = `Contributor picture`\n\n // Series image / artwork\n case \"05\":\n\t\tc.Body = `Series image / artwork`\n\n // Series logo\n case \"06\":\n\t\tc.Body = `Series logo`\n\n // For example, an isolated image from the front cover (without text), image of a completed jigsaw\n case \"07\":\n\t\tc.Body = `Product image / artwork`\n\n // Product logo\n case \"08\":\n\t\tc.Body = `Product logo`\n\n // Publisher logo\n case \"09\":\n\t\tc.Body = `Publisher logo`\n\n // Imprint logo\n case \"10\":\n\t\tc.Body = `Imprint logo`\n\n // Contributor interview\n case \"11\":\n\t\tc.Body = `Contributor interview`\n\n // Contributor presentation and/or commentary\n case \"12\":\n\t\tc.Body = `Contributor presentation`\n\n // Contributor reading\n case \"13\":\n\t\tc.Body = `Contributor reading`\n\n // Link to a schedule in iCalendar format\n case \"14\":\n\t\tc.Body = `Contributor event schedule`\n\n // For example: a short excerpt, sample text or a complete sample chapter, page images, screenshots etc\n case \"15\":\n\t\tc.Body = `Sample content`\n\n // A ‘look inside’ feature presented as a small embeddable application\n case \"16\":\n\t\tc.Body = `Widget`\n\n // Review text held in a separate downloadable file, not in the ONIX record. Equivalent of code 06 in List 153. Use the <TextContent> composite for review quotes carried in the ONIX record. Use the <CitedContent> composite for a third-party review which is referenced from the ONIX record. Use <SupportingResource> for review text offered as a separate file resource for reproduction as part of promotional material for the product\n case \"17\":\n\t\tc.Body = `Review`\n\n // Other commentary / discussion\n case \"18\":\n\t\tc.Body = `Other commentary / discussion`\n\n // Reading group guide\n case \"19\":\n\t\tc.Body = `Reading group guide`\n\n // Incuding associated teacher / instructor resources\n case \"20\":\n\t\tc.Body = `Teacher’s guide`\n\n // Feature article provided by publisher\n case \"21\":\n\t\tc.Body = `Feature article`\n\n // Fictional character ‘interview’\n case \"22\":\n\t\tc.Body = `Character ‘interview’`\n\n // Wallpaper / screensaver\n case \"23\":\n\t\tc.Body = `Wallpaper / screensaver`\n\n // Press release\n case \"24\":\n\t\tc.Body = `Press release`\n\n // A table of contents held in a separate downloadable file, not in the ONIX record. Equivalent of code 04 in List 153. Use the <TextContent> composite for a table of contents carried in the ONIX record. Use <Supporting Resource> for text offered as a separate file resource\n case \"25\":\n\t\tc.Body = `Table of contents`\n\n // A promotional video (or audio), similar to a movie trailer (sometimes referred to as a ‘book trailer’)\n case \"26\":\n\t\tc.Body = `Trailer`\n\n // Intended ONLY for transitional use, where ONIX 2.1 records referencing existing thumbnail assets of unknown pixel size are being re-expressed in ONIX 3.0. Use code 01 for all new cover assets, and where the pixel size of older assets is known\n case \"27\":\n\t\tc.Body = `Cover thumbnail`\n\n // The full content of the product (or the product itself), supplied for example to support full-text search or indexing\n case \"28\":\n\t\tc.Body = `Full content`\n\n // Includes cover, back cover, spine and – where appropriate – any flaps\n case \"29\":\n\t\tc.Body = `Full cover`\n\n // Master brand logo\n case \"30\":\n\t\tc.Body = `Master brand logo`\n\n // Descriptive text in a separate downloadable file, not in the ONIX record. Equivalent of code 03 in List 153. Use the <TextContent> composite for descriptions carried in the ONIX record. Use <Supporting Resource> for text offered as a separate file resource for reproduction as part of promotional material for the product\n case \"31\":\n\t\tc.Body = `Description`\n\n // Index text held in a separate downloadable file, not in the ONIX record. Equivalent of code 15 in List 153. Use the <TextContent> composite for index text carried in the ONIX record. Use <Supporting Resource> for an index offered as a separate file resource\n case \"32\":\n\t\tc.Body = `Index`\n\n // Including associated student / learner resources\n case \"33\":\n\t\tc.Body = `Student’s guide`\n\n // For example a PDF or other digital representation of a publisher’s ‘new titles’ or range catalogue\n case \"34\":\n\t\tc.Body = `Publisher’s catalogue`\n\n // For example a banner ad for the product. Pixel dimensions should typically be included in <ResourceVersionFeature>\n case \"35\":\n\t\tc.Body = `Online advertisement panel`\n\n // German ‘Búhnenbild’\n case \"36\":\n\t\tc.Body = `Online advertisement page`\n\n // For example, posters, logos, banners, advertising templates for use in connection with a promotional event\n case \"37\":\n\t\tc.Body = `Promotional event material`\n\n // Availability of a digital review or digital proof copy, may be limited to authorised users or account holders\n case \"38\":\n\t\tc.Body = `Digital review copy`\n\n // For example, video showing how to use the product\n case \"39\":\n\t\tc.Body = `Instructional material`\n\n // Errata\n case \"40\":\n\t\tc.Body = `Errata`\n\n // Introduction, preface or other preliminary material in a separate resource file\n case \"41\":\n\t\tc.Body = `Introduction`\n\n // Descriptive material in a separate resource file, not in the ONIX record. Equivalent of code 17 in List 153. Use the <TextContent> composite for collection descriptions carried in the ONIX record. Use <Supporting Resource> for material (which need not be solely only) offered as a separate file resource for reproduction as part of promotional material for the product and collection\n case \"42\":\n\t\tc.Body = `Collection description`\n\n // Complete list of books by the author(s), supplied as a separate resource file\n case \"43\":\n\t\tc.Body = `Bibliography`\n\n // Formal summary of content (normally used with academic and scholarly content only)\n case \"44\":\n\t\tc.Body = `Abstract`\n\n // Image that may be used for promotional purposes in place of a front cover, ONLY where the front cover itself cannot be provided or used for any reason. Typically, holding images may comprise logos, artwork or an unfinished front cover image. Senders should ensure removal of the holding image from the record as soon as a cover image is available. Recipients must ensure replacement of the holding image with the cover image when it is supplied\n case \"45\":\n\t\tc.Body = `Cover holding image`\n\n // Eg for a game, kit\n case \"46\":\n\t\tc.Body = `Rules or instructions`\n\n // Full transcript of audio or video content of the product\n case \"47\":\n\t\tc.Body = `Transcript`\n\n // Link to a license covering permitted usage of the product content. Deprecated in favor of <EpubLicense>. This was a temporary workaround in ONIX 3.0, and use of <EpubLicense> is strongly preferred\n case \"99\":\n\t\tc.Body = `License`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for ResourceContentType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *CollectionType) 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 // Collection type is not determined\n case \"00\":\n\t\tc.Body = `Unspecified (default)`\n\n // The collection is a bibliographic collection (eg a series or set (Fr. série)) defined and identified by a publisher, either on the product itself or in product information supplied by the publisher. The books in the collection generally share a subject, narrative, design style or authorship. They may may have a specific order, or the collection may be unordered\n case \"10\":\n\t\tc.Body = `Publisher collection`\n\n // The collection is a bibliographic collection defined and identified by a publisher, either on the product itself or in product information supplied by the publisher, where the books in the collection have no specific order, shared subject, narrative, style or shared authorship, and are grouped by the publisher largely for marketing purposes. The collection has many of the characteristics of an imprint or marque. Used primarily in French book publishing, to distinguish between ‘série’ (using the normal code 10) and ‘collection’ (code 11), and where the collection éditoriale is not an imprint\n case \"11\":\n\t\tc.Body = `Collection éditoriale`\n\n // The collection has been defined and identified by a party in the metadata supply chain other than the publisher, typically an aggregator.\n case \"20\":\n\t\tc.Body = `Ascribed collection`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for CollectionType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func DecodeXML(r io.Reader, v interface{}) error {\n\tdefer io.Copy(ioutil.Discard, r) //nolint:errcheck\n\treturn xml.NewDecoder(r).Decode(v)\n}", "func fromXml(xmlBytes []byte) (ResumeData, error) {\n\tvar data ResumeData\n\terr := xml.Unmarshal(xmlBytes, &data)\n\tif err == nil {\n\t\t// The marshal process in `toXml()` will use field tags to populate the `ResumeData.XMLName` field\n\t\t// with `resume`. When unmarshalling from XML, we likewise strip this field value back off... to\n\t\t// better facilitate equality comparison between `ResumeData` structs (e.g. in unit testing).\n\t\tdata.XMLName.Local = \"\"\n\t}\n\treturn data, err\n}", "func (c *DefaultCurrencyCode) 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 // United Arab Emirates\n case \"AED\":\n\t\tc.Body = `UAE Dirham`\n\n // Afghanistan. DEPRECATED, replaced by AFN\n case \"AFA\":\n\t\tc.Body = `Afghani`\n\n // Afghanistan (prices normally quoted as integers)\n case \"AFN\":\n\t\tc.Body = `Afghani`\n\n // Albania (prices normally quoted as integers)\n case \"ALL\":\n\t\tc.Body = `Lek`\n\n // Armenia (prices normally quoted as integers)\n case \"AMD\":\n\t\tc.Body = `Armenian Dram`\n\n // Curaçao, Sint Maarten\n case \"ANG\":\n\t\tc.Body = `Netherlands Antillian Guilder`\n\n // Angola\n case \"AOA\":\n\t\tc.Body = `Kwanza`\n\n // Argentina\n case \"ARS\":\n\t\tc.Body = `Argentine Peso`\n\n // Austria. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"ATS\":\n\t\tc.Body = `Schilling`\n\n // Australia, Christmas Island, Cocos (Keeling) Islands, Heard Island and McDonald Islands, Kiribati, Nauru, Norfolk Island, Tuvalu\n case \"AUD\":\n\t\tc.Body = `Australian Dollar`\n\n // Aruba\n case \"AWG\":\n\t\tc.Body = `Aruban Florin`\n\n // Azerbaijan\n case \"AZN\":\n\t\tc.Body = `Azerbaijan Manat`\n\n // Bosnia and Herzegovina\n case \"BAM\":\n\t\tc.Body = `Convertible Marks`\n\n // Barbados\n case \"BBD\":\n\t\tc.Body = `Barbados Dollar`\n\n // Bangladesh\n case \"BDT\":\n\t\tc.Body = `Taka`\n\n // Belgium. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"BEF\":\n\t\tc.Body = `Belgian Franc`\n\n // DEPRECATED, replaced by BGN\n case \"BGL\":\n\t\tc.Body = `Bulgarian Lev`\n\n // Bulgaria\n case \"BGN\":\n\t\tc.Body = `Bulgarian Lev`\n\n // Bahrain (prices normally quoted with 3 decimal places)\n case \"BHD\":\n\t\tc.Body = `Bahraini Dinar`\n\n // Burundi (prices normally quoted as integers)\n case \"BIF\":\n\t\tc.Body = `Burundi Franc`\n\n // Bermuda\n case \"BMD\":\n\t\tc.Body = `Bermudian Dollar`\n\n // Brunei Darussalam\n case \"BND\":\n\t\tc.Body = `Brunei Dollar`\n\n // Bolivia\n case \"BOB\":\n\t\tc.Body = `Boliviano`\n\n // Brazil\n case \"BRL\":\n\t\tc.Body = `Brazilian Real`\n\n // Bahamas\n case \"BSD\":\n\t\tc.Body = `Bahamian Dollar`\n\n // Bhutan\n case \"BTN\":\n\t\tc.Body = `Ngultrun`\n\n // Botswana\n case \"BWP\":\n\t\tc.Body = `Pula`\n\n // Belarus (prices normally quoted as integers). Deprecated – now replaced by new Belarussian Ruble (BYN): use only for historical prices that pre-date the introduction of the new Belarussian Ruble\n case \"BYR\":\n\t\tc.Body = `(Old) Belarussian Ruble`\n\n // Belarus\n case \"BYN\":\n\t\tc.Body = `Belarussian Ruble`\n\n // Belize\n case \"BZD\":\n\t\tc.Body = `Belize Dollar`\n\n // Canada\n case \"CAD\":\n\t\tc.Body = `Canadian Dollar`\n\n // Congo (Democratic Republic of the)\n case \"CDF\":\n\t\tc.Body = `Franc Congolais`\n\n // Switzerland, Liechtenstein\n case \"CHF\":\n\t\tc.Body = `Swiss Franc`\n\n // Chile (prices normally quoted as integers)\n case \"CLP\":\n\t\tc.Body = `Chilean Peso`\n\n // China\n case \"CNY\":\n\t\tc.Body = `Yuan Renminbi`\n\n // Colombia (prices normally quoted as integers)\n case \"COP\":\n\t\tc.Body = `Colombian Peso`\n\n // Costa Rica (prices normally quoted as integers)\n case \"CRC\":\n\t\tc.Body = `Costa Rican Colon`\n\n // Deprecated, replaced by RSD\n case \"CSD\":\n\t\tc.Body = `Serbian Dinar`\n\n // Cuba (alternative currency)\n case \"CUC\":\n\t\tc.Body = `Cuban Convertible Peso`\n\n // Cuba\n case \"CUP\":\n\t\tc.Body = `Cuban Peso`\n\n // Cabo Verde (prices normally quoted as integers)\n case \"CVE\":\n\t\tc.Body = `Cabo Verde Escudo`\n\n // Cyprus. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"CYP\":\n\t\tc.Body = `Cyprus Pound`\n\n // Czechia\n case \"CZK\":\n\t\tc.Body = `Czech Koruna`\n\n // Germany. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"DEM\":\n\t\tc.Body = `Mark`\n\n // Djibouti (prices normally quoted as integers)\n case \"DJF\":\n\t\tc.Body = `Djibouti Franc`\n\n // Denmark, Faroe Islands, Greenland\n case \"DKK\":\n\t\tc.Body = `Danish Krone`\n\n // Dominican Republic\n case \"DOP\":\n\t\tc.Body = `Dominican Peso`\n\n // Algeria\n case \"DZD\":\n\t\tc.Body = `Algerian Dinar`\n\n // Estonia.Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"EEK\":\n\t\tc.Body = `Kroon`\n\n // Egypt\n case \"EGP\":\n\t\tc.Body = `Egyptian Pound`\n\n // Eritrea\n case \"ERN\":\n\t\tc.Body = `Nakfa`\n\n // Spain. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro (prices normally quoted as integers)\n case \"ESP\":\n\t\tc.Body = `Peseta`\n\n // Ethiopia\n case \"ETB\":\n\t\tc.Body = `Ethiopian Birr`\n\n // Eurozone: Andorra, Austria, Belgium, Cyprus, Estonia, Finland, France, Fr Guiana, Fr S Territories, Germany, Greece, Guadeloupe, Holy See (Vatican City), Ireland, Italy, Latvia, Lithuania, Luxembourg, Martinique, Malta, Mayotte, Monaco, Montenegro, Netherlands, Portugal, Réunion, St Barthelemy, St Martin, St Pierre and Miquelon, San Marino, Slovakia, Slovenia, Spain\n case \"EUR\":\n\t\tc.Body = `Euro`\n\n // Finland. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"FIM\":\n\t\tc.Body = `Markka`\n\n // Fiji\n case \"FJD\":\n\t\tc.Body = `Fiji Dollar`\n\n // Falkland Islands (Malvinas)\n case \"FKP\":\n\t\tc.Body = `Falkland Islands Pound`\n\n // France. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"FRF\":\n\t\tc.Body = `Franc`\n\n // United Kingdom, Isle of Man, Channel Islands, South Georgia, South Sandwich Islands, British Indian Ocean Territory (de jure)\n case \"GBP\":\n\t\tc.Body = `Pound Sterling`\n\n // Georgia\n case \"GEL\":\n\t\tc.Body = `Lari`\n\n // Deprecated, replaced by GHS\n case \"GHC\":\n\t\tc.Body = `Ghana Cedi`\n\n // Ghana\n case \"GHS\":\n\t\tc.Body = `Ghana Cedi`\n\n // Gibraltar\n case \"GIP\":\n\t\tc.Body = `Gibraltar Pound`\n\n // Gambia\n case \"GMD\":\n\t\tc.Body = `Dalasi`\n\n // Guinea (prices normally quoted as integers)\n case \"GNF\":\n\t\tc.Body = `Guinean Franc`\n\n // Greece. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"GRD\":\n\t\tc.Body = `Drachma`\n\n // Guatemala\n case \"GTQ\":\n\t\tc.Body = `Quetzal`\n\n // Now replaced by the CFA Franc BCEAO XOF use only for historical prices that pre-date use of the CFA Franc\n case \"GWP\":\n\t\tc.Body = `Guinea-Bissau Peso`\n\n // Guyana (prices normally quoted as integers)\n case \"GYD\":\n\t\tc.Body = `Guyana Dollar`\n\n // Hong Kong\n case \"HKD\":\n\t\tc.Body = `Hong Kong Dollar`\n\n // Honduras\n case \"HNL\":\n\t\tc.Body = `Lempira`\n\n // Croatia\n case \"HRK\":\n\t\tc.Body = `Kuna`\n\n // Haiti\n case \"HTG\":\n\t\tc.Body = `Gourde`\n\n // Hungary (prices normally quoted as integers)\n case \"HUF\":\n\t\tc.Body = `Forint`\n\n // Indonesia (prices normally quoted as integers)\n case \"IDR\":\n\t\tc.Body = `Rupiah`\n\n // Ireland. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"IEP\":\n\t\tc.Body = `Punt`\n\n // Israel\n case \"ILS\":\n\t\tc.Body = `New Israeli Sheqel`\n\n // India, Bhutan (prices normally quoted as integers)\n case \"INR\":\n\t\tc.Body = `Indian Rupee`\n\n // Iraq (prices normally quoted as integers)\n case \"IQD\":\n\t\tc.Body = `Iraqi Dinar`\n\n // Iran (Islamic Republic of) (prices normally quoted as integers)\n case \"IRR\":\n\t\tc.Body = `Iranian Rial`\n\n // Iceland (prices normally quoted as integers)\n case \"ISK\":\n\t\tc.Body = `Iceland Krona`\n\n // Italy. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro (prices normally quoted as integers)\n case \"ITL\":\n\t\tc.Body = `Lira`\n\n // Jamaica\n case \"JMD\":\n\t\tc.Body = `Jamaican Dollar`\n\n // Jordan (prices normally quoted with 3 decimal places)\n case \"JOD\":\n\t\tc.Body = `Jordanian Dinar`\n\n // Japan (prices normally quoted as integers)\n case \"JPY\":\n\t\tc.Body = `Yen`\n\n // Kenya\n case \"KES\":\n\t\tc.Body = `Kenyan Shilling`\n\n // Kyrgyzstan\n case \"KGS\":\n\t\tc.Body = `Som`\n\n // Cambodia\n case \"KHR\":\n\t\tc.Body = `Riel`\n\n // Comoros (prices normally quoted as integers)\n case \"KMF\":\n\t\tc.Body = `Comorian Franc`\n\n // Korea (Democratic People’s Republic of) (prices normally quoted as integers)\n case \"KPW\":\n\t\tc.Body = `North Korean Won`\n\n // Korea (Republic of) (prices normally quoted as integers)\n case \"KRW\":\n\t\tc.Body = `Won`\n\n // Kuwait (prices normally quoted with 3 decimal places)\n case \"KWD\":\n\t\tc.Body = `Kuwaiti Dinar`\n\n // Cayman Islands\n case \"KYD\":\n\t\tc.Body = `Cayman Islands Dollar`\n\n // Kazakstan\n case \"KZT\":\n\t\tc.Body = `Tenge`\n\n // Lao People’s Democratic Republic (prices normally quoted as integers)\n case \"LAK\":\n\t\tc.Body = `Lao Kip`\n\n // Lebanon (prices normally quoted as integers)\n case \"LBP\":\n\t\tc.Body = `Lebanese Pound`\n\n // Sri Lanka\n case \"LKR\":\n\t\tc.Body = `Sri Lanka Rupee`\n\n // Liberia\n case \"LRD\":\n\t\tc.Body = `Liberian Dollar`\n\n // Lesotho\n case \"LSL\":\n\t\tc.Body = `Loti`\n\n // Lithuania. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"LTL\":\n\t\tc.Body = `Litus`\n\n // Luxembourg. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro (prices normally quoted as integers)\n case \"LUF\":\n\t\tc.Body = `Luxembourg Franc`\n\n // Latvia. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"LVL\":\n\t\tc.Body = `Latvian Lats`\n\n // Libyan Arab Jamahiriya (prices normally quoted with 3 decimal places)\n case \"LYD\":\n\t\tc.Body = `Libyan Dinar`\n\n // Morocco, Western Sahara\n case \"MAD\":\n\t\tc.Body = `Moroccan Dirham`\n\n // Moldova, Republic of\n case \"MDL\":\n\t\tc.Body = `Moldovan Leu`\n\n // Madagascar (prices normally quoted with 0 or 1 decimal place – 1 iraimbilanja = Ar0.2)\n case \"MGA\":\n\t\tc.Body = `Malagasy Ariary`\n\n // Now replaced by the Ariary (MGA) (prices normally quoted as integers)\n case \"MGF\":\n\t\tc.Body = `Malagasy Franc`\n\n // North Macedonia (formerly FYR Macedonia)\n case \"MKD\":\n\t\tc.Body = `Denar`\n\n // Myanmar (prices normally quoted as integers)\n case \"MMK\":\n\t\tc.Body = `Kyat`\n\n // Mongolia (prices normally quoted as integers)\n case \"MNT\":\n\t\tc.Body = `Tugrik`\n\n // Macau\n case \"MOP\":\n\t\tc.Body = `Pataca`\n\n // Mauritania (prices normally quoted with 0 or 1 decimal place – 1 khoums = UM0.2). Was interchangeable with MRU (New) Ouguiya at rate of 10:1 until June 2018. DEPRECATED, use MRU instead\n case \"MRO\":\n\t\tc.Body = `(Old) Ouguiya`\n\n // Mauritania (prices normally quoted with 0 or 1 decimal place – 1 khoums = UM0.2). Replaced MRO (old) Ouguiya at rate of 10:1 in June 2018. For use in ONIX 3.0 only\n case \"MRU\":\n\t\tc.Body = `Ouguiya`\n\n // Malta. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"MTL\":\n\t\tc.Body = `Maltese Lira`\n\n // Mauritius (prices normally quoted as integers)\n case \"MUR\":\n\t\tc.Body = `Mauritius Rupee`\n\n // Maldives\n case \"MVR\":\n\t\tc.Body = `Rufiyaa`\n\n // Malawi\n case \"MWK\":\n\t\tc.Body = `Malawi Kwacha`\n\n // Mexico\n case \"MXN\":\n\t\tc.Body = `Mexican Peso`\n\n // Malaysia\n case \"MYR\":\n\t\tc.Body = `Malaysian Ringgit`\n\n // Mozambique\n case \"MZN\":\n\t\tc.Body = `Mozambique Metical`\n\n // Namibia\n case \"NAD\":\n\t\tc.Body = `Namibia Dollar`\n\n // Nigeria\n case \"NGN\":\n\t\tc.Body = `Naira`\n\n // Nicaragua\n case \"NIO\":\n\t\tc.Body = `Cordoba Oro`\n\n // Netherlands. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"NLG\":\n\t\tc.Body = `Guilder`\n\n // Norway, Bouvet Island, Svalbard and Jan Mayen\n case \"NOK\":\n\t\tc.Body = `Norwegian Krone`\n\n // Nepal\n case \"NPR\":\n\t\tc.Body = `Nepalese Rupee`\n\n // New Zealand, Cook Islands, Niue, Pitcairn, Tokelau\n case \"NZD\":\n\t\tc.Body = `New Zealand Dollar`\n\n // Oman (prices normally quoted with 3 decimal places)\n case \"OMR\":\n\t\tc.Body = `Rial Omani`\n\n // Panama\n case \"PAB\":\n\t\tc.Body = `Balboa`\n\n // Peru (formerly Nuevo Sol)\n case \"PEN\":\n\t\tc.Body = `Sol`\n\n // Papua New Guinea\n case \"PGK\":\n\t\tc.Body = `Kina`\n\n // Philippines\n case \"PHP\":\n\t\tc.Body = `Philippine Peso`\n\n // Pakistan (prices normally quoted as integers)\n case \"PKR\":\n\t\tc.Body = `Pakistan Rupee`\n\n // Poland\n case \"PLN\":\n\t\tc.Body = `Złoty`\n\n // Portugal. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"PTE\":\n\t\tc.Body = `Escudo`\n\n // Paraguay (prices normally quoted as integers)\n case \"PYG\":\n\t\tc.Body = `Guarani`\n\n // Qatar\n case \"QAR\":\n\t\tc.Body = `Qatari Rial`\n\n // Deprecated, replaced by RON\n case \"ROL\":\n\t\tc.Body = `Romanian Old Leu`\n\n // Romania\n case \"RON\":\n\t\tc.Body = `Romanian Leu`\n\n // Serbia (prices normally quoted as integers)\n case \"RSD\":\n\t\tc.Body = `Serbian Dinar`\n\n // Russian Federation\n case \"RUB\":\n\t\tc.Body = `Russian Ruble`\n\n // DEPRECATED, replaced by RUB\n case \"RUR\":\n\t\tc.Body = `Russian Ruble`\n\n // Rwanda (prices normally quoted as integers)\n case \"RWF\":\n\t\tc.Body = `Rwanda Franc`\n\n // Saudi Arabia\n case \"SAR\":\n\t\tc.Body = `Saudi Riyal`\n\n // Solomon Islands\n case \"SBD\":\n\t\tc.Body = `Solomon Islands Dollar`\n\n // Seychelles\n case \"SCR\":\n\t\tc.Body = `Seychelles Rupee`\n\n // Now replaced by the Sudanese Pound (SDG)\n case \"SDD\":\n\t\tc.Body = `Sudanese Dinar`\n\n // Sudan\n case \"SDG\":\n\t\tc.Body = `Sudanese Pound`\n\n // Sweden\n case \"SEK\":\n\t\tc.Body = `Swedish Krona`\n\n // Singapore\n case \"SGD\":\n\t\tc.Body = `Singapore Dollar`\n\n // Saint Helena\n case \"SHP\":\n\t\tc.Body = `Saint Helena Pound`\n\n // Slovenia. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"SIT\":\n\t\tc.Body = `Tolar`\n\n // Slovakia. Now replaced by the Euro (EUR). Deprecated – use only for historical prices that pre-date the introduction of the Euro\n case \"SKK\":\n\t\tc.Body = `Slovak Koruna`\n\n // Sierra Leone (prices normally quoted as integers)\n case \"SLL\":\n\t\tc.Body = `Leone`\n\n // Somalia (prices normally quoted as integers)\n case \"SOS\":\n\t\tc.Body = `Somali Shilling`\n\n // Suriname\n case \"SRD\":\n\t\tc.Body = `Surinam Dollar`\n\n // DEPRECATED, replaced by SRD\n case \"SRG\":\n\t\tc.Body = `Suriname Guilder`\n\n // São Tome and Principe (prices normally quoted as integers). Was interchangeable with STN (New) Dobra at rate of 1000:1 until June 2018. DEPRECATED, use STN instead\n case \"STD\":\n\t\tc.Body = `(Old) Dobra`\n\n // São Tome and Principe. Replaced STD (old) Dobra at rate of 1000:1 in June 2018. For use in ONIX 3.0 only\n case \"STN\":\n\t\tc.Body = `Dobra`\n\n // El Salvador\n case \"SVC\":\n\t\tc.Body = `El Salvador Colon`\n\n // Syrian Arab Republic (prices normally quoted as integers)\n case \"SYP\":\n\t\tc.Body = `Syrian Pound`\n\n // Eswatini (formerly known as Swaziland)\n case \"SZL\":\n\t\tc.Body = `Lilangeni`\n\n // Thailand\n case \"THB\":\n\t\tc.Body = `Baht`\n\n // Tajikistan\n case \"TJS\":\n\t\tc.Body = `Somoni`\n\n // Deprecated, replaced by TMT (prices normally quoted as integers)\n case \"TMM\":\n\t\tc.Body = `Turkmenistan Manat`\n\n // Turkmenistan\n case \"TMT\":\n\t\tc.Body = `Turkmenistan New Manat`\n\n // Tunisia (prices normally quoted with 3 decimal places)\n case \"TND\":\n\t\tc.Body = `Tunisian Dinar`\n\n // Tonga\n case \"TOP\":\n\t\tc.Body = `Pa’anga`\n\n // Deprecated. Timor-Leste now uses the US Dollar\n case \"TPE\":\n\t\tc.Body = `Timor Escudo`\n\n // Deprecated, replaced by TRY (prices normally quoted as integers)\n case \"TRL\":\n\t\tc.Body = `Turkish Lira (old)`\n\n // Turkey, from 1 January 2005\n case \"TRY\":\n\t\tc.Body = `Turkish Lira`\n\n // Trinidad and Tobago\n case \"TTD\":\n\t\tc.Body = `Trinidad and Tobago Dollar`\n\n // Taiwan (Province of China)\n case \"TWD\":\n\t\tc.Body = `New Taiwan Dollar`\n\n // Tanzania (United Republic of) (prices normally quoted as integers)\n case \"TZS\":\n\t\tc.Body = `Tanzanian Shilling`\n\n // Ukraine\n case \"UAH\":\n\t\tc.Body = `Hryvnia`\n\n // Uganda (prices normally quoted as integers)\n case \"UGX\":\n\t\tc.Body = `Uganda Shilling`\n\n // United States, American Samoa, Bonaire, Sint Eustatius and Saba, British Indian Ocean Territory, Ecuador, El Salvador, Guam, Haiti, Marshall Is, Micronesia (Federated States of), Northern Mariana Is, Palau, Panama, Puerto Rico, Timor-Leste, Turks and Caicos Is, US Minor Outlying Is, Virgin Is (British), Virgin Is (US)\n case \"USD\":\n\t\tc.Body = `US Dollar`\n\n // Uruguay\n case \"UYU\":\n\t\tc.Body = `Peso Uruguayo`\n\n // Uzbekistan (prices normally quoted as integers)\n case \"UZS\":\n\t\tc.Body = `Uzbekistan Sum`\n\n // Deprecated, replaced by VEF\n case \"VEB\":\n\t\tc.Body = `Bolívar`\n\n // Venezuela (formerly Bolívar fuerte). Deprecated, replaced by VES\n case \"VEF\":\n\t\tc.Body = `Bolívar`\n\n // Venezuela (replaced VEF from August 2018 at rate of 100,000:1). For use in ONIX 3.0 only\n case \"VES\":\n\t\tc.Body = `Bolívar Soberano`\n\n // Viet Nam (prices normally quoted as integers)\n case \"VND\":\n\t\tc.Body = `Dong`\n\n // Vanuatu (prices normally quoted as integers)\n case \"VUV\":\n\t\tc.Body = `Vatu`\n\n // Samoa\n case \"WST\":\n\t\tc.Body = `Tala`\n\n // Cameroon, Central African Republic, Chad, Congo, Equatorial Guinea, Gabon (prices normally quoted as integers)\n case \"XAF\":\n\t\tc.Body = `CFA Franc BEAC`\n\n // Anguilla, Antigua and Barbuda, Dominica, Grenada, Montserrat, Saint Kitts and Nevis, Saint Lucia, Saint Vincent and the Grenadines\n case \"XCD\":\n\t\tc.Body = `East Caribbean Dollar`\n\n // Benin, Burkina Faso, Côte D’Ivoire, Guinea-Bissau, Mali, Niger, Senegal, Togo (prices normally quoted as integers)\n case \"XOF\":\n\t\tc.Body = `CFA Franc BCEAO`\n\n // French Polynesia, New Caledonia, Wallis and Futuna (prices normally quoted as integers)\n case \"XPF\":\n\t\tc.Body = `CFP Franc`\n\n // Yemen (prices normally quoted as integers)\n case \"YER\":\n\t\tc.Body = `Yemeni Rial`\n\n // DEPRECATED, replaced by CSD\n case \"YUM\":\n\t\tc.Body = `Yugoslavian Dinar`\n\n // South Africa, Namibia, Lesotho\n case \"ZAR\":\n\t\tc.Body = `Rand`\n\n // Zambia. Deprecated, replaced with ZMW (prices normally quoted as integers)\n case \"ZMK\":\n\t\tc.Body = `Kwacha`\n\n // Zambia\n case \"ZMW\":\n\t\tc.Body = `Zambian Kwacha`\n\n // Deprecated, replaced with ZWL (prices normally quoted as integers)\n case \"ZWD\":\n\t\tc.Body = `Zimbabwe Dollar`\n\n // Zimbabwe\n case \"ZWL\":\n\t\tc.Body = `Zimbabwe Dollar`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for DefaultCurrencyCode has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *TitleElementLevel) 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 // The title element refers to an individual product\n case \"01\":\n\t\tc.Body = `Product`\n\n // The title element refers to the top level of a bibliographic collection\n case \"02\":\n\t\tc.Body = `Collection level`\n\n // The title element refers to an intermediate level of a bibliographic collection that comprises two or more ‘sub-collections’\n case \"03\":\n\t\tc.Body = `Subcollection`\n\n // The title element refers to a content item within a product, eg a work included in a combined or ‘omnibus’ edition, or a chapter in a book. Generally used only for titles within <ContentItem> (Block 3)\n case \"04\":\n\t\tc.Body = `Content item`\n\n // The title element names a master brand where the use of the brand spans multiple collections and product forms, and possibly multiple imprints and publishers. Used only for branded media properties carrying, for example, a children’s character brand\n case \"05\":\n\t\tc.Body = `Master brand`\n\n // The title element refers to an intermediate level of a bibliographic collection that is a subdivision of a sub-collection (a third level of collective identity)\n case \"06\":\n\t\tc.Body = `Sub-subcollection`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for TitleElementLevel has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func isXML(docNodeName string) DetectFunc {\n\treturn func(p []byte) bool {\n\t\td := xml.NewDecoder(bytes.NewReader(p))\n\t\tdoc, err := nextStartElement(d)\n\t\treturn err == nil && doc.Name.Local == docNodeName\n\t}\n}", "func XmlReadMemory(buffer string, URL string, encoding string, options int) (g_ret *XmlDoc, err error) {\n\tc_buffer := (*C.char)(unsafe.Pointer(C.CString(buffer)))\n\tdefer C.free(unsafe.Pointer(c_buffer))\n\tc_URL := (*C.char)(unsafe.Pointer(C.CString(URL)))\n\tdefer C.free(unsafe.Pointer(c_URL))\n\tc_encoding := (*C.char)(unsafe.Pointer(C.CString(encoding)))\n\tdefer C.free(unsafe.Pointer(c_encoding))\n\tc_options := C.int(options)\n\tc_size := C.int(len(buffer) * 1)\n\tc_ret := C.xmlReadMemory(c_buffer, c_size, c_URL, c_encoding, c_options)\n\n\tif c_ret == nil {\n\t\terr = fmt.Errorf(\"xmlReadMemory errno %d\", c_ret)\n\t} else {\n\t\tg_ret = &XmlDoc{handler: (C.xmlDocPtr)(c_ret)}\n\t}\n\treturn\n}", "func (c *ReligiousTextFeatureType) 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 // A church season or activity for which a religious text is intended. Religious text feature code must be taken from List 90\n case \"01\":\n\t\tc.Body = `Church season or activity`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for ReligiousTextFeatureType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *BibleTextOrganization) 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 // A Bible with the text organized in the order in which events are believed to have happened\n case \"CHR\":\n\t\tc.Body = `Chronological`\n\n // A Bible which explores keywords or themes by referring text to preceding or following text\n case \"CHA\":\n\t\tc.Body = `Chain reference`\n\n // A Bible or other text in which different versions are printed one line above the other, so that the variations can easily be detected\n case \"INT\":\n\t\tc.Body = `Interlinear`\n\n // A Bible with two or more versions printed side by side\n case \"PAR\":\n\t\tc.Body = `Parallel`\n\n // A Bible in which the text is presented in the traditional order\n case \"STN\":\n\t\tc.Body = `Standard`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for BibleTextOrganization has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (xs *Stylesheet) Transform(xml []byte) ([]byte, error) {\n\n\tvar (\n\t\tcxml *C.char\n\t\tcout *C.char\n\t\tret C.int\n\t\tsize C.size_t\n\t)\n\n\tcxml = C.CString(string(xml))\n\tdefer C.free(unsafe.Pointer(cxml))\n\n\tret = C.apply_style(xs.ptr, cxml, &cout, &size)\n\tif ret != 0 {\n\t\tdefer C.free(unsafe.Pointer(cout))\n\t\treturn nil, ErrXSLTFailure\n\t}\n\n\tptr := unsafe.Pointer(cout)\n\tdefer C.free(ptr)\n\n\treturn C.GoBytes(ptr, C.int(size)), nil\n}", "func (f *Font) GetCharset() string { return f.charset }", "func Parse(xmlFileBytes []byte) ([]byte, error) {\n\tvar cs cheatsheet;\n\tif marshalErr := xml.Unmarshal(xmlFileBytes, &cs); marshalErr != nil {\n\t\treturn nil, marshalErr\n\t}\n\tfmt.Println(cs.Title)\n\n\tt, parseErr := template.ParseFiles(getTemplatePath());\n\tif parseErr != nil {\n\t\treturn nil, parseErr\n\t}\n\n\tvar tpl bytes.Buffer\n\tif executeErr := t.Execute(&tpl, cs); executeErr != nil {\n\t\treturn nil, executeErr\n\t}\n\n\treturn tpl.Bytes(), nil\n}", "func (*XMLDocument) InputEncoding() (inputEncoding string) {\n\tmacro.Rewrite(\"$_.inputEncoding\")\n\treturn inputEncoding\n}", "func XmlReadFile(URL string, encoding string, options int) (g_ret *XmlDoc, err error) {\n\tc_URL := (*C.char)(unsafe.Pointer(C.CString(URL)))\n\tdefer C.free(unsafe.Pointer(c_URL))\n\tc_encoding := (*C.char)(unsafe.Pointer(C.CString(encoding)))\n\tdefer C.free(unsafe.Pointer(c_encoding))\n\tc_options := C.int(options)\n\n\tc_ret := C.xmlReadFile(c_URL, c_encoding, c_options)\n\n\tif c_ret == nil {\n\t\terr = fmt.Errorf(\"xmlReadFile errno %d\", c_ret)\n\t} else {\n\t\tg_ret = &XmlDoc{handler: (C.xmlDocPtr)(c_ret)}\n\t}\n\treturn\n}", "func ParseContentString(text string) (*Appcast, error) {\n\tvar appcast = New()\n\tif err := xml.Unmarshal([]byte(text), appcast); err != nil {\n\t\treturn nil, err\n\t}\n\treturn appcast, nil\n}", "func (c *ThesisType) 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 // Professorial dissertation (thesis for postdoctoral lecturing qualification)\n case \"01\":\n\t\tc.Body = `Habilitationsschrift`\n\n // Doctoral thesis\n case \"02\":\n\t\tc.Body = `Dissertationsschrift`\n\n // State examination thesis\n case \"03\":\n\t\tc.Body = `Staatsexamensarbeit`\n\n // Magisters degree thesis\n case \"04\":\n\t\tc.Body = `Magisterarbeit`\n\n // Diploma degree thesis\n case \"05\":\n\t\tc.Body = `Diplomarbeit`\n\n // Bachelors degree thesis\n case \"06\":\n\t\tc.Body = `Bachelorarbeit`\n\n // Masters degree thesis\n case \"07\":\n\t\tc.Body = `Masterarbeit`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for ThesisType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *TextItemType) 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 // A complete work which is published as a content item in a product which carries two or more such works, eg when two or three novels are published in a single omnibus volume\n case \"01\":\n\t\tc.Body = `Textual work`\n\n // Text components such as Preface, Introduction etc which appear as preliminaries to the main body of text content in a product\n case \"02\":\n\t\tc.Body = `Front matter`\n\n // Text components such as Part, Chapter, Section etc which appear as part of the main body of text content in a product\n case \"03\":\n\t\tc.Body = `Body matter`\n\n // Text components such as Index which appear after the main body of text in a product\n case \"04\":\n\t\tc.Body = `Back matter`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for TextItemType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func FromHTML(content []byte) string {\n\tif cset := FromBOM(content); cset != \"\" {\n\t\treturn cset\n\t}\n\tif cset := fromHTML(content); cset != \"\" {\n\t\treturn cset\n\t}\n\treturn FromPlain(content)\n}", "func DecodeXMLCharEl(d *xml.Decoder) (name, val string, err error) {\n\tvar st xml.StartElement\n\tst, err = DecodeXMLStartEl(d)\n\tif err != nil {\n\t\treturn\n\t}\n\tname = st.Name.Local\n\tval, err = DecodeXMLCharData(d)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = DecodeXMLEndEl(d, st)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (c *EpubLicenseExpressionType) 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 // Document (eg Word file, PDF or web page) Intended for the lay reader\n case \"01\":\n\t\tc.Body = `Human readable`\n\n // Document (eg Word file, PDF or web page) Intended for the legal specialist reader\n case \"02\":\n\t\tc.Body = `Professional readable`\n\n // ONIX-PL\n case \"10\":\n\t\tc.Body = `ONIX-PL`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for EpubLicenseExpressionType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *ContentAudience) 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 // Any audience\n case \"00\":\n\t\tc.Body = `Unrestricted`\n\n // Distribution by agreement between the parties to the ONIX exchange (this value is provided to cover applications where ONIX content includes material which is not for general distribution)\n case \"01\":\n\t\tc.Body = `Restricted`\n\n // Distributors, bookstores, publisher’s own staff etc\n case \"02\":\n\t\tc.Body = `Booktrade`\n\n // End-customers\n case \"03\":\n\t\tc.Body = `End-customers`\n\n // Librarians\n case \"04\":\n\t\tc.Body = `Librarians`\n\n // Teachers\n case \"05\":\n\t\tc.Body = `Teachers`\n\n // Students\n case \"06\":\n\t\tc.Body = `Students`\n\n // Press or other media\n case \"07\":\n\t\tc.Body = `Press`\n\n // Where a specially formatted description is required for this audience\n case \"08\":\n\t\tc.Body = `Shopping comparison service`\n\n // Text not intended for display, but may be used (in addition to any less restricted text) for indexing and search\n case \"09\":\n\t\tc.Body = `Search engine index`\n\n // (Including vloggers, influencers etc) Where this is distinct from end customers or the Press\n case \"10\":\n\t\tc.Body = `Bloggers`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for ContentAudience has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *BibleContents) 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 // The seven portions of the Apocrypha added to the Catholic canon at the Council of Trent in 1546: Tobit; Judith; Wisdom of Solomon; Sirach (Ecclesiasticus); Baruch, including the Letter of Jeremiah; I and II Maccabees; Extra portions of Esther and Daniel (Additions to Esther; the Prayer of Azariah; Song of the Three Jews; Susannah; Bel and the Dragon). These are not generally included in the Protestant canon\n case \"AP\":\n\t\tc.Body = `Apocrypha (Catholic canon)`\n\n // A collection of Apocryphal texts, canon not specified\n case \"AQ\":\n\t\tc.Body = `Apocrypha (canon unspecified)`\n\n // I Esdras; Prayer of Manasseh; Psalm 151; III Maccabees\n case \"AX\":\n\t\tc.Body = `Additional Apocryphal texts: Greek Orthodox canon`\n\n // I and II Esdras; Prayer of Manasseh; Psalm 151; III and IV Maccabees\n case \"AY\":\n\t\tc.Body = `Additional Apocryphal texts: Slavonic Orthodox canon`\n\n // Additional Apocryphal texts included in some Bible versions: I and II Esdras; Prayer of Manasseh\n case \"AZ\":\n\t\tc.Body = `Additional Apocryphal texts`\n\n // The 66 books included in the Protestant, Catholic and Orthodox canons, together with the seven portions of the Apocrypha included in the Catholic canon. (Equivalent to OT plus NT plus AP)\n case \"GA\":\n\t\tc.Body = `General canon with Apocrypha (Catholic canon)`\n\n // The 66 books included in the Protestant, Catholic and Orthodox canons, together with Apocryphal texts, canon not specified. (Equivalent to OT plus NT plus AQ)\n case \"GC\":\n\t\tc.Body = `General canon with Apocryphal texts (canon unspecified)`\n\n // The 66 books included in the Protestant, Catholic and Orthodox canons, 39 from the Old Testament and 27 from the New Testament. The sequence of books may differ in different canons. (Equivalent to OT plus NT)\n case \"GE\":\n\t\tc.Body = `General canon`\n\n // The books of Matthew, Mark, Luke and John\n case \"GS\":\n\t\tc.Body = `Gospels`\n\n // Those 39 books which were included in the Jewish canon by the rabbinical academy established at Jamma in 90 CE. Also known as the Jewish or Hebrew scriptures\n case \"OT\":\n\t\tc.Body = `Old Testament`\n\n // The 27 books included in the Christian canon through the Easter Letter of Athanasius, Bishop of Alexandria and also by a general council of the Christian church held near the end of the 4th century CE\n case \"NT\":\n\t\tc.Body = `New Testament`\n\n // Includes the 27 books of the New Testament plus Psalms and Proverbs from the Old Testament. Equivalent to NT plus PP)\n case \"NP\":\n\t\tc.Body = `New Testament with Psalms and Proverbs`\n\n // The books containing the letters of Paul to the various early Christian churches\n case \"PE\":\n\t\tc.Body = `Paul’s Epistles`\n\n // The book of Psalms and the book of Proverbs combined\n case \"PP\":\n\t\tc.Body = `Psalms and Proverbs`\n\n // The book of Psalms\n case \"PS\":\n\t\tc.Body = `Psalms`\n\n // The first five books of the Bible: Genesis, Exodus, Numbers, Leviticus, Deuteronomy. Also applied to the Torah\n case \"PT\":\n\t\tc.Body = `Pentateuch`\n\n // Selected books of either the OT or NT not otherwise noted\n case \"ZZ\":\n\t\tc.Body = `Other portions`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for BibleContents has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *BarcodeType) 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 // Not barcoded\n case \"00\":\n\t\tc.Body = `Not barcoded`\n\n // Barcoded, scheme unspecified\n case \"01\":\n\t\tc.Body = `Barcoded, scheme unspecified`\n\n // GTIN-13\n case \"02\":\n\t\tc.Body = `GTIN-13`\n\n // GTIN-13+5 (US dollar price encoded)\n case \"03\":\n\t\tc.Body = `GTIN-13+5 (US dollar price encoded)`\n\n // GTIN-13+5 (CAN dollar price encoded)\n case \"04\":\n\t\tc.Body = `GTIN-13+5 (CAN dollar price encoded)`\n\n // GTIN-13+5 (no price encoded)\n case \"05\":\n\t\tc.Body = `GTIN-13+5 (no price encoded)`\n\n // AKA item/price\n case \"06\":\n\t\tc.Body = `UPC-12 (item-specific)`\n\n // AKA item/price\n case \"07\":\n\t\tc.Body = `UPC-12+5 (item-specific)`\n\n // AKA price/item\n case \"08\":\n\t\tc.Body = `UPC-12 (price-point)`\n\n // AKA price/item\n case \"09\":\n\t\tc.Body = `UPC-12+5 (price-point)`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for BarcodeType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func xmlDecoder(body io.Reader, v interface{}) error {\n\td := xml.NewDecoder(body)\n\treturn d.Decode(v)\n}", "func xmlDecoder(body io.Reader, v interface{}) error {\n\td := xml.NewDecoder(body)\n\treturn d.Decode(v)\n}", "func (c *SourceTypeCode) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for SourceTypeCode has been passed, got [%s]\", v)\n\t}\n}", "func (downloader *HTTPDownloader) changeCharsetEncodingAuto(contentTypeStr string, sor io.ReadCloser) string {\r\n\tvar err error\r\n\tdestReader, err := charset.NewReader(sor, contentTypeStr)\r\n\r\n\tif err != nil {\r\n\t\tmlog.LogInst().LogError(err.Error())\r\n\t\tdestReader = sor\r\n\t}\r\n\r\n\tvar sorbody []byte\r\n\tif sorbody, err = ioutil.ReadAll(destReader); err != nil {\r\n\t\tmlog.LogInst().LogError(err.Error())\r\n\t\t// For gb2312, an error will be returned.\r\n\t\t// Error like: simplifiedchinese: invalid GBK encoding\r\n\t\t// return \"\"\r\n\t}\r\n\t//e,name,certain := charset.DetermineEncoding(sorbody,contentTypeStr)\r\n\tbodystr := string(sorbody)\r\n\r\n\treturn bodystr\r\n}", "func ExtractXML(jsdata []byte) ([]byte, error) {\n\tvar kc KCode\n\tif err := json.Unmarshal(jsdata, &kc); err != nil {\n\t\treturn nil, errInvalidJSON\n\t}\n\t// Extract and return []byte \"source\" from .kcode file which is well formed JSON per KCode struct\n\tkcode := []byte(kc.Source)\n\treturn kcode, nil\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 (p *Parser) CharsetReader(c string, i io.Reader) (r io.Reader, e error) {\n\tswitch c {\n\tcase \"windows-1251\":\n\t\tr = decodeWin1251(i)\n\t}\n\treturn\n}", "func (c *CollectionSequenceType) 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 // A short explanatory label for the sequence should be provided in <CollectionSequenceTypeName>\n case \"01\":\n\t\tc.Body = `Proprietary`\n\n // Order as specified by the title, eg by volume or part number sequence, provided for confirmation\n case \"02\":\n\t\tc.Body = `Title order`\n\n // Order of publication of products within the collection\n case \"03\":\n\t\tc.Body = `Publication order`\n\n // Order defined by a continuing narrative or temporal sequence within products in the collection. Applicable to either fiction or to non-fiction (eg within a collection of history textbooks)\n case \"04\":\n\t\tc.Body = `Temporal/narrative order`\n\n // Original publication order, for a republished collection or collected works originally published outside a collection\n case \"05\":\n\t\tc.Body = `Original publication order`\n\n // Where it is different from the title order, publication order, narrative order etc\n case \"06\":\n\t\tc.Body = `Suggested reading order`\n\n // Where it is different from the title order, publication order, narrative order, reading order etc\n case \"07\":\n\t\tc.Body = `Suggested display order`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for CollectionSequenceType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (s *ResponseModifier) DecodeXML(userStruct interface{}, charsetReader XMLCharDecoder) error {\n\tbuf, err := s.ReadBytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\txmlDecoder := xml.NewDecoder(bytes.NewReader(buf))\n\tif charsetReader != nil {\n\t\txmlDecoder.CharsetReader = charsetReader\n\t}\n\tif err := xmlDecoder.Decode(&userStruct); err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *CurrencyZone) 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 // Countries that at the time being have the Euro as their national currency. Deprecated\n case \"EUR\":\n\t\tc.Body = `Eurozone`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for CurrencyZone has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func (c *StyleSheet) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for StyleSheet has been passed, got [%s]\", v)\n\t}\n}", "func (c *SourceType) 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 // Printed media\n case \"01\":\n\t\tc.Body = `Printed media`\n\n // Website\n case \"02\":\n\t\tc.Body = `Website`\n\n // Radio\n case \"03\":\n\t\tc.Body = `Radio`\n\n // TV\n case \"04\":\n\t\tc.Body = `TV`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for SourceType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func DecodeXML(r *http.Request, maxMemory int64, v interface{}) (err error) {\n\treturn xml.NewDecoder(io.LimitReader(r.Body, maxMemory)).Decode(v)\n}", "func (xpm *XMLProcessorManager) ProcessXML(reader io.Reader) {\n\tdecoder := xml.NewDecoder(reader)\n\tvar curData xml.CharData\n\tcurPath := NewXMLPath()\n\n\tfor {\n\t\ttk, err := decoder.Token()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tswitch tk.(type) {\n\t\tcase xml.StartElement:\n\t\t\tstartElem, _ := tk.(xml.StartElement)\n\t\t\tcurPath.AddChild(startElem.Name.Local)\n\t\t\tcurData = nil\n\t\tcase xml.CharData:\n\t\t\tdata, _ := tk.(xml.CharData)\n\t\t\tcurData = data.Copy()\n\t\tcase xml.EndElement:\n\t\t\tif curData != nil {\n\t\t\t\txpm.ProcessLeafNode(curPath.String(), string(curData))\n\t\t\t}\n\t\t\txpm.ProcessSwitchTypeNode(curPath.String())\n\t\t\tcurPath.RemoveLast()\n\t\t}\n\t}\n}", "func (u Ups) PostXml(url string, xml string) (content []byte, err error) {\n\tresp, err := http.Post(url, \"text/xml\", strings.NewReader(xml))\n\tif err != nil {\n\t\treturn content, err\n\t}\n\tdefer resp.Body.Close()\n\treturn ioutil.ReadAll(resp.Body)\n}", "func (c *ReligiousTextIdentifier) 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\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for ReligiousTextIdentifier has been passed, got [%s]\", v)\n\t}\n}", "func (c *Controller) RenderXML(context ...interface{}) Result {\n\tctx, err := c.buildContext(context)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc.setContentTypeIfNotExists(\"application/xml\")\n\tbuf, err := xml.Marshal(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &resultContent{\n\t\tBody: bytes.NewReader(buf),\n\t}\n}", "func (f *File) ParseContent(doc *Doc) (err error) {\n\tcontent, err := f.Open(\"content.xml\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer content.Close()\n\n\td := xml.NewDecoder(content)\n\terr = d.Decode(doc)\n\treturn\n}", "func XmlInitParser() {\n\n\tC.xmlInitParser()\n\n}", "func NewXMLStyle(r io.Reader) (*Style, error) {\n\tdec := xml.NewDecoder(r)\n\tstyle := &Style{}\n\treturn style, dec.Decode(style)\n}", "func (ctx *Context) ReadXML(t interface{}) error {\n\tdata, err := wsutil.ReadClientText(ctx.Conn)\n\tif err != nil {\n\t\treturn createError(err)\n\t}\n\treturn xml.Unmarshal(data, t)\n}", "func GetXML(filename string) (kcode []byte) {\n\tdata := ReadFile(filename)\n\t// Convert it to JSON and extract kcode XML\n\tkcode, err := ExtractXML(data)\n\tcheck(\"getkcode\", err)\n\treturn\n}", "func (rc *Ctx) XML() XMLResultProvider {\n\treturn XML\n}", "func Parse(content, inEncoding, url []byte, options int, outEncoding []byte) (doc *HtmlDocument, err error) {\n\tinEncoding = AppendCStringTerminator(inEncoding)\n\toutEncoding = AppendCStringTerminator(outEncoding)\n\n\tvar docPtr *C.xmlDoc\n\tcontentLen := len(content)\n\n\tif contentLen > 0 {\n\t\tvar contentPtr, urlPtr, encodingPtr unsafe.Pointer\n\n\t\tcontentPtr = unsafe.Pointer(&content[0])\n\t\tif len(url) > 0 {\n\t\t\turl = AppendCStringTerminator(url)\n\t\t\turlPtr = unsafe.Pointer(&url[0])\n\t\t}\n\t\tif len(inEncoding) > 0 {\n\t\t\tencodingPtr = unsafe.Pointer(&inEncoding[0])\n\t\t}\n\n\t\tdocPtr = C.htmlParse(contentPtr, C.int(contentLen), urlPtr, encodingPtr, C.int(options), nil, 0)\n\n\t\tif docPtr == nil {\n\t\t\terr = ERR_FAILED_TO_PARSE_HTML\n\t\t} else {\n\t\t\tdoc = NewDocument(unsafe.Pointer(docPtr), contentLen, inEncoding, outEncoding)\n\t\t}\n\t}\n\tif docPtr == nil {\n\t\tdoc = CreateEmptyDocument(inEncoding, outEncoding)\n\t}\n\treturn\n}", "func (service *XMLService) PackageXML(app api.Application) (template.HTML, error) {\n\treturn template.HTML(\"<span>test</span>\"), nil\n}", "func (c *ProductClassificationType) 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 // World Customs Organization Harmonized Commodity Coding and Description System. Use 6 (or occasionally 8 or 10) digits, without punctuation\n case \"01\":\n\t\tc.Body = `WCO Harmonized System`\n\n // UN Standard Product and Service Classification. Use 8 (or occasionally 10) digits, without punctuation\n case \"02\":\n\t\tc.Body = `UNSPSC`\n\n // UK Revenue and Customs classifications, based on the Harmonized System (8 or 10 digits, without punctuation, for export and import respectively)\n case \"03\":\n\t\tc.Body = `HMRC`\n\n // German export trade classification, based on the Harmonised System\n case \"04\":\n\t\tc.Body = `Warenverzeichnis für die Außenhandelsstatistik`\n\n // EU TARIC codes, an extended version of the Harmonized System. Use 10 digits, without punctuation\n case \"05\":\n\t\tc.Body = `TARIC`\n\n // Centraal Boekhuis free classification field for publishers\n case \"06\":\n\t\tc.Body = `Fondsgroep`\n\n // A product category (not a subject classification) assigned by the sender\n case \"07\":\n\t\tc.Body = `Sender’s product category`\n\n // Product classification maintained by the Chinese General Administration of Press and Publication (http://www.gapp.gov.cn)\n case \"08\":\n\t\tc.Body = `GAPP Product Class`\n\n // Statistical Classification of Products by Activity in the European Economic Community, see http://ec.europa.eu/eurostat/ramon/nomenclatures/index.cfm?TargetUrl=LST_NOM_DTL&StrNom=CPA_2008. Use 6 digits, without punctuation. For example, printed children’s books are ‘58.11.13’, but the periods are normally ommited in ONIX\n case \"09\":\n\t\tc.Body = `CPA`\n\n // Mercosur/Mercosul Common Nomenclature, based on the Harmonised System. Use 8 digits, without punctuation\n case \"10\":\n\t\tc.Body = `NCM`\n\n // Common Procurement Vocabulary, uses to describe requirements for tender for public tendering and procurement within the EU. Code is a nine digit number (including the check digit). See http://eur-lex.europa.eu/legal-content/EN/TXT/?uri=URISERV:l22008\n case \"11\":\n\t\tc.Body = `CPV`\n\n // Polish Classification of Products and Services (2015). Use a single letter followed by 2 to 7 digits, without punctuation. For use in ONIX 3.0 only\n case \"12\":\n\t\tc.Body = `PKWiU`\n\n // US HTS (or HTSA) commodity codes for import of goods into USA (10 digits, without punctuation). For use in ONIX 3.0 only. See https://hts.usitc.gov/current\n case \"13\":\n\t\tc.Body = `HTSUS`\n\n // US Schedule B commodity codes for export from USA (10 digits, without punctuation). For use in ONIX 3.0 only. See http://uscensus.prod.3ceonline.com\n case \"14\":\n\t\tc.Body = `US Schedule B`\n\n // Typologie de marché géré par Electre (Market segment code maintained by Electre)\n case \"50\":\n\t\tc.Body = `Electre genre`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for ProductClassificationType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func ConvertToUTF8(source, charset string) (string, error) {\n\tswitch {\n\tcase strings.EqualFold(\"utf-8\", charset):\n\t\treturn source, nil\n\tcase strings.EqualFold(\"iso-8859-1\", charset):\n\t\treturn source, nil\n\tcase strings.EqualFold(\"us-ascii\", charset):\n\t\treturn source, nil\n\tdefault:\n\t\tenc, err := htmlindex.Get(charset)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tin := bytes.NewReader([]byte(source))\n\t\tout := transform.NewReader(in, enc.NewDecoder())\n\t\tresult, err := ioutil.ReadAll(out)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn string(result), nil\n\t}\n}", "func (c *TFrame) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tswitch v {\n\n // \n case \"void\":\n\t\t*c = ``\n\n // \n case \"above\":\n\t\t*c = ``\n\n // \n case \"below\":\n\t\t*c = ``\n\n // \n case \"hsides\":\n\t\t*c = ``\n\n // \n case \"lhs\":\n\t\t*c = ``\n\n // \n case \"rhs\":\n\t\t*c = ``\n\n // \n case \"vsides\":\n\t\t*c = ``\n\n // \n case \"box\":\n\t\t*c = ``\n\n // \n case \"border\":\n\t\t*c = ``\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for TFrame has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}" ]
[ "0.5717283", "0.5122572", "0.5050487", "0.49114284", "0.48861176", "0.4834948", "0.47757518", "0.4718692", "0.46741027", "0.46601808", "0.46510512", "0.46262515", "0.45246148", "0.44681928", "0.4459197", "0.44277203", "0.44131136", "0.44046798", "0.43961614", "0.43892246", "0.43831396", "0.43779144", "0.43662333", "0.43549824", "0.43499938", "0.43321368", "0.43188038", "0.43188038", "0.43098393", "0.43068233", "0.43039885", "0.4279447", "0.4270178", "0.42643583", "0.42616823", "0.42486885", "0.42174885", "0.42168126", "0.42127246", "0.42039254", "0.41557273", "0.41440886", "0.4138536", "0.41366348", "0.41277948", "0.41250402", "0.41206458", "0.41011935", "0.4098097", "0.40872812", "0.40726283", "0.4070657", "0.4066153", "0.40478572", "0.40470263", "0.40469557", "0.40461037", "0.40401438", "0.40367904", "0.40366772", "0.40194058", "0.40036345", "0.40013632", "0.40009952", "0.39992177", "0.3983508", "0.39831766", "0.39827526", "0.39738178", "0.39724213", "0.39646113", "0.3960778", "0.39382842", "0.39382842", "0.3937141", "0.3936362", "0.39190376", "0.39104939", "0.3886037", "0.3885477", "0.38769698", "0.38708943", "0.38668367", "0.38663876", "0.38636854", "0.38594243", "0.38584808", "0.38505587", "0.3831923", "0.38252553", "0.38250795", "0.38184243", "0.38093168", "0.38040945", "0.3787984", "0.3782872", "0.37648845", "0.3763759", "0.3755438", "0.37432444" ]
0.68024933
0
FromHTML returns the charset of an HTML document. It first looks if a BOM is present and if so uses it to determine the charset. If no BOM is present, it relies on the meta tag and falls back on the plain text content.
func FromHTML(content []byte) string { if cset := FromBOM(content); cset != "" { return cset } if cset := fromHTML(content); cset != "" { return cset } return FromPlain(content) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DetectCharset(body []byte, contentType string) (string, error) {\n\t// 1. Use charset.DetermineEncoding\n\t_, name, certain := charset.DetermineEncoding(body, contentType)\n\tif certain {\n\t\treturn name, nil\n\t}\n\n\t// Handle uncertain cases\n\t// 2. Use chardet.Detector.DetectBest\n\tr, err := chardet.NewHtmlDetector().DetectBest(body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif r.Confidence == 100 {\n\t\treturn strings.ToLower(r.Charset), nil\n\t}\n\n\t// 3. Parse meta tag for Content-Type\n\troot, err := html.Parse(bytes.NewReader(body))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdoc := goquery.NewDocumentFromNode(root)\n\tvar csFromMeta string\n\tdoc.Find(\"meta\").EachWithBreak(func(i int, s *goquery.Selection) bool {\n\t\t// <meta http-equiv=\"Content-Type\" content=\"text/html; charset=MS949\"/>\n\t\tif c, exists := s.Attr(\"content\"); exists && strings.Contains(c, \"charset\") {\n\t\t\tif _, params, err := mime.ParseMediaType(c); err == nil {\n\t\t\t\tif cs, ok := params[\"charset\"]; ok {\n\t\t\t\t\tcsFromMeta = strings.ToLower(cs)\n\t\t\t\t\t// Handle Korean charsets.\n\t\t\t\t\tif csFromMeta == \"ms949\" || csFromMeta == \"cp949\" {\n\t\t\t\t\t\tcsFromMeta = \"euc-kr\"\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\n\t\t// <meta charset=\"utf-8\"/>\n\t\tif c, exists := s.Attr(\"charset\"); exists {\n\t\t\tcsFromMeta = c\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t})\n\n\tif csFromMeta == \"\" {\n\t\treturn \"\", fmt.Errorf(\"failed to detect charset\")\n\t}\n\n\treturn csFromMeta, nil\n}", "func FromHTMLParseTree(h *html.Node, css cssom.StyleSheet) *W3CNode {\n\tif h == nil {\n\t\tT().Infof(\"Cannot create DOM for null-HTML\")\n\t\treturn nil\n\t}\n\tstyles := douceuradapter.ExtractStyleElements(h)\n\tT().Debugf(\"Extracted %d <style> elements\", len(styles))\n\ts := cssom.NewCSSOM(nil) // nil = no additional properties\n\tfor _, sty := range styles {\n\t\ts.AddStylesForScope(nil, sty, cssom.Script)\n\t}\n\tif css != nil {\n\t\ts.AddStylesForScope(nil, css, cssom.Author)\n\t}\n\tstytree, err := s.Style(h, styledtree.Creator())\n\tif err != nil {\n\t\tT().Errorf(\"Cannot style test document: %s\", err.Error())\n\t\treturn nil\n\t}\n\treturn domify(stytree)\n}", "func ProcessHtml(r io.Reader) *bytes.Buffer {\n\tinsideTextGo := false\n\ttokenizer := html.NewTokenizer(r)\n\tvar buf bytes.Buffer\n\n\tfor {\n\t\tif tokenizer.Next() == html.ErrorToken {\n\t\t\terr := tokenizer.Err()\n\t\t\tif err == io.EOF {\n\t\t\t\treturn &buf\n\t\t\t}\n\n\t\t\treturn &bytes.Buffer{}\n\t\t}\n\n\t\traw := string(tokenizer.Raw())\n\n\t\ttoken := tokenizer.Token()\n\t\tswitch token.Type {\n\t\tcase html.DoctypeToken:\n\t\t\tbuf.WriteString(token.String())\n\t\tcase html.CommentToken:\n\t\t\tbuf.WriteString(token.String())\n\t\tcase html.StartTagToken:\n\t\t\tif token.DataAtom == atom.Script && getType(token.Attr) == \"text/go\" {\n\t\t\t\tinsideTextGo = true\n\n\t\t\t\tbuf.WriteString(`<script type=\"text/javascript\">`)\n\n\t\t\t\tif srcs := getSrcs(token.Attr); len(srcs) != 0 {\n\t\t\t\t\tbuf.WriteString(handleJsError(goFilesToJs(srcs)))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbuf.WriteString(token.String())\n\t\t\t}\n\t\tcase html.EndTagToken:\n\t\t\tif token.DataAtom == atom.Script && insideTextGo {\n\t\t\t\tinsideTextGo = false\n\t\t\t}\n\t\t\tbuf.WriteString(token.String())\n\t\tcase html.SelfClosingTagToken:\n\t\t\t// TODO: Support <script type=\"text/go\" src=\"...\" />.\n\t\t\tbuf.WriteString(token.String())\n\t\tcase html.TextToken:\n\t\t\tif insideTextGo {\n\t\t\t\tbuf.WriteString(handleJsError(goToJs(token.Data)))\n\t\t\t} else {\n\t\t\t\tbuf.WriteString(raw)\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"unknown token type\")\n\t\t}\n\t}\n}", "func tryFromHTML(body []byte) (string, error) {\n\tmatches := pRe.FindStringSubmatch(string(body))\n\tif matches == nil {\n\t\treturn \"\", fmt.Errorf(\"Can't find a message in %v\", string(body))\n\t}\n\n\t// matches should have the format [ \"<p>message</p>\" \"message\" ], so we want\n\t// the second element\n\treturn matches[1], nil\n}", "func (f *Font) GetCharset() string { return f.charset }", "func NewFromHTML(name, htmlstring string) (r *Recipe, err error) {\n\tr = &Recipe{FileName: name}\n\tr.FileContent = htmlstring\n\terr = r.parseHTML()\n\treturn\n}", "func NewHTMLParser(t testing.TB, body *bytes.Buffer) *HTMLDoc {\n\tt.Helper()\n\tdoc, err := goquery.NewDocumentFromReader(body)\n\tassert.NoError(t, err)\n\treturn &HTMLDoc{doc: doc}\n}", "func FromPlain(content []byte) string {\n\tif len(content) == 0 {\n\t\treturn \"\"\n\t}\n\tif cset := FromBOM(content); cset != \"\" {\n\t\treturn cset\n\t}\n\torigContent := content\n\t// Try to detect UTF-8.\n\t// First eliminate any partial rune at the end.\n\tfor i := len(content) - 1; i >= 0 && i > len(content)-4; i-- {\n\t\tb := content[i]\n\t\tif b < 0x80 {\n\t\t\tbreak\n\t\t}\n\t\tif utf8.RuneStart(b) {\n\t\t\tcontent = content[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\thasHighBit := false\n\tfor _, c := range content {\n\t\tif c >= 0x80 {\n\t\t\thasHighBit = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif hasHighBit && utf8.Valid(content) {\n\t\treturn \"utf-8\"\n\t}\n\n\t// ASCII is a subset of UTF8. Follow W3C recommendation and replace with UTF8.\n\tif ascii(origContent) {\n\t\treturn \"utf-8\"\n\t}\n\n\treturn latin(origContent)\n}", "func ParseHTML(buf io.Reader) (*Object, error) {\n\tobj := newObject()\n\tisInsideHead := false\n\tisInsideTitle := false\n\tz := html.NewTokenizer(buf)\n\tfor {\n\t\ttt := z.Next()\n\t\tif tt == html.ErrorToken {\n\t\t\tif z.Err() == io.EOF {\n\t\t\t\treturn obj, nil\n\t\t\t}\n\n\t\t\treturn nil, z.Err()\n\t\t}\n\n\t\tisStartTagToken := tt == html.StartTagToken\n\t\tif !isInsideHead && !isStartTagToken {\n\t\t\tcontinue\n\t\t}\n\t\tif tt == html.CommentToken || tt == html.DoctypeToken {\n\t\t\tcontinue\n\t\t}\n\n\t\tif isInsideTitle {\n\t\t\tisInsideTitle = false\n\t\t\tif tt == html.TextToken {\n\t\t\t\ttitleText := string(z.Text())\n\t\t\t\tobj.Title = titleText\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tisEndTagToken := tt == html.EndTagToken\n\t\tisSelfClosingTagToken := tt == html.SelfClosingTagToken\n\t\tif isStartTagToken || isEndTagToken || isSelfClosingTagToken {\n\t\t\tname, hasAttr := z.TagName()\n\t\t\tnameAtom := atom.Lookup(name)\n\t\t\tif !isInsideHead {\n\t\t\t\tif nameAtom == atom.Head {\n\t\t\t\t\tif isStartTagToken {\n\t\t\t\t\t\tisInsideHead = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn obj, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif nameAtom == atom.Title && isStartTagToken {\n\t\t\t\tif isStartTagToken {\n\t\t\t\t\tisInsideTitle = true\n\t\t\t\t} else if isEndTagToken {\n\t\t\t\t\tisInsideTitle = false\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// skip if the current tag doesn't have any attributes or is an end\n\t\t\t// tag token\n\t\t\tif !hasAttr || isEndTagToken {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// base tag\n\t\t\tif nameAtom == atom.Base {\n\t\t\t\tvar key, value []byte\n\t\t\t\tvar keyString string\n\t\t\t\tfor hasAttr {\n\t\t\t\t\tkey, value, hasAttr = z.TagAttr()\n\t\t\t\t\tkeyString = atom.String(key)\n\t\t\t\t\tif keyString == attrHREF {\n\t\t\t\t\t\tif href := string(value); validator.ValidateHREF(href) {\n\t\t\t\t\t\t\tobj.Base = href\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\t// link tag\n\t\t\tif nameAtom == atom.Link {\n\t\t\t\tvar key, value []byte\n\t\t\t\tvar keyString, relValue string\n\t\t\t\tlink := &Link{}\n\t\t\t\tfor hasAttr {\n\t\t\t\t\tkey, value, hasAttr = z.TagAttr()\n\t\t\t\t\tkeyString = atom.String(key)\n\t\t\t\t\tif keyString == attrRel {\n\t\t\t\t\t\trelValue = string(value)\n\t\t\t\t\t} else if keyString == attrHREF {\n\t\t\t\t\t\tif href := string(value); validator.ValidateHREF(href) {\n\t\t\t\t\t\t\tlink.HREF = href\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if keyString == attrType {\n\t\t\t\t\t\t// TODO: validation\n\t\t\t\t\t\tlink.Type = string(value)\n\t\t\t\t\t} else if keyString == attrTitle {\n\t\t\t\t\t\tlink.Title = string(value)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif relValue != \"\" {\n\t\t\t\t\tobj.Links[relValue] = append(obj.Links[relValue], link)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// meta tag\n\t\t\tif nameAtom == atom.Meta {\n\t\t\t\tvar key, value []byte\n\t\t\t\tvar keyString, propertyValue, contentValue string\n\t\t\t\tvar hasCharset bool\n\t\t\t\tfor hasAttr {\n\t\t\t\t\tkey, value, hasAttr = z.TagAttr()\n\t\t\t\t\tkeyString = atom.String(key)\n\t\t\t\t\tif keyString == attrCharset {\n\t\t\t\t\t\t// TODO: validation\n\t\t\t\t\t\tobj.Charset = string(value)\n\t\t\t\t\t\thasCharset = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else if keyString == attrProperty ||\n\t\t\t\t\t\tkeyString == attrName ||\n\t\t\t\t\t\tkeyString == attrHTTPEquiv ||\n\t\t\t\t\t\tkeyString == attrItemProp {\n\t\t\t\t\t\tpropertyValue = string(value)\n\t\t\t\t\t} else if keyString == \"content\" {\n\t\t\t\t\t\tcontentValue = string(value)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !hasCharset && propertyValue != \"\" {\n\t\t\t\t\tobj.Metas[propertyValue] = contentValue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func NewReader(r io.Reader, cpn ...string) (io.Reader, error) {\n\tif r == nil {\n\t\treturn r, errInputIsNil\n\t}\n\ttmpReader := bufio.NewReader(r)\n\tvar err error\n\tcp := ASCII\n\tif len(cpn) > 0 {\n\t\tcp = codepageByName(cpn[0])\n\t}\n\tif cp == ASCII {\n\t\tcp, err = CodepageDetect(tmpReader)\n\t}\n\t//TODO внимательно нужно посмотреть что может вернуть CodepageDetect()\n\t//эти случаи обработать, например через func unsupportedCodepageToDecode(cp)\n\tswitch {\n\tcase (cp == UTF32) || (cp == UTF32BE) || (cp == UTF32LE):\n\t\treturn r, errUnsupportedCodepage\n\tcase cp == ASCII: // кодировку определить не удалось, неизвестную кодировку возвращаем как есть\n\t\treturn r, errUnknown\n\tcase err != nil: // и если ошибка при чтении, то возвращаем как есть\n\t\treturn r, err\n\t}\n\n\tif checkBomExist(tmpReader) {\n\t\t//ошибку не обрабатываем, если мы здесь, то эти байты мы уже читали\n\t\ttmpReader.Read(make([]byte, cp.BomLen())) // считываем в никуда количество байт занимаемых BOM этой кодировки\n\t}\n\tif cp == UTF8 {\n\t\treturn tmpReader, nil // когда удалили BOM тогда можно вернуть UTF-8, ведь его конвертировать не нужно\n\t}\n\t//ошибку не обрабатываем, htmlindex.Get() возвращает ошибку только если не найдена кодировка, здесь это уже невозможно\n\t//здесь cp может содержать только кодировки имеющиеся в htmlindex\n\te, _ := htmlindex.Get(cp.String())\n\tr = transform.NewReader(tmpReader, e.NewDecoder())\n\treturn r, nil\n}", "func HTMLParser(response string) *html.Node {\n\tdoc, err := html.Parse(strings.NewReader(response))\n\tif err != nil {\n\t\tfmt.Println(\"Can't parse the html5 utf-8 encoded response\")\n\t\tos.Exit(1)\n\t}\n\treturn doc\n\n}", "func (input *BeegoInput) AcceptsHTML() bool {\n\treturn acceptsHTMLRegex.MatchString(input.Header(\"Accept\"))\n}", "func (c Crawler) getHTMLDoc(body io.ReadCloser) (*goquery.Document, error) {\n doc, err := goquery.NewDocumentFromReader(body)\n if err != nil {\n return nil, err\n }\n return doc, nil\n}", "func (downloader *HTTPDownloader) changeCharsetEncodingAuto(contentTypeStr string, sor io.ReadCloser) string {\r\n\tvar err error\r\n\tdestReader, err := charset.NewReader(sor, contentTypeStr)\r\n\r\n\tif err != nil {\r\n\t\tmlog.LogInst().LogError(err.Error())\r\n\t\tdestReader = sor\r\n\t}\r\n\r\n\tvar sorbody []byte\r\n\tif sorbody, err = ioutil.ReadAll(destReader); err != nil {\r\n\t\tmlog.LogInst().LogError(err.Error())\r\n\t\t// For gb2312, an error will be returned.\r\n\t\t// Error like: simplifiedchinese: invalid GBK encoding\r\n\t\t// return \"\"\r\n\t}\r\n\t//e,name,certain := charset.DetermineEncoding(sorbody,contentTypeStr)\r\n\tbodystr := string(sorbody)\r\n\r\n\treturn bodystr\r\n}", "func (*XMLDocument) Charset() (charset string) {\n\tmacro.Rewrite(\"$_.charset\")\n\treturn charset\n}", "func NewHTMLMail(msg *mail.Message, boundary string) (*HTMLMailMessage, error) {\n\tmr := multipart.NewReader(msg.Body, boundary)\n\tm := &HTMLMailMessage{\n\t\tbody: msg.Body,\n\t\theader: msg.Header,\n\t}\n\tfor {\n\t\tp, err := mr.NextPart()\n\t\tif err == io.EOF {\n\t\t\treturn m, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmt, params, err := mime.ParseMediaType(p.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch mt {\n\t\tcase \"text/plain\":\n\t\t\ttext, err := parseTextPart(p, params[\"charset\"])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tm.text = text\n\t\tcase \"text/html\":\n\t\t\thtml, err := parseHTMLPart(p, params[\"charset\"])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tm.html = html\n\t\t}\n\t}\n}", "func FromBOM(content []byte) string {\n\tfor _, b := range boms {\n\t\tif bytes.HasPrefix(content, b.bom) {\n\t\t\treturn b.enc\n\t\t}\n\t}\n\treturn \"\"\n}", "func parseHTML(r io.Reader) (*Node, error) {\r\n\tn, err := newParser(r).parse()\r\n\treturn n, err\r\n}", "func ExtractTextFromHTML(str string) string {\n\tvar buffer bytes.Buffer\n\tdoc, err := html.Parse(strings.NewReader(str))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\textract(doc, &buffer)\n\treturn buffer.String()\n}", "func ParseHTMLDocument(r io.ReadCloser) (*html.Node, error) {\n\tdoc, err := html.Parse(r)\n\n\tif err != nil {\n\t\tpanic(\"error parsing document\")\n\t}\n\n\treturn doc, nil\n}", "func HTML(r io.Reader, b *entity.Builder, opts Options) error {\n\topts.setDefaults()\n\tp := htmlParser{\n\t\ttokenizer: html.NewTokenizer(r),\n\t\tbuilder: b,\n\t\tattr: map[string]string{},\n\t\topts: opts,\n\t}\n\n\tif err := p.parse(); err != nil {\n\t\treturn errors.Wrap(err, \"parse\")\n\t}\n\tb.ShrinkPreCode()\n\treturn nil\n}", "func (input *Input) AcceptsHTML() bool {\n\treturn acceptsHTMLRegex.MatchString(input.Header(\"Accept\"))\n}", "func (p *Parser) CharsetReader(c string, i io.Reader) (r io.Reader, e error) {\n\tswitch c {\n\tcase \"windows-1251\":\n\t\tr = decodeWin1251(i)\n\t}\n\treturn\n}", "func XHTMLtoHTML(r io.Reader) (string, error) {\n\tb := new(bytes.Buffer)\n\tz := html.NewTokenizer(r)\n\tfor {\n\t\ttt := z.Next()\n\t\tif tt == html.ErrorToken {\n\t\t\terr := z.Err()\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn \"\", z.Err()\n\t\t}\n\t\tt := z.Token()\n\t\tswitch t.Type {\n\t\tcase html.StartTagToken, html.EndTagToken, html.SelfClosingTagToken:\n\t\t\tidx := strings.Index(t.Data, \":\")\n\t\t\tt.Data = t.Data[idx+1:]\n\t\t}\n\t\tvar na []html.Attribute\n\t\tfor _, a := range t.Attr {\n\t\t\tif strings.HasPrefix(a.Key, \"xmlns\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tna = append(na, a)\n\t\t}\n\t\tt.Attr = na\n\t\tb.WriteString(t.String())\n\t}\n\n\tdoc, err := goquery.NewDocumentFromReader(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefs := doc.Find(\"defs\")\n\tdhtml, err := defs.First().Html()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdoc.Find(\"head\").AppendHtml(dhtml)\n\tdefs.Remove()\n\tdoc.Find(\"svg\").First().Remove()\n\tdoc.Find(\"meta[http-equiv]\").Remove()\n\tdoc.Find(\"head\").PrependHtml(`<meta charset=\"UTF-8\">`)\n\tdoc.Find(\"a[name]:not([href])\").Each(func(_ int, s *goquery.Selection) {\n\t\tname, exists := s.Attr(\"name\")\n\t\tif !exists {\n\t\t\treturn\n\t\t}\n\t\ts.SetAttr(\"href\", \"#\"+name)\n\t})\n\ts, err := doc.Find(\"html\").Html()\n\ts = \"<!DOCTYPE html><html>\" + s + \"</html>\"\n\treturn s, err\n}", "func HTML2str(html string) string {\n\n\tre, _ := regexp.Compile(`\\<[\\S\\s]+?\\>`)\n\thtml = re.ReplaceAllStringFunc(html, strings.ToLower)\n\n\t//remove STYLE\n\tre, _ = regexp.Compile(`\\<style[\\S\\s]+?\\</style\\>`)\n\thtml = re.ReplaceAllString(html, \"\")\n\n\t//remove SCRIPT\n\tre, _ = regexp.Compile(`\\<script[\\S\\s]+?\\</script\\>`)\n\thtml = re.ReplaceAllString(html, \"\")\n\n\tre, _ = regexp.Compile(`\\<[\\S\\s]+?\\>`)\n\thtml = re.ReplaceAllString(html, \"\\n\")\n\n\tre, _ = regexp.Compile(`\\s{2,}`)\n\thtml = re.ReplaceAllString(html, \"\\n\")\n\n\thtml = Htmlunquote(html)\n\treturn strings.TrimSpace(html)\n}", "func WithCharset(nli int) CharsetOption {\n\treturn CharsetOption{nli}\n}", "func NewHTMLToPDFClient(accessToken string) HTMLToPDFClient {\n\treturn &htmlToPDFClient{\n\t\tclient: &client{\n\t\t\thttpClient: request.New(),\n\t\t\taccessToken: accessToken,\n\t\t\tbasePath: \"https://restpack.io/api/html2pdf/v5\",\n\t\t},\n\t}\n}", "func GetHTML(url string) []byte {\r\n\treq, err := http.Get(url)\r\n\tif err != nil {\r\n\t\treturn []byte{}\r\n\t\t// panic(fmt.Errorf(\"%s\", err))\r\n\t}\r\n\tdefer req.Body.Close()\r\n\r\n\tb, err := ioutil.ReadAll(req.Body)\r\n\tif err != nil {\r\n\t\tpanic(fmt.Errorf(\"%s\", err))\r\n\t}\r\n\treturn b\r\n}", "func (r *Recipe) parseHTML() (rerr error) {\n\tif r == nil {\n\t\tr = &Recipe{}\n\t}\n\tif r.FileContent == \"\" || r.FileName == \"\" {\n\t\trerr = fmt.Errorf(\"no file loaded\")\n\t\treturn\n\t}\n\n\tr.Lines, rerr = getIngredientLinesInHTML(r.FileContent)\n\treturn r.parseRecipe()\n\n}", "func GetFromHtml(value template.HTML, scopes ...string) template.HTML {\n\tif config.Get().Language == \"\" {\n\t\treturn value\n\t}\n\n\tif locale, ok := Lang[config.Get().Language][JoinScopes(scopes)+strings.ToLower(string(value))]; ok {\n\t\treturn template.HTML(locale)\n\t}\n\n\treturn value\n}", "func Parse(content, inEncoding, url []byte, options int, outEncoding []byte) (doc *HtmlDocument, err error) {\n\tinEncoding = AppendCStringTerminator(inEncoding)\n\toutEncoding = AppendCStringTerminator(outEncoding)\n\n\tvar docPtr *C.xmlDoc\n\tcontentLen := len(content)\n\n\tif contentLen > 0 {\n\t\tvar contentPtr, urlPtr, encodingPtr unsafe.Pointer\n\n\t\tcontentPtr = unsafe.Pointer(&content[0])\n\t\tif len(url) > 0 {\n\t\t\turl = AppendCStringTerminator(url)\n\t\t\turlPtr = unsafe.Pointer(&url[0])\n\t\t}\n\t\tif len(inEncoding) > 0 {\n\t\t\tencodingPtr = unsafe.Pointer(&inEncoding[0])\n\t\t}\n\n\t\tdocPtr = C.htmlParse(contentPtr, C.int(contentLen), urlPtr, encodingPtr, C.int(options), nil, 0)\n\n\t\tif docPtr == nil {\n\t\t\terr = ERR_FAILED_TO_PARSE_HTML\n\t\t} else {\n\t\t\tdoc = NewDocument(unsafe.Pointer(docPtr), contentLen, inEncoding, outEncoding)\n\t\t}\n\t}\n\tif docPtr == nil {\n\t\tdoc = CreateEmptyDocument(inEncoding, outEncoding)\n\t}\n\treturn\n}", "func ConvertToUTF8(source, charset string) (string, error) {\n\tswitch {\n\tcase strings.EqualFold(\"utf-8\", charset):\n\t\treturn source, nil\n\tcase strings.EqualFold(\"iso-8859-1\", charset):\n\t\treturn source, nil\n\tcase strings.EqualFold(\"us-ascii\", charset):\n\t\treturn source, nil\n\tdefault:\n\t\tenc, err := htmlindex.Get(charset)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tin := bytes.NewReader([]byte(source))\n\t\tout := transform.NewReader(in, enc.NewDecoder())\n\t\tresult, err := ioutil.ReadAll(out)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn string(result), nil\n\t}\n}", "func (ft *FieldType) GetCharset() string {\n\treturn ft.charset\n}", "func Reader(charset string, input io.Reader) (io.Reader, error) {\n\tcharset = strings.ToLower(charset)\n\t// \"ascii\" is not in the spec but is common\n\tif charset == \"utf-8\" || charset == \"us-ascii\" || charset == \"ascii\" {\n\t\treturn input, nil\n\t}\n\tif enc, ok := charsets[charset]; ok {\n\t\treturn enc.NewDecoder().Reader(input), nil\n\t}\n\treturn nil, fmt.Errorf(\"unhandled charset %q\", charset)\n}", "func ParseHTML(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar htmlText starlark.String\n\tif err := starlark.UnpackArgs(\"parseHtml\", args, kwargs, \"htmlText\", &htmlText); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontent, err := AsString(htmlText)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot := soup.HTMLParse(string(content))\n\treturn NewSoupNode(&root), nil\n}", "func ParseHTML(url string) *html.Node {\r\n\t_, body, err := fasthttp.Get(nil, url)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tdocument, err := html.Parse(bytes.NewReader(body))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\treturn document\r\n}", "func TestHTML(t *testing.T) {\n\tm := MarkHub{}\n\terr := m.ParseString(\"# title 1\")\n\tif err != nil {\n\t\tt.Errorf(\"TestHTML(): got -> %v, want: nil\", err)\n\t}\n\thtml := m.HTML()\n\tif len(html) == 0 {\n\t\tt.Errorf(\"TestHTML(): got -> %v, want: length > 0\", len(html))\n\t}\n}", "func BuildHTMLTree(f *os.File) (*branch.Branch, error) {\n\tbuf := bufio.NewReader(f)\n\n\tst := NewHTMLTree(cBody)\n\tst.br, _ = st.root.AddBranch(-1, cP)\n\n\tfor {\n\t\tline, err := buf.ReadString('\\n')\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn st.root, err\n\t\t}\n\t\tst.Build(line)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn st.root, nil\n}", "func validateUTF8ForHTML(html string) error {\n\tpos := 0\n\tfor pos < len(html) {\n\t\tr, width := utf8.DecodeRuneInString(html[pos:])\n\t\t// Check that the code point wasn't ill-formed. utf8.RuneError\n\t\t// == '\\uFFFD' so we need to check for a mismatched width, too.\n\t\tif r == utf8.RuneError && width < 2 {\n\t\t\treturn errors.Errorf(\"invalid UTF-8 at byte position %d\", pos)\n\t\t}\n\t\tif !isHTMLValid(r) {\n\t\t\treturn errors.Errorf(\"character U+%04x at position %d is not allowed in AMPHTML\", r, pos)\n\t\t}\n\t\tpos += width\n\t}\n\treturn nil\n}", "func getHTMLContent(articleContent *goquery.Selection) string {\n\thtml, err := articleContent.Html()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\thtml = ghtml.UnescapeString(html)\n\thtml = rxComments.ReplaceAllString(html, \"\")\n\thtml = rxKillBreaks.ReplaceAllString(html, \"<br />\")\n\thtml = rxSpaces.ReplaceAllString(html, \" \")\n\treturn html\n}", "func RequestHTML(method string, url url.URL) (*goquery.Document, error) {\n\theaders := map[string]string{\n\t\t\"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n\t\t\"user-agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/83.0.4103.61 Chrome/83.0.4103.61 Safari/537.36\",\n\t}\n\n\tdata, err := Request(method, url, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Load the HTML document\n\tdoc, err := goquery.NewDocumentFromReader(bytes.NewReader(data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn doc, nil\n}", "func (fh *FileHandler) UnTarGzipHTML(tarFilePath, repoName, branchName, tagName, commit *string) error {\n\thtmlPath := \"\"\n\tif *tagName == \"\" {\n\t\thtmlPath = fmt.Sprintf(\"%s/%s/%s/html/%s/\", *fh.repoPath, *repoName, *branchName, *commit)\n\t} else {\n\t\thtmlPath = fmt.Sprintf(\"%s/%s/%s/html/%s/%s/\", *fh.repoPath, *repoName, *branchName, *tagName, *commit)\n\t}\n\tfile, err := os.Open(*tarFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tgr, err := gzip.NewReader(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer gr.Close()\n\n\ttr := tar.NewReader(gr)\n\tfor {\n\t\theader, err := tr.Next()\n\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\tif err != nil {\n\n\t\t\treturn err\n\t\t}\n\t\tfileName := htmlPath + header.Name\n\t\tswitch header.Typeflag {\n\t\tcase tar.TypeDir:\n\t\t\tcontinue\n\t\tcase tar.TypeReg:\n\t\t\toutFile, err := fh.createFile(fileName)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\tdefer outFile.Close()\n\t\t\tif _, err := io.Copy(outFile, tr); err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tlog.Printf(\n\t\t\t\t\"ExtractTarGz: uknown type: %v in %s\",\n\t\t\t\theader.Typeflag,\n\t\t\t\theader.Name)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *BaseMail) GetHTML() string {\n\treturn c.HTML\n}", "func (ctx *ProxyCtx) Charset() string {\n\tcharsets := charsetFinder.FindStringSubmatch(ctx.Resp.Header.Get(\"Content-Type\"))\n\tif charsets == nil {\n\t\treturn \"\"\n\t}\n\treturn charsets[1]\n}", "func NewHTMLTranslater(client *translate.Client) *HTMLTranslater {\n\treturn &HTMLTranslater{Client: client}\n}", "func (d Decoder) WithCharset(set charset.Decoder) Decoder {\n\td.set = set\n\treturn d\n}", "func HTMLContentTypeMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=UTF-8\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func GetBOMByTKRName(ctx context.Context, c client.Client, tkrName string) (*bomtypes.Bom, error) {\n\tconfigMapList := &corev1.ConfigMapList{}\n\tvar bomConfigMap *corev1.ConfigMap\n\tif err := c.List(ctx, configMapList, client.InNamespace(constants.TKGBomNamespace), client.MatchingLabels{constants.TKRLabel: tkrName}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(configMapList.Items) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tbomConfigMap = &configMapList.Items[0]\n\tbomData, ok := bomConfigMap.BinaryData[constants.TKGBomContent]\n\tif !ok {\n\t\tbomDataString, ok := bomConfigMap.Data[constants.TKGBomContent]\n\t\tif !ok {\n\t\t\treturn nil, nil\n\t\t}\n\t\tbomData = []byte(bomDataString)\n\t}\n\n\tbom, err := bomtypes.NewBom(bomData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &bom, nil\n}", "func (ctx *Context) AcceptHTML() bool {\r\n\treturn acceptsHTMLRegex.MatchString(ctx.HeaderParam(HeaderAccept))\r\n}", "func (self *Response) ResetHtmlParser() *goquery.Document {\n\tr := strings.NewReader(self.body)\n\tvar err error\n\tself.docParser, err = goquery.NewDocumentFromReader(r)\n\tif err != nil {\n\t\treporter.Log.Println(err.Error())\n\t\tpanic(err.Error())\n\t}\n\treturn self.docParser\n}", "func ISO8859_1toUTF8(in string) (out string, err error) {\n\t// create a Reader using the input string as Reader and ISO8859 decoder\n\tdecoded := transform.NewReader(strings.NewReader(in), charmap.ISO8859_1.NewDecoder())\n\tdecodedBytes, err := ioutil.ReadAll(decoded)\n\tif err != nil {\n\t\treturn\n\t}\n\tout = string(decodedBytes)\n\treturn\n}", "func (hm *HTMLMailMessage) HTML() []byte {\n\treturn hm.html\n}", "func StringFromCharset(length int, charset string) (string, error) {\n\tresult := make([]byte, length) // Random string to return\n\tcharsetlen := big.NewInt(int64(len(charset)))\n\n\tfor i := 0; i < length; i++ {\n\t\tb, err := rand.Int(rand.Reader, charsetlen)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tr := int(b.Int64())\n\t\tresult[i] = charset[r]\n\t}\n\n\treturn string(result), nil\n}", "func convertToHTML(file []byte) (string, error) {\n\tvar buf bytes.Buffer\n\n\tmd := goldmark.New(\n\t\tgoldmark.WithExtensions(extension.GFM),\n\t\tgoldmark.WithParserOptions(\n\t\t\tparser.WithAutoHeadingID(),\n\t\t),\n\t)\n\n\tif err := md.Convert(file, &buf); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn buf.String(), nil\n}", "func HTML(c *slurp.C, data interface{}) slurp.Stage {\n\treturn func(in <-chan slurp.File, out chan<- slurp.File) {\n\n\t\ttemplates := html.New(\"\")\n\n\t\tvar wg sync.WaitGroup\n\t\tdefer wg.Wait() //Wait before all templates are executed.\n\n\t\tfor f := range in {\n\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\t_, err := buf.ReadFrom(f.Reader)\n\t\t\tf.Close()\n\t\t\tif err != nil {\n\t\t\t\tc.Println(err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ttemplate, err := templates.New(f.Stat.Name()).Parse(buf.String())\n\t\t\tif err != nil {\n\t\t\t\tc.Println(err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tf.Reader = NewTemplateReadCloser(c, wg, template, data)\n\n\t\t\tout <- f\n\t\t}\n\t}\n}", "func (b *Blueprint) GetCharset() string {\n\treturn b.charset\n}", "func DecodeAutoDetect(src []byte) (string, error) {\n\tfor _, enc := range encodings {\n\t\te, _ := charset.Lookup(enc)\n\t\tif e == nil {\n\t\t\tcontinue\n\t\t}\n\t\tvar buf bytes.Buffer\n\t\tr := transform.NewWriter(&buf, e.NewDecoder())\n\t\t_, err := r.Write(src)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\terr = r.Close()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tf := buf.Bytes()\n\t\tif isInvalidRune(f) {\n\t\t\tcontinue\n\t\t}\n\t\tif utf8.Valid(f) {\n\t\t\tif hasBom(f) {\n\t\t\t\tf = stripBom(f)\n\t\t\t}\n\t\t\treturn string(f), nil\n\t\t}\n\t}\n\treturn string(src), errors.New(\"could not determine character code\")\n}", "func HTML(title string, bodyTag []byte) []byte {\n\tb := bytes.NewBuffer(nil)\n\tfmt.Fprintf(b, htmlHead, html.EscapeString(title))\n\tb.Write(bodyTag)\n\tb.WriteString(\"\\n</html>\")\n\treturn b.Bytes()\n}", "func getHTML(str string) template.HTML {\n\tmarkdown := string(blackfriday.Run([]byte(str)))\n\treturn template.HTML(markdown)\n}", "func (u UnsafeBytes) HTML(ctx context.Context) (HTML, error) {\n\treturn nil, errHTMLOnPrimitive(\"UnsafeBytes\")\n}", "func TokenizeHTML(s string) (*Node, error) {\r\n\thtmlContent := strings.NewReader(s)\r\n\tdoc, err := html.Parse(htmlContent)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tchildren := make([]*Node, 0)\r\n\tbody := &Node{\r\n\t\tTag: \"body\",\r\n\t\tText: \"\",\r\n\t\tAttrs: []map[string]string{},\r\n\t\tChildren: children,\r\n\t}\r\n\texcludedTags := map[string]bool{\r\n\t\t\"html\": true, \"head\": true, \"body\": true,\r\n\t}\r\n\r\n\tvar f func(*html.Node, *[]*Node) []*Node\r\n\tf = func(n *html.Node, nodes *[]*Node) []*Node {\r\n\t\tchildNode := &Node{}\r\n\t\tchildNode.Children = make([]*Node, 0)\r\n\r\n\t\tcontinueTokenization := true\r\n\t\tif n.Type == html.DocumentNode {\r\n\t\t\tcontinueTokenization = false\r\n\t\t}\r\n\r\n\t\tif n.Type == html.ElementNode {\r\n\t\t\tif found := excludedTags[n.Data]; found {\r\n\t\t\t\tcontinueTokenization = false\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif continueTokenization {\r\n\t\t\tattrs := make([]map[string]string, 0)\r\n\t\t\tif n.Type == html.ElementNode {\r\n\t\t\t\tfor _, a := range n.Attr {\r\n\t\t\t\t\tattrs = append(attrs, map[string]string{\"key\": a.Key, \"value\": a.Val})\r\n\t\t\t\t}\r\n\t\t\t\tchildNode.Tag = n.Data\r\n\t\t\t} else if n.Type == html.TextNode {\r\n\t\t\t\tchildNode.Text = n.Data\r\n\t\t\t}\r\n\t\t\tchildNode.Attrs = attrs\r\n\t\t}\r\n\r\n\t\tfor child := n.FirstChild; child != nil; child = child.NextSibling {\r\n\t\t\tchildNode.Children = f(child, &childNode.Children)\r\n\t\t}\r\n\r\n\t\tif continueTokenization {\r\n\t\t\t*nodes = append(*nodes, childNode)\r\n\t\t} else {\r\n\t\t\t*nodes = childNode.Children\r\n\t\t}\r\n\r\n\t\treturn *nodes\r\n\t}\r\n\r\n\tbody.Children = f(doc, &body.Children)\r\n\r\n\treturn body, nil\r\n}", "func BOMReader(ir io.Reader) io.Reader {\n\tr := bufio.NewReader(ir)\n\tb, err := r.Peek(3)\n\tif err != nil {\n\t\treturn r\n\t}\n\tif b[0] == bom0 && b[1] == bom1 && b[2] == bom2 {\n\t\tr.Discard(3)\n\t}\n\treturn r\n}", "func GetUTF8Body(body []byte, contentType string,\n\tignoreInvalidUTF8Chars bool) (string, error) {\n\t// Detect charset.\n\tcs, err := DetectCharset(body, contentType)\n\tif err != nil {\n\t\tif !ignoreInvalidUTF8Chars {\n\t\t\treturn \"\", err\n\t\t}\n\t\tcs = \"utf-8\"\n\t}\n\n\t// Remove utf8.RuneError if ignoreInvalidUTF8Chars is true.\n\tbs := string(body)\n\tif ignoreInvalidUTF8Chars {\n\t\tif !utf8.ValidString(bs) {\n\t\t\tv := make([]rune, 0, len(bs))\n\t\t\tfor i, r := range bs {\n\t\t\t\tif r == utf8.RuneError {\n\t\t\t\t\t_, size := utf8.DecodeRuneInString(bs[i:])\n\t\t\t\t\tif size == 1 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tv = append(v, r)\n\t\t\t}\n\t\t\tbs = string(v)\n\t\t}\n\t}\n\n\t// Convert body.\n\tconverted, err := iconv.ConvertString(bs, cs, \"utf-8\")\n\tif err != nil && !strings.Contains(converted, \"</head>\") {\n\t\treturn \"\", err\n\t}\n\n\treturn converted, nil\n}", "func (lf *localFile) ContentEncoding() string {\n\tif lf.matcher == nil {\n\t\treturn \"\"\n\t}\n\tif lf.matcher.Gzip {\n\t\treturn \"gzip\"\n\t}\n\treturn lf.matcher.ContentEncoding\n}", "func (self *Response) GetHtmlParser() *goquery.Document {\n\treturn self.docParser\n}", "func fromgb(in []byte) string {\n\tout := make([]byte, len(in)*4)\n\n\t_, _, err := iconv.Convert(in, out, \"gb2312\", \"utf-8\")\n\tcheck(err)\n\treturn strings.Trim(string(out), \" \\n\\r\\x00\")\n}", "func (g Goose) ExtractFromRawHTML(RawHTML string, url string) (*Article, error) {\n\tcc := NewCrawler(g.config)\n\treturn cc.Crawl(RawHTML, url)\n}", "func NewHTMLContentTypeBinder(decoder *formam.Decoder) HTMLContentTypeBinder {\n\tdecoder.RegisterCustomType(decoders.TimeDecoderFn(), []interface{}{time.Time{}}, nil)\n\tdecoder.RegisterCustomType(decoders.NullTimeDecoderFn(), []interface{}{nulls.Time{}}, nil)\n\n\treturn HTMLContentTypeBinder{\n\t\tdecoder: decoder,\n\t}\n}", "func Info(name string) *Charset {\n\tfor _, f := range factories {\n\t\tif info := f.Info(name); info != nil {\n\t\t\treturn info\n\t\t}\n\t}\n\treturn nil\n}", "func FromXML(content []byte) string {\n\tif cset := fromXML(content); cset != \"\" {\n\t\treturn cset\n\t}\n\treturn FromPlain(content)\n}", "func CodepageDetect(r io.Reader) (IDCodePage, error) {\n\tif r == nil {\n\t\treturn ASCII, nil\n\t}\n\tbuf, err := bufio.NewReader(r).Peek(ReadBufSize)\n\tif (err != nil) && (err != io.EOF) {\n\t\treturn ASCII, err\n\t}\n\t//match code page from BOM, support: utf-8, utf-16le, utf-16be, utf-32le or utf-32be\n\tif idCodePage, ok := CheckBOM(buf); ok {\n\t\treturn idCodePage, nil\n\t}\n\tif ValidUTF8(buf) {\n\t\treturn UTF8, nil\n\t}\n\treturn CodepageAutoDetect(buf), nil\n}", "func ReadHtmlFile(name string) []byte {\n\tdata, err := ioutil.ReadFile(name)\n\tif err !=nil{\n\t\tpanic(0)\n\t}\n\treturn data\n}", "func (h *htmlProcessor) extractFromHTML(reader io.Reader, writer io.Writer) error {\n\ttokenizer := html.NewTokenizer(reader)\n\tfor {\n\t\ttoken := tokenizer.Next()\n\t\tif token == html.ErrorToken {\n\t\t\terr := tokenizer.Err()\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif token == html.StartTagToken {\n\t\t\tif h.requireScopeStack {\n\t\t\t\toffset := len(tokenizer.Raw())\n\t\t\t\tname, _ := tokenizer.TagName()\n\t\t\t\tscope := fmt.Sprintf(\"%s:%v\", name, offset)\n\t\t\t\tif len(h.scopeStack) > 0 {\n\t\t\t\t\tn := len(h.scopeStack) - 1\n\t\t\t\t\tinnerScope := fmt.Sprintf(\"%s::%s\", h.scopeStack[n], scope)\n\t\t\t\t\th.scopeStack = append(h.scopeStack, innerScope)\n\t\t\t\t\timplicitDirective := fmt.Sprintf(\" sashimi:begin('%s') \", innerScope)\n\t\t\t\t\t_, err := writer.Write([]byte(implicitDirective))\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} else {\n\t\t\t\t\th.scopeStack = append(h.scopeStack, scope)\n\t\t\t\t\timplicitDirective := fmt.Sprintf(\" sashimi:begin('%s') \", scope)\n\t\t\t\t\t_, err := writer.Write([]byte(implicitDirective))\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}\n\t\t\t}\n\t\t}\n\t\tif token == html.EndTagToken {\n\t\t\tif h.requireScopeStack {\n\t\t\t\tn := len(h.scopeStack) - 1\n\t\t\t\timplicitDirective := fmt.Sprintf(\" sashimi:end('%s') \", h.scopeStack[n])\n\t\t\t\t_, err := writer.Write([]byte(implicitDirective))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\th.scopeStack = h.scopeStack[:n]\n\t\t\t\tif len(h.scopeStack) == 0 {\n\t\t\t\t\th.requireScopeStack = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif token == html.CommentToken {\n\t\t\tcontent := tokenizer.Text()\n\t\t\tif bytes.Contains(content, []byte(\"sashimi:\")) {\n\t\t\t\tif bytes.Contains(content, []byte(\"sashimi:repeat\")) {\n\t\t\t\t\tif !h.requireScopeStack {\n\t\t\t\t\t\th.scopeStack = make([]string, 0)\n\t\t\t\t\t}\n\t\t\t\t\th.requireScopeStack = true\n\t\t\t\t}\n\t\t\t\t_, err := writer.Write(content)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func RenderHTMLFromFile(filename string, settings ...configuration.Setting) (string, types.Metadata, error) {\n\tinfo, err := os.Stat(filename)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn \"\", types.Metadata{}, err\n\t}\n\n\tallSettings := append([]configuration.Setting{\n\t\tconfiguration.WithLastUpdated(info.ModTime()),\n\t\tconfiguration.WithFilename(filename),\n\t\tconfiguration.WithBackEnd(\"html5\")},\n\t\tsettings...)\n\tconfig := configuration.NewConfiguration(allSettings...)\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn \"\", types.Metadata{}, err\n\t}\n\tdefer func() { f.Close() }()\n\tresultWriter := bytes.NewBuffer(nil)\n\tmetadata, err := libasciidoc.Convert(f, resultWriter, config)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn \"\", types.Metadata{}, err\n\t}\n\tif log.IsLevelEnabled(log.DebugLevel) {\n\t\tlog.Debug(resultWriter.String())\n\t}\n\treturn resultWriter.String(), metadata, nil\n}", "func NewFromString(htmlString string) (r *Recipe, err error) {\n\tr = &Recipe{FileName: \"string\"}\n\tr.FileContent = htmlString\n\terr = r.parseHTML()\n\treturn\n}", "func RenderHTMLWithMetadata(actual string, settings ...configuration.Setting) (string, types.Metadata, error) {\n\tallSettings := append([]configuration.Setting{configuration.WithFilename(\"test.adoc\"), configuration.WithBackEnd(\"html5\")}, settings...)\n\tconfig := configuration.NewConfiguration(allSettings...)\n\tcontentReader := strings.NewReader(actual)\n\tresultWriter := bytes.NewBuffer(nil)\n\tmetadata, err := libasciidoc.Convert(contentReader, resultWriter, config)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn \"\", types.Metadata{}, err\n\t}\n\tif log.IsLevelEnabled(log.DebugLevel) {\n\t\tlog.Debug(resultWriter.String())\n\t}\n\treturn resultWriter.String(), metadata, nil\n}", "func WriteHtml(in <-chan Chunk) <-chan HtmlFile {\n\n\thtmlfilec := make(chan HtmlFile)\n\n\tgo func() {\n\n\t\t// we need a waitgroup to assure that `htmlfilec` is closed\n\t\t// only after all inner go routines have been closed.\n\n\t\tvar wg sync.WaitGroup\n\n\t\tfor chunk := range in {\n\t\t\twg.Add(1)\n\t\t\t// use a closure here to prevent blocking\n\n\t\t\t// this inner closure needs to receive chunk as an argument\n\t\t\t// to prevent race conditions due to the typical closure issue...\n\t\t\tgo func(c Chunk) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tbytes, err := json.Marshal(c.Json)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tresultc := piperunner.Exec(\"pandoc -f json -t html\", bytes)\n\n\t\t\t\tresult := <-resultc\n\n\t\t\t\tif err = result.Err; err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\thtmlfilec <- HtmlFile{Path: c.Path, Title: c.Title, Contents: result.Text}\n\n\t\t\t}(chunk)\n\t\t}\n\n\t\twg.Wait()\n\t\tclose(htmlfilec)\n\t}()\n\n\treturn htmlfilec\n}", "func NewHTML(t string) http.Handler {\n\treturn &HTMLhandler{t}\n}", "func fmtHTML(in string) string {\n\tdoc, err := html.Parse(strings.NewReader(in))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tout := &bytes.Buffer{}\n\tif err := html.Render(out, doc); err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(out.Bytes())\n}", "func (_ HTMLProcessor) Process(c *Chunk) *Chunk {\n\tnodes := ToCharNodes(c.Data)\n\tnodesLen := len(nodes)\n\n\tif len(c.Matches) > 0 {\n\t\tfor _, match := range c.Matches {\n\t\t\tif len(match.Indices) == 0 {\n\t\t\t\tnodes[0].AddBefore(OpenTag(match.Label, match.Message))\n\t\t\t\tnodes[nodesLen-1].AddAfter(CloseTag())\n\t\t\t} else {\n\t\t\t\tnodes[match.Indices[0]].AddBefore(OpenTag(match.Label, match.Message))\n\t\t\t\tnodes[match.Indices[1]-1].AddAfter(CloseTag())\n\t\t\t}\n\t\t}\n\t}\n\n\tc.Data = nodes.ToString()\n\n\treturn c\n}", "func (cs *CsvStructure) checkForConvertToUtf8(textBytes []byte) (outBytes []byte) {\n\tvar strByte []byte\n\tvar err error\n\toutBytes = make([]byte, len(textBytes))\n\tcopy(outBytes, textBytes)\n\t_, cs.Charset, _ = charset.DetermineEncoding(textBytes, \"\")\n\t// fmt.Println(cs.Charset)\n\tif cs.Charset != \"utf-8\" { // convert to UTF-8\n\t\tif reader, err := charset.NewReader(strings.NewReader(string(textBytes)), cs.Charset); err == nil {\n\t\t\tif strByte, err = ioutil.ReadAll(reader); err == nil {\n\t\t\t\toutBytes = make([]byte, len(strByte))\n\t\t\t\tcopy(outBytes, strByte)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tfmt.Println(\"Error while trying to convert %s to utf-8: \", cs.Charset)\n\t}\n\treturn outBytes\n}", "func ReplaceHTMLTags(text string) string {\n\tvar (\n\t\tparser = html.NewTokenizer(strings.NewReader(text))\n\t\ttagStack = stack.New()\n\t\ttextToTag = map[int]string{}\n\t)\n\n\tfor {\n\t\tnode := parser.Next()\n\t\tswitch node {\n\t\tcase html.ErrorToken:\n\t\t\tresult := strings.Replace(textToTag[0], \"&nbsp;\", \" \", -1)\n\t\t\treturn result\n\t\tcase html.TextToken:\n\t\t\tt := string(parser.Text())\n\t\t\ttextToTag[tagStack.Len()] = strings.Join([]string{textToTag[tagStack.Len()], t}, \"\")\n\t\tcase html.StartTagToken:\n\t\t\ttagName, hasAttr := parser.TagName()\n\t\t\tif string(tagName) == scriptTag {\n\t\t\t\t// We can skip script tags, as they are invisible for the user, but we can indicate that there are\n\t\t\t\t// scripts in the task. To skip tag, it is necessary to call Next() two times:\n\t\t\t\t// 1) returns TextToken with the script body\n\t\t\t\t// 2) returns EndTagToken for the closed script tag\n\t\t\t\t// Usually script tag doesn't have any neste tags, so this aproach should work\n\t\t\t\tlog.Printf(\"[INFO] Skipping script tag\")\n\t\t\t\tparser.Next()\n\t\t\t\tparser.Next()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttag := Tag{Tag: string(tagName), Attrs: map[string]string{}}\n\t\t\tif hasAttr {\n\t\t\t\tfor {\n\t\t\t\t\tattr, val, moreAttr := parser.TagAttr()\n\t\t\t\t\tif DEBUG {\n\t\t\t\t\t\tlog.Printf(\"[DEBUG] Found attr %s\", attr)\n\t\t\t\t\t}\n\t\t\t\t\ttag.Attrs[string(attr)] = string(val)\n\t\t\t\t\tif !moreAttr {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif DEBUG {\n\t\t\t\tlog.Printf(\"[DEBUG] Found tag %q\", tag)\n\t\t\t}\n\t\t\ttagStack.Push(tag)\n\t\tcase html.EndTagToken:\n\t\t\tvar (\n\t\t\t\taddText string\n\t\t\t\ttagNo = tagStack.Len()\n\t\t\t\ttag = tagStack.Pop()\n\t\t\t\tclosedTag, _ = parser.TagName()\n\t\t\t)\n\t\t\tif tag.(Tag).Tag != string(closedTag) {\n\t\t\t\tlog.Printf(\"[WARNING] Found closed tag %q but expected %q\", closedTag, tag)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif DEBUG {\n\t\t\t\tlog.Printf(\"[DEBUG] Found end of tag %q\", closedTag)\n\t\t\t}\n\t\t\tswitch tag.(Tag).Tag {\n\t\t\tcase iTag:\n\t\t\t\taddText = fmt.Sprintf(\"_%s_\", textToTag[tagNo])\n\t\t\tcase bTag, strongTag:\n\t\t\t\taddText = fmt.Sprintf(\"*%s*\", textToTag[tagNo])\n\t\t\tcase aTag:\n\t\t\t\t// if strings.Compare(string(attr), \"href\") == 0 {\n\t\t\t\taddText = fmt.Sprintf(\"[%s](%s)\", textToTag[tagNo], tag.(Tag).Attrs[\"href\"])\n\t\t\t\t// }\n\t\t\tdefault:\n\t\t\t\taddText = textToTag[tagNo]\n\t\t\t}\n\t\t\ttextToTag[tagStack.Len()] = strings.Join([]string{textToTag[tagStack.Len()], addText}, \"\")\n\t\t\tdelete(textToTag, tagNo)\n\t\t}\n\t}\n}", "func (*XMLDocument) SetCharset(charset string) {\n\tmacro.Rewrite(\"$_.charset = $1\", charset)\n}", "func FetchHtmlFromUrl(url string) ([]byte, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn make([]byte, 0), err\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn make([]byte, 0), err\n\t}\n\n\terr = resp.Body.Close()\n\tif err != nil {\n\t\treturn make([]byte, 0), err\n\t}\n\treturn body, nil\n}", "func Html(url string) ([]byte, error) {\n\trsp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not make request: %w\", err)\n\t}\n\tdefer rsp.Body.Close()\n\tbody, err := ioutil.ReadAll(rsp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not read response body: %w\", err)\n\t}\n\treturn body, nil\n}", "func getToc(pageURL string) (t toc, err error) {\n\ts, err := getTocText(pageURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn parseTocText(s)\n}", "func (e Encoder) WithCharset(set charset.Encoder) Encoder {\n\te.set = set\n\treturn e\n}", "func (p *Page) MustHTML() string {\n\thtml, err := p.HTML()\n\tp.e(err)\n\treturn html\n}", "func (ra *ResponseAsserter) HTML() *HTMLAsserter {\n\t// @TODO do some basic html validation checking\n\treturn newHTMLAsserter(ra, ra.fail)\n}", "func TestLoadedSimpleFontEncoding(t *testing.T) {\n\trawpdf := `\n59 0 obj\n<</BaseFont /Helvetica/Encoding 60 0 R/Name /Helv/Subtype /Type1/Type /Font>>\nendobj\n60 0 obj\n<</Differences [24 /breve /caron /circumflex /dotaccent /hungarumlaut /ogonek /ring /tilde 39 /quotesingle 96 /grave 128 /bullet /dagger /daggerdbl /ellipsis /emdash /endash /florin /fraction /guilsinglleft /guilsinglright /minus /perthousand /quotedblbase /quotedblleft /quotedblright /quoteleft /quoteright /quotesinglbase /trademark /fi /fl /Lslash /OE /Scaron /Ydieresis /Zcaron /dotlessi /lslash /oe /scaron /zcaron 160 /Euro 164 /currency 166 /brokenbar 168 /dieresis /copyright /ordfeminine 172 /logicalnot /.notdef /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu 183 /periodcentered /cedilla /onesuperior /ordmasculine 188 /onequarter /onehalf /threequarters 192 /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis]/Type /Encoding>>\nendobj\n`\n\n\tobjects, err := testutils.ParseIndirectObjects(rawpdf)\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %v\", err)\n\t}\n\n\tfont, err := model.NewPdfFontFromPdfObject(objects[59])\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// The expected encoding is StandardEncoding with the applied differences.\n\tbaseEncoding := newStandandTextEncoder(t)\n\n\tdifferencesMap := map[textencoding.CharCode]rune{\n\t\t24: '˘',\n\t\t25: 'ˇ',\n\t\t26: 'ˆ',\n\t\t27: '˙',\n\t\t28: '˝',\n\t\t29: '˛',\n\t\t30: '˚',\n\t\t31: '˜',\n\t\t39: '\\'',\n\t\t96: '`',\n\t\t128: '•',\n\t\t129: '†',\n\t\t130: '‡',\n\t\t131: '…',\n\t\t132: '—',\n\t\t133: '–',\n\t\t134: 'ƒ',\n\t\t135: '⁄',\n\t\t136: '‹',\n\t\t137: '›',\n\t\t138: '−',\n\t\t139: '‰',\n\t\t140: '„',\n\t\t141: '“',\n\t\t142: '”',\n\t\t143: '‘',\n\t\t144: '’',\n\t\t145: '‚',\n\t\t146: '™',\n\t\t147: 'fi',\n\t\t148: 'fl',\n\t\t149: 'Ł',\n\t\t150: 'Œ',\n\t\t151: 'Š',\n\t\t152: 'Ÿ',\n\t\t153: 'Ž',\n\t\t154: 'ı',\n\t\t155: 'ł',\n\t\t156: 'œ',\n\t\t157: 'š',\n\t\t158: 'ž',\n\t\t160: '€',\n\t\t164: '¤',\n\t\t166: '¦',\n\t\t168: '¨',\n\t\t169: '©',\n\t\t170: 'ª',\n\t\t172: '¬',\n\t\t173: '�',\n\t\t174: '®',\n\t\t175: '¯',\n\t\t176: '°',\n\t\t177: '±',\n\t\t178: '²',\n\t\t179: '³',\n\t\t180: '´',\n\t\t181: 'µ',\n\t\t183: '·',\n\t\t184: '¸',\n\t\t185: '¹',\n\t\t186: 'º',\n\t\t188: '¼',\n\t\t189: '½',\n\t\t190: '¾',\n\t\t192: 'À',\n\t\t193: 'Á',\n\t\t194: 'Â',\n\t\t195: 'Ã',\n\t\t196: 'Ä',\n\t\t197: 'Å',\n\t\t198: 'Æ',\n\t\t199: 'Ç',\n\t\t200: 'È',\n\t\t201: 'É',\n\t\t202: 'Ê',\n\t\t203: 'Ë',\n\t\t204: 'Ì',\n\t\t205: 'Í',\n\t\t206: 'Î',\n\t\t207: 'Ï',\n\t\t208: 'Ð',\n\t\t209: 'Ñ',\n\t\t210: 'Ò',\n\t\t211: 'Ó',\n\t\t212: 'Ô',\n\t\t213: 'Õ',\n\t\t214: 'Ö',\n\t\t215: '×',\n\t\t216: 'Ø',\n\t\t217: 'Ù',\n\t\t218: 'Ú',\n\t\t219: 'Û',\n\t\t220: 'Ü',\n\t\t221: 'Ý',\n\t\t222: 'Þ',\n\t\t223: 'ß',\n\t\t224: 'à',\n\t\t225: 'á',\n\t\t226: 'â',\n\t\t227: 'ã',\n\t\t228: 'ä',\n\t\t229: 'å',\n\t\t230: 'æ',\n\t\t231: 'ç',\n\t\t232: 'è',\n\t\t233: 'é',\n\t\t234: 'ê',\n\t\t235: 'ë',\n\t\t236: 'ì',\n\t\t237: 'í',\n\t\t238: 'î',\n\t\t239: 'ï',\n\t\t240: 'ð',\n\t\t241: 'ñ',\n\t\t242: 'ò',\n\t\t243: 'ó',\n\t\t244: 'ô',\n\t\t245: 'õ',\n\t\t246: 'ö',\n\t\t247: '÷',\n\t\t248: 'ø',\n\t\t249: 'ù',\n\t\t250: 'ú',\n\t\t251: 'û',\n\t\t252: 'ü',\n\t\t253: 'ý',\n\t\t254: 'þ',\n\t\t255: 'ÿ',\n\t}\n\n\tenc := font.Encoder()\n\tfor code := textencoding.CharCode(32); code < 255; code++ {\n\t\tfontrune, has := enc.CharcodeToRune(code)\n\t\tif !has {\n\t\t\tbaserune, bad := baseEncoding.CharcodeToRune(code)\n\t\t\tif bad {\n\t\t\t\tt.Fatalf(\"font not having glyph for char code %d - whereas base encoding had %q\", code, baserune)\n\t\t\t}\n\t\t}\n\n\t\t// Check if in differencesmap first.\n\t\trune, has := differencesMap[code]\n\t\tif has {\n\t\t\tif rune != fontrune {\n\t\t\t\tt.Fatalf(\"Mismatch for char code %d, font has: %q and expected is: %q (differences)\", code, fontrune, rune)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// If not in differences, should be according to StandardEncoding (base).\n\t\trune, has = baseEncoding.CharcodeToRune(code)\n\t\tif has && rune != fontrune {\n\t\t\tt.Fatalf(\"Mismatch for char code %d (%X), font has: %q and expected is: %q (StandardEncoding)\", code, code, fontrune, rune)\n\t\t}\n\t}\n}", "func (c *customerio) BodyHTML(body string) Mailer {\n\tc.bodyHTML = body\n\treturn c\n}", "func getTestHTML() string {\n\treturn `\n\t\t<html xmlns:fo=\"http://www.w3.org/1999/XSL/Format\">\n\t\t<head>\n\t\t<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n\t\t<meta charset=\"UTF-8\">\n\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n\t\t<meta name=\"format-detection\" content=\"telephone=no\">\n\t\t<meta name=\"x-apple-disable-message-reformatting\">\n\t\t</head>\n\t\t<body style=\"padding:0;\">\n\t\t<div class=\"smart-alert\">\n\t\t<link href=\"https://cdn.etrade.net/1/1d/aempros/etc/designs/smartalerts/styles/smartalerts.css\" rel=\"stylesheet\" type=\"text/css\">\n\t\t<table align=\"center\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" bgcolor=\"#ffffff\" style=\"background-color:#ffffff;\">\n\t\t<tbody>\n\t\t<div class=\"previewHeader\" style=\"display:none;font-size:0;line-height:0;max-height:0;mso-hide:all\">Portfolio Digest As of\n\t\t Mon Dec 2 21:10:59 2019Portfolio: XXXX--9323 Personal Trading\n\t\t &nbsp;\n\t\t Market Value:\n\t\t $394,004.72 (\n\t\t -$23.67/-1.91%)\n\t\t &nbsp;\n\t\t SymbolCurrentPr</div>\n\t\t<tr>\n\t\t<td valign=\"top\" align=\"center\" bgcolor=\"#ffffff\">\n\t\t<table width=\"640\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"table-layout: fixed;\" class=\"em_main_table\">\n\t\t<tbody>\n\t\t<tr>\n\t\t<td width=\"20px\" bgcolor=\"#ffffff\">&nbsp;</td><td valign=\"top\" align=\"center\">\n\t\t<table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"em_main_table\" bgcolor=\"#ffffff\">\n\t\t<tbody>\n\t\t<tr>\n\t\t<td height=\"12\" style=\"line-height:1px; font-size:1px;\">&nbsp;</td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td valign=\"top\" align=\"center\">\n\t\t<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" class=\"em_main_table\">\n\t\t<tbody>\n\t\t<tr>\n\t\t<td valign=\"top\" align=\"left\"><a href=\"https://us.etrade.com/home\" target=\"_blank\" title=\"E*TRADE\" alias=\"preheader_logo\" style=\"text-decoration:none; color:#51ae31;\"><img src=\"https://cdn.etrade.net/1/1d/aempros/content/dam/etrade/smart-alerts/en_US/images/etrade_logo_small.png\" width=\"241\" height=\"auto\" alt=\"E*TRADE\" style=\"display:block; font-family:Arial, sans-serif; font-size:25px; line-height:49px; color:#51ae31; font-weight:bold; text-align:center;height:auto;width:241px\" border=\"0\" class=\"em_img\"></a></td><td width=\"100\" class=\"em_side\">&nbsp;</td><td valign=\"bottom\" align=\"right\">\n\t\t<table width=\"315\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" align=\"right\" class=\"em_hide\">\n\t\t<tbody>\n\t\t<tr>\n\t\t<td valign=\"bottom\" align=\"right\" style=\"font-family: Arial, sans-serif; font-size:13px; line-height:18px; color:#555555; text-align:right;font-weight:normal;\" class=\"em_hide\"><span class=\"em_hide\"><a href=\"https://us.etrade.com/e/t/alerts/Alertinbox\" target=\"_blank\" alias=\"preheader\" style=\"text-decoration:none; color:#6633cc;\"><span style=\"color:#6633cc; text-decoration:none;\">Alert Inbox</span></a>&nbsp;&nbsp;|&nbsp;&nbsp;</span><a href=\"https://us.etrade.com/e/t/user/login\" target=\"_blank\" mcdisabled-title=\"\" alias=\"preheader\" style=\"text-decoration:none; color:#6633cc;\"><span style=\"color:#6633cc; text-decoration:none;\">Log on</span></a></td>\n\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td style=\"line-height:0px; font-size:0px;\" height=\"0\">&nbsp;</td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td height=\"20\" style=\"line-height:1px; font-size:1px;\">&nbsp;</td>\n\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t\t</td><td width=\"20px\" bgcolor=\"#ffffff\">&nbsp;</td>\n\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t<!--[if !mso]>-->\n\t\t<tr>\n\t\t<td valign=\"top\" align=\"center\" bgcolor=\"#ffffff\">\n\t\t<div class=\"hide_disktop\" style=\"display:none;width:0;overflow:hidden;\">\n\t\t<table width=\"620\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"display:none;table-layout: fixed; background-color:#ffffff;\" class=\"em_main_table_hero\">\n\t\t<tbody>\n\t\t<tr>\n\t\t<td width=\"20px\">&nbsp;</td><td height=\"0\" valign=\"top\" align=\"center\" width=\"100%\">\n\t\t<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">\n\t\t<tbody>\n\t\t<tr>\n\t\t<td valign=\"top\" align=\"left\" width=\"45%\" style=\"font-family: Arial, sans-serif; font-size:13px; line-height:18px; color:#555; text-align:left;font-weight:normal;\"><a href=\"https://us.etrade.com/e/t/alerts/Alertinbox\" target=\"_blank\" alias=\"preheader\" style=\"text-decoration:none; color:#6633cc;\"><span class=\"visited\" style=\"color:#6633cc; text-decoration:none;\">Alert Inbox</span></a></td><td valign=\"top\" width=\"45%\" align=\"right\" style=\"font-family: Arial, sans-serif; font-size:13px; line-height:18px; color:#555; text-align:right;font-weight:normal;\"><a href=\"https://us.etrade.com/e/t/user/login\" target=\"_blank\" mcdisabled-title=\"\" alias=\"preheader\" style=\"text-decoration:none; color:#555;\"><span class=\"visited\" style=\"color:#6633cc; text-decoration:none;\">Log On</span></a></td>\n\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t\t</td><td width=\"20px\">&nbsp;</td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td style=\"line-height:0px; font-size:0px;\" height=\"20px\">&nbsp;</td>\n\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t\t</div>\n\t\t</td>\n\t\t</tr>\n\t\t<!--<![endif]-->\n\t\t<tr>\n\t\t<td valign=\"top\" align=\"center\" height=\"15px\" bgcolor=\"#19223c\">\n\t\t \t&nbsp;\n\t\t </td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td align=\"center\" bgcolor=\"#ffffff\">\n\t\t<table valign=\"top\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"640\" class=\"em_wrapper\" bgcolor=\"#ffffff\">\n\t\t<tr>\n\t\t<td height=\"30px\">&nbsp;</td>\n\t\t</tr>\n\t\t</table>\n\t\t<table valign=\"top\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"640px\" class=\"em_wrapper\" bgcolor=\"#ffffff\">\n\t\t<tr>\n\t\t<td width=\"20px\">\n\t\t &nbsp;\n\t\t </td><td valign=\"top\" align=\"left\" width=\"600\" class=\"body-content\" style=\"font-family: Arial, sans-serif;font-size: 18px;line-height: 24px;padding-bottom: 15px;color: #555555;\">\n\t\t<table width=\"600\" class=\"em_wrapper\">\n\t\t<tr>\n\t\t<td align=\"center\"><span style=\"font-size: 20px;\"><b>Portfolio Digest</b></span>\n\t\t<br>\n\t\t<span class=\"coF1\"> As of\n\t\t Mon Dec 2 21:10:59 2019</span></td>\n\t\t</tr>\n\t\t</table>\n\t\t<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"600\">\n\t\t<tr>\n\t\t<td height=\"45\"><strong>Portfolio: </strong>XXXX--9323 Personal Trading</td><td align=\"right\" colspan=\"2\"></td>\n\t\t</tr>\n\t\t</table>\n\t\t<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"600\" style=\"border-collapse: initial;\">\n\t\t<tr>\n\t\t<td style=\"border: 1px solid #ccc; border-bottom: 0;\">\n\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n\t\t<tr>\n\t\t<td height=\"29\" nowrap=\"nowrap\">\n\t\t &nbsp;\n\t\t <b>Market Value:\n\t\t $394,004.72 (\n\t\t <font color=\"#ff0000\">-$23.67</font></b>/<b><font color=\"#ff0000\">-1.91%</font>) </b></td><td align=\"right\" nowrap=\"nowrap\">\n\t\t &nbsp;\n\t\t </td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td>\n\t\t<table border=\"0\" cellpadding=\"3\" cellspacing=\"1\" width=\"100%\" bgcolor=\"#cccccc\" style=\"border-collapse: initial;\">\n\t\t<tr bgcolor=\"#E3E3E3\">\n\t\t<td align=\"center\" colspan=\"2\"><b>Symbol</b></td><td align=\"center\"><b>Current<br>Price</b></td><td colspan=\"2\">\n\t\t<table width=\"100%\">\n\t\t<tr align=\"center\">\n\t\t<td colspan=\"2\"><b>Today's Change</b></td>\n\t\t</tr>\n\t\t<tr align=\"center\">\n\t\t<td width=\"50%\"><b>$</b></td><td width=\"50%\"><b>%</b></td>\n\t\t</tr>\n\t\t</table>\n\t\t</td><td align=\"center\"><b>Today's<br>Gain</b></td><td align=\"center\"><b>Qty</b></td><td align=\"center\"><b>Price Paid</b></td><td colspan=\"2\">\n\t\t<table width=\"100%\">\n\t\t<tr align=\"center\">\n\t\t<td colspan=\"2\"><b>Total Gain</b></td>\n\t\t</tr>\n\t\t<tr align=\"center\">\n\t\t<td width=\"50%\"><b>$</b></td><td width=\"50%\"><b>%</b></td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t<tr bgcolor=\"#ffffff\" align=\"right\">\n\t\t<td><b> <a href=\"https://us.etrade.com/e/t/invest/quotesresearch?traxui=P_MGR&amp;sym=TEAM\" target=\"_blank\">TEAM</a>\n\t\t </b></td><td align=\"center\"> <a href=\"https://us.etrade.com/e/t/invest/socreateentry?ordertype=1&amp;symbol=TEAM\" target=\"_blank\">\n\t\tTrade\n\t\t</a></td><td><b>120.84\n\t\t </b></td><td><font color=\"#ff0000\">-$6.27</font>\n\t\t </td><td><font color=\"#ff0000\">-4.93%</font></td><td><font color=\"#ff0000\">-$10.15</font>\n\t\t </td><td>4\n\t\t </td><td>$123.67\n\t\t </td><td><font color=\"#ff0000\">-$11.33</font>\n\t\t </td><td><font color=\"#ff0000\">-2.29%</font>\n\t\t </td>\n\t\t</tr>\n\t\t<tr bgcolor=\"#ffffff\" align=\"right\">\n\t\t<td><b> <a href=\"https://us.etrade.com/e/t/invest/quotesresearch?traxui=P_MGR&amp;sym=CYBR\" target=\"_blank\">CYBR</a>\n\t\t </b></td><td align=\"center\"> <a href=\"https://us.etrade.com/e/t/invest/socreateentry?ordertype=1&amp;symbol=CYBR\" target=\"_blank\">\n\t\tTrade\n\t\t</a></td><td><b>120.10\n\t\t </b></td><td><font color=\"#ff0000\">-$2.45</font>\n\t\t </td><td><font color=\"#ff0000\">-2.00%</font></td><td><font color=\"#ff0000\">-$4.90</font>\n\t\t </td><td>2\n\t\t </td><td>$124.22\n\t\t </td><td><font color=\"#ff0000\">-$8.24</font>\n\t\t </td><td><font color=\"#ff0000\">-3.32%</font>\n\t\t </td>\n\t\t</tr>\n\t\t<tr bgcolor=\"#ffffff\" align=\"right\">\n\t\t<td><b> <a href=\"https://us.etrade.com/e/t/invest/quotesresearch?traxui=P_MGR&amp;sym=CPRT\" target=\"_blank\">CPRT</a>\n\t\t </b></td><td align=\"center\"> <a href=\"https://us.etrade.com/e/t/invest/socreateentry?ordertype=1&amp;symbol=CPRT\" target=\"_blank\">\n\t\tTrade\n\t\t</a></td><td><b>87.96\n\t\t </b></td><td><font color=\"#ff0000\">-$1.04</font>\n\t\t </td><td><font color=\"#ff0000\">-1.17%</font></td><td><font color=\"#ff0000\">-$3.12</font>\n\t\t </td><td>3\n\t\t </td><td>$90.19\n\t\t </td><td><font color=\"#ff0000\">-$6.70</font>\n\t\t </td><td><font color=\"#ff0000\">-2.48%</font>\n\t\t </td>\n\t\t</tr>\n\t\t<tr bgcolor=\"#ffffff\" align=\"right\">\n\t\t<td><b> <a href=\"https://us.etrade.com/e/t/invest/quotesresearch?traxui=P_MGR&amp;sym=WORK\" target=\"_blank\">WORK</a>\n\t\t </b></td><td align=\"center\"> <a href=\"https://us.etrade.com/e/t/invest/socreateentry?ordertype=1&amp;symbol=WORK\" target=\"_blank\">\n\t\tTrade\n\t\t</a></td><td><b>22.51\n\t\t </b></td><td><font color=\"#ff0000\">-$0.31</font>\n\t\t </td><td><font color=\"#ff0000\">-1.36%</font></td><td><font color=\"#ff0000\">-$3.10</font>\n\t\t </td><td>10\n\t\t </td><td>$22.25\n\t\t </td><td><font color=\"#669900\">$2.60</font>\n\t\t </td><td><font color=\"#669900\">1.17%</font>\n\t\t </td>\n\t\t</tr>\n\t\t<tr bgcolor=\"#ffffff\">\n\t\t<td align=\"right\" colspan=\"5\" bgcolor=\"#cccccc\"><b>Totals</b></td><td align=\"right\"><font color=\"#ff0000\">-$21.27</font></td><td colspan=\"2\">\n\t\t </td><td align=\"right\"><font color=\"#ff0000\">-$23.67</font></td><td align=\"right\"><font color=\"#ff0000\">-1.91%</font></td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t</table>\n\t\t<br>\n\t\t<br>\n\t\t<table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" class=\"em_wrapper\" bgcolor=\"#e5e5e5\">\n\t\t<tr>\n\t\t<td class=\"em_wrapper\" bgcolor=\"#e5e5e5\" valign=\"top\" align=\"left\" style=\"font-family:Arial,sans-serif; font-size:18px; line-height:24px; color:#000000; background-color:#e5e5e5; padding:5px 10px 5px 10px; text-align:left; font-weight:bold;\" width=\"100%\"> Portfolio news </td>\n\t\t</tr>\n\t\t</table>\n\t\t<table width=\"600\" class=\"em_wrapper\">\n\t\t<tr>\n\t\t<td>\n\t\t<table border=\"0\" cellspacing=\"0\" cellpadding=\"4\" width=\"100%\">\n\t\t<tr bgcolor=\"#f4f4f4\">\n\t\t<td width=\"23\" align=\"left\">Date</td><td align=\"left\">News Stories</td><td align=\"left\">Source</td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"3\"><b><a href=\"https://us.etrade.com/e/t/invest/quotesresearch?sym=TEAM\">TEAM</a></b></td>\n\t\t</tr>\n\t\t<TR>\n\t\t<td align=\"left\" colspan=\"2\" style=\"padding: 10px 0px 0px 0px;\"><strong>\n\t\tNov\n\t\t23</strong></td>\n\t\t</TR>\n\t\t<tr valign=\"top\">\n\t\t<td align=\"center\" nowrap=\"nowrap\">&nbsp;&nbsp;&nbsp;09:34 AM\n\t\t&nbsp;&nbsp;&nbsp;</td><td><a href=\"https://us.etrade.com/e/t/invest/Story?ID=STORYID%3D20191123MW000089&amp;provider=MarketWatch.com\">MW UPDATE: U.S. stocks look fully priced -- where to put your money now may surprise you</a>&nbsp;&nbsp;</td><td nowrap=\"nowrap\"><nobr>Reuters World News</nobr></td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"2\" align=\"right\"><a href=\"https://us.etrade.com/e/t/invest/SingleSymbolHeadline?symbol=TEAM&amp;latest=11/23/2019-09:34\">more headlines for TEAM...</a></td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"3\">\n\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n\t\t<tr bgcolor=\"#000000\">\n\t\t<td><img src=\"https://cdn.etrade.net/1/7d/images/spacer.gif\" width=\"500\" height=\"1\"></td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"3\"><b><a href=\"https://us.etrade.com/e/t/invest/quotesresearch?sym=CYBR\">CYBR</a></b></td>\n\t\t</tr>\n\t\t<TR>\n\t\t<td align=\"left\" colspan=\"2\" style=\"padding: 10px 0px 0px 0px;\"><strong>\n\t\tNov\n\t\t25</strong></td>\n\t\t</TR>\n\t\t<tr valign=\"top\">\n\t\t<td align=\"center\" nowrap=\"nowrap\">&nbsp;&nbsp;&nbsp;07:00 AM\n\t\t&nbsp;&nbsp;&nbsp;</td><td><a href=\"https://us.etrade.com/e/t/invest/Story?ID=STORYID%3D20191125DN002369&amp;provider=DowJones\">*DJ CyberArk Software Names Matthew Cohen as Revenue Chief</a>&nbsp;&nbsp;</td><td nowrap=\"nowrap\"><nobr>Reuters World News</nobr></td>\n\t\t</tr>\n\t\t<tr valign=\"top\">\n\t\t<td align=\"center\" nowrap=\"nowrap\">&nbsp;&nbsp;&nbsp;07:00 AM\n\t\t&nbsp;&nbsp;&nbsp;</td><td><a href=\"https://us.etrade.com/e/t/invest/Story?ID=STORYID%3D20191125SN004357&amp;provider=BusinessWire\">CyberArk Names Matthew Cohen Chief Revenue Officer</a>&nbsp;&nbsp;</td><td nowrap=\"nowrap\"><nobr>Business Wire</nobr></td>\n\t\t</tr>\n\t\t<TR>\n\t\t<td align=\"left\" colspan=\"2\" style=\"padding: 10px 0px 0px 0px;\"><strong>\n\t\tNov\n\t\t14</strong></td>\n\t\t</TR>\n\t\t<tr valign=\"top\">\n\t\t<td align=\"center\" nowrap=\"nowrap\">&nbsp;&nbsp;&nbsp;07:05 AM\n\t\t&nbsp;&nbsp;&nbsp;</td><td><a href=\"https://us.etrade.com/e/t/invest/Story?ID=STORYID%3D20191114DN005129&amp;provider=DowJones\">*DJ CyberArk Software Ltd. Announces Pricing of Private Offering of $500M of 0% Convertible Senior Notes Due 2024</a>&nbsp;&nbsp;</td><td nowrap=\"nowrap\"><nobr>Reuters World News</nobr></td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"2\" align=\"right\"><a href=\"https://us.etrade.com/e/t/invest/SingleSymbolHeadline?symbol=CYBR&amp;latest=11/14/2019-07:05\">more headlines for CYBR...</a></td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"3\">\n\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n\t\t<tr bgcolor=\"#000000\">\n\t\t<td><img src=\"https://cdn.etrade.net/1/7d/images/spacer.gif\" width=\"500\" height=\"1\"></td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"3\"><b><a href=\"https://us.etrade.com/e/t/invest/quotesresearch?sym=CPRT\">CPRT</a></b></td>\n\t\t</tr>\n\t\t<TR>\n\t\t<td align=\"left\" colspan=\"2\" style=\"padding: 10px 0px 0px 0px;\"><strong>\n\t\tNov\n\t\t22</strong></td>\n\t\t</TR>\n\t\t<tr valign=\"top\">\n\t\t<td align=\"center\" nowrap=\"nowrap\">&nbsp;&nbsp;&nbsp;09:01 AM\n\t\t&nbsp;&nbsp;&nbsp;</td><td><a href=\"https://us.etrade.com/e/t/invest/Story?ID=STORYID%3D20191122DN004285&amp;provider=DowJones\">DJ Copart Price Target Raised to $100.00/Share From $92.00 by SunTrust Robinson Humphrey</a>&nbsp;&nbsp;</td><td nowrap=\"nowrap\"><nobr>Reuters World News</nobr></td>\n\t\t</tr>\n\t\t<tr valign=\"top\">\n\t\t<td align=\"center\" nowrap=\"nowrap\">&nbsp;&nbsp;&nbsp;07:47 AM\n\t\t&nbsp;&nbsp;&nbsp;</td><td><a href=\"https://us.etrade.com/e/t/invest/Story?ID=STORYID%3D20191122MW000165&amp;provider=MarketWatch.com\">MW Copart stock price target raised to $100 from $92 at SunTrust RH</a>&nbsp;&nbsp;</td><td nowrap=\"nowrap\"><nobr>Reuters World News</nobr></td>\n\t\t</tr>\n\t\t<TR>\n\t\t<td align=\"left\" colspan=\"2\" style=\"padding: 10px 0px 0px 0px;\"><strong>\n\t\tNov\n\t\t21</strong></td>\n\t\t</TR>\n\t\t<tr valign=\"top\">\n\t\t<td align=\"center\" nowrap=\"nowrap\">&nbsp;&nbsp;&nbsp;\n\t\t04:24 PM\n\t\t&nbsp;&nbsp;&nbsp;</td><td><a href=\"https://us.etrade.com/e/t/invest/Story?ID=STORYID%3D20191121DN009915&amp;provider=DowJones\">DJ Copart's Management on Q1 2020 Results -- Earnings Call Transcript &gt;CPRT</a>&nbsp;&nbsp;</td><td nowrap=\"nowrap\"><nobr>Reuters World News</nobr></td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"2\" align=\"right\"><a href=\"https://us.etrade.com/e/t/invest/SingleSymbolHeadline?symbol=CPRT&amp;latest=11/21/2019-16:24\">more headlines for CPRT...</a></td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"3\">\n\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n\t\t<tr bgcolor=\"#000000\">\n\t\t<td><img src=\"https://cdn.etrade.net/1/7d/images/spacer.gif\" width=\"500\" height=\"1\"></td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"3\"><b><a href=\"https://us.etrade.com/e/t/invest/quotesresearch?sym=WORK\">WORK</a></b></td>\n\t\t</tr>\n\t\t<TR>\n\t\t<td align=\"left\" colspan=\"2\" style=\"padding: 10px 0px 0px 0px;\"><strong>\n\t\tNov\n\t\t25</strong></td>\n\t\t</TR>\n\t\t<tr valign=\"top\">\n\t\t<td align=\"center\" nowrap=\"nowrap\">&nbsp;&nbsp;&nbsp;\n\t\t01:15 PM\n\t\t&nbsp;&nbsp;&nbsp;</td><td><a href=\"https://us.etrade.com/e/t/invest/Story?ID=STORYID%3D20191125DN008404&amp;provider=DowJones\">DJ Burned by WeWork, SoftBank CEO Masayoshi Son Focuses on Cash Flow -- Barrons.com</a>&nbsp;&nbsp;</td><td nowrap=\"nowrap\"><nobr>Reuters World News</nobr></td>\n\t\t</tr>\n\t\t<TR>\n\t\t<td align=\"left\" colspan=\"2\" style=\"padding: 10px 0px 0px 0px;\"><strong>\n\t\tNov\n\t\t20</strong></td>\n\t\t</TR>\n\t\t<tr valign=\"top\">\n\t\t<td align=\"center\" nowrap=\"nowrap\">&nbsp;&nbsp;&nbsp;08:03 AM\n\t\t&nbsp;&nbsp;&nbsp;</td><td><a href=\"https://us.etrade.com/e/t/invest/Story?ID=STORYID%3D20191120MW000116&amp;provider=MarketWatch.com\">MW UPDATE: Microsoft Teams is making Slack investors nervous with its growth</a>&nbsp;&nbsp;</td><td nowrap=\"nowrap\"><nobr>Reuters World News</nobr></td>\n\t\t</tr>\n\t\t<TR>\n\t\t<td align=\"left\" colspan=\"2\" style=\"padding: 10px 0px 0px 0px;\"><strong>\n\t\tNov\n\t\t19</strong></td>\n\t\t</TR>\n\t\t<tr valign=\"top\">\n\t\t<td align=\"center\" nowrap=\"nowrap\">&nbsp;&nbsp;&nbsp;\n\t\t05:32 PM\n\t\t&nbsp;&nbsp;&nbsp;</td><td><a href=\"https://us.etrade.com/e/t/invest/Story?ID=STORYID%3D20191119MW000510&amp;provider=MarketWatch.com\">MW UPDATE: Slack shares slump as Microsoft continues to make corporate inroads</a>&nbsp;&nbsp;</td><td nowrap=\"nowrap\"><nobr>Reuters World News</nobr></td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td colspan=\"2\" align=\"right\"><a href=\"https://us.etrade.com/e/t/invest/SingleSymbolHeadline?symbol=WORK&amp;latest=11/19/2019-17:32\">more headlines for WORK...</a></td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t</table>\n\t\t<style> @media only screen and (max-width: 700px) { table[class=em_wrapper_mobile] { display:block !important; width:100% !important; } table[class=em_wrapper_desktop] { display:none !important; width:100% !important; } } .em_wrapper_mobile, .em_wrapper_desktop{ font-size: 16px !important; color: #000000;} .first_td { padding: 0 0 2px 15px; } .last_td { padding-bottom: 15px;} .smart-alert * {line-height: 24px;} .mob_date{ font-size: 14px; font-weight: bold;} .body-content , .sa-inbox-body{font-size: 12px !important; color: #000000 !important; } </style>\n\t\t</td><td width=\"20px\">\n\t\t &nbsp;\n\t\t </td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td valign=\"top\" align=\"center\" bgcolor=\"#eeeeee\"><a name=\"disclaimer\" id=\"disclaimer\"></a></td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td valign=\"top\" align=\"center\" style=\"border-top:5px solid #dbdbdb;\" bgcolor=\"#eeeeee\"></td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td bgcolor=\"#eeeeee\" align=\"center\" valign=\"top\">\n\t\t<table width=\"640\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"em_main_table_disc\">\n\t\t<tbody>\n\t\t<tr>\n\t\t<td align=\"center\" valign=\"top\">\n\t\t<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">\n\t\t<tbody>\n\t\t<tr>\n\t\t<td align=\"center\" valign=\"top\">\n\t\t<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">\n\t\t<tbody>\n\t\t<tr>\n\t\t<td align=\"left\" valign=\"top\" class=\"disclaimer_text\" style=\"font-family: Arial, sans-serif; font-size: 11px; line-height: 16px; padding: 20px; color: #555555;\">\n\t\t<p>Change or manage your alert <a href=\"https://us.etrade.com/e/t/alerts/setdelivery\" target=\"_blank\" style=\"color: #555555;text-decoration: underline; \">delivery preferences</a>.</p>\n\t\t<p>(c) 2019 E*TRADE Securities LLC, Member <a href=\"http://www.finra.org/\" target=\"_blank\" style=\"color: #555555;text-decoration: underline; \">FINRA</a>/<a href=\"http://www.sipc.org/\" target=\"_blank\" style=\"color: #555555;text-decoration: underline; \">SIPC</a>. All rights reserved. <a href=\"https://us.etrade.com/l/f/s/brokerage\" target=\"_blank\" style=\"color: #555555;text-decoration: underline; \">Important disclosures</a>.</p>\n\t\t</td>\n\t\t</tr>\n\t\t<tr></tr>\n\t\t<tr>\n\t\t<td height=\"28\" class=\"em_height\" style=\"line-height:1px;font-size:1px;\">&nbsp;\n\t\t <div class=\"em_non\" style=\" white-space:nowrap; font:20px courier; color:#eeeeee;\">\n\t\t &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>\n\t\t</td>\n\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t\t</td>\n\t\t</tr>\n\t\t</tbody>\n\t\t</table>\n\t\t</div>\n\t\t</body>\n\t\t</html>\n`\n}", "func (f Frag) HTML(ctx context.Context) (HTML, error) {\n\treturn nil, errHTMLOnPrimitive(\"Frag\")\n}", "func detectCharEncode(body []byte) CharEncode {\n\tdet := chardet.NewTextDetector()\n\tres, err := det.DetectBest(body)\n\tif err != nil {\n\t\treturn CharUnknown\n\t}\n\treturn typeOfCharEncode(res.Charset)\n}", "func parseHTMLFile(filePath string) (\n\timports map[string]importedPkg,\n\tcomDefs map[string]comDef,\n\terr error) {\n\n\timports = make(map[string]importedPkg)\n\tcomDefs = make(map[string]comDef)\n\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnodes, err := whtml.Parse(file)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor _, node := range nodes {\n\t\tif node.Type == whtml.ElementNode {\n\t\t\t// import tag\n\t\t\tif node.Data == importSTag {\n\t\t\t\timpName, pkg, err := htmlImportTag(node)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\n\t\t\t\timports[impName] = pkg\n\t\t\t}\n\n\t\t\t// component definition element\n\t\t\tif isCapitalized(node.Data) {\n\t\t\t\tcleanGarbageTextChildren(node)\n\n\t\t\t\tcomDefs[node.Data] = comDef{\n\t\t\t\t\tname: node.Data,\n\t\t\t\t\tmarkup: node.FirstChild,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn imports, comDefs, nil\n}", "func templatesCartHtml() (*asset, error) {\n\tpath := filepath.Join(rootDir, \"templates/cart.html\")\n\tname := \"templates/cart.html\"\n\tbytes, err := bindataRead(path, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error reading asset info %s at %s: %v\", name, path, err)\n\t}\n\n\ta := &asset{bytes: bytes, info: fi}\n\treturn a, err\n}", "func GetParseableHTML(url string) (*html.Node, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn root, nil\n}", "func getHTML(link *url.URL) ([]byte, error) {\n resp, err := http.Get(link.String())\n if err != nil {\n return nil, err\n }\n defer resp.Body.Close()\n\n return ioutil.ReadAll(resp.Body)\n}", "func (*HTMLData) Descriptor() ([]byte, []int) {\n\treturn file_adarender_proto_rawDescGZIP(), []int{2}\n}", "func FontFaceSetFromJS(value js.Value) *FontFaceSet {\n\tif typ := value.Type(); typ == js.TypeNull || typ == js.TypeUndefined {\n\t\treturn nil\n\t}\n\tret := &FontFaceSet{}\n\tret.Value_JS = value\n\treturn ret\n}" ]
[ "0.5426141", "0.50550556", "0.45451325", "0.45442522", "0.45194867", "0.44955236", "0.442707", "0.43587136", "0.433263", "0.43174842", "0.4248463", "0.42175716", "0.41477165", "0.41116217", "0.40516052", "0.40427002", "0.4034448", "0.40284556", "0.40279502", "0.40227816", "0.40223637", "0.39954275", "0.39610046", "0.39319885", "0.39262366", "0.39161232", "0.39024878", "0.38856316", "0.38667193", "0.3866025", "0.38582626", "0.381653", "0.3816174", "0.3812356", "0.38089785", "0.37981528", "0.37934932", "0.37703454", "0.37596023", "0.37582788", "0.37420118", "0.37242383", "0.3708115", "0.3703899", "0.36633363", "0.36537072", "0.3644272", "0.36385188", "0.36316863", "0.36260596", "0.3625383", "0.3605845", "0.35790414", "0.35653046", "0.3553057", "0.355004", "0.35327813", "0.353159", "0.35309568", "0.35289964", "0.3527658", "0.35210416", "0.35050547", "0.3496213", "0.34928572", "0.34674475", "0.3465977", "0.34384018", "0.34330043", "0.34260964", "0.34237722", "0.34151852", "0.34142396", "0.34088162", "0.3393315", "0.33805257", "0.33693752", "0.33575967", "0.33379614", "0.33359492", "0.3330919", "0.33279914", "0.3327162", "0.33140174", "0.3311009", "0.3299002", "0.32957107", "0.32956192", "0.329013", "0.32806224", "0.32751876", "0.3271302", "0.32613137", "0.32502636", "0.3249725", "0.32449913", "0.32372224", "0.32289717", "0.32270944", "0.3225044" ]
0.66964644
0
trimLWS trims whitespace from beginning of the input. TODO: find a way to call trimLWS once per detection instead of once in each detector which needs the trimmed input.
func trimLWS(in []byte) []byte { firstNonWS := 0 for ; firstNonWS < len(in) && isWS(in[firstNonWS]); firstNonWS++ { } return in[firstNonWS:] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func LTrim(p projection) *trimFunc {\n\treturn &trimFunc{\n\t\tsubject: p.(element),\n\t\tsel: p.from(),\n\t\tlocation: TRIM_LEADING,\n\t}\n}", "func (d *Dialer) LTRIM(key string, start int, stop int) (string, error) {\n\tcmd := []string{\"LTRIM\", key, strconv.Itoa(start), strconv.Itoa(stop)}\n\tresult, err := d.Resp.cmd(cmd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn result.(string), nil\n}", "func trimLeadingWhiteSpace(buf string) string {\n\treturn strings.TrimLeft(buf, \" \")\n}", "func (n *nodeHeader) leftTrimPrefix(l uint16) {\n\tif l < 1 {\n\t\treturn\n\t}\n\tpLen, pBytes := n.prefixFields()\n\tif l > *pLen {\n\t\tl = *pLen\n\t}\n\tnewLen := *pLen - uint16(l)\n\tcopy(pBytes[0:newLen], pBytes[l:*pLen])\n\t*pLen = newLen\n}", "func trimLeadingWhiteSpace(s []byte) []byte {\n\tfor (len(s) > 0) && ((s[0] == ' ') || (s[0] == '\\t')) {\n\t\ts = s[1:]\n\t}\n\treturn s\n}", "func TrimNL(s string) string {\n\ts = strings.TrimSuffix(s, \"\\n\")\n\ts = strings.TrimSuffix(s, \"\\r\")\n\n\treturn s\n}", "func LTrimChars(p projection, chars string) *trimFunc {\n\treturn &trimFunc{\n\t\tsubject: p.(element),\n\t\tsel: p.from(),\n\t\tlocation: TRIM_LEADING,\n\t\tchars: chars,\n\t}\n}", "func TestTrim(t *testing.T) {\n\ttext := \"Hola Mundo TDA\"\n\tt.Logf(\"text:[%s]\", text)\n\tt.Logf(\"trim:[%s]\", utl.Trim(text))\n}", "func trimLeadingWhiteSpaceAndNewLines(s []byte) []byte {\n\tfor (len(s) > 0) && ((s[0] == ' ') || (s[0] == '\\t') || (s[0] == '\\n')) {\n\t\ts = s[1:]\n\t}\n\treturn s\n}", "func filterTrim(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value {\n\treturn strings.TrimSpace(stick.CoerceString(val))\n}", "func TrimLeadingSpaces(p []byte) []byte {\n\tfor i := 0; i < len(p); i++ {\n\t\tif p[i] != 0x20 && p[i] != '\\t' {\n\t\t\treturn p[i:]\n\t\t}\n\t}\n\t// it was all spaces\n\treturn p[:0]\n}", "func removeWhiteSpace(input string) string {\n\tif runtime.GOOS == \"windows\" {\n\t\tinput = strings.TrimRight(input, \"\\r\\n\")\n\t} else {\n\t\tinput = strings.TrimRight(input, \"\\n\")\n\t}\n\treturn input\n}", "func splitWidthWords(s string, w int) []string {\n\tvar (\n\t\tsl []string\n\t\tline string\n\t)\n\tfor _, word := range splitWords(s) {\n\t\tif uLen(line)+uLen(word) < w {\n\t\t\tline += word\n\t\t} else {\n\t\t\ttrimmedLine := strings.TrimSpace(line)\n\t\t\tif strings.HasSuffix(trimmedLine, \"--\") {\n\t\t\t\t// Move the double dash to the beginning of the next line\n\t\t\t\ttrimmedLine = trimmedLine[:uLen(trimmedLine)-2]\n\t\t\t\tsl = append(sl, trimmedLine)\n\t\t\t\tline = \"-- \" + word\n\t\t\t} else {\n\t\t\t\tsl = append(sl, trimmedLine)\n\t\t\t\tline = word\n\t\t\t}\n\t\t}\n\t}\n\tif uLen(line) == 0 {\n\t\treturn sl\n\t}\n\treturn append(sl, strings.TrimSpace(line))\n}", "func trimWS(input string) string {\n\n\tvar out strings.Builder\n\tfor _, v := range input {\n\t\tif !(v == '\\u0009' || v == '\\u0020' || v == '\\u000A' || v == '\\u000D' || v == ',') {\n\t\t\tout.WriteRune(v)\n\t\t}\n\t}\n\treturn out.String()\n\n}", "func TrimSpacesList(ls []string) []string {\n\tout := []string{}\n\tfor _, str := range ls {\n\t\tv := strings.TrimSpace(str)\n\t\tif v == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, v)\n\t}\n\treturn out\n}", "func trim(s string) string {\n\tfor len(s) > 0 {\n\t\tif s[0] <= ' ' {\n\t\t\ts = s[1:]\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tfor len(s) > 0 {\n\t\tif s[len(s)-1] <= ' ' {\n\t\t\ts = s[:len(s)-1]\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\treturn s\n}", "func (seg *Segmenter) CutTrim(str string, hmm ...bool) []string {\n\ts := seg.Cut(str, hmm...)\n\treturn seg.Trim(s)\n}", "func (s *Str) TrimLeft(cutset string) *Str {\n\ts.val = strings.TrimLeft(s.val, cutset)\n\treturn s\n}", "func TrimToVisualLength(message string, length int) string {\n\tfor VisualLength(message) > length && len(message) > 1 {\n\t\tmessage = message[:len(message)-1]\n\t}\n\treturn message\n}", "func trimTrailingWhiteSpace(s []byte) []byte {\n\tfor (len(s) > 0) && ((s[len(s)-1] == ' ') || (s[len(s)-1] == '\\t')) {\n\t\ts = s[:len(s)-1]\n\t}\n\treturn s\n}", "func trim(s []byte) []byte {\n\ti := 0\n\tfor i < len(s) && (s[i] == ' ' || s[i] == '\\t') {\n\t\ti++\n\t}\n\tn := len(s)\n\tfor n > i && (s[n-1] == ' ' || s[n-1] == '\\t') {\n\t\tn--\n\t}\n\treturn s[i:n]\n}", "func trim(s []byte) []byte {\n\ti := 0\n\tfor i < len(s) && (s[i] == ' ' || s[i] == '\\t') {\n\t\ti++\n\t}\n\tn := len(s)\n\tfor n > i && (s[n-1] == ' ' || s[n-1] == '\\t') {\n\t\tn--\n\t}\n\treturn s[i: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}", "func trimWave(buf []int16) {\n\tif len(buf) == 0 {\n\t\treturn\n\t}\n\tbufsize := len(buf)\n\tcut := bufsize - 1\n\tvar last int16\n\tfor i := range buf {\n\t\tif i == 0 {\n\t\t\tlast = buf[cut]\n\t\t}\n\t\tif buf[cut] < last {\n\t\t\t// falling\n\t\t\tif buf[cut] < 0 && buf[cut] < 32 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tlast = buf[cut]\n\t\tif i > 1024 {\n\t\t\t// too long\n\t\t\tcut = len(buf) - 1\n\t\t\tbreak\n\t\t}\n\t\tcut--\n\t\tif cut == 0 {\n\t\t\t// volume must be low\n\t\t\tcut = len(buf) - 1\n\t\t\tbreak\n\t\t}\n\t}\n\tfor i := cut; i < bufsize; i++ {\n\t\tbuf[i] = 0\n\t}\n}", "func Trim(s string, l int, ellipsis string) string {\n\tif len(s) < l {\n\t\treturn s\n\t}\n\treturn s[:l] + ellipsis\n}", "func TrimEleSpaceAndRemoveEmpty(vs []string) (r []string) {\n\tfor _, v := range vs {\n\t\tv = strings.TrimSpace(v)\n\t\tif v != \"\" {\n\t\t\tr = append(r, v)\n\t\t}\n\t}\n\n\treturn\n}", "func TrimAllSpaceAndNewline(input string) string {\n\toutput := input\n\tfor _, f := range []string{\"\\n\", \"\\t\", \" \"} {\n\t\toutput = strings.Replace(output, f, \"\", -1)\n\t}\n\n\treturn output\n}", "func RTrim(p projection) *trimFunc {\n\treturn &trimFunc{\n\t\tsubject: p.(element),\n\t\tsel: p.from(),\n\t\tlocation: TRIM_TRAILING,\n\t}\n}", "func trim(name string) string {\n\treturn strings.TrimPrefix(name, Prefix)\n}", "func StripStart(str string) string {\n\treturn regexp.MustCompile(`^\\s+`).ReplaceAllString(str, \"\")\n}", "func TrimRedundantSpaces(text string) string {\n\ttext = spaceRegex.ReplaceAllString(text, \" \")\n\treturn strings.TrimSpace(text)\n}", "func RemoveZeroWidthNonJoiner(s string) string {\n\treturn strings.Replace(s, string(ZWNJ), empty, -1)\n}", "func trimStringN(c *C.char, l C.int) string {\n\tvar rc string\n\ts := C.GoStringN(c, l)\n\ti := strings.IndexByte(s, 0)\n\tif i == -1 {\n\t\trc = s\n\t} else {\n\t\trc = s[0:i]\n\t}\n\treturn strings.TrimSpace(rc)\n}", "func (e EmbeddedString) Trim() string {\n\ts := string(e)\n\tif strings.HasPrefix(s, \"// Copyright \") {\n\t\tif i := strings.Index(s, \"\\n\\n\"); i >= 0 {\n\t\t\ts = s[i+2:]\n\t\t}\n\t}\n\treturn s\n}", "func execTrimString(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := textproto.TrimString(args[0].(string))\n\tp.Ret(1, ret)\n}", "func RemoveZeroWidthNoBreakSpace(s string) string {\n\treturn strings.Replace(s, string(ZWNBSP), empty, -1)\n}", "func (s *Stringish) TrimPrefixSpaces() *Stringish {\n\treturn s.TrimPrefix(\" \")\n}", "func nlnl(s string) string {\n\treturn strings.TrimLeft(s, \"\\n\")\n}", "func (b *Bar) TrimLeftSpace() *Bar {\n\tif isClosed(b.done) {\n\t\treturn b\n\t}\n\tb.trimLeftCh <- true\n\treturn b\n}", "func trim(strn string) string {\n\treturn strings.Trim(strn, \" \\t\\n\\r\")\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 (f *File) TrimSilence() {\n\t// TODO: calibrate constants\n\tf.AudioData.TrimSilent(0.03, 0.25)\n}", "func leadingWhitespace(s string) string {\n\tfor i, r := range s {\n\t\tif !unicode.IsSpace(r) {\n\t\t\treturn s[:i]\n\t\t}\n\t}\n\treturn s\n}", "func Trim(p projection) *trimFunc {\n\treturn &trimFunc{\n\t\tsubject: p.(element),\n\t\tsel: p.from(),\n\t\tlocation: TRIM_BOTH,\n\t}\n}", "func trimmed(bs []byte) []byte {\n\tfor i, b := range bs {\n\t\tif b == 0x00 {\n\t\t\treturn bs[:i]\n\t\t}\n\t}\n\treturn bs\n}", "func trimToLength(p []string, length int) (trimmedP []string) {\n trimmedP = make([]string, len(p))\n for i := range p {\n r := []rune(p[i])\n newR := make([]rune, length)\n for j := 0; j < length; j++ {\n newR[j] = r[j]\n }\n trimmedP[i]=string(newR)\n }\n return trimmedP\n}", "func trimLeft(r *syntax.Regexp) (bool, *syntax.Regexp) {\n\tif eqPrefixAnyRegex(r, patDotStar, patNullBeginDotStar) {\n\t\ttmp := *r\n\t\ttmp.Sub = tmp.Sub[1:]\n\t\treturn true, &tmp\n\t}\n\n\treturn false, r\n}", "func trimCut(label []byte, maxlen int, left, right string) []byte {\n\ttrim := bytes.TrimLeft(label, left)\n\tsize := min(len(trim), maxlen)\n\thead := bytes.TrimRight(trim[:size], right)\n\tif len(head) == size {\n\t\treturn head\n\t}\n\ttail := bytes.TrimLeft(trim[size:], right)\n\tif len(tail) > 0 {\n\t\treturn append(head, tail[:min(len(tail), size-len(head))]...)\n\t}\n\treturn head\n}", "func TrimLeft(cutset string) MapFunc {\n\treturn func(s string) string { return strings.TrimLeft(s, cutset) }\n}", "func Trim(read bioutil.Read, mean int, window int, minLength int) (cutoff int, originalMean float32, finalMean float32) {\n\tif window > minLength {\n\t\tpanic(\"QTrim: window must be <= minimum read length\")\n\t}\n\n\tline := read.Quality()\n\tlength := read.Length()\n\n\ttotal := 0\n\twindowTotal := 0\n\tfor i, b := range line {\n\t\tquality := Score(b)\n\t\ttotal += quality\n\t\tif i > length-window {\n\t\t\twindowTotal += quality\n\t\t}\n\t}\n\n\toriginalMean = float32(total) / float32(length)\n\n\twindowCompare := mean * window\n\tcutoff = length\n\tif cutoff <= minLength || cutoff <= window { // Discard this sequence\n\t\treturn 0, originalMean, 0\n\t}\n\tfor !(total >= mean*cutoff && windowTotal >= windowCompare) {\n\t\tif cutoff <= minLength || cutoff <= window { // Discard this sequence\n\t\t\treturn 0, originalMean, 0\n\t\t}\n\t\tcutoff--\n\t\ttrimmedScore := Score(line[cutoff])\n\t\ttotal -= trimmedScore\n\t\twindowTotal = windowTotal - trimmedScore + Score(line[cutoff-window])\n\t}\n\tfor Score(line[cutoff-1]) < mean {\n\t\tif cutoff <= minLength || cutoff <= window { // Discard this sequence\n\t\t\treturn 0, originalMean, 0\n\t\t}\n\t\tcutoff--\n\t}\n\tfinalMean = float32(total) / float32(cutoff)\n\treturn\n}", "func stripWhiteSpace(str string) string {\n\treturn strings.ReplaceAll(str, \" \", \"\")\n}", "func TrimTrailingSpaces(p []byte) []byte {\n\tfor i := len(p) - 1; i >= 0; i-- {\n\t\tif p[i] != 0x20 && p[i] != '\\n' && p[i] != '\\t' {\n\t\t\treturn p[:i+1]\n\t\t}\n\t}\n\t// it was all spaces\n\treturn p[:0]\n}", "func TrimLeft(chars string, operand string) string { return strings.TrimLeft(operand, chars) }", "func vtlCleanup(b string) (string, error) {\n\tswitch {\n\tcase strings.HasPrefix(b, \"=\"):\n\t\tfallthrough\n\tcase strings.Contains(b, \"Luna\"):\n\t\treturn \"\", nil\n\t}\n\treturn strings.ReplaceAll(b, \"#\", \"\"), nil\n}", "func StripLeftTabs(s string) string { return cptNC.stripLeftTabs(s) }", "func TrimLineSpaces(str string) string {\n\treturn TrimLineSpaces2(str, \"\")\n}", "func LeftTrim(str, chars string) string {\n\tif chars == \"\" {\n\t\treturn strings.TrimLeftFunc(str, unicode.IsSpace)\n\t}\n\tr, _ := regexp.Compile(\"^[\" + chars + \"]+\")\n\treturn r.ReplaceAllString(str, \"\")\n}", "func trimS(s string) string {\r\n\treturn strings.TrimSpace(s)\r\n}", "func Trim(text string) string {\n\treturn trimRx.FindStringSubmatch(text)[1]\n}", "func TrimAll(s string) string {\n\treturn strings.Join(strings.Fields(s), \" \")\n}", "func (chars *Chars) TrimLength() uint16 {\n\tif chars.trimLengthKnown {\n\t\treturn chars.trimLength\n\t}\n\tchars.trimLengthKnown = true\n\tvar i int\n\tlen := chars.Length()\n\tfor i = len - 1; i >= 0; i-- {\n\t\tchar := chars.Get(i)\n\t\tif !unicode.IsSpace(char) {\n\t\t\tbreak\n\t\t}\n\t}\n\t// Completely empty\n\tif i < 0 {\n\t\treturn 0\n\t}\n\n\tvar j int\n\tfor j = 0; j < len; j++ {\n\t\tchar := chars.Get(j)\n\t\tif !unicode.IsSpace(char) {\n\t\t\tbreak\n\t\t}\n\t}\n\tchars.trimLength = AsUint16(i - j + 1)\n\treturn chars.trimLength\n}", "func (p *Parser) Trim(input string) string {\n\tt := strings.Replace(strings.Replace(input, \"<output>\", \"\", -1), \"</output>\", \"\", -1)\n\tt1 := strings.Replace(strings.Replace(t, \"<configuration-information>\", \"\", -1), \"</configuration-information>\", \"\", -1)\n\treturn strings.Replace(strings.Replace(t1, \"<configuration-output>\", \"\", -1), \"</configuration-output>\", \"\", -1)\n}", "func (ls *linestate) deletePrevWord() {\n\toldPos := ls.pos\n\t// remove spaces\n\tfor ls.pos > 0 && ls.buf[ls.pos-1] == ' ' {\n\t\tls.pos--\n\t}\n\t// remove word\n\tfor ls.pos > 0 && ls.buf[ls.pos-1] != ' ' {\n\t\tls.pos--\n\t}\n\tls.buf = append(ls.buf[:ls.pos], ls.buf[oldPos:]...)\n\tls.refreshLine()\n}", "func RemoveZeroWidthJoiner(s string) string {\n\treturn strings.Replace(s, string(ZWJ), empty, -1)\n}", "func (gc *LinearConverter) TrimLatitude() float64 {\n\treturn 16\n}", "func trimWhitespaces(value string) string {\n\treturn strings.Trim(value, \"\")\n}", "func StripLeftTabsOnly(s string) string { return cptNC.stripLeftTabsOnly(s) }", "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 (sampler TwitterServerSampler) Trim(sample *Sample) {\n\ttrimmed := make(Metrics)\n\tfor k, v := range sample.Metrics {\n\t\tif rtRequest.MatchString(k) || rtLatency.MatchString(k) || jvmStat.MatchString(k) {\n\t\t\ttrimmed[k] = v\n\t\t}\n\t}\n\tsample.Metrics = trimmed\n}", "func (r *StreamReader) stripEmpty() {\n\tfor len(r.current) > 0 && len(r.current[0].Bytes) == 0 {\n\t\tr.current = r.current[1:]\n\t\tr.lossReported = false\n\t}\n}", "func TrimWGConfig() opt.Bool {\n\tv, _ := controlTrimWGConfig.Load().(opt.Bool)\n\treturn v\n}", "func RemoveZeroWidthSpace(s string) string {\n\treturn strings.Replace(s, string(ZWSP), empty, -1)\n}", "func (m *Model) deleteWordLeft() bool {\n\tif m.pos == 0 || len(m.value) == 0 {\n\t\treturn false\n\t}\n\n\tif m.EchoMode != EchoNormal {\n\t\treturn m.deleteBeforeCursor()\n\t}\n\n\t// Linter note: it's critical that we acquire the initial cursor position\n\t// here prior to altering it via SetCursor() below. As such, moving this\n\t// call into the corresponding if clause does not apply here.\n\toldPos := m.pos //nolint:ifshort\n\n\tblink := m.setCursor(m.pos - 1)\n\tfor unicode.IsSpace(m.value[m.pos]) {\n\t\tif m.pos <= 0 {\n\t\t\tbreak\n\t\t}\n\t\t// ignore series of whitespace before cursor\n\t\tblink = m.setCursor(m.pos - 1)\n\t}\n\n\tfor m.pos > 0 {\n\t\tif !unicode.IsSpace(m.value[m.pos]) {\n\t\t\tblink = m.setCursor(m.pos - 1)\n\t\t} else {\n\t\t\tif m.pos > 0 {\n\t\t\t\t// keep the previous space\n\t\t\t\tblink = m.setCursor(m.pos + 1)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif oldPos > len(m.value) {\n\t\tm.value = m.value[:m.pos]\n\t} else {\n\t\tm.value = append(m.value[:m.pos], m.value[oldPos:]...)\n\t}\n\n\treturn blink\n}", "func StripLow(str string, keepNewLines bool) string {\n\tchars := \"\"\n\tif keepNewLines {\n\t\tchars = \"\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F\"\n\t} else {\n\t\tchars = \"\\x00-\\x1F\\x7F\"\n\t}\n\treturn BlackList(str, chars)\n}", "func trimToPrefix(str, prefix string) string {\n\ti := strings.Index(str, prefix)\n\tif i < 0 {\n\t\treturn str\n\t}\n\treturn str[i:]\n}", "func trimSpace(b []byte) string {\n\treturn string(bytes.TrimRight(b, \" \"))\n}", "func trimSpace(b []byte) string {\n\treturn string(bytes.TrimRight(b, \" \"))\n}", "func (seg *Segmenter) Trim(s []string) (r []string) {\n\tfor i := 0; i < len(s); i++ {\n\t\tsi := FilterSymbol(s[i])\n\t\tif !seg.NotStop && seg.IsStop(si) {\n\t\t\tsi = \"\"\n\t\t}\n\n\t\tif si != \"\" {\n\t\t\tr = append(r, si)\n\t\t}\n\t}\n\n\treturn\n}", "func wordWrap(s string, width int) []string {\n\ts = colorPattern.ReplaceAllString(s, \"\")\n\tif len(s) <= width {\n\t\treturn []string{s}\n\t}\n\n\tvar wrapped []string\n\tfor len(s) > 0 {\n\t\textract := runewidth.Truncate(s, width, \"\")\n\t\tif len(extract) == 0 {\n\t\t\tgr := uniseg.NewGraphemes(s)\n\t\t\tgr.Next()\n\t\t\t_, to := gr.Positions()\n\t\t\textract = s[:to]\n\t\t}\n\t\tif len(extract) < len(s) {\n\t\t\t// Add any spaces from the next line.\n\t\t\tif spaces := spacePattern.FindStringIndex(s[len(extract):]); spaces != nil && spaces[0] == 0 {\n\t\t\t\textract = s[:len(extract)+spaces[1]]\n\t\t\t}\n\n\t\t\t// Can we split before the mandatory end?\n\t\t\tmatches := boundaryPattern.FindAllStringIndex(extract, -1)\n\t\t\tif len(matches) > 0 {\n\t\t\t\t// Yes. Let's split there.\n\t\t\t\textract = extract[:matches[len(matches)-1][1]]\n\t\t\t}\n\t\t}\n\t\twrapped = append(wrapped, extract)\n\t\ts = s[len(extract):]\n\t}\n\treturn wrapped\n}", "func trimLeftSlash(name string) string {\n\treturn strings.TrimPrefix(name, \"/\")\n}", "func TrimExtraSpaces(s string) string {\n\tspace := regexp.MustCompile(`\\s+`)\n\ts = space.ReplaceAllString(s, \" \")\n\ts = strings.TrimPrefix(s, \" \")\n\ts = strings.TrimSuffix(s, \" \")\n\treturn s\n}", "func (rf *Raft) TrimLog(lastIncludedIndex int, lastIncludedTerm int) []byte {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\trf.lastIncludedIndex = lastIncludedIndex\n\trf.lastIncludedTerm = lastIncludedTerm\n\ttrimIdx := rf.getTrimmedLogIndex(rf.lastIncludedIndex)\n\tif trimIdx < len(rf.log) {\n\t\trf.log = rf.log[trimIdx+1:]\n\t} else {\n\t\trf.log = []LogEntry{}\n\t}\n\trf.Log(LogInfo, \"New Snapshot loaded.\\n - LastIncludedIndex\", lastIncludedIndex, \"\\n - LastIncludedTerm\", lastIncludedTerm, \"\\n - rf.log\", rf.log)\n\treturn rf.GetStateBytes(false)\n}", "func RemoveMiddleSpaces(s string) string {\n\treturn strings.Join(Tokenize(s), \" \")\n}", "func trim_string_before_s(s string, x string) (r string) {\n\tif idx := strings.LastIndex(s, x); idx != -1 {\n\t\treturn s[idx+1:]\n\t}\n\treturn s\n}", "func TrimmedString(ss []string, target string) int {\n\ttarget = strings.TrimSpace(target)\n\n\treturn IndexOf(len(ss), func(i int) bool { return strings.TrimSpace(ss[i]) == target })\n}", "func (l Line) BytesTrimmed() []byte {\n\t// inline optimization with goto instead of for\nLoop:\n\tif len(l.line) == 0 {\n\t\treturn l.line\n\t}\n\n\tlast := l.line[len(l.line)-1]\n\tif last == '\\n' || last == '\\r' || last == ' ' {\n\t\tl.line = l.line[:len(l.line)-1]\n\t} else {\n\t\treturn l.line\n\t}\n\tgoto Loop\n}", "func TrimLeftChar(s string) string {\n\tfor i := range s {\n\t\tif i > 0 {\n\t\t\treturn s[i:]\n\t\t}\n\t}\n\treturn s[:0]\n}", "func (s *Stringish) TrimPrefix(prefix string) *Stringish {\n\ts.str = strings.TrimPrefix(s.str, prefix)\n\treturn s\n}", "func trimSelf(ss []string, s string) []string {\n\tif !containsStr(ss, s) {\n\t\treturn ss\n\t}\n\tret := make([]string, 0, len(ss))\n\tfor _, v := range ss {\n\t\tif v != s {\n\t\t\tret = append(ret, v)\n\t\t}\n\t}\n\treturn ret\n}", "func (l Line) StringTrimmed() string {\n\ttrimmedString := l.BytesTrimmed()\n\treturn *(*string)(unsafe.Pointer(&trimmedString))\n}", "func (l *FSList) TruncFilter() {\n\tfl := len(l.Filter)\n\tif fl <= 0 {\n\t\treturn\n\t}\n\tl.Filter = l.Filter[:fl-1]\n}", "func (b *TestDriver) FlatTrim() (err error) {\n\treturn err\n}", "func (t *Text) TrimSpace() *Text {\n\tleft := 0\n\toutput := strings.TrimLeftFunc(t.output, func(r rune) bool {\n\t\tif unicode.IsSpace(r) {\n\t\t\tleft++\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\n\toutput = strings.TrimRightFunc(output, unicode.IsSpace)\n\tt.lines[t.textLines] = output\n\treturn t\n}", "func (t *standard) trim() {\n\n\tt.trimIfAdded()\n\tt.trimIfSubtracted()\n\n\tif t.Day() < 0 {\n\t\tpanic(ErrNegativeTime)\n\t}\n\n}", "func execTrimBytes(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := textproto.TrimBytes(args[0].([]byte))\n\tp.Ret(1, ret)\n}", "func RemoveTralingNewline(s string) string {\n\ts = strings.TrimSuffix(s, \"\\n\")\n\n\tif runtime.GOOS == \"windows\" {\n\t\ts = strings.TrimSuffix(s, \"\\r\")\n\t}\n\n\treturn s\n}", "func trimTrailingWhitespace(details string) string {\n\treturn strings.TrimSuffix(details, \" \")\n}", "func Wton(w string) (n int64, err error) {\n\twords := strings.FieldsFunc(w, func(r rune) bool {\n\t\treturn r == '\t' || r == '-'\n\t})\n\tlog.Println(words)\n\treturn\n}", "func ScanlineTrim() string {\n\treturn strings.TrimSpace(Scanline())\n}", "func (o *DcimRacksListParams) SetOuterWidthLt(outerWidthLt *string) {\n\to.OuterWidthLt = outerWidthLt\n}" ]
[ "0.66111934", "0.57674", "0.56255776", "0.55611163", "0.55452734", "0.55432266", "0.54476035", "0.54053825", "0.5395027", "0.538255", "0.5317298", "0.5231223", "0.51944345", "0.51682323", "0.5155594", "0.51345545", "0.49562576", "0.49432087", "0.49140376", "0.48905653", "0.48887295", "0.48887295", "0.48846248", "0.48446044", "0.48317695", "0.48315433", "0.4807658", "0.47970065", "0.47928318", "0.47831514", "0.47796902", "0.47628602", "0.4749587", "0.47495767", "0.47274747", "0.47248685", "0.47229046", "0.47060895", "0.47051248", "0.47013062", "0.46821105", "0.46672824", "0.4660359", "0.46603528", "0.4650749", "0.46456128", "0.46422908", "0.46390602", "0.4638651", "0.46350703", "0.4620566", "0.45912346", "0.4583163", "0.45655072", "0.45558602", "0.45518798", "0.45498216", "0.45447665", "0.45427367", "0.45402014", "0.45358506", "0.4535446", "0.45349726", "0.45347202", "0.45337668", "0.45258233", "0.45216748", "0.45199656", "0.4512367", "0.45028198", "0.44889116", "0.44867384", "0.44819507", "0.4481482", "0.44790986", "0.44776228", "0.44776228", "0.44703266", "0.4469614", "0.44632062", "0.4460399", "0.44580364", "0.44470683", "0.4435893", "0.44330266", "0.43995792", "0.43988842", "0.4384892", "0.43805182", "0.4380316", "0.43736342", "0.43730393", "0.4362156", "0.43563774", "0.43507737", "0.43454835", "0.4341882", "0.43401316", "0.4340042", "0.43370724" ]
0.75690883
0
Initialize the generator from a seed
func (mt *MersenneTwister) seedMT(seed int32) { mt.index = mt.n mt.arr[0] = seed for i := 1; i < mt.n; i++ { // loop over each element mt.arr[i] = ((1 << mt.w) - 1) & (mt.f*(mt.arr[i-1]^(mt.arr[i-1]>>(mt.w-2))) + int32(i)) } mt.seeded = true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Seed(seed int64) { globalRand.Seed(seed) }", "func (s CrSource) Seed(int64) {}", "func (rng *Rng) Seed(seed int64) {\n\trng.State = uint64(seed)\n}", "func (gen *CMWC) Seed(seed int64) {\n\tgen.lock.Lock()\n\tdefer gen.lock.Unlock()\n\n\tgen.c = cmwcC\n\ts := uint32(seed)\n\tfor i := 0; i < 4096; i++ {\n\t\ts = s ^ s<<uint(i%63)\n\t\tgen.state[i] = s ^ uint32(seed)\n\t}\n}", "func Seed(seed int64) {\n\tr.Seed(seed)\n}", "func (r *Rand) Seed(s int64) {\n\t*r = Rand(uint64(s))\n}", "func (g *Generator) Seed(seed int64) {\n\tif _, err := g.hash.Write(int64ToBytes(seed)); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := g.reseed(); err != nil {\n\t\tpanic(err)\n\t}\n}", "func Init(seed int) {\n\tif seed <= 0 {\n\t\tseed = int(time.Now().Unix())\n\t}\n\trand.Seed(int64(seed))\n}", "func Seed (seed int64) {\n\tlocalRand.Seed(seed)\n}", "func (r *IncrementRand) Seed(seed int64) {\n\tr.seed = seed\n\tr.value = seed\n}", "func (r *OrgBucketID) Seed(seed int64) {\n\tr.m.Lock()\n\tr.src = rand.New(rand.NewSource(seed))\n\tr.m.Unlock()\n}", "func (rng *splitMix64Source) Seed(seed int64) {\n\trng.state = uint64(seed)\n}", "func (r *ConstantRand) Seed(seed int64) {\n\tr.seed = seed\n}", "func (R *RAND) Seed(rawlen int, raw []byte) { /* initialise from at least 128 byte string of raw random entropy */\n\tvar b [4]byte\n\tsh := NewHASH256()\n\tR.pool_ptr = 0\n\n\tfor i := 0; i < rand_NK; i++ {\n\t\tR.ira[i] = 0\n\t}\n\tif rawlen > 0 {\n\t\tfor i := 0; i < rawlen; i++ {\n\t\t\tsh.Process(raw[i])\n\t\t}\n\t\tdigest := sh.Hash()\n\n\t\t/* initialise PRNG from distilled randomness */\n\n\t\tfor i := 0; i < 8; i++ {\n\t\t\tb[0] = digest[4*i]\n\t\t\tb[1] = digest[4*i+1]\n\t\t\tb[2] = digest[4*i+2]\n\t\t\tb[3] = digest[4*i+3]\n\t\t\tR.sirand(pack(b))\n\t\t}\n\t}\n\tR.fill_pool()\n}", "func Initialisieren (keim int64) {\n\trand.Seed (keim)\n}", "func (src *MT19937_64) Seed(seed uint64) {\n\tsrc.mt[0] = seed\n\tfor src.mti = 1; src.mti < mt19937_64NN; src.mti++ {\n\t\tsrc.mt[src.mti] = (6364136223846793005*(src.mt[src.mti-1]^(src.mt[src.mti-1]>>62)) + src.mti)\n\t}\n}", "func (pcg *PCGSource) Seed(seed uint64) {\n\tpcg.low = seed\n\tpcg.high = seed // TODO: What is right?\n}", "func init() {\n\t\n\t\t// note:\n\t\t// Each time you set the same seed, you get the same sequence\n\t\t// You have to set the seed only once\n\t\t// you simply call Intn to get the next random integer\n\t\trand.Seed(time.Now().UTC().UnixNano())\n\t}", "func Seed(seed int64) {\n\tif seed == 0 {\n\t\trand.Seed(time.Now().UTC().UnixNano())\n\t} else {\n\t\trand.Seed(seed)\n\t}\n}", "func (r *Random) initGenrand(s uint32) {\n\tvar mti uint32\n\tmt := &r.state\n\tmt[0] = s\n\tfor mti = 1; mti < cN; mti++ {\n\t\t/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */\n\t\t/* In the previous versions, MSBs of the seed affect */\n\t\t/* only MSBs of the array mt[]. */\n\t\t/* 2002/01/09 modified by Makoto Matsumoto */\n\t\tmt[mti] = uint32(1812433253)*(mt[mti-1]^(mt[mti-1]>>30)) + mti\n\t}\n\tr.index = mti\n}", "func (p *PCG64) Seed(low, high uint64) {\n\tp.low = low\n\tp.high = high\n}", "func init() {\n\trand.Seed(time.Now().UTC().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UTC().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UTC().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UTC().UnixNano())\n}", "func (p *Pcg128) Seed(stateHigh, stateLow uint64) {\n\tp.lcg_128_seed(stateHigh, stateLow)\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\trand.Seed(time.Now().UnixNano())\n}", "func init() {\n\tvar b [8]byte\n\t_, err := crand.Read(b[:])\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tvar seed = int64(binary.LittleEndian.Uint64(b[:]))\n\trand.Seed(seed)\n}", "func init() {\n\t// As rand.Seed() expect an int64 as input,\n\t// convert the time to unix nano before passing it to the function.\n\trand.Seed(time.Now().UnixNano())\n}", "func (h *Hash) initSeed() {\n\tif h.seed.s == 0 {\n\t\tseed := MakeSeed()\n\t\th.seed = seed\n\t\th.state = seed\n\t}\n}", "func init() {\n\trand.Seed(time.Now().UnixNano()) // initialize rand module\n}", "func init() {\n\t//seed := uint64(0x9E3779B97F4A7C15) // goldenRatio\n\tseed := time.Now().UnixNano()\n\trand.Seed(seed)\n\tfmt.Printf(\"seed: 0x%x\\n\", seed)\n}", "func (genA *GeneticAlgorithm) SetSeed(seed int64) {\n\tgenA.RandomEngine = rand.New(rand.NewSource(seed))\n}", "func (r *ISAAC) Seed(seed int64) {\n\tr.randrsl = padSeed(uint64(seed))\n\tr.randInit()\n}", "func (sp *SuperSpin) Seed(seed int64) {\n\tsp.seed = seed\n}", "func (r *lockedRandSource) Seed(seed int64) {\n\tr.lock.Lock()\n\tr.src.Seed(seed)\n\tr.lock.Unlock()\n}", "func NewGenerator(seed int64) *Generator {\n\tg := &Generator{\n\t\tseed: seed,\n\t\tnoise: opensimplex.New(seed),\n\t}\n\n\treturn g\n}", "func (baseModel *BaseModel) SetSeed(seed int64) {\n baseModel.Rng = rand.New(rand.NewSource(seed)).Float64\n baseModel.RngSet = true\n}", "func (mt *MT19937) seed(val uint32) {\n\tmt.index = n\n\tmt.state[0] = val\n\tfor i := 1; i < (n - 1); i++ {\n\t\tmt.state[i] = f*(mt.state[i-1]^(mt.state[i-1]>>(w-2))) + uint32(i)\n\t}\n}", "func (m *MT) Seed(theseed int64) {\n\t// Lower 32bit\n\tseed := uint32(theseed)\n\tfor m.lp = 0; m.lp < 624; m.lp++ {\n\t\tm.Key[m.lp] = seed\n\t\tseed = (uint32(1812433253)*(seed^(seed>>30)) + m.lp + 1) & 0xffffffff\n\t\t//m.arrayL[m.lp] = 0x6c078965*(m.arrayL[m.lp-1]^(m.arrayL[m.lp-1]>>30)) + m.lp\n\t}\n}", "func New(seed int64) *Faker {\n\t// If passing 0 create crypto safe int64 for initial seed number\n\tif seed == 0 {\n\t\tbinary.Read(crand.Reader, binary.BigEndian, &seed)\n\t}\n\n\treturn &Faker{Rand: rand.New(&lockedSource{src: rand.NewSource(seed).(rand.Source64)})}\n}", "func (u Universe) Seed() {\n\tfor i := 0; i < (width * height / 4); i++ {\n\t\tu.Set(rand.Intn(width), rand.Intn(height), true)\n\t}\n}", "func (m *Model) SetSeed(seed int64) {}", "func seedRandomizer() {\n var b [8]byte\n _, err := crypto_rand.Read(b[:])\n if err != nil {\n panic(\"cannot seed math/rand package with cryptographically secure random number generator\")\n }\n math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))\n}", "func New(seed int64) *rand.Rand {\n\treturn rand.New(NewSource(seed))\n}", "func init() {\n\t// Seed the random number generator.\n\trand.Seed(time.Now().UnixNano())\n}", "func newGenerator(h hash.Hash, seed []byte) generator {\n\tif h == nil {\n\t\th = sha256.New()\n\t}\n\tb := h.Size()\n\tg := generator{\n\t\tkey: make([]byte, b),\n\t\tcounter: make([]byte, 16),\n\t\tmaxBytesPerRequest: (1 << 15) * b,\n\t\ttemp: make([]byte, b),\n\t\th: h,\n\t}\n\tif len(seed) != 0 {\n\t\t_, _ = g.Write(seed)\n\t}\n\treturn g\n}", "func (u Universe) Seed() {\n\t//random numbers - using math/rand lib rand.Intn()\n\t//25% of cells in Universe\n\tpercentageOfCells := int(float64(len(u)*len(u[0])) * 0.25)\n\tfor i := 0; i <= percentageOfCells; i++ {\n\t\tu[rand.Intn(15)][rand.Intn(80)] = true\n\t}\n\t//\n}", "func (x *SplitMix64) Seed(seed int64) {\n\t*x = SplitMix64(seed)\n}", "func (r *lockedSource) Seed(seed int64) {\n\tr.mut.Lock()\n\tr.src.Seed(seed)\n\tr.mut.Unlock()\n}", "func (f *Fortuna) Seed(seed int64) {\n\tif err := f.AddRandomEvent(0, 0, int64ToBytes(seed)); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (w *Wallet) InitSeed(s *aklib.DBConfig, pwd []byte) error {\n\tseed := make([]byte, 32)\n\tif _, err := rand.Read(seed); err != nil {\n\t\tpanic(err)\n\t}\n\tw.EncSeed = address.EncryptSeed(seed, pwd)\n\treturn w.put(s)\n}", "func New(seed int64) Rand {\n\treturn Rand{\n\t\tRand: rand.New(NewLockedSource64(rand.NewSource(seed))),\n\t}\n}", "func (p *prng) init(seed string) {\n\thv := sha512.Sum512([]byte(seed))\n\tcopy(p.buf[:], hv[:])\n\tp.ptr = 0\n}", "func NewGenerator(seed uint64, delay int) Generator {\n\tprng := rand.New(mt19937.New())\n\tprng.Seed(int64(seed))\n\treturn &generator{\n\t\tseed: seed,\n\t\tdelay: delay,\n\t\tprng: prng,\n\t}\n}", "func RandomizerInit() Randomizer {\n\t//initialize our starting seed and our letter dictionary\n\tr := Randomizer{\n\t\ttime.Now().Unix(),\n\t\t[52]string{\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"},\n\t}\n\n\treturn r\n}", "func (rng *Tunafish) Seed() ([]byte, error) {\n\tif !rng.Initialised() {\n\t\treturn nil, ErrNotInitialised\n\t}\n\n\tvar p = make([]byte, SeedFileLength)\n\t_, err := io.ReadFull(rng, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p, nil\n}", "func getSeed() {\n\tpid := os.Getpid()\n\tvar pid64 int64\n\tpid64 = int64(pid)\n\ttimeNow := time.Now().UTC().UnixNano()\n\tseedInt := pid64 + timeNow\n\trand.Seed(seedInt)\n}", "func NewGenerator() Generator {\n\treturn Generator{\n\t\tcurrentState: rand.Intn(30),\n\t}\n}", "func TestSeed(t *testing.T) {\n\tzeroBytes := make([]byte, 32)\n\tsecurityDomain := []byte(\"test\")\n\tr := NewPRNG(securityDomain)\n\tr.Reseed(zeroBytes)\n}", "func Seed(n int) {\n\tdatastore.Seed(n)\n}", "func NewGenerator(h hash.Hash, seed []byte) io.ReadWriter {\n\tg := newGenerator(h, seed)\n\treturn &g\n}", "func NewSeed() Seed {\n\treturn SeedFromEntropy(frand.Entropy128())\n}", "func randWithSeed(max int) (rnd int) {\n\ttime.Sleep(1)\n\trand.Seed(time.Now().UnixNano())\n\trnd = rand.Intn(max)\n\treturn\n}", "func (board *Board) Seed() {\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\ttimes := 0\n\n\tfor times == 0 {\n\t\ttimes = r.Intn(board.Rows * board.Columns)\n\t}\n\n\tfor t := 0; t < times; t++ {\n\t\ti, j := rand.Intn(board.Rows), rand.Intn(board.Columns)\n\n\t\tboard.Cells[i][j].SetAlive(true)\n\t}\n}", "func GenerateSeed(rand io.Reader) (string, error) {\n\tif rand == nil {\n\t\trand = cryptorand.Reader\n\t}\n\tbytes := make([]byte, 32)\n\tif _, err := rand.Read(bytes); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn hex.EncodeToString(bytes), nil\n}", "func (sg *SeedGenerator) Next() (*Seed, error) {\n\tseed := Seed{}\n\t_, err := rand.Read(seed[:])\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"[ SeedGenerator::Next ]\")\n\t}\n\n\treturn &seed, nil\n}", "func randSeed() uint32 {\n\treturn uint32(time.Now().UnixNano() + int64(os.Getpid()))\n}", "func (h *Hash) Seed() Seed {\n\th.initSeed()\n\treturn h.seed\n}", "func NewSeed(seed int64) SkipList {\n\treturn NewSeedEps(seed, eps)\n}", "func (rng *RandomNumberGenerator) SetSeed(seed int64) {\n\trng.seed = seed\n}", "func seedRandom() error {\n\t/* Get an int64 from the CSPRNG */\n\tb := make([]byte, 8)\n\t_, err := crand.Read(b)\n\tif nil != err {\n\t\treturn err\n\t}\n\ti := binary.LittleEndian.Uint64(b)\n\n\t/* Use it to seed the PRNG */\n\tmrand.Seed(int64(i))\n\n\treturn nil\n}", "func (g *Game) SeedRand() {\n\n\t//Find the center (approximate for odd height or width) Cell of the board\n\txMid := g.cols / 2\n\tyMid := g.rows / 2\n\n\t//TEMP placeholder for actual random number generator\n\trand := []int{0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1}\n\n\t//Iterate over a 4x4 square around the center Cell\n\ti := 0\n\tfor y := yMid - 1; y < yMid+3; y++ {\n\t\tfor x := xMid - 1; x < xMid+3; x++ {\n\t\t\tif rand[i] == 1 {\n\t\t\t\tg.state[y][x].Alive = !g.state[y][x].Alive\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n\n\t//Update the copy\n\tfor y := 0; y < int(g.rows); y++ {\n\t\tfor x := 0; x < int(g.cols); x++ {\n\t\t\tg.board[y][x] = g.state[y+1][x+1]\n\t\t}\n\t}\n\n\treturn\n}", "func NewRandFromSeed(seed []byte) *rand.Rand {\n\thash := sha256.Sum256(seed)\n\treturn rand.New(rand.NewSource(int64(binary.BigEndian.Uint64(hash[8:]))))\n}", "func Randomisieren () {\n\trand.Seed(time.Now().UnixNano())\n}", "func seedDice(seed uint64) {\n\trng := pcg.NewPCG64()\n\trng.Seed(rng.Random(), rng.Random(), rng.Random(), rng.Random())\n\trng.Seed(seed, DiceSeq, seed*seed, DiceSeq+1)\n\tdice.SetDefaultRandomness(rng)\n}", "func InitGenRand64(seed uint64) {\n\tC.init_genrand64(C.ulonglong(seed))\n}", "func (b *Handler) Seed() []byte {\n\tb.lock.RLock()\n\tdefer b.lock.RUnlock()\n\n\tcpy := make([]byte, len(b.seed))\n\tcopy(cpy, b.seed)\n\n\treturn cpy\n}", "func New(seed uint64) nhash.Hash64 {\n\ts := n(seed)\n\treturn s\n}", "func (this *XXHash64) SetSeed(seed uint64) {\n\tthis.seed = seed\n}", "func SeedPRNG() {\n\tb := make([]byte, 8)\n\t_, err := crand.Read(b)\n\tif nil != err {\n\t\tpanic(fmt.Sprintf(\"Rand: %v\", err))\n\t}\n\trand.Seed(int64(binary.LittleEndian.Uint64(b)))\n}", "func newDetermRand(seed []byte) io.Reader {\n\treturn &determRand{next: seed}\n}", "func (m *Model) Initialize(seed uint64) {\n\tr := rand.NewLockedRand(seed)\n\teps := m.Config.InitEps / mat.Float(m.Config.DimSeq)\n\tinitializers.Uniform(m.Proj.W.Value(), -eps, eps, r)\n\tinitializers.Constant(m.Proj.B.Value(), 1)\n}", "func Init() {\n\trand.Seed(time.Now().Unix())\n}", "func (kp *FromAddress) Seed() (string, error) {\n\treturn \"\", ErrNoSeed\n}", "func (rng *splitMix64Source) Seed64(seed uint64) {\n\trng.state = seed\n}", "func NewGenerator(opts ...Option) *Generator {\n\tg := &Generator{}\n\n\tfor _, opt := range opts {\n\t\topt.apply(g)\n\t}\n\n\t// Default time source\n\tif g.clock == nil {\n\t\tg.clock = &systemClock{}\n\t}\n\n\t// Default entropy source\n\tif g.entropy == nil {\n\t\tg.entropy = ulid.Monotonic(rand.New(rand.NewSource(g.clock.Now().UnixNano())), 0)\n\t}\n\n\treturn g\n}", "func SetSeed() error {\n\t// 为math\n\tseedByte, err := walletRand.GenerateSeedWithStrengthAndKeyLen(walletRand.KeyStrengthHard, walletRand.KeyLengthInt64)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbytesBuffer := bytes.NewBuffer(seedByte)\n\tvar seed int64\n\tbinary.Read(bytesBuffer, binary.BigEndian, &seed)\n\trand.Seed(seed)\n\n\treturn nil\n}", "func sourceMathRand() {\n\tseed, _ := dice.CryptoInt64()\n\tdice.Source = rand.New(rand.NewSource(seed))\n}", "func New(seed int64) rand.Source64 {\n\tx := new(SplitMix64)\n\tx.Seed(seed)\n\treturn x\n}", "func GenerateNewSeed(Read func(buf []byte) (n int, err error)) ([]byte, error) {\n\tvar seed []byte\n\n\tif Read == nil {\n\t\tRead = rand.Read\n\t}\n\n\tfor {\n\t\t// random seed\n\t\tseed = make([]byte, 64)\n\n\t\t_, err := Read(seed)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Ensure the seed can be used for generating a BLS keypair.\n\t\t// If not, we retry.\n\t\t_, err = generateKeys(seed)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn seed, nil\n}", "func NewEventGenerator(seed int64) *EventGenerator {\n\treturn &EventGenerator{\n\t\tr: rand.New(rand.NewSource(seed)),\n\t\tg: gen.NewGenerator(seed + 1),\n\t}\n}", "func New(seedName string) (seed model.Seed) {\n\tswitch seedName {\n\tcase \"acorn\":\n\t\tseed = Acorn\n\tcase \"blinker\":\n\t\tseed = Blinker\n\tcase \"diehard\":\n\t\tseed = DieHard\n\tcase \"glider\":\n\t\tseed = Glider\n\tcase \"rpentomino\":\n\t\tseed = RPentomino\n\tdefault:\n\t\tpanic(\"unknown seed\")\n\t}\n\treturn\n}", "func GenStrategyRandom(typ Type, seed int) interface{} {\n\treturn newRandomNumber(typ)\n}", "func New() Randomizer {\n\treturn &randomizer{seededRand: mrand.New(mrand.NewSource(time.Now().UTC().UnixNano()))} //nolint:gosec //like it\n}" ]
[ "0.7424726", "0.73450845", "0.70709896", "0.70261484", "0.701139", "0.69750804", "0.69515306", "0.6946966", "0.69348735", "0.6905683", "0.69012666", "0.68930334", "0.6877657", "0.6824542", "0.6807385", "0.68068874", "0.6796626", "0.6760957", "0.67509663", "0.66529834", "0.661328", "0.65454555", "0.65454555", "0.65454555", "0.65454555", "0.64798015", "0.64773643", "0.64773643", "0.64773643", "0.64773643", "0.64773643", "0.64773643", "0.64773643", "0.64729255", "0.64679796", "0.64471334", "0.64404505", "0.63465255", "0.6346505", "0.6342012", "0.6303129", "0.624794", "0.6235616", "0.62301284", "0.6225549", "0.6204893", "0.62013197", "0.61167383", "0.60926884", "0.608983", "0.60786027", "0.6069972", "0.6065348", "0.6047299", "0.60386187", "0.60276747", "0.60225", "0.599943", "0.59551775", "0.59380674", "0.5934623", "0.5925542", "0.5920551", "0.59191424", "0.5877219", "0.5877198", "0.5874037", "0.5869135", "0.5827092", "0.5815588", "0.580495", "0.58008856", "0.5793767", "0.57877845", "0.5786967", "0.578532", "0.5731154", "0.5720892", "0.5716691", "0.5692926", "0.56895137", "0.5686353", "0.56679404", "0.56643987", "0.5656709", "0.56426084", "0.5630735", "0.5603068", "0.5580271", "0.5572534", "0.5566897", "0.55595577", "0.55571496", "0.5546005", "0.5538865", "0.5519288", "0.5515567", "0.5513173", "0.5496691", "0.54862225", "0.5484496" ]
0.0
-1
Extract a tempered value based on MT[index] Generate the next n values from the series x_i
func (mt *MersenneTwister) twist() { for i := 0; i < mt.n; i++ { x := (mt.arr[i] & mt.upperMask) + (mt.arr[(i+1)%mt.n] & mt.lowerMask) xA := x >> 1 if (x % 2) != 0 { // lowest bit of x is 1 xA = xA % mt.a } mt.arr[i] = mt.arr[(int32(i)+mt.m)%int32(mt.n)] ^ xA } mt.index = 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func temp(i int) float64 { return temp0 * math.Exp(-k*float64(i)/n) }", "func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n\treturn func(time float64) float64 {\n\t\treturn ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n\t}\n}", "func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {\n\treturn func(time float64) float64 {\n\t\treturn ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)\n\t}\n}", "func t(i int) float64 {\n\treturn t_0 + *deltaT*float64(i)\n}", "func (d Datapoints) ValueAt(n int) float64 { return d[n].Value }", "func (mt *MersenneTwister) seedMT(seed int32) {\n\tmt.index = mt.n\n\tmt.arr[0] = seed\n\tfor i := 1; i < mt.n; i++ { // loop over each element\n\t\tmt.arr[i] = ((1 << mt.w) - 1) & (mt.f*(mt.arr[i-1]^(mt.arr[i-1]>>(mt.w-2))) + int32(i))\n\t}\n\tmt.seeded = true\n}", "func calculateTempDelta(window *([]*Percept), weight float64, sec, currentIndex int, flag DataQuery, value func(int)(int,int64,error), mean meanCalc) (result DataResponse) {\n\n\tvar lastTemp int // value of last boiler temp\n\tvar lastTimeStamp int64 // value of last timestamp\n\tvar meanValue float64 // mean value from which the result is generated\n\n\t// make sure sec value is in bounds\n\talignBound(window,&sec)\n\n\tcheckAndValidate(&weight)\n\n\tvar firstIndex int\n\tfirstIndex = -1\n\n\tupdate := func (i int)(){\n\t\ttemp,timestamp,err := value(i)\n\t\tif err == nil {\n\t\t\tif firstIndex < 0 {\n\t\t\t\tfirstIndex = i\n\t\t\t}\n\t\t\tmean(\n\t\t\t\ttemp,\n\t\t\t\ttimestamp,\n\t\t\t\t&lastTemp,\n\t\t\t\t&lastTimeStamp,\n\t\t\t\t&meanValue,\n\t\t\t\tweight,\n\t\t\t\tsec,\n\t\t\t)\n\t\t}\n\t}\n\n\tswitch {\n\tcase currentIndex - sec < 0:\n\t\t// array overflow; loop from first position after currentIndex to last slot in slice\n\t\tfor i := cap(*window) - (sec - currentIndex); i < cap(*window); i++ {\n\t\t\tupdate(i)\n\t\t}\n\t\t// add a second loop from fist slot in slice up to currentIndex\n\t\tfor i := 0; i <= currentIndex; i++ {\n\t\t\tupdate(i)\n\t\t}\n\tdefault:\n\t\tfor i := currentIndex - sec; i <= currentIndex; i++ {\n\t\t\tupdate(i)\n\t\t}\n\t}\n\n\tvar intervalLength int\n\t//fmt.Printf(\"%.2f\\tFirst Index: %d; Last Index: %d\\n\",meanValue,firstIndex,currentIndex)\n\tif firstIndex < 0 {\n\t\t// no data items tracked\n\t\tfmt.Println(\"No items found for mean calculation.\")\n\t\tlastTimeStamp = math.MaxInt64\n\t\tintervalLength = 0\n\t} else {\n\t\tif firstIndex <= currentIndex {\n\t\t\tintervalLength = currentIndex - firstIndex + 1\n\t\t} else {\n\t\t\tintervalLength = currentIndex + cap(*window) - firstIndex + 1\n\t\t}\n\t}\n\n\tresult = generateResponse(flag, meanValue, intervalLength, lastTimeStamp)\n\treturn\n}", "func NextN(t time.Time, te TemporalExpression, n int) []time.Time {\n\ttt := make([]time.Time, n)\n\tfor i := 0; i < n; i++ {\n\t\tt = Next(t, te)\n\t\ttt[i] = t\n\t\tt = t.Add(24 * time.Hour)\n\t}\n\treturn tt\n}", "func CgenTemp(n *Node) *Node", "func (g *GeneratorJakes) GenerateN(tstart, tinterval float64, N int) []complex128 {\n\tg.tInterval = tinterval\n\tresult := make([]complex128, N)\n\tt := tstart\n\tfor i, _ := range result {\n\t\tresult[i] = g.generate(t)\n\t\tt += tinterval\n\t}\n\treturn result\n}", "func NewMTFromSlice(initKey []uint32) *MT {\n\tmt := NewMTFromSeed(19650218)\n\ti := uint32(1)\n\tj := uint32(0)\n\tk := uint32(len(initKey))\n\tif n > k {\n\t\tk = n\n\t}\n\tfor ; k != 0; k-- {\n\t\tmt.state[i] = (mt.state[i] ^ ((mt.state[i-1] ^ (mt.state[i-1] >> 30)) * 1664525)) + initKey[j] + j // non linear, apparently\n\t\ti++\n\t\tj++\n\t\tif i >= n {\n\t\t\tmt.state[0] = mt.state[n-1]\n\t\t\ti = 1\n\t\t}\n\t\tif j >= uint32(len(initKey)) {\n\t\t\tj = 0\n\t\t}\n\t}\n\tfor k = n - 1; k != 0; k-- {\n\t\tmt.state[i] = (mt.state[i] ^ ((mt.state[i-1] ^ (mt.state[i-1] >> 30)) * 1566083941)) - i // non linear, again apparently\n\t\ti++\n\t\tif i >= n {\n\t\t\tmt.state[0] = mt.state[n-1]\n\t\t\ti = 1\n\t\t}\n\t}\n\tmt.state[0] = 0x80000000 // MSB is 1 assuring non-zero initial array\n\treturn mt\n}", "func (s *Series) index(t time.Time) int64 {\n\treturn int64(math.Mod(float64(s.floor(t).Unix()), float64(s.Duration.Seconds())))\n}", "func NextXAt(t time.Time, dfmt string, interval int) time.Time {\n\treturn XAt(t, dfmt, absInterval(interval))\n}", "func DuplicateMT(mt *MT) *MT {\n\tnewMT := MT{}\n\tfor i := 0; i < n; i++ {\n\t\tnewMT.state[i] = Untemper(mt.Next())\n\t}\n\treturn &newMT\n}", "func GenPeriodicTemp(d time.Duration, c mqtt.Client) error {\n\n\trand.Seed(time.Now().UTC().UnixNano())\n\tticker := time.NewTicker(d)\n\n\tgo func() {\n\t\tfor x := range ticker.C{\n\n\t\t\treqRandTemp := GetRandomfloat()\n\t\t\trandomInt := GetRandomInt(0, 10)\n\t\t\trandomIntString := fmt.Sprintf(\"%d\", randomInt)\n\t\t\tsensorID := \"sensorID\" + \"-\" + randomIntString\n\n\t\t\ttemp := &models.TempReading{\n\t\t\t\tSensorID: sensorID,\n\t\t\t\tType: \"Temperature\",\n\t\t\t\tValue: reqRandTemp,\n\t\t\t}\n\n\t\t\tout, err := json.Marshal(temp)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tbroker := &models.BrokerPub{\n\t\t\t\tTopic: \"/readings/temperature\",\n\t\t\t\tAction: \"pub\",\n\t\t\t\tPayload: string(out),\n\t\t\t\tNum: 1,\n\t\t\t}\n\n\t\t\terr = Publish(broker, c)\n\t\t\tif err != nil {\n\t\t\t\terr = errors.New(\"Unable to publish reading\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Printf(\"%+v published at %v \\n\", broker, x)\n\n\t\t}\n\n\t}()\n\n\ttime.Sleep(time.Second * 20)\n\tticker.Stop()\n\n\treturn nil\n}", "func GenerateData[N Number](len int, dtype DataType) []Element[N] {\n\tres := make([]Element[N], len)\n\tt := int64(0)\n\tfor i := 0; i < len; i++ {\n\t\tswitch dtype {\n\t\tcase Int32:\n\t\t\tres[i] = Element[N]{\n\t\t\t\tTimestamp: t,\n\t\t\t\tValue: N(int32(i)),\n\t\t\t}\n\t\tcase Float32:\n\t\t\tres[i] = Element[N]{\n\t\t\t\tTimestamp: t,\n\t\t\t\tValue: N(float32(i)),\n\t\t\t}\n\t\tcase Float64:\n\t\t\tres[i] = Element[N]{\n\t\t\t\tTimestamp: t,\n\t\t\t\tValue: N(float64(i)),\n\t\t\t}\n\t\t}\n\t\tt += 3\n\t}\n\treturn res\n}", "func randomTemp() float64 {\n\treturn math.Round(rand.Float64()*300)/10 + 60\n}", "func MOVNTPS(x, m operand.Op) { ctx.MOVNTPS(x, m) }", "func NextSample() []Value {\n\tsmp := make([]Value, masterSpec.Channels)\n\tvar fireSample []Value\n\tfor _, fire := range mixLiveFires {\n\t\tif fireTz := fire.FireAt(nowTz); fireTz > 0 {\n\t\t\tfireSample = mixSourceAt(fire.Source, fire.Volume, fire.Pan, fireTz)\n\t\t\tfor c := 0; c < masterSpec.Channels; c++ {\n\t\t\t\tsmp[c] += fireSample[c]\n\t\t\t}\n\t\t}\n\t}\n\t//\tdebug.Printf(\"*Mixer.nextSample %+v\\n\", sample)\n\tnowTz++\n\tout := make([]Value, masterSpec.Channels)\n\tfor c := 0; c < masterSpec.Channels; c++ {\n\t\tout[c] = mixLogarithmicRangeCompression(smp[c])\n\t}\n\tif nowTz > nextCycleTz {\n\t\tmixCycle()\n\t}\n\treturn out\n}", "func makeCorpus(numSeries, numValuesPerSeries int, fn func(*rand.Rand) interface{}) corpus {\n\trng := rand.New(rand.NewSource(int64(numSeries) * int64(numValuesPerSeries)))\n\tvar unixNano int64\n\tcorpus := make(corpus, numSeries)\n\tfor i := 0; i < numSeries; i++ {\n\t\tvals := make([]tsm1.Value, numValuesPerSeries)\n\t\tfor j := 0; j < numValuesPerSeries; j++ {\n\t\t\tvals[j] = tsm1.NewValue(unixNano, fn(rng))\n\t\t\tunixNano++\n\t\t}\n\n\t\tk := fmt.Sprintf(\"m,t=%d\", i)\n\t\tcorpus[tsm1.SeriesFieldKey(k, \"x\")] = vals\n\t}\n\n\treturn corpus\n}", "func genValue(i int, ev *replication.BinlogEvent) []byte {\n\traw := ev.RawData\n\trowValueIndex := ev.Event.(*replication.RowsEvent).RowValueIndex\n\treturn raw[rowValueIndex[i]:rowValueIndex[i+1]] // 共享内存\n}", "func PopSize(r, x0 float64, max_t int) []float64 {\n var x float64 = x0\n var x_t []float64\n x_t = make([]float64, 0)\n for i := 0; i < max_t; i++ {\n if x < 0 {\n x = 0\n }\n x = r * x * (1 - x)\n // fmt.Println(x)\n x_t = append(x_t, x)\n }\n return x_t\n}", "func (mt *MT19937) Next() int32 {\n\tif mt.index >= n {\n\t\tif mt.index > n {\n\t\t\t// if not already seeded, seed it manually; 5489 appears in reference implementation\n\t\t\t// this implementation should _never_ reach this block\n\t\t\t// this is here just for sake of completeness\n\t\t\tmt.seed(5489)\n\t\t}\n\t\tmt.twist()\n\t}\n\n\tvar y = mt.state[mt.index]\n\tmt.index++\n\treturn int32(mt.temper(y))\n}", "func future_value_formula(pv float64, i float64, n int64) float64 {\n\tif n < 0 {\n\t\t// should throw an error\n\t}\n\n\tvar fv float64 = math.Pow( float64(1) + i, float64(n)) * pv\n\treturn fv\n}", "func (mt *MT19937) temper(y uint32) uint32 {\n\ty = y ^ ((y >> u) & d)\n\ty = y ^ ((y << s) & b)\n\ty = y ^ ((y << t) & c)\n\ty = y ^ (y >> l)\n\treturn y\n}", "func generateTIN(testTIN bool) []int {\n\t// Possible set of digits\n\tpossibleDigits := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n\t// Resultset for the created TIN\n\ttin := make([]int, len(possibleDigits)+1)\n\n\t// Decide wether one digit should exist twice or thrice in the TIN\n\tisTwice := isTwice()\n\t// Get the indices for the lucky digit\n\tluckyIndices := getLuckyIndices(isTwice)\n\tfmt.Println(luckyIndices)\n\t// Determine digit which should exist twice or thrice\n\tluckyDigit := determineLuckyDigit(luckyIndices, testTIN)\n\t// Remove the lucky digit from the set of possible digits (value set to -1)\n\tremoveDigitFromPossibleDigits(luckyDigit, possibleDigits)\n\n\tfor i := 0; i < len(possibleDigits); i++ {\n\t\t// If we hit a lucky index we set the lucky digit\n\t\t// Because #determineLuckyDigit does not allow the value 0 for a non-testing TIN we do not need to check for 0 here\n\t\tif (isTwice && (i == luckyIndices[0] || i == luckyIndices[1])) || (!isTwice && (i == luckyIndices[0] || i == luckyIndices[1] || i == luckyIndices[2])) {\n\t\t\ttin[i] = luckyDigit\n\t\t} else {\n\t\t\t// Else we pseudorandomly take one remaining possible digit and remove it afterwards\n\t\t\t// from the set of possible digits (value set to -1)\n\t\t\tfor {\n\t\t\t\tpossibleDigit, _ := rand.Int(rand.Reader, big.NewInt(int64(len(possibleDigits))))\n\t\t\t\tselectedDigit := possibleDigits[int(possibleDigit.Uint64())]\n\t\t\t\tif selectedDigit != -1 {\n\t\t\t\t\tisDigitSave := false\n\t\t\t\t\t// If we do not have a TIN for testing purposes we need to assure that the first index does not get the value 0.\n\t\t\t\t\tif !testTIN {\n\t\t\t\t\t\tif selectedDigit == 0 && i != 0 || selectedDigit != 0 && i == 0 || selectedDigit != 0 && i != 0 {\n\t\t\t\t\t\t\tisDigitSave = true\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tisDigitSave = true\n\t\t\t\t\t}\n\t\t\t\t\tif isDigitSave {\n\t\t\t\t\t\ttin[i] = selectedDigit\n\t\t\t\t\t\tremoveDigitFromPossibleDigits(selectedDigit, possibleDigits)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//if selectedDigit != -1 /*&& (!testTIN && selectedDigit != 0 && i != 0)*/ {\n\t\t\t\t//\tif (!testTIN && selectedDigit != 0 && i == 0) || (!testTIN && selectedDigit == 0 && i != 0) {\n\n\t\t\t\t//\t}\n\t\t\t\t//\ttin[i] = selectedDigit\n\t\t\t\t//\tremoveDigitFromPossibleDigits(selectedDigit, possibleDigits)\n\t\t\t\t//\tbreak\n\t\t\t\t//}\n\t\t\t}\n\t\t}\n\t}\n\ttin[len(tin)-1] = calcCheckDigitTIN(tin)\n\treturn tin\n}", "func RegulateTemp (value float64) float64{\n\n\tif value> 22 {\n\t\treturn (22 * 100)/ value\n\t}else if value < 22{\n return 100.0\n\t}\n\n\treturn 0.0\n}", "func (n *TemperatureSensorNtcConf) getTemp(rntc float64) float64 {\n\t// 1/T = 1/T0 + 1/B * ln(R/R0)\n\t//\n\t// B/T = B/T0 + ln(R/R0) = k, B/T0 = r\n\t// T = B/k, Tc = T - 273\n\n\tk := n.r + math.Log(rntc/n.R0)\n\treturn n.B/k - kelvinOffset\n}", "func (p Polynom) ValueAt(x0 *big.Int) *big.Int {\n\tval := big.NewInt(0)\n\tfor i := len(p.coeff) - 1; i >= 0; i-- {\n\t\tval.Mul(val, x0)\n\t\tval.Add(val, p.coeff[i])\n\t\tval.Mod(val, p.mod)\n\t}\n\treturn val\n}", "func generateInput(n int) []time.Duration {\n\tar := []time.Duration{}\n\tfor i := 0; i < n; i++ {\n\t\td := time.Duration(rand.Int63n(6000))\n\t\tar = append(ar, d)\n\t}\n\treturn ar\n}", "func RandomFlt(ln int) []float64 {\n\tvar numbers []float64\n\t//var array [40]float64\n\trand.Seed(time.Now().UTC().UnixNano())\n\tfor i := ln - 1; i > 0; i-- {\n\t\t//j := rand.Intn(i + 1)\n\t\tn := rand.Float64() * 90 // simulate number close to 90\n\t\t//array[i], array[j] = array[j], array[i]\n\t\tnumbers = append(numbers, n)\n\t}\n\treturn numbers\n}", "func randset(arr []T, n int) {\n\n}", "func (ft *Time) Next() {\n\ta := rand.Float64()\n\n\t// Ensure first time doesn't have any variance to respect the start time parameter\n\tif ft.firstVal {\n\t\tft.firstVal = false\n\t\tft.v = ft.ts\n\n\t\tif ft.keepStats {\n\t\t\tft.Stats.Add(ft.v)\n\t\t}\n\n\t\treturn\n\t}\n\n\tft.ts = ft.ts.Add(time.Duration(ft.increment) * time.Millisecond)\n\ttmp := (float64(ft.variance) * a) - float64(int64(float64(ft.variance)*a))\n\ttmp2 := float64(-1)\n\n\tif ft.direction < 0 {\n\t\ttmp2 = float64(-1)\n\t} else if ft.direction > 0 {\n\t\ttmp2 = float64(1)\n\t} else if tmp > 0.5 {\n\t\ttmp2 = float64(1)\n\t}\n\n\tc := int64(round(float64(ft.variance)*a, 0.0000000005) * tmp2)\n\tft.v = ft.ts.Add(time.Duration(c) * time.Millisecond)\n\n\tif ft.keepStats {\n\t\tft.Stats.Add(ft.v)\n\t}\n}", "func (m *Model) EvaluateAt(seq Sequence, start int) {\n\tfor _, t := range m.Trees {\n\t\tfor i, ts := range seq[start:] {\n\t\t\tleaf := t.Evaluate(&TimestepSample{Sequence: seq, Index: i + start})\n\t\t\tv1 := blas32.Vector{Inc: 1, Data: leaf.OutputDelta}\n\t\t\tv2 := blas32.Vector{Inc: 1, Data: ts.Output}\n\t\t\tblas32.Axpy(len(ts.Output), 1.0, v1, v2)\n\t\t\tif leaf.Feature != 0 {\n\t\t\t\tts.Features.Set(leaf.Feature, true)\n\t\t\t}\n\t\t}\n\t}\n}", "func (l *LookupOscillator) BatchInterpolateTick(freq float64, nframes int) []float64 {\n\tout := make([]float64, nframes)\n\tfor i := 0; i < nframes; i++ {\n\t\tbaseIndex := int(l.curphase)\n\t\tnextIndex := baseIndex + 1\n\t\tif l.curfreq != freq {\n\t\t\tl.curfreq = freq\n\t\t\tl.incr = l.SizeOverSr * l.curfreq\n\t\t}\n\t\tcurphase := l.curphase\n\t\tfrac := curphase - float64(baseIndex)\n\t\tval := l.Table.data[baseIndex]\n\t\tslope := l.Table.data[nextIndex] - val\n\t\tval += frac * slope\n\t\tcurphase += l.incr\n\n\t\tfor curphase > float64(Len(l.Table)) {\n\t\t\tcurphase -= float64(Len(l.Table))\n\t\t}\n\t\tfor curphase < 0.0 {\n\t\t\tcurphase += float64(Len(l.Table))\n\t\t}\n\n\t\tl.curphase = curphase\n\t\tout[i] = val\n\t}\n\treturn out\n}", "func tonesFrom(data [][4]float32, dur, fund sc.Input) []sc.Input {\n\ttones := make([]sc.Input, len(data))\n\n\tfor i, row := range data {\n\t\tvar (\n\t\t\tfreq = sc.C(row[0])\n\t\t\toffset = sc.C(row[1])\n\t\t\tamp = sc.C(row[2])\n\t\t\tdurr = sc.C(row[3])\n\n\t\t\tampenv = sc.EnvGen{\n\t\t\t\tEnv: sc.EnvPerc{\n\t\t\t\t\tRelease: dur.Mul(durr).Add(sc.C(-0.01)),\n\t\t\t\t},\n\t\t\t}.Rate(sc.KR)\n\t\t)\n\t\ttones[i] = sc.SinOsc{\n\t\t\tFreq: fund.Mul(freq).Add(offset),\n\t\t}.Rate(sc.AR).Mul(amp.Mul(ampenv))\n\t}\n\treturn tones\n}", "func efficientWayOfGeneratingAmount(){\n\tdone := make(chan interface{})\n\tdefer close(done)\n\tfor num := range take(done, repeat(done, 1), 10) {\n \tfmt.Printf(\"%v\", num)\n\t}\n\tfmt.Println()\n}", "func tripleGenerator(k int, x uint16) (int, uint32, uint32) {\n\tl, _, _ := intermediateSymbols(k)\n\tlprime := smallestPrimeGreaterOrEqual(l)\n\tq := uint32(65521) // largest prime < 2^16\n\tjk := uint32(systematicIndextable[k])\n\n\ta := uint32((53591 + (uint64(jk) * 997)) % uint64(q))\n\tb := (10267 * (jk + 1)) % q\n\ty := uint32((uint64(b) + (uint64(x) * uint64(a))) % uint64(q))\n\tv := raptorRand(y, 0, 1048576) // 1048576 == 2^20\n\td := deg(v)\n\ta = 1 + raptorRand(y, 1, uint32(lprime-1))\n\tb = raptorRand(y, 2, uint32(lprime))\n\n\treturn d, a, b\n}", "func (mt *MT) twist() {\n\tfor i := 0; i < n; i++ {\n\t\tx := (mt.state[i] & upper_mask) + (mt.state[(i+1)%n] & lower_mask)\n\t\txA := x >> 1\n\t\tif x%2 == 1 {\n\t\t\txA = xA ^ a\n\t\t}\n\t\tmt.state[i] = mt.state[(i+m)%n] ^ xA\n\t}\n\tmt.index = 0\n}", "func MOVNTPD(x, m operand.Op) { ctx.MOVNTPD(x, m) }", "func OpTempYieldVar(o *base.Op, lzVars *base.Vars, lzYieldVals base.YieldVals,\n\tlzYieldErr base.YieldErr, path, pathNext string) {\n\ttempIdx := o.Params[0].(int)\n\n\tlzVal := lzVars.Temps[tempIdx].(base.Val)\n\n\t_, lzOk := base.ArrayYield(lzVal, lzYieldVals, nil)\n\tif !lzOk {\n\t\tlzVals := base.Vals{lzVal}\n\n\t\tlzYieldVals(lzVals)\n\t}\n\n\tlzYieldErr(nil)\n}", "func xirrPart1(values, dates []float64, rate float64) float64 {\n\tr := rate + 1\n\tresult := values[0]\n\tvlen := len(values)\n\tfirstDate := dates[0]\n\tfor i := 1; i < vlen; i++ {\n\t\tresult += values[i] / math.Pow(r, (dates[i]-firstDate)/365)\n\t}\n\treturn result\n}", "func prepareTrendGrowthMtxX(mtxX [][]float64) [][]float64 {\n\tvar mtx [][]float64\n\tfor i := 0; i < len(mtxX); i++ {\n\t\tfor j := 0; j < len(mtxX[i]); j++ {\n\t\t\tif mtxX[i][j] == 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfor x := len(mtx); x <= j; x++ {\n\t\t\t\tmtx = append(mtx, []float64{})\n\t\t\t}\n\t\t\tfor y := len(mtx[j]); y <= i; y++ {\n\t\t\t\tmtx[j] = append(mtx[j], 0)\n\t\t\t}\n\t\t\tmtx[j][i] = mtxX[i][j]\n\t\t}\n\t}\n\treturn mtx\n}", "func Repeat[T any](t T, n int) (tt []T) {\n\tfor i := 0; i < n; i++ {\n\t\ttt = append(tt, t)\n\t}\n\treturn tt\n}", "func TestTemp5(t *testing.T) {\n\tedge := []*train{\n\t\tnew(train).init(1, 3, 800, fmtTime(\"18:00\"), fmtTime(\"21:00\")),\n\t\tnew(train).init(1, 2, 650, fmtTime(\"13:30\"), fmtTime(\"14:00\")),\n\t\tnew(train).init(1, 2, 350, fmtTime(\"13:30\"), fmtTime(\"14:00\")),\n\t\tnew(train).init(1, 2, 150, fmtTime(\"13:30\"), fmtTime(\"14:00\")),\n\t\tnew(train).init(2, 3, 100, fmtTime(\"14:00\"), fmtTime(\"18:00\")),\n\t\tnew(train).init(2, 3, 300, fmtTime(\"14:30\"), fmtTime(\"19:00\")),\n\t\tnew(train).init(2, 3, 200, fmtTime(\"15:00\"), fmtTime(\"19:30\")),\n\t}\n\ttemp(3, edge)\n}", "func TemperatureSensorNtcScaler(vRef uint, rOhm uint, reverse bool, ntc TemperatureSensorNtcConf) func(input int) (value float64) {\n\tntc.initialize()\n\treturn (func(input int) (value float64) {\n\t\tif input < 0 {\n\t\t\tinput = 0\n\t\t}\n\t\trTherm := temperaturSensorGetResistance(uint(input), vRef, rOhm, reverse)\n\t\ttemp := ntc.getTemp(rTherm)\n\t\treturn temp\n\t})\n}", "func Mltp(r [3]float64, c float64) (result [3]float64) {\n result[0] = r[0] * c\n result[1] = r[1] * c\n result[2] = r[2] * c\n\n return result\n}", "func stepValue(i, n uint, min, max float64) float64 {\n\tif n == 0 || i == n || min > max {\n\t\tpanic(\"domain requirements are violated\")\n\t}\n\tstep := ((max - min) / float64(n-1))\n\treturn float64(i)*step + min\n}", "func (items Float64Slice) Value(index int) interface{} { return items[index] }", "func (s *f64) Sample(i int) float64 {\n\treturn float64(s.buffer[i])\n}", "func IndexToAssignment(factorvalues []int, factornval []int) *mu.Matrix {\n\tvaluevector := mu.NewVector(factorvalues)\n\tnvalvector := mu.NewVector(factornval)\n\trepeatI := mu.Repmat(valuevector.T(), 1, len(factornval))\n\tfmt.Println(\"repeat_I\", repeatI)\n\tcprod := mu.Cumprod(mu.CreateNewSlice([]int{1}, nvalvector.Data[:len(nvalvector.Data)-1]))\n\tcprodvector := mu.NewVector(cprod)\n\trepeatD := mu.Repmat(cprodvector, len(factorvalues), 1)\n\tfmt.Println(\"repeat_D\", repeatD)\n\tnumerator, err := mu.MatrixDivision(repeatI, repeatD)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(\"numerator\", numerator)\n\tdenominator := mu.Repmat(nvalvector, len(factorvalues), 1)\n\tfmt.Println(\"den\", denominator)\n\tindexes, err := mu.MatrixMod(numerator, denominator)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(\"indexes\", indexes)\n\treturn indexes\n}", "func naiveDFT(x []complex128) (y []complex128) {\n\ty = make([]complex128, len(x))\n\tdt := -2 * math.Pi / float64(len(x))\n\tfor i := range x {\n\t\targ1 := float64(i) * dt\n\t\tfor k, xv := range x {\n\t\t\targ2 := float64(k) * arg1\n\t\t\ty[i] += complex(math.Cos(arg2), math.Sin(arg2)) * xv\n\t\t}\n\t}\n\treturn y\n}", "func (_CraftingI *CraftingICaller) TokenByIndex(opts *bind.CallOpts, index *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CraftingI.contract.Call(opts, &out, \"tokenByIndex\", index)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func FillMean(ts TimeSeries) (TimeSeries, error) {\n\tif len(ts) < 3 {\n\t\tlog.Printf(\"not enough data to impute\")\n\t\treturn ts, nil\n\t}\n\tkeys := make([]string, 0)\n\tvar mean float64 = 0\n\tfor k, v := range ts {\n\t\tkeys = append(keys, k)\n\t\tmean += v\n\t}\n\tmean = mean / float64(len(keys))\n\n\tvar parseFormat string\n\tswitch len(keys[0]) {\n\tcase 4:\n\t\tparseFormat = yearfmt\n\tcase 7:\n\t\tparseFormat = monthfmt\n\tcase 10:\n\t\tparseFormat = dayfmt\n\t}\n\n\tif parseFormat == \"\" {\n\t\treturn ts, errors.New(\"date format is not ISO 8601\")\n\t}\n\n\tyStep, mStep, dStep := diff(keys, parseFormat)\n\n\tlog.Printf(\"Step is equal to : %v years, %v months, %v days \\n\", yStep, mStep, dStep)\n\n\tsort.Strings(keys)\n\n\t//TODO(eftekhari-mhs): Handle errors.\n\tstartDate, _ := time.Parse(parseFormat, keys[0])\n\tendDate, _ := time.Parse(parseFormat, keys[len(keys)-1])\n\n\tfor d := startDate; d.After(endDate) == false; d = d.AddDate(yStep, mStep, dStep) {\n\t\tif _, ok := ts[fmt.Sprint(d.Format(parseFormat))]; !ok {\n\t\t\tts[fmt.Sprint(d.Format(parseFormat))] = mean\n\t\t}\n\t}\n\treturn ts, nil\n}", "func (ant *Ant) NextN(steps int) (cell *Cell, err error) {\n\tif steps < 0 {\n\t\tpanic(\"steps must be >= 0\")\n\t}\n\tif steps == 0 {\n\t\treturn ant.Position, nil\n\t}\n\tfor i := 0; i < steps; i++ {\n\t\tcell, err = ant.Next()\n\t\tif err != nil {\n\t\t\treturn cell, err\n\t\t}\n\t}\n\treturn cell, err\n}", "func getValues() [samp_len]int {\r\n\r\n var tmp [samp_len] int\r\n rand.Seed(time.Now().UnixNano()) //Using current time in nanosenconds as a seed so it changes everytime\r\n for i := 0; i< len(tmp); i++ {\r\n tmp[i] = rand.Int() //Generating random value\r\n //check(tmp[i])\r\n }\r\n return tmp\r\n}", "func (_ElvTradable *ElvTradableCaller) TokenByIndex(opts *bind.CallOpts, index *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ElvTradable.contract.Call(opts, &out, \"tokenByIndex\", index)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func TestTemp(t *testing.T) {\n\tedge := []*train{\n\t\tnew(train).init(1, 3, 800, fmtTime(\"18:00\"), fmtTime(\"21:00\")),\n\t\tnew(train).init(1, 2, 650, fmtTime(\"13:30\"), fmtTime(\"14:00\")),\n\t\tnew(train).init(2, 3, 100, fmtTime(\"14:00\"), fmtTime(\"18:00\")),\n\t\tnew(train).init(2, 3, 300, fmtTime(\"14:30\"), fmtTime(\"19:00\")),\n\t\tnew(train).init(2, 3, 200, fmtTime(\"15:00\"), fmtTime(\"19:30\")),\n\t}\n\ttemp(3, edge)\n}", "func TestSeriesSMAIteration3(t *testing.T) {\n\n\tstart := time.Now()\n\tdata := OHLCVTestData(start, 4, 5*60*1000)\n\tdata[0].C = 13\n\tdata[1].C = 15\n\tdata[2].C = 17\n\tdata[3].C = 18\n\n\tlog.Printf(\"Data[0].S, %+v, 3s: %+v\", data[0].S, data[3].S)\n\n\tseries, err := NewOHLCVSeries(data)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tseries.Next()\n\tseries.Next()\n\tseries.Next()\n\n\ttestTable := []struct {\n\t\tlookback int\n\t\texp float64\n\t\tisNil bool\n\t}{\n\t\t{\n\t\t\tlookback: 1,\n\t\t\texp: 17,\n\t\t},\n\t\t{\n\t\t\tlookback: 2,\n\t\t\texp: 16,\n\t\t},\n\t\t{\n\t\t\tlookback: 3,\n\t\t\texp: 15,\n\t\t},\n\t\t{\n\t\t\tlookback: 4,\n\t\t\texp: 0,\n\t\t\tisNil: true,\n\t\t},\n\t}\n\n\tfor i, v := range testTable {\n\t\tprop := OHLCVAttr(series, OHLCPropClose)\n\n\t\tsma := SMA(prop, int64(v.lookback))\n\n\t\tif sma == nil {\n\t\t\tt.Errorf(\"Expected to be non nil but got nil at idx: %d\", i)\n\t\t}\n\t\tif v.isNil && sma.Val() != nil {\n\t\t\tt.Error(\"expected to be nil but got non nil\")\n\t\t}\n\t\tif !v.isNil && *sma.Val() != v.exp {\n\t\t\tt.Errorf(\"Expected to get %+v but got %+v for lookback %+v\", v.exp, *sma.Val(), v.lookback)\n\t\t}\n\t}\n}", "func (g *GeneratorJakes) NextSample() (float64, complex128) {\n\t// fmt.Printf(\"My SEED %v | \", g.seed())\n\tg.lastSampletime += g.tInterval\n\treturn g.lastSampletime, g.generate(g.lastSampletime)\n}", "func Txa(c *CPU) {\n\tc.ApplyNZ(c.X)\n\tc.A = c.X\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 (ps *PrimeStore) GetByIndex(nth uint64) (n uint64) {\n\tdefer Tracer(NewTrace(\"GetByIndex\"))\n\n\tn = 0\n\tif nth < ps.base || nth >= (ps.base+ps.count) {\n\t\tlog.Print(\"out of range.\", nth, \" \", ps)\n\t\treturn\n\t}\n\n\tn = ps.index[nth-ps.base]\n\treturn\n}", "func (_ERC721Enumerable *ERC721EnumerableCaller) TokenByIndex(opts *bind.CallOpts, index *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ERC721Enumerable.contract.Call(opts, &out, \"tokenByIndex\", index)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func TestSeriesSMAIteration4(t *testing.T) {\n\n\tstart := time.Now()\n\tdata := OHLCVTestData(start, 4, 5*60*1000)\n\tdata[0].C = 15\n\tdata[1].C = 16\n\tdata[2].C = 17\n\tdata[3].C = 18\n\n\tlog.Printf(\"Data[0].S, %+v, 3s: %+v\", data[0].S, data[3].S)\n\n\tseries, err := NewOHLCVSeries(data)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tseries.Next()\n\tseries.Next()\n\tseries.Next()\n\tseries.Next()\n\n\ttestTable := []struct {\n\t\tlookback int\n\t\texp float64\n\t}{\n\t\t{\n\t\t\tlookback: 1,\n\t\t\texp: 18,\n\t\t},\n\t\t{\n\t\t\tlookback: 2,\n\t\t\texp: 17.5,\n\t\t},\n\t\t{\n\t\t\tlookback: 3,\n\t\t\texp: 17,\n\t\t},\n\t\t{\n\t\t\tlookback: 4,\n\t\t\texp: 16.5,\n\t\t},\n\t}\n\n\tfor i, v := range testTable {\n\t\tprop := OHLCVAttr(series, OHLCPropClose)\n\n\t\tsma := SMA(prop, int64(v.lookback))\n\t\tif sma == nil {\n\t\t\tt.Errorf(\"Expected to be non nil but got nil at idx: %d\", i)\n\t\t}\n\t\tif *sma.Val() != v.exp {\n\t\t\tt.Errorf(\"Expected to get %+v but got %+v for lookback %+v\", v.exp, sma, v.lookback)\n\t\t}\n\t}\n}", "func Momentum(n int) func(s []float64) []float64 {\n\treturn func(s []float64) (res []float64) {\n\t\tf := Skip(n)(s)\n\t\tres = make([]float64, len(f))\n\t\tfor i := range res {\n\t\t\tres[i] = f[i]/s[i] - 1\n\t\t}\n\n\t\treturn\n\t}\n}", "func (v valuer) Value(i int) float64 {\n\treturn v.data[i]\n}", "func genN(value byte, n int) []byte {\n\tvalues := make([]byte, n, n)\n\n\tfor i := 0; i < n; i++ {\n\t\tvalues = append(values, value)\n\t}\n\n\treturn values\n}", "func funcTimestamp(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tvec := vals[0].(Vector)\n\tfor _, el := range vec {\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(el.Metric),\n\t\t\tF: float64(el.T) / 1000,\n\t\t})\n\t}\n\treturn enh.Out\n}", "func (r MockRateRepository) TrendDataByCurrency(base, counter string) ([]models.ExchangeData, error) {\n\tif base == \"USD\" && counter == \"IDR\" {\n\t\treturn []models.ExchangeData{}, errors.New(\"mock some err \")\n\t}\n\treturn []models.ExchangeData{}, nil\n}", "func transactionGetter(s bool, t []*Transaction) func() *Transaction {\n\tc := len(t)\n\n\tif s {\n\t\ti := 0\n\t\treturn func() *Transaction {\n\t\t\tif i == c {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tr := t[i]\n\t\t\ti++\n\t\t\treturn r\n\t\t}\n\t}\n\trand.Seed(time.Now().Unix())\n\treturn func() *Transaction {\n\t\tr := rand.Intn(c)\n\t\treturn t[r]\n\t}\n}", "func TestTemp1(t *testing.T) {\n\tedge := []*train{\n\t\tnew(train).init(1, 2, 1000, fmtTime(\"0:00\"), fmtTime(\"12:00\")),\n\t\tnew(train).init(1, 2, 100, fmtTime(\"0:30\"), fmtTime(\"14:00\")),\n\t\tnew(train).init(1, 2, 100, fmtTime(\"0:30\"), fmtTime(\"15:00\")),\n\t\tnew(train).init(2, 3, 300, fmtTime(\"16:00\"), fmtTime(\"24:00\")),\n\t\tnew(train).init(2, 3, 200, fmtTime(\"16:30\"), fmtTime(\"24:00\")),\n\t}\n\ttemp(3, edge)\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 (self *ResTransaction)GetOutputAt(i int)*TrOutput{\n return &self.Output\n}", "func (t *MCTS) sampleChild() int {\n\tvar accum, denominator float32\n\tvar accumVector []float32\n\tchildren := t.Children(t.root)\n\tfor _, kid := range children {\n\t\tchild := t.nodeFromNaughty(kid)\n\t\tif child.IsValid() {\n\t\t\tvisits := child.Visits()\n\t\t\tdenominator += math32.Pow(float32(visits), 1/t.Config.RandomTemperature)\n\t\t}\n\t}\n\n\tfor _, kid := range children {\n\t\tchild := t.nodeFromNaughty(kid)\n\t\tnumerator := math32.Pow(float32(child.Visits()), 1/t.Config.RandomTemperature)\n\t\taccum += numerator / denominator\n\t\taccumVector = append(accumVector, accum)\n\t}\n\n\trnd := t.rand.Float32()\n\tvar index int\n\tfor i, a := range accumVector {\n\t\tif rnd < a {\n\t\t\tindex = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn index\n}", "func Kst(values []float64, rocPeriods []int, avgPeriods []int, signalPeriod int) ([]float64,[]float64) {\n var ksts []float64\n for i := 0; i < len(values); i++ {\n rocma1 := Sma(Roc(values[:i+1], rocPeriods[0]), avgPeriods[0])\n rocma2 := Sma(Roc(values[:i+1], rocPeriods[1]), avgPeriods[1])\n rocma3 := Sma(Roc(values[:i+1], rocPeriods[2]), avgPeriods[2])\n rocma4 := Sma(Roc(values[:i+1], rocPeriods[3]), avgPeriods[3])\n if !(len(rocma1)>0 && len(rocma2)>0 && len(rocma3)>0 && len(rocma4)>0) {\n continue\n }\n kst := rocma1[len(rocma1)-1] + (rocma2[len(rocma2)-1]*2) + (rocma3[len(rocma3)-1]*3) + (rocma4[len(rocma4)-1]*4)\n ksts = append(ksts, kst)\n }\n kstSignals := Sma(ksts, signalPeriod)\n return ksts, kstSignals\n}", "func MogTar() int {\r\n\treturn rand.Intn(3) + 1\r\n}", "func at[T interface{ ~[]E }, E any](x T, i int) E {\n\treturn x[i]\n}", "func (it *Mcmc3intmcMetricsIterator) Next() *Mcmc3intmcMetrics {\n\tmtr := it.iter.Next()\n\tif mtr == nil {\n\t\treturn nil\n\t}\n\n\ttmtr := &Mcmc3intmcMetrics{metrics: mtr}\n\ttmtr.Unmarshal()\n\treturn tmtr\n}", "func moment(data []float64, c float64, p float64, N int) float64 {\n\n\tsum := 0.0\n\tfor i := 0; i < N; i++ {\n\t\tsum += math.Pow(data[i]-c, p)\n\t}\n\n\treturn sum / float64(N)\n}", "func generator(startingValue int64, factor int64) (Result []int64) {\n\n\tdefer measureTime(time.Now(), \"generator\"+strconv.FormatInt(startingValue, 10))\n\tpreviousValue := startingValue //\tint64(startingValue)\n\n\tfor ig := 1; ig <= numberofPairs; ig++ {\n\n\t\tproductValue := previousValue * factor //\tMultiplication is resulting in more than uint32\t=>\tuint64\n\t\tnextValue := productValue % int64(divisor) //\tRemainder of x / y\t=> Guaranteed to be 32 bits\n\n\t\tResult = append(Result, nextValue) //\tPopulating slice of resulting values\n\t\tpreviousValue = nextValue //\tPreparing for the next run of the loop\n\n\t}\n\treturn Result\n}", "func Intn(n int) int { return globalRand.Intn(n) }", "func Intn(n int) int { return globalRand.Intn(n) }", "func Intn(n int) int { return globalRand.Intn(n) }", "func TestTemp3(t *testing.T) {\n\tedge := []*train{\n\t\tnew(train).init(1, 2, 100, fmtTime(\"0:30\"), fmtTime(\"14:00\")),\n\t\tnew(train).init(1, 2, 200, fmtTime(\"1:00\"), fmtTime(\"16:00\")),\n\t\tnew(train).init(2, 3, 300, fmtTime(\"16:00\"), fmtTime(\"24:00\")),\n\t\tnew(train).init(2, 3, 200, fmtTime(\"16:30\"), fmtTime(\"24:00\")),\n\t}\n\ttemp(3, edge)\n}", "func (m NumSeriesDistribution) Get(index int) *NumSeries {\n\tif index > -1 {\n\t\tif s, ok := m[index]; ok {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn nil\n}", "func (r *Result) GetxN(index int) Nullable {\n\tif index < 0 || index >= len(r.val.columns) {\n\t\tpanic(ErrorColumnNotFound{At: \"GetxN\", Index: index})\n\t}\n\treturn r.val.buffer[index]\n}", "func (t Tuple) At(idx int) float64 {\n\treturn t[idx]\n}", "func (pool *TxPool) GetRandomTips(n int) (v []types.Txi) {\n\tpool.mu.RLock()\n\tdefer pool.mu.RUnlock()\n\n\t// select n random hashes\n\tvalues := pool.tips.GetAllValues()\n\tindices := generateRandomIndices(n, len(values))\n\n\tfor _, i := range indices {\n\t\tv = append(v, values[i])\n\t}\n\treturn v\n}", "func GenerateBeaverTriplet(N *big.Int) [3]*big.Int {\n\tvar triplet [3]*big.Int\n\n\tx, y := getRandom(N), getRandom(N)\n\n\tif mr.Intn(2) > 0 {\n\t\t// u = x, v = y, w = xy mod N\n\t\tw := new(big.Int).Mul(x, y)\n\t\ttriplet[0] = w.Mod(w, N)\n\t\ttriplet[1] = x\n\t\ttriplet[2] = y\n\t} else {\n\t\t// v = x, w = y, u = (xy^-1)^-1 mod N\n\t\tu := new(big.Int).Mul(x, new(big.Int).ModInverse(y, N))\n\t\ttriplet[0] = y\n\t\ttriplet[1] = x\n\t\ttriplet[2] = u.ModInverse(u, N)\n\t}\n\n\treturn triplet\n}", "func (c *Context) MOVNTPS(x, m operand.Op) {\n\tc.addinstruction(x86.MOVNTPS(x, m))\n}", "func (s *Simulator) SeriesN() int {\n\treturn s.TagsN() * s.Measurements\n}", "func (x *Lazy) Take(n int, ar AnyValue) {\n\toar := reflect.ValueOf(ar)\n\tfor i := 0; i < n; i++ {\n\t\tif v, ok := x.omap[i]; ok {\n\t\t\toar.Index(i).Set(v)\n\t\t\tcontinue\n\t\t}\n\t\tvar v = []reflect.Value{x.iar.Index(i)}\n\t\tfor j := 0; j < len(x.fns); j++ {\n\t\t\tv = x.fns[j].Call(v)\n\t\t}\n\t\toar.Index(i).Set(v[0])\n\t\tx.omap[i] = oar.Index(i)\n\t}\n}", "func getNext(server *sheets.Service) string{\n tab := \"Transactions!\"\n firstColumn := \"B\"\n firstLine := \"5\"\n lastColumn := \"E\"\n\n expensesRange := tab + firstColumn + firstLine + \":\" + lastColumn\n expensesValueRange := getValues(expensesRange, server).Values\n totalRegisters := len(expensesValueRange)\n intFirstLine, _ := strconv.Atoi(firstLine)\n\n nextLine := totalRegisters + intFirstLine\n\n return tab + firstColumn + strconv.Itoa(nextLine)\n}", "func (_ElvTradableLocal *ElvTradableLocalCaller) TokenByIndex(opts *bind.CallOpts, index *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ElvTradableLocal.contract.Call(opts, &out, \"tokenByIndex\", index)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func TestTemp4(t *testing.T) {\n\tedge := []*train{\n\t\tnew(train).init(1, 2, 100, fmtTime(\"0:30\"), fmtTime(\"14:00\")),\n\t\tnew(train).init(1, 2, 200, fmtTime(\"1:00\"), fmtTime(\"16:30\")),\n\t\tnew(train).init(2, 3, 300, fmtTime(\"16:00\"), fmtTime(\"24:00\")),\n\t\tnew(train).init(2, 3, 200, fmtTime(\"16:30\"), fmtTime(\"24:00\")),\n\t}\n\ttemp(3, edge)\n}", "func Memoization(index uint) uint {\n\tif _, ok := numbers[index]; ok {\n\t\treturn numbers[index]\n\t}\n\n\tif index <= 2 {\n\t\tnumbers[index] = 1\n\t} else {\n\t\tnumbers[index] = Memoization(index-1) + Memoization(index-2)\n\t}\n\n\treturn numbers[index]\n}", "func calcTrendValue(i int, sf, tf, s0, s1, b float64) float64 {\n\tif i == 0 {\n\t\treturn b\n\t}\n\n\tx := tf * (s1 - s0)\n\ty := (1 - tf) * b\n\n\treturn x + y\n}", "func (ns *EsIndexer) IndexTxs(block *types.Block, txs []*types.Tx, channel chan EsType, nameChannel chan EsType) {\n\t// This simply pushes all Txs to the channel to be consumed elsewhere\n\tblockTs := time.Unix(0, block.Header.Timestamp)\n\tfor _, tx := range txs {\n\t\td := ConvTx(tx)\n\t\td.Timestamp = blockTs\n\t\td.BlockNo = block.Header.BlockNo\n\t\tchannel <- d\n\n\t\tif tx.GetBody().GetType() == types.TxType_GOVERNANCE && string(tx.GetBody().GetRecipient()) == \"aergo.name\" {\n\t\t\tnameDoc := ConvNameTx(tx)\n\t\t\tnameDoc.UpdateBlock = d.BlockNo\n\t\t\tnameChannel <- nameDoc\n\t\t}\n\t}\n}", "func (a *Aggregator) emitTick(product ProductType) *AgrTickMsg {\n\n\tif total, ok := a.totalSources[product]; ok {\n\t\tif prodFeeds, ok := a.feeds[product]; ok {\n\n\t\t\tactive := 0\n\t\t\tvar minAskPrice, maxBidPrice float64\n\n\t\t\tfor _, msg := range prodFeeds {\n\t\t\t\tif msg != nil {\n\t\t\t\t\tactive += 1\n\t\t\t\t\tif msg.Ts > 0 {\n\t\t\t\t\t\tif msg.BidPrice > maxBidPrice {\n\t\t\t\t\t\t\tmaxBidPrice = msg.BidPrice\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif minAskPrice == 0 || msg.AskPrice < minAskPrice {\n\t\t\t\t\t\t\tminAskPrice = msg.AskPrice\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\tif active > 0 {\n\t\t\t\tagrMsg := &AgrTickMsg{\n\t\t\t\t\tProduct: product,\n\t\t\t\t\tAskPrice: minAskPrice,\n\t\t\t\t\tBidPrice: maxBidPrice,\n\t\t\t\t\tActiveSources: active,\n\t\t\t\t\tTotalSources: total,\n\t\t\t\t}\n\n\t\t\t\t// log.Printf(\"emitTick: %v\", *agrMsg)\n\n\t\t\t\ta.Tick <- agrMsg\n\n\t\t\t\treturn agrMsg\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.58206636", "0.51634", "0.51634", "0.50613075", "0.4883064", "0.48517308", "0.46625176", "0.46531016", "0.46157056", "0.46082562", "0.45802093", "0.45716262", "0.4527733", "0.45255494", "0.45206347", "0.4507735", "0.45058075", "0.44996315", "0.44682333", "0.4420023", "0.44097352", "0.44010013", "0.43992642", "0.43824646", "0.43495062", "0.43208593", "0.43164158", "0.43065077", "0.42547745", "0.42502183", "0.424207", "0.42255625", "0.42174497", "0.42038405", "0.42033613", "0.4201371", "0.42008168", "0.41893485", "0.4183792", "0.41689494", "0.41467384", "0.41443852", "0.41370612", "0.41352674", "0.41324517", "0.4129261", "0.41198328", "0.41175425", "0.41083932", "0.41068435", "0.41062987", "0.40937218", "0.40703273", "0.40617225", "0.40595785", "0.4058843", "0.40558192", "0.40463987", "0.40447587", "0.4040371", "0.4039024", "0.40387386", "0.40351456", "0.40346646", "0.4033285", "0.40295398", "0.4028938", "0.40280703", "0.4026394", "0.40225297", "0.40209433", "0.4019825", "0.40196145", "0.4019312", "0.40165198", "0.40116602", "0.4011582", "0.40069824", "0.4005131", "0.39984477", "0.39964944", "0.39906734", "0.39906734", "0.39906734", "0.39882252", "0.39862815", "0.39846584", "0.3982963", "0.39760935", "0.3964888", "0.3963015", "0.39604473", "0.39596182", "0.3958472", "0.39580348", "0.3957067", "0.39550382", "0.39502856", "0.39491373", "0.39483318" ]
0.4006851
78
calling twist() every n numbers
func (mt *MersenneTwister) RandomInt() int32 { if !mt.seeded { panic(errors.New("Generator was never seeded")) } if mt.index == mt.n { mt.twist() } y := mt.arr[mt.index] y = y ^ ((y >> mt.u) & mt.d) y = y ^ ((y << mt.s) & mt.b) y = y ^ ((y << mt.t) & mt.c) y = y ^ (y >> mt.l) mt.index++ return ((1 << mt.w) - 1) & (y) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mt *MT19937) twist() {\n\tfor i := 0; i < (n - 1); i++ {\n\t\tvar x = (mt.state[i] & upper) + (mt.state[(i+1)%n] & lower)\n\t\tvar next = x >> 1\n\t\tif (x % 2) != 0 {\n\t\t\tnext = next ^ a\n\t\t}\n\t\tmt.state[i] = mt.state[(i+m)%n] ^ next\n\t}\n\tmt.index = 0\n}", "func (mt *MersenneTwister) twist() {\n\tfor i := 0; i < mt.n; i++ {\n\t\tx := (mt.arr[i] & mt.upperMask) + (mt.arr[(i+1)%mt.n] & mt.lowerMask)\n\t\txA := x >> 1\n\t\tif (x % 2) != 0 { // lowest bit of x is 1\n\t\t\txA = xA % mt.a\n\t\t}\n\t\tmt.arr[i] = mt.arr[(int32(i)+mt.m)%int32(mt.n)] ^ xA\n\t}\n\tmt.index = 0\n}", "func (mt *MT) twist() {\n\tfor i := 0; i < n; i++ {\n\t\tx := (mt.state[i] & upper_mask) + (mt.state[(i+1)%n] & lower_mask)\n\t\txA := x >> 1\n\t\tif x%2 == 1 {\n\t\t\txA = xA ^ a\n\t\t}\n\t\tmt.state[i] = mt.state[(i+m)%n] ^ xA\n\t}\n\tmt.index = 0\n}", "func applyNTimes(factor, sum, accFactor, accSum *big.Int, n int64) (*big.Int, *big.Int) {\n\tif n == 0 {\n\t\treturn accFactor, accSum\n\t}\n\n\tif n%2 == 1 {\n\t\taccFactor = mod(mul(accFactor, factor), bigSize)\n\t\taccSum = mod(add(mul(accSum, factor), sum), bigSize)\n\t}\n\n\tfactor2 := mod(mul(factor, factor), bigSize)\n\tsum2 := mod(add(mul(factor, sum), sum), bigSize)\n\n\treturn applyNTimes(factor2, sum2, accFactor, accSum, n/2)\n}", "func efficientWayOfGeneratingAmount(){\n\tdone := make(chan interface{})\n\tdefer close(done)\n\tfor num := range take(done, repeat(done, 1), 10) {\n \tfmt.Printf(\"%v\", num)\n\t}\n\tfmt.Println()\n}", "func round(n int) int {\n\theadCount := 0\n\tfor i := 0; i < n; i++ {\n\t\tif rand.Intn(2) == 1 {\n\t\t\theadCount++\n\t\t}\n\t}\n\treturn headCount\n}", "func main() {\n\tfor n := range sq(sq(gen(2, 3))) {\n\t\tfmt.Println(n)\n\t}\n}", "func RepeatInt64N(v int64, n int) <-chan int64 {\n\tch := make(chan int64, 1)\n\tgo func() {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tch <- v\n\t\t}\n\t}()\n\treturn ch\n}", "func IntRand(z *big.Int, rnd *rand.Rand, n *big.Int,) *big.Int", "func updateN(n int, b *testing.B) {\n\tb.StopTimer()\n\tw := benchWorld()\n\tp := benchPlayer()\n\n\tvar bds boids\n\tboidVal := bds.Generate(rand.New(rand.NewSource(rand.Int63())), n)\n\tbds = boidVal.Interface().(boids)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tUpdateBoids(uint(i), bds, p, w)\n\t}\n}", "func Ints(n int, fn func([]int)) {\n\ta := make([]int, n)\n\tfor i := range a {\n\t\ta[i] = i\n\t}\n\tpermutations(a, 0, fn)\n}", "func main() {\n\tfor n := range sq(sq(gen(1, 2, 3, 4, 5, 6, 7))) {\n\t\tfmt.Printf(\"SQ: %d\\n\", n)\n\t}\n}", "func _runN(*B, int)", "func multiples(n, limit int) (multiples []int) {\n\tfor i := n; i < limit; i++ {\n\t\tif i%n == 0 {\n\t\t\tmultiples = append(multiples, i)\n\t\t}\n\t}\n\treturn\n}", "func main() {\n\n\thittable := make(map[int]bool)\n\tans := int64(0)\n\n\tfor i := 1; i*i <= top*9*9; i++ {\n\t\thittable[i*i] = true\n\t}\n\n\tfor i := range hittable {\n\t\tways, _ := enumerate(9, top, i)\n\t\tfor i := 0; i < len(ways); i++ {\n\t\t\tans += process(ways[i])\n\t\t\tans %= mod\n\t\t}\n\t}\n\n\tfmt.Println(\"171/ Find the last nine digits of the sum of all n, 0 < n < 10^20, such that f(n) is a perfect square\")\n\tfmt.Println(ans)\n}", "func main() {\n\tvalues := gen(20)\n\n\tfactorials := calc(values)\n\n\tfor n := range factorials {\n\t\tfmt.Println(n)\n\t}\n}", "func RepeatIntN(v int, n int) <-chan int {\n\tch := make(chan int, 1)\n\tgo func() {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tch <- v\n\t\t}\n\t}()\n\treturn ch\n}", "func RepeatUint64N(v uint64, n int) <-chan uint64 {\n\tch := make(chan uint64, 1)\n\tgo func() {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tch <- v\n\t\t}\n\t}()\n\treturn ch\n}", "func BenchmarkThirt(b *testing.B) {\n\tinput := 987654321\n\tfor index := 0; index < b.N; index++ {\n\t\tThirt(input)\n\t}\n}", "func double(n int) {\n\tn *= 2\n}", "func TakeInt64(n int, list []int64) []int64 {\n\tif n < 0 {\n\t\treturn []int64{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]int64, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func GenerateAtkin(to int) ([]int, error) {\n\n\tif to == 1 {\n\t\treturn []int{}, nil\n\t}\n\n\tif to == 2 {\n\t\treturn []int{2}, nil\n\t}\n\n\tif to == 3 {\n\t\treturn []int{2, 3}, nil\n\t}\n\n\tfto := float64(to)\n\tsieveLim := int(math.Sqrt(fto))\n\n\tif sieveLim <= 0 || to <= 0 {\n\t\treturn nil, errors.New(\"invalid range\")\n\t}\n\n\t// init sieve\n\tisPrime := make([]bool, to+1, to+1) // all elements are false (bool default)\n\n\tisPrime[2] = true\n\tisPrime[3] = true\n\tprimesCount := 2\n\n\tx2 := 0\n\tn := 0\n\tfor i := 1; i <= sieveLim; i++ {\n\t\tx2 += 2*i - 1\n\t\ty2 := 0\n\t\tfor j := 1; j <= sieveLim; j++ {\n\t\t\ty2 += 2*j - 1\n\t\t\tn = 4*x2 + y2\n\n\t\t\tif (n <= to) && (n%12 == 1 || n%12 == 5) {\n\t\t\t\tisPrime[n] = !isPrime[n]\n\t\t\t\tif isPrime[n] {\n\t\t\t\t\tprimesCount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// n = 3 * x2 + y2;\n\t\t\tn -= x2\n\t\t\tif (n <= to) && (n%12 == 7) {\n\t\t\t\tisPrime[n] = !isPrime[n]\n\t\t\t\tif isPrime[n] {\n\t\t\t\t\tprimesCount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// n = 3 * x2 - y2;\n\t\t\tn -= 2 * y2\n\t\t\tif (i > j) && (n <= to) && (n%12 == 11) {\n\t\t\t\tisPrime[n] = !isPrime[n]\n\t\t\t\tif isPrime[n] {\n\t\t\t\t\tprimesCount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// Filter out squares of existing prime numbers [5, sqrt(to)].\n\tfor i := 5; i <= sieveLim; i++ {\n\t\tif isPrime[i] {\n\t\t\tn = i * i\n\t\t\tfor j := n; j <= to; j += n {\n\t\t\t\tif isPrime[j] {\n\t\t\t\t\tprimesCount--\n\t\t\t\t}\n\t\t\t\tisPrime[j] = false\n\t\t\t}\n\t\t}\n\t}\n\n\tres := make([]int, primesCount, primesCount)\n\tres[0] = 2\n\tres[1] = 3\n\tif primesCount >= 3 {\n\t\tres[2] = 5\n\t}\n\tidx := 3\n\tfor i := 6; i <= to; i++ {\n\t\tif isPrime[i] {\n\t\t\tres[idx] = i\n\t\t\tidx++\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func main() {\n\ttotal := int64(0)\n\tvectors := ways(10, top, 3)\n\tfor _, vector := range vectors {\n\t\ttotal += distribute(vector)\n\t}\n\n\tfmt.Println(\"172/ How many 18-digit numbers n (without leading zeros) are there such that no digit occurs more than three times in n?\")\n\tfmt.Println(total)\n}", "func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }", "func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }", "func Intn(n int) int { return globalRand.Intn(n) }", "func Intn(n int) int { return globalRand.Intn(n) }", "func Intn(n int) int { return globalRand.Intn(n) }", "func GenerateBeaverTriplet(N *big.Int) [3]*big.Int {\n\tvar triplet [3]*big.Int\n\n\tx, y := getRandom(N), getRandom(N)\n\n\tif mr.Intn(2) > 0 {\n\t\t// u = x, v = y, w = xy mod N\n\t\tw := new(big.Int).Mul(x, y)\n\t\ttriplet[0] = w.Mod(w, N)\n\t\ttriplet[1] = x\n\t\ttriplet[2] = y\n\t} else {\n\t\t// v = x, w = y, u = (xy^-1)^-1 mod N\n\t\tu := new(big.Int).Mul(x, new(big.Int).ModInverse(y, N))\n\t\ttriplet[0] = y\n\t\ttriplet[1] = x\n\t\ttriplet[2] = u.ModInverse(u, N)\n\t}\n\n\treturn triplet\n}", "func main() {\n\tn := 1000 - 1\n\tsum := numbers.SumOfMultiples(3, n) + numbers.SumOfMultiples(5, n) - numbers.SumOfMultiples(15, n)\n\n\tlog.Println(sum)\n}", "func main() {\n var num int\n flag.IntVar(&num, \"n\", 10, \"Set the number of fibonacci numbers to crunch [10]\")\n flag.Parse()\n f1, f2 := big.NewInt(1), big.NewInt(1)\n for i:=1;i<num+1;i+=1 {\n tmp := new(big.Int)\n tmp.Add(f1, f2)\n f1 , f2 = f2, tmp\n }\n fmt.Printf(\"%s\\n\", f1.String())\n}", "func benchmarker(n int, f action) (err error) {\n\tfor i := 0; i < n; i++ {\n\t\tif err = f(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Rd(n int) int {\n\treturn rand.Intn(n)\n}", "func main() {\n\tn := 10 // number of functions to spawn\n\tc := make(chan int) // unbuffered integer channel\n\tdone := make(chan bool) // semaphore channel\n\n\tfor i := 0; i < n; i++ {\n\t\tgo func(n int) {\n\t\t\tfor i := 0 + (n*10); i < 10 +(n*10); i++ {\n\t\t\t\tc <- i\n\t\t\t}\n\t\t\tdone <- true\n\t\t}(i)\n\t}\n\n\tgo func() {\n\t\tfor i := 0; i < n; i++ {\n\t\t\t<-done\n\t\t}\n\t\tclose(c)\n\t}()\n\n\tfor n := range c {\n\t\tfmt.Println(n)\n\t}\n}", "func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {}", "func Thirt(n int) int {\n\tsum := 0\n\tnumber := n\n\n\tfor i := 1; number > 0; i *= 10 {\n\t\tsum += (i % 13) * (number % 10)\n\t\tnumber /= 10\n\t}\n\n\tif n == sum {\n\t\treturn n\n\t}\n\n\treturn Thirt(sum)\n}", "func RandomFlt(ln int) []float64 {\n\tvar numbers []float64\n\t//var array [40]float64\n\trand.Seed(time.Now().UTC().UnixNano())\n\tfor i := ln - 1; i > 0; i-- {\n\t\t//j := rand.Intn(i + 1)\n\t\tn := rand.Float64() * 90 // simulate number close to 90\n\t\t//array[i], array[j] = array[j], array[i]\n\t\tnumbers = append(numbers, n)\n\t}\n\treturn numbers\n}", "func numbers(done chan<- bool) {\n\tfor i := 0; i < 5; i++ {\n\t\ttime.Sleep(2 * time.Second)\n\t\tfmt.Println(i)\n\t}\n\n\tdone <- true\n}", "func hash_func(x, y, n HashValue) (HashValue) {\n return (x*1640531513 ^ y*2654435789) % n\n}", "func main() {\n var N int\n fmt.Scan(&N)\n\n tryPoint := 5\n transformPoint := 2\n penaDropPoint := 3\n\n var results []string\n\n possibleTryTimes := int(math.Floor(float64(N / tryPoint)))\n for tryTimes := possibleTryTimes; tryTimes >= 0; tryTimes-- {\n tryPoints := tryPoint * tryTimes\n\n possibleTransformationTimes := int(math.Min(float64((N - tryPoints) / transformPoint), float64(tryTimes)))\n for transformationTimes := possibleTransformationTimes; transformationTimes >= 0; transformationTimes-- {\n transformPoints := transformPoint * transformationTimes\n\n reminingPoints := N - tryPoints - transformPoints\n if reminingPoints % penaDropPoint == 0 {\n penaltieOrDropTimes := reminingPoints / penaDropPoint\n result := fmt.Sprintf(\"%d %d %d\", tryTimes, transformationTimes, penaltieOrDropTimes)\n\n results = append([]string{result}, results...)\n }\n }\n }\n\n // fmt.Fprintln(os.Stderr, \"Debug messages...\")\n // fmt.Println(\"tries transformations penalties\")// Write answer to stdout\n for _, v := range results {\n fmt.Println(v)\n }\n}", "func RepeatFloat64N(v float64, n int) <-chan float64 {\n\tch := make(chan float64, 1)\n\tgo func() {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tch <- v\n\t\t}\n\t}()\n\treturn ch\n}", "func evenFib() func() float64 {\n\tx := float64(0)\n\ty := float64(1)\n\treturn func() float64 {\n\t\tx, y = y, x+y\n\t\treturn y\n\t}\n}", "func main() {\n\ttNumber := 0\n\tfor i := 1; true; i++ {\n\t\ttNumber += i\n\t\tf := factorsCount(int64(tNumber))\n\t\tfmt.Printf(\"%d: %d -> %d \\n\", i, tNumber, f)\n\t\tif f > 500 {\n\t\t\tfmt.Println(\"Number: \", tNumber)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (in *CF1551A) Run() {\n\tt := in.NextInt()\n\tfor ; t > 0; t-- {\n\t\tn := in.NextInt()\n\t\ttwo := int(math.Ceil(float64(n) / 3.0))\n\t\tone := int(math.Floor(float64(n) / 3.0))\n\n\t\tif (two * 2) + one != n {\n\t\t\tone, two = two, one\n\t\t}\n\t\tfmt.Println(one, two)\n\t}\n}", "func printSquare (idx int, sleeptime int) {\n if idx % 2 == 0 {\n time.Sleep(time.Millisecond * time.Duration(sleeptime))\n }\n fmt.Println(\"square of \", idx, \"is\", idx*idx)\n}", "func RelChangeN(n int) func(s []float64) (res []float64) {\n\treturn func(s []float64) (res []float64) {\n\t\tif n > len(s) {\n\t\t\treturn []float64{}\n\t\t}\n\t\td := Skip(n)(s)\n\t\tres = make([]float64, len(d))\n\n\t\tfor i := range d {\n\t\t\tres[i] = (d[i] - s[i]) / s[i]\n\t\t}\n\t\treturn\n\t}\n}", "func generateLuckyNumbers(value int) {\n if value > limit {\n return\n }\n if value > 0 {\n luckyNumbers = append(luckyNumbers, value)\n }\n generateLuckyNumbers(value * 10 + 4)\n generateLuckyNumbers(value * 10 + 7)\n}", "func waysToChange(n int) int {\n\tdp := make([]int, n+1)\n\tdp[0] = 1\n\tcoins := []int{1, 5, 10, 25}\n\tfor _, coin := range coins {\n\t\tfor i := coin; i <= n; i++ {\n\t\t\tdp[i] = (dp[i] + dp[i-coin]) % 1000000007\n\t\t}\n\t}\n\treturn dp[n]\n}", "func doItLessVerbose() {\n\tsum := 1\n\tfor ; sum < 60; {\n\t\tfmt.Println(sum)\n\t\tsum += sum\n\t}\n}", "func _for(p population, f consumer, withRandom bool, start, end int) {\n\tN := end - start\n\tn := runtime.GOMAXPROCS(0)\n\tif p.NThread > 0 {\n\t\tn = p.NThread\n\t}\n\tif N < n {\n\t\tsem := make(Semaphore, N)\n\t\tsem.P(N)\n\t\tfor ; start < end; start++ {\n\t\t\tgo func(i int) {\n\t\t\t\tvar r *rand.Rand\n\t\t\t\tif withRandom {\n\t\t\t\t\tr = rand.New(rand.NewSource(int64(i)))\n\t\t\t\t}\n\t\t\t\tf.Apply(i, p.Genes[i], r)\n\t\t\t\tsem.Signal()\n\t\t\t}(start)\n\t\t}\n\t\tsem.Wait(N)\n\t} else {\n\t\ts := N / n\n\t\tsem := make(Semaphore, n)\n\t\tsem.P(n)\n\t\tfor i := 0; i < n; i++ {\n\t\t\tgo func(i int) {\n\t\t\t\tvar r *rand.Rand\n\t\t\t\tif withRandom {\n\t\t\t\t\tr = rand.New(rand.NewSource(int64(i)))\n\t\t\t\t}\n\t\t\t\tfor j := i*s + start; j < (i+1)*s+start; j++ {\n\t\t\t\t\tf.Apply(j, p.Genes[j], r)\n\t\t\t\t}\n\t\t\t\tsem.Signal()\n\t\t\t}(i)\n\t\t}\n\t\tsem.Wait(n)\n\t\tif n*s != N {\n\t\t\t_for(p, f, withRandom, n*s+start, end)\n\t\t}\n\t}\n}", "func Intn(n int) int {\n\tmu.Lock()\n\tres := r.Intn(n)\n\tmu.Unlock()\n\treturn res\n}", "func (t thing) run(me int, big int, two_chan chan string, cntl_chan chan string) {\n waituntil := <-cntl_chan\n t.validate_start(waituntil)\n for n:=0; n<big; n++ {\n newt := thing(math.Sqrt(float64(t * t + thing(me))))\n if n % (big / 4) == 0 {\n two_chan <- fmt.Sprintf(\"%s %d %d\\n\", PROGRESS, me, n)\n fmt.Printf(\"%s %d %d\\n\", PROGRESS, me, n)\n }\n t = newt\n }\n fmt.Printf(\"%d ended with final result %f\\n\", me, float64(t))\n two_chan <- STOP\n}", "func generator(startingValue int64, factor int64) (Result []int64) {\n\n\tdefer measureTime(time.Now(), \"generator\"+strconv.FormatInt(startingValue, 10))\n\tpreviousValue := startingValue //\tint64(startingValue)\n\n\tfor ig := 1; ig <= numberofPairs; ig++ {\n\n\t\tproductValue := previousValue * factor //\tMultiplication is resulting in more than uint32\t=>\tuint64\n\t\tnextValue := productValue % int64(divisor) //\tRemainder of x / y\t=> Guaranteed to be 32 bits\n\n\t\tResult = append(Result, nextValue) //\tPopulating slice of resulting values\n\t\tpreviousValue = nextValue //\tPreparing for the next run of the loop\n\n\t}\n\treturn Result\n}", "func fistStep(numbers []int) []int {\n\n\tdouble := make([]int, len(numbers))\n\n\tcopy(double, numbers)\n\n\tfor i := 0; i < len(double); i++ {\n\t\tif i%2 != 0 {\n\t\t\tdouble[i] = double[i] * 2\n\t\t\tif double[i] > 9 {\n\t\t\t\tdouble[i] = double[i] - 9\n\t\t\t}\n\t\t}\n\t}\n\n\treturn double\n}", "func Intn(n int) int {\n\treturn int(src.Int63() % int64(n))\n}", "func main() {\n\tnextfib := fibgen()\n\tvar evenfibsum int\n\tfor {\n\t\tcur := nextfib()\n\t\tif cur > 4000000 { // is there a better way to write 4 million?\n\t\t\tbreak\n\t\t}\n\t\tif iseven(cur) {\n\t\t\tevenfibsum += cur\n\t\t}\n\t}\n\tfmt.Println(\"sum =\", evenfibsum)\n}", "func main() {\n\tvar n, m, cur int\n\tfmt.Scan(&n)\n\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Scan(&m)\n\t\tsum := 0\n\t\tfor j := 0; j < m; j++ {\n\t\t\tfmt.Scan(&cur)\n\t\t\tsum += cur\n\t\t}\n\t\tfmt.Println(sum)\n\t}\n}", "func oetRun(value *int, procid int, steps int,\n toPred, fromPred, toSucc, fromSucc chan int) {\n for t := 0; t < steps; t += 1 {\n if (procid + t) % 2 == 0 && toSucc != nil {\n exchangeWith(mini, value, fromSucc, toSucc)\n }\n if (procid + t) % 2 == 1 && toPred != nil {\n exchangeWith(maxi, value, fromPred, toPred)\n }\n }\n}", "func TakeUint64(n int, list []uint64) []uint64 {\n\tif n < 0 {\n\t\treturn []uint64{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]uint64, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func inc(n int) int {\n\tn++\n\tif Repeat > 0 {\n\t\tn %= Repeat\n\t}\n\treturn n\n}", "func main() {\n //fmt.Println(sum_of_even_fibs_up_to(25))\n //=> 10\n\n fmt.Println(sum_of_even_fibs_up_to(4000000))\n //=> ?? \n}", "func daisy_sample() {\n\tconst n = 1000\n\tleftmost := make(chan int)\n\tright := leftmost\n\tleft := leftmost\n\n\tfor i := 0; i < n; i++ {\n\t\tright = make(chan int)\n\t\tgo f(left, right)\n\t\tleft = right\n\t}\n\n\tgo func(c chan int) { c <- 1 }(right)\n\tfmt.Println(<-leftmost)\n}", "func Repeat[T any](t T, n int) (tt []T) {\n\tfor i := 0; i < n; i++ {\n\t\ttt = append(tt, t)\n\t}\n\treturn tt\n}", "func BenchmarkWorknMulti(b *testing.B) {\n\tfoundValues, bob := randomNumMap(6)\n\ttype wrkr func(NumCol, *NumMap) SolLst\n\ttype wrkrTest struct {\n\t\tfc wrkr\n\t\tdesc string\n\t}\n\trunners := []wrkrTest{\n\t\t{workN, \"old\"},\n\t}\n\tfor _, runner := range runners {\n\t\trunFunc := func(tb *testing.B) {\n\t\t\tfor i := 0; i < tb.N; i++ {\n\t\t\t\ttb.StopTimer()\n\t\t\t\tfv := foundValues.Duplicate()\n\t\t\t\ttb.StartTimer()\n\t\t\t\trunner.fc(bob, fv)\n\t\t\t}\n\t\t}\n\t\trunString := runner.desc\n\t\tb.Run(runString, runFunc)\n\t}\n}", "func generate(n int, A []int) {\n\tif n == 1 {\n\t\t// fmt.Println(A)\n\t\tcountsubFactorial(A)\n\t} else {\n\t\tfor i := 0; i < n-1; i++ {\n\t\t\tgenerate(n-1, A)\n\t\t\tif n%2 == 0 {\n\t\t\t\t// swap\n\t\t\t\tt := A[i]\n\t\t\t\tA[i] = A[n-1]\n\t\t\t\tA[n-1] = t\n\t\t\t} else {\n\t\t\t\t// swap\n\t\t\t\tt := A[0]\n\t\t\t\tA[0] = A[n-1]\n\t\t\t\tA[n-1] = t\n\t\t\t}\n\t\t}\n\t\tgenerate(n-1, A)\n\t}\n}", "func Intn(n int) int {\n\treturn global.Intn(n)\n}", "func main() {\n\thighWater := 10\n\tif len(os.Args) == 2 {\n\t\tif n, err := strconv.Atoi(os.Args[1]); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t} else {\n\t\t\thighWater = n\n\t\t}\n\t}\n\n\tvar curr, prev int\n\n\tcurr = 1\n\tsum := 0\n\tfor i := 0; curr < highWater; i++ {\n\t\tif curr%2 == 0 {\n\t\t\tsum += curr\n\t\t}\n\n\t\tprev, curr = curr, curr+prev\n\t}\n\n\tlog.Printf(\"The sum of the even-valued terms below %d is %d\", highWater, sum)\n}", "func (r *Randomness) GenerateMany(n int) ([]int64, error) {\n\tnumbers := []int64{}\n\n\tfor i := 0; i < n; i++ {\n\t\tn, err := r.Generate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnumbers = append(numbers, n)\n\t}\n\n\treturn numbers, nil\n}", "func TakeFloat64(n int, list []float64) []float64 {\n\tif n < 0 {\n\t\treturn []float64{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]float64, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func secondStep(numbers []int) bool {\n\n\tsum := 0\n\n\tfor _, num := range numbers {\n\t\tsum += num\n\t}\n\n\treturn sum%10 == 0\n}", "func SumOfFirstNIntegers(n int) int {\n return (1 + n) * n / 2\n}", "func (b *NthBigInt) Nth(n int64, value *big.Int) *big.Int {\n\tif n <= b.numTaken {\n\t\tpanic(kNotGreater)\n\t}\n\tfor n > b.numTaken {\n\t\tb.stream.Next(value)\n\t\tb.numTaken++\n\t}\n\treturn value\n}", "func main() {\n start := time.Now()\n max, num := 0, 0\n for i := 1; i < 1000; i++ {\n if drdmath.IsPrime(uint64(i)) {\n if r := rcl(i); r > max {\n max, num = r, i\n }\n }\n }\n fmt.Printf(\"the recurring cycle of 1/%d is %d.\\n\", num, max)\n end := time.Now()\n fmt.Fprintln(os.Stderr, end.Sub(start))\n}", "func FibIterative(n int) int {\n\tif n < 2 {\n\t\treturn n\n\t}\n\ta, b := 0, 1\n\n\tfor i := 1; i < n; i++ {\n\t\ta, b = b, a+b\n\t}\n\n\treturn b\n\n}", "func calculateFibonacci(n int) []int {\n\t//We must set the first two seed values\n\tslice := []int{0, 1}\n\n\t//If we're calculating more than 2 vals, perform the calculation.\n\t//Otherwise, simply return a subset of the first two seeds.\n\tif n >= 2 {\n\t\tfor i := 2; i < n; i++ {\n\t\t\tnewVal := slice[i-1] + slice[i-2]\n\t\t\tslice = append(slice, newVal)\n\t\t}\n\t} else {\n\t\treturn slice[:n]\n\t}\n\treturn slice\n}", "func main() {\n\tvar sum int\n\tfor _, value := range getFibonacciNumbersBelow(4000000) {\n\t\tif value%2 == 0 {\n\t\t\tsum += value\n\t\t}\n\t}\n\tfmt.Println(\"Sum: \", sum)\n}", "func SumN(f myFunc) func(int) int {\n\n\treturn func(number int) int {\n\t\tsum := 0\n\t\tfor i := 1; i <= number; i++ {\n\t\t\tsum += f(i)\n\t\t}\n\n\t\treturn sum\n\t}\n}", "func makeEvenGenerator() func() uint {\n\ti := uint(0)\n\n\treturn func() (result uint) {\n\t\tresult = i\n\t\ti += 3\n\t\treturn\n\t}\n}", "func main2() {\n\tvar sum = 10\n\tvar n3 = 2\n\tvar n6 = 8\n\n\tfor ; n6 < 1000000; {\n\t\tvar tmp = n3 + n6 * 4\n\t\tsum += tmp\n\t\tn3 = n6\n\t\tn6 = tmp\n\t}\n\n\tfmt.Printf(\"Result: %d\", sum)\n}", "func sf(n int) int {\n\tsum := 0\n\tfor _, d := range digits(f(n)) {\n\t\tsum += d\n\t}\n\treturn sum\n}", "func climbStairs(n int) int {\r\n a, b := 1, 1\r\n for i := 2; i <= n; i++ {\r\n a, b = a + b, a\r\n }\r\n return a\r\n}", "func (s *Int64) Iterate(fn func(int64)) {\n\tfor val := range s.m {\n\t\tfn(val)\n\t}\n}", "func (g *GeneratorJakes) GenerateN(tstart, tinterval float64, N int) []complex128 {\n\tg.tInterval = tinterval\n\tresult := make([]complex128, N)\n\tt := tstart\n\tfor i, _ := range result {\n\t\tresult[i] = g.generate(t)\n\t\tt += tinterval\n\t}\n\treturn result\n}", "func gogen(startingValue int64, factor int64, result chan []int64) {\n\n\tdefer measureTime(time.Now(), \"gogen\"+strconv.FormatInt(startingValue, 10))\n\n\tgenValues := []int64{} //\tEmpty Slice\n\tpreviousValue := startingValue //\tuint64(startingValue)\n\tdefer close(result) //\tclosing channel on return\n\n\tfor ig := 1; ig <= numberofPairs; ig++ {\n\n\t\tproductValue := previousValue * factor //\tMultiplication is resulting in more than uint32\t=>\tuint64(factor)\n\t\tnextValue := productValue % int64(divisor) //\tRemainder of x / y\t=> Guaranteed to be 32 bits\n\n\t\tgenValues = append(genValues, nextValue) //\tPopulating slice of resulting values\n\t\tpreviousValue = nextValue //\tPreparing for the next run of the loop\n\t}\n\n\tresult <- genValues //\tDone sending...\n\treturn //\tcleaning everything...\n}", "func Solution(N int) []int {\n\t// write your code in Go 1.4\n\t//Use better seed for better randomness.\n\trand.Seed(time.Now().UnixNano())\n\tres := make([]int, N)\n\n\tfor i := 0; i < N; i++ {\n\t\tr := rand.Intn(i + 1)\n\t\tres[i] = r + 1\n\t}\n\treturn res\n}", "func sum_of_multiples_under_n(m, n int) int {\n // the sum of multiples of m under n is the sum of the arithmetic\n // series that star with m, has difference of m, and has n/m elements\n return aritmetic_sereies_sum(m, n/m, m)\n}", "func g(i int) (n int) {\n\tfor n = 1; sf(n) != i; n++ {\n\t}\n\treturn\n}", "func RepeatUintN(v uint, n int) <-chan uint {\n\tch := make(chan uint, 1)\n\tgo func() {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tch <- v\n\t\t}\n\t}()\n\treturn ch\n}", "func randNums(ch chan<- int, kill chan<- bool, num int) {\n rand.Seed(42) // Consistent random numbers\n for i := 0; i < num ; i++{\n i := rand.Intn(num)\n ch <- i\n }\n kill <- true\n}", "func main() {\n\tvar res uint64\n\tvar N int\n\tfmt.Scanf(\"%v\", &N)\n\tx := make([]uint64, N)\n\ty := make([]interface{}, len(x))\n\tfor i := range x {\n\t\ty[i] = &x[i]\n\t}\n\tfmt.Scanln(y...)\n\tfor _,val := range x {\n\t\tres += val\n\t}\n\tfmt.Printf(\"%d\", res)\n}", "func TwoThreeSieve() func() int {\n i := 5\n two, first := true, true\n return func() int {\n if first {\n first = false\n return 5\n }\n if two {\n two = false; i += 2\n return i\n } else {\n two = true; i += 4\n return i\n }\n }\n}", "func BTW(ir, mr operand.Op) { ctx.BTW(ir, mr) }", "func showMeSomeNumbers() {\n\tsum := 1\n\tfor i := 1; i <= 10; i++ {\n\t\tfmt.Println(i, sum)\n\t\tsum += i\n\t}\n}", "func main() {\n\tnum1, num2 := next2Values(5)\n\tfmt.Println(num1, num2)\n}", "func main() {\n\tfmt.Println(findLucky([]int{7, 7, 7, 7, 7, 7, 7}))\n\tfmt.Println(findLucky([]int{2, 2, 2, 3, 3}))\n\tfmt.Println(findLucky([]int{2, 2, 3, 4}))\n}", "func main(){\n in := gen(2, 3)\n\n // Distribute the sq work across two goroutines that both read from in.\n c1 := square(in)\n c2 := square(in)\n\n // Consume the merged output from c1 and c2.\n for n := range merge(c1, c2) {\n fmt.Println(n) // 4 then 9, or 9 then 4\n }\n}", "func Benchmark_SliceIntIncr2(b *testing.B) {\n\tb.ResetTimer()\n\tfor i := 0; i <= b.N; i++ {\n\t\tn := [10]int{}\n\t\tfor i := range n {\n\t\t\tn[i]++\n\t\t}\n\t}\n}", "func SquareMiddleGenerator(seed int, numDigits int) []int {\n\n\tret := make([]int, 0)\n\n\tret = append(ret, seed)\n\tfor !HasRepeat(ret) {\n\t\tret = append(ret, SquareMiddle(ret[len(ret)-1], numDigits))\n\t}\n\treturn ret\n\n}", "func TakeInt(n int, list []int) []int {\n\tif n < 0 {\n\t\treturn []int{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]int, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func main() {\n\tvar count int64\n\tvar maxDistance int64\n\tfor {\n\t\tn, _ := fmt.Scan(&count, &maxDistance)\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tlines := make([]int64, count)\n var i int64\n\t\tfor i = 0; i < count; i++ {\n\t\t\tfmt.Scanf(\"%d\", &lines[i])\n\t\t}\n\n solutionCount := do(lines, maxDistance)\n fmt.Println(solutionCount % 99997867)\n }\n}", "func TestHowMany(t *testing.T) {\n\thm := func(x, y int) int {\n\t\treturn ((x) + ((y) - 1)) / (y)\n\t}\n\tr := hm(5, 3)\n\tif r != 2 {\n\t\tt.Errorf(\"r: %d\", r)\n\t}\n}" ]
[ "0.6886169", "0.687985", "0.6683788", "0.5794861", "0.56401026", "0.54962915", "0.5489031", "0.5430558", "0.5381281", "0.5380072", "0.534473", "0.5317879", "0.52988625", "0.52855694", "0.52002597", "0.5171031", "0.51393366", "0.51295286", "0.51225346", "0.5104639", "0.50958663", "0.5089207", "0.5087694", "0.508547", "0.508547", "0.50791764", "0.50791764", "0.50791764", "0.50599575", "0.5035149", "0.5033348", "0.50249386", "0.50169367", "0.5014158", "0.5012619", "0.5007158", "0.4996728", "0.49762353", "0.4969315", "0.49683788", "0.4967879", "0.49572673", "0.49423027", "0.4940967", "0.4918786", "0.49004316", "0.4898601", "0.48913765", "0.48912305", "0.4889778", "0.4879743", "0.4874905", "0.48745304", "0.48607284", "0.48607236", "0.4859204", "0.4856495", "0.48541045", "0.48496053", "0.48416725", "0.48288053", "0.4823951", "0.48223984", "0.4822005", "0.48160776", "0.481274", "0.48118892", "0.48115268", "0.4809987", "0.48088706", "0.48084253", "0.48076352", "0.4797693", "0.47973555", "0.47969684", "0.47953174", "0.4792773", "0.47922388", "0.47903278", "0.47685784", "0.47623986", "0.47610566", "0.475973", "0.4749632", "0.47471973", "0.47471264", "0.474614", "0.47417498", "0.47407648", "0.47391", "0.47380626", "0.4737797", "0.47371563", "0.47343212", "0.47241214", "0.47199482", "0.4715512", "0.47144803", "0.47053027", "0.47007623", "0.4697896" ]
0.0
-1
Register register new moudle
func (l *ModuleList) Register(m Module) { *l = append(*l, m) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *ModuleManager) Register(m Module) {\n\tif topic := m.GetTopic(); topic != \"\" {\n\t\tmd := new(DefaultModule)\n\t\tmd.mi = m\n\t\tmd.closeSig = make(chan bool, 1)\n\t\tm.RegisterMgr(this)\n\t\tthis.mods[topic] = md\n\t}\n}", "func (s *Server) Register(name string, h Handler) error {\n if _, ok := s.registry[name]; ok {\n return fmt.Errorf(\"cannot register name %q twice\", name)\n }\n s.registry[name] = &register{handler: h}\n return nil\n}", "func (ctl *ManagerController) register() {\n\tmanagers := ctl.router.Group(\"/managers\")\n\n\tmanagers.GET(\"\", ctl.ListManager)\n\n\t// CRUD\n\tmanagers.POST(\"\", ctl.CreateManager)\n\tmanagers.GET(\":id\", ctl.GetManager)\n\tmanagers.PUT(\":id\", ctl.UpdateManager)\n\tmanagers.DELETE(\":id\", ctl.DeleteManager)\n}", "func (c *Component) Register() {}", "func register(name string, p Plugin) {\n\tdirectory[name] = p\n}", "func RegWMD(name string, manager interface{}) {\n\tif manager == nil {\n\t\tpanic(\"WalletManager: Register adapter is nil\")\n\t}\n\tif _, ok := managers[name]; ok {\n\t\tlog.Printf(\"WalletManager: Register called twice for adapter \\n\" + name)\n\t\treturn\n\t}\n\tmanagers[name] = manager\n}", "func Register(name string, builder Builder) {\n\tregistry[name] = builder\n}", "func (s *Service) Register(name string, mp Provider) error {\n\ts.providers[name] = mp\n\treturn nil\n}", "func (p *Pupil) register(_sock *mangos.Socket) {\n\tsock := *_sock\n\tvar err error\n\tlog.Printf(\"Registering with master at %s\\n\", p.MasterCommandURL)\n\tif err = sock.Dial(p.MasterCommandURL); err != nil {\n\t\tlog.Fatalf(\"Wasn't able to reach the monk master at %s - %s\", p.MasterCommandURL, err.Error())\n\t}\n\t// We need to receive this only once\n\tvar regMessage []byte\n\tregMessage, err = messages.MarshalCommand(\"register\", p)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't prepare registation command\")\n\t}\n\terr = messages.SendCommand(&sock, regMessage)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't send registration request\\n\")\n\t}\n\tvar msg []byte\n\tmsg, err = sock.Recv()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error on registering with the monk master - %s\\n\", err.Error())\n\t}\n\tresp := unpackResponse(msg)\n\tif !resp.Success() {\n\t\tlog.Fatalf(\"Couldn't register with the master - %s\\n\", resp.Message())\n\t}\n}", "func (m *Manager) Register(name string, plugin Plugin) {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\tm.plugins = append(m.plugins, namedplugin{\n\t\tname: name,\n\t\tplugin: plugin,\n\t})\n}", "func (cli *CLI) register(rgst any, cmds ...string) {\n\tif len(cmds) > 0 {\n\t\tcmd := cmds[0]\n\t\tif len(cmds) > 1 {\n\t\t\tcli.cmdMap[cmd] = cmds[1]\n\t\t}\n\t\t// make the function map th struct\n\t\tcli.commands[cmd] = Cmd{\n\t\t\tCommand: cmd,\n\t\t\tAlias: cli.cmdMap[cmd],\n\t\t}\n\t\t// register feedback\n\t\tcli.cmds[cmd] = rgst\n\t}\n}", "func Register(id int, handlerName string) int", "func (w *worker) register() {\n\targs := &RegisterArgs{}\n\treply := &RegisterArgs{}\n\n\tif ok := call(\"Master.RegisterWorker\", args, reply); !ok {\n\t\tlog.Fatal(\"Register of worker failed\")\n\t}\n\tw.id = reply.WorkerId\n}", "func (self *Mediator) OnRegister() {\n\n}", "func RegisterMunger(munger PRMunger) error {\n\tif _, found := mungerMap[munger.Name()]; found {\n\t\treturn fmt.Errorf(\"a munger with that name (%s) already exists\", munger.Name())\n\t}\n\tmungerMap[munger.Name()] = munger\n\tglog.Infof(\"Registered %#v at %s\", munger, munger.Name())\n\treturn nil\n}", "func (s *Service) Register(ctx context.Context, item *types.Managers) (string, error) {\n\n\tvar token string\n\tvar id int64\n\n\tsql1 := `INSERT INTO managers (name, phone, is_admin) \n\t\tVALUES ($1, $2, $3) ON CONFLICT (phone) DO NOTHING RETURNING id;`\n\terr := s.pool.QueryRow(ctx, sql1, item.Name, item.Phone, item.IsAdmin).Scan(&id)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn \"\", ErrInternal\n\t}\n\n\tbuffer := make([]byte, 256)\n\tn, err := rand.Read(buffer)\n\tif n != len(buffer) || err != nil {\n\t\treturn \"\", ErrInternal\n\t}\n\ttoken = hex.EncodeToString(buffer)\n\n\tsql2 := `INSERT INTO managers_tokens (token, manager_id) VALUES($1, $2);`\n\t_, err = s.pool.Exec(ctx, sql2, token, id)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\", ErrInternal\n\t}\n\treturn token, nil\n}", "func (s *Server) Register(tm server.StateHandlerType, hmi interface{}) {\n\ts.pub.Register(tm, hmi)\n}", "func (ctl *MedicalequipmentController) register() {\n\tmedicalequipments := ctl.router.Group(\"/medicalequipments\")\n\n\tmedicalequipments.GET(\"\", ctl.ListMedicalequipment)\n\n\t// CRUD\n\tmedicalequipments.POST(\"\", ctl.CreateMedicalequipment)\n\tmedicalequipments.GET(\":id\", ctl.GetMedicalequipment)\n\tmedicalequipments.PUT(\":id\", ctl.UpdateMedicalequipment)\n\tmedicalequipments.DELETE(\":id\", ctl.DeleteMedicalequipment)\n}", "func (ctl *UnitOfMedicineController) register() {\n\tUnitOfMedicine := ctl.router.Group(\"/UnitOfMedicine\")\n\n\tUnitOfMedicine.GET(\"\", ctl.ListUnitOfMedicine)\n\n\t// CRUD\n\tUnitOfMedicine.POST(\"\", ctl.CreateUnitOfMedicine)\n\tUnitOfMedicine.GET(\":id\", ctl.GetUnitOfMedicine)\n\tUnitOfMedicine.PUT(\":id\", ctl.UpdateUnitOfMedicine)\n\tUnitOfMedicine.DELETE(\":id\", ctl.DeleteUnitOfMedicine)\n}", "func Register(cm map[int]string) {\n\t_messages.Store(cm)\n}", "func Register(a *apl.Apl, name string) {\n\tif name == \"\" {\n\t\tname = \"u\"\n\t}\n\tpkg := map[string]apl.Value{\n\t\t\"button\": apl.ToFunction(button),\n\t\t\"cls\": apl.ToFunction(cls),\n\t\t\"sam\": apl.ToFunction(sam),\n\t\t\"f\": apl.ToFunction(setCallback),\n\t\t\"kb\": apl.ToFunction(kb),\n\t\t\"split\": apl.ToFunction(split),\n\t\t\"top\": apl.ToFunction(top),\n\t}\n\tcmd := map[string]scan.Command{\n\t\t\"c\": rw0(\"cls\"),\n\t\t\"e\": toCommand(samCmd),\n\t\t\"k\": rw0(\"kb\"),\n\t}\n\ta.AddCommands(cmd)\n\ta.RegisterPackage(name, pkg)\n}", "func (n networkRoute) Register(m *mux.Router, handler http.Handler) {\n}", "func (m *manager) Register(name string, item interface{}, tags map[string]string) error {\n\tif err := dtos.ValidateMetricName(name, \"metric\"); err != nil {\n\t\treturn err\n\t}\n\n\tif len(tags) > 0 {\n\t\tif err := m.setMetricTags(name, tags); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := m.registry.Register(name, item); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Register(functions ...func()) *Manager {\n\treturn defaultManager.Register(functions...)\n}", "func (cli *CLI) Register(fun Function, name string, params []string, help string) {\n\tcli.commands = append(cli.commands, Command{fun, name, params, help})\n}", "func (m Metrics) register(m metric) error {\n\t// Register with Prometheus.\n\tprometheus.MustRegister(m.definition())\n}", "func (ctl *RemedyController) register() {\n\tRemedy := ctl.router.Group(\"/remedys\")\n\tRemedy.GET(\"\", ctl.ListRemedy)\n\t// CRUD\n\tRemedy.POST(\"\", ctl.CreateRemedy)\n\tRemedy.GET(\":id\", ctl.GetRemedy)\n\tRemedy.PUT(\":id\", ctl.UpdateRemedy)\n\tRemedy.DELETE(\":id\", ctl.DeleteRemedy)\n}", "func (ctl *ClubController) register() {\n\tclub := ctl.router.Group(\"/club\")\n\n\tclub.GET(\"\", ctl.ListClub)\n\n\t// CRUD\n\tclub.POST(\"\", ctl.CreateClub)\n\tclub.GET(\":id\", ctl.GetClub)\n\tclub.PUT(\":id\", ctl.UpdateClub)\n\tclub.DELETE(\":id\", ctl.DeleteClub)\n}", "func (server *Server) Register(action INetworkAction) {\n\n}", "func Register(name string, builder WebHandlerBuilder) {\n\thmu.Lock()\n\thandlers[name] = builder\n\thmu.Unlock()\n}", "func (p *JSONProtocol) Register(msg interface{}) {\n\tt := reflect.TypeOf(msg)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\tname := t.PkgPath() + \"/\" + t.Name()\n\tp.types[name] = t\n\tp.names[t] = name\n}", "func Register(m Model) {\n\tModels = append(Models, m)\n}", "func (handler commandHandler) register(name string, comman func(context), cooldown int) {\n\thandler.Cmds[name] = command{comman, cooldown}\n\tif len(name) > 2 {\n\t\thandler.Cmds[name[:2]] = command{comman, cooldown}\n\t}\n}", "func (ctl *MealController) register() {\n\tmeals := ctl.router.Group(\"/meals\")\n\n\tmeals.GET(\"\", ctl.ListMeal)\n\n\t// CRUD\n\tmeals.POST(\"\", ctl.CreateMeal)\n\tmeals.GET(\":id\", ctl.GetMeal)\n\tmeals.PUT(\":id\", ctl.UpdateMeal)\n\tmeals.DELETE(\":id\", ctl.DeleteMeal)\n}", "func (session *Session) register() error {\n\n\t// Create registration\n\tcmd, err := CreateRegistration(session.registration.Host, session.registration.User)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Send registration to server\n\tlog.Println(\"Registering with the server.\")\n\tSendMessage(cmd, session.socket)\n\treturn nil\n}", "func (m *Monocular) Register(echoContext echo.Context) error {\n\tlog.Debug(\"Helm Repository Register...\")\n\treturn m.portalProxy.RegisterEndpoint(echoContext, m.Info)\n}", "func Register(scheme string, b Broker) {\n\tbrokerRegistery[scheme] = b\n}", "func Register(g *echo.Group, apps *app.Container, m *middleware.Middleware) {\n\th := &handler{\n\t\tapps: apps,\n\t}\n\n\tg.GET(\"\", h.getAllAcompanhamento, m.Auth.Public)\n\tg.GET(\"/:acompanhamento_id\", h.getAcompanhamentoById, m.Auth.Public)\n\tg.GET(\"/byProcedimento/:procedimento_id\", h.getAcompanhamentoByIdProcedimento, m.Auth.Public)\n\tg.POST(\"/anything\", h.getAcompanhamentoByAnything, m.Auth.Public)\n\tg.POST(\"\", h.setAcompanhamento, m.Auth.Public)\n\tg.PUT(\"\", h.updateAcompanhamento, m.Auth.Public)\n\tg.DELETE(\"/:acompanhamento_id\", h.deleteAcompanhamento, m.Auth.Public)\n}", "func Register() map[string]string {\n\treturn map[string]string{\n\t\t\"name\": \"Beubo Example Plugin\",\n\t\t// identifier should be a unique identifier used to differentiate this plugin from other plugins\n\t\t\"identifier\": \"beubo_example_plugin\",\n\t}\n}", "func (w Ws) Register(r *gin.RouterGroup) {\n\tst := r.Group(\"\")\n\tst.GET(\"/ws/:id\", w.Server)\n\tst.DELETE(\"/ws/:id\", w.Offline)\n\tst.PUT(\"/ws/:id\", w.Dispatch)\n}", "func (m *Mgr) Register(ledgerid string, l ChaincodeLifecycleEventListener) {\n\t// write lock to synchronize concurrent 'chaincode install' operations with ledger creation/open\n\tm.rwlock.Lock()\n\tdefer m.rwlock.Unlock()\n\tm.ccLifecycleListeners[ledgerid] = append(m.ccLifecycleListeners[ledgerid], l)\n}", "func Register(p Protocol, n NewFunc) {\n\treglock.Lock()\n\tdefer reglock.Unlock()\n\tregistry[p] = 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}", "func (t *targetrunner) register() error {\n\tjsbytes, err := json.Marshal(t.si)\n\tif err != nil {\n\t\tglog.Errorf(\"Unexpected failure to json-marshal %+v, err: %v\", t.si, err)\n\t\treturn err\n\t}\n\turl := ctx.config.Proxy.URL + \"/\" + Rversion + \"/\" + Rcluster\n\t_, err = t.call(url, http.MethodPost, jsbytes)\n\treturn err\n}", "func Register(name string, h Holder) {\n\tmux.Lock()\n\tdefer mux.Unlock()\n\tif h == nil {\n\t\tpanic(\"Register Holder is nil\")\n\t}\n\tif _, dup := pool[name]; dup {\n\t\tpanic(\"Register called twice for Holder \" + name)\n\t}\n\tpool[name] = h\n}", "func register(stub shim.ChaincodeStubInterface) peer.Response {\n\t\tMSPid, _ := shim.GetMSPID()\n\t\t// Init datatypes\n\t\tvoter_list := []Operators{}\n\n\t\t// Get Operator list\n\t\tvalue, _ := stub.GetState(\"Operators\")\n\t\tjson.Unmarshal(value, &voter_list)\n\n\t\t// Get current Operator\n\t\tfor i := 0; i < len(voter_list); i++ {\n\t\t\tif(voter_list[i].OperatorID == MSPid) {\n\t\t\t\treturn shim.Success([]byte(\"User already registerd\"))\n\t\t\t}\n\t\t}\n\n\t\tOperator := Operators{OperatorID: MSPid, OclToken: 200}\n\t\turlsJson, _ := json.Marshal(append(voter_list, Operator))\n\n\t\tstub.PutState(\"Operators\", urlsJson)\n\n\t\treturn shim.Success(urlsJson)\n}", "func Register(m map[string]transformer.Transformer) {\n\tm[operationName] = &Add{}\n}", "func (router *Router) Register(modules ...IModule) {\n\tfor _, m := range modules {\n\t\trouter.modules[m.GetMID()] = m\n\t}\n}", "func Register(name string, obj interface{}) {\n\ti.Register(name, obj)\n}", "func cliRegister(name string, servport, myport int){\n\t//este serv va a enviarle un mensaje a un servidor\n\t//save a quien se va a conectar y le envia el nombre, su credencial\n\tresp := send(servport + 1, name, fmt.Sprintf(\"%d\", myport))\n\t//con la rspta necesitamos crear un mapa temporal de tipo entero\n\ttemp := make(map[int]string)\n\t_ = json.Unmarshal([]byte(resp),&temp)\n\tfor port, na := range temp {\n\t\tlib[port] = na\n\t}\n\tfmt.Println(lib)\n}", "func (a *PushKeyAPI) register(params interface{}) (resp *rpc.Response) {\n\treturn rpc.Success(a.mods.PushKey.Register(cast.ToStringMap(params)))\n}", "func Register(name string, f messageConstructorFunc) {\n\tregistry[name] = f\n}", "func (ctl *FoodmenuController) register() {\n\tfoodmenus := ctl.router.Group(\"/foodmenus\")\n\n\tfoodmenus.GET(\"\", ctl.ListFoodmenu)\n\n\t// CRUD\n\tfoodmenus.POST(\"\", ctl.CreateFoodmenu)\n\tfoodmenus.GET(\":id\", ctl.GetFoodmenu)\n\tfoodmenus.PUT(\":id\", ctl.UpdateFoodmenu)\n\tfoodmenus.DELETE(\":id\", ctl.DeleteFoodmenu)\n}", "func (asr *sessionRegistry) register(clt *Client) {\n\tasr.lock.Lock()\n\tasr.registry[clt.Session.Key] = clt\n\tasr.lock.Unlock()\n}", "func (m *RdmaDevPlugin) register() error {\n\tkubeletEndpoint := filepath.Join(deprecatedSockDir, kubeEndPoint)\n\tconn, err := dial(kubeletEndpoint, 5*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := &pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: m.socketName,\n\t\tResourceName: m.resourceName,\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func RegisterNamer(n Namer) {\n\tnamer = n\n}", "func (ctl *IllnessController) register() {\n\tillnesss := ctl.router.Group(\"/illnesss\")\n \n\tillnesss.GET(\"\", ctl.ListIllness)\n \n\t// CRUD\n\tillnesss.POST(\"\", ctl.CreateIllness)\n\tillnesss.GET(\":id\", ctl.GetIllness)\n\tillnesss.PUT(\":id\", ctl.UpdateIllness)\n\tillnesss.DELETE(\":id\", ctl.DeleteIllness)\n }", "func (reg *registrar) Register(example interface{}) error {\n\treg.lock.Lock()\n\tdefer reg.lock.Unlock()\n\treturn reg.Registry.Register(example)\n}", "func (ctl *ClubTypesController) register() {\r\n\tClubTypes := ctl.router.Group(\"/ClubTypess\")\r\n\r\n\tClubTypes.GET(\"\", ctl.ListClubTypes)\r\n\r\n\t// CRUD\r\n\tClubTypes.POST(\"\", ctl.CreateClubTypes)\r\n\tClubTypes.GET(\":id\", ctl.GetClubTypes)\r\n\tClubTypes.PUT(\":id\", ctl.UpdateClubTypes)\r\n\tClubTypes.DELETE(\":id\", ctl.DeleteClubTypes)\r\n}", "func Register(c Factory) {\n\tfactories[c.String()] = c\n}", "func (app *manager) Register(bridge Bridge) {\n\t// hydrated:\n\thydrated := bridge.Hydrated()\n\n\t// hydrated pointer:\n\thydratedPtrType := reflect.Indirect(reflect.ValueOf(hydrated.Pointer())).Type()\n\thydratedPtrName := fmt.Sprintf(doubleStringPattern, hydratedPtrType.PkgPath(), hydratedPtrType.Name())\n\tapp.mp[hydratedPtrName] = bridge\n\n\t// dehydrated:\n\tdehyrated := bridge.Dehydrated()\n\n\t// dehydrated interface:\n\tdehyratedInterfaceType := reflect.TypeOf(dehyrated.Interface())\n\tdehyratedInterfaceName := fmt.Sprintf(doubleStringPattern, dehyratedInterfaceType.PkgPath(), dehyratedInterfaceType.Name())\n\tapp.mp[dehyratedInterfaceName] = bridge\n\n\t// dehydrated pointer:\n\tdehydratedPtrType := reflect.Indirect(reflect.ValueOf(dehyrated.Pointer())).Type()\n\tdehydratedPtrName := fmt.Sprintf(doubleStringPattern, dehydratedPtrType.PkgPath(), dehydratedPtrType.Name())\n\tapp.mp[dehydratedPtrName] = bridge\n}", "func (c *SingletonRepository) Register(name string, f FactoryMethod) {\n\tc.beans[name] = &containerItem{sync.Once{}, f, nil}\n\treturn\n}", "func (handler commandHandler) register(name string, cmd func(context)) {\n\thandler.Cmds[name] = command{cmd}\n\tif len(name) > 2 {\n\t\thandler.Cmds[name[:2]] = command{cmd}\n\t}\n}", "func(peers *PeerList) Register(id int32) {\n\tpeers.mux.Lock()\n\tdefer peers.mux.Unlock()\n\tpeers.selfId = id\n\tfmt.Printf(\"SelfId=%v\\n\", id)\n}", "func (ctl *CounterStaffController) register() {\n\tcounterstaffs := ctl.router.Group(\"/CounterStaffs\")\n\n\tcounterstaffs.GET(\"\", ctl.ListCounterStaff)\n\n\t// CRUD\n\tcounterstaffs.POST(\"\", ctl.CreateCounterStaff)\n\tcounterstaffs.PUT(\":id\", ctl.UpdateCounterStaff)\n\tcounterstaffs.GET(\":id\", ctl.GetCounterStaff)\n\tcounterstaffs.DELETE(\":id\", ctl.DeleteCounterStaff)\n}", "func (mod *ModuleImpl) Register(method string, path string, handler gin.HandlerFunc, typeM string) {\n\tlog.Println(\"REGISTER - \", path)\n\tr := GetModManager().GetRouter()\n\tr.Handle(method, path, handler)\n\n\tif typeM == \"WEB\" {\n\t\tif len(path) > 1 {\n\t\t\tpath += \"/\"\n\t\t}\n\t\tr.HTMLRender = ginview.Default()\n\t\tr.Use(static.ServeRoot(path+mod.RessourcePath, \"./\"+mod.RessourcePath))\n\t}\n\tGetModManager().SetRouter(r)\n}", "func (my *MySQL) Register(sql string) {\n my.init_cmds = append(my.init_cmds, sql)\n}", "func (role *Role) Register(name string, fc func(req *http.Request, currentUser interface{}) bool) {\n\tif role.definitions == nil {\n\t\trole.definitions = map[string]func(req *http.Request, currentUser interface{}) bool{}\n\t}\n\n\tdefinition := role.definitions[name]\n\tif definition != nil {\n\t\tfmt.Printf(\"%v already defined, overwrited it!\\n\", name)\n\t}\n\trole.definitions[name] = fc\n}", "func (c *Conn) RegisterMachine(name string, id []byte, service string, class string, pid int, root_directory string) error {\n\treturn c.object.Call(dbusInterface+\".RegisterMachine\", 0, name, id, service, class, uint32(pid), root_directory).Err\n}", "func (command *Command) Register(shell sfinterfaces.IShell) {\n\n}", "func Register() {\n\tdefer trace()()\n\tif !conf.UCMConfig.ServiceDiscovery.Enabled {\n\t\treturn\n\t}\n\n\t//prepare for consul registration\n\treg := consul.CatalogRegistration{\n\t\tNode: hostname,\n\t\tAddress: hostip[0],\n\t\tDatacenter: conf.UCMConfig.ServiceDiscovery.Datacenter,\n\t\tService: &consul.AgentService{\n\t\t\tID: conf.UCMConfig.ServiceDiscovery.ServiceID,\n\t\t\tService: conf.UCMConfig.ServiceDiscovery.RegisterServiceName,\n\t\t\tTags: metadataToTags(),\n\t\t\tPort: conf.UCMConfig.Service.ListenPort,\n\t\t\tAddress: hostip[0],\n\t\t},\n\t\tCheck: &consul.AgentCheck{\n\t\t\tNode: hostname,\n\t\t\tCheckID: \"service:\" + conf.UCMConfig.ServiceDiscovery.ServiceID,\n\t\t\tName: conf.UCMConfig.ServiceDiscovery.ServiceID + \" health check\",\n\t\t\tStatus: consul.HealthPassing,\n\t\t\tServiceID: conf.UCMConfig.ServiceDiscovery.ServiceID,\n\t\t},\n\t}\n\n\t//Get the Consul client\n\tcconfig := consul.DefaultNonPooledConfig()\n\tcconfig.Address = conf.UCMConfig.ServiceDiscovery.GetAddress()\n\tclient, err := consul.NewClient(cconfig)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tcatalog := client.Catalog()\n\n\t//make the API call to register\n\tw, err := catalog.Register(&reg, &consul.WriteOptions{})\n\tif err != nil {\n\t\tlog.Error(err)\n\t} else {\n\t\tlog.Infof(\"OK: Consul registration succeeded after %d ns.\", w.RequestTime.Nanoseconds())\n\t}\n}", "func (w *Widget) Register(name string, action IAction) {\n\tw.actions[name] = action\n}", "func Register() {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tregister()\n}", "func (_m *IService) RegisterMix(info models.MixRegistrationInfo) {\n\t_m.Called(info)\n}", "func (ctl *LocationController) register() {\n\tlocations := ctl.router.Group(\"/locations\")\n \n\tlocations.GET(\"\", ctl.ListLocation)\n \n\t// CRUD\n\tlocations.POST(\"\", ctl.CreateLocation)\n\tlocations.GET(\":id\", ctl.GetLocation)\n\tlocations.PUT(\":id\", ctl.UpdateLocation)\n\tlocations.DELETE(\":id\", ctl.DeleteLocation)\n }", "func (s SwxProxy) Register(_ context.Context, _ *protos.RegistrationRequest) (*protos.RegistrationAnswer, error) {\n\treturn &protos.RegistrationAnswer{}, nil\n}", "func (client *Client) register() {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tprint(\"Register your name : \")\n\tfor {\n\t\ttext := getLine(scanner)\n\t\tif len(text) != 0 {\n\t\t\tclient.packet.Name = text\n\t\t\tclient.conn = client.connect(\"tcp\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func RegisterManager(name string, fn SecretManagerFunc) {\n\tmanagersLock.Lock()\n\tdefer managersLock.Unlock()\n\n\tif _, ok := managers[name]; ok {\n\t\tpanic(fmt.Sprintf(\"secret manager %q is already registered\", name))\n\t}\n\tmanagers[name] = fn\n}", "func (b *bot) Register(p Plugin, kind Kind, cb Callback) {\n\tr := regexp.MustCompile(`.*`)\n\tresp := func(r Request) bool {\n\t\treturn cb(r.Conn, r.Kind, r.Msg, r.Args...)\n\t}\n\tb.RegisterRegex(p, kind, r, resp)\n}", "func (a *Manager) Register(name string, fn interface{}, description ...string) error {\n\tif name == \"\" {\n\t\treturn errors.New(\"the helper name cannot be empty\")\n\t}\n\n\tif fn == nil {\n\t\treturn errors.New(\"the helper function cannot be nil\")\n\t}\n\n\tif kind := reflect.TypeOf(fn).Kind(); kind != reflect.Func {\n\t\treturn fmt.Errorf(\"wrong type for 'fn', %v , must be a function\", kind)\n\t}\n\n\ta.helpers[name] = &Helper{\n\t\tName: name,\n\t\tFunction: fn,\n\t\tDescription: stringx.GetOrDefault(\"\", description...),\n\t}\n\n\treturn nil\n}", "func (ctl *RoomTypeController) register() {\n\troomtype := ctl.router.Group(\"/roomtype\")\n\n\troomtype.GET(\"\", ctl.ListRoomType)\n\n\t// CRUD\n\troomtype.POST(\"\", ctl.CreateRoomType)\n\troomtype.GET(\":id\", ctl.GetRoomType)\n\troomtype.PUT(\":id\", ctl.UpdateRoomType)\n\troomtype.DELETE(\":id\", ctl.DeleteRoomType)\n}", "func Register() map[string]string {\n\treturn map[string]string{\n\t\t\"name\": \"Beubo gRPC\",\n\t\t// identifier should be a unique identifier used to differentiate this plugin from other plugins\n\t\t\"identifier\": \"beubo_grpc\",\n\t}\n}", "func Register(name string, c Creator) {\n\tcreatorMu.Lock()\n\tdefer creatorMu.Unlock()\n\n\tif c == nil {\n\t\tpanic(fmt.Sprintf(\"%s gatherer creator can't register as a nil\", name))\n\t}\n\n\tif _, dup := creators[name]; dup {\n\t\tpanic(fmt.Sprintf(\"%s gatherer creator already registered\", name))\n\t}\n\n\tlog.Logger.Infof(\"Gatherer creator registered: %s\", name)\n\tcreators[name] = c\n}", "func register(writer http.ResponseWriter, request *http.Request) {\n\terr := request.ParseForm()\n\tif err != nil {\n\t\tfmt.Fprintln(writer, \"Cannot parse form\")\n\t}\n\tprint(request.PostFormValue(\"title\"))\n\tprint(request.PostFormValue(\"body\"))\n\tregisterfile(request.PostFormValue(\"title\"), request.PostFormValue(\"body\"))\n\n\thttp.Redirect(writer, request, \"/viewlist\", 302)\n}", "func Register(name string, generator Generator) {\n\tGenerators[name] = generator\n}", "func Register(controller controller.Controller) {\n\tregistry.Register(controller)\n}", "func Register(name string, drv Driver) error {\n\tif _, f := drivers[name]; f {\n\t\treturn fmt.Errorf(\"morsel: driver '%s' already registered\", name)\n\t}\n\tdrivers[name] = drv\n\treturn nil\n}", "func Register(w http.ResponseWriter, r *http.Request) {\n\n\tdata := map[string]interface{}{\n\t\t\"Title\": \"REGISTER\",\n\t}\n\tif err := controller.ModelosRegister.ExecuteTemplate(w, \"register.html\", data); err != nil {\n\t\thttp.Error(w, \"[CONTENT ERRO] Erro in the execute template\", http.StatusInternalServerError)\n\t\tlog.Fatal(err.Error())\n\t}\n}", "func (sh *SimHandlerState) Register(r *mango.Router) {\n\tr.Get(\"/api/simulation/{sim_id}\", sh.Get)\n\tr.Put(\"/api/simulation/{sim_id}\", sh.Put)\n\tr.Get(\"/api/simulation/{sim_id}/{stepResultsRunGenerate}\", sh.GetStepsOrResults)\n\tr.Post(\"/api/simulation/{sim_id}/{stepResultsRunGenerate}\", sh.RunGenerateParseNetwork)\n\tr.Delete(\"/api/simulation/{sim_id}/step/{step_id}\", sh.DeleteStep)\n}", "func RegisterServer(name string, c ServerCreator) {\n\tserverMap[name] = c\n}", "func (zk *ZookeeperMaster) Register() error {\n\tif err := zk.createSelfNode(); err != nil {\n\t\treturn err\n\t}\n\t//create event loop for master flag\n\tgo zk.masterLoop()\n\tgo zk.healthLoop()\n\treturn nil\n\n}", "func (a *GaugeMetric) register() {\n\tmetrics := gauges[a.ServiceID]\n\tif metrics == nil {\n\t\tmetrics = make(map[MetricID]*GaugeMetric)\n\t\tgauges[a.ServiceID] = metrics\n\t}\n\tif _, exists := metrics[a.MetricID]; !exists {\n\t\tmetricsRegistry.MustRegister(a.Gauge)\n\t\tmetrics[a.MetricID] = a\n\t}\n}", "func (r *bitroute) register(method, path string, f func(router.Control)) {\n\tif r.handlers[method] == nil {\n\t\tr.handlers[method] = newParser()\n\t}\n\tr.handlers[method].register(path, f)\n}", "func (d *WindowsDataplane) RegisterManager(mgr Manager) {\n\td.allManagers = append(d.allManagers, mgr)\n}", "func Register(mut Mutation) {\n\tgob.Register(mut)\n\tt := reflect.TypeOf(mut)\n\tregistry[t.String()] = t\n}", "func (r *RepoStruct) Register() {\n\tif r == nil {\n\t\treturn\n\t}\n\tif r.forge == nil {\n\t\treturn\n\t}\n\tr.forge.ForjCore.Repos[r.name] = r\n}", "func Register(token string, userID uuid.UUID, lang int) {\n\tdefer mutex.Unlock()\n\tmutex.Lock()\n\n\ttokenAvailable[token] = session{\n\t\tuserID: userID,\n\t\tlang: lang,\n\t}\n\tlog.Printf(\"[Auth] -> Registering user ID: %s\", userID)\n}", "func Register(r shared.Responder) {\n\tserver.Register(r)\n}", "func (ctl *ResearchController) register() {\n\tresearches := ctl.router.Group(\"/researches\")\n\tresearches.GET(\"\", ctl.ListResearch)\n\n searchresearchs := ctl.router.Group(\"/searchresearchs\")\n\tsearchresearchs.GET(\"\",ctl.GetSearchResearch)\n\n\t// CRUD\n\tresearches.POST(\"\", ctl.CreateResearch)\n\tresearches.GET(\":id\", ctl.GetResearch)\n\tresearches.PUT(\":id\", ctl.UpdateResearch)\n\tresearches.DELETE(\":id\", ctl.DeleteResearch)\n}", "func (r *RegisterMonitor) register() {\n\tcatalog := r.Client.Catalog()\n\tserviceID := r.serviceID()\n\tserviceName := r.serviceName()\n\n\t// Determine the current state of this service in Consul\n\tvar currentService *api.CatalogService\n\tservices, _, err := catalog.Service(\n\t\tserviceName, \"\",\n\t\t&api.QueryOptions{AllowStale: true})\n\tif err == nil {\n\t\tfor _, service := range services {\n\t\t\tif serviceID == service.ServiceID {\n\t\t\t\tcurrentService = service\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we have a matching service, then we verify if we need to reregister\n\t// by comparing if it matches what we expect.\n\tif currentService != nil &&\n\t\tcurrentService.ServiceAddress == r.LocalAddress &&\n\t\tcurrentService.ServicePort == r.LocalPort {\n\t\tr.Logger.Printf(\"[DEBUG] proxy: service already registered, not re-registering\")\n\t\treturn\n\t}\n\n\t// If we're here, then we're registering the service.\n\terr = r.Client.Agent().ServiceRegister(&api.AgentServiceRegistration{\n\t\tKind: api.ServiceKindConnectProxy,\n\t\tID: serviceID,\n\t\tName: serviceName,\n\t\tAddress: r.LocalAddress,\n\t\tPort: r.LocalPort,\n\t\tProxy: &api.AgentServiceConnectProxyConfig{\n\t\t\tDestinationServiceName: r.Service,\n\t\t},\n\t\tCheck: &api.AgentServiceCheck{\n\t\t\tCheckID: r.checkID(),\n\t\t\tName: \"proxy heartbeat\",\n\t\t\tTTL: \"30s\",\n\t\t\tNotes: \"Built-in proxy will heartbeat this check.\",\n\t\t\tStatus: \"passing\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tr.Logger.Printf(\"[WARN] proxy: Failed to register Consul service: %s\", err)\n\t\treturn\n\t}\n\n\tr.Logger.Printf(\"[INFO] proxy: registered Consul service: %s\", serviceID)\n}" ]
[ "0.6469083", "0.6293646", "0.62846386", "0.62665445", "0.62664825", "0.6193526", "0.616421", "0.61630034", "0.6146137", "0.6117437", "0.6090346", "0.60891265", "0.6076839", "0.6058277", "0.60479873", "0.60440356", "0.60355157", "0.60273236", "0.60040057", "0.5985058", "0.59810734", "0.597027", "0.5935611", "0.59223837", "0.5916445", "0.5892845", "0.58927566", "0.58876884", "0.58814585", "0.58762443", "0.5865416", "0.5855146", "0.5850447", "0.58498514", "0.58483034", "0.584265", "0.5807833", "0.5806258", "0.5792917", "0.5790647", "0.5780655", "0.5753282", "0.5742951", "0.5740396", "0.57402605", "0.57337177", "0.5733255", "0.5728557", "0.57245886", "0.5716984", "0.57152414", "0.57148165", "0.5711977", "0.5710453", "0.5710253", "0.5705632", "0.5705051", "0.56993705", "0.5688951", "0.5685503", "0.5681743", "0.5678653", "0.56695807", "0.5665019", "0.565525", "0.56494033", "0.5645675", "0.5631672", "0.5631236", "0.5625139", "0.56244504", "0.5620838", "0.5618154", "0.5609797", "0.5608477", "0.56044245", "0.56022054", "0.55954117", "0.5578871", "0.55738837", "0.556522", "0.5562014", "0.55573833", "0.5551714", "0.5549713", "0.55489635", "0.5548872", "0.5548069", "0.5543301", "0.5539899", "0.55390984", "0.5536815", "0.553363", "0.5525132", "0.55236393", "0.5520112", "0.55192333", "0.55178374", "0.55170965", "0.55167717" ]
0.57465833
42
Module get module form registered modules with gvien name.
func (l *ModuleList) Module(cmd string) Module { for _, v := range *l { if v.Cmd() == cmd { return v } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (AppModuleBasic) Name() string { return types.ModuleName }", "func (*gaeModule) Name() module.Name {\n\treturn ModuleName\n}", "func (AppModule) Name() string { return types.ModuleName }", "func (r *Roster) Name() string { return ModuleName }", "func (g *Guessit) Name() string {\n\treturn moduleName\n}", "func getMain(c *gin.Context) {\n\n\tc.HTML(http.StatusOK, \"index.html\", gin.H{\n\t\t\"module\": biModule,\n\t})\n}", "func (AppModuleBasic) Name() string {\r\n\treturn ModuleName\r\n}", "func (AppModuleBasic) Name() string {\n\treturn commontypes.ModuleName\n}", "func (AppModuleBasic) Name() string {\n\treturn types.ModuleName\n}", "func (AppModuleBasic) Name() string {\n\treturn types.ModuleName\n}", "func (AppModuleBasic) Name() string {\n\treturn types.ModuleName\n}", "func (m *Module) FindByName(project *Project) (modules []Module, err error) {\n\tif err = database.BackendDB.DB.Model(project).Related(&modules).Where(\"name = ? \", m.Name).Error; err != nil {\n\t\tlog.Print(err)\n\t\treturn nil, err\n\t}\n\treturn modules, nil\n}", "func (_Votes *VotesCaller) ModuleName(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _Votes.contract.Call(opts, out, \"moduleName\")\n\treturn *ret0, err\n}", "func GenModuleIDFromName(name string) ModuleID {\n\treturn ModuleID{hash: xxhash.Sum64String(name)}\n}", "func (res moduleBase) Module() *types.Module {\n\treturn res.module\n}", "func (AppModuleBasic) Name() string {\n\treturn ModuleName\n}", "func (AppModuleBasic) Name() string {\n\treturn ModuleName\n}", "func (AppModuleBasic) Name() string {\n\treturn ModuleName\n}", "func (AppModuleBasic) Name() string {\n\treturn ModuleName\n}", "func (AppModuleBasic) Name() string {\n\treturn ModuleName\n}", "func (v version) Modules() []string {\n\treturn []string{}\n}", "func (config *Config) OnModule(name string) *Module {\n\tfor _, moduleConfig := range config.Modules {\n\t\tif moduleConfig.Name == name {\n\t\t\treturn moduleConfig\n\t\t}\n\t}\n\treturn config.CreateModule(name)\n}", "func newModule(moduleName, name string, vrf *VrfInfo) Module {\n\tfactory, found := moduleFactories[moduleName]\n\tif !found {\n\t\tLogger.Printf(\"Module '%s' doesn't exist.\\n\", moduleName)\n\t\treturn nil\n\t}\n\n\trp, ok := ringParams[name]\n\tif !ok {\n\t\trp = defaultRingParam\n\t}\n\trp.Flags = dpdk.RING_F_SC_DEQ\n\n\t// Create a parameter for the module\n\tmodType := moduleTypes[moduleName]\n\tparam := &ModuleParam{\n\t\tt: modType,\n\t\tname: name,\n\t\tvrf: vrf,\n\t\trp: rp,\n\t\tvrp: rp,\n\t\trules: newRules(),\n\t}\n\n\tswitch modType {\n\tcase TypeVif:\n\t\tparam.vif = newVif()\n\tcase TypeBridge:\n\t\tparam.bridge = newBridge()\n\tdefault:\n\t\t// nop\n\t}\n\n\tmodule, err := factory(param)\n\tif err != nil {\n\t\tLogger.Printf(\"Creating module '%s' with name '%s' failed.\\n\", moduleName, name)\n\t\treturn nil\n\t}\n\n\tswitch modType {\n\tcase TypeVif:\n\t\top, ok := module.(VifOp)\n\t\tif !ok {\n\t\t\tLogger.Fatalf(\"'%s' doesn't conform to VifModule interface!\\n\", moduleName)\n\t\t\tbreak\n\t\t}\n\t\tms, _ := module.(ModuleService)\n\t\tparam.vif.config(op, ms)\n\n\tdefault:\n\t\t// nop\n\t}\n\n\tmodules = append(modules, module)\n\n\treturn module\n}", "func (AppModule) Name() string {\n\treturn types.ModuleName\n}", "func (AppModule) Name() string {\n\treturn types.ModuleName\n}", "func Name() string {\n\treturn types.SubModuleName\n}", "func Name() string {\n\treturn types.SubModuleName\n}", "func Name() string {\n\treturn types.SubModuleName\n}", "func Name() string {\n\treturn types.SubModuleName\n}", "func (c commandRegistry) Get(moduleName string) moduleCommands {\n\tif mcs, ok := c[moduleName]; ok {\n\t\treturn mcs\n\t}\n\tres := make(moduleCommands)\n\tc[moduleName] = res\n\treturn res\n}", "func (p Plugin) GoMod(ctx context.Context, module string, vsn string) ([]byte, error) {\n\tresp, err := p.c.GetMod(ctx, &stpb.GetModuleRequest{Module: module, Version: vsn})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.GetData(), nil\n}", "func (*serverModule) Name() module.Name {\n\treturn ModuleName\n}", "func getBuildModule() *debug.Module {\n\tbi, ok := debug.ReadBuildInfo()\n\tif ok {\n\t\t// The recommended way to build Caddy involves\n\t\t// creating a separate main module, which\n\t\t// preserves caddy a read-only dependency\n\t\t// TODO: track related Go issue: https://github.com/golang/go/issues/29228\n\t\tfor _, mod := range bi.Deps {\n\t\t\tif mod.Path == \"github.com/caddyserver/caddy\" {\n\t\t\t\treturn mod\n\t\t\t}\n\t\t}\n\t}\n\treturn &debug.Module{Version: \"unknown\"}\n}", "func getLegacyModules(ctx context.Context, root span.URI, fs source.FileSource) (map[span.URI]struct{}, error) {\n\turi := span.URIFromPath(filepath.Join(root.Filename(), \"go.mod\"))\n\tmodules := make(map[span.URI]struct{})\n\texists, err := fileExists(ctx, uri, fs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif exists {\n\t\tmodules[uri] = struct{}{}\n\t}\n\treturn modules, nil\n}", "func (n *Node) GetModule(module interface{}) interface{} {\n\treturn nil\n}", "func getModuleData(sacJSON *sac.Sac) (Module, error) {\n\tvar mod Module\n\n\tmod.name = sacJSON.GetString(JSONNameKey)\n\tmod.description = sacJSON.GetString(JSONDescriptionKey)\n\tmod.is_core = sacJSON.GetBool(\"dessert.is_core\")\n\tmod.replaces = sacJSON.GetStringSlice(\"dessert.replaces\")\n\n\tpropArr := []string{JSONNameKey, JSONDescriptionKey, JSONIsCoreKey}\n\n\tfor _, elem := range propArr {\n\t\tif b := checkPropertyString(&mod, elem); !b {\n\t\t\treturn mod, fmt.Errorf(\"missing %s property in package.json\", elem)\n\t\t}\n\t}\n\n\treturn mod, nil\n}", "func readModuleName() (string, error) {\n\tmodFile, err := os.Open(\"./go.mod\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer modFile.Close()\n\tscanner := bufio.NewScanner(modFile)\n\tfor scanner.Scan() {\n\t\tpieces := strings.Split(scanner.Text(), \" \")\n\t\tfmt.Printf(\"FOund pieces as %+v\\n\", pieces)\n\t\tif len(pieces) >= 2 && pieces[0] == \"module\" {\n\t\t\treturn pieces[1], nil\n\t\t}\n\t}\n\treturn \"\", nil\n}", "func (r *Resolver) Name() string {\n\treturn r.ModuleName\n}", "func (m *moduleService) Name() string {\n\treturn m.name\n}", "func (Flagr) CaddyModule() caddy.ModuleInfo {\n\treturn caddy.ModuleInfo{\n\t\tID: \"http.handlers.flagr\",\n\t\tNew: func() caddy.Module { return new(Flagr) }, // return a singleton.\n\t}\n}", "func getModules(client k8sclient.Interface) (map[string]protos.Module, error) {\n\tfoundModules := make(map[string]protos.Module)\n\tdsList, err := client.ExtensionsV1beta1().DaemonSets(defaultNS).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor ii := range dsList.Items {\n\t\tfoundModules[dsList.Items[ii].Name] = protos.Module{\n\t\t\tTypeMeta: api.TypeMeta{\n\t\t\t\tKind: \"Module\",\n\t\t\t},\n\t\t\tSpec: protos.ModuleSpec{\n\t\t\t\tType: protos.ModuleSpec_DaemonSet,\n\t\t\t},\n\t\t}\n\t}\n\tdList, err := client.ExtensionsV1beta1().Deployments(defaultNS).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor ii := range dList.Items {\n\t\tfoundModules[dList.Items[ii].Name] = protos.Module{\n\t\t\tTypeMeta: api.TypeMeta{\n\t\t\t\tKind: \"Module\",\n\t\t\t},\n\t\t\tSpec: protos.ModuleSpec{\n\t\t\t\tType: protos.ModuleSpec_Deployment,\n\t\t\t},\n\t\t}\n\t}\n\tcjList, err := client.BatchV1beta1().CronJobs(defaultNS).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor ii := range cjList.Items {\n\t\tfoundModules[cjList.Items[ii].Name] = protos.Module{\n\t\t\tTypeMeta: api.TypeMeta{\n\t\t\t\tKind: \"Module\",\n\t\t\t},\n\t\t\tSpec: protos.ModuleSpec{\n\t\t\t\tType: protos.ModuleSpec_Job,\n\t\t\t},\n\t\t}\n\t}\n\treturn foundModules, nil\n}", "func (this *Motto) AddModule(id string, loader ModuleLoader) {\n this.modules[id] = loader\n}", "func (mc ModuleController) GetModule(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\t// Grab id\n\tid := p.ByName(\"id\")\n\n\t// Verify id is ObjectId, otherwise bail\n\tif !bson.IsObjectIdHex(id) {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\t// Grab id\n\toid := bson.ObjectIdHex(id)\n\n\t// Stub user\n\tu := models.Module{}\n\n\t// Fetch user\n\tif err := mc.session.DB(\"go_rest_tutorial\").C(\"users\").FindId(oid).One(&u); err != nil {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\t// Marshal provided interface into JSON structure\n\tuj, _ := json.Marshal(u)\n\n\t// Write content-type, statuscode, payload\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"%s\", uj)\n}", "func (_Votes *VotesSession) ModuleName() (string, error) {\n\treturn _Votes.Contract.ModuleName(&_Votes.CallOpts)\n}", "func (i *Instance) GetModuleName() string {\n\treturn i.Module\n}", "func ModuleName() string {\n\treturn \"http\"\n}", "func (uri *Pkcs11URI) GetModule() (string, error) {\n\tvar searchdirs []string\n\tv, ok := uri.queryAttributes[\"module-path\"]\n\n\tif ok {\n\t\tinfo, err := os.Stat(v)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"module-path '%s' is not accessible\", v)\n\t\t}\n\t\tif err == nil && info.Mode().IsRegular() {\n\t\t\t// it's a file\n\t\t\tif uri.isAllowedPath(v, uri.allowedModulePaths) {\n\t\t\t\treturn v, nil\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\"module-path '%s' is not allowed by policy\", v)\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\treturn \"\", fmt.Errorf(\"module-path '%s' points to an invalid file type\", v)\n\t\t}\n\t\t// v is a directory\n\t\tsearchdirs = []string{v}\n\t} else {\n\t\tsearchdirs = uri.GetModuleDirectories()\n\t}\n\n\tmoduleName, ok := uri.queryAttributes[\"module-name\"]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"module-name attribute is not set\")\n\t}\n\tmoduleName = strings.ToLower(moduleName)\n\n\tfor _, dir := range searchdirs {\n\t\tfiles, err := ioutil.ReadDir(dir)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, file := range files {\n\t\t\tfileLower := strings.ToLower(file.Name())\n\n\t\t\ti := strings.Index(fileLower, moduleName)\n\t\t\tif i < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// we require that the fileLower ends with moduleName or that\n\t\t\t// a suffix follows so that softhsm will not match libsofthsm2.so but only\n\t\t\t// libsofthsm.so\n\t\t\tif len(fileLower) == i+len(moduleName) || fileLower[i+len(moduleName)] == '.' {\n\t\t\t\tf := filepath.Join(dir, file.Name())\n\t\t\t\tif uri.isAllowedPath(f, uri.allowedModulePaths) {\n\t\t\t\t\treturn f, nil\n\t\t\t\t}\n\t\t\t\treturn \"\", fmt.Errorf(\"module '%s' is not allowed by policy\", f)\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"No module could be found\")\n}", "func (AppModule) Name() string {\n\treturn ModuleName\n}", "func (AppModule) Name() string {\n\treturn ModuleName\n}", "func (AppModule) Name() string {\n\treturn ModuleName\n}", "func (app AppModule) Name() string {\n\treturn ModuleName\n}", "func (am AppModule) Name() string {\n\treturn am.AppModuleBasic.Name()\n}", "func (_Votes *VotesCallerSession) ModuleName() (string, error) {\n\treturn _Votes.Contract.ModuleName(&_Votes.CallOpts)\n}", "func Module(filename, input string) func(r *Zego) {\n\treturn func(r *Zego) {\n\t\tr.modules = append(r.modules, rawModule{\n\t\t\tfilename: filename,\n\t\t\tmodule: input,\n\t\t})\n\t}\n}", "func (m Module) Name() ast.ModuleName {\n\treturn m.name\n}", "func (c BitfinexCrawler) GetName() string {\r\n\treturn BITFINEX_MODULE_NAME\r\n}", "func (am AppModule) Name() string {\n\treturn am.cosmosAppModule.Name()\n}", "func AddModule(id string, m ModuleLoader) {\n globalModules[id] = m\n}", "func moduleName() string {\n\td, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tf, err := os.Open(filepath.Join(d, \"go.mod\"))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tdefer f.Close()\n\ts := bufio.NewScanner(f)\n\tvar m string\n\tfor s.Scan() {\n\t\tm = s.Text()\n\t\tp := strings.SplitN(m, \" \", 2)\n\t\tif len(p) == 2 && p[0] == \"module\" {\n\t\t\treturn p[1]\n\t\t}\n\t}\n\treturn \"\"\n}", "func main() {\n\tpgs.Init().RegisterModule(&cMod{&pgs.ModuleBase{}}).Render()\n}", "func registerModules(appState *state.State) error {\n\tappState.Logger.\n\t\tWithField(\"action\", \"startup\").\n\t\tDebug(\"start registering modules\")\n\n\tappState.Modules = modules.NewProvider()\n\n\tenabledModules := map[string]bool{}\n\tif len(appState.ServerConfig.Config.EnableModules) > 0 {\n\t\tmodules := strings.Split(appState.ServerConfig.Config.EnableModules, \",\")\n\t\tfor _, module := range modules {\n\t\t\tenabledModules[strings.TrimSpace(module)] = true\n\t\t}\n\t}\n\n\tif _, ok := enabledModules[\"text2vec-contextionary\"]; ok {\n\t\tappState.Modules.Register(modcontextionary.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", \"text2vec-contextionary\").\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[\"text2vec-transformers\"]; ok {\n\t\tappState.Modules.Register(modtransformers.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", \"text2vec-transformers\").\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modgpt4all.Name]; ok {\n\t\tappState.Modules.Register(modgpt4all.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modgpt4all.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modrerankertransformers.Name]; ok {\n\t\tappState.Modules.Register(modrerankertransformers.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modrerankertransformers.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modrerankercohere.Name]; ok {\n\t\tappState.Modules.Register(modrerankercohere.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modrerankercohere.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[\"qna-transformers\"]; ok {\n\t\tappState.Modules.Register(modqna.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", \"qna-transformers\").\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[\"sum-transformers\"]; ok {\n\t\tappState.Modules.Register(modsum.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", \"sum-transformers\").\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[\"img2vec-neural\"]; ok {\n\t\tappState.Modules.Register(modimage.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", \"img2vec-neural\").\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[\"ner-transformers\"]; ok {\n\t\tappState.Modules.Register(modner.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", \"ner-transformers\").\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[\"text-spellcheck\"]; ok {\n\t\tappState.Modules.Register(modspellcheck.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", \"text-spellcheck\").\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[\"multi2vec-clip\"]; ok {\n\t\tappState.Modules.Register(modclip.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", \"multi2vec-clip\").\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[\"text2vec-openai\"]; ok {\n\t\tappState.Modules.Register(modopenai.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", \"text2vec-openai\").\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[\"qna-openai\"]; ok {\n\t\tappState.Modules.Register(modqnaopenai.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", \"qna-openai\").\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modgenerativecohere.Name]; ok {\n\t\tappState.Modules.Register(modgenerativecohere.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modgenerativecohere.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modgenerativeopenai.Name]; ok {\n\t\tappState.Modules.Register(modgenerativeopenai.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modgenerativeopenai.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modhuggingface.Name]; ok {\n\t\tappState.Modules.Register(modhuggingface.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modhuggingface.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modgenerativepalm.Name]; ok {\n\t\tappState.Modules.Register(modgenerativepalm.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modgenerativepalm.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modtext2vecpalm.Name]; ok {\n\t\tappState.Modules.Register(modtext2vecpalm.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modtext2vecpalm.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modstgfs.Name]; ok {\n\t\tappState.Modules.Register(modstgfs.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modstgfs.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modstgs3.Name]; ok {\n\t\tappState.Modules.Register(modstgs3.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modstgs3.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modstggcs.Name]; ok {\n\t\tappState.Modules.Register(modstggcs.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modstggcs.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modstgazure.Name]; ok {\n\t\tappState.Modules.Register(modstgazure.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modstgazure.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modcentroid.Name]; ok {\n\t\tappState.Modules.Register(modcentroid.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modcentroid.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modcohere.Name]; ok {\n\t\tappState.Modules.Register(modcohere.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modcohere.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tif _, ok := enabledModules[modbind.Name]; ok {\n\t\tappState.Modules.Register(modbind.New())\n\t\tappState.Logger.\n\t\t\tWithField(\"action\", \"startup\").\n\t\t\tWithField(\"module\", modbind.Name).\n\t\t\tDebug(\"enabled module\")\n\t}\n\n\tappState.Logger.\n\t\tWithField(\"action\", \"startup\").\n\t\tDebug(\"completed registering modules\")\n\n\treturn nil\n}", "func registerModules(){\n\tweb.Register()\t\t//http server.\n\tdevicetwin.Register()\t\n\teventhub.Register()\t\n}", "func (JWTAuth) CaddyModule() caddy.ModuleInfo {\n\treturn caddy.ModuleInfo{\n\t\tID: \"http.authentication.providers.jwt\",\n\t\tNew: func() caddy.Module { return new(JWTAuth) },\n\t}\n}", "func (m *Module) String() string {\n\treturn m.name\n}", "func ModuleName() string {\n\treturn \"runtime\"\n}", "func translateModuleName(old string, sensors []*data.ModuleSensor) string {\n\tif newName, ok := NameMap[old]; ok {\n\t\treturn newName\n\t}\n\n\tif old == \"water\" {\n\t\tif len(sensors) == 1 {\n\t\t\treturn \"modules.water.\" + sensors[0].Name\n\t\t} else {\n\t\t\treturn \"modules.water.ec\"\n\t\t}\n\t}\n\n\treturn old\n}", "func (p *GitProvider) GetName() string { return \"git\" }", "func (state *State) FetchModule(name string) *Module {\n\treturn state.global.FetchModule(name)\n}", "func (GenesisUpdater) Name() string {\n\treturn ModuleName\n}", "func (Plugin) Name() string { return pluginName }", "func init() {\n\tmodules.Register(\"k6/x/mllp\", new(MLLP))\n}", "func (mm *ModuleManager) GetModule(id string) *shared.Module {\n\tval, ok := mm.modules[id]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tcpy := *val\n\n\tfor i, setting := range cpy.Settings {\n\t\tkey := path.Join(\"module\", id, setting.Name)\n\t\terr := mm.storage.Get(key, &setting.Value)\n\n\t\tif err != nil {\n\t\t\tif _, ok := err.(storage.KeyNotFound); !ok {\n\t\t\t\tlog.Printf(\"Error getting data from storage: %v\", err)\n\t\t\t}\n\t\t\tsetting.Value = setting.Default\n\t\t}\n\t\tcpy.Settings[i] = setting\n\t}\n\n\treturn &cpy\n}", "func init() {\n\tpolochon.RegisterModule(&Guessit{})\n}", "func (p *JSONifyModule) Name() string { return \"jsonify\" }", "func (m *Module) Inspect() string { return m.name }", "func (r *Registry) Modules() []bar.Module {\n\treturn r.modules\n}", "func (c *ModuleClient) Get(ctx context.Context, id int) (*Module, error) {\n\treturn c.Query().Where(module.ID(id)).Only(ctx)\n}", "func (mi TestModuleInfo) Name() string {\n\treturn mi.ModuleName\n}", "func (m *Module) Name() string {\n\treturn C.GoString(m.ptr.name)\n}", "func RegisterModule() {\n\tvar module Module\n\t_, err := zgrab2.AddCommand(\"fox\", \"fox\", module.Description(), 1911, &module)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (omc *OtherModuleTestContext) ModuleFromName(name string) (blueprint.Module, bool) {\n\tfor _, m := range omc.Modules {\n\t\tif m.ModuleName == name {\n\t\t\treturn m, true\n\t\t}\n\t}\n\treturn TestModuleInfo{}, false\n}", "func (c *Module) GetBySearch(params cmap.CMap) interface{} {\n\n\tvar wx applet.Applet\n\twx.Appid = params.Get(\"appid\")\n\tif wx.Appid != \"\" {\n\t\tparams.Del(\"appid\")\n\t\tif err := wx.GetByAppid(wx.Appid); err != nil {\n\t\t\treturn result.CError(err)\n\t\t}\n\t\tparams.Add(\"admin_id\", strconv.FormatUint(wx.AdminID, 10))\n\t}\n\n\tvar datas []*Module\n\tcrud.Params(gt.Data(&datas))\n\tcd := crud.GetBySearch(params)\n\tif cd.Error() != nil {\n\t\t//log.Log.Error(err.Error())\n\t\treturn result.CError(cd.Error())\n\t}\n\treturn result.GetSuccessPager(datas, cd.Pager()).Add(\"admin_id\", wx.AdminID).Add(\"logo\", wx.Logo)\n}", "func (h *HTTP) Name() string {\n\treturn ModuleName()\n}", "func (f *Function) GetModule() *Module {\n\treturn NewModule(f.ptr.module)\n}", "func register(name string, p Plugin) {\n\tdirectory[name] = p\n}", "func (pm *pluginManager) getPlugin(name string) (NodePlugin, error) {\n\tif p, ok := pm.plugins[name]; ok {\n\t\treturn p, nil\n\t}\n\n\tpc, err := pm.pg.Get(name, DockerCSIPluginCap, plugingetter.Lookup)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpa, ok := pc.(plugingetter.PluginAddr)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"plugin does not implement PluginAddr interface\")\n\t}\n\n\tp := pm.newNodePluginFunc(name, pc, pa, pm.secrets)\n\tpm.plugins[name] = p\n\treturn p, nil\n}", "func (module *Crawler) Name() string {\n\treturn Name\n}", "func (cr *cmdRunner) getModules() (storage.ScmModules, error) {\n\tdiscovery, err := cr.binding.GetModules(cr.log)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to discover pmem modules\")\n\t}\n\tcr.log.Debugf(\"discovered %d pmem modules\", len(discovery))\n\n\tmodules := make(storage.ScmModules, 0, len(discovery))\n\tfor _, d := range discovery {\n\t\tmodules = append(modules, &storage.ScmModule{\n\t\t\tChannelID: uint32(d.Channel_id),\n\t\t\tChannelPosition: uint32(d.Channel_pos),\n\t\t\tControllerID: uint32(d.Memory_controller_id),\n\t\t\tSocketID: uint32(d.Socket_id),\n\t\t\tPhysicalID: uint32(d.Physical_id),\n\t\t\tCapacity: d.Capacity,\n\t\t\tUID: d.Uid.String(),\n\t\t\tPartNumber: d.Part_number.String(),\n\t\t\tFirmwareRevision: d.Fw_revision.String(),\n\t\t})\n\t}\n\n\treturn modules, nil\n}", "func GenModuleID(p *policyv1.Policy) ModuleID {\n\treturn GenModuleIDFromName(ModuleName(p))\n}", "func (_Votes *VotesCaller) ModuleImplName(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _Votes.contract.Call(opts, out, \"moduleImplName\")\n\treturn *ret0, err\n}", "func (o ModuleDefaultVersionOutput) ModuleName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ModuleDefaultVersion) pulumi.StringPtrOutput { return v.ModuleName }).(pulumi.StringPtrOutput)\n}", "func (p Plugin) Info(ctx context.Context, module string, vsn string) ([]byte, error) {\n\tresp, err := p.c.GetInfo(ctx, &stpb.GetModuleRequest{Module: module, Version: vsn})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.GetData(), nil\n}", "func GetModules(rw http.ResponseWriter) error {\n\tlines, err := share.ReadFullFile(procModulesPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to read: %s\", procModulesPath)\n\t\treturn errors.New(\"Failed to read /proc/modules\")\n\t}\n\n\tmodules := make([]Modules, len(lines))\n\tfor i, line := range lines {\n\t\tfields := strings.Fields(line)\n\n\t\tmodule := Modules{}\n\n\t\tfor j, field := range fields {\n\t\t\tswitch j {\n\t\t\tcase 0:\n\t\t\t\tmodule.Module = field\n\t\t\t\tbreak\n\t\t\tcase 1:\n\t\t\t\tmodule.MemorySize = field\n\t\t\t\tbreak\n\t\t\tcase 2:\n\t\t\t\tmodule.Instances = field\n\t\t\t\tbreak\n\t\t\tcase 3:\n\t\t\t\tmodule.Dependent = field\n\t\t\t\tbreak\n\t\t\tcase 4:\n\t\t\t\tmodule.State = field\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tmodules[i] = module\n\t}\n\n\treturn share.JSONResponse(modules, rw)\n}", "func init() {\n\tmodules.Register(\"k6/x/faker\", New())\n}", "func (c *Context) Module() *module.Tree {\n\treturn c.module\n}", "func ModulesRequest(id_module string) Module{\n var ob []Module\n \n ses, c := accessDB(modules_collection)\n defer ses.Close()\n \n err := c.Find(bson.M{\"id_moduleiot\":id_module,\"sensors.state\": \"free\"}).All(&ob)\n VerifyErr(err)\n js, __ := json.Marshal(ob)\n if __ != nil || js == nil{\n panic(__)\n }\n return ob[0]\n}", "func (reg DefaultComponentRegistry) Get(name string) (component.Registration, bool) {\n\treturn component.Get(name)\n}", "func (p *Plugin) Name() string {\n\treturn \"gump\"\n}", "func GetModuleById(genericModuleId, specificModuleId string) Module {\n\treturn registeredModulesById[genericModuleId][specificModuleId]\n}", "func (Config) ModuleInfo() (m debug.Module) {\n\tconst pkg = \"entgo.io/ent\"\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\treturn\n\t}\n\t// Was running as a CLI (ent/cmd/ent).\n\tif info.Main.Path == pkg {\n\t\treturn info.Main\n\t}\n\t// Or, as a main package (ent/entc).\n\tfor _, dep := range info.Deps {\n\t\tif dep.Path == pkg {\n\t\t\treturn *dep\n\t\t}\n\t}\n\treturn\n}" ]
[ "0.60053366", "0.59756225", "0.5796", "0.5633089", "0.5611626", "0.5451433", "0.5424479", "0.5417639", "0.5297246", "0.5297246", "0.5297246", "0.52445704", "0.5234721", "0.522639", "0.52197266", "0.5181634", "0.5181634", "0.5181634", "0.5181634", "0.5181634", "0.5161481", "0.5161371", "0.5150542", "0.5145972", "0.5145972", "0.51425594", "0.51425594", "0.51425594", "0.51425594", "0.5133739", "0.51201457", "0.5105922", "0.51026225", "0.5083869", "0.50831366", "0.50830746", "0.5082955", "0.5047117", "0.5046695", "0.50221527", "0.5005766", "0.49871868", "0.49821484", "0.49813905", "0.49770054", "0.49644202", "0.49577683", "0.49533013", "0.49533013", "0.49533013", "0.4950897", "0.49507996", "0.4938629", "0.49367508", "0.4921277", "0.4911854", "0.49017182", "0.4893582", "0.48882765", "0.48773524", "0.48622724", "0.48614895", "0.48576066", "0.48552155", "0.48416516", "0.4832725", "0.48311287", "0.48269993", "0.48267362", "0.4813134", "0.48119634", "0.4781959", "0.47745222", "0.47663146", "0.4765466", "0.47626606", "0.47605845", "0.47543314", "0.47489208", "0.4748534", "0.47472358", "0.47465926", "0.47316572", "0.47313088", "0.47067288", "0.46880937", "0.4676237", "0.46754166", "0.46690446", "0.46674627", "0.46649945", "0.4662568", "0.46595195", "0.4647537", "0.46381027", "0.46366674", "0.46332383", "0.463225", "0.46115443", "0.46047956" ]
0.49537915
47
NewChatrooms returns a new Chatrooms handler with the given logger
func NewChatrooms(l hclog.Logger, pdb *data.ChatroomsDB) *Chatrooms { return &Chatrooms{l, pdb} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newLogger(buffer int64) *Logger {\n\tl := &Logger{\n\t\tmsg: make(chan *logMsg, buffer),\n\t\toutputs: make(map[string]LoggerInterface),\n\t\tquit: make(chan bool),\n\t}\n\tgo l.StartLogger()\n\treturn l\n}", "func New(topics []Topic) Chatroom {\n\troom := Room{\n\t\tIn: make(chan interface{}),\n\t\tOut: make(chan interface{}),\n\t}\n\tchatroom := Chatroom{\n\t\ttopics: topics,\n\t\tRoom: room,\n\t}\n\tgo chatroom.talk(room)\n\treturn chatroom\n}", "func NewLogger() Logger {\n\tdepth := 6\n\treturn new(&depth)\n}", "func newLogger(lineCap int) *logger {\n\treturn &logger{\n\t\tlogs: make(chan *LogLine, lineCap),\n\t}\n}", "func newLoggerHandler(level Level, extraStackDepth int, handlers []Handler) log.Handler {\n\tvar logHandler log.Handler\n\n\tif len(handlers) == 0 {\n\t\tlogHandler = log.StderrHandler\n\t} else {\n\t\thandlerArr := []log.Handler{}\n\t\tfor _, handler := range handlers {\n\t\t\tvar lh log.Handler\n\t\t\tif l, ok := handler.(*fromLog15Handler); ok {\n\t\t\t\tlh = l.internal\n\t\t\t} else {\n\t\t\t\tlh = &toLog15Handler{handler}\n\t\t\t}\n\t\t\thandlerArr = append(handlerArr, lh)\n\t\t}\n\n\t\tif len(handlerArr) == 1 {\n\t\t\tlogHandler = handlerArr[0]\n\t\t} else {\n\t\t\tlogHandler = log.MultiHandler(handlerArr...)\n\t\t}\n\t}\n\n\treturn log.LvlFilterHandler(log.Lvl(level),\n\t\tcallerFileLog15Handler(8+extraStackDepth, logHandler))\n}", "func NewLogger(client *Client, mode int, ttl time.Duration) *Logger {\n\tl := &Logger{\n\t\tclient: client,\n\t\tqueue: make(chan LogEntry, 1024),\n\t\tnow: time.Now,\n\t\tmode: mode,\n\t}\n\tif mode != LogDiscard {\n\t\tgo l.readQueue(ttl)\n\t}\n\treturn l\n}", "func newChat(l int64) *chat {\n\treturn &chat{latency: l}\n}", "func newRoom(id int) *room {\n\treturn &room{\n\t\tID: id,\n\t\tclients: make(map[*client]bool),\n\t\tmessages: make(chan string), //initialize channel, or...deadlock\n\t\tjoining: make(chan *client), //initialize channel, or...deadlock\n\t\tleaving: make(chan *client), //initialize channel, or...deadlock\n\t}\n}", "func NewLogger(ctx echo.Context) *Logger {\n\t// id := getID(ctx)\n\tl := &Logger{\n\t\tLogger: ctx.Logger(),\n\t\tDurations: durations{},\n\t\tExtras: extras{},\n\t}\n\treturn l\n}", "func NewLogger(lv Level) *Logger {\n\treturn &Logger{level: lv, minLevel: disabledLevel} // disable all levels for empty logger\n}", "func New(l logrus.FieldLogger) ctxlog.Logger {\n\tif l == nil {\n\t\tl = logrus.New()\n\t}\n\n\treturn logrusAdapter{l}\n}", "func New(ctx ...interface{}) MultiLogger {\n\tr := &RevelLogger{Logger: log15.New(ctx...)}\n\tr.SetStackDepth(0)\n\treturn r\n}", "func NewTwitchChat(j TwitchJoinHandler) *TwitchChat {\n\tc := &TwitchChat{\n\t\tdialer: websocket.Dialer{HandshakeTimeout: SocketHandshakeTimeout},\n\t\theaders: http.Header{\"Origin\": []string{GetConfig().Twitch.OriginURL}},\n\t\tmessages: make(map[string]chan *Message, 0),\n\t\tchannels: make([]string, 0),\n\t\tjoinHandler: j,\n\t\tadmins: make(map[string]bool, len(GetConfig().Twitch.Admins)),\n\t\tevicted: make(chan string, 0),\n\t}\n\n\tfor _, u := range GetConfig().Twitch.Admins {\n\t\tc.admins[u] = true\n\t}\n\n\td, err := ioutil.ReadFile(GetConfig().Twitch.ChannelListPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to read channels %s\", err)\n\t}\n\tif err := json.Unmarshal(d, &c.channels); err != nil {\n\t\tlog.Fatalf(\"unable to read channels %s\", err)\n\t}\n\tsort.Strings(c.channels)\n\tgo c.runEvictHandler()\n\treturn c\n}", "func New(ctx ...interface{}) MultiLogger {\n\tr := &RevelLogger{Logger: log15.New(ctx...)}\n\tr.SetStackDepth(1)\n\treturn r\n}", "func newLogger() logger {\n\tleKey := os.Getenv(\"LOG_ENTRIES_KEY\")\n\tfmtFallback := &fmtLogger{}\n\n\tif leKey == \"\" {\n\t\treturn fmtFallback\n\t}\n\n\tle, err := le_go.Connect(leKey)\n\n\tif err != nil {\n\t\treturn fmtFallback\n\t}\n\n\tdefer le.Close()\n\n\treturn le\n}", "func createRoom(name string) *chatRoom {\n\t// Initialize chat room struct\n\tc := &chatRoom{\n\t\tname: name,\n\t\tmessages: make(chan string),\n\t\tmembers: make(map[string]*client, 0),\n\t\thistory: []string{},\n\t}\n\tlog.Printf(\"creating room %v\", c.name)\n\n\t//spin off new routine to listen for messages\n\tgo func(c *chatRoom) {\n\t\tfor {\n\t\t\tout := <-c.messages\n\t\t\tfor _, v := range c.members {\n\t\t\t\tv.Message <- out\n\t\t\t\tlog.Printf(\"createroom: broadcasting msg in room: %v to member: %v\", c.name, v.Name)\n\t\t\t}\n\t\t}\n\t}(c)\n\n\treturn c\n}", "func NewLogger() *Clogger {\n\tl := &Clogger{\n\t\tin: make(chan string, 256),\n\t\tw: os.Stderr,\n\t}\n\tgo l.run()\n\treturn l\n}", "func NewLogger(prefix string, logf func(ctx context.Context, format string, args ...interface{})) datastore.Middleware {\n\treturn &logger{Prefix: prefix, Logf: logf, counter: 1}\n}", "func New(conf Config) (log.CloseHandler, error) {\n\tctx := conf.Ctx\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\tclient, err := logging.NewClient(ctx, conf.Parent, conf.Opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\th := &handler{\n\t\tlogName: conf.LogName,\n\t\tclient: client,\n\t\tcodec: conf.Codec,\n\t}\n\tif h.codec == nil {\n\t\th.codec = codec.Simple()\n\t}\n\treturn h, nil\n}", "func newLogger(dbg bool) *lgr.Logger {\n\tif dbg {\n\t\treturn lgr.New(lgr.Msec, lgr.Debug, lgr.CallerFile, lgr.CallerFunc, lgr.LevelBraces)\n\t}\n\n\treturn lgr.New(lgr.Msec, lgr.LevelBraces)\n}", "func (alog *AppLogger) New(requestID string) Logger {\n\t// shortcut\n\tif alog.requestID == requestID {\n\t\treturn alog\n\t}\n\n\tlg := alog.pool.Get()\n\tif nlog, ok := lg.(*AppLogger); ok {\n\t\tnlog.requestID = requestID\n\t\tnlog.SetTags(requestID)\n\n\t\treturn nlog\n\t}\n\n\treturn lg.(Logger).New(requestID)\n}", "func NewChats(conf *Config) *Chats {\n\tc := new(Chats)\n\tc.config = conf\n\tc.chatList = []*ChatInfo{}\n\tc.chatFinder = models.NewChatFinder().Limit(c.config.PageNum, c.config.PageSize)\n\treturn c\n}", "func newCMLogger(name string, chainId string, logger *zap.SugaredLogger, logLevel log.LOG_LEVEL) *CMLogger {\n\treturn &CMLogger{name: name, chainId: chainId, SugaredLogger: logger, logLevel: logLevel}\n}", "func NewLogger(l *zerolog.Logger, lvl log.Level, f map[string]interface{}) log.Logger {\n\tif len(f) == 0 {\n\t\tf = make(map[string]interface{})\n\t}\n\tzl := l.Level(levelMap[lvl]).With().Fields(f).Logger()\n\treturn &Logger{logger: &zl}\n}", "func New(level string, writer string, prettyprint string) Logger {\n\tvar lg Logger\n\tlg.level = stringToLevel()[level]\n\tlg.logger = json.NewEncoder(stringToWriter(writer))\n\tif prettyprint == \"true\" {\n\t\tlg.logger.SetIndent(\"\", \" \")\n\t}\n\n\tvar process = strings.Split(os.Args[0], \"/\")\n\tlg.json.Process = process[len(process)-1]\n\n\treturn lg\n}", "func startChatLogPump(room IrcNick) *chatLogInteral {\n\n\tcli := chatLogInteral{\n\t\tnewSubs: make(chan subToChatPump, 10),\n\t\tkillSubs: make(chan subToChatPump, 10),\n\t\tnewLines: make(chan LogLineParsed, 10),\n\t\tChatFile: getChatLogWriter(room),\n\t}\n\n\tgo cli.run()\n\n\treturn &cli\n}", "func chat(w http.ResponseWriter, r *http.Request, store *sessions.CookieStore, room *ChatRoom) {\n\n //check for session to see if client is authenticated\n session, err := store.Get(r, \"flash-session\")\n if err != nil {\n http.Error(w, err.Error(), http.StatusInternalServerError)\n }\n fm := session.Flashes(\"message\")\n if fm == nil {\n fmt.Println(\"Trying to log in as invalid user\")\n fmt.Fprint(w, \"No flash messages\")\n return\n }\n //session.Save(r, w)\n\n fmt.Println(\"New user connected to chat\")\n\n //use the id and username attached to the session to create the player\n chatterHandler := ChatterHandler{Id: session.Values[\"userid\"].(int), Username: session.Values[\"username\"].(string), Room: room}\n\n chatterHandler.createChatter(w, r)\n}", "func (c *LoggerConfig) NewLogger() (log15.Logger, error) {\n\tvar handlers []log15.Handler\n\n\tif c.Level == \"\" {\n\t\tc.Level = \"info\"\n\t}\n\tfor _, hc := range c.Handlers {\n\t\tif hc == nil {\n\t\t\treturn nil, fmt.Errorf(\"nil handler\")\n\t\t}\n\n\t\th, err := hc.NewHandler()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t//set log level\n\t\t//TODO: use level: how to get root level??\n\t\tl := c.Level\n\t\tif hc.GetLevel() != \"\" {\n\t\t\tl = hc.GetLevel()\n\t\t}\n\n\t\tlvl, err := log15.LvlFromString(strings.ToLower(l))\n\t\tif err != nil {\n\t\t\t//TODO: better explanation!\n\t\t\treturn nil, err\n\t\t}\n\t\th = log15.LvlFilterHandler(lvl, h)\n\n\t\thandlers = append(handlers, h)\n\t}\n\n\thall := log15.MultiHandler(handlers...)\n\n\tif c.BufSize > 0 {\n\t\thall = log15.BufferedHandler(c.BufSize, hall)\n\t}\n\n\tl := log15.New(c.Extra)\n\tl.SetHandler(hall)\n\treturn l, nil\n}", "func newRoom() *room {\n\treturn &room{\n\t\tfoward: make(chan []byte),\n\t\tjoin: make(chan *client),\n\t\tleave: make(chan *client),\n\t\tclients: make(map[*client]bool),\n\t\t//default trace sets as Off\n\t\ttracer: trace.Off(),\n\t}\n}", "func New(logLevel uint, logDir string, format logrus.Formatter) (*logrus.Logger, error) {\n\tlog := logrus.New()\n\tlog.Level = logrus.Level(logLevel)\n\n\tvar logFName string\n\tts := time.Now().Format(\"tccbot-2006-01-02-15-04-05\")\n\tif logDir != \"\" {\n\t\tlogFName = filepath.Join(logDir, ts+\".log\")\n\n\t\tlogFile, err := os.OpenFile(logFName, os.O_CREATE|os.O_WRONLY, 0644)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.SetOutput(logFile)\n\t\tlogrus.RegisterExitHandler(func() {\n\t\t\tif logFile == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogFile.Close()\n\t\t})\n\t}\n\n\tlog.SetFormatter(format)\n\n\tlog.WithFields(logrus.Fields{\"application\": \"tccbot\", \"location\": logFName})\n\n\treturn log, nil\n}", "func newJsonLogger(o *logOptions) Logger {\n\treturn &jsonLogger{\n\t\tjsonLogParser: newJsonLogParser(o),\n\t}\n}", "func NewLogger(l logger.Logger) Logger {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tww := cw.NewWrapResponseWriter(w, r.ProtoMajor)\n\t\t\tt1 := time.Now()\n\t\t\tdefer func() {\n\t\t\t\tmethod := r.Method\n\t\t\t\turl := r.URL\n\t\t\t\trequestID, _ := r.Context().Value(cw.RequestIDKey).(string)\n\t\t\t\tl.Info(\n\t\t\t\t\tfmt.Sprintf(\"%s %s %s\", method, r.URL, r.Proto),\n\t\t\t\t\tzap.Int(\"status\", ww.Status()),\n\t\t\t\t\tzap.String(\"url\", url.String()),\n\t\t\t\t\tzap.String(\"proto\", r.Proto),\n\t\t\t\t\tzap.String(\"ip\", r.RemoteAddr),\n\t\t\t\t\tzap.Int(\"byte\", ww.BytesWritten()),\n\t\t\t\t\tzap.Duration(\"latency\", time.Since(t1)),\n\t\t\t\t\tzap.String(\"reqID\", requestID),\n\t\t\t\t)\n\t\t\t}()\n\t\t\tnext.ServeHTTP(ww, r)\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func New(opts ...Option) log.Logger {\n\tl := new(logger)\n\tfor _, opt := range append(defaultOptions, opts...) {\n\t\topt(l)\n\t}\n\n\treturn l.setLevelMode(l.level).\n\t\tsetLogFormat(l.format)\n}", "func New(opts ...Option) log.Logger {\n\tl := new(logger)\n\tfor _, opt := range append(defaultOptions, opts...) {\n\t\topt(l)\n\t}\n\n\treturn l.setLevelMode(l.level).\n\t\tsetLogFormat(l.format)\n}", "func NewRoomHandler(e *echo.Echo, us usecase.RoomUsecase) {\n\thandler := &RoomHandler{\n\t\tRoomUsecase: us,\n\t}\n\te.GET(\"/rooms\", handler.GetRoomList)\n\te.POST(\"/rooms\", handler.Add)\n\te.DELETE(\"/rooms/:id\", handler.Delete)\n}", "func NewLogger(cfg configFile) *log.Logger {\n\t//This creates new logger\n\tLog = log.New()\n\tLog.Formatter = new(log.JSONFormatter)\n\tLog.Hooks.Add(lfshook.NewHook(lfshook.PathMap{\n\t\tlog.InfoLevel: cfg.Log.Path,\n\t\tlog.ErrorLevel: cfg.Log.Path,\n\t\tlog.DebugLevel: cfg.Log.Path,\n\t}))\n\tLog.Hooks.Add(&metricsHook{\n\t\tmetrics,\n\t})\n\tclient, err := elastic.NewClient(\n\t\telastic.SetURL(cfg.Elastic.URL),\n\t\telastic.SetBasicAuth(cfg.Elastic.Username, cfg.Elastic.Password))\n\tif err != nil {\n\t\tlog.Error(err)\n\t} else {\n\t\thook, err := elogrus.NewElasticHook(client, cfg.Server.Host, log.DebugLevel, \"goplag\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t} else {\n\t\t\tLog.Hooks.Add(hook)\n\t\t}\n\n\t}\n\n\treturn Log\n}", "func New(lev Level, lis Listener, layout string) *Logger {\n\tlogger := &Logger{\n\t\tlev: lev,\n\t\tlis: []Listener{lis},\n\t}\n\tlogger.SetLayout(layout)\n\treturn logger\n}", "func New(opts ...logging.Option) logging.Logger {\n\tl := &logger{\n\t\tlg: log.New(),\n\t}\n\n\tfor _, fn := range opts {\n\t\tfn(l)\n\t}\n\n\treturn l\n}", "func NewHandler(log zerolog.Logger) func(httpserver.Handler) httpserver.Handler {\n\treturn func(next httpserver.Handler) httpserver.Handler {\n\t\treturn httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {\n\t\t\t// Create a copy of the logger (including internal context slice)\n\t\t\t// to prevent data race when using UpdateContext.\n\t\t\tl := log.With().Logger()\n\t\t\tr = r.WithContext(l.WithContext(r.Context()))\n\t\t\treturn next.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func NewRoom(name, logFilePath string) (*Room, error) {\n\n\tp, err := expandPath(logFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error while getting log file path: %w\", err)\n\t}\n\n\tlogFileName := path.Join(p, strings.ReplaceAll(name, \" \", \"_\")+\".dat\")\n\tlog.Printf(\"Log file location: %s\\n\", logFileName)\n\n\tlogFile, err := os.OpenFile(logFileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error opening/creating log file: %v\", err)\n\t}\n\n\treturn &Room{name: name, logFile: logFile}, nil\n}", "func MessagesCreateNewMessageHandler(params messages.CreateNewMessageParams, principal *models.Principal) middleware.Responder {\n\tchat, err := dao.GetChatByIDAndUserID(params.ChatID, principal.Userid.Hex())\n\tif err != nil {\n\t\tattribute := \"error\"\n\t\tmessage := err.Error()\n\t\treturn messages.NewCreateNewMessageBadRequest().WithPayload(&models.InvalidParameterInput{Attribute: &attribute, Message: &message})\n\t}\n\n\tmessage := params.Body\n\tmessage.From = &models.UserShort{\n\t\tID: principal.Userid,\n\t}\n\tmessage.Time = strfmt.NewDateTime()\n\n\tdao.TouchChat(chat.ID.Hex())\n\tdao.SaveMessage(*chat, *message)\n\n\treturn messages.NewCreateNewMessageOK().WithPayload(message)\n}", "func New(info logger.Info) (logger.Logger, error) {\n\tlogDir := removeLogDirOption(info.Config)\n\tif logDir == \"\" {\n\t\tlogDir = defaultLogDir\n\t}\n\tinfo.LogPath = filepath.Join(logDir, info.ContainerID)\n\n\tif err := os.MkdirAll(filepath.Dir(info.LogPath), 0755); err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting up logger dir: %v\", err)\n\t}\n\n\treturn jsonfilelog.New(info)\n}", "func NewApp(pgURI string) *App {\n\tr := mux.NewRouter()\n\n\tdbOpts, err := pg.ParseURL(pgURI)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\n\tdb := pg.Connect(dbOpts)\n\n\twsUpgrader := websocket.Upgrader{\n\t\tReadBufferSize: 0,\n\t\tWriteBufferSize: 0,\n\t}\n\n\tr.HandleFunc(\"/chat\", func(w http.ResponseWriter, r *http.Request) {\n\t\tc, err := wsUpgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\n\t\t\treturn\n\t\t}\n\t\tdefer c.Close()\n\n\t\tuuid := uuid.NewV4().String()\n\n\t\tgb := make(chan interface{})\n\n\t\tpt := time.NewTicker(time.Second)\n\t\tdefer pt.Stop()\n\n\t\tgo func() {\n\t\t\tln := db.Listen(\"chat\")\n\t\t\tdefer ln.Close()\n\n\t\t\tcch := ln.Channel()\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase n := <-cch:\n\t\t\t\t\tvar m Msg\n\n\t\t\t\t\tif err := json.Unmarshal([]byte(n.Payload), &m); err != nil {\n\t\t\t\t\t\tlog.Print(err)\n\t\t\t\t\t}\n\n\t\t\t\t\tm.Me = m.UUID == uuid\n\n\t\t\t\t\terr = c.WriteJSON(&m)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tgb <- nil\n\t\t\t\t\t}\n\t\t\t\tcase <-pt.C:\n\t\t\t\t\terr := c.WriteMessage(websocket.PingMessage, []byte(\"pong\"))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tgb <- nil\n\t\t\t\t\t}\n\t\t\t\tcase <-gb:\n\t\t\t\t\tlog.Printf(\"%s just left the chat!\", uuid)\n\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tlog.Printf(\"%s just entered the chat!\", uuid)\n\n\t\tfor {\n\t\t\tmessageType, p, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tgb <- nil\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tswitch messageType {\n\t\t\tcase websocket.TextMessage:\n\t\t\t\tjson, _ := json.Marshal(&Msg{time.Now(), string(p), uuid, false})\n\n\t\t\t\tgo func() {\n\t\t\t\t\tif _, err := db.Exec(\"NOTIFY chat, ?\", string(json)); err != nil {\n\t\t\t\t\t\tlog.Print(err)\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t}).Name(\"chat\")\n\n\tr.PathPrefix(\"/\").Handler(http.FileServer(http.Dir(\"vue/mojochat\"))).Methods(\"GET\").Name(\"index\")\n\n\treturn &App{r, db, &wsUpgrader}\n}", "func NewLogger(scope string) Logger {\n\n\tg := glg.New()\n\n\tl := logger{\n\t\tglg: g,\n\t\tscope: scope,\n\t\tbuffer: LogMeta{Tags: make(tagMap), Data: make(dataMap)},\n\t}\n\n\tl.setScopeLevels()\n\treturn &l\n\n}", "func newMessageHandler(m chan<- string, f parserFunc) *messageHandler {\n\treturn &messageHandler{\n\t\tmessages: m,\n\t\tparserFunc: f,\n\t}\n}", "func NewRoom(name string, u user.Service, logger logger.Service, server *Server) *Room {\n\tlogger.Info(\"cmp\", \"Room\", \"method\", \"NewRoom\", \"msg\", fmt.Sprintf(\"new Room %s Created\", name))\n\t// clientService := client.NewService()\n\treturn &Room{\n\t\tName: name,\n\t\tuserService: u,\n\t\tAddClientChan: make(chan *websocket.Conn, 100),\n\t\tEventDespatcher: NewEventDispatcher(),\n\t\tClients: make(map[string]*Client),\n\t\tlogger: logger,\n\t\tserver: server,\n\t}\n}", "func NewMulti(ls ...Logger) Logger {\n\treturn &mLog{ls: ls}\n}", "func New(c *Config) (l *Logger, err error) {\n\t// set FlushAfterSeconds\n\tif c.FlushAfterSeconds > LoggerFlushAfterSecondsMax {\n\t\tlog.Printf(\"Limiting FlushAfterSeconds to %d\", LoggerFlushAfterSecondsMax)\n\t\tc.FlushAfterSeconds = LoggerFlushAfterSecondsMax\n\t}\n\n\tconsumers := make([]chan DataUnit, 0)\n\tl = &Logger{\n\t\tconsumers: consumers,\n\t\tconfig: *c,\n\n\t\tstop: make(chan struct{}, 0),\n\t}\n\terr = l.initLoggerBuffer()\n\treturn\n}", "func CreateLogger(c echo.Context, uuid uuid.IUUID, level log.Level) {\n\tonce.Do(func() {\n\n\t\tformatter := new(log.JSONFormatter)\n\t\tformatter.TimestampFormat = \"2018-12-30 23:05:05\"\n\t\tformatter.DisableTimestamp = false\n\t\tlog.SetFormatter(formatter)\n\n\t\tfile, _ := os.OpenFile(\"mylog.txt\", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)\n\t\tmw := io.MultiWriter(os.Stdout, file)\n\t\tlog.SetOutput(mw)\n\t\tlog.SetLevel(level)\n\n\t\tinstance = &Logger{\n\t\t\tType: \"REQUEST\",\n\t\t\tProcessID: uuid.GetUUID(),\n\t\t\tSourceIP: c.Request().RemoteAddr,\n\t\t\tHTTPMethod: c.Request().Method,\n\t\t\tEndPoint: c.Request().URL.Path,\n\t\t\tTrackingID: \"\", // User ID\n\t\t\tAppID: \"\", // App ID\n\t\t}\n\t})\n}", "func New(handler Handler, flag int) *Logger {\n\tvar l = new(Logger)\n\n\tl.level = LevelInfo\n\tl.handler = handler\n\n\tl.flag = flag\n\n\tl.quit = make(chan struct{})\n\tl.closed = false\n\n\tl.msg = make(chan []byte, 1024)\n\n\tl.bufs = make([][]byte, 0, 16)\n\n\tl.wg.Add(1)\n\tgo l.run()\n\n\treturn l\n}", "func NewLogger(lv Level) *Logger {\n\treturn &Logger{level: lv}\n}", "func NewLogger(channelLen int64) *DldbLogger {\n\tlog := new(DldbLogger)\n\tlog.msgChan = make(chan *logMsg, channelLen)\n\tlog.outputs = make(map[string]LoggerInterface)\n\tgo log.startLogger()\n\treturn log\n}", "func NewLogger(kitlogger log.Logger, options ...LoggerOption) *Logger {\n\tlogger := &Logger{\n\t\tinfoLogger: level.Info(kitlogger),\n\t\terrorLogger: level.Error(kitlogger),\n\n\t\tmessageKey: \"msg\",\n\t}\n\n\tfor _, option := range options {\n\t\toption(logger)\n\t}\n\n\treturn logger\n}", "func NewGoogleChat(opts GoogleChatOpts) (*GoogleChatManager, error) {\n\ttransport := &http.Transport{\n\t\tMaxIdleConnsPerHost: opts.MaxIdleConn,\n\t}\n\n\t// Add a proxy to make upstream requests if specified in config.\n\tif opts.ProxyURL != \"\" {\n\t\tu, err := url.Parse(opts.ProxyURL)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing proxy URL: %s\", err)\n\t\t}\n\t\ttransport.Proxy = http.ProxyURL(u)\n\t}\n\n\t// Initialise a generic HTTP Client for communicating with the G-Chat APIs.\n\tclient := &http.Client{\n\t\tTimeout: opts.Timeout,\n\t\tTransport: transport,\n\t}\n\n\t// Initialise the map of active alerts.\n\talerts := make(map[string]AlertDetails, 0)\n\n\t// Initialise message template functions.\n\ttemplateFuncMap := template.FuncMap{\n\t\t\"Title\": strings.Title,\n\t\t\"toUpper\": strings.ToUpper,\n\t\t\"Contains\": strings.Contains,\n\t}\n\n\t// Load the template.\n\ttmpl, err := template.New(filepath.Base(opts.Template)).Funcs(templateFuncMap).ParseFiles(opts.Template)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmgr := &GoogleChatManager{\n\t\tlo: opts.Log,\n\t\tmetrics: opts.Metrics,\n\t\tclient: client,\n\t\tendpoint: opts.Endpoint,\n\t\troom: opts.Room,\n\t\tactiveAlerts: &ActiveAlerts{\n\t\t\talerts: alerts,\n\t\t\tlo: opts.Log,\n\t\t\tmetrics: opts.Metrics,\n\t\t},\n\t\tmsgTmpl: tmpl,\n\t\tdryRun: opts.DryRun,\n\t}\n\t// Start a background worker to cleanup alerts based on TTL mechanism.\n\tgo mgr.activeAlerts.startPruneWorker(1*time.Hour, opts.ThreadTTL)\n\n\treturn mgr, nil\n}", "func chatHandler(w http.ResponseWriter, r *http.Request) {\n\t// Parse the chat room name out of the url query params, i.e. ?room=skiabot_alerts.\n\tto := r.URL.Query().Get(\"room\")\n\tif to == \"\" {\n\t\thttputils.ReportError(w, r, fmt.Errorf(\"Missing room in URL: %q\", r.RequestURI), \"Chat room name missing.\")\n\t\treturn\n\t}\n\n\t// Compose the message.\n\tbody, err := alertmanager.Chat(r.Body)\n\tif err != nil {\n\t\thttputils.ReportError(w, r, err, \"Failed to encode outgoing chat.\")\n\t\treturn\n\t}\n\n\t// Send the message to the chat room.\n\tif err := chatbot.Send(body, to); err != nil {\n\t\thttputils.ReportError(w, r, err, \"Failed to send outgoing chat.\")\n\t\treturn\n\t}\n}", "func newHandler(conn net.Conn, l logger, c *config, users map[string]string) (*handler, error) {\n\t// get current directory\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a new handler object\n\th := &handler{\n\t\tconfig: c,\n\t\tconn: conn,\n\t\tlogger: l,\n\t\tdir: dir,\n\t\tusers: users,\n\t\tisLoggedIn: false,\n\t\tcommands: make(map[CommandCode]handleFunc),\n\t}\n\n\th.logMessage(fmt.Sprintf(\"Accepted connection from %v\", h.conn.RemoteAddr()))\n\n\t// initialize commands for not logged in state\n\th.initCommandTable()\n\n\t//initialize default data connection\n\tif h.config.pasv {\n\t\th.initPassiveDataConn()\n\t} else {\n\t\t// calculate default data port\n\t\thost, port, err := net.SplitHostPort(conn.RemoteAddr().String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar portNum int\n\t\t_, err = fmt.Sscanf(port, \"%d\", &portNum)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tportNum++\n\t\tport = fmt.Sprintf(\"%d\", portNum)\n\t\th.initActiveDataConn(net.JoinHostPort(host, port))\n\t}\n\n\treturn h, nil\n}", "func NewJSONLogger(logPath, filename, lv string) (*Logger, error) {\n\tlogger := logrus.New()\n\tlogger.AddHook(NewHook())\n\n\tlogger.Formatter = &logrus.JSONFormatter{}\n\n\tlevel, err := logrus.ParseLevel(lv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.SetLevel(level)\n\n\tfd, err := os.OpenFile(\n\t\tpath.Join(logPath, filename),\n\t\tos.O_CREATE|os.O_APPEND|os.O_WRONLY,\n\t\t0644,\n\t)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif os.MkdirAll(logPath, 0777) != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tgoto Finally\n\t\t}\n\t\treturn nil, err\n\t}\n\nFinally:\n\tlogger.Out = io.MultiWriter(os.Stdout, fd)\n\treturn &Logger{logger}, nil\n}", "func New(ctx logger.Context) (logger.Logger, error) {\n\tlog, err := os.OpenFile(ctx.LogPath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar capval int64 = -1\n\tif capacity, ok := ctx.Config[\"max-size\"]; ok {\n\t\tvar err error\n\t\tcapval, err = units.FromHumanSize(capacity)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar maxFiles = 1\n\tif maxFileString, ok := ctx.Config[\"max-file\"]; ok {\n\t\tmaxFiles, err = strconv.Atoi(maxFileString)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif maxFiles < 1 {\n\t\t\treturn nil, fmt.Errorf(\"max-file cannot be less than 1\")\n\t\t}\n\t}\n\n\tvar extra []byte\n\tif attrs := ctx.ExtraAttributes(nil); len(attrs) > 0 {\n\t\tvar err error\n\t\textra, err = json.Marshal(attrs)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &JSONFileLogger{\n\t\tf: log,\n\t\tbuf: bytes.NewBuffer(nil),\n\t\tctx: ctx,\n\t\tcapacity: capval,\n\t\tn: maxFiles,\n\t\treaders: make(map[*logger.LogWatcher]struct{}),\n\t\tnotifyRotate: pubsub.NewPublisher(0, 1),\n\t\textra: extra,\n\t}, nil\n}", "func New(ctx logger.Context) (logger.Logger, error) {\n\tlog, err := os.OpenFile(ctx.LogPath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar capval int64 = -1\n\tif capacity, ok := ctx.Config[\"max-size\"]; ok {\n\t\tvar err error\n\t\tcapval, err = units.FromHumanSize(capacity)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar maxFiles = 1\n\tif maxFileString, ok := ctx.Config[\"max-file\"]; ok {\n\t\tmaxFiles, err = strconv.Atoi(maxFileString)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif maxFiles < 1 {\n\t\t\treturn nil, fmt.Errorf(\"max-file cannot be less than 1\")\n\t\t}\n\t}\n\n\tvar extra []byte\n\tif attrs := ctx.ExtraAttributes(nil); len(attrs) > 0 {\n\t\tvar err error\n\t\textra, err = json.Marshal(attrs)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &JSONFileLogger{\n\t\tf: log,\n\t\tbuf: bytes.NewBuffer(nil),\n\t\tctx: ctx,\n\t\tcapacity: capval,\n\t\tn: maxFiles,\n\t\treaders: make(map[*logger.LogWatcher]struct{}),\n\t\tnotifyRotate: pubsub.NewPublisher(0, 1),\n\t\textra: extra,\n\t}, nil\n}", "func NewCompositeLogger(loggers ...Logger) *CompositeLogger {\n\treturn &CompositeLogger{loggers: loggers}\n}", "func NewChat(client *rpc.Client, selfID peer.ID, contentTopic string, useV1Payload bool, nickname string) (*Chat, error) {\n\tvar defaultTopic = \"/waku/2/default-waku/proto\"\n\t// join the default waku topic and subscribe to it\n\t_, err := nwaku.PostWakuRelaySubscriptions(client, []string{defaultTopic})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := &Chat{\n\t\t//node: n,\n\t\tclient: client,\n\t\t// XXX Not used directly anymore\n\t\t//sub: sub,\n\t\tpubsubTopic: defaultTopic,\n\t\tself: selfID,\n\t\tcontentTopic: contentTopic,\n\t\tnick: nickname,\n\t\tuseV1Payload: useV1Payload,\n\t\tMessages: make(chan *pb.Chat2Message, 1024),\n\t}\n\n\t// start reading messages from the subscription in a loop\n\tgo c.readLoop()\n\n\treturn c, nil\n}", "func NewLogger(env string) *log.Logger {\n\n\tonce.Do(func() {\n\t\tlogger = log.New()\n\n\t\tif env == \"production\" {\n\t\t\tlog.SetFormatter(&log.JSONFormatter{})\n\t\t} else {\n\t\t\t// The TextFormatter is default, you don't actually have to do this.\n\t\t\tlog.SetFormatter(&log.TextFormatter{})\n\t\t}\n\t})\n\n\treturn logger\n}", "func New(url string, cpus int, rooms int, version string) *ChatServer {\n\tcs := ChatServer{\n\t\turl: url,\n\t\trooms: rooms,\n\t\tcpus: cpus,\n\t\tversion: version,\n\t}\n\tcs.Updatecapacity()\n\tcs.Updatetimestamp()\n\treturn &cs\n}", "func NewLogger(defaultLogger *log.Logger, v *log.Logger, lv int) *Logger {\n\treturn &Logger{\n\t\td: defaultLogger,\n\t\tv: v,\n\t\tlevel: lv,\n\t\tdepth: 2,\n\t}\n}", "func New(ctx ...interface{}) log15.Logger {\n\tl := log15.New(ctx...)\n\tl.SetHandler(defaultHandler)\n\treturn l\n}", "func NewLogger(p Priority, logFlag int) (*log.Logger, error) {}", "func NewLogger(l *zap.Logger) middleware.Logger {\n\treturn &adapter{l}\n}", "func newLogentriesLogger(lvl logger.Level, token string, enableColors bool) logger.FieldLogger {\n\tl := logrus.New()\n\tl.AddHook(NewLogentriesHook(token))\n\tl.SetOutput(os.Stdout)\n\n\tl.Level = lvl\n\tl.Formatter = &textFormatter{\n\t\tForceColors: enableColors,\n\t}\n\n\treturn LogrusLogger{l}\n}", "func makeLogger(basePath string) middlewareFunc {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tlog := structlog.FromContext(r.Context(), nil)\n\t\t\tlog.SetDefaultKeyvals(\n\t\t\t\tdef.LogRemote, r.RemoteAddr,\n\t\t\t\tdef.LogHTTPStatus, \"\",\n\t\t\t\tdef.LogHTTPMethod, r.Method,\n\t\t\t\tdef.LogFunc, path.Join(\"/\", strings.TrimPrefix(r.URL.Path, basePath)),\n\t\t\t)\n\t\t\tr = r.WithContext(structlog.NewContext(r.Context(), log))\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func New() *Handler {\n\treturn &Handler{\n\t\tEntries: make([]log.Entry, 0),\n\t}\n}", "func NewLogger(bufLen int64, name, provider, config string) *Logger {\n\terr := NewNamedLogger(DEFAULT, bufLen, name, provider, config)\n\tif err != nil {\n\t\tCriticalWithSkip(1, \"Unable to create default logger: %v\", err)\n\t\tpanic(err)\n\t}\n\tl, _ := NamedLoggers.Load(DEFAULT)\n\treturn l\n}", "func newWriteLogger(log *log.Logger, w io.Writer) io.Writer {\n\treturn &writeLogger{log, w}\n}", "func NewLogger(logs string) (result Reporter) {\n\tlog.Printf(\"[INFO] new reporter, path=%s\", logs)\n\t_ = os.MkdirAll(logs, 0o750)\n\tresult = Reporter{logsPath: logs, messages: make(chan string, 1000)}\n\tgo result.activate()\n\treturn result\n}", "func NewRooms(r io.Reader, commands []Command) (Rooms, error) {\n\tdec := json.NewDecoder(r)\n\tdec.DisallowUnknownFields()\n\n\ts := []Room{}\n\trms := Rooms{}\n\trms.rooms = make(map[string]Room)\n\terr := dec.Decode(&s)\n\tif err != nil {\n\t\treturn rms, fmt.Errorf(\"error decoding rooms JSON: %v\", err)\n\t}\n\n\tfor _, rm := range s {\n\t\tif strings.Contains(rm.Name, \" \") {\n\t\t\treturn rms, fmt.Errorf(\"room name \\\"%v\\\" should not contain a space\", rm.Name)\n\t\t}\n\t\trms.addRoom(rm)\n\t}\n\n\trms.groups = make(map[string]map[string]Command)\n\tfor _, c := range commands {\n\t\tm, ok := rms.groups[c.Group]\n\t\tif !ok {\n\t\t\tm = make(map[string]Command)\n\t\t\trms.groups[c.Group] = m\n\t\t}\n\t\tm[c.Command] = c\n\t}\n\n\treturn rms, nil\n}", "func New(out io.Writer) Logger {\n\tl := log.NewJSONLogger(log.NewSyncWriter(out))\n\tl = log.With(l, \"ts\", log.DefaultTimestampUTC)\n\treturn &logger{l}\n}", "func newLog(jobId string) Log {\n\treturn Log{\n\t\tId: uniuri.New(),\n\t\tJobId: jobId,\n\t\tStatus: \"New\",\n\t}\n}", "func (l Loggers) NewLogger(name string, level logging.Level, handlers ...logging.Handler) *logging.Logger {\n\ths := []logging.Handler{}\n\tif l.writer != nil {\n\t\ths = append(hs, &logging.WriteHandler{\n\t\t\tFormatter: &logging.StandardFormatter{TimeFormat: logging.StandardTimeFormat},\n\t\t\tWriter: l.writer,\n\t\t\tLevel: logging.DEBUG,\n\t\t})\n\t} else {\n\t\tfor _, h := range handlers {\n\t\t\tif h != nil {\n\t\t\t\ths = append(hs, h)\n\t\t\t}\n\t\t}\n\t}\n\treturn logging.NewLogger(name, level, hs, 0)\n}", "func New(prefix string, writers ...io.Writer) *log.Logger {\n\treturn log.New(NewWriter(prefix, writers...), \"\", 0)\n}", "func NewMatchRoomHandler(c *core.Core) *MatchRoomHandler {\n\treturn &MatchRoomHandler{\n\t\tcore: c,\n\t\tupgrader: websocket.Upgrader{},\n\t}\n}", "func NewLogger(name, tag string) Logger {\n\tif entry, ok := loggerEntryMap[name]; ok {\n\t\treturn entry.NewLogger(tag)\n\t}\n\n\tfmt.Printf(\"Invalid logger: %s\", name)\n\treturn nil\n}", "func New(logger logger.Logger) *Handler {\n\treturn &Handler{\n\t\tlogger: logger,\n\t}\n}", "func NewRoom() *Room {\n\treturn &Room{\n\t\tforward: make(chan *Message),\n\t\tjoin: make(chan *Client),\n\t\tleave: make(chan *Client),\n\t\tclients: make(map[*Client]bool),\n\t}\n}", "func NewLvLogger(out io.Writer, prefix string, flag int, level int8) *LvLogger {\n\tinner := log.New(out, prefix, flag)\n\treturn &LvLogger{inner: inner, level: level}\n}", "func NewChatMessage()(*ChatMessage) {\n m := &ChatMessage{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewRoom(t *testing.T, creator *User, modifiers ...roomModifier) *Room {\n\tt.Helper()\n\tcounter := atomic.AddInt64(&roomIDCounter, 1)\n\n\t// set defaults then let roomModifiers override\n\tr := &Room{\n\t\tID: fmt.Sprintf(\"!%d:localhost\", counter),\n\t\tcreator: creator,\n\t\tauthEvents: gomatrixserverlib.NewAuthEvents(nil),\n\t\tpreset: PresetPublicChat,\n\t\tVersion: gomatrixserverlib.RoomVersionV9,\n\t}\n\tfor _, m := range modifiers {\n\t\tm(t, r)\n\t}\n\tr.insertCreateEvents(t)\n\treturn r\n}", "func NewLogger() *Logger {\n\tlog := new(Logger)\n\tlog.filterLevels = make(map[string]int)\n\tlog.filterLogWriters = make(map[string]LogWriter)\n\treturn log\n}", "func NewChatAdapter(c glados.Context) glados.ChatAdapter {\n\tslackClient := slack.New(c.Env(\"GLADOS_SLACK_BOT_UAER_TOKEN\", \"\"))\n\trtm := slackClient.NewRTM()\n\tadapter := &slackChatAdapter{\n\t\tusers: make(map[string]*slack.User),\n\t\tchannels: make(map[string]*slack.Channel),\n\t\tcontext: c,\n\t\tclient: slackClient,\n\t\trtm: rtm,\n\t}\n\tgo rtm.ManageConnection()\n\tgo adapter.handleRTMEvent()\n\treturn adapter\n}", "func New(shardID int, logLevel, timezoneLocation, discordrusWebHookURL string) *Logger {\n\tlocation := parseTimezoneLocation(timezoneLocation)\n\n\tlogrusLogger := &logrus.Logger{\n\t\tFormatter: &locale{\n\t\t\t&logrus.TextFormatter{},\n\t\t\tlocation,\n\t\t},\n\t\tOut: os.Stdout,\n\t\tLevel: logrus.InfoLevel,\n\t\tHooks: make(logrus.LevelHooks),\n\t}\n\n\tlog := &Logger{\n\t\tEntry: logrus.NewEntry(logrusLogger).WithField(\"shardID\", shardID),\n\t\tLocation: location,\n\t\tDiscordrusWebHookURL: discordrusWebHookURL,\n\t}\n\n\tlog.UpdateLevel(logLevel)\n\n\treturn log\n}", "func NewLeveledLogger(l kit_log.Logger) Logger {\n\treturn &ctLogger{\n\t\tlogger: l,\n\t}\n}", "func NewRequestLogger() heimdall.Plugin {\n return &requestLogger{}\n}", "func NewMultiLogger(timeFormat, prefix string, outs, errs []NamedWriter) *MultiLogger {\n\treturn createMultiLogger(timeFormat, prefix, outs, errs)\n}", "func NewAdapter(l ...level.LogLevel) *ReadWriter {\n\tw := &ReadWriter{\n\t\tdone: make(chan struct{}, 1),\n\t}\n\tif len(l) > 0 {\n\t\tw.logLevel = l[0]\n\t}\n\treturn w\n}", "func New(channelID string, session *discordgo.Session) *Logger {\n\n\tl := &Logger{\n\t\tChannelID: channelID,\n\t\tLogDeletes: false,\n\t\tLogEdits: false,\n\t\tLogImages: false,\n\t}\n\n\treturn l\n}", "func newLogger() services.Logger {\n\treturn &services.SystemOutLogger{}\n}", "func New(configurations ...func(*Logger)) *Logger {\n\t// default log config\n\tlogger := Logger{\n\t\tlogCritical: log.New(os.Stderr, fmt.Sprintf(\"%-9s\", LevelCritical), DefaultLogFlags),\n\t\tlogError: log.New(os.Stderr, fmt.Sprintf(\"%-9s\", LevelError), DefaultLogFlags),\n\t\tlogWarning: log.New(os.Stdout, fmt.Sprintf(\"%-9s\", LevelWarning), DefaultLogFlags),\n\t\tlogNotice: log.New(os.Stdout, fmt.Sprintf(\"%-9s\", LevelNotice), DefaultLogFlags),\n\t\tlogInfo: log.New(os.Stdout, fmt.Sprintf(\"%-9s\", LevelInfo), DefaultLogFlags),\n\t\tlogDebug: log.New(os.Stdout, fmt.Sprintf(\"%-9s\", LevelDebug), DefaultLogFlags),\n\t\tlogTrace: log.New(os.Stdout, fmt.Sprintf(\"%-9s\", LevelTrace), DefaultLogFlags),\n\t\tlevel: Info,\n\t}\n\n\t// now customize logger\n\tfor _, config := range configurations {\n\t\tconfig(&logger)\n\t}\n\n\treturn &logger\n}", "func new(level string) *logrus.Logger {\n\tlog := logrus.New()\n\n\tlog.SetOutput(os.Stdout)\n\tlog.SetFormatter(&logrus.JSONFormatter{})\n\n\tif l, err := logrus.ParseLevel(level); err != nil {\n\t\tlog.WithField(\"invalidLevel\", level).\n\t\t\tError(\"invalid log level, defaulting to 'info'\")\n\t} else {\n\t\tlog.SetLevel(l)\n\t\tlog.WithField(\"to\", level).\n\t\t\tInfo(\"log level set\")\n\t}\n\treturn log\n}", "func NewLogger(src chan interface{}, dst io.Writer) *Logger {\n\tif src == nil {\n\t\tsrc = make(chan interface{}, iounit)\n\t}\n\tl := Logger{\n\t\tsrc: src,\n\t\tdst: dst,\n\t\tdone: make(chan bool),\n\t\thalt: make(chan bool),\n\t\tonce: make(chan bool, 1),\n\t}\n\tl.once <- true\n\tgo l.start()\n\treturn &l\n}", "func Chat(chub *connections.ConnectionHub) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tgo chub.WriteMessage()\n\t\tlog.Println(\"wrote message\")\n\t})\n}", "func NewLogger(logger *log.Logger) LogAdapter {\n\treturn &adapter{Logger: logger}\n}", "func New() LogWriter {\n\tinitBuf := &bytes.Buffer{}\n\treturn &logWriter{\n\t\tinitBuf: initBuf,\n\t\tw: bufio.NewWriter(initBuf),\n\t\tfirstSet: true,\n\t\twriteLock: new(sync.Mutex),\n\t\tloggers: make([]Logger, MaxLoggers),\n\t\tcurLoggersIdx: new(uint32),\n\t}\n}" ]
[ "0.57262474", "0.5666914", "0.5642704", "0.559965", "0.5584999", "0.55159354", "0.5479154", "0.53701144", "0.53389204", "0.52973133", "0.5297095", "0.5291896", "0.5281995", "0.5271505", "0.52591103", "0.5215096", "0.52024347", "0.5174453", "0.5168299", "0.5163351", "0.51610357", "0.51566505", "0.51528984", "0.5127992", "0.5121714", "0.5096407", "0.50900656", "0.50868213", "0.5081628", "0.5060809", "0.50462425", "0.5028319", "0.5023499", "0.5023499", "0.50121844", "0.5005878", "0.50001174", "0.49995062", "0.4991527", "0.49887392", "0.49879885", "0.49836734", "0.49649248", "0.49566588", "0.49559858", "0.4952976", "0.49432397", "0.49414685", "0.4936588", "0.4923224", "0.4919905", "0.49156845", "0.4898328", "0.48907813", "0.48907784", "0.48848185", "0.48749667", "0.48674545", "0.48674545", "0.48659962", "0.4864183", "0.48518413", "0.4843472", "0.48405513", "0.48384905", "0.48370725", "0.48367554", "0.48326415", "0.48323277", "0.4821323", "0.48160765", "0.4810556", "0.4810514", "0.48103693", "0.48063973", "0.4805119", "0.47961527", "0.47951362", "0.4793403", "0.47929078", "0.47861177", "0.47784537", "0.47770953", "0.47750187", "0.47680485", "0.47676176", "0.4759738", "0.47546044", "0.47478434", "0.47444668", "0.473931", "0.47366387", "0.4735347", "0.4735108", "0.47069222", "0.4706821", "0.47021335", "0.47000486", "0.46991566", "0.4697071" ]
0.70414895
0
Sets the address to the value of b. If b is larger than len(a) it will panic
func (a *Address) SetBytes(b []byte) { if len(b) > len(a) { b = b[len(b)-AddressLength:] } copy(a[AddressLength-len(b):], b) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *Address) SetBytes(b []byte) {\n\tif len(b) > len(a) {\n\t\tb = b[len(b)-AddressLength:]\n\t}\n\n\tcopy(a[AddressLength-len(b):], b)\n}", "func (m *BookingBusiness) SetAddress(value PhysicalAddressable)() {\n err := m.GetBackingStore().Set(\"address\", value)\n if err != nil {\n panic(err)\n }\n}", "func (a *Address) Set(s string) error {\n\tx, err := parseHex(s)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\t*a = Address(x)\n\treturn nil\n}", "func (z *Bits) Set(b Bits) {\n\tif z.Num != b.Num {\n\t\t*z = New(b.Num)\n\t}\n\tcopy(z.Bits, b.Bits)\n}", "func (h *Host) SetAdress(a string) {\n}", "func (b IGMP) SetGroupAddress(address tcpip.Address) {\n\taddrBytes := address.As4()\n\tif n := copy(b[igmpGroupAddressOffset:], addrBytes[:]); n != IPv4AddressSize {\n\t\tpanic(fmt.Sprintf(\"copied %d bytes, expected %d\", n, IPv4AddressSize))\n\t}\n}", "func brokerSetAddress(bs *v1alpha1.BrokerStatus, url *apis.URL) {\n\tif url != nil {\n\t\tbs.Address.Hostname = url.Host\n\t\tbs.Address.URL = url\n\t\tbrokerCondSet.Manage(bs).MarkTrue(v1alpha1.BrokerConditionAddressable)\n\t} else {\n\t\tbs.Address.Hostname = \"\"\n\t\tbs.Address.URL = nil\n\t\tbrokerCondSet.Manage(bs).MarkFalse(v1alpha1.BrokerConditionAddressable, \"NotAddressable\", \"broker service has .status.addressable.url == nil\")\n\t}\n}", "func (_m *MockDataCoord) SetAddress(address string) {\n\t_m.Called(address)\n}", "func (w *Wallet) SetAddr(a string) {\n\tw.mutex.Lock()\n\tw.Addr = a\n\tw.mutex.Unlock()\n}", "func (x *Writer) SetAddress(a uint16) {\n\tx.addr = a\n}", "func (p *PoolAllocatorType) SetAddress(addrID uint32) (string, error) {\n\tif addrID < p.StartRange || addrID > p.EndRange {\n\t\treturn \"\", fmt.Errorf(\"SetAddress: addr_id '%d' out of range '%d-%d\",\n\t\t\taddrID, p.StartRange, p.EndRange)\n\t}\n\n\tp.Allocated[addrID] = struct{}{}\n\n\treturn p.formatIPAddress(addrID), nil\n}", "func (a *Addr) Set(s string) error {\n\tpA, err := ParseAddr(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = pA\n\treturn nil\n}", "func (m *FlatMemory) StoreAddress(addr uint16, v uint16) {\n\tm.b[addr] = byte(v & 0xff)\n\tif (addr & 0xff) == 0xff {\n\t\tm.b[addr-0xff] = byte(v >> 8)\n\t} else {\n\t\tm.b[addr+1] = byte(v >> 8)\n\t}\n}", "func (_Contract *ContractTransactor) SetAddr(opts *bind.TransactOpts, node [32]byte, coinType *big.Int, a []byte) (*types.Transaction, error) {\n\treturn _Contract.contract.Transact(opts, \"setAddr\", node, coinType, a)\n}", "func (_m *MockQueryCoord) SetAddress(address string) {\n\t_m.Called(address)\n}", "func (p *program) ensureAddr(addr int) {\n\textend := addr - len(p.mem) + 1\n\tif addr >= len(p.mem) {\n\t\tp.mem = append(p.mem, make([]int, extend)...)\n\t}\n}", "func BytesToAddress(b []byte) Address {\n\tvar a Address\n\tif len(b) > AddressLength {\n\t\tb = b[len(b)-AddressLength:]\n\t}\n\tcopy(a[AddressLength-len(b):], b)\n\treturn a\n}", "func BytesToAddress(b []byte) types.Address {\n\tvar a types.Address\n\tif len(b) > len(a) {\n\t\tb = b[len(b)-AddressLength:]\n\t}\n\tcopy(a[AddressLength-len(b):], b)\n\treturn a\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}", "func (_m *MockHTTPServerInterface) SetAddr(_a0 string) {\n\t_m.Called(_a0)\n}", "func (r *Resolver) SetMultiAddress(opts *bind.TransactOpts, coinType uint64, address []byte) (*types.Transaction, error) {\n\tnameHash, err := NameHash(r.domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Contract.SetAddr0(opts, nameHash, big.NewInt(int64(coinType)), address)\n}", "func (r *registry) SetGuardianAddress(addr string) {\n\tr.mu.Lock()\n\tr.guardianAddress = addr\n\tr.mu.Unlock()\n}", "func SetAddress(net Addresser) {\n\taddress = net\n}", "func (a Vector) Set(b []float64) {\n\tcopy(a, b)\n}", "func (s *service) SetAddr(val string) {\n\n\ts.mu.Lock()\n\ts.addr = val\n\ts.mu.Unlock()\n}", "func insertPtr(b []byte, ptr uintptr) {\n\tswitch ptrOffset {\n\tcase 8:\n\t\tb[0] = byte(ptr >> 56)\n\t\tb[1] = byte(ptr >> 48)\n\t\tb[2] = byte(ptr >> 40)\n\t\tb[3] = byte(ptr >> 32)\n\t\tb[4] = byte(ptr >> 24)\n\t\tb[5] = byte(ptr >> 16)\n\t\tb[6] = byte(ptr >> 8)\n\t\tb[7] = byte(ptr)\n\t\treturn\n\tcase 4:\n\t\tb[0] = byte(ptr >> 24)\n\t\tb[1] = byte(ptr >> 16)\n\t\tb[2] = byte(ptr >> 8)\n\t\tb[3] = byte(ptr)\n\t\treturn\n\t}\n\tpanic(\"Invalid size detected\")\n}", "func (b *B) SetBytes(n int64) {}", "func (client *LANHostConfigManagement1) SetReservedAddress(NewReservedAddresses string) (err error) {\n\treturn client.SetReservedAddressCtx(context.Background(),\n\t\tNewReservedAddresses,\n\t)\n}", "func (r *Resolver) SetAddress(opts *bind.TransactOpts, address common.Address) (*types.Transaction, error) {\n\tnameHash, err := NameHash(r.domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Contract.SetAddr(opts, nameHash, address)\n}", "func (this *ValueTransaction) SetAddress(address trinary.Trytes) bool {\n\tthis.addressMutex.RLock()\n\tif this.address == nil || *this.address != address {\n\t\tthis.addressMutex.RUnlock()\n\t\tthis.addressMutex.Lock()\n\t\tdefer this.addressMutex.Unlock()\n\t\tif this.address == nil || *this.address != address {\n\t\t\tthis.address = &address\n\n\t\t\tthis.BlockHasher()\n\t\t\tcopy(this.trits[ADDRESS_OFFSET:ADDRESS_END], trinary.MustTrytesToTrits(address)[:ADDRESS_SIZE])\n\t\t\tthis.UnblockHasher()\n\n\t\t\tthis.SetModified(true)\n\t\t\tthis.ReHash()\n\n\t\t\treturn true\n\t\t}\n\t} else {\n\t\tthis.addressMutex.RUnlock()\n\t}\n\n\treturn false\n}", "func (_Contract *ContractSession) SetAddr(node [32]byte, coinType *big.Int, a []byte) (*types.Transaction, error) {\n\treturn _Contract.Contract.SetAddr(&_Contract.TransactOpts, node, coinType, a)\n}", "func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) }", "func main() {\n\ta := 1337\n\tfmt.Println(a) // 1337\n\tfmt.Println(&a) // MEMORY ADDRESS\n\n\t//CREATE A VAR b AND SET IT\n\t//TO TYPE \"INT POINTER\" AND\n\t//ASSIGN IT THE MEMORY ADDRESS OF a\n\tvar b *int = &a\n\n\t//PRINT OUT WHAT B IS\n\tfmt.Println(b) // SAME MEMORY ADDRESS AS a\n\t//*b = DEREFERENCING VAR A\n\t//IN THIS CASE IT IS THE VALUE OF a\n\tfmt.Println(*b) // 1337\n\n\t//UPDATE THE VALUE AT THIS ADDRESS\n\t*b = 1101110011110001\n\t//PRINT OUT VAR a WITH NEW VALUE\n\tfmt.Println(a)\n}", "func (c *Client) SetAddress(addr string) error {\n\tc.modifyLock.Lock()\n\tdefer c.modifyLock.Unlock()\n\n\tparsedAddr, err := c.config.ParseAddress(addr)\n\tif err != nil {\n\t\treturn errwrap.Wrapf(\"failed to set address: {{err}}\", err)\n\t}\n\n\tc.addr = parsedAddr\n\treturn nil\n}", "func (m *PrinterLocation) SetStreetAddress(value *string)() {\n err := m.GetBackingStore().Set(\"streetAddress\", value)\n if err != nil {\n panic(err)\n }\n}", "func (as *Addresses) Set(index int, value *Address) error {\n\tif index < 0 || index >= len(as.values) {\n\t\treturn errors.New(\"set: index out of range\")\n\t}\n\tas.values[index] = value.addr\n\treturn nil\n}", "func (c *Constraint) SlideJointSetAnchorB(anchorB Vect) {\n\tC.cpSlideJointSetAnchorB(\n\t\tc.c,\n\t\t*(*C.cpVect)(unsafe.Pointer(&anchorB)),\n\t)\n}", "func (b *B) SetBytes(n int64)", "func (_Contract *ContractTransactorSession) SetAddr(node [32]byte, coinType *big.Int, a []byte) (*types.Transaction, error) {\n\treturn _Contract.Contract.SetAddr(&_Contract.TransactOpts, node, coinType, a)\n}", "func (d *ModeDiff) setAddress(mode rune, address string) {\n\td.pos.setAddress(mode, address)\n\td.neg.unsetAddress(mode, address)\n}", "func (h *Hash) SetBytes(b []byte) {\n\tif len(*h) == len(b) {\n\t\tcopy(h[:], b[:HashSize])\n\t}\n}", "func (b *Block) SetValue(value []byte) {\n\tif !bytes.Equal(b.value, value) {\n\t\tb.value = value\n\t\t// copy(b.value, value)\n\t\tb.wire = []byte{}\n\t}\n}", "func (_e *MockDataCoord_Expecter) SetAddress(address interface{}) *MockDataCoord_SetAddress_Call {\n\treturn &MockDataCoord_SetAddress_Call{Call: _e.mock.On(\"SetAddress\", address)}\n}", "func (b *bgpserver) setAddresses() error {\n\t// pull existing\n\tconfiguredV4, _, err := b.ipLoopback.Get()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// get desired set VIP addresses\n\tdesired := []string{}\n\tfor ip, _ := range b.config.Config {\n\t\tdesired = append(desired, string(ip))\n\t}\n\n\tremovals, additions := b.ipLoopback.Compare4(configuredV4, desired)\n\tb.logger.Debugf(\"additions_v4=%v removals_v4=%v\", additions, removals)\n\tb.metrics.LoopbackAdditions(len(additions), addrKindIPV4)\n\tb.metrics.LoopbackRemovals(len(removals), addrKindIPV4)\n\tb.metrics.LoopbackTotalDesired(len(desired), addrKindIPV4)\n\tb.metrics.LoopbackConfigHealthy(1, addrKindIPV4)\n\n\tfor _, addr := range removals {\n\t\tb.logger.WithFields(logrus.Fields{\"device\": b.ipLoopback.Device(), \"addr\": addr, \"action\": \"deleting\"}).Info()\n\t\tif err := b.ipLoopback.Del(addr); err != nil {\n\t\t\tb.metrics.LoopbackRemovalErr(1, addrKindIPV4)\n\t\t\tb.metrics.LoopbackConfigHealthy(0, addrKindIPV4)\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, addr := range additions {\n\t\tb.logger.WithFields(logrus.Fields{\"device\": b.ipLoopback.Device(), \"addr\": addr, \"action\": \"adding\"}).Info()\n\t\tif err := b.ipLoopback.Add(addr); err != nil {\n\t\t\tb.metrics.LoopbackAdditionErr(1, addrKindIPV4)\n\t\t\tb.metrics.LoopbackConfigHealthy(0, addrKindIPV4)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func BytesToAddress(b []byte) (Address, error) {\n\tif len(b) > AddressLength {\n\t\treturn Address{}, AddressOverflowError\n\t}\n\tvar a Address\n\ta.SetBytes(b)\n\treturn a, nil\n}", "func (image *Image2D) SetB(x, y int, b uint8) {\n\tidx := image.getIdx(x, y)\n\timage.data[idx+2] = b\n}", "func (m *FlatMemory) StoreBytes(addr uint16, b []byte) {\n\tcopy(m.b[addr:], b)\n}", "func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) }", "func (o *VerifiableAddress) SetValue(v string) {\n\to.Value = v\n}", "func (b *BlockQueue) addAddress(address string, balance int64, tx *Tx) {\n\t\n\t// Add tx to address index\n\tif b.addrTx[address] == nil {\n\t\tb.addrTx[address] = queue.New()\n\t}\n\n\tb.addrTx[address] .PushBack(tx)\n\n\t// Update accumulated address balance\n\tnew_balance := b.addrBalance[address] + balance\n\tif new_balance == 0 {\n\t\tdelete(b.addrBalance, address)\n\t} else {\n\t\tb.addrBalance[address] = new_balance\n\t}\n}", "func (p *PublicKey) SetBytes(b []byte) {\n\tif len(b) > len(p) {\n\t\tb = b[len(b)-PublicKeyLength:]\n\t}\n\n\tcopy(p[PublicKeyLength-len(b):], b)\n}", "func (d *DataPacket) SetSyncAddress(sync uint16) {\n\td.replace(109, getAsBytes16(sync)[:])\n}", "func (_e *MockQueryCoord_Expecter) SetAddress(address interface{}) *MockQueryCoord_SetAddress_Call {\n\treturn &MockQueryCoord_SetAddress_Call{Call: _e.mock.On(\"SetAddress\", address)}\n}", "func (w *Wireguard) SetAddr(cidr string) error {\n\taddr, err := netlink.ParseAddr(cidr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := netlink.AddrAdd(w, addr); err != nil && !os.IsExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_ResolverContract *ResolverContractTransactor) SetAddr(opts *bind.TransactOpts, node [32]byte, addr common.Address) (*types.Transaction, error) {\n\treturn _ResolverContract.contract.Transact(opts, \"setAddr\", node, addr)\n}", "func addressFromBytes(b []byte) (Address, error) {\n\ta := Address{}\n\tkeyLen := len(a.Key)\n\tif len(b) != keyLen+len(a.Checksum)+1 {\n\t\treturn a, errors.New(\"Invalid address bytes\")\n\t}\n\tcopy(a.Key[:], b[:keyLen])\n\ta.Version = b[keyLen]\n\tcopy(a.Checksum[:], b[keyLen+1:])\n\tif !a.HasValidChecksum() {\n\t\treturn a, errors.New(\"Invalid checksum\")\n\t} else {\n\t\treturn a, nil\n\t}\n}", "func (m *BgpConfiguration) SetIpAddress(value *string)() {\n err := m.GetBackingStore().Set(\"ipAddress\", value)\n if err != nil {\n panic(err)\n }\n}", "func SetAuxAddress(addr string) func(*Server) error {\n\treturn func(s *Server) error {\n\t\ts.auxAddr = addr\n\t\treturn nil\n\t}\n}", "func BytesToAddress(b []byte) Address {\n\tvar a Address\n\ta.SetBytes(b)\n\treturn a\n}", "func (this *fixedSize) marshalTo(buf *bytes.Buffer /*, addrs map[uintptr]uint64*/) (err error) {\n\tbuf.Write((*[3384]byte)(unsafe.Pointer(this))[:])\n\treturn\n}", "func (b *Buffer) AttachBytes(buffer []byte, offset int, size int) {\n if len(buffer) < size {\n panic(\"invalid buffer\")\n }\n if size <= 0 {\n panic(\"invalid size\")\n }\n if offset > size {\n panic(\"invalid offset\")\n }\n\n b.data = buffer\n b.size = size\n b.offset = offset\n}", "func (h *Hash) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-HashLength:]\n\t}\n\n\tcopy(h[HashLength-len(b):], b)\n}", "func (h *Hash) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-HashLength:]\n\t}\n\n\tcopy(h[HashLength-len(b):], b)\n}", "func (h *Hash) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-HashLength:]\n\t}\n\n\tcopy(h[HashLength-len(b):], b)\n}", "func (m *MuxedAccount) SetAddress(address string) error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tswitch len(address) {\n\tcase 56:\n\t\treturn m.SetEd25519Address(address)\n\tcase 69:\n\t\traw, err := strkey.Decode(strkey.VersionByteMuxedAccount, address)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(raw) != 40 {\n\t\t\treturn fmt.Errorf(\"invalid binary length: %d\", len(raw))\n\t\t}\n\t\tvar muxed MuxedAccountMed25519\n\t\tcopy(muxed.Ed25519[:], raw[:32])\n\t\tif err = muxed.Id.UnmarshalBinary(raw[32:]); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*m, err = NewMuxedAccount(CryptoKeyTypeKeyTypeMuxedEd25519, muxed)\n\t\treturn err\n\tdefault:\n\t\treturn errors.New(\"invalid address length\")\n\t}\n\n}", "func (h *Hash32) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-32:]\n\t}\n\n\tcopy(h[32-len(b):], b)\n}", "func (_ResolverContract *ResolverContractSession) SetMultiaddr(node [32]byte, multiaddr []byte) (*types.Transaction, error) {\n\treturn _ResolverContract.Contract.SetMultiaddr(&_ResolverContract.TransactOpts, node, multiaddr)\n}", "func (r *RTNL) SetAddr(iface int, a net.IPNet) error {\n\tif err := r.init(); err != nil {\n\t\treturn err\n\t}\n\tones, _ := a.Mask.Size()\n\tmsg := rtnetlink.AddressMessage{\n\t\tFamily: uint8(getFamily(a.IP)),\n\t\tPrefixLength: uint8(ones),\n\t\t// TODO detect the right scope to set, or get it as input argument\n\t\tScope: unix.RT_SCOPE_UNIVERSE,\n\t\tIndex: uint32(iface),\n\t\tAttributes: rtnetlink.AddressAttributes{\n\t\t\tAddress: a.IP,\n\t\t\tLocal: a.IP,\n\t\t},\n\t}\n\tif a.IP.To4() != nil {\n\t\t// Broadcast is only required for IPv4\n\t\tip := make(net.IP, net.IPv4len)\n\t\tbinary.BigEndian.PutUint32(\n\t\t\tip,\n\t\t\tbinary.BigEndian.Uint32(a.IP.To4())|\n\t\t\t\t^binary.BigEndian.Uint32(net.IP(a.Mask).To4()))\n\t\tmsg.Attributes.Broadcast = ip\n\t}\n\tif err := r.conn.Address.New(&msg); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (k *Keypair) SetBytes(b []byte) (*Keypair, error) {\n\tif len(b) != 96 {\n\t\treturn nil, fmt.Errorf(\"invalid input size\")\n\t}\n\n\tvar (\n\t\tpub PubKey\n\t\tpriv PrivKey\n\t)\n\n\tcopy(pub[:], b[:32])\n\tcopy(priv[:], b[32:])\n\n\ttd := make([]byte, 32)\n\trand.Read(td)\n\tsig := Sign(&priv, td)\n\tif !Verify(&pub, td, sig) {\n\t\treturn nil, fmt.Errorf(\"invalid keypair\")\n\t}\n\n\tk.priv = priv\n\tk.pub = pub\n\treturn k, nil\n}", "func (m *User) SetStreetAddress(value *string)() {\n m.streetAddress = value\n}", "func (h *Hash20) SetBytes(b []byte) {\n\tif len(b) > len(h) {\n\t\tb = b[len(b)-32:]\n\t}\n\n\tcopy(h[32-len(b):], b)\n}", "func (b IPv6Fragment) SetDestinationAddress(tcpip.Address) {\n\tpanic(\"not supported\")\n}", "func (m *FlatMemory) LoadAddress(addr uint16) uint16 {\n\tif (addr & 0xff) == 0xff {\n\t\treturn uint16(m.b[addr]) | uint16(m.b[addr-0xff])<<8\n\t}\n\treturn uint16(m.b[addr]) | uint16(m.b[addr+1])<<8\n}", "func (_ResolverContract *ResolverContractTransactorSession) SetMultiaddr(node [32]byte, multiaddr []byte) (*types.Transaction, error) {\n\treturn _ResolverContract.Contract.SetMultiaddr(&_ResolverContract.TransactOpts, node, multiaddr)\n}", "func SetServerAddress(address string) ServerOptions {\n\treturn func(s *Server) error {\n\t\tif err := util.CheckTCPAddress(address); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.address = address\n\t\treturn nil\n\t}\n}", "func (s *server) Address(a string) Server {\n\ts.address = a\n\treturn s\n}", "func (mt *mockTokenBuilder) SetIPAddress(ip string) {\n\t//TODO some mocking\n}", "func (v *Virtual) SetVirtualAddress(bindAddr string, port int32) {\n\tv.Destination = \"\"\n\tif bindAddr == \"\" && port == 0 {\n\t\tv.VirtualAddress = nil\n\t} else {\n\t\tv.VirtualAddress = &virtualAddress{\n\t\t\tBindAddr: bindAddr,\n\t\t\tPort: port,\n\t\t}\n\t\t// Validate the IP address, and create the destination\n\t\tip, rd := split_ip_with_route_domain(bindAddr)\n\t\tif len(rd) > 0 {\n\t\t\trd = \"%\" + rd\n\t\t}\n\t\taddr := net.ParseIP(ip)\n\t\tif nil != addr {\n\t\t\tvar format string\n\t\t\tif nil != addr.To4() {\n\t\t\t\tformat = \"/%s/%s%s:%d\"\n\t\t\t} else {\n\t\t\t\tformat = \"/%s/%s%s.%d\"\n\t\t\t}\n\t\t\tv.Destination = fmt.Sprintf(format, v.Partition, ip, rd, port)\n\t\t}\n\t}\n}", "func (v *Txn) Setb(json []byte) (resp *api.Assigned, err error) {\n\treturn v.Mutate(&api.Mutation{\n\t\tSetJson: json,\n\t})\n}", "func Replace(a, b interface{}) error {\n\tvb := reflect.ValueOf(b).Elem()\n\tfor i := 0; i < vb.NumField(); i++ {\n\t\tfield := vb.Field(i)\n\t\tif field.CanInterface() && IsZeroOfUnderlyingType(field.Interface()) {\n\t\t\tname := vb.Type().Field(i).Name\n\t\t\tfa := reflect.ValueOf(a).FieldByName(name)\n\t\t\tif fa.IsValid() {\n\t\t\t\tif field.CanSet() {\n\t\t\t\t\tfield.Set(fa)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (b *Bound) Set(west, east, south, north float64) {\n\tb.sw[0] = west\n\tb.sw[1] = south\n\n\tb.ne[0] = east\n\tb.ne[1] = north\n}", "func (p *Pinger) SetAddr(addr string) error {\n\toldAddr := p.addr\n\tp.addr = addr\n\terr := p.Resolve()\n\tif err != nil {\n\t\tp.addr = oldAddr\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Passwords) Set(a interface{}, password string) error {\n\t// generate a salt\n\tsalt, err := s.Config.GenSalt()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// compute derived key which we call \"hash\"\n\thash, err := s.Config.HashPassword([]byte(password), salt)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// encode config, salt and hash\n\tdata := s.Config.Encode(salt, hash)\n\treturn s.SetAccountPasswordData(a, data)\n}", "func (b *ByteSlice) Set(v []byte) {\n\tif v == nil {\n\t\tb.ByteSlice = nil\n\t\tb.Valid = false\n\t\treturn\n\t}\n\t// Make sure Set initializes null ByteSlices.\n\t// If b.ByteSlice is nil and len(v) == 0, b.ByteSlice would remain nil. We\n\t// don't want to that.\n\tif !b.Valid {\n\t\tb.ByteSlice = []byte{}\n\t\tb.Valid = true\n\t}\n\tb.ByteSlice = append(b.ByteSlice[0:0], v...)\n\tb.Valid = true\n}", "func limitAddress(a uint32) uint32 {\n\treturn a & 0x0003\n}", "func SetAddressVersion(name string) {\n\taddressVersion = MustVersionByName(name)\n\t//logger.Debug(\"Set address version to %s\", name)\n}", "func (m *FlatMemory) LoadBytes(addr uint16, b []byte) {\n\tif int(addr)+len(b) <= len(m.b) {\n\t\tcopy(b, m.b[addr:])\n\t} else {\n\t\tr0 := len(m.b) - int(addr)\n\t\tr1 := len(b) - r0\n\t\tcopy(b, m.b[addr:])\n\t\tcopy(b[r0:], make([]byte, r1))\n\t}\n}", "func (_ BufferPtrPool512) Put(b *[]byte) {\n\tPutBytesSlicePtr512(b)\n}", "func (_BaseLibrary *BaseLibraryTransactor) SetAddressKMS(opts *bind.TransactOpts, address_KMS common.Address) (*types.Transaction, error) {\n\treturn _BaseLibrary.contract.Transact(opts, \"setAddressKMS\", address_KMS)\n}", "func (du *DoctorUpdate) SetAddress(s string) *DoctorUpdate {\n\tdu.mutation.SetAddress(s)\n\treturn du\n}", "func (d *Device1Receiver) SetB(b int) {\n\td.b = b\n}", "func main() {\n\tvar a = 5\n\tvar ptrA = &a\n\n\tvar b = 3\n\tvar ptrB = &b\n\n\tfmt.Println(a, b)\n\n\tswap(ptrA, ptrB)\n\n\tfmt.Println(a, b)\n}", "func (b IPv6Fragment) SetSourceAddress(tcpip.Address) {\n\tpanic(\"not supported\")\n}", "func (b *BlockQueue)blockUpdateAddress(block *Block, reverse bool) {\n\t\n\tfor _, tx := range block.Transactions {\n\t\tif reverse {\n\t\t\ttx.ForEachAddress(b.delAddress)\n\t\t} else {\n\t\t\ttx.ForEachAddress(b.addAddress)\n\t\t}\n\t}\n}", "func (uc *UserCreate) SetAddress(s string) *UserCreate {\n\tuc.mutation.SetAddress(s)\n\treturn uc\n}", "func (l *Link) Set(x *Link) *Link {\n\til := (*big.Int)(l)\n\tix := (*big.Int)(x)\n\n\tw := il.Set(ix)\n\treturn (*Link)(w)\n}", "func (uu *UserUpdate) SetAddress(s string) *UserUpdate {\n\tuu.mutation.SetAddress(s)\n\treturn uu\n}" ]
[ "0.61116755", "0.5422969", "0.5313864", "0.52743495", "0.52538496", "0.5247057", "0.5244366", "0.5223461", "0.5209904", "0.5203097", "0.51277965", "0.51088876", "0.5108626", "0.5082703", "0.50706017", "0.49597877", "0.49350923", "0.49285477", "0.49117425", "0.48942706", "0.4894262", "0.48831168", "0.48529", "0.48350453", "0.4799328", "0.4793619", "0.47907272", "0.47887397", "0.477619", "0.47728938", "0.4771902", "0.47709605", "0.4759956", "0.4757898", "0.4740264", "0.47281146", "0.47150347", "0.47062075", "0.46987516", "0.4692977", "0.46909177", "0.46654102", "0.46293995", "0.46083778", "0.46072808", "0.46032432", "0.45884818", "0.45859516", "0.45771638", "0.45770934", "0.45708388", "0.45554978", "0.4538224", "0.4535874", "0.45324528", "0.45250052", "0.45082313", "0.45078337", "0.45075274", "0.44979802", "0.44949943", "0.44890776", "0.44890776", "0.44890776", "0.4487239", "0.44860297", "0.44850472", "0.4482597", "0.44698912", "0.44697312", "0.4469277", "0.44626695", "0.44481966", "0.4443179", "0.44419992", "0.44303423", "0.44297203", "0.44290048", "0.44284236", "0.44278944", "0.44261593", "0.44199738", "0.44189125", "0.4418732", "0.4408962", "0.44070497", "0.43944016", "0.4392901", "0.4378233", "0.43734822", "0.43676215", "0.43663812", "0.4351776", "0.43494415", "0.43486202", "0.4348431", "0.43480968" ]
0.6082643
3
Hex returns an EIP55compliant hex string representation of the address.
func (a Address) Hex() string { unchecksummed := hex.EncodeToString(a[:]) sha := sha3.NewKeccak256() sha.Write([]byte(unchecksummed)) hash := sha.Sum(nil) result := []byte(unchecksummed) for i := 0; i < len(result); i++ { hashByte := hash[i/2] if i%2 == 0 { hashByte = hashByte >> 4 } else { hashByte &= 0xf } if result[i] > '9' && hashByte > 7 { result[i] -= 32 } } return "0x" + string(result) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a Address) Hex() string {\n\treturn fmt.Sprintf(\"%x\", a[:])\n}", "func (a Address) Hex() string {\n\treturn hex.EncodeToString(a.Bytes())\n}", "func (addr *Address) Hex() string {\n\tvar format = \"0x%s\"\n\thexStr := strings.ToUpper(big.NewInt(0).SetBytes(addr.Payload).Text(16))\n\n\t// Prepend a zero\n\tif len(hexStr)%2 == 1 {\n\t\tformat = \"0x0%s\"\n\t}\n\n\treturn fmt.Sprintf(format, hexStr)\n}", "func (a Address) Hex() string {\n\tunchecksummed := hex.EncodeToString(a[:])\n\tsha := sha3.NewLegacyKeccak256()\n\tsha.Write([]byte(unchecksummed))\n\thash := sha.Sum(nil)\n\n\tresult := []byte(unchecksummed)\n\tfor i := 0; i < len(result); i++ {\n\t\thashByte := hash[i/2]\n\t\tif i%2 == 0 {\n\t\t\thashByte = hashByte >> 4\n\t\t} else {\n\t\t\thashByte &= 0xf\n\t\t}\n\t\tif result[i] > '9' && hashByte > 7 {\n\t\t\tresult[i] -= 32\n\t\t}\n\t}\n\treturn \"0x\" + strings.ToLower(string(result))\n}", "func (id ID) AddressHex() string {\n\treturn hex.EncodeToString(id.EthAddress)\n}", "func (a Address) String() string {\n\tbech32Addr, err := bech32.Encode(AddressBech32HRP.String(), a[:])\n\tif err != nil {\n\t\treturn \"[malformed]\"\n\t}\n\treturn bech32Addr\n}", "func (a Address) String() string {\n\treturn a.Hex()\n}", "func (n *Machine) HexAddress() string {\n\treturn Hexaddr(n.Address)\n}", "func (extEthCompatAddress ExtEthCompatAddress) String() string {\n\treturn hex.EncodeToString(extEthCompatAddress[:])\n}", "func (a *Address) ToHex() string {\n\treturn \"0x\" + hex.EncodeToString(a.addr.Bytes())\n}", "func (a Address) String() string {\n\treturn fmt.Sprintf(\"0x%X\", uint64(a))\n}", "func (a Address) String() string {\n\tsn := uint64(0x00ffffffffffff00&a) >> 8\n\tcrc := uint64(a & 0xff)\n\treturn fmt.Sprintf(\"%02x.%012x.%02x\", a.Family(), sn, crc)\n}", "func (b Beacon) Hex() string { return util.Encode(b[:]) }", "func (h Hash20) Hex() string { return util.Encode(h[:]) }", "func encodeAddress(hash160 []byte, netID [2]byte) string {\n\t// Format is 2 bytes for a network and address class (i.e. P2PKH vs\n\t// P2SH), 20 bytes for a RIPEMD160 hash, and 4 bytes of checksum.\n\treturn base58.CheckEncode(hash160[:ripemd160.Size], netID)\n}", "func (h Hash32) Hex() string { return util.Encode(h[:]) }", "func (f Fingerprint) Hex() string {\n\tf.assertIsSet()\n\tb := f.fingerprintBytes\n\n\treturn fmt.Sprintf(\"%0X\", b)\n}", "func (address ICAOAddress) ToString() string {\n\treturn fmt.Sprintf(\"%02X %02X %02X \",\n\t\tbyte((address&0x00FF0000)>>16),\n\t\tbyte((address&0x0000FF00)>>8),\n\t\tbyte(address&0x000000FF))\n}", "func withHexPrefix(address string) string {\n\tif address == \"\" {\n\t\treturn \"\"\n\t}\n\n\tif address[0:2] == \"0x\" {\n\t\treturn address\n\t}\n\n\treturn fmt.Sprintf(\"0x%s\", address)\n}", "func (n Name) Hex() string {\n\treturn hex.EncodeToString([]byte(n))\n}", "func Hex(n int) string { return String(n, HexChars) }", "func (a Address) ToString() string {\n\treturn base64.StdEncoding.EncodeToString(a)\n}", "func (this UUID) Hex() string {\n\tx := [16]byte(this)\n\treturn fmt.Sprintf(\"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\",\n\t\tx[0], x[1], x[2], x[3], x[4],\n\t\tx[5], x[6],\n\t\tx[7], x[8],\n\t\tx[9], x[10], x[11], x[12], x[13], x[14], x[15])\n\n}", "func Hex(n int) string {\n\treturn fmt.Sprintf(\"0x%x\", n)\n}", "func (self *Address) String() string {\n\treturn string(base58.Hex2Base58(self.Bytes()))\n}", "func Address(pub *ecdsa.PublicKey, compressed, testnet bool) string {\n\t// this is the raw (non-encoded) bitcoin address\n\tvar netPkHashCheck [25]byte\n\tif compressed {\n\t\tsrc := hash.Hash160(pub.MarshalCompressed())\n\t\tcopy(netPkHashCheck[1:21], src[:])\n\t} else {\n\t\tsrc := hash.Hash160(pub.Marshal())\n\t\tcopy(netPkHashCheck[1:21], src[:])\n\t}\n\tif testnet {\n\t\tnetPkHashCheck[0] = 0x6f\n\t} else {\n\t\tnetPkHashCheck[0] = 0x00\n\t}\n\n\t// calculate the checksum\n\tchecksum := hash.Hash256(netPkHashCheck[:21])\n\tcopy(netPkHashCheck[21:], checksum[:4])\n\n\t// encode in base58 and return\n\treturn base58encode(netPkHashCheck[:])\n}", "func Hex(n int) (ss string, err error) {\n\tbs, err := Bytes(n)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tss = hex.EncodeToString(bs)\n\n\treturn\n}", "func (h Hash) Hex() string { return hexutil.Encode(h[:]) }", "func (addr *Address) Encode() (string, error) {\n\tripe := addr.Ripe[:]\n\n\tswitch addr.Version {\n\tcase 2:\n\t\tfallthrough\n\tcase 3:\n\t\tif ripe[0] == 0x00 {\n\t\t\tripe = ripe[1:] // exclude first byte\n\t\t\tif ripe[0] == 0x00 {\n\t\t\t\tripe = ripe[1:] // exclude second byte as well\n\t\t\t}\n\t\t}\n\tcase 4:\n\t\tripe = bytes.TrimLeft(ripe, \"\\x00\")\n\tdefault:\n\t\treturn \"\", errors.New(\"unsupported address version\")\n\t}\n\n\tvar binaryData bytes.Buffer\n\tbinaryData.Write(addr.Version.Serialize())\n\tbinaryData.Write(addr.Stream.Serialize())\n\tbinaryData.Write(ripe)\n\n\tsha := sha512.New()\n\tsha.Write(binaryData.Bytes())\n\tcurrentHash := sha.Sum(nil) // calc hash\n\tsha.Reset() // reset hash\n\tsha.Write(currentHash)\n\tchecksum := sha.Sum(nil)[:4] // calc checksum from another round of SHA512\n\n\ttotalBin := append(binaryData.Bytes(), checksum...)\n\n\ti := new(big.Int).SetBytes(totalBin)\n\treturn \"BM-\" + string(base58.EncodeBig(nil, i)), nil // done\n}", "func HexadecimalString(length int) string {\n\treturn StringWithCharset(length, hexadecimalCharset)\n}", "func HexToAddress(s string) types.Address { return BytesToAddress(FromHex(s)) }", "func (d Digest) Hex() string {\n\treturn d.hex\n}", "func (r Register) Hex() string {\n\tvar buf bytes.Buffer\n\tfmt.Fprintf(&buf, \"0x%.8X\", int32(r))\n\treturn buf.String()\n}", "func Hex(data []byte) string {\n\treturn fmt.Sprintf(\"%x\", data)\n}", "func (id GID) Hex() string {\n\treturn hex.EncodeToString(id)\n}", "func (sid SpanID) HexString() string {\n\tif sid.IsEmpty() {\n\t\treturn \"\"\n\t}\n\treturn hex.EncodeToString(sid.id[:])\n}", "func hex(bytes []byte) string {\n\t// return number of spaces to print based on i's position in slice s\n\tspaces := func(s []byte, i int) int {\n\t\tif i == len(s)-1 {\n\t\t\treturn 0\n\t\t}\n\t\tif (i+1)%4 == 0 {\n\t\t\treturn 2\n\t\t}\n\t\treturn 1\n\t}\n\n\tsb := strings.Builder{}\n\tfor i := range bytes {\n\t\tfmt.Fprintf(&sb, \"%02x%*s\", bytes[i], spaces(bytes, i), \"\")\n\t}\n\treturn sb.String()\n}", "func Hex(value interface{}) (string, error) {\n\tswitch v := value.(type) {\n\tcase Hexer:\n\t\treturn v.Hex(), nil\n\tcase []byte:\n\t\treturn fmt.Sprintf(\"%#x\", v), nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"does not support %T\", v)\n\t}\n}", "func (z *Int) Hex() string {\n\treturn fmt.Sprintf(\"%016x.%016x.%016x.%016x\", z[3], z[2], z[1], z[0])\n}", "func EncodeToHex(value interface{}) (string, error) {\n\tbz, err := Encode(value)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%#x\", bz), nil\n}", "func hex(num uint) string {\r\n\ttemp := []byte{'0', '0', '0', '0', '0', '0'}\r\n\r\n\tfor counter := 0; num > 0; counter++ {\r\n\t\tn := uint8(num & 0xF)\r\n\t\tif n < 10 {\r\n\t\t\ttemp[5-counter] = '0' + n\r\n\t\t} else {\r\n\t\t\ttemp[5-counter] = ('A' - 10) + n\r\n\t\t}\r\n\r\n\t\tnum >>= 4\r\n\t}\r\n\r\n\treturn string(temp)\r\n}", "func (w *Wallet) Address() []byte {\n\tpubKeyHash := HashPubKey(w.PubKey)\n\n\tversionedPubKeyHash := append([]byte{version}, pubKeyHash...)\n\tchecksum := checksum(versionedPubKeyHash)\n\n\treturn Base58Encode(append(versionedPubKeyHash, checksum...))\n}", "func (b Bytes) HexStr(noPrefix ...bool) string { return ToHex(b.Bytes(), noPrefix...) }", "func (pk PublicKey) Hex() string {\n\treturn ToHex(pk.Bytes())\n}", "func (addr BitcoinAddress) String() string {\n\treturn string(base58.Encode(addr.Bytes()))\n}", "func (a *Address) String() string {\n\treturn types.AccAddress(a.PubKey.Address().Bytes()).String()\n}", "func BitcoinAddress() string {\n\treturn RandomString([]string{\"1\", \"3\"}) + Password(true, true, true, false, false, Number(25, 34))\n}", "func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) }", "func (a *Address) String() string {\n\tbuf := bytes.NewBufferString(\"\")\n\tif a.LocalPart != \"\" {\n\t\tbuf.WriteString(a.LocalPart)\n\t\tbuf.WriteString(\"@\")\n\t}\n\n\tbuf.WriteString(a.DomainPart)\n\n\tif a.ResourcePart != \"\" {\n\t\tbuf.WriteString(\"/\")\n\t\tbuf.WriteString(a.ResourcePart)\n\t}\n\n\treturn buf.String()\n}", "func (addr *Address) Encode() (string, error) {\n\tripe := addr.Ripe[:]\n\n\tswitch addr.Version {\n\tcase 2:\n\t\tfallthrough\n\tcase 3:\n\t\tif ripe[0] == 0x00 {\n\t\t\tripe = ripe[1:] // exclude first byte\n\t\t\tif ripe[0] == 0x00 {\n\t\t\t\tripe = ripe[1:] // exclude second byte as well\n\t\t\t}\n\t\t}\n\tcase 4:\n\t\tripe = bytes.TrimLeft(ripe, \"\\x00\")\n\tdefault:\n\t\treturn \"\", ErrUnknownAddressType\n\t}\n\n\tif len(ripe) > 19 {\n\t\treturn \"\", errors.New(\"improper ripe, doesn't have null bytes in front\")\n\t}\n\n\tvar binaryData bytes.Buffer\n\tWriteVarInt(&binaryData, addr.Version)\n\tWriteVarInt(&binaryData, addr.Stream)\n\tbinaryData.Write(ripe)\n\n\t// calc checksum from 2 rounds of SHA512\n\tchecksum := DoubleSha512(binaryData.Bytes())[:4]\n\n\ttotalBin := append(binaryData.Bytes(), checksum...)\n\n\treturn \"BM-\" + string(base58.Encode(totalBin)), nil // done\n}", "func (fa TestAddr) String() string { return fa.Addr }", "func (a Address) String() string {\n\treturn fmt.Sprintf(\"%s:%d\", a.Address, a.Port)\n}", "func (id ID) Hex() string {\n\treturn hex.EncodeToString(id[:])\n}", "func IsHexAddress(s string) bool {\n\tif HasHexPrefix(s) {\n\t\ts = s[2:]\n\t}\n\treturn len(s) == 2*AddressLength && IsHex(s)\n}", "func (t TraceID) HexString() string {\n\treturn data.TraceID(t).HexString()\n}", "func (b Beacon) String() string { return b.Hex() }", "func (a Addr) String() string {\n\tvar host, port string\n\n\tswitch a[0] { // address type\n\tcase AtypIPv4:\n\t\thost = net.IP(a[1 : 1+net.IPv4len]).String()\n\t\tport = strconv.Itoa((int(a[1+net.IPv4len]) << 8) | int(a[1+net.IPv4len+1]))\n\tcase AtypDomainName:\n\t\thost = string(a[2 : 2+int(a[1])])\n\t\tport = strconv.Itoa((int(a[2+int(a[1])]) << 8) | int(a[2+int(a[1])+1]))\n\tcase AtypIPv6:\n\t\thost = net.IP(a[1 : 1+net.IPv6len]).String()\n\t\tport = strconv.Itoa((int(a[1+net.IPv6len]) << 8) | int(a[1+net.IPv6len+1]))\n\t}\n\n\treturn net.JoinHostPort(host, port)\n}", "func getAddress(str []byte) (address string){\n\thash :=userlib.NewSHA256()\n\thash.Write(str)\n\taddress = hex.EncodeToString(hash.Sum(nil))\n\treturn\n}", "func (b Bytes32) HexStr() string {\n\treturn ToHex(b.Bytes())\n}", "func (w Wallet) Address() []byte {\n\tripemd160 := PublicKeyHash(w.PublicKey)\n\n\tversionedRimpemd160 := append([]byte{version}, ripemd160...)\n\tchecksum := CheckSumSlice(versionedRimpemd160)\n\n\tfullHash := append(versionedRimpemd160, checksum...)\n\taddress := Base58Encode(fullHash)\n\n\treturn address\n}", "func (a *AddressScriptHash) EncodeAddress() string {\n\treturn EncodeAddressFromH160(a.hash[:], a.magic)\n}", "func (a L3n4Addr) Hash() string {\n\tconst lenProto = 0 // proto is omitted for now\n\tconst lenScope = 1 // scope is uint8 which is an alias for byte\n\tconst lenPort = 2 // port is uint16 which is 2 bytes\n\n\tb := make([]byte, cmtypes.AddrClusterLen+lenProto+lenScope+lenPort)\n\tac20 := a.AddrCluster.As20()\n\tcopy(b, ac20[:])\n\t// FIXME: add Protocol once we care about protocols\n\t// scope is a uint8 which is an alias for byte so a cast is safe\n\tb[net.IPv6len+lenProto] = byte(a.Scope)\n\t// port is a uint16, so 2 bytes\n\tb[net.IPv6len+lenProto+lenScope] = byte(a.Port >> 8)\n\tb[net.IPv6len+lenProto+lenScope+1] = byte(a.Port & 0xff)\n\treturn string(b)\n}", "func (c Hex) Hex() string {\n\treturn c.Code\n}", "func uint32StrHex(u uint32) string {\n\tstr := fmt.Sprintf(\"%x\", u)\n\t// Add a 0 to the start of odd-length string. This converts \"0x1AB\" to \"0x01AB\"\n\tif (len(str) % 2) != 0 {\n\t\tstr = \"0\" + str\n\t}\n\treturn \"0x\" + str\n}", "func str2hex(text string) string {\n\n\thasher := md5.New()\n\thasher.Write([]byte(text))\n\n\tenc := hex.EncodeToString(hasher.Sum(nil))\n\tcode := enc[0:6]\n\n\treturn fmt.Sprintf(\"#%s\", code)\n}", "func (color *Color) Hex() string {\n\thexColor := colorful.LinearRgb(\n\t\tfloat64(color.R)/255,\n\t\tfloat64(color.G)/255,\n\t\tfloat64(color.B)/255,\n\t)\n\treturn hexColor.Hex()\n}", "func intr2hex (i int) string {\n d:= fmt.Sprintf(\"0x%02x\", i)\n return d\n}", "func (tx *Tx) Hex() string {\n\treturn hex.EncodeToString(tx.Bytes())\n}", "func (h PublicKey) Hex() string { return strings.ToLower(hex.EncodeToString(h[:])) }", "func (a *AddressPubKeyHash) String() string {\n\treturn a.EncodeAddress()\n}", "func GetAddrFormat(addr string) string {\n\treturn fmt.Sprintf(\"%021s\", addr)\n}", "func Hex(v uint64) string {\n\tcstr := C.malloc(17)\n\tdefer C.free(unsafe.Pointer(cstr)) // #nosec\n\tC.variantkey_hex(C.uint64_t(v), (*C.char)(cstr))\n\treturn C.GoStringN((*C.char)(cstr), C.int(16))\n}", "func hex(buf []byte) string {\n\tconst hexa = \"0123456789abcdef\"\n\tres := make([]byte, len(buf)*2)\n\tfor i, b := range buf {\n\t\tres[i*2] = hexa[b>>4]\n\t\tres[i*2+1] = hexa[b&0x0f]\n\t}\n\treturn string(res)\n}", "func (s Snowflake) HexString() string {\n\treturn strconv.FormatUint(uint64(s), 16)\n}", "func (a Address) String() string {\n\treturn string(a)\n}", "func (s StorageDataRaw) Hex() string {\n\treturn fmt.Sprintf(\"%#x\", s)\n}", "func (a Address) StreetAddress() string {\n\t// ATM, USPS standard is used. Maybe, we need to take into count Country's specifics.\n\tb := strings.Builder{}\n\tb.WriteString(a.BuildingNumber)\n\tif len(a.Street) > 0 {\n\t\tif b.Len() > 0 {\n\t\t\tb.WriteString(\" \")\n\t\t}\n\t\tb.WriteString(a.Street)\n\t}\n\n\treturn b.String()\n}", "func HexStringOfBytes(ar []byte) string {\n\treturn fmt.Sprintf(\"%0X\", ar)\n}", "func HexString(length int) string {\n\treturn generateString(length, hexAlphabet)\n}", "func (a Address) Hash() Hash { return BytesToHash(a[:]) }", "func Hash20Hex(v []byte) string {\n\treturn hex.EncodeToString(Hash20(v))\n}", "func (addr Address) String() string {\n\treturn fmt.Sprintf(\"/%v/%v/%v/%v\", addr.Protocol, addr.Value, addr.Nonce, addr.Signature)\n}", "func GetAddress(h *string, p *int) string {\n\treturn *h + \":\" + strconv.FormatUint(uint64(*p), 10)\n}", "func (b *Buffer) ToStringHex() string {\n\treturn hex.EncodeToString(b.b)\n}", "func (address Address) String() string {\n\tswitch address.Type {\n\tcase TypeIPv4, TypeIPv6:\n\t\treturn net.JoinHostPort(address.IP.String(), strconv.Itoa(int(address.Port)))\n\n\tcase TypeDomain:\n\t\treturn net.JoinHostPort(address.Host, strconv.Itoa(int(address.Port)))\n\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func HexToAddress(h string) Address {\n\ttrimmed := strings.TrimPrefix(h, \"0x\")\n\tif len(trimmed)%2 == 1 {\n\t\ttrimmed = \"0\" + trimmed\n\t}\n\tb, _ := hex.DecodeString(trimmed)\n\treturn BytesToAddress(b)\n}", "func formatAddress(ctx *snow.Context, addr ids.ShortID) (string, error) {\n\tchainIDAlias, err := ctx.BCLookup.PrimaryAlias(ctx.ChainID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thrp := constants.GetHRP(ctx.NetworkID)\n\treturn address.Format(chainIDAlias, hrp, addr.Bytes())\n}", "func hex(data []byte) string {\n\tbuf := make([]byte, 4*len(data))\n\tconst digits = \"0123456789abcdef\"\n\tfor i, b := range data {\n\t\tbuf[i*4] = '\\\\'\n\t\tbuf[(i*4)+1] = 'x'\n\t\tbuf[(i*4)+2] = digits[b>>4]\n\t\tbuf[(i*4)+3] = digits[b&0x0F]\n\t}\n\treturn string(buf)\n}", "func (a Address) String() string { return string(a) }", "func EncodeELA(base uint16) string {\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(fmt.Sprintf(\":020000%02X%04X\", int(ExtendedLinearAddress), base))\n\traw := []byte{byte(base & 0xff00 >> 8), byte(base & 0x00ff)}\n\tcs := createChecksum(raw, 0, ExtendedLinearAddress)\n\tbuf.WriteString(fmt.Sprintf(\"%02X\", cs))\n\treturn buf.String()\n}", "func EncodeELA(base uint16) string {\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(fmt.Sprintf(\":020000%02X%04X\", int(ExtendedLinearAddress), base))\n\traw := []byte{byte(base & 0xff00 >> 8), byte(base & 0x00ff)}\n\tcs := createChecksum(raw, 0, ExtendedLinearAddress)\n\tbuf.WriteString(fmt.Sprintf(\"%02X\", cs))\n\treturn buf.String()\n}", "func (addr DevAddr) String() string {\n\tif addr.IsEmpty() {\n\t\treturn \"\"\n\t}\n\treturn strings.ToUpper(hex.EncodeToString(addr.Bytes()))\n}", "func (a *Address) String() string {\n\treturn a.addr\n}", "func (pubKey PubKeyEd25519) Address() []byte {\n\tw, n, err := new(bytes.Buffer), new(int64), new(error)\n\twire.WriteBinary(pubKey[:], w, n, err)\n\tif *err != nil {\n\t\tPanicCrisis(*err)\n\t}\n\t// append type byte\n\tencodedPubkey := append([]byte{1}, w.Bytes()...)\n\thasher := ripemd160.New()\n\thasher.Write(encodedPubkey) // does not error\n\treturn hasher.Sum(nil)\n}", "func (a UnresolvedAddr) String() string {\n\treturn a.AddressField\n}", "func (a *AddressScriptHash) String() string {\n\treturn a.EncodeAddress()\n}", "func (v *VCard) StreetAddress() string {\n\treturn v.getFirstAddressField(2)\n}", "func (id ObjectId) Hex() string {\n\treturn hex.EncodeToString([]byte(id))\n}", "func BigIntToHexStr(i *big.Int) string {\n\th := i.Text(16)\n\tif len(h)%2 == 1 {\n\t\th = \"0\" + h // make sure that the length is even\n\t}\n\treturn \"0x\" + h\n}" ]
[ "0.7553822", "0.74404615", "0.73742026", "0.713287", "0.7079945", "0.69498605", "0.6869245", "0.68466544", "0.683117", "0.6828471", "0.6741587", "0.663839", "0.64232194", "0.6412231", "0.62632865", "0.62215394", "0.62165624", "0.61880445", "0.6133213", "0.6107497", "0.6101739", "0.6100058", "0.6083638", "0.60392255", "0.59909993", "0.5969865", "0.5899776", "0.58733505", "0.58716077", "0.5839121", "0.5823854", "0.5788443", "0.5786509", "0.5758398", "0.5751175", "0.5747082", "0.5745854", "0.5744719", "0.5722762", "0.57168615", "0.5693789", "0.5677924", "0.5675993", "0.56728715", "0.5663111", "0.56574917", "0.5648632", "0.56259555", "0.56177694", "0.56146264", "0.5602983", "0.55844426", "0.557813", "0.55696654", "0.5566128", "0.5552447", "0.5536239", "0.55339736", "0.5524949", "0.5509253", "0.5487408", "0.5483857", "0.5482624", "0.5478236", "0.5465495", "0.54560506", "0.5449728", "0.54427445", "0.54386306", "0.5426414", "0.5420475", "0.5410329", "0.5407317", "0.5402048", "0.5400993", "0.5397455", "0.53939223", "0.5389253", "0.5389007", "0.53842455", "0.53800535", "0.537982", "0.5373748", "0.53726953", "0.53683925", "0.53676003", "0.53669167", "0.53571886", "0.53541994", "0.535162", "0.535162", "0.5347771", "0.53379965", "0.53233445", "0.53120786", "0.53093183", "0.5307825", "0.530751", "0.52992535" ]
0.71236336
5
must be top >= 0 && bot >= top
func (b *Slice) Sub(top, bot int) *Slice { if top < 0 || bot < top { return nil } return &Slice{ buffer: b.buffer, top: b.top + top, bot: b.top + bot, cap: b.cap, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b *Bound) Top() float64 {\n\treturn b.ne[1]\n}", "func (s *layoutStack) topNextPointMustBeEmpty() bool {\n\treturn s.top().nextPointMustBeEmpty\n}", "func (o *TileBounds) HasTop() bool {\n\tif o != nil && o.Top != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *TileBounds) GetTopOk() (*int32, bool) {\n\tif o == nil || o.Top == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Top, true\n}", "func (self *Graphics) Top() int{\n return self.Object.Get(\"top\").Int()\n}", "func (self *TileSprite) Top() int{\n return self.Object.Get(\"top\").Int()\n}", "func (s *layoutStack) setTopNextPointMustBeEmpty(nextPointMustBeEmpty bool) {\n\tif s.topLayout() != geom.XYM {\n\t\tpanic(\"setTopNextPointMustBeEmpty called for non-XYM geometry collection\")\n\t}\n\ts.top().nextPointMustBeEmpty = nextPointMustBeEmpty\n}", "func (self *Rectangle) Top() int{\n return self.Object.Get(\"top\").Int()\n}", "func (m *MockDriver) UseTopClause() bool { return false }", "func canMakeTwoRightOneTop(p int) bool {\n\tif p >= 49 {\n\t\treturn false\n\t}\n\n\tswitch p {\n\tcase 8, 16, 24, 32, 40, 48, 56, 64:\n\t\treturn false\n\t}\n\treturn true\n}", "func (c Chessboard) validMoveBishop(from int, to int) bool {\n fromRow := rowFromPosition(from)\n fromCol := colFromPosition(from)\n toRow := rowFromPosition(to)\n toCol := colFromPosition(to)\n\n for offset := 1; offset <= 7; offset++ {\n if ((toRow == (fromRow + offset) ||\n toRow == (fromRow - offset)) &&\n (toCol == (fromCol + offset) ||\n toCol == (fromCol - offset))) {\n\n return true\n\n }\n }\n\n return false\n\n}", "func TestMoveTopToBottom(t *testing.T) {\n\tdeck := Deck{}\n\ttop, middle, bottom := Card{id: 1}, Card{id: 2}, Card{id: 3}\n\tdeck.cards = &[]Card{top, middle, bottom}\n\tcards := *deck.cards\n\n\tif cards[0].id != top.id {\n\t\tt.Error(\"Initial Top card is wrong\")\n\t}\n\n\tdeck.MoveTopToBottom()\n\n\tlog.Printf(strconv.Itoa(cards[0].id))\n\n\tif cards[0].id == top.id {\n\t\tt.Error(\"The Top card is still on top\")\n\t}\n\n\tif cards[2].id != top.id {\n\t\tt.Error(\"The Top card has not been moved to the bottom\")\n\t}\n}", "func amIWithinTheBlastRadius(myX int, myY int, bomb Bomb) bool{\n if myX > bomb.x + bomb.reach || myX < bomb.x - bomb.reach || myY > bomb.y + bomb.reach || myY < bomb.y - bomb.reach {return true}\n return false\n}", "func (self *Rectangle) SetTopA(member int) {\n self.Object.Set(\"top\", member)\n}", "func (me TxsdPresentationAttributesTextContentElementsAlignmentBaseline) IsTop() bool {\n\treturn me.String() == \"top\"\n}", "func (p *pwmGroup) Top() uint32 {\n\treturn p.getWrap()\n}", "func canMakeTwoTopOneLeft(p int) bool {\n\tif p <= 8 {\n\t\treturn false\n\t}\n\n\tswitch p {\n\tcase 16, 24, 32, 40, 48, 56, 64, 15, 23, 31, 39, 47, 55, 63:\n\t\treturn false\n\t}\n\treturn true\n}", "func (s Square) Bottom() int {\n\treturn s.top + s.height\n}", "func (l Layout) Top(name string) float64 {\n\tpanel := l.getPanelDef(name)\n\treturn panel.Pos.Y + panel.Height/2\n}", "func (self *TileSprite) Bottom() int{\n return self.Object.Get(\"bottom\").Int()\n}", "func main() {\n\tbots := ReadInput(\"day23_input.txt\")\n\n\tvar largestBot Nanobot\n\tfor _, b := range bots {\n\t\tif b.r > largestBot.r {\n\t\t\tlargestBot = b\n\t\t}\n\t}\n\n\tinRangeCount := 0\n\tminX := math.MaxInt32\n\tminY := math.MaxInt32\n\tminZ := math.MaxInt32\n\tmaxX := math.MinInt32\n\tmaxY := math.MinInt32\n\tmaxZ := math.MinInt32\n\tmeanX := 0\n\tmeanY := 0\n\tmeanZ := 0\n\tfor _, b := range bots {\n\t\td := IntAbs(b.x - largestBot.x) + IntAbs(b.y - largestBot.y) + IntAbs(b.z - largestBot.z)\n\t\tmeanX += b.x\n\t\tmeanY += b.y\n\t\tmeanZ += b.z\n\n\t\tif d <= largestBot.r {\n\t\t\tinRangeCount += 1\n\t\t}\n\t\tif b.x > maxX {\n\t\t\tmaxX = b.x\n\t\t}\n\t\tif b.y > maxY {\n\t\t\tmaxY = b.y\n\t\t}\n\t\tif b.z > maxZ {\n\t\t\tmaxZ = b.z\n\t\t}\n\t\tif b.x < minX {\n\t\t\tminX = b.x\n\t\t}\n\t\tif b.y < minY {\n\t\t\tminY = b.y\n\t\t}\n\t\tif b.z < minZ {\n\t\t\tminZ = b.z\n\t\t}\n\t}\n\tmeanX = meanX / len(bots)\n\tmeanY = meanY / len(bots)\n\tmeanZ = meanZ / len(bots)\n\n\tfmt.Printf(\"Number in range for part 1: %d\\n\", inRangeCount)\n\t\n\t\n\tfmt.Printf(\"Number range x: (%d, %d), y: (%d, %d), z: (%d, %d)\\n\", minX, maxX, minY, maxY, minZ, maxZ)\n\n\t// The score at the center is a good heuristic to allow us to skip any \n\t// sub volumes with a lower score, so it will be used as the starting \"maxValue\"\n\tcenterScore := CubeScore(meanX, meanY, meanZ, 0, bots)\n\tfmt.Printf(\"Center: (%d, %d, %d), score: %d\\n\", meanX, meanY, meanZ, centerScore)\n\t\n\n\t// Do pyramid style search\n\tscores := ScaledSearch(minX, maxX, minY, maxY, minZ, maxZ, 4*1024*1024, bots)\n\tfmt.Println(\"Top 20 scores:\")\n\tfor i, s := range scores {\n\t\tfmt.Println(s.score)\n\t\tif i > 20 {\n\t\t\tbreak\n\t\t} \n\t}\n\n\ttopSize := 0\n\tif maxX - minX > topSize {\n\t\ttopSize = maxX - minX\n\t}\n\tif maxY - minY > topSize {\n\t\ttopSize = maxY - minY\n\t}\n\tif maxZ - minZ > topSize {\n\t\ttopSize = maxZ - minZ\n\t}\n\ttopVolume := Score{(minX + maxX)/2, (minY + maxY)/2, (minZ + maxZ)/2, topSize, 0}\n\tfmt.Printf(\"Initial volume: (%d, %d, %d) size: %d\\n\", topVolume.x, topVolume.y, topVolume.z, topVolume.size)\n\t// Do two passes: \n\t// - On first pass, only collect the top score\n\t// - On second pass, collect all the locations that achieve the top score\n\t// This is because the algorithm will waste much too much time collecting the many, many\n\t// locations that meet a lower score, before it figures out there are higher scores\n\ttopScore, _ := Recurse(topVolume, centerScore, bots, false)\n\tfmt.Println(\"Top score: \", topScore)\n\ttopScore, locations := Recurse(topVolume, topScore, bots, true)\n\tfmt.Printf(\"Found %d locations with score %d\\n\", len(locations), topScore)\n\tfor _, l := range locations {\n\t\tfmt.Println(\"Location: \", l)\n\t\t// Compute the distance to origin\n\t\tdistance := CubeDistance(0, 0, 0, 0, l.x, l.y, l.z)\n\t\t// re-compute the score...just as a sanity check\n\t\trecomputeScore := CubeScore(l.x, l.y, l.z, 0, bots)\n\t\tfmt.Println(\"Distance from origin: \", distance)\n\t\tfmt.Println(\"recomputed score: \", recomputeScore)\n\t}\n}", "func (self *TileSprite) SetTopA(member int) {\n self.Object.Set(\"top\", member)\n}", "func (t *TopK) isTop(freq uint64) bool {\n\tif t.elements.Len() < int(t.k) {\n\t\treturn true\n\t}\n\n\treturn freq >= (*t.elements)[0].Freq\n}", "func (self *TileSprite) BringToTopI(args ...interface{}) *DisplayObject{\n return &DisplayObject{self.Object.Call(\"bringToTop\", args)}\n}", "func (s *Stack) PrepTop() int {\n\tnum := 0\n\tfor _, v := range s.cakes {\n\t\tif !v {\n\t\t\tbreak\n\t\t}\n\t\tnum++\n\t}\n\treturn num\n}", "func canMakeTwoLeftOneTop(p int) bool {\n\tif p <= 16 {\n\t\treturn false\n\t}\n\n\tswitch p {\n\tcase 24, 32, 40, 48, 56, 64:\n\t\treturn false\n\t}\n\treturn true\n}", "func (c Chessboard) validMoveRook(from int, to int) bool {\n fromRow := rowFromPosition(from)\n fromCol := colFromPosition(from)\n toRow := rowFromPosition(to)\n toCol := colFromPosition(to)\n\n return fromRow == toRow || fromCol == toCol\n\n}", "func top_left(n int) bool { return n == 0 }", "func (self *Graphics) Bottom() int{\n return self.Object.Get(\"bottom\").Int()\n}", "func (s *MyStack) Top() int {\n\tif s.Empty() {\n\t\treturn -1\n\t}\n\n\treturn s.Q[len(s.Q)-1]\n}", "func (self *TileSprite) BringToTop() *DisplayObject{\n return &DisplayObject{self.Object.Call(\"bringToTop\")}\n}", "func (r Rectangle) TopLeft() Point {\n\treturn r.Min\n}", "func TestBoardNotFullButGameNotOver(t *testing.T) {\n\tboard := model.Board{GameBoard: [3][3]int{{1, 1, -1},\n\t\t{-1, 1, -1},\n\t\t{1, 0, 1}}}\n\n\tif isOver, _ := board.IsGameOver(); isOver == false {\n\t\tt.Errorf(\"Game is over false negative\")\n\t}\n}", "func (s *Asteroid) checkEdges() {\n\t//Right bound\n\tif s.x > 1 {\n\t\ts.getPoints()\n\t\ts.points = TranslatePoints(s.points, -2, 0)\n\t\ts.points = RotatePoints(s.points, s.rot, s.x, s.y)\n\t\ts.x = -1\n\t} else if s.x < -1 { //Left bound\n\t\ts.getPoints()\n\t\ts.points = TranslatePoints(s.points, 2, 0)\n\t\ts.points = RotatePoints(s.points, s.rot, s.x, s.y)\n\t\ts.x = 1\n\t}\n\t//Upper bound\n\tif s.y > 1 {\n\t\ts.y = -1\n\t\ts.getPoints()\n\t\ts.points = TranslatePoints(s.points, 0, -2)\n\t\ts.points = RotatePoints(s.points, s.rot, s.x, s.y)\n\t} else if s.y < -1 { //Lower bound\n\t\ts.y = 1\n\t\ts.getPoints()\n\t\ts.points = TranslatePoints(s.points, 0, 2)\n\t\ts.points = RotatePoints(s.points, s.rot, s.x, s.y)\n\t}\n}", "func (self *Graphics) SetTopA(member int) {\n self.Object.Set(\"top\", member)\n}", "func (this *MyStack) Top() int {\n\n}", "func (e Pos) In(r Rect) bool {\n\treturn r.Min.I <= e.I && e.I < r.Max.I && r.Min.J <= e.J && e.J < r.Max.J\n}", "func (o *WorkbookChart) HasTop() bool {\n\tif o != nil && o.Top != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (w *Writer) shardTop(depth uint) (uint, error) {\n\tswitch depth {\n\tcase w.height:\n\t\treturn w.split, nil\n\tcase w.split:\n\t\treturn 0, nil\n\t}\n\treturn 0, fmt.Errorf(\"unexpected depth %d\", depth)\n}", "func (f Board) validMove(pair Pair, p int) bool {\n\tfmt.Println(\"in valid move\")\n\t//In go, a move is valid unless:\n\t//You place a stone where it would have no liberties (be immediately captured) without creating a liberty\n\t//You place a stone that returns the board exactly to its previous position\n\n\t//within board boundaries\n\tif pair.x < 0 || pair.x > f.maxX || pair.y < 0 || pair.y > f.maxY {\n\t\tfmt.Println(\"out of boundaries\")\n\t\treturn false\n\t}\t\n\n\t//on top of another stone\n\tif f.board[pair.x][pair.y] != 0 {\n\t\tfmt.Println(\"on top of stone\")\n\t\treturn false\n\t}\t\t\n\n\t//check to see if would have 0 liberties\n\ttestBoard := f.copy()\n\ttestBoard.board[pair.x][pair.y] = p\n\tif !(testBoard.checkLibs(pair, p) > 0) {\n\t\t//check to see if it will create a liberty\n\t\t//check if any of the adjacent stones have only 1 liberty\n\t\t//since we already checked that this lib is open, they necessarily have only this liberty\n\t\t//if it does make a liberty, we still must check to see if is a ko situation\n\t\tmakesLib := 0\n\n\t\t//left\n\t\tif pair.x-1 > 0 {\n\t\t\tfmt.Println(\"check left\")\n\t\t\tcheckLeft := newPair(pair.x-1,pair.y)\n\t\t\tif f.checkLibs(*checkLeft, f.board[checkLeft.x][checkLeft.y]) == 1 {\n\t\t\t\tmakesLib++\n\t\t\t}\n\t\t}\n\t\t//above\n\t\tif pair.y-1 > 0 {\n\t\t\tfmt.Println(\"check above\")\n\t\t\tcheckAbove := newPair(pair.x,pair.y-1)\n\t\t\tif f.checkLibs(*checkAbove, f.board[checkAbove.x][checkAbove.y]) == 1 {\n\t\t\t\tmakesLib++\n\t\t\t}\n\t\t}\t\n\n\t\t//right\n\t\tif pair.x+1 < f.maxX {\n\t\t\tfmt.Println(\"check right\")\n\t\t\tcheckRight := newPair(pair.x+1,pair.y)\n\t\t\tif f.checkLibs(*checkRight, f.board[checkRight.x][checkRight.y]) == 1 {\n\t\t\t\tmakesLib++\n\t\t\t}\n\t\t}\n\n\t\t//below\n\t\tif pair.y+1 < f.maxY {\n\t\t\tfmt.Println(\"check below\")\n\t\t\tcheckBelow := newPair(pair.x,pair.y+1)\n\t\t\tif f.checkLibs(*checkBelow, f.board[checkBelow.x][checkBelow.y]) == 1 {\n\t\t\t\tmakesLib++\n\t\t\t}\n\t\t}\n\n\t\t//do we need to check if ko or not?\n\t\t//just check to see if \n\t\tif makesLib > 0 {\n\n\t\t\t//can never have ko if you make more than one lib\n\t\t\tif makesLib > 1 {\n\t\t\t\tfmt.Println(\"makes more than one lib\")\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\t//cannot play a move that brings the board back to the previous position\n\t\t\ttestBoard = f.copy()\n\n\t\t\t//what will the board look like after playing there\n\t\t\ttestBoard.board[pair.x][pair.y] = p\n\n\t\t\t//does match the board's position after your last turn\n\t\t\tf.board[f.moveList.Last().x][f.moveList.Last().y] = 0\n\t\t\tif f.equals(testBoard) {\n\t\t\t\tfmt.Println(\"breaks ko rule\")\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tfmt.Println(\"doesn't make any liberties, wouldn't have any\")\n\t\treturn false\n\t}\n\tfmt.Println(\"has liberties, valid move\")\n\treturn true \n}", "func (tm *Term) Top() error {\n\ttm.RowOff = tm.RowsPer - tm.MaxRows\n\ttm.RowSt = 0\n\treturn tm.Draw()\n}", "func (this *MyStack) Top() int {\n\tres := this.v[len(this.v)-1]\n\treturn res\n}", "func (r ApiGetHyperflexNodeListRequest) Top(top int32) ApiGetHyperflexNodeListRequest {\n\tr.top = &top\n\treturn r\n}", "func (a area) has(p *Position) bool {\n\tif p.height > a.minHeigth && p.height <= a.maxHeigth {\n\t\treturn true\n\t}\n\treturn false\n}", "func (p *PodsWidget) SelectTop() {\n\tp.ScrollTop()\n}", "func (self *Rectangle) Bottom() int{\n return self.Object.Get(\"bottom\").Int()\n}", "func (t Tile) top(reversed bool) int {\n bits := t.data[0]\n if reversed {\n bits = reverse(bits)\n }\n return asBinaryNumber(bits)\n}", "func TestPushTop(t *testing.T) {\n\tstack := NewStack()\n\tstack.Push(\"foobar\")\n\tisEmpty := stack.IsEmpty()\n\tif isEmpty {\n\t\tt.Fatalf(\"expected: %t; got: %t\", false, isEmpty)\n\t}\n}", "func isGameOver(s Shape) bool {\n\tfor i := 0; i < 4; i++ {\n\t\tif s[i].row >= 20 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (s *Scroll) DrawOnTop(t ggl.Target, c *drw.Geom) {\n\tif s.X.use {\n\t\trect := mat.AABB{Min: s.Frame.Min, Max: s.corner}\n\t\tc.Color(s.RailColor).AABB(rect)\n\t\trect.Min.X, rect.Max.X = s.barBounds(&s.X, 0)\n\t\tc.Color(s.BarColor).AABB(rect)\n\t}\n\tif s.Y.use {\n\t\trect := mat.AABB{Min: s.corner, Max: s.Frame.Max}\n\t\tc.Color(s.RailColor).AABB(rect)\n\t\trect.Min.Y, rect.Max.Y = s.barBounds(&s.Y, 1)\n\t\tc.Color(s.BarColor).AABB(rect)\n\t}\n\n\tif s.X.use && s.Y.use {\n\t\trect := mat.A(s.corner.X, s.Frame.Min.Y, s.Frame.Max.X, s.corner.Y)\n\t\tc.Color(s.IntersectionColor).AABB(rect)\n\t}\n\n\tc.Fetch(t)\n}", "func (b *Bound) Bottom() float64 {\n\treturn b.sw[1]\n}", "func (r *Ring) Top() (interface{}, bool) {\n\tif r.IsEmpty() {\n\t\treturn nil, false\n\t}\n\treturn r.data[r.out], true\n}", "func (s *session) handleTOP(args []string) error {\n\treturn s.withMessageDo(args[0], func(msgId uint64) error {\n\t\tnoLines, err := strconv.ParseUint(args[1], 10, 64)\n\t\tif err != nil {\n\t\t\treturn errInvalidSyntax\n\t\t}\n\t\tif err := s.writer.PrintfLine(\"+OK\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treadCloser, err := s.handler.GetMessageReader(msgId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer s.closeOrReport(readCloser)\n\t\tdotWriter := s.writer.DotWriter()\n\t\tdefer s.closeOrReport(dotWriter)\n\t\tprotoReader := textproto.NewReader(bufio.NewReader(readCloser))\n\t\tfor i := uint64(0); i < noLines; i++ {\n\t\t\tline, readErr := protoReader.ReadLineBytes()\n\t\t\tif err := printTopLine(line, readErr, dotWriter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (p *pwmGroup) SetTop(top uint32) {\n\tp.setWrap(uint16(top))\n}", "func parseTop(ds *docState) {\n\tif n, ok := parseNode(ds); ok {\n\t\tif n != nil {\n\t\t\tds.appendNodes(n)\n\t\t}\n\t\treturn\n\t}\n\tds.push(nil)\n\tnn := parseSubtree(ds)\n\tds.pop()\n\tds.appendNodes(parser.CompactNodes(nn)...)\n}", "func nearbymonst() bool {\n\tfor x := max(playerx-1, 0); x < min(playerx+2, MAXX-1); x++ {\n\t\tfor y := max(playery-1, 0); y < min(playery+2, MAXY-1); y++ {\n\t\t\tif mitem[x][y] != 0 {\n\t\t\t\treturn true /* if monster nearby */\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (s *MyStack) Top() int {\n return s.queue1[0]\n}", "func (level *Level) bresenhum(start Pos, end Pos) {\n\tsteep := math.Abs(float64(end.Y-start.Y)) > math.Abs(float64(end.X-start.X)) // Is the line steep or not?\n\t// Swap the x and y for start and end\n\tif steep {\n\t\tstart.X, start.Y = start.Y, start.X\n\t\tend.X, end.Y = end.Y, end.X\n\t}\n\n\tdeltaY := int32(math.Abs(float64(end.Y - start.Y)))\n\n\tvar err int32\n\ty := start.Y\n\tvar ystep int32 = 1 // How far we are stepping when err is above threshold\n\tif start.Y >= end.Y {\n\t\tystep = -1 // Reverse it when we step\n\t}\n\t// Are we on the left or right side of graph\n\tif start.X > end.X {\n\t\tdeltaX := start.X - end.X // We know start.X will be larger than end.X\n\t\t// Count down so lines extend FROM the player, not TO\n\t\tfor x := start.X; x > end.X; x-- {\n\t\t\tvar pos Pos\n\t\t\tif steep {\n\t\t\t\tpos = Pos{y, x} // If we are steep, x and y will be swapped\n\t\t\t} else {\n\t\t\t\tpos = Pos{x, y}\n\t\t\t}\n\t\t\tlevel.Map[pos.Y][pos.X].Visible = true\n\t\t\tlevel.Map[pos.Y][pos.X].Seen = true\n\t\t\tif !canSeeThrough(level, pos) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr += deltaY\n\t\t\tif 2*err >= deltaX {\n\t\t\t\ty += ystep // Go up or down depending on the direction of our line\n\t\t\t\terr -= deltaX\n\t\t\t}\n\t\t}\n\t} else {\n\t\tdeltaX := end.X - start.X // We know start.X will be larger than end.X\n\t\tfor x := start.X; x < end.X; x++ {\n\t\t\tvar pos Pos\n\t\t\tif steep {\n\t\t\t\tpos = Pos{y, x} // If we are steep, x and y will be swapped\n\t\t\t} else {\n\t\t\t\tpos = Pos{x, y}\n\t\t\t}\n\t\t\tlevel.Map[pos.Y][pos.X].Visible = true\n\t\t\tlevel.Map[pos.Y][pos.X].Seen = true\n\t\t\tif !canSeeThrough(level, pos) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr += deltaY\n\t\t\tif 2*err >= deltaX {\n\t\t\t\ty += ystep // Go up or down depending on the direction of our line\n\t\t\t\terr -= deltaX\n\t\t\t}\n\t\t}\n\t}\n}", "func (l *line) isTopIndent() bool {\n\treturn l.indent == indentTop\n}", "func topElement(s string) bool {\n\treturn indent(s) == indentTop\n}", "func inBound(x int, y int, length int, width int) bool {\n\tif 0 <= x && x < length && y >= 0 && y < width {\n\t\treturn true\n\t}\n\treturn false\n}", "func checkVerticalSplit(ctx context.Context, tconn *chrome.TestConn, displayWorkArea coords.Rect) error {\n\toverActivityWInfo, err := ash.GetARCAppWindowInfo(ctx, tconn, wm.Pkg24Secondary)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get arc app window info for over activity\")\n\t}\n\tunderActivityWInfo, err := ash.GetARCAppWindowInfo(ctx, tconn, wm.Pkg24)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get arc app window info for under activity\")\n\t}\n\t// Over activity must be snapped to the left.\n\tif overActivityWInfo.BoundsInRoot.Left != 0 ||\n\t\toverActivityWInfo.BoundsInRoot.Top != 0 ||\n\t\toverActivityWInfo.BoundsInRoot.Width >= displayWorkArea.Width/2 ||\n\t\toverActivityWInfo.BoundsInRoot.Height != displayWorkArea.Height {\n\t\treturn errors.Errorf(\"invalid snapped to the left activity bounds, got: Left = %d, Top = %d, Width = %d, Height = %d; want: Left = 0, Top = 0, Width < %d, Height = %d\",\n\t\t\toverActivityWInfo.BoundsInRoot.Left, overActivityWInfo.BoundsInRoot.Top, overActivityWInfo.BoundsInRoot.Width, overActivityWInfo.BoundsInRoot.Height, displayWorkArea.Width/2, displayWorkArea.Height)\n\t}\n\t// Under activity must be snapped to the right.\n\tif underActivityWInfo.BoundsInRoot.Left <= displayWorkArea.Width/2 ||\n\t\tunderActivityWInfo.BoundsInRoot.Top != 0 ||\n\t\tunderActivityWInfo.BoundsInRoot.Width >= displayWorkArea.Width/2 ||\n\t\tunderActivityWInfo.BoundsInRoot.Height != displayWorkArea.Height ||\n\t\tunderActivityWInfo.BoundsInRoot.Left+underActivityWInfo.BoundsInRoot.Width != displayWorkArea.Width {\n\t\treturn errors.Errorf(\"invalid snapped to the right activity bounds, got: Left = %d, Top = %d, Width = %d, Height = %d, Right = %d; want: Left > %d, Top = 0, Width < %d, Height = %d, Right = %d\",\n\t\t\tunderActivityWInfo.BoundsInRoot.Left, underActivityWInfo.BoundsInRoot.Top, underActivityWInfo.BoundsInRoot.Width, underActivityWInfo.BoundsInRoot.Height,\n\t\t\tunderActivityWInfo.BoundsInRoot.Left+underActivityWInfo.BoundsInRoot.Width, displayWorkArea.Width/2, displayWorkArea.Width/2, displayWorkArea.Height, displayWorkArea.Width)\n\t}\n\n\treturn nil\n}", "func confirms(txHeight, curHeight int32) int32 {\n\tswitch {\n\tcase txHeight == -1, txHeight > curHeight:\n\t\treturn 0\n\tdefault:\n\t\treturn curHeight - txHeight + 1\n\t}\n}", "func confirms(txHeight, curHeight int32) int32 {\n\tswitch {\n\tcase txHeight == -1, txHeight > curHeight:\n\t\treturn 0\n\tdefault:\n\t\treturn curHeight - txHeight + 1\n\t}\n}", "func within(p, q, r float64) bool {\n\treturn (p <= q) && (q <= r) || (r <= q) && (q <= p)\n}", "func (tv *TextView) ScrollToTop(pos int) bool {\n\tly := tv.ParentScrollLayout()\n\tif ly == nil {\n\t\treturn false\n\t}\n\treturn ly.ScrollDimToStart(mat32.Y, pos)\n}", "func TestTopEmptyStack(t *testing.T) {\n\tstack := NewStack()\n\titem := stack.Top()\n\tif item != nil {\n\t\tt.Fatalf(\"expected: %v; got: %v\", nil, item)\n\t}\n}", "func drawTopBanner(ctx *gg.Context, text string) {\n\tx := float64(ctx.Width()) / 2\n\ty := IMAGE_MARGIN\n\tdrawText(ctx, text, x, y, 0.5, 0.0, TOP_TEXT_DIVISOR)\n}", "func (r ApiGetHyperflexTargetListRequest) Top(top int32) ApiGetHyperflexTargetListRequest {\n\tr.top = &top\n\treturn r\n}", "func (p *Stack) Top() (v interface{}, ok bool) {\n\n\tn := len(p.data)\n\tif n > 0 {\n\t\tv, ok = p.data[n-1], true\n\t}\n\treturn\n}", "func (this *MyStack) Top() int {\n\treturn this.q.PeekFromFront()\n}", "func (this *MyStack) Top() int {\n\treturn this.Ele[this.Len-1]\n}", "func (this *MyStack) Top() int {\n\treturn this.val[0]\n}", "func (this *MyStack) Top() int {\n\treturn this.l.Back().Value.(int)\n}", "func (q *SensorStack) Bottom() (top *SensorReading, err error) {\n\ttop = &errorReading\n\tif q.Len() == 0 {\n\t\terr = errors.New(\"Empty Stack\")\n\t\treturn\n\t}\n\ttop = (*q)[0]\n\treturn\n}", "func Top() Option {\n\treturn func(pg *pager) {\n\n\t\tpg.style = func(p *pager) (from, to, selected int) {\n\n\t\t\tfrom = p.selected\n\t\t\tto = p.selected + p.height\n\n\t\t\tif p.dataLen < to {\n\t\t\t\tto = p.dataLen\n\t\t\t}\n\n\t\t\treturn from, to, 0\n\t\t}\n\t}\n}", "func (g *Game) checkNext(c Side, x, y int) error {\n\tn := g.nextSide()\n\tif n == Blank {\n\t\treturn g.errorOf(ErrorGameEnded)\n\t}\n\n\tif n != c {\n\t\treturn g.errorOf(ErrorNotYourTurn)\n\t}\n\n\tif x < 0 || x > 7 || y < 0 || y > 7 {\n\t\treturn g.errorOf(ErrorBadRequest)\n\t}\n\n\tif !g.roomIsValid(c, x, y) {\n\t\treturn g.errorOf(ErrorBadRequest)\n\t}\n\n\treturn nil\n}", "func (o *TileBounds) GetTop() int32 {\n\tif o == nil || o.Top == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Top\n}", "func canSeeThrough(level *Level, pos Pos) bool {\n\tif inRange(level, pos) {\n\t\t// Check tile for solid object\n\t\tt := level.Map[pos.Y][pos.X]\n\t\tswitch t.Rune {\n\t\tcase StoneWall, CloseDoor, Void:\n\t\t\treturn false\n\t\tdefault:\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (c *Cutter) CutFromTop(x, cells int) {\n\t// skip empty columns\n\tif len(c.terrain.columns[x]) == 0 {\n\t\treturn\n\t}\n\n\t// get the top column on x\n\tcolumn := c.terrain.columns[x][0]\n\n\t// update canvas\n\tnewCanvas := *column.canvas\n\tnewCanvas[0] = newCanvas[0][cells:]\n\tcolumn.canvas = &newCanvas\n\n\t// update entity\n\tx, y := column.Position()\n\t//t.body.Position.Y += float64(cells)\n\tcolumn.Entity = tl.NewEntityFromCanvas(x, y+cells, newCanvas)\n}", "func (q *QueryTop) IsValid() (bool, error) {\n\treturn true, nil\n}", "func (s *StackInt) Top() int {\nlength := len(s.s)\nres := s.s[length-1]\nreturn res\n}", "func (tr *trooper) fullHealth() bool { return tr.neo != nil }", "func (m *CockroachDriver) UseTopClause() bool {\n\treturn false\n}", "func (b *Board) IsValid(d int, s int, e int) bool { // s = start, e = end\n\tif (GetPieces(b.Turn, b.Bar) != 0) && (s >= 0) { // If trying to move from the bar, put a neg num as input\n\t\treturn false // Has pieces in the Bar but trying to move pieces not in the bar\n\t}\n\tabsChange := (e - s) * Dir(b.Turn)\n\tif absChange != d { // Handles Dice AND going counterclockwise/clockwise\n\t\treturn false\n\t}\n\tif GetPieces(!b.Turn, b.Tris[e]) >= 2 { // Spot is not open\n\t\treturn false\n\t}\n\tif GetPieces(b.Turn, b.Tris[s]) <= 0 { // No Pieces to move\n\t\treturn false\n\t}\n\tif GetPieces(!b.Turn, b.Tris[e]) == 1 { // Blot! - Increase in bar\n\t\tb.Tris[e] = SetPieces(!b.Turn, b.Tris[e], 0)\n\t\tb.Bar = SetPieces(!b.Turn, b.Bar, GetPieces(!b.Turn, b.Bar)+1)\n\t}\n\treturn true\n}", "func (c Chessboard) rookPositionBeforeCastle(color int, from int, to int) int {\n if color == 0 && from == 60 && to == 62 {\n return 63\n }\n\n if color == 0 && from == 60 && to == 58 {\n return 56\n }\n\n if color == 1 && from == 4 && to == 6 {\n return 7\n }\n\n if color == 1 && from == 4 && to == 2 {\n return 0\n }\n\n return -1\n}", "func (o *TileBounds) SetTop(v int32) {\n\to.Top = &v\n}", "func valid(state State) bool {\n\tswitch {\n\tcase state.left.m < 0 || state.left.c < 0 || state.right.m < 0 || state.right.c < 0:\n\t\treturn false\n\tcase state.left.m > 0 && state.left.c > state.left.m:\n\t\treturn false\n\tcase state.right.m > 0 && state.right.c > state.right.m:\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}", "func (b *Bound) Empty() bool {\n\treturn b.sw.X() >= b.ne.X() || b.sw.Y() >= b.ne.Y()\n}", "func (r1 Rect) OverlapsWith(r2 Rect) bool {\n if r1.Position.X > (r2.Position.X + float64(r2.Size.Width)) {\n //log.Info(\"a\")\n return false\n }\n\n if (r1.Position.X + float64(r1.Size.Width)) < r1.Position.X {\n //log.Info(\"b\")\n return false\n }\n\n if r1.Position.Y > (r2.Position.Y + float64(r2.Size.Height)) {\n //log.Info(\"c\")\n return false\n }\n\n if (r1.Position.Y + float64(r1.Size.Height)) < r2.Position.Y {\n //log.Info(\"d\")\n return false\n }\n\n log.Infof(\"COLLIDE: %@, %@\", r1, r2)\n return true\n}", "func isPositionSafe(pos Position, state State) bool {\n\tboardVal := state.board[pos.y][pos.x]\n\treturn boardVal == 0 || boardVal == 3\n}", "func (wa *WaitingArea) withinBounds(x, y int) bool {\n\t// we'll assume all lines have the same width as the first one.\n\treturn x >= 0 && y >= 0 && x < len(wa.seats[0]) && y < len(wa.seats)\n}", "func (this *MyStack) Top() int {\n\treturn this.top.Val\n}", "func (r ApiGetEtherPortChannelListRequest) Top(top int32) ApiGetEtherPortChannelListRequest {\n\tr.top = &top\n\treturn r\n}", "func scoreACell(x int, y int, myX int, myY int, bombsOnTheFloor []Bomb, myReach int, floor [WIDTH][HEIGHT]int) Cell {\n if (myX != x || myY != y) { // I'm not already standing here\n if !canIBeHere(x, y, 1, bombsOnTheFloor, floor) {return Cell{score: WALL_SCORE, distance: TOO_FAR}} // cannot move to here next turn\n }\n moves, maybe := canIGoToThere(myX, myY, myX, myY, x, y, SEARCH_DEPTH_LIMIT, bombsOnTheFloor, floor)\n if !maybe {return Cell{score: WALL_SCORE, distance: TOO_FAR}} // cannot get here, even after multiple turns\n if willIDieHere(x, y, bombsOnTheFloor, floor) {return Cell{score: DANGER_SCORE, distance: TOO_FAR}} // does not account for time left on the bomb, could optimize here rather than walling it off\n score := 0\n for i := 0; i < myReach; i++ {\n if x+i < WIDTH && floor[x+i][y] >= BOX {score++}\n if x-i > 0 && floor[x-i][y] >= BOX {score++}\n if y+i < HEIGHT && floor[x][y+i] >= BOX {score++}\n if y-i > 0 && floor[x][y-i] >= BOX {score++}\n }\n if floor[x][y] > BOX {score++} // there's an item in the box\n return Cell{score: score, distance: moves}\n}", "func NewTop() *Top {\n\treturn &Top{\n\t\tobjects: make(map[string]api.Object),\n\t\tindex: make(map[string]map[string]map[string]api.Object),\n\t}\n}", "func NewTop() *Top {\n\treturn &Top{\n\t\tobjects: make(map[string]api.Object),\n\t\tindex: make(map[string]map[string]map[string]api.Object),\n\t}\n}", "func (c Chessboard) validMoveKing(from int, to int) bool {\n if !c.validPieceKing(from) {\n return false\n }\n\n if from == to {\n return false\n }\n\n fromRow := rowFromPosition(from)\n fromCol := colFromPosition(from)\n toRow := rowFromPosition(to)\n toCol := colFromPosition(to)\n\n if abs(fromRow - toRow) <= 1 && abs(fromCol - toCol) <= 1 {\n return true\n }\n\n return false\n\n}", "func MayContainBuilds(low, high time.Time) bool {\n\tswitch {\n\tcase !high.IsZero() && (high.Before(beginningOfTheWorld) || high.Equal(beginningOfTheWorld)):\n\t\treturn false\n\tcase !low.IsZero() && !high.IsZero() && high.Before(low):\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}", "func (b board) IsValidPos(x, y int) bool {\n\treturn (x > -1 && x < b.xSize && y > -1 && y < b.ySize)\n}", "func (this *MyStack) Top() int {\n\tfor this.l.Front().Next() != nil {\n\t\tthis.t.PushBack(this.l.Remove(this.l.Front()))\n\t}\n\ttop := this.l.Remove(this.l.Front())\n\tfor this.t.Front() != nil {\n\t\tthis.l.PushBack(this.t.Remove(this.t.Front()))\n\t}\n\tthis.l.PushBack(top)\n\treturn top.(int)\n}" ]
[ "0.58156013", "0.55438685", "0.55241835", "0.5485187", "0.5483397", "0.54507685", "0.5449822", "0.5430507", "0.5325831", "0.5263753", "0.52568996", "0.5253762", "0.5217812", "0.5198413", "0.5181171", "0.5156824", "0.51537", "0.51515627", "0.5141098", "0.5124773", "0.511888", "0.5105846", "0.5097428", "0.5062523", "0.5061049", "0.5054194", "0.5048739", "0.5032361", "0.50014246", "0.49901754", "0.49808824", "0.4969029", "0.4944397", "0.49277085", "0.49138921", "0.49121293", "0.4905972", "0.48855048", "0.48728335", "0.48589218", "0.48495737", "0.48468134", "0.48361945", "0.48289576", "0.48256603", "0.48221195", "0.4818843", "0.48079827", "0.48074117", "0.47896352", "0.47895902", "0.47839397", "0.4776126", "0.47512007", "0.47356966", "0.47345474", "0.4710282", "0.4700917", "0.46939301", "0.46902528", "0.4678197", "0.4675777", "0.4670505", "0.4670505", "0.46700555", "0.46697763", "0.4669182", "0.4659222", "0.46571293", "0.4648295", "0.4643429", "0.4632521", "0.46315515", "0.46301898", "0.46300474", "0.46237534", "0.46196076", "0.46183866", "0.46166232", "0.46093634", "0.46087137", "0.46018812", "0.46018076", "0.4592693", "0.45925972", "0.45903453", "0.4588433", "0.4587295", "0.45862213", "0.45830473", "0.45758748", "0.4573663", "0.45734975", "0.4572733", "0.45720196", "0.4570897", "0.4570897", "0.45705372", "0.4560169", "0.4558925", "0.45567518" ]
0.0
-1
LoadConfig returns a configuration structure populated with the ENV values provided. If no ENV values are present, defaults are used.
func LoadConfig() Config { var configuration Config configuration.RPCHost = configEnv("RPCHOST", "http://[::1]") configuration.RPCPort = configEnv("RPCPORT", "55000") configuration.RedisHost = configEnv("REDISHOST", "localhost") configuration.RedisPort = configEnv("REDISPORT", "22000") var timeoutErr error configuration.TimeoutDuration, timeoutErr = strconv.Atoi(configEnv("TIMEOUTDURATION", "60")) if timeoutErr != nil { fmt.Println("Error converting timeout duration to int:", timeoutErr) } configuration.NanoWebsocketHost = configEnv("NANOWEBSOCKETHOST", "ws://[::1]") configuration.NanoWebsocketPort = configEnv("NANOWEBSOCKETPORT", "57000") return configuration }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Load(env string) (Config, error) {\n\tconfig, err := configFromFile(env)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\tconfig.Environment = env\n\n\t// override with environment variables as needed and accepted by `Config`\n\terr = envconfig.Init(&config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\treturn config, nil\n}", "func LoadConfig() (Config, error) {\n\tvar c Config\n\n\tctx := context.Background()\n\n\terr := envconfig.Process(ctx, &c)\n\treturn c, err\n}", "func LoadConfig() (*Config, error) {\n\tvar cfg Config\n\n\terr := envconfig.Process(\"\", &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &cfg, nil\n}", "func LoadConfig(path string, env string) (Config, error) {\n\tvar config Config\n\tviper.AddConfigPath(path + \"/env\")\n\tviper.SetConfigName(env)\n\tviper.SetConfigType(\"env\")\n\tviper.AutomaticEnv()\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\treturn config, err\n\t}\n\terr = viper.Unmarshal(&config)\n\treturn config, err\n}", "func LoadEnvConfig() *Config {\n\tcfg := &Config{}\n\tif err := envconfig.Process(\"\", cfg); err != nil {\n\t\tlogrus.Fatalf(\"config: Unable to load config for %T: %s\", cfg, err)\n\t}\n\treturn cfg\n}", "func Load() (config *Config, err error) {\n\tconfig = &Config{}\n\n\tif err = env.Set(config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn\n}", "func LoadConfig() (*Config, error) {\n\tvar config Config\n\tif err := envconfig.Process(\"\", &config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &config, nil\n}", "func LoadConfig(path string) (config Config, err error) {\n\tviper.AddConfigPath(path)\n\tviper.SetConfigName(\"app\") // since app.env\n\tviper.SetConfigType(\"env\") // json-xml etx could have been also be used\n\n\tviper.AutomaticEnv()\n\t// automatically override values from config file with the values of the env vars\n\n\t// start reading\n\terr = viper.ReadInConfig()\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// unmarshal the values to target config object\n\terr = viper.Unmarshal(&config)\n\treturn\n}", "func Load(env string) (*Configuration, error) {\n\tbytes, err := ioutil.ReadFile(\"config.\" + env + \".yaml\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading config file, %s\", err)\n\t}\n\tvar cfg = new(Configuration)\n\tif err := yaml.Unmarshal(bytes, cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to decode into struct, %v\", err)\n\t}\n\treturn cfg, nil\n}", "func Load(env string) (*Configuration, error) {\n\tbytes, err := ioutil.ReadFile(\"config.\" + env + \".yaml\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading config file, %s\", err)\n\t}\n\tvar cfg = new(Configuration)\n\tif err := yaml.Unmarshal(bytes, cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to decode into struct, %v\", err)\n\t}\n\treturn cfg, nil\n}", "func LoadConfig(logger *zap.Logger, cfg interface{}) {\n\terr := envconfig.Process(\"\", cfg)\n\tif err != nil {\n\t\tenvconfig.Usage(\"\", cfg)\n\t\tlogger.Fatal(\"app: could not process config\", zap.Error(err))\n\t}\n}", "func LoadConfig(logger *zap.Logger) (*Config, error) {\n\tlogger.Info(\"loading configuration from the environment ...\")\n\n\tvar (\n\t\tcfg Config\n\t\tredisURL string\n\t\tapiKey string\n\t)\n\n\tok := []bool{\n\t\tfetch(logger, &cfg.Addr, \"ADDR\"),\n\n\t\tfetch(logger, &apiKey, \"API_KEY\") &&\n\t\t\tcfg.setAPIKey(logger, apiKey),\n\n\t\tfetch(logger, &cfg.PurgeryID, \"PURGERY_ID\"),\n\n\t\tfetch(logger, &redisURL, \"REDIS_URL\") &&\n\t\t\tcfg.dialRedis(logger, redisURL),\n\n\t\tfetch(logger, &cfg.VarnishAddr, \"VARNISH_ADDR\"),\n\t}\n\n\tfor _, ok := range ok {\n\t\tif !ok {\n\t\t\treturn nil, errLoadConfig\n\t\t}\n\t}\n\n\treturn &cfg, nil\n}", "func LoadConfig(env string) (*AppConfig, error) {\n\tv := viper.New()\n\tv.SetConfigType(\"json\")\n\tv.SetConfigName(env)\n\tv.AddConfigPath(\"./\")\n\tif err := v.ReadInConfig(); err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read the configuration file: %s\", err)\n\t}\n\n\tvar config AppConfig\n\tif err := v.Unmarshal(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}", "func (c *Config) Load() error {\n\tif err := env.Parse(c); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func LoadConfig() {\n\tviper.SetEnvPrefix(\"yestea\")\n\tviper.AutomaticEnv()\n\n\tviper.SetConfigType(\"yaml\")\n\tviper.AddConfigPath(RootPath() + \"config\")\n\n\tviper.SetConfigName(\"config\")\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tpanic(fmt.Errorf(\"read common config failed: [%s]\", err))\n\t}\n\n\tenv := viper.GetString(\"ENV\")\n\tif env == \"\" {\n\t\tviper.SetConfigName(\"dev\")\n\t}\n\tviper.SetConfigName(env)\n\tif err := viper.MergeInConfig(); err != nil {\n\t\tpanic(fmt.Errorf(\"merge environment config failed: [%s]\", err))\n\t}\n}", "func LoadConfig(filename string) (*Configuration, error) {\n\tif err := loadEnvironment(filename); err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := new(Configuration)\n\tif err := envconfig.Process(\"oe\", config); err != nil {\n\t\treturn nil, err\n\t}\n\tconfig.ApplyDefaults()\n\treturn config, nil\n}", "func (config *Config) Load() error {\n\tvar env string\n\tflag.StringVar(&env, \"env\", \"dev\", \"environment\")\n\n\tflag.Parse()\n\n\tviperRegistry := viper.New()\n\tviperRegistry.AddConfigPath(\"./config\")\n\tviperRegistry.SetConfigName(env)\n\tviperRegistry.SetConfigType(\"json\")\n\tviperRegistry.SetEnvPrefix(\"todo\")\n\tviperRegistry.AutomaticEnv()\n\n\tconfig.Env = env\n\n\tif err := viperRegistry.ReadInConfig(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureApplication(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureDB(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureAuth(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func LoadConfig(path string) (config Config, err error) {\n\tSetDefaults()\n\tviper.AddConfigPath(path)\n\t// viper.SetConfigName(\"\")\n\tviper.SetConfigFile(\".env\")\n\tviper.SetConfigType(\"env\")\n\tviper.SetEnvPrefix(\"ezptt\") // will be uppercased automatically\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\tif err = viper.ReadInConfig(); err != nil {\n\t\tfmt.Println(\"ReadInConfig:\", err)\n\t}\n\n\terr = viper.Unmarshal(&config)\n\tfmt.Println(\"config:\", config)\n\treturn\n}", "func LoadConfig(path string) (config Config, err error) {\n\tviper.AddConfigPath(path)\n\tviper.SetConfigName(\".env\")\n\tviper.SetConfigType(\"env\")\n\n\tviper.AutomaticEnv()\n\n\terr = viper.ReadInConfig()\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = viper.Unmarshal(&config)\n\treturn\n}", "func LoadConfig() *Config {\n\tviper.SetConfigName(\"config\")\n\tviper.AddConfigPath(\"./\")\n\tviper.AddConfigPath(\"../../\")\n\tviper.SetConfigType(\"yaml\")\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\tviper.AutomaticEnv()\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\tfmt.Println(\"No config file. Envs will be used\")\n\t\t} else {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\terr = bindEnvKeys(Config{})\n\tthrowError(err, \"Unable to bind env keys\")\n\n\tvar config Config\n\tdefaults.SetDefaults(&config)\n\terr = viper.Unmarshal(&config)\n\tthrowError(err, \"viper unmarshal failed\")\n\treturn &config\n}", "func LoadConfigFromEnv() Config {\n\tvar gcp Config\n\tconfig.LoadEnvConfig(&gcp)\n\treturn gcp\n}", "func Load(environmentVariablesWithDefaults Map) *config {\n\tparsedConfigs := Map{}\n\n\t// Load bundledConfigs into custom ones only if custom not define them already\n\tfor environmentVariable, defaultValue := range bundledConfigs {\n\t\tif _, exists := environmentVariablesWithDefaults[environmentVariable]; !exists {\n\t\t\tenvironmentVariablesWithDefaults[environmentVariable] = defaultValue\n\t\t}\n\t}\n\n\t// Parse merge custom and bundledConfigs fetching environment variables\n\tfor environmentVariable, defaultValue := range environmentVariablesWithDefaults {\n\t\tparsedConfigs[toCamelCase(environmentVariable)] = getEnvVarWithDefault(environmentVariable, defaultValue)\n\t}\n\n\treturn &config{parsedConfigs}\n}", "func ConfigFromEnv() Config {\n\tdefaultEnv := func(key, def string) string {\n\t\tif val := os.Getenv(key); val != \"\" {\n\t\t\treturn val\n\t\t}\n\t\treturn def\n\t}\n\n\treturn Config{\n\t\tDailySnapshots: true,\n\t\tDatabasePath: defaultEnv(\"HIPPIAS_DB\", \"\"),\n\t\tListenPort: defaultEnv(\"HIPPIAS_PORT\", \"10100\"),\n\t\tOasisSocket: defaultEnv(\"HIPPIAS_SOCKET\", \"./internal.sock\"),\n\t\tSnapshotFrequency: 0,\n\t}\n}", "func LoadConfigFromEnv() Config {\n\tvar ora Config\n\tconfig.LoadEnvConfig(&ora)\n\treturn ora\n}", "func LoadConfigs() (Config, error) {\n\tvar cfg Config\n\terr := envconfig.Process(\"\", &cfg)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\treturn cfg, nil\n}", "func LoadEnv() (Config, error) {\n\n\tpathToEnv := os.Getenv(EnvConfigPath)\n\tif pathToEnv == \"\" {\n\t\tpathToEnv = \".env\"\n\t}\n\n\tlog.Info().Msgf(\"Now reading config file %s\", pathToEnv)\n\tvar c Config\n\terr := godotenv.Load(pathToEnv)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\terr = envconfig.Process(configPrefix, &c)\n\treturn c, err\n}", "func LoadConfigFromEnv() Config {\n\tvar conf Config\n\tenvconfig.Load(&conf)\n\treturn conf\n}", "func LoadConfigFromEnv() (*Config, error) {\n\tvar c Config\n\n\tuser, ok := os.LookupEnv(\"DB_USER\")\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"DB_USER is empty\")\n\t}\n\n\tpass, ok := os.LookupEnv(\"DB_PASS\")\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"DB_PASS is empty\")\n\t}\n\n\tname, ok := os.LookupEnv(\"DB_NAME\")\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"DB_NAME is empty\")\n\t}\n\n\tport, ok := os.LookupEnv(\"DB_PORT\")\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"DB_PORT is empty\")\n\t}\n\n\thost, ok := os.LookupEnv(\"DB_HOST\")\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"DB_HOST is empty\")\n\t}\n\n\tc.DBUser = user\n\tc.DBPass = pass\n\tc.DBName = name\n\tc.DBPort = port\n\tc.DBHost = host\n\n\treturn &c, nil\n}", "func LoadConfig() {\n\terr := godotenv.Load(\".env\")\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to load the .env file\")\n\t}\n}", "func LoadConfig() *Config {\n\tconfig := Config{}\n\tdefConf := DefaultConfig()\n\tfile := FileConfig(ConfigPath())\n\tenv := EnvConfig()\n\treturn config.Apply(defConf).Apply(file).Apply(env)\n}", "func LoadConfig(filePath string) (*MainConfig, error) {\n\tcfg := MainConfig{}\n\tif filePath != \"\" {\n\t\terr := readFile(&cfg, filePath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\terr := readEnv(&cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cfg, nil\n}", "func LoadConfig() Config {\n\tnotSet := 0\n\t_, isSet := os.LookupEnv(\"POSTGRES_PORT\")\n\tif !isSet {\n\t\tfmt.Println(\"POSTGRES_PORT not set\")\n\t\tnotSet++\n\t}\n\t_, isSet = os.LookupEnv(\"POSTGRES_USER\")\n\tif !isSet {\n\t\tfmt.Println(\"POSTGRES_USER not set\")\n\t\tnotSet++\n\t}\n\t_, isSet = os.LookupEnv(\"POSTGRES_PASSWORD\")\n\tif !isSet {\n\t\tfmt.Println(\"POSTGRES_PASSWORD not set\")\n\t\tnotSet++\n\t}\n\t_, isSet = os.LookupEnv(\"POSTGRES_DB\")\n\tif !isSet {\n\t\tfmt.Println(\"POSTGRES_DB not set\")\n\t\tnotSet++\n\t}\n\t_, isSet = os.LookupEnv(\"POSTGRES_HOST\")\n\tif !isSet {\n\t\tfmt.Println(\"POSTGRES_HOST not set\")\n\t\tnotSet++\n\t}\n\tif notSet != 0 {\n\t\tfmt.Println(\"Using default config...\")\n\t\treturn DefaultConfig()\n\t}\n\tfmt.Println(\"Using env vars to config connection... \\n POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB, POSTGRES_HOST, POSTGRES_PORT\")\n\treturn EnvVarsConfig()\n}", "func loadEnv() Configuration {\n\thistorySize := 10\n\thistorySizeStr := os.Getenv(\"HISTORY_SIZE\")\n\tif historySizeStr != \"\" {\n\t\thistorySize , _ = strconv.Atoi(historySizeStr)\n\t}\n\tthreads := 10\n\tthreadsStr := os.Getenv(\"THREADS\")\n\tif threadsStr != \"\" {\n\t\tthreads, _ = strconv.Atoi(threadsStr)\n\t}\n\tserverUrl := os.Getenv(\"SERVER_URL\")\n\tif serverUrl == \"\" {\n\t\tserverUrl = \":9000\"\n\t}\n\tclientUrl := os.Getenv(\"CLIENT_URL\")\n\tif clientUrl == \"\" {\n\t\tclientUrl = \":9001\"\n\t}\n\treturn Configuration{\n\t\tHistorySize: historySize,\n\t\tClientUrl: clientUrl,\n\t\tServerUrl: serverUrl,\n\t\tThreads: threads}\n}", "func Load() *Config {\n\tif savedConfig != nil {\n\t\treturn savedConfig\n\t}\n\n\tif os.Getenv(envUseEnvConfig) == \"true\" {\n\t\tlog.Println(\"Info: [config] Load from env\")\n\t\tsavedConfig = loadFromEnv()\n\t} else {\n\t\tpath := os.Getenv(envConfigPath)\n\t\tif len(path) == 0 {\n\t\t\tpath = defaultConfigPath\n\t\t}\n\t\tlog.Println(\"Info: [config] Load from file: \", path)\n\t\tsavedConfig = loadFromConfig(path)\n\t}\n\n\tlog.Printf(\"Info: [config] Load, load: %+v\\n\", savedConfig)\n\treturn savedConfig\n}", "func LoadConfig(path string) (config Config, err error) {\n\tviper.AddConfigPath(path)\n\tviper.SetConfigName(\"app\")\n\tviper.SetConfigType(\"env\")\n\n\tviper.AutomaticEnv()\n\n\terr = viper.ReadInConfig()\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = viper.Unmarshal(&config)\n\treturn\n}", "func LoadConfig(path string) (config Config, err error) {\n\tviper.AddConfigPath(path)\n\tviper.SetConfigName(\"app\")\n\tviper.SetConfigType(\"env\")\n\n\tviper.AutomaticEnv()\n\n\terr = viper.ReadInConfig()\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = viper.Unmarshal(&config)\n\treturn\n}", "func LoadConfig(path string) (config Config, err error) {\n\tviper.AddConfigPath(path)\n\tviper.SetConfigName(\"app\")\n\tviper.SetConfigType(\"env\")\n\n\tviper.AutomaticEnv()\n\n\terr = viper.ReadInConfig()\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = viper.Unmarshal(&config)\n\treturn\n}", "func Load(appName string) (*Configuration, error) {\n\tvar cfg Configuration\n\tif err := envconfig.Process(appName, &cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"error loading configuration for %s: %s\", appName, err)\n\t}\n\n\treturn &cfg, nil\n}", "func (c *Config) LoadFromEnv() error {\n\terr := envconfig.Process(\"\", c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't process environment for config: %w\", err)\n\t}\n\n\treturn nil\n}", "func LoadConfigFromEnv() *Config {\n\tvar mongo Config\n\tconfig.LoadEnvConfig(&mongo)\n\treturn &mongo\n}", "func LoadConfig(filename string) (*Configuration, error) {\n\tif err := loadEnvironment(filename); err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := new(Configuration)\n\tif err := envconfig.Process(\"gocommerce\", config); err != nil {\n\t\treturn nil, err\n\t}\n\tconfig.ApplyDefaults()\n\treturn config, nil\n}", "func loadConfig() {\n\terr := godotenv.Load()\n\n\tif err != nil {\n\t\tlog.Println(\"did not load any .env file\")\n\t}\n\n\terr = env.Parse(&cfg)\n\n\tif err != nil {\n\t\tlog.Fatal(\"The .env format is not valid\", err)\n\t}\n}", "func LoadConfig(prefix string) (*Config, error) {\n\tres := &Config{}\n\treturn res, errors.Wrap(envconfig.Process(prefix, res), \"parse config\")\n}", "func (c *AppConfig) LoadConfig() {\n\tif Config.WorkPath != Config.AppPath {\n\t\tos.Chdir(Config.AppPath)\n\t}\n\n\tconfigFile := filepath.Join(Config.AppPath, \".env\")\n\tif _, err := os.Stat(configFile); os.IsNotExist(err) {\n\t\tlog.Warnf(\"No Config File Loaded, Using Default Config ...\")\n\t} else {\n\t\tgodotenv.Load(configFile)\n\t}\n}", "func LoadConfig(configPath string) *models.Configuration {\r\n\r\n\tviper.SetEnvPrefix(\"EDUCATIVE\")\r\n\tviper.AddConfigPath(\".\")\r\n\tviper.SetConfigFile(configPath)\r\n\terr := viper.MergeInConfig()\r\n\tif err != nil {\r\n\t\tfmt.Println(\"Error in reading config\")\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\terr = viper.Unmarshal(&CFG, func(config *mapstructure.DecoderConfig) {\r\n\t\tconfig.TagName = \"yaml\"\r\n\t})\r\n\tif err != nil {\r\n\t\tfmt.Println(\"Error in un-marshaling config\")\r\n\t\tpanic(err)\r\n\t}\r\n\t// fillBanningJobTime()\r\n\tif CFG.APP.LogLevel == \"info\" {\r\n\t\tfmt.Printf(\"%#v \\n\", CFG)\r\n\t}\r\n\r\n\tpostgres, err := GetPostgres()\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tutil.Initialize()\r\n\treturn &models.Configuration{\r\n\t\tPostgresConnection: postgres,\r\n\t}\r\n}", "func Load(env string) *Configuration {\n\t_, filePath, _, _ := runtime.Caller(0)\n\tconfigName := \"config.\" + env + \".yaml\"\n\tconfigPath := filePath[:len(filePath)-9] + \"files\" + string(filepath.Separator)\n\n\tviper.SetConfigName(configName)\n\tviper.AddConfigPath(configPath)\n\tviper.SetConfigType(\"yaml\")\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar config Configuration\n\tviper.Unmarshal(&config)\n\tsetGinMode(config.Server.Mode)\n\n\treturn &config\n}", "func loadFromEnvvar() (*Config, error) {\n\t// App\n\tappServerPort, _ := strconv.Atoi(GetEnvOrDef(\"POSLAN_SERVER_PORT\", \"8080\"))\n\tappLogLevel := GetEnvOrDef(\"POSLAN_LOG_LEVEL\", \"debug\")\n\tproviders := loadProvidersFromEnvars()\n\n\tapp := AppConfig{\n\t\tServerPort: appServerPort,\n\t\tLogLevel: logLevel(appLogLevel),\n\t}\n\n\tmailers := MailerConfig{\n\t\tProviders: providers,\n\t}\n\n\tcfg := &Config{\n\t\tApp: app,\n\t\tMailer: mailers,\n\t}\n\n\treturn cfg, nil\n}", "func LoadConfig(logger *logrus.Logger) *AppConfiguration {\n\tconfig := viper.New()\n\tconfig.AddConfigPath(\"./\")\n\tconfig.SetConfigName(\"config\")\n\n\tvar currentConfig *AppConfiguration\n\tconfig.ReadInConfig()\n\terr := config.Unmarshal(&currentConfig)\n\tif os.Getenv(\"CONFIG\") != \"\" {\n\t\terr = yaml.Unmarshal([]byte(os.Getenv(\"CONFIG\")), currentConfig)\n\t}\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Cannot load the configuration file %s\", err.Error()))\n\t}\n\tcurrentConfig.Print(logger)\n\treturn currentConfig\n}", "func Load() (Config, error) {\n\tvar c Config\n\terr := envconfig.Process(\"ferrum\", &c)\n\tif err != nil {\n\t\treturn Config{}, fmt.Errorf(\"failed to parse configuration env vars: %v\", err)\n\t}\n\n\tc.LogLevel, err = log.ParseLevel(c.LogLevelRaw)\n\tif err != nil {\n\t\treturn Config{}, fmt.Errorf(\"failed to parse log level: %v\", err)\n\t}\n\n\tc.Version = version\n\tc.BuildDate = buildDate\n\n\treturn c, nil\n}", "func (c *Config) LoadConfig() (err error) {\n\tpath = os.Getenv(envConfigPath)\n\tif path == \"\" {\n\t\tpath, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif path == \"/\" {\n\t\t\tpath = \".\"\n\t\t}\n\t}\n\tpath = path + \"/config.json\"\n\n\terr = LoadConfig(path, c)\n\tif err != nil {\n\t\tfmt.Println(\"LoadConfig err\", err)\n\t\treturn\n\t}\n\terr = c.overWrite()\n\n\treturn\n}", "func Config() (*Configuration, error) {\n\n\t// viper config/env key replacer configuration\n\tviper.AutomaticEnv()\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\n\t// Bind viper keys to env vars\n\tfor _, v := range envVars {\n\t\tif err := viper.BindEnv(v); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// unmarshall the configuration structure\n\tvar config Configuration\n\tif err := viper.Unmarshal(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set env config. file name, type and path\n\tviper.SetConfigName(\".env\")\n\tviper.SetConfigType(\"env\")\n\tviper.AddConfigPath(\".\")\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := viper.Unmarshal(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set every one of env variables into os\n\tfor _, v := range envVars {\n\t\tos.Setenv(v, viper.GetString(v))\n\t}\n\n\treturn &config, nil\n}", "func LoadConfig(configFile string) (*Config, error) {\n\tvar data []byte\n\tvar err error\n\tif data, err = ioutil.ReadFile(configFile); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Expand envirovment variables defined in the config\n\tdata = []byte(os.ExpandEnv(string(data)))\n\n\tvar c Config\n\tif err := yaml.Unmarshal([]byte(data), &c); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &c, nil\n}", "func LoadConfig() (*Config, error) {\n\tconfig := Config{\n\t\tMetricBatchIntervalMilliseconds: 60000,\n\t\tMetricSourceID: \"metron\",\n\t\tIncomingUDPPort: 3457,\n\t\tDebugPort: 14824,\n\t\tGRPC: GRPC{\n\t\t\tPort: 3458,\n\t\t},\n\t}\n\terr := envstruct.Load(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config.RouterAddr == \"\" {\n\t\treturn nil, fmt.Errorf(\"RouterAddr is required\")\n\t}\n\n\tconfig.RouterAddrWithAZ, err = idna.ToASCII(config.RouterAddrWithAZ)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig.RouterAddrWithAZ = strings.Replace(config.RouterAddrWithAZ, \"@\", \"-\", -1)\n\n\treturn &config, nil\n}", "func loadConfig() configuration {\n\terr := godotenv.Load(\"config.env\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading .env file\")\n\t}\n\n\tconfig := configuration{}\n\n\tconfig.cityName = os.Getenv(\"CITY_NAME\")\n\tconfig.cityLat, err = strconv.ParseFloat(os.Getenv(\"CITY_LAT\"), 64)\n\tif err != nil {\n\t\tlog.Fatal(\"CITY_LAT configuration is missing\")\n\t}\n\n\tconfig.cityLong, err = strconv.ParseFloat(os.Getenv(\"CITY_LONG\"), 64)\n\tif err != nil {\n\t\tlog.Fatal(\"CITY_LONG configuration is missing\")\n\t}\n\n\tconfig.cityTimezone, err = strconv.Atoi(os.Getenv(\"CITY_TIMEZONE\"))\n\tif err != nil {\n\t\tlog.Fatal(\"CITY_TIMEZONE configuration is missing\")\n\t}\n\n\tconfig.azanFile = os.Getenv(\"AZAN_FILENAME\")\n\tif config.azanFile == \"\" {\n\t\tlog.Fatal(\"AZAN_FILENAME configuration is missing\")\n\t}\n\n\tconfig.method = os.Getenv(\"METHOD\")\n\tif config.azanFile == \"\" {\n\t\tlog.Fatal(\"METHOD configuration is missing\")\n\t}\n\n\treturn config\n}", "func LoadConfig() (*Config, error) {\n\tc := Config{}\n\n\tif len(viper.ConfigFileUsed()) == 0 {\n\t\t// NOTE: this is here because if someone doesn't have a config.yml it will ignore the ENV vars\n\t\tif err := env.ParseWithOptions(&c, env.Options{Prefix: \"IPSW_\"}); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"config: failed to parse env vars: %v\", err)\n\t\t}\n\t}\n\n\tif err := viper.Unmarshal(&c); err != nil {\n\t\treturn nil, fmt.Errorf(\"config: failed to unmarshal: %v\", err)\n\t}\n\n\tif err := c.verify(); err != nil {\n\t\treturn nil, fmt.Errorf(\"config: failed to verify: %v\", err)\n\t}\n\n\treturn &c, nil\n}", "func Load() error {\n\tfile, err := os.Open(\".env/config.json\")\n\tdefer file.Close()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparser := json.NewDecoder(file)\n\terr = parser.Decode(&config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(config.Backend.MongoDB.URI) < 1 {\n\t\tconfig.Backend.MongoDB.URI = \"mongodb://127.0.0.1:27017\"\n\t}\n\n\tif len(config.Backend.MongoDB.Database) < 1 {\n\t\tconfig.Backend.MongoDB.Database = \"ikuta\"\n\t}\n\n\tif len(config.HTTP.Address) < 1 {\n\t\tconfig.HTTP.Address = \":7136\"\n\t}\n\n\treturn nil\n}", "func LoadConfig(configPath string, env string) error {\n\tv := viper.New()\n\n\tif env != \"\" {\n\t\tv.SetConfigName(\"config.\" + env)\n\t}\n\n\tv.SetConfigType(\"yaml\")\n\tv.AddConfigPath(configPath)\n\n\terr := v.ReadInConfig()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to read the configuration file: %s\", err)\n\t}\n\n\tv.SetEnvPrefix(\"tomo\")\n\tv.AutomaticEnv()\n\n\terr = v.Unmarshal(&Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// log information\n\n\tlogger.Infof(\"Server port: %v\", Config.ServerPort)\n\tlogger.Infof(\"Ethereum node HTTP url: %v\", Config.Ethereum[\"http_url\"])\n\tlogger.Infof(\"Ethereum node WS url: %v\", Config.Ethereum[\"ws_url\"])\n\tlogger.Infof(\"MongoDB url: %v\", Config.DSN)\n\tlogger.Infof(\"Redis url: %v\", Config.Redis)\n\tlogger.Infof(\"RabbitMQ url: %v\", Config.Rabbitmq)\n\tlogger.Infof(\"Exchange contract address: %v\", Config.Ethereum[\"exchange_address\"])\n\tlogger.Infof(\"Fee Account: %v\", Config.Ethereum[\"fee_account\"])\n\n\treturn Config.Validate()\n}", "func Load() (*Config, error) {\n\tcfg := &Config{}\n\terr := envconfig.Process(\"\", cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.TranslationsPath == \"\" {\n\t\tv, err := promtParameter(\"TRANSLATIONS_PATH\", true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcfg.TranslationsPath = v\n\t}\n\n\tif cfg.TargetAPIAuthorizationKey == \"\" {\n\t\tv, err := promtParameter(\"TARGET_API_AUTHORIZATION_KEY\", true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg.TargetAPIAuthorizationKey = v\n\t}\n\n\tif cfg.TargetAPIHost == \"\" {\n\t\tv, err := promtParameter(\"TARGET_API_HOST\", true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg.TargetAPIHost = v\n\t}\n\n\tif cfg.OrgIDSNCF == \"\" {\n\t\tv, err := promtParameter(\"ORGID_SNCF\", false)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif v == \"\" {\n\t\t\tfmt.Println(fmt.Sprintf(\"Note! Translations won't be uploaded for SNCF\"))\n\t\t}\n\n\t\tcfg.OrgIDSNCF = v\n\t}\n\n\tif cfg.OrgIDThalys == \"\" {\n\t\tv, err := promtParameter(\"ORGID_THALYS\", false)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif v == \"\" {\n\t\t\tfmt.Println(fmt.Sprintf(\"Note! Translations won't be uploaded for THALYS\"))\n\t\t}\n\n\t\tcfg.OrgIDThalys = v\n\t}\n\n\treturn cfg, nil\n}", "func (kr *KRun) LoadConfig(ctx context.Context) error {\n\terr := kr.K8SClient(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Load additional settings from env.\n\tkr.initFromEnv()\n\n\t// It is possible to have only one of the 2 mesh connector services installed\n\tif kr.XDSAddr == \"\" || kr.ProjectNumber == \"\" ||\n\t\t(kr.MeshConnectorAddr == \"\" && kr.MeshConnectorInternalAddr == \"\") {\n\t\terr := kr.loadMeshEnv(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn err\n}", "func Load(c Config) error {\n\tc.setDefaults()\n\tc.setCoreUp()\n\n\tif err := c.load(defaultEnv); err != nil {\n\t\treturn fmt.Errorf(\"error reading default configuration file:\", err)\n\t}\n\n\tenv := c.getEnv()\n\tif err := c.merge(env); err != nil {\n\t\treturn fmt.Errorf(\"error reading %s configuration file:\", env, err)\n\t}\n\n\treturn nil\n}", "func loadEnvironmentConfig(env string) types.Options {\n\tconfigFile := \"config/\" + ServiceName + \"/\" + env + \".json\"\n\tif _, err := os.Stat(configFile); os.IsNotExist(err) {\n\t\tpanic(err)\n\t}\n\treturn parseConfigFile(configFile)\n}", "func ReadConfig() (*Config, error) {\n\tconfig := &Config{}\n\tconfig.MinIOProvider = &MinIOProvider{}\n\n\tfor _, cv := range configVars {\n\t\tvar value any\n\t\tvar parseErr error\n\t\tstrValue, err := readConfigVar(cv)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Parse the environment variable depending of its type\n\t\tswitch cv.varType {\n\t\tcase stringType:\n\t\t\tvalue = strings.TrimSpace(strValue)\n\t\tcase stringSliceType:\n\t\t\tvalue = parseStringSlice(strValue)\n\t\tcase intType:\n\t\t\tvalue, parseErr = strconv.Atoi(strValue)\n\t\tcase boolType:\n\t\t\tvalue, parseErr = strconv.ParseBool(strValue)\n\t\tcase secondsType:\n\t\t\tvalue, parseErr = parseSeconds(strValue)\n\t\tcase serverlessBackendType:\n\t\t\tvalue, parseErr = parseServerlessBackend(strValue)\n\t\tcase urlType:\n\t\t\t// Only check if can be parsed\n\t\t\t_, parseErr = url.Parse(strValue)\n\t\t\tvalue = strValue\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t\t// If there are some parseErr return error\n\t\tif parseErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"the %s value is not valid. Expected type: %s. Error: %v\", cv.envVarName, cv.varType, parseErr)\n\t\t}\n\n\t\t// Set the value in the Config struct\n\t\tsetValue(value, cv.name, config)\n\n\t}\n\n\treturn config, nil\n}", "func (ts *Tester) LoadConfig() (eksconfig.Config, error) {\n\treturn *ts.cfg, nil\n}", "func LoadConfig() (*Config, error) {\n\tc := Config{\n\t\tInterval: time.Minute,\n\t}\n\n\tif err := envstruct.Load(&c); err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvstruct.WriteReport(&c)\n\treturn &c, nil\n}", "func LoadConfig() (*Config, error) {\n\tconfig := Config{\n\t\tMetricEmitterInterval: time.Minute,\n\t}\n\n\terr := envstruct.Load(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = config.validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = envstruct.WriteReport(&config)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to print a report of the from environment: %s\\n\", err)\n\t}\n\n\treturn &config, nil\n}", "func (c *Config) LoadConfig() (err error) {\n\tpath := os.Getenv(envConfigPath)\n\tif path == \"\" {\n\t\tpath, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif path == \"/\" {\n\t\t\tpath = \".\"\n\t\t}\n\t}\n\tc.path = path + \"/config.json\"\n\terr = LoadConfig(c.path, c)\n\tif err != nil {\n\t\tfmt.Println(\"LoadConfig err\", err)\n\t\treturn\n\t}\n\n\terr = c.overWrite()\n\n\treturn\n}", "func Load(configFile string) (*Config, error) {\n\t// User explicitly specified a config file\n\tif configFile != \"\" {\n\t\treturn ParseConfigFile(configFile)\n\t}\n\n\t// There is a config in the current directory\n\tif fi, err := os.Stat(defaultConfigFile); err == nil {\n\t\treturn ParseConfigFile(fi.Name())\n\t}\n\n\t// Use default values\n\tlog.Println(\"Running dev mode with default settings, consult config when you're ready to run in production\")\n\tcfg := defaultConfig()\n\treturn cfg, envOverride(cfg)\n}", "func loadConfig() (config Config) {\n var set bool\n if config.DockerSock, set = os.LookupEnv(\"DOCKER_SOCK\"); !set {\n config.DockerSock = \"/var/run/docker.sock\"\n }\n if config.VaultAddr, set = os.LookupEnv(\"VAULT_ADDR\"); !set {\n config.VaultAddr = \"http://127.0.0.1:8200\"\n }\n config.VaultSalt, _ = os.LookupEnv(\"VAULT_SALT\")\n return\n}", "func LoadConfig(debug bool, environment string, configDir string) Config {\n\tv := viper.GetViper()\n\n\tv.AddConfigPath(configDir)\n\tv.SetConfigName(fmt.Sprintf(\"config.%s\", environment))\n\n\terr := v.ReadInConfig()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config from %s\", configDir))\n\t}\n\n\tport := v.GetInt(\"api.server.port\")\n\treturn NewConfig(debug, port)\n}", "func LoadConfig(configFile string) (*Configuration, error) {\n\tsetConfigDefaults()\n\n\tif len(configFile) > 0 {\n\t\tviper.SetConfigFile(configFile)\n\t} else {\n\t\tviper.SetConfigName(\"copyql\")\n\t\tviper.AddConfigPath(\".\")\n\t}\n\n\tviper.SetEnvPrefix(\"copyql\")\n\tviper.AutomaticEnv()\n\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\n\tviper.ReadInConfig()\n\n\tvar config Configuration\n\terr := viper.Unmarshal(&config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}", "func Load() (Config, error) {\n\tvar cfg Config\n\tcfg.AwsRegion = findEnvVar(\"AWS_REGION\")\n\treturn cfg, nil\n}", "func ConfigFromEnv() Config {\n\treturn Config{\n\t\tServerPort: getEnvOrElse(\"SERVER_PORT\", \"8080\"),\n\t\tDBPort: getEnvOrElse(\"DB_PORT\", \"28015\"),\n\t\tDBHost: getEnvOrElse(\"DB_HOST\", \"localhost\"),\n\t\tDBName: getEnvOrElse(\"DB_NAME\", \"been_there\"),\n\t\tVisitsTable: getEnvOrElse(\"VISITS_TABLE\", \"visits\"),\n\t\tCitiesTable: getEnvOrElse(\"CITIES_TABLE\", \"cities\"),\n\t}\n}", "func LoadConfig(filename string) *revel.MergedConfig {\n\tif *searchPath != \"\" {\n\t\tAddSearchPath(*searchPath)\n\t\t*searchPath = \"\"\n\t}\n\n\tc, err := loadPriorConfig(filename)\n\tif err != nil {\n\t\trevel.ERROR.Printf(\"error load config: %s\", err.Error())\n\t\trevel.ERROR.Printf(\"filename: %s, runmode: %s, path: %s\", filename, revel.RunMode, revel.ConfPaths)\n\t}\n\treturn c\n}", "func LoadConfig() (*Config, error) {\n\tnodeMap, err := loadNodeMapFromEnv()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// NodeMap's key has '.', set viper key delimiter to avoid parsing it as a nested key\n\tv := viper.NewWithOptions(viper.KeyDelimiter(keyDelimiter))\n\tv.SetConfigType(configTypeYaml)\n\n\t// read the default\n\tif err := v.ReadConfig(bytes.NewBuffer([]byte(defaultConfig))); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// load configuration file from current directory\n\tv.SetConfigName(configName)\n\tv.AddConfigPath(\".\")\n\tif err := mergeExternalConfigFile(v); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif envConfigFile, ok := os.LookupEnv(apiConfigEnvKey); ok {\n\t\tv.SetConfigFile(envConfigFile)\n\t\tif err := mergeExternalConfigFile(v); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// enable parsing env variables after the configuration files are loaded so viper knows all configuration keys\n\t// and can override the config accordingly\n\tv.AutomaticEnv()\n\tv.SetEnvKeyReplacer(strings.NewReplacer(keyDelimiter, envKeyDelimiter))\n\n\tvar config fullConfig\n\tcompositeDecodeHookFunc := mapstructure.ComposeDecodeHookFunc(\n\t\tmapstructure.StringToTimeDurationHookFunc(),\n\t\tnodeMapDecodeHookFunc,\n\t)\n\tif err := v.Unmarshal(&config, viper.DecodeHook(compositeDecodeHookFunc)); err != nil {\n\t\treturn nil, err\n\t}\n\n\trosettaConfig := &config.Hedera.Mirror.Rosetta\n\trosettaConfig.Network = strings.ToLower(rosettaConfig.Network)\n\tif len(nodeMap) != 0 {\n\t\trosettaConfig.Nodes = nodeMap\n\t}\n\n\tvar password = rosettaConfig.Db.Password\n\trosettaConfig.Db.Password = \"\" // Don't print password\n\tlog.Infof(\"Using configuration: %+v\", rosettaConfig)\n\trosettaConfig.Db.Password = password\n\n\treturn rosettaConfig, nil\n}", "func loadConfig() *config {\n\tc := &config{}\n\tdefaults := configDefaults[Env()]\n\tconfigFile, err := loadConfigFile(os.ExpandEnv(\"$HOME/.gotrix/config.json\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tc.ApplicationName = configValue(\"APPLICATION_NAME\", configFile.ApplicationName, defaults.ApplicationName)\n\tc.DatabaseURL = configValue(\"DATABASE_URL\", configFile.DatabaseURL, defaults.DatabaseURL)\n\tc.Port = configValue(\"PORT\", configFile.Port, defaults.Port)\n\n\treturn c\n}", "func LoadConfig() *Config {\n\tvar config Config\n\terr := env.Load(prefix, &config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to load configuration. err: \" + err.Error())\n\t}\n\tACCESSSECRET = config.accessSecret\n\tREFRESHSECRET = config.refreshSecret\n\tlog.Println(\"Config successfully Loaded\")\n\treturn &config\n}", "func ReadConfig() *error {\n\tvar env = os.Getenv(\"ENV\")\n\n\tgame.Appartement.Bots = Config.Bots\n\tfile, err := os.Open(\"/env/config.\" + env + \".json\")\n\tif err != nil {\n\t\tlog.Println(prefixWarn, \"ENV must be of: 'localhost', 'dev' or 'prod'. starting with default configuration\")\n\t\treturn &err\n\t}\n\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&Config)\n\tif err != nil {\n\t\treturn &err\n\t}\n\n\treturn nil\n}", "func loadConfig() Config {\n\tvar args struct {\n\t\tConfigfile string `arg:\"positional\" help:\"the name of the .toml config file to load\"`\n\t\tNoCheck bool `help:\"set this to disable checking that envvar substitutions are fully resolved\"`\n\t}\n\targ.MustParse(&args)\n\n\tvar cfg Config\n\tvar err error\n\tif args.Configfile != \"\" {\n\t\tcfg, err = Load(args.Configfile, args.NoCheck)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\treturn cfg\n\t}\n\tfmt.Println(\"a config file name is required!\")\n\tos.Exit(1)\n\treturn cfg\n}", "func LoadConfig(parentPath string, container string, env string, fileNames ...string) ServiceConfig {\n\tviper.AutomaticEnv()\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\", \".\", \"_\"))\n\tviper.SetConfigType(\"yaml\")\n\n\tfor _, fileName := range fileNames {\n\t\tviper.SetConfigName(fileName)\n\t}\n\n\tviper.AddConfigPath(\"./\" + container + \"/\")\n\tif len(parentPath) > 0 {\n\t\tviper.AddConfigPath(\"./\" + parentPath + \"/\" + container + \"/\")\n\t}\n\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tswitch err.(type) {\n\t\tcase viper.ConfigFileNotFoundError:\n\t\t\tlog.Println(\"config file not found\")\n\t\tdefault:\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tif len(env) > 0 {\n\t\tenv2 := strings.ToLower(env)\n\t\tfor _, fileName2 := range fileNames {\n\t\t\tname := fileName2 + \"-\" + env2\n\t\t\tviper.SetConfigName(name)\n\t\t\tviper.MergeInConfig()\n\t\t}\n\t}\n\tvar c ServiceConfig\n\tbindEnvs(c)\n\tviper.Unmarshal(&c)\n\treturn c\n}", "func LoadAuthConfig(filenames ...string) (authConfig AuthConfig, err error) {\n\terr = gotenv.Load(filenames...)\n\tif err != nil {\n\t\tlogging.Error(\"Error loading .env file: \", err)\n\t\treturn\n\t}\n\tauthConfig = map[string]map[string]string{\n\t\t\"google\": {\n\t\t\t\"clientID\": loadStringEnv(\"GOOGLE_CLIENT_ID\"),\n\t\t\t\"clientSecret\": loadStringEnv(\"GOOGLE_CLIENT_SECRET\"),\n\t\t\t\"callbackURL\": loadStringEnv(\"GOOGLE_CALLBACK_URL\"),\n\t\t},\n\t}\n\treturn\n}", "func LoadConfig(configPaths ...string) error {\n\tv := viper.New()\n\n\t// Postgreslq config\n\tv.SetDefault(\"db_max_open_conns\", 5)\n\tv.SetDefault(\"db_conn_exec_timeout\", 3000000)\n\tv.SetDefault(\"db_max_idle_conns_rate\", 0.5)\n\tv.SetDefault(\"db_conn_max_lifetime\", time.Minute*30)\n\n\t// Server port\n\tv.SetDefault(\"server_port\", 9393)\n\tv.SetDefault(\"address\", \"http://localhost:9393\")\n\tv.SetDefault(\"access_token_TTL\", 8)\n\tv.SetDefault(\"jwt_signing_method\", \"HS256\")\n\n\tlogrus.Infof(\"Load configuration in DEV mode\")\n\tv.SetConfigName(\"app\")\n\tv.SetConfigType(\"yaml\")\n\tv.AutomaticEnv()\n\tfor _, path := range configPaths {\n\t\tv.AddConfigPath(path)\n\t}\n\tif err := v.ReadInConfig(); err != nil {\n\t\treturn fmt.Errorf(\"Failed to read the configuration file: %s\", err)\n\t}\n\n\tif err := v.Unmarshal(&Config); err != nil {\n\t\treturn err\n\t}\n\n\treturn Config.Validate()\n}", "func LoadConfig() {\n\t//viper.SetDefault(\"LOG_LEVEL\", \"debug\")\n\t//viper.AutomaticEnv()\n\n\tviper.SetConfigName(\"application\")\n\tviper.AddConfigPath(\"./\")\n\tviper.AddConfigPath(\"../\")\n\tviper.AddConfigPath(\"../../\")\n\tviper.SetConfigType(\"yaml\")\n\n\tviper.ReadInConfig()\n\terr := viper.ReadInConfig() // Find and read the config file\n\tif err != nil { // Handle errors reading the config file\n\t\tpanic(fmt.Errorf(\"Fatal error config file: %s \\n\", err))\n\t}\n}", "func ReadConfigFromEnv() *Config {\n\tvar c = Config{\n\t\tPort: SafeStringToInt(os.Getenv(\"PORT\"), 8080),\n\t\tHost: os.Getenv(\"HOST\"),\n\t\tMongoDbDatabase: os.Getenv(\"MONGO_DB_DATABASE\"),\n\t\tMongoDbURI: os.Getenv(\"MONGO_DB_URI\"),\n\t}\n\treturn &c\n}", "func LoadConfiguration() (Config, error) {\n\tvar config Config\n\tconfigFile, err := os.Open(\"./config/config.\" + os.Getenv(\"ENV\") + \".json\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn config, err\n\t}\n\tdefer configFile.Close()\n\tjsonParser := json.NewDecoder(configFile)\n\terr = jsonParser.Decode(&config)\n\treturn config, err\n}", "func NewConfigFromEnv() (Config, error) {\n\tcfg := Config{\n\t\tVnetResourceGroupName: os.Getenv(VnetResourceGroupEnvName),\n\t\tVnetName: os.Getenv(VnetEnvName),\n\t\tNatSubnetName: os.Getenv(NatSubnetEnvName),\n\t\tNatSubnetPrefix: os.Getenv(NatSubnetPrefixEnvName),\n\t\tLoadBalancerResourceGroup: os.Getenv(LoadBalancerResourceGroupEnvName),\n\t\tLoadBalancerName: os.Getenv(LoadBalancerEnvName),\n\t\tServiceAnnotation: os.Getenv(ServiceAnnotationEnvName),\n\t\tAzureAuthLocation: os.Getenv(AzureAuthLocationEnvName),\n\t}\n\n\tif i, err := strconv.Atoi(os.Getenv(SyncPeriodEnvName)); err == nil{\n\t\tcfg.SyncPeriod = time.Duration(i) * time.Second\n\t} else {\n\t\tcfg.SyncPeriod = time.Duration(DefaultSyncPeriod) * time.Second\n\t}\n\n\tif i, err := strconv.Atoi(os.Getenv(MinRetryDelayEnvName)); err == nil{\n\t\tcfg.MinRetryDelay = time.Duration(i) * time.Second \n\t} else {\n\t\tcfg.MinRetryDelay = time.Duration(DefaultMinRetryDelay) * time.Second\n\t}\n\n\tif i, err := strconv.Atoi(os.Getenv(MaxRetryDelayEnvName)); err == nil{\n\t\tcfg.MaxRetryDelay = time.Duration(i)\n\t} else {\n\t\tcfg.MaxRetryDelay = time.Duration(DefaultMaxRetryDelay) * time.Second\n\t}\n\n\tif cfg.ServiceAnnotation == \"\" {\n\t\tcfg.ServiceAnnotation = DefaultServiceAnnotation\n\t}\n\n\tif err := cfg.parse(); err != nil {\n\t\treturn cfg, err\n\t} \n\n\treturn cfg, nil\n}", "func LoadConfig() (Config, []string, error) {\n\t// check if config file does not exist and create it before proceeding\n\tvar configFileExists bool\n\tif _, err := os.Stat(AppConfigFilePath); os.IsNotExist(err) {\n\t\tconfigFileExists = createConfigFile()\n\t} else if !os.IsNotExist(err) {\n\t\tconfigFileExists = true\n\t}\n\n\t// load default config values and create parser object with it\n\tconfig := defaultConfig()\n\tparser := flags.NewParser(&config, flags.IgnoreUnknown)\n\n\t// parse command-line args and return any error encountered\n\tunknownArgs, err := parser.Parse()\n\tif err != nil {\n\t\treturn config, unknownArgs, err\n\t}\n\n\t// check if any of the unknown command-line args belong in the config file and alert user to set such values in config file only\n\tif hasConfigFileOption(unknownArgs) {\n\t\treturn config, unknownArgs, fmt.Errorf(\"Unexpected command-line flag/option, \"+\n\t\t\t\"see godcr -h for supported command-line flags/options\"+\n\t\t\t\"\\nSet other flags/options in %s\", AppConfigFilePath)\n\t}\n\n\t// if config file doesn't exist, no need to attempt to parse and then re-parse command-line args\n\tif !configFileExists {\n\t\treturn config, unknownArgs, nil\n\t}\n\n\t// Load additional config from file\n\terr = parseConfigFile(parser)\n\tif err != nil {\n\t\treturn config, unknownArgs, err\n\t}\n\n\t// Parse command line options again to ensure they take precedence.\n\tunknownArgs, err = parser.Parse()\n\n\t// return parsed config, unknown args encountered and any error that occurred during last parsing\n\treturn config, unknownArgs, err\n}", "func LoadConfig() (map[string]interface{}, error) {\n\treturn ReadConfig(\"\", \"\")\n}", "func LoadConfig() (bool, *Config) {\n\tconfig := new(Config)\n\tconfigEnvironment := os.Getenv(\"ENVIRONMENT_TYPE\")\n\t// Default to the development config since it is safer\n\tconfigFileName := \"config-dev.json\"\n\n\tif configEnvironment == \"PROD\" {\n\t\t// Development Environment\n\t\tconfigFileName = \"config-prod.json\"\n\t}\n\n\t// Open our jsonFile\n\tjsonFile, err := os.Open(configFileName)\n\t// if we os.Open returns an error then handle it and return an empty config\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false, config\n\t}\n\t// defer the closing of our jsonFile so that we can parse it later on\n\tdefer jsonFile.Close()\n\n\tjsonParser := json.NewDecoder(jsonFile)\n\n\tparseError := jsonParser.Decode(config)\n\tif parseError != nil {\n\t\t// Return config as is, program will end anyway as we return false here\n\t\tfmt.Println(err)\n\t\treturn false, config\n\t}\n\treturn true, config\n}", "func LoadConfig() (*Config, error) {\n\tvar config Config\n\tvar filePath string\n\n\t// Default file location\n\tif cwd, err := os.Getwd(); err == nil {\n\t\tfilePath = filepath.Join(cwd, \"config.toml\")\n\t} else {\n\t\treturn config, fmt.Errorf(\"error getting working directory: %s\", err.Error())\n\t}\n\n\t// Check if PathEnvKey is set\n\tif val, set := os.LookupEnv(PathEnvKey); set {\n\t\t// Override filePath with custom user provided value\n\t\tfilePath = val\n\t}\n\n\t// Check if filePath exists\n\tif _, err := os.Stat(filePath); os.IsNotExist(err) {\n\t\treturn config, fmt.Errorf(\"config path does not exist: %s\", filePath)\n\t}\n\n\t// Read file contents\n\tdata, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn config, fmt.Errorf(\"error reading config file \\\"%s\\\": %s\", filePath, err.Error())\n\t}\n\n\t// Load toml\n\tif _, err := toml.Decode(string(data), &config); err != nil {\n\t\treturn config, fmt.Errorf(\"failed to parse toml config file \\\"%s\\\": %s\", filePath, err.Error())\n\t}\n\n\t// Validate\n\tif err := config.Validate(); err != nil {\n\t\treturn config, fmt.Errof(\"error verifying config: %s\", err.Error())\n\t}\n\n\t// All done, return\n\treturn config, nil\n}", "func FromEnv() (*Configuration, error) {\n\treturn &Configuration{\n\t\tEndpoint: Endpoint(os.Getenv(\"OVH_ENDPOINT\")),\n\t\tApplicationKey: os.Getenv(\"OVH_APPLICATION_KEY\"),\n\t\tApplicationSecret: os.Getenv(\"OVH_APPLICATION_SECRET\"),\n\t\tConsumerKey: os.Getenv(\"OVH_CONSUMER_KEY\"),\n\t}, nil\n}", "func LoadConfig(filename string) (*viper.Viper, error) {\n\tv := viper.New()\n\t\n\tv.SetConfigName(filename)\n\tv.AddConfigPath(\".\")\n\tv.AutomaticEnv()\n\tif err := v.ReadInConfig(); err != nil {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\treturn nil, errors.New(\"config file not found\")\n\t\t}\n\t\treturn nil, err\n\t}\n\t\n\treturn v, nil\n}", "func loadConfig() (Config, error) {\n\t// We're looking for a file named \"stee.yaml\"\n\tviper.SetConfigName(\"stee\")\n\tviper.SetConfigType(\"yaml\")\n\n\t// In those directories\n\tviper.AddConfigPath(\".\")\n\tviper.AddConfigPath(\"/etc/stee/\")\n\n\t// Environement variables take precedence over file config. See https://github.com/spf13/viper#why-viper\n\tviper.AutomaticEnv()\n\n\t// Defaults are the less important values. https://github.com/spf13/viper#why-viper\n\tsetConfigDefaults()\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\tvar cfg Config\n\terr = viper.Unmarshal(&cfg)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\treturn cfg, err\n}", "func GetFromEnv() *Config {\n\tv := viper.New()\n\tv.SetDefault(DomainSuffix, \".docker.\")\n\tv.SetDefault(ServerHost, \"0.0.0.0\")\n\tv.SetDefault(ServerPort, 5300)\n\tv.SetDefault(ServerProtocol, \"udp\")\n\n\tv.AutomaticEnv()\n\n\treturn &Config{\n\t\tDomainSuffix: v.GetString(DomainSuffix),\n\t\tServerHost: v.GetString(ServerHost),\n\t\tServerPort: v.GetInt(ServerPort),\n\t\tServerProtocol: v.GetString(ServerProtocol),\n\t}\n}", "func Load() (*Config, error) {\n\tvar config Config\n\terr := envconfig.Process(\"BENJERRY\", &config)\n\treturn &config, err\n}", "func (e *Environment) LoadConfigs() {\n\t// todo: generate this based on a config file\n\tconfig = Configs{\n\t\tURL: \"https://www.mangapanda.com/one-piece/196\",\n\t\tWhitelist: []string{IMAGES},\n\t\tConcurrentRequests: 1,\n\t\tBaseURL: \"https://www.mangapanda.com\",\n\t\tRelativeURL: \"/one-piece/196\",\n\t\tMangaName: \"one-piece\",\n\t}\n}", "func LoadCfgFromEnv(e *Env) (*Cfg, error) {\n\tvar env Env\n\tvar err error\n\tif e == nil {\n\t\tif err = cli.SetEnvFields(&env); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\te = &env\n\t}\n\tc := &Cfg{\n\t\tSrc: \"Environment\",\n\t\tTenantID: e.TenantID,\n\t\tSubscriptionID: e.SubscriptionID,\n\t}\n\tif e.EnvName == \"\" || strings.EqualFold(e.EnvName, \"AzureCloud\") {\n\t\tc.Environment = azure.PublicCloud\n\t} else {\n\t\tc.Environment, err = azure.EnvironmentFromName(e.EnvName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif e.ClientSecret != \"\" {\n\t\terr = c.useClientSecret(e.ClientID, e.ClientSecret)\n\t} else if e.CertFile != \"\" {\n\t\terr = c.useClientCert(e.ClientID, e.CertFile, e.CertPass)\n\t} else {\n\t\terr = fmt.Errorf(\"az: client secret or cert file must be specified\")\n\t}\n\tif err != nil {\n\t\tc = nil\n\t}\n\treturn c, err\n}", "func New(configPath, env string) (*Config, error) {\n\tconf := &Config{env: env}\n\n\tconfigData, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\terr = yaml.Unmarshal(configData, conf)\n\tif err != nil {\n\t\treturn conf, fmt.Errorf(\"[ parsing ] an error occurred during parsing config file, please check if it's formatted correctly\")\n\t}\n\n\tif conf.Environments[conf.env] == nil {\n\t\treturn nil, fmt.Errorf(\"[ parsing ] '%s' couldn't find such an environment in configuration file\", conf.env)\n\t}\n\n\treturn conf, nil\n}", "func loadConfig(envParams envParams) error {\n\tconfigFile := getConfigFile()\n\tif _, err := os.Stat(configFile); err != nil {\n\t\treturn err\n\t}\n\n\tsrvCfg := &serverConfigV14{}\n\n\tqc, err := quick.New(srvCfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = qc.Load(configFile); err != nil {\n\t\treturn err\n\t}\n\n\t// If env is set override the credentials from 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\tif strings.ToLower(srvCfg.GetBrowser()) == \"off\" {\n\t\tglobalIsBrowserEnabled = false\n\t}\n\n\t// hold the mutex lock before a new config is assigned.\n\tserverConfigMu.Lock()\n\t// Save the loaded config globally.\n\tserverConfig = srvCfg\n\tserverConfigMu.Unlock()\n\n\tif serverConfig.Version != v14 {\n\t\treturn errors.New(\"Unsupported config version `\" + serverConfig.Version + \"`.\")\n\t}\n\n\treturn nil\n}", "func LoadConfig() Configuration {\n\treturn Configuration{\n\t\tTenant: env.String(\"VAULT_TENANT\", \"\"),\n\t\tLakeHostname: env.String(\"VAULT_LAKE_HOSTNAME\", \"127.0.0.1\"),\n\t\tRootStorage: env.String(\"VAULT_STORAGE\", \"/data\") + \"/\" + \"t_\" + env.String(\"VAULT_TENANT\", \"\"),\n\t\tLogLevel: strings.ToUpper(env.String(\"VAULT_LOG_LEVEL\", \"INFO\")),\n\t\tSnapshotSaturationTreshold: env.Int(\"VAULT_SNAPSHOT_SATURATION_TRESHOLD\", 100),\n\t\tMetricsStastdEndpoint: env.String(\"VAULT_STATSD_ENDPOINT\", \"127.0.0.1:8125\"),\n\t}\n}", "func InitConfig() Config {\n\tif !(testingMode == \"true\") && gopath != \"\" {\n\t\tfullpath := gopath + \"/src/github.com/lancetw/lubike/.env\"\n\t\terr := godotenvLoad(fullpath)\n\t\tif err != nil {\n\t\t\tlogFatalf(\"Error loading .env file %v\", fullpath)\n\t\t}\n\t}\n\n\tvar config Config\n\tconfig.UbikeEndpoint = os.Getenv(\"UBIKE_ENDPOINT\")\n\tconfig.UbikeEndpointTimeout, _ = strconv.Atoi(os.Getenv(\"UBIKE_ENDPOINT_TIMEOUT\"))\n\tconfig.MapquestAPIKey = os.Getenv(\"MAPQUEST_API_KEY\")\n\tconfig.MapquestRouteMatrixEndpoint = os.Getenv(\"MAPQUEST_ROUTE_MATRIX_ENDPOINT\")\n\tconfig.MapquestRouteMatrixEndpointTimeout, _ = strconv.Atoi(os.Getenv(\"MAPQUEST_ROUTE_MATRIX_ENDPOINT_TIMEOUT\"))\n\tconfig.GoogleMapMatrixAPIKey = os.Getenv(\"GOOGLEMAP_MATRIX_API_KEY\")\n\tconfig.GoogleMapMatrixEndpoint = os.Getenv(\"GOOGLEMAP_MATRIX_ENDPOINT\")\n\tconfig.GoogleMapMatrixEndpointTimeout, _ = strconv.Atoi(os.Getenv(\"GOOGLEMAP_MATRIX_API_ENDPOINT_TIMEOUT\"))\n\n\treturn config\n}" ]
[ "0.7702205", "0.75420463", "0.7376848", "0.7359594", "0.73004353", "0.7258485", "0.72555983", "0.72312206", "0.72135556", "0.72135556", "0.72126746", "0.7197951", "0.71574664", "0.714359", "0.7132457", "0.7123728", "0.7091951", "0.7059884", "0.70489025", "0.70198023", "0.701915", "0.70142835", "0.697287", "0.6968933", "0.69467366", "0.6942876", "0.6940311", "0.693531", "0.6900028", "0.6875352", "0.6872936", "0.6872119", "0.6869541", "0.6865157", "0.68629974", "0.68629974", "0.68629974", "0.6853229", "0.6827553", "0.6808644", "0.6805208", "0.6796195", "0.6795865", "0.6788654", "0.67865294", "0.678008", "0.6760773", "0.67548126", "0.67470163", "0.67450243", "0.6738398", "0.6735783", "0.6731769", "0.67317605", "0.6724022", "0.6720744", "0.67184657", "0.6709983", "0.66908556", "0.6682343", "0.6681243", "0.66737366", "0.666628", "0.6660213", "0.66549665", "0.6644856", "0.6640087", "0.6635642", "0.66308063", "0.661911", "0.66188097", "0.66099674", "0.65985197", "0.65945613", "0.6589026", "0.65869486", "0.6571536", "0.6567206", "0.654439", "0.65308744", "0.65019226", "0.6476871", "0.6464236", "0.645832", "0.6455352", "0.64454824", "0.64447045", "0.64309144", "0.6419852", "0.6414031", "0.6409874", "0.6408982", "0.6402961", "0.6394371", "0.6391146", "0.6391019", "0.6386866", "0.63795596", "0.6374165", "0.636733" ]
0.63605803
100
CToF converts a Celsius temperature to Fahrenheit.
func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32.0) * 5.0 / 9.0) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) / 1.8)\n}", "func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) * 5 / 9)\n}", "func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) * 5 / 9)\n}", "func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) * 5 / 9)\n}", "func FToC(f Fahrenheit) Celsius {\n\tif f <= AbsoluteZeroF {\n\t\treturn AbsoluteZeroC\n\t}\n\treturn Celsius((f - 32) * 5 / 9)\n}", "func FToC(f Farenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9.0/5.0 + 32.0) }", "func CToF(c Celsius) Farenheit { return Farenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit {\n\tif c <= AbsoluteZeroC {\n\t\treturn AbsoluteZeroF\n\t}\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*1.8 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func (c Celsius) ToF() Fahrenheit {\n\treturn CToF(c)\n}", "func CtoF(t float32) float32 {\n\treturn (t*9/5 + 32)\n}", "func toFahrenheit(t Celsius) Fahrenheit {\n\n\tvar temp Fahrenheit\n\tvar tt float32\n\ttt = (float32(t) * 1.8) + float32(32)\n\ttemp = Fahrenheit(tt)\n\treturn temp\n\n}", "func (f Fahrenheit) ToC() Celsius {\n\treturn FToC(f)\n}", "func (c Celcious) Fahrenheit() Fahrenheit {\n\treturn Fahrenheit((c * 1.8) + 32)\n}", "func (c Celsius) Fahrenheit() Fahrenheit {\n\treturn Fahrenheit((float32(c) * 1.8) + 32)\n}", "func DisplayFToC() {\n\tconst freezingF, boilingF = 32.0, 212.0\n\tfmt.Printf(\"%g°F = %g°C\\n\", freezingF, fToC(freezingF)) // 32°F = 0°C\n\tfmt.Printf(\"%g°F = %g°C\\n\", boilingF, fToC(boilingF)) // 212°F = 100°C\n}", "func (c ConversionHandler) ConvertCtoF(writer http.ResponseWriter, request *http.Request) {\n\tresult, err := decodeRequest(request)\n\n\tif err != nil {\n\t\thandleError(writer, err)\n\t\treturn\n\t}\n\n\tfahrenheit := convert.CelsiusToFahrenheit(convert.Celsius(result))\n\tformatAndSendResponse(writer, \"Fahrenheit\", fahrenheit.String())\n}", "func (f Fahrenheit) Celsius() Celsius {\n\treturn Celsius((float32(f) - 32) * float32(5) / float32(9))\n}", "func (c ConversionHandler) ConvertFtoC(writer http.ResponseWriter, request *http.Request) {\n\tresult, err := decodeRequest(request)\n\n\tif err != nil {\n\t\thandleError(writer, err)\n\t\treturn\n\t}\n\n\tcelsius := convert.FahrenheitToCelsius(convert.Fahrenheit(result))\n\tformatAndSendResponse(writer, \"Celsius\", celsius.String())\n}", "func (t Temperature) Fahrenheit() float64 {\n\treturn float64(t)\n}", "func Fahrenheit(f float64) Temperature {\n\treturn Temperature(f)\n}", "func (f Fahrenheit) Celcious() Celcious {\n\treturn Celcious((f - 32) / 1.8)\n}", "func (kh kelvinHandler) ToFahrenheit(temp float64) float64 {\n\treturn (kh.ToCelsius(temp) * fahrenheitMultiplier) + FahrenheitBase\n}", "func (t Temperature) Celsius() float64 {\n\treturn (t.Fahrenheit() - 32.0) * 5.0 / 9.0\n}", "func KToF(k Kelvin) Fahrenheit { return CToF(KToC(k)) }", "func (nch *NvmeHealth) TempF() float32 {\n\treturn (nch.TempC() * (9.0 / 5.0)) + 32.0\n}", "func convertFtoc() {\n\tconst freezingF, boilingF = 32.0, 212.0\n\n\tfmt.Printf(\"%gF = %gC\\n\", freezingF, ftoc(freezingF)) //\"32F = 0C\"\t\n\tfmt.Printf(\"%gF = %gC\\n\", boilingF, ftoc(boilingF)) //\"212F\" = 100C\"\n\n}", "func kToFToC(rowNum int) (col1, col2, col3 string, kColor, fColor, cColor int) {\n\tk := kelvin(rowNum * 5)\n\tf := k.fahrenheit()\n\tc := k.celsius()\n\tcol1 = fmt.Sprintf(tempFmt, k)\n\tcol2 = fmt.Sprintf(tempFmt, f)\n\tcol3 = fmt.Sprintf(tempFmt, c)\n\tkColor = k.color()\n\tfColor = f.color()\n\tcColor = c.color()\n\treturn col1, col2, col3, kColor, fColor, cColor\n}", "func (c *Channel) TempF() int {\n\treturn int(c.temp)\n}", "func Celsius(c float64) Temperature {\n\treturn Temperature(c*1.8 + 32.0)\n}", "func (t *Temp) F() int {\n\ttemp := math.Floor(float64(*t)*9/5) + 32\n\tif temp < 0 {\n\t\treturn int(temp - 1.0)\n\t}\n\treturn int(temp)\n}", "func TempFromF(f int) Temp {\n\tc := math.Floor(float64((f - 32)) / 1.8)\n\treturn Temp(c)\n\n}", "func (f Fahrenheit) Fahrenheit() Fahrenheit {\n\treturn f\n}", "func franc(f int) *Money {\n\treturn &Money{\n\t\tamount: f,\n\t\tcurrency: \"CHF\",\n\t}\n}", "func KToC(k Kelvin) Celsius { return Celsius(k - 273.15) }", "func KToC(k Kelvin) Celsius { return Celsius(k + 273.15) }", "func (nch *NvmeHealth) TempC() float32 {\n\treturn float32(nch.Temperature) - 273.15\n}", "func KtoF(k Kalvin) Fahrenheit {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// (t°K - 273.15) * 9/5 + 32\n\treturn Fahrenheit(round((float64(k)-273.15)*1.8+32, 100))\n}", "func CgoFal03(t float64) float64 {\n\tvar cF C.double\n\tcF = C.iauFal03(C.double(t))\n\treturn float64(cF)\n}", "func KToF(k Kelvin) Fahrenheit { return Fahrenheit((k-273.15)*9.0/5.0 + 32.0) }", "func main() {\n\tvar tempFahrenheit, tempCelsius float32\n\n\tfmt.Println(\"Enter temperature in Fahrenheit(F): \")\n\tfmt.Scanln(&tempFahrenheit)\n\ttempCelsius = (tempFahrenheit - 32) * (5.0 / 9)\n\tfmt.Println(\"The temperature in Celsius(C) is: \", tempCelsius)\n\n}", "func KToF(k Kelvin) Fahrenheit {\n\treturn Fahrenheit(k*9/5 - 459.67)\n}", "func KToF(k Kelvin) Fahrenheit {\n\tif k <= AbsoluteZeroK {\n\t\treturn AbsoluteZeroF\n\t}\n\treturn Fahrenheit(k*9/5) + AbsoluteZeroF\n}", "func (o Cos) F(t float64, x []float64) float64 {\n\treturn o.a*math.Cos(o.b*t) + o.c\n}", "func (c *Channel) TempC() int {\n\treturn f2c(int(c.temp))\n}", "func FToK(f Fahrenheit) Kelvin { return Kelvin(((f - 32.0) * 5.0 / 9.0) + 273.15) }", "func KToC(k Kelvin) Celsius {\n\treturn Celsius(k - 273.15)\n}", "func (this *Device) GetCoreTemperatureCelcius() (float64, error) {\n\t// retrieve value as text\n\tvalue, err := this.GeneralCommand(GENCMD_MEASURE_TEMP)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\n\t// Find value within text\n\tmatch := REGEXP_TEMP.FindStringSubmatch(value)\n\tif len(match) != 2 {\n\t\treturn 0.0, this.log.Error(\"Bad Response from %v\", GENCMD_MEASURE_TEMP)\n\t}\n\n\t// Convert to float64\n\tvalue2, err := strconv.ParseFloat(match[1], 64)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\n\t// Return value as float64\n\treturn value2, nil\n}", "func (c Celsius) Celsius() Celsius {\n\treturn c\n}", "func KtoC(k Kalvin) Celsius {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// t°K - 273.15\n\treturn Celsius(round(float64(k)-273.15, 100))\n}", "func main() {\n\tfmt.Println(\"The program converts temperature from Celsius to Fahrenheit.\")\n\tfmt.Println(\"Enter the temperature in Celsius: \")\n\tvar x float64\n\tfmt.Scan(&x)\n\tx = x*9/5 + 32\n\tfmt.Println(\"The temperature in Fahrenheit:\", x)\n\n}", "func (cti CubicThousandthInch) ToCubicFeet() CubicFeet {\n\tcubicThousandthInchPerCubicFoot := thousandthInchPerFoot * thousandthInchPerFoot * thousandthInchPerFoot\n\treturn CubicFeet(float64(cti) / float64(cubicThousandthInchPerCubicFoot))\n}", "func FToK(f Fahrenheit) Kelvin {\n\tif f <= AbsoluteZeroF {\n\t\treturn AbsoluteZeroK\n\t}\n\treturn Kelvin((f - AbsoluteZeroF) * 5 / 9)\n}", "func KToC(k Kelvin) Celsius {\n\tif k <= AbsoluteZeroK {\n\t\treturn AbsoluteZeroC\n\t}\n\treturn Celsius(k) + AbsoluteZeroC\n}", "func KToC(k Kelvin) Celsius {\n\treturn Celsius(k + Kelvin(AbsoluteZeroC))\n}", "func (h *MPU6050Driver) convertToCelsius() {\n\th.Temperature = (h.Temperature + 12412) / 340\n}", "func (kh kelvinHandler) ToCelsius(temp float64) float64 {\n\treturn temp - KelvinBase\n}", "func (t TestDescription) FCIt(text string, body func(context.Context), timeout time.Duration, opts ...TestOption) {\n\ttestOptions := &TestOptions{}\n\ttestOptions.ApplyOptions(opts)\n\n\ttestOptions.Complete(func() {\n\t\tFCIt(fmt.Sprintf(\"%s %s\", t.String(), text), body, timeout)\n\t})\n}", "func (k Kelvin) Celcious() Celcious {\n\treturn Celcious(k - 273.15)\n}", "func FToK(f Fahrenheit) Kelvin {\n\treturn Kelvin((f + 459.67) * 5 / 9)\n}", "func CgoFapa03(t float64) float64 {\n\tvar cF C.double\n\tcF = C.iauFapa03(C.double(t))\n\treturn float64(cF)\n}", "func convertTemperature(fromUOM, toUOM string, value float64) float64 {\n\tfromUOM = resolveTemperatureSynonyms(fromUOM)\n\ttoUOM = resolveTemperatureSynonyms(toUOM)\n\tif fromUOM == toUOM {\n\t\treturn value\n\t}\n\t// convert to Kelvin\n\tswitch fromUOM {\n\tcase \"F\":\n\t\tvalue = (value-32)/1.8 + 273.15\n\tcase \"C\":\n\t\tvalue += 273.15\n\tcase \"Rank\":\n\t\tvalue /= 1.8\n\tcase \"Reau\":\n\t\tvalue = value*1.25 + 273.15\n\t}\n\t// convert from Kelvin\n\tswitch toUOM {\n\tcase \"F\":\n\t\tvalue = (value-273.15)*1.8 + 32\n\tcase \"C\":\n\t\tvalue -= 273.15\n\tcase \"Rank\":\n\t\tvalue *= 1.8\n\tcase \"Reau\":\n\t\tvalue = (value - 273.15) * 0.8\n\t}\n\treturn value\n}", "func MtoFT(d Meter) Feet {\n\treturn Feet(d / 3.28084)\n}", "func (m *Money) Setfc(f float64, currency string) *Money {\n\tfDPf := f * DPf\n\tr := int64(f * DPf)\n\treturn m.Setc(Rnd(r, fDPf-float64(r)), currency)\n}", "func FCIt(text string, body func(context.Context), timeout time.Duration) {\n\tginkgo.FIt(text, contextify(body, timeout), timeout.Seconds())\n}", "func (_AccessControl *AccessControlTransactor) SetCfo(opts *bind.TransactOpts, newCfo common.Address) (*types.Transaction, error) {\n\treturn _AccessControl.contract.Transact(opts, \"setCfo\", newCfo)\n}", "func GetTemperature()float32{\n\treturn 0\n}", "func main() {\n fmt.Print(\"fahrenheit grades: \")\n var far float64\n fmt.Scanf(\"%f\", &far)\n // formula: c = (f-32) * 5/9\n celsius := ((far - 32) * 5 ) / 9\n fmt.Println(\"Celsius:\", celsius)\n}", "func (_MonsterAccessControl *MonsterAccessControlTransactorSession) SetCFO(_newCFO common.Address) (*types.Transaction, error) {\n\treturn _MonsterAccessControl.Contract.SetCFO(&_MonsterAccessControl.TransactOpts, _newCFO)\n}", "func (cvr Converter) FeetToCentimeter(ft Feet) Centimeter {\n\treturn Centimeter(ft * 30.48)\n}", "func (_MonsterAccessControl *MonsterAccessControlTransactor) SetCFO(opts *bind.TransactOpts, _newCFO common.Address) (*types.Transaction, error) {\n\treturn _MonsterAccessControl.contract.Transact(opts, \"setCFO\", _newCFO)\n}", "func (c *Change) Temperature(temp int) *Change {\n\tc.params[\"ct\"] = temp\n\treturn c\n}", "func adcToTemperature(adc int16) float64 {\n\treturn float64(adc)*0.3125e-3*10.0 - 20.0\n}", "func (_MonsterOwnership *MonsterOwnershipTransactorSession) SetCFO(_newCFO common.Address) (*types.Transaction, error) {\n\treturn _MonsterOwnership.Contract.SetCFO(&_MonsterOwnership.TransactOpts, _newCFO)\n}", "func (c *Channel) AlarmTempF() int {\n\treturn int(c.curAlarm)\n}", "func (_MonsterAccessControl *MonsterAccessControlSession) SetCFO(_newCFO common.Address) (*types.Transaction, error) {\n\treturn _MonsterAccessControl.Contract.SetCFO(&_MonsterAccessControl.TransactOpts, _newCFO)\n}", "func TestExample_one(t *testing.T) {\n\tgot := BoilingC - FreezingC\n\twant := Celcius(100)\n\tif got != want {\n\t\tt.Fatalf(\"want %g, got %g\", want, got)\n\t}\n\tt.Logf(\"%g\\n\", got) // \"100\" °C\n\tboilingF := CToF(BoilingC)\n\tt.Logf(\"%g\\n\", boilingF-CToF(FreezingC)) // \"180\" °F\n\t/*\n\t\tfmt.Printf(\"%g\\n\", boilingF-FreezingC) // compile error: type mismatch\n\t*/\n}", "func MToF(m Meters) Feet {\n\treturn Feet(m * 3.2808)\n}", "func (_MonsterOwnership *MonsterOwnershipTransactor) SetCFO(opts *bind.TransactOpts, _newCFO common.Address) (*types.Transaction, error) {\n\treturn _MonsterOwnership.contract.Transact(opts, \"setCFO\", _newCFO)\n}" ]
[ "0.8550536", "0.85274", "0.85274", "0.85274", "0.85274", "0.85274", "0.85274", "0.85274", "0.85274", "0.85234416", "0.8494078", "0.8494078", "0.8494078", "0.84316254", "0.8394293", "0.8152615", "0.8119239", "0.8065906", "0.8057416", "0.8033207", "0.8033207", "0.8033207", "0.8033207", "0.7940184", "0.77789646", "0.7705088", "0.7641043", "0.72555816", "0.7015386", "0.698597", "0.6869915", "0.68564373", "0.68029267", "0.67712766", "0.6728284", "0.66663027", "0.6621999", "0.6580388", "0.6538712", "0.65334415", "0.6525474", "0.648177", "0.64285684", "0.6331633", "0.6244908", "0.6239918", "0.62139463", "0.6142758", "0.60895497", "0.60729814", "0.5971718", "0.59488684", "0.5904262", "0.5902937", "0.59004194", "0.58480346", "0.5841269", "0.5810313", "0.575541", "0.570332", "0.5691261", "0.5689717", "0.56836474", "0.56688327", "0.5606591", "0.56052244", "0.5586699", "0.5575368", "0.5555556", "0.55246454", "0.5500153", "0.5490737", "0.5473772", "0.5402968", "0.53831553", "0.5372046", "0.53694624", "0.53687906", "0.5318598", "0.5297106", "0.5291134", "0.5285381", "0.52663994", "0.52588993", "0.52321327", "0.52289283", "0.52045023", "0.5198768", "0.51831645", "0.51814264", "0.5171728", "0.5167844", "0.51656365" ]
0.82126224
22
FToC converts a Fahrenheit temperature to Celsius.
func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) / 1.8)\n}", "func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) * 5 / 9)\n}", "func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) * 5 / 9)\n}", "func FToC(f Fahrenheit) Celsius {\n\treturn Celsius((f - 32) * 5 / 9)\n}", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32.0) * 5.0 / 9.0) }", "func FToC(f Fahrenheit) Celsius {\n\tif f <= AbsoluteZeroF {\n\t\treturn AbsoluteZeroC\n\t}\n\treturn Celsius((f - 32) * 5 / 9)\n}", "func FToC(f Farenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func (f Fahrenheit) ToC() Celsius {\n\treturn FToC(f)\n}", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*1.8 + 32)\n}", "func (c Celsius) ToF() Fahrenheit {\n\treturn CToF(c)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\tif c <= AbsoluteZeroC {\n\t\treturn AbsoluteZeroF\n\t}\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9.0/5.0 + 32.0) }", "func CToF(c Celsius) Farenheit { return Farenheit(c*9/5 + 32) }", "func toFahrenheit(t Celsius) Fahrenheit {\n\n\tvar temp Fahrenheit\n\tvar tt float32\n\ttt = (float32(t) * 1.8) + float32(32)\n\ttemp = Fahrenheit(tt)\n\treturn temp\n\n}", "func (c ConversionHandler) ConvertFtoC(writer http.ResponseWriter, request *http.Request) {\n\tresult, err := decodeRequest(request)\n\n\tif err != nil {\n\t\thandleError(writer, err)\n\t\treturn\n\t}\n\n\tcelsius := convert.FahrenheitToCelsius(convert.Fahrenheit(result))\n\tformatAndSendResponse(writer, \"Celsius\", celsius.String())\n}", "func CtoF(t float32) float32 {\n\treturn (t*9/5 + 32)\n}", "func (c ConversionHandler) ConvertCtoF(writer http.ResponseWriter, request *http.Request) {\n\tresult, err := decodeRequest(request)\n\n\tif err != nil {\n\t\thandleError(writer, err)\n\t\treturn\n\t}\n\n\tfahrenheit := convert.CelsiusToFahrenheit(convert.Celsius(result))\n\tformatAndSendResponse(writer, \"Fahrenheit\", fahrenheit.String())\n}", "func DisplayFToC() {\n\tconst freezingF, boilingF = 32.0, 212.0\n\tfmt.Printf(\"%g°F = %g°C\\n\", freezingF, fToC(freezingF)) // 32°F = 0°C\n\tfmt.Printf(\"%g°F = %g°C\\n\", boilingF, fToC(boilingF)) // 212°F = 100°C\n}", "func kToFToC(rowNum int) (col1, col2, col3 string, kColor, fColor, cColor int) {\n\tk := kelvin(rowNum * 5)\n\tf := k.fahrenheit()\n\tc := k.celsius()\n\tcol1 = fmt.Sprintf(tempFmt, k)\n\tcol2 = fmt.Sprintf(tempFmt, f)\n\tcol3 = fmt.Sprintf(tempFmt, c)\n\tkColor = k.color()\n\tfColor = f.color()\n\tcColor = c.color()\n\treturn col1, col2, col3, kColor, fColor, cColor\n}", "func (c Celcious) Fahrenheit() Fahrenheit {\n\treturn Fahrenheit((c * 1.8) + 32)\n}", "func (f Fahrenheit) Celsius() Celsius {\n\treturn Celsius((float32(f) - 32) * float32(5) / float32(9))\n}", "func (c Celsius) Fahrenheit() Fahrenheit {\n\treturn Fahrenheit((float32(c) * 1.8) + 32)\n}", "func (kh kelvinHandler) ToFahrenheit(temp float64) float64 {\n\treturn (kh.ToCelsius(temp) * fahrenheitMultiplier) + FahrenheitBase\n}", "func KToC(k Kelvin) Celsius { return Celsius(k - 273.15) }", "func KToC(k Kelvin) Celsius { return Celsius(k + 273.15) }", "func (t Temperature) Celsius() float64 {\n\treturn (t.Fahrenheit() - 32.0) * 5.0 / 9.0\n}", "func (f Fahrenheit) Celcious() Celcious {\n\treturn Celcious((f - 32) / 1.8)\n}", "func Celsius(c float64) Temperature {\n\treturn Temperature(c*1.8 + 32.0)\n}", "func Fahrenheit(f float64) Temperature {\n\treturn Temperature(f)\n}", "func KToC(k Kelvin) Celsius {\n\treturn Celsius(k - 273.15)\n}", "func KToF(k Kelvin) Fahrenheit { return CToF(KToC(k)) }", "func (h *MPU6050Driver) convertToCelsius() {\n\th.Temperature = (h.Temperature + 12412) / 340\n}", "func KToC(k Kelvin) Celsius {\n\treturn Celsius(k + Kelvin(AbsoluteZeroC))\n}", "func (t Temperature) Fahrenheit() float64 {\n\treturn float64(t)\n}", "func KtoC(k Kalvin) Celsius {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// t°K - 273.15\n\treturn Celsius(round(float64(k)-273.15, 100))\n}", "func KToC(k Kelvin) Celsius {\n\tif k <= AbsoluteZeroK {\n\t\treturn AbsoluteZeroC\n\t}\n\treturn Celsius(k) + AbsoluteZeroC\n}", "func (kh kelvinHandler) ToCelsius(temp float64) float64 {\n\treturn temp - KelvinBase\n}", "func (c *Channel) TempF() int {\n\treturn int(c.temp)\n}", "func (nch *NvmeHealth) TempC() float32 {\n\treturn float32(nch.Temperature) - 273.15\n}", "func (nch *NvmeHealth) TempF() float32 {\n\treturn (nch.TempC() * (9.0 / 5.0)) + 32.0\n}", "func convertFtoc() {\n\tconst freezingF, boilingF = 32.0, 212.0\n\n\tfmt.Printf(\"%gF = %gC\\n\", freezingF, ftoc(freezingF)) //\"32F = 0C\"\t\n\tfmt.Printf(\"%gF = %gC\\n\", boilingF, ftoc(boilingF)) //\"212F\" = 100C\"\n\n}", "func franc(f int) *Money {\n\treturn &Money{\n\t\tamount: f,\n\t\tcurrency: \"CHF\",\n\t}\n}", "func (c *Channel) TempC() int {\n\treturn f2c(int(c.temp))\n}", "func TempFromF(f int) Temp {\n\tc := math.Floor(float64((f - 32)) / 1.8)\n\treturn Temp(c)\n\n}", "func (c Celsius) Celsius() Celsius {\n\treturn c\n}", "func KtoF(k Kalvin) Fahrenheit {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// (t°K - 273.15) * 9/5 + 32\n\treturn Fahrenheit(round((float64(k)-273.15)*1.8+32, 100))\n}", "func (f Fahrenheit) Fahrenheit() Fahrenheit {\n\treturn f\n}", "func kelvinToCelsius(k kelvin) celsius {\n\t// type must be converted before return\n\treturn celsius(k - 273.15)\n}", "func KToF(k Kelvin) Fahrenheit { return Fahrenheit((k-273.15)*9.0/5.0 + 32.0) }", "func (o Cos) F(t float64, x []float64) float64 {\n\treturn o.a*math.Cos(o.b*t) + o.c\n}", "func (k Kelvin) Celcious() Celcious {\n\treturn Celcious(k - 273.15)\n}", "func main() {\n\tvar tempFahrenheit, tempCelsius float32\n\n\tfmt.Println(\"Enter temperature in Fahrenheit(F): \")\n\tfmt.Scanln(&tempFahrenheit)\n\ttempCelsius = (tempFahrenheit - 32) * (5.0 / 9)\n\tfmt.Println(\"The temperature in Celsius(C) is: \", tempCelsius)\n\n}", "func KToF(k Kelvin) Fahrenheit {\n\treturn Fahrenheit(k*9/5 - 459.67)\n}", "func KToF(k Kelvin) Fahrenheit {\n\tif k <= AbsoluteZeroK {\n\t\treturn AbsoluteZeroF\n\t}\n\treturn Fahrenheit(k*9/5) + AbsoluteZeroF\n}", "func (cti CubicThousandthInch) ToCubicFeet() CubicFeet {\n\tcubicThousandthInchPerCubicFoot := thousandthInchPerFoot * thousandthInchPerFoot * thousandthInchPerFoot\n\treturn CubicFeet(float64(cti) / float64(cubicThousandthInchPerCubicFoot))\n}", "func (t *Temp) F() int {\n\ttemp := math.Floor(float64(*t)*9/5) + 32\n\tif temp < 0 {\n\t\treturn int(temp - 1.0)\n\t}\n\treturn int(temp)\n}", "func FToK(f Fahrenheit) Kelvin { return Kelvin(((f - 32.0) * 5.0 / 9.0) + 273.15) }", "func CgoFal03(t float64) float64 {\n\tvar cF C.double\n\tcF = C.iauFal03(C.double(t))\n\treturn float64(cF)\n}", "func (this *Device) GetCoreTemperatureCelcius() (float64, error) {\n\t// retrieve value as text\n\tvalue, err := this.GeneralCommand(GENCMD_MEASURE_TEMP)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\n\t// Find value within text\n\tmatch := REGEXP_TEMP.FindStringSubmatch(value)\n\tif len(match) != 2 {\n\t\treturn 0.0, this.log.Error(\"Bad Response from %v\", GENCMD_MEASURE_TEMP)\n\t}\n\n\t// Convert to float64\n\tvalue2, err := strconv.ParseFloat(match[1], 64)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\n\t// Return value as float64\n\treturn value2, nil\n}", "func kelvinToCelsius(k float64) float64 {\n\tk -= 273.15\n\treturn k\n}", "func convertTemperature(fromUOM, toUOM string, value float64) float64 {\n\tfromUOM = resolveTemperatureSynonyms(fromUOM)\n\ttoUOM = resolveTemperatureSynonyms(toUOM)\n\tif fromUOM == toUOM {\n\t\treturn value\n\t}\n\t// convert to Kelvin\n\tswitch fromUOM {\n\tcase \"F\":\n\t\tvalue = (value-32)/1.8 + 273.15\n\tcase \"C\":\n\t\tvalue += 273.15\n\tcase \"Rank\":\n\t\tvalue /= 1.8\n\tcase \"Reau\":\n\t\tvalue = value*1.25 + 273.15\n\t}\n\t// convert from Kelvin\n\tswitch toUOM {\n\tcase \"F\":\n\t\tvalue = (value-273.15)*1.8 + 32\n\tcase \"C\":\n\t\tvalue -= 273.15\n\tcase \"Rank\":\n\t\tvalue *= 1.8\n\tcase \"Reau\":\n\t\tvalue = (value - 273.15) * 0.8\n\t}\n\treturn value\n}", "func (c Celsius) String() string {\n\treturn fmt.Sprintf(\"%.2f C\", float32(c))\n}", "func CToK(c Celsius) Kelvin { return Kelvin(c - 273.15) }", "func main() {\n\tfmt.Println(\"The program converts temperature from Celsius to Fahrenheit.\")\n\tfmt.Println(\"Enter the temperature in Celsius: \")\n\tvar x float64\n\tfmt.Scan(&x)\n\tx = x*9/5 + 32\n\tfmt.Println(\"The temperature in Fahrenheit:\", x)\n\n}", "func CToK(c Celsius) Kelvin { return Kelvin(c + 273.15) }", "func FToK(f Fahrenheit) Kelvin {\n\tif f <= AbsoluteZeroF {\n\t\treturn AbsoluteZeroK\n\t}\n\treturn Kelvin((f - AbsoluteZeroF) * 5 / 9)\n}", "func (k kelvin) celsius() celsius {\n\treturn celsius(k - 273.15)\n}", "func (cvr Converter) FeetToCentimeter(ft Feet) Centimeter {\n\treturn Centimeter(ft * 30.48)\n}", "func FToK(f Fahrenheit) Kelvin {\n\treturn Kelvin((f + 459.67) * 5 / 9)\n}", "func CToK(c Celsius) Kelvin {\n\tif c <= AbsoluteZeroC {\n\t\treturn AbsoluteZeroK\n\t}\n\treturn Kelvin(c - AbsoluteZeroC)\n}", "func CToK(c Celsius) Kelvin {\n\treturn Kelvin(c - AbsoluteZeroC)\n}", "func adcToTemperature(adc int16) float64 {\n\treturn float64(adc)*0.3125e-3*10.0 - 20.0\n}", "func (c *Channel) AlarmTempC() int {\n\treturn f2c(int(c.curAlarm))\n}", "func (cvr Converter) FeetToCentimeter(f Feet) Centimeter {\n\treturn Centimeter(f) * Centimeter(30.48)\n}", "func (_AccessControl *AccessControlTransactor) SetCfo(opts *bind.TransactOpts, newCfo common.Address) (*types.Transaction, error) {\n\treturn _AccessControl.contract.Transact(opts, \"setCfo\", newCfo)\n}", "func (_MonsterAccessControl *MonsterAccessControlTransactor) SetCFO(opts *bind.TransactOpts, _newCFO common.Address) (*types.Transaction, error) {\n\treturn _MonsterAccessControl.contract.Transact(opts, \"setCFO\", _newCFO)\n}", "func (_MonsterAccessControl *MonsterAccessControlTransactorSession) SetCFO(_newCFO common.Address) (*types.Transaction, error) {\n\treturn _MonsterAccessControl.Contract.SetCFO(&_MonsterAccessControl.TransactOpts, _newCFO)\n}", "func NewFranc(a int) *Money {\n\treturn NewMoney(a, \"CHF\")\n}", "func main() {\n fmt.Print(\"fahrenheit grades: \")\n var far float64\n fmt.Scanf(\"%f\", &far)\n // formula: c = (f-32) * 5/9\n celsius := ((far - 32) * 5 ) / 9\n fmt.Println(\"Celsius:\", celsius)\n}", "func (_MonsterOwnership *MonsterOwnershipTransactor) SetCFO(opts *bind.TransactOpts, _newCFO common.Address) (*types.Transaction, error) {\n\treturn _MonsterOwnership.contract.Transact(opts, \"setCFO\", _newCFO)\n}", "func (_MonsterOwnership *MonsterOwnershipTransactorSession) SetCFO(_newCFO common.Address) (*types.Transaction, error) {\n\treturn _MonsterOwnership.Contract.SetCFO(&_MonsterOwnership.TransactOpts, _newCFO)\n}" ]
[ "0.9023909", "0.8993624", "0.8993624", "0.8993624", "0.88913953", "0.88472736", "0.86949044", "0.8260731", "0.81655014", "0.81655014", "0.81655014", "0.81655014", "0.81655014", "0.81655014", "0.81655014", "0.81655014", "0.8151689", "0.8143085", "0.8126588", "0.8126588", "0.8126588", "0.8126588", "0.81241417", "0.81226426", "0.8045857", "0.7586812", "0.755952", "0.7482839", "0.73567694", "0.72240335", "0.71643686", "0.7102806", "0.7018644", "0.6983424", "0.6816937", "0.67865545", "0.67533207", "0.6743137", "0.6592996", "0.6576315", "0.653001", "0.65052664", "0.64816576", "0.6396746", "0.63402843", "0.6331677", "0.63160557", "0.624851", "0.62280065", "0.6227799", "0.61651886", "0.6164625", "0.6111002", "0.60400325", "0.5968116", "0.5942384", "0.5906572", "0.5906217", "0.586429", "0.5833757", "0.5825518", "0.58195424", "0.5816765", "0.5800139", "0.57846546", "0.5723916", "0.5707773", "0.5705383", "0.5701191", "0.55777407", "0.55757725", "0.55681914", "0.55545455", "0.5526388", "0.5516872", "0.54666793", "0.5465873", "0.54394037", "0.5419612", "0.54154307", "0.5396163", "0.53123397", "0.52837497", "0.5280594", "0.52482885", "0.5246027", "0.523395", "0.52139354", "0.520881", "0.519827", "0.5194709", "0.5169869", "0.515631" ]
0.8873047
12
MToF converts a Meter length to Feet.
func MToF(m Meter) Feet { return Feet(m / 0.3048) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func MToF(m Meters) Feet {\n\treturn Feet(m * 3.2808)\n}", "func MToF(m Meter) Foot { return Foot(m / 0.3048) }", "func FToM(f Feet) Meter { return Meter(f * 0.3048) }", "func FToM(f Feet) Meters {\n\treturn Meters(f / 3.2808)\n}", "func FTtoM(d Feet) Meter {\n\treturn Meter(d * 3.28084)\n}", "func MtoFT(d Meter) Feet {\n\treturn Feet(d / 3.28084)\n}", "func MeterToFeet(m Meter) Foot { return Foot(m / 3) }", "func FToM(f Foot) Meter { return Meter(f * 0.3048) }", "func FootToMeters(f Foot) Meter { return Meter(f * 3) }", "func FeetToMeters(units float64) float64 {\n\treturn units * 0.3048\n}", "func (d *Distance) Feet() (result int) {\n\tswitch d.Unit {\n\tcase M:\n\t\tresult = cnv.MToFt(d.Value)\n\tcase FT:\n\t\tresult = d.Value\n\tcase SM:\n\t\tresult = cnv.SMileToFt(float64(d.Value) + d.FractionValue)\n\tdefault:\n\t\tresult = cnv.MToFt(d.Value)\n\t}\n\treturn\n}", "func CToF(c Celsius) Farenheit { return Farenheit(c*9/5 + 32) }", "func ToF(str string) float64 {\n\tval, err := strconv.ParseFloat(str, 64)\n\tL.IsError(err, str)\n\treturn val\n}", "func (cvr Converter) CentimeterToFeet(cm Centimeter) Feet {\n\treturn Feet(cm / 30.48)\n}", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9.0/5.0 + 32.0) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func (cvr Converter) CentimeterToFeet(c Centimeter) Feet {\n\treturn Feet(c / 30.48)\n}", "func (t *Temp) F() int {\n\ttemp := math.Floor(float64(*t)*9/5) + 32\n\tif temp < 0 {\n\t\treturn int(temp - 1.0)\n\t}\n\treturn int(temp)\n}", "func KToF(k Kelvin) Fahrenheit { return Fahrenheit((k-273.15)*9.0/5.0 + 32.0) }", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func (v Volume) Femtolitres() float64 {\n\treturn float64(v / Femtolitre)\n}", "func CToF(c Celsius) Fahrenheit {\n\treturn Fahrenheit(c*1.8 + 32)\n}", "func KToF(k Kelvin) Fahrenheit { return CToF(KToC(k)) }", "func CtoF(t float32) float32 {\n\treturn (t*9/5 + 32)\n}", "func ConvertFromM(n float64, toUnit string) float64 {\n\ttoUnit = strings.TrimSpace(strings.ToLower(toUnit))\n\tif v, is := SPEED_UNITS[toUnit]; is {\n\t\treturn n / v\n\t}\n\tif v, is := Units[toUnit]; is {\n\t\treturn n / v\n\t}\n\treturn 0\n}", "func CToF(c Celsius) Fahrenheit {\n\tif c <= AbsoluteZeroC {\n\t\treturn AbsoluteZeroF\n\t}\n\treturn Fahrenheit(c*9/5 + 32)\n}", "func KToF(k Kelvin) Fahrenheit {\n\treturn Fahrenheit(k*9/5 - 459.67)\n}", "func (kh kelvinHandler) ToFahrenheit(temp float64) float64 {\n\treturn (kh.ToCelsius(temp) * fahrenheitMultiplier) + FahrenheitBase\n}", "func (c Celsius) ToF() Fahrenheit {\n\treturn CToF(c)\n}", "func (cvr Converter) FeetToCentimeter(ft Feet) Centimeter {\n\treturn Centimeter(ft * 30.48)\n}", "func toFahrenheit(t Celsius) Fahrenheit {\n\n\tvar temp Fahrenheit\n\tvar tt float32\n\ttt = (float32(t) * 1.8) + float32(32)\n\ttemp = Fahrenheit(tt)\n\treturn temp\n\n}", "func KtoF(k Kalvin) Fahrenheit {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// (t°K - 273.15) * 9/5 + 32\n\treturn Fahrenheit(round((float64(k)-273.15)*1.8+32, 100))\n}", "func KToF(k Kelvin) Fahrenheit {\n\tif k <= AbsoluteZeroK {\n\t\treturn AbsoluteZeroF\n\t}\n\treturn Fahrenheit(k*9/5) + AbsoluteZeroF\n}", "func (cvr Converter) FeetToCentimeter(f Feet) Centimeter {\n\treturn Centimeter(f) * Centimeter(30.48)\n}", "func (t Temperature) Fahrenheit() float64 {\n\treturn float64(t)\n}", "func (cti CubicThousandthInch) ToCubicFeet() CubicFeet {\n\tcubicThousandthInchPerCubicFoot := thousandthInchPerFoot * thousandthInchPerFoot * thousandthInchPerFoot\n\treturn CubicFeet(float64(cti) / float64(cubicThousandthInchPerCubicFoot))\n}", "func (d *Distance) Meters() (result int) {\n\tswitch d.Unit {\n\tcase M:\n\t\tresult = d.Value\n\tcase FT:\n\t\tresult = cnv.FtToM(d.Value)\n\tcase SM:\n\t\tresult = cnv.SMileToM(float64(d.Value) + d.FractionValue)\n\tdefault:\n\t\tresult = d.Value\n\t}\n\treturn\n}", "func (m *Message) MFI() (*MFI, error) {\n\tps, err := m.Parse(\"MFI\")\n\tpst, ok := ps.(*MFI)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func (t *Ticker) NewMFI(inTimePeriod int32) *MFI {\n\tcalculator := &mfiCalculator{\n\t\tTicker: t,\n\t\tFlowIdx: 0,\n\t\tMaxFlowIdx: inTimePeriod - 1,\n\t\tPeriod: inTimePeriod,\n\t\tMoneyFlow: make([]moneyFlow, inTimePeriod),\n\t}\n\treturn &MFI{\n\t\tCalculator: calculator,\n\t}\n}", "func (m *Message) MFE() (*MFE, error) {\n\tps, err := m.Parse(\"MFE\")\n\tpst, ok := ps.(*MFE)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func FToK(f Fahrenheit) Kelvin {\n\tif f <= AbsoluteZeroF {\n\t\treturn AbsoluteZeroK\n\t}\n\treturn Kelvin((f - AbsoluteZeroF) * 5 / 9)\n}", "func TempFromF(f int) Temp {\n\tc := math.Floor(float64((f - 32)) / 1.8)\n\treturn Temp(c)\n\n}", "func ConvertToFloatModifier(i interface{}) (interface{}, error) {\n\tswitch v := i.(type) {\n\tcase string:\n\t\ti, err := strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn i, nil\n\tcase int:\n\t\treturn float64(v), nil\n\tcase int32:\n\t\treturn float64(v), nil\n\tcase int64:\n\t\treturn float64(v), nil\n\tcase float64:\n\t\treturn float64(v), nil\n\tcase float32:\n\t\treturn float64(v), nil\n\t}\n\treturn nil, fmt.Errorf(\"Invalid type (%v) to make float\", reflect.TypeOf(i))\n}", "func (d HypergeometicDist) PMF(k float64) float64 {\n\tki := int(math.Floor(k))\n\tl, h := d.bounds()\n\tif ki < l || ki > h {\n\t\treturn 0\n\t}\n\treturn d.pmf(ki)\n}", "func FToK(f Fahrenheit) Kelvin {\n\treturn Kelvin((f + 459.67) * 5 / 9)\n}", "func (t *Type) toFloat(typeTo reflect.Kind) FloatAccessor {\n\tnv := &NullFloat{}\n\tif !t.rv.IsValid() || !isFloat(typeTo) {\n\t\tnv.Error = ErrConvert\n\t\treturn nv\n\t}\n\tswitch {\n\tcase t.IsString(true):\n\t\tvalue, err := strconv.ParseFloat(t.rv.String(), bitSizeMap[typeTo])\n\t\tnv.P = &value\n\t\tnv.Error = err\n\t\treturn nv\n\tcase t.IsFloat(true):\n\t\tfloatValue := t.rv.Float()\n\t\tnv.P = &floatValue\n\t\tif !isSafeFloat(floatValue, bitSizeMap[typeTo]) {\n\t\t\tnv.Error = ErrConvert\n\t\t}\n\t\treturn nv\n\tcase t.IsInt(true):\n\t\tintValue := t.rv.Int()\n\t\tv := float64(intValue)\n\t\tnv.P = &v\n\t\tif !isSafeIntToFloat(intValue, bitSizeMap[typeTo]) {\n\t\t\tnv.Error = ErrConvert\n\t\t}\n\t\treturn nv\n\tcase t.IsUint(true):\n\t\tuintValue := t.rv.Uint()\n\t\tv := float64(uintValue)\n\t\tnv.P = &v\n\t\tif !isSafeUintToFloat(uintValue, bitSizeMap[typeTo]) {\n\t\t\tnv.Error = ErrConvert\n\t\t}\n\t\treturn nv\n\tcase t.IsComplex(true):\n\t\tcomplexValue := t.rv.Complex()\n\t\tv := float64(real(complexValue))\n\t\tnv.P = &v\n\t\tif !isSafeComplexToFloat(complexValue, bitSizeMap[typeTo]) {\n\t\t\tnv.Error = ErrConvert\n\t\t}\n\t\treturn nv\n\tcase t.IsBool(true):\n\t\tvar v float64\n\t\tif t.rv.Bool() {\n\t\t\tv = 1\n\t\t\tnv.P = &v\n\t\t} else {\n\t\t\tnv.P = &v\n\t\t}\n\t\treturn nv\n\t}\n\tnv.Error = ErrConvert\n\treturn nv\n}", "func Fp2f(x *float64) float64 {\n\tif x == nil {\n\t\t// this is not initialized yet - return NaN\n\t\treturn math.Log(-1.0)\n\t} else {\n\t\treturn *x\n\t}\n}", "func ToFloat(value interface{}) (v float64, e error) {\n\tswitch value.(type) {\n\tcase string:\n\t\tv, e = strconv.ParseFloat((value).(string), 64)\n\tcase int, int8, int16, int32, int64:\n\t\tval := reflect.ValueOf(value).Int()\n\t\tv = float64(val)\n\tcase float32:\n\t\tval, _ := ToString(value) // convert float32 into string, to maintain precision\n\t\tv, e = ToFloat(val)\n\tcase float64:\n\t\tv = reflect.ValueOf(value).Float()\n\tdefault:\n\t\te = fmt.Errorf(\"Value %T is type %s\", value, reflect.TypeOf(value).Kind())\n\t}\n\n\treturn\n}", "func convertFtoc() {\n\tconst freezingF, boilingF = 32.0, 212.0\n\n\tfmt.Printf(\"%gF = %gC\\n\", freezingF, ftoc(freezingF)) //\"32F = 0C\"\t\n\tfmt.Printf(\"%gF = %gC\\n\", boilingF, ftoc(boilingF)) //\"212F\" = 100C\"\n\n}", "func FToK(f Fahrenheit) Kelvin { return Kelvin(((f - 32.0) * 5.0 / 9.0) + 273.15) }", "func (c Celcious) Fahrenheit() Fahrenheit {\n\treturn Fahrenheit((c * 1.8) + 32)\n}", "func (nch *NvmeHealth) TempF() float32 {\n\treturn (nch.TempC() * (9.0 / 5.0)) + 32.0\n}", "func (r Qword) GetF() float64 {\n\treturn *(*float64)(unsafe.Pointer(&r))\n}", "func (t *Triangle) MetaballField(coord Coord) float64 {\n\treturn -t.SDF(coord)\n}", "func (c Currency) Getf() float64 {\n\treturn float64(c.m) / c.dpf\n}", "func main() {\n\t\n\tvar dimen_ft float64= 1362\n\t\n\tfmt.Print(\"The height of WTC is: \")\n\tfmt.Println(dimen_ft)\n\t\n\tvar f2m_conv = 0.3048\n\n\tvar dimen_m = dimen_ft * f2m_conv\n\n\tfmt.Print(\"The height in meters is: \")\n\tfmt.Println(dimen_m)\n\n}", "func (c *Capsule) MetaballField(coord Coord) float64 {\n\treturn -c.SDF(coord)\n}", "func (c ConversionHandler) ConvertCtoF(writer http.ResponseWriter, request *http.Request) {\n\tresult, err := decodeRequest(request)\n\n\tif err != nil {\n\t\thandleError(writer, err)\n\t\treturn\n\t}\n\n\tfahrenheit := convert.CelsiusToFahrenheit(convert.Celsius(result))\n\tformatAndSendResponse(writer, \"Fahrenheit\", fahrenheit.String())\n}", "func (p *prng) mkgf(d *[4]uint64) {\n\tvar t [4]uint64\n\tp.mk256(&t)\n\tcopy(d[:], t[:])\n}", "func MiFromCm(cm uint32) float64 {\n\treturn (float64(cm) * Km2miles) / 100000\n}", "func calculateFuel(mass float64) float64{\n return math.Floor(mass / 3) - 2\n}", "func P2MMetricFamilies(mfs []*dto.MetricFamily) []*MetricFamily {\n\tmoMfs := make([]*MetricFamily, 0, len(mfs))\n\tfor _, mf := range mfs {\n\t\tif mf.GetType() == dto.MetricType_UNTYPED {\n\t\t\t// Untyped is used as a placeholder, it has no data\n\t\t\tcontinue\n\t\t}\n\t\tmoMf := &MetricFamily{\n\t\t\tName: mf.GetName(),\n\t\t\tHelp: mf.GetHelp(),\n\t\t}\n\t\tswitch mf.GetType() {\n\t\tcase dto.MetricType_COUNTER:\n\t\t\tmoMf.Type = MetricType_COUNTER\n\t\t\tmoMf.Metric = P2MCounters(mf.Metric)\n\t\tcase dto.MetricType_GAUGE:\n\t\t\tmoMf.Type = MetricType_GAUGE\n\t\t\tmoMf.Metric = P2MGauges(mf.Metric)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unsupported metric type in mo %v\", mf.GetType()))\n\t\t}\n\t\tmoMfs = append(moMfs, moMf)\n\t}\n\treturn moMfs\n}", "func Ftoa(num float64, offset int) string {\n\tf := fmt.Sprintf(\"%%.%df\", offset)\n\treturn stripTrailingZeros(fmt.Sprintf(f, num))\n}", "func (c *Circle) MetaballField(coord Coord) float64 {\n\treturn -c.SDF(coord)\n}", "func ToFloat(value interface{}) (val float64, err error) {\n\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = errors.New(\"can not convert to as type float\")\n\t\t\treturn\n\t\t}\n\t}()\n\n\tval = reflect.ValueOf(value).Float()\n\treturn\n}", "func (d *Distance) Miles() (result float64) {\n\tswitch d.Unit {\n\tcase M:\n\t\tresult = cnv.MToSMile(d.Value)\n\tcase FT:\n\t\tresult = float64(cnv.FtToSMile(int(d.Value)))\n\tcase SM:\n\t\tresult = float64(d.Value) + d.FractionValue\n\tdefault:\n\t\tresult = cnv.MToSMile(d.Value)\n\t}\n\treturn\n}", "func (m *Message) AllMFI() ([]*MFI, error) {\n\tpss, err := m.ParseAll(\"MFI\")\n\treturn pss.([]*MFI), err\n}", "func (ft *FieldType) GetFlen() int {\n\treturn ft.flen\n}", "func (m *Message) AllMFE() ([]*MFE, error) {\n\tpss, err := m.ParseAll(\"MFE\")\n\treturn pss.([]*MFE), err\n}", "func (m *Float64Measure) M(v float64) Measurement {\n\treturn Measurement{\n\t\tm: m,\n\t\tdesc: m.desc,\n\t\tv: v,\n\t}\n}", "func (f Fahrenheit) Fahrenheit() Fahrenheit {\n\treturn f\n}", "func ToFloat(value interface{}) (float64, error) {\n\tv := reflect.ValueOf(value)\n\tswitch v.Kind() {\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn v.Float(), nil\n\t}\n\treturn 0, fmt.Errorf(\"cannot convert %v to float64\", v.Kind())\n}", "func (m *Money) Setfc(f float64, currency string) *Money {\n\tfDPf := f * DPf\n\tr := int64(f * DPf)\n\treturn m.Setc(Rnd(r, fDPf-float64(r)), currency)\n}", "func (r *Rect) MetaballField(coord Coord) float64 {\n\treturn -r.SDF(coord)\n}", "func Fre(text string) float64 {\n\tsylCnt := float64(CntSyls(text))\n\twordCnt := float64(CntWords(text))\n\tsentCnt := float64(CntSents(text))\t\n\treturn 206.835 - 1.015*(wordCnt/sentCnt) - 84.6*(sylCnt/wordCnt)\n}", "func (f *Float) bigFtoa(buf []byte, fmt byte, prec int) []byte {\n\tif debugFloat && f.IsInf() {\n\t\tpanic(\"non-finite float\")\n\t}\n\n\t// 1) convert Float to multiprecision decimal\n\tvar mant nat\n\tif f.form == finite {\n\t\tmant = f.mant\n\t}\n\tvar d decimal\n\td.init(mant, int(f.exp)-f.mant.bitLen())\n\n\t// 2) round to desired precision\n\tshortest := false\n\tif prec < 0 {\n\t\tshortest = true\n\t\tpanic(\"unimplemented\")\n\t\t// TODO(gri) complete this\n\t\t// roundShortest(&d, f.mant, int(f.exp))\n\t\t// Precision for shortest representation mode.\n\t\tswitch fmt {\n\t\tcase 'e', 'E':\n\t\t\tprec = len(d.mant) - 1\n\t\tcase 'f':\n\t\t\tprec = max(len(d.mant)-d.exp, 0)\n\t\tcase 'g', 'G':\n\t\t\tprec = len(d.mant)\n\t\t}\n\t} else {\n\t\t// round appropriately\n\t\tswitch fmt {\n\t\tcase 'e', 'E':\n\t\t\t// one digit before and number of digits after decimal point\n\t\t\td.round(1 + prec)\n\t\tcase 'f':\n\t\t\t// number of digits before and after decimal point\n\t\t\td.round(d.exp + prec)\n\t\tcase 'g', 'G':\n\t\t\tif prec == 0 {\n\t\t\t\tprec = 1\n\t\t\t}\n\t\t\td.round(prec)\n\t\t}\n\t}\n\n\t// 3) read digits out and format\n\tswitch fmt {\n\tcase 'e', 'E':\n\t\treturn fmtE(buf, fmt, prec, f.neg, d)\n\tcase 'f':\n\t\treturn fmtF(buf, prec, f.neg, d)\n\tcase 'g', 'G':\n\t\t// trim trailing fractional zeros in %e format\n\t\teprec := prec\n\t\tif eprec > len(d.mant) && len(d.mant) >= d.exp {\n\t\t\teprec = len(d.mant)\n\t\t}\n\t\t// %e is used if the exponent from the conversion\n\t\t// is less than -4 or greater than or equal to the precision.\n\t\t// If precision was the shortest possible, use eprec = 6 for\n\t\t// this decision.\n\t\tif shortest {\n\t\t\teprec = 6\n\t\t}\n\t\texp := d.exp - 1\n\t\tif exp < -4 || exp >= eprec {\n\t\t\tif prec > len(d.mant) {\n\t\t\t\tprec = len(d.mant)\n\t\t\t}\n\t\t\treturn fmtE(buf, fmt+'e'-'g', prec-1, f.neg, d)\n\t\t}\n\t\tif prec > d.exp {\n\t\t\tprec = len(d.mant)\n\t\t}\n\t\treturn fmtF(buf, max(prec-d.exp, 0), f.neg, d)\n\t}\n\n\t// unknown format\n\treturn append(buf, '%', fmt)\n}", "func parseSpecifier(b string) float64 {\n\tlb := len(b)\n\tif lb == 0 {\n\t\treturn 0\n\t}\n\n\tvar b0, b1 byte\n\tif lb < 2 {\n\t\tb0 = b[0]\n\t\tb1 = '0'\n\t} else {\n\t\tb1 = b[1]\n\t\tb0 = b[0]\n\t}\n\n\tif b1 != '0' {\n\t\tif b1 == 'b' { // bits, so convert bytes to bits for os.Seek()\n\t\t\tif b0 == 'k' || b0 == 'K' {\n\t\t\t\treturn 0.0078125\n\t\t\t}\n\n\t\t\tif b0 == 'm' || b0 == 'M' {\n\t\t\t\treturn 7.62939453125e-06\n\t\t\t}\n\n\t\t\tif b0 == 'g' || b0 == 'G' {\n\t\t\t\treturn 7.45058059692383e-09\n\t\t\t}\n\t\t}\n\n\t\tif b1 == 'B' { // kilo/mega/giga- bytes are assumed\n\t\t\tif b0 == 'k' || b0 == 'K' {\n\t\t\t\treturn 1024\n\t\t\t}\n\n\t\t\tif b0 == 'm' || b0 == 'M' {\n\t\t\t\treturn 1048576\n\t\t\t}\n\n\t\t\tif b0 == 'g' || b0 == 'G' {\n\t\t\t\treturn 1073741824\n\t\t\t}\n\t\t}\n\t} else { // kilo/mega/giga- bytes are assumed for single b, k, m, g\n\t\tif b0 == 'k' || b0 == 'K' {\n\t\t\treturn 1024\n\t\t}\n\n\t\tif b0 == 'm' || b0 == 'M' {\n\t\t\treturn 1048576\n\t\t}\n\n\t\tif b0 == 'g' || b0 == 'G' {\n\t\t\treturn 1073741824\n\t\t}\n\t}\n\n\treturn 1 // assumes bytes as fallback\n}", "func NewFMul(x, y value.Value) *InstFMul {\n\tinst := &InstFMul{X: x, Y: y}\n\t// Compute type.\n\tinst.Type()\n\treturn inst\n}", "func (w *QWriter) F(f float64) {\n\tn := int(f)\n\tif float64(n) == f {\n\t\t// Fast path - just int.\n\t\tw.D(n)\n\t\treturn\n\t}\n\n\t// Slow path.\n\tw.FPrec(f, -1)\n}", "func toMetricFamily(\n\tdtoMF *io_prometheus_client.MetricFamily,\n\tbind BindFunc,\n) *MetricFamily {\n\tmf := &MetricFamily{\n\t\t//Time: time.Now(),\n\t\tName: dtoMF.GetName(),\n\t\tHelp: dtoMF.GetHelp(),\n\t\tType: dtoMF.GetType().String(),\n\n\t\tValues: make([]*MetricValue, 0),\n\t}\n\n\tswitch dtoMF.GetType() {\n\tcase io_prometheus_client.MetricType_SUMMARY:\n\t\t// TODO: implement summary type converter\n\tcase io_prometheus_client.MetricType_HISTOGRAM:\n\t\t// TODO: implement histogram type converter\n\tcase\n\t\tio_prometheus_client.MetricType_GAUGE,\n\t\tio_prometheus_client.MetricType_COUNTER,\n\t\tio_prometheus_client.MetricType_UNTYPED:\n\n\t\tuniqueTags := map[string]bool{}\n\n\t\tfor _, m := range dtoMF.Metric {\n\t\t\tlabels := makeLabels(m)\n\t\t\tentities, labels := bind(labels)\n\t\t\tfor label := range labels {\n\t\t\t\tuniqueTags[label] = true\n\t\t\t}\n\n\t\t\tif entities != nil {\n\t\t\t\tmf.Values = append(\n\t\t\t\t\tmf.Values,\n\t\t\t\t\t&MetricValue{\n\t\t\t\t\t\tEntities: entities,\n\n\t\t\t\t\t\tTags: labels,\n\t\t\t\t\t\tValue: getValue(m),\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tmetricTags := make([]string, len(uniqueTags))\n\t\ti := 0\n\t\tfor tag := range uniqueTags {\n\t\t\tmetricTags[i] = tag\n\t\t\ti++\n\t\t}\n\t\tmf.Tags = metricTags\n\t}\n\n\treturn mf\n}", "func CalculateEthMDLValue(wei *big.Int, mdlPerETH string, maxDecimals int) (uint64, error) {\n\tif wei.Sign() < 0 {\n\t\treturn 0, errors.New(\"wei must be greater than or equal to 0\")\n\t}\n\tif maxDecimals < 0 {\n\t\treturn 0, errors.New(\"maxDecimals can't be negative\")\n\t}\n\trate, err := mathutil.ParseRate(mdlPerETH)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\teth := decimal.NewFromBigInt(wei, 0)\n\tethToWei := decimal.New(WeiPerETH, 0)\n\teth = eth.DivRound(ethToWei, 18)\n\n\tmdl := eth.Mul(rate)\n\tmdl = mdl.Truncate(int32(maxDecimals))\n\n\tmdlToDroplets := decimal.New(droplet.Multiplier, 0)\n\tdroplets := mdl.Mul(mdlToDroplets)\n\n\tamt := droplets.IntPart()\n\tif amt < 0 {\n\t\t// This should never occur, but double check before we convert to uint64,\n\t\t// otherwise we would send all the coins due to integer wrapping.\n\t\treturn 0, errors.New(\"calculated mdl amount is negative\")\n\t}\n\n\treturn uint64(amt), nil\n}", "func (measurement *DimMeasurement) ToInches() float64 {\n\tvar result float64\n\tresult = 0.0\n\tval := measurement.value\n\tswitch measurement.precision {\n\tcase constants.DimWholeNumber:\n\t\t{\n\t\t\tswitch measurement.Indicator {\n\t\t\tcase constants.DimInch:\n\t\t\t\t{\n\t\t\t\t\tif s, err := strconv.Atoi(val); err == nil {\n\t\t\t\t\t\tresult = float64(s)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase constants.DimFoot:\n\t\t\t\t{\n\t\t\t\t\tif s, err := strconv.Atoi(val); err == nil {\n\t\t\t\t\t\tresult = float64(s * 12)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase constants.DimFraction:\n\t\t{\n\t\t\t//representation format whole_numerator/denominator\n\t\t\tnumval := splitterRegExp.Split(val, -1)\n\t\t\twhole, _ := strconv.ParseFloat(numval[0], 64)\n\t\t\tnum, _ := strconv.ParseFloat(numval[1], 64)\n\t\t\tdenom, _ := strconv.ParseFloat(numval[2], 64)\n\n\t\t\tswitch measurement.Indicator {\n\t\t\tcase constants.DimInch:\n\t\t\t\t{\n\t\t\t\t\tresult = whole + (num / denom)\n\t\t\t\t}\n\t\t\tcase constants.DimFoot:\n\t\t\t\t{\n\t\t\t\t\tresult = (whole + (num / denom)) * float64(12)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase constants.DimReal:\n\t\t{\n\t\t\tswitch measurement.Indicator {\n\t\t\tcase constants.DimInch:\n\t\t\t\t{\n\t\t\t\t\tif s, err := strconv.ParseFloat(val, 64); err == nil {\n\t\t\t\t\t\tresult = float64(s)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase constants.DimFoot:\n\t\t\t\t{\n\t\t\t\t\tif s, err := strconv.ParseFloat(val, 64); err == nil {\n\t\t\t\t\t\tresult = float64(s * 12)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func (b Datasize) Megabits() float64 {\n\treturn float64(b / Megabit)\n}", "func main() {\n fmt.Print(\"fahrenheit grades: \")\n var far float64\n fmt.Scanf(\"%f\", &far)\n // formula: c = (f-32) * 5/9\n celsius := ((far - 32) * 5 ) / 9\n fmt.Println(\"Celsius:\", celsius)\n}", "func (c Celsius) Fahrenheit() Fahrenheit {\n\treturn Fahrenheit((float32(c) * 1.8) + 32)\n}", "func makeFloatFromMandE(negative bool, e int, m []byte, tmp []byte) float64 {\n\t// ±.dddde±dd.\n\tb := tmp[:0]\n\tif n := len(m)*2 + 6; cap(b) < n {\n\t\tb = make([]byte, 0, n)\n\t}\n\tif negative {\n\t\tb = append(b, '-')\n\t}\n\tb = append(b, '.')\n\tfor i, v := range m {\n\t\tt := int(v)\n\t\tif i == len(m) {\n\t\t\tt--\n\t\t}\n\t\tt /= 2\n\t\tb = append(b, byte(t/10)+'0', byte(t%10)+'0')\n\t}\n\tb = append(b, 'e')\n\te = 2 * e\n\tif e < 0 {\n\t\tb = append(b, '-')\n\t\te = -e\n\t} else {\n\t\tb = append(b, '+')\n\t}\n\n\tvar buf [3]byte\n\ti := len(buf)\n\tfor e >= 10 {\n\t\ti--\n\t\tbuf[i] = byte(e%10 + '0')\n\t\te /= 10\n\t}\n\ti--\n\tbuf[i] = byte(e + '0')\n\n\tb = append(b, buf[i:]...)\n\n\t// We unsafely convert the []byte to a string to avoid the usual allocation\n\t// when converting to a string.\n\tf, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&b)), 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}", "func (c *Configurator) Float64F(name string, value float64, usage string) *float64 {\n\tp := new(float64)\n\n\tc.Float64VarF(p, name, value, usage)\n\n\treturn p\n}", "func Fahrenheit(f float64) Temperature {\n\treturn Temperature(f)\n}", "func FMod(arg float64, arg2 float64) float64 {\n\tflooRit := Floor(arg / arg2)\n\treturn arg - (flooRit * arg2)\n}", "func (s *Smplen) Float() float64 {\n\treturn s.f\n}" ]
[ "0.8732629", "0.8295069", "0.80937177", "0.80568784", "0.7716991", "0.7639768", "0.7630176", "0.75540096", "0.64776665", "0.63208914", "0.60592836", "0.5965205", "0.58784807", "0.579836", "0.57480294", "0.57229114", "0.57229114", "0.57229114", "0.57229114", "0.57229114", "0.57229114", "0.57229114", "0.57229114", "0.5671252", "0.5669211", "0.5618563", "0.5530842", "0.5530842", "0.5530842", "0.5530842", "0.5529625", "0.5529567", "0.5522556", "0.5499836", "0.547651", "0.5472383", "0.54169935", "0.53951883", "0.5343184", "0.53130007", "0.53115094", "0.5289978", "0.5242117", "0.522554", "0.51448846", "0.51067126", "0.509405", "0.50539833", "0.50136393", "0.50032485", "0.49389285", "0.49108303", "0.49075526", "0.4863818", "0.48534065", "0.48531544", "0.47935182", "0.47859606", "0.4784396", "0.47709817", "0.47530234", "0.47488245", "0.4745934", "0.47384155", "0.47260776", "0.47227547", "0.47134018", "0.47104806", "0.46972573", "0.4686956", "0.46686003", "0.465907", "0.46444625", "0.46427834", "0.46279034", "0.45982358", "0.4597864", "0.45878035", "0.4584829", "0.4581265", "0.45689386", "0.45661595", "0.45410007", "0.4540994", "0.45402762", "0.4538622", "0.45304495", "0.45264542", "0.45178276", "0.45169073", "0.4506783", "0.45052394", "0.44784218", "0.44727695", "0.44605696", "0.44587848", "0.44525075", "0.4445372", "0.444264", "0.444105" ]
0.8949944
0
FToM converts a Feet length to Meter.
func FToM(f Feet) Meter { return Meter(f * 0.3048) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FToM(f Feet) Meters {\n\treturn Meters(f / 3.2808)\n}", "func FToM(f Foot) Meter { return Meter(f * 0.3048) }", "func FTtoM(d Feet) Meter {\n\treturn Meter(d * 3.28084)\n}", "func MToF(m Meter) Feet { return Feet(m / 0.3048) }", "func MToF(m Meters) Feet {\n\treturn Feet(m * 3.2808)\n}", "func MToF(m Meter) Foot { return Foot(m / 0.3048) }", "func MeterToFeet(m Meter) Foot { return Foot(m / 3) }", "func FootToMeters(f Foot) Meter { return Meter(f * 3) }", "func MtoFT(d Meter) Feet {\n\treturn Feet(d / 3.28084)\n}", "func FeetToMeters(units float64) float64 {\n\treturn units * 0.3048\n}", "func ConvertFromM(n float64, toUnit string) float64 {\n\ttoUnit = strings.TrimSpace(strings.ToLower(toUnit))\n\tif v, is := SPEED_UNITS[toUnit]; is {\n\t\treturn n / v\n\t}\n\tif v, is := Units[toUnit]; is {\n\t\treturn n / v\n\t}\n\treturn 0\n}", "func (d *Distance) Meters() (result int) {\n\tswitch d.Unit {\n\tcase M:\n\t\tresult = d.Value\n\tcase FT:\n\t\tresult = cnv.FtToM(d.Value)\n\tcase SM:\n\t\tresult = cnv.SMileToM(float64(d.Value) + d.FractionValue)\n\tdefault:\n\t\tresult = d.Value\n\t}\n\treturn\n}", "func (d *Distance) Miles() (result float64) {\n\tswitch d.Unit {\n\tcase M:\n\t\tresult = cnv.MToSMile(d.Value)\n\tcase FT:\n\t\tresult = float64(cnv.FtToSMile(int(d.Value)))\n\tcase SM:\n\t\tresult = float64(d.Value) + d.FractionValue\n\tdefault:\n\t\tresult = cnv.MToSMile(d.Value)\n\t}\n\treturn\n}", "func (cvr Converter) CentimeterToFeet(cm Centimeter) Feet {\n\treturn Feet(cm / 30.48)\n}", "func MiFromCm(cm uint32) float64 {\n\treturn (float64(cm) * Km2miles) / 100000\n}", "func (d *Distance) Feet() (result int) {\n\tswitch d.Unit {\n\tcase M:\n\t\tresult = cnv.MToFt(d.Value)\n\tcase FT:\n\t\tresult = d.Value\n\tcase SM:\n\t\tresult = cnv.SMileToFt(float64(d.Value) + d.FractionValue)\n\tdefault:\n\t\tresult = cnv.MToFt(d.Value)\n\t}\n\treturn\n}", "func ConvertKilometersToMiles(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {\n\tdistance, err := strconv.ParseFloat(in.String(), 64)\n\tif err != nil {\n\t\tdistance = 0\n\t}\n\n\treturn pongo2.AsValue(fmt.Sprintf(\"%01.1f\", float64(distance)*kmToMilesConstant)), nil\n}", "func (cvr Converter) CentimeterToFeet(c Centimeter) Feet {\n\treturn Feet(c / 30.48)\n}", "func (cvr Converter) FeetToCentimeter(ft Feet) Centimeter {\n\treturn Centimeter(ft * 30.48)\n}", "func (cvr Converter) FeetToCentimeter(f Feet) Centimeter {\n\treturn Centimeter(f) * Centimeter(30.48)\n}", "func (d HypergeometicDist) PMF(k float64) float64 {\n\tki := int(math.Floor(k))\n\tl, h := d.bounds()\n\tif ki < l || ki > h {\n\t\treturn 0\n\t}\n\treturn d.pmf(ki)\n}", "func (m *Float64Measure) M(v float64) Measurement {\n\treturn Measurement{\n\t\tm: m,\n\t\tdesc: m.desc,\n\t\tv: v,\n\t}\n}", "func ToF(str string) float64 {\n\tval, err := strconv.ParseFloat(str, 64)\n\tL.IsError(err, str)\n\treturn val\n}", "func (g GeoPoint) MilesTo(point GeoPoint) float64 {\n\treturn g.RadiansTo(point) * 3958.8\n}", "func (c *Coord) M() float64 { return c[3] }", "func main() {\n\t\n\tvar dimen_ft float64= 1362\n\t\n\tfmt.Print(\"The height of WTC is: \")\n\tfmt.Println(dimen_ft)\n\t\n\tvar f2m_conv = 0.3048\n\n\tvar dimen_m = dimen_ft * f2m_conv\n\n\tfmt.Print(\"The height in meters is: \")\n\tfmt.Println(dimen_m)\n\n}", "func (m *Message) MFI() (*MFI, error) {\n\tps, err := m.Parse(\"MFI\")\n\tpst, ok := ps.(*MFI)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func (p *prng) mkgf(d *[4]uint64) {\n\tvar t [4]uint64\n\tp.mk256(&t)\n\tcopy(d[:], t[:])\n}", "func ToMB(data uint64) uint64 {\n\treturn data / 1024 / 1024\n}", "func (t *Ticker) NewMFI(inTimePeriod int32) *MFI {\n\tcalculator := &mfiCalculator{\n\t\tTicker: t,\n\t\tFlowIdx: 0,\n\t\tMaxFlowIdx: inTimePeriod - 1,\n\t\tPeriod: inTimePeriod,\n\t\tMoneyFlow: make([]moneyFlow, inTimePeriod),\n\t}\n\treturn &MFI{\n\t\tCalculator: calculator,\n\t}\n}", "func (m *Message) MFE() (*MFE, error) {\n\tps, err := m.Parse(\"MFE\")\n\tpst, ok := ps.(*MFE)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func (t *Temp) F() int {\n\ttemp := math.Floor(float64(*t)*9/5) + 32\n\tif temp < 0 {\n\t\treturn int(temp - 1.0)\n\t}\n\treturn int(temp)\n}", "func FToK(f Fahrenheit) Kelvin {\n\tif f <= AbsoluteZeroF {\n\t\treturn AbsoluteZeroK\n\t}\n\treturn Kelvin((f - AbsoluteZeroF) * 5 / 9)\n}", "func (c *Capsule) MetaballField(coord Coord) float64 {\n\treturn -c.SDF(coord)\n}", "func (v Volume) Millilitres() float64 {\n\treturn float64(v / Millilitre)\n}", "func (t *Triangle) MetaballField(coord Coord) float64 {\n\treturn -t.SDF(coord)\n}", "func FToK(f Fahrenheit) Kelvin {\n\treturn Kelvin((f + 459.67) * 5 / 9)\n}", "func FToK(f Fahrenheit) Kelvin { return Kelvin(((f - 32.0) * 5.0 / 9.0) + 273.15) }", "func (c *Circle) MetaballField(coord Coord) float64 {\n\treturn -c.SDF(coord)\n}", "func P2MMetricFamilies(mfs []*dto.MetricFamily) []*MetricFamily {\n\tmoMfs := make([]*MetricFamily, 0, len(mfs))\n\tfor _, mf := range mfs {\n\t\tif mf.GetType() == dto.MetricType_UNTYPED {\n\t\t\t// Untyped is used as a placeholder, it has no data\n\t\t\tcontinue\n\t\t}\n\t\tmoMf := &MetricFamily{\n\t\t\tName: mf.GetName(),\n\t\t\tHelp: mf.GetHelp(),\n\t\t}\n\t\tswitch mf.GetType() {\n\t\tcase dto.MetricType_COUNTER:\n\t\t\tmoMf.Type = MetricType_COUNTER\n\t\t\tmoMf.Metric = P2MCounters(mf.Metric)\n\t\tcase dto.MetricType_GAUGE:\n\t\t\tmoMf.Type = MetricType_GAUGE\n\t\t\tmoMf.Metric = P2MGauges(mf.Metric)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unsupported metric type in mo %v\", mf.GetType()))\n\t\t}\n\t\tmoMfs = append(moMfs, moMf)\n\t}\n\treturn moMfs\n}", "func MphFromMps(mps float64) float64 {\n\treturn (float64(mps) * 3600 * Km2miles) / 1000\n}", "func TempFromF(f int) Temp {\n\tc := math.Floor(float64((f - 32)) / 1.8)\n\treturn Temp(c)\n\n}", "func (r *Rect) MetaballField(coord Coord) float64 {\n\treturn -r.SDF(coord)\n}", "func (v Volume) Femtolitres() float64 {\n\treturn float64(v / Femtolitre)\n}", "func (g *Circle) Meters() float64 {\n\treturn g.meters\n}", "func (measurement *DimMeasurement) ToInches() float64 {\n\tvar result float64\n\tresult = 0.0\n\tval := measurement.value\n\tswitch measurement.precision {\n\tcase constants.DimWholeNumber:\n\t\t{\n\t\t\tswitch measurement.Indicator {\n\t\t\tcase constants.DimInch:\n\t\t\t\t{\n\t\t\t\t\tif s, err := strconv.Atoi(val); err == nil {\n\t\t\t\t\t\tresult = float64(s)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase constants.DimFoot:\n\t\t\t\t{\n\t\t\t\t\tif s, err := strconv.Atoi(val); err == nil {\n\t\t\t\t\t\tresult = float64(s * 12)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase constants.DimFraction:\n\t\t{\n\t\t\t//representation format whole_numerator/denominator\n\t\t\tnumval := splitterRegExp.Split(val, -1)\n\t\t\twhole, _ := strconv.ParseFloat(numval[0], 64)\n\t\t\tnum, _ := strconv.ParseFloat(numval[1], 64)\n\t\t\tdenom, _ := strconv.ParseFloat(numval[2], 64)\n\n\t\t\tswitch measurement.Indicator {\n\t\t\tcase constants.DimInch:\n\t\t\t\t{\n\t\t\t\t\tresult = whole + (num / denom)\n\t\t\t\t}\n\t\t\tcase constants.DimFoot:\n\t\t\t\t{\n\t\t\t\t\tresult = (whole + (num / denom)) * float64(12)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase constants.DimReal:\n\t\t{\n\t\t\tswitch measurement.Indicator {\n\t\t\tcase constants.DimInch:\n\t\t\t\t{\n\t\t\t\t\tif s, err := strconv.ParseFloat(val, 64); err == nil {\n\t\t\t\t\t\tresult = float64(s)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase constants.DimFoot:\n\t\t\t\t{\n\t\t\t\t\tif s, err := strconv.ParseFloat(val, 64); err == nil {\n\t\t\t\t\t\tresult = float64(s * 12)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func (g *GaugeUint64) Mtype() int {\n\treturn MeterGauge\n}", "func CToF(c Celsius) Farenheit { return Farenheit(c*9/5 + 32) }", "func (b Datasize) Megabits() float64 {\n\treturn float64(b / Megabit)\n}", "func (s Size) Mebibytes() float64 { return float64(s) / float64(Mebibyte) }", "func MphFromMMs(mms uint32) float64 {\n\treturn (float64(mms) * 3600 * Km2miles) / 1000000\n}", "func (cti CubicThousandthInch) ToCubicFeet() CubicFeet {\n\tcubicThousandthInchPerCubicFoot := thousandthInchPerFoot * thousandthInchPerFoot * thousandthInchPerFoot\n\treturn CubicFeet(float64(cti) / float64(cubicThousandthInchPerCubicFoot))\n}", "func CtoF(t float32) float32 {\n\treturn (t*9/5 + 32)\n}", "func pxToMM(px float64) float64 {\n\treturn mmPerPixel * px\n}", "func Momentum(n int) func(s []float64) []float64 {\n\treturn func(s []float64) (res []float64) {\n\t\tf := Skip(n)(s)\n\t\tres = make([]float64, len(f))\n\t\tfor i := range res {\n\t\t\tres[i] = f[i]/s[i] - 1\n\t\t}\n\n\t\treturn\n\t}\n}", "func parseSpecifier(b string) float64 {\n\tlb := len(b)\n\tif lb == 0 {\n\t\treturn 0\n\t}\n\n\tvar b0, b1 byte\n\tif lb < 2 {\n\t\tb0 = b[0]\n\t\tb1 = '0'\n\t} else {\n\t\tb1 = b[1]\n\t\tb0 = b[0]\n\t}\n\n\tif b1 != '0' {\n\t\tif b1 == 'b' { // bits, so convert bytes to bits for os.Seek()\n\t\t\tif b0 == 'k' || b0 == 'K' {\n\t\t\t\treturn 0.0078125\n\t\t\t}\n\n\t\t\tif b0 == 'm' || b0 == 'M' {\n\t\t\t\treturn 7.62939453125e-06\n\t\t\t}\n\n\t\t\tif b0 == 'g' || b0 == 'G' {\n\t\t\t\treturn 7.45058059692383e-09\n\t\t\t}\n\t\t}\n\n\t\tif b1 == 'B' { // kilo/mega/giga- bytes are assumed\n\t\t\tif b0 == 'k' || b0 == 'K' {\n\t\t\t\treturn 1024\n\t\t\t}\n\n\t\t\tif b0 == 'm' || b0 == 'M' {\n\t\t\t\treturn 1048576\n\t\t\t}\n\n\t\t\tif b0 == 'g' || b0 == 'G' {\n\t\t\t\treturn 1073741824\n\t\t\t}\n\t\t}\n\t} else { // kilo/mega/giga- bytes are assumed for single b, k, m, g\n\t\tif b0 == 'k' || b0 == 'K' {\n\t\t\treturn 1024\n\t\t}\n\n\t\tif b0 == 'm' || b0 == 'M' {\n\t\t\treturn 1048576\n\t\t}\n\n\t\tif b0 == 'g' || b0 == 'G' {\n\t\t\treturn 1073741824\n\t\t}\n\t}\n\n\treturn 1 // assumes bytes as fallback\n}", "func (bd *BaseItems) CalcSatM() {\n\tdd := *bd\n\tepoch := bd.GetItem(\"satEpoch\")\n\tm0 := (dd[\"planetMeanAno\"].Value / 180.0) * math.Pi\n\tdelT := dd[\"tempNow\"].Value - epoch // TODO: need to add error checking\n\tfmt.Println(\"Delta T\", delT, epoch, dd[\"tempNow\"].Value)\n\t// if delT < 0.0 {\n\t// \tdelT = 0.0\n\t// }\n\tm := m0 + (2.0*math.Pi*delT)/dd[\"planetPeriod\"].Value\n\n\tm = math.Mod(m, 2.0*math.Pi)\n\n\tdd[\"planetM\"] = BaseItem{\n\t\tName: \"planetM\",\n\t\tValue: skymath.ToDegrees(m),\n\t\tNumonic: \"M\",\n\t\tDescription: \"Degrees: Planet mean anomaly at desired epoch\",\n\t}\n}", "func (e PrecisionTiming) durationToMs(x time.Duration) float64 {\n\treturn float64(x) / float64(time.Millisecond)\n}", "func BytesToMb(b uint64) uint64 {\n\treturn b / 1024 / 1024\n}", "func (fn *formulaFuncs) MDURATION(argsList *list.List) formulaArg {\n\targs := fn.prepareDurationArgs(\"MDURATION\", argsList)\n\tif args.Type != ArgList {\n\t\treturn args\n\t}\n\tduration := fn.duration(args.List[0], args.List[1], args.List[2], args.List[3], args.List[4], args.List[5])\n\tif duration.Type != ArgNumber {\n\t\treturn duration\n\t}\n\treturn newNumberFormulaArg(duration.Number / (1 + args.List[3].Number/args.List[4].Number))\n}", "func (kh kelvinHandler) ToFahrenheit(temp float64) float64 {\n\treturn (kh.ToCelsius(temp) * fahrenheitMultiplier) + FahrenheitBase\n}", "func bToMb(b uint64) uint64 {\n\treturn b / 1024 / 1024\n}", "func GetDurationInMillseconds(start time.Time) float64 {\n\tend := time.Now()\n\tduration := end.Sub(start)\n\tmilliseconds := float64(duration) / float64(time.Millisecond)\n\trounded := float64(int(milliseconds*100+.5)) / 100\n\treturn rounded\n}", "func GetDurationInMillseconds(start time.Time) float64 {\n\tend := time.Now()\n\tduration := end.Sub(start)\n\tmilliseconds := float64(duration) / float64(time.Millisecond)\n\trounded := float64(int(milliseconds*100+.5)) / 100\n\treturn rounded\n}", "func DaytoMinutes(day float32) float32 {\n\treturn day * 1440\n}", "func floatSmplen(f float64) *Smplen {\n\treturn &Smplen{f: f, flag: Float}\n}", "func (mv MassVal) Convert(to UnitType) (UnitVal, error) {\n\tif to, ok := to.(*MassUnit); ok {\n\t\tmv.U = to\n\t\treturn mv, nil\n\t}\n\treturn nil, ErrorConversion{mv.U, to}\n}", "func (fn *formulaFuncs) MUNIT(argsList *list.List) (result formulaArg) {\n\tif argsList.Len() != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"MUNIT requires 1 numeric argument\")\n\t}\n\tdimension := argsList.Back().Value.(formulaArg).ToNumber()\n\tif dimension.Type == ArgError || dimension.Number < 0 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, dimension.Error)\n\t}\n\tmatrix := make([][]formulaArg, 0, int(dimension.Number))\n\tfor i := 0; i < int(dimension.Number); i++ {\n\t\trow := make([]formulaArg, int(dimension.Number))\n\t\tfor j := 0; j < int(dimension.Number); j++ {\n\t\t\tif i == j {\n\t\t\t\trow[j] = newNumberFormulaArg(1.0)\n\t\t\t} else {\n\t\t\t\trow[j] = newNumberFormulaArg(0.0)\n\t\t\t}\n\t\t}\n\t\tmatrix = append(matrix, row)\n\t}\n\treturn newMatrixFormulaArg(matrix)\n}", "func (m *Money) Mulf(f float64) *Money {\n\ti := m.M * int64(f*Guardf*DPf)\n\tr := i / Guard / DP\n\treturn m.Set(Rnd(r, float64(i)/Guardf/DPf-float64(r)))\n}", "func toMetricFamily(\n\tdtoMF *io_prometheus_client.MetricFamily,\n\tbind BindFunc,\n) *MetricFamily {\n\tmf := &MetricFamily{\n\t\t//Time: time.Now(),\n\t\tName: dtoMF.GetName(),\n\t\tHelp: dtoMF.GetHelp(),\n\t\tType: dtoMF.GetType().String(),\n\n\t\tValues: make([]*MetricValue, 0),\n\t}\n\n\tswitch dtoMF.GetType() {\n\tcase io_prometheus_client.MetricType_SUMMARY:\n\t\t// TODO: implement summary type converter\n\tcase io_prometheus_client.MetricType_HISTOGRAM:\n\t\t// TODO: implement histogram type converter\n\tcase\n\t\tio_prometheus_client.MetricType_GAUGE,\n\t\tio_prometheus_client.MetricType_COUNTER,\n\t\tio_prometheus_client.MetricType_UNTYPED:\n\n\t\tuniqueTags := map[string]bool{}\n\n\t\tfor _, m := range dtoMF.Metric {\n\t\t\tlabels := makeLabels(m)\n\t\t\tentities, labels := bind(labels)\n\t\t\tfor label := range labels {\n\t\t\t\tuniqueTags[label] = true\n\t\t\t}\n\n\t\t\tif entities != nil {\n\t\t\t\tmf.Values = append(\n\t\t\t\t\tmf.Values,\n\t\t\t\t\t&MetricValue{\n\t\t\t\t\t\tEntities: entities,\n\n\t\t\t\t\t\tTags: labels,\n\t\t\t\t\t\tValue: getValue(m),\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tmetricTags := make([]string, len(uniqueTags))\n\t\ti := 0\n\t\tfor tag := range uniqueTags {\n\t\t\tmetricTags[i] = tag\n\t\t\ti++\n\t\t}\n\t\tmf.Tags = metricTags\n\t}\n\n\treturn mf\n}", "func (c Converter) Convert() (float64, error) {\n\tst := reflect.TypeOf(c.from)\n\tdt := reflect.TypeOf(c.to)\n\t// 解析source\n\tif st.Name() != dt.Name() {\n\t\treturn 0, fmt.Errorf(\"unit type error: source type[%s], destination type[%s]\", st.Name(), dt.Name())\n\t}\n\td := c.from.Float64() * c.data / c.to.Float64()\n\treturn d, nil\n}", "func bToMb(b uint64) uint64 {\r\n return b / 1024 / 1024\r\n}", "func (_ECC *ECCSession) Mf(arg0 common.Address) (bool, error) {\n\treturn _ECC.Contract.Mf(&_ECC.CallOpts, arg0)\n}", "func (m *Message) AllMFI() ([]*MFI, error) {\n\tpss, err := m.ParseAll(\"MFI\")\n\treturn pss.([]*MFI), err\n}", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }", "func durationFromMvhdAtom(mvhdStart int64, mvhdLength int64, file *os.File) (int, error) {\n\tbuffer := make([]byte, 8)\n\t_, err := file.ReadAt(buffer, mvhdStart+20) // The timescale field starts at the 21st byte of the mvhd atom\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// The timescale is bytes 21-24.\n\t// The duration is bytes 25-28\n\ttimescale := convertBytesToInt(buffer[0:4]) // This is in number of units per second\n\tdurationInTimeScale := convertBytesToInt(buffer[4:])\n\treturn int(durationInTimeScale) / int(timescale), nil\n}", "func KToF(k Kelvin) Fahrenheit { return Fahrenheit((k-273.15)*9.0/5.0 + 32.0) }", "func (b Datasize) Mebibits() float64 {\n\treturn float64(b / Mebibit)\n}", "func getMegabytes(data *speedTestData) float64 {\n\treturn float64(data.Bytes) / 1048576\n}", "func FastMetersPerDegreeLng(lng float64) float64 {\n\ti0 := int(math.Floor(lng))\n\ti1 := int(math.Ceil(lng))\n\tx := lng - float64(i0)\n\tm0 := metersPerDegreeLng[i0]\n\tm1 := metersPerDegreeLng[i1]\n\treturn m0 + (m1-m0)*x\n}", "func (m *Message) AllMFE() ([]*MFE, error) {\n\tpss, err := m.ParseAll(\"MFE\")\n\treturn pss.([]*MFE), err\n}", "func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9.0/5.0 + 32.0) }", "func NewMAF(size int, labels []string) (*MAF, error) {\n\tif size == 0 {\n\t\treturn nil, fmt.Errorf(\"size must be > 0\")\n\t}\n\tif len(labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"must specify at least one label\")\n\t}\n\tmaf := &MAF{\n\t\tstate: map[string]*labelState{},\n\t}\n\tfor _, label := range labels {\n\t\tmaf.state[label] = &labelState{0, 0, make([]float64, size)}\n\t}\n\treturn maf, nil\n}", "func Meter(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"meter\", Attributes: attrs, Children: children}\n}", "func (m Message) UnitOfMeasure() (*field.UnitOfMeasureField, quickfix.MessageRejectError) {\n\tf := &field.UnitOfMeasureField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func ConvertToFloatModifier(i interface{}) (interface{}, error) {\n\tswitch v := i.(type) {\n\tcase string:\n\t\ti, err := strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn i, nil\n\tcase int:\n\t\treturn float64(v), nil\n\tcase int32:\n\t\treturn float64(v), nil\n\tcase int64:\n\t\treturn float64(v), nil\n\tcase float64:\n\t\treturn float64(v), nil\n\tcase float32:\n\t\treturn float64(v), nil\n\t}\n\treturn nil, fmt.Errorf(\"Invalid type (%v) to make float\", reflect.TypeOf(i))\n}", "func (_ECC *ECCCallerSession) Mf(arg0 common.Address) (bool, error) {\n\treturn _ECC.Contract.Mf(&_ECC.CallOpts, arg0)\n}", "func calculateFuel(mass float64) float64{\n return math.Floor(mass / 3) - 2\n}", "func getMegabits(data *speedTestData) float64 {\n\treturn (float64(data.Bytes) / 1048576) * 8\n}", "func NewFMul(x, y value.Value) *InstFMul {\n\tinst := &InstFMul{X: x, Y: y}\n\t// Compute type.\n\tinst.Type()\n\treturn inst\n}", "func KToF(k Kelvin) Fahrenheit { return CToF(KToC(k)) }", "func KToF(k Kelvin) Fahrenheit {\n\treturn Fahrenheit(k*9/5 - 459.67)\n}", "func (m *Money) Get() float64 {\n\treturn float64(m.M) / DPf\n}" ]
[ "0.881617", "0.85965323", "0.81678784", "0.8112541", "0.7776817", "0.77148", "0.73424447", "0.72268784", "0.7085568", "0.69765157", "0.6155982", "0.5629086", "0.5628927", "0.5565895", "0.55502135", "0.5509309", "0.548419", "0.5455039", "0.54531205", "0.5435615", "0.53889567", "0.53658235", "0.528354", "0.52835083", "0.5241645", "0.5205179", "0.5090528", "0.50751346", "0.50732607", "0.5042086", "0.5034246", "0.50193137", "0.49150214", "0.49002662", "0.48925632", "0.48888695", "0.48875496", "0.48813492", "0.486713", "0.48533025", "0.48302516", "0.4818144", "0.47768986", "0.47709477", "0.47660354", "0.4762281", "0.47332764", "0.4731008", "0.47237962", "0.47161257", "0.47128582", "0.47061828", "0.47020915", "0.46908545", "0.46481004", "0.46471068", "0.46350965", "0.46323252", "0.46230724", "0.45880824", "0.45818907", "0.45752752", "0.4575026", "0.4575026", "0.4566312", "0.45392343", "0.45286828", "0.45226192", "0.452241", "0.4503777", "0.45017737", "0.4500666", "0.44978267", "0.44910172", "0.4490014", "0.4490014", "0.4490014", "0.4490014", "0.4490014", "0.4490014", "0.4490014", "0.4490014", "0.44841447", "0.44840857", "0.44837162", "0.44758955", "0.44629496", "0.4448902", "0.44427294", "0.4436905", "0.44301823", "0.44278228", "0.44244075", "0.44208005", "0.44157758", "0.44088277", "0.4402548", "0.43992805", "0.4393966", "0.4388798" ]
0.8957964
0
KToP converts a Kilogram weight to Pound.
func KToP(k Kilogram) Pound { return Pound(k / 0.45359237) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func KToP(k Kilogram) Pound {\n\treturn Pound(k * 2.205)\n}", "func KToP(k Kilogram) Pound { return Pound(k * 2.205) }", "func KToP(k Kilogram) Pound { return Pound(k / OnePoundInKilograms) }", "func KToP(k Kilograms) Pounds { return Pounds(k * conversion) }", "func KToP(k Kilograms) Pounds {\n\treturn Pounds(k * 2.205)\n}", "func PToK(p Pound) Kilogram {\n\treturn Kilogram(p / 2.205)\n}", "func PToK(p Pound) Kilogram { return Kilogram(p * OnePoundInKilograms) }", "func PToK(p Pound) Kilogram { return Kilogram(p * 0.45359237) }", "func PToK(p Pound) Kilogram { return Kilogram(p * 0.45359237) }", "func PToK(p Pounds) Kilograms { return Kilograms(p / conversion) }", "func PToK(p Pounds) Kilograms {\n\treturn Kilograms(p / 2.205)\n}", "func KgToPound(kgs Kilogram) Pound {\n\treturn Pound(kgs * KgToLbRatio)\n}", "func KiloToPounds(k Kilogram) Pound { return Pound(k / 2.2) }", "func PoundToKilos(p Pound) Kilogram { return Kilogram(p * 2.2) }", "func LbsToKgs(lbs Pound) Kilogram {\n\treturn Kilogram(lbs * LbToKgRatio)\n}", "func ConvertToPPK(privateKey *rsa.PrivateKey, pub []byte) ([]byte, error) {\n\t// https://the.earth.li/~sgtatham/putty/0.76/htmldoc/AppendixC.html#ppk\n\t// RSA keys are stored using an algorithm-name of 'ssh-rsa'. (Keys stored like this are also used by the updated RSA signature schemes that use\n\t// hashes other than SHA-1. The public key data has already provided the key modulus and the public encoding exponent. The private data stores:\n\t// mpint: the private decoding exponent of the key.\n\t// mpint: one prime factor p of the key.\n\t// mpint: the other prime factor q of the key. (RSA keys stored in this format are expected to have exactly two prime factors.)\n\t// mpint: the multiplicative inverse of q modulo p.\n\tppkPrivateKey := new(bytes.Buffer)\n\n\t// mpint: the private decoding exponent of the key.\n\t// this is known as 'D'\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(privateKey.D))\n\n\t// mpint: one prime factor p of the key.\n\t// this is known as 'P'\n\t// the RSA standard dictates that P > Q\n\t// for some reason what PuTTY names 'P' is Primes[1] to Go, and what PuTTY names 'Q' is Primes[0] to Go\n\tP, Q := privateKey.Primes[1], privateKey.Primes[0]\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(P))\n\n\t// mpint: the other prime factor q of the key. (RSA keys stored in this format are expected to have exactly two prime factors.)\n\t// this is known as 'Q'\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(Q))\n\n\t// mpint: the multiplicative inverse of q modulo p.\n\t// this is known as 'iqmp'\n\tiqmp := new(big.Int).ModInverse(Q, P)\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(iqmp))\n\n\t// now we need to base64-encode the PPK-formatted private key which is made up of the above values\n\tppkPrivateKeyBase64 := make([]byte, base64.StdEncoding.EncodedLen(ppkPrivateKey.Len()))\n\tbase64.StdEncoding.Encode(ppkPrivateKeyBase64, ppkPrivateKey.Bytes())\n\n\t// read Teleport public key\n\t// fortunately, this is the one thing that's in exactly the same format that the PPK file uses, so we can just copy it verbatim\n\t// remove ssh-rsa plus additional space from beginning of string if present\n\tif !bytes.HasPrefix(pub, []byte(constants.SSHRSAType+\" \")) {\n\t\treturn nil, trace.BadParameter(\"pub does not appear to be an ssh-rsa public key\")\n\t}\n\tpub = bytes.TrimSuffix(bytes.TrimPrefix(pub, []byte(constants.SSHRSAType+\" \")), []byte(\"\\n\"))\n\n\t// the PPK file contains an anti-tampering MAC which is made up of various values which appear in the file.\n\t// copied from Section C.3 of https://the.earth.li/~sgtatham/putty/0.76/htmldoc/AppendixC.html#ppk:\n\t// hex-mac-data is a hexadecimal-encoded value, 64 digits long (i.e. 32 bytes), generated using the HMAC-SHA-256 algorithm with the following binary data as input:\n\t// string: the algorithm-name header field.\n\t// string: the encryption-type header field.\n\t// string: the key-comment-string header field.\n\t// string: the binary public key data, as decoded from the base64 lines after the 'Public-Lines' header.\n\t// string: the plaintext of the binary private key data, as decoded from the base64 lines after the 'Private-Lines' header.\n\n\t// these values are also used in the MAC generation, so we declare them as variables\n\tkeyType := constants.SSHRSAType\n\tencryptionType := \"none\"\n\t// as work for the future, it'd be nice to get the proxy/user pair name in here to make the name more\n\t// of a unique identifier. this has to be done at generation time because the comment is part of the MAC\n\tfileComment := \"teleport-generated-ppk\"\n\n\t// string: the algorithm-name header field.\n\tmacKeyType := getRFC4251String([]byte(keyType))\n\t// create a buffer to hold the elements needed to generate the MAC\n\tmacInput := new(bytes.Buffer)\n\tbinary.Write(macInput, binary.LittleEndian, macKeyType)\n\n\t// string: the encryption-type header field.\n\tmacEncryptionType := getRFC4251String([]byte(encryptionType))\n\tbinary.Write(macInput, binary.BigEndian, macEncryptionType)\n\n\t// string: the key-comment-string header field.\n\tmacComment := getRFC4251String([]byte(fileComment))\n\tbinary.Write(macInput, binary.BigEndian, macComment)\n\n\t// base64-decode the Teleport public key, as we need its binary representation to generate the MAC\n\tdecoded := make([]byte, base64.StdEncoding.EncodedLen(len(pub)))\n\tn, err := base64.StdEncoding.Decode(decoded, pub)\n\tif err != nil {\n\t\treturn nil, trace.Errorf(\"could not base64-decode public key: %v, got %v bytes successfully\", err, n)\n\t}\n\tdecoded = decoded[:n]\n\t// append the decoded public key bytes to the MAC buffer\n\tmacPublicKeyData := getRFC4251String(decoded)\n\tbinary.Write(macInput, binary.BigEndian, macPublicKeyData)\n\n\t// append our PPK-formatted private key bytes to the MAC buffer\n\tmacPrivateKeyData := getRFC4251String(ppkPrivateKey.Bytes())\n\tbinary.Write(macInput, binary.BigEndian, macPrivateKeyData)\n\n\t// as per the PPK spec, the key for the MAC is blank when the PPK file is unencrypted.\n\t// therefore, the key is a zero-length byte slice.\n\thmacHash := hmac.New(sha256.New, []byte{})\n\t// generate the MAC using HMAC-SHA-256\n\thmacHash.Write(macInput.Bytes())\n\tmacString := hex.EncodeToString(hmacHash.Sum(nil))\n\n\t// build the string-formatted output PPK file\n\tppk := new(bytes.Buffer)\n\tfmt.Fprintf(ppk, \"PuTTY-User-Key-File-3: %v\\n\", keyType)\n\tfmt.Fprintf(ppk, \"Encryption: %v\\n\", encryptionType)\n\tfmt.Fprintf(ppk, \"Comment: %v\\n\", fileComment)\n\t// chunk the Teleport-formatted public key into 64-character length lines\n\tchunkedPublicKey := chunk(string(pub), 64)\n\tfmt.Fprintf(ppk, \"Public-Lines: %v\\n\", len(chunkedPublicKey))\n\tfor _, r := range chunkedPublicKey {\n\t\tfmt.Fprintf(ppk, \"%s\\n\", r)\n\t}\n\t// chunk the PPK-formatted private key into 64-character length lines\n\tchunkedPrivateKey := chunk(string(ppkPrivateKeyBase64), 64)\n\tfmt.Fprintf(ppk, \"Private-Lines: %v\\n\", len(chunkedPrivateKey))\n\tfor _, r := range chunkedPrivateKey {\n\t\tfmt.Fprintf(ppk, \"%s\\n\", r)\n\t}\n\tfmt.Fprintf(ppk, \"Private-MAC: %v\\n\", macString)\n\n\treturn ppk.Bytes(), nil\n}", "func TrezorP2WPKH() []int {\n\treturn []int{39, 40, 41, 42}\n}", "func keypen(k int) (p float64) { return rowpen[row(k)] + fingerpen[finger(k)] }", "func CToK(c Celsius) Kelvin { return Kelvin(c + 273.15) }", "func CToK(c Celsius) Kelvin {\n\tif c <= AbsoluteZeroC {\n\t\treturn AbsoluteZeroK\n\t}\n\treturn Kelvin(c - AbsoluteZeroC)\n}", "func Pwm(pinNo int, freq int, duty int) {\n\tdutyCyle := (float32(duty)) / 100.0\n\tperiod := (1.0 / float32(freq)) * 1000.0\n\tperiodHigh := period * dutyCyle\n\tperiodLow := period - (period * dutyCyle)\n\n\tdHigh := (time.Duration(periodHigh*1000) * time.Microsecond)\n\tdLow := (time.Duration(periodLow*1000) * time.Microsecond)\n\n\tSetDirection(pinNo, 1)\n\n\tfor {\n\t\tWrite(pinNo, 1)\n\t\ttime.Sleep(dHigh)\n\t\tWrite(pinNo, 0)\n\t\ttime.Sleep(dLow)\n\t}\n}", "func CToK(c Celsius) Kelvin {\n\treturn Kelvin(c - AbsoluteZeroC)\n}", "func CToK(c Celsius) Kelvin { return Kelvin(c - 273.15) }", "func FToK(f Fahrenheit) Kelvin {\n\treturn Kelvin((f + 459.67) * 5 / 9)\n}", "func (kh kelvinHandler) ToKelvin(temp float64) float64 {\n\treturn temp\n}", "func (kg Kilogram) Weight() {\n\n}", "func Convert(number int) string {\n\n\tvar raindropSound string\n\n\t// Slice named keys which will keep the keys of the map numberToSound in order\n\tvar keys []int\n\n\tnumberToSound := map[int]string{\n\t\t3: \"Pling\",\n\t\t5: \"Plang\",\n\t\t7: \"Plong\",\n\t}\n\n\t// Append the keys in the numberToSound map into a slice named keys\n\tfor k := range numberToSound {\n\t\tkeys = append(keys, k)\n\t}\n\n\t// Sort the keys\n\tsort.Ints(keys)\n\n\tfor _, key := range keys {\n\t\tif number%key == 0 {\n\t\t\traindropSound += numberToSound[key]\n\t\t}\n\t}\n\n\tif raindropSound != \"\" {\n\t\treturn raindropSound\n\t}\n\n\treturn strconv.Itoa(number)\n}", "func FToK(f Fahrenheit) Kelvin { return Kelvin(((f - 32.0) * 5.0 / 9.0) + 273.15) }", "func KtoF(k Kalvin) Fahrenheit {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// (t°K - 273.15) * 9/5 + 32\n\treturn Fahrenheit(round((float64(k)-273.15)*1.8+32, 100))\n}", "func Convert(sound int) (result string) {\n\n\tif sound%3 == 0 {\n\t\tresult += \"Pling\"\n\t}\n\n\tif sound%5 == 0 {\n\t\tresult += \"Plang\"\n\t}\n\n\tif sound%7 == 0 {\n\t\tresult += \"Plong\"\n\t}\n\n\tif sound%3 != 0 &&\n\t\tsound%5 != 0 &&\n\t\tsound%7 != 0 {\n\t\tresult += strconv.Itoa(sound)\n\t}\n\treturn\n}", "func KToF(k Kelvin) Fahrenheit {\n\treturn Fahrenheit(k*9/5 - 459.67)\n}", "func FToK(f Fahrenheit) Kelvin {\n\tif f <= AbsoluteZeroF {\n\t\treturn AbsoluteZeroK\n\t}\n\treturn Kelvin((f - AbsoluteZeroF) * 5 / 9)\n}", "func penalty(b board) (p float64) {\n\tfor k := range pen {\n\t\tp += pen[k] * freq[b[k]]\n\t}\n\treturn\n}", "func KToF(k Kelvin) Fahrenheit {\n\tif k <= AbsoluteZeroK {\n\t\treturn AbsoluteZeroF\n\t}\n\treturn Fahrenheit(k*9/5) + AbsoluteZeroF\n}", "func (o InitialStateConfigOutput) Pk() FileContentBufferPtrOutput {\n\treturn o.ApplyT(func(v InitialStateConfig) *FileContentBuffer { return v.Pk }).(FileContentBufferPtrOutput)\n}", "func KToF(k Kelvin) Fahrenheit { return CToF(KToC(k)) }", "func (cpu *Mos6502) plp() uint8 {\n\tcpu.stkp++\n\tcpu.status = cpu.read(0x0100 + word(cpu.stkp))\n\tcpu.setStatusFlag(U, true)\n\treturn 0\n}", "func possibleK(pair messagePair, pub *dsa.PublicKey) *big.Int {\n\tz1 := new(big.Int).SetBytes(pair.fst.sum)\n\tz2 := new(big.Int).SetBytes(pair.snd.sum)\n\n\tz1.Sub(z1, z2)\n\tz2.Sub(pair.fst.s, pair.snd.s)\n\tz2.ModInverse(z2, pub.Q)\n\tk := z1.Mul(z1, z2)\n\n\treturn k.Mod(k, pub.Q)\n}", "func (o InitialStateConfigPtrOutput) Pk() FileContentBufferPtrOutput {\n\treturn o.ApplyT(func(v *InitialStateConfig) *FileContentBuffer {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Pk\n\t}).(FileContentBufferPtrOutput)\n}", "func Convert(number int) string {\n\tvar raindropSpeak bytes.Buffer\n\tif (number % 3) == 0 {\n\t\traindropSpeak.WriteString(\"Pling\")\n\t}\n\tif (number % 5) == 0 {\n\t\traindropSpeak.WriteString(\"Plang\")\n\t}\n\tif (number % 7) == 0 {\n\t\traindropSpeak.WriteString(\"Plong\")\n\t}\n\tif len(raindropSpeak.String()) == 0 {\n\t\traindropSpeak.WriteString(strconv.Itoa(number))\n\t}\n\n\treturn raindropSpeak.String()\n}", "func CVTPL2PD(mx, x operand.Op) { ctx.CVTPL2PD(mx, x) }", "func Convert(drop int) string {\n\tvar dropSpeak string\n\n\t// Check the drop-speak applicable factors\n\tif drop%3 == 0 {\n\t\tdropSpeak += \"Pling\"\n\t}\n\tif drop%5 == 0 {\n\t\tdropSpeak += \"Plang\"\n\t}\n\tif drop%7 == 0 {\n\t\tdropSpeak += \"Plong\"\n\t}\n\n\t// If conversion is not applicable, set it to the number\n\tif dropSpeak == \"\" {\n\t\tdropSpeak = strconv.Itoa(drop)\n\t}\n\n\treturn dropSpeak\n}", "func Convert(rain int) string {\n\tvar x = \"\"\n\tif rain%3 == 0 {\n\t\tx += \"Pling\"\n\t}\n\n\tif rain%5 == 0 {\n\t\tx += \"Plang\"\n\t}\n\n\tif rain%7 == 0 {\n\t\tx += \"Plong\"\n\t}\n\n\tif rain%3 != 0 && rain%5 != 0 && rain%7 != 0 {\n\t\tx = strconv.Itoa(rain)\n\t}\n\n\treturn x\n}", "func KToF(k Kelvin) Fahrenheit { return Fahrenheit((k-273.15)*9.0/5.0 + 32.0) }", "func (rt *RecvTxOut) PkScript() []byte {\n\ttx := rt.tx.MsgTx()\n\treturn tx.TxOut[rt.outpoint.Index].PkScript\n}", "func CMYKtoDecimal(cmyk CMYK) Decimal {\n\treturn RGBtoDecimal(CMYKtoRGB(cmyk))\n}", "func packweight() int {\n\tk := c[GOLD] / 1000\n\tj := 25\n\tfor iven[j] == 0 && j > 0 {\n\t\tj--\n\t}\n\tfor i := 0; i <= j; i++ {\n\t\tswitch iven[i] {\n\t\tcase 0:\n\t\tcase OSSPLATE, OPLATEARMOR:\n\t\t\tk += 40\n\t\tcase OPLATE:\n\t\t\tk += 35\n\t\tcase OHAMMER:\n\t\t\tk += 30\n\t\tcase OSPLINT:\n\t\t\tk += 26\n\t\tcase OSWORDofSLASHING, OCHAIN, OBATTLEAXE, O2SWORD:\n\t\t\tk += 23\n\t\tcase OLONGSWORD, OSWORD, ORING, OFLAIL:\n\t\t\tk += 20\n\t\tcase OLANCE, OSTUDLEATHER:\n\t\t\tk += 15\n\t\tcase OLEATHER, OSPEAR:\n\t\t\tk += 8\n\t\tcase OORBOFDRAGON, OBELT:\n\t\t\tk += 4\n\t\tcase OSHIELD:\n\t\t\tk += 7\n\t\tcase OCHEST:\n\t\t\tk += 30 + ivenarg[i]\n\t\tdefault:\n\t\t\tk++\n\t\t}\n\t}\n\treturn k\n}", "func Convert(input int) string {\n\tvar output string\n\tif input%3 == 0 {\n\t\toutput += \"Pling\"\n\t}\n\tif input%5 == 0 {\n\t\toutput += \"Plang\"\n\t}\n\tif input%7 == 0 {\n\t\toutput += \"Plong\"\n\t}\n\tif output == \"\" {\n\t\toutput = strconv.Itoa(input)\n\t}\n\treturn output\n}", "func KmToPrice(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tfmt.Println(params[\"devise\"]) // TODO handle several devise\n\tdistance, err := strconv.ParseFloat(params[\"km\"], 64)\n\tif err != nil {\n\t\tfmt.Println(\"bad parameters : \" + params[\"km\"])\n\t}\n\tfmt.Println(distance)\n\n\tprice := KmPriceRatio * distance\n\tres := &responseKmToPrice{\n\t\tDevise: params[\"devise\"],\n\t\tPrice: price,\n\t\tDistance: distance,\n\t}\n\n\terr = json.NewEncoder(w).Encode(res)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func Convert(input int) string {\n\n\tvar result string\n\n\tif input%3 == 0 {\n\t\tresult = \"Pling\"\n\t}\n\n\tif input%5 == 0 {\n\t\tresult += \"Plang\"\n\t}\n\n\tif input%7 == 0 {\n\t\tresult += \"Plong\"\n\t}\n\n\tif len(result) == 0 {\n\t\tresult = strconv.Itoa(input)\n\t}\n\n\treturn result\n}", "func Convert(val int) string {\n\tpling := playSound(val, pli, \"Pling\")\n\tplang := playSound(val, pla, \"Plang\")\n\tplong := playSound(val, plo, \"Plong\")\n\tanswer := strings.Join([]string{pling, plang, plong}, \"\")\n\tif len(answer) == 0 {\n\t\treturn strconv.Itoa(val)\n\t}\n\treturn answer\n}", "func Convert(n int) string {\n\tm := map[int]string{\n\t\t3: \"Pling\",\n\t\t5: \"Plang\",\n\t\t7: \"Plong\",\n\t}\n\tvar r string\n\tfor k, v := range m {\n\t\tif n%k == 0 {\n\t\t\tr += v\n\t\t}\n\t}\n\n\tif len(r) == 0 {\n\t\treturn fmt.Sprintf(\"%v\", n)\n\t}\n\n\treturn r\n}", "func Convert(n int) string {\n\trainspeak := \"\"\n\tif n%3 == 0 {\n\t\trainspeak += \"Pling\"\n\t}\n\tif n%5 == 0 {\n\t\trainspeak += \"Plang\"\n\t}\n\tif n%7 == 0 {\n\t\trainspeak += \"Plong\"\n\t}\n\tif len(rainspeak) == 0 {\n\t\trainspeak = strconv.Itoa(n)\n\t}\n\treturn rainspeak\n}", "func CVTPL2PS(mx, x operand.Op) { ctx.CVTPL2PS(mx, x) }", "func Convert(n int) string {\n\tvar output string\n\n\tif n%3 == 0 {\n\t\toutput += \"Pling\"\n\t}\n\n\tif n%5 == 0 {\n\t\toutput += \"Plang\"\n\t}\n\n\tif n%7 == 0 {\n\t\toutput += \"Plong\"\n\t}\n\n\tif output == \"\" {\n\t\toutput += strconv.Itoa(n)\n\t}\n\n\treturn output\n}", "func (p Pound) Weight() {\n\n}", "func (f *Fpdf) UnitToPointConvert(u float64) (pt float64) {\n\treturn u * f.k\n}", "func Pwidth(wp, cw, defval float64) float64 {\n\tif wp == 0 {\n\t\treturn defval\n\t}\n\treturn (wp / 100) * cw\n}", "func calProb(N,K float64) float64{\r\n return Factorial(N)/(Factorial(N-K)*math.Pow(N,K))\r\n}", "func (this *activityGroupStruct) WeightKG() string {\n\tw := &this.weightKG\n\ts := w.String()\n\treturn s\n}", "func (qs ControlQS) KpLe(v float64) ControlQS {\n\treturn qs.filter(`\"kp\" <=`, v)\n}", "func ElectrumP2WPKH() []int {\n\treturn []int{31, 32, 33, 34}\n}", "func Convert(num int) string {\n\n\tout := \"\"\n\n\tif num%3 == 0 {\n\t\tout += \"Pling\"\n\t}\n\tif num%5 == 0 {\n\t\tout += \"Plang\"\n\t}\n\tif num%7 == 0 {\n\t\tout += \"Plong\"\n\t}\n\n\tif out == \"\" {\n\t\tout = strconv.Itoa(num)\n\t}\n\n\treturn out\n}", "func Convert(num int) string {\n\tsound := \"\"\n\n\t// If num has 3 as a factor, add \"Pling\" sound.\n\tif num%3 == 0 {\n\t\tsound += \"Pling\"\n\t}\n\n\t// If num has 5 as a factor, add \"Plang\" sound.\n\tif num%5 == 0 {\n\t\tsound += \"Plang\"\n\t}\n\n\t// If num has 7 as a factor, add \"Plong\" sound.\n\tif num%7 == 0 {\n\t\tsound += \"Plong\"\n\t}\n\n\t// If num does not have any 3, 5, 7 as a factor the sound will be the num\n\t// itself.\n\tif sound == \"\" {\n\t\tsound = strconv.Itoa(num)\n\t}\n\n\treturn sound\n}", "func Convert(n int) string {\n\tsounds := \"\"\n\tif n%3 == 0 {\n\t\tsounds += \"Pling\"\n\t}\n\tif n%5 == 0 {\n\t\tsounds += \"Plang\"\n\t}\n\tif n%7 == 0 {\n\t\tsounds += \"Plong\"\n\t}\n\n\tif sounds == \"\" {\n\t\tsounds += strconv.Itoa(n)\n\t}\n\n\treturn sounds\n}", "func Convert(number int) string {\n\tvar result string\n\n\tif number%3 == 0 {\n\t\tresult += \"Pling\"\n\t}\n\n\tif number%5 == 0 {\n\t\tresult += \"Plang\"\n\t}\n\n\tif number%7 == 0 {\n\t\tresult += \"Plong\"\n\t}\n\n\tif len(result) == 0 {\n\t\treturn strconv.Itoa(number)\n\t}\n\n\treturn result\n}", "func KUNPCKBW(k, k1, k2 operand.Op) { ctx.KUNPCKBW(k, k1, k2) }", "func Convert(n int) string {\n\tvar s string\n\n\tif n%3 == 0 {\n\t\ts += \"Pling\"\n\t}\n\tif n%5 == 0 {\n\t\ts += \"Plang\"\n\t}\n\tif n%7 == 0 {\n\t\ts += \"Plong\"\n\t}\n\tif s == \"\" {\n\t\ts = strconv.Itoa(n)\n\t}\n\n\treturn s\n}", "func TrezorP2WPKHAndP2SH() []int {\n\treturn []int{35, 36, 37, 38}\n}", "func PpModel(file *os.File, model ModelT, width uint32, height uint32, offset uint32) int32 {\n\treturn int32(C.yices_pp_model_fd(C.int(file.Fd()), ymodel(model), C.uint32_t(width), C.uint32_t(height), C.uint32_t(offset)))\n}", "func RoundP(x float64, p int) float64 {\n\tk := math.Pow10(p)\n\treturn math.Floor(x*k+0.5) / k\n}", "func Convert(value int) string {\n\tvar result string\n\tif value%3 == 0 {\n\t\tresult += \"Pling\"\n\t}\n\n\tif value%5 == 0 {\n\t\tresult += \"Plang\"\n\t}\n\n\tif value%7 == 0 {\n\t\tresult += \"Plong\"\n\t}\n\tif len(result) == 0 {\n\t\tresult = strconv.Itoa(value)\n\t}\n\treturn result\n}", "func Convert(number int) string {\n\n\tvar raindropSound string\n\n\tvar numberToSoundConverter = []struct {\n\t\tsoundNumber int\n\t\tsound string\n\t}{\n\t\t{3, \"Pling\"},\n\t\t{5, \"Plang\"},\n\t\t{7, \"Plong\"},\n\t}\n\n\tfor _, conversionElement := range numberToSoundConverter {\n\t\tif number%conversionElement.soundNumber == 0 {\n\t\t\traindropSound += conversionElement.sound\n\t\t}\n\t}\n\n\tif raindropSound != \"\" {\n\t\treturn raindropSound\n\t}\n\n\treturn strconv.Itoa(number)\n}", "func (o InitialStateConfigResponseOutput) Pk() FileContentBufferResponseOutput {\n\treturn o.ApplyT(func(v InitialStateConfigResponse) FileContentBufferResponse { return v.Pk }).(FileContentBufferResponseOutput)\n}", "func Convert(inputNumber int) string {\n\n\tvar buffer bytes.Buffer\n\tif inputNumber%3 == 0 {\n\t\tbuffer.WriteString(\"Pling\")\n\t}\n\tif inputNumber%5 == 0 {\n\t\tbuffer.WriteString(\"Plang\")\n\t}\n\tif inputNumber%7 == 0 {\n\t\tbuffer.WriteString(\"Plong\")\n\t}\n\tif buffer.Len() == 0 {\n\t\treturn fmt.Sprintf(\"%d\", inputNumber)\n\t}\n\treturn buffer.String()\n\t// BenchmarkConvert-4 \t 1000000\t 1579 ns/op\n}", "func (b *Builder) P(text string) *Builder {\n\treturn b.writeln(text).nl()\n}", "func (k *Kyber) Encrypt(packedPK, msg, r []byte) []byte {\n\n\tif len(msg) < n/8 {\n\t\tprintln(\"Message is too short to be encrypted.\")\n\t\treturn nil\n\t}\n\n\tif len(packedPK) != k.SIZEPK() {\n\t\tprintln(\"Cannot encrypt with this public key.\")\n\t\treturn nil\n\t}\n\n\tif len(r) != SEEDBYTES {\n\t\tr = make([]byte, SEEDBYTES)\n\t\trand.Read(r[:])\n\t}\n\n\tK := k.params.K\n\tpk := k.UnpackPK(packedPK)\n\tAhat := expandSeed(pk.Rho[:], true, K)\n\n\tsp := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tsp[i] = polyGetNoise(k.params.ETA1, r[:], byte(i))\n\t\tsp[i].ntt()\n\t\tsp[i].reduce()\n\t}\n\tep := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tep[i] = polyGetNoise(eta2, r[:], byte(i+K))\n\t\tep[i].ntt()\n\t}\n\tepp := polyGetNoise(eta2, r[:], byte(2*K))\n\tepp.ntt()\n\n\tu := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tu[i] = vecPointWise(Ahat[i], sp, K)\n\t\tu[i].toMont()\n\t\tu[i] = add(u[i], ep[i])\n\t\tu[i].invntt()\n\t\tu[i].reduce()\n\t\tu[i].fromMont()\n\t}\n\n\tm := polyFromMsg(msg)\n\tm.ntt()\n\n\tv := vecPointWise(pk.T, sp, K)\n\tv.toMont()\n\tv = add(v, epp)\n\tv = add(v, m)\n\tv.invntt()\n\tv.reduce()\n\tv.fromMont()\n\n\tc := make([]byte, k.params.SIZEC)\n\tcopy(c[:], u.compress(k.params.DU, K))\n\tcopy(c[K*k.params.DU*n/8:], v.compress(k.params.DV))\n\treturn c[:]\n}", "func (p FracProfile) KmerProbability(kmer DNA8) float64 {\n\tpr := 1.\n\tfor i, b := range kmer {\n\t\tpr *= p[i][b>>1&3]\n\t}\n\treturn pr\n}", "func ImportPk(k []byte) string {\n\terr := ioutil.WriteFile(tmpfile, k, 0644)\n\tlog.Check(log.WarnLevel, \"Writing Pubkey to temp file\", err)\n\n\tcommand := exec.Command(\"gpg\", \"--import\", tmpfile)\n\tout, err := command.CombinedOutput()\n\tlog.Check(log.WarnLevel, \"Importing MH public key\", err)\n\n\tos.Remove(tmpfile)\n\treturn string(out)\n}", "func Convert(number int) string {\n\tvar output string\n\tif number%3 == 0 {\n\t\toutput += \"Pling\"\n\t}\n\tif number%5 == 0 {\n\t\toutput += \"Plang\"\n\t}\n\tif number%7 == 0 {\n\t\toutput += \"Plong\"\n\t}\n\n\tif output == \"\" {\n\t\treturn fmt.Sprint(number)\n\t}\n\treturn output\n}", "func (p *Pump) Pump(string) (phono.PumpFunc, error) {\n\treturn func() (phono.Buffer, error) {\n\t\tif p.decoder == nil {\n\t\t\treturn nil, errors.New(\"Source is not defined\")\n\t\t}\n\n\t\treadSamples, err := p.decoder.PCMBuffer(p.ib)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif readSamples == 0 {\n\t\t\treturn nil, phono.ErrEOP\n\t\t}\n\t\t// prune buffer to actual size\n\t\tp.ib.Data = p.ib.Data[:readSamples]\n\t\t// convert buffer to buffer\n\t\tb, err := AsSamples(p.ib)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn b, nil\n\t}, nil\n}", "func Convert(number int) string {\n\ttext := \"\"\n\tif number%3 == 0 {\n\t\ttext += \"Pling\"\n\t}\n\tif number%5 == 0 {\n\t\ttext += \"Plang\"\n\t}\n\tif number%7 == 0 {\n\t\ttext += \"Plong\"\n\t}\n\tif text == \"\" {\n\t\ttext = strconv.Itoa(number)\n\t}\n\treturn text\n}", "func Convert(n int) string {\n\tfinalString := \"\"\n\n\tif n%3 == 0 {\n\t\tfinalString += \"Pling\"\n\t}\n\tif n%5 == 0 {\n\t\tfinalString += \"Plang\"\n\t}\n\tif n%7 == 0 {\n\t\tfinalString += \"Plong\"\n\t}\n\tif finalString == \"\" {\n\t\tfinalString = strconv.Itoa(n)\n\t}\n\treturn finalString\n}", "func Convert(num int) (str string) {\n\tif num%3 == 0 {\n\t\tstr += \"Pling\"\n\t}\n\tif num%5 == 0 {\n\t\tstr += \"Plang\"\n\t}\n\tif num%7 == 0 {\n\t\tstr += \"Plong\"\n\t}\n\tif len(str) == 0 {\n\t\treturn strconv.Itoa(num)\n\t}\n\treturn str\n}", "func Convert(value int) string {\n\ttext := \"\"\n\tif value%3 == 0 {\n\t\ttext += \"Pling\"\n\t}\n\tif value%5 == 0 {\n\t\ttext += \"Plang\"\n\t}\n\tif value%7 == 0 {\n\t\ttext += \"Plong\"\n\t}\n\tif text == \"\" {\n\t\ttext = strconv.Itoa(value)\n\t}\n\treturn text\n}", "func (bbs BollingerBandsSeries) GetK(defaults ...float64) float64 {\n\tif bbs.K == 0 {\n\t\tif len(defaults) > 0 {\n\t\t\treturn defaults[0]\n\t\t}\n\t\treturn 2.0\n\t}\n\treturn bbs.K\n}", "func getPermutationOriginal(n int, k int) string {\n\tif n == 1 && k == 1 {\n\t\treturn strconv.Itoa(n)\n\t}\n\tsum := 1\n\tfor i := 1; i <= n-1; i++ {\n\t\tsum *= i\n\t}\n\n\tmul := k / sum\n\trem := k % sum\n\n\tstart := 1 + mul\n\tvar str []int\n\tfor i := 1; i <= n; i++ {\n\t\tif i == start {\n\t\t\tcontinue\n\t\t}\n\t\tstr = append(str, i)\n\t}\n\n\tvar res [][]int\n\thelper(str, 0, &res)\n\n\tvar tmp string\n\tfor _, v := range res[rem-1] {\n\t\ttmp += strconv.Itoa(v)\n\t}\n\treturn strconv.Itoa(start) + tmp\n}", "func Convert(number int) string {\n\tvar result string\n\tif number%3 == 0 {\n\t\tresult += \"Pling\"\n\t}\n\tif number%5 == 0 {\n\t\tresult += \"Plang\"\n\t}\n\tif number%7 == 0 {\n\t\tresult += \"Plong\"\n\t}\n\tif result == \"\" {\n\t\tresult = strconv.Itoa(number)\n\t}\n\treturn result\n}", "func PWprint(L *lua.LState) int {\n\ttext := L.ToString(1)\n\tx := L.ToInt(2)\n\ty := L.ToInt(3)\n\tcolor := L.ToInt(4)\n\n\tc := palette[color]\n\txx := x\n\tsx := x\n\tyy := y\n\n\tfor _, ch := range text {\n\t\tchar := font[string(ch)]\n\t\tfor i := 0; i < char.Height; i++ {\n\t\t \tbin := char.Data[i]\n\n\t\t\tfor _, pix := range bin {\n\t\t\t\tif string(pix) == \"1\" { setpixel(xx + sx, char.Y + yy, int(c[0]), int(c[1]), int(c[2])) }\n\t\t\t \txx += 1\n\t\t\t}\n\t\t\tyy += 1\n\t\t\txx = x\n\t\t}\n\t\tsx += char.Width\n\t\tyy = y\n\t}\n\n\treturn 1\n}", "func (k *Kyber) PKEKeyGen(seed []byte) ([]byte, []byte) {\n\tif seed == nil || len(seed) != SEEDBYTES {\n\t\tseed = make([]byte, SEEDBYTES)\n\t\trand.Read(seed)\n\t}\n\n\tK := k.params.K\n\tETA1 := k.params.ETA1\n\n\tvar rho, sseed [SEEDBYTES]byte\n\tstate := sha3.New512()\n\tstate.Write(seed)\n\thash := state.Sum(nil)\n\tcopy(rho[:], hash[:32])\n\tcopy(sseed[:], hash[32:])\n\n\tAhat := expandSeed(rho[:], false, K)\n\n\tshat := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tshat[i] = polyGetNoise(ETA1, sseed[:], byte(i))\n\t\tshat[i].ntt()\n\t\tshat[i].reduce()\n\t}\n\n\tehat := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tehat[i] = polyGetNoise(ETA1, sseed[:], byte(i+K))\n\t\tehat[i].ntt()\n\t}\n\n\tt := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tt[i] = vecPointWise(Ahat[i], shat, K)\n\t\tt[i].toMont()\n\t\tt[i] = add(t[i], ehat[i])\n\t\tt[i].reduce()\n\t}\n\n\treturn k.PackPK(&PublicKey{T: t, Rho: rho[:]}), k.PackPKESK(&PKEPrivateKey{S: shat})\n}", "func PWpchar(L *lua.LState) int {\n\tchar := L.ToString(1)\n\tx := L.ToInt(2)\n\ty := L.ToInt(3)\n\tcolor := L.ToInt(4)\n\n\tc := palette[color]\n\txx := x\n\tyy := y\n\n\tfor i := 0; i < 8; i++ {\n\t \tbin := font[char].Data[i]\n\t\tbinarr := strings.Split(bin, \"\")\n\n\t\tfor _, pix := range binarr {\n\t\t\tif pix == \"1\" { setpixel(xx, yy, int(c[0]), int(c[1]), int(c[2])) }\n\t\t \txx += 1\n\t\t}\n\t\tyy += 1\n\t\txx = x\n\t}\n\n\tL.Push(lua.LNumber(font[char].Width))\n\n\treturn 1\n}", "func (qs ControlQS) KpLt(v float64) ControlQS {\n\treturn qs.filter(`\"kp\" <`, v)\n}", "func Convert(number int) string {\n\train := \"\"\n\tif number%3 == 0 {\n\t\train += \"Pling\"\n\t}\n\tif number%5 == 0 {\n\t\train += \"Plang\"\n\t}\n\tif number%7 == 0 {\n\t\train += \"Plong\"\n\t}\n\tif rain == \"\" {\n\t\train = strconv.Itoa(number)\n\t}\n\treturn rain\n}", "func PublicKeyToSnk(pubKey crypto.PublicKey) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tswitch k := pubKey.(type) {\n\tcase *rsa.PublicKey:\n\t\tmodulus := bigIntToLE(k.N)\n\t\tif err := binary.Write(&buf, binary.LittleEndian, blobRsaPub{\n\t\t\tsnkHeader: snkHeader{\n\t\t\t\tPubAlgorithm: calgRsaSign,\n\t\t\t\tHashAlgorithm: calgSha1,\n\t\t\t\tBlobSize: uint32(20 + len(modulus)),\n\t\t\t\tKeyType: snkRsaPub,\n\t\t\t\tVersion: snkRsaVersion,\n\t\t\t\tPubAlgorithm2: calgRsaSign,\n\t\t\t},\n\t\t\tKeyMagic: bcryptRsaPubMagic,\n\t\t\tBitLength: uint32(8 * len(modulus)),\n\t\t\tPubExponent: uint32(k.E),\n\t\t}); err != nil {\n\t\t\treturn nil, nil\n\t\t}\n\t\tbuf.Write(modulus)\n\tcase *ecdsa.PublicKey:\n\t\t// TODO: This is a best guess based on piecing together various\n\t\t// Microsoft documentation and header values, but some pieces are still\n\t\t// missing. ECDSA isn't supported for strong name signing, and\n\t\t// calcuating the publicKeyToken for SN is the only reason this\n\t\t// function is even here.\n\t\tvar keyMagic uint32\n\t\tswitch k.Curve {\n\t\tcase elliptic.P256():\n\t\t\tkeyMagic = bcryptEcdsaPubP256\n\t\tcase elliptic.P384():\n\t\t\tkeyMagic = bcryptEcdsaPubP384\n\t\tcase elliptic.P521():\n\t\t\tkeyMagic = bcryptEcdsaPubP521\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"unsupported ECDSA curve\")\n\t\t}\n\t\t// TODO: are these supposed to be big-endian? the documentation for\n\t\t// BCRYPT_ECCKEY_BLOB says so, but it also said that about the RSA one\n\t\t// and yet the SNK format actually uses little endian...\n\t\tx := k.X.Bytes()\n\t\ty := k.Y.Bytes()\n\t\tif err := binary.Write(&buf, binary.LittleEndian, blobEcdsaPub{\n\t\t\tsnkHeader: snkHeader{\n\t\t\t\tPubAlgorithm: calgEcdsa,\n\t\t\t\tHashAlgorithm: calgSha1,\n\t\t\t\tBlobSize: uint32(12 + 2*len(x)),\n\t\t\t\tKeyType: snkRsaPub, // TODO\n\t\t\t\tVersion: snkRsaVersion, // TODO\n\t\t\t\tPubAlgorithm2: calgEcdsa,\n\t\t\t},\n\t\t\tKeyMagic: keyMagic,\n\t\t\tByteLength: uint32(len(x)),\n\t\t}); err != nil {\n\t\t\treturn nil, nil\n\t\t}\n\t\tbuf.Write(x)\n\t\tbuf.Write(y)\n\tdefault:\n\t\treturn nil, errors.New(\"unsupported key type for strong name signing\")\n\t}\n\treturn buf.Bytes(), nil\n}", "func (c *CPU6502) plp() uint8 {\n\tc.sp++\n\tc.status = c.read(0x0100 + uint16(c.sp))\n\tc.setFlag(flagU, true)\n\treturn 0\n}", "func pembagian(num1, num2 int) (int, error) {\n\tif num2 == 0 {\n\t\t// return 0, utils.DibagiNolError{utils.DIVIDED_BY_ZERO}\n\t\treturn 0, utils.DibagiNolError{}\n\t}\n\tresult := (num1 / num2)\n\treturn result, nil\n}", "func convertDictToProb(dictionary map[string][]TagFrequency) {\n\t// dictionary is a global variable\n\tvar total float32\n\tfor key := range dictionary {\n\t\ttotal = 0\n\t\tfor i := 0; i < len(dictionary[key]); i++ {\n\t\t\ttotal = total + dictionary[key][i].freq\n\t\t}\n\t\tfor i := 0; i < len(dictionary[key]); i++ {\n\t\t\tdictionary[key][i].freq = dictionary[key][i].freq / total\n\t\t}\n\t}\n}", "func Convert(input int) string {\n\tout := \"\"\n\n\t//check if this number is divisible by 3 (Pling)\n\tif input%3 == 0 {\n\t\tout = \"Pling\"\n\t}\n\n\t//check if the number is divisible by 5 (Plang)\n\tif input%5 == 0 {\n\t\tout = out + \"Plang\"\n\t}\n\n\t//check if the number is divisible by 7 (Plong)\n\tif input%7 == 0 {\n\t\tout = out + \"Plong\"\n\t}\n\n\t//if we go into this branch, we have no factors in {3,5,7}\n\tif len(out) == 0 {\n\t\treturn strconv.Itoa(input)\n\t}\n\n\treturn out\n}", "func (c *Canvas) ToPPM(writer io.Writer, goTemplate string) error {\n\tif writer == nil {\n\t\treturn errors.New(\"writer must not be nil\")\n\t}\n\n\tfuncMap := template.FuncMap{\n\t\t\"pixels\": writePPMPixels,\n\t}\n\n\ttmpl, err := template.New(ppmID).Funcs(funcMap).Parse(goTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = tmpl.Execute(writer, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Convert(number int) (result string) {\n\tif number%3 == 0 {\n\t\tresult += \"Pling\"\n\t}\n\n\tif number%5 == 0 {\n\t\tresult += \"Plang\"\n\t}\n\n\tif number%7 == 0 {\n\t\tresult += \"Plong\"\n\t}\n\n\tif len(result) == 0 {\n\t\tresult = strconv.Itoa(number)\n\t}\n\n\treturn\n}" ]
[ "0.89415634", "0.8818414", "0.87461317", "0.87275547", "0.86757314", "0.8171249", "0.7945646", "0.7921015", "0.7921015", "0.7836996", "0.78272784", "0.773706", "0.75550985", "0.6958648", "0.5670779", "0.55859274", "0.51602", "0.514136", "0.5107808", "0.50888765", "0.5077458", "0.5069617", "0.50449955", "0.5001693", "0.49290425", "0.4918963", "0.49183923", "0.49022347", "0.48874357", "0.4886102", "0.48622218", "0.48555273", "0.48508054", "0.48456204", "0.48454204", "0.48097348", "0.48072535", "0.48031816", "0.47554287", "0.47449404", "0.47118485", "0.47113544", "0.47060123", "0.46503", "0.4637922", "0.4633388", "0.46180528", "0.46134272", "0.46118855", "0.4603491", "0.45982373", "0.4582708", "0.45806327", "0.45606646", "0.455605", "0.45461985", "0.4544222", "0.45270255", "0.45241788", "0.45212546", "0.45210722", "0.45145813", "0.45104602", "0.4510009", "0.44976005", "0.4485766", "0.44842616", "0.44840124", "0.4479785", "0.44785595", "0.44785413", "0.4477279", "0.44747424", "0.44727424", "0.44708586", "0.44631946", "0.44590968", "0.44585878", "0.44503784", "0.44290504", "0.44217986", "0.44204056", "0.44024318", "0.43988353", "0.4395096", "0.43889138", "0.4388247", "0.43824077", "0.43813807", "0.4380999", "0.43743712", "0.437037", "0.43626332", "0.43443823", "0.43426058", "0.4342011", "0.43390137", "0.43360457", "0.4330489", "0.43295732" ]
0.87146086
4
PToK converts a Pound weight to Kilogram.
func PToK(p Pound) Kilogram { return Kilogram(p * 0.45359237) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PToK(p Pound) Kilogram {\n\treturn Kilogram(p / 2.205)\n}", "func PToK(p Pound) Kilogram { return Kilogram(p * OnePoundInKilograms) }", "func PToK(p Pounds) Kilograms { return Kilograms(p / conversion) }", "func PToK(p Pounds) Kilograms {\n\treturn Kilograms(p / 2.205)\n}", "func KToP(k Kilogram) Pound {\n\treturn Pound(k * 2.205)\n}", "func KToP(k Kilogram) Pound { return Pound(k / OnePoundInKilograms) }", "func KToP(k Kilogram) Pound { return Pound(k * 2.205) }", "func KToP(k Kilogram) Pound { return Pound(k / 0.45359237) }", "func KToP(k Kilograms) Pounds {\n\treturn Pounds(k * 2.205)\n}", "func KToP(k Kilograms) Pounds { return Pounds(k * conversion) }", "func PoundToKilos(p Pound) Kilogram { return Kilogram(p * 2.2) }", "func KiloToPounds(k Kilogram) Pound { return Pound(k / 2.2) }", "func KgToPound(kgs Kilogram) Pound {\n\treturn Pound(kgs * KgToLbRatio)\n}", "func FToK(f Fahrenheit) Kelvin {\n\treturn Kelvin((f + 459.67) * 5 / 9)\n}", "func LbsToKgs(lbs Pound) Kilogram {\n\treturn Kilogram(lbs * LbToKgRatio)\n}", "func FToK(f Fahrenheit) Kelvin {\n\tif f <= AbsoluteZeroF {\n\t\treturn AbsoluteZeroK\n\t}\n\treturn Kelvin((f - AbsoluteZeroF) * 5 / 9)\n}", "func CToK(c Celsius) Kelvin {\n\tif c <= AbsoluteZeroC {\n\t\treturn AbsoluteZeroK\n\t}\n\treturn Kelvin(c - AbsoluteZeroC)\n}", "func CToK(c Celsius) Kelvin {\n\treturn Kelvin(c - AbsoluteZeroC)\n}", "func CToK(c Celsius) Kelvin { return Kelvin(c + 273.15) }", "func CToK(c Celsius) Kelvin { return Kelvin(c - 273.15) }", "func FToK(f Fahrenheit) Kelvin { return Kelvin(((f - 32.0) * 5.0 / 9.0) + 273.15) }", "func (kg Kilogram) Weight() {\n\n}", "func (qs ControlQS) KpLe(v float64) ControlQS {\n\treturn qs.filter(`\"kp\" <=`, v)\n}", "func keypen(k int) (p float64) { return rowpen[row(k)] + fingerpen[finger(k)] }", "func (kh kelvinHandler) ToKelvin(temp float64) float64 {\n\treturn temp\n}", "func KToF(k Kelvin) Fahrenheit { return CToF(KToC(k)) }", "func k(x float64) float64 {\n\treturn math.Pow(3, 3*x-1)\n}", "func KToF(k Kelvin) Fahrenheit {\n\tif k <= AbsoluteZeroK {\n\t\treturn AbsoluteZeroF\n\t}\n\treturn Fahrenheit(k*9/5) + AbsoluteZeroF\n}", "func NumToKmer(x int, K int) string {\n y := make([]byte, K)\n for i:=K-1; i>=0; i-- {\n base := x%4\n switch base {\n case 0: y[i] = 'A'\n case 1: y[i] = 'C'\n case 2: y[i] = 'G'\n case 3: y[i] = 'T'\n }\n x = (x-base)>>2\n }\n return string(y)\n}", "func KtoF(k Kalvin) Fahrenheit {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// (t°K - 273.15) * 9/5 + 32\n\treturn Fahrenheit(round((float64(k)-273.15)*1.8+32, 100))\n}", "func possibleK(pair messagePair, pub *dsa.PublicKey) *big.Int {\n\tz1 := new(big.Int).SetBytes(pair.fst.sum)\n\tz2 := new(big.Int).SetBytes(pair.snd.sum)\n\n\tz1.Sub(z1, z2)\n\tz2.Sub(pair.fst.s, pair.snd.s)\n\tz2.ModInverse(z2, pub.Q)\n\tk := z1.Mul(z1, z2)\n\n\treturn k.Mod(k, pub.Q)\n}", "func KToF(k Kelvin) Fahrenheit {\n\treturn Fahrenheit(k*9/5 - 459.67)\n}", "func Kilos(n int64, decimals int, long bool) string {\n\tpadding := \" \"\n\tlevels := []string{\n\t\t\"\", \"k\", \"M\", \"G\", \"T\", \"P\", \"E\", /* \"Z\", \"Y\" will overflow int64 */\n\t}\n\tif long {\n\t\tlevels = []string{\n\t\t\t\"s\", \"kilo\", \"mega\", \"giga\", \"tera\", \"peta\", \"exa\",\n\t\t}\n\t}\n\n\treturn human(n, levels, 1000, decimals, padding)\n}", "func ConvertToPPK(privateKey *rsa.PrivateKey, pub []byte) ([]byte, error) {\n\t// https://the.earth.li/~sgtatham/putty/0.76/htmldoc/AppendixC.html#ppk\n\t// RSA keys are stored using an algorithm-name of 'ssh-rsa'. (Keys stored like this are also used by the updated RSA signature schemes that use\n\t// hashes other than SHA-1. The public key data has already provided the key modulus and the public encoding exponent. The private data stores:\n\t// mpint: the private decoding exponent of the key.\n\t// mpint: one prime factor p of the key.\n\t// mpint: the other prime factor q of the key. (RSA keys stored in this format are expected to have exactly two prime factors.)\n\t// mpint: the multiplicative inverse of q modulo p.\n\tppkPrivateKey := new(bytes.Buffer)\n\n\t// mpint: the private decoding exponent of the key.\n\t// this is known as 'D'\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(privateKey.D))\n\n\t// mpint: one prime factor p of the key.\n\t// this is known as 'P'\n\t// the RSA standard dictates that P > Q\n\t// for some reason what PuTTY names 'P' is Primes[1] to Go, and what PuTTY names 'Q' is Primes[0] to Go\n\tP, Q := privateKey.Primes[1], privateKey.Primes[0]\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(P))\n\n\t// mpint: the other prime factor q of the key. (RSA keys stored in this format are expected to have exactly two prime factors.)\n\t// this is known as 'Q'\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(Q))\n\n\t// mpint: the multiplicative inverse of q modulo p.\n\t// this is known as 'iqmp'\n\tiqmp := new(big.Int).ModInverse(Q, P)\n\tbinary.Write(ppkPrivateKey, binary.BigEndian, getRFC4251Mpint(iqmp))\n\n\t// now we need to base64-encode the PPK-formatted private key which is made up of the above values\n\tppkPrivateKeyBase64 := make([]byte, base64.StdEncoding.EncodedLen(ppkPrivateKey.Len()))\n\tbase64.StdEncoding.Encode(ppkPrivateKeyBase64, ppkPrivateKey.Bytes())\n\n\t// read Teleport public key\n\t// fortunately, this is the one thing that's in exactly the same format that the PPK file uses, so we can just copy it verbatim\n\t// remove ssh-rsa plus additional space from beginning of string if present\n\tif !bytes.HasPrefix(pub, []byte(constants.SSHRSAType+\" \")) {\n\t\treturn nil, trace.BadParameter(\"pub does not appear to be an ssh-rsa public key\")\n\t}\n\tpub = bytes.TrimSuffix(bytes.TrimPrefix(pub, []byte(constants.SSHRSAType+\" \")), []byte(\"\\n\"))\n\n\t// the PPK file contains an anti-tampering MAC which is made up of various values which appear in the file.\n\t// copied from Section C.3 of https://the.earth.li/~sgtatham/putty/0.76/htmldoc/AppendixC.html#ppk:\n\t// hex-mac-data is a hexadecimal-encoded value, 64 digits long (i.e. 32 bytes), generated using the HMAC-SHA-256 algorithm with the following binary data as input:\n\t// string: the algorithm-name header field.\n\t// string: the encryption-type header field.\n\t// string: the key-comment-string header field.\n\t// string: the binary public key data, as decoded from the base64 lines after the 'Public-Lines' header.\n\t// string: the plaintext of the binary private key data, as decoded from the base64 lines after the 'Private-Lines' header.\n\n\t// these values are also used in the MAC generation, so we declare them as variables\n\tkeyType := constants.SSHRSAType\n\tencryptionType := \"none\"\n\t// as work for the future, it'd be nice to get the proxy/user pair name in here to make the name more\n\t// of a unique identifier. this has to be done at generation time because the comment is part of the MAC\n\tfileComment := \"teleport-generated-ppk\"\n\n\t// string: the algorithm-name header field.\n\tmacKeyType := getRFC4251String([]byte(keyType))\n\t// create a buffer to hold the elements needed to generate the MAC\n\tmacInput := new(bytes.Buffer)\n\tbinary.Write(macInput, binary.LittleEndian, macKeyType)\n\n\t// string: the encryption-type header field.\n\tmacEncryptionType := getRFC4251String([]byte(encryptionType))\n\tbinary.Write(macInput, binary.BigEndian, macEncryptionType)\n\n\t// string: the key-comment-string header field.\n\tmacComment := getRFC4251String([]byte(fileComment))\n\tbinary.Write(macInput, binary.BigEndian, macComment)\n\n\t// base64-decode the Teleport public key, as we need its binary representation to generate the MAC\n\tdecoded := make([]byte, base64.StdEncoding.EncodedLen(len(pub)))\n\tn, err := base64.StdEncoding.Decode(decoded, pub)\n\tif err != nil {\n\t\treturn nil, trace.Errorf(\"could not base64-decode public key: %v, got %v bytes successfully\", err, n)\n\t}\n\tdecoded = decoded[:n]\n\t// append the decoded public key bytes to the MAC buffer\n\tmacPublicKeyData := getRFC4251String(decoded)\n\tbinary.Write(macInput, binary.BigEndian, macPublicKeyData)\n\n\t// append our PPK-formatted private key bytes to the MAC buffer\n\tmacPrivateKeyData := getRFC4251String(ppkPrivateKey.Bytes())\n\tbinary.Write(macInput, binary.BigEndian, macPrivateKeyData)\n\n\t// as per the PPK spec, the key for the MAC is blank when the PPK file is unencrypted.\n\t// therefore, the key is a zero-length byte slice.\n\thmacHash := hmac.New(sha256.New, []byte{})\n\t// generate the MAC using HMAC-SHA-256\n\thmacHash.Write(macInput.Bytes())\n\tmacString := hex.EncodeToString(hmacHash.Sum(nil))\n\n\t// build the string-formatted output PPK file\n\tppk := new(bytes.Buffer)\n\tfmt.Fprintf(ppk, \"PuTTY-User-Key-File-3: %v\\n\", keyType)\n\tfmt.Fprintf(ppk, \"Encryption: %v\\n\", encryptionType)\n\tfmt.Fprintf(ppk, \"Comment: %v\\n\", fileComment)\n\t// chunk the Teleport-formatted public key into 64-character length lines\n\tchunkedPublicKey := chunk(string(pub), 64)\n\tfmt.Fprintf(ppk, \"Public-Lines: %v\\n\", len(chunkedPublicKey))\n\tfor _, r := range chunkedPublicKey {\n\t\tfmt.Fprintf(ppk, \"%s\\n\", r)\n\t}\n\t// chunk the PPK-formatted private key into 64-character length lines\n\tchunkedPrivateKey := chunk(string(ppkPrivateKeyBase64), 64)\n\tfmt.Fprintf(ppk, \"Private-Lines: %v\\n\", len(chunkedPrivateKey))\n\tfor _, r := range chunkedPrivateKey {\n\t\tfmt.Fprintf(ppk, \"%s\\n\", r)\n\t}\n\tfmt.Fprintf(ppk, \"Private-MAC: %v\\n\", macString)\n\n\treturn ppk.Bytes(), nil\n}", "func TrezorP2WPKH() []int {\n\treturn []int{39, 40, 41, 42}\n}", "func (f *Font) Kern(left, right rune) float32 { return float32(f.kerner.Kern(left, right).Round()) }", "func KToF(k Kelvin) Fahrenheit { return Fahrenheit((k-273.15)*9.0/5.0 + 32.0) }", "func (qs ControlQS) KpEq(v float64) ControlQS {\n\treturn qs.filter(`\"kp\" =`, v)\n}", "func (bbs BollingerBandsSeries) GetK(defaults ...float64) float64 {\n\tif bbs.K == 0 {\n\t\tif len(defaults) > 0 {\n\t\t\treturn defaults[0]\n\t\t}\n\t\treturn 2.0\n\t}\n\treturn bbs.K\n}", "func packweight() int {\n\tk := c[GOLD] / 1000\n\tj := 25\n\tfor iven[j] == 0 && j > 0 {\n\t\tj--\n\t}\n\tfor i := 0; i <= j; i++ {\n\t\tswitch iven[i] {\n\t\tcase 0:\n\t\tcase OSSPLATE, OPLATEARMOR:\n\t\t\tk += 40\n\t\tcase OPLATE:\n\t\t\tk += 35\n\t\tcase OHAMMER:\n\t\t\tk += 30\n\t\tcase OSPLINT:\n\t\t\tk += 26\n\t\tcase OSWORDofSLASHING, OCHAIN, OBATTLEAXE, O2SWORD:\n\t\t\tk += 23\n\t\tcase OLONGSWORD, OSWORD, ORING, OFLAIL:\n\t\t\tk += 20\n\t\tcase OLANCE, OSTUDLEATHER:\n\t\t\tk += 15\n\t\tcase OLEATHER, OSPEAR:\n\t\t\tk += 8\n\t\tcase OORBOFDRAGON, OBELT:\n\t\t\tk += 4\n\t\tcase OSHIELD:\n\t\t\tk += 7\n\t\tcase OCHEST:\n\t\t\tk += 30 + ivenarg[i]\n\t\tdefault:\n\t\t\tk++\n\t\t}\n\t}\n\treturn k\n}", "func (comb *Combination) K() K {\n\treturn comb.k\n}", "func (qs ControlQS) KpLt(v float64) ControlQS {\n\treturn qs.filter(`\"kp\" <`, v)\n}", "func KUNPCKBW(k, k1, k2 operand.Op) { ctx.KUNPCKBW(k, k1, k2) }", "func (fnt *Font) Kern(r0, r1 rune) float64 {\n\treturn float64(fnt.face.Kern(r0, r1).Ceil())\n}", "func (this *activityGroupStruct) WeightKG() string {\n\tw := &this.weightKG\n\ts := w.String()\n\treturn s\n}", "func (sfnt *SFNT) Kerning(left, right uint16) int16 {\n\tif sfnt.Kern == nil {\n\t\treturn 0\n\t}\n\treturn sfnt.Kern.Get(left, right)\n}", "func penalty(b board) (p float64) {\n\tfor k := range pen {\n\t\tp += pen[k] * freq[b[k]]\n\t}\n\treturn\n}", "func kaprekarNumbers(p int32, q int32) {\n\t// Write your code here\n\tfound := false\n\tfor n := p; n <= q; n++ {\n\t\tsqr := int64(n) * int64(n)\n\t\tstr := strconv.FormatInt(sqr, 10)\n\t\tsum := int64(0)\n\t\td := int64(0)\n\t\tnCopy := n\n\t\tfor nCopy > 0 {\n\t\t\tnCopy /= 10\n\t\t\td++\n\t\t}\n\n\t\tleft, _ := strconv.Atoi(str[:len(str)-int(d)])\n\t\tright, err := strconv.Atoi(str[len(str)-int(d):])\n\n\t\tsum = int64(left) + int64(right)\n\n\t\tif right == 0 && err == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// fmt.Println(\"n\", n, \"sqr\", sqr, \"left\", left, \"right\", right, \"sum\", sum)\n\n\t\tif sum == int64(n) {\n\t\t\tif !found {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t\tfmt.Print(n)\n\t\t\tfmt.Print(\" \")\n\t\t}\n\t}\n\tif !found {\n\t\tfmt.Println(\"INVALID RANGE\")\n\t}\n}", "func (k *Kyber) PKEKeyGen(seed []byte) ([]byte, []byte) {\n\tif seed == nil || len(seed) != SEEDBYTES {\n\t\tseed = make([]byte, SEEDBYTES)\n\t\trand.Read(seed)\n\t}\n\n\tK := k.params.K\n\tETA1 := k.params.ETA1\n\n\tvar rho, sseed [SEEDBYTES]byte\n\tstate := sha3.New512()\n\tstate.Write(seed)\n\thash := state.Sum(nil)\n\tcopy(rho[:], hash[:32])\n\tcopy(sseed[:], hash[32:])\n\n\tAhat := expandSeed(rho[:], false, K)\n\n\tshat := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tshat[i] = polyGetNoise(ETA1, sseed[:], byte(i))\n\t\tshat[i].ntt()\n\t\tshat[i].reduce()\n\t}\n\n\tehat := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tehat[i] = polyGetNoise(ETA1, sseed[:], byte(i+K))\n\t\tehat[i].ntt()\n\t}\n\n\tt := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tt[i] = vecPointWise(Ahat[i], shat, K)\n\t\tt[i].toMont()\n\t\tt[i] = add(t[i], ehat[i])\n\t\tt[i].reduce()\n\t}\n\n\treturn k.PackPK(&PublicKey{T: t, Rho: rho[:]}), k.PackPKESK(&PKEPrivateKey{S: shat})\n}", "func QuarksToKin(amount int64) string {\n\tquarks := big.NewFloat(0)\n\tquarks.SetInt64(amount)\n\n\treturn new(big.Float).Quo(quarks, quarkCoeff).Text('f', 5)\n}", "func (bm VolumeBindingMode) ToK8s() *storv1.VolumeBindingMode {\n\tmode := bindingMode[bm]\n\treturn &mode\n}", "func KmToPrice(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tfmt.Println(params[\"devise\"]) // TODO handle several devise\n\tdistance, err := strconv.ParseFloat(params[\"km\"], 64)\n\tif err != nil {\n\t\tfmt.Println(\"bad parameters : \" + params[\"km\"])\n\t}\n\tfmt.Println(distance)\n\n\tprice := KmPriceRatio * distance\n\tres := &responseKmToPrice{\n\t\tDevise: params[\"devise\"],\n\t\tPrice: price,\n\t\tDistance: distance,\n\t}\n\n\terr = json.NewEncoder(w).Encode(res)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (qs ControlQS) KpNe(v float64) ControlQS {\n\treturn qs.filter(`\"kp\" <>`, v)\n}", "func toKB(n int64) int64 {\n\treturn int64(math.Floor((float64(n) / 1024) + 0.5))\n}", "func (qs ControlQS) KpGe(v float64) ControlQS {\n\treturn qs.filter(`\"kp\" >=`, v)\n}", "func (c Celcious) Kelvin() Kelvin {\n\treturn Kelvin(c + 273.15)\n}", "func Kmer2Num(sequence []byte, K int, i int) (int, int) {\n id := 0\n id_rc := 0\n for j:=i; j<K+i; j++ {\n switch sequence[j] {\n case 'A': id = id<<2\n case 'C': id = id<<2 + 1\n case 'G': id = id<<2 + 2\n case 'T': id = id<<2 + 3\n default:\n return -1, -1\n }\n switch sequence[K+i-1+i-j] {\n case 'T': id_rc = id_rc<<2\n case 'G': id_rc = id_rc<<2 + 1\n case 'C': id_rc = id_rc<<2 + 2\n case 'A': id_rc = id_rc<<2 + 3\n default:\n return -1, -1\n }\n }\n return id, id_rc\n}", "func (p FracProfile) KmerProbability(kmer DNA8) float64 {\n\tpr := 1.\n\tfor i, b := range kmer {\n\t\tpr *= p[i][b>>1&3]\n\t}\n\treturn pr\n}", "func KthDigit(n int, k int) int {\n n = n / int(math.Pow(10, float64(k - 1)))\n n = n % 10\n return int(math.Abs(float64(n)))\n}", "func KtoC(k Kalvin) Celsius {\n\tif k < AbsoluteZeroK {\n\t\tpanic(\"Your input cannot be below absolute zero.\")\n\t}\n\n\t// Conversation formula\n\t// t°K - 273.15\n\treturn Celsius(round(float64(k)-273.15, 100))\n}", "func (qs ControlQS) KpGt(v float64) ControlQS {\n\treturn qs.filter(`\"kp\" >`, v)\n}", "func KToC(k Kelvin) Celsius {\n\tif k <= AbsoluteZeroK {\n\t\treturn AbsoluteZeroC\n\t}\n\treturn Celsius(k) + AbsoluteZeroC\n}", "func main() {\n\tk := 3\n\ts := \"aabbaa\"\n\tres := kpalindromes.Kpalindromes(k, s)\n\tfmt.Println(res)\n}", "func ToKB(data uint64) uint64 {\n\treturn data / 1024\n}", "func KLDivKNN(samples []bmc.Sample, dist Distribution) float64 {\n\treturn 0.\n}", "func (pro Protocol) ToK8s() v1.Protocol {\n\tif r := pros[pro]; r != \"\" {\n\t\treturn r\n\t}\n\treturn v1.ProtocolTCP\n}", "func (ng NGram) Key() string {\n\t// n-grams always have at least 1 element, thus this should always work\n\tkey := ng[0]\n\tfor i := 1; i < len(ng); i++ {\n\t\tkey += \" \" + ng[i]\n\t}\n\treturn key\n}", "func LabelToKey(input string) string {\n\toutput := strings.Replace(input, \" \", \"_\", -1)\n\treturn strings.ToLower(output)\n}", "func (rt RouteTable) K() int {\n\treturn rt.dht.NumNodes()\n}", "func Compute_n_gsm(kmer int, pr float64, gsm map[string]int, length map[string]int) (map[string]int){\n n := make(map[string]int)\n \n for k := range gsm {\n temp := int(Round((pr*float64(gsm[k])), 0.5, 0))\n if (temp == 0){\n n[k] = 1\n }else{\n n[k] = int(math.Min(float64(temp), float64(gsm[k])))/2\n }\n //fmt.Println(k, n[k])\n }\n \n\n return n\n}", "func KToC(k Kelvin) Celsius {\n\treturn Celsius(k + Kelvin(AbsoluteZeroC))\n}", "func (t *topK) K() int {\n\treturn t.k\n}", "func numberLtKToWords(num int) string {\n if num < 20 {\n return LESS_THAN_20[num]\n }\n if num < 100 {\n if num % 10 != 0 {\n return TENS[num/10] + \" \" + LESS_THAN_20[num%10] \n } else {\n return TENS[num/10]\n }\n }\n if num%100 != 0 {\n return LESS_THAN_20[num/100] + \" Hundred \" + numberLtKToWords(num%100)\n } else {\n return LESS_THAN_20[num/100] + \" Hundred\"\n } \n}", "func (rb *RankEvalMetricRecallBuilder) K(k int) *RankEvalMetricRecallBuilder {\n\trb.v.K = &k\n\treturn rb\n}", "func New(T, C, K int) (*ph, error) {\n\tvar errList []string\n\tif !powerOf2(T) {\n\t\terrList = append(errList, fmt.Sprintf(\"T must be a power of 2, got: %d\", T))\n\t}\n\tif K >= T {\n\t\terrList = append(errList, \"K must be less than T\")\n\t}\n\tif !powerOf2(C) || C >= T {\n\t\terrList = append(errList, \"C must be a power of 2 and less than T\")\n\t}\n\tif len(errList) > 0 {\n\t\treturn nil, errors.New(strings.Join(errList, \"\\n\"))\n\t}\n\tlog2C := int(math.Log2(float64(C)))\n\tlog2T := int(math.Log2(float64(T)))\n\tpublicKeyLen := N * C\n\n\tp := &ph{\n\t\tt: T,\n\t\tc: C,\n\t\tk: K,\n\n\t\tlog2T: log2T,\n\t\tlog2C: log2C,\n\n\t\t_SKLEN: 2 * N,\n\t\tstreamLen: 8 * K,\n\t\tpublicKeyLen: publicKeyLen,\n\n\t\tekLen: N * T,\n\n\t\tsigLen: (K * N) + (K * (log2T - log2C) * N) + N,\n\t}\n\n\treturn p, nil\n}", "func (k *Kyber) Encrypt(packedPK, msg, r []byte) []byte {\n\n\tif len(msg) < n/8 {\n\t\tprintln(\"Message is too short to be encrypted.\")\n\t\treturn nil\n\t}\n\n\tif len(packedPK) != k.SIZEPK() {\n\t\tprintln(\"Cannot encrypt with this public key.\")\n\t\treturn nil\n\t}\n\n\tif len(r) != SEEDBYTES {\n\t\tr = make([]byte, SEEDBYTES)\n\t\trand.Read(r[:])\n\t}\n\n\tK := k.params.K\n\tpk := k.UnpackPK(packedPK)\n\tAhat := expandSeed(pk.Rho[:], true, K)\n\n\tsp := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tsp[i] = polyGetNoise(k.params.ETA1, r[:], byte(i))\n\t\tsp[i].ntt()\n\t\tsp[i].reduce()\n\t}\n\tep := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tep[i] = polyGetNoise(eta2, r[:], byte(i+K))\n\t\tep[i].ntt()\n\t}\n\tepp := polyGetNoise(eta2, r[:], byte(2*K))\n\tepp.ntt()\n\n\tu := make(Vec, K)\n\tfor i := 0; i < K; i++ {\n\t\tu[i] = vecPointWise(Ahat[i], sp, K)\n\t\tu[i].toMont()\n\t\tu[i] = add(u[i], ep[i])\n\t\tu[i].invntt()\n\t\tu[i].reduce()\n\t\tu[i].fromMont()\n\t}\n\n\tm := polyFromMsg(msg)\n\tm.ntt()\n\n\tv := vecPointWise(pk.T, sp, K)\n\tv.toMont()\n\tv = add(v, epp)\n\tv = add(v, m)\n\tv.invntt()\n\tv.reduce()\n\tv.fromMont()\n\n\tc := make([]byte, k.params.SIZEC)\n\tcopy(c[:], u.compress(k.params.DU, K))\n\tcopy(c[K*k.params.DU*n/8:], v.compress(k.params.DV))\n\treturn c[:]\n}", "func Kprobe(symbol string, prog *ebpf.Program) (Link, error) {\n\tk, err := kprobe(symbol, prog, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = k.attach(prog)\n\tif err != nil {\n\t\tk.Close()\n\t\treturn nil, err\n\t}\n\n\treturn k, nil\n}", "func NewKelvinConverter() Converter {\n\treturn &kelvinHandler{\n\t\tBase: Kelvin,\n\t}\n}", "func KToC(k Kelvin) Celsius { return Celsius(k + 273.15) }", "func (p Pound) Weight() {\n\n}", "func (qs ControlQS) KiLe(v float64) ControlQS {\n\treturn qs.filter(`\"ki\" <=`, v)\n}", "func obound_mid2key(mid uint16) string {\n\treturn fmt.Sprintf(\"%s%d\", _OBOUND_PREFIX, mid)\n}", "func Compute_n_glength(kmer int, pr float64, gsm map[string]int, length map[string]int) (map[string]int){\n n := make(map[string]int)\n \n for k := range gsm {\n temp := int(Round((pr*float64(length[k]))/float64(kmer), 0.5, 0))\n //temp := int(Round((pr*gsm[k]), 0.5, 0))\n if (temp == 0){\n n[k] = 1\n }else{\n n[k] = int(math.Min(float64(temp), float64(gsm[k])))/2\n }\n //fmt.Println(k, n[k])\n }\n \n\n return n\n}", "func calProb(N,K float64) float64{\r\n return Factorial(N)/(Factorial(N-K)*math.Pow(N,K))\r\n}", "func (o InitialStateConfigOutput) Pk() FileContentBufferPtrOutput {\n\treturn o.ApplyT(func(v InitialStateConfig) *FileContentBuffer { return v.Pk }).(FileContentBufferPtrOutput)\n}", "func KANDW(k, k1, k2 operand.Op) { ctx.KANDW(k, k1, k2) }", "func KToC(k Kelvin) Celsius { return Celsius(k - 273.15) }", "func KDF(purpose string, seed []byte) []byte {\n\th := sha256.New()\n\th.Write([]byte(purpose))\n\th.Write(seed)\n\treturn h.Sum(nil)\n\t//return pbkdf2.Key(password, nil, 1, 32, sha256.New)\n}", "func (c *Context) KUNPCKBW(k, k1, k2 operand.Op) {\n\tc.addinstruction(x86.KUNPCKBW(k, k1, k2))\n}", "func KinToQuarks(val string) (int64, error) {\n\tx, _, err := big.ParseFloat(val, 10, 64, big.ToZero)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tr, accuracy := new(big.Float).Mul(x, quarkCoeff).Int64()\n\tif accuracy != big.Exact {\n\t\treturn 0, errors.New(\"value cannot be represented with quarks\")\n\t}\n\n\treturn r, nil\n}", "func (c *CurveOperations) Pow2k(xP *ProjectivePoint, params *CurveCoefficientsEquiv, k uint32) {\n\tvar t0, t1 Fp2Element\n\tvar op = c.Params.Op\n\n\tx, z := &xP.X, &xP.Z\n\tfor i := uint32(0); i < k; i++ {\n\t\top.Sub(&t0, x, z) // t0 = Xp - Zp\n\t\top.Add(&t1, x, z) // t1 = Xp + Zp\n\t\top.Square(&t0, &t0) // t0 = t0 ^ 2\n\t\top.Square(&t1, &t1) // t1 = t1 ^ 2\n\t\top.Mul(z, &params.C, &t0) // Z2p = C24 * t0\n\t\top.Mul(x, z, &t1) // X2p = Z2p * t1\n\t\top.Sub(&t1, &t1, &t0) // t1 = t1 - t0\n\t\top.Mul(&t0, &params.A, &t1) // t0 = A24+ * t1\n\t\top.Add(z, z, &t0) // Z2p = Z2p + t0\n\t\top.Mul(z, z, &t1) // Zp = Z2p * t1\n\t}\n}", "func (w *Wallet) ToKey(address string) (keys.PublicKey, error) {\n\treturn keys.PublicKey{}, nil\n}", "func KLDivergence(p, q []float64) float64 {\n\tif len(p) != len(q) {\n\t\tlog.Fatalf(\"len(p) == %v, len(q) == %v\", len(p), len(q))\n\t}\n\tvar total float64\n\tfor i := 0; i < len(p); i++ {\n\t\tif p[i] > 0 {\n\t\t\ttotal += p[i] * math.Log(q[i]/p[i])\n\t\t}\n\t}\n\treturn -total\n}", "func (qs ControlQS) OrderByKp() ControlQS {\n\tqs.order = append(qs.order, `\"kp\"`)\n\n\treturn qs\n}", "func Solution(S string, K int) int {\n\t// write your code in Go 1.4\n\n\tN := len(S)\n\n\t// boundary case 1\n\tif K == 0 {\n\t\tret := 0\n\t\tfor i := 0; i < N; i++ {\n\t\t\tch := S[i]\n\t\t\tif ch == 'M' {\n\t\t\t\tret++\n\t\t\t}\n\t\t}\n\t\treturn ret\n\t}\n\n\tarr1 := make([]int, N)\n\n\tmaxl := 0\n\ttc := -1\n\tprevm := false\n\tfor i := 0; i < N; i++ {\n\t\tif S[i] == 'M' {\n\t\t\tif prevm {\n\t\t\t\ttc++\n\t\t\t} else {\n\t\t\t\ttc = 1\n\t\t\t}\n\t\t\tif tc > maxl {\n\t\t\t\tmaxl = tc\n\t\t\t}\n\t\t\tarr1[i] = tc\n\t\t\tprevm = true\n\n\t\t} else {\n\t\t\tarr1[i] = 0\n\t\t\tprevm = false\n\t\t}\n\n\t}\n\n\t// calculate M count, for K sliding window\n\tarr2 := make([]int, N)\n\tinit_sum := 0\n\tfor i := 0; i < K; i++ {\n\t\tif S[i] == 'M' {\n\t\t\tinit_sum++\n\t\t}\n\t\tarr2[i] = init_sum\n\t}\n\n\tfor i := K; i < N; i++ {\n\t\tarr2[i] = arr2[i-1]\n\t\tif S[i-K] == 'M' {\n\t\t\tarr2[i]--\n\t\t}\n\n\t\tif S[i] == 'M' {\n\t\t\tarr2[i]++\n\t\t}\n\t}\n\n\tfmt.Println(\"arr2: %v\\n\", arr2)\n\n\tif K == maxl {\n\t\treturn 0\n\t} else if K < maxl {\n\t\tret := 0\n\t\tfor i := 1; i < N; i++ {\n\t\t\tif arr1[i] == 0 && arr1[i-1] > 0 {\n\t\t\t\tif arr1[i-1] > K {\n\t\t\t\t\tret += arr1[i-1] / (K + 1)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif arr1[N-1] > K {\n\t\t\tret += arr1[N-1] / (K + 1)\n\t\t}\n\t\treturn ret\n\t} else {\n\n\t\tminret := N\n\n\t\tfor i := K - 1; i < N; i++ {\n\t\t\ttmpret := K - arr2[i]\n\t\t\tif i < N-1 && S[i+1] == 'M' {\n\t\t\t\ttmpret++\n\t\t\t}\n\n\t\t\tif i-K >= 0 && S[i-K] == 'M' {\n\t\t\t\ttmpret++\n\t\t\t}\n\n\t\t\tif tmpret < minret {\n\t\t\t\tminret = tmpret\n\t\t\t}\n\n\t\t}\n\t\treturn minret\n\t}\n\n\treturn N\n}", "func KToC(k Kelvin) Celsius {\n\treturn Celsius(k - 273.15)\n}", "func (g SimplePoint) Weight() int {\n\treturn 2 * 8\n}", "func CountPckt(metric_in, m1Prefix string) (metric_out string) {\n\tv := GetVersion(metric_in)\n\tif v == M20 {\n\t\tparts := strings.Split(metric_in, \".\")\n\t\tfor i, part := range parts {\n\t\t\tif strings.HasPrefix(part, \"unit=\") {\n\t\t\t\tparts[i] = \"unit=Pckt\"\n\t\t\t\tparts = append(parts, \"orig_unit=\"+part[5:])\n\t\t\t}\n\t\t\tif strings.HasPrefix(part, \"target_type=\") {\n\t\t\t\tparts[i] = \"target_type=count\"\n\t\t\t}\n\t\t}\n\t\tparts = append(parts, \"pckt_type=sent\")\n\t\tparts = append(parts, \"direction=in\")\n\t\tmetric_out = strings.Join(parts, \".\")\n\t} else if v == M20NoEquals {\n\t\tparts := strings.Split(metric_in, \".\")\n\t\tfor i, part := range parts {\n\t\t\tif strings.HasPrefix(part, \"unit_is_\") {\n\t\t\t\tparts[i] = \"unit_is_Pckt\"\n\t\t\t\tparts = append(parts, \"orig_unit_is_\"+part[8:])\n\t\t\t}\n\t\t\tif strings.HasPrefix(part, \"target_type_is_\") {\n\t\t\t\tparts[i] = \"target_type_is_count\"\n\t\t\t}\n\t\t}\n\t\tparts = append(parts, \"pckt_type_is_sent\")\n\t\tparts = append(parts, \"direction_is_in\")\n\t\tmetric_out = strings.Join(parts, \".\")\n\t} else {\n\t\tmetric_out = m1Prefix + metric_in + \".count\"\n\t}\n\treturn\n}", "func intermediateSymbols(k int) (int, int, int) {\n\t// X is the smallest positive integer such that X*(X-1) >= 2*K\n\tx := int(math.Floor(math.Sqrt(2 * float64(k))))\n\tif x < 1 {\n\t\tx = 1\n\t}\n\n\tfor (x * (x - 1)) < (2 * k) {\n\t\tx++\n\t}\n\n\t// S is the smallest prime such that S >= ceil(0.01*K) + X\n\ts := int(math.Ceil(0.01*float64(k))) + x\n\ts = smallestPrimeGreaterOrEqual(s)\n\n\t// H is the smallest integer such that choose(H, ceil(H/2)) >= K + S\n\t// choose(h, h/2) <= 4^(h/2), so begin with\n\t// h/2 ln(4) = ln K+S\n\t// h = ln(K+S)/ln(4)\n\th := int(math.Floor(math.Log(float64(s)+float64(k)) / math.Log(4)))\n\tfor centerBinomial(h) < k+s {\n\t\th++\n\t}\n\n\treturn k + s + h, s, h\n}" ]
[ "0.89727426", "0.8958424", "0.86161137", "0.85757494", "0.8084288", "0.8082232", "0.80411553", "0.80002993", "0.78352004", "0.7834906", "0.7710743", "0.7053544", "0.68725115", "0.611798", "0.6045883", "0.5957929", "0.5954145", "0.5945921", "0.5937484", "0.5887384", "0.5864581", "0.5551213", "0.5313566", "0.53041023", "0.5263585", "0.5164896", "0.5113615", "0.5092303", "0.5077946", "0.5071893", "0.5066041", "0.50240207", "0.49955449", "0.49796003", "0.4951257", "0.49047107", "0.48639092", "0.4845549", "0.48438627", "0.48418862", "0.48328003", "0.4820494", "0.48090687", "0.4801077", "0.47978115", "0.47765312", "0.47681302", "0.4754287", "0.4729001", "0.46954325", "0.46763614", "0.46673876", "0.46562994", "0.46543273", "0.46541142", "0.4641104", "0.46137217", "0.4588695", "0.45875314", "0.45838314", "0.4578508", "0.456409", "0.45583194", "0.45370007", "0.45321295", "0.4525674", "0.45159563", "0.44988033", "0.4495039", "0.44870883", "0.4477511", "0.4466329", "0.4447959", "0.44471896", "0.44401106", "0.4432285", "0.44266152", "0.44213977", "0.44180956", "0.44138736", "0.43946025", "0.4392151", "0.4386", "0.43851033", "0.4367926", "0.4359647", "0.4357658", "0.43554407", "0.43535742", "0.43459994", "0.43451905", "0.4344474", "0.43404043", "0.43359616", "0.43319768", "0.43289796", "0.43262973", "0.4326242", "0.43193197" ]
0.8949021
3
ensureNoOsFs makes a besteffort attempt to ensure you haven't used afero.OsFs directly in any of these backends; to do so would risk exposing you to RemoveAll against your `/` directory.
func ensureNoOsFs(name string, fs afero.Fs) error { if _, ok := fs.(*afero.OsFs); ok { return fmt.Errorf("gofakes3: invalid OsFs passed to %s,. s3afero backends assume they have control over the filesystem's root. use afero.NewBasePathFs() to avoid misery", name) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewOsFS() FS {\n\treturn afero.NewOsFs()\n}", "func forceUnmount(target string) (err error) {\n\t// Simple retry logic for unmount\n\tfor i := 0; i < 10; i++ {\n\t\tif err = sysUnmount(target, 0); err == nil {\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\treturn\n}", "func SetupOrNOOP() func() {\n\tif !IsTmpFriendDir(\"\") {\n\t\tcleanup, err := RootTempDir(\"\")\n\t\tif err == nil {\n\t\t\treturn cleanup\n\t\t}\n\t}\n\treturn func() {}\n}", "func cleanupFilesystem(helper *clients.TestClient, k8sh *utils.K8sHelper, s *suite.Suite, namespace string, filesystemName string) {\n\tlogger.Infof(\"Deleting file system\")\n\terr := helper.FSClient.Delete(filesystemName, namespace)\n\tassert.Nil(s.T(), err)\n\tlogger.Infof(\"File system %s deleted\", filesystemName)\n}", "func Fremovefs(name string) bool {\n\tif Fremovef(name) {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func cleanUmociMetadata(bundlePath string) error {\n\tents, err := ioutil.ReadDir(bundlePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, ent := range ents {\n\t\tif ent.Name() == \"rootfs\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tos.Remove(path.Join(bundlePath, ent.Name()))\n\t}\n\n\treturn nil\n}", "func NewOsFs() FS {\n\treturn &osFs{}\n}", "func (obj *ocsCephFilesystems) ensureDeleted(r *StorageClusterReconciler, sc *ocsv1.StorageCluster) (reconcile.Result, error) {\n\tfoundCephFilesystem := &cephv1.CephFilesystem{}\n\tcephFilesystems, err := r.newCephFilesystemInstances(sc)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tfor _, cephFilesystem := range cephFilesystems {\n\t\terr := r.Client.Get(context.TODO(), types.NamespacedName{Name: cephFilesystem.Name, Namespace: sc.Namespace}, foundCephFilesystem)\n\t\tif err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\tr.Log.Info(\"Uninstall: CephFileSystem not found.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tr.Log.Error(err, \"Uninstall: Unable to retrieve CephFileSystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\treturn reconcile.Result{}, fmt.Errorf(\"uninstall: Unable to retrieve CephFileSystem %v: %v\", cephFilesystem.Name, err)\n\t\t}\n\n\t\tif cephFilesystem.GetDeletionTimestamp().IsZero() {\n\t\t\tr.Log.Info(\"Uninstall: Deleting cephFilesystem.\", \"CephFileSystem\", klog.KRef(foundCephFilesystem.Namespace, foundCephFilesystem.Name))\n\t\t\terr = r.Client.Delete(context.TODO(), foundCephFilesystem)\n\t\t\tif err != nil {\n\t\t\t\tr.Log.Error(err, \"Uninstall: Failed to delete CephFileSystem.\", \"CephFileSystem\", klog.KRef(foundCephFilesystem.Namespace, foundCephFilesystem.Name))\n\t\t\t\treturn reconcile.Result{}, fmt.Errorf(\"uninstall: Failed to delete CephFileSystem %v: %v\", foundCephFilesystem.Name, err)\n\t\t\t}\n\t\t}\n\n\t\terr = r.Client.Get(context.TODO(), types.NamespacedName{Name: cephFilesystem.Name, Namespace: sc.Namespace}, foundCephFilesystem)\n\t\tif err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\tr.Log.Info(\"Uninstall: CephFilesystem is deleted.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tr.Log.Error(err, \"Uninstall: Waiting for CephFileSystem to be deleted.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\treturn reconcile.Result{}, fmt.Errorf(\"uninstall: Waiting for CephFileSystem %v to be deleted\", cephFilesystem.Name)\n\n\t}\n\treturn reconcile.Result{}, nil\n}", "func (mfs *MountedFS) DisableFsIDCheck() { mfs.checkFsID = false }", "func cleanupProviderFiles(path string, payloads []*v1alpha1.File) error {\n\tfor i := range payloads {\n\t\t// AtomicWriter only symlinks the top file or directory\n\t\tfirstComponent := strings.Split(payloads[i].GetPath(), string(os.PathSeparator))[0]\n\n\t\tp := filepath.Join(path, firstComponent)\n\t\tinfo, err := os.Lstat(p)\n\t\tif os.IsNotExist(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// skip symlinks\n\t\tif info.Mode()&os.ModeSymlink != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif err := os.RemoveAll(p); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (fs FilesystemStorage) Ensure() (err error) {\n\t_, err = os.Stat(fs.String())\n\tif os.IsNotExist(err) {\n\t\t// directory does not exist, create it\n\t\terr = os.Mkdir(fs.String(), 0755)\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"pkg\": \"fs-store\",\n\t\t\t\t\"filepath\": fs.String(),\n\t\t\t}).Error(\"failed to ensure directory\", err)\n\t\t\t// failed to create initial directory\n\t\t\treturn\n\t\t}\n\t}\n\n\t// ensure subdirectories\n\tfor _, subdir := range []string{\"att\", \"thm\", \"articles\", \"tmp\"} {\n\t\tfpath := filepath.Join(fs.String(), subdir)\n\t\t_, err = os.Stat(fpath)\n\t\tif os.IsNotExist(err) {\n\t\t\t// make subdirectory\n\t\t\terr = os.Mkdir(fpath, 0755)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"pkg\": \"fs-store\",\n\t\t\t\t\t\"filepath\": fpath,\n\t\t\t\t}).Error(\"failed to ensure sub-directory\", err)\n\t\t\t\t// failed to create subdirectory\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func mkfsOptions(fs string) []string {\n\tif fs == xfs && !kernel.CheckKernelVersion(3, 16, 0) {\n\t\t// For kernels earlier than 3.16 (and newer xfsutils),\n\t\t// some xfs features need to be explicitly disabled.\n\t\treturn []string{\"-m\", \"crc=0,finobt=0\"}\n\t}\n\n\treturn []string{}\n}", "func fixStdioPermissions(u *user.ExecUser) error {\n\tvar null syscall.Stat_t\n\tif err := syscall.Stat(\"/dev/null\", &null); err != nil {\n\t\treturn err\n\t}\n\tfor _, fd := range []uintptr{\n\t\tos.Stdin.Fd(),\n\t\tos.Stderr.Fd(),\n\t\tos.Stdout.Fd(),\n\t} {\n\t\tvar s syscall.Stat_t\n\t\tif err := syscall.Fstat(int(fd), &s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// skip chown of /dev/null if it was used as one of the STDIO fds.\n\t\tif s.Rdev == null.Rdev {\n\t\t\tcontinue\n\t\t}\n\t\tif err := syscall.Fchown(int(fd), u.Uid, u.Gid); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func deleteOdoDir(componentContext string) {\n\todoDir := filepath.Join(componentContext, \".odo\")\n\tif util.CheckPathExists(odoDir) {\n\t\t_ = dfutil.DeletePath(odoDir)\n\t}\n}", "func ensureOCIImages(vm *api.VM) error {\n\t// Check if a image with this name already exists, or import it\n\timage, err := operations.FindOrImportImage(c, vm.Spec.Image.OCI)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Populate relevant data from the Image on the VM object\n\tvm.SetImage(image)\n\n\t// Check if a kernel with this name already exists, or import it\n\tkernel, err := operations.FindOrImportKernel(c, vm.Spec.Kernel.OCI)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Populate relevant data from the Kernel on the VM object\n\tvm.SetKernel(kernel)\n\n\t// Save the file to disk. This will also write the file to /var/lib/firecracker for compatibility.\n\treturn c.VMs().Set(vm)\n}", "func cleanup() {\n\tos.Remove(dummyPath)\n}", "func OS(root string) FileSystem {\n\treturn osFS{root, vfs.OS(root)}\n}", "func MakeFsOnDisk() FileSystem { return filesys.MakeFsOnDisk() }", "func TestHealEmptyDirectoryErasure(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tnDisks := 16\n\tfsDirs, err := getRandomDisks(nDisks)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer removeRoots(fsDirs)\n\n\t// Everything is fine, should return nil\n\tobj, _, err := initObjectLayer(ctx, mustGetPoolEndpoints(fsDirs...))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbucket := \"bucket\"\n\tobject := \"empty-dir/\"\n\tvar opts ObjectOptions\n\n\terr = obj.MakeBucketWithLocation(ctx, bucket, BucketOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to make a bucket - %v\", err)\n\t}\n\n\t// Upload an empty directory\n\t_, err = obj.PutObject(ctx, bucket, object, mustGetPutObjReader(t,\n\t\tbytes.NewReader([]byte{}), 0, \"\", \"\"), opts)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Remove the object backend files from the first disk.\n\tz := obj.(*erasureServerPools)\n\ter := z.serverPools[0].sets[0]\n\tfirstDisk := er.getDisks()[0]\n\terr = firstDisk.DeleteVol(context.Background(), pathJoin(bucket, encodeDirObject(object)), true)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to delete a file - %v\", err)\n\t}\n\n\t// Heal the object\n\thr, err := obj.HealObject(ctx, bucket, object, \"\", madmin.HealOpts{ScanMode: madmin.HealNormalScan})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to heal object - %v\", err)\n\t}\n\n\t// Check if the empty directory is restored in the first disk\n\t_, err = firstDisk.StatVol(context.Background(), pathJoin(bucket, encodeDirObject(object)))\n\tif err != nil {\n\t\tt.Fatalf(\"Expected object to be present but stat failed - %v\", err)\n\t}\n\n\t// Check the state of the object in the first disk (should be missing)\n\tif hr.Before.Drives[0].State != madmin.DriveStateMissing {\n\t\tt.Fatalf(\"Unexpected drive state: %v\", hr.Before.Drives[0].State)\n\t}\n\n\t// Check the state of all other disks (should be ok)\n\tfor i, h := range append(hr.Before.Drives[1:], hr.After.Drives...) {\n\t\tif h.State != madmin.DriveStateOk {\n\t\t\tt.Fatalf(\"Unexpected drive state (%d): %v\", i+1, h.State)\n\t\t}\n\t}\n\n\t// Heal the same object again\n\thr, err = obj.HealObject(ctx, bucket, object, \"\", madmin.HealOpts{ScanMode: madmin.HealNormalScan})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to heal object - %v\", err)\n\t}\n\n\t// Check that Before & After states are all okay\n\tfor i, h := range append(hr.Before.Drives, hr.After.Drives...) {\n\t\tif h.State != madmin.DriveStateOk {\n\t\t\tt.Fatalf(\"Unexpected drive state (%d): %v\", i+1, h.State)\n\t\t}\n\t}\n}", "func TestFSDeleteObject(t *testing.T) {\n\t// Prepare for tests\n\tdisk := filepath.Join(globalTestTmpDir, \"minio-\"+nextSuffix())\n\tdefer os.RemoveAll(disk)\n\n\tobj := initFSObjects(disk, t)\n\tfs := obj.(*FSObjects)\n\tbucketName := \"bucket\"\n\tobjectName := \"object\"\n\n\tobj.MakeBucketWithLocation(context.Background(), bucketName, \"\")\n\tobj.PutObject(context.Background(), bucketName, objectName, mustGetPutObjReader(t, bytes.NewReader([]byte(\"abcd\")), int64(len(\"abcd\")), \"\", \"\"), ObjectOptions{})\n\n\t// Test with invalid bucket name\n\tif err := fs.DeleteObject(context.Background(), \"fo\", objectName); !isSameType(err, BucketNameInvalid{}) {\n\t\tt.Fatal(\"Unexpected error: \", err)\n\t}\n\t// Test with bucket does not exist\n\tif err := fs.DeleteObject(context.Background(), \"foobucket\", \"fooobject\"); !isSameType(err, BucketNotFound{}) {\n\t\tt.Fatal(\"Unexpected error: \", err)\n\t}\n\t// Test with invalid object name\n\tif err := fs.DeleteObject(context.Background(), bucketName, \"\\\\\"); !isSameType(err, ObjectNameInvalid{}) {\n\t\tt.Fatal(\"Unexpected error: \", err)\n\t}\n\t// Test with object does not exist.\n\tif err := fs.DeleteObject(context.Background(), bucketName, \"foooobject\"); !isSameType(err, ObjectNotFound{}) {\n\t\tt.Fatal(\"Unexpected error: \", err)\n\t}\n\t// Test with valid condition\n\tif err := fs.DeleteObject(context.Background(), bucketName, objectName); err != nil {\n\t\tt.Fatal(\"Unexpected error: \", err)\n\t}\n\n\t// Delete object should err disk not found.\n\tos.RemoveAll(disk)\n\tif err := fs.DeleteObject(context.Background(), bucketName, objectName); err != nil {\n\t\tif !isSameType(err, BucketNotFound{}) {\n\t\t\tt.Fatal(\"Unexpected error: \", err)\n\t\t}\n\t}\n\n}", "func cleanupUpper(ctx context.Context, parent *Inode, name string) {\n\tif err := parent.InodeOperations.Remove(ctx, parent, name); err != nil {\n\t\t// Unfortunately we don't have much choice. We shouldn't\n\t\t// willingly give the caller access to a nonsense filesystem.\n\t\tpanic(fmt.Sprintf(\"overlay filesystem is in an inconsistent state: failed to remove %q from upper filesystem: %v\", name, err))\n\t}\n}", "func (fs *FakeFilesystem) Use() func() {\n\t// create the new fake fs root dir in /tmp/sriov...\n\ttmpDir, err := os.MkdirTemp(\"\", \"k8s-rdma-shared-dev-plugin-\")\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"error creating fake root dir: %s\", err.Error()))\n\t}\n\tfs.RootDir = tmpDir\n\n\tfor _, dir := range fs.Dirs {\n\t\tosErr := os.MkdirAll(path.Join(fs.RootDir, dir), 0700)\n\t\tif osErr != nil {\n\t\t\tpanic(fmt.Errorf(\"error creating fake directory: %s\", osErr.Error()))\n\t\t}\n\t}\n\tfor filename, body := range fs.Files {\n\t\tioErr := os.WriteFile(path.Join(fs.RootDir, filename), body, 0600)\n\t\tif ioErr != nil {\n\t\t\tpanic(fmt.Errorf(\"error creating fake file: %s\", ioErr.Error()))\n\t\t}\n\t}\n\tfor link, target := range fs.Symlinks {\n\t\tosErr := os.Symlink(target, path.Join(fs.RootDir, link))\n\t\tif osErr != nil {\n\t\t\tpanic(fmt.Errorf(\"error creating fake symlink: %s\", osErr.Error()))\n\t\t}\n\t}\n\terr = os.MkdirAll(path.Join(fs.RootDir, \"usr/share/hwdata\"), 0700)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"error creating fake directory: %s\", err.Error()))\n\t}\n\n\t// TODO: Remove writing pci.ids file once ghw is mocked\n\t// This is to fix the CI failure where ghw lib fails to\n\t// unzip pci.ids file downloaded from internet.\n\tpciData, err := os.ReadFile(\"/usr/share/hwdata/pci.ids\")\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"error reading file: %s\", err.Error()))\n\t}\n\terr = os.WriteFile(path.Join(fs.RootDir, \"usr/share/hwdata/pci.ids\"), pciData, 0600)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"error creating fake file: %s\", err.Error()))\n\t}\n\n\tsysNetDevices = path.Join(fs.RootDir, \"/sys/class/net\")\n\n\treturn func() {\n\t\t// remove temporary fake fs\n\t\terr := os.RemoveAll(fs.RootDir)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"error tearing down fake filesystem: %s\", err.Error()))\n\t\t}\n\t}\n}", "func (obj *ocsCephFilesystems) ensureCreated(r *StorageClusterReconciler, instance *ocsv1.StorageCluster) (reconcile.Result, error) {\n\treconcileStrategy := ReconcileStrategy(instance.Spec.ManagedResources.CephFilesystems.ReconcileStrategy)\n\tif reconcileStrategy == ReconcileStrategyIgnore {\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\tcephFilesystems, err := r.newCephFilesystemInstances(instance)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\tfor _, cephFilesystem := range cephFilesystems {\n\t\texisting := cephv1.CephFilesystem{}\n\t\terr = r.Client.Get(context.TODO(), types.NamespacedName{Name: cephFilesystem.Name, Namespace: cephFilesystem.Namespace}, &existing)\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\tif reconcileStrategy == ReconcileStrategyInit {\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\t}\n\t\t\tif existing.DeletionTimestamp != nil {\n\t\t\t\tr.Log.Info(\"Unable to restore CephFileSystem because it is marked for deletion.\", \"CephFileSystem\", klog.KRef(existing.Namespace, existing.Name))\n\t\t\t\treturn reconcile.Result{}, fmt.Errorf(\"failed to restore initialization object %s because it is marked for deletion\", existing.Name)\n\t\t\t}\n\n\t\t\tr.Log.Info(\"Restoring original CephFilesystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\texisting.ObjectMeta.OwnerReferences = cephFilesystem.ObjectMeta.OwnerReferences\n\t\t\texisting.Spec = cephFilesystem.Spec\n\t\t\terr = r.Client.Update(context.TODO(), &existing)\n\t\t\tif err != nil {\n\t\t\t\tr.Log.Error(err, \"Unable to update CephFileSystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\t\tcase errors.IsNotFound(err):\n\t\t\tr.Log.Info(\"Creating CephFileSystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\terr = r.Client.Create(context.TODO(), cephFilesystem)\n\t\t\tif err != nil {\n\t\t\t\tr.Log.Error(err, \"Unable to create CephFileSystem.\", \"CephFileSystem\", klog.KRef(cephFilesystem.Namespace, cephFilesystem.Name))\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn reconcile.Result{}, nil\n}", "func (d *Driver) Cleanup() error {\n\tlogrus.Debugf(\"Cleanup\")\n\terr := d.ioctl(UmountAll, \"\", \"\")\n\tif fd != 0 {\n\t\tsyscall.Close(fd)\n\t\tfd = 0\n\t}\n\treturn err\n}", "func NewOS() FS {\n\treturn &OS{}\n}", "func CleanEFS(client clientpkg.Client, logger logr.Logger) error {\n\n\tfileSystemToBeDeleted, err := ListEFS(client, logger)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to list EFS\")\n\t\treturn err\n\t}\n\terr = DeleteEFS(client, fileSystemToBeDeleted, logger)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to delete file systems\")\n\t\treturn err\n\t}\n\n\tlogger.Info(\"all EFS removed for this region\")\n\treturn nil\n}", "func TestFSys(t *testing.T) {\n\ta := startAcme(t)\n\tdefer a.Cleanup()\n\tfsys := a.fsys\n\n\tt.Run(\"Dirread\", func(t *testing.T) {\n\t\tt.SkipNow() // Only used for debugging?\n\t\tfid, err := fsys.Open(\"/\", 0) // Readonly\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to open/: %v\", err)\n\t\t}\n\n\t\tdirs, err := fid.Dirread()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to open/: %v\", err)\n\t\t}\n\t\tfor _, d := range dirs {\n\t\t\tt.Logf(\"%v\\n\", d.String())\n\t\t}\n\t\tfid.Close()\n\n\t\tfid, err = fsys.Open(\"/1\", plan9.OREAD)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to walk to /1: %v\", err)\n\t\t}\n\t\tdirs, err = fid.Dirread()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to open/: %v\", err)\n\t\t}\n\t\tfor _, d := range dirs {\n\t\t\tt.Logf(\"%v\\n\", d.String())\n\t\t}\n\t})\n\tt.Run(\"Basic\", func(t *testing.T) {\n\t\tfid, err := fsys.Open(\"/new/body\", plan9.OWRITE)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to open/: %v\", err)\n\t\t}\n\t\ttext := []byte(\"This is a test\\nof the emergency typing system\\n\")\n\t\tfid.Write(text)\n\t\tfid.Close()\n\n\t\tfid, err = fsys.Open(\"/2/body\", plan9.OREAD)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to open /2/body: %v\", err)\n\t\t}\n\t\tbuf := make([]byte, len(text))\n\t\t_, err = fid.ReadFull(buf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to read back body: %v\", err)\n\t\t}\n\t\tif string(buf) != string(text) {\n\t\t\tt.Errorf(\"Corrupted body readback: %v\", buf)\n\t\t}\n\t\tfid.Close()\n\n\t\tfid, err = fsys.Open(\"/2/addr\", plan9.OWRITE)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to open /2/addr: %v\", err)\n\t\t}\n\t\tfid.Write([]byte(\"#5\"))\n\t\tfid.Close()\n\n\t\t// test insertion\n\t\tfid, err = fsys.Open(\"/2/data\", plan9.OWRITE)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to open /2/data: %v\", err)\n\t\t}\n\t\tfid.Write([]byte(\"insertion\"))\n\t\tfid.Close()\n\n\t\tfid, err = fsys.Open(\"/2/body\", plan9.OREAD)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to open /2/body: %v\", err)\n\t\t}\n\t\ttext = append(text[0:5], append([]byte(\"insertion\"), text[5:]...)...)\n\t\tbuf = make([]byte, len(text))\n\t\t_, err = fid.ReadFull(buf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to read back body: %v\", err)\n\t\t}\n\t\tif string(buf) != string(text) {\n\t\t\tt.Errorf(\"Corrupted body readback: %v instead of %v\", string(buf), string(text))\n\t\t}\n\t\tfid.Close()\n\n\t\t// Delete the window\n\t\tfid, err = fsys.Open(\"/2/ctl\", plan9.OWRITE)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to open /2/ctl: %v\", err)\n\t\t}\n\t\tfid.Write([]byte(\"delete\"))\n\t\tfid.Close()\n\n\t\t// Make sure it's gone from the directory\n\t\tfid, err = fsys.Open(\"/1\", plan9.OREAD)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to walk to /1: %v\", err)\n\t\t}\n\t\tdirs, err := fid.Dirread()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to open/: %v\", err)\n\t\t}\n\t\tfor _, d := range dirs {\n\t\t\tif d.Name == \"2\" {\n\t\t\t\tt.Errorf(\"delete didn't remove /2\")\n\t\t\t}\n\t\t}\n\t\tfid.Close()\n\t})\n\tt.Run(\"BigBody\", func(t *testing.T) {\n\t\t// Create a large string with some non-latin characters so that\n\t\t// we exercise buffering and unicode encoding in xfidutfread\n\t\tvar b bytes.Buffer\n\t\tfor i := 0; i < BUFSIZE; i++ {\n\t\t\tb.WriteString(\"Go 世界\\n\")\n\t\t}\n\t\ttext := b.Bytes()\n\n\t\tw, err := acme.New()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Creating new window failed: %v\\n\", err)\n\t\t}\n\t\tdefer w.Del(true)\n\n\t\tw.Write(\"body\", text)\n\t\tbuf, err := w.ReadAll(\"body\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Reading body failed: %v\\n\", err)\n\t\t}\n\t\tif string(buf) != string(text) {\n\t\t\tt.Errorf(\"Read %v bytes from body; expected %v\\n\", len(buf), len(text))\n\t\t}\n\t})\n\tt.Run(\"CtlWrite\", func(t *testing.T) {\n\t\tw, err := acme.New()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Creating new window failed: %v\\n\", err)\n\t\t}\n\t\tdefer w.Del(true)\n\n\t\tfor _, tc := range []struct {\n\t\t\tname string\n\t\t\tok bool\n\t\t}{\n\t\t\t{\"/edwood/test1\", true},\n\t\t\t{\"/edwood/世界.txt\", true},\n\t\t\t{\"/edwood/name with space\", false},\n\t\t\t{\"/edwood/\\x00\\x00test2\", false},\n\t\t} {\n\t\t\terr := w.Name(tc.name)\n\t\t\tif !tc.ok {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"Writing window name %q returned nil error\\n\", tc.name)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Failed to write window name %q: %v\\n\", tc.name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tb, err := w.ReadAll(\"tag\")\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Failed to read tag: %v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttag := strings.SplitN(string(b), \" \", 2)\n\t\t\tif tc.name != tag[0] {\n\t\t\t\tt.Errorf(\"Window name is %q; expected %q\\n\", tag[0], tc.name)\n\t\t\t}\n\t\t}\n\n\t\tdump := \"Watch go test\"\n\t\tif err := w.Ctl(\"dump \" + dump); err != nil {\n\t\t\tt.Errorf(\"Failed to write dump %q: %v\\n\", dump, err)\n\t\t}\n\t\tdumpdir := \"/home/gopher/src/edwood\"\n\t\tif err := w.Ctl(\"dumpdir \" + dumpdir); err != nil {\n\t\t\tt.Errorf(\"Failed to write dumpdir %q: %v\\n\", dumpdir, err)\n\t\t}\n\t})\n}", "func ReuseAmbivalentFilesystem() types.Test {\n\tname := \"filesystem.reuse.ambivalent\"\n\tin := []types.Disk{\n\t\t{\n\t\t\tAlignment: types.DefaultAlignment,\n\t\t\tPartitions: types.Partitions{\n\t\t\t\t{\n\t\t\t\t\tNumber: 1,\n\t\t\t\t\tLabel: \"ROOT\",\n\t\t\t\t\tTypeCode: \"data\",\n\t\t\t\t\tLength: 131072,\n\t\t\t\t\tFilesystemType: \"ext4\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tNumber: 2,\n\t\t\t\t\tLabel: \"ZFS\",\n\t\t\t\t\tTypeCode: \"data\",\n\t\t\t\t\tLength: 131072,\n\t\t\t\t\tFilesystemType: \"image\",\n\t\t\t\t\tFilesystemImage: fixtures.Ext4ZFS,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tout := []types.Disk{\n\t\t{\n\t\t\tAlignment: types.DefaultAlignment,\n\t\t\tPartitions: types.Partitions{\n\t\t\t\t{\n\t\t\t\t\tNumber: 1,\n\t\t\t\t\tLabel: \"ROOT\",\n\t\t\t\t\tTypeCode: \"data\",\n\t\t\t\t\tLength: 131072,\n\t\t\t\t\tFilesystemType: \"ext4\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tNumber: 2,\n\t\t\t\t\tLabel: \"ZFS\",\n\t\t\t\t\tTypeCode: \"data\",\n\t\t\t\t\tLength: 131072,\n\t\t\t\t\tFilesystemType: \"ext4\",\n\t\t\t\t\tFilesystemUUID: \"f63bf118-f6d7-40a3-b64c-a92b05a7f9ee\",\n\t\t\t\t\tFilesystemLabel: \"some-label\",\n\t\t\t\t\tAmbivalent: true,\n\t\t\t\t\tFiles: []types.File{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tNode: types.Node{\n\t\t\t\t\t\t\t\tName: \"bar\",\n\t\t\t\t\t\t\t\tDirectory: \"foo\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tContents: \"example file\\n\",\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\tmntDevices := []types.MntDevice{\n\t\t{\n\t\t\tLabel: \"ZFS\",\n\t\t\tSubstitution: \"$DEVICE\",\n\t\t},\n\t}\n\tconfig := `{\n\t\t\"ignition\": {\"version\": \"$version\"},\n\t\t\"storage\": {\n\t\t\t\"filesystems\": [\n\t\t\t{\n\t\t\t\t\"path\": \"/tmp0\",\n\t\t\t\t\"device\": \"$DEVICE\",\n\t\t\t\t\"wipeFilesystem\": false,\n\t\t\t\t\"format\": \"ext4\",\n\t\t\t\t\"label\": \"some-label\",\n\t\t\t\t\"uuid\": \"f63bf118-f6d7-40a3-b64c-a92b05a7f9ee\"\n\t\t\t}]\n\t\t}\n\t}`\n\tconfigMinVersion := \"3.0.0\"\n\n\treturn types.Test{\n\t\tName: name,\n\t\tIn: in,\n\t\tOut: out,\n\t\tMntDevices: mntDevices,\n\t\tConfig: config,\n\t\tConfigMinVersion: configMinVersion,\n\t}\n}", "func MakeEmptyDirInMemory() FileSystem { return filesys.MakeEmptyDirInMemory() }", "func (p *Pod) cleanupFiles(silent bool) error {\n\tfor _, ns := range p.namespaces {\n\t\tglog.V(8).Infof(\"Removing binded namespace %s\", ns.Path)\n\t\terr := namespace.Remove(ns)\n\t\tif err != nil && !silent {\n\t\t\treturn fmt.Errorf(\"could not remove namespace: %v\", err)\n\t\t}\n\t}\n\tglog.V(8).Infof(\"Removing pod base directory %s\", p.baseDir)\n\terr := os.RemoveAll(p.baseDir)\n\tif err != nil && !silent {\n\t\treturn fmt.Errorf(\"could not cleanup pod: %v\", err)\n\t}\n\tglog.V(8).Infof(\"Removing pod log directory %s\", p.GetLogDirectory())\n\terr = os.RemoveAll(p.GetLogDirectory())\n\tif err != nil && !silent {\n\t\treturn fmt.Errorf(\"could not remove log directory: %v\", err)\n\t}\n\treturn nil\n}", "func unmountSquashFS(ctx context.Context, mountPath string, uo unmountOpts) error {\n\targs := []string{\n\t\t\"-u\",\n\t\tfilepath.Clean(mountPath),\n\t}\n\tcmd := exec.CommandContext(ctx, uo.fusermountPath, args...) //nolint:gosec\n\tcmd.Stdout = uo.stdout\n\tcmd.Stderr = uo.stderr\n\n\tif err := cmd.Run(); err != nil {\n\t\treturn fmt.Errorf(\"failed to unmount: %w\", err)\n\t}\n\n\treturn nil\n}", "func cleanup() {\n\tlog.Verbose(\"Cleaning up sensitive and temp files\")\n\tif _, err := os.Stat(\"ca.crt\"); err == nil {\n\t\tdeleteFile(\"ca.crt\")\n\t}\n\n\tif _, err := os.Stat(\"ca.key\"); err == nil {\n\t\tdeleteFile(\"ca.key\")\n\t}\n\n\tif _, err := os.Stat(\"client.crt\"); err == nil {\n\t\tdeleteFile(\"client.crt\")\n\t}\n\n\tif _, err := os.Stat(\"bearer.token\"); err == nil {\n\t\tdeleteFile(\"bearer.token\")\n\t}\n\n\tfor _, app := range s.Apps {\n\t\tif _, err := os.Stat(app.SecretsFile + \".dec\"); err == nil {\n\t\t\tdeleteFile(app.SecretsFile + \".dec\")\n\t\t}\n\t\tfor _, secret := range app.SecretsFiles {\n\t\t\tif _, err := os.Stat(secret + \".dec\"); err == nil {\n\t\t\t\tdeleteFile(secret + \".dec\")\n\t\t\t}\n\t\t}\n\t}\n\n}", "func TestConditionalFilePathOs(t *testing.T) {\n\tfSys := &afero.Afero{Fs: afero.NewMemMapFs()}\n\t//s := ConditionalFilePath2(fSys, \"off\")\n\t//assert.Equal(t, \"off\", s)\n\t//s = ConditionalFilePath2(fSys, \"none\")\n\t//assert.Equal(t, \"none\", s)\n\ts := fullFilePath2(fSys, \"/tatue/tata\")\n\tb := filepath.Base(s)\n\tassert.Equal(t, b, \"tata\")\n}", "func removeLegacyGoRepository(f *rule.File) {\n\tfor _, l := range f.Loads {\n\t\tif l.Name() == \"@io_bazel_rules_go//go:def.bzl\" {\n\t\t\tl.Remove(\"go_repository\")\n\t\t\tif l.IsEmpty() {\n\t\t\t\tl.Delete()\n\t\t\t}\n\t\t}\n\t}\n}", "func RecreateSafely(dirname string) error {\n\tvar err error\n\tfname := dirname + \"/.goeasyops-dir\"\n\tif FileExists(dirname) {\n\t\tif FileExists(fname) {\n\t\t\terr = os.RemoveAll(dirname)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"not recreating dir \\\"%s\\\", it exists already, but .goeasyops-dir does not.\", dirname)\n\t\t}\n\t}\n\tif FileExists(dirname) {\n\t\treturn fmt.Errorf(\"Attempt to delete dir \\\"%s\\\" failed\", dirname)\n\t}\n\terr = os.MkdirAll(dirname, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = WriteFile(fname, make([]byte, 0))\n\treturn err\n}", "func TestStatFs(t *testing.T) {\n\tts := NewTestCase(t)\n\tdefer ts.Cleanup()\n\n\tempty := syscall.Statfs_t{}\n\ts1 := empty\n\terr := syscall.Statfs(ts.orig, &s1)\n\tif err != nil {\n\t\tt.Fatal(\"statfs orig\", err)\n\t}\n\n\ts2 := syscall.Statfs_t{}\n\terr = syscall.Statfs(ts.mnt, &s2)\n\n\tif err != nil {\n\t\tt.Fatal(\"statfs mnt\", err)\n\t}\n\n\tclearStatfs(&s1)\n\tclearStatfs(&s2)\n\tif fmt.Sprintf(\"%v\", s2) != fmt.Sprintf(\"%v\", s1) {\n\t\tt.Error(\"Mismatch\", s1, s2)\n\t}\n}", "func (*FileSystemBase) Destroy() {\n}", "func filesystemFlags() uint16 {\n\tconst (\n\t\tnoI = 1 << iota // uncompressed metadata\n\t\tnoD // uncompressed data\n\t\t_\n\t\tnoF // uncompressed fragments\n\t\tnoFrag // never use fragments\n\t\talwaysFrag // always use fragments\n\t\tduplicateChecking // de-duplication\n\t\texportable // exportable via NFS\n\t\tnoX // uncompressed xattrs\n\t\tnoXattr // no xattrs\n\t\tcompopt // compressor-specific options present?\n\t)\n\t// TODO: is noXattr still accurate?\n\treturn noI | noF | noFrag | noX | noXattr\n}", "func (f *fixture) cleanUp(ctx context.Context, s *testing.FixtState) {\n\tif err := ash.CloseAllWindows(ctx, f.tconn); err != nil {\n\t\ts.Error(\"Failed trying to close all windows: \", err)\n\t}\n\n\tf.tconn = nil\n\n\tif len(f.drivefsOptions) > 0 && f.driveFs != nil {\n\t\tif err := f.driveFs.ClearCommandLineFlags(); err != nil {\n\t\t\ts.Fatal(\"Failed to remove command line args file: \", err)\n\t\t}\n\t}\n\tf.driveFs = nil\n\tf.mountPath = \"\"\n\n\t// Clean up files in this account that are older than 1 hour, files past this\n\t// date are assumed no longer required and were not successfully cleaned up.\n\t// Note this removal can take a while ~1s per file and may end up exceeding\n\t// the timeout, this is not a failure as the next run will try to remove the\n\t// files that weren't deleted in time.\n\tfileList, err := f.APIClient.ListAllFilesOlderThan(ctx, time.Hour)\n\tif err != nil {\n\t\ts.Error(\"Failed to list all my drive files: \", err)\n\t} else {\n\t\ts.Logf(\"Attempting to remove %d files older than 1 hour\", len(fileList.Files))\n\t\tfor _, i := range fileList.Files {\n\t\t\tif err := f.APIClient.RemoveFileByID(ctx, i.Id); err != nil {\n\t\t\t\ts.Logf(\"Failed to remove file %q (%s): %v\", i.Name, i.Id, err)\n\t\t\t} else {\n\t\t\t\ts.Logf(\"Successfully removed file %q (%s, %s)\", i.Name, i.Id, i.ModifiedTime)\n\t\t\t}\n\t\t}\n\t}\n\tf.APIClient = nil\n\tif f.cr != nil {\n\t\tif err := f.cr.Close(ctx); err != nil {\n\t\t\ts.Log(\"Failed closing chrome: \", err)\n\t\t}\n\t\tf.cr = nil\n\t}\n}", "func ForceUnmount(m Mount) error {\n\tpoint := m.MountPoint()\n\tlog.Infof(\"Force-Unmounting %s...\", point)\n\n\tvar cmd *exec.Cmd\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\tcmd = exec.Command(\"diskutil\", \"umount\", \"force\", point)\n\tcase \"linux\":\n\t\tcmd = exec.Command(\"fusermount\", \"-u\", point)\n\tdefault:\n\t\treturn fmt.Errorf(\"unmount: unimplemented\")\n\t}\n\n\terrc := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(errc)\n\n\t\t// try vanilla unmount first.\n\t\tif err := exec.Command(\"umount\", point).Run(); err == nil {\n\t\t\treturn\n\t\t}\n\n\t\t// retry to unmount with the fallback cmd\n\t\terrc <- cmd.Run()\n\t}()\n\n\tselect {\n\tcase <-time.After(2 * time.Second):\n\t\treturn fmt.Errorf(\"umount timeout\")\n\tcase err := <-errc:\n\t\treturn err\n\t}\n}", "func MustRegisterFS(namespace string, in fs.FS) {\n\tif err := RegisterFS(namespace, in); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (s *Store) Clean() error {\n\tsBackend, ok := s.backend.(*os.File)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unsupported cleaning backend\")\n\t}\n\n\ttmpBackend, err := ioutil.TempFile(os.TempDir(), \"cleanup_simplekv_*\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\ttmpStore := &Store{\n\t\tbackend: tmpBackend,\n\t}\n\n\t//Write initial header\n\tif err := tmpStore.updateHeader(); err != nil {\n\t\treturn err\n\t}\n\n\tcutoff := time.Now().Add(-5 * time.Minute).Unix()\n\n\tval := []byte{}\n\n\tfor _, rec := range s.recs {\n\t\tif rec.ts >= cutoff || rec.ts == 0 {\n\t\t\tval, _ = rec.value()\n\t\t\ttmpStore.addRecTxTs(rec.Key, val[:rec.valLen], rec.tx, rec.ts)\n\t\t}\n\t}\n\n\t//Close off\n\tif err := tmpStore.updateHeader(); err != nil {\n\t\treturn err\n\t}\n\ttmpStore.backend.Close()\n\n\t//swap backends\n\ts.backend.Close()\n\tfilename := sBackend.Name()\n\tos.Rename(filename, filename+\"_\")\n\n\tos.Rename(tmpBackend.Name(), filename)\n\tf, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, newStoreDefaultPerms)\n\tif err != nil {\n\t\tos.Rename(filename+\"_\", filename)\n\t\tbackF, _ := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, newStoreDefaultPerms)\n\t\ts.backend = backF\n\t}\n\n\ts.backend = f\n\ts.reread()\n\n\treturn os.Remove(filename + \"_\")\n}", "func removeSafely(pathToFile string) {\n\terr := os.Remove(pathToFile)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func SetupTestOSContext(t *testing.T) func() {\n\tc := SetupTestOSContextEx(t)\n\treturn func() { c.Cleanup(t) }\n}", "func SafeRMF(path string) error {\n\t// TODO: add safety checks\n\n\treturn os.RemoveAll(path)\n}", "func NewTestFsOrFail(t *testing.T) (*ObjStorFs, func()) {\n\ttmpDir, err := ioutil.TempDir(\"\", \"test\")\n\tcleanupFunc := func() { os.RemoveAll(tmpDir) }\n\tassert.Nil(t, err)\n\n\tfsBucket, err := fileblob.NewBucket(tmpDir)\n\tassert.Nil(t, err)\n\n\tfs, err := NewFs(WithBucket(fsBucket))\n\tassert.Nil(t, err)\n\n\treturn fs, cleanupFunc\n}", "func resolveFilesystems() []model.Filesystem {\n\tresult := []model.Filesystem{}\n\n\terr := readFile(mountTableFile, func(line string) error {\n\t\tfields := strings.Fields(line)\n\n\t\tdevName := fields[0]\n\t\tdirName := fields[1]\n\t\tsysTypeName := fields[2]\n\n\t\ttotal, free, available, err := getFilesystemUsage(dirName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tresult = append(result, model.Filesystem{\n\t\t\tFilesystem: devName,\n\t\t\tTypeName: sysTypeName,\n\t\t\tMountDir: dirName,\n\t\t\tTotal: total,\n\t\t\tFree: free,\n\t\t\tAvailable: available,\n\t\t})\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to resolve filesystems from %s, fallback to empty list. Error: %s\", mountTableFile, err)\n\t}\n\treturn result\n}", "func TestCleaner_CleanDeadSymlinks(t *testing.T) {\n\tcases := []struct {\n\t\tos *FakeOS\n\t\tdirpath string\n\t\texpectedError error\n\t}{\n\t\t{\n\t\t\t// cannot open dir\n\t\t\tos: &FakeOS{\n\t\t\t\tOpenError: errors.New(\"Cannot open dir\"),\n\t\t\t},\n\t\t\tdirpath: \"/some/path\",\n\t\t\texpectedError: errors.New(\"Cannot open dir\"),\n\t\t},\n\t\t{\n\t\t\t// dir stat returned error\n\t\t\tos: &FakeOS{\n\t\t\t\tOpenResult: &FakeFile{\n\t\t\t\t\tStatError: errors.New(\"Some error\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\tdirpath: \"/some/path\",\n\t\t\texpectedError: errors.New(\"Some error\"),\n\t\t},\n\t\t{\n\t\t\t// dir is not a dir\n\t\t\tos: &FakeOS{\n\t\t\t\tOpenResult: &FakeFile{\n\t\t\t\t\tStatResult: &FakeFileInfo{\n\t\t\t\t\t\tIsDirValue: false,\n\t\t\t\t\t},\n\t\t\t\t\tReaddirError: errors.New(\"Cannot read dir\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\tdirpath: \"/some/path\",\n\t\t\texpectedError: errors.New(\"Specified dirPath /some/path is not a directory\"),\n\t\t},\n\t\t{\n\t\t\t// dir readdir returned error\n\t\t\tos: &FakeOS{\n\t\t\t\tOpenResult: &FakeFile{\n\t\t\t\t\tStatResult: &FakeFileInfo{\n\t\t\t\t\t\tIsDirValue: true,\n\t\t\t\t\t},\n\t\t\t\t\tReaddirError: errors.New(\"Cannot read dir\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\tdirpath: \"/some/path\",\n\t\t\texpectedError: errors.New(\"Cannot read dir\"),\n\t\t},\n\t\t{\n\t\t\t// file is a dir\n\t\t\tos: &FakeOS{\n\t\t\t\tOpenResult: &FakeFile{\n\t\t\t\t\tStatResult: &FakeFileInfo{\n\t\t\t\t\t\tIsDirValue: true,\n\t\t\t\t\t},\n\t\t\t\t\tReaddirResult: []os.FileInfo{\n\t\t\t\t\t\t&FakeFileInfo{\n\t\t\t\t\t\t\tModeValue: os.ModeDir,\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\tdirpath: \"/some/path\",\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\t// file is a correct symlink\n\t\t\tos: &FakeOS{\n\t\t\t\tOpenResult: &FakeFile{\n\t\t\t\t\tStatResult: &FakeFileInfo{\n\t\t\t\t\t\tIsDirValue: true,\n\t\t\t\t\t},\n\t\t\t\t\tReaddirResult: []os.FileInfo{\n\t\t\t\t\t\t&FakeFileInfo{\n\t\t\t\t\t\t\tModeValue: os.ModeSymlink,\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\tdirpath: \"/some/path\",\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\t// file is a symlink, but error on stat\n\t\t\tos: &FakeOS{\n\t\t\t\tOpenResult: &FakeFile{\n\t\t\t\t\tStatResult: &FakeFileInfo{\n\t\t\t\t\t\tIsDirValue: true,\n\t\t\t\t\t},\n\t\t\t\t\tReaddirResult: []os.FileInfo{\n\t\t\t\t\t\t&FakeFileInfo{\n\t\t\t\t\t\t\tModeValue: os.ModeSymlink,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tStatError: os.ErrInvalid,\n\t\t\t},\n\t\t\tdirpath: \"/some/path\",\n\t\t\texpectedError: os.ErrInvalid,\n\t\t},\n\t\t{\n\t\t\t// file is a symlink, but error on removal\n\t\t\tos: &FakeOS{\n\t\t\t\tOpenResult: &FakeFile{\n\t\t\t\t\tStatResult: &FakeFileInfo{\n\t\t\t\t\t\tIsDirValue: true,\n\t\t\t\t\t},\n\t\t\t\t\tReaddirResult: []os.FileInfo{\n\t\t\t\t\t\t&FakeFileInfo{\n\t\t\t\t\t\t\tModeValue: os.ModeSymlink,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tStatError: os.ErrNotExist,\n\t\t\t\tRemoveError: os.ErrPermission,\n\t\t\t},\n\t\t\tdirpath: \"/some/path\",\n\t\t\texpectedError: os.ErrPermission,\n\t\t},\n\t\t{\n\t\t\t// file is a symlink, successfully removed\n\t\t\tos: &FakeOS{\n\t\t\t\tOpenResult: &FakeFile{\n\t\t\t\t\tStatResult: &FakeFileInfo{\n\t\t\t\t\t\tIsDirValue: true,\n\t\t\t\t\t},\n\t\t\t\t\tReaddirResult: []os.FileInfo{\n\t\t\t\t\t\t&FakeFileInfo{\n\t\t\t\t\t\t\tModeValue: os.ModeSymlink,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tStatError: os.ErrNotExist,\n\t\t\t},\n\t\t\tdirpath: \"/some/path\",\n\t\t\texpectedError: nil,\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tcleaner := NewCleaner(&FakeOutputer{}, c.os)\n\n\t\t/*\n\t\t\t// the hack\n\t\t\thome, err := os.Open(os.ExpandEnv(\"$HOME\"))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(\"Cannot open $HOME\")\n\t\t\t}\n\t\t\tc.os.OpenResult = home\n\t\t*/\n\n\t\terr := cleaner.CleanDeadSymlinks(c.dirpath)\n\n\t\tif !reflect.DeepEqual(err, c.expectedError) {\n\t\t\tt.Errorf(\"Expected err to be %v but it was %v\\n\", c.expectedError, err)\n\t\t}\n\n\t}\n}", "func TestFSHealObjects(t *testing.T) {\n\tdisk := filepath.Join(globalTestTmpDir, \"minio-\"+nextSuffix())\n\tdefer os.RemoveAll(disk)\n\n\tobj := initFSObjects(disk, t)\n\terr := obj.HealObjects(context.Background(), \"bucket\", \"prefix\", nil)\n\tif err == nil || !isSameType(err, NotImplemented{}) {\n\t\tt.Fatalf(\"Heal Object should return NotImplemented error \")\n\t}\n}", "func (fs ReverseHttpFs) RemoveAll(p string) error {\n\treturn syscall.EPERM\n}", "func (fsys *FS) Destroy() {\n\tdefer fs.Trace(fsys.f, \"\")(\"\")\n}", "func Force(path string, force bool) RunFn {\n\tif path == \".\" || path == \"\" {\n\t\tpwd, _ := os.Getwd()\n\t\tpath = pwd\n\t}\n\treturn func(r *Runner) error {\n\t\t_, err := os.Stat(path)\n\t\tif err != nil {\n\t\t\t// path doesn't exist. move on.\n\t\t\treturn nil\n\t\t}\n\t\tif !force {\n\t\t\treturn errors.Errorf(\"path %s already exists\", path)\n\t\t}\n\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\treturn nil\n\t}\n}", "func TestFSShutdown(t *testing.T) {\n\tbucketName := \"testbucket\"\n\tobjectName := \"object\"\n\t// Create and return an fsObject with its path in the disk\n\tprepareTest := func() (*FSObjects, string) {\n\t\tdisk := filepath.Join(globalTestTmpDir, \"minio-\"+nextSuffix())\n\t\tobj := initFSObjects(disk, t)\n\t\tfs := obj.(*FSObjects)\n\n\t\tobjectContent := \"12345\"\n\t\tobj.MakeBucketWithLocation(context.Background(), bucketName, \"\")\n\t\tobj.PutObject(context.Background(), bucketName, objectName, mustGetPutObjReader(t, bytes.NewReader([]byte(objectContent)), int64(len(objectContent)), \"\", \"\"), ObjectOptions{})\n\t\treturn fs, disk\n\t}\n\n\t// Test Shutdown with regular conditions\n\tfs, disk := prepareTest()\n\tif err := fs.Shutdown(context.Background()); err != nil {\n\t\tt.Fatal(\"Cannot shutdown the FS object: \", err)\n\t}\n\tos.RemoveAll(disk)\n\n\t// Test Shutdown with faulty disk\n\tfs, disk = prepareTest()\n\tfs.DeleteObject(context.Background(), bucketName, objectName)\n\tos.RemoveAll(disk)\n\tif err := fs.Shutdown(context.Background()); err != nil {\n\t\tt.Fatal(\"Got unexpected fs shutdown error: \", err)\n\t}\n}", "func destroyKnative() {\n\n\t//Make command options for Knative Setup\n\tco := utils.NewCommandOptions()\n\n\t//Install Openshift Serveless and Knative Serving\n\tco.Commands = append(co.Commands, \"https://raw.githubusercontent.com/redhat-iot/iot-dev/master/yamls/knative/setup/knative-eventing.yaml\")\n\n\tco.Commands = append(co.Commands, \"https://raw.githubusercontent.com/redhat-iot/iot-dev/master/yamls/knative/setup/knative-serving.yaml\")\n\tIOStreams, _, out, _ := genericclioptions.NewTestIOStreams()\n\n\tco.SwitchContext(\"knative-eventing\")\n\n\tlog.Info(\"Remove Openshift Serverless Operator and Knative Serving\")\n\tfor commandNumber, command := range co.Commands {\n\t\tif commandNumber == 1 {\n\t\t\tco.SwitchContext(\"knative-serving\")\n\t\t}\n\t\tcmd := delete.NewCmdDelete(co.CurrentFactory, IOStreams)\n\t\tcmd.Flags().Set(\"filename\", command)\n\t\tcmd.Run(cmd, []string{})\n\t\tlog.Info(out.String())\n\t\tout.Reset()\n\t\t//Allow time for Operator to distribute to all namespaces\n\t}\n\n\t/*\n\n\t\tcurrentCSV, err := exec.Command(\"bash\", \"-c\", \"./oc get subscription serverless-operator -n openshift-operators -o jsonpath='{.status.currentCSV}'\").Output()\n\t\terr = exec.Command(\"./oc\", \"delete\", \"subscription\", \"serverless-operator\", \"-n\", \"openshift-operators\").Run()\n\t\tif err != nil {\n\t\t\t//Ignore Resource Not found error and continue, but still notify the user\n\t\t\tlog.Println(err)\n\t\t}\n\t\terr = exec.Command(\"./oc\", \"delete\", \"clusterserviceversion\", string(currentCSV), \"-n\", \"openshift-operators\").Run()\n\t\tif err != nil {\n\t\t\t//Igonore Resource Not found error and continue, but still notify the user\n\t\t\tlog.Println(err)\n\t\t}\n\t\tos.Remove(\"oc\")\n\t*/\n\n}", "func Use(s FSType) {\n\tswitch s {\n\tcase OsFS:\n\t\tfilesystem = osfs.NewOSFS(os.TempDir())\n\tcase MemoryFS:\n\t\t//TODO\n\t\tfilesystem = memory.NewMemory()\n\tdefault:\n\t\tpanic(\"unexpected FSType\")\n\t}\n}", "func CheckVolumeModeFilesystem(volumeSpec *volume.Spec) (bool, error) {\n\tvolumeMode, err := GetVolumeMode(volumeSpec)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tif volumeMode == v1.PersistentVolumeBlock {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}", "func TestReadOnlyThanosSetup(t *testing.T) {\n\tt.Skip(\"This is interactive test - it will run until you will kill it or curl 'finish' endpoint. Comment and run as normal test to use it!\")\n\n\t// Create series of TSDB blocks. Cache them to 'data' dir so we don't need to re-create on every run.\n\t_, err := os.Stat(data)\n\tif os.IsNotExist(err) {\n\t\ttestutil.Ok(t, createData())\n\t} else {\n\t\ttestutil.Ok(t, err)\n\t\tfmt.Println(\"Skipping blocks generation, found data directory.\")\n\t}\n\n\te, err := e2e.NewDockerEnvironment(\"interactive\")\n\ttestutil.Ok(t, err)\n\tt.Cleanup(e.Close)\n\n\tm, err := e2emon.Start(e)\n\ttestutil.Ok(t, err)\n\n\t// Initialize object storage with two buckets (our long term storage).\n\t//\n\t//\t┌──────────────┐\n\t//\t│ │\n\t//\t│ Minio │\n\t//\t│ │\n\t//\t├──────────────┼──────────────────────────────────────────────────┐\n\t//\t│ Bucket: bkt1 │ {cluster=eu1, replica=0} 10k series [t-2w, t-1w] │\n\t//\t├──────────────┼──────────────────────────────────────────────────┘\n\t//\t│ │\n\t//\t├──────────────┼──────────────────────────────────────────────────┐\n\t//\t│ Bucket: bkt2 │ {cluster=us1, replica=0} 10k series [t-2w, t-1w] │\n\t//\t└──────────────┴──────────────────────────────────────────────────┘\n\t//\n\tm1 := e2edb.NewMinio(e, \"minio-1\", \"default\")\n\ttestutil.Ok(t, exec(\"cp\", \"-r\", store1Data+\"/.\", filepath.Join(m1.Dir(), \"bkt1\")))\n\ttestutil.Ok(t, exec(\"cp\", \"-r\", store2Data+\"/.\", filepath.Join(m1.Dir(), \"bkt2\")))\n\n\t// Setup Jaeger.\n\tj := e.Runnable(\"tracing\").WithPorts(map[string]int{\"http-front\": 16686, \"jaeger.thrift\": 14268}).Init(e2e.StartOptions{Image: \"jaegertracing/all-in-one:1.25\"})\n\ttestutil.Ok(t, e2e.StartAndWaitReady(j))\n\n\tjaegerConfig, err := yaml.Marshal(tracingclient.TracingConfig{\n\t\tType: tracingclient.Jaeger,\n\t\tConfig: jaeger.Config{\n\t\t\tServiceName: \"thanos\",\n\t\t\tSamplerType: \"const\",\n\t\t\tSamplerParam: 1,\n\t\t\tEndpoint: \"http://\" + j.InternalEndpoint(\"jaeger.thrift\") + \"/api/traces\",\n\t\t},\n\t})\n\ttestutil.Ok(t, err)\n\n\t// Create two store gateways, one for each bucket (access point to long term storage).\n\t//\t ┌───────────┐\n\t//\t │ │\n\t//\t┌──────────────┐ │ Store 1 │\n\t//\t│ Bucket: bkt1 │◄───┤ │\n\t//\t├──────────────┼ └───────────┘\n\t//\t│ │\n\t//\t├──────────────┼ ┌───────────┐\n\t//\t│ Bucket: bkt2 │◄───┤ │\n\t//\t└──────────────┴ │ Store 2 │\n\t//\t │ │\n\t//\t └───────────┘\n\tbkt1Config, err := yaml.Marshal(client.BucketConfig{\n\t\tType: client.S3,\n\t\tConfig: s3.Config{\n\t\t\tBucket: \"bkt1\",\n\t\t\tAccessKey: e2edb.MinioAccessKey,\n\t\t\tSecretKey: e2edb.MinioSecretKey,\n\t\t\tEndpoint: m1.InternalEndpoint(\"http\"),\n\t\t\tInsecure: true,\n\t\t},\n\t})\n\ttestutil.Ok(t, err)\n\tstore1 := e2edb.NewThanosStore(\n\t\te,\n\t\t\"store1\",\n\t\tbkt1Config,\n\t\te2edb.WithImage(\"thanos:latest\"),\n\t\te2edb.WithFlagOverride(map[string]string{\n\t\t\t\"--tracing.config\": string(jaegerConfig),\n\t\t\t\"--consistency-delay\": \"0s\",\n\t\t}),\n\t)\n\n\tbkt2Config, err := yaml.Marshal(client.BucketConfig{\n\t\tType: client.S3,\n\t\tConfig: s3.Config{\n\t\t\tBucket: \"bkt2\",\n\t\t\tAccessKey: e2edb.MinioAccessKey,\n\t\t\tSecretKey: e2edb.MinioSecretKey,\n\t\t\tEndpoint: m1.InternalEndpoint(\"http\"),\n\t\t\tInsecure: true,\n\t\t},\n\t})\n\ttestutil.Ok(t, err)\n\n\tstore2 := e2edb.NewThanosStore(\n\t\te,\n\t\t\"store2\",\n\t\tbkt2Config,\n\t\te2edb.WithImage(\"thanos:latest\"),\n\t\te2edb.WithFlagOverride(map[string]string{\n\t\t\t\"--tracing.config\": string(jaegerConfig),\n\t\t\t\"--consistency-delay\": \"0s\",\n\t\t}),\n\t)\n\n\t// Create two Prometheus replicas in HA, and one separate one (short term storage + scraping).\n\t// Add a Thanos sidecar.\n\t//\n\t// ┌────────────┐\n\t// ┌───────────────────────────────────────────────┐ │ │\n\t// │ {cluster=eu1, replica=0} 10k series [t-1w, t] │◄───┤ Prom-ha0 │\n\t// └───────────────────────────────────────────────┘ │ │\n\t// ├────────────┤\n\t// │ Sidecar │\n\t// └────────────┘\n\t//\n\t// ┌────────────┐\n\t// ┌───────────────────────────────────────────────┐ │ │\n\t// │ {cluster=eu1, replica=1} 10k series [t-1w, t] │◄───┤ Prom-ha1 │\n\t// └───────────────────────────────────────────────┘ │ │\n\t// ├────────────┤\n\t// │ Sidecar │\n\t// └────────────┘\n\t//\n\t// ┌────────────┐\n\t// ┌───────────────────────────────────────────────┐ │ │\n\t// │ {cluster=us1, replica=0} 10k series [t-1w, t] │◄───┤ Prom 2 │\n\t// └───────────────────────────────────────────────┘ │ │\n\t// ├────────────┤\n\t// │ Sidecar │\n\t// └────────────┘\n\tpromHA0 := e2edb.NewPrometheus(e, \"prom-ha0\")\n\tpromHA1 := e2edb.NewPrometheus(e, \"prom-ha1\")\n\tprom2 := e2edb.NewPrometheus(e, \"prom2\")\n\n\tsidecarHA0 := e2edb.NewThanosSidecar(e, \"sidecar-prom-ha0\", promHA0, e2edb.WithImage(\"thanos:latest\"), e2edb.WithFlagOverride(map[string]string{\"--tracing.config\": string(jaegerConfig)}))\n\tsidecarHA1 := e2edb.NewThanosSidecar(e, \"sidecar-prom-ha1\", promHA1, e2edb.WithImage(\"thanos:latest\"), e2edb.WithFlagOverride(map[string]string{\"--tracing.config\": string(jaegerConfig)}))\n\tsidecar2 := e2edb.NewThanosSidecar(e, \"sidecar2\", prom2, e2edb.WithImage(\"thanos:latest\"))\n\n\treceive1 := e2ethanos.NewReceiveBuilder(e, \"receiver-1\").WithIngestionEnabled().Init()\n\n\ttestutil.Ok(t, exec(\"cp\", \"-r\", prom1Data+\"/.\", promHA0.Dir()))\n\ttestutil.Ok(t, exec(\"sh\", \"-c\", \"find \"+prom1Data+\"/ -maxdepth 1 -type d | tail -5 | xargs -I {} cp -r {} \"+promHA1.Dir())) // Copy only 5 blocks from 9 to mimic replica 1 with partial data set.\n\ttestutil.Ok(t, exec(\"cp\", \"-r\", prom2Data+\"/.\", prom2.Dir()))\n\n\ttestutil.Ok(t, promHA0.SetConfig(promconfig.Config{\n\t\tGlobalConfig: promconfig.GlobalConfig{\n\t\t\tExternalLabels: map[model.LabelName]model.LabelValue{\n\t\t\t\t\"cluster\": \"eu-1\",\n\t\t\t\t\"replica\": \"0\",\n\t\t\t},\n\t\t},\n\t}))\n\ttestutil.Ok(t, promHA1.SetConfig(promconfig.Config{\n\t\tGlobalConfig: promconfig.GlobalConfig{\n\t\t\tExternalLabels: map[model.LabelName]model.LabelValue{\n\t\t\t\t\"cluster\": \"eu-1\",\n\t\t\t\t\"replica\": \"1\",\n\t\t\t},\n\t\t},\n\t}))\n\ttestutil.Ok(t, prom2.SetConfig(promconfig.Config{\n\t\tGlobalConfig: promconfig.GlobalConfig{\n\t\t\tExternalLabels: map[model.LabelName]model.LabelValue{\n\t\t\t\t\"cluster\": \"us-1\",\n\t\t\t\t\"replica\": \"0\",\n\t\t\t},\n\t\t},\n\t}))\n\n\ttestutil.Ok(t, e2e.StartAndWaitReady(m1))\n\ttestutil.Ok(t, e2e.StartAndWaitReady(promHA0, promHA1, prom2, sidecarHA0, sidecarHA1, sidecar2, store1, store2, receive1))\n\n\t// Let's start query on top of all those 6 store APIs (global query engine).\n\t//\n\t// ┌──────────────┐\n\t// │ │\n\t// │ Minio │ ┌───────────┐\n\t// │ │ │ │\n\t// ├──────────────┼──────────────────────────────────────────────────┐ │ Store 1 │◄──────┐\n\t// │ Bucket: bkt1 │ {cluster=eu1, replica=0} 10k series [t-2w, t-1w] │◄───┤ │ │\n\t// ├──────────────┼──────────────────────────────────────────────────┘ └───────────┘ │\n\t// │ │ │\n\t// ├──────────────┼──────────────────────────────────────────────────┐ ┌───────────┐ │\n\t// │ Bucket: bkt2 │ {cluster=us1, replica=0} 10k series [t-2w, t-1w] │◄───┤ │ │\n\t// └──────────────┴──────────────────────────────────────────────────┘ │ Store 2 │◄──────┤\n\t// │ │ │\n\t// └───────────┘ │\n\t// │\n\t// │\n\t// │ ┌───────────────┐\n\t// ┌────────────┐ │ │ │\n\t// ┌───────────────────────────────────────────────┐ │ │ ├──────┤ Querier │◄────── PromQL\n\t// │ {cluster=eu1, replica=0} 10k series [t-1w, t] │◄───┤ Prom-ha0 │ │ │ │\n\t// └───────────────────────────────────────────────┘ │ │ │ └───────────────┘\n\t// ├────────────┤ │\n\t// │ Sidecar │◄─────┤\n\t// └────────────┘ │\n\t// │\n\t// ┌────────────┐ │\n\t// ┌───────────────────────────────────────────────┐ │ │ │\n\t// │ {cluster=eu1, replica=1} 10k series [t-1w, t] │◄───┤ Prom-ha1 │ │\n\t// └───────────────────────────────────────────────┘ │ │ │\n\t// ├────────────┤ │\n\t// │ Sidecar │◄─────┤\n\t// └────────────┘ │\n\t// │\n\t// ┌────────────┐ │\n\t// ┌───────────────────────────────────────────────┐ │ │ │\n\t// │ {cluster=us1, replica=0} 10k series [t-1w, t] │◄───┤ Prom 2 │ │\n\t// └───────────────────────────────────────────────┘ │ │ │\n\t// ├────────────┤ │\n\t// │ Sidecar │◄─────┘\n\t// └────────────┘\n\t//\n\tquery1 := e2edb.NewThanosQuerier(\n\t\te,\n\t\t\"query1\",\n\t\t[]string{\n\t\t\tstore1.InternalEndpoint(\"grpc\"),\n\t\t\tstore2.InternalEndpoint(\"grpc\"),\n\t\t\tsidecarHA0.InternalEndpoint(\"grpc\"),\n\t\t\tsidecarHA1.InternalEndpoint(\"grpc\"),\n\t\t\tsidecar2.InternalEndpoint(\"grpc\"),\n\t\t\treceive1.InternalEndpoint(\"grpc\"),\n\t\t},\n\t\te2edb.WithImage(\"thanos:latest\"),\n\t\te2edb.WithFlagOverride(map[string]string{\"--tracing.config\": string(jaegerConfig)}),\n\t)\n\ttestutil.Ok(t, e2e.StartAndWaitReady(query1))\n\n\t// Wait until we have 6 gRPC connections.\n\ttestutil.Ok(t, query1.WaitSumMetricsWithOptions(e2emon.Equals(6), []string{\"thanos_store_nodes_grpc_connections\"}, e2emon.WaitMissingMetrics()))\n\n\tconst path = \"graph?g0.expr=sum(continuous_app_metric0)%20by%20(cluster%2C%20replica)&g0.tab=0&g0.stacked=0&g0.range_input=2w&g0.max_source_resolution=0s&g0.deduplicate=0&g0.partial_response=0&g0.store_matches=%5B%5D&g0.end_input=2021-07-27%2000%3A00%3A00\"\n\ttestutil.Ok(t, e2einteractive.OpenInBrowser(fmt.Sprintf(\"http://%s/%s\", query1.Endpoint(\"http\"), path)))\n\ttestutil.Ok(t, e2einteractive.OpenInBrowser(fmt.Sprintf(\"http://%s/%s\", prom2.Endpoint(\"http\"), path)))\n\n\t// Tracing endpoint.\n\ttestutil.Ok(t, e2einteractive.OpenInBrowser(\"http://\"+j.Endpoint(\"http-front\")))\n\t// Monitoring Endpoint.\n\ttestutil.Ok(t, m.OpenUserInterfaceInBrowser())\n\ttestutil.Ok(t, e2einteractive.RunUntilEndpointHit())\n}", "func (f *Fs) CleanUp() error {\n\tdo := f.Fs.Features().CleanUp\n\tif do == nil {\n\t\treturn errors.New(\"can't CleanUp\")\n\t}\n\treturn do()\n}", "func setup(t *testing.T) {\n\terr := os.RemoveAll(storagePath)\n\trequire.NoError(t, err)\n}", "func SafeFilter(hdr *tar.Header) bool {\n\tif hdr.Typeflag == tar.TypeDir {\n\t\thdr.Mode = 0o770\n\t\treturn true\n\t}\n\tif hdr.Typeflag == tar.TypeReg {\n\t\thdr.Mode = 0o660\n\t\treturn true\n\t}\n\treturn false\n}", "func CheckOrMountFS(bpfRoot string) {\n\tmountOnce.Do(func() {\n\t\tif err := checkOrMountFS(bpfRoot); err != nil {\n\t\t\tlog.WithError(err).Fatal(\"Unable to mount BPF filesystem\")\n\t\t}\n\t})\n}", "func NewOsFileWriter() *OsFileWriter {\n\treturn &OsFileWriter{\n\t\tmake(map[string]bool, 0),\n\t}\n}", "func MakeFsInMemory() FileSystem { return filesys.MakeFsInMemory() }", "func CreateNativeZeroLengthFiles(info *metainfo.Info, dir string) (err error) {\n\tfor _, fi := range info.UpvertedFiles() {\n\t\tif fi.Length != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tname := filepath.Join(append([]string{dir, info.Name}, fi.Path...)...)\n\t\tos.MkdirAll(filepath.Dir(name), 0777)\n\t\tvar f io.Closer\n\t\tf, err = os.Create(name)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tf.Close()\n\t}\n\treturn\n}", "func cleanupNode(ctx context.Context, cs clientset.Interface) {\n\t// Per-node cleanup function\n\tcleanup := func(nodeName string) error {\n\t\tnode, err := cs.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\tupdate := false\n\t\tupdateStatus := false\n\t\t// Gather info about all NFD-managed node assets outside the default prefix\n\t\tnfdLabels := map[string]struct{}{}\n\t\tfor _, name := range strings.Split(node.Annotations[nfdv1alpha1.FeatureLabelsAnnotation], \",\") {\n\t\t\tif strings.Contains(name, \"/\") {\n\t\t\t\tnfdLabels[name] = struct{}{}\n\t\t\t}\n\t\t}\n\t\tnfdERs := map[string]struct{}{}\n\t\tfor _, name := range strings.Split(node.Annotations[nfdv1alpha1.ExtendedResourceAnnotation], \",\") {\n\t\t\tif strings.Contains(name, \"/\") {\n\t\t\t\tnfdERs[name] = struct{}{}\n\t\t\t}\n\t\t}\n\n\t\t// Remove labels\n\t\tfor key := range node.Labels {\n\t\t\t_, ok := nfdLabels[key]\n\t\t\tif ok || strings.HasPrefix(key, nfdv1alpha1.FeatureLabelNs) {\n\t\t\t\tdelete(node.Labels, key)\n\t\t\t\tupdate = true\n\t\t\t}\n\t\t}\n\n\t\t// Remove annotations\n\t\tfor key := range node.Annotations {\n\t\t\tif strings.HasPrefix(key, nfdv1alpha1.AnnotationNs) {\n\t\t\t\tdelete(node.Annotations, key)\n\t\t\t\tupdate = true\n\t\t\t}\n\t\t}\n\n\t\t// Remove taints\n\t\tfor _, taint := range node.Spec.Taints {\n\t\t\tif strings.HasPrefix(taint.Key, nfdv1alpha1.TaintNs) {\n\t\t\t\tnewTaints, removed := taintutils.DeleteTaint(node.Spec.Taints, &taint)\n\t\t\t\tif removed {\n\t\t\t\t\tnode.Spec.Taints = newTaints\n\t\t\t\t\tupdate = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Remove extended resources\n\t\tfor key := range node.Status.Capacity {\n\t\t\t// We check for FeatureLabelNs as -resource-labels can create ERs there\n\t\t\t_, ok := nfdERs[string(key)]\n\t\t\tif ok || strings.HasPrefix(string(key), nfdv1alpha1.FeatureLabelNs) {\n\t\t\t\tdelete(node.Status.Capacity, key)\n\t\t\t\tdelete(node.Status.Allocatable, key)\n\t\t\t\tupdateStatus = true\n\t\t\t}\n\t\t}\n\n\t\tif updateStatus {\n\t\t\tBy(\"Deleting NFD extended resources from node \" + nodeName)\n\t\t\tif _, err := cs.CoreV1().Nodes().UpdateStatus(ctx, node, metav1.UpdateOptions{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif update {\n\t\t\tBy(\"Deleting NFD labels, annotations and taints from node \" + node.Name)\n\t\t\tif _, err := cs.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Cleanup all nodes\n\tnodeList, err := cs.CoreV1().Nodes().List(ctx, metav1.ListOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\n\tfor _, n := range nodeList.Items {\n\t\tvar err error\n\t\tfor retry := 0; retry < 5; retry++ {\n\t\t\tif err = cleanup(n.Name); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t}\n\t\tExpect(err).NotTo(HaveOccurred())\n\t}\n}", "func testCmdUnmountFilesystem(t *testing.T) {\n\tt.Log(\"TODO\")\n}", "func RemoveAllExceptDataVolumes(services []string) {\n\n\tdataVolumesList := []string{}\n\n\tfor _, service := range services {\n\t\tdataVolumes := getYamlPathData(\".dataVolumes.\" + service)\n\t\tdataVolumesList = append(dataVolumesList, service+\": \"+dataVolumes)\n\t}\n\n\tLogDebug(\"All directories will be deleted except the following: \" +\n\t\tstrings.Join(dataVolumesList, \"|\") + \".\")\n\t//In case more base dirs get added in the future.\n\trootDirs := []string{INSTALL_ROOT}\n\tfor _, dir := range rootDirs {\n\t\t// Only remove all except data volumes if the base directories exist.\n\t\tif _, err := os.Stat(dir); err == nil {\n\t\t\tfor _, service := range services {\n\n\t\t\t\tbaseDir := dir + \"/\" + service\n\t\t\t\tsplitBaseDir := strings.Split(baseDir, \"/\")\n\t\t\t\tbaseDirOneUp := strings.Join(splitBaseDir[0:len(splitBaseDir)-1], \"/\")\n\t\t\t\tdataVolumes := getYamlPathData(\".dataVolumes.\" + service)\n\t\t\t\tif strings.ReplaceAll(strings.TrimSuffix(dataVolumes, \"\\n\"), \" \", \"\") != \"\" {\n\t\t\t\t\tsplitDataVolumes := strings.Split(dataVolumes, \",\")\n\t\t\t\t\tfor _, volume := range splitDataVolumes {\n\t\t\t\t\t\tvolume = strings.ReplaceAll(volume, \" \", \"\")\n\t\t\t\t\t\tvolume = baseDir + \"/\" + volume\n\t\t\t\t\t\tif _, err := os.Stat(volume); err == nil {\n\t\t\t\t\t\t\tif strings.Contains(volume, baseDir) {\n\t\t\t\t\t\t\t\tvolumeMoved := strings.ReplaceAll(volume, baseDir, baseDirOneUp)\n\t\t\t\t\t\t\t\tMoveFileGolang(volume, volumeMoved)\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\tos.RemoveAll(baseDir)\n\t\t\t\tos.MkdirAll(baseDir, os.ModePerm)\n\t\t\t\tif strings.ReplaceAll(strings.TrimSuffix(dataVolumes, \"\\n\"), \" \", \"\") != \"\" {\n\t\t\t\t\tsplitDataVolumes := strings.Split(dataVolumes, \",\")\n\t\t\t\t\tfor _, volume := range splitDataVolumes {\n\t\t\t\t\t\tvolume = strings.ReplaceAll(volume, \" \", \"\")\n\t\t\t\t\t\tvolume = baseDir + \"/\" + volume\n\t\t\t\t\t\tif strings.Contains(volume, baseDir) {\n\t\t\t\t\t\t\tvolumeMoved := strings.ReplaceAll(volume, baseDir, baseDirOneUp)\n\t\t\t\t\t\t\tif _, err := os.Stat(volumeMoved); err == nil {\n\t\t\t\t\t\t\t\tMoveFileGolang(volumeMoved, volume)\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}", "func (com Common) Uninstall() {\n\n\tservice0 := \"yb-platform\"\n\tservice1 := \"prometheus\"\n\tservice2 := \"postgres\"\n\tservices := []string{service0, service1, service2}\n\n\tif hasSudoAccess() {\n\n\t\tcommand := \"service\"\n\n\t\tfor index := range services {\n\t\t\tcommandCheck0 := \"bash\"\n\t\t\tsubCheck0 := SYSTEMCTL + \" list-unit-files --type service | grep -w \" + services[index]\n\t\t\targCheck0 := []string{\"-c\", subCheck0}\n\t\t\tout0, _ := ExecuteBashCommand(commandCheck0, argCheck0)\n\t\t\tif strings.TrimSuffix(string(out0), \"\\n\") != \"\" {\n\t\t\t\targStop := []string{services[index], \"stop\"}\n\t\t\t\tExecuteBashCommand(command, argStop)\n\t\t\t}\n\t\t}\n\t} else {\n\n\t\tfor index := range services {\n\t\t\tcommandCheck0 := \"bash\"\n\t\t\targCheck0 := []string{\"-c\", \"pgrep -f \" + services[index] + \" | head -1\"}\n\t\t\tout0, _ := ExecuteBashCommand(commandCheck0, argCheck0)\n\t\t\t// Need to stop the binary if it is running, can just do kill -9 PID (will work as the\n\t\t\t// process itself was started by a non-root user.)\n\t\t\tif strings.TrimSuffix(string(out0), \"\\n\") != \"\" {\n\t\t\t\tpid := strings.TrimSuffix(string(out0), \"\\n\")\n\t\t\t\targStop := []string{\"-c\", \"kill -9 \" + pid}\n\t\t\t\tExecuteBashCommand(commandCheck0, argStop)\n\t\t\t}\n\t\t}\n\t}\n\n\tRemoveAllExceptDataVolumes([]string{\"yb-platform\", \"prometheus\", \"postgres\"})\n\n\t// Removed the INSTALL_VERSION_DIR if it exists if we are not performing an upgrade\n\t// (since we would essentially perform a fresh install).\n\n\tos.RemoveAll(INSTALL_VERSION_DIR)\n\n\t// Remove the hidden marker file so that we are able to perform fresh installs of YBA,\n\t// with the retained data directories.\n\tos.RemoveAll(INSTALL_ROOT + \"/.installCompleted\")\n}", "func (f *Flock) ensureFhState() {\n\tif !f.l && !f.r && f.fh != nil {\n\t\tf.fh.Close()\n\t\tf.fh = nil\n\t}\n}", "func checkOrMountDefaultLocations() error {\n\t// Check whether /sys/fs/bpf has a BPFFS mount.\n\tmounted, bpffsInstance, err := mountinfo.IsMountFS(mountinfo.FilesystemTypeBPFFS, bpffsRoot)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If /sys/fs/bpf is not mounted at all, we should mount\n\t// BPFFS there.\n\tif !mounted {\n\t\tif err := mountFS(false); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif !bpffsInstance {\n\t\t// If /sys/fs/bpf has a mount but with some other filesystem\n\t\t// than BPFFS, it means that Cilium is running inside container\n\t\t// and /sys/fs/bpf is not mounted on host. We should mount BPFFS\n\t\t// in /run/cilium/bpffs automatically. This will allow operation\n\t\t// of Cilium but will result in unmounting of the filesystem\n\t\t// when the pod is restarted. This in turn will cause resources\n\t\t// such as the connection tracking table of the BPF programs to\n\t\t// be released which will cause all connections into local\n\t\t// containers to be dropped. User is going to be warned.\n\t\tlog.Warnf(\"BPF filesystem is going to be mounted automatically \"+\n\t\t\t\"in %s. However, it probably means that Cilium is running \"+\n\t\t\t\"inside container and BPFFS is not mounted on the host. \"+\n\t\t\t\"for more information, see: https://cilium.link/err-bpf-mount\",\n\t\t\tdefaults.BPFFSRootFallback,\n\t\t)\n\t\tsetBPFFSRoot(defaults.BPFFSRootFallback)\n\n\t\tcMounted, cBpffsInstance, err := mountinfo.IsMountFS(mountinfo.FilesystemTypeBPFFS, bpffsRoot)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !cMounted {\n\t\t\tif err := mountFS(false); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if !cBpffsInstance {\n\t\t\tlog.Fatalf(\"%s is mounted but has a different filesystem than BPFFS\", defaults.BPFFSRootFallback)\n\t\t}\n\t}\n\n\tlog.Infof(\"Detected mounted BPF filesystem at %s\", bpffsRoot)\n\n\treturn nil\n}", "func AppFullCleanup(instanceName string) {\n\tvar (\n\t\tpath, _ = os.Getwd()\n\t\tappDir = filepath.Join(path, fmt.Sprintf(\"storage/%s\", instanceName))\n\t)\n\tstoreCleanupChan := make(chan error)\n\tcontainerCleanupChan := make(chan error)\n\tgo func() {\n\t\tstoreCleanupChan <- StorageCleanup(appDir)\n\t}()\n\tgo func() {\n\t\tcontainerCleanupChan <- ContainerCleanup(instanceName)\n\t}()\n\t<-storeCleanupChan\n\t<-containerCleanupChan\n}", "func TestHealObjectErasure(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tnDisks := 16\n\tfsDirs, err := getRandomDisks(nDisks)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer removeRoots(fsDirs)\n\n\t// Everything is fine, should return nil\n\tobj, _, err := initObjectLayer(ctx, mustGetPoolEndpoints(fsDirs...))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbucket := \"bucket\"\n\tobject := \"object\"\n\tdata := bytes.Repeat([]byte(\"a\"), 5*1024*1024)\n\tvar opts ObjectOptions\n\n\terr = obj.MakeBucketWithLocation(ctx, bucket, BucketOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to make a bucket - %v\", err)\n\t}\n\n\t// Create an object with multiple parts uploaded in decreasing\n\t// part number.\n\tuploadID, err := obj.NewMultipartUpload(ctx, bucket, object, opts)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create a multipart upload - %v\", err)\n\t}\n\n\tvar uploadedParts []CompletePart\n\tfor _, partID := range []int{2, 1} {\n\t\tpInfo, err1 := obj.PutObjectPart(ctx, bucket, object, uploadID, partID, mustGetPutObjReader(t, bytes.NewReader(data), int64(len(data)), \"\", \"\"), opts)\n\t\tif err1 != nil {\n\t\t\tt.Fatalf(\"Failed to upload a part - %v\", err1)\n\t\t}\n\t\tuploadedParts = append(uploadedParts, CompletePart{\n\t\t\tPartNumber: pInfo.PartNumber,\n\t\t\tETag: pInfo.ETag,\n\t\t})\n\t}\n\n\t// Remove the object backend files from the first disk.\n\tz := obj.(*erasureServerPools)\n\ter := z.serverPools[0].sets[0]\n\tfirstDisk := er.getDisks()[0]\n\n\t_, err = obj.CompleteMultipartUpload(ctx, bucket, object, uploadID, uploadedParts, ObjectOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to complete multipart upload - %v\", err)\n\t}\n\n\terr = firstDisk.Delete(context.Background(), bucket, pathJoin(object, xlStorageFormatFile), false)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to delete a file - %v\", err)\n\t}\n\n\t_, err = obj.HealObject(ctx, bucket, object, \"\", madmin.HealOpts{ScanMode: madmin.HealNormalScan})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to heal object - %v\", err)\n\t}\n\n\tif err = firstDisk.CheckFile(context.Background(), bucket, object); err != nil {\n\t\tt.Errorf(\"Expected er.meta file to be present but stat failed - %v\", err)\n\t}\n\n\terasureDisks := er.getDisks()\n\tz.serverPools[0].erasureDisksMu.Lock()\n\ter.getDisks = func() []StorageAPI {\n\t\t// Nil more than half the disks, to remove write quorum.\n\t\tfor i := 0; i <= len(erasureDisks)/2; i++ {\n\t\t\terasureDisks[i] = nil\n\t\t}\n\t\treturn erasureDisks\n\t}\n\tz.serverPools[0].erasureDisksMu.Unlock()\n\n\t// Try healing now, expect to receive errDiskNotFound.\n\t_, err = obj.HealObject(ctx, bucket, object, \"\", madmin.HealOpts{ScanMode: madmin.HealDeepScan})\n\t// since majority of er.meta's are not available, object quorum can't be read properly and error will be errErasureReadQuorum\n\tif _, ok := err.(InsufficientReadQuorum); !ok {\n\t\tt.Errorf(\"Expected %v but received %v\", InsufficientReadQuorum{}, err)\n\t}\n}", "func (d *btrfs) Delete(op *operations.Operation) error {\n\t// If the user completely destroyed it, call it done.\n\tif !shared.PathExists(GetPoolMountPath(d.name)) {\n\t\treturn nil\n\t}\n\n\t// Delete potential intermediate btrfs subvolumes.\n\tfor _, volType := range d.Info().VolumeTypes {\n\t\tfor _, dir := range BaseDirectories[volType] {\n\t\t\tpath := filepath.Join(GetPoolMountPath(d.name), dir)\n\t\t\tif !shared.PathExists(path) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !d.isSubvolume(path) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\terr := d.deleteSubvolume(path, true)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed deleting btrfs subvolume %q\", path)\n\t\t\t}\n\t\t}\n\t}\n\n\t// On delete, wipe everything in the directory.\n\tmountPath := GetPoolMountPath(d.name)\n\terr := wipeDirectory(mountPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed removing mount path %q: %w\", mountPath, err)\n\t}\n\n\t// Unmount the path.\n\t_, err = d.Unmount()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If the pool path is a subvolume itself, delete it.\n\tif d.isSubvolume(mountPath) {\n\t\terr := d.deleteSubvolume(mountPath, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// And re-create as an empty directory to make the backend happy.\n\t\terr = os.Mkdir(mountPath, 0700)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed creating directory %q: %w\", mountPath, err)\n\t\t}\n\t}\n\n\t// Delete any loop file we may have used.\n\tloopPath := loopFilePath(d.name)\n\terr = os.Remove(loopPath)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"Failed removing loop file %q: %w\", loopPath, err)\n\t}\n\n\treturn nil\n}", "func cleanup(ctx context.Context, fs fs, logger log.FieldLogger, props processorProps) {\n\tspan, _ := opentracing.StartSpanFromContext(ctx, \"cleanup\")\n\tdefer span.Finish()\n\n\terr := fs.DeleteDir(props.WorkDir)\n\tif err != nil {\n\t\tlogger.Errorf(\"%+v\\n\", err)\n\t}\n}", "func (z *zfsctl) DestroyFileSystemOrVolume(ctx context.Context, name, options string) *execute {\n\targs := []string{\"destroy\"}\n\tif len(options) > 0 {\n\t\targs = append(args, options)\n\t}\n\targs = append(args, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (rhelpf LinuxPlatformFlavor) getOsFlavor() ([]cm.Flavor, error) {\n\tlog.Trace(\"flavor/types/linux_platform_flavor:getOsFlavor() Entering\")\n\tdefer log.Trace(\"flavor/types/linux_platform_flavor:getOsFlavor() Leaving\")\n\n\tvar errorMessage = \"Error during creation of OS flavor\"\n\tvar err error\n\tvar osPcrs = rhelpf.getPcrList(cf.FlavorPartOs)\n\tvar includeEventLog = rhelpf.eventLogRequired(cf.FlavorPartOs)\n\tvar allPcrDetails = pfutil.GetPcrDetails(\n\t\trhelpf.HostManifest.PcrManifest, osPcrs, includeEventLog)\n\tvar filteredPcrDetails = pfutil.IncludeModulesToEventLog(\n\t\tallPcrDetails, osModules)\n\n\tnewMeta, err := pfutil.GetMetaSectionDetails(rhelpf.HostInfo, rhelpf.TagCertificate, \"\", cf.FlavorPartOs,\n\t\thcConstants.VendorIntel)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, errorMessage+\" Failure in Meta section details\")\n\t}\n\tlog.Debugf(\"flavor/types/linux_platform_flavor:getOsFlavor() New Meta Section: %v\", *newMeta)\n\n\tnewBios := pfutil.GetBiosSectionDetails(rhelpf.HostInfo)\n\tif newBios == nil {\n\t\treturn nil, errors.Errorf(\"%s Failure in Bios section details\", errorMessage)\n\t}\n\tlog.Debugf(\"flavor/types/linux_platform_flavor:getOsFlavor() New Bios Section: %v\", *newBios)\n\n\t// Assemble the OS Flavor\n\tosFlavor := cm.NewFlavor(newMeta, newBios, nil, filteredPcrDetails, nil, nil)\n\n\tlog.Debugf(\"flavor/types/linux_platform_flavor:getOSFlavor() New OS Flavor: %v\", osFlavor)\n\n\treturn []cm.Flavor{*osFlavor}, nil\n}", "func EnsureOwner(uid, gid int, paths ...string) error {\n\tfor _, p := range paths {\n\t\tfi, err := os.Stat(p)\n\t\tif os.IsNotExist(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif stat, ok := fi.Sys().(*syscall.Stat_t); ok && canWrite(uid, gid, stat) {\n\t\t\t// if a dir has correct ownership, assume it's children do, for performance\n\t\t\tcontinue\n\t\t}\n\t\tif err := recursiveEnsureOwner(p, uid, gid); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Clean() error {\n\tfixtureDir := filepath.Join(\"integration\", \"testdata\", \"fixtures\")\n\tpaths := []string{\n\t\tfilepath.Join(fixtureDir, \"images\"),\n\t\tfilepath.Join(fixtureDir, \"vm-images\"),\n\t}\n\tfor _, p := range paths {\n\t\tif err := sh.Rm(p); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (s *service) doesAnyFileSystemHaveIO(ctx context.Context, rep *podmon.ValidateVolumeHostConnectivityResponse, arrayID string, fsIds []string) (bool, error) {\n\tctx, log, _ := GetRunidLog(ctx)\n\n\t// Get two samples over the interval period and get a difference between the values\n\t// found. If any are found to be non-zero, then we return true, otherwise false.\n\tvar (\n\t\tfirst, second *types.MetricQueryResult\n\t\tfirstSample, secondSample map[string]int\n\t\tgetErr, getValueErr error\n\t)\n\n\t// Retrieve the latest files system read/write metrics\n\tfirst, getErr = s.getMetrics(ctx, arrayID, fileSystemRWs)\n\tif getErr != nil {\n\t\treturn false, getErr\n\t}\n\n\ttime.Sleep(time.Duration(CollectionWait) * time.Millisecond)\n\n\t// Retrieve the metrics for a second time\n\tsecond, getErr = s.getMetrics(ctx, arrayID, fileSystemRWs)\n\tif getErr != nil {\n\t\treturn false, getErr\n\t}\n\n\tfoundVolumeWithIO := false\n\tfor _, fsID := range fsIds {\n\t\tfirstSample, getValueErr = s.getMetricValues(ctx, first, arrayID, fsID)\n\t\tif getValueErr != nil {\n\t\t\treturn false, getValueErr\n\t\t}\n\t\tlog.Debugf(\"firstSample = %v\", firstSample)\n\n\t\tsecondSample, getValueErr = s.getMetricValues(ctx, second, arrayID, fsID)\n\t\tif getValueErr != nil {\n\t\t\treturn false, getValueErr\n\t\t}\n\t\tlog.Debugf(\"secondSample = %v\", secondSample)\n\n\t\thasOrNot := \"no \"\n\t\tfor metricName, v1 := range firstSample {\n\t\t\tv2, ok := secondSample[metricName]\n\t\t\tif !ok {\n\t\t\t\treturn false, fmt.Errorf(\"unexpected result. Could not find metric value for %s\", metricName)\n\t\t\t}\n\t\t\t// Any case found where the difference between the first\n\t\t\t// and the second queries is non-zero should return true.\n\t\t\tdiff := v2 - v1\n\t\t\tif diff > 0 {\n\t\t\t\thasOrNot = \"\"\n\t\t\t\tfoundVolumeWithIO = true\n\t\t\t}\n\t\t}\n\t\trep.Messages = append(rep.Messages, fmt.Sprintf(\"%s on array %s has %sIOs\", fsID, arrayID, hasOrNot))\n\t}\n\treturn foundVolumeWithIO, nil\n}", "func ensureNoTxs(t *testing.T, reactor *Reactor, timeout time.Duration) {\n\ttime.Sleep(timeout) // wait for the txs in all mempools\n\tassert.Zero(t, reactor.mempool.Size())\n}", "func _escFS(useLocal bool) http.FileSystem {\n\tif useLocal {\n\t\treturn _escLocal\n\t}\n\treturn _escStatic\n}", "func _escFS(useLocal bool) http.FileSystem {\n\tif useLocal {\n\t\treturn _escLocal\n\t}\n\treturn _escStatic\n}", "func _escFS(useLocal bool) http.FileSystem {\n\tif useLocal {\n\t\treturn _escLocal\n\t}\n\treturn _escStatic\n}", "func _escFS(useLocal bool) http.FileSystem {\n\tif useLocal {\n\t\treturn _escLocal\n\t}\n\treturn _escStatic\n}", "func WithBoundOS() Option {\n\treturn func(o *options) {\n\t\to.Type = BoundOSFS\n\t}\n}", "func TestFS(fsys writefs.WriteFS) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tdirs := []string{\n\t\t\t\"dir1\",\n\t\t\t\"dir1/dirsub1\",\n\t\t\t\"dirempty\",\n\t\t}\n\t\tfiles := []string{\n\t\t\t\"dir1/file1\",\n\t\t\t\"dir1/file2\",\n\t\t\t\"dir1/dirsub1/file3\",\n\t\t}\n\n\t\tt.Run(\"initialize testing FS\", func(t *testing.T) {\n\t\t\tfor _, dir := range dirs {\n\t\t\t\terr := writefs.MkDir(fsys, dir, fs.FileMode(0755))\n\t\t\t\t//if !(err == nil || errors.Is(err, fs.ErrExist)) {\n\t\t\t\t//\tfmt.Println(err, dir)\n\t\t\t\t//}\n\t\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrExist))\n\n\t\t\t}\n\n\t\t\tfor _, file := range files {\n\t\t\t\tfake := []byte(file + \" content\\n\")\n\t\t\t\tn, err := writefs.WriteFile(fsys, file, fake)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, len(fake), n)\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"pass TestFS\", func(t *testing.T) {\n\t\t\terr := fstest.TestFS(fsys, append(files, dirs...)...)\n\t\t\tassert.NoError(t, err)\n\t\t})\n\n\t\tdirExists := func(t *testing.T, dir string) {\n\t\t\tinfo, err := fs.Stat(fsys, dir)\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.True(t, info.IsDir())\n\t\t\t}\n\t\t}\n\n\t\tfileExists := func(t *testing.T, dir string) {\n\t\t\tinfo, err := fs.Stat(fsys, dir)\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.True(t, info.Mode().IsRegular())\n\t\t\t}\n\t\t}\n\n\t\tfileNotExists := func(t *testing.T, dir string) {\n\t\t\tinfo, err := fs.Stat(fsys, dir)\n\t\t\tassert.True(t, errors.Is(err, fs.ErrNotExist))\n\t\t\tassert.Nil(t, info)\n\t\t}\n\n\t\tcheckDirCreated := func(t *testing.T, dir string) {\n\t\t\tfileNotExists(t, dir)\n\n\t\t\terr := writefs.Remove(fsys, dir)\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrNotExist))\n\n\t\t\tf, err := writefs.OpenFile(fsys, dir, os.O_CREATE, fs.FileMode(0755)|fs.ModeDir)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.Nil(t, f)\n\t\t\tdirExists(t, dir)\n\t\t}\n\t\tdirRemove := func(t *testing.T, dir string) {\n\t\t\tf, _ := writefs.OpenFile(fsys, dir, os.O_TRUNC, 0)\n\t\t\tassert.Nil(t, f)\n\t\t\tfileNotExists(t, dir)\n\t\t}\n\t\tcheckDirRemoved := func(t *testing.T, dir string) {\n\t\t\terr := writefs.MkDir(fsys, dir, fs.FileMode(0755))\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrExist))\n\t\t\tdirExists(t, dir)\n\n\t\t\tf, err := writefs.OpenFile(fsys, dir, os.O_TRUNC, 0)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.Nil(t, f)\n\t\t\tfileNotExists(t, dir)\n\t\t}\n\t\tt.Run(\"creates directories with OpenFile - nested and not recursively\", func(t *testing.T) {\n\t\t\tdirRemove(t, \"dir1/adir/nested\")\n\t\t\tdirRemove(t, \"dir1/adir\")\n\n\t\t\t// nested dir return error\n\t\t\tf, err := writefs.OpenFile(fsys, \"dir1/adir/nested\", os.O_CREATE, fs.FileMode(0755)|fs.ModeDir)\n\t\t\tassert.Error(t, err)\n\t\t\tassert.Nil(t, f)\n\t\t\tassert.True(t, errors.Is(err, fs.ErrNotExist))\n\n\t\t\tcheckDirCreated(t, \"dir1/adir\")\n\t\t\tcheckDirCreated(t, \"dir1/adir/nested\")\n\t\t})\n\n\t\tt.Run(\"OpenFile return *PathError on bad paths\", func(t *testing.T) {\n\t\t\tcheckBadPath(t, \"afilename\", \"OpenFile\", func(name string) error {\n\t\t\t\t_, err := writefs.OpenFile(fsys, name, 0, 0)\n\t\t\t\treturn err\n\t\t\t})\n\t\t})\n\n\t\tt.Run(\"remove files with OpenFile\", func(t *testing.T) {\n\t\t\tfile := \"dir1/somenewfile\"\n\t\t\t_, err := writefs.WriteFile(fsys, file, []byte(file))\n\t\t\tassert.NoError(t, err)\n\n\t\t\tfileExists(t, file)\n\n\t\t\tf, err := writefs.OpenFile(fsys, file, os.O_TRUNC, 0)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.Nil(t, f)\n\n\t\t\tfileNotExists(t, file)\n\t\t})\n\n\t\tt.Run(\"remove directories with OpenFile - nested and not recursively\", func(t *testing.T) {\n\t\t\t// non empty dir return error\n\t\t\tf, err := writefs.OpenFile(fsys, \"dir1/adir\", os.O_TRUNC, 0)\n\t\t\tassert.Error(t, err)\n\t\t\tassert.Nil(t, f)\n\t\t\tassert.True(t, errors.Is(err, fs.ErrInvalid))\n\t\t\t//assert.True(t, errors.Is(err, &fs.PathError{}))\n\n\t\t\tcheckDirRemoved(t, \"dir1/adir/nested\")\n\t\t\tcheckDirRemoved(t, \"dir1/adir\")\n\t\t})\n\t\tt.Run(\"create and write on new files\", func(t *testing.T) {\n\t\t\tfile := \"dir1/file1new\"\n\t\t\terr := writefs.Remove(fsys, file)\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrNotExist))\n\t\t\tfileNotExists(t, file)\n\n\t\t\tf, err := writefs.OpenFile(fsys, file, os.O_CREATE|os.O_WRONLY, fs.FileMode(0644))\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.NotNil(t, f)\n\t\t\t\tbuf := []byte(\"ciao\\n\")\n\t\t\t\tn, err := f.Write(buf)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, len(buf), n)\n\t\t\t\terr = f.Close()\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\n\t\t\tt.Run(\"set modtime to now\", func(t *testing.T) {\n\t\t\t\tinfo, err := fs.Stat(fsys, file)\n\t\t\t\tif assert.NoError(t, err) {\n\t\t\t\t\tassert.Less(t, time.Now().Sub(info.ModTime()), time.Second)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"set content\", func(t *testing.T) {\n\t\t\t\tbuf := []byte(\"ciao\\n\")\n\t\t\t\tactual, err := fs.ReadFile(fsys, file)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, buf, actual)\n\t\t\t})\n\t\t})\n\n\t\tt.Run(\"write on existing files\", func(t *testing.T) {\n\t\t\tfile := \"dir1/file1new\"\n\t\t\terr := writefs.Remove(fsys, file)\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrExist))\n\t\t\t_, err = writefs.WriteFile(fsys, file, []byte(\"ciao\\n\"))\n\t\t\tassert.NoError(t, err)\n\n\t\t\tfileExists(t, file)\n\n\t\t\tf, err := writefs.OpenFile(fsys, file, os.O_WRONLY, fs.FileMode(0644))\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.NotNil(t, f)\n\t\t\t\tbuf := []byte(\"mi\")\n\t\t\t\tn, err := f.Write(buf)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, len(buf), n)\n\t\t\t\terr = f.Close()\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\n\t\t\tt.Run(\"updates modtime\", func(t *testing.T) {\n\t\t\t\tinfo, err := fs.Stat(fsys, file)\n\t\t\t\tif assert.NoError(t, err) {\n\t\t\t\t\tassert.Less(t, time.Now().Sub(info.ModTime()), time.Second)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"update content\", func(t *testing.T) {\n\t\t\t\tactual, err := fs.ReadFile(fsys, file)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, []byte(\"miao\\n\"), actual)\n\t\t\t})\n\t\t})\n\t\tt.Run(\"write on existing files truncating\", func(t *testing.T) {\n\t\t\tfile := \"dir1/file1new\"\n\t\t\terr := writefs.Remove(fsys, file)\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrExist))\n\t\t\t_, err = writefs.WriteFile(fsys, file, []byte(\"ciao\\n\"))\n\t\t\tassert.NoError(t, err)\n\n\t\t\tfileExists(t, file)\n\n\t\t\tf, err := writefs.OpenFile(fsys, file, os.O_WRONLY|os.O_TRUNC, fs.FileMode(0644))\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.NotNil(t, f)\n\t\t\t\tbuf := []byte(\"mi\")\n\t\t\t\tn, err := f.Write(buf)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, len(buf), n)\n\t\t\t\terr = f.Close()\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\n\t\t\tt.Run(\"updates modtime\", func(t *testing.T) {\n\t\t\t\tinfo, err := fs.Stat(fsys, file)\n\t\t\t\tif assert.NoError(t, err) {\n\t\t\t\t\tassert.Less(t, time.Now().Sub(info.ModTime()), time.Second)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"set content\", func(t *testing.T) {\n\t\t\t\tactual, err := fs.ReadFile(fsys, file)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, []byte(\"mi\"), actual)\n\t\t\t})\n\t\t})\n\n\t\tt.Run(\"appending to existing files\", func(t *testing.T) {\n\t\t\tfile := \"dir1/file1new\"\n\t\t\terr := writefs.Remove(fsys, file)\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrExist))\n\t\t\t_, err = writefs.WriteFile(fsys, file, []byte(\"ciao\\n\"))\n\t\t\tassert.NoError(t, err)\n\n\t\t\tfileExists(t, file)\n\n\t\t\tf, err := writefs.OpenFile(fsys, file, os.O_WRONLY|os.O_APPEND, fs.FileMode(0644))\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.NotNil(t, f)\n\t\t\t\tbuf := []byte(\"mi\")\n\t\t\t\tn, err := f.Write(buf)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, len(buf), n)\n\t\t\t\terr = f.Close()\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\n\t\t\tt.Run(\"updates modtime\", func(t *testing.T) {\n\t\t\t\tinfo, err := fs.Stat(fsys, file)\n\t\t\t\tif assert.NoError(t, err) {\n\t\t\t\t\tassert.Less(t, time.Now().Sub(info.ModTime()), time.Second)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"updates content\", func(t *testing.T) {\n\t\t\t\tactual, err := fs.ReadFile(fsys, file)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, []byte(\"ciao\\nmi\"), actual)\n\t\t\t})\n\t\t})\n\n\t\tt.Run(\"opening non existing files\", func(t *testing.T) {\n\t\t\tf, err := writefs.OpenFile(fsys, \"unkfile\", os.O_WRONLY, fs.FileMode(0644))\n\t\t\tassert.Error(t, err)\n\t\t\tassert.True(t, errors.Is(err, fs.ErrNotExist))\n\t\t\tassert.Nil(t, f)\n\t\t})\n\t\t/*\n\t\t\tt.Run(\"opening read-only files for write\", func(t *testing.T) {\n\t\t\t\tf, err := writefs.OpenFile(fsys,\"/etc/passwd\", os.O_WRONLY, fs.FileMode(0644))\n\t\t\t\tassert.Error(t, err)\n\t\t\t\tassert.Nil(t, f)\n\t\t\t})\n\t\t*/\n\t}\n}", "func UnmountAll(mount string, flags int) error {\n\treturn ErrNotImplementOnUnix\n}", "func (b *TestBackend) IgnoreCleanable() {}", "func (o FioSpecVolumeVolumeSourceStorageosOutput) FsType() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceStorageos) *string { return v.FsType }).(pulumi.StringPtrOutput)\n}", "func UnmountAllSmbMounts(ctx context.Context, cr *chrome.Chrome) error {\n\t// Open the test API.\n\ttconn, err := cr.TestAPIConn(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create the test API conn\")\n\t}\n\t// Open the Files App.\n\tfiles, err := filesapp.Launch(ctx, tconn)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to launch Files app\")\n\t}\n\tdefer files.Close(ctx)\n\t// Get connection to foreground Files app to verify changes.\n\tfilesSWA := \"chrome://file-manager/\"\n\tmatchFilesApp := func(t *chrome.Target) bool {\n\t\treturn t.URL == filesSWA\n\t}\n\tconn, err := cr.NewConnForTarget(ctx, matchFilesApp)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to connect to Files app foreground window\")\n\t}\n\tdefer conn.Close()\n\n\tinfo, err := sysutil.MountInfoForPID(sysutil.SelfPID)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to mount info\")\n\t}\n\tfor i := range info {\n\t\tif info[i].Fstype == \"fuse.smbfs\" {\n\t\t\tsmbfsUniqueID := filepath.Base(info[i].MountPath)\n\t\t\tif err := conn.Call(ctx, nil,\n\t\t\t\t`(mount) => new Promise((resolve, reject) =>\n\t\t\t\t\tchrome.fileManagerPrivate.removeMount(mount, () => {\n\t\t\t\t\t\tif (chrome.runtime.lastError) {\n\t\t\t\t\t\t\treject(chrome.runtime.lastError.message);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t}\n\t\t\t\t\t}))`, \"smb:\"+smbfsUniqueID,\n\t\t\t); err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"failed to unmount SMB mountpoint %q\", smbfsUniqueID)\n\t\t\t}\n\t\t\ttesting.ContextLog(ctx, \"Unmounted SMB mountpoint \", smbfsUniqueID)\n\t\t}\n\t}\n\treturn nil\n}", "func IsSysErrNoSys(err error) bool {\n\tif err == syscall.ENOSYS {\n\t\treturn true\n\t}\n\tpathErr, ok := err.(*os.PathError)\n\treturn ok && pathErr.Err == syscall.ENOSYS\n}", "func Cgroupfs(l *LinuxFactory) error {\n\tl.NewCgroupsManager = func(config *configs.Cgroup, paths map[string]string) cgroups.Manager {\n\t\treturn &fs.Manager{\n\t\t\tCgroups: config,\n\t\t\tPaths: paths,\n\t\t}\n\t}\n\treturn nil\n}", "func removeDeleteme(){\n lvm_count := exec.Command(\"/bin/bash\", \"-c\", \"lvs | grep deleteme | wc -l\")\n if lvm_count > 1 {\n fmt.Println(\"Multiple deleteme logical volumes detected. Please remove the deleteme volumes manually.\")\n os.Exit(1)\n } else if lvm_count == 0 {\n fmt.Println(\"No deleteme logical volumes detected.\")\n } else {\n exec.Command(\"/bin/bash\", \"-c\", \"umount /delete\")\n exec.Command(\"/bin/bash\", \"-c\", \"rmdir /deleteme\")\n exec.Command(\"/bin/bash\", \"-c\", \"lvchange -an /dev/mapper/$(lvs | grep deleteme | awk ' { print $2 }')-deleteme00\")\n exec.Command(\"/bin/bash\", \"-c\", \"lvremove -f /dev/mapper/$(lvs | grep deleteme | awk ' { print $2 }')-deleteme00\")\n exec.Command(\"/bin/bash\", \"-c\", \"cp /etc/fstab /home/rack/fstab.bak\")\n exec.Command(\"/bin/bash\", \"-c\", \"sed -i '/\\/deleteme/d' /etc/fstab\")\n fmt.Println(\"The deleteme volume has been successfully removed.\")\n }\n}", "func isWellKnownFS(fn string) bool {\n\tvar fs syscall.Statfs_t\n\terr := syscall.Statfs(fn, &fs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif fs.Type == EXT4_SUPER_MAGIC || fs.Type == TMPFS_MAGIC {\n\t\treturn true\n\t}\n\treturn false\n}", "func TestFailingFSRecorder(t *testing.T) {\n\tappFs = afero.NewMemMapFs()\n\n\tevt := event.New()\n\n\trec := New(logs, evt, fakedir, 60, false).Start()\n\n\t_ = afero.WriteFile(appFs, fakedir+\"/foo.yaml\", []byte{42}, 0600)\n\n\t// switching to failing (read-only) filesystem\n\tappFs = afero.NewReadOnlyFs(appFs)\n\n\terr := rec.save(\"foo\", []byte(\"bar\"))\n\tif err == nil {\n\t\tt.Error(\"save should return an error in case of failure\")\n\t}\n\n\t// shouldn't panic in case of failures\n\trec.deleteObsoleteFiles()\n\n\t// shouldn't block (the controllers event loop will retry anyway)\n\tch := make(chan struct{})\n\tgo func() {\n\t\tevt.Send(newNotif(event.Upsert, \"foo3\"))\n\t\tevt.Send(newNotif(event.Upsert, \"foo4\"))\n\t\tch <- struct{}{}\n\t}()\n\n\tselect {\n\tcase <-ch:\n\tcase <-time.After(5 * time.Second):\n\t\tt.Error(\"recorder shouldn't block in case of fs failure\")\n\t}\n\n\t// back to normal operations\n\trec.Stop() // just to flush ongoing ops before switch filesystem\n\tappFs = afero.NewMemMapFs()\n\trec.stopch = make(chan struct{})\n\trec.donech = make(chan struct{})\n\trec.Start()\n\tevt.Send(newNotif(event.Upsert, \"foo2\"))\n\trec.Stop() // flush ongoing ops\n\n\texist, _ := afero.Exists(appFs, fakedir+\"/foo-foo2.yaml\")\n\tif !exist {\n\t\tt.Error(\"foo-foo2.yaml should exist; recorder should recover from fs failures\")\n\t}\n}", "func setupNullDisk(t *testing.T, s *DiskIO, devName string) func() {\n\ttd, err := os.CreateTemp(\"\", \".telegraf.DiskInfoTest\")\n\trequire.NoError(t, err)\n\n\tif s.infoCache == nil {\n\t\ts.infoCache = make(map[string]diskInfoCache)\n\t}\n\tic, ok := s.infoCache[devName]\n\tif !ok {\n\t\t// No previous calls for the device were done, easy to poison the cache\n\t\ts.infoCache[devName] = diskInfoCache{\n\t\t\tmodifiedAt: 0,\n\t\t\tudevDataPath: td.Name(),\n\t\t\tvalues: map[string]string{},\n\t\t}\n\t}\n\torigUdevPath := ic.udevDataPath\n\n\tcleanFunc := func() {\n\t\tic.udevDataPath = origUdevPath\n\t\tos.Remove(td.Name())\n\t}\n\n\tic.udevDataPath = td.Name()\n\t_, err = td.Write(nullDiskInfo)\n\tif err != nil {\n\t\tcleanFunc()\n\t\tt.Fatal(err)\n\t}\n\n\treturn cleanFunc\n}", "func (c *MockFileStorageClient) DeleteFileSystem(ctx context.Context, id string) error {\n\treturn nil\n}", "func TestManagedDisks_NoOAuthRequired(t *testing.T) {\n\tRunScenarios(\n\t\tt,\n\t\teOperation.Copy(),\n\t\teTestFromTo.Other(common.EFromTo.BlobLocal()),\n\t\teValidate.Auto(),\n\t\tanonymousAuthOnly,\n\t\tanonymousAuthOnly,\n\t\tparams{\n\t\t\tdisableParallelTesting: true,\n\t\t},\n\t\tnil,\n\t\ttestFiles{\n\t\t\tshouldTransfer: []interface{}{\n\t\t\t\t\"\",\n\t\t\t},\n\t\t}, // Managed disks will always have a transfer target of \"\"\n\t\tEAccountType.Standard(),\n\t\tEAccountType.StdManagedDisk(),\n\t\t\"\",\n\t)\n}", "func (fs *bundleFs) RemoveAll(path string) error {\n\treturn ErrReadOnly\n}", "func (cli *CLI) SystemDelete() {\n\tsys := &nbv1.NooBaa{\n\t\tTypeMeta: metav1.TypeMeta{Kind: \"NooBaa\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cli.SystemName,\n\t\t\tNamespace: cli.Namespace,\n\t\t},\n\t}\n\n\tutil.KubeDelete(cli.Client, sys)\n\n\t// TEMPORARY ? delete PVCs here because we couldn't own them in openshift\n\t// See https://github.com/noobaa/noobaa-operator/issues/12\n\t// So we delete the PVC here on system delete.\n\tcoreApp := util.KubeObject(bundle.File_deploy_internal_statefulset_core_yaml).(*appsv1.StatefulSet)\n\tfor i := range coreApp.Spec.VolumeClaimTemplates {\n\t\tt := &coreApp.Spec.VolumeClaimTemplates[i]\n\t\tpvc := &corev1.PersistentVolumeClaim{\n\t\t\tTypeMeta: metav1.TypeMeta{Kind: \"PersistentVolumeClaim\"},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: t.Name + \"-\" + cli.SystemName + \"-core-0\",\n\t\t\t\tNamespace: cli.Namespace,\n\t\t\t},\n\t\t}\n\t\tutil.KubeDelete(cli.Client, pvc)\n\t}\n}" ]
[ "0.53957534", "0.53667784", "0.5331955", "0.5323168", "0.5301859", "0.52755934", "0.52395886", "0.5217741", "0.51287127", "0.5039392", "0.50211424", "0.5002997", "0.49385625", "0.49130845", "0.49005198", "0.48919713", "0.48695275", "0.48681164", "0.4860014", "0.485658", "0.48282713", "0.48279673", "0.48118675", "0.47928274", "0.47842798", "0.47756273", "0.47530922", "0.47436154", "0.47280303", "0.47183648", "0.47101888", "0.47077057", "0.46948677", "0.46831197", "0.46750864", "0.466643", "0.46323174", "0.46153814", "0.45972016", "0.45846432", "0.45813683", "0.4576992", "0.456484", "0.45461416", "0.45363164", "0.453094", "0.45255384", "0.452214", "0.4513038", "0.45054218", "0.44998205", "0.44988963", "0.44842327", "0.44828743", "0.44751307", "0.44741413", "0.4473975", "0.44718572", "0.44682744", "0.44677708", "0.44662046", "0.44628733", "0.44609937", "0.4457285", "0.4449985", "0.44450927", "0.44238743", "0.44177547", "0.44160032", "0.44120872", "0.44108048", "0.44086838", "0.4394447", "0.4393518", "0.43921104", "0.4389323", "0.4381113", "0.43808287", "0.437454", "0.43627372", "0.43618408", "0.43618408", "0.43618408", "0.43618408", "0.43617004", "0.43530434", "0.43474752", "0.43461016", "0.43449533", "0.43423858", "0.43414485", "0.43395787", "0.43385917", "0.43375054", "0.4334085", "0.4330518", "0.43248904", "0.4322471", "0.43217084", "0.4320975" ]
0.7901684
0
FsPath returns an afero.Fs rooted to the path provided. If the path is invalid, or is less than 2 levels down from the filesystem root, an error is returned.
func FsPath(path string) (afero.Fs, error) { if path == "" { return nil, fmt.Errorf("gofakes3: empty path") } path, err := filepath.Abs(path) if err != nil { return nil, err } stat, err := os.Stat(path) if err != nil { return nil, err } else if !stat.IsDir() { return nil, fmt.Errorf("gofakes3: path %q is not a directory", path) } parts := strings.Split(path, string(filepath.Separator)) if len(parts) < 2 { // cheap and nasty footgun check: return nil, fmt.Errorf("gofakes3: invalid path %q", path) } return afero.NewBasePathFs(afero.NewOsFs(), path), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Path(subpath string) (string, error) {\n\tif !isinit {\n\t\treturn \"\", fmt.Errorf(\"pathresolver not initialized\")\n\t}\n\n\tif subpath == \"\" {\n\t\treturn basedirectory, nil\n\t}\n\n\tif filepath.IsAbs(subpath) {\n\t\treturn \"\", fmt.Errorf(\"cannot use absolute path as subpath\")\n\t}\n\n\treturn filepath.Join(basedirectory, subpath), nil\n}", "func (o FioSpecVolumeVolumeSourceNfsOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceNfs) string { return v.Path }).(pulumi.StringOutput)\n}", "func (o FioSpecVolumeVolumeSourceGlusterfsOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceGlusterfs) string { return v.Path }).(pulumi.StringOutput)\n}", "func (p *Pod) rootfsPath() string {\n\treturn filepath.Join(p.baseDir, podBundlePath, podRootfsPath)\n}", "func (o IopingSpecVolumeVolumeSourceNfsOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceNfs) string { return v.Path }).(pulumi.StringOutput)\n}", "func (p *Tmpfs) Path(ctx driver.Context, v *types.Volume) (string, error) {\n\tctx.Log.Debugf(\"Tmpfs volume mount path: %s\", v.Name)\n\treturn path.Join(dataDir, v.Name), nil\n}", "func (r *RelativePath) RootPath() string {\n\treturn \"/\" + strings.Join(r.stack[:r.limit], \"/\")\n}", "func (d ImagefsDriver) Path(r *volume.PathRequest) (*volume.PathResponse, error) {\n\tgetReq := volume.GetRequest{\n\t\tName: r.Name,\n\t}\n\tret, err := d.Get(&getReq)\n\tvar _ret *volume.PathResponse\n\tif ret != nil {\n\t\t_ret = &volume.PathResponse{\n\t\t\tMountpoint: ret.Volume.Mountpoint,\n\t\t}\n\t}\n\treturn _ret, err\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot = parsePath(root)\n\tclient := fshttp.NewClient(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tsrv: rest.NewClient(client).SetRoot(rootURL),\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t\tm: m,\n\t\tauthExpiry: parseExpiry(opt.AuthorizationExpiry),\n\t}\n\tf.features = (&fs.Features{\n\t\tCaseInsensitive: true,\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\tf.srv.SetSigner(f.getAuth) // use signing hook to get the auth\n\tf.srv.SetErrorHandler(errorHandler)\n\n\t// Get rootID\n\tif f.opt.RootID == \"\" {\n\t\tuser, err := f.getUser(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.opt.RootID = user.SyncFolders\n\t\tif strings.HasSuffix(f.opt.RootID, \"/contents\") {\n\t\t\tf.opt.RootID = f.opt.RootID[:len(f.opt.RootID)-9]\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"unexpected rootID %q\", f.opt.RootID)\n\t\t}\n\t\t// Cache the results\n\t\tf.m.Set(\"root_id\", f.opt.RootID)\n\t\tf.opt.DeletedID = user.Deleted\n\t\tf.m.Set(\"deleted_id\", f.opt.DeletedID)\n\t}\n\tf.dirCache = dircache.New(root, f.opt.RootID, f)\n\n\t// Find the current root\n\terr = f.dirCache.FindRoot(ctx, false)\n\tif err != nil {\n\t\t// Assume it is a file\n\t\tnewRoot, remote := dircache.SplitPath(root)\n\t\toldDirCache := f.dirCache\n\t\tf.dirCache = dircache.New(newRoot, f.opt.RootID, f)\n\t\tf.root = newRoot\n\t\tresetF := func() {\n\t\t\tf.dirCache = oldDirCache\n\t\t\tf.root = root\n\t\t}\n\t\t// Make new Fs which is the parent\n\t\terr = f.dirCache.FindRoot(ctx, false)\n\t\tif err != nil {\n\t\t\t// No root so return old f\n\t\t\tresetF()\n\t\t\treturn f, nil\n\t\t}\n\t\t_, err := f.newObjectWithInfo(ctx, remote, nil)\n\t\tif err != nil {\n\t\t\tif err == fs.ErrorObjectNotFound {\n\t\t\t\t// File doesn't exist so return old f\n\t\t\t\tresetF()\n\t\t\t\treturn f, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\treturn f, nil\n}", "func (o FioSpecVolumeVolumeSourceDownwardAPIItemsOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceDownwardAPIItems) string { return v.Path }).(pulumi.StringOutput)\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\t// Parse config into Options struct\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(opt.Headers)%2 != 0 {\n\t\treturn nil, errors.New(\"odd number of headers supplied\")\n\t}\n\n\tif !strings.HasSuffix(opt.Endpoint, \"/\") {\n\t\topt.Endpoint += \"/\"\n\t}\n\n\t// Parse the endpoint and stick the root onto it\n\tbase, err := url.Parse(opt.Endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu, err := rest.URLJoin(base, rest.URLPathEscape(root))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := fshttp.NewClient(ctx)\n\n\tendpoint, isFile := getFsEndpoint(ctx, client, u.String(), opt)\n\tfs.Debugf(nil, \"Root: %s\", endpoint)\n\tu, err = url.Parse(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tci := fs.GetConfig(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tci: ci,\n\t\thttpClient: client,\n\t\tendpoint: u,\n\t\tendpointURL: u.String(),\n\t}\n\tf.features = (&fs.Features{\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\n\tif isFile {\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\n\tif !strings.HasSuffix(f.endpointURL, \"/\") {\n\t\treturn nil, errors.New(\"internal error: url doesn't end with /\")\n\t}\n\n\treturn f, nil\n}", "func (o FioSpecVolumeVolumeSourceGlusterfsPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceGlusterfs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (o IopingSpecVolumeVolumeSourceGlusterfsOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceGlusterfs) string { return v.Path }).(pulumi.StringOutput)\n}", "func (o FioSpecVolumeVolumeSourceNfsPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceNfs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (o FioSpecVolumeVolumeSourceCephfsOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceCephfs) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (d Dir) Path() string {\n\tif d.env == \"\" {\n\t\tpanic(\"xdgdir.Dir.Path() on zero Dir\")\n\t}\n\tp := d.path()\n\tif p != \"\" && d.userOwned {\n\t\tinfo, err := os.Stat(p)\n\t\tif err != nil {\n\t\t\treturn \"\"\n\t\t}\n\t\tif !info.IsDir() || info.Mode().Perm() != 0700 {\n\t\t\treturn \"\"\n\t\t}\n\t\tst, ok := info.Sys().(*syscall.Stat_t)\n\t\tif !ok || int(st.Uid) != geteuid() {\n\t\t\treturn \"\"\n\t\t}\n\t}\n\treturn p\n}", "func (m *wasiSnapshotPreview1Impl) pathOpen(pfd wasiFd, pdirflags wasiLookupflags, ppath list, poflags wasiOflags, pfsRightsBase wasiRights, pfsRightsInheriting wasiRights, pfdflags wasiFdflags) (rv wasiFd, err wasiErrno) {\n\tpath, err := m.loadPath(ppath)\n\tif err != wasiErrnoSuccess {\n\t\treturn 0, err\n\t}\n\n\trequiredRights := uint64(wasiRightsPathOpen)\n\tif poflags&wasiOflagsCreat != 0 {\n\t\trequiredRights |= wasiRightsPathCreateFile\n\t}\n\n\tf, err := m.files.acquireFile(pfd, requiredRights)\n\tif err != wasiErrnoSuccess {\n\t\treturn 0, err\n\t}\n\tdefer m.files.releaseFile(pfd, f)\n\n\tif f.rights&pfsRightsBase != pfsRightsBase {\n\t\treturn 0, wasiErrnoNotcapable\n\t}\n\n\tdir, ok := f.f.(Directory)\n\tif !ok {\n\t\treturn 0, wasiErrnoNotdir\n\t}\n\n\tfd, wasiFile, err := m.files.allocate(pfsRightsBase, pfsRightsInheriting)\n\tif err != wasiErrnoSuccess {\n\t\treturn 0, err\n\t}\n\n\tfsFile, ferr := dir.Open(path, int(poflags), int(pfdflags))\n\tif ferr != nil {\n\t\treturn 0, fileErrno(ferr)\n\t}\n\n\twasiFile.open, wasiFile.fdflags, wasiFile.f = true, pfdflags, fsFile\n\treturn fd, wasiErrnoSuccess\n}", "func NewFS(db *bolt.DB, bucketpath string) (*FileSystem, error) {\n\n\t// create buckets\n\terr := db.Update(func(tx *bolt.Tx) error {\n\t\treturn bucketInit(tx, bucketpath)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// load or initialize\n\trootIno := uint64(1)\n\tfs := &FileSystem{\n\t\tdb: db,\n\t\tbucket: bucketpath,\n\t\trootIno: rootIno,\n\t\tcwd: \"/\",\n\t}\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\tbb, err := openBucket(tx, bucketpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb := newFsBucket(bb)\n\n\t\t// create the `nil` node if it doesn't exist\n\t\terr = b.InodeInit()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// load the\n\t\tdata := make([]byte, 4)\n\t\tbinary.BigEndian.PutUint32(data, uint32(0755))\n\t\t_, err = b.LoadOrSet(\"umask\", data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// load the root Ino if one is available\n\t\tdata, err = b.LoadOrSet(\"rootIno\", i2b(rootIno))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trootIno = b2i(data)\n\n\t\t_, err = b.GetInode(rootIno)\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err == os.ErrNotExist {\n\t\t\tnode := newInode(os.ModeDir | 0755)\n\t\t\tnode.countUp()\n\t\t\terr = b.PutInode(rootIno, node)\n\t\t\tif err != nil {\n\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfs.rootIno = rootIno\n\treturn fs, nil\n\n}", "func (b *Bucket) Path() (string, error) {\n\tconf := b.conf.Viper.ConfigFileUsed()\n\tif conf == \"\" {\n\t\treturn b.cwd, nil\n\t}\n\treturn filepath.Dir(filepath.Dir(conf)), nil\n}", "func (f *Flock) Path() string {\n\treturn f.path\n}", "func (c Chunk) Path(rootPath *string) (path string, err error) {\n\tvar (\n\t\tidStr string\n\t\tparts []string\n\t\tindex int\n\t\tdir string\n\t)\n\n\tif rootPath == nil {\n\t\trootPath = &config.DefaultConfig.Chunk.RootPath\n\t}\n\tif c.ID < 10000 {\n\t\treturn \"\", ErrInvalidChunkID\n\t}\n\tidStr = strconv.FormatUint(c.ID, 10)\n\tparts = make([]string, (len(idStr)/3)+1)\n\tfor ; len(idStr) > 3; index++ {\n\t\tparts[index] = util.SubStrFromToEnd(idStr, -3)\n\t\tidStr = util.SubStrFromTo(idStr, 0, -3)\n\t}\n\tparts[index] = idStr\n\tparts = parts[1:]\n\tutil.ReverseSlice(parts)\n\tdir = filepath.Join(strings.TrimSuffix(*rootPath, string(os.PathSeparator)), filepath.Join(parts...))\n\tpath = filepath.Join(dir, strconv.FormatUint(c.ID, 10))\n\tif !util.IsDir(dir) {\n\t\terr = os.MkdirAll(dir, os.ModePerm)\n\t}\n\treturn path, err\n}", "func (o FioSpecVolumeVolumeSourceHostPathOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceHostPath) string { return v.Path }).(pulumi.StringOutput)\n}", "func pathDir(path string) string {\n\t// Disallow synchronization root paths.\n\tif path == \"\" {\n\t\tpanic(\"empty path\")\n\t}\n\n\t// Identify the index of the last slash in the path.\n\tlastSlashIndex := strings.LastIndexByte(path, '/')\n\n\t// If there is no slash, then the parent is the synchronization root.\n\tif lastSlashIndex == -1 {\n\t\treturn \"\"\n\t}\n\n\t// Verify that the parent path isn't empty. There aren't any scenarios where\n\t// this is allowed.\n\tif lastSlashIndex == 0 {\n\t\tpanic(\"empty parent path\")\n\t}\n\n\t// Trim off the slash and everything that follows.\n\treturn path[:lastSlashIndex]\n}", "func (d *DirectorySpec) AbsPath() string {\n\treturn (*directory)(d).AbsPath()\n}", "func GetRootPath() string {\n\t_, filename, _, ok := runtime.Caller(0)\n\tif !ok {\n\t\tpanic(\"Cannot get file into for env\")\n\t}\n\n\treturn path.Dir(path.Dir(filename))\n}", "func (o FioSpecVolumeVolumeSourceCephfsPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceCephfs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (d *SourceFilesystem) Path(filename string) string {\n\tfor _, dir := range d.Dirs {\n\t\tmeta := dir.Meta()\n\t\tif strings.HasPrefix(filename, meta.Filename) {\n\t\t\tp := strings.TrimPrefix(strings.TrimPrefix(filename, meta.Filename), filePathSeparator)\n\t\t\tif mountRoot := meta.MountRoot; mountRoot != \"\" {\n\t\t\t\treturn filepath.Join(mountRoot, p)\n\t\t\t}\n\t\t\treturn p\n\t\t}\n\t}\n\treturn \"\"\n}", "func (f *Fs) rootSlash() string {\n\tif f.root == \"\" {\n\t\treturn f.root\n\t}\n\treturn f.root + \"/\"\n}", "func (bsr *blockStreamReader) Path() string {\n\tpath := bsr.streamReaders.metaindexReader.Path()\n\treturn filepath.Dir(path)\n}", "func PathBase(path string) string {\n\t// If this is the root path, then just return an empty string.\n\tif path == \"\" {\n\t\treturn \"\"\n\t}\n\n\t// Identify the index of the last slash in the path.\n\tlastSlashIndex := strings.LastIndexByte(path, '/')\n\n\t// If there is no slash, then the path is a file directly under the\n\t// synchronization root.\n\tif lastSlashIndex == -1 {\n\t\treturn path\n\t}\n\n\t// Verify that the base name isn't empty (i.e. that the string doesn't end\n\t// with a slash). We could do additional validation here (e.g. validating\n\t// the path segment before the slash), but it would be costly and somewhat\n\t// unnecessary. This check is sufficient to ensure that this function can\n\t// return a meaningful answer.\n\tif lastSlashIndex == len(path)-1 {\n\t\tpanic(\"empty base name\")\n\t}\n\n\t// Extract the base name.\n\treturn path[lastSlashIndex+1:]\n}", "func (cl *Client) Realpath(path string) (node fs.DirEntry, err error) {\n\tvar (\n\t\tlogp = \"Realpath\"\n\t\treq = cl.generatePacket()\n\t\tpayload = req.fxpRealpath(path)\n\t)\n\n\tres, err := cl.send(payload)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %w\", logp, err)\n\t}\n\tif res.kind == packetKindFxpStatus {\n\t\treturn nil, handleStatusCode(res.code, res.message)\n\t}\n\tif res.kind != packetKindFxpName {\n\t\treturn nil, errUnexpectedResponse(packetKindFxpName, res.kind)\n\t}\n\tnode = res.nodes[0]\n\tres.nodes = nil\n\treturn node, nil\n}", "func getRootPath() string {\n\tp, _ := filepath.Abs(\"../../\")\n\treturn p + string(filepath.Separator)\n}", "func (o IopingSpecVolumeVolumeSourceCephfsOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceCephfs) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (fs *Bcpfs) Realpath(p string) string {\n\tif !fs.IsServicePath(p) {\n\t\treturn slashpath.Join(\n\t\t\tfs.OrgUnitDir, p,\n\t\t)\n\t}\n\n\t// Path `p` must be a service path.\n\tparts := strings.Split(p, \"/\")\n\tif len(parts) < 2 {\n\t\t// Path too short. Return an empty string to indicate the\n\t\t// problem instead of full error handling, because paths must\n\t\t// not be too short for a valid configuration.\n\t\treturn \"\"\n\t}\n\n\tif fs.IsFacilityPath(p) {\n\t\treturn slashpath.Join(append(\n\t\t\t[]string{fs.ServiceDir}, parts[1:]...,\n\t\t)...)\n\t}\n\n\tou := parts[0]\n\tsrv := parts[1]\n\trest := parts[2:]\n\treturn slashpath.Join(append(\n\t\t[]string{fs.ServiceDir, srv, ou}, rest...,\n\t)...)\n}", "func (o IopingSpecVolumeVolumeSourceNfsPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceNfs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (d *VolumeDriver) Path(r volume.Request) volume.Response {\n\treturn volume.Response{Mountpoint: getMountPoint(r.Name)}\n}", "func (me *inode) GetPath() (path string, mount *mountData) {\n\tme.mount.treeLock.RLock()\n\tdefer me.mount.treeLock.RUnlock()\n\t\t\n\tif me.NodeId != FUSE_ROOT_ID && me.Parent == nil {\n\t\t// Deleted node. Treat as if the filesystem was unmounted.\n\t\treturn \".deleted\", nil\n\t}\n\n\trev_components := make([]string, 0, 10)\n\tinode := me\n\n\tfor ; inode != nil && inode.mountPoint == nil; inode = inode.Parent {\n\t\trev_components = append(rev_components, inode.Name)\n\t}\n\tif inode == nil {\n\t\tpanic(fmt.Sprintf(\"did not find parent with mount: %v\", rev_components))\n\t}\n\tmount = inode.mountPoint\n\n\tif mount.unmountPending {\n\t\treturn \"\", nil\n\t}\n\treturn ReverseJoin(rev_components, \"/\"), mount\n}", "func (u UFSPathBuilder) GenAlluxioUFSRootPath(items []datav1alpha1.Mount) (string, *datav1alpha1.Mount) {\n\t// if have multi ufs mount point or empty\n\t// use local storage root path by default\n\tif len(items) > 1 || len(items) == 0 {\n\t\treturn u.GetLocalStorageRootDir(), nil\n\t}\n\n\tm := items[0]\n\n\t// if fluid native scheme : use local storage root path\n\tif common.IsFluidNativeScheme(m.MountPoint) {\n\t\treturn u.GetLocalStorageRootDir(), nil\n\t}\n\n\t// only if user define mount.path as \"/\", work as alluxio.master.mount.table.root.ufs\n\tif filepath.IsAbs(m.Path) && len(m.Path) == 1 {\n\t\treturn m.MountPoint, &m\n\t}\n\n\treturn u.GetLocalStorageRootDir(), nil\n\n}", "func (o FioSpecVolumeVolumeSourceProjectedSourcesDownwardAPIItemsOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceProjectedSourcesDownwardAPIItems) string { return v.Path }).(pulumi.StringOutput)\n}", "func (metadata EventMetadata) GetPath() (string, error) {\n\tpath, err := os.Readlink(\n\t\tfilepath.Join(\n\t\t\tProcFsFdInfo,\n\t\t\tstrconv.FormatUint(\n\t\t\t\tuint64(metadata.Fd),\n\t\t\t\t10,\n\t\t\t),\n\t\t),\n\t)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"fanotify: %w\", err)\n\t}\n\n\treturn path, nil\n}", "func Init(path string, dir string) *Fs {\n\tfs := Fs{filepath.Join(path, dir)}\n\tif fi, err := os.Stat(fs.Path); err != nil || !fi.IsDir() {\n\t\tlog.Fatal(\"%s is inaccesible\", fs)\n\t}\n\treturn &fs\n}", "func (driver *Driver) Path(volumeName, volumeID string) (string, error) {\n\tif volumeName == \"\" && volumeID == \"\" {\n\t\treturn \"\", errors.New(\"Missing volume name or ID\")\n\t}\n\n\tinstances, err := driver.sdm.GetInstance()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch {\n\tcase len(instances) == 0:\n\t\treturn \"\", errors.New(\"No instances\")\n\tcase len(instances) > 1:\n\t\treturn \"\", errors.New(\"Too many instances returned, limit the storagedrivers\")\n\t}\n\n\tvolumes, err := driver.sdm.GetVolume(volumeID, volumeName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch {\n\tcase len(volumes) == 0:\n\t\treturn \"\", errors.New(\"No volumes returned by name\")\n\tcase len(volumes) > 1:\n\t\treturn \"\", errors.New(\"Multiple volumes returned by name\")\n\t}\n\n\tvolumeAttachment, err := driver.sdm.GetVolumeAttach(volumes[0].VolumeID, instances[0].InstanceID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(volumeAttachment) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\tmounts, err := driver.osdm.GetMounts(volumeAttachment[0].DeviceName, \"\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(mounts) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\treturn mounts[0].Mountpoint, nil\n}", "func RootedPath(elem ...string) string { return filesys.RootedPath(elem...) }", "func (fs HgmFs) Root() (fs.Node, error) {\n\treturn &HgmDir{hgmFs: fs, localDir: \"/\"}, nil\n}", "func ValidatePath(path string) error {\n\tif path == \"\" {\n\t\treturn fmt.Errorf(\"path cannot be empty\")\n\t}\n\tif string(path[0]) != \"/\" {\n\t\treturn fmt.Errorf(\"path must start with / character\")\n\t}\n\tif len(path) == 1 { // done checking - it's the root\n\t\treturn nil\n\t}\n\n\tif string(path[len(path)-1]) == \"/\" {\n\t\treturn fmt.Errorf(\"path must not end with / character\")\n\t}\n\n\tvar reason string\n\tlastr := '/'\n\tchars := []rune(path)\n\tfor i := 1; i < len(chars); i++ {\n\t\tr := chars[i]\n\t\tif r == 0 {\n\t\t\treason = fmt.Sprintf(\"null character not allowed @%d\", i)\n\t\t\tbreak\n\t\t} else if r == '/' && lastr == '/' {\n\t\t\treason = fmt.Sprintf(\"empty node name specified @%d\", i)\n\t\t\tbreak\n\t\t} else if r == '.' && lastr == '.' {\n\t\t\tif chars[i-2] == '/' && (i+1 == len(chars) || chars[i+1] == '/') {\n\t\t\t\treason = fmt.Sprintf(\"relative paths not allowed @%d\", i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else if r == '.' {\n\t\t\tif chars[i-1] == '/' && (i+1 == len(chars) || chars[i+1] == '/') {\n\t\t\t\treason = fmt.Sprintf(\"relative paths not allowed @%d\", i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else if r > '\\u0000' && r <= '\\u001f' || r >= '\\u007f' && r <= '\\u009F' || r >= 0xd800 && r <= 0xf8ff || r >= 0xfff0 && r <= 0xffff {\n\t\t\treason = fmt.Sprintf(\"invalid character @%d\", i)\n\t\t\tbreak\n\t\t}\n\n\t\tlastr = r\n\t}\n\tif reason != \"\" {\n\t\treturn fmt.Errorf(\"Invalid path string \\\"\" + path + \"\\\" caused by \" + reason)\n\t}\n\treturn nil\n}", "func (o IopingSpecVolumeVolumeSourceGlusterfsPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceGlusterfs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *mountPoint) Path() string {\n\tif m.Volume != nil {\n\t\treturn m.Volume.Path()\n\t}\n\n\treturn m.Source\n}", "func NewFs(client *api.Client) (*fs, nodefs.Node) {\n\tdefaultfs := pathfs.NewDefaultFileSystem() // Returns ENOSYS by default\n\treadonlyfs := pathfs.NewReadonlyFileSystem(defaultfs) // R/W calls return EPERM\n\n\tkwfs := &fs{readonlyfs, client}\n\tnfs := pathfs.NewPathNodeFs(kwfs, nil)\n\tnfs.SetDebug(true)\n\treturn kwfs, nfs.Root()\n}", "func Path(value string) string {\n\treturn filepath.Dir(value)\n}", "func (r *Repository) FileSystem(at vcs.CommitID) (vfs.FileSystem, error) {\n\tr.editLock.RLock()\n\tdefer r.editLock.RUnlock()\n\n\tc, err := r.getCommit(at)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer c.Free()\n\n\ttree, err := c.Tree()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &gitFSLibGit2{r.Dir, c.Id(), at, tree, r.u, &r.editLock}, nil\n}", "func (d *Fs) getPath(key string) (fPath string) {\n\tfPath = d.basePath\n\trunes := []rune(key)\n\tif len(key) > 4 {\n\t\tfPath = filepath.Join(fPath, string(runes[0:2]), string(runes[2:4]))\n\t}\n\treturn\n}", "func (d *driver) fullPath(path string) string {\n\treturn _path.Join(\"/ipfs\", d.roothash, path)\n}", "func (d *Directory) Path() string {\n\telems := []string{d.name}\n\n\tdir, _ := d.Parent().(*Directory)\n\n\tfor dir != nil {\n\t\telems = append([]string{dir.name}, elems...)\n\t\tdir, _ = dir.Parent().(*Directory)\n\t}\n\n\treturn filepath.Join(elems...)\n}", "func (pool *PackagePool) FullPath(path string) string {\n\treturn filepath.Join(pool.rootPath, path)\n}", "func (d *MinioDriver) Path(r volume.Request) volume.Response {\n\td.m.RLock()\n\tdefer d.m.RUnlock()\n\n\tv, exists := d.volumes[r.Name]\n\tif !exists {\n\t\treturn volumeResp(\"\", \"\", nil, capability, newErrVolNotFound(r.Name).Error())\n\t}\n\treturn volumeResp(v.mountpoint, r.Name, nil, capability, \"\")\n}", "func (r Ref) AbsPath(rootDir string) string {\n\tpath := filepath.Join(rootDir, r.GetPath())\n\tpath, _ = filepath.Abs(path)\n\tpath = filepath.ToSlash(path)\n\treturn path\n}", "func GetAbsPath(path string) string {\n\tif path != \"\" && path[0] == '/' {\n\t\treturn path\n\t}\n\treturn filepath.Join(*rootPath, path)\n}", "func (r *RelativePath) Apply(path string) *RelativePath {\n\t// absolute path?\n\tif strings.HasPrefix(path, \"/\") {\n\t\t// same root?\n\t\tif !strings.HasPrefix(path, r.RootPath()) {\n\t\t\t// if not: return copy of r without applying\n\t\t\treturn CreatePath(r.RootPath(), r.SubPath())\n\t\t}\n\t\t// otherwise set new subpath\n\t\trelPath := CreatePathRoot(path)\n\t\trelPath.limit = r.limit\n\t\treturn relPath\n\t}\n\t// relative path simply replaces the sub path\n\trelPath := CreatePath(r.RootPath(), path)\n\treturn relPath\n}", "func TryOpen(path string) *os.File {\n\tvar f *os.File\n\tf, err := os.Open(fmt.Sprintf(\"../%s\", path))\n\tif err != nil {\n\t\tf, err = os.Open(path)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn f\n\n\t}\n\treturn f\n\n}", "func (o IopingSpecVolumeVolumeSourceDownwardAPIItemsOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceDownwardAPIItems) string { return v.Path }).(pulumi.StringOutput)\n}", "func getDriveFile(path string) (*drive.File, error) {\n\tparent, err := getFileById(\"root\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get Drive root directory: %v\", err)\n\t}\n\n\tdirs := strings.Split(path, \"/\")\n\t// Walk through the directories in the path in turn.\n\tfor _, dir := range dirs {\n\t\tif dir == \"\" {\n\t\t\t// The first string in the split is \"\" if the\n\t\t\t// path starts with a '/'.\n\t\t\tcontinue\n\t\t}\n\n\t\tquery := fmt.Sprintf(\"title='%s' and '%s' in parents and trashed=false\",\n\t\t\tdir, parent.Id)\n\t\tfiles := runDriveQuery(query)\n\n\t\tif len(files) == 0 {\n\t\t\treturn nil, fileNotFoundError{\n\t\t\t\tpath: path,\n\t\t\t}\n\t\t} else if len(files) > 1 {\n\t\t\treturn nil, fmt.Errorf(\"%s: multiple files found\", path)\n\t\t} else {\n\t\t\tparent = files[0]\n\t\t}\n\t}\n\treturn parent, nil\n}", "func (fs osFS) resolve(path string) string {\n\t// Clean the path so that it cannot possibly begin with ../.\n\t// If it did, the result of filepath.Join would be outside the\n\t// tree rooted at root. We probably won't ever see a path\n\t// with .. in it, but be safe anyway.\n\tpath = pathpkg.Clean(\"/\" + path)\n\n\treturn filepath.Join(string(fs.root), path)\n}", "func RerootPath(p string, relto string) (string, error) {\n\tvar err error\n\tp, err = Homeopathy(p)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tp = os.ExpandEnv(p)\n\tif !path.IsAbs(p) {\n\t\tp = path.Join(relto, p)\n\t}\n\tp = path.Clean(p)\n\treturn p, nil\n}", "func Path(relPath string) string {\n\tif filepath.IsAbs(relPath) {\n\t\treturn relPath\n\t}\n\n\treturn filepath.Join(basepath, relPath)\n}", "func (f File) Path() string {\n\treturn string(f)\n}", "func (cfp *FsPool) GetPath(fileIndex int64) string {\n\treturn cfp.diskPath(cfp.GetRelativePath(fileIndex))\n}", "func NewChrootFs(fs afero.Fs, root string) *ChrootFs {\n\tif !filepath.IsAbs(root) {\n\t\tvar err error\n\t\troot, err = filepath.Abs(root)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn &ChrootFs{fs: fs, root: root}\n}", "func (o IopingSpecVolumeVolumeSourceCephfsPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceCephfs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func expandPath(path string) (string, error) {\n\tif len(path) == 0 {\n\t\treturn \"\", nil\n\t}\n\tif path[0] == '~' && (len(path) == 1 || os.IsPathSeparator(path[1])) {\n\t\tusr, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"Failed to get the home directory of the user\")\n\t\t}\n\t\tpath = filepath.Join(usr.HomeDir, path[1:])\n\t}\n\n\tvar err error\n\tpath, err = filepath.Abs(path)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Failed to generate absolute path\")\n\t}\n\treturn path, nil\n}", "func rootDir(path string) string {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn filepath.Join(`c:\\`, path)\n\t}\n\treturn filepath.Join(\"/\", path)\n}", "func (l *Local) FullPath(path string) string {\n\t// append the given path to the base path\n\treturn filepath.Join(l.basePath, path)\n}", "func (o FioSpecVolumeVolumeSourceHostPathPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceHostPath) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *Mounter) GetRootPath(mountPath string) (string, error) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tfor _, v := range m.mounts {\n\t\tfor _, p := range v.Mountpoint {\n\t\t\tif p.Path == mountPath {\n\t\t\t\treturn p.Root, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", ErrEnoent\n}", "func GetMountedFilePath(inputVal string, flags uintptr) (string, error) {\n\ts := strings.Split(inputVal, \":\")\n\tif len(s) != 2 {\n\t\treturn \"\", fmt.Errorf(\"%s: Usage: <block device identifier>:<path>\", inputVal)\n\t}\n\n\t// s[0] can be sda or UUID.\n\tdevice, err := GetStorageDevice(s[0])\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"fn GetStorageDevice: err = %v\", err)\n\t}\n\n\tdevName := device.Name\n\tmountPath, err := MountDevice(device, flags)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to mount %s , flags=%v, err=%v\", devName, flags, err)\n\t}\n\n\tfPath := filepath.Join(mountPath, s[1])\n\treturn fPath, nil\n}", "func NewFS(path string) (*FsRepo, error) {\n\tpath, err := homedir.Expand(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &FsRepo{\n\t\tpath: path,\n\t\tconfigPath: filepath.Join(path, fsConfig),\n\t}, nil\n}", "func (f *Fs) Root() string {\n\treturn f.root\n}", "func (f *Fs) Root() string {\n\treturn f.root\n}", "func (f *Fs) Root() string {\n\treturn f.root\n}", "func (f *Fs) Root() string {\n\treturn f.root\n}", "func (f *Fs) Root() string {\n\treturn f.root\n}", "func (f *Fs) Root() string {\n\treturn f.root\n}", "func (f *Fs) Root() string {\n\treturn f.root\n}", "func EnsurePath(filepath string) error {\n\tif _, err := os.Stat(filepath); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err = MakeDirs(filepath); err != nil {\n\t\t\t\tlogger.E(\"Make path err:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.E(\"Stat path err:\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (f FinagleFmt) Path() string {\n\treturn BaseZnodePath(f.role, f.environment, f.service)\n}", "func checkPath(path string) (string, error) {\n\tpath, err := filepath.Abs(path)\n\tif err != nil {\n\t\tlog.Error(\"Failed to resolve absolute path: \", err)\n\t\treturn \"\", err\n\t}\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\tlog.Error(\"Error checking directory: \", err)\n\t\treturn \"\", err\n\t}\n\tif !fi.IsDir() {\n\t\tlog.Error(\"Path is not a directory\")\n\t\treturn \"\", errors.New(\"Not a directory: \" + path)\n\t}\n\treturn path, nil\n}", "func Open(path, bucketpath string) (*FileSystem, error) {\n\n\t// Open or create boltdb file.\n\tdb, err := bolt.Open(path, 0644, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create buckets\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\treturn bucketInit(tx, bucketpath)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// load or initialize\n\trootIno := uint64(1)\n\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\tb := newFsBucket(tx)\n\n\t\t// create the `nil` node if it doesn't exist\n\t\terr := b.InodeInit()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// load the root Ino if one is available\n\t\tdata, err := b.LoadOrSet(\"rootIno\", i2b(rootIno))\n\t\tif err == nil {\n\t\t\trootIno = b2i(data)\n\t\t}\n\t\tnode, err := b.GetInode(rootIno)\n\t\tif err != nil {\n\t\t\tnode = newInode(os.ModeDir | 0755)\n\t\t\tnode.countUp()\n\t\t\terr = b.PutInode(rootIno, node)\n\t\t}\n\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfs := &FileSystem{\n\t\tdb: db,\n\t\tbucket: bucketpath,\n\t\trootIno: rootIno,\n\t\tcwd: \"/\",\n\t}\n\n\treturn fs, nil\n}", "func (lv *LogicalVolume) Path() (string, error) {\n\tresult := new(lvsOutput)\n\tif err := run(\"lvs\", result, \"--options=lv_path\", lv.vg.name+\"/\"+lv.name); err != nil {\n\t\tif IsLogicalVolumeNotFound(err) {\n\t\t\treturn \"\", ErrLogicalVolumeNotFound\n\t\t}\n\t\tlog.Errorf(\"device path for the logical volume error: %s\", err.Error())\n\t\treturn \"\", err\n\t}\n\tfor _, report := range result.Report {\n\t\tfor _, lv := range report.Lv {\n\t\t\treturn lv.LvPath, nil\n\t\t}\n\t}\n\treturn \"\", ErrLogicalVolumeNotFound\n}", "func (f *File) Path() string {\n\treturn f.path\n}", "func (o FioSpecVolumeVolumeSourceSecretItemsOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceSecretItems) string { return v.Path }).(pulumi.StringOutput)\n}", "func (o *QtreeCollectionGetParams) SetFilesystemPath(filesystemPath *string) {\n\to.FilesystemPath = filesystemPath\n}", "func GoModRootPath(path string) (string, error) {\n\tif path == \"\" {\n\t\treturn \"\", &PathIsNotSetError{}\n\t}\n\n\tpath = filepath.Clean(path)\n\n\tfor {\n\t\tif fi, err := os.Stat(filepath.Join(path, goModFilename)); err == nil && !fi.IsDir() {\n\t\t\treturn path, nil\n\t\t}\n\n\t\td := filepath.Dir(path)\n\t\tif d == path {\n\t\t\tbreak\n\t\t}\n\n\t\tpath = d\n\t}\n\n\treturn \"\", nil\n}", "func (r *RelativePath) FullPath() string {\n\treturn \"/\" + strings.Join(r.stack, \"/\")\n}", "func fullPath(path string) (string, error) {\n\tpath = strings.Replace(path, \"~\", os.Getenv(\"HOME\"), 1)\n\n\treturn filepath.Abs(path)\n}", "func (pool *PackagePool) Path(filename string, hashMD5 string) (string, error) {\n\trelative, err := pool.RelativePath(filename, hashMD5)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(pool.rootPath, relative), nil\n}", "func (f *File) Path() string {\n\treturn \"/\" + f.key\n}", "func (c *Driver) MountPath(do storage.DriverOptions) (string, error) {\n\tvolName, err := c.internalName(do.Volume.Name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(c.mountpath, do.Volume.Params[\"pool\"], volName), nil\n}", "func (f *FileSystem) Root() (fs.Node, error) {\n\tf.logger.Debugf(\"Root() request\\n\")\n\n\troot, err := f.get(nil, 0)\n\tif err != nil {\n\t\tf.logger.Printf(\"Root failed: %v\\n\", err)\n\t\treturn nil, fuse.EIO\n\t}\n\n\taccount, err := f.putio.Account.Info(nil)\n\tif err != nil {\n\t\tf.logger.Debugf(\"Fetching account info failed: %v\\n\", err)\n\t\treturn nil, fuse.EIO\n\t}\n\tf.account = account\n\n\treturn &Dir{\n\t\tfs: f,\n\t\tFile: &root,\n\t}, nil\n}", "func (c *Config) StoragePath() string {\n\tif c.options.StoragePath == \"\" {\n\t\tconst dirName = \"\"\n\n\t\tstorageDir := fs.FindDir(fs.StoragePaths)\n\t\tif fs.PathWritable(storageDir) && !c.ReadOnly() {\n\t\t\treturn storageDir\n\t\t}\n\t\t// Use .esp in home directory?\n\t\tif usr, _ := user.Current(); usr.HomeDir != \"\" {\n\t\t\tp := fs.Abs(filepath.Join(usr.HomeDir, fs.HiddenPath, dirName))\n\t\t\tif fs.PathWritable(p) || c.ReadOnly() {\n\t\t\t\treturn p\n\t\t\t}\n\t\t}\n\n\t\t// Fallback directory in case nothing else works.\n\t\tif c.ReadOnly() {\n\t\t\treturn fs.Abs(filepath.Join(fs.HiddenPath, dirName))\n\t\t}\n\n\t\treturn \"\"\n\t}\n\n\treturn fs.Abs(c.options.StoragePath)\n}", "func (o IopingSpecVolumeVolumeSourceHostPathOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceHostPath) string { return v.Path }).(pulumi.StringOutput)\n}", "func (r *Repository) Path(id digest.Digest) (dir, path string) {\n\tdir = filepath.Join(r.Root, id.Hex()[:2])\n\treturn dir, filepath.Join(dir, id.Hex()[2:])\n}" ]
[ "0.57531434", "0.5277183", "0.51853925", "0.51646703", "0.5140813", "0.5072053", "0.5021119", "0.5012564", "0.5010159", "0.50050765", "0.49880546", "0.49860793", "0.49815685", "0.4975883", "0.49581364", "0.4956426", "0.49397066", "0.4935071", "0.49024147", "0.4882562", "0.48779637", "0.48626357", "0.48592323", "0.48568752", "0.48288652", "0.48199412", "0.48123842", "0.48119944", "0.48061872", "0.48007455", "0.47833818", "0.47673666", "0.4766713", "0.47667128", "0.47663113", "0.4761962", "0.47600186", "0.4755787", "0.47496322", "0.47458014", "0.4722035", "0.47160313", "0.47143972", "0.47110257", "0.47081292", "0.4694353", "0.46912682", "0.46864948", "0.4682677", "0.46713698", "0.4670214", "0.46548748", "0.4650633", "0.46477377", "0.46399483", "0.46396923", "0.46354225", "0.4632717", "0.46260032", "0.46249706", "0.46178734", "0.461247", "0.46074098", "0.45960614", "0.45946568", "0.45939636", "0.45927933", "0.45901224", "0.45884138", "0.45882618", "0.45850113", "0.45848683", "0.4583642", "0.458109", "0.45561174", "0.45540208", "0.45540208", "0.45540208", "0.45540208", "0.45540208", "0.45540208", "0.45540208", "0.45458794", "0.45452064", "0.45395574", "0.45393252", "0.45355037", "0.45346746", "0.45246232", "0.45233643", "0.45116708", "0.45108375", "0.45099953", "0.45089048", "0.45064914", "0.4496942", "0.4496602", "0.4493641", "0.44934145", "0.44897318" ]
0.75748575
0
New creates a new deque
func New[T any]() *Deque[T] { dq := &Deque[T]{ pool: newPool[T](), segs: make([]*Segment[T], 0), } return dq }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New() *Deque {\n\tresult := new(Deque)\n\tresult.blocks = [][]interface{}{make([]interface{}, blockSize)}\n\tresult.right = result.blocks[0]\n\tresult.left = result.blocks[0]\n\treturn result\n}", "func New() Deque {\n\treturn Deque{}\n}", "func New() *Deque {\n\td := &Deque{}\n\t// create sentinal nodes\n\thn := &node{}\n\td.head = hn\n\td.tail = hn\n\n\treturn d\n}", "func NewDeque() *Deque {\n\treturn &Deque{}\n}", "func NewDeque(cap int) *Deque {\n\tq := new(Deque)\n\tq.values = make([]interface{}, cap, cap)\n\tq.front = 0\n\tq.back = 0\n\tq.size = 0\n\tq.endItr = new(DequeIterator)\n\tq.endItr.index = -1\n\tq.endItr.deque = q\n\treturn q\n}", "func NewDeque(v ...Value) *Deque {\n\treturn &Deque{\n\t\thead: NewList(v...),\n\t\ttail: EmptyList,\n\t}\n}", "func newQueue() *Queue {\n\tl := list.New()\n\treturn &Queue{Elements: l}\n}", "func new(size int) queue {\n\treturn queue{\n\t\tfront: -1,\n\t\trear: -1,\n\t\tsize: size,\n\t\tvalue: make([]int, size),\n\t}\n}", "func New() Queue {\n\treturn Queue{list: linkedlist.New()}\n}", "func NewQueue() *Queue {\n return &Queue{member: make([]interface{}, 0)}\n}", "func Constructor(k int) MyCircularDeque {\n\tq := MyCircularDeque{}\n\tq.l = list.New()\n\tq.cap = k\n\tq.len = 0\n\treturn q\n}", "func Constructor(k int) MyCircularDeque {\n return MyCircularDeque {\n head : 0,\n tail : 0,\n capacity : k + 1,\n data : make([]int, k + 1),\n }\n}", "func newQueue(size int) metricQueue {\n\treturn metricQueue{elt: make([]MetricElt, size), start: 0, currentSize: 0, size: size}\n}", "func New() *queue {\n\treturn &queue{\n\t\titems: make([]item, DefaultCapacity),\n\t\tcapacity: DefaultCapacity,\n\t}\n}", "func New(hint int) *Queue {\n\treturn &Queue{\n\t\titems: make([]interface{}, 0, hint),\n\t}\n}", "func Constructor(k int) MyCircularDeque {\n\thNode := &Node{}\n\ttNode := &Node{}\n\thNode.next = tNode\n\ttNode.prev = hNode\n\tdeque := MyCircularDeque{k, 0, hNode, tNode}\n\treturn deque\n}", "func Constructor(k int) MyCircularDeque {\n\treturn MyCircularDeque{\n\t\tsize: k,\n\t\tqueue: make([]int, k),\n\t}\n}", "func New[T any]() *Queue[T] {\n\tnode := newNode[T]()\n\treturn &Queue[T]{\n\t\tTx: Tx[T]{\n\t\t\ttail: node,\n\t\t\tmu: chanmutex.NewUnlocked(),\n\t\t},\n\t\tRx: Rx[T]{head: node},\n\t}\n}", "func Linked() Queue { return new(linkedQueue) }", "func Constructor(k int) MyCircularDeque {\n\treturn MyCircularDeque{Val: make([]int, 0, k), Size: k}\n}", "func Constructor(k int) MyCircularDeque {\n\treturn MyCircularDeque{\n\t\thead: nil,\n\t\ttail: nil,\n\t\tsize: k,\n\t\tlen: 0,\n\t}\n}", "func New(size int) *FIFO {\n\treturn &FIFO{\n\t\tcache: make(Map, size),\n\t\tq: list.New(),\n\t\tsize: size,\n\t}\n\n}", "func New() *Prque {\n\treturn &Prque{newSstack()}\n}", "func New() *Prque {\n\treturn &Prque{newSstack()}\n}", "func NewDequeuer(sub *pubsub.Subscription) (*D, error) {\n\t// Create internal channel\n\tpsChan := make(chan []byte, 65535)\n\n\t// Create D\n\td := &D{\n\t\tsub: sub,\n\t\tpsChan: psChan,\n\t}\n\treturn d, nil\n}", "func Constructor() MyQueue {\n\treturn Myqueue{list: listNew()}\n}", "func Constructor(k int) MyCircularDeque {\n\tres := MyCircularDeque{\n\t\tdata: make([]int, k+1, k+1),\n\t\tfront: 0,\n\t\tend: 0,\n\t}\n\treturn res\n}", "func Constructor(k int) MyCircularDeque {\n\ts := new(Node)\n\ts.Pre, s.Next = s, s\n\treturn MyCircularDeque{s, s, 0, k}\n}", "func (d *Deque) Reset() {\n\t*d = *New()\n}", "func New() *Queue {\r\n\treturn &Queue{\r\n\t\tdata: []int{},\r\n\t}\r\n}", "func New() *Queue {\n\tq := new(Queue)\n\tq.length = 0\n\tq.s1 = stack.New()\n\tq.s2 = stack.New()\n\n\treturn q\n}", "func New() *Queue {\r\n\treturn &Queue{nil,nil,0}\r\n}", "func New() *Dqueue {\n\treturn &Dqueue{\n\t\tdqueue: &doublelinkedlist.DoubleLinkedList{},\n\t}\n}", "func Constructor(k int) MyCircularDeque {\n\treturn MyCircularDeque{\n\t\tfront: 0,\n\t\trear: 0,\n\t\tcapacity: k + 1,\n\t\tdata: make([]int, k+1, k+1),\n\t}\n}", "func ConstructorQuene() MyQueue {\n\treturn MyQueue{}\n}", "func New() *Queue {\n\titems := []*item.Item{}\n\tlock := &sync.Mutex{}\n\treturn &Queue{items, lock}\n}", "func NewQueue(size int) *Queue {\r\n\treturn &Queue{\r\n\t\tnodes: make([]*Cust, size),\r\n\t\tsize: size,\r\n\t}\r\n}", "func New() Queue {\n\tc := make(chan uint16, size)\n\treturn Queue(c)\n}", "func newRingBuf(size int) *CircularQueue {\n\tvar buf = new(CircularQueue)\n\tbuf.Make(size)\n\tglog.Info(\"maximum backups: \" + strconv.Itoa(size))\n\treturn buf\n}", "func NewQueue() Queue{\n\treturn Queue{values: make([]*unsafe.Pointer,50), end: 0,}\n}", "func New(callback func(interface{}), duration time.Duration) *Queue {\r\n\treturn &Queue{\r\n\t\tm: make(map[interface{}]*element),\r\n\t\tduration: duration,\r\n\t\tcb: callback,\r\n\t}\r\n}", "func NewQueue(newNode *node.Node) *Queue {\n\tq := Queue{size: 0, final: newNode}\n\treturn &q\n}", "func New() *Queue {\n\treturn &Queue{nil, nil, 0}\n}", "func New() *Queue {\n\treturn &Queue{nil, nil, 0}\n}", "func New() *Queue {\n\tq := Queue{}\n\tq.cv = sync.NewCond(&q.mtx)\n\treturn &q\n}", "func New() *Queue {\n\treturn &Queue{\n\t\tidleCh: make(chan interface{}),\n\t\tclosed: false,\n\t}\n}", "func NewQueue() *QueueSlice {\n\treturn &QueueSlice{}\n}", "func newQueueBuffer(limit uint64) *queueBuffer {\n\treturn &queueBuffer{\n\t\tfirst: nil,\n\t\tlast: nil,\n\t\tdepth: 0,\n\t\tlimit: limit,\n\t\tunlimited: (limit == 0),\n\t\tlock: sync.Mutex{},\n\t}\n}", "func Constructor(k int) MyCircularQueue {\n return MyCircularQueue{Size: k, Items: make([]int, k), HeadIndex: -1, TailIndex: -1}\n}", "func Constructor() MyQueue {\n\treturn MyQueue{sIn: newStack(), sOut: newStack()}\n}", "func New(dir string) (*Queue, error) {\n\tentries, err := readKeys(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar current int\n\tif len(entries) > 0 {\n\t\tcurrent = entries[len(entries)-1]\n\t}\n\treturn &Queue{\n\t\tdir: dir,\n\t\tentries: entries,\n\t\tcurrent: current,\n\t}, nil\n}", "func Constructor() MyQueue {\n\treturn MyQueue{stack: NewStack()}\n}", "func Constructor() MyQueue {\n\treturn MyQueue{}\n}", "func Constructor() MyQueue {\n\treturn MyQueue{}\n}", "func New(threads, length int) *Queue {\n\treturn NewWithWriter(threads, length, stderrWriter)\n}", "func NewQueue() *Queue {\n\treturn &Queue{\n\t\titems: []Lit{},\n\t}\n}", "func Constructor() MyQueue {\n return MyQueue{q: []int{}}\n}", "func newCQT(sz, maxSz int) *cQT {\n\tif sz <= 0 || uint32(sz)&(uint32(sz)-1) != 0 ||\n\t\tuint32(maxSz)&(uint32(maxSz)-1) != 0 ||\n\t\tmaxSz < sz {\n\t\tpanic(\"Invalid Q size\")\n\t}\n\tcq := &cQT{\n\t\tsz: uint32(sz), maxSz: uint32(maxSz),\n\t\tm: uint32(sz) - 1,\n\t\ts: 0, e: 0,\n\t}\n\tcq.b = make([]T, sz)\n\treturn cq\n}", "func Constructor(capacity int) MyCircularQueue {\n\tdummyHead, dummyTail := NewNode(0), NewNode(0)\n\tdummyHead.Next = dummyTail\n\tdummyTail.Pre = dummyHead\n\treturn MyCircularQueue{dummyHead, dummyTail, 0, capacity}\n}", "func NewQueue() Queue {\r\n\tvar empty []int\r\n\treturn Queue{empty, len(empty)}\r\n}", "func NewQueue() *queue {\n q := new(queue)\n q.head = new(task)\n q.tail = q.head\n\treturn q\n}", "func NewQueue() *Queue {\n\tqueue := &Queue{\n\t\tcontents: make([]interface{}, 1),\n\t\tstart: -1,\n\t\tend: -1,\n\t\tlength: 0,\n\t}\n\n\treturn queue\n}", "func NewQueue(cap int) *Queue {\n\treturn &Queue{\n\t\tnodes: make([]*Node, cap),\n\t\tcap: cap,\n\t\tlength: 0,\n\t\thead: 0,\n\t\ttail: 0,\n\t}\n}", "func NewQueue() *Queue {\n\treturn &Queue{\n\t\telements: list.New(),\n\t}\n}", "func NewQueue() *Queue {\n\treturn &Queue{\n\t\telements: list.New(),\n\t}\n}", "func NewQueue() Queue {\n\treturn Queue{}\n}", "func Constructor() MyQueue {\n\treturn MyQueue{\n\t\tin: New(),\n\t\tout: New(),\n\t}\n}", "func NewQueue() *Queue {\n\tstorageListener := storage.NewListener()\n\tw := window.New(storageListener, 1, time.Microsecond)\n\tgo w.Exec()\n\treturn &Queue{\n\t\tdata: map[int][]byte{},\n\t\tfront: -1,\n\t\tback: 0,\n\t\tstorageW: window.New(storageListener, 64, 500*time.Nanosecond),\n\t}\n}", "func NewQueue(allowDups bool) *Queue {\n\treturn &Queue{\n\t\thead: nil,\n\t\ttail: nil,\n\t\tlength: 0,\n\t\tindex: hashtable.NewLinearHash(),\n\t\tlock: new(sync.Mutex),\n\t\tallowDups: allowDups,\n\t}\n}", "func New(cfg config.Queue, n notifier) *Queue {\n\tq := &Queue{\n\t\taddCh: make(chan struct{}, cfg.QueueSize),\n\t\tpopCh: make(chan struct{}, cfg.GoRoutinesSize),\n\t\taddMessage: make(chan entity.NotifierMessage, 1),\n\t\tpopMessage: make(chan entity.NotifierMessage, 1),\n\t\tnotifier: n,\n\t}\n\n\tgo q.pop()\n\tgo q.add()\n\n\treturn q\n}", "func MyQueueConstructor() MyQueue {\n\treturn MyQueue{}\n}", "func Make /*[T algo.Any]*/ () *Queue /*[T]*/ {\n\treturn new(Queue)\n}", "func Constructor(k int) MyCircularQueue {\n return MyCircularQueue{vals: make([]int, k), head: 0, tail: 0, n: k, l: 0 }\n}", "func New(maxSize int, dropBehavior DropBehavior) *Queue {\n\treturn &Queue{\n\t\tmaxSize: maxSize,\n\t\tdropBehavior: dropBehavior,\n\t}\n}", "func New(capacity int) (b *Ring) {\n\treturn &Ring{\n\t\tbuf: make([]interface{}, capacity),\n\t\thead: -1,\n\t}\n}", "func New(db *bolt.DB, bucket []byte, memQueueSize, writeBufSize int) (wq queue.WaitQueue, err error) {\n\tq, err := NewDiskQueue(db, bucket, memQueueSize, writeBufSize)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn queue.WithChannel(q), nil\n}", "func (q *baseCircularFifoQueue) Push(n interface{}) {\n\tif q.head == q.tail && q.count > 0 {\n\t\tLold := len(q.nodes) // old capacity\n\t\tLnew := q.fnExtendCap(Lold) // new capacity\n\t\t/*\n\t\t\tif Lnew < Lold {\n\t\t\t\tpanic(fmt.Sprintf(\"fnExtendCap(%d) -> %d : new cap must be greater the old cap!\", Lold, Lnew))\n\t\t\t}\n\t\t*/\n\t\tnodes := make([]interface{}, Lnew)\n\t\tcopy(nodes, q.nodes[q.head:])\n\t\tcopy(nodes[Lold-q.head:], q.nodes[:q.head])\n\t\tq.head = 0\n\t\tq.tail = Lold\n\t\tq.nodes = nodes\n\t}\n\tq.nodes[q.tail] = n\n\tq.tail = (q.tail + 1) % len(q.nodes)\n\tq.count++\n}", "func newQueryQueue() *queryQueue {\n\tq := &queryQueue{\n\t\tqueue: make(queryPQ, 0),\n\t}\n\theap.Init(&q.queue)\n\treturn q\n}", "func New(quantum int) bqueue.T {\n\tq := &T{writers: make(map[bqueue.ID]*writer), quantum: quantum}\n\tq.cond = sync.NewCond(&q.mutex)\n\treturn q\n}", "func NewQueue(cap int) Queue {\n\treturn &queue{\n\t\tcap: cap,\n\t\thead: -1,\n\t\tdata: make([]interface{}, cap),\n\t\tlimit: int(^uint(0) >> 1), // max int\n\t}\n}", "func New() *ItemQueue {\n\treturn &ItemQueue{items: []Item{}}\n}", "func NewQueue() *Queue {\n\thead := queueitem{next: nil, v: nil} // allocate a free item\n\treturn &Queue{\n\t\ttail: unsafe.Pointer(&head), // both head and tail points\n\t\thead: unsafe.Pointer(&head), // to the free item\n\t}\n}", "func New(opts Options) (*Queue, error) {\n\tif opts.HardLimit <= 0 || opts.HardLimit < opts.SoftQuota {\n\t\treturn nil, errHardLimit\n\t}\n\tif opts.BurstCredit < 0 {\n\t\treturn nil, errBurstCredit\n\t}\n\tif opts.SoftQuota <= 0 {\n\t\topts.SoftQuota = opts.HardLimit\n\t}\n\tif opts.BurstCredit == 0 {\n\t\topts.BurstCredit = float64(opts.SoftQuota)\n\t}\n\tsentinel := new(entry)\n\tq := &Queue{\n\t\tsoftQuota: opts.SoftQuota,\n\t\thardLimit: opts.HardLimit,\n\t\tcredit: opts.BurstCredit,\n\t\tback: sentinel,\n\t\tfront: sentinel,\n\t}\n\tq.nempty = sync.NewCond(&q.mu)\n\treturn q, nil\n}", "func New(capacity int32) *FreeArray {\n\titems := make([]node, capacity)\n\tfor i := range items {\n\t\titems[i] = node{\n\t\t\tnext: int32(i + 1),\n\t\t\tprev: int32(i - 1),\n\t\t\tdata: nil,\n\t\t}\n\t}\n\titems[0].prev = -1\n\titems[capacity-1].next = -1\n\treturn &FreeArray{\n\t\titems: items,\n\t\tfreehead: 0,\n\t\tbusyhead: -1,\n\t}\n}", "func (s *StringQueue) New() *StringQueue {\n\ts.items = []string{}\n\treturn s\n}", "func NewDisque(servers []string, cycle int) *Disque {\n\treturn &Disque{\n\t\tservers: servers,\n\t\tcycle: cycle,\n\t\tnodes: make(map[string]string),\n\t\tstats: make(map[string]int),\n\t}\n}", "func Constructor1(k int) MyCircularDeque1 {\n\thead := Node{\n\t\tVal: -1,\n\t\tNext: nil,\n\t\tPre: nil,\n\t}\n\ttail := Node{\n\t\tVal: -1,\n\t\tNext: nil,\n\t\tPre: nil,\n\t}\n\thead.Next = &tail\n\ttail.Pre = &head\n\n\treturn MyCircularDeque1{\n\t\thead: &head,\n\t\ttail: &tail,\n\t\tlen: 0,\n\t\tcap: k,\n\t}\n}", "func newURLQueue(size int) *urlQueue {\n\treturn &urlQueue{\n\t\tnodes: make([]*URLEntry, size),\n\t\tsize: size,\n\t}\n}", "func NewQueue() *Queue {\n\treturn &Queue{nil, nil, 0}\n}", "func Constructor() MyStack {\n\treturn MyStack{queue: list.New()}\n}", "func main() {\n\tcircularDeque := Constructor(3) // 设置容量大小为3\n\tcircularDeque.InsertLast(1) // 返回 true\n\tcircularDeque.InsertLast(2) // 返回 true\n\tcircularDeque.InsertFront(3) // 返回 true\n\t// 已经满了,返回 false\n\tfmt.Println(circularDeque.InsertFront(4))\n\t// 返回 2\n\tfmt.Println(circularDeque.GetRear())\n\tfmt.Println(circularDeque)\n\tcircularDeque.IsFull() // 返回 true\n\tcircularDeque.DeleteLast() // 返回 true\n\tcircularDeque.InsertFront(4) // 返回 true\n\tcircularDeque.GetFront() // 返回 4\n}", "func New(name string, c config.Config) *Queue {\n\treturn &Queue{\n\t\tname: name,\n\t\tconf: c,\n\t}\n}", "func NewQueue(size int) *Queue {\n\treturn &Queue{\n\t\tdata: make([]interface{}, size),\n\t\thead: -1, // empty list\n\t\ttail: -1, // start inserting at position 0\n\t}\n}", "func New(\n\tlogger *zap.SugaredLogger,\n\tflushFunc, closeFunc func(),\n\topts Options,\n) *Queue {\n\tif flushFunc == nil {\n\t\tflushFunc = func() {}\n\t}\n\tif closeFunc == nil {\n\t\tcloseFunc = func() {}\n\t}\n\tif opts.Rate == 0 {\n\t\topts.Rate = 5 * time.Second\n\t}\n\n\tvar counter = int32(0)\n\treturn &Queue{\n\t\tl: logger,\n\n\t\tcloseFunc: closeFunc,\n\t\tflushFunc: flushFunc,\n\n\t\tpendingC: make(chan func(), 3*opts.BatchSize),\n\t\tpending: &counter,\n\t\trate: opts.Rate,\n\t\tbatchSize: opts.BatchSize,\n\n\t\tstopC: make(chan bool, 1),\n\t\tstopped: false,\n\t}\n}", "func BenchmarkDeque_3(b *testing.B) {\r\n\tfor i := 0; i < b.N; i++ {\r\n\t\tvar d = &Deque{}\r\n\t\tde(d)\r\n\t}\r\n}", "func CreateNew(val interface{}) (*Queue, error) {\r\n\treturn &Queue{\r\n\t\tQueueList: []interface{}{val},\r\n\t}, nil\r\n}", "func NewQueue(size int) Queue {\n\treturn make(Queue, 0, size)\n}", "func NewQueue(size int) *Queue {\n\treturn &Queue{\n\t\tnodes: make([]Any, size),\n\t\tsize: size,\n\t}\n}", "func newStack() *stack {\n\treturn &stack{\n\t\tns: make([]*Node, 0),\n\t}\n}", "func NewBaseCircularFifoQueue(initCap int, fnExtendCap ExtendCapFunc) Queue {\n\tif initCap <= 0 {\n\t\tpanic(\"initCap must be > 0\")\n\t}\n\treturn &baseCircularFifoQueue{\n\t\tnodes: make([]interface{}, initCap),\n\t\tfnExtendCap: fnExtendCap,\n\t}\n}" ]
[ "0.7735765", "0.76372993", "0.7620072", "0.7398418", "0.70435524", "0.6839348", "0.681317", "0.66848385", "0.64489764", "0.64214355", "0.641228", "0.63644093", "0.6344399", "0.63280785", "0.63015765", "0.62999356", "0.627769", "0.6261868", "0.62428474", "0.62241197", "0.61820483", "0.61586744", "0.61432576", "0.61432576", "0.6108996", "0.60852534", "0.60702676", "0.60667497", "0.60298866", "0.60258317", "0.6020574", "0.60161525", "0.6015991", "0.60035646", "0.5941654", "0.5920699", "0.5918647", "0.59127367", "0.5893139", "0.5885245", "0.588512", "0.58620137", "0.5853257", "0.5853257", "0.58208805", "0.581156", "0.57983243", "0.57905114", "0.5790185", "0.5789718", "0.5776254", "0.57128066", "0.56907326", "0.56907326", "0.5688156", "0.5676876", "0.5653245", "0.5645843", "0.5636501", "0.5628463", "0.56272715", "0.56248", "0.5612161", "0.55967665", "0.55967665", "0.55921733", "0.55670446", "0.55473286", "0.5541365", "0.55403394", "0.5536165", "0.55280566", "0.552511", "0.55177593", "0.5516297", "0.5514121", "0.549376", "0.5492835", "0.5474269", "0.5474004", "0.5455008", "0.5446812", "0.5438339", "0.5432817", "0.5422883", "0.54163194", "0.5396322", "0.5392942", "0.53920436", "0.53919923", "0.539064", "0.53893995", "0.538604", "0.53785545", "0.53751236", "0.536609", "0.53556067", "0.53517205", "0.53502905", "0.53480285" ]
0.7611314
3
Size returns the amount of values in the deque
func (d *Deque[T]) Size() int { return d.size }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *Deque) size() int {\n\treturn d.count\n}", "func (q *Deque) Size() int {\n\treturn q.size\n}", "func (Q *Deque) Size() int {\n\treturn Q.size\n}", "func (d *Deque) Size() int {\n\tif d == nil {\n\t\treturn 0\n\t}\n\treturn d.size\n}", "func (d *Deque) Size() int {\n\tif d.IsEmpty() {\n\t\treturn 0\n\t}\n\tsize := 0\n\tif d.head != nil {\n\t\tsize++\n\t}\n\tif d.tail != nil {\n\t\tsize++\n\t}\n\tif d.child != nil {\n\t\tsize += d.child.Size()\n\t}\n\treturn size\n}", "func (d *Deque) Size() int {\n\tif d.rightIdx > d.leftIdx {\n\t\treturn (d.rightIdx-d.leftIdx)*blockSize - d.leftOff + d.rightOff\n\t} else if d.rightIdx < d.leftIdx {\n\t\treturn (len(d.blocks)-d.leftIdx+d.rightIdx)*blockSize - d.leftOff + d.rightOff\n\t} else {\n\t\treturn d.rightOff - d.leftOff\n\t}\n}", "func (q *Queue) Size() int {\n\tif q.Empty() {\n\t\treturn 0\n\t}\n\treturn (q.tail + 1) - (q.head % cap(q.data))\n}", "func (q *Queue) Size() int {\n\treturn q.Elements.Len()\n}", "func (q *PriorityQueue) Size() int {\n\treturn q.items.Cardinality()\n}", "func (q *Queue) Size() int {\n\treturn len(q.items)\n}", "func (q *queue) Size() int {\n\tq.Lock()\n\tdefer q.Unlock()\n\n\treturn q.items.Len()\n}", "func (q *SliceQueue) Size() int {\n\treturn len(q.Data)\n}", "func (d *Deque) Length() uint {\n\treturn d.length\n}", "func (q *LLQueue) Size() int {\n\tvar cnt int\n\tfor i := q.head; i != nil; i = i.next {\n\t\tcnt++\n\t}\n\treturn cnt\n}", "func(q *Queue)Size() int {\n\treturn q.rear - q.front\n}", "func (q *Queue) Size() (int) {\r\n\t\treturn q.count\r\n}", "func (e *ElementQueue) Size() int {\n\treturn len(e.elements)\n}", "func (q *SimpleQueue) Size() int64 {\n\treturn q.length\n}", "func (s *PacketDurationQueue) Size() int {\n\treturn len(s.items)\n}", "func (q *Queue) Size() int {\n\treturn q.length\n}", "func (s *FIFO) Size() int {\n\treturn s.size\n}", "func (q *arrayQueue) Size() int {\n\treturn q.listSize\n}", "func (que *Queue) Len() int {\n\treturn len(que.values)\n}", "func (q *ItemQueue) Size() int {\n\treturn len(q.items)\n}", "func (q *ItemQueue) Size() int {\n\treturn len(q.items)\n}", "func (set *Set) Size() int {\n\treturn len(set.items)\n}", "func (q *Queue /*[T]*/) Len() int {\n\treturn len(q.items)\n}", "func (h *Queue) Len() int { return len(h.slice) }", "func (p *Prque) Size() int {\n\treturn p.cont.Len()\n}", "func (p *Prque) Size() int {\n\treturn p.cont.Len()\n}", "func (q *queue) Len() int {\n\tq.lock.RLock()\n\tdefer q.lock.RUnlock()\n\tc := q.tail - q.head\n\tif c < 0 {\n\t\tc = 0\n\t}\n\n\treturn c\n}", "func (self *Queue) Size() int {\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\treturn self.length\n}", "func (q *queue) Size() int {\n\treturn q.size\n}", "func (set *SetThreadSafe) Size() int {\n\ti := 0\n\tset.Items.Range(func(k, v interface{}) bool {\n\t\ti++\n\t\treturn true\n\t})\n\treturn i\n}", "func (s *StringQueue) Size() int {\n\treturn len(s.items)\n}", "func (q *Queue) Size() int {\n\treturn q.Queue.Length\n}", "func (dq *Dqueue) Size() int {\n\treturn dq.dqueue.Size()\n}", "func (q *FileQueue) Size() int64 {\n\tsz := q.HeadIndex - q.FrontIndex\n\tif sz < 0 {\n\t\tsz = 0\n\t}\n\treturn int64(sz)\n}", "func (q *Queue) Len() int { return q.data.Len() }", "func (s *RedisQueue) Size() (int, error) {\n\tsize, err := s.r.LLen(s.Key()).Result()\n\treturn int(size), err\n}", "func (s *Sliding) Size() int {\n\treturn s.numUsed\n}", "func (m *MRUQueue) Size() int {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\treturn m.store.Len()\n}", "func (s *ItemQueue) Size() int {\n\treturn len(s.items)\n}", "func (q *PriorityQueue) Size() int {\n\treturn q.size\n}", "func (q *Stack) Size() int {\n\treturn q.Items.Size()\n}", "func (q *Queue) Size() int {\n\treturn q.size\n}", "func (q *Deque) MaxSize() int {\n\treturn cap(q.values)\n}", "func (q *Queue) Length() int{\n return len(q.queue)\n}", "func (s *ItemQueue) Size() int {\n\ts.lock.Lock()\n\tvar size = len(s.items)\n\ts.lock.Unlock()\n\treturn size\n}", "func (s *stack) Size() int {\n\tsize := 0\n\titem := s.last\n\tfor {\n\t\tif item != nil {\n\t\t\tsize++\n\t\t\titem = item.prev\n\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn size\n}", "func (q *wantConnQueue) len() int {\n\treturn len(q.head) - q.headPos + len(q.tail)\n}", "func (s *Stack[T]) Size() int {\n\treturn len(s.array)\n}", "func (q *linkedQueue) Size() int {\n\treturn q.size\n}", "func (q *Queue) Len() int {\n\tlength := 0\n\n\tfor _, current := range q.Items {\n\t\tif !current.IsReserved() {\n\t\t\tlength++\n\t\t}\n\t}\n\n\treturn length\n}", "func (list *ArrayList[T]) Size() int {\n\treturn len(list.elems)\n}", "func (h *data) Len() int { return len(h.queue) }", "func (q *Queue) Len() int {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn len(q.items)\n}", "func (q *Queue) Len() uint {\n\treturn q.size\n}", "func (q *queue) Len() int {\n\treturn len(q.slice)\n}", "func (q *Queue) Len() int {\n\tq.RLock()\n\tdefer q.RUnlock()\n\n\treturn q.size\n}", "func (s *LinkedStack) Size() int { return s.count }", "func (q *BytesQueue) Len() int {\n\treturn q.count\n}", "func (qi *Items) Len() int {\n\tqi.RLock()\n\tc := qi.Length\n\tlog.Printf(\"queue length: %d\\n\", c)\n\tqi.RUnlock()\n\treturn c\n}", "func (q *BoundedQueue) Size() int {\n\treturn int(atomic.LoadInt32(&q.size))\n}", "func (s *SliceQueue) Len() int {\n\treturn len(s.elements)\n}", "func (d *Deque) Count() int {\n\treturn d.head.Count() + d.tail.Count()\n}", "func (s *PriorityQueue) Size() int {\n\treturn len(s.pq.array)\n}", "func (q *PriorityQueue) Length() int {\n\treturn q.count\n}", "func (md MinQueue) Len() int { return len(md) }", "func (q *queue) Length() uint64 {\n\treturn q.Tail - q.Head\n}", "func (self *Queue) Size() int {\n\treturn self.size\n}", "func (q Queue) Len() int {\n\treturn len(q)\n}", "func (queue PriorityQueue) Len() int {\n\treturn queue.heap.Len()\n}", "func (this *CirCleQueue)Size() int{\n return (this.tail + this.maxSize- this.head) % this.maxSize\n}", "func (q *Queue) Len() int {\n\treturn q.length\n}", "func (q *Queue) Len() int {\n\treturn q.length\n}", "func (b *Ring) Size() int {\n\tb.lock.RLock()\n\tdefer b.lock.RUnlock()\n\treturn b.size\n}", "func (set *IntSet) Size() int {\n\treturn len(set.members)\n}", "func (s *IntSet) Size() int {\n\treturn len(s.members)\n}", "func (h *hashRing) Size() int {\n\treturn len(h.nodes)\n}", "func (d *Dam) Size() int {\n\td.mutex.RLock()\n\tl := len(d.storage)\n\td.mutex.RUnlock()\n\treturn l\n}", "func (q LinkedListQueue) Len() int {\n\treturn q.list.Len()\n}", "func (s *IntSet) Size() int {\n\treturn len(s.elem)\n}", "func (t queueStorage) Len() int {\n\treturn len(t)\n}", "func (q *UnsafeQueue64) Size() uint64 {\n\tif q.putPos >= q.getPos {\n\t\treturn q.putPos - q.getPos\n\t}\n\treturn q.capMod + (q.putPos - q.getPos)\n}", "func (r *SlidingWindow) Capacity() int {return len(r.values)}", "func (pq PriorityQueue) Len() int { return len(pq) }", "func (pq PriorityQueue) Len() int { return len(pq) }", "func (q *Queue) Len() int {\r\n\tq.mu.Lock()\r\n\tdefer q.mu.Unlock()\r\n\r\n\treturn len(q.m)\r\n}", "func (s *Set) Size() (l int) {\n\ts.mutex.RLock()\n\tl = len(s.m)\n\ts.mutex.RUnlock()\n\n\treturn\n}", "func (d Dense) Size() int {\n\treturn d.len\n}", "func (q *queue) Len() int {\n\treturn q.len\n}", "func (q *Queue) Count() int {\n\treturn q.front - q.back + 1\n}", "func (this *Queue) Len() int {\r\n\treturn this.length\r\n}", "func (q *Queue) Length() int {\n\treturn len(q.queue)\n}", "func (self *Queue)Len()int{\r\n\treturn self.list.Len()\r\n}", "func (hat *HashedArrayTree) Size() int {\n\treturn hat.size\n}", "func (queue *Queue) Length() int {\n\treturn len(queue.data)\n}", "func (s *Stack) Size() int {\n\treturn len(s.element)\n}", "func (r *RlogcHeap) Len() int { return r.queue.Len() }" ]
[ "0.8327133", "0.8314534", "0.82967895", "0.81141996", "0.8077751", "0.7836637", "0.7786763", "0.7747203", "0.77386045", "0.76841855", "0.7672367", "0.7663158", "0.75817704", "0.75733036", "0.75609314", "0.7527956", "0.74956876", "0.749503", "0.74711734", "0.7441365", "0.74146813", "0.73845625", "0.7364173", "0.73478276", "0.73478276", "0.733252", "0.73308843", "0.7328709", "0.73198503", "0.73198503", "0.731948", "0.7290738", "0.72894984", "0.72875607", "0.72663546", "0.72598106", "0.7257525", "0.7255359", "0.72532153", "0.7228764", "0.7228283", "0.7223913", "0.72120196", "0.72035986", "0.7199051", "0.71947414", "0.71945566", "0.7192486", "0.71888036", "0.7167846", "0.71616983", "0.7159161", "0.7156558", "0.71391517", "0.7120756", "0.71150655", "0.7110778", "0.71046823", "0.7101042", "0.70786905", "0.7067553", "0.70535976", "0.70499843", "0.70178103", "0.7010335", "0.70063144", "0.6993542", "0.6990811", "0.6976347", "0.6959436", "0.6958307", "0.69361526", "0.6932875", "0.6921534", "0.6919835", "0.6919835", "0.69185436", "0.6917953", "0.691555", "0.6914827", "0.69105595", "0.6900594", "0.6883397", "0.68683916", "0.68641275", "0.68611383", "0.68601584", "0.68601584", "0.68537503", "0.6852886", "0.685105", "0.6848666", "0.6846165", "0.6841779", "0.68401724", "0.6835859", "0.6834902", "0.68335044", "0.6827648", "0.6827199" ]
0.83975625
0
Empty returns true if the deque is empty,otherwise returns false.
func (d *Deque[T]) Empty() bool { return d.size == 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Deque) Empty() bool {\n\treturn q.size == 0\n}", "func (d *Deque) Empty() bool {\n\treturn d.Size() == 0\n}", "func (d *Deque) Empty() bool {\n\treturn d.leftIdx == d.rightIdx && d.leftOff == d.rightOff\n}", "func (this *MyCircularDeque) IsEmpty() bool {\n\tif this.len == 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (this *MyCircularDeque) IsEmpty() bool {\n\treturn this.length == 0\n}", "func (this *MyCircularDeque) IsEmpty() bool {\n\treturn this.Size == 0\n}", "func (this *MyCircularDeque) IsEmpty() bool {\n\treturn this.len == 0\n}", "func (this *MyCircularDeque) IsEmpty() bool {\n\treturn this.front == this.end\n}", "func (d *MyCircularDeque) IsEmpty() bool {\n\treturn len(d.Val) == 0\n}", "func (this *MyCircularDeque) IsEmpty() bool {\n\tthis.mutex.RLock()\n\tdefer this.mutex.RUnlock()\n\treturn this.rear == this.front\n}", "func (q *queue) Empty() bool {\n\treturn q.len == 0\n}", "func (q *SimpleQueue) Empty() bool {\n\treturn q.length == 0\n}", "func (d *Deque) isEmpty() bool {\n\t// assert that both first and last must be nil if one is\n\tif (d.first == nil) != (d.last == nil) {\n\t\tpanic(\"data structure irregularity\")\n\t}\n\treturn d.first == nil\n}", "func (dq *Dqueue) Empty() bool {\n\treturn dq.dqueue.Empty()\n}", "func (this *MyCircularDeque) IsEmpty() bool {\n\treturn this.head == nil\n}", "func (this *MyCircularDeque) IsEmpty() bool {\n return this.tail == this.head\n}", "func (d *Deque) IsEmpty() bool {\n\treturn d.head == nil && d.tail == nil\n}", "func (self *Queue) Empty() bool {\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\treturn self.length <= 0\n}", "func (q *Queue) Empty() bool {\n\treturn q.size == 0\n}", "func (q *Queue) Empty() bool {\n\treturn q.tail == -1 && q.head == -1\n}", "func (this *MyQueue) Empty() bool {\n\treturn this.in.Len() == 0 && this.out.Len() == 0\n}", "func (p *Prque) Empty() bool {\n\treturn p.cont.Len() == 0\n}", "func (p *Prque) Empty() bool {\n\treturn p.cont.Len() == 0\n}", "func (this *MyQueue) Empty() bool {\n\treturn len(this.q) == 0\n}", "func (this *MyQueue) Empty() bool {\n\treturn len(this.in) == 0 && len(this.out) == 0\n}", "func (q *Queue) IsEmpty() (bool) {\r\n\tif q.count == 0 {\r\n\t\treturn true\r\n\t} else {\r\n\t\treturn false\r\n\t}\r\n}", "func (self *Queue)Empty()bool{\r\n\treturn self.list.Len()==0\r\n}", "func (q *SliceQueue) IsEmpty() bool {\n\treturn len(q.Data) == 0\n}", "func (this *MyCircularQueue) IsEmpty() bool {\n\treturn this.Count == 0\n}", "func (q *MyQueue) Empty() bool {\n\treturn q.list.Len() == 0\n}", "func (q *FileQueue) IsEmpty() bool {\n\treturn q.FrontIndex >= q.HeadIndex\n}", "func (d *Deque) IsEmpty() bool {\n\treturn d.head.IsEmpty() && d.tail.IsEmpty()\n}", "func (q *Queue) IsEmpty() bool {\n\treturn q.length == 0\n}", "func (q *Queue) IsEmpty() bool {\n\treturn q.length == 0\n}", "func (this *MyCircularDeque1) IsEmpty() bool {\n\treturn this.head.Next == this.tail\n}", "func (Q *Queue) IsEmpty() bool {\n\treturn Q.size == 0\n}", "func (this *MyQueue) Empty() bool {\n\treturn len(this.Stack) == 0\n}", "func (q *MyQueue) Empty() bool {\n\treturn len(q.list) == 0\n}", "func (this *MyQueue) Empty() bool {\n return len(this.q) == 0\n}", "func (q *Queue) IsEmpty() bool {\n\treturn q.Length() < 1\n}", "func (q *queue) IsEmpty() bool {\n\treturn q.Size() == 0\n}", "func (q *Queue) IsEmpty() bool {\n\treturn q.len == 0\n}", "func(q *Queue)IsEmpty() bool {\n\treturn q.front == q.rear\n}", "func (q *PriorityQueue) Empty() bool {\n\treturn q.size == 0\n}", "func (q *Queue) IsEmpty() bool {\r\n\treturn len(q.data) == 0\r\n}", "func (q *Queue) IsEmpty() bool {\n\treturn len(*q) == 0\n\n}", "func (que *QueueUsingStack) IsEmpty() bool {\r\n\treturn que.Length() == 0\r\n}", "func (this *MyQueue) Empty() bool {\n\treturn len(this.inStack) == 0 && len(this.outStack) == 0\n}", "func (h *Queue) IsEmpty() bool {\n\tif len(h.slice) == 0 {\n\t\treturn true\n\t}\n\n\tif h.trimSet && (h.slice[0].Estimate >= h.trimValue) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *MyStack) Empty() bool {\n\treturn len(s.Q) <= 0\n}", "func (q *linkedQueue) IsEmpty() bool {\n\treturn q.size == 0\n}", "func (q *LLQueue) Empty() bool {\n\treturn q.head == nil && q.tail == nil\n}", "func (q *objQueue) empty() bool {\n\treturn q.head == q.tail\n}", "func (mcq *MyCircularQueue) IsEmpty() bool {\n\treturn mcq.length == 0\n}", "func (q *UniqueQueue) Empty() bool {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\t// \thead == tail -> empty\n\treturn q.head == q.tail\n}", "func (this *MyCircularDeque) IsFull() bool {\n\treturn this.size == this.len\n}", "func (this *MyCircularDeque) IsFull() bool {\n\treturn this.len == this.size\n}", "func (this *MyQueue) Empty() bool {\n\tif len(this.a) == 0 && len(this.b) == 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (this *MyQueue) Empty() bool {\n\treturn this.sIn.isEmpty() && this.sOut.isEmpty()\n}", "func (q *RingQueue) IsEmpty() bool {\n\treturn q.front == q.rear\n}", "func (q *arrayQueue) IsEmpty() bool {\n\treturn q.listSize == 0\n}", "func (this *MyCircularDeque) IsFull() bool {\n\treturn this.length == this.size\n}", "func (q Queue) IsEmpty() bool {\n\treturn len(q) == 0\n}", "func (this *MyCircularDeque) IsFull() bool {\n\n\treturn (this.end+1)%len(this.data) == this.front\n}", "func (this *MyQueue) Empty() bool {\n\tif len(this.inStack) == 0 && len(this.outStack) == 0 {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func (this *MyQueue) Empty() bool {\n\tif len(this.popStack) == 0 && len(this.pushStack) == 0 {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func (this *MyCircularQueue) IsEmpty() bool {\n return this.HeadIndex == -1\n}", "func (m *MRUQueue) Empty() bool {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\treturn m.store.Len() == 0\n}", "func (q Queue) IsEmpty() bool {\n\treturn q.First == nil\n}", "func (q *Queue) isEmpty() bool {\n\treturn q.Size() == 0\n}", "func (q *Queue) Empty() bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn len(q.items) == 0\n}", "func (this *MyStack) Empty() bool {\n\treturn this.queue.Len() == 0\n}", "func (d *MyCircularDeque) IsFull() bool {\n\treturn len(d.Val) == d.Size\n}", "func (this *MyQueue) Empty() bool {\n\treturn this.stack.IsEmpty()\n}", "func (this *MyCircularQueue) IsEmpty() bool {\n\tif (this.rear)%this.size == this.front%this.size {\n\t\treturn true\n\t}\n\treturn false\n}", "func (s *MyStack) Empty() bool {\n return len(s.queue1) == 0\n}", "func (q *Queue) IsEmpty() bool {\n\treturn q.list.Size() == 0\n}", "func (q *Queue) IsEmpty() bool {\n\treturn len(q.items) == 0\n}", "func (this *MyStack) Empty() bool {\n\treturn len(this.Queue) == 0\n}", "func (this *MyCircularDeque) IsFull() bool {\n\treturn this.Cap == this.Size\n}", "func (q *Queue) IsEmpty() bool {\n\tq.RLock()\n\tdefer q.RUnlock()\n\n\treturn q.size < 1\n}", "func (s *MyStack) Empty() bool {\n\treturn len(s.queue) == 0\n}", "func (this *MyCircularDeque) IsFull() bool {\n\tthis.mutex.RLock()\n\tdefer this.mutex.RUnlock()\n\treturn (this.rear+1)%this.capacity == this.front\n}", "func (this *MyCircularQueue) IsEmpty() bool {\n\treturn this.CircularQueue[this.Head] == -1\n}", "func (q *Queue) isEmpty() bool {\n\tif len(q.values) == 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (this *MyStack) Empty() bool {\n\treturn this.q.IsEmpty()\n}", "func (list *DoublyLinkedList) Empty() bool {\n\treturn list.size == 0\n}", "func (q *Queue) IsEmpty() bool {\r\n\treturn len(q.QueueList) == 0\r\n}", "func (this *MyStack) Empty() bool {\n\tif this.queueA.Len() == 0 && this.queueB.Len() == 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (this *MyCircularDeque) IsFull() bool {\n\tif this.len == this.cap {\n\t\treturn true\n\t}\n\treturn false\n}", "func (this *MyCircularQueue) IsEmpty() bool {\n return this.l == 0\n}", "func (e *ElementQueue) IsEmpty() bool {\n\treturn len(e.elements) == 0\n}", "func (this *MyCircularDeque1) IsFull() bool {\n\treturn this.len == this.cap\n}", "func (q *LinkQueue) IsEmpty() bool {\n\treturn q.size == 0\n}", "func (this *MyStack) Empty() bool {\n\treturn this.Len == 0\n}", "func (this *MyStack) Empty() bool {\n\treturn this.Len == 0\n}", "func (s *PacketDurationQueue) IsEmpty() bool {\n\treturn len(s.items) == 0\n}", "func (d *Doubly) IsEmpty() bool {\n\td.rwLock.RLock()\n\tdefer d.rwLock.RUnlock()\n\treturn d.head == nil\n}", "func (s *StringQueue) IsEmpty() bool {\n\treturn len(s.items) == 0\n}", "func (q *SignalQueue) IsEmpty() bool {\n\treturn len(q.Queue) == 0\n}" ]
[ "0.88758296", "0.8749898", "0.8610301", "0.8512436", "0.8507321", "0.85013646", "0.84951454", "0.8486105", "0.83650386", "0.8322681", "0.83145297", "0.82644045", "0.82419497", "0.82382345", "0.8200082", "0.8187246", "0.81671274", "0.81631935", "0.81266284", "0.8112796", "0.8109484", "0.8109251", "0.8109251", "0.8094721", "0.80850506", "0.8082422", "0.80597", "0.80412143", "0.80298895", "0.8021987", "0.80155176", "0.8002038", "0.8000424", "0.8000424", "0.7997231", "0.799113", "0.798581", "0.79813397", "0.796773", "0.7964953", "0.7964556", "0.795529", "0.795412", "0.7954023", "0.79383147", "0.7932746", "0.79241407", "0.7923964", "0.79094434", "0.7899327", "0.7894143", "0.7892065", "0.788191", "0.787596", "0.7858841", "0.78524977", "0.78517985", "0.78466296", "0.784273", "0.78409237", "0.7838535", "0.78340095", "0.78333586", "0.78292394", "0.78265846", "0.7814408", "0.780266", "0.7787311", "0.7786555", "0.7777659", "0.7775393", "0.77593863", "0.7755266", "0.7748057", "0.774292", "0.7738968", "0.77364224", "0.7726664", "0.77263236", "0.7722924", "0.7719695", "0.76905394", "0.7684746", "0.76814187", "0.7661162", "0.7644843", "0.76285315", "0.7627785", "0.7613075", "0.7612083", "0.7597288", "0.7578692", "0.75743574", "0.75719875", "0.7553446", "0.7553446", "0.75500274", "0.7549952", "0.7540469", "0.75338304" ]
0.8880059
0
PushFront pushed a value to the front of the deque
func (d *Deque[T]) PushFront(value T) { d.firstAvailableSegment().pushFront(value) d.size++ if d.segUsed() >= len(d.segs) { d.expand() } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Deque) PushFront(v interface{}) {\n\tif q.size == cap(q.values) {\n\t\tnewCap := 2\n\t\tif cap(q.values) > 0 {\n\t\t\tnewCap = cap(q.values) * 2\n\t\t}\n\t\tq.Resize(newCap)\n\t}\n\n\tq.front--\n\tif q.front < 0 {\n\t\tq.front = cap(q.values) - 1\n\t}\n\n\tq.values[q.front] = v\n\tq.size++\n}", "func (dq *Dqueue) PushFront(value interface{}) {\n\tdq.dqueue.Prepend(value)\n}", "func (d *Deque) PushFront(value interface{}) *Deque {\n\tfree := &dequeNode{value, d.head, d.tail}\n\tif d.IsEmpty() {\n\t\treturn &Deque{free, &Deque{}, nil}\n\t}\n\treturn &Deque{free, d, nil}\n}", "func (l *List) PushFront(v interface{}) {\r\n\tif l.first == nil {\r\n\t\t// zerovalue for bool is false\r\n\t\tl.first = &Item{data: v, parent: l, invalidated: new(bool)}\r\n\t\tl.last = l.first\r\n\t} else {\r\n\t\tformerFirst := l.first\r\n\t\tl.first = &Item{data: v, next: formerFirst, parent: l, invalidated: new(bool)}\r\n\t\tformerFirst.prev = l.first\r\n\t}\r\n\tl.length++\r\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n if this.IsFull() {\n return false\n }\n this.head = (this.head - 1 + this.capacity) % this.capacity\n this.data[this.head] = value\n return true\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tthis.front = (len(this.data) + this.front - 1) % len(this.data)\n\tthis.data[this.front] = value\n\treturn true\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.Cap == this.Size {\n\t\treturn false\n\t}\n\ts := new(Node)\n\ts.Data = value\n\ts.Next = this.First.Next\n\tthis.First.Next.Pre = s\n\n\tthis.First.Next = s\n\ts.Pre = this.First\n\tif this.Size == 0 {\n\t\tthis.Last = s\n\t}\n\tthis.Size++\n\treturn true\n}", "func (d *MyCircularDeque) InsertFront(value int) bool {\n\treturn d.Insert(value, 0)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tthis.len++\n\tthis.head = (this.head + 1) % this.size\n\tthis.queue[this.head] = value\n\treturn true\n}", "func (l *List) PushFront(v interface{}) {\n\tn := Node{Val: v, next: l.first}\n\tif l.first != nil {\n\t\tl.first.prev = &n\n\t}\n\tl.first = &n\n\tif l.last == nil {\n\t\tl.last = &n\n\t}\n}", "func (d *Deque) PushFront(data interface{}) bool {\n\tif d == nil {\n\t\treturn false\n\t}\n\t// create a new node out of the data\n\tnewNode := node{\n\t\tdata: data,\n\t\tprev: d.front,\n\t}\n\n\tif d.front != nil {\n\t\td.front.next = &newNode\n\t} else {\n\t\td.back = &newNode\n\t}\n\td.front = &newNode\n\td.size++\n\treturn true\n}", "func (l *List) PushFront(v interface{}) {\n\tnode := &Node{Val: v, next: l.head}\n\tif l.head == nil {\n\t\tl.last = node\n\t} else {\n\t\tl.head.previous = node\n\t}\n\tl.head = node\n}", "func (cq *cQT) PushFront(el T) (ok bool) {\n\tif cq.e-cq.s == cq.sz {\n\t\tif cq.sz == cq.maxSz {\n\t\t\treturn false\n\t\t}\n\t\tcq.resize(cq.sz << 1)\n\t}\n\tcq.s--\n\tcq.b[cq.s&cq.m] = el\n\treturn true\n}", "func (l *List) PushFront(value interface{}) {\n\ttemp := &node{value, nil, nil}\n\tl.Lock()\n\tif l.length == 0 {\n\t\tl.head = temp\n\t\tl.tail = temp\n\t} else {\n\t\ttemp.next = l.head\n\t\tl.head = temp\n\t}\n\tl.length++\n\tl.Unlock()\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.len == this.cap {\n\t\treturn false\n\t}\n\tthis.l.PushFront(value)\n\tthis.len++\n\treturn true\n}", "func (l *List) PushToFront(val interface{}) *Element {\n\te := &Element{prev: nil, next: nil, Val: val}\n\treturn l.Insert(e, l.head)\n}", "func (l *List) PushFront(elem interface{}) {\n\tnode := &Node{Val: elem, next: l.head}\n\n\tif l.head != nil {\n\t\tl.head.prev = node\n\t}\n\n\tif l.tail == nil {\n\t\tl.tail = node\n\t}\n\n\tl.head = node\n}", "func (l *List) PushFront(v interface{}) *Node {\n\tl.lazyInit()\n\treturn l.InsertValue(v, &l.root)\n}", "func (this *MyCircularDeque1) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\ttemp := this.head.Next\n\ttempNode := Node{\n\t\tVal: value,\n\t\tNext: temp,\n\t\tPre: this.head,\n\t}\n\tthis.head.Next = &tempNode\n\ttemp.Pre = &tempNode\n\tthis.len++\n\treturn true\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\n\tthis.mutex.Lock()\n\tdefer this.mutex.Unlock()\n\tthis.front = (this.front - 1 + this.capacity) % this.capacity\n\tthis.data[this.front] = value\n\treturn true\n}", "func (ll *LinkedList) PushFront(t T) {\n\tn := &node{\n\t\tval: t,\n\t}\n\n\tif ll.head == nil {\n\t\tll.head = n\n\t\tll.tail = n\n\t} else {\n\t\tn.next = ll.head\n\t\tll.head.prev = n\n\t\tll.head = n\n\t}\n\n\tll.size++\n}", "func (l *List) PushFront(v interface{}) {\n\tn := &Node{Val: v}\n\tif l.Len == 0 {\n\t\tl.Len, l.head, l.tail = 1, n, n\n\t\treturn\n\t}\n\tn.next = l.head\n\tl.head.prev = n\n\tl.head = n\n\tl.Len++\n}", "func (l *List) PushFront(element interface{}) {\n\titem := Item{Value: element, Prev: nil, Next: nil}\n\tif l.len > 0 {\n\t\titem.Next = l.firstElement\n\t\tl.firstElement.Prev = &item\n\t\tl.firstElement = &item\n\t} else {\n\t\tl.lastElement = &item\n\t\tl.firstElement = &item\n\t}\n\tl.len++\n}", "func (vector *Vector) PushFront(element interface{}) {\n\t*vector = append([]interface{}{element}, *vector...)\n}", "func (l *List) PushFront(value interface{}) int {\n\tnewItem := Item{Value: value, Next: l.First}\n\t// In case, when we add the first item\n\tif l.Last == nil {\n\t\tl.Last = &newItem\n\t}\n\tif l.First == nil {\n\t\tl.First = &newItem\n\t}\n\tl.First.Prev = &newItem\n\tl.First = &newItem\n\tl.Len++\n\treturn l.Len\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tnode := &Node{nil, nil, value}\n\tif this.head == nil {\n\t\tthis.head = node\n\t\tthis.tail = node\n\t} else {\n\t\tthis.head.last = node\n\t\tnode.next = this.head\n\t\tthis.head = node\n\t}\n\tthis.len++\n\treturn true\n}", "func (l *List) PushFront(v interface{}) {\n\tnewitem := &Item{value: v, next: l.head}\n\tif l.len == 0 {\n\t\tl.head = newitem\n\t\tl.tail = newitem\n\t} else {\n\t\tl.head.prev = newitem\n\t\tl.head = newitem\n\t}\n\tl.len++\n}", "func (Q *Deque) AddFirst(val interface{}) {\n\tnode := &Node{\n\t\tval: val,\n\t}\n\tif Q.front == nil {\n\t\tQ.front = node\n\t\tQ.back = node\n\t} else {\n\t\tcurrentNode := Q.front\n\t\tQ.front = node\n\t\tQ.front.next = currentNode\n\t}\n\tQ.size++\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.length == this.size {\n\t\treturn false\n\t}\n\n\tnode := &Node{value, nil, nil}\n\tthis.head.next.prev = node\n\tnode.next = this.head.next\n\tnode.prev = this.head\n\tthis.head.next = node\n\tthis.length++\n\treturn true\n}", "func (l *idList) PushFront(v doc.Metadata) *idElement {\n\tl.lazyInit()\n\treturn l.insertValue(v, &l.root)\n}", "func (gdt *Array) PushFront(value Variant) {\n\targ0 := gdt.getBase()\n\targ1 := value.getBase()\n\n\tC.go_godot_array_push_front(GDNative.api, arg0, arg1)\n}", "func (d *Deque[T]) PushBack(value T) {\n\td.lastAvailableSegment().pushBack(value)\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (q *Deque) PushBack(v interface{}) {\n\tif q.size == cap(q.values) {\n\t\tnewCap := 2\n\t\tif cap(q.values) > 0 {\n\t\t\tnewCap = cap(q.values) * 2\n\t\t}\n\t\tq.Resize(newCap)\n\t}\n\n\tq.values[q.back] = v\n\tq.size++\n\tq.back = (q.back + 1) % cap(q.values)\n}", "func (d *Deque) PushBack(value interface{}) *Deque {\n\tfree := &dequeNode{value, d.head, d.tail}\n\tif d.IsEmpty() {\n\t\treturn &Deque{nil, &Deque{}, free}\n\t}\n\treturn &Deque{nil, d, free}\n}", "func (lst *List) PushFront(n Val_t){\n\tnewNode := &ListNode{Val:n}\n\tif lst.Len <= 0{\n\t\tlst.Head,lst.Tail = newNode,newNode\n\t}else{\n\t\tnewNode.Next = lst.Head\n\t\tlst.Head = newNode\n\t}\n\tlst.Len++\n}", "func (dq *Dqueue) PushBack(value interface{}) {\n\tdq.dqueue.Append(value)\n}", "func (b *BlockQueue) PushFront(block *Block) {\n\t\n\tb.blocks.PushFront(block)\n\t\n\t// Update balance index\n\tb.blockUpdateAddress(block, false)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block, false)\n}", "func (l *List) AddToFront(d interface{}) *Node {\n\tl.lazyInit()\n\treturn l.insertData(d, &l.root)\n}", "func (this *MyCircularDeque) GetFront() int {\n if this.IsEmpty() {\n return -1\n }\n return this.data[this.head]\n}", "func (s *FIFO) Push(t T) {\n\tnode := &queueNode{v: t, next: nil}\n\tif s.front == nil {\n\t\ts.front = node\n\t\ts.back = node\n\t} else {\n\t\ts.back.next = node\n\t\ts.back = node\n\t}\n\ts.size++\n}", "func (d *Deque) Push(value interface{}) error {\n\tn := &node{}\n\tn.value = value\n\tn.next = d.head.next\n\tn.prev = d.head\n\td.head.next = n\n\n\tif d.length == 0 {\n\t\td.tail = n\n\t}\n\td.length++\n\n\treturn nil\n}", "func (this *MyCircularDeque1) GetFront() int {\n\treturn this.head.Next.Val\n}", "func (b *Ring) push(value interface{}) {\n\tb.lock.Lock()\n\tdefer b.lock.Unlock()\n\tif len(b.buf) == 0 || b.size == 0 { // nothing to do\n\t\treturn\n\t}\n\tnext := Next(1, b.head, len(b.buf))\n\tb.buf[next] = value\n\tb.head = next\n\t// note that the oldest is auto pruned, when size== capacity, but with the size attribute we know it has been discarded\n}", "func (cll *CircularLinkedList) AddElementAtFront(value int) {\n\tvar newNode = Node{data: value}\n\n\ttempHead := cll.head\n\n\tif cll.head == nil {\n\t\tcll.head = &newNode\n\t\tnewNode.next = &newNode\n\t\treturn\n\t}\n\n\tif tempHead.next == tempHead {\n\t\tnewNode.next = tempHead\n\t\ttempHead.next = &newNode\n\t\tcll.head = &newNode\n\t\treturn\n\t}\n\n\tfor ; tempHead.next != cll.head; {\n\t\ttempHead = tempHead.next\n\t}\n\tcll.head = &newNode\n\tnewNode.next = tempHead.next\n\ttempHead.next = &newNode\n}", "func (self *Dll) AppendFront(str string){\n\tnewNode := new(node)\n\tnewNode.data = str\n\tself.enqueue(newNode)\n}", "func (q *Queue) Push(value interface{}) {\n\tfor q.Count >= q.Capacity {\n\t\tq.Pop()\n\t}\n\n\te := new(Element)\n\te.Value = value\n\te.Prev = nil\n\n\tif q.Count <= 0 {\n\t\tq.Head = e\n\t\tq.Tail = e\n\t\te.Next = nil\n\t} else {\n\t\te.Next = q.Head\n\t\tq.Head.Prev = e\n\t\tq.Head = e\n\t}\n\tq.Count += 1\n}", "func (list *LinkedList[T]) AddFront(entry T) {\n\ttoAppend := &llNode[T]{\n\t\tpayload: entry,\n\t}\n\n\tlist.key.Lock()\n\tdefer list.key.Unlock()\n\n\tlist.addNodeFront(toAppend)\n}", "func (lru *LRUMap) addToFrontOfQueue(node *keyValNode) {\n\tnode.next = nil\n\tnode.prev = lru.front\n\n\tif lru.rear == nil {\n\t\t// node is only node in the queue\n\t\tlru.rear = node\n\t} else {\n\t\t// link \"front\" to the new front\n\t\tlru.front.next = node\n\t}\n\n\t// move front pointer to the new front node\n\tlru.front = node\n}", "func (s *Queue) Push(val interface{}) {\n\tif s.IsEmpty() {\n\t\ttmp := new(node)\n\t\ttmp.val = val\n\t\ts.head = tmp\n\t\ts.tail = tmp\n\t\ts.len += 1\n\t} else {\n\t\tcurrent_tail := s.tail\n\t\ttmp := new(node)\n\t\ttmp.val = val\n\t\tcurrent_tail.previous = tmp\n\t\ttmp.next = current_tail\n\t\ts.tail = tmp\n\t\ts.len += 1\n\t}\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.head.value\n}", "func (c *Cache) insertInFront(node *lruNode) {\n\tc.front.prev = node\n\tnode.next = c.front\n\tc.front = node\n}", "func (l *LinkedList) InsertAtFront(val fmt.Stringer) error {\n\tnode := Node{val, l.head}\n\tif l.Empty() {\n\t\tl.tail = &node\n\t} else if l.size == 1 {\n\t\tl.tail = l.head\n\t}\n\tl.head = &node\n\tl.size++\n\treturn nil\n}", "func (d *MyCircularDeque) GetFront() int {\n\tif d.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn d.Val[0]\n}", "func (q *Queue) Enqueue(value interface{}) {\n\tq.Lock()\n\tdefer q.Unlock()\n\n\titem := &qItem{value: value}\n\tif q.tail == nil {\n\t\tq.head = item\n\t\tq.tail = item\n\t} else {\n\t\tq.tail.next = item // set current tail's next (conceptually previous) to new item\n\t\tq.tail = item //add to back\n\t}\n\tq.size++\n}", "func (q *Deque) PopFront() {\n\tif !q.Empty() {\n\t\tq.front = (q.front + 1) % cap(q.values)\n\t\tq.size--\n\t}\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.length == 0 {\n\t\treturn -1\n\t}\n\treturn this.head.next.val\n}", "func (q *Queue) Enqueue(value interface{}) {\n\tn := &node{value, nil}\n\tif q.length == 0 {\n\t\tq.start = n\n\t\tq.end = n\n\t} else {\n\t\tq.end.next = n\n\t\tq.end = n\n\t}\n\tq.length++\n}", "func (dq *Dqueue) Front() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\treturn\n}", "func (q *Queue) Enqueue(value interface{}) {\n\tn := &node{value, nil}\n\tif q.length != 0 {\n\t\tq.end.next = n\n\t\tq.end = n\n\t} else {\n\t\tq.start, q.end = n, n\n\t}\n\tq.length++\n}", "func (st *FixedFIFO) Enqueue(value interface{}) error {\n\tif st.IsLocked() {\n\t\treturn NewQueueError(QueueErrorCodeLockedQueue, \"The queue is locked\")\n\t}\n\n\t// check if there is a listener waiting for the next element (this element)\n\tselect {\n\tcase listener := <-st.waitForNextElementChan:\n\t\t// verify whether it is possible to notify the listener (it could be the listener is no longer\n\t\t// available because the context expired: DequeueOrWaitForNextElementContext)\n\t\tselect {\n\t\t// sends the element through the listener's channel instead of enqueueing it\n\t\tcase listener <- value:\n\t\tdefault:\n\t\t\t// push the element into the queue instead of sending it through the listener's channel (which is not available at this moment)\n\t\t\treturn st.enqueueIntoQueue(value)\n\t\t}\n\n\tdefault:\n\t\t// enqueue the element into the queue\n\t\treturn st.enqueueIntoQueue(value)\n\t}\n\n\treturn nil\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.First.Next.Data\n}", "func (q *Queue) Enqueue(v interface{}) {\n\t_ = q.Elements.PushBack(v)\n}", "func (s *stack) pushMin(value interface{}) {\n\tif s.min == nil {\n\t\ts.min = &node{value, nil}\n\t} else {\n\t\tnode := &node{\n\t\t\tvalue: value,\n\t\t\tprev: s.min,\n\t\t}\n\t\ts.min = node\n\t}\n}", "func main() {\n\tcircularDeque := Constructor(3) // 设置容量大小为3\n\tcircularDeque.InsertLast(1) // 返回 true\n\tcircularDeque.InsertLast(2) // 返回 true\n\tcircularDeque.InsertFront(3) // 返回 true\n\t// 已经满了,返回 false\n\tfmt.Println(circularDeque.InsertFront(4))\n\t// 返回 2\n\tfmt.Println(circularDeque.GetRear())\n\tfmt.Println(circularDeque)\n\tcircularDeque.IsFull() // 返回 true\n\tcircularDeque.DeleteLast() // 返回 true\n\tcircularDeque.InsertFront(4) // 返回 true\n\tcircularDeque.GetFront() // 返回 4\n}", "func (d *Doubly) PushHead(data interface{}) {\n\td.rwLock.Lock()\n\tdefer d.rwLock.Unlock()\n\tif d.head == nil {\n\t\td.head = &doublyNode{Next: nil, Prev: nil, Data: data}\n\t\td.tail = d.head\n\t} else {\n\t\td.head.Prev = &doublyNode{Next: d.head, Prev: nil, Data: data}\n\t\td.head = d.head.Prev\n\t}\n\td.size++\n}", "func (q *Queue) enqueue(value int) {\n\tq.values = append(q.values, value)\n}", "func (this *Queue) Enqueue(value interface{}) {\r\n\tn := &node{value,nil}\r\n\tif this.length == 0 {\r\n\t\tthis.start = n\r\n\t\tthis.end = n\t\t\r\n\t} else {\r\n\t\tthis.end.next = n\r\n\t\tthis.end = n\r\n\t}\r\n\tthis.length++\r\n}", "func (q *Queue) Push(value interface{}) {\n\tq.mu.Lock()\n\tq.elements.PushBack(value)\n\tq.mu.Unlock()\n}", "func (q *Queue) Push(value interface{}) {\n\tq.mu.Lock()\n\tq.elements.PushBack(value)\n\tq.mu.Unlock()\n}", "func (mcq *MyCircularQueue) Front() int {\n\tif mcq.length == 0 {\n\t\treturn -1\n\t}\n\treturn mcq.dummyHead.Next.Val\n}", "func (q *Queue) Push(n Any) {\n\t// The queue size is reached it doesn't resize. It just pops the item.\n\tif q.count == q.size {\n\t\tq.Pop()\n\t}\n\tq.nodes[q.backIndex()] = n\n\tq.count++\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.len == 0 {\n\t\treturn -1\n\t}\n\treturn this.queue[this.head]\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\n\treturn this.data[this.front]\n}", "func (Q *Queue) Enqueue(value interface{}) error {\n\tif Q.IsFull() {\n\t\treturn errors.New(\"queue is full. You can't add element in your queue(\")\n\t}\n\telement := &Node {\n\t\tvalue: value,\n\t}\n\tif Q.head == nil {\n\t\tQ.tail = element\n\t\tQ.head = element\n\t} else {\n\t\tQ.tail.next = element\n\t\tQ.tail = element\n\t}\n\tQ.size++\n\treturn nil\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\n\tthis.mutex.RLock()\n\tdefer this.mutex.RUnlock()\n\treturn this.data[this.front]\n\n}", "func (s *stack) Push(value interface{}) interface{} {\n\ttop := &node{\n\t\tvalue: value,\n\t\tprev: s.top,\n\t}\n\ts.top = top\n\ts.length += 1\n\ts.calcMin(value, false)\n\treturn s.top.value\n}", "func (this *MyCircularQueue) Front() int {\n if this.IsEmpty() { return -1 }\n return this.vals[this.head]\n}", "func (l *idList) PushFrontList(other *idList) {\n\tl.lazyInit()\n\tfor i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() {\n\t\tl.insertValue(e.Value, &l.root)\n\t}\n}", "func (q *Stack) Push(v interface{}) *list.Element {\n\treturn q.data.PushFront(v)\n}", "func (d *Deque[T]) Insert(pos int, value T) {\n\tif pos < 0 || pos > d.size {\n\t\treturn\n\t}\n\tif pos == 0 {\n\t\td.PushFront(value)\n\t\treturn\n\t}\n\tif pos == d.size {\n\t\td.PushBack(value)\n\t\treturn\n\t}\n\tseg, pos := d.pos(pos)\n\tif seg < d.segUsed()-seg {\n\t\t// seg is closer to the front\n\t\td.moveFrontInsert(seg, pos, value)\n\t} else {\n\t\t// seg is closer to the back\n\t\td.moveBackInsert(seg, pos, value)\n\t}\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (this *MyQueue) Push(x int) {\n\tif this.Empty() {\n\t\tthis.stack.Push(x)\n\t\treturn\n\t}\n\tdata := this.stack.Pop()\n\tthis.Push(x)\n\tthis.stack.Push(data)\n}", "func (q *Queue) Enqueue(data []byte) (int, error) {\n\tq.lock.Lock()\n\tq.data[q.front+1] = data\n\tf := q.front + 1\n\tq.front = f\n\tq.lock.Unlock()\n\tgo func() {\n\t\tq.storageW.C <- data\n\t}()\n\treturn q.front, nil\n\n}", "func (q *queue) Front() (interface{}, error) {\n\tif q.Empty() {\n\t\treturn nil, errors.New(\"error: can not get element from empty queue\")\n\t}\n\treturn q.items[q.head].Data, nil\n}", "func (q *Queue) Enqueue(newVal interface{}) {\n\tq.s1.Push(newVal)\n}", "func (q *MyQueue) Push(x int) {\n\tq.list.PushBack(x)\n}", "func(q *Queue)GetFront()int{\n\tif q.IsEmpty() {\n\t\tpanic(\"Get front error.queue is empty\")\n\t}\n\treturn q.arr[q.front]\n}", "func (this *MyStack) Push(x int) {\n\tif this.q.IsEmpty() {\n\t\tthis.q.PushToBack(x)\n\t\treturn\n\t}\n\n\ttmp := newQ()\n\tfor !this.q.IsEmpty() {\n\t\ttmp.PushToBack(this.q.PeekFromFront())\n\t\tthis.q.PopFromFront()\n\t}\n\n\tthis.q.PushToBack(x)\n\tfor !tmp.IsEmpty() {\n\t\tthis.q.PushToBack(tmp.PeekFromFront())\n\t\ttmp.PopFromFront()\n\t}\n}", "func (s *List) PushHead(x interface{}) {\n\ti := newItem(x)\n\tif !s.addFirstItem(i) {\n\t\ts.Head.Prev = i\n\t\ti.Next = s.Head\n\t\ts.Head = i\n\t}\n}", "func Push(t Interface, x interface{}) {\n\tif l := t.Len(); l < t.K() {\n\t\theap.Push(t, x)\n\t} else if l > 0 && t.IsLess(t.Peek(), x) {\n\t\theap.Pop(t) // remove the smallest element\n\t\theap.Push(t, x) // push the new one\n\t}\n}", "func (q *RingQueue) Enqueue(e interface{}) interface{} {\n\tif q.IsFull() {\n\t\treturn nil\n\t}\n\tq.data[q.rear] = e\n\tq.rear = (q.rear + 1) % q.size\n\treturn e\n}", "func (q *Deque) Front() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.front]\n\t}\n\treturn nil\n}", "func (d *Deque) PushBack(data interface{}) bool {\n\tif d == nil {\n\t\treturn false\n\t}\n\t// create a new node\n\tnewNode := node{\n\t\tdata: data,\n\t\tnext: d.back,\n\t}\n\n\tif d.back != nil {\n\t\td.back.prev = &newNode\n\t} else {\n\t\td.front = &newNode\n\t}\n\td.back = &newNode\n\td.size++\n\treturn true\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.len <= 0 {\n\t\treturn -1\n\t}\n\n\tn := this.l.Front().Value.(int)\n\treturn n\n}", "func (dq *Dqueue) PopFront() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\tdq.dqueue.Remove(0)\n\treturn\n}", "func (this *MyCircularQueue) Front() int {\n if this.IsEmpty() {\n return -1\n }\n return this.Items[this.HeadIndex]\n}", "func InsertFront(head *Node, data int) {\n\t// fmt.Println(\"LinkedList -> InsertFront \", data)\n\t// create a new node\n\tnode := Node{\n\t\tData: data,\n\t\tNext: nil,\n\t}\n\n\t// fmt.Println(\"Node : \", node)\n\n\t// check if the head has next node\n\tif head.Next != nil {\n\t\t// Get the node next to head\n\t\theadNext := head.Next\n\n\t\t// make node's next node as head's next node\n\t\tnode.Next = headNext\n\t}\n\t// set the new node as head's next node\n\thead.Next = &node\n}", "func (self *Queue) Push(data interface{}) {\n\tif self.final == nil {\n\t\tself.final = node.NewNode(data, nil)\n\t\tself.final.SetNext(self.final)\n\t} else {\n\t\tself.final.SetNext(node.NewNode(data, self.final.GetNext()))\n\t\tself.final = self.final.GetNext()\n\t}\n\tself.size++\n}", "func (q *wantConnQueue) peekFront() *wantConn {\n\tif q.headPos < len(q.head) {\n\t\treturn q.head[q.headPos]\n\t}\n\tif len(q.tail) > 0 {\n\t\treturn q.tail[0]\n\t}\n\treturn nil\n}", "func (o *ordering) front() *entry {\n\te := o.ordered[0]\n\tif e.prev != nil {\n\t\tlog.Panicf(\"unexpected first entry: %v\", e)\n\t}\n\t// The first entry is always a logical position, which should not be indexed.\n\te, _ = e.nextIndexed()\n\treturn e\n}", "func (q *queue) enqueueHead(v *Vertex) {\n\tn := &node{v: v}\n\n\tif q.tail == nil {\n\t\tq.head = n\n\t\tq.tail = n\n\t\treturn\n\t}\n\tn.next = q.head\n\tq.head = n\n}" ]
[ "0.8590243", "0.84054154", "0.81194776", "0.77864844", "0.77001005", "0.7512009", "0.75098604", "0.7503036", "0.7499266", "0.74926984", "0.74849594", "0.7483095", "0.7460131", "0.74490845", "0.7444826", "0.74252987", "0.7411353", "0.7403993", "0.73797286", "0.7347217", "0.7338795", "0.733564", "0.7316818", "0.72830826", "0.727135", "0.7204238", "0.71890396", "0.7166297", "0.71624476", "0.70532125", "0.68954337", "0.6807565", "0.67618996", "0.6720162", "0.6703852", "0.66667396", "0.6663412", "0.6645577", "0.66163194", "0.6502907", "0.6479326", "0.6474936", "0.64747304", "0.646598", "0.64634556", "0.642265", "0.64100754", "0.6406882", "0.6383566", "0.63570416", "0.63520634", "0.6312907", "0.6310631", "0.6287876", "0.6286706", "0.62852013", "0.62847143", "0.6278072", "0.6267697", "0.623883", "0.62310153", "0.6167924", "0.6167515", "0.6165125", "0.6152747", "0.61196893", "0.61190486", "0.6114998", "0.6114998", "0.6110085", "0.6109596", "0.6100109", "0.60881305", "0.6083267", "0.60830224", "0.6082058", "0.6073765", "0.6059411", "0.6057623", "0.6053348", "0.60458505", "0.60335046", "0.6033347", "0.6023455", "0.60184747", "0.5998991", "0.5998291", "0.5990564", "0.5980048", "0.5965114", "0.59605753", "0.59528637", "0.5949772", "0.59364605", "0.5933799", "0.59107727", "0.59071565", "0.5900018", "0.5896292", "0.5894783" ]
0.84480065
1
PushBack pushed a value to the back of deque
func (d *Deque[T]) PushBack(value T) { d.lastAvailableSegment().pushBack(value) d.size++ if d.segUsed() >= len(d.segs) { d.expand() } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Deque) PushBack(v interface{}) {\n\tif q.size == cap(q.values) {\n\t\tnewCap := 2\n\t\tif cap(q.values) > 0 {\n\t\t\tnewCap = cap(q.values) * 2\n\t\t}\n\t\tq.Resize(newCap)\n\t}\n\n\tq.values[q.back] = v\n\tq.size++\n\tq.back = (q.back + 1) % cap(q.values)\n}", "func (dq *Dqueue) PushBack(value interface{}) {\n\tdq.dqueue.Append(value)\n}", "func (d *Deque) PushBack(value interface{}) *Deque {\n\tfree := &dequeNode{value, d.head, d.tail}\n\tif d.IsEmpty() {\n\t\treturn &Deque{nil, &Deque{}, free}\n\t}\n\treturn &Deque{nil, d, free}\n}", "func (d *Deck) PushBack(v string) {\n\tif d.head-1 == d.tail {\n\t\tinv = 1\n\t\td.pushtocap(v)\n\t} else {\n\t\tif d.tail == cap(d.deck)-1 && d.head == 0 {\n\t\t\tinv = -1\n\t\t} else if d.tail == cap(d.deck) && d.head > 0 {\n\t\t\td.tail = 0\n\t\t\tinv = 1\n\t\t}\n\t\td.deck[d.tail] = v\n\t\td.tail += inv\n\t}\n}", "func (cq *cQT) PushBack(el T) (ok bool) {\n\tif cq.e-cq.s == cq.sz {\n\t\tif cq.sz == cq.maxSz {\n\t\t\treturn false\n\t\t}\n\t\tcq.resize(cq.sz << 1)\n\t}\n\tcq.b[cq.e&cq.m] = el\n\tcq.e++\n\treturn true\n}", "func (q *Queue) PutBack(value []byte) error {\n\tq.Lock()\n\tdefer q.Unlock()\n\tif q.head < 1 {\n\t\treturn ErrInvalidHeadValue\n\t}\n\terr := q.db.Put(q.dbKey(q.head), value, nil)\n\tif err == nil {\n\t\tq.head--\n\t}\n\treturn err\n}", "func (q *wantConnQueue) pushBack(w *wantConn) {\n\tq.tail = append(q.tail, w)\n}", "func (q *Deque) PopBack() {\n\tif !q.Empty() {\n\t\tq.back--\n\t\tq.size--\n\t}\n}", "func (l *List) PushBack(v interface{}) {\r\n\tif l.first == nil {\r\n\t\tl.first = &Item{data: v, parent: l, invalidated: new(bool)}\r\n\t\tl.last = l.first\r\n\t} else {\r\n\t\tformerLast := l.last\r\n\t\tl.last = &Item{data: v, prev: formerLast, parent: l, invalidated: new(bool)}\r\n\t\tformerLast.next = l.last\r\n\t}\r\n\tl.length++\r\n}", "func (dq *Dqueue) Back() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\treturn\n}", "func (q *Deque) Back() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.back-1]\n\t}\n\treturn nil\n}", "func (dq *Dqueue) PopBack() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\tdq.dqueue.Remove(dq.Size() - 1)\n\treturn\n}", "func (l *List) PushBack(v interface{}) *Node {\n\tl.lazyInit()\n\treturn l.InsertValue(v, l.root.prev)\n}", "func (self *Dll) pushBack(n *node){\n\t//special empty list case\n\tif self.len == 0 {\n\t\tn.setNext(self.tail)\n\t\tn.setPrev(self.head)\n\t\tself.tail.setPrev(n)\n\t\tself.head.setNext(n)\n\t}\n\t//general case\n\tif self.len > 0 {\n\t\tn.setNext(self.tail)\n\t\tn.setPrev(self.tail.prev)\n\t\tself.tail.prev.setNext(n)\n\t\tself.tail.setPrev(n)\n\t}\n\tself.len++\n\n}", "func (d *Deque[T]) Back() T {\n\treturn d.lastSegment().back()\n}", "func (q *Deque) PushFront(v interface{}) {\n\tif q.size == cap(q.values) {\n\t\tnewCap := 2\n\t\tif cap(q.values) > 0 {\n\t\t\tnewCap = cap(q.values) * 2\n\t\t}\n\t\tq.Resize(newCap)\n\t}\n\n\tq.front--\n\tif q.front < 0 {\n\t\tq.front = cap(q.values) - 1\n\t}\n\n\tq.values[q.front] = v\n\tq.size++\n}", "func (l *List) PushBack(value interface{}) {\n\ttemp := &node{value, nil, nil}\n\tl.Lock()\n\tif l.length == 0 {\n\t\tl.head = temp\n\t\tl.tail = temp\n\t} else {\n\t\ttemp.prev = l.tail\n\t\tl.tail = temp\n\t}\n\tl.length++\n\tl.Unlock()\n}", "func (l *List) PushBack(element interface{}) {\n\titem := Item{Value: element, Prev: nil, Next: nil}\n\tif l.len > 0 {\n\t\titem.Prev = l.lastElement\n\t\tl.lastElement.Next = &item\n\t\tl.lastElement = &item\n\t} else {\n\t\tl.lastElement = &item\n\t\tl.firstElement = &item\n\t}\n\tl.len++\n}", "func (d *Deque) PushBack(data interface{}) bool {\n\tif d == nil {\n\t\treturn false\n\t}\n\t// create a new node\n\tnewNode := node{\n\t\tdata: data,\n\t\tnext: d.back,\n\t}\n\n\tif d.back != nil {\n\t\td.back.prev = &newNode\n\t} else {\n\t\td.front = &newNode\n\t}\n\td.back = &newNode\n\td.size++\n\treturn true\n}", "func (d *Deque[T]) PopBack() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\tseg := d.preIndex(d.end)\n\ts := d.segs[seg]\n\tv := s.popBack()\n\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[seg] = nil\n\t\td.end = seg\n\t}\n\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (ll *LinkedList) PushBack(t T) {\n\tn := &node{\n\t\tval: t,\n\t}\n\n\tif ll.tail == nil {\n\t\tll.head = n\n\t\tll.tail = n\n\t} else {\n\t\tn.prev = ll.tail\n\t\tll.tail.next = n\n\t\tll.tail = n\n\t}\n\n\tll.size++\n}", "func (builder *ListBuilder) PushBack(c *Cons) {\n\tif builder.Head == nil {\n\t\tbuilder.Head = c\n\t} else {\n\t\tbuilder.Tail.Cdr = c\n\t}\n\n\tbuilder.Tail = c\n}", "func (l *List) PushBack(v interface{}) {\n\tn := &Node{Val: v}\n\tif l.Len == 0 {\n\t\tl.Len, l.head, l.tail = 1, n, n\n\t\treturn\n\t}\n\tn.prev = l.tail\n\tl.tail.next = n\n\tl.tail = n\n\tl.Len++\n}", "func (l *List) PushBack(v interface{}) {\n\tnode := &Node{Val: v, previous: l.last}\n\n\tif l.last == nil {\n\t\tl.head = node\n\t} else {\n\t\tl.last.next = node\n\t}\n\tl.last = node\n\n}", "func (l *List) PushBack(v interface{}) {\n\tn := Node{Val: v, prev: l.last}\n\tif l.last != nil {\n\t\tl.last.next = &n\n\t}\n\tl.last = &n\n\tif l.first == nil {\n\t\tl.first = &n\n\t}\n}", "func (head *Node) pushBack(node *Node) {\n\tif head == nil {\n\t\treturn\n\t}\n\n\tafter := head\n\tfor after.next != nil {\n\t\tafter = after.next\n\t}\n\n\tnode.prev = after\n\tnode.next = nil\n\tafter.next = node\n}", "func (builder *BitVectorBuilderData) PushBack(b bool) {\n\tbuilder.vec.pushBack(b)\n}", "func (l *List) PushBack(elem interface{}) {\n\tnode := &Node{Val: elem, prev: l.tail}\n\n\tif l.tail != nil {\n\t\tl.tail.next = node\n\t}\n\n\tif l.head == nil {\n\t\tl.head = node\n\t}\n\n\tl.tail = node\n}", "func (self *Dll) popBack() *node{\n\n\tret := self.tail.prev\n\ttemp := ret.prev\n\ttemp.setNext(self.tail)\n\tself.tail.setPrev(temp)\n\n\tret.setPrev(nil)\n\tret.setNext(nil)\n\n\tself.len -= 1\n\n\treturn ret\n}", "func (d *Deque) Back() (*interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\treturn &d.back.data, true\n}", "func (b *Ring) push(value interface{}) {\n\tb.lock.Lock()\n\tdefer b.lock.Unlock()\n\tif len(b.buf) == 0 || b.size == 0 { // nothing to do\n\t\treturn\n\t}\n\tnext := Next(1, b.head, len(b.buf))\n\tb.buf[next] = value\n\tb.head = next\n\t// note that the oldest is auto pruned, when size== capacity, but with the size attribute we know it has been discarded\n}", "func (Q *Deque) AddLast(val interface{}) {\n\tnode := &Node{\n\t\tval: val,\n\t}\n\tif Q.back == nil {\n\t\tQ.front = node\n\t\tQ.back = node\n\t} else {\n\t\t//First point the nex of the last element to the node\n\t\t// The new last element will be pointing to the back\n\t\tQ.back.next = node\n\t\tQ.back = Q.back.next\n\t}\n\tQ.size++\n}", "func (l *List) PushBack(value interface{}) int {\n\tnewItem := Item{Value: value, Prev: l.Last}\n\t// In case, when we add the first item\n\tif l.First == nil {\n\t\tl.First = &newItem\n\t}\n\tif l.Last == nil {\n\t\tl.Last = &newItem\n\t}\n\tl.Last.Next = &newItem\n\tl.Last = &newItem\n\tl.Len++\n\treturn l.Len\n}", "func (this *Vector)PushBack(x ...interface{}){\n\tthis.init()\n\tfor _,tmp:=range x{\n\t\tthis.v=append(this.v,tmp)\n\t}\n}", "func (cq *cQT) PopBack() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tcq.e--\n\tel = cq.b[cq.e&cq.m]\n\tcq.b[cq.e&cq.m] = zero\n\treturn el, true\n}", "func (l *List) PushBack(v interface{}) {\n\tnewitem := &Item{value: v, prev: l.tail}\n\tif l.len == 0 {\n\t\tl.head = newitem\n\t\tl.tail = newitem\n\t} else {\n\t\tl.tail.next = newitem\n\t\tl.tail = newitem\n\t}\n\tl.len++\n \t\n}", "func (v *Vector) PushBack(d string) {\n\tv.Vector = append(v.Vector, d)\n}", "func (l *TwoList) PushBack(v interface{}) *Element {\n\te := &Element{\n\t\tValue: v,\n\t}\n\tif l.tail == nil {\n\t\tl.tail = e\n\t} else {\n\t\te.next = l.tail\n\t\tl.tail = e\n\t}\n\treturn e\n}", "func (l *idList) PushBack(v doc.Metadata) *idElement {\n\tl.lazyInit()\n\treturn l.insertValue(v, l.root.prev)\n}", "func (d *Deque[T]) PushFront(value T) {\n\td.firstAvailableSegment().pushFront(value)\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (b *BlockQueue) PushBack(block *Block) {\n\n\tb.blocks.PushBack(block)\n\n\t// Update balance index\n\tb.blockUpdateAddress(block, false)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block, false)\n}", "func (dq *Dqueue) PushFront(value interface{}) {\n\tdq.dqueue.Prepend(value)\n}", "func (ll *LinkedList) PushBack(data interface{}) {\n\tll.Lock()\n\n\tnewNode := &LinkedListNode{\n\t\tdata: data,\n\t\tprev: ll.tail,\n\t\tnext: nil,\n\t}\n\n\tif ll.tail != nil {\n\t\tll.tail.next = newNode\n\t}\n\n\tif ll.head == nil {\n\t\tll.head = newNode\n\t}\n\n\tll.tail = newNode\n\tll.size++\n\n\tll.Unlock()\n}", "func (q *Queue) Push(v interface{}) *list.Element {\n\treturn q.data.PushBack(v)\n}", "func (d *Deque) PushFront(value interface{}) *Deque {\n\tfree := &dequeNode{value, d.head, d.tail}\n\tif d.IsEmpty() {\n\t\treturn &Deque{free, &Deque{}, nil}\n\t}\n\treturn &Deque{free, d, nil}\n}", "func (l *PList) PushBack(v interface{}) *Element {\n\tl.Clone()\n\te := &Element{\n\t\tValue: v,\n\t}\n\tif l.head == nil {\n\t\tl.tail = e\n\t\tl.head = e\n\t} else {\n\t\tl.tail.next = e\n\t\tl.tail = e\n\t}\n\treturn e\n}", "func (l *List) AddToBack(d interface{}) *Node {\n\t// lazyInit just in case\n\t// this will guarantee that the next and prev nodes of root are not nil\n\tl.lazyInit()\n\n\t// insert the node to the end of the list\n\treturn l.insertData(d, l.root.prev)\n}", "func(q *Queue)GetBack() int{\n\tif q.IsEmpty() {\n\t\tpanic(\"Get back error.queue is empty\")\n\t}\n\treturn q.arr[q.rear-1]\n}", "func (this *MyCircularDeque) InsertLast(value int) bool {\n if this.IsFull() {\n return false\n }\n this.data[this.tail] = value\n this.tail = (this.tail + 1 + this.capacity) % this.capacity\n return true\n}", "func (q *Queue) Push(value interface{}) {\n\tq.mu.Lock()\n\tq.elements.PushBack(value)\n\tq.mu.Unlock()\n}", "func (q *Queue) Push(value interface{}) {\n\tq.mu.Lock()\n\tq.elements.PushBack(value)\n\tq.mu.Unlock()\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n if this.IsFull() {\n return false\n }\n this.head = (this.head - 1 + this.capacity) % this.capacity\n this.data[this.head] = value\n return true\n}", "func (m *clistModel) PushBack(t *rapid.T) {\n\tvalue := rapid.String().Draw(t, \"value\").(string)\n\tel := m.clist.PushBack(value)\n\tm.model = append(m.model, el)\n}", "func (gdt *Array) PushBack(value Variant) {\n\targ0 := gdt.getBase()\n\targ1 := value.getBase()\n\n\tC.go_godot_array_push_back(GDNative.api, arg0, arg1)\n}", "func (q *Queue) Push(value interface{}) {\n\tfor q.Count >= q.Capacity {\n\t\tq.Pop()\n\t}\n\n\te := new(Element)\n\te.Value = value\n\te.Prev = nil\n\n\tif q.Count <= 0 {\n\t\tq.Head = e\n\t\tq.Tail = e\n\t\te.Next = nil\n\t} else {\n\t\te.Next = q.Head\n\t\tq.Head.Prev = e\n\t\tq.Head = e\n\t}\n\tq.Count += 1\n}", "func (q *Queue) Enqueue(v interface{}) {\n\t_ = q.Elements.PushBack(v)\n}", "func (q *Deque) PopFront() {\n\tif !q.Empty() {\n\t\tq.front = (q.front + 1) % cap(q.values)\n\t\tq.size--\n\t}\n}", "func (d *Deque) PopBack() (*Deque, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.tail != nil:\n\t\treturn &Deque{d.head, d.child, nil}, true\n\n\tdefault:\n\t\tdd, _ := d.child.PopFront()\n\t\treturn &Deque{d.head, dd, nil}, true\n\t}\n}", "func (this *MyQueue) Pop() int {\n x := this.q[0]\n this.q = this.q[1:]\n return x\n}", "func (q *MyQueue) Push(x int) {\n\tq.list.PushBack(x)\n}", "func (q *Queue) Push(v int) {\n\t//这里的*q是一个指针接受者, 指针接受者时可以改变里面的值的\n\t// 后面使用*q 前面也要加一个*\n\t*q = append(*q, v)\n}", "func (q *Queue) enqueue(value int) {\n\tq.values = append(q.values, value)\n}", "func (ll *LinkedList) PopBack() T {\n\tif ll.tail == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.tail.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\ttail := ll.tail.prev\n\t\ttail.next = nil\n\t\tll.tail.prev = nil\n\t\tll.tail = tail\n\t}\n\n\tll.size--\n\treturn val\n}", "func (this *MyQueue) Push(x int) {\n this.q = append(this.q, x)\n}", "func (d *Deque) Push(value interface{}) error {\n\tn := &node{}\n\tn.value = value\n\tn.next = d.head.next\n\tn.prev = d.head\n\td.head.next = n\n\n\tif d.length == 0 {\n\t\td.tail = n\n\t}\n\td.length++\n\n\treturn nil\n}", "func (list *LinkedList[T]) AddBack(entry T) {\n\tlist.key.Lock()\n\tdefer list.key.Unlock()\n\n\ttoAppend := &llNode[T]{\n\t\tpayload: entry,\n\t}\n\n\tlist.addNodeBack(toAppend)\n}", "func (d *Deque) PopBack() (interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\toldBack := d.back\n\td.back = oldBack.next\n\tif d.back == nil {\n\t\td.front = nil\n\t} else {\n\t\td.back.prev = nil\n\t}\n\tret := oldBack.data\n\t// clean up\n\toldBack.next = nil\n\toldBack.prev = nil\n\td.size--\n\treturn ret, true\n}", "func (v *Vector) PopBack() (string, error) {\n\tif len(v.Vector) == 0 {\n\t\treturn \"\", fmt.Errorf(\"nothing to pop\")\n\t}\n\tres := v.Vector[len(v.Vector)-1]\n\t// v.Vector[len(v.Vector)-1] = \"\"\n\tv.Vector = v.Vector[:len(v.Vector)-1]\n\treturn res, nil\n}", "func (q *Queue) Push(v interface{}) {\n\tq.queue = append(q.queue, v)\n}", "func (r *batchRangeVectorIterator) popBack(newStart int64) {\n\t// possible improvement: if there is no overlap we can just remove all.\n\tfor fp := range r.window {\n\t\tlastPoint := 0\n\t\tremove := false\n\t\tfor i, p := range r.window[fp].Points {\n\t\t\tif p.T <= newStart {\n\t\t\t\tlastPoint = i\n\t\t\t\tremove = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif remove {\n\t\t\tr.window[fp].Points = r.window[fp].Points[lastPoint+1:]\n\t\t}\n\t\tif len(r.window[fp].Points) == 0 {\n\t\t\ts := r.window[fp]\n\t\t\tdelete(r.window, fp)\n\t\t\tputSeries(s)\n\t\t}\n\t}\n}", "func (q *Queue) Push(n Any) {\n\t// The queue size is reached it doesn't resize. It just pops the item.\n\tif q.count == q.size {\n\t\tq.Pop()\n\t}\n\tq.nodes[q.backIndex()] = n\n\tq.count++\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn 0, ErrEmptyList\n\t}\n\n\tdata := l.last.Val\n\n\tif l.last.Prev() == nil {\n\t\tl.head = nil\n\t\tl.last = nil\n\t} else {\n\t\tl.last.Prev().next = nil\n\t\tl.last = l.last.Prev()\n\t}\n\n\treturn data, nil\n}", "func (stack *Stack) Push(value interface{}) {\n\tstack.list.PushBack(value)\n}", "func (list *linkedList) pushBack(node *node) {\n\tif list.head == nil {\n\t\tlist.head = node\n\t\tlist.tail = node\n\t\tnode.next = list.head\n\n\t\tlist.length++\n\t\treturn\n\t}\n\n\tlist.tail.next = node\n\tlist.tail = node\n\tlist.tail.next = list.head\n\tlist.length++\n}", "func (s *FIFO) Push(t T) {\n\tnode := &queueNode{v: t, next: nil}\n\tif s.front == nil {\n\t\ts.front = node\n\t\ts.back = node\n\t} else {\n\t\ts.back.next = node\n\t\ts.back = node\n\t}\n\ts.size++\n}", "func (q *Queue) Pop() int {\n\t//这里的括号是定界符\n\t//这里是取出第0个元素进行返回\n\thead := (*q)[0]\n\t//将q的内存地址中的数据, 修改为将q的下标为1开始剪切到最后一个的数据\n\t// 后面使用*q 前面也要加一个*\n\t*q = (*q)[1:]\n\treturn head\n}", "func (q *Queue) Enqueue(value interface{}) {\n\tq.Lock()\n\tdefer q.Unlock()\n\n\titem := &qItem{value: value}\n\tif q.tail == nil {\n\t\tq.head = item\n\t\tq.tail = item\n\t} else {\n\t\tq.tail.next = item // set current tail's next (conceptually previous) to new item\n\t\tq.tail = item //add to back\n\t}\n\tq.size++\n}", "func (q *queue) dequeue() (int, error) {\n\tif q.front == -1 {\n\t\treturn 0, errors.New(\"The queue is empty\")\n\t}\n\n\tif q.front == q.rear{\n\t\tv := q.value[q.front]\n\t\tq.value[q.front] = 0\n\t\tq.front =-1\n\t\tq.rear = -1\n\t\treturn v,nil\n\t} else {\n\t\tv := q.value[q.front]\n\t\tq.value[q.front] = 0\n\t\tq.front = (q.front + 1) % q.size\n\t\treturn v,nil\n\t}\n}", "func (d *Deck) PopBack() (string, error) {\n\tif d.head == d.tail {\n\t\treturn \"\", fmt.Errorf(\"nothing to pop\")\n\t}\n\td.tail -= inv\n\tif d.tail < 0 {\n\t\td.tail = cap(d.deck) - 1\n\t}\n\tres := d.deck[d.tail]\n\td.deck[d.tail] = \"\"\n\treturn res, nil\n}", "func (l *List) PushBack(newNode *Node) {\n\n\tl.size++\n \tl.tail = newNode\n \tif l.head == nil {\n \t\tl.head = newNode\n \t\treturn\n \t} \n\tcurrentNode := l.head\n\tfor currentNode.next != nil {\n\t\tcurrentNode = currentNode.next\n\t}\n\tcurrentNode.next = newNode \n}", "func (s *queue) pop() func() {\n\tif len(*s) > 0 {\n\t\tf := (*s)[0]\n\t\t*s = (*s)[1:]\n\t\treturn f\n\t}\n\n\treturn nil\n}", "func (self *Queue) Pop() {\n\tcurr := self.final.GetNext()\n\tif self.final.GetNext() == nil {\n\t\tself.final = nil\n\t} else {\n\t\tself.final.SetNext(curr.GetNext())\n\t}\n\tself.size--\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\tn := l.last\n\tif l.first == n {\n\t\tl.first = nil\n\t}\n\tl.last = n.prev\n\tif l.last != nil {\n\t\tl.last.next = nil\n\t}\n\treturn n.Val, nil\n}", "func (q *Queue) dequeue() int {\n\tif q.isEmpty() {\n\t\tfmt.Println(\"Queue empty\")\n\t\treturn -1\n\t}\n\tvalue := q.values[0]\n\tq.values = q.values[1:]\n\treturn value\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.Len == 0 {\n\t\treturn nil, ErrEmptyList\n\t}\n\tv := l.tail.Val\n\tl.tail = l.tail.prev\n\tl.Len--\n\tif l.Len == 0 {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\treturn v, nil\n}", "func (q *Queue) shift() {\n\tfor {\n\t\tv, ok := q.newest.Pop()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\n\t\tq.oldest.Push(v)\n\t}\n}", "func (l *List) PushBack(p *Process) {\n\t*l = append(*l, p)\n}", "func (self *Queue)Push(value interface{})(error){\r\n\tdefer self.pushkey.Release()\r\n\tself.pushkey.Get()\r\n\tif self.capacity==0 || self.capacity>self.list.Len(){\r\n\t\tself.list.PushBack(value)\r\n\t\tself.empty=false\r\n\t\treturn nil\r\n\t}else{\r\n\t\treturn errors.New(\"Queue is Full! it will ignore the new item to push in\")\r\n\t}\r\n}", "func (self *Queue) Push(data interface{}) {\n\tif self.final == nil {\n\t\tself.final = node.NewNode(data, nil)\n\t\tself.final.SetNext(self.final)\n\t} else {\n\t\tself.final.SetNext(node.NewNode(data, self.final.GetNext()))\n\t\tself.final = self.final.GetNext()\n\t}\n\tself.size++\n}", "func (q *Queue) Shift() {\r\n\tq.data = q.data[:len(q.data)-1]\r\n\tq.length--\r\n}", "func (q *PriorityQueue) Pop() {\n\tif q.size == 0 {\n\t\treturn\n\t}\n\tq.elements[0] = q.elements[q.size-1]\n\tq.elements[q.size-1] = nil\n\tq.size--\n\tq.siftdown()\n}", "func (l *List) PushFront(v interface{}) {\r\n\tif l.first == nil {\r\n\t\t// zerovalue for bool is false\r\n\t\tl.first = &Item{data: v, parent: l, invalidated: new(bool)}\r\n\t\tl.last = l.first\r\n\t} else {\r\n\t\tformerFirst := l.first\r\n\t\tl.first = &Item{data: v, next: formerFirst, parent: l, invalidated: new(bool)}\r\n\t\tformerFirst.prev = l.first\r\n\t}\r\n\tl.length++\r\n}", "func (this *MyQueue) Pop() int {\n\tthis.Peek()\n\te := this.b[len(this.b)-1]\n\tthis.b = this.b[:len(this.b)-1]\n\treturn e\n}", "func (this *myStack) push(val int) {\n\n\tdif := abcDiff(this.x, val)\n\tif dif >= this.maxDif {\n\t\treturn\n\t}\n\n\t// put to last position in list\n\tthis.result[this.lastId] = val\n\n\t// move to truth position\n\t// res must be sorted\n\tfor i := this.lastId; i > 0; i-- {\n\t\tif dif >= abcDiff(this.x, this.result[i-1]) {\n\t\t\tbreak\n\t\t}\n\t\tthis.result[i-1], this.result[i] = this.result[i], this.result[i-1]\n\t}\n\n\tthis.maxDif = abcDiff(this.x, this.result[this.lastId])\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.tail == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\n\tval := l.tail.Val\n\tl.tail = l.tail.prev\n\n\tif l.tail == nil {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\n\treturn val, nil\n}", "func (lst *List) PushBack(n Val_t){\n\tnewNode := &ListNode{Val:n}\n\tif lst.Len <= 0{\n\t\tlst.Head,lst.Tail = newNode,newNode\n\t}else{\n\t\tlst.Tail.Next = newNode\n\t\tlst.Tail = newNode\n\t}\n\tlst.Len++\n}", "func (d *Deque) Pop() (interface{}, error) {\n\tif d.length == 0 {\n\t\treturn nil, fmt.Errorf(\"Can not pop from an empty deque.\")\n\t}\n\n\titem := d.head.next\n\td.head.next = d.head.next.next\n\n\tif d.head.next != nil {\n\t\td.head.next.prev = d.head\n\t}\n\n\td.length--\n\n\treturn item.value, nil\n}", "func (q *baseCircularFifoQueue) Push(n interface{}) {\n\tif q.head == q.tail && q.count > 0 {\n\t\tLold := len(q.nodes) // old capacity\n\t\tLnew := q.fnExtendCap(Lold) // new capacity\n\t\t/*\n\t\t\tif Lnew < Lold {\n\t\t\t\tpanic(fmt.Sprintf(\"fnExtendCap(%d) -> %d : new cap must be greater the old cap!\", Lold, Lnew))\n\t\t\t}\n\t\t*/\n\t\tnodes := make([]interface{}, Lnew)\n\t\tcopy(nodes, q.nodes[q.head:])\n\t\tcopy(nodes[Lold-q.head:], q.nodes[:q.head])\n\t\tq.head = 0\n\t\tq.tail = Lold\n\t\tq.nodes = nodes\n\t}\n\tq.nodes[q.tail] = n\n\tq.tail = (q.tail + 1) % len(q.nodes)\n\tq.count++\n}", "func (q *objQueue) pushTail(obj types.Object) {\n\tif len(q.ring) == 0 {\n\t\tq.ring = make([]types.Object, 16)\n\t} else if q.head+len(q.ring) == q.tail {\n\t\t// Grow the ring.\n\t\tnring := make([]types.Object, len(q.ring)*2)\n\t\t// Copy the old elements.\n\t\tpart := q.ring[q.head%len(q.ring):]\n\t\tif q.tail-q.head <= len(part) {\n\t\t\tpart = part[:q.tail-q.head]\n\t\t\tcopy(nring, part)\n\t\t} else {\n\t\t\tpos := copy(nring, part)\n\t\t\tcopy(nring[pos:], q.ring[:q.tail%len(q.ring)])\n\t\t}\n\t\tq.ring, q.head, q.tail = nring, 0, q.tail-q.head\n\t}\n\n\tq.ring[q.tail%len(q.ring)] = obj\n\tq.tail++\n}", "func (l *sampleList) PushBack(sample *Sample) {\n\tsample.prev = l.tail\n\tsample.next = nil\n\tif l.head == nil {\n\t\tl.head = sample\n\t} else {\n\t\tl.tail.next = sample\n\t}\n\n\tl.tail = sample\n}" ]
[ "0.84234816", "0.82241744", "0.8054644", "0.7533997", "0.7354398", "0.7313678", "0.7304932", "0.729556", "0.72849613", "0.72223055", "0.7057391", "0.70428455", "0.7011919", "0.70089567", "0.70046943", "0.7002175", "0.695624", "0.6912441", "0.69081235", "0.6858717", "0.68019277", "0.67795944", "0.6774786", "0.676859", "0.6751622", "0.6734337", "0.6734266", "0.67274094", "0.6693038", "0.6668056", "0.6658781", "0.6658312", "0.6646343", "0.66369075", "0.6626903", "0.6609865", "0.65974694", "0.6502053", "0.64864904", "0.64840907", "0.6417397", "0.641024", "0.6397368", "0.63853806", "0.6341892", "0.6337198", "0.6307084", "0.6306799", "0.6304396", "0.62942356", "0.62942356", "0.6253907", "0.62538093", "0.6241191", "0.6236683", "0.6225426", "0.6215829", "0.6206252", "0.6190788", "0.6178675", "0.6174079", "0.61544585", "0.615034", "0.61392903", "0.61385983", "0.61323076", "0.6107065", "0.609722", "0.60922265", "0.60584265", "0.60537857", "0.6047036", "0.60429436", "0.6031745", "0.6029302", "0.6024314", "0.60228586", "0.60213727", "0.60164887", "0.6012487", "0.6011419", "0.6003435", "0.5997085", "0.59926116", "0.5988779", "0.5972622", "0.5967291", "0.59650284", "0.596267", "0.5961289", "0.5948763", "0.59431225", "0.59384775", "0.5922962", "0.5912502", "0.5909312", "0.58988917", "0.5888635", "0.5872704", "0.5871934" ]
0.80534244
3
Insert inserts a value to the position pos of the deque
func (d *Deque[T]) Insert(pos int, value T) { if pos < 0 || pos > d.size { return } if pos == 0 { d.PushFront(value) return } if pos == d.size { d.PushBack(value) return } seg, pos := d.pos(pos) if seg < d.segUsed()-seg { // seg is closer to the front d.moveFrontInsert(seg, pos, value) } else { // seg is closer to the back d.moveBackInsert(seg, pos, value) } d.size++ if d.segUsed() >= len(d.segs) { d.expand() } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ref Ref) Insert(x *Term, pos int) Ref {\n\tswitch {\n\tcase pos == len(ref):\n\t\treturn ref.Append(x)\n\tcase pos > len(ref)+1:\n\t\tpanic(\"illegal index\")\n\t}\n\tcpy := make(Ref, len(ref)+1)\n\tcopy(cpy, ref[:pos])\n\tcpy[pos] = x\n\tcopy(cpy[pos+1:], ref[pos:])\n\treturn cpy\n}", "func (q *PriorityQueue) Insert(value interface{}) {\n\tq.nodes = append(q.nodes, value)\n\tq.upHeap(len(q.nodes) - 1)\n}", "func (l *LinkedList) InsertAt(pos int, val interface{}) {\n\tn := &Node{value: val}\n\t// If the given position is lower than the list length\n\t// the element will be inserted at the end of the list\n\tswitch {\n\tcase l.length < pos:\n\t\tl.Insert(val)\n\tcase pos == 1:\n\t\tn.SetNext(l.head)\n\t\tl.head = n\n\tdefault:\n\t\tnode := l.head\n\t\t// Position - 2 since we want the element replacing the given position\n\t\tfor i := 1; i < (pos - 1); i++ {\n\t\t\tnode = node.Next()\n\t\t}\n\t\tn.SetNext(node.Next())\n\t\tnode.SetNext(n)\n\t}\n\n\tl.length = l.length + 1\n}", "func (c *CBuf) Insert(e interface{}) error {\n\tif c.len == c.cap {\n\t\treturn queue.ErrFull\n\t}\n\tc.elems[c.tail()] = e\n\tc.len++\n\treturn nil\n}", "func (ll *LinkedList) InsertAt(t Item, pos int) error {\n\tll.lock.RLock()\n\tdefer ll.lock.RUnlock()\n\n\tif ll.head == nil || pos < 0 || ll.count < pos {\n\t\treturn fmt.Errorf(\"Index out of bounds\")\n\t}\n\n\tnewNode := Node{t, nil}\n\tcurrent := ll.head\n\tindex := 0\n\n\tif pos == 0 {\n\t\tnewNode.next = ll.head\n\t\tll.head = &newNode\n\t\tll.count++\n\t\treturn nil\n\t}\n\n\tfor index < pos-2 {\n\t\tindex++\n\t\tcurrent = current.next\n\t}\n\n\tnewNode.next = current.next\n\tcurrent.next = &newNode\n\tll.count++\n\treturn nil\n}", "func (b *Bag) Insert(val rune) {\n\tb.data[val]++\n}", "func (o *KeyValueOrdered) Insert(key Key, idx int, value Value) {\n\to.Remove(key)\n\to.m[key] = idx\n\to.shift(idx, len(o.s), 1)\n\to.s = append(append(append(make([]KeyValueCapsule, 0, len(o.s)+1), o.s[:idx]...), KeyValueCapsule{key, value}), o.s[idx:]...)\n}", "func (dl *DoublyLinkedList) insert(position int32, value int32) bool {\n\tif dl.length == 0 || position >= dl.length {\n\t\treturn false\n\t}\n\tif position == 0 {\n\t\tdl.unshift(value)\n\t\treturn true\n\t} else if position == dl.length-1 {\n\t\tdl.push(value)\n\t\treturn true\n\t} else {\n\t\tnode := dl.get(position)\n\t\tnewNode := Node{value, nil, nil}\n\t\tnewNode.previous = node.previous\n\t\tnode.previous.next = &newNode\n\t\tnode.previous = &newNode\n\t\tnewNode.next = node\n\t\tdl.length++\n\t\treturn true\n\t}\n}", "func (m *MsgMemoryBuffer) Insert(value interface{}) {\n\tm.buff.Value = value\n\tm.buff = m.buff.Next()\n}", "func (l *List) Insert(pos int, v interface{}) error {\n\tif pos == 0 {\n\t\tl.head = &Node{v, l.head}\n\t\treturn nil\n\t}\n\n\tp := l.head\n\ti := pos - 1\n\tfor i != 0 {\n\t\tif p.next == nil {\n\t\t\treturn fmt.Errorf(\"%v is not a valid position for a %v long list\", pos, pos-i)\n\t\t}\n\t\tp = p.next\n\t\ti--\n\t}\n\n\tp.next = &Node{v, p.next}\n\treturn nil\n}", "func (t *Indexed) Insert(index, value int) {\n\tnewNode := NewNodeWithValue(index, value)\n\tl, r := t.split(t.root, index-1)\n\txl, xr := t.split(r, index)\n\tif xl == nil {\n\t\tt.size++\n\t}\n\tl = t.merge(l, newNode)\n\tt.root = t.merge(l, xr)\n}", "func (h *binaryHeap) Insert(val int) {\n\tidx := h.len + 1\n\tif h.idxOutOfRange(idx) { // bug\n\t\treturn\n\t}\n\th.len++\n\th.tree[idx] = h.doNegative(val)\n\th.bubbleUp(idx)\n}", "func (nl *nodeList) insert(i int, n *Node) {\n\t// Add a nil value to the end of the slice, to make room for the new Node.\n\tnl.elements = append(nl.elements, nil)\n\t// Copy values from the insertion point to the right by one\n\tcopy(nl.elements[i+1:], nl.elements[i:])\n\t// Set the value at the insertion point\n\tnl.elements[i] = n\n}", "func (e *ObservableEditableBuffer) Insert(p0 OffsetTuple, s []byte, nr int) {\n\tbefore := e.getTagStatus()\n\tdefer e.notifyTagObservers(before)\n\n\te.f.Insert(p0, s, nr, e.seq)\n\tif e.seq < 1 {\n\t\te.f.FlattenHistory()\n\t}\n\te.inserted(p0, s, nr)\n}", "func (q *dStarLiteQueue) insert(u *dStarLiteNode, k key) {\n\tu.key = k\n\theap.Push(q, u)\n}", "func (heap *MinHeap) Insert(val int) {\n\theap.elements = append(heap.elements, val)\n\theap.minHeapify(heap.getParent(heap.lastIndex()))\n}", "func (v *Data) Insert(idx int, val PicData) {\n\tdv := *v\n\t*v = append(append(append(make(Data, 0, len(dv)+1), dv[:idx]...), val), dv[idx:]...)\n}", "func (l *LinkedList) InsertAt(pos int, value interface{}) {\n\t// create a new node\n\tnewNode := Node{}\n\tnewNode.data = value\n\t// validate the position\n\tif pos < 0 {\n\t\tfmt.Println(\"Position can not be negative, skipping insertion of: \", value)\n\t\treturn\n\t}\n\tif pos == 0 && l.len == 0 {\n\t\tl.head = &newNode\n\t\tl.tail = &newNode\n\t\tl.len++\n\t\treturn\n\t}\n\tif pos > l.len {\n\t\tfmt.Println(\"Position can not be greater than list size\")\n\t\treturn\n\t}\n\tn := l.GetAt(pos)\n\tif n != nil {\n\t\tn.prev = &newNode\n\t}\n\tnewNode.next = n\n\tprevNode := l.GetAt(pos - 1)\n\tif prevNode != nil {\n\t\tprevNode.next = &newNode\n\t}\n\tnewNode.prev = prevNode\n\t// change tail with newly added node only if no node present at given position\n\tif n == nil {\n\t\tl.tail = &newNode\n\t} else if pos == 0 {\n\t\t// change head with newly added node only if adding node at 0th position\n\t\tl.head = &newNode\n\t}\n\tl.len++\n}", "func (gdt *Array) Insert(pos Int, value Variant) {\n\targ0 := gdt.getBase()\n\targ1 := pos.getBase()\n\targ2 := value.getBase()\n\n\tC.go_godot_array_insert(GDNative.api, arg0, arg1, arg2)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n if this.IsFull() {\n return false\n }\n this.head = (this.head - 1 + this.capacity) % this.capacity\n this.data[this.head] = value\n return true\n}", "func (s *Slab) Insert(val interface{}) int {\n\tkey := s.next\n\ts.insertAt(key, val)\n\treturn key\n}", "func (s *items) insertAt(index int, item Item) {\n\t*s = append(*s, nil)\n\tif index < len(*s) {\n\t\tcopy((*s)[index+1:], (*s)[index:])\n\t}\n\t(*s)[index] = item\n}", "func (d *Deque[T]) Set(pos int, val T) error {\n\tif pos < 0 || pos >= d.size {\n\t\treturn ErrOutOfRange\n\t}\n\tseg, pos := d.pos(pos)\n\td.segmentAt(seg).set(pos, val)\n\treturn nil\n}", "func (hat *HashedArrayTree) Insert(index int, values ...interface{}) error {\n\tlenValues := len(values)\n\tnewSize := hat.size + lenValues\n\tif err := hat.resize(newSize); err != nil {\n\t\treturn err\n\t}\n\t// Move items in the middle of the buffer by the length of values\n\tfor i := hat.size - 1; i >= index; i-- {\n\t\tbti, bli := hat.topIndex(i), hat.leafIndex(i)\n\t\tati, ali := hat.topIndex(i+lenValues), hat.leafIndex(i+lenValues)\n\t\that.top[ati][ali] = hat.top[bti][bli]\n\t}\n\tfor i, j := index, 0; i < index+lenValues; i, j = i+1, j+1 {\n\t\tti, li := hat.topIndex(i), hat.leafIndex(i)\n\t\that.top[ti][li] = values[j]\n\t}\n\that.size = newSize\n\treturn nil\n}", "func (q *Q) Insert(v interface{}, prio int32) {\n\n\trng := rdrand()\n\n\t// Implementing our own lock and spinning here is probably bad,\n\t// but sync.Mutex has no TryLock()\n\t// https://github.com/golang/go/issues/6123\n\tvar c uint32\n\tvar iter int\n\tfor {\n\t\trng = xorshiftMult64(rng)\n\t\tc = reduce(uint32(rng), len(q.locks))\n\t\tgotlock := q.locks[c].trylock()\n\t\tif gotlock {\n\t\t\tbreak\n\t\t}\n\t\titer++\n\t\tif iter >= len(q.locks) {\n\t\t\truntime.Gosched()\n\t\t}\n\t}\n\n\t// insert the item into priority queue c\n\theap.Push(&q.qs[c], &pq.Item{Value: v, Priority: prio})\n\n\t// update the stored minimum\n\tatomic.StoreInt32(&q.mins[c], q.qs[c][0].Priority)\n\n\t// unlock\n\tq.locks[c].unlock()\n}", "func (sl *Slice) Insert(k Ki, idx int) {\n\tSliceInsert((*[]Ki)(sl), k, idx)\n}", "func (fdb *fdbSlice) Insert(k Key, v Value) error {\n\n\tfdb.cmdCh <- kv{k: k, v: v}\n\treturn fdb.fatalDbErr\n\n}", "func (h *Heap) Insert(data interface{}) {\n\tif h.size == 0 {\n\t\th.values = append([]interface{}{nil}, data)\n\t\th.size++\n\t} else {\n\t\th.values = append(h.values, data)\n\t\th.size++\n\t\th.bubbleUp()\n\t}\n}", "func (a *DynamicArray) Insert(index int, value int) error {\n\tif index < 0 || index > a.len {\n\t\treturn ErrArrIndexOutOfBound\n\t}\n\tif a.len == a.cap {\n\t\ta.resize(a.cap * 2)\n\t}\n\n\t// if insert value in the middle of array, shift the elements after index\n\tif index < a.len {\n\t\tcopy(a.data[index+1:], a.data[index:])\n\t}\n\ta.data[index] = value\n\ta.len++\n\n\treturn nil\n}", "func (list *List) Insert(idx int, element interface{}) error {\n\tif list.Length() < idx || idx < 0 {\n\t\treturn fmt.Errorf(\"index out of range\")\n\t}\n\tlist_ := []interface{}(*list)\n\t*list = append(list_[:idx], append([]interface{}{element}, list_[idx:]...)...)\n\treturn nil\n}", "func (node *LinkList) InsertAtPos(data, pos int) {\n\tif node == nil {\n\t\tfmt.Println(\"list is empty\")\n\t\treturn\n\t}\n\tnewNode := new(LinkList)\n\tnewNode.data = data\n\tnewNode.next = nil\n\tcount := 1\n\ttemp := node\n\tfor temp.next != nil && count < pos {\n\t\ttemp = temp.next\n\t\tcount++\n\t}\n\tif count < pos {\n\t\tfmt.Println(\"Not enough element present in the list\")\n\t\treturn\n\t}\n\tnewNode.next = temp.next\n\ttemp.next = newNode\n}", "func insert(array []int8, val int8, pos int) []int8 {\r\n\tvar length = len(array)\r\n\tvar tempArray = make([]int8, length+1)\r\n\tfmt.Printf(\"\\n\")\r\n\r\n\t// copy each value from start to position\r\n\t// leave the pos we want to fill empty and copy each value after that\r\n\t// eg at pos 3: 1 2 3 x 4 5 6 7 -> 1 2 3 21 4 5 6 7\r\n\r\n\tfor i := 0; i < length; i++ {\r\n\t\tif i < pos {\r\n\t\t\ttempArray[i] = array[i]\r\n\t\t} else {\r\n\t\t\ttempArray[i+1] = array[i]\r\n\t\t}\r\n\t}\r\n\r\n\ttempArray[pos] = val\r\n\treturn tempArray\r\n}", "func (v *IntVec) Insert(idx int, val ...int) {\n\tdv := *v\n\tdv = append(dv, val...)\n\tcopy(dv[idx+len(val):], dv[idx:])\n\tcopy(dv[idx:], val)\n\t*v = dv\n}", "func (o *Outline) Insert(index uint, item *OutlineItem) {\n\tl := uint(len(o.items))\n\tif index > l {\n\t\tindex = l\n\t}\n\n\to.items = append(o.items[:index], append([]*OutlineItem{item}, o.items[index:]...)...)\n}", "func (h *heap) insert(a int) error {\n\tif h.n == cap(h.q) {\n\t\treturn errors.New(\"Error: heap overflow\")\n\t}\n\n\th.q[h.n] = a\n\tbubbleUp(h, h.n)\n\th.n++\n\n\treturn nil\n}", "func (n *Node) Insert(v Boxer) {\n\t// If this node does not contain the given box return.\n\tif !n.boundingBox.ContainsCenter(v.Box()) {\n\t\treturn\n\t}\n\n\ti := n.index(v)\n\n\tif i == -1 {\n\t\tn.values = append(n.values, v)\n\n\t\tif len(n.values) > maxNodeSize {\n\t\t\tn.split()\n\t\t}\n\t} else {\n\t\tn.children[i].Insert(v)\n\t}\n}", "func (p *PriorityQueue) Insert(v interface{}, priority float64) {\n\t_, ok := p.lookup[v]\n\tif ok {\n\t\treturn\n\t}\n\n\tnewItem := &item{\n\t\tvalue: v,\n\t\tpriority: priority,\n\t}\n\theap.Push(p.itemHeap, newItem)\n\tp.lookup[v] = newItem\n}", "func (h *Heap) Insert(value int) {\n\tif h.count >= h.capacity {\n\t\treturn\n\t}\n\th.array[h.count] = value\n\th.heapify(h.count, h.cmpFunc)\n\th.count++\n}", "func (s *children) insertAt(index int, n *node) {\n\t*s = append(*s, nil)\n\tif index < len(*s) {\n\t\tcopy((*s)[index+1:], (*s)[index:])\n\t}\n\t(*s)[index] = n\n}", "func (s *SweepPruneSet[T]) Insert(position dprec.Vec3, radius float64, value T) SweepPruneItemID {\n\tvar itemIndex uint32\n\tif !s.freeItemIDs.IsEmpty() {\n\t\titemIndex = s.freeItemIDs.Pop()\n\t} else {\n\t\titemIndex = uint32(len(s.items))\n\t\ts.items = append(s.items, sweepPruneItem[T]{})\n\t\ts.seriesX = append(s.seriesX, sweepPruneMarker{\n\t\t\tItemIndex: itemIndex,\n\t\t\tIsStart: true,\n\t\t})\n\t\ts.seriesX = append(s.seriesX, sweepPruneMarker{\n\t\t\tItemIndex: itemIndex,\n\t\t\tIsStart: false,\n\t\t})\n\t\ts.seriesY = append(s.seriesY, sweepPruneMarker{\n\t\t\tItemIndex: itemIndex,\n\t\t\tIsStart: true,\n\t\t})\n\t\ts.seriesY = append(s.seriesY, sweepPruneMarker{\n\t\t\tItemIndex: itemIndex,\n\t\t\tIsStart: false,\n\t\t})\n\t\ts.seriesZ = append(s.seriesZ, sweepPruneMarker{\n\t\t\tItemIndex: itemIndex,\n\t\t\tIsStart: true,\n\t\t})\n\t\ts.seriesZ = append(s.seriesZ, sweepPruneMarker{\n\t\t\tItemIndex: itemIndex,\n\t\t\tIsStart: false,\n\t\t})\n\t}\n\titem := &s.items[itemIndex]\n\titem.Position = position\n\titem.Radius = radius\n\titem.Value = value\n\ts.dirtyItemIDs[itemIndex] = struct{}{}\n\treturn SweepPruneItemID(itemIndex)\n}", "func Insert(value, index int) {\n\tnewNode := &Node{value: value, freq: 1}\n\tif index >= size {\n\t\tfmt.Println(\"\\n-- Not enough space in array. --\")\n\t\treturn\n\t}\n\tif bst[index] == nil {\n\t\tbst[index] = newNode\n\t} else if bst[index].value == value {\n\t\tbst[index].freq++\n\t} else {\n\t\tif value < bst[index].value {\n\t\t\tInsert(value, (index*2)+1)\n\t\t} else {\n\t\t\tInsert(value, (index*2)+2)\n\t\t}\n\t}\n}", "func (bids *Bids) insert(index int, Bid Bid) {\n\tif len(bids.ticks) == index { // nil or empty slice or after last element\n\t\tbids.ticks = append(bids.ticks, Bid)\n\t}\n\tbids.ticks = append(bids.ticks[:index+1], bids.ticks[index:]...) // index < len(a)\n\tbids.ticks[index] = Bid\n}", "func (d *Deque[T]) PushFront(value T) {\n\td.firstAvailableSegment().pushFront(value)\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func insert(slice []int, index, value int) []int {\n // Grow the slice by one element.\n slice = slice[0 : len(slice)+1]\n // Use copy to move the upper part of the slice out of the way and open a hole.\n copy(slice[index+1:], slice[index:])\n // Store the new value.\n slice[index] = value\n // Return the result.\n return slice\n}", "func insert(x []int, index, value int) []int {\n\t// Grow the slice by one element.\n\tx = x[0 : len(x)+1]\n\t// Create room for new element.\n\tcopy(x[index+1:], x[index:])\n\t// Insert the new element.\n\tx[index] = value\n\treturn x\n}", "func (recv *ValueArray) Insert(index uint32, value *Value) *ValueArray {\n\tc_index_ := (C.guint)(index)\n\n\tc_value := (*C.GValue)(C.NULL)\n\tif value != nil {\n\t\tc_value = (*C.GValue)(value.ToC())\n\t}\n\n\tretC := C.g_value_array_insert((*C.GValueArray)(recv.native), c_index_, c_value)\n\tretGo := ValueArrayNewFromC(unsafe.Pointer(retC))\n\n\treturn retGo\n}", "func (a *Array) Insert(index uint, v int) error {\n\t// data is full\n\tif a.Len() == uint(cap(a.data)) {\n\t\treturn errors.New(\"array is full\")\n\t}\n\n\t// index is out of range\n\tif a.IsIndexOutOfRange(index) {\n\t\treturn errors.New(\"out of index range\")\n\t}\n\n\tfor i := a.Len(); i > index; i++ {\n\t\ta.data[i] = a.data[i-1]\n\t}\n\ta.data[index] = v\n\ta.length++\n\treturn nil\n}", "func (d *DirectAddress) Insert(key int, value interface{}) {\n\tif err := d.validateKey(key); err != nil {\n\t\treturn\n\t}\n\td.array[key-d.uMin] = value\n}", "func (m *PriorityQueue) Insert(item *PqItem) error {\r\n\tm.heapArray = append(m.heapArray, item)\r\n\tm.size++\r\n\tm.upHeapify(m.size - 1)\r\n\treturn nil\r\n}", "func (pq *PQueue) insert(val int) {\n\tif pq.pos <= pq.max {\n\t\tpq.queue[pq.pos] = val\n\t\t\n\t\tfor i := pq.pos ; i>1 ; i/=2 {\n\t\t\tif pq.queue[i] > pq.queue[i/2] {\n\t\t\t\tpq.queue[i], pq.queue[i/2] = pq.queue[i/2], pq.queue[i]\n\t\t\t}\n\t\t}\n\t\t\n\t\tpq.pos++\n\t} else {\n\t\t// going to use the extra slot.\n\t\tpq.queue[pq.pos] = val\n\n\t\tfor i := pq.pos ; i>1 ; i/=2 {\n\t\t\tif pq.queue[i] > pq.queue[i/2] {\n\t\t\t\tpq.queue[i], pq.queue[i/2] = pq.queue[i/2], pq.queue[i]\n\t\t\t}\n\t\t}\n\n\t\t// remove ever item except the last item.\n\t\ttmp := make([]int, 0)\n\t\tfor i := 0 ; i < pq.pos ; i++ {\n\t\t\ttmp = append(tmp, pq.removeMax())\n\t\t}\n\n\t\t// insert again.\n\t\tfor k := 0 ; k < len(tmp) ; k++ {\n\t\t\tpq.queue[pq.pos] = tmp[k]\n\t\t\n\t\t\tfor i := pq.pos ; i>1 ; i/=2 {\n\t\t\t\tif pq.queue[i] > pq.queue[i/2] {\n\t\t\t\t\tpq.queue[i], pq.queue[i/2] = pq.queue[i/2], pq.queue[i]\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tpq.pos++\n\t\t}\n\t}\n}", "func (h *Heap) Insert(v ...int) {\n for _, val := range(v){\n h.data = append(h.data, val)\n }\n\n n := len(h.data)\n\n i := (float64) ((n / 2) - 1)\n h.num_nodes = (int) (math.Floor(i))\n}", "func insert(a []int, index int, value int) []int {\r\n\tif len(a) == index { // nil or empty slice or after last element\r\n\t\treturn append(a, value)\r\n\t}\r\n\ta = append(a[:index+1], a[index:]...) // index < len(a)\r\n\ta[index] = value\r\n\treturn a\r\n}", "func (oi *OutlineItem) Insert(index uint, item *OutlineItem) {\n\tl := uint(len(oi.items))\n\tif index > l {\n\t\tindex = l\n\t}\n\n\toi.items = append(oi.items[:index], append([]*OutlineItem{item}, oi.items[index:]...)...)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.len == this.cap {\n\t\treturn false\n\t}\n\tthis.l.PushFront(value)\n\tthis.len++\n\treturn true\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tthis.front = (len(this.data) + this.front - 1) % len(this.data)\n\tthis.data[this.front] = value\n\treturn true\n}", "func (l *LinkedList) Insert(index int, value interface{}) error {\n\t// Abort if index is not valid\n\tif index > l.length+1 || index <= 0 {\n\t\treturn errors.New(\"index is not valid. It should be between 1 and the length of the list + 1\")\n\t}\n\n\tp := l.head\n\tif p == nil {\n\t\tl.head = &Node{value: value}\n\t\tl.length++\n\t\treturn nil\n\t}\n\n\tif index == 1 {\n\t\tnewNode := &Node{value: value}\n\t\tl.Prepend(newNode)\n\t\treturn nil\n\t}\n\n\t// loop until the place right before the desired spot (index - 2)\n\tfor i := 0; i < index-2; i++ {\n\t\tp = p.next\n\t}\n\n\t// Save next node\n\taux := p.next\n\tp.next = &Node{value: value, next: aux}\n\tl.length++\n\treturn nil\n}", "func (s *nodeBlock) insertItemAt(index int, item Metadata) {\n\t_ = s.items[maxItems-1-s.itemsSize]\n\tcopy(s.items[index+1:], s.items[index:])\n\ts.items[index] = item\n\ts.itemsSize++\n\ts.markDirty()\n}", "func (e *ObservableEditableBuffer) InsertAt(rp0 int, rs []rune) {\n\tp0 := e.f.RuneTuple(rp0)\n\ts, nr := RunesToBytes(rs)\n\n\te.Insert(p0, s, nr)\n}", "func (p *IntVector) Insert(i int, x int)\t{ p.Vector.Insert(i, x) }", "func (i *Input) Insert(r rune) {\n\ti.Buffer.InsertRune(r, i.Pos)\n\ti.Pos++\n}", "func (fb *FlowBox) Insert(widget IWidget, position int) {\n\tC.gtk_flow_box_insert(fb.native(), widget.toWidget(), C.gint(position))\n}", "func (w *Window) Insert(e interface{}) {\n\tw.insertAt(time.Now(), e)\n}", "func (h *heap) insert(e int) {\n\th.H[h.V] = e;\n\th.bubble_up(h.V);\n\th.V++;\n}", "func (q *Queue) Insert(l Lit) {\n\tq.items = append(q.items, l)\n}", "func (h *MinHeap) Insert(value int) {\n\th.Heap = append(h.Heap, value)\n\th.siftUp(len(h.Heap) - 1)\n}", "func (a *Array) Insert(index uint, v int) error {\n\tif a.Len() == uint(cap(a.data)) {\n\t\treturn errors.New(\"full array\")\n\t}\n\t// Call the Insert function directly, index must be an existing subscript\n \n\tif index != a.length && a.isIndexOutOfRange(index) {\n\t\treturn errors.New(\"out of index range\")\n\t}\n\tfor i := a.length; i > index; i-- {\n\t\ta.data[i] = a.data[i-1]\n\t}\n\ta.data[index] = v\n\ta.length++\n\treturn nil\n}", "func (s *SliceInt) Insert(index, value int) *SliceInt {\n\t// Grow the slice by one element.\n\ts.data = s.data[0 : len(s.data)+1]\n\t// Use copy to move the upper part of the slice out of the way and open a hole.\n\tcopy(s.data[index+1:], s.data[index:])\n\t// Store the new value.\n\ts.data[index] = value\n\t// Return the result.\n\treturn s\n}", "func (t *Tree) Insert(v interface{}) {\n\tvar flags Flags\n\tif t.root, flags = t.root.insert(v, t.lessFunc); flags&FLAGS_IS_INSERTED != FLAGS_NONE {\n\t\tt.len++\n\t}\n}", "func (v *nodes) insert(ele int) {\r\n\tif len(v.n) == 0 {\r\n\t\tv.n = append(v.n, node{ele, -1, -1, -1, 0})\r\n\t\treturn\r\n\t}\r\n\ti := 0\r\n\tfor true {\r\n\t\tif ele <= v.n[i].value {\r\n\t\t\tif v.n[i].left < 0 {\r\n\t\t\t\tv.n = append(v.n, node{ele, i, -1, -1, 0})\r\n\t\t\t\tv.n[i].left = len(v.n)-1\r\n\t\t\t\tbreak\r\n\t\t\t} else {\r\n\t\t\t\ti = v.n[i].left\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif v.n[i].right < 0 {\r\n\t\t\t\tv.n = append(v.n, node{ele, i, -1, -1, 0})\r\n\t\t\t\tv.n[i].right = len(v.n)-1\r\n\t\t\t\tbreak\r\n\t\t\t} else {\r\n\t\t\t\ti = v.n[i].right\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n}", "func Insert(str string, pos int, value string) string {\n\treturn string([]rune(str)[:pos]) + value + string([]rune(str)[pos:])\n}", "func (tree *Tree) Insert(value int) {\n\ttree.root, _ = tree.root.Insert(value)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\n\tthis.mutex.Lock()\n\tdefer this.mutex.Unlock()\n\tthis.front = (this.front - 1 + this.capacity) % this.capacity\n\tthis.data[this.front] = value\n\treturn true\n}", "func (list *List) Insert(index int, values ...interface{}) {\n\n\tif !list.withinRange(index) {\n\t\t// Append\n\t\tif index == list.size {\n\t\t\tlist.Add(values...)\n\t\t}\n\t\treturn\n\t}\n\n\tlist.size += len(values)\n\n\tvar beforeElement *element\n\tfoundElement := list.first\n\tfor e := 0; e != index; e, foundElement = e+1, foundElement.next {\n\t\tbeforeElement = foundElement\n\t}\n\n\tif foundElement == list.first {\n\t\toldNextElement := list.first\n\t\tfor i, value := range values {\n\t\t\tnewElement := &element{value: value}\n\t\t\tif i == 0 {\n\t\t\t\tlist.first = newElement\n\t\t\t} else {\n\t\t\t\tbeforeElement.next = newElement\n\t\t\t}\n\t\t\tbeforeElement = newElement\n\t\t}\n\t\tbeforeElement.next = oldNextElement\n\t} else {\n\t\toldNextElement := beforeElement.next\n\t\tfor _, value := range values {\n\t\t\tnewElement := &element{value: value}\n\t\t\tbeforeElement.next = newElement\n\t\t\tbeforeElement = newElement\n\t\t}\n\t\tbeforeElement.next = oldNextElement\n\t}\n}", "func (dl *DcmList) Insert(obj *DcmObject, pos E_ListPos) *DcmObject {\n\tif obj != nil {\n\t\tif dl.Empty() { // list is empty !\n\t\t\tdl.currentNode = NewDcmListNode(obj)\n\t\t\tdl.firstNode = dl.currentNode\n\t\t\tdl.lastNode = dl.currentNode\n\t\t\tdl.cardinality = dl.cardinality + 1\n\t\t} else {\n\t\t\tif pos == ELP_last {\n\t\t\t\tdl.Append(obj) // cardinality++;\n\t\t\t} else if pos == ELP_first {\n\t\t\t\tdl.Prepend(obj) // cardinality++;\n\t\t\t} else if dl.Valid() != true {\n\t\t\t\t// set current node to the end if there is no predecessor or\n\t\t\t\t// there are successors to be determined\n\t\t\t\tdl.Append(obj) // cardinality++;\n\t\t\t} else if pos == ELP_prev { // insert before current node\n\t\t\t\tnode := NewDcmListNode(obj)\n\t\t\t\tif dl.currentNode.prevNode == nil {\n\t\t\t\t\tdl.firstNode = node // insert at the beginning\n\t\t\t\t} else {\n\t\t\t\t\tdl.currentNode.prevNode.nextNode = node\n\t\t\t\t}\n\t\t\t\tnode.prevNode = dl.currentNode.prevNode\n\t\t\t\tnode.nextNode = dl.currentNode\n\t\t\t\tdl.currentNode.prevNode = node\n\t\t\t\tdl.currentNode = node\n\t\t\t\tdl.cardinality = dl.cardinality + 1\n\t\t\t} else { //( pos==ELP_next || pos==ELP_atpos )\n\t\t\t\t// insert after current node\n\t\t\t\tnode := NewDcmListNode(obj)\n\t\t\t\tif dl.currentNode.nextNode == nil {\n\t\t\t\t\tdl.lastNode = node // append to the end\n\t\t\t\t} else {\n\t\t\t\t\tdl.currentNode.nextNode.prevNode = node\n\t\t\t\t}\n\t\t\t\tnode.nextNode = dl.currentNode.nextNode\n\t\t\t\tnode.prevNode = dl.currentNode\n\t\t\t\tdl.currentNode.nextNode = node\n\t\t\t\tdl.currentNode = node\n\t\t\t\tdl.cardinality = dl.cardinality + 1\n\t\t\t}\n\t\t}\n\t}\n\treturn obj\n}", "func (bh* BinomialHeap) Insert(value int) {\n bh.size += 1\n\n newnode := newBinomialHeapNode(value)\n bh.insert(newnode)\n}", "func (s *S43_SmallSetOfIntegers) Insert(n int, done chan bool) {\n\tdefer close(done)\n\n\ti := s.SEARCH(n)\n\tif i < s.size {\n\t\tdone <- false\n\t\treturn // nothing to do\n\t}\n\t// not found, insert to the array\n\tif i == s.size && s.size < 100 {\n\t\ts.content[s.size] = n\n\t\ts.size++\n\t\tdone <- true\n\t\treturn\n\t}\n\n\tdone <- false\n\treturn\n}", "func (d *Deque) Inject(value interface{}) error {\n\tn := &node{}\n\tn.value = value\n\n\td.tail.next = n\n\tn.prev = d.tail\n\td.tail = n\n\n\td.length++\n\treturn nil\n}", "func (d *dll) insert(i int) {\n\tn := new(node)\n\n\tn.x = i\n\tn.prev = d.dummy\n\tn.next = d.dummy.next\n\n\td.dummy.next.prev = n\n\td.dummy.next = n\n\n}", "func (list *Linked_List) Insert_Before_At(index int, data interface{}) {\n\tlist.Insert_Before(list.At(index), data)\n}", "func insertIndex(index []byte, c byte, idx int) {\n\t// Append to \"grow\" the slice, should never reallocate so we don't need to\n\t// return the slice to the caller since the underlying byte array has been\n\t// modified as desired.\n\tindex = append(index, c)\n\tcopy(index[idx+1:], index[idx:])\n\tindex[idx] = c\n}", "func (h *MinHeap) Insert(value int) {\n\t// return if the heap is full\n\tif h.IsFull() {\n\t\treturn\n\t}\n\n\th.used++\n\th.data[h.used] = value\n\n\tfor i := h.used; i>>1 > 0 && h.data[i] < h.data[i>>1]; i >>= 1 {\n\t\th.data[i], h.data[i>>1] = h.data[i>>1], h.data[i]\n\t}\n}", "func (b *BTree) insertInNodeAtIdx(n *memNode, item *Item, i int) {\n\ts := n.node.Items\n\ts = append(s, nil)\n\tif i < len(s) {\n\t\tcopy(s[i+1:], s[i:])\n\t}\n\ts[i] = item\n\tn.node.Items = s\n}", "func (lst *List) InsertAt(idx int, n Val_t){\n\tif(idx < 0 || idx > lst.Len){\n\t\tpanic(\"index is out of boundary\")\n\t}\n\n\tnewNode := &ListNode{Val:n}\n\n\tdummy := &ListNode{Val:math.MaxInt32}\n\tdummy.Next = lst.Head\n\tpre,cur := dummy,dummy.Next\n\tfor idx > 0{\n\t\tpre = cur\n\t\tcur = cur.Next\n\t\tidx--\n\t}\n\n\t//insert new node\n\tpre.Next = newNode\n\tnewNode.Next = cur\n\t\n\t//update the ref of head and tail\n\tlst.Len++\n\tlst.Head = dummy.Next\n\n\ttail := lst.Head\n\tfor tail.Next != nil{\n\t\ttail = tail.Next\n\t}\n\tlst.Tail = tail\n}", "func (h *Heap) Insert(e *Element, k int) {\n\th.size++\n\th.root = insert(e, k, h.root)\n}", "func (h *_heap) Insert(values ...interface{}) {\n\tif len(values) == 1 {\n\t\theap.Push(h, values[0])\n\t} else {\n\t\tvar correctedValues []containers.Container\n\t\tvar total int\n\t\tfor _, value := range values {\n\t\t\tcorrectedValues = append(correctedValues, h.datatype.Validate(value))\n\t\t\ttotal++\n\t\t}\n\t\th.data = append(h.data, correctedValues...)\n\t\th.size = h.size + total\n\t\theap.Init(h)\n\t}\n}", "func (d *Data) Insert(items ...interface{}) {\n\tfor _, value := range items {\n\t\td.Lock()\n\t\tv, ok := d.m[value]\n\t\td.Unlock()\n\t\tif ok {\n\t\t\td.Lock()\n\t\t\td.m[value] = v + 1\n\t\t\td.Unlock()\n\t\t\tcontinue\n\t\t}\n\t\td.Lock()\n\t\td.m[value] = 1\n\t\td.Unlock()\n\t}\n}", "func (d *Deque[T]) PushBack(value T) {\n\td.lastAvailableSegment().pushBack(value)\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (q *Deque) PushFront(v interface{}) {\n\tif q.size == cap(q.values) {\n\t\tnewCap := 2\n\t\tif cap(q.values) > 0 {\n\t\t\tnewCap = cap(q.values) * 2\n\t\t}\n\t\tq.Resize(newCap)\n\t}\n\n\tq.front--\n\tif q.front < 0 {\n\t\tq.front = cap(q.values) - 1\n\t}\n\n\tq.values[q.front] = v\n\tq.size++\n}", "func (bst *BST) Insert(val interface{}) *Node {\n\treturn InsertItem(bst, val)\n}", "func (t *TopK) insert(data []byte, freq uint64) {\n\tfor i, element := range *t.elements {\n\t\tif bytes.Equal(data, element.Data) {\n\t\t\t// Element already in top-k, replace it with new frequency.\n\t\t\theap.Remove(t.elements, i)\n\t\t\telement.Freq = freq\n\t\t\theap.Push(t.elements, element)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif t.elements.Len() == int(t.k) {\n\t\t// Remove minimum-frequency element.\n\t\theap.Pop(t.elements)\n\t}\n\n\t// Add element to top-k.\n\theap.Push(t.elements, &Element{Data: data, Freq: freq})\n}", "func (q *quartileIndex) Insert(n int, at int) error {\n\tif n%4 != 0 {\n\t\tpanic(\"can only extend by nibbles (multiples of 4)\")\n\t}\n\terr := q.bits.Insert(n, at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tnewlen := q.bits.Len()\n\tfor i := 0; i < 3; i++ {\n\t\tq.adjust(i, n, at, (newlen * (i + 1) / 4))\n\t}\n\treturn nil\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tthis.len++\n\tthis.head = (this.head + 1) % this.size\n\tthis.queue[this.head] = value\n\treturn true\n}", "func (h *binaryHeap) Insert(items ...int) {\n\tif h.size+len(items) >= len(h.items) {\n\t\th.resize(len(items))\n\t}\n\tfor _, element := range items {\n\t\th.items[h.size] = element\n\t\th.size++\n\t\th.siftup(h.size - 1)\n\t}\n}", "func (b *Buffer) Insert(o, n int) {\n\tp := make([]*Tile, n)\n\tb.Tiles = append(b.Tiles[:o], append(p, b.Tiles[o:]...)...)\n}", "func (vector *Vector) Insert(i int, element interface{}) {\n\t//a = append(a[:i], append([]T{x}, a[i:]...)...)\n\t// NOTE The second append creates a new slice with its own underlying storage and copies\n\t// elements in a[i:] to that slice, and these elements are then copied back to slice a\n\t// (by the first append). The creation of the new slice (and thus memory garbage) and the\n\t// second copy can be avoided by using an alternative way:\n\n\t*vector = append(*vector, 0 /* use the zero value of the element type */)\n\tcopy((*vector)[i+1:], (*vector)[i:])\n\t(*vector)[i] = element\n}", "func (rbst *RBSTAbelGroup) Insert(root *Node, pos int, node *Node) *Node {\r\n\tn := rbst.Size(root)\r\n\tif pos < 0 {\r\n\t\tpos += n\r\n\t}\r\n\tif pos < 0 {\r\n\t\tpos = 0\r\n\t}\r\n\tif pos > n {\r\n\t\tpos = n\r\n\t}\r\n\tleft, right := rbst.SplitByRank(root, pos)\r\n\treturn rbst.Merge(left, rbst.Merge(node, right))\r\n}", "func (b *Builder) Insert(key []byte, val uint64) error {\n\t// ensure items are added in lexicographic order\n\tif bytes.Compare(key, b.last) < 0 {\n\t\treturn ErrOutOfOrder\n\t}\n\tif len(key) == 0 {\n\t\tb.len = 1\n\t\tb.unfinished.setRootOutput(val)\n\t\treturn nil\n\t}\n\n\tprefixLen, out := b.unfinished.findCommonPrefixAndSetOutput(key, val)\n\tb.len++\n\terr := b.compileFrom(prefixLen)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.copyLastKey(key)\n\tb.unfinished.addSuffix(key[prefixLen:], out)\n\n\treturn nil\n}", "func (s *nodeBlock) insertChildAt(index int, n *nodeBlock) {\n\t_ = s._children[maxChildren-1-s.childrenSize]\n\tcopy(s._children[index+1:], s._children[index:])\n\tcopy(s.childrenOffset[index+1:], s.childrenOffset[index:])\n\ts._children[index] = n\n\ts.childrenOffset[index] = n.offset\n\ts.childrenSize++\n\ts.markDirty()\n}", "func (v *TreeStore) Insert(parent *TreeIter, position int) *TreeIter {\n\tvar ti C.GtkTreeIter\n\tvar cParent *C.GtkTreeIter\n\tif parent != nil {\n\t\tcParent = parent.native()\n\t}\n\tC.gtk_tree_store_insert(v.native(), &ti, cParent, C.gint(position))\n\titer := &TreeIter{ti}\n\treturn iter\n}", "func (t *BinarySearchTree) Insert(v interface{}) {\n\n}" ]
[ "0.7247191", "0.70202947", "0.68909967", "0.6774521", "0.67006373", "0.6673834", "0.66587466", "0.6604654", "0.659842", "0.65970945", "0.65699613", "0.65685594", "0.6564811", "0.6559058", "0.6536338", "0.65324277", "0.6524486", "0.6516789", "0.6509166", "0.6507782", "0.6500091", "0.649124", "0.6467677", "0.6457501", "0.63618565", "0.63592666", "0.63589495", "0.6352855", "0.6350132", "0.63409114", "0.63380796", "0.6308945", "0.630172", "0.62983865", "0.6283173", "0.62828666", "0.62764543", "0.62761694", "0.62673235", "0.623722", "0.62355256", "0.6234108", "0.6207403", "0.61924803", "0.61909425", "0.6188679", "0.616767", "0.6163374", "0.61603093", "0.6156327", "0.6148593", "0.6145222", "0.6144047", "0.6142601", "0.6136269", "0.6134521", "0.6132066", "0.6124045", "0.6116276", "0.6109938", "0.61045766", "0.60997057", "0.6098938", "0.6090511", "0.6089871", "0.6078857", "0.6076155", "0.60749143", "0.6070347", "0.6063516", "0.60530174", "0.6049992", "0.6046613", "0.6043317", "0.60407317", "0.60364187", "0.603103", "0.6030878", "0.6018501", "0.60139394", "0.60101795", "0.6010089", "0.6004267", "0.60042495", "0.599166", "0.5983848", "0.596224", "0.59592515", "0.59557635", "0.5952327", "0.59522116", "0.594946", "0.594869", "0.59444237", "0.59424394", "0.59289014", "0.5918892", "0.59124", "0.5905642", "0.5903838" ]
0.84035724
0
Front returns the value at the first position of the deque
func (d *Deque[T]) Front() T { return d.firstSegment().front() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Deque) Front() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.front]\n\t}\n\treturn nil\n}", "func (d *MyCircularDeque) GetFront() int {\n\tif d.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn d.Val[0]\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.head.value\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.First.Next.Data\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.length == 0 {\n\t\treturn -1\n\t}\n\treturn this.head.next.val\n}", "func (this *MyCircularDeque1) GetFront() int {\n\treturn this.head.Next.Val\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\n\treturn this.data[this.front]\n}", "func (this *MyCircularDeque) GetFront() int {\n if this.IsEmpty() {\n return -1\n }\n return this.data[this.head]\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\n\tthis.mutex.RLock()\n\tdefer this.mutex.RUnlock()\n\treturn this.data[this.front]\n\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.len == 0 {\n\t\treturn -1\n\t}\n\treturn this.queue[this.head]\n}", "func (dq *Dqueue) Front() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\treturn\n}", "func (q *queue) Front() (interface{}, error) {\n\tif q.Empty() {\n\t\treturn nil, errors.New(\"error: can not get element from empty queue\")\n\t}\n\treturn q.items[q.head].Data, nil\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.len <= 0 {\n\t\treturn -1\n\t}\n\n\tn := this.l.Front().Value.(int)\n\treturn n\n}", "func (q *Queue) Front() interface{} {\n\treturn q.data[q.head]\n}", "func (this *MyCircularQueue) Front() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.items[this.front]\n}", "func (mcq *MyCircularQueue) Front() int {\n\tif mcq.length == 0 {\n\t\treturn -1\n\t}\n\treturn mcq.dummyHead.Next.Val\n}", "func (q *SliceQueue) Front() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\treturn q.Data[0]\n}", "func (this *MyCircularQueue) Front() int {\n\tif this.Count == 0 {\n\t\treturn -1\n\t}\n\treturn this.Queue[this.Head]\n}", "func (d *Deque) Front() (*interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\treturn &d.front.data, true\n}", "func (this *MyCircularQueue) Front() int {\n\treturn this.CircularQueue[this.Head]\n}", "func (this *MyCircularQueue) Front() int {\n if this.IsEmpty() { return -1 }\n return this.vals[this.head]\n}", "func (q *LLQueue) Front() interface{} {\n\tif q.head == nil {\n\t\treturn nil\n\t}\n\treturn q.head.data\n}", "func (l *List) Front() interface{} {\n\tl.RLock()\n\tdefer l.RUnlock()\n\n\tif l.length == 0 {\n\t\treturn nil\n\t}\n\treturn l.head.value\n}", "func (self *Queue) Front() interface{} {\n\treturn self.final.GetNext().GetData()\n}", "func (this *MyCircularQueue) Front() int {\n if this.IsEmpty() {\n return -1\n }\n return this.Items[this.HeadIndex]\n}", "func (d *Deque[T]) PopFront() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\ts := d.segs[d.begin]\n\tv := s.popFront()\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[d.begin] = nil\n\t\td.begin = d.nextIndex(d.begin)\n\t}\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (this *LinkedList) Front() interface{} {\n\tif this.head == nil {\n\t\treturn nil\n\t}\n\treturn this.head.elem\n}", "func(q *Queue)GetFront()int{\n\tif q.IsEmpty() {\n\t\tpanic(\"Get front error.queue is empty\")\n\t}\n\treturn q.arr[q.front]\n}", "func (q *Queue) GetFront() interface{} {\r\n\tif len(q.QueueList) > 0 {\r\n\t\treturn q.QueueList[0]\r\n\t}\r\n\treturn nil\r\n}", "func (q *Queue) Front() string {\n\tif !q.isEmpty() {\n\t\treturn q.Queue.Start.Value\n\t}\n\treturn \"\"\n}", "func (q *LinkQueue) Front() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\treturn q.head.Data\n}", "func (s *PacketDurationQueue) Front() float32 {\n\ts.lock.RLock()\n\titem := s.items[0]\n\ts.lock.RUnlock()\n\treturn item\n}", "func (q *wantConnQueue) peekFront() *wantConn {\n\tif q.headPos < len(q.head) {\n\t\treturn q.head[q.headPos]\n\t}\n\tif len(q.tail) > 0 {\n\t\treturn q.tail[0]\n\t}\n\treturn nil\n}", "func (d *Deque) TopFront() (interface{}, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.head != nil:\n\t\treturn d.head.value, true\n\n\tcase d.child != nil:\n\t\treturn d.child.TopFront()\n\n\tdefault:\n\t\treturn d.tail.value, true\n\t}\n}", "func (list *SkipList) Front() *Element {\n\treturn list.next[0]\n}", "func (q *Deque) PopFront() {\n\tif !q.Empty() {\n\t\tq.front = (q.front + 1) % cap(q.values)\n\t\tq.size--\n\t}\n}", "func (q *ItemQueue) Front() *Item {\n\tq.lock.RLock()\n\tdefer q.lock.RUnlock()\n\titem := q.items[0]\n\treturn &item\n}", "func (s *StringQueue) Front() *string {\n\ts.lock.RLock()\n\titem := s.items[0]\n\ts.lock.RUnlock()\n\treturn &item\n}", "func (s *SinglyLinkedList) Front() *Node {\n return s.front\n}", "func (l *List) Front() *Elem { return l.front }", "func (o *ordering) front() *entry {\n\te := o.ordered[0]\n\tif e.prev != nil {\n\t\tlog.Panicf(\"unexpected first entry: %v\", e)\n\t}\n\t// The first entry is always a logical position, which should not be indexed.\n\te, _ = e.nextIndexed()\n\treturn e\n}", "func (s *ItemQueue) Front() *Item {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\titem := s.items[0]\n\treturn &item\n}", "func (queueslice *QueueSlice) QueueFront() int {\n\tlength := len(queueslice.Q)\n\tif length == 0 {\n\t\tfmt.Println(\"Q is empty\")\n\t\treturn -1\n\t}\n\n\treturn queueslice.Q[0]\n}", "func (nl *NodeList) Front() *Node {\n\treturn nl.front\n}", "func (l *List) Front() *Node {\n\n\tif l.size == 0 {\n\t\treturn nil\n\t}\n\treturn l.head \n}", "func (cq *cQT) PopFront() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tel = cq.b[cq.s&cq.m]\n\tcq.b[cq.s&cq.m] = zero\n\tcq.s++\n\treturn el, true\n}", "func (dq *Dqueue) PopFront() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\tdq.dqueue.Remove(0)\n\treturn\n}", "func (ll *LinkedList) PopFront() T {\n\tif ll.head == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.head.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\thead := ll.head.next\n\t\thead.prev = nil\n\t\tll.head.next = nil\n\t\tll.head = head\n\t}\n\n\tll.size--\n\treturn val\n}", "func (l *List) Front() *Node {\n\tif l.Len == 0 {\n\t\treturn nil\n\t}\n\treturn l.root.next\n}", "func (d *Deque) PopFront() (interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\toldFront := d.front\n\td.front = oldFront.prev\n\n\tif d.front == nil {\n\t\td.back = nil\n\t} else {\n\t\td.front.next = nil\n\t}\n\t// collect the data\n\tret := oldFront.data\n\t// clean up\n\toldFront.next = nil\n\toldFront.prev = nil\n\t// size decrement\n\td.size--\n\treturn ret, true\n}", "func (d *MyCircularDeque) InsertFront(value int) bool {\n\treturn d.Insert(value, 0)\n}", "func (l *List) PopFront() (interface{}, error) {\n\tif l.first == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\tn := l.first\n\tif l.last == n {\n\t\tl.last = nil\n\t}\n\tl.first = n.next\n\tif l.first != nil {\n\t\tl.first.prev = nil\n\t}\n\treturn n.Val, nil\n}", "func (l *List) PopFront() (interface{}, error) {\n\tif l.Len == 0 {\n\t\treturn nil, ErrEmptyList\n\t}\n\tv := l.head.Val\n\tl.head = l.head.next\n\tl.Len--\n\tif l.Len == 0 {\n\t\tl.tail = nil\n\t} else {\n\t\tl.head.prev = nil\n\t}\n\treturn v, nil\n}", "func (l *List) PopFront() (interface{}, error) {\n\tif l.head == nil {\n\t\treturn 0, ErrEmptyList\n\t}\n\n\tdata := l.head.Val\n\n\tif l.head.Next() == nil {\n\t\tl.head = nil\n\t\tl.last = nil\n\t} else {\n\t\tl.head.Next().previous = nil\n\t\tl.head = l.head.Next()\n\t}\n\n\treturn data, nil\n\n}", "func (l *TwoList) PeekFront() *Element {\n\treturn l.seekFront(false)\n}", "func (d *Deque) PushFront(value interface{}) *Deque {\n\tfree := &dequeNode{value, d.head, d.tail}\n\tif d.IsEmpty() {\n\t\treturn &Deque{free, &Deque{}, nil}\n\t}\n\treturn &Deque{free, d, nil}\n}", "func (q *Deque) PushFront(v interface{}) {\n\tif q.size == cap(q.values) {\n\t\tnewCap := 2\n\t\tif cap(q.values) > 0 {\n\t\t\tnewCap = cap(q.values) * 2\n\t\t}\n\t\tq.Resize(newCap)\n\t}\n\n\tq.front--\n\tif q.front < 0 {\n\t\tq.front = cap(q.values) - 1\n\t}\n\n\tq.values[q.front] = v\n\tq.size++\n}", "func (d *Deque) First() Value {\n\tf, _, _ := d.Split()\n\treturn f\n}", "func (l *List) PopFront() (interface{}, error) {\n\tif l.head == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\n\tval := l.head.Val\n\tl.head = l.head.next\n\n\tif l.head == nil {\n\t\tl.tail = nil\n\t} else {\n\t\tl.head.prev = nil\n\t}\n\n\treturn val, nil\n}", "func (l *LRU) PeekFront() (key, val interface{}) {\n\tl.lazyInit()\n\treturn l.shard(1).front()\n}", "func (q *wantConnQueue) popFront() *wantConn {\n\tif q.headPos >= len(q.head) {\n\t\tif len(q.tail) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\t// Pick up tail as new head, clear tail.\n\t\tq.head, q.headPos, q.tail = q.tail, 0, q.head[:0]\n\t}\n\n\tw := q.head[q.headPos]\n\tq.head[q.headPos] = nil\n\tq.headPos++\n\treturn w\n}", "func (list *LinkedList[T]) PeekFront() (T, bool) {\n\tlist.key.RLock()\n\tdefer list.key.RUnlock()\n\n\tif list.first == nil {\n\t\treturn *new(T), false\n\t}\n\treturn list.first.payload, true\n}", "func (b *BlockQueue) Front() *Block{\n\tblock := b.blocks.Back()\n\tif block == nil {\n\t\treturn nil \n\t}\n\treturn block.(*Block)\n}", "func (d *Deque[T]) PushFront(value T) {\n\td.firstAvailableSegment().pushFront(value)\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (cq *cQT) PeekFront() (el T, ok bool) {\n\tif cq.s == cq.e {\n\t\treturn el, false\n\t}\n\treturn cq.b[cq.s&cq.m], true\n}", "func (d *Deque[T]) First() *DequeIterator[T] {\n\treturn d.IterAt(0)\n}", "func (l *idList) Front() *idElement {\n\tif l.len == 0 {\n\t\treturn nil\n\t}\n\treturn l.root.next\n}", "func (l *TwoList) PopFront() *Element {\n\treturn l.seekFront(true)\n}", "func (l *sampleList) Front() *Sample { return l.head }", "func (q *Deque) Back() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.back-1]\n\t}\n\treturn nil\n}", "func (vector *Vector) PopFront() {\n\tvar element interface{}\n\telement, *vector = (*vector)[0], (*vector)[1:]\n\t// Note: dropping element here.\n\t_ = element\n}", "func (l *SliceList[T]) PopFront() (v T, ok bool) {\n\tif len(*l) > 0 {\n\t\tv, *l = (*l)[0], (*l)[1:]\n\t\treturn\n\t}\n\n\treturn\n}", "func (d *Deque) PopFront() (*Deque, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.head != nil:\n\t\treturn &Deque{nil, d.child, d.tail}, true\n\n\tdefault:\n\t\tdd, _ := d.child.PopFront()\n\t\treturn &Deque{nil, dd, d.tail}, true\n\t}\n}", "func (q *Queue) popFront() interface{} {\n\te := q.front.link\n\tq.front.link = e.link\n\tif e == q.back {\n\t\tq.back = q.front\n\t}\n\tq.queueLen--\n\n\tif q.queueLen < q.softQuota {\n\t\t// Successfully removing items from the queue below half the soft quota\n\t\t// lowers the soft quota. This has the effect of increasing the credit cap\n\t\t// and the amount of credit given for removing items to better approximate\n\t\t// the rate at which the consumer is servicing the queue.\n\t\tif q.softQuota > 1 && q.queueLen < q.softQuota/2 {\n\t\t\tq.softQuota--\n\t\t}\n\n\t\t// Give credit for being below the soft quota. Note we do this after\n\t\t// adjusting the quota so the credit reflects the item we just removed.\n\t\tq.credit += float64(q.softQuota-q.queueLen) / float64(q.softQuota)\n\t\tif cap := float64(q.hardLimit - q.softQuota); q.credit > cap {\n\t\t\tq.credit = cap\n\t\t}\n\t}\n\n\treturn e.item\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.Cap == this.Size {\n\t\treturn false\n\t}\n\ts := new(Node)\n\ts.Data = value\n\ts.Next = this.First.Next\n\tthis.First.Next.Pre = s\n\n\tthis.First.Next = s\n\ts.Pre = this.First\n\tif this.Size == 0 {\n\t\tthis.Last = s\n\t}\n\tthis.Size++\n\treturn true\n}", "func (q *Queue) First() *list.Element {\n\n\treturn q.orders.Front()\n}", "func (v *IntVec) PopFront() int {\n\treturn v.Remove(0)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n if this.IsFull() {\n return false\n }\n this.head = (this.head - 1 + this.capacity) % this.capacity\n this.data[this.head] = value\n return true\n}", "func (l *TwoList) seekFront(remove bool) *Element {\n\thead := l.head\n\tif head != nil {\n\t\tif remove {\n\t\t\tl.head = head.next\n\t\t}\n\t\treturn head\n\t}\n\n\tif l.tail == nil {\n\t\treturn nil\n\t}\n\n\t// list which starts from head is empty, so\n\t// reverse list which starts from tail and attach to head(not tail)\n\tvar prev *Element\n\tfor e := l.tail; e != nil; e = e.next {\n\t\tel := &Element{\n\t\t\tValue: e.Value,\n\t\t}\n\t\tif prev != nil {\n\t\t\tel.next = prev\n\t\t}\n\t\tprev = el\n\t}\n\t// reset list\n\tl.tail = nil\n\tif !remove {\n\t\tl.head = prev\n\t} else {\n\t\tl.head = prev.next\n\t}\n\treturn prev\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tthis.len++\n\tthis.head = (this.head + 1) % this.size\n\tthis.queue[this.head] = value\n\treturn true\n}", "func (v *Int32Vec) PopFront() int32 {\n\treturn v.Remove(0)\n}", "func (itr *DequeIterator) Value() interface{} {\n\treturn itr.deque.At(itr.index)\n}", "func (l *PList) PopFront() *Element {\n\tl.Clone()\n\thead := l.head\n\n\tif head == nil {\n\t\t// zero length\n\t\treturn nil\n\t} else if head == l.tail {\n\t\t// one length\n\t\tl.head = nil\n\t\tl.tail = nil\n\t\t// avoid memory leaks\n\t\thead.next = nil\n\t} else {\n\t\tl.head = head.next\n\t\t// avoid memory leaks\n\t\thead.next = nil\n\t}\n\treturn head\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tthis.front = (len(this.data) + this.front - 1) % len(this.data)\n\tthis.data[this.front] = value\n\treturn true\n}", "func (f *Sink) Front() *Endpoint {\n\tif f.orderedList.Front() == nil {\n\t\treturn nil\n\t}\n\treturn f.orderedList.Front().Value.(*Endpoint)\n}", "func (q *Deque) At(idx int) interface{} {\n\tif idx >= len(q.values) {\n\t\treturn nil\n\t}\n\tactualIdx := idx\n\tif q.front != 0 {\n\t\tactualIdx = (idx + q.front) % cap(q.values)\n\t}\n\treturn q.values[actualIdx]\n}", "func (this *MyCircularDeque1) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\ttemp := this.head.Next\n\ttempNode := Node{\n\t\tVal: value,\n\t\tNext: temp,\n\t\tPre: this.head,\n\t}\n\tthis.head.Next = &tempNode\n\ttemp.Pre = &tempNode\n\tthis.len++\n\treturn true\n}", "func (l List) Front() *Process {\n\treturn l[0]\n}", "func (dq *Dqueue) PushFront(value interface{}) {\n\tdq.dqueue.Prepend(value)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.len == this.cap {\n\t\treturn false\n\t}\n\tthis.l.PushFront(value)\n\tthis.len++\n\treturn true\n}", "func (v *Data) PopFront() PicData {\n\treturn v.Remove(0)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\n\tthis.mutex.Lock()\n\tdefer this.mutex.Unlock()\n\tthis.front = (this.front - 1 + this.capacity) % this.capacity\n\tthis.data[this.front] = value\n\treturn true\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tnode := &Node{nil, nil, value}\n\tif this.head == nil {\n\t\tthis.head = node\n\t\tthis.tail = node\n\t} else {\n\t\tthis.head.last = node\n\t\tnode.next = this.head\n\t\tthis.head = node\n\t}\n\tthis.len++\n\treturn true\n}", "func (d *Deque[T]) Back() T {\n\treturn d.lastSegment().back()\n}", "func (d *Deque[T]) Begin() *DequeIterator[T] {\n\treturn d.First()\n}", "func (Q *Deque) RemoveFirst() (interface{}, error) {\n\tif Q.size == 0 {\n\t\treturn nil, errors.New(\"Queue is empty\")\n\t}\n\tcurrentVal := Q.front.val\n\tnextNode := Q.front.next\n\tQ.front = nextNode\n\treturn currentVal, nil\n}", "func (cq *cQT) PushFront(el T) (ok bool) {\n\tif cq.e-cq.s == cq.sz {\n\t\tif cq.sz == cq.maxSz {\n\t\t\treturn false\n\t\t}\n\t\tcq.resize(cq.sz << 1)\n\t}\n\tcq.s--\n\tcq.b[cq.s&cq.m] = el\n\treturn true\n}", "func (d *Deque) Left() interface{} {\n\treturn d.left[d.leftOff]\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.length == this.size {\n\t\treturn false\n\t}\n\n\tnode := &Node{value, nil, nil}\n\tthis.head.next.prev = node\n\tnode.next = this.head.next\n\tnode.prev = this.head\n\tthis.head.next = node\n\tthis.length++\n\treturn true\n}", "func (d *Deque) Back() (*interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\treturn &d.back.data, true\n}" ]
[ "0.86083055", "0.8543091", "0.8420691", "0.84094536", "0.84055096", "0.83924806", "0.8358179", "0.8341596", "0.83161813", "0.8234288", "0.8232738", "0.81514317", "0.8130265", "0.81239563", "0.811889", "0.8117524", "0.81163365", "0.8006853", "0.7999997", "0.7968733", "0.7919543", "0.7900249", "0.78890586", "0.7811876", "0.77818245", "0.7749447", "0.7720678", "0.76852554", "0.7681346", "0.7646906", "0.76458323", "0.7638624", "0.7522407", "0.7514986", "0.7506993", "0.7504962", "0.7491023", "0.7470779", "0.7467996", "0.7461746", "0.73845184", "0.7372253", "0.73678356", "0.7317661", "0.73120713", "0.7279355", "0.7164597", "0.7147403", "0.70725393", "0.70647395", "0.7028966", "0.7005913", "0.7003641", "0.69980234", "0.69884145", "0.69851005", "0.6968369", "0.6966294", "0.69471455", "0.6942033", "0.69307005", "0.6919074", "0.6915746", "0.6913493", "0.69100386", "0.68729085", "0.68683445", "0.68578756", "0.68420774", "0.6835126", "0.67959124", "0.6783062", "0.675607", "0.67329574", "0.67248094", "0.67172194", "0.668683", "0.66523176", "0.662753", "0.6614782", "0.6610786", "0.65876454", "0.6581773", "0.6579502", "0.6576638", "0.6559378", "0.65373886", "0.65039694", "0.64963907", "0.64720875", "0.64481175", "0.6411842", "0.6398087", "0.6395942", "0.6392166", "0.6374449", "0.6336529", "0.6324054", "0.6310185", "0.63060695" ]
0.8409546
3
Back returns the value at the last position of the deque
func (d *Deque[T]) Back() T { return d.lastSegment().back() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Deque) Back() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.back-1]\n\t}\n\treturn nil\n}", "func (dq *Dqueue) Back() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\treturn\n}", "func (d *Deque[T]) PopBack() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\tseg := d.preIndex(d.end)\n\ts := d.segs[seg]\n\tv := s.popBack()\n\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[seg] = nil\n\t\td.end = seg\n\t}\n\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (d *Deque) Back() (*interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\treturn &d.back.data, true\n}", "func(q *Queue)GetBack() int{\n\tif q.IsEmpty() {\n\t\tpanic(\"Get back error.queue is empty\")\n\t}\n\treturn q.arr[q.rear-1]\n}", "func (q *Deque) PopBack() {\n\tif !q.Empty() {\n\t\tq.back--\n\t\tq.size--\n\t}\n}", "func (dq *Dqueue) PopBack() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\tdq.dqueue.Remove(dq.Size() - 1)\n\treturn\n}", "func (cq *cQT) PopBack() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tcq.e--\n\tel = cq.b[cq.e&cq.m]\n\tcq.b[cq.e&cq.m] = zero\n\treturn el, true\n}", "func (d *Deck) PopBack() (string, error) {\n\tif d.head == d.tail {\n\t\treturn \"\", fmt.Errorf(\"nothing to pop\")\n\t}\n\td.tail -= inv\n\tif d.tail < 0 {\n\t\td.tail = cap(d.deck) - 1\n\t}\n\tres := d.deck[d.tail]\n\td.deck[d.tail] = \"\"\n\treturn res, nil\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn 0, ErrEmptyList\n\t}\n\n\tdata := l.last.Val\n\n\tif l.last.Prev() == nil {\n\t\tl.head = nil\n\t\tl.last = nil\n\t} else {\n\t\tl.last.Prev().next = nil\n\t\tl.last = l.last.Prev()\n\t}\n\n\treturn data, nil\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\tn := l.last\n\tif l.first == n {\n\t\tl.first = nil\n\t}\n\tl.last = n.prev\n\tif l.last != nil {\n\t\tl.last.next = nil\n\t}\n\treturn n.Val, nil\n}", "func (l *List) Back() *Node {\n\n\tif l.size == 0 {\n\t\treturn nil\n\t}\n\treturn l.tail\n}", "func (ll *LinkedList) PopBack() T {\n\tif ll.tail == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.tail.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\ttail := ll.tail.prev\n\t\ttail.next = nil\n\t\tll.tail.prev = nil\n\t\tll.tail = tail\n\t}\n\n\tll.size--\n\treturn val\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.Len == 0 {\n\t\treturn nil, ErrEmptyList\n\t}\n\tv := l.tail.Val\n\tl.tail = l.tail.prev\n\tl.Len--\n\tif l.Len == 0 {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\treturn v, nil\n}", "func (self *Dll) popBack() *node{\n\n\tret := self.tail.prev\n\ttemp := ret.prev\n\ttemp.setNext(self.tail)\n\tself.tail.setPrev(temp)\n\n\tret.setPrev(nil)\n\tret.setNext(nil)\n\n\tself.len -= 1\n\n\treturn ret\n}", "func (v *Vector) PopBack() (string, error) {\n\tif len(v.Vector) == 0 {\n\t\treturn \"\", fmt.Errorf(\"nothing to pop\")\n\t}\n\tres := v.Vector[len(v.Vector)-1]\n\t// v.Vector[len(v.Vector)-1] = \"\"\n\tv.Vector = v.Vector[:len(v.Vector)-1]\n\treturn res, nil\n}", "func (l *List) Back() *Elem {\n\tif l.len == 0 {\n\t\treturn nil\n\t}\n\te := l.front\n\tfor e.next != nil {\n\t\te = e.next\n\t}\n\treturn e\n}", "func (ll *LinkedList) PopBack() interface{} {\n\tll.Lock()\n\tdefer ll.Unlock()\n\n\tif ll.size == 0 {\n\t\treturn nil\n\t}\n\n\tnode := ll.tail\n\tll.removeNode(ll.size - 1)\n\n\treturn node.data\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.tail == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\n\tval := l.tail.Val\n\tl.tail = l.tail.prev\n\n\tif l.tail == nil {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\n\treturn val, nil\n}", "func (nl *NodeList) Back() *Node {\n\treturn nl.back\n}", "func (l *idList) Back() *idElement {\n\tif l.len == 0 {\n\t\treturn nil\n\t}\n\treturn l.root.prev\n}", "func (q *Deque) PushBack(v interface{}) {\n\tif q.size == cap(q.values) {\n\t\tnewCap := 2\n\t\tif cap(q.values) > 0 {\n\t\t\tnewCap = cap(q.values) * 2\n\t\t}\n\t\tq.Resize(newCap)\n\t}\n\n\tq.values[q.back] = v\n\tq.size++\n\tq.back = (q.back + 1) % cap(q.values)\n}", "func (b *BlockQueue) Back() *Block{\n\tblock := b.blocks.Back()\n\tif block == nil {\n\t\treturn nil \n\t} \n\treturn block.(*Block)\n}", "func (d *Deque) TopBack() (interface{}, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.tail != nil:\n\t\treturn d.tail.value, true\n\n\tcase d.child != nil:\n\t\treturn d.child.TopFront()\n\n\tdefault:\n\t\treturn d.head.value, true\n\t}\n}", "func (l *sampleList) Back() *Sample { return l.tail }", "func (d *Deque) PopBack() (interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\toldBack := d.back\n\td.back = oldBack.next\n\tif d.back == nil {\n\t\td.front = nil\n\t} else {\n\t\td.back.prev = nil\n\t}\n\tret := oldBack.data\n\t// clean up\n\toldBack.next = nil\n\toldBack.prev = nil\n\td.size--\n\treturn ret, true\n}", "func (gdt *Array) PopBack() Variant {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_array_pop_back(GDNative.api, arg0)\n\n\treturn Variant{base: &ret}\n\n}", "func (q *Deque) Front() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.front]\n\t}\n\treturn nil\n}", "func (self *Queue) Front() interface{} {\n\treturn self.final.GetNext().GetData()\n}", "func (cq *cQT) PeekBack() (el T, ok bool) {\n\tif cq.s == cq.e {\n\t\treturn el, false\n\t}\n\treturn cq.b[(cq.e-1)&cq.m], true\n}", "func (q *Deque) PopFront() {\n\tif !q.Empty() {\n\t\tq.front = (q.front + 1) % cap(q.values)\n\t\tq.size--\n\t}\n}", "func (d *Deque) PopBack() (*Deque, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.tail != nil:\n\t\treturn &Deque{d.head, d.child, nil}, true\n\n\tdefault:\n\t\tdd, _ := d.child.PopFront()\n\t\treturn &Deque{d.head, dd, nil}, true\n\t}\n}", "func (q *Queue) PutBack(value []byte) error {\n\tq.Lock()\n\tdefer q.Unlock()\n\tif q.head < 1 {\n\t\treturn ErrInvalidHeadValue\n\t}\n\terr := q.db.Put(q.dbKey(q.head), value, nil)\n\tif err == nil {\n\t\tq.head--\n\t}\n\treturn err\n}", "func (this *MyQueue) Pop() int {\n x := this.q[0]\n this.q = this.q[1:]\n return x\n}", "func (d *Deque[T]) PopFront() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\ts := d.segs[d.begin]\n\tv := s.popFront()\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[d.begin] = nil\n\t\td.begin = d.nextIndex(d.begin)\n\t}\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (t *queueStorage) Pop() interface{} {\n\tn := len(*t)\n\tres := (*t)[n-1]\n\t*t = (*t)[:n-1]\n\treturn res\n}", "func (h *Queue) Pop() interface{} {\n\told := h.slice\n\tn := len(old)\n\titem := old[n-1]\n\th.slice = old[0 : n-1]\n\treturn item\n}", "func (s *SinglyLinkedList) Back() *Node {\n currentNode := s.front\n for currentNode != nil && currentNode.next != nil {\n currentNode = currentNode.next\n }\n return currentNode\n}", "func (q *SliceQueue) Front() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\treturn q.Data[0]\n}", "func (gdt *Array) Back() Variant {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_array_back(GDNative.api, arg0)\n\n\treturn Variant{base: &ret}\n\n}", "func (x *MQQueueManager) Back() error {\n\tvar mqrc C.MQLONG\n\tvar mqcc C.MQLONG\n\n\tC.MQBACK(x.hConn, &mqcc, &mqrc)\n\n\tmqreturn := MQReturn{MQCC: int32(mqcc),\n\t\tMQRC: int32(mqrc),\n\t\tverb: \"MQBACK\",\n\t}\n\n\tif mqcc != C.MQCC_OK {\n\t\treturn &mqreturn\n\t}\n\n\treturn nil\n\n}", "func (q *queue) Front() (interface{}, error) {\n\tif q.Empty() {\n\t\treturn nil, errors.New(\"error: can not get element from empty queue\")\n\t}\n\treturn q.items[q.head].Data, nil\n}", "func (t *topK) Pop() interface{} {\n\tn := len(t.values)\n\tx := t.values[n-1]\n\tt.values = t.values[:n-1]\n\treturn x\n}", "func (l *List) PopBack() *Node{\n\tvar n *Node\n\n\tl.size--\n \tif l.tail == nil {\n \t\treturn nil\n \t}\n\n \tn = l.tail\n \tif l.tail == l.head {\n \t\tl.head = nil\n \t\tl.tail = nil\n \t\treturn n\n \t}\n\n \tcurrentNode := l.head\n \tfor currentNode.next != l.tail {\n \t\tcurrentNode = currentNode.next\n \t}\n \tcurrentNode.next = nil\n \tl.tail = currentNode\n \treturn n\n}", "func (d *Deque) PushBack(value interface{}) *Deque {\n\tfree := &dequeNode{value, d.head, d.tail}\n\tif d.IsEmpty() {\n\t\treturn &Deque{nil, &Deque{}, free}\n\t}\n\treturn &Deque{nil, d, free}\n}", "func (dq *Dqueue) Front() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\treturn\n}", "func (shelf *Shelf) Pop() interface{} {\n\tx := shelf.queue[shelf.Len()-1]\n\tshelf.queue = shelf.queue[:shelf.Len()-1]\n\treturn x\n}", "func (this *MyQueue) Pop() int {\n\tthis.Peek()\n\te := this.b[len(this.b)-1]\n\tthis.b = this.b[:len(this.b)-1]\n\treturn e\n}", "func (q *queue) dequeue() (int, error) {\n\tif q.front == -1 {\n\t\treturn 0, errors.New(\"The queue is empty\")\n\t}\n\n\tif q.front == q.rear{\n\t\tv := q.value[q.front]\n\t\tq.value[q.front] = 0\n\t\tq.front =-1\n\t\tq.rear = -1\n\t\treturn v,nil\n\t} else {\n\t\tv := q.value[q.front]\n\t\tq.value[q.front] = 0\n\t\tq.front = (q.front + 1) % q.size\n\t\treturn v,nil\n\t}\n}", "func (dq *Dqueue) PushBack(value interface{}) {\n\tdq.dqueue.Append(value)\n}", "func (d *Deck) PushBack(v string) {\n\tif d.head-1 == d.tail {\n\t\tinv = 1\n\t\td.pushtocap(v)\n\t} else {\n\t\tif d.tail == cap(d.deck)-1 && d.head == 0 {\n\t\t\tinv = -1\n\t\t} else if d.tail == cap(d.deck) && d.head > 0 {\n\t\t\td.tail = 0\n\t\t\tinv = 1\n\t\t}\n\t\td.deck[d.tail] = v\n\t\td.tail += inv\n\t}\n}", "func (q *Queue) Front() interface{} {\n\treturn q.data[q.head]\n}", "func (s *Queue) Pop() interface{} {\n\tif s.IsEmpty() {\n\t\tpanic(\"Pop on empty queue\")\n\t} else {\n\t\tcurrent_head := s.head\n\t\tval := current_head.val\n\t\ts.head = current_head.previous\n\t\tcurrent_head.val = nil\n\t\treturn val\n\t}\n}", "func (que *Queue) Pop() string {\n\tnode := que.values[0]\n\tque.values = que.values[1:]\n\treturn node\n}", "func (d *Deque) Pop() (interface{}, error) {\n\tif d.length == 0 {\n\t\treturn nil, fmt.Errorf(\"Can not pop from an empty deque.\")\n\t}\n\n\titem := d.head.next\n\td.head.next = d.head.next.next\n\n\tif d.head.next != nil {\n\t\td.head.next.prev = d.head\n\t}\n\n\td.length--\n\n\treturn item.value, nil\n}", "func (this *Stack) Pop() interface{} {\n\tif this.length == 0 {\n\t\treturn nil\n\t}\n\n\tn := this.top\n\tthis.top = n.prev\n\tthis.length--\n\treturn n.value\n}", "func (this *MyQueue) Pop() int {\n\tv := this.Stack[0]\n\tthis.Stack = this.Stack[1:]\n\treturn v\n}", "func (this *MyCircularDeque) GetFront() int {\n if this.IsEmpty() {\n return -1\n }\n return this.data[this.head]\n}", "func (c *consumer) Back() error {\n\tif err := c.store.Back(c.topic, c.ackOffset); err != nil {\n\t\treturn fmt.Errorf(\"backing topic %s with offset %d: %v\", c.topic, c.ackOffset, err)\n\t}\n\n\tc.outstanding = false\n\tc.notifier.NotifyConsumer(c.topic, eventTypeBack)\n\n\treturn nil\n}", "func (list *LinkedList[T]) PeekBack() (T, bool) {\n\tlist.key.RLock()\n\tdefer list.key.RUnlock()\n\n\tif list.last == nil {\n\t\treturn *new(T), false\n\t}\n\treturn list.last.payload, true\n}", "func (q *Queue) Pop() int {\n\t//这里的括号是定界符\n\t//这里是取出第0个元素进行返回\n\thead := (*q)[0]\n\t//将q的内存地址中的数据, 修改为将q的下标为1开始剪切到最后一个的数据\n\t// 后面使用*q 前面也要加一个*\n\t*q = (*q)[1:]\n\treturn head\n}", "func (s *MyStack) Pop() int {\n v := s.queue1[0]\n s.queue1 = s.queue1[1:]\n return v\n}", "func (q *LLQueue) Front() interface{} {\n\tif q.head == nil {\n\t\treturn nil\n\t}\n\treturn q.head.data\n}", "func (this *MyCircularDeque1) GetRear() int {\n\treturn this.tail.Pre.Val\n}", "func (d *Deque[T]) PushBack(value T) {\n\td.lastAvailableSegment().pushBack(value)\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (q *Queue) Front() string {\n\tif !q.isEmpty() {\n\t\treturn q.Queue.Start.Value\n\t}\n\treturn \"\"\n}", "func (d *Deque[T]) Front() T {\n\treturn d.firstSegment().front()\n}", "func (q *Queue) popFront() interface{} {\n\te := q.front.link\n\tq.front.link = e.link\n\tif e == q.back {\n\t\tq.back = q.front\n\t}\n\tq.queueLen--\n\n\tif q.queueLen < q.softQuota {\n\t\t// Successfully removing items from the queue below half the soft quota\n\t\t// lowers the soft quota. This has the effect of increasing the credit cap\n\t\t// and the amount of credit given for removing items to better approximate\n\t\t// the rate at which the consumer is servicing the queue.\n\t\tif q.softQuota > 1 && q.queueLen < q.softQuota/2 {\n\t\t\tq.softQuota--\n\t\t}\n\n\t\t// Give credit for being below the soft quota. Note we do this after\n\t\t// adjusting the quota so the credit reflects the item we just removed.\n\t\tq.credit += float64(q.softQuota-q.queueLen) / float64(q.softQuota)\n\t\tif cap := float64(q.hardLimit - q.softQuota); q.credit > cap {\n\t\t\tq.credit = cap\n\t\t}\n\t}\n\n\treturn e.item\n}", "func (m *OrderedMap[K,V]) PopBack() (k K, v V, ok bool) {\n\te := m.list.Back()\n\tif e == nil {\n\t\treturn\n\t}\n\tk, v, ok = e.Value.Key, e.Value.Value, true\n\tdelete(m.mp, k)\n\tm.list.Remove(e)\n\treturn\n}", "func (l *LexInner) Back() {\n\tif l.Last() == '\\n' {\n\t\tl.mark.line--\n\t}\n\tl.mark.pos -= l.mark.width\n\tl.mark.width = 0\n}", "func (s *PacketDurationQueue) Front() float32 {\n\ts.lock.RLock()\n\titem := s.items[0]\n\ts.lock.RUnlock()\n\treturn item\n}", "func (q *Queue) dequeue() int {\n\tif q.isEmpty() {\n\t\tfmt.Println(\"Queue empty\")\n\t\treturn -1\n\t}\n\tvalue := q.values[0]\n\tq.values = q.values[1:]\n\treturn value\n}", "func (this *MyCircularQueue) Front() int {\n if this.IsEmpty() { return -1 }\n return this.vals[this.head]\n}", "func (this *MyCircularDeque) GetRear() int {\n\tif this.length == 0 {\n\t\treturn -1\n\t}\n\treturn this.tail.prev.val\n}", "func (q *RingQueue) Dequeue() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\te := q.data[q.front]\n\tq.front = (q.front + 1) % q.size\n\treturn e\n}", "func (this *MyQueue) Pop() int {\n\tr := this.q[len(this.q)-1]\n\tthis.q = this.q[:len(this.q)-1]\n\treturn r\n}", "func (s *Stack[T]) Pop() T {\n\tv := s.array[len(s.array)-1]\n\ts.array = s.array[:len(s.array)-1]\n\treturn v\n}", "func (q *Stack) Pop() string {\n\ts := *q\n\tlast := s[len(s)-1]\n\t*q = s[:len(s)-1]\n\treturn last\n}", "func (cq *cQT) PushBack(el T) (ok bool) {\n\tif cq.e-cq.s == cq.sz {\n\t\tif cq.sz == cq.maxSz {\n\t\t\treturn false\n\t\t}\n\t\tcq.resize(cq.sz << 1)\n\t}\n\tcq.b[cq.e&cq.m] = el\n\tcq.e++\n\treturn true\n}", "func (s *Stack) Pop() interface{} {\n\tv := s.v[len(s.v)]\n\ts.v = s.v[:len(s.v)-1]\n\treturn v\n}", "func (this *Stack) Pop() interface{} {\n\tsize := len(this.stack)\n\tres := this.stack[size-1]\n\tthis.stack = append([]interface{}{}, this.stack[0:size-1]...)\n\treturn res\n}", "func (cq *cQT) PopFront() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tel = cq.b[cq.s&cq.m]\n\tcq.b[cq.s&cq.m] = zero\n\tcq.s++\n\treturn el, true\n}", "func (r *Ring) Dequeue() interface{} {\n\tr.checkInit()\n\tif r.head == -1 {\n\t\treturn nil\n\t}\n\tv := r.get(r.tail)\n\tif r.tail == r.head {\n\t\tr.head = -1\n\t\tr.tail = 0\n\t} else {\n\t\tr.tail = r.mod(r.tail + 1)\n\t}\n\treturn v\n}", "func (s *StringQueue) Front() *string {\n\ts.lock.RLock()\n\titem := s.items[0]\n\ts.lock.RUnlock()\n\treturn &item\n}", "func (c StringArrayCollection) Pop() interface{} {\n\tlast := c.value[len(c.value)-1]\n\tc.value = c.value[:len(c.value)-1]\n\treturn last\n}", "func (s *Stack) Pop() interface{} {\r\n\tn := len(s.stk)\r\n\tvalue := s.stk[n-1]\r\n\ts.stk = s.stk[:n-1]\r\n\treturn value\r\n}", "func (self *Queue)Pop()interface{}{\r\n\tdefer self.popkey.Release()\r\n\tself.popkey.Get()\t\r\n\te:=self.list.Front()\r\n\tif e!=nil {\r\n\t\tself.list.Remove(e)\r\n\t\treturn e.Value\r\n\t}else{\r\n\t\treturn e\r\n\t}\r\n}", "func (a *Array) Pop() interface{} {\n\tdefer func() {\n\t\ta.Data = a.Data[:a.Length-1]\n\t\ta.Length--\n\t}()\n\treturn a.Data[a.Length-1]\n}", "func (d *MyCircularDeque) GetFront() int {\n\tif d.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn d.Val[0]\n}", "func (l *List) Front() interface{} {\n\tl.RLock()\n\tdefer l.RUnlock()\n\n\tif l.length == 0 {\n\t\treturn nil\n\t}\n\treturn l.head.value\n}", "func (this *MyCircularDeque) GetRear() int {\n if this.IsEmpty() {\n return -1\n }\n return this.data[(this.tail - 1 + this.capacity) % this.capacity]\n}", "func (this *MyStack) Pop() int {\n\tres := this.v[len(this.v)-1]\n\tthis.v = this.v[:len(this.v)-1]\n\treturn res\n}", "func (b *BlockQueue) PopBack() *Block {\n\t\n\tblock := b.blocks.PopBack()\n\tif block == nil {\n\t\treturn nil\n\t}\n\n\t// Update address index\n\tb.blockUpdateAddress(block.(*Block), true)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block.(*Block), true)\n\n\treturn block.(*Block)\n}", "func (s *Stack) Pop() (value interface{}) {\n\n if s.size > 0 {\n\n value, s.top = s.top.value, s.top.next\n\n s.size--\n\n return\n\n }\n\n return nil\n\n}", "func (this *MyQueue) Pop() int {\n\tif len(this.outStack) == 0 {\n\t\tthis.inToOut()\n\t}\n\tx := this.outStack[len(this.outStack)-1]\n\tthis.outStack = this.outStack[:len(this.outStack)-1]\n\treturn x\n}", "func (itr *DequeIterator) Value() interface{} {\n\treturn itr.deque.At(itr.index)\n}", "func (q *Queue) Tail() uint64 { return q.tail }", "func (this *MyCircularQueue) Front() int {\n\tif this.Count == 0 {\n\t\treturn -1\n\t}\n\treturn this.Queue[this.Head]\n}", "func (q *Queue /*[T]*/) Dequeue() T {\n\tvar v T\n\tif len(q.items) > 0 {\n\t\tv = q.items[0]\n\t\tq.items = q.items[1:]\n\t}\n\treturn v\n}", "func (this *MyCircularDeque) GetRear() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.Last.Data\n}" ]
[ "0.89047986", "0.8572705", "0.8056145", "0.79477197", "0.7791636", "0.7752885", "0.77389866", "0.769303", "0.73951185", "0.73864317", "0.7339523", "0.73379695", "0.7323949", "0.730555", "0.72718644", "0.7257018", "0.7209697", "0.71921057", "0.7189263", "0.71875894", "0.70745534", "0.70592207", "0.70332414", "0.7008774", "0.6981715", "0.6979956", "0.6967737", "0.6944562", "0.69352657", "0.6913012", "0.6829196", "0.6805487", "0.67986816", "0.6762572", "0.67427015", "0.67322403", "0.67073524", "0.6693982", "0.6693465", "0.66734755", "0.6668345", "0.6657521", "0.66323346", "0.6624953", "0.6608002", "0.6607273", "0.6594422", "0.6587809", "0.6583646", "0.65752494", "0.6574517", "0.65695447", "0.6564467", "0.6561347", "0.65448105", "0.6521999", "0.6518808", "0.65054935", "0.64969295", "0.6490666", "0.6482139", "0.6478986", "0.64745367", "0.6473241", "0.64631784", "0.64626324", "0.64561874", "0.64444023", "0.6442514", "0.64413714", "0.6436943", "0.64293504", "0.64264673", "0.6419124", "0.6417284", "0.6415499", "0.64088386", "0.640857", "0.64046425", "0.6403885", "0.63906825", "0.63851166", "0.63836217", "0.63748914", "0.6368776", "0.6368584", "0.6367552", "0.6361478", "0.63609934", "0.6356311", "0.6355061", "0.6352817", "0.63476914", "0.6343769", "0.6338682", "0.63347113", "0.6332197", "0.6317286", "0.63157666", "0.63144463" ]
0.86817414
1
At returns the value at position pos of the deque
func (d *Deque[T]) At(pos int) T { if pos < 0 || pos >= d.Size() { panic("out off range") } seg, pos := d.pos(pos) return d.segmentAt(seg).at(pos) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Deque) At(idx int) interface{} {\n\tif idx >= len(q.values) {\n\t\treturn nil\n\t}\n\tactualIdx := idx\n\tif q.front != 0 {\n\t\tactualIdx = (idx + q.front) % cap(q.values)\n\t}\n\treturn q.values[actualIdx]\n}", "func (q Deque) At(i int) E {\r\n\tif i < len(q.l) {\r\n\t\treturn q.l[len(q.l)-1-i]\r\n\t}\r\n\treturn q.r[i-len(q.l)]\r\n}", "func (q Deque) At(i int) D {\r\n\tif i < len(q.l) {\r\n\t\treturn q.l[len(q.l)-1-i]\r\n\t}\r\n\treturn q.r[i-len(q.l)]\r\n}", "func (q Deque) At(i int) D {\r\n\tif i < len(q.l) {\r\n\t\treturn q.l[len(q.l)-1-i]\r\n\t}\r\n\treturn q.r[i-len(q.l)]\r\n}", "func (queue *PriorityQueue) At(index int) *Element {\n\treturn queue.heap[index]\n}", "func (args *Args) at(index int) *Arg {\n\tif len(args.items) > index && index >= 0 {\n\t\treturn args.items[index]\n\t}\n\treturn nil\n}", "func (da *cedar) get(key []byte, from, pos int) *int {\n\tfor ; pos < len(key); pos++ {\n\t\tif value := da.Array[from].Value; value >= 0 && value != ValueLimit {\n\t\t\tto := da.follow(from, 0)\n\t\t\tda.Array[to].Value = value\n\t\t}\n\t\tfrom = da.follow(from, key[pos])\n\t}\n\tto := from\n\tif da.Array[from].Value < 0 {\n\t\tto = da.follow(from, 0)\n\t}\n\treturn &da.Array[to].Value\n}", "func (d *Deque[T]) IterAt(pos int) *DequeIterator[T] {\n\treturn &DequeIterator[T]{dq: d, position: pos}\n}", "func (list elemlist) At(index int) interface{} {\n\tvar foundItem interface{}\n\n\tif index < len(list.elements) {\n\t\tfoundItem = list.elements[index]\n\t}\n\n\treturn foundItem\n}", "func (v variable) At(index int) interface{} {\n\tm, ok := v.store.Get(v.Name)\n\tif !ok {\n\t\treturn nil\n\t}\n\tif intArray, ok := m.([]interface{}); ok {\n\t\tif index < 1 || index > len(intArray) {\n\t\t\treturn nil\n\t\t}\n\t\treturn intArray[index-1]\n\t}\n\tif indexable, ok := m.(core.Indexable); ok {\n\t\treturn indexable.At(index)\n\t}\n\tif sequenceable, ok := m.(core.Sequenceable); ok {\n\t\treturn core.BuildSequence(sequenceable.S().At(index))\n\t}\n\treturn nil\n}", "func (d *Deque[T]) Set(pos int, val T) error {\n\tif pos < 0 || pos >= d.size {\n\t\treturn ErrOutOfRange\n\t}\n\tseg, pos := d.pos(pos)\n\td.segmentAt(seg).set(pos, val)\n\treturn nil\n}", "func (tt Slice) At(at int) interface{} {\n\tif len(tt) > at {\n\t\treturn tt[at]\n\t}\n\treturn nil\n}", "func (itr *DequeIterator) Value() interface{} {\n\treturn itr.deque.At(itr.index)\n}", "func (tt PSlice) At(at int) interface{} {\n\tif len(tt) > at {\n\t\treturn tt[at]\n\t}\n\treturn nil\n}", "func (q *Deque) Front() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.front]\n\t}\n\treturn nil\n}", "func (l LinkedList) ValueAt(index int) (interface{}, error) {\n\tif index >= l.Size {\n\t\treturn \"\", fmt.Errorf(\"Index %d out of range\", index)\n\t}\n\n\tvar val interface{}\n\tnode := l.Head\n\n\tfor i := 0; i < l.Size; i++ {\n\t\tif i == index {\n\t\t\tval = node.Data\n\t\t\tbreak\n\t\t}\n\n\t\tnode = node.Next\n\t}\n\n\treturn val, nil\n}", "func (this *MyCircularDeque) GetFront() int {\n if this.IsEmpty() {\n return -1\n }\n return this.data[this.head]\n}", "func (t *Tensor) ItemAt(pos ...int) *Tensor {\n\tif !t.idx.Validate(pos) {\n\t\tpanic(errorc.New(\"invalid position %v for %v\", pos, t.idx))\n\t}\n\n\treturn &Tensor{\n\t\tidx: t.idx.Scalar(pos),\n\t\tbuf: t.buf,\n\t}\n}", "func (seq *Sequence) At(i int) Node { return seq.Nodes[i] }", "func (this *MyCircularQueue) Front() int {\n if this.IsEmpty() { return -1 }\n return this.vals[this.head]\n}", "func (s *SinglyLinkedList) GetAtPos(index int) *Node {\n currentNode := s.front\n count := 0\n for count < index && currentNode != nil && currentNode.next != nil {\n currentNode = currentNode.next\n count++\n }\n\n if count == index {\n return currentNode\n } else {\n return nil\n }\n}", "func (nl *nodeList) at(i int) *Node {\n\tif i > len(nl.elements) - 1 || i < 0 {\n\t\treturn nil\n\t}\n\n\treturn nl.elements[i]\n}", "func (this *MyCircularQueue) Front() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.items[this.front]\n}", "func (l *LinkedList) GetAt(pos int) *Node {\n\tptr := l.head\n\tif pos < 0 {\n\t\tfmt.Println(\"Position: \", pos, \" can not be negative, hence returning\")\n\t\treturn nil\n\t}\n\tif pos > (l.len - 1) {\n\t\t// fmt.Println(\"Position: \", pos, \" can not be greater than list size, hence returning\")\n\t\treturn nil\n\t}\n\tfor i := 0; i < pos; i++ {\n\t\tptr = ptr.next\n\t}\n\treturn ptr\n}", "func (d *MyCircularDeque) GetFront() int {\n\tif d.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn d.Val[0]\n}", "func (a Slice[T]) At(index int) *T {\n\tlen := len(a)\n\n\tif index < 0 {\n\t\tif -index <= len {\n\t\t\treturn &a[len+index]\n\t\t}\n\t\treturn nil\n\t}\n\n\tif index < len {\n\t\treturn &a[index]\n\t}\n\n\treturn nil\n}", "func (v *V) At(i int) float64 {\n\tif i < 0 || i >= v.Dim() {\n\t\tpanic(ErrIndex)\n\t}\n\treturn v.Data[i]\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\n\treturn this.data[this.front]\n}", "func (v Vector) At(idx int) float64 {\n\treturn v[idx]\n}", "func (b *Ring) Get(i int) (interface{}, error) {\n\tb.lock.RLock()\n\tdefer b.lock.RUnlock()\n\tif b.size == 0 {\n\t\treturn 0, ErrEmpty\n\t}\n\tposition := Index(i, b.head, b.size, len(b.buf))\n\treturn b.buf[position], nil\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\n\tthis.mutex.RLock()\n\tdefer this.mutex.RUnlock()\n\treturn this.data[this.front]\n\n}", "func (this *MyCircularQueue) Front() int {\n\treturn this.CircularQueue[this.Head]\n}", "func (this *MyCircularQueue) Front() int {\n if this.IsEmpty() {\n return -1\n }\n return this.Items[this.HeadIndex]\n}", "func (q *memQueue) position(datum []byte) (pos int, err error) {\n\tfor pos, candidate := range q.q {\n\t\tif bytes.Equal(candidate, datum) {\n\t\t\treturn pos, nil\n\t\t}\n\t}\n\n\treturn -1, nil\n}", "func (this *MyCircularQueue) Front() int {\n\tif this.Count == 0 {\n\t\treturn -1\n\t}\n\treturn this.Queue[this.Head]\n}", "func (aa *Array) Get(idx int) interface{} {\n\t// do not lock if not needed\n\tif idx < 0 || idx >= aa.length {\n\t\treturn nil\n\t}\n\n\taa.mutex.RLock()\n\tres := aa.items[idx]\n\taa.mutex.RUnlock()\n\treturn res\n}", "func (mcq *MyCircularQueue) Front() int {\n\tif mcq.length == 0 {\n\t\treturn -1\n\t}\n\treturn mcq.dummyHead.Next.Val\n}", "func (d *Decoder) at(i int) byte {\n\tif d.r1+i < len(d.buf) {\n\t\treturn d.buf[d.r1+i]\n\t}\n\treturn 0\n}", "func (dq *Dqueue) Front() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\treturn\n}", "func (l *LinkedList) Get(pos int) interface{} {\n\tif pos > l.length {\n\t\treturn nil\n\t}\n\n\tnode := l.head\n\t// Position - 1 since we want the value in the given position\n\tfor i := 0; i < pos-1; i++ {\n\t\tnode = node.Next()\n\t}\n\n\treturn node.Value()\n}", "func (arr *Array) Get(pos *Term) *Term {\n\tnum, ok := pos.Value.(Number)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\ti, ok := num.Int()\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tif i >= 0 && i < len(arr.elems) {\n\t\treturn arr.elems[i]\n\t}\n\n\treturn nil\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.head.value\n}", "func (ns Seq) At(pos int) byte {\n\tif pos%2 == 0 {\n\t\treturn n16TableRev[ns.Seq[pos/2]>>4]\n\t}\n\treturn n16TableRev[ns.Seq[pos/2]&0xf]\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.length == 0 {\n\t\treturn -1\n\t}\n\treturn this.head.next.val\n}", "func (q *Queue) Front() interface{} {\n\treturn q.data[q.head]\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.First.Next.Data\n}", "func (l *list) ElementAt(index int) interface{} {\n\treturn l.elements[index]\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.len == 0 {\n\t\treturn -1\n\t}\n\treturn this.queue[this.head]\n}", "func (t Tuple) At(idx int) float64 {\n\treturn t[idx]\n}", "func (bb *ByteSliceBuffer) GetPos(pos uint64) ([]byte, bool) {\n\tif n, ok := bb.Buffer.TransPos(pos); ok {\n\t\treturn bb.data[n], true\n\t}\n\treturn nil, false\n}", "func (q *SliceQueue) Front() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\treturn q.Data[0]\n}", "func (jz *Jzon) ValueAt(i int) (v *Jzon, err error) {\n\tif jz.Type != JzTypeArr {\n\t\treturn v, expectTypeOf(JzTypeArr, jz.Type)\n\t}\n\n\tif i < 0 || i >= len(jz.data.([]*Jzon)) {\n\t\terr = errors.New(\"index is out of bound\")\n\t\treturn\n\t}\n\n\treturn jz.data.([]*Jzon)[i], nil\n}", "func (d *Deque[T]) Front() T {\n\treturn d.firstSegment().front()\n}", "func (tt PMap) At(at int) interface{} {\n\tif len(tt) > at {\n\t\treturn tt[at]\n\t}\n\treturn nil\n}", "func (a Vector) At(p int) float64 {\n\treturn a[p]\n}", "func (l List) ValueAt(index int) (value uint16, err error) {\n\n\tif l.Root == nil {\n\t\treturn value, fmt.Errorf(\"Oops! Looks like the list is empty\")\n\t}\n\n\tcurrent := l.Root\n\tcurrentIndex := 0\n\n\tfor current != nil {\n\t\tif currentIndex == index {\n\t\t\treturn current.Value, err\n\t\t} else if current.Next == nil && index > currentIndex {\n\t\t\treturn value, fmt.Errorf(\"Provided index %v is out of bounds\", index)\n\t\t}\n\t\tcurrentIndex++\n\t\tcurrent = current.Next\n\t}\n\treturn value, err\n}", "func (l *DcmList) Seek(pos E_ListPos) *DcmObject {\n\tswitch pos {\n\tcase ELP_first:\n\t\tl.currentNode = l.firstNode\n\tcase ELP_last:\n\t\tl.currentNode = l.lastNode\n\tcase ELP_prev:\n\t\tif l.Valid() {\n\t\t\tl.currentNode = l.currentNode.prevNode\n\t\t}\n\tcase ELP_next:\n\t\tif l.Valid() {\n\t\t\tl.currentNode = l.currentNode.nextNode\n\t\t}\n\n\t}\n\tif l.Valid() {\n\t\treturn l.currentNode.Value()\n\t} else {\n\t\treturn nil\n\t}\n}", "func (da *DataFrame) GetPos(j int) interface{} {\n\tif da.done {\n\t\treturn nil\n\t}\n\n\treturn da.data[j][da.chunk-1]\n}", "func (q *queue) Front() (interface{}, error) {\n\tif q.Empty() {\n\t\treturn nil, errors.New(\"error: can not get element from empty queue\")\n\t}\n\treturn q.items[q.head].Data, nil\n}", "func (this *MyCircularDeque1) GetFront() int {\n\treturn this.head.Next.Val\n}", "func (f *finder) At(ctx context.Context, at, after int64) (ch swarm.Chunk, current, next feeds.Index, err error) {\n\tfor i := uint64(0); ; i++ {\n\t\tu, err := f.getter.Get(ctx, &index{i})\n\t\tif err != nil {\n\t\t\tif !errors.Is(err, storage.ErrNotFound) {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\treturn ch, &index{i - 1}, &index{i}, nil\n\t\t}\n\t\tts, err := feeds.UpdatedAt(u)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tif ts > uint64(at) {\n\t\t\treturn ch, &index{i}, nil, nil\n\t\t}\n\t\tch = u\n\t}\n}", "func (d *Deque[T]) EraseAt(pos int) {\n\tif pos < 0 || pos >= d.size {\n\t\treturn\n\t}\n\tseg, pos := d.pos(pos)\n\td.segmentAt(seg).eraseAt(pos)\n\tif seg < d.size-seg-1 {\n\t\tfor i := seg; i > 0; i-- {\n\t\t\tcur := d.segmentAt(i)\n\t\t\tpre := d.segmentAt(i - 1)\n\t\t\tcur.pushFront(pre.popBack())\n\t\t}\n\t\tif d.firstSegment().empty() {\n\t\t\td.putToPool(d.firstSegment())\n\t\t\td.segs[d.begin] = nil\n\t\t\td.begin = d.nextIndex(d.begin)\n\t\t\td.shrinkIfNeeded()\n\t\t}\n\t} else {\n\t\tfor i := seg; i < d.segUsed()-1; i++ {\n\t\t\tcur := d.segmentAt(i)\n\t\t\tnext := d.segmentAt(i + 1)\n\t\t\tcur.pushBack(next.popFront())\n\t\t}\n\t\tif d.lastSegment().empty() {\n\t\t\td.putToPool(d.lastSegment())\n\t\t\td.segs[d.preIndex(d.end)] = nil\n\t\t\td.end = d.preIndex(d.end)\n\t\t\td.shrinkIfNeeded()\n\t\t}\n\t}\n\td.size--\n}", "func (m memVec) ReadAt(b []byte, off int64) (int, error) {\n\tvar end int64\n\tif int64(len(m.Data))-off > int64(len(b)) {\n\t\tend = off + int64(len(b))\n\t} else {\n\t\tend = off + int64(len(m.Data))\n\t}\n\tif end > int64(len(m.Data)) {\n\t\tend = int64(len(m.Data))\n\t}\n\n\tn := copy(b, m.Data[off:end])\n\tif n == 0 {\n\t\treturn n, io.EOF\n\t}\n\treturn n, nil\n}", "func (ba *FilterBitArray) ValueAt(i uint) byte {\n\tif i < ba.Capacity() {\n\t\treturn (*ba)[i/byteSize] & (1 << (i % byteSize))\n\t}\n\treturn 0\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.len <= 0 {\n\t\treturn -1\n\t}\n\n\tn := this.l.Front().Value.(int)\n\treturn n\n}", "func (p Point) At(idx int) float64 {\n\treturn p[idx]\n}", "func (b *Bag) ItemAt(index int) *Item {\n\treturn &b.items[index]\n}", "func (cache *Cache) GetAt(seqno uint16, index uint16, result []byte) uint16 {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\tif int(index) >= len(cache.entries) {\n\t\treturn 0\n\t}\n\tif cache.entries[index].seqno != seqno {\n\t\treturn 0\n\t}\n\treturn uint16(copy(\n\t\tresult[:cache.entries[index].length()],\n\t\tcache.entries[index].buf[:]),\n\t)\n}", "func (obj VECTOR_TYPE) ValueAt(i int) float64 {\n if i < 0 || i >= obj.Dim() {\n panic(\"index out of bounds\")\n }\n if v, ok := obj.values[i]; ok {\n return v.GetValue()\n } else {\n return 0.0\n }\n}", "func (q *queue) dequeue() (int, error) {\n\tif q.front == -1 {\n\t\treturn 0, errors.New(\"The queue is empty\")\n\t}\n\n\tif q.front == q.rear{\n\t\tv := q.value[q.front]\n\t\tq.value[q.front] = 0\n\t\tq.front =-1\n\t\tq.rear = -1\n\t\treturn v,nil\n\t} else {\n\t\tv := q.value[q.front]\n\t\tq.value[q.front] = 0\n\t\tq.front = (q.front + 1) % q.size\n\t\treturn v,nil\n\t}\n}", "func (ms Float64Slice) At(i int) float64 {\n\treturn (*ms.getOrig())[i]\n}", "func (slice stringSlice) pos(value string) int {\n\tfor p, v := range slice {\n\t\tif v == value {\n\t\t\treturn p\n\t\t}\n\t}\n\n\treturn -1\n}", "func (s Scanner) peekAt(i int) byte {\n\tif s.reachedEnd() {\n\t\treturn '\\000'\n\t}\n\n\treturn s.source[s.current]\n}", "func (s *Seriet) At(i int) Point {\n\treturn s.serie[i]\n}", "func (v View) ItemAt(i int) bool {\n\treturn v.data[v.index[i]]\n}", "func (f *finder) At(ctx context.Context, at int64, _ uint64) (ch swarm.Chunk, current, next feeds.Index, err error) {\n\tfor i := uint64(0); ; i++ {\n\t\tu, err := f.getter.Get(ctx, &index{i})\n\t\tif err != nil {\n\t\t\tif !errors.Is(err, storage.ErrNotFound) {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\tif i > 0 {\n\t\t\t\tcurrent = &index{i - 1}\n\t\t\t}\n\t\t\treturn ch, current, &index{i}, nil\n\t\t}\n\t\tts, err := feeds.UpdatedAt(u)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\t// if index is later than the `at` target index, then return previous chunk and index\n\t\tif ts > uint64(at) {\n\t\t\treturn ch, &index{i - 1}, &index{i}, nil\n\t\t}\n\t\tch = u\n\t}\n}", "func (q *BytesQueue) Get(index int) ([]byte, error) {\n\tdata, _, err := q.peek(index)\n\treturn data, err\n}", "func (it *emptyIterator) At() (int64, float64) { return 0, 0 }", "func (t *StringSlice) At(i int) string {\n\treturn t.items[i]\n}", "func (vector *Vector) ElementAt(index int) interface{} {\n\treturn (*vector)[index]\n}", "func (lst *List) GetAt(idx int) *ListNode{\n\tif(idx < 0 || idx > lst.Len){\n\t\tpanic(\"index is out of boundary\")\n\t}\n\n\tcur := lst.Head\n\tfor idx > 0{\n\t\tcur = cur.Next\n\t\tidx--\n\t}\n\treturn cur\n}", "func (q *PriorityQueue) Get(i int) interface{} {\n\t// If indexing backwards, convert to positive index.\n\tif i < 0 {\n\t\ti += q.count\n\t}\n\tif i < 0 || i >= q.count {\n\t\tpanic(\"queue: Get() called with index out of range\")\n\t}\n\t// bitwise modulus\n\treturn q.buf[(q.head+i)&(len(q.buf)-1)]\n}", "func (s *ItemScroller) ItemAt(pos int) IPanel {\n\n\tif pos < 0 || pos >= len(s.items) {\n\t\treturn nil\n\t}\n\treturn s.items[pos]\n}", "func (seq List) Value(i int) interface{} { return seq[i] }", "func (d *Deque[T]) Insert(pos int, value T) {\n\tif pos < 0 || pos > d.size {\n\t\treturn\n\t}\n\tif pos == 0 {\n\t\td.PushFront(value)\n\t\treturn\n\t}\n\tif pos == d.size {\n\t\td.PushBack(value)\n\t\treturn\n\t}\n\tseg, pos := d.pos(pos)\n\tif seg < d.segUsed()-seg {\n\t\t// seg is closer to the front\n\t\td.moveFrontInsert(seg, pos, value)\n\t} else {\n\t\t// seg is closer to the back\n\t\td.moveBackInsert(seg, pos, value)\n\t}\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (arr *ArrayList) Get(index uint32) ItemType {\n if index < arr.length {\n return arr.data[index]\n }\n panic(\"out of bounds\")\n}", "func (iter *Iterator) Position() uint64 { return iter.impl.Value() }", "func (this *MyQueue) Peek() int {\n return this.q[0]\n}", "func Position(v int) predicate.QueueItem {\n\treturn predicate.QueueItem(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldPosition), v))\n\t})\n}", "func (r *runestring) SafeAt(pos int) rune {\n\tif pos < 0 || pos >= len(*r) {\n\t\treturn 0\n\t} else {\n\t\treturn (*r)[pos]\n\t}\n}", "func (s *PacketDurationQueue) Front() float32 {\n\ts.lock.RLock()\n\titem := s.items[0]\n\ts.lock.RUnlock()\n\treturn item\n}", "func (obj *SparseRealVector) ValueAt(i int) float64 {\n if i < 0 || i >= obj.Dim() {\n panic(\"index out of bounds\")\n }\n if v, ok := obj.values[i]; ok {\n return v.GetValue()\n } else {\n return 0.0\n }\n}", "func (d *Deque[T]) PopFront() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\ts := d.segs[d.begin]\n\tv := s.popFront()\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[d.begin] = nil\n\t\td.begin = d.nextIndex(d.begin)\n\t}\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (q *Queue) dequeue() int {\n\tif q.isEmpty() {\n\t\tfmt.Println(\"Queue empty\")\n\t\treturn -1\n\t}\n\tvalue := q.values[0]\n\tq.values = q.values[1:]\n\treturn value\n}", "func (p padVec) ReadAt(b []byte, off int64) (int, error) {\n\tn := int(p.Size - off)\n\n\tif n > len(b) {\n\t\tn = len(b)\n\t}\n\n\tif n == 0 {\n\t\treturn 0, io.EOF\n\t}\n\tb = make([]byte, n)\n\treturn n, nil\n}", "func (rb *RingBuffer) Get(index int) (ans stats.Record) {\n\trb.lock.RLock()\n\tdefer rb.lock.RUnlock()\n\tif index < 0 {\n\t\tindex = len(rb.data) + index\n\t}\n\treturn rb.data[(rb.seq+uint64(index))%uint64(len(rb.data))]\n}", "func (v *View) ReadAt(data []byte, off int64) (int, error) { return v.data.ReadAt(data, off) }", "func (s *Stack) Get(index int) (interface{}, error) {\n\tif index < 0 || index >= s.count {\n\t\treturn nil, fmt.Errorf(\"Requested index %d outside stack, length %d\", index, s.count)\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tn := s.top\n\tfor i := 1; i < s.count-index; i++ {\n\t\tn = n.next\n\t}\n\n\treturn n.data, nil\n}", "func (sa *SuffixArray) PositionAt(index uint64) (uint64, error) {\n\treturn sa.ba.ValueAt(index)\n}", "func (s *Scanner) pos() Pos {\n\treturn s.bufpos[s.bufi]\n}" ]
[ "0.8094775", "0.7393817", "0.73156494", "0.73156494", "0.6522282", "0.62914234", "0.62829775", "0.6275218", "0.6259047", "0.62472516", "0.6238725", "0.62124693", "0.6206992", "0.61630225", "0.61569047", "0.61540556", "0.6102033", "0.60968405", "0.6037998", "0.60040617", "0.600201", "0.59899104", "0.5989598", "0.5978252", "0.5967843", "0.5923669", "0.59019893", "0.58992475", "0.5878913", "0.58770216", "0.5873156", "0.58605236", "0.58523184", "0.58227557", "0.5807288", "0.58052206", "0.58017564", "0.5790483", "0.5783341", "0.5777962", "0.5773789", "0.577333", "0.5766502", "0.576316", "0.5738812", "0.5736826", "0.572892", "0.5728854", "0.5724321", "0.5707496", "0.5699264", "0.5682819", "0.56776035", "0.5657509", "0.56561255", "0.5656012", "0.5655958", "0.5655648", "0.5652167", "0.5637933", "0.56358963", "0.5634185", "0.56301856", "0.56293255", "0.5626372", "0.56060094", "0.5596925", "0.55961144", "0.55950224", "0.55939996", "0.55825347", "0.55803406", "0.5573666", "0.5570622", "0.5561781", "0.55612093", "0.5557181", "0.55420333", "0.55361766", "0.55300474", "0.55197096", "0.5502881", "0.5499015", "0.54940397", "0.549296", "0.5478804", "0.5465185", "0.54544353", "0.5448624", "0.54396135", "0.5437997", "0.5425319", "0.5421154", "0.54152733", "0.5407944", "0.5403821", "0.54029495", "0.538944", "0.53831184", "0.5366087" ]
0.7843133
1
Set sets the value of the deque's position pos with value val
func (d *Deque[T]) Set(pos int, val T) error { if pos < 0 || pos >= d.size { return ErrOutOfRange } seg, pos := d.pos(pos) d.segmentAt(seg).set(pos, val) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (iter *SliceIterator) SetValue(val interface{}) {\n\titer.s.Set(iter.position, val)\n}", "func (iter *Iterator) SetPosition(pos uint64) { iter.impl.SetValue(pos) }", "func (r *Ring) set(p int, v interface{}) {\n\tr.buff[r.mod(p)] = v\n}", "func (c *FIFO) Set(key, val T) {\n\tdefer c.dump()\n\t// if it already exists\n\tif val, ok := c.cache[key]; ok {\n\t\tc.cache[key] = val\n\t\treturn\n\t}\n\n\t// when cache is not full\n\tif len(c.cache) < c.size {\n\t\tc.cache[key] = val\n\t\tc.q.PushBack(key)\n\t\treturn\n\n\t}\n\te := c.q.Front()\n\tdelete(c.cache, e.Value)\n\tc.q.Remove(e)\n\tc.cache[key] = val\n\tc.q.PushBack(key)\n\treturn\n}", "func (q *quartileIndex) Set(at int, val bool) {\n\tcur := q.bits.Get(at)\n\tif cur && val {\n\t\treturn\n\t}\n\tif !cur && !val {\n\t\treturn\n\t}\n\tq.bits.Set(at, val)\n\tvar delta int\n\tif val {\n\t\tdelta = 1\n\t} else {\n\t\tdelta = -1\n\t}\n\tfor i, o := range q.offsets {\n\t\tif at < o {\n\t\t\tq.counts[i] += delta\n\t\t}\n\t}\n}", "func (aa *Array) Set(idx int, node interface{}) error {\n\t// do not lock if not needed\n\tif idx < 0 || idx >= aa.length {\n\t\treturn fmt.Errorf(\"index %d is larger than array size (%d)\", idx, aa.length)\n\t}\n\n\taa.mutex.Lock()\n\taa.items[idx] = node\n\taa.mutex.Unlock()\n\treturn nil\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 (v *VectorImpl) Set(i int, item Value) *VectorImpl {\n\tif i < 0 || uint(i) >= v.len {\n\t\tpanic(\"Index out of bounds\")\n\t}\n\n\tif uint(i) >= v.tailOffset() {\n\t\tnewTail := make([]Value, len(v.tail))\n\t\tcopy(newTail, v.tail)\n\t\tnewTail[i&shiftBitMask] = item\n\t\treturn &VectorImpl{root: v.root, tail: newTail, len: v.len, shift: v.shift}\n\t}\n\n\treturn &VectorImpl{root: v.doAssoc(v.shift, v.root, uint(i), item), tail: v.tail, len: v.len, shift: v.shift}\n}", "func (iter *ListIterator) SetValue(value interface{}) {\n\tif iter.node != nil {\n\t\titer.node.Value = value\n\t}\n}", "func (ds databaseSequencer) SetVal(val int64) error {\n\terr := ds.db.RawQuery(\"SELECT setval($1, $2)\", ds.sequenceName, val).Exec()\n\treturn err\n}", "func (sa *SnapshotArray) Set(index int, val int) {\n\tsa.current[index] = val\n}", "func (r *SlidingWindow) Set(index int, value interface{}) bool {\n\tindex -= r.base\n\tif index < 0 || index >= r.Capacity() {return false}\n\tindex = r.normalize(index + r.start)\n\tr.values[index].value = value\n\tif !r.values[index].present {\n\t\tr.values[index].present = true\n\t\tr.count++\n\t}\n\treturn true\n}", "func (d *Deque[T]) Insert(pos int, value T) {\n\tif pos < 0 || pos > d.size {\n\t\treturn\n\t}\n\tif pos == 0 {\n\t\td.PushFront(value)\n\t\treturn\n\t}\n\tif pos == d.size {\n\t\td.PushBack(value)\n\t\treturn\n\t}\n\tseg, pos := d.pos(pos)\n\tif seg < d.segUsed()-seg {\n\t\t// seg is closer to the front\n\t\td.moveFrontInsert(seg, pos, value)\n\t} else {\n\t\t// seg is closer to the back\n\t\td.moveBackInsert(seg, pos, value)\n\t}\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func set(l *foo, i byte, to *foo) {\n\tif i == Next {\n\t\tl.next = to\n\t\treturn\n\t}\n\tl.prev = to\n}", "func (r *Radix) set(v interface{}) {\n\tr.value = v\n}", "func (b *Board) Set(p Position, val byte) {\n\tb[p.row][p.col] = val\n}", "func (n *Node) SetVal(v Val)", "func (uni *UniformMatrix3f) Set(pos int, v float32) {\n\n\tuni.v[pos] = v\n}", "func (q *Queue) enqueue(value int) {\n\tq.values = append(q.values, value)\n}", "func (ll *LinkedList) Set(index uint, data interface{}) {\n\tll.Lock()\n\tdefer ll.Unlock()\n\n\tif index >= ll.size {\n\t\tpanic(&IndexOutOfRangeError{size: ll.size})\n\t}\n\n\tnode := ll.findNode(index)\n\tnode.data = data\n}", "func (list *List) Set(index int, value interface{}) {\n\n\tif !list.withinRange(index) {\n\t\t// Append\n\t\tif index == list.size {\n\t\t\tlist.Add(value)\n\t\t}\n\t\treturn\n\t}\n\n\tfoundElement := list.first\n\tfor e := 0; e != index; {\n\t\te, foundElement = e+1, foundElement.next\n\t}\n\tfoundElement.value = value\n}", "func (qiuo *QueueItemUpdateOne) SetPosition(i int) *QueueItemUpdateOne {\n\tqiuo.mutation.ResetPosition()\n\tqiuo.mutation.SetPosition(i)\n\treturn qiuo\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 (b *Bitset) Set(pos int) error {\n\tif pos < 0 || pos >= b.length*32 {\n\t\treturn fmt.Errorf(\"invalid position for bitset of length %d\", b.length)\n\t}\n\t// Pos will take a value between 0 and length\n\t// each chunck of the bitset is a 4 byte integer\n\t// so for e.g Set(10) will need to set the 10th\n\t// bit which is found in the first chunck i.e bitvec[0].\n\t// By reducing modulo 32 we find the local position in the bitvec.\n\trpos := pos / 32 // (relative position inside the integer slice)\n\tbpos := pos % 32 // (local bit position inside bitvec[rpos])\n\n\tflag := int32(1) << bpos\n\tb.bitvec[rpos] = b.bitvec[rpos] | flag\n\n\treturn nil\n}", "func (t *FenwickTreeSimple) Set(index int, value int) {\n\tt.Update(index, value-t.Get(index))\n}", "func (this *SnapshotArray) Set(index int, val int) {\n\tif len(this.arr[index]) < this.snapId+1 {\n\t\tfor len(this.arr[index]) < this.snapId+1 {\n\t\t\tthis.arr[index] = append(this.arr[index], this.arr[index][len(this.arr[index])-1])\n\t\t}\n\t}\n\tthis.arr[index][this.snapId] = val\n}", "func (s *SGTree) Set(i int, e interface{}) {\n\ts.data[i] = e\n\ts.set(0, 0, len(s.data)-1, i, e)\n}", "func (qiu *QueueItemUpdate) SetPosition(i int) *QueueItemUpdate {\n\tqiu.mutation.ResetPosition()\n\tqiu.mutation.SetPosition(i)\n\treturn qiu\n}", "func (uni *Uniform1fv) Set(pos int, v float32) {\n\n\tuni.v[pos] = v\n}", "func (vn *VecN) Set(i int, val float64) {\n\tvn.vec[i] = val\n}", "func (l *List) Set(i *Item, value interface{}) {\n\ti.value = l.valueToPointer(value)\n}", "func (l *LRU) Set(ID T, val T) {\r\n\tel := Element{ID, val}\r\n//\tdefer l.dump()\r\n\r\n\tif e, ok := l.cache[ID]; ok {\r\n\t\te.Value = el\r\n\t\tl.link.MoveToFront(e)\r\n\t\treturn\r\n\t}\r\n\tif len(l.cache) < l.size {\r\n\t\tl.cache[ID] = l.link.PushFront(el)\r\n\t\treturn\r\n\r\n\t}\r\n\te := l.link.Back()\r\n\tdelete(l.cache, e.Value.(Element).ID)\r\n\tl.link.Remove(e)\r\n\tl.cache[ID] = l.link.PushFront(el)\r\n\treturn\r\n}", "func (arr *Array) set(i int, v *Term) {\n\tarr.ground = arr.ground && v.IsGround()\n\tarr.elems[i] = v\n\tarr.hashs[i] = v.Value.Hash()\n}", "func (b *box) setFieldValue(x, y, v int) {\n\t// Matrix conversion, see: https://stackoverflow.com/a/14015582\n\tb.values[x+y*3] = v\n}", "func (n *Node) SetValue(value int) {\n\tpriorValues := map[*Node]int{n: n.value}\n\tn.value = value\n\tqueue := append([]*Node{}, n.dependencies...)\n\n\t// update values of all dependencies in a BFS manner, tracking prior values\n\tfor len(queue) > 0 {\n\t\tnext := queue[0]\n\t\tqueue = append(queue[1:], next.dependencies...)\n\t\tpriorValues[next] = next.value\n\t\tif next.f1 != nil {\n\t\t\tnext.value = next.f1(next.a.Value())\n\t\t} else if next.f2 != nil {\n\t\t\tnext.value = next.f2(next.a.Value(), next.b.Value())\n\t\t}\n\t}\n\n\t// for any changed value, also trigger callbacks\n\tfor m := range priorValues {\n\t\tif priorValues[m] != m.value {\n\t\t\tfor _, f := range m.callbacks {\n\t\t\t\tif f != nil {\n\t\t\t\t\tf(m.value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *NodeMutation) SetValue(i int) {\n\tm.value = &i\n\tm.addvalue = nil\n}", "func (iter *RbTreeIterator) SetValue(val interface{}) error {\n\titer.node.SetValue(val)\n\treturn nil\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 (m *Matrix) Set(x, y int, v int64) {\n\txl, yl := int(m.focus.Min().X)+x, int(m.focus.Min().Y)+y\n\tif xl < 0 || xl >= m.WAbs() || yl < 0 || yl >= m.HAbs() {\n\t\treturn\n\t}\n\tm.list[xl+m.WAbs()*yl] = v\n}", "func (queue *Queue) enq(value *unsafe.Pointer) {\n\ti := queue.getAndIncrement()\n\tqueue.values[i] = value\n}", "func (e *Element) SetValue(val interface{}) {\n\te.value = val\n}", "func (m *CardMutation) SetValue(i int) {\n\tm.value = &i\n\tm.addvalue = nil\n}", "func (uni *Uniform3fv) SetPos(pos int, v float32) {\n\n\tuni.v[pos] = v\n}", "func (sv *SyncVal) Set(val interface{}) {\n\tsv.lock.Lock()\n\tsv.val = val\n\tsv.lock.Unlock()\n}", "func (node *Node) SetValue(value int) {\n\tnode.Value = value\n}", "func (uni *Uniform4fv) SetPos(pos int, v float32) {\n\n\tuni.v[pos] = v\n}", "func (d *Deque[T]) PushFront(value T) {\n\td.firstAvailableSegment().pushFront(value)\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (access FloatAccess) Set(row int, val float64) {\n access.rawData[access.indices[row]] = val\n}", "func (c *Cache) Set(key string, value interface{}) {\n\tif c.lists[0].Len() < c.capacity {\n\t\tc.data[key] = c.lists[0].PushFront(&cacheItem{0, key, value})\n\t\treturn\n\t}\n\n\t// reuse the tail item\n\te := c.lists[0].Back()\n\titem := e.Value.(*cacheItem)\n\n\tdelete(c.data, item.key)\n\titem.key = key\n\titem.value = value\n\tc.data[key] = e\n\tc.lists[0].MoveToFront(e)\n}", "func (q *Deque) PushFront(v interface{}) {\n\tif q.size == cap(q.values) {\n\t\tnewCap := 2\n\t\tif cap(q.values) > 0 {\n\t\t\tnewCap = cap(q.values) * 2\n\t\t}\n\t\tq.Resize(newCap)\n\t}\n\n\tq.front--\n\tif q.front < 0 {\n\t\tq.front = cap(q.values) - 1\n\t}\n\n\tq.values[q.front] = v\n\tq.size++\n}", "func (buf *ListBuffer) Set(idx BufferIndex, item Item) (*error.Error) {\n\tinRange, initialized := buf.legalIndex(idx)\n\tif !inRange {\n\t\tdesc := fmt.Sprintf(\n\t\t\t\"idx, %d, is out of range for IndexBuffer of length %d.\",\n\t\t\tidx, len(buf.Buffer),\n\t\t)\n\t\treturn error.New(error.Value, desc)\n\t} else if !initialized {\n\t\tdesc := fmt.Sprintf(\n\t\t\t\"Item at idx, %d, has the Type value Uninitialized.\", idx,\n\t\t)\n\t\treturn error.New(error.Value, desc)\n\t}\n\n\tbuf.Buffer[idx].Item = item\n\treturn nil\n}", "func (A *Matrix) Set(i, j int, v float64){\n\tA.data[i * A.stride + j] = v\n}", "func (d *DynamicArr) Set(index int, value interface{}) error {\n\tif index < 0 {\n\t\treturn errors.New(\"Index has to be greater than or equal to zero\")\n\t}\n\n\tfor index > d.capacity {\n\t\td.growSize()\n\t\td.length = d.capacity\n\t}\n\n\td.array[index] = value\n\td.length++\n\treturn nil\n}", "func (lo *LuaObject) Set(idx interface{}, val interface{}) interface{} {\n L := lo.L\n lo.Push() // the table\n GoToLua(L, nil, valueOf(idx))\n GoToLua(L, nil, valueOf(val))\n L.SetTable(-3)\n L.Pop(1) // the table\n return val\n}", "func (q *Queue) Enqueue(value interface{}) {\n\tn := &node{value, nil}\n\tif q.length == 0 {\n\t\tq.start = n\n\t\tq.end = n\n\t} else {\n\t\tq.end.next = n\n\t\tq.end = n\n\t}\n\tq.length++\n}", "func (s *inMemoryStore) Set(ctx context.Context, h types.Metric, resetTime time.Time, fieldVals []any, value any) {\n\tif resetTime.IsZero() {\n\t\tresetTime = clock.Now(ctx)\n\t}\n\tm := s.getOrCreateData(h)\n\tt := s.findTarget(ctx, m)\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tc := m.get(fieldVals, t, resetTime)\n\n\tif m.ValueType.IsCumulative() && isLessThan(value, c.Value) {\n\t\tlogging.Errorf(ctx,\n\t\t\t\"Attempted to set cumulative metric %q to %v, which is lower than the previous value %v\",\n\t\t\th.Info().Name, value, c.Value)\n\t\treturn\n\t}\n\n\tc.Value = value\n}", "func (h *HexWidget) Set(val uint) {\n\tval = val % 16\n\th.UpdateSegments(segmentLookupTable[val])\n}", "func (field *Field) SetValue(parser *ArgParse, args ...string) (size int, err error) {\n\tsize = 1\n\t// the basic setter\n\tif size, err = field.setValue(field.Value, args...); err != nil {\n\t\treturn\n\t}\n\n\tif fn := GetCallback(parser.Value, field.Callback); fn != nil {\n\t\tlog.Debug(\"try execute %v\", field.Callback)\n\t\t// trigger the callback, exit when callback return true\n\t\tif fn(parser) && ExitWhenCallback {\n\t\t\tlog.Info(\"execute callback %v, and exit 0\", field.Callback)\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tfield.BeenSet = true\n\tif field.Value.Kind() == reflect.Ptr && field.Value.Elem().Kind() == reflect.Slice {\n\t\t// can set repeat\n\t\tfield.BeenSet = false\n\t}\n\tlog.Info(\"set %v as %v (%d)\", field.Name, field.Value, size)\n\treturn\n}", "func (ms HistogramBucketExemplar) SetValue(v float64) {\n\t(*ms.orig).Value = v\n}", "func (m *M) Set(r, c int, v Frac) {\n\tr, c = r-1, c-1\n\tm.values[r*m.c+c] = v.Reduce()\n}", "func (f *Int64) Set(val int64) {\n\tf.set(-1, val, false)\n}", "func (q *Queue) Enqueue(value interface{}) {\n\tn := &node{value, nil}\n\tif q.length != 0 {\n\t\tq.end.next = n\n\t\tq.end = n\n\t} else {\n\t\tq.start, q.end = n, n\n\t}\n\tq.length++\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 (q *Sque) SetLen(l int) {\n\tq.Slen = l\n}", "func (c *AdapterMemory) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error {\n\texpireTime := c.getInternalExpire(duration)\n\tc.data.Set(key, adapterMemoryItem{\n\t\tv: value,\n\t\te: expireTime,\n\t})\n\tc.eventList.PushBack(&adapterMemoryEvent{\n\t\tk: key,\n\t\te: expireTime,\n\t})\n\treturn nil\n}", "func (m *Matrix) Set(x, y int, val float64) {\n\treturn\n}", "func (this *Tuple) Set(n int, item interface{}) {\n\tthis.data[this.Offset(n)] = item\n}", "func (access IntAccess) Set(row int, val int) {\n access.rawData[access.indices[row]] = val\n}", "func (ms Float64Slice) SetAt(i int, val float64) {\n\t(*ms.getOrig())[i] = val\n}", "func (ct *Ctr) Set(cur int) bool {\n\tif ct.Cur == cur {\n\t\tct.Chg = false\n\t\treturn false\n\t}\n\tct.Chg = true\n\tct.Prv = ct.Cur\n\tct.Cur = cur\n\treturn true\n}", "func (this *Queue) Enqueue(value interface{}) {\r\n\tn := &node{value,nil}\r\n\tif this.length == 0 {\r\n\t\tthis.start = n\r\n\t\tthis.end = n\t\t\r\n\t} else {\r\n\t\tthis.end.next = n\r\n\t\tthis.end = n\r\n\t}\r\n\tthis.length++\r\n}", "func SetValue(r interface{}, val string) error {\n\tiVal, err := ValueFromString(val, reflect.TypeOf(r))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trecv := reflect.ValueOf(r)\n\tif recv.Type().Kind() == reflect.Ptr {\n\t\trecv = recv.Elem()\n\t}\n\n\tv := reflect.ValueOf(iVal)\n\tif v.Type().Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\trecv.Set(v)\n\treturn nil\n}", "func (f *BatchFuture) Set(index uint64, err error) {\n\tf.index = index\n\tf.err = err\n\tclose(f.waitCh)\n}", "func (c *cell) SetValue(v int) {\n\tr := c.reactor\n\tr.startWorking()\n\tif c.value != v {\n\t\tr.addChangingCell(c)\n\t\tc.saveValue(v)\n\t}\n\tr.stopWorking()\n}", "func (l *List) Set(val interface{}) (err error) {\n\tslice, ok := val.([]interface{})\n\tif !ok {\n\t\treturn newError(ErrType, \"expected a list value\")\n\t}\n\n\tnewList := make([]Item, len(slice))\n\n\tfor i, item := range slice {\n\t\tnewItem := MakeZeroValue(l.valType)\n\t\tif err := newItem.Set(item); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnewList[i] = newItem\n\t}\n\n\tl.value = newList\n\n\treturn nil\n}", "func (ms Int64DataPoint) SetValue(v int64) {\n\t(*ms.orig).Value = v\n}", "func (c *Cursor) Seek(pos SeqNum) {\n\tc.pos = pos\n}", "func (q *Queue) Push(v int) {\n\t//这里的*q是一个指针接受者, 指针接受者时可以改变里面的值的\n\t// 后面使用*q 前面也要加一个*\n\t*q = append(*q, v)\n}", "func (m *redisDB) Set(key string, val []byte, expiration time.Duration) (err error) {\n\n\treturn m.client.Set(m.ctx, key, string(val), expiration).Err()\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 SetValue(db storage.Store, cmd *fsm.Command, val *Value) error {\n\tk := KeyFromCommand(cmd)\n\treturn db.Set(k.ToBytes(), val.ToBytes())\n}", "func (c Cube) Set(x, y, z int, val []float64) {\n\tc.Data[x][y][z] = val\n}", "func (d *Datum) Set(value int64, timestamp time.Time) {\n\tatomic.StoreInt64(&d.Value, value)\n\td.stamp(timestamp)\n}", "func (d *Datum) Set(value int64, timestamp time.Time) {\n\tatomic.StoreInt64(&d.Value, value)\n\td.stamp(timestamp)\n}", "func (rs *RedisStorage) Set(key string, val []byte, ttl time.Duration) error {\n\tresult := rs.redisClient.Set(context.Background(), key, val, ttl)\n\treturn result.Err()\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n if this.IsFull() {\n return false\n }\n this.head = (this.head - 1 + this.capacity) % this.capacity\n this.data[this.head] = value\n return true\n}", "func (nu *NodeUpdate) SetValue(i int) *NodeUpdate {\n\tnu.value = &i\n\tnu.addvalue = nil\n\treturn nu\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 (b *Bar) Set(n int) error {\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\tif n > b.Total {\n\t\treturn ErrMaxCurrentReached\n\t}\n\tb.current = n\n\treturn nil\n}", "func (i *queueIndex) putTail(aid, pos int) {\n\ti.indexArena.WriteUint64(16, uint64(aid))\n\ti.indexArena.WriteUint64(24, uint64(pos))\n}", "func (s *VectorImplSlice) Set(i int, item Value) *VectorImplSlice {\n\tif i < 0 || s.start+i >= s.stop {\n\t\tpanic(\"Index out of bounds\")\n\t}\n\n\treturn s.vector.Set(s.start+i, item).Slice(s.start, s.stop)\n}", "func (s *SQLite) Set(key string, val []byte) error {\n\t// Override the old value with new one.\n\tstmt, err := s.db.Prepare(\"REPLACE INTO key_value (key, value) VALUES (?,?)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(key, val)\n\treturn err\n}", "func (s *sliding) update(pos LogPosition, u Update) {\n\ts.log[s.mutable-s.start:][pos-s.mutable] = u\n}", "func (c *Cache) Set(key []byte, val []byte, db *pebble.DB) error {\n\tc.lock.Lock()\n\tc.moveItemToFront(key)\n\tc.hitCounter = c.hitCounter + 1\n\tc.lock.Unlock()\n\t// Manage clearing the cache only once every 20 sets\n\t// Adjust this number back to 20 after debugging for better\n\t// performance\n\tif c.hitCounter%1 == 0 {\n\t\ttableSize := getTableSize(db)\n\t\tif tableSize > c.MaxSizeInBytes {\n\t\t\terr := c.evictFromCache(db)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n\terr := db.Set(key, val, pebble.Sync)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (v *NullableWidgetLiveSpan) Set(val *WidgetLiveSpan) {\n\tv.value = val\n\tv.isSet = true\n}", "func (llrb *LLRB) Set(key, value, oldvalue []byte) (ov []byte, cas uint64) {\n\tif !llrb.lock() {\n\t\treturn\n\t}\n\n\tllrb.seqno++\n\n\troot, newnd, oldnd := llrb.upsert(llrb.getroot(), 1 /*depth*/, key, value)\n\troot.setblack()\n\tnewnd.cleardeleted()\n\tnewnd.cleardirty()\n\tnewnd.setseqno(llrb.seqno)\n\tseqno := llrb.seqno\n\n\tllrb.setroot(root)\n\tllrb.upsertcounts(key, value, oldnd)\n\n\tif oldvalue != nil {\n\t\tvar val []byte\n\t\tif oldnd != nil && oldnd.isdeleted() == false {\n\t\t\tval = oldnd.Value()\n\t\t}\n\t\toldvalue = lib.Fixbuffer(oldvalue, int64(len(val)))\n\t\tcopy(oldvalue, val)\n\t}\n\n\tllrb.freenode(oldnd)\n\n\tllrb.unlock()\n\treturn oldvalue, seqno\n}", "func (c *Counter) Set(v uint64) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.ticksCurrent = atomic.LoadInt64(&ticks)\n\tc.v = v\n\n\t// initialize previous values to current if counter\n\t// overflows or if this is our first value\n\tif c.ticksPrevious == 0 || c.p > c.v {\n\t\tc.p = c.v\n\t\tc.ticksPrevious = c.ticksCurrent\n\t}\n}", "func (r *Record) SetValue(fid int, val *Value) {\n\tif len(r.Fields) == 0 {\n\t\tr.Fields = make(map[int]*Value)\n\t}\n\tr.Fields[fid] = val\n}", "func (f *fragment) setValue(columnID uint64, bitDepth uint, value int64) (changed bool, err error) {\n\treturn f.setValueBase(columnID, bitDepth, value, false)\n}", "func (s *Queue) Push(val interface{}) {\n\tif s.IsEmpty() {\n\t\ttmp := new(node)\n\t\ttmp.val = val\n\t\ts.head = tmp\n\t\ts.tail = tmp\n\t\ts.len += 1\n\t} else {\n\t\tcurrent_tail := s.tail\n\t\ttmp := new(node)\n\t\ttmp.val = val\n\t\tcurrent_tail.previous = tmp\n\t\ttmp.next = current_tail\n\t\ts.tail = tmp\n\t\ts.len += 1\n\t}\n}" ]
[ "0.66146106", "0.6509227", "0.59827954", "0.59693074", "0.5921609", "0.5893793", "0.58464926", "0.5811844", "0.5784987", "0.57620317", "0.5759898", "0.57593936", "0.575584", "0.5694425", "0.5663744", "0.56510544", "0.5649973", "0.560702", "0.560366", "0.5591572", "0.55874825", "0.5547491", "0.5526044", "0.55104923", "0.5507439", "0.5506566", "0.5493937", "0.5492618", "0.548301", "0.5480979", "0.54801834", "0.5478473", "0.5472215", "0.5472203", "0.54534143", "0.5448943", "0.5442175", "0.54382247", "0.54347765", "0.54167664", "0.5411455", "0.5406801", "0.5383885", "0.5379227", "0.53783345", "0.5373366", "0.5366529", "0.5364344", "0.53549224", "0.53537166", "0.5351128", "0.5348797", "0.5345388", "0.5343759", "0.5343303", "0.5332391", "0.53296316", "0.5322682", "0.5321968", "0.5319635", "0.5307118", "0.5302065", "0.52771115", "0.52648836", "0.52621686", "0.524616", "0.52421904", "0.52352434", "0.5235015", "0.5219339", "0.5212806", "0.5211815", "0.51961267", "0.519515", "0.5185826", "0.5184385", "0.5183378", "0.5178971", "0.517828", "0.51772547", "0.5176427", "0.51728135", "0.51647425", "0.51647425", "0.51529235", "0.5141077", "0.512355", "0.51202184", "0.5119636", "0.51160175", "0.5115231", "0.5115137", "0.51112753", "0.5108402", "0.5108347", "0.51053035", "0.51040107", "0.5100566", "0.50979835", "0.5095707" ]
0.8170814
0
PopFront returns the value at the first position of the deque and removes it
func (d *Deque[T]) PopFront() T { if d.size == 0 { panic("deque is empty") } s := d.segs[d.begin] v := s.popFront() if s.size() == 0 { d.putToPool(s) d.segs[d.begin] = nil d.begin = d.nextIndex(d.begin) } d.size-- d.shrinkIfNeeded() return v }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Deque) PopFront() {\n\tif !q.Empty() {\n\t\tq.front = (q.front + 1) % cap(q.values)\n\t\tq.size--\n\t}\n}", "func (dq *Dqueue) PopFront() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\tdq.dqueue.Remove(0)\n\treturn\n}", "func (d *Deque) PopFront() (interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\toldFront := d.front\n\td.front = oldFront.prev\n\n\tif d.front == nil {\n\t\td.back = nil\n\t} else {\n\t\td.front.next = nil\n\t}\n\t// collect the data\n\tret := oldFront.data\n\t// clean up\n\toldFront.next = nil\n\toldFront.prev = nil\n\t// size decrement\n\td.size--\n\treturn ret, true\n}", "func (cq *cQT) PopFront() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tel = cq.b[cq.s&cq.m]\n\tcq.b[cq.s&cq.m] = zero\n\tcq.s++\n\treturn el, true\n}", "func (ll *LinkedList) PopFront() T {\n\tif ll.head == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.head.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\thead := ll.head.next\n\t\thead.prev = nil\n\t\tll.head.next = nil\n\t\tll.head = head\n\t}\n\n\tll.size--\n\treturn val\n}", "func (l *List) PopFront() (interface{}, error) {\n\tif l.head == nil {\n\t\treturn 0, ErrEmptyList\n\t}\n\n\tdata := l.head.Val\n\n\tif l.head.Next() == nil {\n\t\tl.head = nil\n\t\tl.last = nil\n\t} else {\n\t\tl.head.Next().previous = nil\n\t\tl.head = l.head.Next()\n\t}\n\n\treturn data, nil\n\n}", "func (l *List) PopFront() (interface{}, error) {\n\tif l.Len == 0 {\n\t\treturn nil, ErrEmptyList\n\t}\n\tv := l.head.Val\n\tl.head = l.head.next\n\tl.Len--\n\tif l.Len == 0 {\n\t\tl.tail = nil\n\t} else {\n\t\tl.head.prev = nil\n\t}\n\treturn v, nil\n}", "func (q *Queue) popFront() interface{} {\n\te := q.front.link\n\tq.front.link = e.link\n\tif e == q.back {\n\t\tq.back = q.front\n\t}\n\tq.queueLen--\n\n\tif q.queueLen < q.softQuota {\n\t\t// Successfully removing items from the queue below half the soft quota\n\t\t// lowers the soft quota. This has the effect of increasing the credit cap\n\t\t// and the amount of credit given for removing items to better approximate\n\t\t// the rate at which the consumer is servicing the queue.\n\t\tif q.softQuota > 1 && q.queueLen < q.softQuota/2 {\n\t\t\tq.softQuota--\n\t\t}\n\n\t\t// Give credit for being below the soft quota. Note we do this after\n\t\t// adjusting the quota so the credit reflects the item we just removed.\n\t\tq.credit += float64(q.softQuota-q.queueLen) / float64(q.softQuota)\n\t\tif cap := float64(q.hardLimit - q.softQuota); q.credit > cap {\n\t\t\tq.credit = cap\n\t\t}\n\t}\n\n\treturn e.item\n}", "func (l *List) PopFront() (interface{}, error) {\n\tif l.head == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\n\tval := l.head.Val\n\tl.head = l.head.next\n\n\tif l.head == nil {\n\t\tl.tail = nil\n\t} else {\n\t\tl.head.prev = nil\n\t}\n\n\treturn val, nil\n}", "func (l *List) PopFront() (interface{}, error) {\n\tif l.first == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\tn := l.first\n\tif l.last == n {\n\t\tl.last = nil\n\t}\n\tl.first = n.next\n\tif l.first != nil {\n\t\tl.first.prev = nil\n\t}\n\treturn n.Val, nil\n}", "func (v *Data) PopFront() PicData {\n\treturn v.Remove(0)\n}", "func (vector *Vector) PopFront() {\n\tvar element interface{}\n\telement, *vector = (*vector)[0], (*vector)[1:]\n\t// Note: dropping element here.\n\t_ = element\n}", "func (v *IntVec) PopFront() int {\n\treturn v.Remove(0)\n}", "func (q *wantConnQueue) popFront() *wantConn {\n\tif q.headPos >= len(q.head) {\n\t\tif len(q.tail) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\t// Pick up tail as new head, clear tail.\n\t\tq.head, q.headPos, q.tail = q.tail, 0, q.head[:0]\n\t}\n\n\tw := q.head[q.headPos]\n\tq.head[q.headPos] = nil\n\tq.headPos++\n\treturn w\n}", "func (l *TwoList) PopFront() *Element {\n\treturn l.seekFront(true)\n}", "func (d *Deque) Pop() (interface{}, error) {\n\tif d.length == 0 {\n\t\treturn nil, fmt.Errorf(\"Can not pop from an empty deque.\")\n\t}\n\n\titem := d.head.next\n\td.head.next = d.head.next.next\n\n\tif d.head.next != nil {\n\t\td.head.next.prev = d.head\n\t}\n\n\td.length--\n\n\treturn item.value, nil\n}", "func (que *Queue) Pop() string {\n\tnode := que.values[0]\n\tque.values = que.values[1:]\n\treturn node\n}", "func (v *Int32Vec) PopFront() int32 {\n\treturn v.Remove(0)\n}", "func (d *Deque) PopFront() (*Deque, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.head != nil:\n\t\treturn &Deque{nil, d.child, d.tail}, true\n\n\tdefault:\n\t\tdd, _ := d.child.PopFront()\n\t\treturn &Deque{nil, dd, d.tail}, true\n\t}\n}", "func (d *Deque[T]) PopBack() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\tseg := d.preIndex(d.end)\n\ts := d.segs[seg]\n\tv := s.popBack()\n\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[seg] = nil\n\t\td.end = seg\n\t}\n\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (s *Queue) Pop() interface{} {\n\tif s.IsEmpty() {\n\t\tpanic(\"Pop on empty queue\")\n\t} else {\n\t\tcurrent_head := s.head\n\t\tval := current_head.val\n\t\ts.head = current_head.previous\n\t\tcurrent_head.val = nil\n\t\treturn val\n\t}\n}", "func (d *MyCircularDeque) GetFront() int {\n\tif d.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn d.Val[0]\n}", "func (Q *Deque) RemoveFirst() (interface{}, error) {\n\tif Q.size == 0 {\n\t\treturn nil, errors.New(\"Queue is empty\")\n\t}\n\tcurrentVal := Q.front.val\n\tnextNode := Q.front.next\n\tQ.front = nextNode\n\treturn currentVal, nil\n}", "func (l *SliceList[T]) PopFront() (v T, ok bool) {\n\tif len(*l) > 0 {\n\t\tv, *l = (*l)[0], (*l)[1:]\n\t\treturn\n\t}\n\n\treturn\n}", "func (l *PList) PopFront() *Element {\n\tl.Clone()\n\thead := l.head\n\n\tif head == nil {\n\t\t// zero length\n\t\treturn nil\n\t} else if head == l.tail {\n\t\t// one length\n\t\tl.head = nil\n\t\tl.tail = nil\n\t\t// avoid memory leaks\n\t\thead.next = nil\n\t} else {\n\t\tl.head = head.next\n\t\t// avoid memory leaks\n\t\thead.next = nil\n\t}\n\treturn head\n}", "func (q *Deque) PopBack() {\n\tif !q.Empty() {\n\t\tq.back--\n\t\tq.size--\n\t}\n}", "func (q *Deque) Front() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.front]\n\t}\n\treturn nil\n}", "func (dq *Dqueue) PopBack() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\tdq.dqueue.Remove(dq.Size() - 1)\n\treturn\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.head.value\n}", "func (q *Queue) Pop() int {\n\t//这里的括号是定界符\n\t//这里是取出第0个元素进行返回\n\thead := (*q)[0]\n\t//将q的内存地址中的数据, 修改为将q的下标为1开始剪切到最后一个的数据\n\t// 后面使用*q 前面也要加一个*\n\t*q = (*q)[1:]\n\treturn head\n}", "func (l *List) PopFront() *Process {\n\tp := (*l)[0]\n\t*l = (*l)[1:]\n\treturn p\n}", "func (q *Queue) Pop() interface{} {\n\tif len(q.queue) < 1 {\n\t\treturn nil\n\t}\n\n\tfirst := q.queue[0]\n\tq.queue = q.queue[1:]\n\n\treturn first\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.First.Next.Data\n}", "func (s *FIFO) Pop() (T, bool) {\n\tif s.front == nil {\n\t\treturn nil, false\n\t}\n\tnode := s.front\n\ts.front = node.next\n\ts.size--\n\treturn node.v, true\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.length == 0 {\n\t\treturn -1\n\t}\n\treturn this.head.next.val\n}", "func (sll *SingleLinkedList) Pop(index int) interface{} {\n\t// Panic if index is smaller 0\n\tif index < 0 {\n\t\tpanic(\"index < 0\")\n\t}\n\n\t// Pop first element\n\tif index == 0 {\n\t\t// Result\n\t\tv := sll.first.value\n\t\t// Remove first element\n\t\tsll.first = sll.first.next\n\t\t// Decrease length\n\t\tsll.length--\n\t\treturn v\n\t}\n\n\t// Get node before the one to pop\n\tn := sll.getNode(index - 1)\n\t// Result\n\tv := n.next.value\n\t// Remove reference to remove element\n\tn.next = n.next.next\n\t// Decrease length\n\tsll.length--\n\treturn v\n}", "func (m *OrderedMap[K,V]) PopFront() (k K, v V, ok bool) {\n\te := m.list.Front()\n\tif e == nil {\n\t\treturn\n\t}\n\tk, v, ok = e.Value.Key, e.Value.Value, true\n\tdelete(m.mp, k)\n\tm.list.Remove(e)\n\treturn\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\n\treturn this.data[this.front]\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\n\tthis.mutex.RLock()\n\tdefer this.mutex.RUnlock()\n\treturn this.data[this.front]\n\n}", "func (q *Queue) Pop() Any {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\titem := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn item\n}", "func (gdt *Array) PopFront() Variant {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_array_pop_front(GDNative.api, arg0)\n\n\treturn Variant{base: &ret}\n\n}", "func (this *MyCircularDeque) GetFront() int {\n if this.IsEmpty() {\n return -1\n }\n return this.data[this.head]\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.len == 0 {\n\t\treturn -1\n\t}\n\treturn this.queue[this.head]\n}", "func (d *Deque) PopBack() (interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\toldBack := d.back\n\td.back = oldBack.next\n\tif d.back == nil {\n\t\td.front = nil\n\t} else {\n\t\td.back.prev = nil\n\t}\n\tret := oldBack.data\n\t// clean up\n\toldBack.next = nil\n\toldBack.prev = nil\n\td.size--\n\treturn ret, true\n}", "func (this *MyCircularDeque1) GetFront() int {\n\treturn this.head.Next.Val\n}", "func (c *Clac) Pop() (value.Value, error) {\n\tx, err := c.remove(0, 1)\n\tif err != nil {\n\t\treturn zero, err\n\t}\n\treturn x[0], err\n}", "func (q *Deque) Back() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.back-1]\n\t}\n\treturn nil\n}", "func (q *Stack) Pop() interface{} {\n\treturn q.data.Remove(q.data.Front())\n}", "func (dq *Dqueue) Front() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\treturn\n}", "func (cq *cQT) PopBack() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tcq.e--\n\tel = cq.b[cq.e&cq.m]\n\tcq.b[cq.e&cq.m] = zero\n\treturn el, true\n}", "func (ll *LinkedList) PopBack() T {\n\tif ll.tail == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.tail.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\ttail := ll.tail.prev\n\t\ttail.next = nil\n\t\tll.tail.prev = nil\n\t\tll.tail = tail\n\t}\n\n\tll.size--\n\treturn val\n}", "func (q *Queue) Dequeue() Lit {\n\tif len(q.items) == 0 {\n\t\treturn Undef\n\t}\n\tfirst := q.items[0]\n\tq.items = q.items[1:len(q.items)]\n\n\treturn first\n}", "func (this *MyQueue) Pop() int {\n x := this.q[0]\n this.q = this.q[1:]\n return x\n}", "func (q *RingQueue) Dequeue() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\te := q.data[q.front]\n\tq.front = (q.front + 1) % q.size\n\treturn e\n}", "func (h *Queue) Pop() interface{} {\n\told := h.slice\n\tn := len(old)\n\titem := old[n-1]\n\th.slice = old[0 : n-1]\n\treturn item\n}", "func (s *MyStack) Pop() int {\n v := s.queue1[0]\n s.queue1 = s.queue1[1:]\n return v\n}", "func (md *MinQueue) Pop() interface{} {\n\told := *md\n\tn := len(old)\n\titem := old[n-1]\n\t*md = old[:n-1]\n\titem.index = n\n\treturn item\n}", "func (this *LinkedList) Pop() interface{} {\n\tif this.head == nil {\n\t\treturn nil\n\t}\n\treturn this.RemoveAt(0)\n}", "func (shelf *Shelf) Pop() interface{} {\n\tx := shelf.queue[shelf.Len()-1]\n\tshelf.queue = shelf.queue[:shelf.Len()-1]\n\treturn x\n}", "func (d *Deque) TopFront() (interface{}, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.head != nil:\n\t\treturn d.head.value, true\n\n\tcase d.child != nil:\n\t\treturn d.child.TopFront()\n\n\tdefault:\n\t\treturn d.tail.value, true\n\t}\n}", "func (ll *LinkedList) PopBack() interface{} {\n\tll.Lock()\n\tdefer ll.Unlock()\n\n\tif ll.size == 0 {\n\t\treturn nil\n\t}\n\n\tnode := ll.tail\n\tll.removeNode(ll.size - 1)\n\n\treturn node.data\n}", "func (pq *MinPQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (s *MyStack) Pop() int {\n\titem := s.queue[0]\n\ts.queue = s.queue[1:]\n\treturn item\n}", "func (q *baseCircularFifoQueue) Pop() interface{} {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\tnode := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn node\n}", "func (s *Stack) Pop() (val interface{}) {\n\tif s.isEmpty() {\n\t\treturn\n\t}\n\treturn s.list.RemoveHead()\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (t *topK) Pop() interface{} {\n\tn := len(t.values)\n\tx := t.values[n-1]\n\tt.values = t.values[:n-1]\n\treturn x\n}", "func (r *Ring) Dequeue() interface{} {\n\tr.checkInit()\n\tif r.head == -1 {\n\t\treturn nil\n\t}\n\tv := r.get(r.tail)\n\tif r.tail == r.head {\n\t\tr.head = -1\n\t\tr.tail = 0\n\t} else {\n\t\tr.tail = r.mod(r.tail + 1)\n\t}\n\treturn v\n}", "func (q *Queue) Pop() interface{} {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tel := q.elements.Front()\n\tif el == nil {\n\t\treturn nil\n\t}\n\treturn q.elements.Remove(el)\n}", "func (q *Queue) Pop() interface{} {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tel := q.elements.Front()\n\tif el == nil {\n\t\treturn nil\n\t}\n\treturn q.elements.Remove(el)\n}", "func (q *Queue) GetFront() interface{} {\r\n\tif len(q.QueueList) > 0 {\r\n\t\treturn q.QueueList[0]\r\n\t}\r\n\treturn nil\r\n}", "func (self *Queue)Pop()interface{}{\r\n\tdefer self.popkey.Release()\r\n\tself.popkey.Get()\t\r\n\te:=self.list.Front()\r\n\tif e!=nil {\r\n\t\tself.list.Remove(e)\r\n\t\treturn e.Value\r\n\t}else{\r\n\t\treturn e\r\n\t}\r\n}", "func(q *Queue)GetFront()int{\n\tif q.IsEmpty() {\n\t\tpanic(\"Get front error.queue is empty\")\n\t}\n\treturn q.arr[q.front]\n}", "func (s *Stack) Pop() interface{} {\n\tif s.head == nil {\n\t\treturn nil\n\t}\n\tf := s.head\n\ts.head = s.head.next\n\ts.size--\n\treturn f.Value\n}", "func (q *Queue /*[T]*/) Dequeue() T {\n\tvar v T\n\tif len(q.items) > 0 {\n\t\tv = q.items[0]\n\t\tq.items = q.items[1:]\n\t}\n\treturn v\n}", "func (q *Queue) Dequeue() interface{} {\n\tq.Lock()\n\tdefer q.Unlock()\n\n\tif q.head == nil {\n\t\treturn nil\n\t}\n\titem := q.head\n\tq.head = item.next\n\n\tif q.head == nil {\n\t\tq.tail = nil\n\t}\n\tq.size--\n\n\treturn item.value\n}", "func (s *Stack) Pop() (value interface{}) {\r\n\tif s.size > 0 {\r\n\t\tvalue, s.top = s.top.value, s.top.next\r\n\t\ts.size--\r\n\t\treturn value\r\n\t}\r\n\treturn nil\r\n}", "func (this *MyQueue) Pop() int {\n\tv := this.Stack[0]\n\tthis.Stack = this.Stack[1:]\n\treturn v\n}", "func (q *Queue) Pop() *Element {\n\tif q.Count <= 0 {\n\t\treturn nil\n\t}\n\te := q.Tail\n\tif q.Count == 1 {\n\t\tq.Head = nil\n\t\tq.Tail = nil\n\t} else {\n\t\tq.Tail = e.Prev\n\t\tq.Tail.Next = nil\n\t}\n\tq.Count -= 1\n\n\te.Prev = nil\n\te.Next = nil\n\treturn e\n}", "func (d *Deque[T]) Front() T {\n\treturn d.firstSegment().front()\n}", "func (q *SliceQueue) Front() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\treturn q.Data[0]\n}", "func (s *Stack) Pop() (value interface{}) {\n\n if s.size > 0 {\n\n value, s.top = s.top.value, s.top.next\n\n s.size--\n\n return\n\n }\n\n return nil\n\n}", "func (q *Queue) Dequeue() (interface{}, error) {\n\ttheQueue := *q\n\tif len(theQueue) <= 0 {\n\t\treturn nil, errors.New(\"Can't dequeue() from empty queue!\")\n\t}\n\tx := theQueue[0]\n\t*q = theQueue[1:]\n\treturn x, nil\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (s *List) PopHead() (interface{}, error) {\n\tif s.IsEmpty() {\n\t\treturn 0, ErrEmpty\n\t}\n\n\tv := s.Head.Data\n\tif s.isLastOne() {\n\t\ts.onEmpty()\n\t} else {\n\t\ts.Head = s.Head.Next\n\t\ts.Head.Prev = nil\n\t}\n\treturn v, nil\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (q *Queue) Dequeue() interface{} {\n\tif q.length == 0 {\n\t\treturn nil\n\t}\n\tn := q.start\n\tif q.length == 1 {\n\t\tq.start = nil\n\t\tq.end = nil\n\t} else {\n\t\tq.start = q.start.next\n\t}\n\tq.length--\n\treturn n.value\n}", "func (q *queue) Front() (interface{}, error) {\n\tif q.Empty() {\n\t\treturn nil, errors.New(\"error: can not get element from empty queue\")\n\t}\n\treturn q.items[q.head].Data, nil\n}", "func (q *queryPQ) Pop() any {\n\titem := (*q)[len(*q)-1]\n\t*q = (*q)[:len(*q)-1]\n\treturn item\n}", "func (q *Queue) Dequeue() interface{} {\n\tif q.length == 0 {\n\t\treturn nil\n\t}\n\n\tn := q.start\n\tif q.length != 1 {\n\t\tq.start = q.start.next\n\t} else {\n\t\tq.start = nil\n\t\tq.end = nil\n\t}\n\n\tq.length--\n\treturn n.value\n}", "func (d *Deque) PopBack() (*Deque, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.tail != nil:\n\t\treturn &Deque{d.head, d.child, nil}, true\n\n\tdefault:\n\t\tdd, _ := d.child.PopFront()\n\t\treturn &Deque{d.head, dd, nil}, true\n\t}\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (s *stack) Pop() (detachedHead interface{}) {\n\tif s.top == nil {\n\n\t\tpanic(StackTopIsNilException{\"Pop\"})\n\t}\n\tdetachedHead = s.top.value\n\tif s.top.prev == nil {\n\t\ts.top = nil\n\t} else {\n\t\ts.top = s.top.prev\n\t}\n\ts.length -= 1\n\ts.calcMin(detachedHead, true)\n\treturn\n}", "func (h *tsHeap) Pop() interface{} {\n\tit := (*h)[len(*h)-1]\n\t// Poison the removed element, for safety.\n\tit.index = -1\n\t*h = (*h)[0 : len(*h)-1]\n\treturn it\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.len <= 0 {\n\t\treturn -1\n\t}\n\n\tn := this.l.Front().Value.(int)\n\treturn n\n}", "func (this *Queue) Dequeue() interface{} {\r\n\tif this.length == 0 {\r\n\t\treturn nil\r\n\t}\r\n\tn := this.start\r\n\tif this.length == 1 {\r\n\t\tthis.start = nil\r\n\t\tthis.end = nil\r\n\t} else {\r\n\t\tthis.start = this.start.next\r\n\t}\r\n\tthis.length--\r\n\treturn n.value\r\n}", "func (s *queue) pop() func() {\n\tif len(*s) > 0 {\n\t\tf := (*s)[0]\n\t\t*s = (*s)[1:]\n\t\treturn f\n\t}\n\n\treturn nil\n}", "func (q *Queue) Dequeue() string {\n\tfront := q.Front()\n\tif front == \"\" {\n\t\treturn \"\"\n\t}\n\tq.Queue.Unshift()\n\treturn front\n}", "func (q *Queue) Dequeue() interface{} {\n\tif q.Empty() {\n\t\treturn nil\n\t}\n\tdefer func() {\n\t\tif q.tail == q.head {\n\t\t\tq.tail, q.head = -1, -1\n\t\t} else {\n\t\t\tq.head = (q.head + 1) % cap(q.data)\n\t\t}\n\t}()\n\tdata := q.data[q.head]\n\tq.data[q.head] = nil\n\treturn data\n}" ]
[ "0.8634477", "0.836322", "0.8075417", "0.8057622", "0.8049638", "0.7966853", "0.79403967", "0.7934168", "0.7909345", "0.7909239", "0.7837496", "0.77566165", "0.7741995", "0.77133715", "0.7710786", "0.7687477", "0.76298", "0.7611565", "0.75820625", "0.75512975", "0.7537698", "0.74844223", "0.74808127", "0.7467529", "0.7451132", "0.73809963", "0.73674244", "0.7362171", "0.73573893", "0.7352744", "0.7333585", "0.73257333", "0.7309682", "0.72918785", "0.7268702", "0.72529215", "0.7248659", "0.72394025", "0.7233679", "0.72297937", "0.72246397", "0.72181696", "0.7176535", "0.7165746", "0.71620256", "0.7150046", "0.7149443", "0.7125969", "0.71017766", "0.70890766", "0.7055701", "0.70555365", "0.70518535", "0.704919", "0.703961", "0.703626", "0.70174164", "0.70140934", "0.7014015", "0.7012785", "0.7003437", "0.7001565", "0.69926375", "0.69763064", "0.6975585", "0.6970992", "0.69705343", "0.69669557", "0.69651353", "0.69651353", "0.6952633", "0.69523406", "0.6950679", "0.69490474", "0.69483995", "0.69466645", "0.693599", "0.6932874", "0.6926436", "0.69233173", "0.69202244", "0.6919723", "0.69177574", "0.6914536", "0.6911632", "0.6907285", "0.6905922", "0.69023454", "0.6901037", "0.68950945", "0.6892958", "0.689244", "0.689244", "0.688984", "0.6888188", "0.68874294", "0.6885485", "0.68852186", "0.688473", "0.6870214" ]
0.8551561
1
PopBack returns the value at the lase position of the deque and removes it
func (d *Deque[T]) PopBack() T { if d.size == 0 { panic("deque is empty") } seg := d.preIndex(d.end) s := d.segs[seg] v := s.popBack() if s.size() == 0 { d.putToPool(s) d.segs[seg] = nil d.end = seg } d.size-- d.shrinkIfNeeded() return v }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Deque) PopBack() {\n\tif !q.Empty() {\n\t\tq.back--\n\t\tq.size--\n\t}\n}", "func (dq *Dqueue) PopBack() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\tdq.dqueue.Remove(dq.Size() - 1)\n\treturn\n}", "func (cq *cQT) PopBack() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tcq.e--\n\tel = cq.b[cq.e&cq.m]\n\tcq.b[cq.e&cq.m] = zero\n\treturn el, true\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn 0, ErrEmptyList\n\t}\n\n\tdata := l.last.Val\n\n\tif l.last.Prev() == nil {\n\t\tl.head = nil\n\t\tl.last = nil\n\t} else {\n\t\tl.last.Prev().next = nil\n\t\tl.last = l.last.Prev()\n\t}\n\n\treturn data, nil\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.Len == 0 {\n\t\treturn nil, ErrEmptyList\n\t}\n\tv := l.tail.Val\n\tl.tail = l.tail.prev\n\tl.Len--\n\tif l.Len == 0 {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\treturn v, nil\n}", "func (q *Deque) Back() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.back-1]\n\t}\n\treturn nil\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\tn := l.last\n\tif l.first == n {\n\t\tl.first = nil\n\t}\n\tl.last = n.prev\n\tif l.last != nil {\n\t\tl.last.next = nil\n\t}\n\treturn n.Val, nil\n}", "func (d *Deck) PopBack() (string, error) {\n\tif d.head == d.tail {\n\t\treturn \"\", fmt.Errorf(\"nothing to pop\")\n\t}\n\td.tail -= inv\n\tif d.tail < 0 {\n\t\td.tail = cap(d.deck) - 1\n\t}\n\tres := d.deck[d.tail]\n\td.deck[d.tail] = \"\"\n\treturn res, nil\n}", "func (d *Deque) PopBack() (interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\toldBack := d.back\n\td.back = oldBack.next\n\tif d.back == nil {\n\t\td.front = nil\n\t} else {\n\t\td.back.prev = nil\n\t}\n\tret := oldBack.data\n\t// clean up\n\toldBack.next = nil\n\toldBack.prev = nil\n\td.size--\n\treturn ret, true\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.tail == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\n\tval := l.tail.Val\n\tl.tail = l.tail.prev\n\n\tif l.tail == nil {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\n\treturn val, nil\n}", "func (ll *LinkedList) PopBack() interface{} {\n\tll.Lock()\n\tdefer ll.Unlock()\n\n\tif ll.size == 0 {\n\t\treturn nil\n\t}\n\n\tnode := ll.tail\n\tll.removeNode(ll.size - 1)\n\n\treturn node.data\n}", "func (ll *LinkedList) PopBack() T {\n\tif ll.tail == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.tail.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\ttail := ll.tail.prev\n\t\ttail.next = nil\n\t\tll.tail.prev = nil\n\t\tll.tail = tail\n\t}\n\n\tll.size--\n\treturn val\n}", "func (v *Vector) PopBack() (string, error) {\n\tif len(v.Vector) == 0 {\n\t\treturn \"\", fmt.Errorf(\"nothing to pop\")\n\t}\n\tres := v.Vector[len(v.Vector)-1]\n\t// v.Vector[len(v.Vector)-1] = \"\"\n\tv.Vector = v.Vector[:len(v.Vector)-1]\n\treturn res, nil\n}", "func (self *Dll) popBack() *node{\n\n\tret := self.tail.prev\n\ttemp := ret.prev\n\ttemp.setNext(self.tail)\n\tself.tail.setPrev(temp)\n\n\tret.setPrev(nil)\n\tret.setNext(nil)\n\n\tself.len -= 1\n\n\treturn ret\n}", "func (dq *Dqueue) Back() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\treturn\n}", "func (d *Deque) PopBack() (*Deque, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.tail != nil:\n\t\treturn &Deque{d.head, d.child, nil}, true\n\n\tdefault:\n\t\tdd, _ := d.child.PopFront()\n\t\treturn &Deque{d.head, dd, nil}, true\n\t}\n}", "func (d *Deque[T]) Back() T {\n\treturn d.lastSegment().back()\n}", "func (d *Deque) Pop() (interface{}, error) {\n\tif d.length == 0 {\n\t\treturn nil, fmt.Errorf(\"Can not pop from an empty deque.\")\n\t}\n\n\titem := d.head.next\n\td.head.next = d.head.next.next\n\n\tif d.head.next != nil {\n\t\td.head.next.prev = d.head\n\t}\n\n\td.length--\n\n\treturn item.value, nil\n}", "func (s *Queue) Pop() interface{} {\n\tif s.IsEmpty() {\n\t\tpanic(\"Pop on empty queue\")\n\t} else {\n\t\tcurrent_head := s.head\n\t\tval := current_head.val\n\t\ts.head = current_head.previous\n\t\tcurrent_head.val = nil\n\t\treturn val\n\t}\n}", "func (m *OrderedMap[K,V]) PopBack() (k K, v V, ok bool) {\n\te := m.list.Back()\n\tif e == nil {\n\t\treturn\n\t}\n\tk, v, ok = e.Value.Key, e.Value.Value, true\n\tdelete(m.mp, k)\n\tm.list.Remove(e)\n\treturn\n}", "func (l *List) PopBack() *Node{\n\tvar n *Node\n\n\tl.size--\n \tif l.tail == nil {\n \t\treturn nil\n \t}\n\n \tn = l.tail\n \tif l.tail == l.head {\n \t\tl.head = nil\n \t\tl.tail = nil\n \t\treturn n\n \t}\n\n \tcurrentNode := l.head\n \tfor currentNode.next != l.tail {\n \t\tcurrentNode = currentNode.next\n \t}\n \tcurrentNode.next = nil\n \tl.tail = currentNode\n \treturn n\n}", "func (gdt *Array) PopBack() Variant {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_array_pop_back(GDNative.api, arg0)\n\n\treturn Variant{base: &ret}\n\n}", "func (q *Deque) PopFront() {\n\tif !q.Empty() {\n\t\tq.front = (q.front + 1) % cap(q.values)\n\t\tq.size--\n\t}\n}", "func (h *Queue) Pop() interface{} {\n\told := h.slice\n\tn := len(old)\n\titem := old[n-1]\n\th.slice = old[0 : n-1]\n\treturn item\n}", "func (que *Queue) Pop() string {\n\tnode := que.values[0]\n\tque.values = que.values[1:]\n\treturn node\n}", "func(q *Queue)GetBack() int{\n\tif q.IsEmpty() {\n\t\tpanic(\"Get back error.queue is empty\")\n\t}\n\treturn q.arr[q.rear-1]\n}", "func (this *Stack) Pop() interface{} {\n\tif this.length == 0 {\n\t\treturn nil\n\t}\n\n\tn := this.top\n\tthis.top = n.prev\n\tthis.length--\n\treturn n.value\n}", "func (d *Deque) Back() (*interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\treturn &d.back.data, true\n}", "func (stack *Stack) Pop() interface{} {\n\te := stack.list.Back()\n\tif e != nil {\n\t\tstack.list.Remove(e)\n\t\treturn e.Value\n\t}\n\treturn nil\n}", "func (self *Queue)Pop()interface{}{\r\n\tdefer self.popkey.Release()\r\n\tself.popkey.Get()\t\r\n\te:=self.list.Front()\r\n\tif e!=nil {\r\n\t\tself.list.Remove(e)\r\n\t\treturn e.Value\r\n\t}else{\r\n\t\treturn e\r\n\t}\r\n}", "func (s *MyStack) Pop() int {\n v := s.queue1[0]\n s.queue1 = s.queue1[1:]\n return v\n}", "func (this *MyQueue) Pop() int {\n\tv := this.Stack[0]\n\tthis.Stack = this.Stack[1:]\n\treturn v\n}", "func (this *MyStack) Pop() int {\n\tfor this.current.Qsize() != 1 {\n\t\tthis.backup.push(this.current.pop())\n\t}\n\tres := this.current.pop()\n\tthis.current, this.backup = this.backup, this.current\n\n\treturn res\n}", "func (t *queueStorage) Pop() interface{} {\n\tn := len(*t)\n\tres := (*t)[n-1]\n\t*t = (*t)[:n-1]\n\treturn res\n}", "func (q *Queue) Pop() int {\n\t//这里的括号是定界符\n\t//这里是取出第0个元素进行返回\n\thead := (*q)[0]\n\t//将q的内存地址中的数据, 修改为将q的下标为1开始剪切到最后一个的数据\n\t// 后面使用*q 前面也要加一个*\n\t*q = (*q)[1:]\n\treturn head\n}", "func (s *Stack) Pop() (value interface{}) {\n\n if s.size > 0 {\n\n value, s.top = s.top.value, s.top.next\n\n s.size--\n\n return\n\n }\n\n return nil\n\n}", "func (s *Stack) Pop() interface{} {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tif s.length == 0 {\n\t\treturn nil\n\t}\n\tn := s.top\n\ts.top = n.prev\n\ts.length--\n\treturn n.value\n}", "func (q *Stack) Pop() string {\n\ts := *q\n\tlast := s[len(s)-1]\n\t*q = s[:len(s)-1]\n\treturn last\n}", "func (s *Stack) Pop() (value interface{}) {\r\n\tif s.size > 0 {\r\n\t\tvalue, s.top = s.top.value, s.top.next\r\n\t\ts.size--\r\n\t\treturn value\r\n\t}\r\n\treturn nil\r\n}", "func (q *Stack) Pop() interface{} {\n\treturn q.data.Remove(q.data.Front())\n}", "func (t *topK) Pop() interface{} {\n\tn := len(t.values)\n\tx := t.values[n-1]\n\tt.values = t.values[:n-1]\n\treturn x\n}", "func (q *PriorityQueue) Pop() {\n\tif q.size == 0 {\n\t\treturn\n\t}\n\tq.elements[0] = q.elements[q.size-1]\n\tq.elements[q.size-1] = nil\n\tq.size--\n\tq.siftdown()\n}", "func (q *Queue) Pop() *Element {\n\tif q.Count <= 0 {\n\t\treturn nil\n\t}\n\te := q.Tail\n\tif q.Count == 1 {\n\t\tq.Head = nil\n\t\tq.Tail = nil\n\t} else {\n\t\tq.Tail = e.Prev\n\t\tq.Tail.Next = nil\n\t}\n\tq.Count -= 1\n\n\te.Prev = nil\n\te.Next = nil\n\treturn e\n}", "func (this *MyQueue) Pop() int {\n x := this.q[0]\n this.q = this.q[1:]\n return x\n}", "func (s *Stack) Pop() (value interface{}) {\n\tif s.size > 0 {\n\t\ts.top, value = s.top.next, s.top.value\n\t\ts.elements = s.elements[:s.size-1]\n\t\ts.size--\n\t\treturn\n\t}\n\treturn nil\n}", "func (this *MyQueue) Pop() int {\n\tthis.Peek()\n\te := this.b[len(this.b)-1]\n\tthis.b = this.b[:len(this.b)-1]\n\treturn e\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (s *MyStack) Pop() int {\n\titem := s.queue[0]\n\ts.queue = s.queue[1:]\n\treturn item\n}", "func (d *Deque[T]) PopFront() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\ts := d.segs[d.begin]\n\tv := s.popFront()\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[d.begin] = nil\n\t\td.begin = d.nextIndex(d.begin)\n\t}\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (this *Stack) Pop() interface{} {\n\tsize := len(this.stack)\n\tres := this.stack[size-1]\n\tthis.stack = append([]interface{}{}, this.stack[0:size-1]...)\n\treturn res\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (s *Stack) Pop() interface{} {\n\tif s.Last == nil {\n\t\treturn nil\n\t}\n\n\ttop := s.Peek()\n\ts.Last = s.Last.Next\n\n\ts.Length--\n\n\treturn top\n}", "func (s *Stack) Pop() interface{} {\n\tv := s.v[len(s.v)]\n\ts.v = s.v[:len(s.v)-1]\n\treturn v\n}", "func (shelf *Shelf) Pop() interface{} {\n\tx := shelf.queue[shelf.Len()-1]\n\tshelf.queue = shelf.queue[:shelf.Len()-1]\n\treturn x\n}", "func (l *List) Pop() (v Value, err error) {\n\tif l.tail == nil {\n\t\terr = errEmpty\n\t} else {\n\t\tv = l.tail.Value\n\t\tl.tail = l.tail.prev\n\t\tif l.tail == nil {\n\t\t\tl.head = nil\n\t\t}\n\t}\n\treturn v, err\n}", "func (s *Stack[T]) Pop() T {\n\tv := s.array[len(s.array)-1]\n\ts.array = s.array[:len(s.array)-1]\n\treturn v\n}", "func (a *Array) Pop() interface{} {\n\tdefer func() {\n\t\ta.Data = a.Data[:a.Length-1]\n\t\ta.Length--\n\t}()\n\treturn a.Data[a.Length-1]\n}", "func (this *MyQueue) Pop() int {\n\tr := this.q[len(this.q)-1]\n\tthis.q = this.q[:len(this.q)-1]\n\treturn r\n}", "func (pq *askPQueue) Pop() *models.Ask {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\n\tif pq.size() < 1 {\n\t\treturn nil\n\t}\n\n\tmax := pq.items[1]\n\n\tpq.exch(1, pq.size())\n\tpq.items = pq.items[0:pq.size()]\n\tpq.elemsCount--\n\tpq.sink(1)\n\n\treturn max.value\n}", "func (this *MyQueue) Pop() int {\n\tif len(this.outStack) == 0 {\n\t\tthis.inToOut()\n\t}\n\tx := this.outStack[len(this.outStack)-1]\n\tthis.outStack = this.outStack[:len(this.outStack)-1]\n\treturn x\n}", "func (s *Stack) Pop() (value interface{}) {\n\tif s.size > 0 {\n\t\tvalue, s.top = s.top.value, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn nil\n}", "func (s *Stack) Pop() (value interface{}) {\n\tif s.size > 0 {\n\t\tvalue, s.top = s.top.value, s.top.next\n\t\ts.size--\n\t\treturn\n\t}\n\treturn nil\n}", "func (s *Stack) Pop() interface{} {\r\n\tn := len(s.stk)\r\n\tvalue := s.stk[n-1]\r\n\ts.stk = s.stk[:n-1]\r\n\treturn value\r\n}", "func (stack *Stack) Pop() (stuff interface{}, err error) {\n\ttheStack := *stack\n\n\tif len(theStack) == 0 {\n\t\treturn nil, errors.New(\"Tried to pop an empty stack.\")\n\t}\n\n\t//get last element\n\tlast := theStack[len(theStack)-1]\n\t//reduce stack by 1\n\t*stack = theStack[:len(theStack)-1]\n\n\treturn last, nil\n}", "func (self *Queue) Pop() {\n\tcurr := self.final.GetNext()\n\tif self.final.GetNext() == nil {\n\t\tself.final = nil\n\t} else {\n\t\tself.final.SetNext(curr.GetNext())\n\t}\n\tself.size--\n}", "func (q *Queue) Pop() Any {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\titem := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (this *MyStack) Pop() int {\n\tx := this.Queue[0]\n\tthis.Queue = this.Queue[1:]\n\treturn x\n}", "func (this *MyStack) Pop() int {\n\tres := this.v[len(this.v)-1]\n\tthis.v = this.v[:len(this.v)-1]\n\treturn res\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (stack *Stack) Pop() (value interface{}) {\n\tif stack.size > 0 {\n\t\tvalue, stack.top = stack.top.value, stack.top.next\n\t\tstack.size--\n\t\treturn\n\t}\n\treturn nil\n}", "func (s *Stack) Pop() (interface{}, error) {\n\tvar e *element = s.top\n\tif e == nil {\n\t\treturn 0, &StackError{msg: \"empty\"}\n\t}\n\ts.top = e.under\n\ts.count -= 1\n\treturn e.value, nil\n}", "func (q *Queue) popFront() interface{} {\n\te := q.front.link\n\tq.front.link = e.link\n\tif e == q.back {\n\t\tq.back = q.front\n\t}\n\tq.queueLen--\n\n\tif q.queueLen < q.softQuota {\n\t\t// Successfully removing items from the queue below half the soft quota\n\t\t// lowers the soft quota. This has the effect of increasing the credit cap\n\t\t// and the amount of credit given for removing items to better approximate\n\t\t// the rate at which the consumer is servicing the queue.\n\t\tif q.softQuota > 1 && q.queueLen < q.softQuota/2 {\n\t\t\tq.softQuota--\n\t\t}\n\n\t\t// Give credit for being below the soft quota. Note we do this after\n\t\t// adjusting the quota so the credit reflects the item we just removed.\n\t\tq.credit += float64(q.softQuota-q.queueLen) / float64(q.softQuota)\n\t\tif cap := float64(q.hardLimit - q.softQuota); q.credit > cap {\n\t\t\tq.credit = cap\n\t\t}\n\t}\n\n\treturn e.item\n}", "func (s *Stack) Pop() int {\n\tl := len(s-item) - 1\n\ttoRemove := s.items[l]\n\ts.items = s.items[:l]\n\treturn toRemove\n}", "func (s *MyStack) Pop() int {\n\tif s.Empty() {\n\t\treturn -1\n\t}\n\tn := len(s.Q)\n\tx := s.Q[n-1]\n\ts.Q = s.Q[:n-1]\n\treturn x\n}", "func (sa *StackArray) Pop() interface{} {\n\tif sa.isEmpty() {\n\t\tfmt.Println(\"The stack is empty\")\n\t\treturn nil\n\t}\n\n\titem := sa.ArrayStack[sa.Top]\n\tsa.Top--\n\n\treturn item\n}", "func (h *Heap) Pop() interface{} {\n\tif h.size == 0 {\n\t\treturn nil\n\t}\n\tres := h.values[1]\n\th.values[1] = h.values[h.size]\n\th.values = h.values[:h.size]\n\th.size--\n\n\th.bubbleDown()\n\n\treturn res\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (q *Queue) Pop() interface{} {\n\tq.m.Lock()\n\tdefer q.m.Unlock()\n\n\tif q.closed {\n\t\treturn nil\n\t}\n\n\tif q.i >= q.j {\n\t\treturn nil\n\t}\n\n\tdefer func() {\n\t\tq.i++\n\t}()\n\n\treturn q.a[q.i]\n}", "func (q *Queue) Pop() interface{} {\n\tif len(q.queue) < 1 {\n\t\treturn nil\n\t}\n\n\tfirst := q.queue[0]\n\tq.queue = q.queue[1:]\n\n\treturn first\n}", "func (s *items) pop() (out Item) {\n\tindex := len(*s) - 1\n\tout = (*s)[index]\n\t(*s)[index] = nil\n\t*s = (*s)[:index]\n\treturn\n}", "func (s *Stack) Pop() interface{} {\n\tif len(s.data) > 0 {\n\t\tret := s.data[len(s.data)-1]\n\t\ts.data = s.data[:len(s.data)-1]\n\t\treturn ret\n\t}\n\n\treturn nil\n}", "func (q *queryPQ) Pop() any {\n\titem := (*q)[len(*q)-1]\n\t*q = (*q)[:len(*q)-1]\n\treturn item\n}", "func (s *Stack) Pop() interface{} {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tvar n *stackItem\n\tif s.top != nil {\n\t\tn = s.top\n\t\ts.top = n.next\n\t\ts.count--\n\t}\n\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\treturn n.data\n\n}", "func (s *Stack) Pop() (int, error) {\n\tif s.Empty() {\n\t\treturn -1, ErrstackEmpty\n\t} else {\n\t\ttop := s.container[s.Length-1]\n\t\ts.container = s.container[:s.Length-1]\n\t\ts.Length--\n\t\treturn top, nil\n\t}\n}", "func (sfm *StackFastMax) Pop() (int, error) {\n\tif sfm.Empty() {\n\t\treturn -1, ErrstackEmpty\n\t}\n\n\t//update container\n\tsfm.length--\n\ttop := sfm.containter[sfm.length]\n\tsfm.containter = sfm.containter[:sfm.length]\n\n\t//update maxer\n\tnowMax := sfm.maxer[len(sfm.maxer)-1]\n\tif nowMax.count > 1 {\n\t\t//the max value remain unchanged, only need to update count\n\t\tnowMax.count--\n\t\tsfm.maxer[len(sfm.maxer)-1] = nowMax\n\t} else {\n\t\t//top is the last max value of nowMax.max in stack\n\t\tsfm.maxer = sfm.maxer[:len(sfm.maxer)-1]\n\t}\n\n\treturn top, nil\n}", "func (pq *MinPQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (s *Stack) Pop() (val interface{}) {\n\tif s.isEmpty() {\n\t\treturn\n\t}\n\treturn s.list.RemoveHead()\n}", "func (this *MyQueue) Pop() int {\n\tif len(this.outStack) == 0 {\n\t\tthis.in2Out()\n\t}\n\n\tx := this.outStack[len(this.outStack)-1]\n\tthis.outStack = this.outStack[:len(this.outStack)-1]\n\treturn x\n}", "func (pq *bidPQueue) Pop() *models.Bid {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\n\tif pq.size() < 1 {\n\t\treturn nil\n\t}\n\n\tmax := pq.items[1]\n\n\tpq.exch(1, pq.size())\n\tpq.items = pq.items[0:pq.size()]\n\tpq.elemsCount--\n\tpq.sink(1)\n\n\treturn max.value\n}", "func (q *Stack) Pop() interface{} {\n\treturn q.Items.Pop().Value\n}", "func (this *MyStack) Pop() int {\n\tans := this.Ele[this.Len-1]\n\tthis.Ele = this.Ele[:this.Len-1]\n\tthis.Len--\n\treturn ans\n}", "func (pq *MaxPQ) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (s *Stack) Pop() int {\n\tlength := len(s.items) - 1\n\ttoRemove := s.items[length]\n\ts.items = s.items[:length]\n\treturn toRemove\n}", "func (Q *Deque) RemoveLast() (interface{}, error) {\n\tif Q.size == 0 {\n\t\treturn nil, errors.New(\"Queue is empty\")\n\t}\n\treturnVal := Q.back.val\n\tcurrentNode := Q.front\n\tfor currentNode.next.next != nil {\n\t\tcurrentNode = currentNode.next\n\t}\n\tQ.back = currentNode\n\tQ.back.next = nil\n\treturn returnVal, nil\n}", "func (s *Stack) Pop() interface{} {\n\tif s.head == nil {\n\t\treturn nil\n\t}\n\tf := s.head\n\ts.head = s.head.next\n\ts.size--\n\treturn f.Value\n}", "func (s *BlockingStack) Pop() interface{} {\n\ts.popLock.Lock()\n\tdefer s.popLock.Unlock()\n\tif s.Len() <= 0 {\n\t\ts.popBlockState = true\n\t\t<-s.popBlock\n\t\ts.popBlockState = false\n\t}\n\tret := s.top.value\n\ts.top = s.top.prev\n\ts.size--\n\tif s.pushBlockState {\n\t\ts.pushBlock <- 1\n\t}\n\treturn ret\n}", "func (s *Queue) Pop() *Data {\n\tif len(s.buf) == 0 {\n\t\treturn nil\n\t}\n\td := s.buf[0]\n\ts.buf = s.buf[1:]\n\n\treturn d\n}", "func (d *Deque) TopBack() (interface{}, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.tail != nil:\n\t\treturn d.tail.value, true\n\n\tcase d.child != nil:\n\t\treturn d.child.TopFront()\n\n\tdefault:\n\t\treturn d.head.value, true\n\t}\n}" ]
[ "0.8709507", "0.85595685", "0.83638006", "0.82592064", "0.825408", "0.82212234", "0.8208058", "0.81936616", "0.8173535", "0.8173105", "0.8167742", "0.8161551", "0.81029683", "0.81028724", "0.79952294", "0.789223", "0.776088", "0.7751448", "0.76618046", "0.7635353", "0.7632908", "0.7615383", "0.75933576", "0.758299", "0.7568058", "0.7556448", "0.7526412", "0.75249845", "0.7500102", "0.74881744", "0.74806696", "0.7477384", "0.74726987", "0.7461613", "0.74598175", "0.7448625", "0.74414927", "0.7427853", "0.7418836", "0.7416618", "0.7415969", "0.7404086", "0.7398474", "0.7395028", "0.7381814", "0.73769236", "0.73762655", "0.73746055", "0.7372859", "0.73717284", "0.7365948", "0.73643404", "0.73629147", "0.7361032", "0.7348785", "0.73468405", "0.73372674", "0.73318326", "0.7327009", "0.7326565", "0.7324913", "0.7324913", "0.7324731", "0.7324512", "0.73142767", "0.7310817", "0.72996175", "0.7297222", "0.72904634", "0.728702", "0.728702", "0.7286256", "0.7278611", "0.72758913", "0.7273496", "0.7271819", "0.72648555", "0.72618824", "0.72510314", "0.72496766", "0.724354", "0.7239304", "0.7239247", "0.72348195", "0.7224261", "0.7219134", "0.72184396", "0.7216278", "0.7213181", "0.72129434", "0.72090447", "0.720882", "0.72050464", "0.7193758", "0.7191748", "0.7190952", "0.71902615", "0.71894735", "0.7187435", "0.71862674" ]
0.8781297
0
EraseAt erases the element at the position pos
func (d *Deque[T]) EraseAt(pos int) { if pos < 0 || pos >= d.size { return } seg, pos := d.pos(pos) d.segmentAt(seg).eraseAt(pos) if seg < d.size-seg-1 { for i := seg; i > 0; i-- { cur := d.segmentAt(i) pre := d.segmentAt(i - 1) cur.pushFront(pre.popBack()) } if d.firstSegment().empty() { d.putToPool(d.firstSegment()) d.segs[d.begin] = nil d.begin = d.nextIndex(d.begin) d.shrinkIfNeeded() } } else { for i := seg; i < d.segUsed()-1; i++ { cur := d.segmentAt(i) next := d.segmentAt(i + 1) cur.pushBack(next.popFront()) } if d.lastSegment().empty() { d.putToPool(d.lastSegment()) d.segs[d.preIndex(d.end)] = nil d.end = d.preIndex(d.end) d.shrinkIfNeeded() } } d.size-- }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Rope) EraseAt(point, n int) (err error) {\n\tif point > r.runes {\n\t\tpoint = r.runes\n\t}\n\tif n >= r.runes-point {\n\t\tn = r.runes - point\n\t}\n\tvar k *knot\n\ts := skiplist{r: r}\n\tif k, err = s.find2(point); err != nil {\n\t\treturn err\n\t}\n\ts.del(k, n)\n\treturn nil\n}", "func (e *ObservableEditableBuffer) DeleteAt(rp0, rp1 int) {\n\tp0 := e.f.RuneTuple(rp0)\n\tp1 := e.f.RuneTuple(rp1)\n\n\te.Delete(p0, p1)\n}", "func (m *Maps) RemoveAt(c types.Coordinate) {\n\tm.active[c.Y][c.X] = Empty{}\n}", "func (b *Bag) DeleteAt(index int) {\n\tb.items[index] = b.items[len(b.items)-1]\n\tb.items = b.items[:len(b.items)-1]\n}", "func (b *Buffer) ClearAt(o int) {\n\tif o < len(b.Tiles) {\n\t\tb.Tiles[o] = nil\n\t}\n}", "func (b *Bookmarks) RemoveAt(idx int) {\n\tif idx < 0 || idx >= len(b.Bookmark) {\n\t\treturn\n\t}\n\tb.Bookmark = append(b.Bookmark[:idx], b.Bookmark[idx+1:]...)\n}", "func (a *DynamicArray) EraseAt(index int) error {\n\tif index < 0 || index >= a.len {\n\t\treturn ErrArrIndexOutOfBound\n\t}\n\n\tcopy(a.data[index:], a.data[index+1:])\n\ta.len--\n\n\t// if the length of the array is 1/4 of current capacity, resize the array to half of the space\n\tif a.len < a.cap/4 {\n\t\ta.resize(a.cap / 2)\n\t}\n\treturn nil\n}", "func (e *T) erase() {\n\tif e.widx <= 0 {\n\t\treturn\n\t}\n\te.widx--\n\te.buf[e.widx] = 0\n}", "func (s *items) removeAt(index int) Item {\n\titem := (*s)[index]\n\tcopy((*s)[index:], (*s)[index+1:])\n\t(*s)[len(*s)-1] = nil\n\t*s = (*s)[:len(*s)-1]\n\treturn item\n}", "func (p *IntArray) Delete_at(del_index int) {\n\ttmp := *p\n\tvar new_array IntArray\n\tfor i := 0; i < len(tmp); i++ {\n\t\tif i != del_index {\n\t\t\tnew_array = append(new_array, tmp[i])\n\t\t}\n\t}\n\t*p = new_array\n}", "func (s *children) removeAt(index int) *node {\n\tn := (*s)[index]\n\tcopy((**s)[index:], (*s)[index+1:])\n\t(*s)[len(*s)-1] = nil\n\t*s = (*s)[:len(*s)-1]\n\treturn n\n}", "func (a Slice[T]) DeleteAt(index int) Slice[T] {\n\treturn append(a[:index], a[index+1:]...)\n}", "func (list *ArrayList[T]) RemoveAt(index int) (T, bool) {\n\tif index < 0 || index >= list.Size() {\n\t\tvar zero T\n\t\treturn zero, false\n\t}\n\tele := list.elems[index]\n\tlist.elems = append(list.elems[:index], list.elems[index+1:]...)\n\treturn ele, true\n}", "func (list *MyArrayList) removeAtIndex(idx int) (int, error) {\n\tif idx >= list.currSize {\n\t\treturn 0, errors.New(\"index out of bounds\")\n\t}\n\toldVal := list.array[idx]\n\tfor i := idx; i< (list.currSize -1); i++ {\n\t\tlist.array[i] = list.array[i+1]\n\t}\n\tlist.currSize--\n\treturn oldVal, nil\n}", "func (p *SliceOfMap) DropAt(i int) ISlice {\n\treturn p.Drop(i, i)\n}", "func (elems *ElementsNR) delete(pt dvid.Point3d) (deleted *ElementNR, changed bool) {\n\t// Delete any elements at point.\n\tvar cut = -1\n\tfor i, elem := range *elems {\n\t\tif pt.Equals(elem.Pos) {\n\t\t\tcut = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif cut >= 0 {\n\t\tdeleted = (*elems)[cut].Copy()\n\t\tchanged = true\n\t\t(*elems)[cut] = (*elems)[len(*elems)-1] // Delete without preserving order.\n\t\t*elems = (*elems)[:len(*elems)-1]\n\t}\n\treturn\n}", "func (b *Buffer) Remove(offset int, size int) {\n if (offset + size) > len(b.data) {\n panic(\"invalid offset & size\")\n }\n\n copy(b.data[offset:], b.data[offset+size:])\n b.size -= size\n if b.offset >= (offset + size) {\n b.offset -= size\n } else if b.offset >= offset {\n b.offset -= b.offset - offset\n if b.offset > b.size {\n b.offset = b.size\n }\n }\n}", "func (lst *List) RemoveAt(idx int) (ret Val_t){\n\tif lst.Len < 1{\n\t\tpanic(\"no item to pop\")\n\t}\n\tcur := lst.GetAt(idx)\n\tret = cur.Val\n\tif(idx == 0){\n\t\treturn lst.PopFront()\n\t}else if idx == lst.Len-1{\n\t\treturn lst.PopBack()\n\t}else{\n\t\tpre,next := lst.GetAt(idx-1),lst.GetAt(idx+1)\n\t\tpre.Next = next\n\t\tlst.Len--\n\t}\n\treturn\n}", "func (c *Board) DeleteEntityAt(row int, col int) error {\n\tc.Space[row][col] = nil\n\treturn nil\n}", "func (b *BTree) removeInNodeAtIdx(n *memNode, idx int) *Item {\n\ts := n.node.Items\n\titem := s[idx]\n\tcopy(s[idx:], s[idx+1:])\n\ts[len(s)-1] = nil\n\ts = s[:len(s)-1]\n\treturn item\n}", "func (s *ItemScroller) RemoveAt(pos int) IPanel {\n\n\t// Validates position\n\tif pos < 0 || pos >= len(s.items) {\n\t\tpanic(\"ItemScroller.RemoveAt(): Invalid position\")\n\t}\n\n\t// Remove event listener\n\titem := s.items[pos]\n\n\t// Remove item from the items array\n\tcopy(s.items[pos:], s.items[pos+1:])\n\ts.items[len(s.items)-1] = nil\n\ts.items = s.items[:len(s.items)-1]\n\n\t// Remove item from the scroller children\n\ts.Panel.Remove(item)\n\ts.autoSize()\n\ts.recalc()\n\treturn item\n}", "func (r *runestring) Del(pos ...int) {\n\tfor _, i := range pos {\n\t\tif i >= 0 && i <= len(*r) {\n\t\t\t*r = append((*r)[:i], (*r)[i+1:]...)\n\t\t}\n\t}\n}", "func (this *LinkedList) RemoveAt(index int) interface{} {\n\tif index < 0 || index >= this.Size() {\n\t\tpanic(\"index out of bound\")\n\t}\n\tpe := this.head\n\tvar ps *entry\n\tvar ele interface{}\n\tps = nil\n\tfor i := 0; i < index; i++ {\n\t\tps = pe\n\t\tpe = pe.next\n\t}\n\tif ps != nil {\n\t\tele = pe.elem\n\t\tps.next = pe.next\n\t\tif pe == this.tail {\n\t\t\t// remove the last element\n\t\t\tthis.tail = ps\n\t\t}\n\t} else {\n\t\t// remove the first element\n\t\tele = pe.elem\n\t\tthis.head = this.head.next\n\t\t// if remove the only one element, tail must be change to nil\n\t\tif this.tail == pe {\n\t\t\tthis.tail = nil\n\t\t}\n\t}\n\tthis.size--\n\treturn ele\n}", "func (elems *Elements) delete(pt dvid.Point3d) (deleted *Element, changed bool) {\n\t// Delete any elements at point.\n\tvar cut = -1\n\tfor i, elem := range *elems {\n\t\tif pt.Equals(elem.Pos) {\n\t\t\tcut = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif cut >= 0 {\n\t\tdeleted = (*elems)[cut].Copy()\n\t\tchanged = true\n\t\t(*elems)[cut] = (*elems)[len(*elems)-1] // Delete without preserving order.\n\t\t*elems = (*elems)[:len(*elems)-1]\n\t}\n\n\t// Delete any relationships with the point.\n\tif elems.deleteRel(pt) {\n\t\tchanged = true\n\t}\n\treturn\n}", "func (l *LinkedList) DeleteAt(pos int) error {\n\t// validate the position\n\tif pos < 0 {\n\t\tfmt.Println(\"position can not be negative\")\n\t\treturn errors.New(\"position can not be negative\")\n\t} else if l.len == 0 {\n\t\tfmt.Println(\"No nodes in list\")\n\t\treturn errors.New(\"No nodes in list\")\n\t} else if pos > (l.len - 1) {\n\t\tfmt.Println(\"Position: \", pos, \" can not be greater than list size, hence returning\")\n\t\treturn errors.New(\"Position can not be greater than list size, hence returning\")\n\t}\n\t// if position is first call DeleteAtFirst()\n\tif pos == 0 {\n\t\treturn l.DeleteAtFirst()\n\t}\n\n\t// if position is last call DeleteAtEnd()\n\tif pos == (l.len - 1) {\n\t\treturn l.DeleteAtEnd()\n\t}\n\t// get node from given position\n\tnode := l.GetAt(pos)\n\tnode.next.prev = node.prev\n\tnode.prev.next = node.next\n\tl.len--\n\treturn nil\n}", "func (uimu *UserIDMappingUpdate) ClearDeletedAt() *UserIDMappingUpdate {\n\tuimu.mutation.ClearDeletedAt()\n\treturn uimu\n}", "func (uimuo *UserIDMappingUpdateOne) ClearDeletedAt() *UserIDMappingUpdateOne {\n\tuimuo.mutation.ClearDeletedAt()\n\treturn uimuo\n}", "func removeByteIndex(bs []byte, idx int) {\n\tcopy(bs[idx:], bs[idx+1:])\n\tbs[len(bs)-1] = 0\n}", "func (o *KeyValueOrdered) RemoveIndex(idx int) (cell KeyValueCapsule) {\n\tcell = o.s[idx]\n\tdelete(o.m, o.s[idx].K)\n\to.shift(idx+1, len(o.s), -1)\n\to.s = append(o.s[:idx], o.s[idx+1:]...)\n\treturn\n}", "func (cll *CircularLinkedList) DeleteFromPosition(pos int) int {\n\tif !(cll.CheckIfEmpty()) {\n\t\thead := cll.Start\n\t\tdeletedEle := head.Data\n\t\tif cll.Len == 1 {\n\t\t\t// delete from beginning\n\t\t\tdeletedEle = cll.DeleteBeginning()\n\t\t\treturn deletedEle\n\t\t}\n\t\tif cll.Len == pos {\n\t\t\t// delete from end\n\t\t\tdeletedEle = cll.DeleteEnd()\n\t\t\treturn deletedEle\n\t\t}\n\t\t// delete from middle\n\t\t//traverse till you find position\n\t\tcount := 1\n\t\tfor {\n\t\t\tif count == pos-1 {\n\t\t\t\tdeletedEle = head.Next.Data\n\t\t\t\tbreak\n\t\t\t}\n\t\t\thead = head.Next\n\t\t}\n\t\thead.Next = head.Next.Next\n\t\tcll.Len--\n\t\treturn deletedEle\n\t}\n\treturn -1\n}", "func (h *binaryHeap) removeIdx(idx int) {\n\tif h.invalidNode(idx) {\n\t\treturn\n\t}\n\th.swapIdx(idx, h.len)\n\th.tree[h.len] = 0\n\th.len--\n\th.bubbleDown(idx)\n}", "func (s *sliding) deleteFrom(newStart LogPosition) {\n\tstart := s.start\n\tfor i, u := range s.log[:s.mutable-start][:newStart-start] {\n\t\tpos := start + LogPosition(i)\n\t\tblkno := u.Addr\n\t\toldPos, ok := s.addrPos[blkno]\n\t\tif ok && oldPos <= pos {\n\t\t\tutil.DPrintf(5, \"memLogMap: del %d %d\\n\", blkno, oldPos)\n\t\t\tdelete(s.addrPos, blkno)\n\t\t}\n\t}\n\ts.log = s.log[newStart-start:]\n\ts.start = newStart\n}", "func (bitmap *bitmap) Unset(index int) {\n\tbitmap.set(index, 0)\n}", "func (d *Deque[T]) EraseRange(firstPos, lastPos int) {\n\tif firstPos < 0 || firstPos >= lastPos || lastPos > d.size {\n\t\treturn\n\t}\n\tnum := lastPos - firstPos\n\tif d.size-firstPos < lastPos {\n\t\t// move back\n\t\tfor pos := firstPos; pos+num < d.size; pos++ {\n\t\t\td.Set(pos, d.At(pos+num))\n\t\t}\n\t\tfor ; num > 0; num-- {\n\t\t\td.PopBack()\n\t\t}\n\t} else {\n\t\t// move front\n\t\tfor pos := lastPos - 1; pos-num >= 0; pos-- {\n\t\t\td.Set(pos, d.At(pos-num))\n\t\t}\n\t\tfor ; num > 0; num-- {\n\t\t\td.PopFront()\n\t\t}\n\t}\n}", "func (node *Node) RemovePropertyAt(i int) {\n\tnode.Properties = append(node.Properties[:i], node.Properties[i+1:]...)\n}", "func (sr *shardResult) RemoveBlockAt(id ident.ID, t time.Time) {\n\tcurSeries, exists := sr.blocks[id.Hash()]\n\tif !exists {\n\t\treturn\n\t}\n\tcurSeries.Blocks.RemoveBlockAt(t)\n\tif curSeries.Blocks.Len() == 0 {\n\t\tsr.RemoveSeries(id)\n\t}\n}", "func (oiuo *OrderInfoUpdateOne) ClearDeletedAt() *OrderInfoUpdateOne {\n\toiuo.mutation.ClearDeletedAt()\n\treturn oiuo\n}", "func (du *DatumUpdate) ClearDeletedAt() *DatumUpdate {\n\tdu.mutation.ClearDeletedAt()\n\treturn du\n}", "func (node *Node) EraseTo(length uint32) (into *Node) {\n\tif length == 0 {\n\t\treturn node\n\t}\n\n\tvar (\n\t\tkey uint32 = length\n\t\tidx uint32\n\t)\n\n\tinto = node.Copy()\n\tnode = into\n\n\tfor node.Shift > 0 {\n\t\tidx = (key >> node.Shift) & MASK\n\n\t\tfor i := idx; i > 0; i-- {\n\t\t\tnode.Elements[i-1] = Null\n\t\t}\n\t\tnode = node.CopySubKey(idx)\n\t}\n\n\tfor i := (key & MASK); i > 0; i-- {\n\t\tnode.Elements[i-1] = Null\n\t}\n\n\treturn\n}", "func (oiu *OrderInfoUpdate) ClearDeletedAt() *OrderInfoUpdate {\n\toiu.mutation.ClearDeletedAt()\n\treturn oiu\n}", "func (cuo *CustomerUpdateOne) ClearRemovedAt() *CustomerUpdateOne {\n\tcuo.mutation.ClearRemovedAt()\n\treturn cuo\n}", "func (li *List) RemoveAt(pos int) IPanel {\n\n\t// Remove the list item from the internal scroller\n\tpan := li.ItemScroller.RemoveAt(pos)\n\tlitem := pan.(*ListItem)\n\n\t// Remove item from the list item children and disposes of the list item panel\n\titem := litem.item\n\tlitem.Remove(item)\n\tlitem.Dispose()\n\treturn item\n}", "func deleteAtFromSubAtMap(sl *Silo, pp *base.ParsedPath, tSaMap map[string]*base.SimpleAttribute, key string, ca *base.ComplexAttribute, prIdx *Index, res *base.Resource, rid string, tx *bolt.Tx, mh *modifyHints) {\n\tnumSubObj := len(ca.SubAts)\n\trt := res.GetType()\n\tif sa, ok := tSaMap[pp.AtType.NormName]; ok {\n\t\tdelete(tSaMap, sa.Name)\n\t\tsl.dropSAtFromIndex(sa, ca.Name+\".\"+sa.Name, prIdx, rt.Name, rid, tx)\n\t\tif len(tSaMap) == 0 {\n\t\t\tif numSubObj == 1 {\n\t\t\t\tres.DeleteAttr(pp.FQAName())\n\t\t\t} else {\n\t\t\t\tdelete(ca.SubAts, key)\n\t\t\t}\n\t\t}\n\n\t\tmh.markDirty()\n\t}\n}", "func (gameTree *GameTree) RemoveNodeAt(i int) {\n\tgameTree.Nodes = append(gameTree.Nodes[:i], gameTree.Nodes[i+1])\n}", "func (ll *Doubly[T]) DelByPos(pos int) (T, bool) {\n\n\tswitch {\n\tcase ll.Head == nil:\n\t\tvar r T\n\t\treturn r, false\n\tcase pos-1 == 0:\n\t\treturn ll.DelAtBeg()\n\tcase pos-1 == ll.Count():\n\t\treturn ll.DelAtEnd()\n\tcase pos-1 > ll.Count():\n\t\tvar r T\n\t\treturn r, false\n\t}\n\tvar prev *Node[T]\n\tvar val T\n\tcur := ll.Head\n\tcount := 0\n\n\tfor count < pos-1 {\n\t\tprev = cur\n\t\tcur = cur.Next\n\t\tcount++\n\t}\n\n\tcur.Next.Prev = prev\n\tval = cur.Val\n\tprev.Next = cur.Next\n\treturn val, true\n}", "func (cu *CustomerUpdate) ClearRemovedAt() *CustomerUpdate {\n\tcu.mutation.ClearRemovedAt()\n\treturn cu\n}", "func (o *DeleteNodeParams) SetAt(at *int64) {\n\to.At = at\n}", "func (c Cluster) RemovePoint(index int) {\n\tpos := sort.SearchInts(c.indices, index)\n\tif pos < len(c.indices) {\n\t\tif len(c.indices) == 1 {\n\t\t\tc.indices = nil\n\t\t} else {\n\t\t\tc.indices[pos] = c.indices[len(c.indices)-1]\n\t\t\tc.indices = c.indices[:len(c.indices)-1]\n\t\t}\n\t}\n}", "func (duo *DatumUpdateOne) ClearDeletedAt() *DatumUpdateOne {\n\tduo.mutation.ClearDeletedAt()\n\treturn duo\n}", "func Erase(seq Sequence, offset, length int) Sequence {\n\tf := Or(Key(\"source\"), Not(Within(offset, offset+length)))\n\tff := seq.Features().Filter(f)\n\tseq = WithFeatures(seq, ff)\n\treturn Delete(seq, offset, length)\n}", "func (this *MyLinkedList) DeleteAtIndex(index int) {\n\tif this.size == 0 {\n\t\treturn\n\t} else if index < 0 || index > this.size-1 {\n\t\treturn\n\t} else {\n\t\tif this.size == 1 {\n\t\t\tthis.head = nil\n\t\t\tthis.tail = nil\n\t\t\tthis.listMap = []*ListNode{}\n\t\t} else {\n\t\t\tthis.listMap[index-1].Next = this.listMap[index].Next\n\t\t\tthis.listMap = append(this.listMap[:index], this.listMap[index+1:]...)\n\t\t}\n\t\tthis.size--\n\t}\n}", "func Remove(v magica.VoxelObject, src magica.VoxelObject, index uint8) (r magica.VoxelObject) {\n\tr = v.Copy()\n\n\titerator := func(x, y, z int) {\n\t\tif x < src.Size.X && y < src.Size.Y && z < src.Size.Z && src.Voxels[x][y][z] != index {\n\t\t\tr.Voxels[x][y][z] = 0\n\t\t}\n\t}\n\n\tr.Iterate(iterator)\n\n\treturn r\n}", "func SliceDeleteAtIndex(sl *[]Ki, idx int) error {\n\tif err := SliceIsValidIndex(sl, idx); err != nil {\n\t\treturn err\n\t}\n\t// this copy makes sure there are no memory leaks\n\tsz := len(*sl)\n\tcopy((*sl)[idx:], (*sl)[idx+1:])\n\t(*sl)[sz-1] = nil\n\t(*sl) = (*sl)[:sz-1]\n\treturn nil\n}", "func delete(array []int8, pos int) []int8 {\r\n\tvar length = len(array)\r\n\tvar tempArray = make([]int8, length+1)\r\n\tfmt.Printf(\"\\n\")\r\n\tfor i := 0; i < length; i++ {\r\n\t\tif i < pos {\r\n\t\t\ttempArray[i] = array[i]\r\n\t\t} else {\r\n\t\t\ttempArray[i-1] = array[i]\r\n\t\t}\r\n\t}\r\n\treturn tempArray\r\n\r\n}", "func (m *SalaryMutation) ClearPosition() {\n\tm.clearedposition = true\n}", "func (v *Data) Remove(idx int) (val PicData) {\n\tvar nil PicData\n\n\tdv := *v\n\n\tval = dv[idx]\n\t*v = append(dv[:idx], dv[1+idx:]...)\n\n\tdv[len(dv)-1] = nil\n\n\treturn val\n}", "func (a *DynamicArray) Remove(val int) {\n\tfor index := 0; index < a.len; {\n\t\tgot, _ := a.IndexAt(index)\n\t\t// If the element is found, erase the element at the index\n\t\tif got == val {\n\t\t\ta.EraseAt(index)\n\t\t\tcontinue\n\t\t}\n\t\t// If the element does not found in current index, shift to the right\n\t\tindex++\n\t}\n}", "func (t *Indexed) Remove(x int) {\n\tl, r := t.split(t.root, x-1)\n\t_, xr := t.split(r, x)\n\tt.root = t.merge(l, xr)\n}", "func (v *Bitmap256) Clear(pos uint8) {\n\tv[pos>>6] &= ^(1 << (pos & 63))\n}", "func (this *MyLinkedList) DeleteAtIndex(index int) {\n\tif this.head == nil || index < 0 {\n\t\treturn\n\t}\n\ttable := make(map[int]*ListNode)\n\ttail, i := this.head, 0\n\tfor tail != nil && i <= index {\n\t\ttable[i] = tail\n\t\ttail = tail.next\n\t\ti++\n\t}\n\tremoveElement := table[index]\n\tif removeElement == nil {\n\t\treturn\n\t}\n\tprev := table[index-1]\n\tvar next *ListNode\n\tif removeElement != nil {\n\t\tnext = removeElement.next\n\t}\n\tif prev == nil && next == nil {\n\t\tthis.head = nil\n\t\tthis.tail = nil\n\t} else {\n\t\tif prev == nil {\n\t\t\tthis.head = next\n\t\t} else {\n\t\t\tprev.next = next\n\t\t}\n\t}\n}", "func (gdt *Array) Remove(idx Int) {\n\targ0 := gdt.getBase()\n\targ1 := idx.getBase()\n\n\tC.go_godot_array_remove(GDNative.api, arg0, arg1)\n}", "func (gdt *Array) Erase(value Variant) {\n\targ0 := gdt.getBase()\n\targ1 := value.getBase()\n\n\tC.go_godot_array_erase(GDNative.api, arg0, arg1)\n}", "func (vector *Vector) Delete(i int) {\n\t//a = append(a[:i], a[i+1:]...)\n\t// or\n\t//a = a[:i+copy(a[i:], a[i+1:])]\n\t// NOTE If the type of the element is a pointer or a struct with pointer fields,\n\t// which need to be garbage collected, the above implementation of Delete has a potential\n\t// memory leak problem: some elements with values are still referenced by slice a and\n\t// thus can not be collected. The following code can fix this problem:\n\n\tcopy((*vector)[i:], (*vector)[i+1:])\n\t(*vector)[len(*vector)-1] = nil // or the zero value of T\n\t*vector = (*vector)[:len(*vector)-1]\n}", "func (ll *LinkedList) DeleteAtPos(pos int) (util.Value, bool) {\n\tif ll.IsEmpty() {\n\t\treturn nil, false\n\t}\n\tif pos >= ll.size {\n\t\treturn nil, false\n\t}\n\n\tvar prev *node\n\tvar cur = ll.head\n\tvar deletedVal util.Value\n\n\tfor i := 0; i < pos; i++ {\n\t\tprev = cur\n\t\tcur = cur.next\n\t}\n\n\t// If prev is nil, then we need to remove head.\n\t// Else, we need to remove the cur node.\n\tdeletedVal = cur.val\n\tif prev == nil {\n\t\tll.head = cur.next\n\t\tcur.next = nil\n\t} else {\n\t\tprev.next = cur.next\n\t\tcur.next = nil\n\t}\n\tcur = nil // setting up for garbage collection.\n\tll.size--\n\treturn deletedVal, true\n}", "func (o *DeleteNodeParams) WithAt(at *int64) *DeleteNodeParams {\n\to.SetAt(at)\n\treturn o\n}", "func (t *StringSlice) RemoveAt(i int) bool {\n\tif i >= 0 && i < len(t.items) {\n\t\tt.items = append(t.items[:i], t.items[i+1:]...)\n\t\treturn true\n\t}\n\treturn false\n}", "func (cuo *CustomerUpdateOne) SetRemovedAt(t time.Time) *CustomerUpdateOne {\n\tcuo.mutation.SetRemovedAt(t)\n\treturn cuo\n}", "func (ll *Doubly[T]) DelAtBeg() (T, bool) {\n\t// no item\n\tif ll.Head.Next == nil {\n\t\tvar r T\n\t\treturn r, false\n\t}\n\n\tn := ll.Head.Next\n\tval := n.Val\n\tll.Remove(n)\n\treturn val, true\n}", "func (root *mTreap) erase(i treapIter) {\n\troot.removeNode(i.t)\n}", "func (srmuo *SysRoleMenuUpdateOne) ClearDeletedAt() *SysRoleMenuUpdateOne {\n\tsrmuo.mutation.ClearDeletedAt()\n\treturn srmuo\n}", "func (b *Bitset) Clear(pos int) error {\n\tvar flag int32 = 1\n\tif pos < 0 || pos >= b.length*32 {\n\t\treturn fmt.Errorf(\"invalid position for bitset of length %d\", b.length)\n\t}\n\trpos := int32(pos) / 32 // (relative position inside the integer slice)\n\tbpos := int32(pos) % 32 // (local bit position inside bitvec[rpos])\n\tflag = flag << bpos\n\tflag = ^flag\n\tb.bitvec[rpos] = b.bitvec[rpos] & flag\n\n\treturn nil\n}", "func (tr *testTalker) erase() {\n\ttr.input = make([]string, 0)\n\ttr.output = make([]string, 0)\n}", "func (stack *savepointStack) popToIdx(idx int) {\n\t*stack = (*stack)[:idx+1]\n}", "func (f * LinkedList) delIdx(idx int) (*Element){\n\t// will return deleted element\n\tif (f.length == 0){\n\t\treturn nil\n\t} else if (idx < f.length) {\n\t\tif (idx == f.length - 1){\n\t\t\treturn f.delLast()\n\t\t} else if (idx == 0){\n\t\t\treturn f.delFirst()\n\t\t} else {\n\t\t\tel := f.getElmt(idx)\n\t\t\tel.prev.next = el.next\n\t\t\tel.next.prev = el.prev\n\t\t\tf.length--\n\t\t\treturn el\n\t\t}\n\t} else {\n\t\treturn nil\n\t}\n}", "func (this *Array) Delete(index uint) (int, error){\n\tif this.isIndexOutOfRange(index){\n\t\treturn 0, errors.New(\"index out of range\")\n\t}\n\tv := this.data[index]\n\tfor i := index; i < this.Len()-1; i++{\n\t\tthis.data[i] = this.data[i+1]\n\t}\n\tthis.length --\n\treturn v, nil\n}", "func (cu *CustomerUpdate) SetRemovedAt(t time.Time) *CustomerUpdate {\n\tcu.mutation.SetRemovedAt(t)\n\treturn cu\n}", "func (gc *GisCache) DelPosition(typ string, name string) {\n\tkey := gc.baseKey + posKey + typ + \":\" + name\n\terr := gc.rc.DelEntry(key)\n\tif err != nil {\n\t\tlog.Error(\"Failed to delete position for \", name, \" with err: \", err.Error())\n\t}\n}", "func (list *List) removeByIndex(idx int) error {\n\tlist_ := []interface{}(*list)\n\t*list = append(list_[:idx], list_[idx+1:]...)\n\treturn nil\n}", "func (u *GameServerUpsertOne) ClearDisabledAt() *GameServerUpsertOne {\n\treturn u.Update(func(s *GameServerUpsert) {\n\t\ts.ClearDisabledAt()\n\t})\n}", "func removeAtIndex(source []int, index int) []int {\n\tlastIndex := len(source) - 1\n\tsource[index], source[lastIndex] = source[lastIndex], source[index]\n\treturn source[:lastIndex]\n}", "func (b *Block) Erase(tlvType uint32) bool {\n\tindexToRemove := -1\n\tfor i, elem := range b.subelements {\n\t\tif elem.Type() == tlvType {\n\t\t\tindexToRemove = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif indexToRemove != -1 {\n\t\tcopy(b.subelements[indexToRemove:], b.subelements[indexToRemove+1:])\n\t\tb.subelements = b.subelements[:len(b.subelements)-1]\n\t\tb.wire = []byte{}\n\t}\n\n\treturn indexToRemove != -1\n}", "func DeleteInSlice(s interface{}, index int) interface{} {\n\tvalue := reflect.ValueOf(s)\n\tif value.Kind() == reflect.Slice {\n\t\t// || value.Kind() == reflect.Array {\n\t\tresult := reflect.AppendSlice(value.Slice(0, index), value.Slice(index+1, value.Len()))\n\t\treturn result.Interface()\n\t}\n\n\tklog.Errorf(\"Only a slice can be passed into this method for deleting an element of it.\")\n\treturn s\n}", "func (w *VT100Writer) EraseUp() {\n\tw.WriteRaw([]byte{0x1b, '[', '1', 'J'})\n}", "func (rbst *RBSTAbelGroup) Erase(root *Node, start, stop int) *Node {\r\n\tx, _, z := rbst.Split3ByRank(root, start, stop)\r\n\treturn rbst.Merge(x, z)\r\n}", "func (list *ArrayList) Remove(index int) {\n\tif !list.boundCheck(index) {\n\t\treturn\n\t}\n\n\tlist.elements[index] = nil\n\tcopy(list.elements[index:], list.elements[index+1:list.size])\n\tlist.size -= 1\n\t//shirnk if necessary\n\tlist.shrink()\n}", "func (self *Graphics) RemoveChildAt(index int) *DisplayObject{\n return &DisplayObject{self.Object.Call(\"removeChildAt\", index)}\n}", "func del(p *vpoint, pred func(x, y float64, e interface{}) bool) {\n\tfor i := len(p.elems) - 1; i >= 0; i-- {\n\t\tif pred(p.x, p.y, p.elems[i]) {\n\t\t\t// Fast del from slice\n\t\t\tlast := len(p.elems) - 1\n\t\t\tp.elems[i] = p.elems[last]\n\t\t\tp.elems = p.elems[:last]\n\t\t}\n\t}\n\treturn\n}", "func (a *Array) Delete(index uint) (int, error) {\n\tif a.isIndexOutOfRange(index) {\n\t\treturn 0, errors.New(\"out of index range\")\n\t}\n\tv := a.data[index]\n\tfor i := index; i < a.Len()-1; i++ {\n\t\ta.data[i] = a.data[i+1]\n\t}\n\ta.length--\n\treturn v, nil\n}", "func (this *MyLinkedList) DeleteAtIndex(index int) {\n\tif index < 0 || index >= this.Length {\n\t\treturn\n\t}\n\tcurrent := this.Head\n\tfor i := 0; i < index; i++ {\n\t\tcurrent = current.Next\n\t}\n\tcurrent.Next = current.Next.Next\n\tthis.Length--\n}", "func (self *TileSprite) RemoveChildAt(index int) *DisplayObject{\n return &DisplayObject{self.Object.Call(\"removeChildAt\", index)}\n}", "func (u *GameServerUpsertBulk) ClearDisabledAt() *GameServerUpsertBulk {\n\treturn u.Update(func(s *GameServerUpsert) {\n\t\ts.ClearDisabledAt()\n\t})\n}", "func (l *List) Del(v interface{} /* val */) *El {\n\tcur := l.search(v, true, true)\n\n\tif cur == nil || l.less(v, cur.val) {\n\t\treturn nil\n\t}\n\n\tl.len--\n\n\th := cur.height()\n\tfor i := h - 1; i >= 0; i-- {\n\t\t*l.up[i] = cur.nexti(i)\n\t}\n\n\tif l.autoreuse {\n\t\tReuse(cur)\n\t}\n\n\treturn cur\n}", "func (s *SetOfInt) Erase() {\n\ts.mux.Lock()\n\tdefer s.mux.Unlock()\n\ts.set = map[int]struct{}{}\n}", "func (this *MyLinkedList) DeleteAtIndex(index int) {\n\tif index < 0 || index >= this.size {\n\t\treturn\n\t}\n\tcurr := this.GetNode(index)\n\tprev := curr.Prev\n\tnext := curr.Next\n\tif prev == nil {\n\t\tthis.Head = next\n\t} else {\n\t\tprev.Next = next\n\t}\n\tif next == nil {\n\t\tthis.Tail = prev\n\t} else {\n\t\tnext.Prev = prev\n\t}\n\tthis.size -= 1\n}", "func (v *OrderedValues) Del(key []byte) {\n\tvar (\n\t\ti int\n\t\tok bool\n\t\tj [][]byte\n\t)\n\tfor i, j = range *v {\n\t\tif len(j) > 0 && bytes.Equal(j[0], key) {\n\t\t\tok = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !ok {\n\t\treturn\n\t}\n\tcopy((*v)[i:], (*v)[i+1:])\n\t(*v)[len(*v)-1] = nil\n\t*v = (*v)[:len(*v)-1]\n}", "func (gsuo *GameServerUpdateOne) ClearDisabledAt() *GameServerUpdateOne {\n\tgsuo.mutation.ClearDisabledAt()\n\treturn gsuo\n}", "func (w *Writer) ZeroUntil(index int64)", "func (v *IntVec) Remove(idx int) (val int) {\n\tvar nil int\n\n\tdv := *v\n\n\tval = dv[idx]\n\t*v = append(dv[:idx], dv[1+idx:]...)\n\n\tdv[len(dv)-1] = nil\n\n\treturn val\n}", "func (srmu *SysRoleMenuUpdate) ClearDeletedAt() *SysRoleMenuUpdate {\n\tsrmu.mutation.ClearDeletedAt()\n\treturn srmu\n}", "func DeleteElement(s []int, i int) []int {\n\tif i < 0 || len(s) <= i {\n\t\tpanic(errors.New(\"[index error]\"))\n\t}\n\t// appendのみの実装\n\tn := make([]int, 0, len(s)-1)\n\tn = append(n, s[:i]...)\n\tn = append(n, s[i+1:]...)\n\treturn n\n}" ]
[ "0.7353664", "0.7003326", "0.67670447", "0.6748609", "0.672052", "0.6689085", "0.6369032", "0.62965", "0.61890763", "0.61140746", "0.6108951", "0.6051568", "0.58953065", "0.5869014", "0.58656377", "0.577955", "0.57686853", "0.57362086", "0.5682408", "0.5645772", "0.5615606", "0.56140023", "0.5592883", "0.5577396", "0.5571837", "0.55660886", "0.5559954", "0.55547094", "0.55251545", "0.55015177", "0.5487439", "0.5409723", "0.54062456", "0.5360957", "0.533521", "0.53211254", "0.5315539", "0.5299304", "0.5298153", "0.5289528", "0.52840817", "0.52809364", "0.5278076", "0.526871", "0.52672285", "0.52510554", "0.5241574", "0.5212624", "0.51983935", "0.5192989", "0.5192372", "0.5187089", "0.51869094", "0.5184691", "0.51659256", "0.5155979", "0.5153041", "0.51522285", "0.5151919", "0.5150576", "0.5148126", "0.51453924", "0.5144913", "0.5131036", "0.51120615", "0.5097503", "0.50964594", "0.50958157", "0.509288", "0.50782186", "0.5068931", "0.50652885", "0.506039", "0.50570714", "0.50546217", "0.50452286", "0.5039395", "0.5036593", "0.5029091", "0.5027433", "0.5023169", "0.50172114", "0.501522", "0.50050086", "0.49996996", "0.49936882", "0.49904343", "0.49802375", "0.4971236", "0.49663743", "0.4964792", "0.49645448", "0.4949088", "0.49453476", "0.4942179", "0.49421212", "0.49369755", "0.4934551", "0.49249807", "0.49200565" ]
0.6766179
3
EraseRange erases elements in range [firstPos, lastPos)
func (d *Deque[T]) EraseRange(firstPos, lastPos int) { if firstPos < 0 || firstPos >= lastPos || lastPos > d.size { return } num := lastPos - firstPos if d.size-firstPos < lastPos { // move back for pos := firstPos; pos+num < d.size; pos++ { d.Set(pos, d.At(pos+num)) } for ; num > 0; num-- { d.PopBack() } } else { // move front for pos := lastPos - 1; pos-num >= 0; pos-- { d.Set(pos, d.At(pos-num)) } for ; num > 0; num-- { d.PopFront() } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i *InmemStore) DeleteRange(min, max uint64) error {\n\ti.l.Lock()\n\tdefer i.l.Unlock()\n\tfor j := min; j <= max; j++ {\n\t\tdelete(i.logs, j)\n\t}\n\ti.lowIndex = max + 1\n\treturn nil\n}", "func (s *Wal) DeleteRange(min, max uint64) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfirst, err := s.log.FirstIndex()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlast, err := s.log.LastIndex()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif min == first {\n\t\tif err := s.log.TruncateFront(max + 1); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if max == last {\n\t\tif err := s.log.TruncateBack(min - 1); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\treturn wal.ErrOutOfRange\n\t}\n\treturn nil\n}", "func (wb *WriteBatch) DeleteRange(beginKey, endKey []byte) {\n\tcBeginKey := bytesToChar(beginKey)\n\tcEndKey := bytesToChar(endKey)\n\tC.rocksdb_writebatch_delete_range(wb.c, cBeginKey, C.size_t(len(beginKey)), cEndKey, C.size_t(len(endKey)))\n}", "func (column TsTimestampColumn) EraseRanges(rgs ...TsRange) (uint64, error) {\n\talias := convertToCharStar(column.parent.alias)\n\tdefer releaseCharStar(alias)\n\tcolumnName := convertToCharStar(column.name)\n\tdefer releaseCharStar(columnName)\n\tranges := rangeArrayToC(rgs...)\n\trangesCount := C.qdb_size_t(len(rgs))\n\terasedCount := C.qdb_uint_t(0)\n\terr := C.qdb_ts_erase_ranges(column.parent.handle, alias, columnName, ranges, rangesCount, &erasedCount)\n\treturn uint64(erasedCount), makeErrorOrNil(err)\n}", "func (ba *FilterBitArray) UnsetRange(begin uint, end uint) {\n\tif begin > ba.Capacity() || begin == end {\n\t\treturn\n\t}\n\n\tstartByteIndex := ba.byteIndex(begin)\n\tendByteIndex := ba.byteIndex(end)\n\n\tfirstByteMask := byteMask << (begin % byteSize)\n\tlastByteMask := byteMask >> ((byteSize - end - 1) % byteSize)\n\n\tif startByteIndex == endByteIndex {\n\t\t(*ba)[startByteIndex] &= ^(firstByteMask & lastByteMask)\n\t} else {\n\t\t(*ba)[startByteIndex] &= ^firstByteMask\n\t\tfor i := startByteIndex + 1; i < endByteIndex; i++ {\n\t\t\t(*ba)[i] = 0\n\t\t}\n\t\t(*ba)[endByteIndex] &= ^lastByteMask\n\t}\n}", "func (b *BadgerStore) DeleteRange(min, max uint64) error {\n\t// we manage the transaction manually in order to avoid ErrTxnTooBig errors\n\ttxn := b.conn.NewTransaction(true)\n\tit := txn.NewIterator(badger.IteratorOptions{\n\t\tPrefetchValues: false,\n\t\tReverse: false,\n\t})\n\n\tfor it.Seek(uint64ToBytes(min)); it.Valid(); it.Next() {\n\t\tkey := make([]byte, 8)\n\t\tit.Item().KeyCopy(key)\n\t\t// Handle out-of-range log index\n\t\tif bytesToUint64(key) > max {\n\t\t\tbreak\n\t\t}\n\t\t// Delete in-range log index\n\t\tif err := txn.Delete(key); err != nil {\n\t\t\tif err == badger.ErrTxnTooBig {\n\t\t\t\tit.Close()\n\t\t\t\terr = txn.Commit(nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn b.DeleteRange(bytesToUint64(key), max)\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\tit.Close()\n\terr := txn.Commit(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (i *LogStore) DeleteRange(min, max uint64) error {\n\ti.l.Lock()\n\tdefer i.l.Unlock()\n\tfor j := min; j <= max; j++ {\n\t\tdelete(i.logs, j)\n\t}\n\ti.lowIndex = max + 1\n\treturn nil\n}", "func (s *IPSet) RemoveRange(r IPRange) {\n\tif r.Valid() {\n\t\ts.out = append(s.out, r)\n\t}\n}", "func (s *IPSet) RemoveRange(r IPRange) {\n\tif r.Valid() {\n\t\ts.out = append(s.out, r)\n\t}\n}", "func (p containerJSONItemRemover) AddRangeToRemove(startIndex int, endIndex int) {\n\tfor i := startIndex; i <= endIndex; i++ {\n\t\tp.removedDataIndex[i] = true\n\t}\n}", "func BenchmarkRemoveRange(t *testing.B) {\n\n\tfor n := 0; n < t.N; n++ {\n\t\tt.StopTimer()\n\t\ttree := New()\n\n\t\tfor i := 0; i < 1000; i++ {\n\t\t\tistr := strconv.Itoa(i)\n\t\t\ttree.Put([]byte(istr), []byte(istr))\n\t\t}\n\n\t\tt.StartTimer()\n\t\t// t.Log(strconv.Itoa(min), strconv.Itoa(max))\n\t\ttree.RemoveRange([]byte(strconv.Itoa(430)), []byte(strconv.Itoa(830)))\n\n\t}\n\tt.Log(t.N)\n\t// t.StopTimer()\n}", "func (b *raftBadger) DeleteRange(min, max uint64) error {\n\tmaxBatchSize := b.gs.GetStore().(*badger.DB).MaxBatchSize()\n\tranges := b.generateRanges(min, max, maxBatchSize)\n\tfor _, r := range ranges {\n\t\ttxn := b.gs.GetStore().(*badger.DB).NewTransaction(true)\n\t\tit := txn.NewIterator(badger.DefaultIteratorOptions)\n\t\tdefer txn.Discard()\n\n\t\tit.Rewind()\n\t\tminKey := logKeyOf(r.from) // Get the key to start at\n\t\tfor it.Seek(minKey); it.ValidForPrefix(dbLogPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tk := string(item.Key()[len(dbLogPrefix):]) // Get the index as a string to convert to uint64\n\t\t\tidx, err := strconv.ParseUint(k, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tit.Close()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif idx > r.to { // Handle out-of-range index\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdelKey := logKeyOf(idx) // Delete in-range index\n\t\t\tif err := txn.Delete(delKey); err != nil {\n\t\t\t\tit.Close()\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tit.Close()\n\t\tif err := txn.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (v *Int32Vec) RemoveSlice(start, end int) {\n\tdv := *v\n\n\t*v = append(dv[:start], dv[end:]...)\n\n\tv.Truncate(len(dv) - (end - start))\n}", "func (b *EtcdBackend) DeleteRange(ctx context.Context, startKey, endKey []byte) error {\n\tif len(startKey) == 0 {\n\t\treturn trace.BadParameter(\"missing parameter startKey\")\n\t}\n\tif len(endKey) == 0 {\n\t\treturn trace.BadParameter(\"missing parameter endKey\")\n\t}\n\tstart := b.clock.Now()\n\t_, err := b.clients.Next().Delete(ctx, b.prependPrefix(startKey), clientv3.WithRange(b.prependPrefix(endKey)))\n\twriteLatencies.Observe(time.Since(start).Seconds())\n\twriteRequests.Inc()\n\tif err != nil {\n\t\treturn trace.Wrap(convertErr(err))\n\t}\n\n\treturn nil\n}", "func (ls *LevelDBStore) DeleteRange(min uint64, max uint64) error {\n\tls.rwMtx.Lock()\n\tdefer ls.rwMtx.Unlock()\n\tr := &util.Range{\n\t\tStart: uint64ToBytes(min),\n\t\tLimit: uint64ToBytes(max + 1),\n\t}\n\n\titer := ls.ldb.NewIterator(r, nil)\n\tdefer iter.Release()\n\n\tbatch := new(leveldb.Batch)\n\tfor iter.Next() {\n\t\tbatch.Delete(iter.Key())\n\t}\n\n\treturn ls.ldb.Write(batch, nil)\n}", "func (v *IntVec) RemoveSlice(start, end int) {\n\tdv := *v\n\n\t*v = append(dv[:start], dv[end:]...)\n\n\tv.Truncate(len(dv) - (end - start))\n}", "func (b *Backend) DeleteRange(ctx context.Context, startKey, endKey []byte) error {\n\tdocs, err := b.getRangeDocs(ctx, startKey, endKey, backend.DefaultRangeLimit)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\treturn trace.Wrap(b.deleteDocuments(docs))\n}", "func (rl *RangeList) Remove(singleRange [rangeBoundarySize]int) {\n\tleftBoundary := singleRange[leftIdx]\n\trightBoundary := singleRange[rightIdx]\n\tleftPos := rl.findPosition(leftBoundary)\n\trightPos := rl.findPosition(rightBoundary)\n\n\tnewList := make([][rangeBoundarySize]int, 0)\n\tnewRange := [rangeBoundarySize]int{}\n\tif leftPos >= 0 {\n\t\tif leftBoundary <= rl.list[leftPos][rightIdx] {\n\t\t\tnewList = append(newList, rl.list[0:leftPos]...)\n\t\t\tif leftBoundary > rl.list[leftPos][leftIdx] {\n\t\t\t\tnewRange[leftIdx] = rl.list[leftPos][leftIdx]\n\t\t\t\tnewRange[rightIdx] = leftBoundary\n\t\t\t\tnewList = append(newList, newRange)\n\t\t\t}\n\t\t} else {\n\t\t\tnewList = append(newList, rl.list[0:leftPos+1]...)\n\t\t}\n\t}\n\n\tif rightPos >= 0 {\n\t\tif rightBoundary < rl.list[rightPos][rightIdx] {\n\t\t\tnewRange[leftIdx] = rightBoundary\n\t\t\tnewRange[rightIdx] = rl.list[rightPos][rightIdx]\n\t\t\tnewList = append(newList, newRange)\n\t\t}\n\t\tif rightPos < len(rl.list)-1 {\n\t\t\tnewList = append(newList, rl.list[rightPos+1:]...)\n\t\t}\n\t} else {\n\t\treturn\n\t}\n\n\trl.list = newList\n}", "func (v *Data) RemoveSlice(start, end int) {\n\tdv := *v\n\n\t*v = append(dv[:start], dv[end:]...)\n\n\tv.Truncate(len(dv) - (end - start))\n}", "func (s *Storage) RangeDelete(start, end []byte) error {\n\ts.kv.RangeDelete(start, end)\n\treturn nil\n}", "func DeleteRange(baseParams BaseParams, bck cmn.Bck, rng string) (string, error) {\n\tdeleteMsg := cmn.ListRangeMsg{Template: rng}\n\treturn doListRangeRequest(baseParams, bck, cmn.ActDelete, deleteMsg)\n}", "func remove(list []*IPRange, index int) []*IPRange {\n\tfor i := index + 1; i < len(list); i++ {\n\t\tlist[i-1] = list[i]\n\t}\n\treturn list[:len(list)-1]\n}", "func (r *raftLog) deleteRange(min, max uint64) error {\n\tvar key [8]byte\n\tbinary.BigEndian.PutUint64(key[:], min)\n\ttx, err := r.conn.Begin(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback()\n\tcurs := tx.Bucket(logsBucket).Cursor()\n\tfor k, _ := curs.Seek(key[:]); k != nil; k, _ = curs.Next() {\n\t\t// If we reach the max, we are done\n\t\tif binary.BigEndian.Uint64(k) > max {\n\t\t\tbreak\n\t\t}\n\t\tif err := curs.Delete(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn tx.Commit()\n}", "func EvictRange(baseParams BaseParams, bck cmn.Bck, rng string) (string, error) {\n\tevictMsg := cmn.ListRangeMsg{Template: rng}\n\treturn doListRangeRequest(baseParams, bck, cmn.ActEvictObjects, evictMsg)\n}", "func (r Range) Exclude(_toExcludes ...Range) Ranges {\n\ttoExcludes := Ranges(_toExcludes)\n\ttoExcludes.SortAndMerge()\n\n\tvar result Ranges\n\tcurStart := r.Offset\n\tcurEnd := r.End()\n\tfor _, toExclude := range toExcludes {\n\t\texcStart := toExclude.Offset\n\t\texcEnd := toExclude.End()\n\t\tif excEnd <= curStart {\n\t\t\tcontinue\n\t\t}\n\t\tif excStart >= curEnd {\n\t\t\tcontinue\n\t\t}\n\n\t\tif curStart < excStart {\n\t\t\tresult = append(result, Range{\n\t\t\t\tOffset: curStart,\n\t\t\t\tLength: excStart - curStart,\n\t\t\t})\n\t\t}\n\n\t\tcurStart = excEnd\n\t\tif curStart >= curEnd {\n\t\t\treturn result\n\t\t}\n\t}\n\n\tresult = append(result, Range{\n\t\tOffset: curStart,\n\t\tLength: curEnd - curStart,\n\t})\n\treturn result\n}", "func replaceRange(in []byte, sub []byte, start, end int) []byte {\n\tout := make([]byte, 0, len(in)+len(sub)+start-end)\n\tout = append(out, in[:start]...)\n\tout = append(out, sub...)\n\tout = append(out, in[end:]...)\n\treturn out\n}", "func (s *sliding) deleteFrom(newStart LogPosition) {\n\tstart := s.start\n\tfor i, u := range s.log[:s.mutable-start][:newStart-start] {\n\t\tpos := start + LogPosition(i)\n\t\tblkno := u.Addr\n\t\toldPos, ok := s.addrPos[blkno]\n\t\tif ok && oldPos <= pos {\n\t\t\tutil.DPrintf(5, \"memLogMap: del %d %d\\n\", blkno, oldPos)\n\t\t\tdelete(s.addrPos, blkno)\n\t\t}\n\t}\n\ts.log = s.log[newStart-start:]\n\ts.start = newStart\n}", "func (s *Tsfs) TestRange(c *C) {\n r := RangeStartEnd(1, 5) // [ 1, 2, 3, 4 ]\n AssertString(c, r, \"1:4\")\n\n // negative arg\n AssertString(c, r.Drop(-1), \"1:4\")\n AssertString(c, r.DropRight(-1), \"1:4\")\n AssertString(c, r.Take(-1), \"0:0\")\n AssertString(c, r.TakeRight(-1), \"0:0\")\n\n // zero arg\n AssertString(c, r.Drop(0), \"1:4\")\n AssertString(c, r.DropRight(0), \"1:4\")\n AssertString(c, r.Take(0), \"0:0\")\n AssertString(c, r.TakeRight(0), \"0:0\")\n\n // positive arg\n AssertString(c, r.Drop(1), \"2:3\")\n AssertString(c, r.DropRight(1), \"1:3\")\n AssertString(c, r.Take(1), \"1:1\")\n AssertString(c, r.TakeRight(1), \"4:1\")\n\n // length - 1\n AssertString(c, r.Drop(3), \"4:1\")\n AssertString(c, r.DropRight(3), \"1:1\")\n AssertString(c, r.Take(3), \"1:3\")\n AssertString(c, r.TakeRight(3), \"2:3\")\n\n // length\n AssertString(c, r.Drop(4), \"0:0\")\n AssertString(c, r.DropRight(4), \"0:0\")\n AssertString(c, r.Take(4), \"1:4\")\n AssertString(c, r.TakeRight(4), \"1:4\")\n\n // length + 1\n AssertString(c, r.Drop(5), \"0:0\")\n AssertString(c, r.DropRight(5), \"0:0\")\n AssertString(c, r.Take(5), \"1:4\")\n AssertString(c, r.TakeRight(5), \"1:4\")\n\n // slice is implemented in terms of take and drop so is\n // primarily assured by the above passing.\n AssertString(c, r.Slice(0, 0), \"0:0\")\n AssertString(c, r.Slice(0, 1), \"1:1\")\n AssertString(c, r.Slice(0, 2), \"1:2\")\n AssertString(c, r.Slice(1, 2), \"2:1\")\n AssertString(c, r.Slice(2, 1), \"0:0\")\n AssertString(c, r.Slice(-2, -1), \"0:0\")\n AssertString(c, r.Slice(-2, 2), \"1:2\")\n\n}", "func ClearInterval(data []uintptr, startIdx, limitIdx int) {\n\tif startIdx >= limitIdx {\n\t\treturn\n\t}\n\tstartWordIdx := startIdx >> Log2BitsPerWord\n\tstartBit := uintptr(1) << uint32(startIdx&(BitsPerWord-1))\n\tlimitWordIdx := limitIdx >> Log2BitsPerWord\n\tlimitBit := uintptr(1) << uint32(limitIdx&(BitsPerWord-1))\n\tif startWordIdx == limitWordIdx {\n\t\t// We can't clear all bits from startBit on in the first word, since the\n\t\t// limit is also within this word.\n\t\tdata[startWordIdx] &= ^(limitBit - startBit)\n\t\treturn\n\t}\n\t// Clear all bits from startBit on in the first word.\n\tdata[startWordIdx] &= startBit - 1\n\t// Clear all bits in intermediate words.\n\tfor wordIdx := startWordIdx + 1; wordIdx < limitWordIdx; wordIdx++ {\n\t\tdata[wordIdx] = 0\n\t}\n\t// Clear just the bottom bits in the last word, if necessary.\n\tif limitBit != 1 {\n\t\tdata[limitWordIdx] &= -limitBit\n\t}\n}", "func (s *storeInstance) UnsafeDestroyRange(ctx context.Context, req *kvrpcpb.UnsafeDestroyRangeRequest) (*kvrpcpb.UnsafeDestroyRangeResponse, error) {\n\tpanic(\"unimplemented\")\n}", "func (fr *FileRing) UpdateRange(start, end int64) []File {\n\tfr.lock.Lock()\n\tdefer fr.lock.Unlock()\n\n\tvar deleted []File\n\n\tfor k, v := range fr.hashMap {\n\t\tif !InRange(k, start, end, M) {\n\t\t\tdeleted = append(deleted, v.SortedFiles()...)\n\t\t\tdelete(fr.hashMap, k)\n\t\t}\n\t}\n\tfr.start = start\n\tfr.end = end\n\n\treturn deleted\n}", "func UnexcludedRange(handRange []HoleCards, runout map[string]bool) []HoleCards {\n\tres := make([]HoleCards, 0, len(handRange))\n\tfor _, hand := range handRange {\n\t\tif !runout[hand[0]] && !runout[hand[1]] {\n\t\t\tres = append(res, hand)\n\t\t}\n\t}\n\treturn res\n}", "func (r *raftLog) DeleteRange(min, max uint64) (retErr error) {\n\n\tif r.hasCache {\n\t\tr.Lock()\n\t\t// Reset cache\n\t\tr.cache = make([]*raft.Log, int(r.cacheSize))\n\t\tr.Unlock()\n\t}\n\n\tstart := time.Now()\n\tr.log.Noticef(\"Deleting raft logs from %v to %v\", min, max)\n\terr := r.deleteRange(min, max)\n\tdur := time.Since(start)\n\tdurTxt := fmt.Sprintf(\"Deletion took %v\", dur)\n\tif dur > 2*time.Second {\n\t\tr.log.Errorf(durTxt)\n\t} else {\n\t\tr.log.Noticef(durTxt)\n\t}\n\treturn err\n}", "func DeleteRange(ctx *grumble.Context) error {\n\treturn executeRange(ctx, \"Deleted messages:\", func(client ldProto.LdClient, execCtx context.Context, keyRange *ldProto.KeyRange) (rangeClient, error) {\n\t\treturn client.DeleteRange(execCtx, keyRange)\n\t})\n}", "func (t *mutableTree) DeleteVersionsRange(fromVersion, toVersion int64) error {\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\terr := t.tree.DeleteVersionsRange(fromVersion, toVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func eraseOverlapIntervals(intervals [][]int) int {\n\tn := len(intervals)\n\treturn n - nonOverlapIntervals(intervals)\n}", "func (list *TList) Trim(start, stop int) {\n\tlist.mux.Lock()\n\n\tstart = list.convertPos(start)\n\tstop = list.convertPos(stop)\n\n\tif start > list.Len()-1 {\n\t\tlist.mux.Unlock()\n\t\treturn\n\t}\n\n\tif start < 0 {\n\t\tstart = 0\n\t}\n\n\tif stop > list.Len() {\n\t\tstop = list.Len() - 1\n\t}\n\n\tif stop < start {\n\t\tlist.mux.Unlock()\n\t\treturn\n\t}\n\n\titemsForRemoveFromHead := start\n\titemsForRemoveFromTail := list.Len() - 1 - stop\n\n\tlist.mux.Unlock()\n\n\t// TODO We need a more optimized method\n\tfor i := itemsForRemoveFromHead; i > 0; i-- {\n\t\tlist.HPop()\n\t}\n\n\tfor i := itemsForRemoveFromTail; i > 0; i-- {\n\t\tlist.TPop()\n\t}\n}", "func removeFromSlice(rrs []dns.RR, i int) []dns.RR {\n\tif i >= len(rrs) {\n\t\treturn rrs\n\t}\n\trrs = append(rrs[:i], rrs[i+1:]...)\n\treturn rrs\n}", "func (r *Range) DeleteRange(args *DeleteRangeRequest, reply *DeleteRangeResponse) {\n\treply.Error = util.Error(\"unimplemented\")\n}", "func (spriteBatch *SpriteBatch) ClearDrawRange() {\n\tspriteBatch.rangeMin = -1\n\tspriteBatch.rangeMax = -1\n}", "func (xs *Sheet) RemoveRowAndKeepRanges(rowFirst int, rowLast int) int {\n\ttmp, _, _ := xs.xb.lib.NewProc(\"xlSheetRemoveRowAndKeepRangesW\").\n\t\tCall(xs.self, I(rowFirst), I(rowLast))\n\treturn int(tmp)\n}", "func RevertRange(\n\tctx context.Context, readWriter storage.ReadWriter, cArgs CommandArgs, resp roachpb.Response,\n) (result.Result, error) {\n\tif cArgs.Header.Txn != nil {\n\t\treturn result.Result{}, ErrTransactionUnsupported\n\t}\n\tlog.VEventf(ctx, 2, \"RevertRange %+v\", cArgs.Args)\n\n\targs := cArgs.Args.(*roachpb.RevertRangeRequest)\n\treply := resp.(*roachpb.RevertRangeResponse)\n\tvar pd result.Result\n\n\tif empty, err := isEmptyKeyTimeRange(\n\t\treadWriter, args.Key, args.EndKey, args.TargetTime, cArgs.Header.Timestamp,\n\t); err != nil {\n\t\treturn result.Result{}, err\n\t} else if empty {\n\t\tlog.VEventf(ctx, 2, \"no keys to clear in specified time range\")\n\t\treturn result.Result{}, nil\n\t}\n\n\tlog.VEventf(ctx, 2, \"clearing keys with timestamp (%v, %v]\", args.TargetTime, cArgs.Header.Timestamp)\n\n\tresume, err := storage.MVCCClearTimeRange(ctx, readWriter, cArgs.Stats, args.Key, args.EndKey,\n\t\targs.TargetTime, cArgs.Header.Timestamp, cArgs.Header.MaxSpanRequestKeys,\n\t\tmaxRevertRangeBatchBytes,\n\t\targs.EnableTimeBoundIteratorOptimization)\n\tif err != nil {\n\t\treturn result.Result{}, err\n\t}\n\n\tif resume != nil {\n\t\tlog.VEventf(ctx, 2, \"hit limit while clearing keys, resume span [%v, %v)\", resume.Key, resume.EndKey)\n\t\treply.ResumeSpan = resume\n\n\t\t// If, and only if, we're returning a resume span do we want to return >0\n\t\t// NumKeys. Distsender will reduce the limit for subsequent requests by the\n\t\t// amount returned, but that doesn't really make sense for RevertRange:\n\t\t// there isn't some combined result set size we're trying to hit across many\n\t\t// requests; just because some earlier range ran X Clears that does not mean\n\t\t// we want the next range to run fewer than the limit chosen for the batch\n\t\t// size reasons. On the otherhand, we have to pass MaxKeys though if we\n\t\t// return a resume span to cause distsender to stop after this request, as\n\t\t// currently response combining's handling of resume spans prefers that\n\t\t// there only be one. Thus we just set it to MaxKeys when, and only when,\n\t\t// we're returning a ResumeSpan.\n\t\treply.NumKeys = cArgs.Header.MaxSpanRequestKeys\n\t\treply.ResumeReason = roachpb.RESUME_KEY_LIMIT\n\t}\n\n\treturn pd, nil\n}", "func (c *CodeInstance) RemoveRanges(t *style.Theme) (reqs []*docs.Request) {\n\t// create parser for each range\n\tvar rangeParsers []parser\n\tfor _, r := range t.Ranges {\n\t\trangeParsers = append(rangeParsers, expectRange(r))\n\t}\n\n\tvar removeRanges []removeRange // ranges to be removed\n\tutf16Offsets := make(map[int]int64) // add utf16 offset at certain utf8 indices in the sanitized string\n\tvar utf8Offset int // utf8 offset in sanitized string\n\tvar utf8MultiRangeStartIndex *int // if multiple ranges in a row, utf8 start index in sanitized string of first range\n\tin := rangeInput{runes: c.Code}\n\tfor r, size := in.current(); r != nil; r, size = in.current() {\n\t\tout := selectAny(rangeParsers)(in)\n\t\tif out.result != nil {\n\t\t\t// if range found, consume it and remove from string\n\t\t\trOutput := out.result.(rangeOutput)\n\t\t\tutf8StartIndex := in.pos\n\t\t\tutf8Size := len(rOutput.result)\n\t\t\tutf16Size := GetUtf16StringSize(rOutput.result)\n\t\t\tremoveRanges = append(removeRanges, removeRange{utf8StartIndex, utf8Size})\n\n\t\t\t// update offset map to recreate utf8 -> utf16 map in sanitized string\n\t\t\tif utf8MultiRangeStartIndex != nil {\n\t\t\t\t// there is at least one range directly before this one\n\t\t\t\t// so update the first range's utf8 -> utf16 index mapping in the sanitized string\n\t\t\t\tutf16Offsets[*utf8MultiRangeStartIndex] = utf16Offsets[*utf8MultiRangeStartIndex] + utf16Size\n\t\t\t} else {\n\t\t\t\t// no range directly before this, so create new utf8 -> utf16 index mapping\n\t\t\t\tutf8RangeStartIndex := utf8StartIndex + utf8Offset\n\t\t\t\tutf16Offsets[utf8RangeStartIndex] = utf16Size\n\t\t\t\tutf8MultiRangeStartIndex = &utf8RangeStartIndex\n\t\t\t}\n\t\t\tutf8Offset -= utf8Size\n\n\t\t\t// create request to update range's color using utf16 indices\n\t\t\tutf16OffsetStartIndex := c.toUTF16[utf8StartIndex]\n\t\t\tutf16Range := request.GetRange(utf16OffsetStartIndex, utf16OffsetStartIndex+utf16Size, \"\")\n\t\t\treqs = append(reqs, request.UpdateForegroundColor(rOutput.rangeType.Color, utf16Range))\n\n\t\t\tin = out.remaining.(rangeInput)\n\t\t\tcontinue\n\t\t}\n\t\t// failed to parse range, advance\n\t\tin = in.advance(size).(rangeInput)\n\t\tutf8MultiRangeStartIndex = nil\n\t}\n\n\tif len(removeRanges) == 0 {\n\t\treturn\n\t}\n\n\tvar sanitized strings.Builder\n\tvar cur removeRange\n\n\t// remove ranges from Code\n\tfor len(removeRanges) > 0 {\n\t\tstart := cur.index + cur.utf8Size\n\t\tcur, removeRanges = removeRanges[0], removeRanges[1:] // pop from slice\n\t\t_, err := sanitized.WriteString(c.Code[start:cur.index])\n\t\tcheck(err)\n\t}\n\t_, err := sanitized.WriteString(c.Code[cur.index+cur.utf8Size:])\n\tcheck(err)\n\n\t// update Code (removed ranges)\n\tc.Code = sanitized.String()\n\n\t// update zero-based utf8 -> offset utf16 index mapping\n\tutf16Index := *c.StartIndex\n\tc.toUTF16 = make(map[int]int64)\n\tvar r rune\n\tfor i, utf8Width := 0, 0; i < len(c.Code); i += utf8Width {\n\t\tif o, ok := utf16Offsets[i]; ok {\n\t\t\tutf16Index += o // add utf16 offset for range removal\n\t\t}\n\t\tr, utf8Width = utf8.DecodeRuneInString(c.Code[i:])\n\t\tc.toUTF16[i] = utf16Index\n\t\tutf16Index += GetUtf16RuneSize(r)\n\t}\n\treturn\n}", "func TestMultiRangeEmptyAfterTruncate(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\ts, _, _ := serverutils.StartServer(t, base.TestServerArgs{})\n\tdefer s.Stopper().Stop()\n\tdb := setupMultipleRanges(t, s, \"c\", \"d\")\n\n\t// Delete the keys within a transaction. The range [c,d) doesn't have\n\t// any active requests.\n\tif err := db.Txn(context.TODO(), func(txn *client.Txn) error {\n\t\tb := txn.NewBatch()\n\t\tb.DelRange(\"a\", \"b\", false)\n\t\tb.DelRange(\"e\", \"f\", false)\n\t\treturn txn.CommitInBatch(b)\n\t}); err != nil {\n\t\tt.Fatalf(\"unexpected error on transactional DeleteRange: %s\", err)\n\t}\n}", "func (f *fragment) rangeBetweenUnsigned(filter *Row, bitDepth uint, predicateMin, predicateMax uint64) (*Row, error) {\n\tkeep1 := NewRow() // GTE\n\tkeep2 := NewRow() // LTE\n\n\t// Filter any bits that don't match the current bit value.\n\tfor i := int(bitDepth - 1); i >= 0; i-- {\n\t\trow := f.row(uint64(bsiOffsetBit + i))\n\t\tbit1 := (predicateMin >> uint(i)) & 1\n\t\tbit2 := (predicateMax >> uint(i)) & 1\n\n\t\t// GTE predicateMin\n\t\t// If bit is set then remove all unset columns not already kept.\n\t\tif bit1 == 1 {\n\t\t\tfilter = filter.Difference(filter.Difference(row).Difference(keep1))\n\t\t} else {\n\t\t\t// If bit is unset then add columns with set bit to keep.\n\t\t\t// Don't bother to compute this on the final iteration.\n\t\t\tif i > 0 {\n\t\t\t\tkeep1 = keep1.Union(filter.Intersect(row))\n\t\t\t}\n\t\t}\n\n\t\t// LTE predicateMax\n\t\t// If bit is zero then remove all set bits not in excluded bitmap.\n\t\tif bit2 == 0 {\n\t\t\tfilter = filter.Difference(row.Difference(keep2))\n\t\t} else {\n\t\t\t// If bit is set then add columns for set bits to exclude.\n\t\t\t// Don't bother to compute this on the final iteration.\n\t\t\tif i > 0 {\n\t\t\t\tkeep2 = keep2.Union(filter.Difference(row))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filter, nil\n}", "func (db *DB) CompactRange(r Range) {\n\tif db.closed {\n\t\tpanic(ErrDBClosed)\n\t}\n\n\tvar start, limit *C.char\n\tif len(r.Start) != 0 {\n\t\tstart = (*C.char)(unsafe.Pointer(&r.Start[0]))\n\t}\n\tif len(r.Limit) != 0 {\n\t\tlimit = (*C.char)(unsafe.Pointer(&r.Limit[0]))\n\t}\n\tC.leveldb_compact_range(\n\t\tdb.Ldb, start, C.size_t(len(r.Start)), limit, C.size_t(len(r.Limit)))\n}", "func (k *Item) RemoveOutsideRange(start, end time.Time) {\n\tvar newCandles []Candle\n\tfor i := range k.Candles {\n\t\tif k.Candles[i].Time.Equal(start) ||\n\t\t\t(k.Candles[i].Time.After(start) && k.Candles[i].Time.Before(end)) {\n\t\t\tnewCandles = append(newCandles, k.Candles[i])\n\t\t}\n\t}\n\tk.Candles = newCandles\n}", "func removeSliceElements(txOuts []*apitypes.AddressTxnOutput, inds []int) []*apitypes.AddressTxnOutput {\n\t// Remove entries from the end to the beginning of the slice.\n\tsort.Slice(inds, func(i, j int) bool { return inds[i] > inds[j] }) // descending indexes\n\tfor _, g := range inds {\n\t\tif g > len(txOuts)-1 {\n\t\t\tcontinue\n\t\t}\n\t\ttxOuts[g] = txOuts[len(txOuts)-1] // overwrite element g with last element\n\t\ttxOuts[len(txOuts)-1] = nil // nil out last element\n\t\ttxOuts = txOuts[:len(txOuts)-1]\n\t}\n\treturn txOuts\n}", "func (a *UnsignedArray) Exclude(min, max int64) {\n\trmin, rmax := a.FindRange(min, max)\n\tif rmin == -1 && rmax == -1 {\n\t\treturn\n\t}\n\n\t// a.Timestamps[rmin] ≥ min\n\t// a.Timestamps[rmax] ≥ max\n\n\tif rmax < a.Len() {\n\t\tif a.Timestamps[rmax] == max {\n\t\t\trmax++\n\t\t}\n\t\trest := a.Len() - rmax\n\t\tif rest > 0 {\n\t\t\tts := a.Timestamps[:rmin+rest]\n\t\t\tcopy(ts[rmin:], a.Timestamps[rmax:])\n\t\t\ta.Timestamps = ts\n\n\t\t\tvs := a.Values[:rmin+rest]\n\t\t\tcopy(vs[rmin:], a.Values[rmax:])\n\t\t\ta.Values = vs\n\t\t\treturn\n\t\t}\n\t}\n\n\ta.Timestamps = a.Timestamps[:rmin]\n\ta.Values = a.Values[:rmin]\n}", "func (ir *IDRing) Clear() {\n\tif ir.locker != nil {\n\t\tir.locker.Lock()\n\t\tdefer ir.locker.Unlock()\n\t}\n\n\tr := Range{Min: ir.OrigMin,\n\t\tMax: ir.OrigMax,\n\t}\n\tir.Ranges = []Range{r}\n\tlog.Tracef(trace.Inside, \"After clear, have %s\\n\", ir)\n}", "func DrawRangeElements(mode uint32, start uint32, end uint32, count int32, xtype uint32, indices unsafe.Pointer) {\n\tsyscall.Syscall6(gpDrawRangeElements, 6, uintptr(mode), uintptr(start), uintptr(end), uintptr(count), uintptr(xtype), uintptr(indices))\n}", "func TestMultiRangeEmptyAfterTruncate(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\ts, db := setupMultipleRanges(t, \"c\", \"d\")\n\tdefer s.Stop()\n\n\t// Delete the keys within a transaction. Implicitly, the intents are\n\t// resolved via ResolveIntentRange upon completion.\n\tif err := db.Txn(func(txn *client.Txn) error {\n\t\tb := &client.Batch{}\n\t\tb.DelRange(\"a\", \"b\")\n\t\tb.DelRange(\"e\", \"f\")\n\t\tb.DelRange(keys.LocalMax, roachpb.KeyMax)\n\t\treturn txn.CommitInBatch(b)\n\t}); err != nil {\n\t\tt.Fatalf(\"unexpected error on transactional DeleteRange: %s\", err)\n\t}\n}", "func (r *batchRangeVectorIterator) popBack(newStart int64) {\n\t// possible improvement: if there is no overlap we can just remove all.\n\tfor fp := range r.window {\n\t\tlastPoint := 0\n\t\tremove := false\n\t\tfor i, p := range r.window[fp].Points {\n\t\t\tif p.T <= newStart {\n\t\t\t\tlastPoint = i\n\t\t\t\tremove = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif remove {\n\t\t\tr.window[fp].Points = r.window[fp].Points[lastPoint+1:]\n\t\t}\n\t\tif len(r.window[fp].Points) == 0 {\n\t\t\ts := r.window[fp]\n\t\t\tdelete(r.window, fp)\n\t\t\tputSeries(s)\n\t\t}\n\t}\n}", "func (s *FrontendServer) RangeDel(ctx context.Context, req *pb.RangeRequest) (*pb.EmptyRes, error) {\n\tvar err error\n\tvar returnErr error = nil\n\tvar returnRes = &pb.EmptyRes{}\n\tstartKey := req.GetStart()\n\tendKey := req.GetEnd()\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\tswitch req.GetType() {\n\tcase utils.LocalData:\n\t\tif startKey > endKey {\n\t\t\treturn returnRes, fmt.Errorf(\"Range Del over local data failed: start > end\")\n\t\t}\n\t\t_, err = s.localSt.Delete(ctx, startKey, clientv3.WithRange(endKey)) // use the key itself, no hashes used\n\t\treturn returnRes, err\n\tcase utils.GlobalData:\n\t\t// keys are assumed to be already hashed\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\tif startKey > endKey {\n\t\t\t// delete keys in ranges: [startKey, MaxID) + MaxID + [0, endKey)\n\t\t\t// because etcd does not have knowledge of the ring and start must be < end for each range request\n\t\t\tend1 := s.gateway.MaxID()\n\t\t\tstart2 := s.gateway.ZeroID()\n\t\t\t_, err = s.globalSt.Delete(ctx, startKey, clientv3.WithRange(end1))\n\t\t\tif returnErr = checkError(err); returnErr != nil {\n\t\t\t\treturn returnRes, status.Errorf(codes.Unknown, \"Range Del failed with error: %v\", returnErr)\n\t\t\t}\n\t\t\t_, err = s.globalSt.Delete(ctx, end1)\n\t\t\tif returnErr = checkError(err); returnErr != nil {\n\t\t\t\treturn returnRes, status.Errorf(codes.Unknown, \"Range Del failed with error: %v\", returnErr)\n\t\t\t}\n\t\t\t_, err = s.globalSt.Delete(ctx, start2, clientv3.WithRange(endKey))\n\t\t\tif returnErr = checkError(err); returnErr != nil {\n\t\t\t\treturn returnRes, status.Errorf(codes.Unknown, \"Range Del failed with error: %v\", returnErr)\n\t\t\t}\n\t\t} else {\n\t\t\t_, err = s.globalSt.Delete(ctx, startKey, clientv3.WithRange(endKey))\n\t\t\tif returnErr = checkError(err); returnErr != nil {\n\t\t\t\treturn returnRes, status.Errorf(codes.Unknown, \"Range Del failed with error: %v\", returnErr)\n\t\t\t}\n\t\t}\n\t}\n\treturn returnRes, nil\n}", "func (a *IntegerArray) Exclude(min, max int64) {\n\trmin, rmax := a.FindRange(min, max)\n\tif rmin == -1 && rmax == -1 {\n\t\treturn\n\t}\n\n\t// a.Timestamps[rmin] ≥ min\n\t// a.Timestamps[rmax] ≥ max\n\n\tif rmax < a.Len() {\n\t\tif a.Timestamps[rmax] == max {\n\t\t\trmax++\n\t\t}\n\t\trest := a.Len() - rmax\n\t\tif rest > 0 {\n\t\t\tts := a.Timestamps[:rmin+rest]\n\t\t\tcopy(ts[rmin:], a.Timestamps[rmax:])\n\t\t\ta.Timestamps = ts\n\n\t\t\tvs := a.Values[:rmin+rest]\n\t\t\tcopy(vs[rmin:], a.Values[rmax:])\n\t\t\ta.Values = vs\n\t\t\treturn\n\t\t}\n\t}\n\n\ta.Timestamps = a.Timestamps[:rmin]\n\ta.Values = a.Values[:rmin]\n}", "func (f FileURL) ClearRange(ctx context.Context, offset int64, count int64) (*FileUploadRangeResponse, error) {\n\tif count <= 0 {\n\t\treturn nil, errors.New(\"invalid argument, count cannot be CountToEnd, and must be > 0\")\n\t}\n\n\treturn f.fileClient.UploadRange(ctx, *toRange(offset, count), FileRangeWriteClear, 0, nil, nil, nil)\n}", "func (r ShardTimeRanges) Subtract(other ShardTimeRanges) {\n\tfor shard, ranges := range r {\n\t\totherRanges, ok := other[shard]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tsubtractedRanges := ranges.RemoveRanges(otherRanges)\n\t\tif subtractedRanges.IsEmpty() {\n\t\t\tdelete(r, shard)\n\t\t} else {\n\t\t\tr[shard] = subtractedRanges\n\t\t}\n\t}\n}", "func (b *Blob) ClearRange(blobRange BlobRange, options *PutPageOptions) error {\n\treturn b.modifyRange(blobRange, nil, options)\n}", "func (this *ViewScanner) MergeRange(newRange *ViewRange) {\n\tlog.Printf(\"considering new range %v\", newRange)\n\tfor _, r := range this.ranges {\n\t\t// if the new range is a subset of an existing range\n\t\t// this new ragne replaces it\n\t\tif newRange.IsSubsetOf(r) {\n\t\t\tlog.Printf(\"new is subset, shrinking\")\n\t\t\tr.Start = newRange.Start\n\t\t\tr.End = newRange.End\n\t\t\treturn\n\t\t}\n\n\t\tif r.IsSubsetOf(newRange) {\n\t\t\tlog.Printf(\"old subset, dropping\")\n\t\t\t// drop this factor\n\t\t\t// we already have a stricter range that contains it\n\t\t\treturn\n\t\t}\n\t}\n\n\tlog.Printf(\"couldn't merge, so add\")\n\t// if we got here, we add it as a new range\n\tthis.ranges = append(this.ranges, newRange)\n}", "func (a *TimestampArray) Exclude(min, max int64) {\n\trmin, rmax := a.FindRange(min, max)\n\tif rmin == -1 && rmax == -1 {\n\t\treturn\n\t}\n\n\t// a.Timestamps[rmin] ≥ min\n\t// a.Timestamps[rmax] ≥ max\n\n\tif rmax < a.Len() {\n\t\tif a.Timestamps[rmax] == max {\n\t\t\trmax++\n\t\t}\n\t\trest := a.Len() - rmax\n\t\tif rest > 0 {\n\t\t\tts := a.Timestamps[:rmin+rest]\n\t\t\tcopy(ts[rmin:], a.Timestamps[rmax:])\n\t\t\ta.Timestamps = ts\n\t\t\treturn\n\t\t}\n\t}\n\n\ta.Timestamps = a.Timestamps[:rmin]\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 (a *StringArray) Exclude(min, max int64) {\n\trmin, rmax := a.FindRange(min, max)\n\tif rmin == -1 && rmax == -1 {\n\t\treturn\n\t}\n\n\t// a.Timestamps[rmin] ≥ min\n\t// a.Timestamps[rmax] ≥ max\n\n\tif rmax < a.Len() {\n\t\tif a.Timestamps[rmax] == max {\n\t\t\trmax++\n\t\t}\n\t\trest := a.Len() - rmax\n\t\tif rest > 0 {\n\t\t\tts := a.Timestamps[:rmin+rest]\n\t\t\tcopy(ts[rmin:], a.Timestamps[rmax:])\n\t\t\ta.Timestamps = ts\n\n\t\t\tvs := a.Values[:rmin+rest]\n\t\t\tcopy(vs[rmin:], a.Values[rmax:])\n\t\t\ta.Values = vs\n\t\t\treturn\n\t\t}\n\t}\n\n\ta.Timestamps = a.Timestamps[:rmin]\n\ta.Values = a.Values[:rmin]\n}", "func fillup(array []byte, endIndex, startIndex int) []byte {\n\n\tfor tmp := startIndex; tmp < endIndex; tmp++ {\n\t\tarray[tmp] = byte(0)\n\t}\n\treturn array\n}", "func (r *Rope) EraseAt(point, n int) (err error) {\n\tif point > r.runes {\n\t\tpoint = r.runes\n\t}\n\tif n >= r.runes-point {\n\t\tn = r.runes - point\n\t}\n\tvar k *knot\n\ts := skiplist{r: r}\n\tif k, err = s.find2(point); err != nil {\n\t\treturn err\n\t}\n\ts.del(k, n)\n\treturn nil\n}", "func (b *logEventBuffer) normalRange(start, end int) (int, int) {\n\tif end < start || end == 0 {\n\t\t// invalid range\n\t\treturn -1, -1\n\t}\n\tsize := b.bufferSize()\n\tif start == 0 {\n\t\t// we reduce start by 1 to make it easier to calculate the index,\n\t\t// but we need to ensure we don't go below 0.\n\t\tstart++\n\t}\n\tif start == end {\n\t\t// ensure we have at least one block in range\n\t\tend++\n\t}\n\tif end-start > size {\n\t\t// ensure we don't have more than the buffer size\n\t\tstart = (end - size) + 1\n\t}\n\tstart = (start - 1) % size\n\tend = end % size\n\n\treturn start, end\n}", "func RangeSlice(start, stop int) []int {\n\tif start > stop {\n\t\tpanic(\"Slice ends before it started\")\n\t}\n\txs := make([]int, stop-start)\n\tfor i := 0; i < len(xs); i++ {\n\t\t// xs[i] = i + 1 + start\n\t\txs[i] = i + start\n\t}\n\treturn xs\n}", "func (a *BooleanArray) Exclude(min, max int64) {\n\trmin, rmax := a.FindRange(min, max)\n\tif rmin == -1 && rmax == -1 {\n\t\treturn\n\t}\n\n\t// a.Timestamps[rmin] ≥ min\n\t// a.Timestamps[rmax] ≥ max\n\n\tif rmax < a.Len() {\n\t\tif a.Timestamps[rmax] == max {\n\t\t\trmax++\n\t\t}\n\t\trest := a.Len() - rmax\n\t\tif rest > 0 {\n\t\t\tts := a.Timestamps[:rmin+rest]\n\t\t\tcopy(ts[rmin:], a.Timestamps[rmax:])\n\t\t\ta.Timestamps = ts\n\n\t\t\tvs := a.Values[:rmin+rest]\n\t\t\tcopy(vs[rmin:], a.Values[rmax:])\n\t\t\ta.Values = vs\n\t\t\treturn\n\t\t}\n\t}\n\n\ta.Timestamps = a.Timestamps[:rmin]\n\ta.Values = a.Values[:rmin]\n}", "func UintRange(items UintIterator, handlers ...UintHandler) error {\n\treturn UintDiscard(UintHandling(items, handlers...))\n}", "func (p *SliceOfMap) Drop(indices ...int) ISlice {\n\tif p == nil || len(*p) == 0 {\n\t\treturn p\n\t}\n\n\t// Handle index manipulation\n\ti, j, err := absIndices(len(*p), indices...)\n\tif err != nil {\n\t\treturn p\n\t}\n\n\t// Execute\n\tn := j - i\n\tif i+n < len(*p) {\n\t\t*p = append((*p)[:i], (*p)[i+n:]...)\n\t} else {\n\t\t*p = (*p)[:i]\n\t}\n\treturn p\n}", "func (r *runestring) Del(pos ...int) {\n\tfor _, i := range pos {\n\t\tif i >= 0 && i <= len(*r) {\n\t\t\t*r = append((*r)[:i], (*r)[i+1:]...)\n\t\t}\n\t}\n}", "func DrawRangeElements(mode uint32, start uint32, end uint32, count int32, xtype uint32, indices unsafe.Pointer) {\n C.glowDrawRangeElements(gpDrawRangeElements, (C.GLenum)(mode), (C.GLuint)(start), (C.GLuint)(end), (C.GLsizei)(count), (C.GLenum)(xtype), indices)\n}", "func Erase(seq Sequence, offset, length int) Sequence {\n\tf := Or(Key(\"source\"), Not(Within(offset, offset+length)))\n\tff := seq.Features().Filter(f)\n\tseq = WithFeatures(seq, ff)\n\treturn Delete(seq, offset, length)\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 (wb *WriteBatch) DeleteRangeCF(cf *ColumnFamilyHandle, beginKey, endKey []byte) {\n\tcBeginKey := bytesToChar(beginKey)\n\tcEndKey := bytesToChar(endKey)\n\tC.rocksdb_writebatch_delete_range_cf(wb.c, cf.c, cBeginKey, C.size_t(len(beginKey)), cEndKey, C.size_t(len(endKey)))\n}", "func (rg Range) Union(r Range) Range {\n\tif rg.Max.X < r.Max.X {\n\t\trg.Max.X = r.Max.X\n\t}\n\tif rg.Max.Y < r.Max.Y {\n\t\trg.Max.Y = r.Max.Y\n\t}\n\tif rg.Min.X > r.Min.X {\n\t\trg.Min.X = r.Min.X\n\t}\n\tif rg.Min.Y > r.Min.Y {\n\t\trg.Min.Y = r.Min.Y\n\t}\n\treturn rg\n}", "func discardLowerRange(data []float64, k int) []float64 {\n\tout := make([]float64, len(data)-k)\n\ti := 0\n\n\t// discard values lower than the desired range\n\tfor k > 0 {\n\t\tlows, pivotValue, highs := partition(data)\n\n\t\tlowLength := len(lows)\n\t\tif lowLength > k {\n\t\t\t// keep all the highs and the pivot\n\t\t\tout[i] = pivotValue\n\t\t\ti++\n\t\t\tcopy(out[i:], highs)\n\t\t\ti += len(highs)\n\t\t\t// iterate over the lows again\n\t\t\tdata = lows\n\t\t} else {\n\t\t\t// discard all the lows\n\t\t\tdata = highs\n\t\t\tk -= lowLength\n\t\t\tif k == 0 {\n\t\t\t\t// if discarded enough lows, keep the pivot\n\t\t\t\tout[i] = pivotValue\n\t\t\t\ti++\n\t\t\t} else {\n\t\t\t\t// able to discard the pivot too\n\t\t\t\tk--\n\t\t\t}\n\t\t}\n\t}\n\tcopy(out[i:], data)\n\treturn out\n}", "func (a *FloatArray) Exclude(min, max int64) {\n\trmin, rmax := a.FindRange(min, max)\n\tif rmin == -1 && rmax == -1 {\n\t\treturn\n\t}\n\n\t// a.Timestamps[rmin] ≥ min\n\t// a.Timestamps[rmax] ≥ max\n\n\tif rmax < a.Len() {\n\t\tif a.Timestamps[rmax] == max {\n\t\t\trmax++\n\t\t}\n\t\trest := a.Len() - rmax\n\t\tif rest > 0 {\n\t\t\tts := a.Timestamps[:rmin+rest]\n\t\t\tcopy(ts[rmin:], a.Timestamps[rmax:])\n\t\t\ta.Timestamps = ts\n\n\t\t\tvs := a.Values[:rmin+rest]\n\t\t\tcopy(vs[rmin:], a.Values[rmax:])\n\t\t\ta.Values = vs\n\t\t\treturn\n\t\t}\n\t}\n\n\ta.Timestamps = a.Timestamps[:rmin]\n\ta.Values = a.Values[:rmin]\n}", "func (c *Client) Remove(ipRange string) error {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tlow, high, err := parseRange(ipRange, \"\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx := c.rdb.TxPipeline()\n\n\tbelow, inside, above, err := c.vicinity(low, high, 1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, bnd := range inside {\n\t\tbnd.Remove(tx)\n\t}\n\n\tbelowNearest := below[0]\n\taboveNearest := above[0]\n\n\tbelowCut := low.Below()\n\tbelowCut.SetUpperBound()\n\tbelowCut.Reason = belowNearest.Reason\n\n\taboveCut := high.Above()\n\taboveCut.SetUpperBound()\n\taboveCut.Reason = aboveNearest.Reason\n\n\tif belowNearest.IsLowerBound() {\n\t\t// need to cut below\n\t\tif !belowNearest.EqualIP(belowCut) {\n\t\t\t// can cut\n\t\t\tbelowCut.Insert(tx)\n\t\t} else {\n\t\t\t// cannot cut\n\t\t\tbelowNearest.SetDoubleBound()\n\t\t\tbelowNearest.Insert(tx)\n\t\t}\n\t}\n\n\tif aboveNearest.IsUpperBound() {\n\t\t// need to cut above\n\t\tif !aboveNearest.EqualIP(aboveCut) {\n\t\t\t// can cut above\n\t\t\taboveCut.Insert(tx)\n\t\t} else {\n\t\t\t// cannot cut above\n\t\t\taboveNearest.SetDoubleBound()\n\t\t\taboveNearest.Insert(tx)\n\n\t\t}\n\t}\n\n\t_, err = tx.Exec()\n\treturn err\n}", "func (d *Deque[T]) EraseAt(pos int) {\n\tif pos < 0 || pos >= d.size {\n\t\treturn\n\t}\n\tseg, pos := d.pos(pos)\n\td.segmentAt(seg).eraseAt(pos)\n\tif seg < d.size-seg-1 {\n\t\tfor i := seg; i > 0; i-- {\n\t\t\tcur := d.segmentAt(i)\n\t\t\tpre := d.segmentAt(i - 1)\n\t\t\tcur.pushFront(pre.popBack())\n\t\t}\n\t\tif d.firstSegment().empty() {\n\t\t\td.putToPool(d.firstSegment())\n\t\t\td.segs[d.begin] = nil\n\t\t\td.begin = d.nextIndex(d.begin)\n\t\t\td.shrinkIfNeeded()\n\t\t}\n\t} else {\n\t\tfor i := seg; i < d.segUsed()-1; i++ {\n\t\t\tcur := d.segmentAt(i)\n\t\t\tnext := d.segmentAt(i + 1)\n\t\t\tcur.pushBack(next.popFront())\n\t\t}\n\t\tif d.lastSegment().empty() {\n\t\t\td.putToPool(d.lastSegment())\n\t\t\td.segs[d.preIndex(d.end)] = nil\n\t\t\td.end = d.preIndex(d.end)\n\t\t\td.shrinkIfNeeded()\n\t\t}\n\t}\n\td.size--\n}", "func (mr *MockMutableListMockRecorder) RemoveRange(min, max interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RemoveRange\", reflect.TypeOf((*MockMutableList)(nil).RemoveRange), min, max)\n}", "func DrawRangeElements(mode uint32, start uint32, end uint32, count int32, xtype uint32, indices unsafe.Pointer) {\n\tC.glowDrawRangeElements(gpDrawRangeElements, (C.GLenum)(mode), (C.GLuint)(start), (C.GLuint)(end), (C.GLsizei)(count), (C.GLenum)(xtype), indices)\n}", "func DrawRangeElements(mode uint32, start uint32, end uint32, count int32, xtype uint32, indices unsafe.Pointer) {\n\tC.glowDrawRangeElements(gpDrawRangeElements, (C.GLenum)(mode), (C.GLuint)(start), (C.GLuint)(end), (C.GLsizei)(count), (C.GLenum)(xtype), indices)\n}", "func discardUpperRange(data []float64, k int) []float64 {\n\tout := make([]float64, len(data)-k)\n\ti := 0\n\n\t// discard values higher than the desired range\n\tfor k > 0 {\n\t\tlows, pivotValue, highs := partition(data)\n\n\t\thighLength := len(highs)\n\t\tif highLength > k {\n\t\t\t// keep all the lows and the pivot\n\t\t\tout[i] = pivotValue\n\t\t\ti++\n\t\t\tcopy(out[i:], lows)\n\t\t\ti += len(lows)\n\t\t\t// iterate over the highs again\n\t\t\tdata = highs\n\t\t} else {\n\t\t\t// discard all the highs\n\t\t\tdata = lows\n\t\t\tk -= highLength\n\t\t\tif k == 0 {\n\t\t\t\t// if discarded enough highs, keep the pivot\n\t\t\t\tout[i] = pivotValue\n\t\t\t\ti++\n\t\t\t} else {\n\t\t\t\t// able to discard the pivot too\n\t\t\t\tk--\n\t\t\t}\n\t\t}\n\t}\n\tcopy(out[i:], data)\n\treturn out\n}", "func (s *SkipList) Range(from, to interface{}) Iterator {\n\tstart := s.getPath(s.header, nil, from)\n\treturn &rangeIterator{\n\t\titer: iter{\n\t\t\tcurrent: &snode{\n\t\t\t\tforward: []*snode{start},\n\t\t\t\tbackward: start,\n\t\t\t},\n\t\t\tlist: s,\n\t\t},\n\t\tupperLimit: to,\n\t\tlowerLimit: from,\n\t}\n}", "func (vuuo *VacUserUpdateOne) ClearRangeKey() *VacUserUpdateOne {\n\tvuuo.mutation.ClearRangeKey()\n\treturn vuuo\n}", "func releaseOverflowPages(\n\tlist regionList,\n\tmaxPages uint, endMarker PageID,\n) (regionList, uint) {\n\toverflowStart, overflowEnd := PageID(maxPages), endMarker\n\tif maxPages == 0 || overflowStart >= overflowEnd {\n\t\treturn list, 0\n\t}\n\n\tvar freed uint\n\tfor i := len(list) - 1; i != -1; i-- {\n\t\tstart, end := list[i].Range()\n\t\tif end < overflowEnd {\n\t\t\tbreak\n\t\t}\n\n\t\tif start < overflowStart {\n\t\t\t// split\n\t\t\tlist[i].count = uint32(overflowStart - start)\n\t\t\tfreed += uint(end - overflowStart)\n\t\t\toverflowEnd = overflowStart\n\t\t} else {\n\t\t\t// remove range\n\t\t\toverflowEnd = start\n\t\t\tfreed += uint(list[i].count)\n\t\t\tlist = list[:i]\n\t\t}\n\t}\n\n\tif len(list) == 0 {\n\t\tlist = nil\n\t}\n\treturn list, freed\n}", "func remove(slice []int, i int) []int {\n // copy(dst, src)\n copy(slice[i:], slice[i+1:]) // over writes the slice from i to end with slice from i+1 to end\n return slice[:len(slice)-1]\n}", "func (rbst *RBSTAbelGroup) Erase(root *Node, start, stop int) *Node {\r\n\tx, _, z := rbst.Split3ByRank(root, start, stop)\r\n\treturn rbst.Merge(x, z)\r\n}", "func (seg *Segmenter) TrimWithPos(se []SegPos, pos ...string) (re []SegPos) {\n\tfor h := 0; h < len(pos); h++ {\n\t\tif h > 0 {\n\t\t\tse = re\n\t\t\tre = nil\n\t\t}\n\n\t\tfor i := 0; i < len(se); i++ {\n\t\t\tif se[i].Pos != pos[h] {\n\t\t\t\tre = append(re, se[i])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func makeEmptyRange() IntRange {\n\treturn IntRange{big.NewInt(+1), big.NewInt(-1)}\n}", "func delete(array []int8, pos int) []int8 {\r\n\tvar length = len(array)\r\n\tvar tempArray = make([]int8, length+1)\r\n\tfmt.Printf(\"\\n\")\r\n\tfor i := 0; i < length; i++ {\r\n\t\tif i < pos {\r\n\t\t\ttempArray[i] = array[i]\r\n\t\t} else {\r\n\t\t\ttempArray[i-1] = array[i]\r\n\t\t}\r\n\t}\r\n\treturn tempArray\r\n\r\n}", "func (seg *Segmenter) TrimPos(s []SegPos) (r []SegPos) {\n\tfor i := 0; i < len(s); i++ {\n\t\tsi := FilterSymbol(s[i].Text)\n\t\tif !seg.NotStop && seg.IsStop(si) {\n\t\t\tsi = \"\"\n\t\t}\n\n\t\tif si != \"\" {\n\t\t\tr = append(r, s[i])\n\t\t}\n\t}\n\n\treturn\n}", "func RemoveFromSlice(slice []int, s int) []int {\n\treturn append(slice[:s], slice[s+1:]...)\n}", "func (s *IPSet) Ranges() []IPRange {\n\tvar points []point\n\tfor _, r := range s.in {\n\t\tpoints = append(points, point{r.From, true, true}, point{r.To, true, false})\n\t}\n\tfor _, r := range s.out {\n\t\tpoints = append(points, point{r.From, false, true}, point{r.To, false, false})\n\t}\n\tsort.Slice(points, func(i, j int) bool { return points[i].Less(points[j]) })\n\tconst debug = false\n\tif debug {\n\t\tdebugf(\"post-sort:\")\n\t\tdebugLogPoints(points)\n\t\tdebugf(\"merging...\")\n\t}\n\n\t// Now build 'want', like points but with \"remove\" ranges removed\n\t// and adjancent blocks merged, and all elements alternating between\n\t// start and end.\n\twant := points[:0]\n\tvar addDepth, removeDepth int\n\tfor i, p := range points {\n\t\tdepth := &addDepth\n\t\tif !p.want {\n\t\t\tdepth = &removeDepth\n\t\t}\n\t\tif p.start {\n\t\t\t*depth++\n\t\t} else {\n\t\t\t*depth--\n\t\t}\n\t\tif debug {\n\t\t\tdebugf(\"at[%d] (%+v), add=%v, remove=%v\", i, p, addDepth, removeDepth)\n\t\t}\n\t\tif p.start && *depth != 1 {\n\t\t\tcontinue\n\t\t}\n\t\tif !p.start && *depth != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif !p.want && addDepth > 0 {\n\t\t\tif p.start {\n\t\t\t\t// If we're transitioning from a range of\n\t\t\t\t// addresses we want to ones we don't, insert\n\t\t\t\t// an end marker for the IP before the one we\n\t\t\t\t// don't.\n\t\t\t\twant = append(want, point{\n\t\t\t\t\tip: p.ip.Prior(),\n\t\t\t\t\twant: true,\n\t\t\t\t\tstart: false,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\twant = append(want, point{\n\t\t\t\t\tip: p.ip.Next(),\n\t\t\t\t\twant: true,\n\t\t\t\t\tstart: true,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif !p.want || removeDepth > 0 {\n\t\t\tcontinue\n\t\t}\n\t\t// Merge adjacent ranges. Remove prior and skip this\n\t\t// start.\n\t\tif p.start && len(want) > 0 {\n\t\t\tprior := &want[len(want)-1]\n\t\t\tif !prior.start && prior.ip == p.ip.Prior() {\n\t\t\t\twant = want[:len(want)-1]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\twant = append(want, p)\n\t}\n\tif debug {\n\t\tdebugf(\"post-merge:\")\n\t\tdebugLogPoints(want)\n\t}\n\n\tif len(want)%2 == 1 {\n\t\tpanic(\"internal error; odd number\")\n\t}\n\n\tout := make([]IPRange, 0, len(want)/2)\n\tfor i := 0; i < len(want); i += 2 {\n\t\tif !want[i].want {\n\t\t\tpanic(\"internal error; non-want in range\")\n\t\t}\n\t\tif !want[i].start {\n\t\t\tpanic(\"internal error; odd not start\")\n\t\t}\n\t\tif want[i+1].start {\n\t\t\tpanic(\"internal error; even not end\")\n\t\t}\n\t\tout = append(out, IPRange{\n\t\t\tFrom: want[i].ip,\n\t\t\tTo: want[i+1].ip,\n\t\t})\n\t}\n\treturn out\n}", "func (ingest *Ingestion) Clear(start int64, end int64) error {\n\tclear := ingest.DB.DeleteRange\n\n\terr := clear(start, end, \"history_effects\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_operation_participants\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_operations\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_transaction_participants\", \"history_transaction_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_transactions\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_ledgers\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = clear(start, end, \"history_trades\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *Range) Unshare() {\n\t//log.Println(\"Calling Range.Unshare()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"Range\", \"unshare\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}", "func DeleteWithRange(config *EtcdConfig, key string, endKey string) (int, error) {\n\tindex, client, err := getClient(config)\n\tif err != nil {\n\t\tfmt.Println(\"put action failed\")\n\t\treturn 0, err\n\t}\n\tKV := client.KV\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\tr, err := KV.Delete(ctx, key, clientv3.WithRange(endKey))\n\tif err != nil {\n\t\t_ = closeClient(index)\n\t\treturn 0, err\n\t}\n\tfmt.Println(\"delete action succeed\")\n\tres := int(r.Deleted)\n\treturn res, nil\n}", "func mergeRanges(input []rng, limit int64) []rng {\n\tif len(input) == 0 {\n\t\treturn input\n\t}\n\n\tlast := 0\n\tfor ix := 1; ix < len(input); ix++ {\n\t\tif (input[ix].start - input[last].end) <= limit {\n\t\t\tinput[last].end = input[ix].end\n\t\t} else {\n\t\t\tlast++\n\t\t\tinput[last] = input[ix]\n\t\t}\n\t}\n\treturn input[:last+1]\n}", "func rangeFinalizer(r *Range) {\n\truntime.SetFinalizer(r, func(r *Range) { gobject.Unref(r) })\n}", "func (s *ShapeIndexRegion) coverRange(first, last CellID, cellIDs []CellID) []CellID {\n\t// The range consists of a single index cell.\n\tif first == last {\n\t\treturn append(cellIDs, first)\n\t}\n\n\t// Add the lowest common ancestor of the given range.\n\tlevel, ok := first.CommonAncestorLevel(last)\n\tif !ok {\n\t\treturn append(cellIDs, CellID(0))\n\t}\n\treturn append(cellIDs, first.Parent(level))\n}" ]
[ "0.67175895", "0.6479833", "0.6460482", "0.6366479", "0.6345222", "0.6323083", "0.62983894", "0.6280757", "0.6280757", "0.6258515", "0.62546563", "0.6234751", "0.6232918", "0.62181437", "0.6175153", "0.6166219", "0.6105894", "0.593791", "0.592265", "0.5890555", "0.5879061", "0.5868366", "0.58374286", "0.58348817", "0.5778346", "0.57505554", "0.5697416", "0.5683198", "0.56702256", "0.56477493", "0.5634326", "0.5591701", "0.5587171", "0.5578993", "0.5576525", "0.5567651", "0.5548728", "0.55441487", "0.5522283", "0.5517597", "0.55086684", "0.5504276", "0.550056", "0.54995996", "0.5485033", "0.5458504", "0.5443773", "0.54405636", "0.5430725", "0.5394355", "0.5371954", "0.53705", "0.53478324", "0.53293675", "0.5320172", "0.5319372", "0.528924", "0.52799386", "0.52581155", "0.5236362", "0.5206411", "0.5189703", "0.5168351", "0.5158447", "0.5154645", "0.5153368", "0.5143167", "0.5140512", "0.51368296", "0.5135443", "0.5130226", "0.51000875", "0.50954044", "0.5095384", "0.50908417", "0.50896794", "0.5071805", "0.5069108", "0.5066207", "0.50658876", "0.5063127", "0.5063127", "0.5061521", "0.5057881", "0.50522727", "0.5045675", "0.50331724", "0.50032383", "0.4998192", "0.49829572", "0.49808085", "0.4978495", "0.4977605", "0.49665478", "0.4966408", "0.4947998", "0.49356797", "0.4927291", "0.49225754", "0.49217007" ]
0.7792587
0
Clear erases all elements in the deque
func (d *Deque[T]) Clear() { d.EraseRange(0, d.size) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Deque) Clear() {\n\tq.front = 0\n\tq.back = 0\n\tq.size = 0\n}", "func (q *Queue) Clear() {\n\tq.items = []Lit{}\n}", "func (queue *Queue) Clear() {\n\tqueue.data = queue.data[:0]\n}", "func (rb *RingBuffer[T]) Clear() {\n\trb.mu.Lock()\n\tdefer rb.mu.Unlock()\n\trb.pos = 0\n\trb.buf = nil\n}", "func (dq *Dqueue) Clear() {\n\tdq.dqueue.Clear()\n}", "func (entry *ElementEntry) Clear() {\n\tif entry.IsEmpty() {\n\t\tfmt.Print(\"this queue is empty,which don/'t need to clear\")\n\t\treturn\n\t}\n\n\tentry.elementSlice = nil\n}", "func (s *PriorityQueue) Clear() {\n\ts.pq.array = nil\n}", "func (q *Queue) Clear() []interface{} {\r\n\tel, l := q.clear()\r\n\telems := make([]interface{}, l)\r\n\tfor i := 0; el != nil; i++ {\r\n\t\telems[i] = el.v\r\n\t\tel = el.next\r\n\t}\r\n\treturn elems\r\n}", "func (r *Ring) Clear() {\n\tr.size, r.in, r.out = 0, 0, 0\n}", "func (list *ArrayList[T]) Clear() {\n\tlist.elems = list.elems[:0]\n}", "func (d *Deque) Reset() {\n\t*d = *New()\n}", "func (list *DoublyLinkedList) Clear() {\n\tlist.size = 0\n\tlist.first = nil\n\tlist.last = nil\n}", "func (q *Stack) Clear() {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tfor {\n\t\tif q.top == nil {\n\t\t\treturn\n\t\t}\n\n\t\tn := q.top\n\t\tq.top = n.below\n\n\t\tif q.top == nil {\n\t\t\tq.bottom = nil\n\t\t}\n\t\tq.count--\n\t}\n}", "func (q *Queue) Reset() {\n\tq.mutex.Lock()\n\tdefer q.mutex.Unlock()\n\n\tq.items = nil\n}", "func (d *Deck) Clear() {\n\td.Cards = []*Card{}\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 (l *list) Clear() {\n\tl.elements = l.elements[:0]\n}", "func (q *Queue) Flush() {\r\n\tel, _ := q.clear()\r\n\r\n\tfor el != nil {\r\n\t\tq.cb(el.v)\r\n\t\tel = el.next\r\n\t}\r\n}", "func (d *Driver) Clear() {\n\tfor i := 0; i < len(d.buff); i++ {\n\t\td.buff[i] = 0\n\t}\n}", "func (q *BytesQueue) Reset() {\n\t// Just reset indexes\n\tq.tail = leftMarginIndex\n\tq.head = leftMarginIndex\n\tq.rightMargin = leftMarginIndex\n\tq.count = 0\n\tq.full = false\n}", "func (list *List) Clear() {\n\tlist.size = 0\n\tlist.first = nil\n\tlist.last = nil\n}", "func (t *T) Clear() {\n\tt.root = nil\n\tt.words = 0\n}", "func (b *messageBuffer) clear() {\n\tb.mu.Lock()\n\tbacklog := b.backlog\n\tb.backlog = nil\n\tb.mu.Unlock()\n\n\tselect {\n\tcase m := <-b.c:\n\t\tm.next()\n\tdefault:\n\t}\n\tfor _, m := range backlog {\n\t\tm.next()\n\t}\n}", "func (list *ArrayList) Clear() {\n\tlist.size = 0\n\tlist.elements = []interface{}{}\n}", "func (t *RbTree[K, V]) Clear() {\n\tt.root = nil\n\tt.size = 0\n}", "func (stack *ArrayStack) Clear() {\n\tstack.list.Clear()\n}", "func (b *Buffer) Clear() {\n\tfor o := range b.Tiles {\n\t\tb.Tiles[o] = nil\n\t}\n}", "func (c *Concurrent) Clear() {\n\tfor {\n\t\tselect {\n\t\tcase <-c.values:\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *RedisQueue) Clear() error {\n\treturn s.r.Del(s.Key()).Err()\n}", "func (il *IntList) Clear() {\n il.first.next = il.last\n il.last.prev = il.first\n il.length = 0\n}", "func (b *baseKVStoreBatch) Clear() {\n\tb.mutex.Lock()\n\tdefer b.mutex.Unlock()\n\tb.writeQueue = nil\n}", "func (t *RedBlackTree) Clear() {\n\tt.root = nil\n\tt.min = nil\n\tt.max = nil\n\tt.size = 0\n}", "func (this *LinkedList) Clear() {\n\tthis.head = nil\n\tthis.tail = nil\n\tthis.size = 0\n}", "func (s *StackF64) clear() {\n\tfor i := 0; i < len(s.data); i++ {\n\t\ts.data[i] = 0\n\t}\n}", "func (b *Buffer) Clear() {\n\tb.series = make(map[string]*influxdb.Series)\n\tb.size = 0\n}", "func (s *IntSet) Clear() {\n\ts.elem = make(intSet)\n}", "func (q *QuadTree) Clear() {\n\tq.objects = make([]*Rectangle, 0)\n\tfor _, node := range q.nodes {\n\t\tnode.Clear()\n\t}\n\tq.nodes = make(map[int]*QuadTree, 4)\n}", "func (s *Stack) Clear() {\n\ts.top = nil\n\ts.length = 0\n}", "func (ll *LinkedList) Clear() {\n\tll.start = nil\n\tll.end = nil\n\tll.length = 0\n}", "func (q *PushQueue) Empty() {\n\tq.mutex.Lock()\n\tq.items = make([]interface{}, 0, q.Depth())\n\tq.mutex.Unlock()\n}", "func (item *Item) Clear() {\n\titem.Count = 0\n\titem.Type = Uninitialized\n\tfor i := 0; i < len(item.Data); i++ {\n\t\titem.Data[i] = 0\n\t}\n}", "func (c Collector) Clear() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}", "func (v *IntVec) Clear() {\n\tv.Truncate(0)\n}", "func (v *Data) Clear() {\n\tv.Truncate(0)\n}", "func (set *Set) Clear() {\n\tset.items = make(map[interface{}]struct{})\n}", "func (s *Scheduler) Clear() {\n\tfor i := 0; i < s.size; i++ {\n\t\ts.jobs[i] = nil\n\t}\n\ts.size = 0\n}", "func (s *LinkedStack) Clear() { s.count = 0; s.topPtr = nil }", "func (c *Cache) Clear() {\n\tfor _, bucket := range c.buckets {\n\t\tbucket.clear()\n\t}\n\tc.size = 0\n\tc.list = list.New()\n}", "func (ll *LinkedList) Clear() {\n\tll.Lock()\n\tif ll.size > 0 {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t\tll.size = 0\n\t}\n\tll.Unlock()\n}", "func Clear() {\n\tEvents = make([]Event, 0)\n}", "func (tb *TransactionBuffer) Clear() {\n\ttb.mux.Lock()\n\ttb.Buffer = make([]TxPublish, 0)\n\ttb.mux.Unlock()\n}", "func (ss *SliceStack) Clear() {\n\tss.backer.Clear()\n}", "func (tq *DefaultTaskQueue) Clear() {\n\ttq.queue = make([]Task, 0)\n}", "func (tree *Tree) Clear() {\n\ttree.Root = nil\n\ttree.size = 0\n}", "func (i *IQR) Clear() {\n\ti.quantile.Clear()\n}", "func (set *SetThreadSafe) Clear() {\n\tset = new(SetThreadSafe)\n}", "func (wr *WatchList) Clear() {\n\tfor wr.First(); wr.Remove() != nil; {\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 (q *queue) Drain() {\n\tq.Lock()\n\tdefer q.Unlock()\n\n\tq.head = nil\n\tq.tail = nil\n\n\tq.count = 0\n}", "func (st *Stack) Clear() {\n\tst.lines = nil\n}", "func (p *Prque) Reset() {\n\tp.cont.Reset()\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 Clear() Sequence {\n\treturn New().Clear()\n}", "func (stack *Stack) Clear() {\n\tstack.list.Clear()\n}", "func (p *PinnedView) Clear() {\n\tp.pinnedItems = nil\n}", "func (it iterator) clear(b *ringBuf) {\n\tb.buf[it] = raftpb.Entry{}\n}", "func (ds *DrawStack) Clear() {\n\tfor _, stackable := range ds.as {\n\t\tstackable.Clear()\n\t}\n}", "func (m BoolMemConcurrentMap) Clear() {\n\tfor item := range m.IterBuffered() {\n\t\tm.Remove(item.Key)\n\t}\n}", "func (r *TimeBucketResults) Clear() {\n\tr.buckets = nil\n}", "func (h *MapInt16ToUint8) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (x *Secp256k1N) Clear() {\n\tx.limbs[0] = 0\n\tx.limbs[1] = 0\n\tx.limbs[2] = 0\n\tx.limbs[3] = 0\n\tx.limbs[4] = 0\n}", "func (c *Chunk) Clear() {\n\tc.data = nil\n}", "func (set *Set) Clear() {\n\tset.tree.Clear()\n}", "func (sa *SuffixArray) Clear() error {\n\titer := sa.Iterate(0, sa.Len())\n\tfor iter.Next() {\n\t\titer.SetPosition(placeholder)\n\t}\n\treturn iter.Close()\n}", "func Clear() {\n\tfor i := 0; i < bufferLength; i++ {\n\t\tbuffer[i] = 0x00\n\t}\n}", "func (sp *Space) Clear() {\n\t*sp = make(Space, 0)\n}", "func (c DeferDirCollector) Clear() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}", "func (l *List) Clear() {\n\tl.head = nil\n}", "func (l *CentroidList) Clear() {\n\t*l = (*l)[:0]\n}", "func (arr *FloatArray) Clear() {\n\tnewArr := *arr\n\t*arr = newArr[:0]\n}", "func (l *RandomAccessGroupLookup) Clear() {\n\tl.elements = nil\n\tl.index = make(map[string]*groupLookupElement)\n}", "func (this *HashSet) Clear() {\n\tthis.mmap.Clear()\n}", "func (s *activeSeriesStripe) clear() {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\ts.oldestEntryTs.Store(0)\n\ts.refs = map[uint64][]activeSeriesEntry{}\n\ts.active = 0\n}", "func (s *IntSet) Clear() {\n\ts.words = []uint64{}\n}", "func (NilCounter) Clear() {}", "func (NilCounter) Clear() {}", "func (h *MapInt16ToInt64) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (batch *Batch) Clear() {\n\tbatch.mutex.Lock()\n\tdefer batch.mutex.Unlock()\n\tbatch.messages = batch.messages[0:0]\n}", "func (sr *Stackers) Clear() {\n\tsr.ro.Lock()\n\t{\n\t\tsr.stacks = nil\n\t}\n\tsr.ro.Unlock()\n}", "func (h *MapInt16ToUint64) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (set *IntSet) Clear() {\n\tfor k := range set.members {\n\t\tdelete(set.members, k)\n\t}\n}", "func (s *IntSlicer) Clear() {\n\ts.slice = []int{}\n}", "func (c *AdapterMemory) Clear(ctx context.Context) error {\n\treturn c.data.Clear()\n}", "func (mg *MoveGen) Clear() {\n\tmg.index = 0\n}", "func (c *QueuedChan) flush() {\n\t// Flush queue.\n\tfor elem := c.Front(); nil != elem; elem = c.Front() {\n\t\tc.popc <- elem.Value\n\t\tc.List.Remove(elem)\n\t}\n}", "func (h *MapInt16ToUint) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (t *AATree) Clear() {\n\tt.root = nil\n}", "func (b *Block) Clear() {\n\tif len(b.subelements) > 0 {\n\t\tb.subelements = []*Block{}\n\t\tb.wire = []byte{}\n\t}\n}", "func (s *Streams) Clear() {\n\ts.Buffer.Clear()\n}", "func (ls *ListStack) Clear() {\n\tif ls.threadSafe {\n\t\tls.lock.Lock()\n\t\tdefer ls.lock.Unlock()\n\t\tls.backer.Init()\n\t\treturn\n\t}\n\n\tls.backer.Init()\n}" ]
[ "0.8428637", "0.7742365", "0.74777764", "0.7248668", "0.7228673", "0.721919", "0.70923746", "0.69747627", "0.69600683", "0.6958391", "0.6894317", "0.6854911", "0.68488055", "0.67305595", "0.6728454", "0.6727046", "0.6727025", "0.6690978", "0.66798145", "0.66723216", "0.66340107", "0.6611691", "0.6602131", "0.65997165", "0.6593526", "0.65850836", "0.65563315", "0.65359473", "0.65328044", "0.65290743", "0.65271455", "0.65254444", "0.64819825", "0.6455086", "0.6446217", "0.6445484", "0.64411384", "0.64326036", "0.64004475", "0.63731706", "0.63715535", "0.63650614", "0.63568103", "0.63408303", "0.6331842", "0.6331087", "0.6331006", "0.63288075", "0.6327252", "0.630947", "0.63014334", "0.630067", "0.6300102", "0.6294277", "0.6267077", "0.62658495", "0.62493443", "0.6226908", "0.6220549", "0.6220444", "0.6215573", "0.6182092", "0.61745995", "0.61622244", "0.61466926", "0.6137323", "0.6118985", "0.6111568", "0.6098354", "0.6095052", "0.60926086", "0.60861886", "0.60855764", "0.607616", "0.60692084", "0.6069144", "0.6068032", "0.60634094", "0.6062948", "0.6058583", "0.6057556", "0.605504", "0.6042026", "0.6039794", "0.6030147", "0.6030147", "0.6019288", "0.6018542", "0.6017071", "0.6011553", "0.600003", "0.59967244", "0.5994691", "0.59944457", "0.59934306", "0.599264", "0.5988722", "0.59880584", "0.5987729", "0.5987223" ]
0.8398588
1