How to use Select method of rod Package

Best Rod code snippet using rod.Select

element_test.go

Source:element_test.go Github

copy

Full Screen

...262 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))263 el := p.MustElement("[type=checkbox]")264 g.True(el.MustClick().MustProperty("checked").Bool())265}266func TestSelectText(t *testing.T) {267 g := setup(t)268 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))269 el := p.MustElement("textarea")270 el.MustInput("test")271 el.MustSelectAllText()272 el.MustInput("test")273 g.Eq("test", el.MustText())274 el.MustSelectText(`es`)275 el.MustInput("__")276 g.Eq("t__t", el.MustText())277 g.Panic(func() {278 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})279 el.MustSelectText("")280 })281 g.Panic(func() {282 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})283 el.MustSelectAllText()284 })285 g.Panic(func() {286 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})287 el.MustInput("")288 })289 g.Panic(func() {290 g.mc.stubErr(1, proto.InputInsertText{})291 el.MustInput("")292 })293}294func TestBlur(t *testing.T) {295 g := setup(t)296 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))297 el := p.MustElement("#blur").MustInput("test").MustBlur()298 g.Eq("ok", *el.MustAttribute("a"))299}300func TestSelectQuery(t *testing.T) {301 g := setup(t)302 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))303 el := p.MustElement("select")304 err := el.Select([]string{`[value="c"]`}, true, rod.SelectorTypeCSSSector)305 g.E(err)306 g.Eq(2, el.MustEval("() => this.selectedIndex").Int())307}308func TestSelectOptions(t *testing.T) {309 g := setup(t)310 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))311 el := p.MustElement("select")312 el.MustSelect("B", "C")313 g.Eq("B,C", el.MustText())314 g.Eq(1, el.MustProperty("selectedIndex").Int())315 // unselect with regex316 err := el.Select([]string{`^B$`}, false, rod.SelectorTypeRegex)317 g.E(err)318 g.Eq("C", el.MustText())319 // unselect with css selector320 err = el.Select([]string{`[value="c"]`}, false, rod.SelectorTypeCSSSector)321 g.E(err)322 g.Eq("", el.MustText())323 // option not found error324 g.Is(el.Select([]string{"not-exists"}, true, rod.SelectorTypeCSSSector), &rod.ErrElementNotFound{})325 {326 g.mc.stubErr(5, proto.RuntimeCallFunctionOn{})327 g.Err(el.Select([]string{"B"}, true, rod.SelectorTypeText))328 }329}330func TestMatches(t *testing.T) {331 g := setup(t)332 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))333 el := p.MustElement("textarea")334 g.True(el.MustMatches(`[cols="30"]`))335 g.Panic(func() {336 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})337 el.MustMatches("")338 })339}340func TestAttribute(t *testing.T) {341 g := setup(t)342 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))343 el := p.MustElement("textarea")344 cols := el.MustAttribute("cols")345 rows := el.MustAttribute("rows")346 g.Eq("30", *cols)347 g.Eq("10", *rows)348 p = g.page.MustNavigate(g.srcFile("fixtures/click.html"))349 el = p.MustElement("button").MustClick()350 g.Eq("ok", *el.MustAttribute("a"))351 g.Nil(el.MustAttribute("b"))352 g.Panic(func() {353 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})354 el.MustAttribute("")355 })356}357func TestProperty(t *testing.T) {358 g := setup(t)359 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))360 el := p.MustElement("textarea")361 cols := el.MustProperty("cols")362 rows := el.MustProperty("rows")363 g.Eq(float64(30), cols.Num())364 g.Eq(float64(10), rows.Num())365 p = g.page.MustNavigate(g.srcFile("fixtures/open-page.html"))366 el = p.MustElement("a")367 g.Eq("link", el.MustProperty("id").Str())368 g.Eq("_blank", el.MustProperty("target").Str())369 g.True(el.MustProperty("test").Nil())370 g.Panic(func() {371 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})372 el.MustProperty("")373 })374}375func TestSetFiles(t *testing.T) {376 g := setup(t)377 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))378 el := p.MustElement(`[type=file]`)379 el.MustSetFiles(380 slash("fixtures/click.html"),381 slash("fixtures/alert.html"),382 )383 list := el.MustEval("() => Array.from(this.files).map(f => f.name)").Arr()384 g.Len(list, 2)385 g.Eq("alert.html", list[1].String())386}387func TestEnter(t *testing.T) {388 g := setup(t)389 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))390 el := p.MustElement("[type=submit]")391 el.MustType(input.Enter)392 g.True(p.MustHas("[event=submit]"))393}394func TestWaitInvisible(t *testing.T) {395 g := setup(t)396 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))397 h4 := p.MustElement("h4")398 btn := p.MustElement("button")399 g.True(h4.MustVisible())400 h4.MustWaitVisible()401 go func() {402 utils.Sleep(0.03)403 h4.MustEval(`() => this.remove()`)404 utils.Sleep(0.03)405 btn.MustEval(`() => this.style.visibility = 'hidden'`)406 }()407 h4.MustWaitInvisible()408 btn.MustWaitInvisible()409 g.False(p.MustHas("h4"))410}411func TestWaitEnabled(t *testing.T) {412 g := setup(t)413 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))414 p.MustElement("button").MustWaitEnabled()415}416func TestWaitWritable(t *testing.T) {417 g := setup(t)418 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))419 p.MustElement("input").MustWaitWritable()420}421func TestWaitStable(t *testing.T) {422 g := setup(t)423 p := g.page.MustNavigate(g.srcFile("fixtures/wait-stable.html"))424 el := p.MustElement("button")425 go func() {426 utils.Sleep(1)427 el.MustEval(`() => this.classList.remove("play")`)428 }()429 start := time.Now()430 el.MustWaitStable()431 g.Gt(time.Since(start), time.Second)432 ctx := g.Context()433 g.mc.stub(1, proto.DOMGetContentQuads{}, func(send StubSend) (gson.JSON, error) {434 go func() {435 utils.Sleep(0.1)436 ctx.Cancel()437 }()438 return send()439 })440 g.Err(el.Context(ctx).WaitStable(time.Minute))441 g.Panic(func() {442 g.mc.stubErr(1, proto.DOMGetContentQuads{})443 el.MustWaitStable()444 })445 g.Panic(func() {446 g.mc.stubErr(2, proto.DOMGetContentQuads{})447 el.MustWaitStable()448 })449}450func TestWaitStableRAP(t *testing.T) {451 g := setup(t)452 p := g.page.MustNavigate(g.srcFile("fixtures/wait-stable.html"))453 el := p.MustElement("button")454 go func() {455 utils.Sleep(1)456 el.MustEval(`() => this.classList.remove("play")`)457 }()458 start := time.Now()459 g.E(el.WaitStableRAF())460 g.Gt(time.Since(start), time.Second)461 g.mc.stubErr(2, proto.RuntimeCallFunctionOn{})462 g.Err(el.WaitStableRAF())463 g.mc.stubErr(1, proto.DOMGetContentQuads{})464 g.Err(el.WaitStableRAF())465}466func TestCanvasToImage(t *testing.T) {467 g := setup(t)468 p := g.page.MustNavigate(g.srcFile("fixtures/canvas.html"))469 src, err := png.Decode(bytes.NewBuffer(p.MustElement("#canvas").MustCanvasToImage()))470 g.E(err)471 g.Eq(src.At(50, 50), color.NRGBA{0xFF, 0x00, 0x00, 0xFF})472}473func TestElementWaitLoad(t *testing.T) {474 g := setup(t)475 p := g.page.MustNavigate(g.srcFile("fixtures/resource.html"))476 p.MustElement("img").MustWaitLoad()477}478func TestResource(t *testing.T) {479 g := setup(t)480 p := g.page.MustNavigate(g.srcFile("fixtures/resource.html"))481 el := p.MustElement("img")482 g.Eq(len(el.MustResource()), 22661)483 g.mc.stub(1, proto.PageGetResourceContent{}, func(send StubSend) (gson.JSON, error) {484 return gson.New(proto.PageGetResourceContentResult{485 Content: "ok",486 Base64Encoded: false,487 }), nil488 })489 g.Eq([]byte("ok"), el.MustResource())490 g.Panic(func() {491 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})492 el.MustResource()493 })494 g.Panic(func() {495 g.mc.stubErr(1, proto.PageGetResourceContent{})496 el.MustResource()497 })498}499func TestBackgroundImage(t *testing.T) {500 g := setup(t)501 p := g.page.MustNavigate(g.srcFile("fixtures/resource.html"))502 el := p.MustElement("div")503 g.Eq(len(el.MustBackgroundImage()), 22661)504 {505 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})506 g.Err(el.BackgroundImage())507 }508}509func TestElementScreenshot(t *testing.T) {510 g := setup(t)511 f := filepath.Join("tmp", "screenshots", g.RandStr(16)+".png")512 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))513 el := p.MustElement("h4")514 data := el.MustScreenshot(f)515 img, err := png.Decode(bytes.NewBuffer(data))516 g.E(err)517 g.Eq(200, img.Bounds().Dx())518 g.Eq(30, img.Bounds().Dy())519 g.Nil(os.Stat(f))520 g.Panic(func() {521 g.mc.stubErr(1, proto.DOMScrollIntoViewIfNeeded{})522 el.MustScreenshot()523 })524 g.Panic(func() {525 g.mc.stubErr(1, proto.PageCaptureScreenshot{})526 el.MustScreenshot()527 })528 g.Panic(func() {529 g.mc.stubErr(3, proto.DOMGetContentQuads{})530 el.MustScreenshot()531 })532}533func TestUseReleasedElement(t *testing.T) {534 g := setup(t)535 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))536 btn := p.MustElement("button")537 btn.MustRelease()538 g.Err(btn.Click("left", 1))539 btn = p.MustElement("button")540 g.E(proto.RuntimeReleaseObject{ObjectID: btn.Object.ObjectID}.Call(p))541 g.Is(btn.Click("left", 1), cdp.ErrObjNotFound)542}543func TestElementRemove(t *testing.T) {544 g := setup(t)545 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))546 btn := p.MustElement("button")547 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})548 g.Err(btn.Remove())549}550func TestElementMultipleTimes(t *testing.T) {551 g := setup(t)552 // To see whether chrome will reuse the remote object ID or not.553 // Seems like it will not.554 page := g.page.MustNavigate(g.srcFile("fixtures/click.html"))555 btn01 := page.MustElement("button")556 btn02 := page.MustElement("button")557 g.Eq(btn01.MustText(), btn02.MustText())558 g.Neq(btn01.Object, btn02.Object)559}560func TestFnErr(t *testing.T) {561 g := setup(t)562 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))563 el := p.MustElement("button")564 _, err := el.Eval("foo()")565 g.Err(err)566 g.Has(err.Error(), "ReferenceError: foo is not defined")567 var e *rod.ErrEval568 g.True(errors.As(err, &e))569 g.Eq(proto.RuntimeRemoteObjectSubtypeError, e.Exception.Subtype)570 _, err = el.ElementByJS(rod.Eval("() => foo()"))571 g.Err(err)572 g.Has(err.Error(), "ReferenceError: foo is not defined")573 g.True(errors.Is(err, &rod.ErrEval{}))574}575func TestElementEWithDepth(t *testing.T) {576 g := setup(t)577 checkStr := `green tea`578 p := g.page.MustNavigate(g.srcFile("fixtures/describe.html"))579 ulDOMNode, err := p.MustElement(`ul`).Describe(-1, true)580 g.Nil(errors.Unwrap(err))581 data, err := json.Marshal(ulDOMNode)582 g.Nil(errors.Unwrap(err))583 // The depth is -1, should contain checkStr584 g.Has(string(data), checkStr)585}586func TestElementOthers(t *testing.T) {587 g := setup(t)588 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))589 el := p.MustElement("form")590 el.MustFocus()591 el.MustScrollIntoView()592 g.Eq("submit", el.MustElement("[type=submit]").MustText())593 g.Eq("<input type=\"submit\" value=\"submit\">", el.MustElement("[type=submit]").MustHTML())594 el.MustWait(`() => true`)595 g.Eq("form", el.MustElementByJS(`() => this`).MustDescribe().LocalName)596 g.Len(el.MustElementsByJS(`() => []`), 0)597}598func TestElementEqual(t *testing.T) {599 g := setup(t)600 p := g.page.MustNavigate(g.srcFile("fixtures/describe.html"))601 el1 := p.MustElement("body > ul")602 el2 := p.MustElement("html > body > ul")603 g.True(el1.MustEqual(el2))604 el3 := p.MustElement("ul ul")605 g.False(el1.MustEqual(el3))606}607func TestElementWait(t *testing.T) {608 g := setup(t)609 p := g.page.MustNavigate(g.srcFile("fixtures/describe.html"))610 e1 := p.MustElement("body > ul > li")611 g.Eq(e1.MustText(), "coffee")612 params := []interface{}{1, 3, 4}613 go func() {614 utils.Sleep(0.3)615 e1.MustEval(`(a, b, c) => this.innerText = 'x'.repeat(a + b + c)`, params...)616 }()617 e1.MustWait(`(a, b, c) => this.innerText.length === (a + b + c)`, params...)618 g.Eq(e1.MustText(), "xxxxxxxx")619}620func TestShapeInIframe(t *testing.T) {621 g := setup(t)622 p := g.page.MustNavigate(g.srcFile("fixtures/click-iframe.html"))623 pt := p.MustElement("iframe").MustFrame().MustElement("button").MustShape().OnePointInside()624 g.InDelta(pt.X, 238, 1)625 g.InDelta(pt.Y, 287, 1)626}627func TestElementFromPointErr(t *testing.T) {628 g := setup(t)629 g.mc.stubErr(1, proto.DOMGetNodeForLocation{})630 g.Err(g.page.ElementFromPoint(10, 10))631}632func TestElementFromNodeErr(t *testing.T) {633 g := setup(t)634 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))635 el := p.MustElementX("//button/text()")636 g.mc.stubErr(3, proto.RuntimeCallFunctionOn{})637 g.Err(p.ElementFromNode(el.MustDescribe()))638}639func TestElementErrors(t *testing.T) {640 g := setup(t)641 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))642 el := p.MustElement("form")643 ctx := g.Timeout(0)644 _, err := el.Context(ctx).Describe(-1, true)645 g.Err(err)646 _, err = el.Context(ctx).Frame()647 g.Err(err)648 err = el.Context(ctx).Focus()649 g.Err(err)650 _, err = el.Context(ctx).KeyActions()651 g.Err(err)652 err = el.Context(ctx).Input("a")653 g.Err(err)654 err = el.Context(ctx).Select([]string{"a"}, true, rod.SelectorTypeText)655 g.Err(err)656 err = el.Context(ctx).WaitStable(0)657 g.Err(err)658 _, err = el.Context(ctx).Resource()659 g.Err(err)660 err = el.Context(ctx).Input("a")661 g.Err(err)662 err = el.Context(ctx).Input("a")663 g.Err(err)664 _, err = el.Context(ctx).HTML()665 g.Err(err)666 _, err = el.Context(ctx).Visible()667 g.Err(err)668 _, err = el.Context(ctx).CanvasToImage("", 0)...

