_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3
values | text stringlengths 52 85.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8900 | New | train | func New(src, packageName string) (*Mocker, error) {
srcPkg, err := pkgInfoFromPath(src, packages.LoadSyntax)
if err != nil {
return nil, fmt.Errorf("Couldn't load source package: %s", err)
}
pkgPath := srcPkg.PkgPath
if len(packageName) == 0 {
packageName = srcPkg.Name
} else {
mockPkgPath := filepath.Joi... | go | {
"resource": ""
} |
q8901 | Mock | train | func (m *Mocker) Mock(w io.Writer, name ...string) error {
if len(name) == 0 {
return errors.New("must specify one interface")
}
doc := doc{
PackageName: m.pkgName,
Imports: moqImports,
}
mocksMethods := false
tpkg := m.srcPkg.Types
for _, n := range name {
iface := tpkg.Scope().Lookup(n)
if ifa... | go | {
"resource": ""
} |
q8902 | Stop | train | func (s *Supervisor) Stop() {
s.Lock()
if s.state == notRunning {
s.state = terminated
s.Unlock()
return
}
s.state = terminated
s.Unlock()
done := make(chan struct{})
if s.sendControl(stopSupervisor{done}) {
<-done
}
} | go | {
"resource": ""
} |
q8903 | NewClient | train | func NewClient(config *Config) (*Client, error) {
if len(config.Contexts) == 0 {
if config.CurrentContext != "" {
return nil, fmt.Errorf("no contexts with name %q", config.CurrentContext)
}
if n := len(config.Clusters); n == 0 {
return nil, errors.New("no clusters provided")
} else if n > 1 {
return ... | go | {
"resource": ""
} |
q8904 | NewInClusterClient | train | func NewInClusterClient() (*Client, error) {
host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT")
if len(host) == 0 || len(port) == 0 {
return nil, errors.New("unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined")
}
names... | go | {
"resource": ""
} |
q8905 | createConfigMap | train | func createConfigMap(client *k8s.Client, name string, values map[string]string) error {
cm := &v1.ConfigMap{
Metadata: &metav1.ObjectMeta{
Name: &name,
Namespace: &client.Namespace,
},
Data: values,
}
err := client.Create(context.Background(), cm)
// If an HTTP error was returned by the API serve... | go | {
"resource": ""
} |
q8906 | Eq | train | func (l *LabelSelector) Eq(key, val string) {
if !validLabelValue(key) || !validLabelValue(val) {
return
}
l.stmts = append(l.stmts, key+"="+val)
} | go | {
"resource": ""
} |
q8907 | In | train | func (l *LabelSelector) In(key string, vals ...string) {
if !validLabelValue(key) || len(vals) == 0 {
return
}
for _, val := range vals {
if !validLabelValue(val) {
return
}
}
l.stmts = append(l.stmts, key+" in ("+strings.Join(vals, ", ")+")")
} | go | {
"resource": ""
} |
q8908 | QueryParam | train | func QueryParam(name, value string) Option {
return optionFunc(func(base string, v url.Values) string {
v.Set(name, value)
return base
})
} | go | {
"resource": ""
} |
q8909 | Timeout | train | func Timeout(d time.Duration) Option {
return QueryParam(
"timeoutSeconds",
strconv.FormatInt(int64(d/time.Second), 10),
)
} | go | {
"resource": ""
} |
q8910 | loadClient | train | func loadClient(kubeconfigPath string) (*k8s.Client, error) {
data, err := ioutil.ReadFile(kubeconfigPath)
if err != nil {
return nil, fmt.Errorf("read kubeconfig: %v", err)
}
// Unmarshal YAML into a Kubernetes config object.
var config k8s.Config
if err := yaml.Unmarshal(data, &config); err != nil {
return... | go | {
"resource": ""
} |
q8911 | marshal | train | func marshal(i interface{}) (string, []byte, error) {
if _, ok := i.(proto.Message); ok {
data, err := marshalPB(i)
return contentTypePB, data, err
}
data, err := json.Marshal(i)
return contentTypeJSON, data, err
} | go | {
"resource": ""
} |
q8912 | unmarshal | train | func unmarshal(data []byte, contentType string, i interface{}) error {
msg, isPBMsg := i.(proto.Message)
if contentType == contentTypePB && isPBMsg {
if err := unmarshalPB(data, msg); err != nil {
return fmt.Errorf("decode protobuf: %v", err)
}
return nil
}
if isPBMsg {
// only decode into JSON of a prot... | go | {
"resource": ""
} |
q8913 | Next | train | func (w *Watcher) Next(r Resource) (string, error) {
return w.watcher.Next(r)
} | go | {
"resource": ""
} |
q8914 | MarshalJSON | train | func (t Time) MarshalJSON() ([]byte, error) {
var seconds, nanos int64
if t.Seconds != nil {
seconds = *t.Seconds
}
if t.Nanos != nil {
nanos = int64(*t.Nanos)
}
return json.Marshal(time.Unix(seconds, nanos))
} | go | {
"resource": ""
} |
q8915 | Has | train | func (t *LLRB) Has(key Item) bool {
return t.Get(key) != nil
} | go | {
"resource": ""
} |
q8916 | Get | train | func (t *LLRB) Get(key Item) Item {
h := t.root
for h != nil {
switch {
case less(key, h.Item):
h = h.Left
case less(h.Item, key):
h = h.Right
default:
return h.Item
}
}
return nil
} | go | {
"resource": ""
} |
q8917 | Min | train | func (t *LLRB) Min() Item {
h := t.root
if h == nil {
return nil
}
for h.Left != nil {
h = h.Left
}
return h.Item
} | go | {
"resource": ""
} |
q8918 | Max | train | func (t *LLRB) Max() Item {
h := t.root
if h == nil {
return nil
}
for h.Right != nil {
h = h.Right
}
return h.Item
} | go | {
"resource": ""
} |
q8919 | ReplaceOrInsert | train | func (t *LLRB) ReplaceOrInsert(item Item) Item {
if item == nil {
panic("inserting nil item")
}
var replaced Item
t.root, replaced = t.replaceOrInsert(t.root, item)
t.root.Black = true
if replaced == nil {
t.count++
}
return replaced
} | go | {
"resource": ""
} |
q8920 | InsertNoReplace | train | func (t *LLRB) InsertNoReplace(item Item) {
if item == nil {
panic("inserting nil item")
}
t.root = t.insertNoReplace(t.root, item)
t.root.Black = true
t.count++
} | go | {
"resource": ""
} |
q8921 | walkDownRot234 | train | func walkDownRot234(h *Node) *Node {
if isRed(h.Left) && isRed(h.Right) {
flip(h)
}
return h
} | go | {
"resource": ""
} |
q8922 | DeleteMin | train | func (t *LLRB) DeleteMin() Item {
var deleted Item
t.root, deleted = deleteMin(t.root)
if t.root != nil {
t.root.Black = true
}
if deleted != nil {
t.count--
}
return deleted
} | go | {
"resource": ""
} |
q8923 | deleteMin | train | func deleteMin(h *Node) (*Node, Item) {
if h == nil {
return nil, nil
}
if h.Left == nil {
return nil, h.Item
}
if !isRed(h.Left) && !isRed(h.Left.Left) {
h = moveRedLeft(h)
}
var deleted Item
h.Left, deleted = deleteMin(h.Left)
return fixUp(h), deleted
} | go | {
"resource": ""
} |
q8924 | DeleteMax | train | func (t *LLRB) DeleteMax() Item {
var deleted Item
t.root, deleted = deleteMax(t.root)
if t.root != nil {
t.root.Black = true
}
if deleted != nil {
t.count--
}
return deleted
} | go | {
"resource": ""
} |
q8925 | Delete | train | func (t *LLRB) Delete(key Item) Item {
var deleted Item
t.root, deleted = t.delete(t.root, key)
if t.root != nil {
t.root.Black = true
}
if deleted != nil {
t.count--
}
return deleted
} | go | {
"resource": ""
} |
q8926 | AscendGreaterOrEqual | train | func (t *LLRB) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) {
t.ascendGreaterOrEqual(t.root, pivot, iterator)
} | go | {
"resource": ""
} |
q8927 | DescendLessOrEqual | train | func (t *LLRB) DescendLessOrEqual(pivot Item, iterator ItemIterator) {
t.descendLessOrEqual(t.root, pivot, iterator)
} | go | {
"resource": ""
} |
q8928 | WithValue | train | func (r *Runtime) WithValue(key string, value interface{}) *Runtime {
r.ctx[key] = value
return r
} | go | {
"resource": ""
} |
q8929 | UnmarshalPayload | train | func (r *Runtime) UnmarshalPayload(reader io.Reader, model interface{}) error {
return r.instrumentCall(UnmarshalStart, UnmarshalStop, func() error {
return UnmarshalPayload(reader, model)
})
} | go | {
"resource": ""
} |
q8930 | UnmarshalManyPayload | train | func (r *Runtime) UnmarshalManyPayload(reader io.Reader, kind reflect.Type) (elems []interface{}, err error) {
r.instrumentCall(UnmarshalStart, UnmarshalStop, func() error {
elems, err = UnmarshalManyPayload(reader, kind)
return err
})
return
} | go | {
"resource": ""
} |
q8931 | UnmarshalManyPayload | train | func UnmarshalManyPayload(in io.Reader, t reflect.Type) ([]interface{}, error) {
payload := new(ManyPayload)
if err := json.NewDecoder(in).Decode(payload); err != nil {
return nil, err
}
models := []interface{}{} // will be populated from the "data"
includedMap := map[string]*Node{} // will be populate... | go | {
"resource": ""
} |
q8932 | assign | train | func assign(field, value reflect.Value) {
value = reflect.Indirect(value)
if field.Kind() == reflect.Ptr {
// initialize pointer so it's value
// can be set by assignValue
field.Set(reflect.New(field.Type().Elem()))
field = field.Elem()
}
assignValue(field, value)
} | go | {
"resource": ""
} |
q8933 | assignValue | train | func assignValue(field, value reflect.Value) {
switch field.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
field.SetInt(value.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
field.SetUint(value.Uint())
case refl... | go | {
"resource": ""
} |
q8934 | Marshal | train | func Marshal(models interface{}) (Payloader, error) {
switch vals := reflect.ValueOf(models); vals.Kind() {
case reflect.Slice:
m, err := convertToSliceInterface(&models)
if err != nil {
return nil, err
}
payload, err := marshalMany(m)
if err != nil {
return nil, err
}
if linkableModels, isLinka... | go | {
"resource": ""
} |
q8935 | marshalOne | train | func marshalOne(model interface{}) (*OnePayload, error) {
included := make(map[string]*Node)
rootNode, err := visitModelNode(model, &included, true)
if err != nil {
return nil, err
}
payload := &OnePayload{Data: rootNode}
payload.Included = nodeMapValues(&included)
return payload, nil
} | go | {
"resource": ""
} |
q8936 | marshalMany | train | func marshalMany(models []interface{}) (*ManyPayload, error) {
payload := &ManyPayload{
Data: []*Node{},
}
included := map[string]*Node{}
for _, model := range models {
node, err := visitModelNode(model, &included, true)
if err != nil {
return nil, err
}
payload.Data = append(payload.Data, node)
}
p... | go | {
"resource": ""
} |
q8937 | JSONAPILinks | train | func (blog Blog) JSONAPILinks() *jsonapi.Links {
return &jsonapi.Links{
"self": fmt.Sprintf("https://example.com/blogs/%d", blog.ID),
}
} | go | {
"resource": ""
} |
q8938 | JSONAPIRelationshipLinks | train | func (blog Blog) JSONAPIRelationshipLinks(relation string) *jsonapi.Links {
if relation == "posts" {
return &jsonapi.Links{
"related": fmt.Sprintf("https://example.com/blogs/%d/posts", blog.ID),
}
}
if relation == "current_post" {
return &jsonapi.Links{
"related": fmt.Sprintf("https://example.com/blogs/%... | go | {
"resource": ""
} |
q8939 | JSONAPIRelationshipMeta | train | func (blog Blog) JSONAPIRelationshipMeta(relation string) *jsonapi.Meta {
if relation == "posts" {
return &jsonapi.Meta{
"detail": "posts meta information",
}
}
if relation == "current_post" {
return &jsonapi.Meta{
"detail": "current post meta information",
}
}
return nil
} | go | {
"resource": ""
} |
q8940 | applyTransform | train | func applyTransform(str string, transform sf) (out string) {
out = ""
for idx, line := range strings.Split(str, "\n") {
out += transform(idx, line)
}
return
} | go | {
"resource": ""
} |
q8941 | MoveCursor | train | func MoveCursor(x int, y int) {
fmt.Fprintf(Screen, "\033[%d;%dH", y, x)
} | go | {
"resource": ""
} |
q8942 | MoveTo | train | func MoveTo(str string, x int, y int) (out string) {
x, y = GetXY(x, y)
return applyTransform(str, func(idx int, line string) string {
return fmt.Sprintf("\033[%d;%dH%s", y+idx, x, line)
})
} | go | {
"resource": ""
} |
q8943 | ResetLine | train | func ResetLine(str string) (out string) {
return applyTransform(str, func(idx int, line string) string {
return fmt.Sprintf("%s%s", RESET_LINE, line)
})
} | go | {
"resource": ""
} |
q8944 | Width | train | func Width() int {
ws, err := getWinsize()
if err != nil {
return -1
}
return int(ws.Col)
} | go | {
"resource": ""
} |
q8945 | Height | train | func Height() int {
ws, err := getWinsize()
if err != nil {
return -1
}
return int(ws.Row)
} | go | {
"resource": ""
} |
q8946 | Flush | train | func Flush() {
for idx, str := range strings.SplitAfter(Screen.String(), "\n") {
if idx > Height() {
return
}
Output.WriteString(str)
}
Output.Flush()
Screen.Reset()
} | go | {
"resource": ""
} |
q8947 | getChartData | train | func getChartData(data *DataTable, index int) (out [][]float64) {
for _, r := range data.rows {
out = append(out, []float64{r[0], r[index]})
}
return
} | go | {
"resource": ""
} |
q8948 | Save | train | func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error {
// Generate an encoded cookie value with the CSRF token.
encoded, err := cs.sc.Encode(cs.name, token)
if err != nil {
return err
}
cookie := &http.Cookie{
Name: cs.name,
Value: encoded,
MaxAge: cs.maxAge,
HttpOnly: cs.http... | go | {
"resource": ""
} |
q8949 | RequestHeader | train | func RequestHeader(header string) Option {
return func(cs *csrf) {
cs.opts.RequestHeader = header
}
} | go | {
"resource": ""
} |
q8950 | CookieName | train | func CookieName(name string) Option {
return func(cs *csrf) {
cs.opts.CookieName = name
}
} | go | {
"resource": ""
} |
q8951 | parseOptions | train | func parseOptions(h http.Handler, opts ...Option) *csrf {
// Set the handler to call after processing.
cs := &csrf{
h: h,
}
// Default to true. See Secure & HttpOnly function comments for rationale.
// Set here to allow package users to override the default.
cs.opts.Secure = true
cs.opts.HttpOnly = true
// ... | go | {
"resource": ""
} |
q8952 | FailureReason | train | func FailureReason(r *http.Request) error {
if val, err := contextGet(r, errorKey); err == nil {
if err, ok := val.(error); ok {
return err
}
}
return nil
} | go | {
"resource": ""
} |
q8953 | envError | train | func envError(r *http.Request, err error) *http.Request {
return contextSave(r, errorKey, err)
} | go | {
"resource": ""
} |
q8954 | ServeHTTP | train | func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Skip the check if directed to. This should always be a bool.
if val, err := contextGet(r, skipCheckKey); err == nil {
if skip, ok := val.(bool); ok {
if skip {
cs.h.ServeHTTP(w, r)
return
}
}
}
// Retrieve the token from the s... | go | {
"resource": ""
} |
q8955 | unauthorizedHandler | train | func unauthorizedHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("%s - %s",
http.StatusText(http.StatusForbidden), FailureReason(r)),
http.StatusForbidden)
return
} | go | {
"resource": ""
} |
q8956 | JsonToSexp | train | func JsonToSexp(json []byte, env *Zlisp) (Sexp, error) {
iface, err := JsonToGo(json)
if err != nil {
return nil, err
}
return GoToSexp(iface, env)
} | go | {
"resource": ""
} |
q8957 | SexpToJson | train | func SexpToJson(exp Sexp) string {
switch e := exp.(type) {
case *SexpHash:
return e.jsonHashHelper()
case *SexpArray:
return e.jsonArrayHelper()
case *SexpSymbol:
return `"` + e.name + `"`
default:
return exp.SexpString(nil)
}
} | go | {
"resource": ""
} |
q8958 | JsonToGo | train | func JsonToGo(json []byte) (interface{}, error) {
var iface interface{}
decoder := codec.NewDecoderBytes(json, &msgpHelper.jh)
err := decoder.Decode(&iface)
if err != nil {
panic(err)
}
VPrintf("\n decoded type : %T\n", iface)
VPrintf("\n decoded value: %#v\n", iface)
return iface, nil
} | go | {
"resource": ""
} |
q8959 | GoToJson | train | func GoToJson(iface interface{}) []byte {
var w bytes.Buffer
encoder := codec.NewEncoder(&w, &msgpHelper.jh)
err := encoder.Encode(&iface)
if err != nil {
panic(err)
}
return w.Bytes()
} | go | {
"resource": ""
} |
q8960 | MsgpackToSexp | train | func MsgpackToSexp(msgp []byte, env *Zlisp) (Sexp, error) {
iface, err := MsgpackToGo(msgp)
if err != nil {
return nil, fmt.Errorf("MsgpackToSexp failed at MsgpackToGo step: '%s", err)
}
sexp, err := GoToSexp(iface, env)
if err != nil {
return nil, fmt.Errorf("MsgpackToSexp failed at GoToSexp step: '%s", err)
... | go | {
"resource": ""
} |
q8961 | MsgpackToGo | train | func MsgpackToGo(msgp []byte) (interface{}, error) {
var iface interface{}
dec := codec.NewDecoderBytes(msgp, &msgpHelper.mh)
err := dec.Decode(&iface)
if err != nil {
return nil, err
}
//fmt.Printf("\n decoded type : %T\n", iface)
//fmt.Printf("\n decoded value: %#v\n", iface)
return iface, nil
} | go | {
"resource": ""
} |
q8962 | dumpComment | train | func (lexer *Lexer) dumpComment() {
str := lexer.buffer.String()
lexer.buffer.Reset()
lexer.AppendToken(lexer.Token(TokenComment, str))
} | go | {
"resource": ""
} |
q8963 | SexpString | train | func (s *Scope) SexpString(ps *PrintState) string {
var label string
head := ""
if s.IsPackage {
head = "(package " + s.PackageName
} else {
label = "scope " + s.Name
if s.IsGlobal {
label += " (global)"
}
}
str, err := s.Show(s.env, ps, s.Name)
if err != nil {
return "(" + label + ")"
}
return ... | go | {
"resource": ""
} |
q8964 | LookupSymbolNonGlobal | train | func (stack *Stack) LookupSymbolNonGlobal(sym *SexpSymbol) (Sexp, error, *Scope) {
return stack.lookupSymbol(sym, 1, nil)
} | go | {
"resource": ""
} |
q8965 | MsgpackMapMacro | train | func MsgpackMapMacro(env *Zlisp, name string,
args []Sexp) (Sexp, error) {
if len(args) < 1 {
return SexpNull, fmt.Errorf("struct-name is missing. use: " +
"(msgpack-map struct-name)\n")
}
return MakeList([]Sexp{
env.MakeSymbol("def"),
args[0],
MakeList([]Sexp{
env.MakeSymbol("quote"),
env.MakeSy... | go | {
"resource": ""
} |
q8966 | RemoveEndsFilter | train | func RemoveEndsFilter(x Sexp) bool {
switch n := x.(type) {
case *SexpSentinel:
if n.Val == SexpEnd.Val {
return false
}
}
return true
} | go | {
"resource": ""
} |
q8967 | MergeFuncMap | train | func MergeFuncMap(funcs ...map[string]ZlispUserFunction) map[string]ZlispUserFunction {
n := make(map[string]ZlispUserFunction)
for _, f := range funcs {
for k, v := range f {
// disallow dups, avoiding possible security implications and confusion generally.
if _, dup := n[k]; dup {
panic(fmt.Sprintf(" d... | go | {
"resource": ""
} |
q8968 | CoreFunctions | train | func CoreFunctions() map[string]ZlispUserFunction {
return map[string]ZlispUserFunction{
"pretty": SetPrettyPrintFlag,
"<": CompareFunction,
">": CompareFunction,
"<=": CompareFunction,
">=": CompareFunction,
"==": CompareFunction,
"!=": CompareFunction,
"... | go | {
"resource": ""
} |
q8969 | GenericAccessFunction | train | func GenericAccessFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) < 1 || len(args) > 3 {
return SexpNull, WrongNargs
}
// handle *SexpSelector
container := args[0]
var err error
if ptr, isPtrLike := container.(Selector); isPtrLike {
container, err = ptr.RHS(env)
if err != nil {
... | go | {
"resource": ""
} |
q8970 | AssignmentFunction | train | func AssignmentFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
Q("\n AssignmentFunction called with name ='%s'. args='%s'\n", name,
env.NewSexpArray(args).SexpString(nil))
narg := len(args)
if narg != 2 {
return SexpNull, fmt.Errorf("assignment requires two arguments: a left-hand-side and a right... | go | {
"resource": ""
} |
q8971 | errIfPrivate | train | func errIfPrivate(pathPart string, pkg *Stack) error {
noDot := stripAnyDotPrefix(pathPart)
// references through a package must be Public
if !unicode.IsUpper([]rune(noDot)[0]) {
return fmt.Errorf("Cannot access private member '%s' of package '%s'",
noDot, pkg.PackageName)
}
return nil
} | go | {
"resource": ""
} |
q8972 | DotFunction | train | func DotFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 2 {
return SexpNull, WrongNargs
}
P("in DotFunction(), name='%v', args[0] = '%v', args[1]= '%v'",
name,
args[0].SexpString(nil),
args[1].SexpString(nil))
return SexpNull, nil
/*
var ret Sexp = SexpNull
var err error
... | go | {
"resource": ""
} |
q8973 | AsUint64Function | train | func AsUint64Function(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 1 {
return SexpNull, WrongNargs
}
var val uint64
switch x := args[0].(type) {
case *SexpInt:
val = uint64(x.Val)
case *SexpFloat:
val = uint64(x.Val)
default:
return SexpNull, fmt.Errorf("Cannot convert %s to uin... | go | {
"resource": ""
} |
q8974 | GenericHpairFunction | train | func GenericHpairFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 2 {
return SexpNull, WrongNargs
}
posreq, isInt := args[1].(*SexpInt)
if !isInt {
return SexpNull, fmt.Errorf("hpair position request must be an integer")
}
pos := int(posreq.Val)
switch seq := args[0].(type) {
... | go | {
"resource": ""
} |
q8975 | CloneFrom | train | func (p *SexpHash) CloneFrom(src *SexpHash) {
p.TypeName = src.TypeName
p.Map = *(src.CopyMap())
p.KeyOrder = src.KeyOrder
p.GoStructFactory = src.GoStructFactory
p.NumKeys = src.NumKeys
p.GoMethods = src.GoMethods
p.GoFields = src.GoFields
p.GoMethSx = src.GoMethSx
p.GoFieldSx = src.GoFieldSx
p.GoType = sr... | go | {
"resource": ""
} |
q8976 | Start | train | func (p *Parser) Start() {
go func() {
defer close(p.Done)
expressions := make([]Sexp, 0, SliceDefaultCap)
// maybe we already have input, be optimistic!
// no need to call p.GetMoreInput() before staring
// our loop.
for {
expr, err := p.ParseExpression(0)
if err != nil || expr == SexpEnd {
if... | go | {
"resource": ""
} |
q8977 | getExpressionWithLiner | train | func (pr *Prompter) getExpressionWithLiner(env *Glisp) (readin string, xs []Sexp, err error) {
line, err := pr.Getline(nil)
if err != nil {
return "", nil, err
}
err = UnexpectedEnd
var x []Sexp
// parse and pause the parser if we need more input.
env.parser.ResetAddNewInput(bytes.NewBuffer([]byte(line + "\... | go | {
"resource": ""
} |
q8978 | TSPrintf | train | func TSPrintf(format string, a ...interface{}) {
fmt.Printf("%s ", ts())
fmt.Printf(format, a...)
} | go | {
"resource": ""
} |
q8979 | MyWordCompleter | train | func MyWordCompleter(line string, pos int) (head string, c []string, tail string) {
beg := []rune(line[:pos])
end := line[pos:]
Q("\nline = '%s' pos=%v\n", line, pos)
Q("\nbeg = '%v'\nend = '%s'\n", string(beg), end)
// find most recent paren in beg
n := len(beg)
last := n - 1
var i int
var p int = -1
outer:
... | go | {
"resource": ""
} |
q8980 | Assignment | train | func (env *Zlisp) Assignment(op string, bp int) *InfixOp {
oper := env.MakeSymbol(op)
operSet := env.MakeSymbol("set")
iop := &InfixOp{
Sym: oper,
Bp: bp,
MunchLeft: func(env *Zlisp, pr *Pratt, left Sexp) (Sexp, error) {
// TODO: check that left is okay as an LVALUE.
right, err := pr.Expression(env, bp... | go | {
"resource": ""
} |
q8981 | PostfixAssign | train | func (env *Zlisp) PostfixAssign(op string, bp int) *InfixOp {
oper := env.MakeSymbol(op)
iop := &InfixOp{
Sym: oper,
Bp: bp,
MunchLeft: func(env *Zlisp, pr *Pratt, left Sexp) (Sexp, error) {
// TODO: check that left is okay as an LVALUE
list := MakeList([]Sexp{
oper, left,
})
Q("postfix assignm... | go | {
"resource": ""
} |
q8982 | Advance | train | func (p *Pratt) Advance() error {
p.Pos++
if p.Pos >= len(p.Stream) {
return io.EOF
}
p.NextToken = p.Stream[p.Pos]
Q("end of Advance, p.NextToken = '%v'", p.NextToken.SexpString(nil))
return nil
} | go | {
"resource": ""
} |
q8983 | LookupSymbolInParentChainOfClosures | train | func (sf *SexpFunction) LookupSymbolInParentChainOfClosures(sym *SexpSymbol, setVal *Sexp, env *Zlisp) (Sexp, error, *Scope) {
cur := sf
par := sf.parent
for par != nil {
//fmt.Printf(" parent chain: cur:%v -> parent:%v\n", cur.name, par.name)
//fmt.Printf(" cur.closures = %s", ClosureToString(cur, env))... | go | {
"resource": ""
} |
q8984 | NilOrHoldsNil | train | func NilOrHoldsNil(iface interface{}) bool {
if iface == nil {
return true
}
return reflect.ValueOf(iface).IsNil()
} | go | {
"resource": ""
} |
q8985 | ImportPackageBuilder | train | func ImportPackageBuilder(env *Zlisp, name string, args []Sexp) (Sexp, error) {
//P("starting ImportPackageBuilder")
n := len(args)
if n != 1 && n != 2 {
return SexpNull, WrongNargs
}
var path Sexp
var alias string
switch n {
case 1:
path = args[0]
case 2:
path = args[1]
//P("import debug: alias posi... | go | {
"resource": ""
} |
q8986 | GenerateNewScope | train | func (gen *Generator) GenerateNewScope(expressions []Sexp) error {
size := len(expressions)
oldtail := gen.Tail
gen.Tail = false
if size == 0 {
return nil
//return NoExpressionsFound
}
gen.AddInstruction(AddScopeInstr{Name: "newScope"})
for _, expr := range expressions[:size-1] {
err := gen.Generate(expr)... | go | {
"resource": ""
} |
q8987 | SetShellCmd | train | func SetShellCmd() {
if runtime.GOOS == "windows" {
ShellCmd = os.Getenv("COMSPEC")
return
}
try := []string{"/usr/bin/bash"}
if !FileExists(ShellCmd) {
for i := range try {
b := try[i]
if FileExists(b) {
ShellCmd = b
return
}
}
}
} | go | {
"resource": ""
} |
q8988 | SystemBuilder | train | func SystemBuilder(env *Zlisp, name string, args []Sexp) (Sexp, error) {
//P("SystemBuilder called with args='%#v'", args)
return SystemFunction(env, name, args)
} | go | {
"resource": ""
} |
q8989 | DumpFunction | train | func DumpFunction(fun ZlispFunction, pc int) {
blank := " "
extra := blank
for i, instr := range fun {
if i == pc {
extra = " PC-> "
} else {
extra = blank
}
fmt.Printf("%s %d: %s\n", extra, i, instr.InstrString())
}
if pc == len(fun) {
fmt.Printf(" PC just past end at %d -----\n\n", pc)
}
} | go | {
"resource": ""
} |
q8990 | FindLoop | train | func (env *Zlisp) FindLoop(target *Loop) (int, error) {
if env.curfunc.user {
panic(fmt.Errorf("impossible in user-defined-function to find a loop '%s'", target.stmtname.name))
}
instruc := env.curfunc.fun
for i := range instruc {
switch loop := instruc[i].(type) {
case LoopStartInstr:
if loop.loop == targ... | go | {
"resource": ""
} |
q8991 | SplitStringFunction | train | func SplitStringFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 2 {
return SexpNull, WrongNargs
}
// make sure the two args are strings
s1, ok := args[0].(*SexpStr)
if !ok {
return SexpNull, fmt.Errorf("split requires a string to split, got %T", args[0])
}
s2, ok := args[1].(*... | go | {
"resource": ""
} |
q8992 | isBalanced | train | func isBalanced(str string) bool {
parens := 0
squares := 0
for _, c := range str {
switch c {
case '(':
parens++
case ')':
parens--
case '[':
squares++
case ']':
squares--
}
}
return parens == 0 && squares == 0
} | go | {
"resource": ""
} |
q8993 | getExpressionWithLiner | train | func (pr *Prompter) getExpressionWithLiner(env *Zlisp, reader *bufio.Reader, noLiner bool) (readin string, xs []Sexp, err error) {
var line, nextline string
if noLiner {
fmt.Printf(pr.prompt)
line, err = getLine(reader)
} else {
line, err = pr.Getline(nil)
}
if err != nil {
return "", nil, err
}
err =... | go | {
"resource": ""
} |
q8994 | AsTmFunction | train | func AsTmFunction(env *Zlisp, name string,
args []Sexp) (Sexp, error) {
if len(args) != 1 {
return SexpNull, WrongNargs
}
var str *SexpStr
switch t := args[0].(type) {
case *SexpStr:
str = t
default:
return SexpNull,
errors.New("argument of astm should be a string RFC3999Nano timestamp that we want to... | go | {
"resource": ""
} |
q8995 | SimpleSourceFunction | train | func SimpleSourceFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 1 {
return SexpNull, WrongNargs
}
src, isStr := args[0].(*SexpStr)
if !isStr {
return SexpNull, fmt.Errorf("-> error: first argument must be a string")
}
file := src.S
if !FileExists(file) {
return SexpNull, f... | go | {
"resource": ""
} |
q8996 | SourceExpressions | train | func (env *Zlisp) SourceExpressions(expressions []Sexp) error {
gen := NewGenerator(env)
err := gen.GenerateBegin(expressions)
if err != nil {
return err
}
//P("debug: in SourceExpressions, FROM expressions='%s'", (&SexpArray{Val: expressions, Env: env}).SexpString(0))
//P("debug: in SourceExpressions, gen=")
... | go | {
"resource": ""
} |
q8997 | sourceItem | train | func (env *Zlisp) sourceItem(item Sexp) error {
switch t := item.(type) {
case *SexpArray:
for _, v := range t.Val {
if err := env.sourceItem(v); err != nil {
return err
}
}
case *SexpPair:
expr := item
for expr != SexpNull {
list := expr.(*SexpPair)
if err := env.sourceItem(list.Head); err !... | go | {
"resource": ""
} |
q8998 | SexpString | train | func (p *RecordDefn) SexpString(ps *PrintState) string {
Q("RecordDefn::SexpString() called!")
if len(p.Fields) == 0 {
return fmt.Sprintf("(struct %s)", p.Name)
}
s := fmt.Sprintf("(struct %s [\n", p.Name)
w := make([][]int, len(p.Fields))
maxnfield := 0
for i, f := range p.Fields {
w[i] = f.FieldWidths()
... | go | {
"resource": ""
} |
q8999 | FieldWidths | train | func (f *SexpField) FieldWidths() []int {
hash := (*SexpHash)(f)
wide := []int{}
for _, key := range hash.KeyOrder {
val, err := hash.HashGet(nil, key)
str := ""
if err == nil {
switch s := key.(type) {
case *SexpStr:
str += s.S + ":"
case *SexpSymbol:
str += s.name + ":"
default:
str +... | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.