doc stringlengths 10 26.3k | code stringlengths 52 3.87M |
|---|---|
//
// Cache
//
// NewLRUCache creates a new Cache that caches content for the given client
// for up to the maximum duration.
//
// See NewCachedClient | func NewLRUCache(
clientID string,
duration time.Duration,
cache *lru.LRUCache) *LRUCache {
return &LRUCache{
ClientID: clientID,
Duration: duration,
DurationSeconds: int64(duration.Seconds()),
Cache: cache,
}
} |
// Set specifies that the given content was retrieved for the given URL at the
// given time. The content for that URL will be available by LRUCache.Get from
// the given 'time' up to 'time + l.Duration' | func (l *LRUCache) Set(url string, time time.Time, content *FantasyContent) {
l.Cache.Set(l.getKey(url, time), &LRUCacheValue{content: content})
} |
// Get the content for the given URL at the given time. | func (l *LRUCache) Get(url string, time time.Time) (content *FantasyContent, ok bool) {
value, ok := l.Cache.Get(l.getKey(url, time))
if !ok {
return nil, ok
}
lruCacheValue, ok := value.(*LRUCacheValue)
if !ok {
return nil, ok
}
return lruCacheValue.content, true
} |
// getKey converts a base key to a key that is unique for the client of the
// LRUCache and the current time period.
//
// The created keys have the following format:
//
// <client-id>:<originalKey>:<period>
//
// Given a client with ID "client-id-01", original key of "key-01", a current
// time of "08/17/2014 1:21p... | func (l *LRUCache) getKey(originalKey string, time time.Time) string {
period := time.Unix() / l.DurationSeconds
return fmt.Sprintf("%s:%s:%d", l.ClientID, originalKey, period)
} |
//
// ContentProvider
// | func (p *cachedContentProvider) Get(url string) (*FantasyContent, error) {
currentTime := time.Now()
content, ok := p.cache.Get(url, currentTime)
if !ok {
content, err := p.delegate.Get(url)
if err == nil {
p.cache.Set(url, currentTime, content)
}
return content, err
}
return content, nil
} |
// fixContent updates the fantasy data with content that can't be unmarshalled
// directly from XML | func fixContent(c *FantasyContent) *FantasyContent {
fixTeam(&c.Team)
for i := range c.League.Teams {
fixTeam(&c.League.Teams[i])
}
for i := range c.League.Standings {
fixTeam(&c.League.Standings[i])
}
for i := range c.League.Players {
fixPoints(&c.League.Players[i].PlayerPoints)
}
for i := range c.League... |
//
// httpAPIClient
//
// Get returns the HTTP response of a GET request to the given URL. | func (o *countingHTTPApiClient) Get(url string) (*http.Response, error) {
o.requestCount++
response, err := o.client.Get(url)
// Known issue where "consumer_key_unknown" is returned for valid
// consumer keys. If this happens, try re-requesting the content a few
// times to see if it fixes itself
//
// See http... |
//
// Yahoo interface
//
// GetFantasyContent directly access Yahoo fantasy resources.
//
// See http://developer.yahoo.com/fantasysports/guide/ for more information | func (c *Client) GetFantasyContent(url string) (*FantasyContent, error) {
return c.Provider.Get(url)
} |
//
// Convenience functions
//
// GetUserLeagues returns a list of the current user's leagues for the given
// year. | func (c *Client) GetUserLeagues(year string) ([]League, error) {
yearKey, ok := YearKeys[year]
if !ok {
return nil, fmt.Errorf("data not available for year=%s", year)
}
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/users;use_login=1/games;game_keys=%s/leagues",
YahooBaseURL,
yearKey))
if err != n... |
// GetPlayersStats returns a list of Players containing their stats for the
// given week in the given year. | func (c *Client) GetPlayersStats(leagueKey string, week int, players []Player) ([]Player, error) {
playerKeys := ""
for index, player := range players {
if index != 0 {
playerKeys += ","
}
playerKeys += player.PlayerKey
}
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/league/%s/players;player_keys... |
// GetTeamRoster returns a team's roster for the given week. | func (c *Client) GetTeamRoster(teamKey string, week int) ([]Player, error) {
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/team/%s/roster;week=%d",
YahooBaseURL,
teamKey,
week))
if err != nil {
return nil, err
}
return content.Team.Roster.Players, nil
} |
// GetAllTeamStats gets teams stats for a given week. | func (c *Client) GetAllTeamStats(leagueKey string, week int) ([]Team, error) {
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/league/%s/teams/stats;type=week;week=%d",
YahooBaseURL,
leagueKey,
week))
if err != nil {
return nil, err
}
return content.League.Teams, nil
} |
// GetTeam returns all available information about the given team. | func (c *Client) GetTeam(teamKey string) (*Team, error) {
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/team/%s;out=stats,metadata,players,standings,roster",
YahooBaseURL,
teamKey))
if err != nil {
return nil, err
}
if content.Team.TeamID == 0 {
return nil, fmt.Errorf("no team returned for key='... |
// GetLeagueMetadata returns the metadata associated with the given league. | func (c *Client) GetLeagueMetadata(leagueKey string) (*League, error) {
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/league/%s/metadata",
YahooBaseURL,
leagueKey))
if err != nil {
return nil, err
}
return &content.League, nil
} |
// GetAllTeams returns all teams playing in the given league. | func (c *Client) GetAllTeams(leagueKey string) ([]Team, error) {
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/league/%s/teams", YahooBaseURL, leagueKey))
if err != nil {
return nil, err
}
return content.League.Teams, nil
} |
// GetMatchupsForWeekRange returns a list of matchups for each week in the
// requested range. | func (c *Client) GetMatchupsForWeekRange(leagueKey string, startWeek, endWeek int) (map[int][]Matchup, error) {
leagueList := strconv.Itoa(startWeek)
for i := startWeek + 1; i <= endWeek; i++ {
leagueList += "," + strconv.Itoa(i)
}
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/league/%s/scoreboard;week=%... |
// List spaces using the provided options.
//
// Librato API docs: http://dev.librato.com/v1/get/spaces | func (s *SpacesService) List(opt *SpaceListOptions) ([]Space, *http.Response, error) {
u, err := urlWithOptions("spaces", opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var spacesResp listSpacesResponse
resp, err := s.clien... |
// Get fetches a space based on the provided ID.
//
// Librato API docs: http://dev.librato.com/v1/get/spaces/:id | func (s *SpacesService) Get(id uint) (*Space, *http.Response, error) {
u, err := urlWithOptions(fmt.Sprintf("spaces/%d", id), nil)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
sp := new(Space)
resp, err := s.client.Do(req, sp)... |
// Create a space with a given name.
//
// Librato API docs: http://dev.librato.com/v1/post/spaces | func (s *SpacesService) Create(space *Space) (*Space, *http.Response, error) {
req, err := s.client.NewRequest("POST", "spaces", space)
if err != nil {
return nil, nil, err
}
sp := new(Space)
resp, err := s.client.Do(req, sp)
if err != nil {
return nil, resp, err
}
return sp, resp, err
} |
// Update a space.
//
// Librato API docs: http://dev.librato.com/v1/put/spaces/:id | func (s *SpacesService) Update(spaceID uint, space *Space) (*http.Response, error) {
u := fmt.Sprintf("spaces/%d", spaceID)
req, err := s.client.NewRequest("PUT", u, space)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
} |
// NewStringLexer creates a new StringLexer instance. This lexer can be
// used only once per input string. Do not try to reuse it | func NewStringLexer(input string, fn LexFn) *StringLexer {
return &StringLexer{
input: input,
inputLength: len(input),
start: 0,
pos: 0,
line: 1,
width: 0,
items: make(chan LexItem, 1),
entryPoint: fn,
}
} |
// Current returns the current rune being considered | func (l *StringLexer) Current() (r rune) {
r, _ = utf8.DecodeRuneInString(l.input[l.pos:])
return r
} |
// Next returns the next rune | func (l *StringLexer) Next() (r rune) {
if l.pos >= l.inputLen() {
l.width = 0
return EOF
}
// if the previous char was a new line, then we're at a new line
if l.pos >= 0 {
if l.input[l.pos] == '\n' {
l.line++
}
}
r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
l.pos += l.width
return r
} |
// Peek returns the next rune, but does not move the position | func (l *StringLexer) Peek() (r rune) {
r = l.Next()
l.Backup()
return r
} |
// Backup moves the cursor position (as many bytes as the last read rune) | func (l *StringLexer) Backup() {
l.pos -= l.width
if l.width == 1 && l.pos >= 0 && l.inputLen() > l.pos {
if l.input[l.pos] == '\n' {
l.line--
}
}
} |
// AcceptString returns true if the given string can be matched exactly.
// This is a utility function to be called from concrete Lexer types | func (l *StringLexer) AcceptString(word string) bool {
return AcceptString(l, word, false)
} |
// PeekString returns true if the given string can be matched exactly,
// but does not move the position | func (l *StringLexer) PeekString(word string) bool {
return AcceptString(l, word, true)
} |
// AcceptRunFunc takes a function, and moves the cursor forward as long as
// the function returns true | func (l *StringLexer) AcceptRunFunc(fn func(r rune) bool) bool {
guard := Mark("AcceptRun")
defer guard()
return AcceptRunFunc(l, fn)
} |
// AcceptRunExcept takes a string, and moves the cursor forward as
// long as the input DOES NOT match one of the given runes in the string | func (l *StringLexer) AcceptRunExcept(valid string) bool {
guard := Mark("AcceptRunExcept")
defer guard()
return AcceptRunExcept(l, valid)
} |
// Grab creates a new Item of type `t`. The value in the item is created
// from the position of the last read item to current cursor position | func (l *StringLexer) Grab(t ItemType) Item {
// special case
str := l.BufferString()
line := l.line
if len(str) > 0 && str[0] == '\n' {
line--
}
return NewItem(t, l.start, line, str)
} |
// Emit creates and sends a new Item of type `t` through the output
// channel. The Item is generated using `Grab` | func (l *StringLexer) Emit(t ItemType) {
l.items <- l.Grab(t)
l.start = l.pos
} |
// BufferString reutrns the string beween LastCursor and Cursor | func (l *StringLexer) BufferString() string {
return l.input[l.start:l.pos]
} |
// convertProcedureStatus maps the status to a code in the required FHIR value set:
// http://hl7.org/fhir/DSTU2/valueset-procedure-status.html | func (p *Procedure) convertProcedureStatus() string {
var status string
statusConcept := p.StatusCode.FHIRCodeableConcept("")
switch {
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "aborted"):
status = "aborted"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStat... |
// convertProcedureRequestStatus maps the status to a code in the required FHIR value set:
// http://hl7.org/fhir/DSTU2/valueset-procedure-request-status.html | func (p *Procedure) convertProcedureRequestStatus() string {
var status string
statusConcept := p.StatusCode.FHIRCodeableConcept("")
switch {
case p.NegationInd == true:
status = "rejected"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "cancelled"):
status = "rejected"
case statu... |
// NewItem creates a new Item | func NewItem(t ItemType, pos int, line int, v string) Item {
return Item{t, pos, line, v}
} |
// String returns the string representation of the Item | func (l Item) String() string {
return fmt.Sprintf("%s (%q)", l.typ, l.val)
} |
// convertStatus maps the status to a code in the required FHIR value set:
// http://hl7.org/fhir/DSTU2/valueset-encounter-state.html
// If the status cannot be reliably mapped, "finished" will be assumed. Note that this code is
// built to handle even some statuses that HDS does not currently return (active, cancel... | func (e *Encounter) convertStatus() string {
var status string
statusConcept := e.StatusCode.FHIRCodeableConcept("")
switch {
// Negated encounters are rare, but if we run into one, call it cancelled
case e.NegationInd:
status = "cancelled"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStat... |
// Async Send mail message | func (s *SesMailer) SendAsync(to, subject, htmlbody string) {
go func() {
if err := s.SendMail(to, subject, htmlbody); err != nil {
beego.Error(fmt.Sprintf("Async send email not send emails: %s", err))
}
}()
} |
/*
Dialect: RandomInt
*/ | func RandomBuiltinFunc() string {
d := orm.NewOrm().Driver()
if d.Type() == orm.DR_Oracle {
return "dbms_random.value(1,100000)"
} else if d.Type() == orm.DR_MySQL {
return "RAND()"
} else {
return "RANDOM()"
}
} |
// MustCompile parses a regular expression and panic if str can not parsed.
// This compatible with regexp.MustCompile but this uses a cache. | func MustCompile(str string) *regexp.Regexp {
re, err := regexpContainer.Get(str)
if err != nil {
// regexp.MustCompile() like message
panic(`regexpcache: Compile(` + quote(str) + `): ` + err.Error())
}
return re
} |
// MustCompilePOSIX parses a regular expression with POSIX ERE syntax and panic if str can not parsed.
// This compatible with regexp.MustCompilePOSIX but this uses a cache. | func MustCompilePOSIX(str string) *regexp.Regexp {
re, err := posixContainer.Get(str)
if err != nil {
// regexp.MustCompilePOSIX() like message
panic(`regexpcache: CompilePOSIX(` + quote(str) + `): ` + err.Error())
}
return re
} |
// Match checks whether a textual regular expression matches a byte slice.
// This compatible with regexp.Match but this uses a cache. | func Match(pattern string, b []byte) (matched bool, err error) {
re, err := Compile(pattern)
if err != nil {
return false, err
}
return re.Match(b), nil
} |
// Match checks whether a textual regular expression matches the RuneReader.
// This compatible with regexp.MatchReader but this uses a cache. | func MatchReader(pattern string, r io.RuneReader) (matched bool, err error) {
re, err := Compile(pattern)
if err != nil {
return false, err
}
return re.MatchReader(r), nil
} |
// simple doubling back-off | func createBackoff(retryIn, maxBackOff time.Duration) func() {
return func() {
log.Debugf("backoff called. will retry in %s.", retryIn)
time.Sleep(retryIn)
retryIn = retryIn * time.Duration(2)
if retryIn > maxBackOff {
retryIn = maxBackOff
}
}
} |
// retrieveBundle retrieves bundle data from a URI | func getURIFileReader(uriString string) (io.ReadCloser, error) {
uri, err := url.Parse(uriString)
if err != nil {
return nil, fmt.Errorf("DownloadFileUrl: Failed to parse urlStr: %s", uriString)
}
// todo: add authentication - TBD?
// assume it's a file if no scheme - todo: remove file support?
if uri.Scheme... |
// NewClient factory Client | func NewClient() *Client {
detector := newDetector()
session := session.NewClient(nil)
return &Client{
detector: detector,
session: session,
}
} |
// Parse get gss.Result | func (c *Client) Parse(url string) (*Result, error) {
header := make(map[string]string)
bytes, err := c.session.Get(url, header)
if err != nil {
return nil, err
}
rssType, err := c.detector.detect(bytes)
if err != nil {
return nil, err
}
parser, err := getParser(rssType)
if err != nil {
return nil, err... |
// NewHTTPClient creates a new BOSH Registry Client. | func NewHTTPClient(
options ClientOptions,
logger boshlog.Logger,
) HTTPClient {
return HTTPClient{
options: options,
logger: logger,
}
} |
// Delete deletes the instance settings for a given instance ID. | func (c HTTPClient) Delete(instanceID string) error {
endpoint := fmt.Sprintf("%s/instances/%s/settings", c.options.EndpointWithCredentials(), instanceID)
c.logger.Debug(httpClientLogTag, "Deleting agent settings from registry endpoint '%s'", endpoint)
request, err := http.NewRequest("DELETE", endpoint, nil)
if er... |
// Fetch gets the agent settings for a given instance ID. | func (c HTTPClient) Fetch(instanceID string) (AgentSettings, error) {
endpoint := fmt.Sprintf("%s/instances/%s/settings", c.options.EndpointWithCredentials(), instanceID)
c.logger.Debug(httpClientLogTag, "Fetching agent settings from registry endpoint '%s'", endpoint)
request, err := http.NewRequest("GET", endpoint... |
// Update updates the agent settings for a given instance ID. If there are not already agent settings for the instance, it will create ones. | func (c HTTPClient) Update(instanceID string, agentSettings AgentSettings) error {
settingsJSON, err := json.Marshal(agentSettings)
if err != nil {
return bosherr.WrapErrorf(err, "Marshalling agent settings, contents: '%#v", agentSettings)
}
endpoint := fmt.Sprintf("%s/instances/%s/settings", c.options.EndpointW... |
// Reset resets an existing timer or creates a new one with given duration | func (timer *RealRTimer) Reset(d time.Duration) {
if timer.innerTimer == nil {
timer.innerTimer = time.NewTimer(d)
} else {
timer.innerTimer.Reset(d)
}
} |
// CreateUser issues the nimbusec API to create the given user. | func (a *API) CreateUser(user *User) (*User, error) {
dst := new(User)
url := a.BuildURL("/v2/user")
err := a.Post(url, Params{}, user, dst)
return dst, err
} |
// GetUser fetches an user by its ID. | func (a *API) GetUser(user int) (*User, error) {
dst := new(User)
url := a.BuildURL("/v2/user/%d", user)
err := a.Get(url, Params{}, dst)
return dst, err
} |
// GetUserByLogin fetches an user by its login name. | func (a *API) GetUserByLogin(login string) (*User, error) {
users, err := a.FindUsers(fmt.Sprintf("login eq \"%s\"", login))
if err != nil {
return nil, err
}
if len(users) == 0 {
return nil, ErrNotFound
}
if len(users) > 1 {
return nil, fmt.Errorf("login %q matched too many users. please contact nimbusec... |
// FindUsers searches for users that match the given filter criteria. | func (a *API) FindUsers(filter string) ([]User, error) {
params := Params{}
if filter != EmptyFilter {
params["q"] = filter
}
dst := make([]User, 0)
url := a.BuildURL("/v2/user")
err := a.Get(url, params, &dst)
return dst, err
} |
// UpdateUser issues the nimbusec API to update an user. | func (a *API) UpdateUser(user *User) (*User, error) {
dst := new(User)
url := a.BuildURL("/v2/user/%d", user.Id)
err := a.Put(url, Params{}, user, dst)
return dst, err
} |
// DeleteUser issues the nimbusec API to delete an user. The root user or tennant
// can not be deleted via this method. | func (a *API) DeleteUser(user *User) error {
url := a.BuildURL("/v2/user/%d", user.Id)
return a.Delete(url, Params{})
} |
// GetDomainSet fetches the set of allowed domains for an restricted user. | func (a *API) GetDomainSet(user *User) ([]int, error) {
dst := make([]int, 0)
url := a.BuildURL("/v2/user/%d/domains", user.Id)
err := a.Get(url, Params{}, &dst)
return dst, err
} |
// UpdateDomainSet updates the set of allowed domains of an restricted user. | func (a *API) UpdateDomainSet(user *User, domains []int) ([]int, error) {
dst := make([]int, 0)
url := a.BuildURL("/v2/user/%d/domains", user.Id)
err := a.Put(url, Params{}, domains, &dst)
return dst, err
} |
// LinkDomain links the given domain id to the given user and adds the priviledges for
// the user to view the domain. | func (a *API) LinkDomain(user *User, domain int) error {
url := a.BuildURL("/v2/user/%d/domains", user.Id)
return a.Post(url, Params{}, domain, nil)
} |
// UnlinkDomain unlinks the given domain id to the given user and removes the priviledges
// from the user to view the domain. | func (a *API) UnlinkDomain(user *User, domain int) error {
url := a.BuildURL("/v2/user/%d/domains/%d", user.Id, domain)
return a.Delete(url, Params{})
} |
// ListuserConfigs fetches the list of all available configuration keys for the
// given domain. | func (a *API) ListUserConfigs(user int) ([]string, error) {
dst := make([]string, 0)
url := a.BuildURL("/v2/user/%d/config", user)
err := a.Get(url, Params{}, &dst)
return dst, err
} |
// GetUserConfig fetches the requested user configuration. | func (a *API) GetUserConfig(user int, key string) (string, error) {
url := a.BuildURL("/v2/user/%d/config/%s/", user, key)
return a.getTextPlain(url, Params{})
} |
// SetUserConfig sets the user configuration `key` to the requested value.
// This method will create the user configuration if it does not exist yet. | func (a *API) SetUserConfig(user int, key string, value string) (string, error) {
url := a.BuildURL("/v2/user/%d/config/%s/", user, key)
return a.putTextPlain(url, Params{}, value)
} |
// DeleteUserConfig issues the API to delete the user configuration with
// the provided key. | func (a *API) DeleteUserConfig(user int, key string) error {
url := a.BuildURL("/v2/user/%d/config/%s/", user, key)
return a.Delete(url, Params{})
} |
// GetNotification fetches a notification by its ID. | func (a *API) GetNotification(user int, id int) (*Notification, error) {
dst := new(Notification)
url := a.BuildURL("/v2/user/%d/notification/%d", user, id)
err := a.Get(url, Params{}, dst)
return dst, err
} |
// FindNotifications fetches all notifications for the given user that match the
// filter criteria. | func (a *API) FindNotifications(user int, filter string) ([]Notification, error) {
params := Params{}
if filter != EmptyFilter {
params["q"] = filter
}
dst := make([]Notification, 0)
url := a.BuildURL("/v2/user/%d/notification", user)
err := a.Get(url, params, &dst)
return dst, err
} |
// CreateOrGetNotifcation issues the nimbusec API to create the given notification. Instead of
// failing when attempting to create a duplicate notification, this method will fetch the
// remote notification instead. | func (a *API) CreateOrGetNotification(user int, notification *Notification) (*Notification, error) {
dst := new(Notification)
url := a.BuildURL("/v2/user/%d/notification", user)
err := a.Post(url, Params{"upsert": "false"}, notification, dst)
return dst, err
} |
// UpdateNotification updates the notification for the given user. | func (a *API) UpdateNotification(user int, notification *Notification) (*Notification, error) {
dst := new(Notification)
url := a.BuildURL("/v2/user/%d/notification/%d", user, notification.Id)
err := a.Put(url, Params{}, notification, dst)
return dst, err
} |
// DeleteNotification deletes the given notification. | func (a *API) DeleteNotification(user int, notification *Notification) error {
url := a.BuildURL("/v2/user/%d/notification/%d", user, notification.Id)
return a.Delete(url, Params{})
} |
// handle client API | func (a *ApiManager) HandleRequest(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var returnValue interface{}
verifyApiKeyReq, err := validateRequest(r.Body, w)
if err != nil {
errorResponse, jsonErr := json.Marshal(errorResponse("Bad_REQUEST", err.Error(), http.St... |
// returns []byte to be written to client | func (apiM ApiManager) verifyAPIKey(verifyApiKeyReq VerifyApiKeyRequest) (*VerifyApiKeySuccessResponse, *common.ErrorResponse) {
dataWrapper := VerifyApiKeyRequestResponseDataWrapper{
verifyApiKeyRequest: verifyApiKeyReq,
}
dataWrapper.verifyApiKeySuccessResponse.ClientId.ClientId = verifyApiKeyReq.Key
dataWrapp... |
// Request issues an HTTP request, marshaling parameters, and unmarshaling results, as configured in the provided Options parameter.
// The Response structure returned, if any, will include accumulated results recovered from the HTTP server.
// See the Response structure for more details. | func Request(method string, url string, opts Options) (*Response, error) {
var body io.Reader
var response Response
client := opts.CustomClient
if client == nil {
client = new(http.Client)
}
contentType := opts.ContentType
body = nil
if opts.ReqBody != nil {
// if the content-type header is empty, but th... |
// not_in returns false if, and only if, the provided needle is _not_
// in the given set of integers. | func not_in(needle int, haystack []int) bool {
for _, straw := range haystack {
if needle == straw {
return false
}
}
return true
} |
// Post makes a POST request against a server using the provided HTTP client.
// The url must be a fully-formed URL string.
// DEPRECATED. Use Request() instead. | func Post(url string, opts Options) error {
r, err := Request("POST", url, opts)
if opts.Response != nil {
*opts.Response = r
}
return err
} |
// Fetch gets access token from UAA server. This auth token
// is s used for accessing traffic-controller. It retuns error if any. | func (tf *defaultTokenFetcher) Fetch() (string, error) {
tf.logger.Printf("[INFO] Getting auth token of %q from UAA (%s)", tf.username, tf.uaaAddr)
client, err := uaago.NewClient(tf.uaaAddr)
if err != nil {
return "", err
}
resCh, errCh := make(chan string), make(chan error)
go func() {
token, err := client.... |
// Parse RSS1.0 feed parse | func (p *Parser) Parse(data []byte) (interfaces.Mappable, error) {
r := bytes.NewReader(data)
decoder := xmlp.NewDecoder(r)
err := decoder.RootElement()
if err != nil {
return nil, err
}
var feed Feed
err = p.decode(decoder, &feed)
if err != nil {
return nil, err
}
return feed, nil
} |
// Initialize a new EOSClient instance | func (e *EOSClient) Initialize() error {
eosError := C.EdsInitializeSDK()
if eosError != C.EDS_ERR_OK {
return errors.New("Error when initializing Canon SDK")
}
return nil
} |
// Release the EOSClient, must be called on termination | func (p *EOSClient) Release() error {
eosError := C.EdsTerminateSDK()
if eosError != C.EDS_ERR_OK {
return errors.New("Error when terminating Canon SDK")
}
return nil
} |
// Get an array representing the cameras currently connected. Each CameraModel
// instance must be released by invoking the Release function once no longer
// needed. | func (e *EOSClient) GetCameraModels() ([]CameraModel, error) {
var eosCameraList *C.EdsCameraListRef
var eosError C.EdsError
var cameraCount int
// get a reference to the cameras list record
if eosError = C.EdsGetCameraList((*C.EdsCameraListRef)(unsafe.Pointer(&eosCameraList))); eosError != C.EDS_ERR_OK {
retur... |
// IsModule current Element is RSS module? | func (md *Decoder) IsModule(d *xmlp.Decoder) bool {
space := d.Space
if space == dublinCoreSpace || space == mediaSpace || space == contentSpace {
return true
}
return false
} |
// DecodeElement RSS module decode | func (md *Decoder) DecodeElement(d *xmlp.Decoder, m *Modules) error {
space := d.Space
switch space {
case dublinCoreSpace:
if err := md.decodeDublinCore(d, &m.DublinCore); err != nil {
return err
}
case mediaSpace:
if err := md.decodeMedia(d, &m.Media); err != nil {
return err
}
case contentSpace:
... |
// MarshalJSON assemble gss.Feed struct | func (f Feed) MarshalJSON() ([]byte, error) {
var date string
if f.Channel.Modules.DublinCore.Date != "" {
date = f.Channel.Modules.DublinCore.Date
}
var updated string
if f.Channel.Modules.DublinCore.Modified != "" {
updated = f.Channel.Modules.DublinCore.Modified
}
gf := &struct {
Title string `j... |
// MarshalJSON assemble gss.Image struct | func (i Image) MarshalJSON() ([]byte, error) {
gi := &struct {
Title string `json:"title"`
URL string `json:"url"`
Link string `json:"link"`
}{
Title: i.Title,
URL: i.URL,
Link: i.Link,
}
return json.Marshal(gi)
} |
// MarshalJSON assemble gss.Item struct | func (i Item) MarshalJSON() ([]byte, error) {
var creator string
if i.Modules.DublinCore.Creator != "" {
creator = i.Modules.DublinCore.Creator
}
type author struct {
Name string `json:"name"`
Email string `json:"email"`
}
a := author{
Name: creator,
}
var authors []author
if a.Name != "" {
authors... |
// NewAPI creates a new nimbusec API client. | func NewAPI(rawurl, key, secret string) (*API, error) {
client := oauth.NewConsumer(key, secret, oauth.ServiceProvider{})
token := &oauth.AccessToken{}
parsed, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
return &API{
url: parsed,
client: client,
token: token,
}, nil
} |
// BuildURL builds the fully qualified url to the nimbusec API. | func (a *API) BuildURL(relpath string, args ...interface{}) string {
if url, err := a.url.Parse(fmt.Sprintf(relpath, args...)); err == nil {
return url.String()
}
return ""
} |
// try is used to encapsulate a HTTP operation and retrieve the optional
// nimbusec error if one happened. | func try(resp *http.Response, err error) (*http.Response, error) {
if resp == nil {
return resp, err
}
if resp.StatusCode < 300 {
return resp, err
}
msg := resp.Header.Get("x-nimbusec-error")
if msg != "" {
return resp, errors.New(msg)
}
return resp, err
} |
// Get is a helper for all GET request with json payload. | func (a *API) Get(url string, params Params, dst interface{}) error {
resp, err := try(a.client.Get(url, params, a.token))
if err != nil {
return err
}
defer resp.Body.Close()
// no destination, so caller was only interested in the
// side effects.
if dst == nil {
return nil
}
decoder := json.NewDecoder... |
// Delete is a helper for all DELETE request with json payload. | func (a *API) Delete(url string, params Params) error {
resp, err := a.client.Delete(url, params, a.token)
resp.Body.Close()
return err
} |
// getTextPlain is a helper for all GET request with plain text payload. | func (a *API) getTextPlain(url string, params Params) (string, error) {
data, err := a.getBytes(url, params)
if err != nil {
return "", err
}
return string(data), nil
} |
// putTextPlain is a helper for all PUT request with plain text payload. | func (a *API) putTextPlain(url string, params Params, payload string) (string, error) {
resp, err := try(a.client.Put(url, "text/plain", string(payload), params, a.token))
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
retu... |
// getBytes is a helper for all GET request with raw byte payload. | func (a *API) getBytes(url string, params Params) ([]byte, error) {
resp, err := try(a.client.Get(url, params, a.token))
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return data, nil
} |
// RandomBirthDate generates a random birth date between 65 and 85 years ago | func RandomBirthDate() time.Time {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
randomYears := r.Intn(20)
yearsAgo := randomYears + 65
randomMonth := r.Intn(11)
randomDay := r.Intn(28)
t := time.Now()
return t.AddDate(-yearsAgo, -randomMonth, -randomDay).Truncate(time.Hour * 24)
} |
// NewContext generates a new context with randomly populated content | func NewContext() Context {
ctx := Context{}
smokingChoices := []randutil.Choice{
{2, "Smoker"},
{3, "Non-smoker"},
{1, "Ex-smoker"}}
sc, _ := randutil.WeightedChoice(smokingChoices)
ctx.Smoker = sc.Item.(string)
alcoholChoices := []randutil.Choice{
{2, "Occasional"},
{1, "Heavy"},
{1, "None"}}
ac, _... |
// Truename returns the shortest absolute pathname
// leading to the specified existing file.
// Note that a single file may have multiple
// hard links or be accessible via multiple bind mounts.
// Truename doesn't account for these situations. | func Truename(filePath string) (string, error) {
p, err := filepath.EvalSymlinks(filePath)
if err != nil {
return filePath, err
}
p, err = filepath.Abs(p)
if err != nil {
return filePath, err
}
return filepath.Clean(p), nil
} |
// IsSubpath returns true if maybeSubpath is a subpath of basepath. It
// uses filepath to be compatible with os-dependent paths. | func IsSubpath(basepath, maybeSubpath string) bool {
rel, err := filepath.Rel(basepath, maybeSubpath)
if err != nil {
return false
}
if strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
// not a subpath if "../" has to be used for the relative path
return false
}
return true
} |
// createAttrPrefix finds the name space prefix attribute to use for the given name space,
// defining a new prefix if necessary. It returns the prefix. | func (p *printer) createAttrPrefix(url string) string {
if prefix := p.attrPrefix[url]; prefix != "" {
return prefix
}
// The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml"
// and must be referred to that way.
// (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xm... |
// marshalValue writes one or more XML elements representing val.
// If val was obtained from a struct field, finfo must have its details. | func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error {
if startTemplate != nil && startTemplate.Name.Local == "" {
return fmt.Errorf("xml: EncodeElement of StartElement with missing name")
}
if !val.IsValid() {
return nil
}
if finfo != nil && finfo.flags&fOmit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.