Full Screen

Full Screen

moves.go

Source:moves.go Github

copy

Full Screen

...42 }43 }44 // select new configuration45 var new_surface_energy float6446 new_rod.orientation, new_surface_energy = SelectWeightedConfig(new_orientations, new_surface_energies, new_weights, new_weight_sum, config.k)47 // run k-1 rosenbluth trials to generate weights for original configuration48 var og_weight_sum float64 = math.Exp(-config.beta * og_surface_energy)49 for i := 0; i < (config.k - 1); i++ {50 GetRandOrientation(config, og_rod)51 GetAxes(og_rod)52 GetVertices(config.n_dim, config.n_vertices, og_rod)53 no_overlaps := CheckNeighborOverlaps(og_rod, grid, rods, config)54 if no_overlaps {55 surface_energy := CalcSurfaceEnergy(og_rod, config)56 og_weight_sum += math.Exp(-config.beta * surface_energy)57 }58 }59 // calculate acceptance probability for swap60 var acc float6461 if config.k == 1 {62 acc = math.Exp(-config.beta * (new_surface_energy - og_surface_energy))63 } else {64 acc = (og_weight_sum / new_weight_sum) * math.Exp(-config.beta*(new_surface_energy-og_surface_energy))65 }66 if rand.Float64() < acc {67 // move accepted68 GetAxes(new_rod)69 GetVertices(config.n_dim, config.n_vertices, new_rod)70 if og_grid_id == new_rod.grid_id {71 rods[rod.id] = new_rod72 } else {73 new_rod.grid_id = og_grid_id // temporarily store old grid_id in rod to update old neighbor lists74 RemFromNeighborLists(new_rod, grid)75 new_rod.grid_id = new_grid_id // restore new grid_id to add to new neighbor lists76 AddToNeighborLists(new_rod, grid)77 rods[rod.id] = new_rod78 }79 config.potential_energy += (new_surface_energy - og_surface_energy)80 config.swap_successes++81 }82 config.swap_attempts++83}84func Translate(rod *Rod, grid []*GridSpace, config *Config, rods []*Rod) {85 // store original rod location and grid id86 og_loc := rod.loc87 og_grid_id := rod.grid_id88 // get new location within 1 distance away from current rod COM89 new_loc := make([]float64, config.n_dim)90 if !config.restrict_translations {91 var max_r float64 = 192 max_theta := 2 * math.Pi93 r := rand.Float64() * max_r94 theta := rand.Float64() * max_theta95 v := [2]float64{r * math.Sin(theta), r * math.Cos(theta)}96 new_loc[0] = og_loc[0] + v[0]97 new_loc[1] = og_loc[1] + v[1]98 if new_loc[0] >= config.box_dims[0] {99 new_loc[0] -= config.box_dims[0]100 }101 if new_loc[1] >= config.box_dims[1] {102 new_loc[1] -= config.box_dims[1]103 }104 if new_loc[0] < 0 {105 new_loc[0] += config.box_dims[0]106 }107 if new_loc[1] < 0 {108 new_loc[1] += config.box_dims[0]109 }110 } else {111 rand_move_idx := rand.Intn(len(config.lattice_moves))112 rand_move := config.lattice_moves[rand_move_idx]113 new_lattice_x := rod.lattice_x + rand_move[0]114 new_lattice_y := rod.lattice_y + rand_move[1]115 if new_lattice_x >= config.lattice_x {116 new_lattice_x -= config.lattice_x117 }118 if new_lattice_y >= config.lattice_y {119 new_lattice_y -= config.lattice_y120 }121 if new_lattice_x < 0 {122 new_lattice_x += config.lattice_x123 }124 if new_lattice_y < 0 {125 new_lattice_y += config.lattice_y126 }127 rod.lattice_x = new_lattice_x128 rod.lattice_y = new_lattice_y129 new_loc[0] = config.lattice_grid[rod.lattice_x][rod.lattice_y][0]130 new_loc[1] = config.lattice_grid[rod.lattice_x][rod.lattice_y][1]131 if new_loc[0] > config.box_dims[0] {132 new_loc[0] -= config.box_dims[0]133 }134 if new_loc[1] > config.box_dims[1] {135 new_loc[1] -= config.box_dims[1]136 }137 if new_loc[0] < 0 {138 new_loc[0] += config.box_dims[0]139 }140 if new_loc[1] < 0 {141 new_loc[1] += config.box_dims[0]142 }143 }144 rod.loc = new_loc145 GetGridID(config.box_dims, config.n_bins, config.grid_bins, rod)146 GetAxes(rod)147 GetVertices(config.n_dim, config.n_vertices, rod)148 new_grid_id := rod.grid_id149 // check new rod location for overlaps150 no_overlaps := CheckNeighborOverlaps(rod, grid, rods, config)151 // automatically accept move if there are no overlaps152 if no_overlaps {153 // move accepted154 if og_grid_id == rod.grid_id {155 rods[rod.id] = rod156 } else {157 rod.grid_id = og_grid_id // temporarily store old grid_id in rod to update old neighbor lists158 RemFromNeighborLists(rod, grid)159 rod.grid_id = new_grid_id // restore new grid_id to add to new neighbor lists160 AddToNeighborLists(rod, grid)161 }162 config.translation_successes++163 } else {164 // move rejected165 rod.loc = og_loc166 rod.grid_id = og_grid_id167 GetAxes(rod)168 GetVertices(config.n_dim, config.n_vertices, rod)169 }170 config.translation_attempts++171}172func Rotate(rod *Rod, grid []*GridSpace, config *Config, rods []*Rod) {173 // copy rod structs to use for rosenbluth trials174 og_rod := RodDeepCopy(rod)175 new_rod := RodDeepCopy(rod)176 // calculate initial surface energy177 og_surface_energy := CalcSurfaceEnergy(og_rod, config)178 // fmt.Printf("Original Surface Energy: %f\n", og_surface_energy)179 // run k rosenbluth trials to generate rotation weights (same location - new orientations)180 GetRandOrientation(config, new_rod)181 GetAxes(new_rod)182 GetVertices(config.n_dim, config.n_vertices, new_rod)183 new_weights := make([]float64, config.k)184 var new_weight_sum float64 = 0185 new_orientations := make([]float64, config.k)186 new_surface_energies := make([]float64, config.k)187 for i := 0; i < config.k; i++ {188 new_orientations[i] = new_rod.orientation189 surface_energy := CalcSurfaceEnergy(new_rod, config)190 no_overlaps := CheckNeighborOverlaps(new_rod, grid, rods, config)191 if no_overlaps {192 p := math.Exp(-config.beta * surface_energy)193 // fmt.Printf("New Surface Energy: %f\n", surface_energy)194 new_weights[i] = p195 new_weight_sum += p196 new_surface_energies[i] = surface_energy197 } else {198 // fmt.Printf("New Surface Energy: %f\n", surface_energy+10e8)199 new_weights[i] = 0200 new_surface_energies[i] = surface_energy + 10e8201 }202 if i != (config.k - 1) {203 GetRandOrientation(config, new_rod)204 GetAxes(new_rod)205 GetVertices(config.n_dim, config.n_vertices, new_rod)206 }207 }208 // select new configuration209 var new_surface_energy float64210 new_rod.orientation, new_surface_energy = SelectWeightedConfig(new_orientations, new_surface_energies, new_weights, new_weight_sum, config.k)211 // run k-1 rosenbluth trials to generate weights for original configuration212 var og_weight_sum float64 = math.Exp(-config.beta * og_surface_energy)213 for i := 0; i < (config.k - 1); i++ {214 GetRandOrientation(config, og_rod)215 GetAxes(og_rod)216 GetVertices(config.n_dim, config.n_vertices, og_rod)217 no_overlaps := CheckNeighborOverlaps(og_rod, grid, rods, config)218 if no_overlaps {219 surface_energy := CalcSurfaceEnergy(og_rod, config)220 og_weight_sum += math.Exp(-config.beta * surface_energy)221 }222 }223 // calculate acceptance probability for rotation224 var acc float64225 if config.k == 1 {226 acc = math.Exp(-config.beta * (new_surface_energy - og_surface_energy))227 } else {228 acc = (og_weight_sum / new_weight_sum) * math.Exp(-config.beta*(new_surface_energy-og_surface_energy))229 }230 // fmt.Printf("acceptance probability: %f\n", acc)231 if rand.Float64() < acc {232 // move accepted233 GetAxes(new_rod)234 GetVertices(config.n_dim, config.n_vertices, new_rod)235 rods[rod.id] = new_rod236 config.potential_energy += (new_surface_energy - og_surface_energy)237 if og_rod.orientation != new_rod.orientation {238 config.rotation_successes++239 }240 }241 config.rotation_attempts++242}243func Insert(grid []*GridSpace, config *Config, rods *[]*Rod) {244 // find rod id to insert and either create new rod or refresh rod state245 fromScratch := false246 var rod *Rod247 if len(config.avail_rod_ids) > 0 {248 rand_id := rand.Intn(len(config.avail_rod_ids))249 rod_id := config.avail_rod_ids[rand_id]250 rod = (*rods)[rod_id]251 RodRefresh(config, rod)252 } else {253 fromScratch = true254 rod_id := config.next_unused_rod_id255 rod = &Rod{}256 rod.id = rod_id257 RodInit(config, rod)258 }259 // set rosenbluth k to 1 for insertion260 k := 1261 // run k rosenbluth trials to generate insertion weights (same location - new orientation)262 new_weights := make([]float64, k)263 var new_weight_sum float64 = 0264 new_orientations := make([]float64, k)265 new_surface_energies := make([]float64, k)266 for i := 0; i < k; i++ {267 new_orientations[i] = rod.orientation268 surface_energy := CalcSurfaceEnergy(rod, config)269 no_overlaps := CheckNeighborOverlaps(rod, grid, *rods, config)270 if no_overlaps {271 p := math.Exp(-config.beta * surface_energy)272 new_weights[i] = p273 new_weight_sum += p274 new_surface_energies[i] = surface_energy275 } else {276 new_weights[i] = 0277 new_surface_energies[i] = surface_energy + 10e8278 }279 if i != (k - 1) {280 GetRandOrientation(config, rod)281 GetAxes(rod)282 GetVertices(config.n_dim, config.n_vertices, rod)283 }284 }285 // select new configuration286 var new_surface_energy float64287 rod.orientation, new_surface_energy = SelectWeightedConfig(new_orientations, new_surface_energies, new_weights, new_weight_sum, k)288 // calculate acceptance probability for insertion289 N := float64(config.n_rods)290 acc := (config.V * math.Exp(config.beta*(config.mu-new_surface_energy)) / (N + 1))291 if rand.Float64() < acc {292 // move accepted293 rod.exists = true294 GetAxes(rod)295 GetVertices(config.n_dim, config.n_vertices, rod)296 // add rod to neighbor lists297 AddToNeighborLists(rod, grid)298 // update avail ids299 if !fromScratch {300 cur_rod_idx := 0301 for i := 0; i < len(config.avail_rod_ids); i++ {...

