_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/tools.go#L93-L127
|
func EnsureFirstUser(store *coal.Store, name, email, password string) error {
// copy store
s := store.Copy()
defer s.Close()
// check existence
n, err := s.C(&User{}).Count()
if err != nil {
return err
} else if n > 0 {
return nil
}
// user is missing
// create user
user := coal.Init(&User{}).(*User)
user.Name = name
user.Email = email
user.Password = password
// set key and secret
err = user.Validate()
if err != nil {
return err
}
// save user
err = s.C(user).Insert(user)
if err != nil {
return err
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L397-L411
|
func (c APIClient) InspectDatum(jobID string, datumID string) (*pps.DatumInfo, error) {
datumInfo, err := c.PpsAPIClient.InspectDatum(
c.Ctx(),
&pps.InspectDatumRequest{
Datum: &pps.Datum{
ID: datumID,
Job: NewJob(jobID),
},
},
)
if err != nil {
return nil, grpcutil.ScrubGRPC(err)
}
return datumInfo, nil
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L248-L274
|
func (gc *GraphicContext) drawString(text string, drawType drawType, x, y float64) float64 {
switch gc.svg.FontMode {
case PathFontMode:
w := gc.CreateStringPath(text, x, y)
gc.drawPaths(drawType)
gc.Current.Path.Clear()
return w
case SvgFontMode:
gc.embedSvgFont(text)
}
// create elements
svgText := Text{}
group := gc.newGroup(drawType)
// set attrs to text element
svgText.Text = text
svgText.FontSize = gc.Current.FontSize
svgText.X = x
svgText.Y = y
svgText.FontFamily = gc.Current.FontData.Name
// attach to group
group.Texts = []*Text{&svgText}
left, _, right, _ := gc.GetStringBounds(text)
return right - left
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L1503-L1507
|
func (v *SearchInResourceParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage16(&r, v)
return r.Error()
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L674-L681
|
func AddScalarWithMask(src *IplImage, value Scalar, dst, mask *IplImage) {
C.cvAddS(
unsafe.Pointer(src),
(C.CvScalar)(value),
unsafe.Pointer(dst),
unsafe.Pointer(mask),
)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/pathutil/path.go#L17-L31
|
func CanonicalURLPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root,
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
np += "/"
}
return np
}
|
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/examples/web_crawler.go#L28-L37
|
func work(args ...interface{}) interface{} {
url := args[0].(string)
depth := args[1].(int)
fetcher := args[2].(Fetcher)
if depth <= 0 {
return crawlResult{}
}
body, urls, err := fetcher.Fetch(url)
return crawlResult{body, urls, err}
}
|
https://github.com/texttheater/golang-levenshtein/blob/d188e65d659ef53fcdb0691c12f1bba64928b649/levenshtein/levenshtein.go#L190-L208
|
func WriteMatrix(source []rune, target []rune, matrix [][]int, writer io.Writer) {
fmt.Fprintf(writer, " ")
for _, targetRune := range target {
fmt.Fprintf(writer, " %c", targetRune)
}
fmt.Fprintf(writer, "\n")
fmt.Fprintf(writer, " %2d", matrix[0][0])
for j, _ := range target {
fmt.Fprintf(writer, " %2d", matrix[0][j+1])
}
fmt.Fprintf(writer, "\n")
for i, sourceRune := range source {
fmt.Fprintf(writer, "%c %2d", sourceRune, matrix[i+1][0])
for j, _ := range target {
fmt.Fprintf(writer, " %2d", matrix[i+1][j+1])
}
fmt.Fprintf(writer, "\n")
}
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/security/controller.go#L118-L157
|
func (c *OAuth2Controller) Token(w http.ResponseWriter, r *http.Request) {
grantType := r.URL.Query().Get("grant_type")
code := r.URL.Query().Get("code")
if strings.Compare(grantType, "authorization_code") != 0 {
http.Error(w, errors.New("Parameter grant_type is required").Error(), http.StatusBadRequest)
return
}
if strings.Compare(code, "") == 0 {
http.Error(w, errors.New("Parameter code is required").Error(), http.StatusBadRequest)
return
}
response, err := DecodeOAuth2Code(code, c.cnf.Jwt.Key)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
i, err := strconv.ParseInt(response.Exp, 10, 64)
exp := time.Unix(i, 0)
if exp.After(time.Now()) {
log.Printf("Code is expired")
} else {
token := jwt.New(jwt.GetSigningMethod("HS256"))
claims := token.Claims.(jwt.MapClaims)
claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
tokenString, _ := token.SignedString([]byte(c.cnf.Jwt.Key))
refreshToken := jwt.New(jwt.GetSigningMethod("HS256"))
refreshClaims := refreshToken.Claims.(jwt.MapClaims)
refreshClaims["exp"] = 0
refreshTokenString, _ := refreshToken.SignedString([]byte(c.cnf.Jwt.Key))
data := map[string]string{
"access_token": tokenString,
"token_type": "bearer",
"refresh_token": refreshTokenString,
"expires_in": "3600",
}
js, _ := json.Marshal(data)
w.Write(js)
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L2101-L2145
|
func headerDirToPutFileRecords(tree hashtree.HashTree, path string, node *hashtree.NodeProto) (*pfs.PutFileRecords, error) {
if node.DirNode == nil || node.DirNode.Shared == nil {
return nil, fmt.Errorf("headerDirToPutFileRecords only works on header/footer dirs")
}
s := node.DirNode.Shared
pfr := &pfs.PutFileRecords{
Split: true,
}
if s.Header != nil {
pfr.Header = &pfs.PutFileRecord{
SizeBytes: s.HeaderSize,
ObjectHash: s.Header.Hash,
}
}
if s.Footer != nil {
pfr.Footer = &pfs.PutFileRecord{
SizeBytes: s.FooterSize,
ObjectHash: s.Footer.Hash,
}
}
if err := tree.List(path, func(child *hashtree.NodeProto) error {
if child.FileNode == nil {
return fmt.Errorf("header/footer dir contains child subdirectory, " +
"which is invalid--header/footer dirs must be created by PutFileSplit")
}
for i, o := range child.FileNode.Objects {
// same hack as copyFile--set size of first object to the size of the
// whole subtree (and size of other objects to 0). I don't think
// PutFileSplit files can have more than one object, but that invariant
// isn't necessary to this code's correctness, so don't verify it.
var size int64
if i == 0 {
size = child.SubtreeSize
}
pfr.Records = append(pfr.Records, &pfs.PutFileRecord{
SizeBytes: size,
ObjectHash: o.Hash,
})
}
return nil
}); err != nil {
return nil, err
}
return pfr, nil // TODO(msteffen) put something real here
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L875-L880
|
func (t *Iterator) Cursor() Cursor {
if t.searchCursor == nil {
return ""
}
return Cursor(*t.searchCursor)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/demos/guestbook/guestbook.go#L38-L41
|
func guestbookKey(ctx context.Context) *datastore.Key {
// The string "default_guestbook" here could be varied to have multiple guestbooks.
return datastore.NewKey(ctx, "Guestbook", "default_guestbook", 0, nil)
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L69-L79
|
func (st *State) PopFrame() *frame.Frame {
x := st.frames.Pop()
if x == nil {
return nil
}
f := x.(*frame.Frame)
for i := st.framestack.Size(); i > f.Mark(); i-- {
st.framestack.Pop()
}
return f
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/healing.go#L26-L47
|
func healingHistoryHandler(w http.ResponseWriter, r *http.Request, t auth.Token) error {
if !permission.Check(t, permission.PermHealingRead) {
return permission.ErrUnauthorized
}
filter := r.URL.Query().Get("filter")
if filter != "" && filter != "node" && filter != "container" {
return &tsuruErrors.HTTP{
Code: http.StatusBadRequest,
Message: "invalid filter, possible values are 'node' or 'container'",
}
}
history, err := healer.ListHealingHistory(filter)
if err != nil {
return err
}
if len(history) == 0 {
w.WriteHeader(http.StatusNoContent)
return nil
}
w.Header().Set("Content-Type", "application/json")
return json.NewEncoder(w).Encode(history)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L115-L133
|
func multiValid(key []*Key) error {
invalid := false
for _, k := range key {
if !k.valid() {
invalid = true
break
}
}
if !invalid {
return nil
}
err := make(appengine.MultiError, len(key))
for i, k := range key {
if !k.valid() {
err[i] = ErrInvalidKey
}
}
return err
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/log.go#L44-L48
|
func Panic(args ...interface{}) {
msg := fmt.Sprint(args...)
logger.Output(2, LevelError, msg)
panic(msg)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L22-L27
|
func List(c context.Context) ([]string, error) {
req := &pb.GetModulesRequest{}
res := &pb.GetModulesResponse{}
err := internal.Call(c, "modules", "GetModules", req, res)
return res.Module, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L2643-L2647
|
func (v *CoverageRange) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler26(&r, v)
return r.Error()
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L102-L119
|
func (r *Raft) requestConfigChange(req configurationChangeRequest, timeout time.Duration) IndexFuture {
var timer <-chan time.Time
if timeout > 0 {
timer = time.After(timeout)
}
future := &configurationChangeFuture{
req: req,
}
future.init()
select {
case <-timer:
return errorFuture{ErrEnqueueTimeout}
case r.configurationChangeCh <- future:
return future
case <-r.shutdownCh:
return errorFuture{ErrRaftShutdown}
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/external-plugins/needs-rebase/plugin/plugin.go#L101-L157
|
func HandleAll(log *logrus.Entry, ghc githubClient, config *plugins.Configuration) error {
log.Info("Checking all PRs.")
orgs, repos := config.EnabledReposForExternalPlugin(PluginName)
if len(orgs) == 0 && len(repos) == 0 {
log.Warnf("No repos have been configured for the %s plugin", PluginName)
return nil
}
var buf bytes.Buffer
fmt.Fprint(&buf, "is:pr is:open")
for _, org := range orgs {
fmt.Fprintf(&buf, " org:\"%s\"", org)
}
for _, repo := range repos {
fmt.Fprintf(&buf, " repo:\"%s\"", repo)
}
prs, err := search(context.Background(), log, ghc, buf.String())
if err != nil {
return err
}
log.Infof("Considering %d PRs.", len(prs))
for _, pr := range prs {
// Skip PRs that are calculating mergeability. They will be updated by event or next loop.
if pr.Mergeable == githubql.MergeableStateUnknown {
continue
}
org := string(pr.Repository.Owner.Login)
repo := string(pr.Repository.Name)
num := int(pr.Number)
l := log.WithFields(logrus.Fields{
"org": org,
"repo": repo,
"pr": num,
})
hasLabel := false
for _, label := range pr.Labels.Nodes {
if label.Name == labels.NeedsRebase {
hasLabel = true
break
}
}
err := takeAction(
l,
ghc,
org,
repo,
num,
string(pr.Author.Login),
hasLabel,
pr.Mergeable == githubql.MergeableStateMergeable,
)
if err != nil {
l.WithError(err).Error("Error handling PR.")
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/types.go#L111-L125
|
func (t *KeyType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch KeyType(in.String()) {
case KeyTypeNumber:
*t = KeyTypeNumber
case KeyTypeString:
*t = KeyTypeString
case KeyTypeDate:
*t = KeyTypeDate
case KeyTypeArray:
*t = KeyTypeArray
default:
in.AddError(errors.New("unknown KeyType value"))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L4893-L4897
|
func (v *CallFunctionOnReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime46(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/mason/client.go#L108-L110
|
func (c *Client) UpdateAll(state string) error {
return c.basic.UpdateAll(state)
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive15.go#L196-L233
|
func readExtTimes(f *fileBlockHeader, b *readBuf) {
if len(*b) < 2 {
return // invalid, not enough data
}
flags := b.uint16()
ts := []*time.Time{&f.ModificationTime, &f.CreationTime, &f.AccessTime}
for i, t := range ts {
n := flags >> uint((3-i)*4)
if n&0x8 == 0 {
continue
}
if i != 0 { // ModificationTime already read so skip
if len(*b) < 4 {
return // invalid, not enough data
}
*t = parseDosTime(b.uint32())
}
if n&0x4 > 0 {
*t = t.Add(time.Second)
}
n &= 0x3
if n == 0 {
continue
}
if len(*b) < int(n) {
return // invalid, not enough data
}
// add extra time data in 100's of nanoseconds
d := time.Duration(0)
for j := 3 - n; j < n; j++ {
d |= time.Duration(b.byte()) << (j * 8)
}
d *= 100
*t = t.Add(d)
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/author_logger_wrapper.go#L78-L91
|
func (a *AuthorLoggerPluginWrapper) ReceiveComment(comment sql.Comment) []Point {
points := a.plugin.ReceiveComment(comment)
if a.enabled {
for i := range points {
if points[i].Values == nil {
points[i].Values = map[string]interface{}{}
}
points[i].Values["author"] = comment.User
}
}
return points
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/clientset/versioned/typed/prowjobs/v1/prowjobs_client.go#L85-L90
|
func (c *ProwV1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/commands.go#L425-L451
|
func validateFlagValue(value string, param *metadata.ActionParam) error {
if param.Regexp != nil {
if !param.Regexp.MatchString(value) {
return fmt.Errorf("Invalid value '%s' for '%s', value must validate /%s/",
value, param.Name, param.Regexp.String())
}
}
if param.NonBlank && value == "" {
return fmt.Errorf("Invalid value for '%s', value must not be blank",
param.Name)
}
if len(param.ValidValues) > 0 && param.Name != "filter[]" { // filter[] is special: it has values just so --help can list them
found := false
for _, v := range param.ValidValues {
if v == value {
found = true
break
}
}
if !found {
return fmt.Errorf("Invalid value for '%s', value must be one of %s, value provided was '%s'",
param.Name, strings.Join(param.ValidValues, ", "), value)
}
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L381-L401
|
func ProfilesExpandDevices(devices types.Devices, profiles []api.Profile) types.Devices {
expandedDevices := types.Devices{}
// Apply all the profiles
profileDevices := make([]types.Devices, len(profiles))
for i, profile := range profiles {
profileDevices[i] = profile.Devices
}
for i := range profileDevices {
for k, v := range profileDevices[i] {
expandedDevices[k] = v
}
}
// Stick the given devices on top
for k, v := range devices {
expandedDevices[k] = v
}
return expandedDevices
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L1221-L1225
|
func (v *ScriptTypeProfile) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler14(&r, v)
return r.Error()
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/api.go#L519-L572
|
func (r *Raft) restoreSnapshot() error {
snapshots, err := r.snapshots.List()
if err != nil {
r.logger.Error(fmt.Sprintf("Failed to list snapshots: %v", err))
return err
}
// Try to load in order of newest to oldest
for _, snapshot := range snapshots {
_, source, err := r.snapshots.Open(snapshot.ID)
if err != nil {
r.logger.Error(fmt.Sprintf("Failed to open snapshot %v: %v", snapshot.ID, err))
continue
}
defer source.Close()
if err := r.fsm.Restore(source); err != nil {
r.logger.Error(fmt.Sprintf("Failed to restore snapshot %v: %v", snapshot.ID, err))
continue
}
// Log success
r.logger.Info(fmt.Sprintf("Restored from snapshot %v", snapshot.ID))
// Update the lastApplied so we don't replay old logs
r.setLastApplied(snapshot.Index)
// Update the last stable snapshot info
r.setLastSnapshot(snapshot.Index, snapshot.Term)
// Update the configuration
if snapshot.Version > 0 {
r.configurations.committed = snapshot.Configuration
r.configurations.committedIndex = snapshot.ConfigurationIndex
r.configurations.latest = snapshot.Configuration
r.configurations.latestIndex = snapshot.ConfigurationIndex
} else {
configuration := decodePeers(snapshot.Peers, r.trans)
r.configurations.committed = configuration
r.configurations.committedIndex = snapshot.Index
r.configurations.latest = configuration
r.configurations.latestIndex = snapshot.Index
}
// Success!
return nil
}
// If we had snapshots and failed to load them, its an error
if len(snapshots) > 0 {
return fmt.Errorf("failed to load any existing snapshots")
}
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/sync/sync.go#L431-L461
|
func PushFile(c *pachclient.APIClient, pfc pachclient.PutFileClient, pfsFile *pfs.File, osFile io.ReadSeeker) error {
fileInfo, err := c.InspectFile(pfsFile.Commit.Repo.Name, pfsFile.Commit.ID, pfsFile.Path)
if err != nil && !isNotExist(err) {
return err
}
var i int
var object *pfs.Object
if fileInfo != nil {
for i, object = range fileInfo.Objects {
hash := pfs.NewHash()
if _, err := io.CopyN(hash, osFile, pfs.ChunkSize); err != nil {
if err == io.EOF {
break
}
return err
}
if object.Hash != pfs.EncodeHash(hash.Sum(nil)) {
break
}
}
}
if _, err := osFile.Seek(int64(i)*pfs.ChunkSize, 0); err != nil {
return err
}
_, err = pfc.PutFileOverwrite(pfsFile.Commit.Repo.Name, pfsFile.Commit.ID, pfsFile.Path, osFile, int64(i))
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/statusreconciler/controller.go#L345-L377
|
func removedBlockingPresubmits(old, new map[string][]config.Presubmit) map[string][]config.Presubmit {
removed := map[string][]config.Presubmit{}
for repo, oldPresubmits := range old {
removed[repo] = []config.Presubmit{}
for _, oldPresubmit := range oldPresubmits {
if !oldPresubmit.ContextRequired() {
continue
}
var found bool
for _, newPresubmit := range new[repo] {
if oldPresubmit.Name == newPresubmit.Name {
found = true
break
}
}
if !found {
removed[repo] = append(removed[repo], oldPresubmit)
logrus.WithFields(logrus.Fields{
"repo": repo,
"name": oldPresubmit.Name,
}).Debug("Identified a removed blocking presubmit.")
}
}
}
var numRemoved int
for _, presubmits := range removed {
numRemoved += len(presubmits)
}
logrus.Infof("Identified %d removed blocking presubmits.", numRemoved)
return removed
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6812-L6818
|
func (u AuthenticatedMessage) ArmForSwitch(sw int32) (string, bool) {
switch Uint32(sw) {
case 0:
return "V0", true
}
return "-", false
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcawsprovisioner/tcawsprovisioner.go#L373-L377
|
func (awsProvisioner *AwsProvisioner) BackendStatus() (*BackendStatusResponse, error) {
cd := tcclient.Client(*awsProvisioner)
responseObject, _, err := (&cd).APICall(nil, "GET", "/backend-status", new(BackendStatusResponse), nil)
return responseObject.(*BackendStatusResponse), err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L810-L814
|
func (v *StopParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler9(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/githuboauth/githuboauth.go#L93-L115
|
func (ga *Agent) HandleLogin(client OAuthClient) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
stateToken := xsrftoken.Generate(ga.gc.ClientSecret, "", "")
state := hex.EncodeToString([]byte(stateToken))
oauthSession, err := ga.gc.CookieStore.New(r, oauthSessionCookie)
oauthSession.Options.Secure = true
oauthSession.Options.HttpOnly = true
if err != nil {
ga.serverError(w, "Creating new OAuth session", err)
return
}
oauthSession.Options.MaxAge = 10 * 60
oauthSession.Values[stateKey] = state
if err := oauthSession.Save(r, w); err != nil {
ga.serverError(w, "Save oauth session", err)
return
}
redirectURL := client.AuthCodeURL(state, oauth2.ApprovalForce, oauth2.AccessTypeOnline)
http.Redirect(w, r, redirectURL, http.StatusFound)
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps/util.go#L14-L28
|
func VisitInput(input *Input, f func(*Input)) {
switch {
case input == nil:
return // Spouts may have nil input
case input.Cross != nil:
for _, input := range input.Cross {
VisitInput(input, f)
}
case input.Union != nil:
for _, input := range input.Union {
VisitInput(input, f)
}
}
f(input)
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/patch_apps_app_parameters.go#L106-L109
|
func (o *PatchAppsAppParams) WithHTTPClient(client *http.Client) *PatchAppsAppParams {
o.SetHTTPClient(client)
return o
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2573-L2593
|
func (c *Client) ListPRCommits(org, repo string, number int) ([]RepositoryCommit, error) {
c.log("ListPRCommits", org, repo, number)
if c.fake {
return nil, nil
}
var commits []RepositoryCommit
err := c.readPaginatedResults(
fmt.Sprintf("/repos/%v/%v/pulls/%d/commits", org, repo, number),
acceptNone,
func() interface{} { // newObj returns a pointer to the type of object to create
return &[]RepositoryCommit{}
},
func(obj interface{}) { // accumulate is the accumulation function for paginated results
commits = append(commits, *(obj.(*[]RepositoryCommit))...)
},
)
if err != nil {
return nil, err
}
return commits, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L185-L202
|
func (c *ClusterTx) ProjectGet(name string) (*api.Project, error) {
filter := ProjectFilter{}
filter.Name = name
objects, err := c.ProjectList(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch Project")
}
switch len(objects) {
case 0:
return nil, ErrNoSuchObject
case 1:
return &objects[0], nil
default:
return nil, fmt.Errorf("More than one project matches")
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/helpers.go#L46-L49
|
func toVarName(name string) string {
p := partsRegexp.ReplaceAllString(name, "_")
return inflect.CamelizeDownFirst(p)
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/iterator.go#L99-L128
|
func (it *Iterator) Next() {
if it.deleted {
it.deleted = false
return
}
retry:
it.valid = true
next, deleted := it.curr.getNext(0)
if deleted {
// Current node is deleted. Unlink current node from the level
// and make next node as current node.
// If it fails, refresh the path buffer and obtain new current node.
if it.s.helpDelete(0, it.prev, it.curr, next, &it.s.Stats) {
it.curr = next
} else {
atomic.AddUint64(&it.s.Stats.readConflicts, 1)
found := it.s.findPath(it.curr.Item(), it.cmp, it.buf, &it.s.Stats) != nil
last := it.curr
it.prev = it.buf.preds[0]
it.curr = it.buf.succs[0]
if found && last == it.curr {
goto retry
}
}
} else {
it.prev = it.curr
it.curr = next
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/endpoints.go#L329-L345
|
func activatedListeners(systemdListeners []net.Listener, cert *shared.CertInfo) map[kind]net.Listener {
listeners := map[kind]net.Listener{}
for _, listener := range systemdListeners {
var kind kind
switch listener.(type) {
case *net.UnixListener:
kind = local
case *net.TCPListener:
kind = network
listener = networkTLSListener(listener, cert)
default:
continue
}
listeners[kind] = listener
}
return listeners
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L171-L174
|
func (p HighlightNodeParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *HighlightNodeParams {
p.BackendNodeID = backendNodeID
return &p
}
|
https://github.com/olorin/nagiosplugin/blob/893f9702af4ea1e2dc4cd6528cbdcdb3dc7ca064/range.go#L24-L70
|
func ParseRange(rangeStr string) (*Range, error) {
// Set defaults
t := &Range{
Start: 0,
End: math.Inf(1),
AlertOnInside: false,
}
// Remove leading and trailing whitespace
rangeStr = strings.Trim(rangeStr, " \n\r")
// Check for inverted semantics
if rangeStr[0] == '@' {
t.AlertOnInside = true
rangeStr = rangeStr[1:]
}
// Parse lower limit
endPos := strings.Index(rangeStr, ":")
if endPos > -1 {
if rangeStr[0] == '~' {
t.Start = math.Inf(-1)
} else {
min, err := strconv.ParseFloat(rangeStr[0:endPos], 64)
if err != nil {
return nil, fmt.Errorf("failed to parse lower limit: %v", err)
}
t.Start = min
}
rangeStr = rangeStr[endPos+1:]
}
// Parse upper limit
if len(rangeStr) > 0 {
max, err := strconv.ParseFloat(rangeStr, 64)
if err != nil {
return nil, fmt.Errorf("failed to parse upper limit: %v", err)
}
t.End = max
}
if t.End < t.Start {
return nil, errors.New("Invalid range definition. min <= max violated!")
}
// OK
return t, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/types.go#L114-L132
|
func (t *VersionStatus) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch VersionStatus(in.String()) {
case VersionStatusNew:
*t = VersionStatusNew
case VersionStatusInstalling:
*t = VersionStatusInstalling
case VersionStatusInstalled:
*t = VersionStatusInstalled
case VersionStatusActivating:
*t = VersionStatusActivating
case VersionStatusActivated:
*t = VersionStatusActivated
case VersionStatusRedundant:
*t = VersionStatusRedundant
default:
in.AddError(errors.New("unknown VersionStatus value"))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4793-L4797
|
func (v FocusParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom54(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L204-L235
|
func (s *FileSequence) Split() FileSequences {
if s.frameSet == nil {
// Return a copy
return FileSequences{s.Copy()}
}
franges := strings.Split(s.frameSet.FrameRange(), ",")
if len(franges) == 1 {
// Return a copy
return FileSequences{s.Copy()}
}
var buf strings.Builder
// Write the dir and base components once
buf.WriteString(s.dir)
buf.WriteString(s.basename)
list := make(FileSequences, len(franges))
var seq *FileSequence
for i, frange := range franges {
buf.WriteString(frange)
buf.WriteString(s.padChar)
buf.WriteString(s.ext)
seq, _ = NewFileSequence(buf.String())
list[i] = seq
buf.Reset()
}
return list
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/clone/clone.go#L181-L189
|
func (g *gitCtx) gitRevParse() (string, error) {
gitRevParseCommand := g.gitCommand("rev-parse", "HEAD")
_, commit, err := gitRevParseCommand.run()
if err != nil {
logrus.WithError(err).Error("git rev-parse HEAD failed!")
return "", err
}
return strings.TrimSpace(commit), nil
}
|
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/decode_reader.go#L182-L233
|
func (d *decodeReader) processFilters() (err error) {
f := d.filters[0]
if f.offset > 0 {
return nil
}
d.filters = d.filters[1:]
if d.win.buffered() < f.length {
// fill() didn't return enough bytes
err = d.readErr()
if err == nil || err == io.EOF {
return errInvalidFilter
}
return err
}
if cap(d.buf) < f.length {
d.buf = make([]byte, f.length)
}
d.outbuf = d.buf[:f.length]
n := d.win.read(d.outbuf)
for {
// run filter passing buffer and total bytes read so far
d.outbuf, err = f.filter(d.outbuf, d.tot)
if err != nil {
return err
}
if cap(d.outbuf) > cap(d.buf) {
// Filter returned a bigger buffer, save it for future filters.
d.buf = d.outbuf
}
if len(d.filters) == 0 {
return nil
}
f = d.filters[0]
if f.offset != 0 {
// next filter not at current offset
f.offset -= n
return nil
}
if f.length != len(d.outbuf) {
return errInvalidFilter
}
d.filters = d.filters[1:]
if cap(d.outbuf) < cap(d.buf) {
// Filter returned a smaller buffer. Copy it back to the saved buffer
// so the next filter can make use of the larger buffer if needed.
d.outbuf = append(d.buf[:0], d.outbuf...)
}
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/generate.go#L144-L160
|
func selectPackage(dir, rel string, packageMap map[string]*Package) (*Package, error) {
if len(packageMap) == 0 {
return nil, nil
}
if len(packageMap) == 1 {
for _, pkg := range packageMap {
return pkg, nil
}
}
defaultPackageName := strings.Replace(rel, "/", "_", -1)
for _, pkg := range packageMap {
if pkgName := goPackageName(pkg); pkgName != "" && pkgName == defaultPackageName {
return pkg, nil
}
}
return nil, fmt.Errorf("%s: directory contains multiple proto packages. Gazelle can only generate a proto_library for one package.", dir)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/types.go#L42-L44
|
func (t WindowState) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/config.go#L528-L570
|
func yamlToConfig(path string, nc interface{}) error {
b, err := ReadFileMaybeGZIP(path)
if err != nil {
return fmt.Errorf("error reading %s: %v", path, err)
}
if err := yaml.Unmarshal(b, nc); err != nil {
return fmt.Errorf("error unmarshaling %s: %v", path, err)
}
var jc *JobConfig
switch v := nc.(type) {
case *JobConfig:
jc = v
case *Config:
jc = &v.JobConfig
}
for rep := range jc.Presubmits {
var fix func(*Presubmit)
fix = func(job *Presubmit) {
job.SourcePath = path
}
for i := range jc.Presubmits[rep] {
fix(&jc.Presubmits[rep][i])
}
}
for rep := range jc.Postsubmits {
var fix func(*Postsubmit)
fix = func(job *Postsubmit) {
job.SourcePath = path
}
for i := range jc.Postsubmits[rep] {
fix(&jc.Postsubmits[rep][i])
}
}
var fix func(*Periodic)
fix = func(job *Periodic) {
job.SourcePath = path
}
for i := range jc.Periodics {
fix(&jc.Periodics[i])
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1033-L1035
|
func (p *RemoveAttributeParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandRemoveAttribute, p, nil)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L199-L225
|
func imports(ctxt *build.Context, srcDir string, gopath []string) (map[string]string, error) {
pkg, err := ctxt.ImportDir(srcDir, 0)
if err != nil {
return nil, fmt.Errorf("unable to analyze source: %v", err)
}
// Resolve all non-standard-library imports
result := make(map[string]string)
for _, v := range pkg.Imports {
if !strings.Contains(v, ".") {
continue
}
src, err := findInGopath(v, gopath)
if err != nil {
return nil, fmt.Errorf("unable to find import %v in gopath %v: %v", v, gopath, err)
}
result[src] = v
im, err := imports(ctxt, src, gopath)
if err != nil {
return nil, fmt.Errorf("unable to parse package %v: %v", src, err)
}
for k, v := range im {
result[k] = v
}
}
return result, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L105-L114
|
func (p *AttachToBrowserTargetParams) Do(ctx context.Context) (sessionID SessionID, err error) {
// execute
var res AttachToBrowserTargetReturns
err = cdp.Execute(ctx, CommandAttachToBrowserTarget, nil, &res)
if err != nil {
return "", err
}
return res.SessionID, nil
}
|
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/types.go#L39-L44
|
func (t *TupleType) AddVersion(fields ...Field) {
t.versions = append(t.versions, fields)
for _, field := range fields {
t.fields[field.Name] = len(t.fields)
}
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/boundary.go#L146-L149
|
func (b *boundaryReader) isTerminator(buf []byte) bool {
idx := bytes.Index(buf, b.final)
return idx != -1
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_dir.go#L44-L51
|
func (s *storageDir) StoragePoolInit() error {
err := s.StorageCoreInit()
if err != nil {
return err
}
return nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L13238-L13240
|
func (api *API) SshKeyLocator(href string) *SshKeyLocator {
return &SshKeyLocator{Href(href), api}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/corrupt.go#L34-L140
|
func (s *EtcdServer) CheckInitialHashKV() error {
if !s.Cfg.InitialCorruptCheck {
return nil
}
lg := s.getLogger()
if lg != nil {
lg.Info(
"starting initial corruption check",
zap.String("local-member-id", s.ID().String()),
zap.Duration("timeout", s.Cfg.ReqTimeout()),
)
} else {
plog.Infof("%s starting initial corruption check with timeout %v...", s.ID(), s.Cfg.ReqTimeout())
}
h, rev, crev, err := s.kv.HashByRev(0)
if err != nil {
return fmt.Errorf("%s failed to fetch hash (%v)", s.ID(), err)
}
peers := s.getPeerHashKVs(rev)
mismatch := 0
for _, p := range peers {
if p.resp != nil {
peerID := types.ID(p.resp.Header.MemberId)
fields := []zap.Field{
zap.String("local-member-id", s.ID().String()),
zap.Int64("local-member-revision", rev),
zap.Int64("local-member-compact-revision", crev),
zap.Uint32("local-member-hash", h),
zap.String("remote-peer-id", peerID.String()),
zap.Strings("remote-peer-endpoints", p.eps),
zap.Int64("remote-peer-revision", p.resp.Header.Revision),
zap.Int64("remote-peer-compact-revision", p.resp.CompactRevision),
zap.Uint32("remote-peer-hash", p.resp.Hash),
}
if h != p.resp.Hash {
if crev == p.resp.CompactRevision {
if lg != nil {
lg.Warn("found different hash values from remote peer", fields...)
} else {
plog.Errorf("%s's hash %d != %s's hash %d (revision %d, peer revision %d, compact revision %d)", s.ID(), h, peerID, p.resp.Hash, rev, p.resp.Header.Revision, crev)
}
mismatch++
} else {
if lg != nil {
lg.Warn("found different compact revision values from remote peer", fields...)
} else {
plog.Warningf("%s cannot check hash of peer(%s): peer has a different compact revision %d (revision:%d)", s.ID(), peerID, p.resp.CompactRevision, rev)
}
}
}
continue
}
if p.err != nil {
switch p.err {
case rpctypes.ErrFutureRev:
if lg != nil {
lg.Warn(
"cannot fetch hash from slow remote peer",
zap.String("local-member-id", s.ID().String()),
zap.Int64("local-member-revision", rev),
zap.Int64("local-member-compact-revision", crev),
zap.Uint32("local-member-hash", h),
zap.String("remote-peer-id", p.id.String()),
zap.Strings("remote-peer-endpoints", p.eps),
zap.Error(err),
)
} else {
plog.Warningf("%s cannot check the hash of peer(%q) at revision %d: peer is lagging behind(%q)", s.ID(), p.eps, rev, p.err.Error())
}
case rpctypes.ErrCompacted:
if lg != nil {
lg.Warn(
"cannot fetch hash from remote peer; local member is behind",
zap.String("local-member-id", s.ID().String()),
zap.Int64("local-member-revision", rev),
zap.Int64("local-member-compact-revision", crev),
zap.Uint32("local-member-hash", h),
zap.String("remote-peer-id", p.id.String()),
zap.Strings("remote-peer-endpoints", p.eps),
zap.Error(err),
)
} else {
plog.Warningf("%s cannot check the hash of peer(%q) at revision %d: local node is lagging behind(%q)", s.ID(), p.eps, rev, p.err.Error())
}
}
}
}
if mismatch > 0 {
return fmt.Errorf("%s found data inconsistency with peers", s.ID())
}
if lg != nil {
lg.Info(
"initial corruption checking passed; no corruption",
zap.String("local-member-id", s.ID().String()),
)
} else {
plog.Infof("%s succeeded on initial corruption checking: no corruption", s.ID())
}
return nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3486-L3489
|
func (e AccountMergeResultCode) String() string {
name, _ := accountMergeResultCodeMap[int32(e)]
return name
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/cmd/aminoscan/aminoscan.go#L294-L301
|
func slide(bzPtr *[]byte, n *int, _n int) bool {
if len(*bzPtr) < _n {
panic("eof")
}
*bzPtr = (*bzPtr)[_n:]
*n += _n
return true
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L652-L664
|
func (c *Cluster) StoragePoolDelete(poolName string) (*api.StoragePool, error) {
poolID, pool, err := c.StoragePoolGet(poolName)
if err != nil {
return nil, err
}
err = exec(c.db, "DELETE FROM storage_pools WHERE id=?", poolID)
if err != nil {
return nil, err
}
return pool, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L955-L961
|
func (c APIClient) PutFileWriter(repoName string, commitID string, path string) (io.WriteCloser, error) {
pfc, err := c.newOneoffPutFileClient()
if err != nil {
return nil, err
}
return pfc.PutFileWriter(repoName, commitID, path)
}
|
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L38-L42
|
func (nb *NotifyBundle) Connected(n Network, c Conn) {
if nb.ConnectedF != nil {
nb.ConnectedF(n, c)
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/common.go#L210-L222
|
func (ud *UserData) Update(new *UserData) {
if new == nil {
return
}
new.Range(func(key, value interface{}) bool {
if value.(string) != "" {
ud.Store(key, value)
} else {
ud.Delete(key)
}
return true
})
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L684-L688
|
func (v SetGeolocationOverrideParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation7(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/tracer.go#L226-L230
|
func (r SpanReference) Apply(o *StartSpanOptions) {
if r.ReferencedContext != nil {
o.References = append(o.References, r)
}
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L263-L267
|
func (eC2Manager *EC2Manager) GetRecentErrors() (*Errors, error) {
cd := tcclient.Client(*eC2Manager)
responseObject, _, err := (&cd).APICall(nil, "GET", "/errors", new(Errors), nil)
return responseObject.(*Errors), err
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/store.go#L32-L36
|
func (rs *redisStore) Set(key, value string) error {
rs.Values[key] = value
err := provider.refresh(rs)
return err
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/listener.go#L412-L417
|
func IsClosedConnError(err error) bool {
// 'use of closed network connection' (Go <=1.8)
// 'use of closed file or network connection' (Go >1.8, internal/poll.ErrClosing)
// 'mux: listener closed' (cmux.ErrListenerClosed)
return err != nil && strings.Contains(err.Error(), "closed")
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/networks.go#L227-L229
|
func (c *ClusterTx) NetworkCreated(name string) error {
return c.networkState(name, networkCreated)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L89-L111
|
func NewWindow(name string, flags ...int) *Window {
win_flags := C.int(CV_WINDOW_AUTOSIZE)
if len(flags) > 0 {
win_flags = C.int(flags[0])
}
win := &Window{
name: name,
name_c: C.CString(name),
flags: win_flags,
trackbarHandle: make(map[string]TrackbarFunc, 50),
trackbarMax: make(map[string]int, 50),
trackbarVal: make(map[string]int, 50),
trackbarName: make(map[string](*C.char), 50),
trackbarParam: make(map[string]([]interface{}), 50),
}
C.cvNamedWindow(win.name_c, win.flags)
C.GoOpenCV_SetMouseCallback(win.name_c)
allWindows[win.name] = win
return win
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L1059-L1063
|
func (v GetCurrentTimeReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoAnimation11(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/header.go#L167-L197
|
func decodeToUTF8Base64Header(input string) string {
if !strings.Contains(input, "=?") {
// Don't scan if there is nothing to do here
return input
}
tokens := strings.FieldsFunc(input, whiteSpaceRune)
output := make([]string, len(tokens))
for i, token := range tokens {
if len(token) > 4 && strings.Contains(token, "=?") {
// Stash parenthesis, they should not be encoded
prefix := ""
suffix := ""
if token[0] == '(' {
prefix = "("
token = token[1:]
}
if token[len(token)-1] == ')' {
suffix = ")"
token = token[:len(token)-1]
}
// Base64 encode token
output[i] = prefix + mime.BEncoding.Encode("UTF-8", decodeHeader(token)) + suffix
} else {
output[i] = token
}
}
// Return space separated tokens
return strings.Join(output, " ")
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2640-L2644
|
func (v *NavigateParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage27(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_project.go#L164-L178
|
func projectCreateDefaultProfile(tx *db.ClusterTx, project string) error {
// Create a default profile
profile := db.Profile{}
profile.Project = project
profile.Name = "default"
profile.Description = fmt.Sprintf("Default LXD profile for project %s", project)
profile.Config = map[string]string{}
profile.Devices = types.Devices{}
_, err := tx.ProfileCreate(profile)
if err != nil {
return errors.Wrap(err, "Add default profile to database")
}
return nil
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L192-L205
|
func (receiver *encryptedTCPReceiver) Receive() ([]byte, error) {
msg, err := receiver.receiver.Receive()
if err != nil {
return nil, err
}
decodedMsg, success := secretbox.Open(nil, msg, &receiver.state.nonce, receiver.state.sessionKey)
if !success {
return nil, fmt.Errorf("Unable to decrypt TCP msg")
}
receiver.state.advance()
return decodedMsg, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L7530-L7534
|
func (v *AddScriptToEvaluateOnNewDocumentReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage83(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/resource_crd.go#L147-L153
|
func (in *ResourceCollection) SetItems(objects []Object) {
var items []*ResourceObject
for _, b := range objects {
items = append(items, b.(*ResourceObject))
}
in.Items = items
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L4591-L4595
|
func (v *EvaluateOnCallFrameParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger43(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L293-L309
|
func LoadConfig(path string, orgs string) (*Configuration, error) {
if path == "" {
return nil, errors.New("empty path")
}
var c Configuration
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
if err = yaml.Unmarshal(data, &c); err != nil {
return nil, err
}
if err = c.validate(orgs); err != nil { // Ensure no dups
return nil, err
}
return &c, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L917-L975
|
func setEnv(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
var e apiTypes.Envs
err = ParseInput(r, &e)
if err != nil {
return err
}
if len(e.Envs) == 0 {
msg := "You must provide the list of environment variables"
return &errors.HTTP{Code: http.StatusBadRequest, Message: msg}
}
appName := r.URL.Query().Get(":app")
a, err := getAppFromContext(appName, r)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermAppUpdateEnvSet,
contextsForApp(&a)...,
)
if !allowed {
return permission.ErrUnauthorized
}
var toExclude []string
if e.Private {
for i := 0; i < len(e.Envs); i++ {
toExclude = append(toExclude, fmt.Sprintf("Envs.%d.Value", i))
}
}
evt, err := event.New(&event.Opts{
Target: appTarget(appName),
Kind: permission.PermAppUpdateEnvSet,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r, toExclude...)),
Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(&a)...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
envs := map[string]string{}
variables := []bind.EnvVar{}
for _, v := range e.Envs {
envs[v.Name] = v.Value
variables = append(variables, bind.EnvVar{Name: v.Name, Value: v.Value, Public: !e.Private})
}
w.Header().Set("Content-Type", "application/x-json-stream")
keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "")
defer keepAliveWriter.Stop()
writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
evt.SetLogWriter(writer)
err = a.SetEnvs(bind.SetEnvArgs{
Envs: variables,
ShouldRestart: !e.NoRestart,
Writer: evt,
})
if v, ok := err.(*errors.ValidationError); ok {
return &errors.HTTP{Code: http.StatusBadRequest, Message: v.Message}
}
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/jobs.go#L307-L318
|
func (ps Postsubmit) ShouldRun(baseRef string, changes ChangedFilesProvider) (bool, error) {
if !ps.CouldRun(baseRef) {
return false, nil
}
if determined, shouldRun, err := ps.RegexpChangeMatcher.ShouldRun(changes); err != nil {
return false, err
} else if determined {
return shouldRun, nil
}
// Postsubmits default to always run
return true, nil
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/route.go#L81-L103
|
func (m *Route) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateFormat(formats); err != nil {
// prop
res = append(res, err)
}
if err := m.validateHeaders(formats); err != nil {
// prop
res = append(res, err)
}
if err := m.validateType(formats); err != nil {
// prop
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
|
https://github.com/delicb/gstring/blob/77637d5e476b8e22d81f6a7bc5311a836dceb1c2/gstring.go#L109-L112
|
func Errorm(format string, args map[string]interface{}) error {
f, a := gformat(format, args)
return fmt.Errorf(f, a...)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L66-L68
|
func (s *SimpleConfig) Empty() bool {
return len(s.Approvers) == 0 && len(s.Reviewers) == 0 && len(s.RequiredReviewers) == 0 && len(s.Labels) == 0
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L281-L289
|
func (q *Query) End(c Cursor) *Query {
q = q.clone()
if c.cc == nil {
q.err = errors.New("datastore: invalid cursor")
return q
}
q.end = c.cc
return q
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L37-L71
|
func newOpenshiftClient(ref openshiftReference) (*openshiftClient, error) {
// We have already done this parsing in ParseReference, but thrown away
// httpClient. So, parse again.
// (We could also rework/split restClientFor to "get base URL" to be done
// in ParseReference, and "get httpClient" to be done here. But until/unless
// we support non-default clusters, this is good enough.)
// Overall, this is modelled on openshift/origin/pkg/cmd/util/clientcmd.New().ClientConfig() and openshift/origin/pkg/client.
cmdConfig := defaultClientConfig()
logrus.Debugf("cmdConfig: %#v", cmdConfig)
restConfig, err := cmdConfig.ClientConfig()
if err != nil {
return nil, err
}
// REMOVED: SetOpenShiftDefaults (values are not overridable in config files, so hard-coded these defaults.)
logrus.Debugf("restConfig: %#v", restConfig)
baseURL, httpClient, err := restClientFor(restConfig)
if err != nil {
return nil, err
}
logrus.Debugf("URL: %#v", *baseURL)
if httpClient == nil {
httpClient = http.DefaultClient
}
return &openshiftClient{
ref: ref,
baseURL: baseURL,
httpClient: httpClient,
bearerToken: restConfig.BearerToken,
username: restConfig.Username,
password: restConfig.Password,
}, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/client.go#L290-L300
|
func (c *Client) Create(obj Object) (Object, error) {
result := c.NewObject()
err := c.cl.Post().
Namespace(c.ns).
Resource(c.t.Plural).
Name(obj.GetName()).
Body(obj).
Do().
Into(result)
return result, err
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L317-L326
|
func (g *Glg) InitWriter() *Glg {
g.logger.Range(func(key, val interface{}) bool {
l := val.(*logger)
l.writer = nil
l.updateMode()
g.logger.Store(key.(LEVEL), l)
return true
})
return g
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/client.go#L529-L541
|
func (c *Client) roundRobinQuorumBackoff(waitBetween time.Duration, jitterFraction float64) backoffFunc {
return func(attempt uint) time.Duration {
// after each round robin across quorum, backoff for our wait between duration
n := uint(len(c.Endpoints()))
quorum := (n/2 + 1)
if attempt%quorum == 0 {
c.lg.Debug("backoff", zap.Uint("attempt", attempt), zap.Uint("quorum", quorum), zap.Duration("waitBetween", waitBetween), zap.Float64("jitterFraction", jitterFraction))
return jitterUp(waitBetween, jitterFraction)
}
c.lg.Debug("backoff skipped", zap.Uint("attempt", attempt), zap.Uint("quorum", quorum))
return 0
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/log_cache.go#L22-L31
|
func NewLogCache(capacity int, store LogStore) (*LogCache, error) {
if capacity <= 0 {
return nil, fmt.Errorf("capacity must be positive")
}
c := &LogCache{
store: store,
cache: make([]*Log, capacity),
}
return c, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/enterprise/cmds/cmds.go#L122-L135
|
func Cmds(noMetrics, noPortForwarding *bool) []*cobra.Command {
var commands []*cobra.Command
enterprise := &cobra.Command{
Short: "Enterprise commands enable Pachyderm Enterprise features",
Long: "Enterprise commands enable Pachyderm Enterprise features",
}
commands = append(commands, cmdutil.CreateAlias(enterprise, "enterprise"))
commands = append(commands, ActivateCmd(noMetrics, noPortForwarding))
commands = append(commands, GetStateCmd(noMetrics, noPortForwarding))
return commands
}
|
https://github.com/pantheon-systems/go-certauth/blob/8764720d23a5034dd9fab090815b7859463c68f6/certutils/certutils_pre_go18.go#L32-L55
|
func NewTLSConfig(level TLSConfigLevel) *tls.Config {
// TLSConfigDefault - golang's default
c := &tls.Config{}
switch level {
case TLSConfigIntermediate:
// Causes servers to use Go's default ciphersuite preferences, which are tuned to avoid attacks. Does nothing on clients.
c.PreferServerCipherSuites = true
// Only use curves which have assembly implementations
c.CurvePreferences = []tls.CurveID{
tls.CurveP256,
}
case TLSConfigModern:
// Modern compat sets TLS_1.2 minimum version and a set of ciphers that support PFS
c.MinVersion = tls.VersionTLS12
c.CipherSuites = []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
}
}
return c
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/node.go#L241-L248
|
func RestartNode(c *Config) Node {
r := newRaft(c)
n := newNode()
n.logger = c.Logger
go n.run(r)
return &n
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L470-L485
|
func (p *Peer) addConnection(c *Connection, direction connectionDirection) error {
conns := p.connectionsFor(direction)
if c.readState() != connectionActive {
return ErrInvalidConnectionState
}
p.Lock()
*conns = append(*conns, c)
p.Unlock()
// Inform third parties that a peer gained a connection.
p.onStatusChanged(p)
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L194-L199
|
func (pcs Trace) TrimAboveName(name string) Trace {
for len(pcs) > 0 && pcs[len(pcs)-1].name() != name {
pcs = pcs[:len(pcs)-1]
}
return pcs
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/updateconfig/updateconfig.go#L90-L164
|
func Update(fg FileGetter, kc corev1.ConfigMapInterface, name, namespace string, updates []ConfigMapUpdate, logger *logrus.Entry) error {
cm, getErr := kc.Get(name, metav1.GetOptions{})
isNotFound := errors.IsNotFound(getErr)
if getErr != nil && !isNotFound {
return fmt.Errorf("failed to fetch current state of configmap: %v", getErr)
}
if cm == nil || isNotFound {
cm = &coreapi.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
}
}
if cm.Data == nil {
cm.Data = map[string]string{}
}
if cm.BinaryData == nil {
cm.BinaryData = map[string][]byte{}
}
for _, upd := range updates {
if upd.Filename == "" {
logger.WithField("key", upd.Key).Debug("Deleting key.")
delete(cm.Data, upd.Key)
delete(cm.BinaryData, upd.Key)
continue
}
content, err := fg.GetFile(upd.Filename)
if err != nil {
return fmt.Errorf("get file err: %v", err)
}
logger.WithFields(logrus.Fields{"key": upd.Key, "filename": upd.Filename}).Debug("Populating key.")
value := content
if upd.GZIP {
buff := bytes.NewBuffer([]byte{})
// TODO: this error is wildly unlikely for anything that
// would actually fit in a configmap, we could just as well return
// the error instead of falling back to the raw content
z := gzip.NewWriter(buff)
if _, err := z.Write(content); err != nil {
logger.WithError(err).Error("failed to gzip content, falling back to raw")
} else {
if err := z.Close(); err != nil {
logger.WithError(err).Error("failed to flush gzipped content (!?), falling back to raw")
} else {
value = buff.Bytes()
}
}
}
if utf8.ValidString(string(value)) {
delete(cm.BinaryData, upd.Key)
cm.Data[upd.Key] = string(value)
} else {
delete(cm.Data, upd.Key)
cm.BinaryData[upd.Key] = value
}
}
var updateErr error
var verb string
if getErr != nil && isNotFound {
verb = "create"
_, updateErr = kc.Create(cm)
} else {
verb = "update"
_, updateErr = kc.Update(cm)
}
if updateErr != nil {
return fmt.Errorf("%s config map err: %v", verb, updateErr)
}
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.