Best K6 code snippet using events.Exports
runs.go
Source:runs.go
1/* ******************************************************************************2* 2019 - present Contributed by Apulis Technology (Shenzhen) Co. LTD3*4* This program and the accompanying materials are made available under the5* terms of the MIT License, which is available at6* https://www.opensource.org/licenses/MIT7*8* See the NOTICE file distributed with this work for additional9* information regarding copyright ownership.10* Unless required by applicable law or agreed to in writing, software11* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT12* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the13* License for the specific language governing permissions and limitations14* under the License.15*16* SPDX-License-Identifier: MIT17******************************************************************************/18package models19import (20 "database/sql"21 "github.com/apulis/bmod/ai-lab-backend/pkg/exports"22 JOB "github.com/apulis/go-business/pkg/jobscheduler"23 "gorm.io/gorm"24 "gorm.io/plugin/soft_delete"25 "k8s.io/apimachinery/pkg/util/uuid"26 "time"27)28type Run struct{29 RunId string `json:"runId" gorm:"primary_key;type:varchar(255)"`30 LabId uint64 `json:"labId" gorm:"index;not null"`31 Bind string `json:"group" gorm:"index;not null"` // user defined group , default same as lab group32 Name string `json:"name" gorm:"type:varchar(255)"`33 Started uint64 `json:"starts,omitempty"`34 Num uint64 `json:"num"` // version number among lab or parent run35 JobType string `json:"jobType" gorm:"type:varchar(32)"` // system defined job types36 Parent string `json:"parent,omitempty" gorm:"index;type:varchar(255)"` // created by parent run37 Creator string `json:"creator" gorm:"type:varchar(255)"`38 //@mark: username may changed, use uid instead !!!39 UserId uint64 `json:"userId"`40 CreatedAt UnixTime `json:"createdAt"`41 DeletedAt soft_delete.DeletedAt `json:"deletedAt,omitempty" gorm:"not null"`42 Description string `json:"description"`43 StartTime *UnixTime `json:"start,omitempty"`44 EndTime *UnixTime `json:"end,omitempty"`45 Deadline int64 `json:"deadline"` // seconds , 0 no limit46 Status int `json:"status"`47 //@add: store extra status (old status) as field48 ExtStatus int `json:"extStatus"`49 Msg string `json:"msg"`50 Arch string `json:"arch" gorm:"type:varchar(32)"`51 Cmd *JsonMetaData `json:"cmd,omitempty"`52 Image string `json:"image,omitempty" `53 Tags *JsonMetaData `json:"tags,omitempty"`54 Config *JsonMetaData `json:"config,omitempty"`55 Resource *JsonMetaData `json:"resource,omitempty"`56 Envs *JsonMetaData `json:"envs,omitempty"`57 Endpoints *JsonMetaData `json:"endpoints,omitempty"`58 Quota *JsonMetaData `json:"quota,omitempty"`59 Output string `json:"output,omitempty"`60 Progress *JsonMetaData `json:"progress,omitempty"`61 Result *JsonMetaData `json:"result,omitempty"`62 Flags uint64 `json:"flags,omitempty"` // some system defined attributes this run behaves63 Token string `json:"token,omitempty"` // @todo: should not return to client user ???64 Namespace string `json:"-" gorm:"-"`65 UserGroupId uint64 `json:"-" gorm:"-"`66 LabBind string `json:"-" gorm:"-"`67 ViewStatus int `json:"viewStatus,omitempty" gorm:"-"`68 RegisterStatus int `json:"registerStatus,omitempty" gorm:"-"`69 ScratchStatus int `json:"scratchStatus,omitempty" gorm:"-"`70}71const (72 list_runs_fields="run_id,lab_id,runs.name,num,job_type,runs.creator,runs.user_id,runs.created_at,runs.deleted_at,start_time,end_time,runs.description,status,runs.tags,runs.flags,runs.quota,msg,parent"73 select_run_status_change = "run_id,status,flags,job_type"74 select_mlrun_context = "run_id,status,ext_status,parent,job_type,output,started,flags,lab_id as id,deleted_at,endpoints"75)76type BasicMLRunContext struct{77 BasicLabInfo78 RunId string `json:"runId"`79 Status int `json:"status"`80 JobType string `json:"jobType"`81 Output string `json:"-"`82 //track how many times nest run started83 Started uint64 `json:"-"`84 Flags uint64 `json:"flags"`85 DeletedAt soft_delete.DeletedAt `json:"deleted"`86 //track endpoints if exists87 Endpoints *JsonMetaData `json:"-"`88 events EventsTrack `json:"-"`89 Parent string `json:"parent"`90 ExtStatus int `json:"-"`91}92func (ctx*BasicMLRunContext) IsLabRun() bool {93 return len(ctx.RunId) == 094}95func (ctx*BasicMLRunContext) IsParentRun() bool {96 return len(ctx.RunId) > 097}98func (ctx*BasicMLRunContext) PrepareJobStatusChange() *JobStatusChange {99 return &JobStatusChange{100 RunId: ctx.RunId,101 JobType: ctx.JobType,102 Flags: ctx.Flags,103 Status: ctx.Status,104 }105}106func (ctx*BasicMLRunContext) WithJobStatusChange(job*JobStatusChange) *BasicMLRunContext{107 return &BasicMLRunContext{108 BasicLabInfo: ctx.BasicLabInfo,109 RunId: job.RunId,110 Status: job.Status,111 JobType: job.JobType,112 Flags: job.Flags,113 events: ctx.events,114 }115}116func (ctx*BasicMLRunContext) StatusIsSuccess() bool {117 return exports.IsRunStatusSuccess(ctx.Status)118}119func (ctx*BasicMLRunContext) StatusIsRunning() bool {120 return exports.IsRunStatusRunning(ctx.Status)121}122func (ctx*BasicMLRunContext) StatusIsActive() bool {123 return exports.IsRunStatusActive(ctx.Status)124}125func (ctx*BasicMLRunContext) StatusIsStopping() bool{126 return exports.IsRunStatusStopping(ctx.Status)127}128func (ctx*BasicMLRunContext) StatusIsIniting() bool{129 return exports.IsRunStatusIniting(ctx.Status)130}131func (ctx*BasicMLRunContext) StatusIsClean() bool{132 return exports.IsRunStatusClean(ctx.Status)133}134func (ctx*BasicMLRunContext) ShouldDiscard() bool{135 return exports.IsRunStatusDiscard(ctx.Status)136}137func (ctx*BasicMLRunContext) IsNativeLocalJob() bool{138 return len(ctx.RunId) > 0 && !exports.IsJobRunWithCloud(ctx.Flags)139}140func (ctx*BasicMLRunContext) IsNeedJoinJob() bool{141 return len(ctx.RunId) > 0 && exports.IsJobNeedWaitForChilds(ctx.Flags)142}143func (ctx*BasicMLRunContext) ChangeStatusTo(status int){144 if ctx.Statistics == nil {145 ctx.Statistics = &JsonMetaData{}146 }147 if ctx.stats == nil {148 ctx.stats = &JobStats{}149 ctx.Statistics.Fetch(ctx.stats)150 }151 ctx.stats.StatusChange(ctx.JobType,ctx.Status,status)152}153func (r*Run) EnableResume() bool{154 return exports.IsJobResumable(r.Flags)155}156func (r*Run) StatusIsRunning() bool {157 return exports.IsRunStatusRunning(r.Status)158}159func (r*Run) StatusIsNonActive()bool {160 return exports.IsRunStatusNonActive(r.Status)161}162func (r*Run) GetNotifierData() * RunStatusNotifier {163 return &RunStatusNotifier{164 RunNotifyScope: RunNotifyScope{165 Bind: r.LabBind,166 UserGroupId: r.UserGroupId,167 RunId: r.RunId,168 Parent: r.Parent,169 JobType: r.JobType,170 },171 RunNotifyPayload: RunNotifyPayload{172 CreatedAt: r.CreatedAt,173 StartTime: r.StartTime,174 EndTime: r.EndTime,175 DeletedAt: r.DeletedAt,176 Status: r.Status,177 Result: r.Result,178 Progress: r.Progress,179 Msg: r.Msg,180 Name: r.Name,181 Creator: r.Creator,182 UserId: r.UserId,183 },184 }185}186type UserResourceQuota struct{187 JOB.ResourceQuota188 Node int `json:"node"`189 Arch string `json:"arch"`190}191func newLabRun(mlrun * BasicMLRunContext,req*exports.CreateJobRequest) *Run{192 run := &Run{193 RunId: req.JobType + "-" + string(uuid.NewUUID()),194 LabId: mlrun.ID,195 Bind: req.JobGroup,196 Name: req.Name,197 JobType: req.JobType,198 Parent: mlrun.RunId,199 Creator: req.Creator,200 UserId: req.UserId,201 Description: req.Description,202 Arch: req.Arch,203 Image: req.Engine,204 Output: req.OutputPath,205 Flags: req.JobFlags,206 Cmd: &JsonMetaData{},207 Token: req.Token,208 }209 run.Cmd.Save(req.Cmd)210 if !exports.IsJobShouldSingleton(req.JobFlags) {211 if mlrun.IsLabRun() {212 run.Num = mlrun.Starts213 }else{214 run.Num = mlrun.Started215 }216 }217 if len(req.Tags) > 0 {218 run.Tags=&JsonMetaData{}219 run.Tags.Save(req.Tags)220 }221 if len(req.Config) > 0{222 run.Config=&JsonMetaData{}223 run.Config.Save(req.Config)224 }225 if len(req.Resource) > 0{226 run.Resource=&JsonMetaData{}227 run.Resource.Save(req.Resource)228 }229 if len(req.Envs) > 0{230 run.Envs=&JsonMetaData{}231 run.Envs.Save(req.Envs)232 }233 if len(req.Endpoints) > 0{234 run.Endpoints=&JsonMetaData{}235 //@mark: convert user endpoints to k8s service236 endpoints :=UserEndpointList{}237 for _,v := range(req.Endpoints) {238 patchName := v.Name239 if patchName[0] == '$' {//@mark: replace $ to - to make k8s compatible240 patchName=patchName[1:] + "-"241 if v.Name == exports.AILAB_SYS_ENDPOINT_SSH {// force sys ssh endpoint to use nodePort service242 v.NodePort = -1243 v.AccessKey=req.Creator244 }245 }246 userEndpoint := UserEndpoint{247 Name: v.Name,248 Port: v.Port,249 ServiceName: patchName + "-" + run.RunId,250 NodePort: v.NodePort,251 SecureKey: v.SecretKey,252 AccessKey: v.AccessKey,253 }254 endpoints=append(endpoints,userEndpoint)255 }256 run.Endpoints.Save(endpoints)257 }258 run.Quota=&JsonMetaData{}259 run.Quota.Save(req.Quota)260 if req.CompactMaster {261 run.Flags |= exports.AILAB_RUN_FLAGS_COMPACT_MASTER262 }263 return run264}265func CreateLabRun(labId uint64,runId string,req*exports.CreateJobRequest,enableRepace bool,syncPrepare bool) (result interface{},err APIError){266 err = execDBTransaction(func(tx *gorm.DB,events EventsTrack) APIError {267 mlrun ,err := getBasicMLRunInfoEx(tx,labId,runId,events)268 if err == nil {269 result, err = preCheckCreateRun(tx,mlrun,req)270 if err != nil && err.Errno() == exports.AILAB_SINGLETON_RUN_EXISTS {271 if !enableRepace {272 return err273 }274 //discard old run if possible275 //@mark: here should delete descend job also !!!276 oldRun := mlrun.WithJobStatusChange(result.(*JobStatusChange))277 _, err = tryRecursiveOpRuns(tx,nil,oldRun,"",true,true,tryForceDeleteRun)278 if err == nil {//@mark: restore lab info279 mlrun.BasicLabInfo=oldRun.BasicLabInfo280 }281 //_,err = tryForceDeleteRun(tx,result.(*JobStatusChange),mlrun)282 }283 }284 var run * Run285 if err == nil{286 if mlrun.IsParentRun() && !mlrun.StatusIsRunning() && exports.IsJobNeedWaitForChilds(req.JobFlags){287 return exports.RaiseAPIError(exports.AILAB_INVALID_RUN_STATUS,"only running job can create wait join child runs !!!")288 }289 //@add: if parent run not resides on cloud, child run cannot resides on cloud also !290 if mlrun.IsNativeLocalJob() && exports.IsJobRunWithCloud(req.JobFlags) {291 return exports.RaiseAPIError(exports.AILAB_LOGIC_ERROR,"native local job cannot create child job run on clouds !!!")292 }293 run = newLabRun(mlrun,req)294 err = allocateLabRunStg(run,mlrun)295 if err == nil{296 //@mark: no resource request !!!297 if !exports.IsJobNeedPrepare(run.Flags){298 run.Flags |= exports.AILAB_RUN_FLAGS_PREPARE_OK299 run.Status = exports.AILAB_RUN_STATUS_STARTING300 run.StartTime = &UnixTime{time.Now()}301 }else if syncPrepare {//@mark: synchronoulsy prepare create deleted run first , then change to starting when prepare success302 run.DeletedAt = soft_delete.DeletedAt(time.Now().Unix())303 }else{304 run.Status = exports.AILAB_RUN_STATUS_INIT305 }306 err = wrapDBUpdateError(tx.Create(&run),1)307 }308 }309 if err == nil{310 err = completeCreateRun(tx,mlrun,req,run)311 }312 if err == nil{313 err = mlrun.Save(tx)314 }315 if err == nil{316 result = run317 }318 return err319 })320 return321}322func QueryRunDetail(runId string,unscoped bool,status int,needChild bool) (run*Run,err APIError){323 run = &Run{}324 inst := db325 if unscoped {326 inst = inst.Unscoped()327 }328 if status > 0 {329 inst = inst.Where("status=?",status)330 }331 err = wrapDBQueryError(inst.First(run,"run_id=?",runId))332 //if err == nil && exports.IsRunStatusStarting(status) {333 if err == nil {334 err = checkDBQueryError(db.Table("labs").Select("namespace,user_group_id,bind").335 Where("id=?",run.LabId).Row().Scan(&run.Namespace,&run.UserGroupId,&run.LabBind))336 }337 if err == nil && needChild{338 err = execDBQuerRows(db.Table("runs").Where("parent = ? and deleted_at=0 and flags&? != 0 ",339 runId,exports.AILAB_RUN_FLAGS_SINGLE_INSTANCE).340 Select("status,job_type"), func(tx *gorm.DB, rows *sql.Rows) APIError {341 status := 0342 jobType := ""343 if err:=checkDBQueryError(rows.Scan(&status,&jobType));err != nil{344 return err345 }346 switch jobType {347 case exports.AILAB_RUN_VISUALIZE: run.ViewStatus=status348 case exports.AILAB_RUN_MODEL_REGISTER: run.RegisterStatus=status349 case exports.AILAB_RUN_SCRATCH: run.ScratchStatus=status350 }351 return nil352 })353 }354 if err != nil {355 run = nil356 }357 return358}359func QueryRunUserInfo(runId string) (*exports.LabRunUserInfo,APIError){360 uinfo := &exports.LabRunUserInfo{}361 err := wrapDBQueryError(db.Model(&Run{}).Select("labs.user_id as lab_user_id,labs.bind as lab_bind, labs.user_group_id,app,runs.user_id,lab_id,job_type").362 Joins("left join labs on runs.lab_id=labs.id").First(uinfo,"run_id=?",runId))363 if err != nil {364 return nil,err365 }else{366 return uinfo,nil367 }368}369func SelectAnyLabRun(labId uint64) (run*Run,err APIError){370 run = &Run{}371 return run,wrapDBQueryError(db.Unscoped().First(run,"lab_id=?",labId))372}373func KillNestRun(labId uint64,runId string , jobType string, deepScan bool ) (counts uint64,err APIError){374 err = execDBTransaction(func(tx *gorm.DB,events EventsTrack) APIError {375 assertCheck(len(runId)>0,"KillNestRun must have runId")376 mlrun ,err := getBasicMLRunInfoEx(tx,labId,runId,events)377 if err == nil{378 counts,err = tryRecursiveOpRuns(tx,nil,mlrun,jobType,deepScan,false,tryKillRun)379 }380 return err381 })382 return383}384func KillLabRun(labId uint64,runId string,deepScan bool) (counts uint64,err APIError) {385 err = execDBTransaction(func(tx*gorm.DB,events EventsTrack)APIError{386 assertCheck(len(runId)>0,"KillLabRun must have runId")387 mlrun,err := getBasicMLRunInfoEx(tx,labId,runId,events)388 if err == nil {389 if deepScan || !mlrun.IsNeedJoinJob(){390 counts,err = tryRecursiveOpRuns(tx,nil,mlrun,"",deepScan,true,tryKillRun)391 }else {//@add: support for `WAITCHILD` jobs392 counts,err = tryRecursiveOpRuns(tx,func(db*gorm.DB)*gorm.DB{393 return db.Where("flags&? != 0",exports.AILAB_RUN_FLAGS_WAIT_CHILD)394 },mlrun,"",true,true,tryKillRun)395 }396 }397 return err398 })399 return400}401func DeleteLabRun(labId uint64,runId string,force bool) (counts uint64, err APIError){402 err = execDBTransaction(func(tx *gorm.DB,events EventsTrack) APIError {403 assertCheck(len(runId)>0,"DeleteLabRun must have runId")404 mlrun ,err := getBasicMLRunInfoEx(tx,labId,runId,events)405 if err == nil{406 if !force {407 counts, err = tryRecursiveOpRuns(tx,nil,mlrun,"",true,true,tryDeleteRun)408 }else{409 counts, err = tryRecursiveOpRuns(tx,nil,mlrun,"",true,true,tryForceDeleteRun)410 }411 }412 return err413 })414 return415}416func CleanLabRun(labId uint64,runId string) (counts uint64,err APIError) {417 err = execDBTransaction(func(tx*gorm.DB,events EventsTrack)APIError{418 assertCheck(len(runId)>0,"CleanLabRun must have runId")419 //@mark: here only need to traverse all deleted runs !!!420 inst := tx.Unscoped().Where("deleted_at !=0").Session(&gorm.Session{})421 mlrun,err := getBasicMLRunInfoEx(inst,labId,runId,events)422 if err == nil {423 counts,err = tryRecursiveOpRuns(inst,nil,mlrun,"",true,true,tryCleanRunWithDeleted)424 }425 return err426 })427 return428}429func ResumeLabRun(labId uint64,runId string) (mlrun *BasicMLRunContext,err APIError){430 err = execDBTransaction(func(tx *gorm.DB,events EventsTrack) APIError {431 assertCheck(len(runId)>0,"ResumeLabRun must have runId")432 mlrun ,err = getBasicMLRunInfoEx(tx,labId,runId,events)433 if err == nil{434 _, err = tryRecursiveOpRuns(tx,nil,mlrun,"",false,true,tryResumeRun)435 }436 return err437 })438 return439}440func UpdateLabRun(labId uint64,runId string,req exports.RequestObject) (APIError) {441 TranslateJsonMeta(req,"progress","result")442 return wrapDBUpdateError(db.Model(&Run{}).Select("description","progress","result").443 Where("run_id=? and lab_id=?",runId,labId).Updates(req),1)444}445func PauseLabRun(labId uint64,runId string) APIError{446 return exports.NotImplementError("PauseLabRun: not implements")447}448func ListAllLabRuns(req*exports.SearchCond,labId uint64,isNeedNestStatus bool) (data interface{} ,err APIError){449 result := []Run{}450 if len(req.Group) == 0 {//filter by lab id451 data,err = makePagedQuery(db.Select(list_runs_fields).Where("lab_id=?",labId),req,&result)452 }else{//need filter by group453 group := req.Group454 req.Group = ""455 data,err = makePagedQuery(db.Select(list_runs_fields + ",labs.bind as bind").456 Joins("left join labs on lab_id=labs.id").Where("labs.bind like ?",group+"%"),457 req,&result)458 }459 if len(result) > 0 && isNeedNestStatus {//retrieve nest child tool runs also460 jobIds :=make([]string,0,len(result))461 jobData:=make(map[string]*Run,len(result))462 for i:=0;i<len(result);i++{463 run := &result[i]464 jobIds=append(jobIds,run.RunId)465 jobData[run.RunId]=run466 }467 err = execDBQuerRows(db.Table("runs").Where("parent in ? and deleted_at=0 and flags&? != 0 ",468 jobIds,exports.AILAB_RUN_FLAGS_SINGLE_INSTANCE).469 Select("parent,status,job_type"), func(tx *gorm.DB, rows *sql.Rows) APIError {470 parent := ""471 status := 0472 jobType := ""473 if err:=checkDBQueryError(rows.Scan(&parent,&status,&jobType));err != nil{474 return err475 }476 switch jobType {477 case exports.AILAB_RUN_VISUALIZE: jobData[parent].ViewStatus=status478 case exports.AILAB_RUN_MODEL_REGISTER: jobData[parent].RegisterStatus=status479 case exports.AILAB_RUN_SCRATCH: jobData[parent].ScratchStatus=status480 }481 return nil482 })483 }484 return485}486func RollBackAllPrepareFailed() (counts uint64,err APIError){487 err= execDBTransaction(func(tx *gorm.DB, track EventsTrack) APIError {488 fail_runs := []string{}489 err := wrapDBQueryError(db.Table("runs").Where("deleted_at != 0 and status=0").Find(&fail_runs))490 if err != nil {491 return err492 }493 statusTo := exports.AILAB_RUN_STATUS_FAIL494 for _,runId := range(fail_runs) {495 err = change_run_status(tx,runId,&statusTo,Evt_clean_discard,0,track)496 if err != nil {497 return err498 }499 counts++500 }501 return nil502 })503 return504}505func PrepareRunSuccess(runId string,resource* JsonMetaData,isRollback bool) APIError{506 if isRollback {// process deleted RUN_STATUS_INIT507 return execDBTransaction(func(tx*gorm.DB,events EventsTrack)APIError{508 mlrun ,err := getBasicMLRunInfoEx(tx.Unscoped().Session(&gorm.Session{}),0 ,runId,events)509 if err != nil{510 if err.Errno() == exports.AILAB_NOT_FOUND {// context not exists511 return nil512 }else{513 return err514 }515 }516 if mlrun.DeletedAt == 0 || !mlrun.StatusIsIniting() {517 return nil518 }519 err = wrapDBUpdateError( tx.Table("runs").Where("run_id=?",runId).520 UpdateColumns(map[string]interface{}{521 "status" : exports.AILAB_RUN_STATUS_STARTING,522 "deleted_at":0,523 "start_time":&UnixTime{time.Now()},524 "end_time" :nil,525 "flags": gorm.Expr("flags|?",exports.AILAB_RUN_FLAGS_PREPARE_OK),526 "resource":resource,}) ,1)527 if err == nil {528 mlrun.Status=exports.AILAB_RUN_STATUS_INVALID529 mlrun.ChangeStatusTo(exports.AILAB_RUN_STATUS_STARTING)530 err = mlrun.Save(tx)531 }532 if err == nil {533 err = logStartingRun(tx,runId,exports.AILAB_RUN_STATUS_STARTING,events)534 }535 return err536 })537 }else{// process normal RUN_STATUS_INIT538 return execDBTransaction(func(tx*gorm.DB,events EventsTrack)APIError{539 err := wrapDBUpdateError( tx.Table("runs").Where("run_id=? and status=? and deleted_at = 0",540 runId,exports.AILAB_RUN_STATUS_INIT).541 UpdateColumns(map[string]interface{}{542 "status" : exports.AILAB_RUN_STATUS_STARTING,543 "start_time":&UnixTime{time.Now()},544 "end_time" :nil,545 "flags": gorm.Expr("flags|?",exports.AILAB_RUN_FLAGS_PREPARE_OK),546 "resource":resource,}) ,1)547 if err != nil && err.Errno() == exports.AILAB_DB_UPDATE_UNEXPECT {// context not exists548 return nil549 }550 if err == nil {551 err = logStartingRun(tx,runId,exports.AILAB_RUN_STATUS_STARTING,events)552 }553 return err554 })555 }556}557func PrepareRunFailed(runId string,msg string, isRollback bool) APIError {558 if isRollback {559 return execDBTransaction(func(tx*gorm.DB,events EventsTrack)APIError{560 mlrun,err := getBasicMLRunInfoEx(tx.Unscoped().Session(&gorm.Session{}),0,runId,events)561 if err != nil{562 if err.Errno() == exports.AILAB_NOT_FOUND {// context not exists563 return nil564 }else{565 return err566 }567 }568 if mlrun.DeletedAt == 0 || !mlrun.StatusIsIniting() {569 return nil570 }571 statusTo := exports.AILAB_RUN_STATUS_FAIL572 err =change_run_status(tx,mlrun.RunId,&statusTo,Evt_clean_discard,mlrun.Flags, mlrun.events)573 return err574 })575 }else{576 return execDBTransaction(func(tx*gorm.DB,events EventsTrack)APIError{577 mlrun,err := getBasicMLRunInfoEx(tx,0,runId,events)578 if err != nil{579 if err.Errno() == exports.AILAB_NOT_FOUND {// context not exists580 return nil581 }else{582 return err583 }584 }585 if !mlrun.StatusIsIniting() {586 return nil587 }588 statusTo := exports.AILAB_RUN_STATUS_FAIL589 err = change_run_status(tx,mlrun.RunId,&statusTo,0,mlrun.Flags,mlrun.events)590 if err == nil {591 err = wrapDBUpdateError(tx.Model(&Run{RunId: runId}).Update("msg",msg),1)592 }593 if err == nil {594 mlrun.ChangeStatusTo(statusTo)595 err = mlrun.Save(tx)596 }597 return err598 })599 }600}601func checkNotifyParentWait(tx*gorm.DB,parent string,track EventsTrack) APIError {602 if len(parent) == 0 {603 return nil604 }605 child := ""606 err := checkDBQueryError(tx.Model(Run{}).Where("parent=? and flags&? != 0 and status < ?",parent,607 exports.AILAB_RUN_FLAGS_WAIT_CHILD,exports.AILAB_RUN_STATUS_MIN_NON_ACTIVE).Select("run_id").Limit(1).Row().Scan(&child))608 if err == nil || err.Errno() != exports.AILAB_NOT_FOUND{// this is the final quit `WAIT RUN`609 return err610 }611 return logWaitChildRun(tx,parent,track)612}613func CheckWaitChildRuns(runId string) APIError {614 return execDBTransaction(func(tx *gorm.DB, track EventsTrack) APIError {615 mlrun,err := getBasicMLRunInfoEx(tx,0,runId,track)616 if err != nil{617 if err.Errno() == exports.AILAB_NOT_FOUND {// context not exists618 return nil619 }else{620 return err621 }622 }623 if mlrun.Status != exports.AILAB_RUN_STATUS_WAIT_CHILD {624 return nil625 }626 child := ""627 err = checkDBQueryError(tx.Model(Run{}).Where("parent=? and flags&? != 0 and status < ?",mlrun.RunId,628 exports.AILAB_RUN_FLAGS_WAIT_CHILD,exports.AILAB_RUN_STATUS_MIN_NON_ACTIVE).Select("run_id").Limit(1).Row().Scan(&child))629 if err == nil || err.Errno() != exports.AILAB_NOT_FOUND{630 return err631 }632 orignalStatus := mlrun.ExtStatus & 0xFF633 err = change_run_status(tx,mlrun.RunId,&orignalStatus,0,0,mlrun.events)634 if err == nil{635 mlrun.ChangeStatusTo(orignalStatus)636 err = mlrun.Save(tx)637 }638 return err639 })640}641func CleanupDone(runId string,extra int,filterStatus int) APIError{642 status,clean := extra&0xFF,extra>>8643 return execDBTransaction(func(tx *gorm.DB, track EventsTrack) APIError {644 mlrun,err := getBasicMLRunInfoEx(tx.Unscoped().Session(&gorm.Session{}),0,runId,track)645 if err != nil{646 if err.Errno() == exports.AILAB_NOT_FOUND {// context not exists647 return nil648 }else{649 return err650 }651 }652 if mlrun.Status != filterStatus {653 return nil654 }655 if clean == Evt_clean_discard {656 status = exports.AILAB_RUN_STATUS_DISCARDS657 err = change_run_status(tx,runId,&status,0,mlrun.Flags,track)658 if err == nil{659 err = tryDiscardRun(tx,runId,track)660 }661 }else if mlrun.DeletedAt == 0{662 err = wrapDBUpdateError(tx.Table("runs").Where("run_id=?",runId).663 UpdateColumns(map[string]interface{}{664 "status": status,665 "end_time": &UnixTime{time.Now()},666 }),1)667 if err == nil && mlrun.IsNeedJoinJob() {668 err = checkNotifyParentWait(tx, mlrun.Parent,track)669 }670 }else{671 err = wrapDBUpdateError(tx.Table("runs").Where("run_id=?",runId).672 UpdateColumn("status",status),1)673 }674 if err == nil && mlrun.DeletedAt == 0 && mlrun.Status != status{675 mlrun.ChangeStatusTo(status)676 err = mlrun.Save(tx)677 }678 return err679 })680}681func CheckIsDistributeJob(runId string) (bool ,APIError){682 quota := &JsonMetaData{}683 if err := checkDBQueryError(db.Model(Run{}).Select("quota").Where("run_id=?",runId).Row().Scan(quota));err != nil {684 return false,err685 }else{686 q := UserResourceQuota{}687 quota.Fetch(&q)688 return q.Node > 1 ,nil689 }690}691func getBasicMLRunInfoEx(tx*gorm.DB,labId uint64,runId string,events EventsTrack) (mlrun*BasicMLRunContext,err APIError){692 mlrun = &BasicMLRunContext{events: events}693 if len(runId) == 0 {694 lab,err := getBasicLabInfo(tx,labId)695 if err != nil{696 return nil,err697 }698 mlrun.BasicLabInfo=*lab699 }else{700 err = wrapDBQueryError(tx.Model(&Run{}).Select(select_mlrun_context).701 First(mlrun,"run_id=?",runId))702 if err == nil && labId != 0 && labId != mlrun.ID {703 err = exports.RaiseAPIError(exports.AILAB_LOGIC_ERROR,"invalid lab id passed for runs")704 }705 if err == nil{706 lab,err := getBasicLabInfo(tx,mlrun.ID)707 if err != nil{708 return nil,err709 }710 mlrun.BasicLabInfo=*lab711 }712 }713 return714}715func tryClearLabRunsByGroup(tx*gorm.DB, labs []uint64) APIError {716 runId := ""717 err := checkDBQueryError(tx.Model(&Run{}).Unscoped().Select("run_id").Limit(1).718 Where("lab_id in ? and status < ?",labs,exports.AILAB_RUN_STATUS_MIN_NON_ACTIVE).Row().Scan(&runId))719 if err == nil {720 return exports.RaiseAPIError(exports.AILAB_STILL_ACTIVE,"still have runs active !")721 }else if err.Errno() == exports.AILAB_NOT_FOUND{722 return wrapDBUpdateError(tx.Model(&Run{}).Where("lab_id in ?",labs).UpdateColumns(723 map[string]interface{}{//@todo: clear lab directly without preclean ???724 "deleted_at" : time.Now().Unix(),725 "status": exports.AILAB_RUN_STATUS_LAB_DISCARD,726 }),0)727 }else{728 return err729 }730}731func tryCleanLabRunsByGroup(tx*gorm.DB,labs [] uint64,events EventsTrack) (counts uint64,err APIError){732 var mlrun *BasicMLRunContext733 jobs := []*JobStatusChange{}734 for _,id := range (labs) {735 mlrun,err = getBasicMLRunInfoEx(tx.Unscoped(),id,"",events)736 if err != nil {737 return738 }739 err = execDBQuerRows(tx.Table("runs").Unscoped().Where("lab_id=? and status >= ? and deleted_at !=0",740 id,exports.AILAB_RUN_STATUS_MIN_NON_ACTIVE).Select(select_run_status_change),741 func(tx*gorm.DB,rows *sql.Rows) APIError {742 stats := &JobStatusChange{}743 if err := checkDBScanError(tx.ScanRows(rows,stats));err != nil {744 return err745 }746 jobs = append(jobs,stats)747 return nil748 })749 if err == nil{750 for _,v := range(jobs){751 cnt,err := tryCleanRunWithDeleted(tx,v,mlrun)752 if err != nil {753 return 0,err754 }755 counts += cnt756 }757 }758 if err == nil { err = mlrun.Save(tx)}759 if err != nil { return }760 }761 return762}763func tryKillLabRunsByGroup(tx*gorm.DB,labs []uint64,events EventsTrack) (counts uint64,err APIError){764 var mlrun *BasicMLRunContext765 jobs := []*JobStatusChange{}766 for _,id := range (labs) {767 mlrun,err = getBasicMLRunInfoEx(tx,id,"",events)768 if err != nil { return }769 err = execDBQuerRows(tx.Model(&Run{}).Where("lab_id=? and status < ?",770 id,exports.AILAB_RUN_STATUS_WAIT_CHILD).Select(select_run_status_change),func(tx*gorm.DB,rows *sql.Rows) APIError {771 stats := &JobStatusChange{}772 if err := checkDBScanError(tx.ScanRows(rows,stats));err != nil {773 return err774 }775 jobs = append(jobs,stats)776 return nil777 })778 if err == nil{779 for _,v := range(jobs) {780 cnt,err := tryKillRun(tx,v,mlrun)781 if err != nil {782 return 0,err783 }784 counts += cnt785 }786 }787 if err == nil { err = mlrun.Save(tx) }788 if err != nil { return}789 }790 return791}792func tryDeleteLabRuns(tx*gorm.DB,labId uint64) APIError{793 runId := ""794 err := checkDBQueryError(tx.Model(&Run{}).Select("run_id").Limit(1).795 Where("lab_id=? and status < ?",labId,exports.AILAB_RUN_STATUS_MIN_NON_ACTIVE).Row().Scan(&runId))796 if err == nil {797 return exports.RaiseAPIError(exports.AILAB_STILL_ACTIVE,"still have runs active !")798 }else if err.Errno() == exports.AILAB_NOT_FOUND{799 return wrapDBUpdateError(tx.Delete(&Run{},"lab_id=?",labId),0)800 }else{801 return err802 }803}804func tryDeleteLabRunsByGroup(tx*gorm.DB, labs []uint64) APIError{805 runId := ""806 err := checkDBQueryError(tx.Model(&Run{}).Select("run_id").Limit(1).807 Where("lab_id in ? and status < ?",labs,exports.AILAB_RUN_STATUS_MIN_NON_ACTIVE).Row().Scan(&runId))808 if err == nil {809 return exports.RaiseAPIError(exports.AILAB_STILL_ACTIVE,"still have runs active !")810 }else if err.Errno() == exports.AILAB_NOT_FOUND{811 return wrapDBUpdateError(tx.Delete(&Run{},"lab_id in ?",labs),0)812 }else{813 return err814 }815}816func checkReturnSingleon(err APIError) APIError {817 if err == nil{//exists singleton instance818 return exports.RaiseAPIError(exports.AILAB_SINGLETON_RUN_EXISTS,"singleton run exists")819 }else if err.Errno() == exports.AILAB_NOT_FOUND {820 return nil821 }else{822 return err823 }824}825func preCheckCreateRun(tx*gorm.DB, mlrun*BasicMLRunContext,req*exports.CreateJobRequest) (old*JobStatusChange,err APIError) {826 if mlrun.IsLabRun() {//create lab run827 if exports.IsJobShouldSingleton(req.JobFlags) {828 old = &JobStatusChange{}829 if exports.IsJobSingleton(req.JobFlags) {830 err = wrapDBQueryError(tx.Model(&Run{}).Select(select_run_status_change).831 First(old, "lab_id=? and job_type=?", mlrun.ID, req.JobType))832 }else{833 err = wrapDBQueryError(tx.Model(&Run{}).Select(select_run_status_change).834 First(old, "lab_id=? and job_type=? and user_id=?", mlrun.ID, req.JobType,req.UserId))835 }836 err = checkReturnSingleon(err)837 }else {838 if exports.IsJobIdentifyName(req.JobFlags){839 old = &JobStatusChange{}840 err = wrapDBQueryError(tx.Model(&Run{}).Select(select_run_status_change).841 First(old, "lab_id=? and job_type=? and name=?", mlrun.ID, req.JobType,req.Name))842 err = checkReturnSingleon(err)843 }844 mlrun.Starts ++845 }846 }else{// create nest run847 if exports.IsJobShouldSingleton(req.JobFlags) {848 old = &JobStatusChange{}849 if exports.IsJobSingleton(req.JobFlags) {850 err = wrapDBQueryError(tx.Model(&Run{}).Select(select_run_status_change).851 First(old, "parent=? and job_type=?", mlrun.RunId, req.JobType))852 }else{853 err = wrapDBQueryError(tx.Model(&Run{}).Select(select_run_status_change).854 First(old, "parent=? and job_type=? and user_id=?", mlrun.RunId, req.JobType,req.UserId))855 }856 err = checkReturnSingleon(err)857 }else {858 if exports.IsJobIdentifyName(req.JobFlags){859 old = &JobStatusChange{}860 err = wrapDBQueryError(tx.Model(&Run{}).Select(select_run_status_change).861 First(old, "parent=? and job_type=? and name=?", mlrun.RunId, req.JobType,req.Name))862 err = checkReturnSingleon(err)863 }864 mlrun.Started++865 }866 }867 return868}869func completeCreateRun(tx*gorm.DB, mlrun*BasicMLRunContext,req*exports.CreateJobRequest,run*Run) (err APIError){870 if !exports.IsJobShouldSingleton(req.JobFlags){//@modify: add singleton user runs871 if mlrun.IsLabRun() {//create lab run872 err = wrapDBUpdateError(tx.Table("labs").Where("id=? and deleted_at =0",mlrun.ID).873 Update("starts",mlrun.Starts),1)874 }else{// create nest run875 err = wrapDBUpdateError(tx.Table("runs").Where("run_id=? and deleted_at = 0",mlrun.RunId).876 Update("started",mlrun.Started),1)877 }878 }879 if err == nil && run.DeletedAt == 0 {// asynchronously prepare data880 mlrun.JobStatusChange(&JobStatusChange{881 JobType: req.JobType,882 Status: exports.AILAB_RUN_STATUS_INVALID,883 StatusTo: run.Status,884 })885 if err == nil {886 err = logStartingRun(tx,run.RunId,run.Status,mlrun.events)887 }888 }889 return err890}...
context.go
Source:context.go
1package oscar2import (3 "database/sql"4 "fmt"5 "regexp"6 "sync"7 "time"8 "github.com/mono83/oscar/events"9)10// NewContext builds and returns context to be used in tests11func NewContext() *Context {12 c := &Context{13 values: make(map[string]string),14 events: make(chan *events.Emitted),15 }16 go c.listenEvents()17 return c18}19// Context is test invocation context20type Context struct {21 parent *Context22 m sync.Mutex23 values map[string]string24 exports map[string]string25 database *sql.DB26 ownerID int27 wg sync.WaitGroup28 events chan *events.Emitted29 onEvent func(*events.Emitted)30}31// Register registers new event listener32func (c *Context) Register(f func(*events.Emitted)) {33 if f == nil {34 return35 }36 c.m.Lock()37 defer c.m.Unlock()38 if c.onEvent == nil {39 c.onEvent = f40 } else {41 prev := c.onEvent42 c.onEvent = func(event *events.Emitted) {43 f(event)44 prev(event)45 }46 }47}48// Fork builds and returns new child test context49func (c *Context) Fork(id int) *Context {50 c2 := &Context{51 parent: c,52 ownerID: id,53 values: make(map[string]string),54 events: make(chan *events.Emitted),55 }56 go c2.listenEvents()57 return c258}59// SetDatabase sets up database connection60func (c *Context) SetDatabase(db *sql.DB) {61 if c.parent != nil {62 c.parent.SetDatabase(db)63 return64 }65 c.m.Lock()66 defer c.m.Unlock()67 c.database = db68}69// GetDatabase returns database connection, associated with test context70func (c *Context) GetDatabase() *sql.DB {71 if c.parent != nil {72 return c.parent.GetDatabase()73 }74 return c.database75}76func (c *Context) listenEvents() {77 for e := range c.events {78 c.wg.Done()79 if c.onEvent != nil {80 c.onEvent(e)81 }82 }83}84// Sleep freezes goroutine for required amount of time85func (c *Context) Sleep(duration time.Duration) {86 if duration.Nanoseconds() > 0 {87 c.Tracef("Entering sleep for %s", duration.String())88 c.Emit(events.Sleep(duration))89 time.Sleep(duration)90 }91}92func (c *Context) realEmit(e *events.Emitted) {93 c.wg.Add(1)94 c.events <- e95 if c.parent != nil {96 c.parent.realEmit(e)97 }98}99// Emit emits event to registered consumers100func (c *Context) Emit(t interface{}) {101 if t != nil {102 c.realEmit(&events.Emitted{OwnerID: c.ownerID, Time: time.Now(), Data: t})103 }104}105// Wait locks goroutine and waits for all events to be delivered106func (c *Context) Wait() {107 if c.parent != nil {108 c.parent.Wait()109 }110 c.wg.Wait()111}112// Tracef sends TRACE event without interpolation but with sprintf formatting113func (c *Context) Tracef(pattern string, a ...interface{}) {114 c.Emit(events.LogEvent{Level: events.LogLevelTrace, Pattern: fmt.Sprintf(pattern, a...)})115}116// Debug sends DEBUG event with variables interpolation117func (c *Context) Debug(message string) {118 c.Emit(events.LogEvent{Level: events.LogLevelDebug, Pattern: c.Interpolate(message)})119}120// Debugf sends DEBUG event without interpolation but with sprintf formatting121func (c *Context) Debugf(pattern string, a ...interface{}) {122 c.Emit(events.LogEvent{Level: events.LogLevelDebug, Pattern: fmt.Sprintf(pattern, a...)})123}124// Info sends INFO event with variables interpolation125func (c *Context) Info(message string) {126 c.Emit(events.LogEvent{Level: events.LogLevelInfo, Pattern: c.Interpolate(message)})127}128// Infof sends INFO event without interpolation but with sprintf formatting129func (c *Context) Infof(pattern string, a ...interface{}) {130 c.Emit(events.LogEvent{Level: events.LogLevelInfo, Pattern: fmt.Sprintf(pattern, a...)})131}132// Errorf sends ERROR event without interpolation but with sprintf formatting133func (c *Context) Errorf(pattern string, a ...interface{}) {134 c.Emit(events.LogEvent{Level: events.LogLevelError, Pattern: fmt.Sprintf(pattern, a...)})135}136// Fail emits Failure event137func (c *Context) Fail(message string) {138 c.Emit(events.Failure(message))139}140// Get returns variable value141func (c *Context) Get(key string) string {142 c.m.Lock()143 defer c.m.Unlock()144 // Reading own values145 if len(c.values) > 0 {146 if value, ok := c.values[key]; ok {147 return value148 }149 }150 // Reading values from parent151 if c.parent != nil {152 return c.parent.Get(key)153 }154 // Reading values from export variables155 if len(c.exports) > 0 {156 if value, ok := c.exports[key]; ok {157 return value158 }159 }160 return ""161}162// GetExport returns map of export variables163func (c *Context) GetExport() map[string]string {164 return c.exports165}166// Set places new variable value167func (c *Context) Set(key, value string) {168 c.m.Lock()169 defer c.m.Unlock()170 var prev *string171 if v, ok := c.values[key]; ok {172 prev = &v173 }174 c.values[key] = value175 c.Emit(events.SetVar{Key: key, Value: value, Previous: prev})176}177// SetExport adds variable on top scope level178func (c *Context) SetExport(key, value string) {179 if c.parent != nil {180 c.parent.SetExport(key, value)181 } else {182 c.m.Lock()183 defer c.m.Unlock()184 if len(c.exports) == 0 {185 c.exports = map[string]string{}186 }187 c.exports[key] = value188 }189}190// Import writes variable values and do not emit event about this191// This method may be used to fill initial data or to copy data from SetUp func192func (c *Context) Import(m map[string]string) {193 c.m.Lock()194 defer c.m.Unlock()195 if len(m) > 0 {196 for k, v := range m {197 c.values[k] = v198 }199 }200}201// AssertFinished sends event about finished assertion202func (c *Context) AssertFinished(success bool, operation, qualifier, doc string, actual, expected interface{}) {203 c.Emit(events.AssertDone{204 Success: success,205 Operation: operation,206 Actual: actual,207 Expected: expected,208 Qualifier: qualifier,209 Doc: doc,210 })211}212var iregex = regexp.MustCompile(`\${([\w.-]+)}`)213// Interpolate replaces all placeholders in provided string using vars from test case or214// global runner215func (c *Context) Interpolate(value string) string {216 return iregex.ReplaceAllStringFunc(value, func(i string) string {217 m := iregex.FindStringSubmatch(i)218 return c.Get(m[1])219 })220}...
contract.go
Source:contract.go
...105 f.Func.SetPtrs(&f.Params.id, &f.Results.id)106 return f107}108func OnLoad() {109 exports := wasmlib.NewScExports()110 exports.AddView(ViewControlAddresses, wasmlib.ViewError)111 exports.AddView(ViewGetBlockInfo, wasmlib.ViewError)112 exports.AddView(ViewGetEventsForBlock, wasmlib.ViewError)113 exports.AddView(ViewGetEventsForContract, wasmlib.ViewError)114 exports.AddView(ViewGetEventsForRequest, wasmlib.ViewError)115 exports.AddView(ViewGetLatestBlockInfo, wasmlib.ViewError)116 exports.AddView(ViewGetRequestIDsForBlock, wasmlib.ViewError)117 exports.AddView(ViewGetRequestReceipt, wasmlib.ViewError)118 exports.AddView(ViewGetRequestReceiptsForBlock, wasmlib.ViewError)119 exports.AddView(ViewIsRequestProcessed, wasmlib.ViewError)120}...
Exports
Using AI Code Generation
1import (2func main() {3 widgets.NewQApplication(len(os.Args), os.Args)4 window := widgets.NewQMainWindow(nil, 0)5 window.SetWindowTitle("Hello World Example")6 window.SetMinimumSize2(200, 200)7 window.SetMaximumSize2(200, 200)8 label := widgets.NewQLabel2("Hello World!", nil, 0)9 label.SetAlignment(core.Qt__AlignCenter)10 window.SetCentralWidget(label)11 window.Show()12 widgets.QApplication_Exec()13}14import (15func main() {16 widgets.NewQApplication(len(os.Args), os.Args)17 window := widgets.NewQMainWindow(nil, 0)18 window.SetWindowTitle("Hello World Example")19 window.SetMinimumSize2(200, 200)20 window.SetMaximumSize2(200, 200)21 label := widgets.NewQLabel2("Hello World!", nil, 0)22 label.SetAlignment(core.Qt__AlignCenter)23 window.SetCentralWidget(label)24 window.Show()25 widgets.QApplication_Exec()26}27import (28func main() {29 widgets.NewQApplication(len(os.Args), os.Args)30 window := widgets.NewQMainWindow(nil, 0)31 window.SetWindowTitle("Hello World Example")32 window.SetMinimumSize2(200, 200)33 window.SetMaximumSize2(200, 200)34 label := widgets.NewQLabel2("Hello World!", nil, 0)35 label.SetAlignment(core.Qt__AlignCenter)36 window.SetCentralWidget(label)37 window.Show()38 widgets.QApplication_Exec()39}40import (
Exports
Using AI Code Generation
1import (2func main() {3 client, err := client.NewClient(client.ClientOptions{4 DefaultUserCredentials: &client.UserCredentials{5 },6 })7 if err != nil {8 log.Fatalf("cannot create client: %s", err)9 }10 defer client.Close()11 _, err = client.AppendToStream(streamName, streamrevision.WriteStreamRevisionNoStream, nil)12 if err != nil {13 log.Fatalf("cannot append to stream: %s", err)14 }15 subscription, err := client.SubscribeToStream(16 &subscriptions.SubscribeToStreamOptions{17 FilterOptions: options.FilterOptions{18 Filter: filtering.EventType("some-event"),19 },20 },21 if err != nil {22 log.Fatalf("cannot subscribe to stream: %s", err)23 }24 event := streams.NewJsonEvent("some-event", nil, []byte(`{"message":"hello world"}`))25 _, err = client.AppendToStream(streamName, streamrevision.WriteStreamRevisionNoStream, []streams.ProposedEvent{event})26 if err != nil {27 log.Fatalf("cannot append to stream: %s", err)28 }29 if !ok {30 log.Fatalf("subscription channel closed unexpectedly")31 }32 fmt.Printf("received event: %s",
Exports
Using AI Code Generation
1import (2func main() {3 svc := cloudwatchevents.New(nil)4 params := &cloudwatchevents.ListRulesInput{5 Limit: aws.Long(10),6 }7 resp, err := svc.ListRules(params)8 if err != nil {9 fmt.Println(err.Error())10 }11 fmt.Println(resp)12}13import (14func main() {15 svc := cloudwatchlogs.New(nil)16 params := &cloudwatchlogs.DescribeLogGroupsInput{17 Limit: aws.Long(10),18 }19 resp, err := svc.DescribeLogGroups(params)20 if err != nil {21 fmt.Println(err.Error())22 }23 fmt.Println(resp)24}25import (26func main() {27 svc := ec2.New(nil)28 params := &ec2.DescribeInstancesInput{29 Filters: []*ec2.Filter{30 Name: aws.String("String"),31 Values: []*string{32 },33 },34 },35 InstanceIDs: []*string{36 },37 MaxResults: aws.Long(1),38 NextToken: aws.String("String"),39 }40 resp, err := svc.DescribeInstances(params)41 if err != nil {42 fmt.Println(err.Error())43 }44 fmt.Println(resp)45}46import (
Exports
Using AI Code Generation
1import (2func main() {3 vm := otto.New()4 underscore.Enable(vm)5 vm.Run(`6 var events = require('events');7 var emitter = new events.EventEmitter();8 emitter.on('test', function() {9 console.log('test event fired');10 });11 emitter.emit('test');12}13import (14func main() {15 vm := otto.New()16 underscore.Enable(vm)17 vm.Run(`18 var events = require('events');19 var emitter = new events.EventEmitter();20 emitter.on('test', function() {21 console.log('test event fired');22 });23 emitter.emit('test');24}25import (26func main() {27 vm := otto.New()28 underscore.Enable(vm)29 vm.Run(`30 var events = require('events');31 var emitter = new events.EventEmitter();32 emitter.on('test', function() {33 console.log('test event fired');34 });35 emitter.emit('test');36}
Exports
Using AI Code Generation
1import (2func main() {3 vm := otto.New()4 vm.Set("print", func(call otto.FunctionCall) otto.Value {5 fmt.Println(call.Argument(0))6 return otto.Value{}7 })8 file, err := os.Open("2.js")9 if err != nil {10 panic(err)11 }12 defer file.Close()13 vm.Run(file)14}15var events = require('events');16var eventEmitter = new events.EventEmitter();17var myEventHandler = function () {18 console.log('I hear a scream!');19}20eventEmitter.on('scream', myEventHandler);21eventEmitter.emit('scream');
Exports
Using AI Code Generation
1import (2func main() {3 xlFile, err := xlsx.OpenFile(excelFileName)4 if err != nil {5 log.Fatal(err)6 }7 for _, sheet := range xlFile.Sheets {8 for _, row := range sheet.Rows {9 for _, cell := range row.Cells {10 text := cell.String()11 fmt.Printf("%s\n", text)12 }13 }14 }15}16import (17func main() {18 xlFile, err := xlsx.OpenFile(excelFileName)19 if err != nil {20 log.Fatal(err)21 }22 for _, sheet := range xlFile.Sheets {23 for _, row := range sheet.Rows {24 for _, cell := range row.Cells {25 text := cell.String()26 fmt.Printf("%s\n", text)27 }28 }29 }30}31import (32func main() {33 xlFile, err := xlsx.OpenFile(excelFileName)34 if err != nil {35 log.Fatal(err)36 }37 for _, sheet := range xlFile.Sheets {38 for _, row := range sheet.Rows {39 for _, cell := range row.Cells {40 text := cell.String()41 fmt.Printf("%s\n", text)42 }43 }44 }45}
Exports
Using AI Code Generation
1import (2var (3 pingPeriod = (pongWait * 9) / 104 newline = []byte{'\n'}5 clients = make(map[*websocket.Conn]bool)6 broadcast = make(chan Message)7type Message struct {8}9var upgrader = websocket.Upgrader{10 CheckOrigin: func(r *http.Request) bool { return true },11}12func main() {13 router := mux.NewRouter()14 router.HandleFunc("/ws", handleConnections)15 go handleMessages()16 log.Println("http server started on :8000")17 err := http.ListenAndServe(":8000", router)18 if err != nil {19 log.Fatal("ListenAndServe: ", err)20 }21}22func handleConnections(w http.ResponseWriter, r *http.Request) {23 ws, err := upgrader.Upgrade(w, r, nil)24 if err != nil {25 log.Fatal(err)26 }27 defer ws.Close()28 for {29 err := ws.ReadJSON(&msg)30 if err != nil {31 log.Printf("error: %v", err)32 delete(clients, ws)
Exports
Using AI Code Generation
1import (2func main() {3 e := events.New()4 e.On("hello", func() {5 fmt.Println("hello")6 })7 e.Emit("hello")8}9import (10func main() {11 e := events.New()12 e.On("hello", func() {13 fmt.Println("hello")14 })15 e.Emit("hello")16}17import (18func main() {19 e := events.New()20 e.On("hello", func() {21 fmt.Println("hello")22 })23 e.Emit("hello")24}25import (26func main() {27 e := events.New()28 e.On("hello", func() {29 fmt.Println("hello")30 })31 e.Emit("hello")32}33import (34func main() {35 e := events.New()36 e.On("hello", func() {37 fmt.Println("hello")38 })39 e.Emit("hello")40}41import (42func main() {43 e := events.New()44 e.On("hello", func() {45 fmt.Println("hello")46 })47 e.Emit("hello")48}49import (50func main() {51 e := events.New()52 e.On("hello", func() {53 fmt.Println("hello")54 })55 e.Emit("hello")56}
Exports
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 events.Exports()5}6import (7func main() {8 fmt.Println("Hello, playground")9 events.Exports()10}11import (12func Exports() {13 fmt.Println("Hello, events")14}15import (16func main() {17 http.HandleFunc("/", handler)18 log.Fatal(http.ListenAndServe("localhost:8000", nil))19}20func handler(w http.ResponseWriter, r *http.Request) {21 fmt.Fprintf(w, "URL.Path = %q22}23net/http.(*conn).serve.func1(0xc04208e000)24panic(0x6b5c40, 0x8a4a80)25main.handler(0x7e7b60, 0xc042070000, 0xc0420a0000)
Exports
Using AI Code Generation
1import (2func main() {3 fmt.Println(stringutil.MyName)4 fmt.Println(stringutil.Reverse("!oG ,olleH"))5}6import (7func main() {8 fmt.Println(stringutil.MyName)9 fmt.Println(stringutil.Reverse("!oG ,olleH"))10}11import (12func main() {13 fmt.Println(stringutil.MyName)14 fmt.Println(stringutil.Reverse("!oG ,olleH"))15}16import (17func main() {18 fmt.Println(stringutil.MyName)19 fmt.Println(stringutil.Reverse("!oG ,olleH"))20}21import (22func main() {23 fmt.Println(stringutil.MyName)24 fmt.Println(stringutil.Reverse("!oG ,olleH"))25}26import (27func main() {28 fmt.Println(stringutil.MyName)29 fmt.Println(stringutil.Reverse("!oG ,olleH"))30}31import (32func main() {33 fmt.Println(stringutil.MyName)34 fmt.Println(stringutil.Reverse("!oG ,olleH"))35}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!