Full Screen

Full Screen

rod.go

Source:rod.go Github

copy

Full Screen

1package rod2import (3 "context"4 "errors"5 "fmt"6 "net/http"7 "strings"8 "sync/atomic"9 "time"10 "github.com/go-rod/rod"11 "github.com/go-rod/rod/lib/launcher"12 "github.com/go-rod/rod/lib/proto"13 "github.com/go-rod/stealth"14 "github.com/vislauh-rain/bbb/bbb"15)16func New(config bbb.Config, rod Config) (bbb.BBB, error) {17 config, err := bbb.Configure(config)18 if err != nil {19 return nil, err20 }21 return bbb.New(impl(config, rod), config.Workers.GetWorkersCount(), config.Log), nil22}23func impl(config bbb.Config, rod Config) bbb.NewImpl {24 return func() bbb.Impl {25 return &bb{config: config, rod: rod}26 }27}28type bb struct {29 config bbb.Config30 rod Config31 launcher *launcher.Launcher32 browser *rod.Browser33 ctx context.Context34}35func (b *bb) Init(ctx context.Context) error {36 b.ctx = ctx37 b.launcher = launcher.New().Context(ctx)38 if b.rod.ShowUi {39 b.launcher.Headless(false)40 }41 url, err := b.launcher.Launch()42 if err != nil {43 b.Done()44 return err45 }46 b.browser = rod.New().Context(ctx).ControlURL(url)47 err = b.browser.Connect()48 if err != nil {49 b.browser = nil50 b.Done()51 return err52 }53 //TODO detect browser close in some way54 return nil55}56func (b *bb) Generate() <-chan bbb.Task {57 return bbb.Generator(b.ctx, b.config.Urls, b.config.Log)58}59func (b *bb) Worker(tasks <-chan bbb.Task) {60 page := stealth.MustPage(b.browser).Context(b.ctx)61 errP := &errPusher{}62 ddos := &ddosDetector{}63 go page.EachEvent(func(e *proto.NetworkResponseReceived) {64 b.config.Log.LogFn(b.ctx, bbb.LogLevelVerbose, fmt.Sprintf("Fetched %q, status %d", e.Response.URL, e.Response.Status))65 if strings.Contains(e.Response.URL, "ddos") {66 ddos.setDdos()67 }68 if e.Type == "Document" && e.Response.Status >= http.StatusBadRequest {69 if e.Response.StatusText != "" {70 errP.Push(errors.New(e.Response.StatusText))71 } else if e.Response.Status >= http.StatusInternalServerError {72 errP.Push(fmt.Errorf("status %d", e.Response.Status))73 }74 }75 })()76 for t := range tasks {77 doTask(page, t, b.config, errP, ddos)78 }79}80func doTask(page *rod.Page, t bbb.Task, config bbb.Config, errP *errPusher, ddos *ddosDetector) {81 defer rec(page.GetContext(), t, config.Log)82 errc := make(chan error, 1)83 errP.Install(errc)84 defer errP.Cleanup()85 timeout, hasTimeout := config.Workers.GetTimeout()86 if hasTimeout {87 p, cancel := ddos.withTimeout(page, timeout, config.Log)88 defer cancel()89 page = p90 }91 config.Log.LogFn(page.GetContext(), bbb.LogLevelVerbose, "Navigating to "+t.Url)92 page.MustNavigate(t.Url)93 page.MustWaitLoad()94 select {95 case err := <-errc:96 config.Log.UpdateFn(page.GetContext(), bbb.UrlUpdate{97 Url: t.UrlConfig,98 Index: t.Index,99 Err: err,100 })101 default:102 config.Log.UpdateFn(page.GetContext(), bbb.UrlUpdate{103 Url: t.UrlConfig,104 Index: t.Index,105 Ok: true,106 })107 }108}109type errPusher struct {110 ch atomic.Value111}112func (e *errPusher) Push(err error) {113 i := e.ch.Load()114 if i == nil {115 return116 }117 ch := i.(chan error)118 if ch == nil {119 return120 }121 select {122 case ch <- err:123 default:124 }125}126func (e *errPusher) Install(ch chan error) {127 e.ch.Store(ch)128}129func (e *errPusher) Cleanup() {130 var ch chan error131 e.ch.Store(ch)132}133type ddosDetector struct {134 ch atomic.Value135}136func (d *ddosDetector) withTimeout(parent *rod.Page, dur time.Duration, log bbb.LogConfig) (*rod.Page, context.CancelFunc) {137 //ctx, cancel := context.WithCancel(parent)138 page, cancel := parent.WithCancel()139 done := make(chan struct{})140 go func() {141 timer := time.NewTimer(dur)142 defer timer.Stop()143 select {144 case <-timer.C:145 cancel()146 case <-done:147 case <-d.ddos():148 log.LogFn(parent.GetContext(), bbb.LogLevelVerbose, "timeout cancelled 'cause of ddos protection")149 }150 }()151 return page, func() {152 close(done)153 cancel()154 }155}156func (d *ddosDetector) ddos() <-chan struct{} {157 ch := make(chan struct{}, 1)158 d.ch.Store(ch)159 return ch160}161func (d *ddosDetector) setDdos() {162 i := d.ch.Load()163 if i == nil {164 return165 }166 ch := i.(chan struct{})167 if ch == nil {168 return169 }170 select {171 case ch <- struct{}{}:172 default:173 }174}175func rec(ctx context.Context, t bbb.Task, log bbb.LogConfig) {176 crash := recover()177 if crash == nil {178 return179 }180 var err error181 if e, ok := crash.(error); ok {182 err = e183 } else {184 err = fmt.Errorf("%v", crash)185 }186 log.UpdateFn(ctx, bbb.UrlUpdate{187 Url: t.UrlConfig,188 Index: t.Index,189 Err: err,190 })191}192func (b *bb) Done() {193 if b.browser != nil {194 b.browser.MustClose()195 b.browser = nil196 }197 b.config.Log.LogFn(context.Background(), bbb.LogLevelVerbose, "browser closed")198 if b.launcher != nil {199 //b.launcher.Cleanup() TODO hungs???200 b.launcher = nil201 }202 b.config.Log.LogFn(context.Background(), bbb.LogLevelVerbose, "launcher cleaned")203}...

Full Screen

Full Screen

Select

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 page.Element("input[name=q]").Input("rod")4 page.Element("input[name=btnK]").Click()5 fmt.Println(page.Element("div#resultStats").Text())6}7import (8func main() {9 page.Element("input[name=q]").Input("rod")10 page.Element("input[name=btnK]").Click()11 fmt.Println(page.Element("div#resultStats").Text())12}13import (14func main() {15 page.Element("input[name=q]").Input("rod")16 page.Element("input[name=btnK]").Click()17 fmt.Println(page.Element("div#resultStats").Text())18}19import (20func main() {21 page.Element("input[name=q]").Input("rod")22 page.Element("input[name=btnK]").Click()23 fmt.Println(page.Element("div#resultStats").Text())24}25import (26func main() {27 page.Element("input[name=q]").Input("rod")28 page.Element("input[name=btnK]").Click()29 fmt.Println(page.Element("div#resultStats").Text())30}

Full Screen

Full Screen

Select

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 defer browser.Close()5 page.Element("#hplogo").MustClick()6 fmt.Println("Clicked")7}

Full Screen

Full Screen

Select

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 page.WaitLoad()5 page.Element("#lst-ib").Input("rod")6}

Full Screen

Full Screen

Select

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 page.WaitLoad()5 searchBar := page.Element("#lst-ib")6 searchBar.Input("Hello, World!")7 searchButton := page.Element("input[name='btnK']")8 searchButton.Click()9 page.WaitLoad()10 firstResult := page.Element("h3.r")11 fmt.Println(firstResult.Text())12}

Full Screen

Full Screen

Select

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().MustConnect().MustLaunch()4 page := browser.MustPage("")5 input := page.MustElement("input[name=q]")6 input.MustInput("rod")7 page.MustElement("input[value='Google Search']").MustClick()8 page.MustWait("h3")9 links := page.MustElements("h3 a")10 for _, link := range links {11 fmt.Println(link.MustProperty("href"))12 }

Full Screen

Full Screen

Select

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 page.Element("#iframeResult").WaitVisible()5 frame := page.Frame("iframeResult")6 frame.Element("#cars").Select("Volvo")7 fmt.Println("Selected Volvo from dropdown")8}

Full Screen

Full Screen

Select

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().MustConnect()4 el := page.MustElement("#lst-ib")5 fmt.Println(el.MustAttribute("value"))6 fmt.Println(el.MustName())7 fmt.Println(el.MustText())8 fmt.Println(el.MustHTML())9 fmt.Println(el.MustBounds())10 fmt.Println(el.MustVisible())11 fmt.Println(el.MustStale())12 fmt.Println(el.MustHandle())13 fmt.Println(el.MustInfo())14 fmt.Println(el.MustDescription())15 fmt.Println(el.MustNodeID())16 fmt.Println(el.MustScrollIntoView())17 fmt.Println(el.MustRelease())18 fmt.Println(el.MustWaitVisible())19 fmt.Println(el.MustWaitStale())20 fmt.Println(el.MustWaitNotVisible())21 fmt.Println(el.MustWaitNotStale())22 fmt.Println(el.MustWaitLoad())23 fmt.Println(el.MustWaitRequestIdle())24 fmt.Println(el.MustWaitNavigation())25 fmt.Println(el.MustWaitRequest())26 fmt.Println(el.MustWaitRequestIdle())27 fmt.Println(el.MustWaitEvent())

Full Screen

Full Screen

Select

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 rod.Select(2)4 rod.Select(3)5 rod.Select(1)6 rod.Select(2)7 fmt.Println(rod)8}9type Rod struct {10}11func (r *Rod) Select(n int) {12 r.selected = append(r.selected, n)13}14type Rod struct {15}16func (r *Rod) Select(n int) {17 r.selected = append(r.selected[:len(r.selected):len(r.selected)], n)18}

Full Screen

Full Screen

Select

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main(){3 r1 := rod{length: 10, diameter: 2}4 fmt.Println("Area of rod is", r1.Area())5 fmt.Println("Volume of rod is", r1.Volume())6}7import "math"8type rod struct{9}10func (r rod) Area() float64{11}12func (r rod) Volume() float64{13}14import "fmt"15func main(){16 r1 := rod{length: 10, diameter: 2}17 fmt.Println("Area of rod is", r1.Area())18 fmt.Println("Volume of rod is", r1.Volume())19}20import "math"21type rod struct{22}23func (r rod) Area() float64{24}25func (r rod) Volume() float64{26}27import "fmt"28func main(){29 r1 := rod{length: 10, diameter: 2}30 fmt.Println("Area of rod is", r1.Area())31 fmt.Println("Volume of rod is", r1.Volume())32}33import "math"34type rod struct{35}36func (r rod) Area() float64{37}38func (r rod) Volume() float64{39}40import "fmt"41func main(){42 r1 := rod{length: 10, diameter:

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Rod automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful