One-row postgres query as CTE/subquery much slower when passing subquery field into function / maybe related to inlining?

I’m using postgres 13.3 with inner and outer queries that both only produce a single row (just some stats about row counts).

I can’t figure out why Query2 below is so much slower than Query1 (they should basically be almost exactly the same, maybe a few ms difference at most)…

Query1: This query takes 49 seconds:

WITH t1 AS (         SELECT             (SELECT COUNT(*) FROM racing.all_computable_xformula_bday_combos) AS all_count,             (SELECT COUNT(*) FROM racing.xday_todo_all) AS todo_count,             (SELECT COUNT(*) FROM racing.xday) AS xday_row_count         OFFSET 0 -- this is to prevent inlining )  SELECT             t1.all_count,             t1.all_count-t1.todo_count AS done_count,             t1.todo_count,             t1.xday_row_count FROM t1 

Query2: This query takes 4 minutes and 30 seconds (only one line difference):

WITH t1 AS (         SELECT             (SELECT COUNT(*) FROM racing.all_computable_xformula_bday_combos) AS all_count,             (SELECT COUNT(*) FROM racing.xday_todo_all) AS todo_count,             (SELECT COUNT(*) FROM racing.xday) AS xday_row_count         OFFSET 0 -- this is to prevent inlining )  SELECT             t1.all_count,             t1.all_count-t1.todo_count AS done_count,             t1.todo_count,             t1.xday_row_count,             -- the line below is the only difference to Query1:             util.divide_ints_and_get_percentage_string(todo_count, all_count) AS todo_percentage FROM t1 
  • Before this point, and with some extra columns in the outer the query (which should have made almost zero difference), the whole query was insanely slow, like 25 minutes, which I think was due to inlining maybe? Hence the OFFSET 0 being added into both queries (which does help a lot).
  • I’ve also been swapping between using the above CTEs vs subqueries, but with the OFFSET 0 included it doesn’t seem to make any difference.

Here’s the definitions of the functions being called in Query2:

CREATE OR REPLACE FUNCTION util.ratio_to_percentage_string(FLOAT, INTEGER) RETURNS TEXT AS $  $   BEGIN     RETURN ROUND($  1::NUMERIC * 100, $  2)::TEXT || '%'; END; $  $   LANGUAGE plpgsql IMMUTABLE;   CREATE OR REPLACE FUNCTION util.divide_ints_and_get_percentage_string(BIGINT, BIGINT) RETURNS TEXT AS $  $   BEGIN          RETURN CASE          WHEN $  2 > 0 THEN util.ratio_to_percentage_string($  1::FLOAT / $  2::FLOAT, 2)         ELSE 'divide_by_zero'          END         ;  END; $  $   LANGUAGE plpgsql IMMUTABLE; 
  • As you can see it’s a very simple function, which is only being called once, from the single row the whole thing produces… how can this cause such a massive slowdown? And why is it affecting whether postgres inlines the initial subquery/WITH (or whatever else might be going on here)

EXPLAIN ANALYZE outputs:

  • Query1: https://explain.depesz.com/s/bq7u
  • Query2: https://explain.depesz.com/s/9w3rY

php mysql create an entry into a field. (INSERT INTO) WHILE logged in currentuser/session

I did the php registration system and it works https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php

but i created extra fields in the DB so the user can add some data to the database.

All search results are only to add to database from scratch, not from CURRENT SESSION USER. or they are just how to make php user reg systems but no further PHP CURRENT SESSION user interaction with DB

DB structure is just like on that site, i posted above, but created a URL field so a user can save their favorite URL. DB = **users > username > URL ** once i get that working im going to figure out how a user can append to the field and keep adding URLs

i came up with this.. .

if (isset($  _SESSION['loggedin']) && $  _SESSION['loggedin'] == true) { echo "<a href="file.php?save=yes>Add to Favorites</a>";}   if(isset($  _GET['save'])){          echo "got a save";      userID = $  _SESSION["username"];      echo $  userID; //it does give the current username, meaning im logged in , session-start is on the header .        $  URL = $  _GET['URLforbookmark'];      $  sql = "INSERT INTO users (URL, UserID)      VALUES ('$  URL', '$  UserID')";            if (mysqli_query($  sql)) {         echo "New record created successfully !";      } else {         echo "Error: " . $  sql . " " . mysqli_error($  sql);      }      mysqli_close($  sql); } 

Feedback Error reads: Error: INSERT INTO users (test, UserID) VALUES (‘theusersfavorurl’, ”)

thank you !

copy fields value to another field

When user registering on my site, they have to entry their phone number for auth (firebase).I have create the phone number field using buddypress’s xprofile plugin, the field named "phone". For some reason, I need to sync the Phone field to user_url field, I tried some plugin like SyncField ,BuddyPress to WordPress Full Sync to help, but the field cannot be sync without modify the content. Any idea to make it work?

Get price field value from gravity forms to use in php code?

I’m trying to integrate Paysera (payment platform) with Gravity Forms. I have Gravity Forms with product price field, I need to retrieve the price field value to use in Paysera API code. I have paysera API code in seperate php file. So basically this is what I need:

On gravity form load -> retrieve pricing field value -> on button press redirect to /paysera.php and pass $ pricing_field_value.

Is this possible? Thanks for any ideas.

Associate custom field with custom taxonomy with shortcode in backend

I am trying to associate a custom field to a custom taxonomy booked_custom_calendar. Custom field here is [notifications_user_id]. All this will be executed using a shortcode. When user clicks on Generate Calendar button, a term will be created and assigned to the current user using custom field and current user’s email as value in it. In this way I can filter and show this term (booked_custom_calendar) anywhere by comparing the email of current user and value in custom field.

Please help me save this field to custom taxonomy.

function createMyCustomCalendar(){      $  current_user = wp_get_current_user();     $  custom_calendar_name = "$  current_user->display_name\'s - Calendar";          $  parent_term = term_exists( $  custom_calendar_name, 'booked_custom_calendars' ); // returns an array if the taxonomy exists     $  parent_term_id = $  parent_term['term_id']; // get the numerical value of the term          $  insert_data = wp_insert_term(     $  custom_calendar_name, // new term     'booked_custom_calendars', // taxonomy     array(     'description' => $  current_user->ID,     'slug' => '',     'parent' => $  parent_term_id     )     );     //Add new meta field and fill with user ID |     // add_term_meta($  term_id, 'term_author_id', $  current_user->ID, true);          if( ! is_wp_error($  insert_data) )     $  term_id = $  insert_data['term_id'];   // A callback function to add a custom field to our "presenters" taxonomy      // Check for existing taxonomy meta for the term you're editing       $  t_id = $  term_id; // Get the ID of the term you're editing       $  term_meta = get_option( "taxonomy_term_$  t_id" ); // Do the check   ?>      <tr class="form-field">        <td>           <input type="text" name="term_meta[notifications_user_id]" id="term_meta[notifications_user_id]" size="25" style="width:60%;" value="<?php echo $  current_user->data->user_email;?>"><br />       </td>   </tr>     <?php           //$  t_id = $  term_id;           //$  term_meta = get_option( "taxonomy_term_$  t_id" );           $  cat_keys = array_keys( $  _POST['term_meta'] );               foreach ( $  cat_keys as $  key ){                   $  term_meta[$  key] = $  _POST['term_meta'][$  key];                                    //save the option array           update_option( "taxonomy_term_$  t_id", $  term_meta );               }     echo '<script>window.location.replace("'.get_admin_url().'?page=booked-appointments");</script>';      }     function showCustomCalendarButton(){  ?>     <form method="post"> <input type="submit" name="button1"  id="btn-1" value="Generate Calendar"/></form>  <?php if(isset($  _POST['button1'])) { createMyCustomCalendar(); }  }  add_shortcode('create-custom-calendar','showCustomCalendarButton'); ?> <?php 

Need help improving my Flow Field and Unit Avoidance code so that the units can properly surround a unit instead of getting stuck

My setup is like this. Every update my movement system moves all of the units on the field. They use some Boid logic to avoid eachother, and a flow field that directs them towards each other. This is the result. https://imgur.com/a/CaUpfT7

My general setup is to calculate 2 flow fields, one for each player. From every field on the map (32×32 fields) I calculate the vector that points towards the closest enemy. Now this is a fine approach but I’d like to somehow take into consideration obstacles somehow (without another round of for loops)? Or should I handle that in my movement system avoidance? I was maybe thinking of doing A* once a unit is close enough to the enemy but all of these systems together seem rather hacky and overkill.

There are no obstacles currently, maybe a spell will generate it in the future. For now there are only units on the battleground without terrain or obstacles (besides units fighting eachother)

Here is some code. Firstly how I create the flowfields (kinda costly, will look into a way to optimize it further, don’t really need every single tile, can probably merge 2 or 3 together)

func (g *Grid) Update() {     g.entityPositions[0] = g.entityPositions[0][:0]     g.entityPositions[1] = g.entityPositions[1][:0]     entities := g.world.GetEntityManager().GetEntities()     posComps := g.world.GetObjectPool().Components["PositionComponent"]      for _, ent := range entities {         g.entityPositions[ent.PlayerTag] = append(g.entityPositions[ent.PlayerTag], posComps[ent.Index].(components.PositionComponent).Position)     }      for x := 0; x <= g.MaxWidth/FlowTileSize; x++ {         for y := 0; y <= g.MaxHeight/FlowTileSize; y++ {              curPosVector := engine.Vector{X: float32(x * 32), Y: float32(y * 32)}             // find closest tile to this one for both players             minDist := float32(100000.0)             minIndx := -1             for indx, pos := range g.entityPositions[0] {                 d := engine.GetDistanceIncludingDiagonal(pos, curPosVector)                 if d < minDist {                     minIndx = indx                     minDist = d                 }             }              //  fmt.Printf("CurPos : %v, enemyPos : %v,  direction %v \n", curPosVector, g.entityPositions[0][minIndx], g.entityPositions[0][minIndx].Subtract(curPosVector).Normalize())             g.flowTiles[1][x][y].Direction = g.entityPositions[0][minIndx].Subtract(curPosVector).Normalize()              minDist1 := float32(100000.0)             minIndx1 := -1             for indx, pos := range g.entityPositions[1] {                 d := engine.GetDistanceIncludingDiagonal(pos, curPosVector)                 if d < minDist1 {                     minIndx1 = indx                     minDist1 = d                 }             }              g.flowTiles[0][x][y].Direction = g.entityPositions[1][minIndx1].Subtract(curPosVector).Normalize()         }     } }  

And my movement code. A lot of code but just basic allignnment cohesion/ separation. With added 2 look ahead vectors to steer away from the collision.

        desiredDirection := world.Grid.GetDesiredDirectionAt(positionComp.Position, tag)         direction := movementComp.Direction         maxSpeed = movementComp.MovementSpeed          //Avoidance         nearbyEntities := helper.GetNearbyEntities(100, world, index)          avoidance := engine.Zero()         avoidance = avoidance.Add(alignment(world, nearbyEntities, direction).MultiplyScalar(alignmentCoef))         avoidance = avoidance.Add(cohesion(world, nearbyEntities, direction, positionComp.Position).MultiplyScalar(cohesionCoef))         avoidance = avoidance.Add(separation(world, nearbyEntities, direction, positionComp.Position).MultiplyScalar(separationCoef))           //Checking ahead of us whether or not we'll encounter something         lookAheadVectorLong := direction.Add(desiredDirection).MultiplyScalar(maxSpeed * 2.5)         lookAheadVectorShort := direction.Add(desiredDirection).MultiplyScalar(maxSpeed)         maxAvoidanceForce := float32(1.0)          checkPosShort := positionComp.Position.Add(lookAheadVectorShort)         checkPosLong := positionComp.Position.Add(lookAheadVectorLong)          collidedIndexShort := world.Grid.IsPositionFree(index, checkPosShort, positionComp.BoundingBox)         collidedIndexLong := world.Grid.IsPositionFree(index, checkPosLong, positionComp.BoundingBox)          if collidedIndexShort != -1 {             direction = engine.Zero()             avoidance = checkPosShort.Subtract(world.ObjectPool.Components["PositionComponent"][collidedIndexShort].(components.PositionComponent).Position).Normalize()             avoidance = avoidance.MultiplyScalar(maxAvoidanceForce * 1.5)         } else if collidedIndexLong != -1 {             direction = direction.MultiplyScalar(breakingForce)             avoidance = checkPosShort.Subtract(world.ObjectPool.Components["PositionComponent"][collidedIndexLong].(components.PositionComponent).Position).Normalize()             avoidance = avoidance.MultiplyScalar(maxAvoidanceForce * 1.2)         }          direction = desiredDirection         direction = direction.Add(avoidance).Normalize()          positionComp.Position = positionComp.Position.Add(direction.MultiplyScalar(maxSpeed))          positionComp.Position.X = engine.Constraint(positionComp.Position.X, 0, 799)         positionComp.Position.Y = engine.Constraint(positionComp.Position.Y, 0, 511)          movementComp.Direction = direction.Normalize()          world.ObjectPool.Components["PositionComponent"][index] = positionComp         world.ObjectPool.Components["MovementComponent"][index] = movementComp          fmt.Printf("I %d am at %v\n", index, positionComp.Position)     }  }  func limit(p engine.Vector, lim float32) engine.Vector {     if p.X > lim {         p.X = lim     } else if p.X < -lim {         p.X = -lim     }     if p.Y > lim {         p.Y = lim     } else if p.Y < -lim {         p.Y = -lim     }     return p } func alignment(world *game.World, siblings []int, velocity engine.Vector) engine.Vector {     avg := engine.Vector{X: 0, Y: 0}     total := float32(0.0)      for _, siblingIndex := range siblings {         avg = avg.Add(world.ObjectPool.Components["MovementComponent"][siblingIndex].(components.MovementComponent).Direction)         total++     }     if total > 0 {         avg = avg.DivideScalar(total)         avg = avg.Normalize().MultiplyScalar(maxSpeed)         avg = avg.Subtract(velocity)         avg = limit(avg, maxForce)         return avg     }     return engine.Vector{X: 0.0, Y: 0.0}  }  func cohesion(world *game.World, siblings []int, velocity engine.Vector, position engine.Vector) engine.Vector {     avg := engine.Vector{X: 0, Y: 0}     total := float32(0)      for _, siblingindex := range siblings {          avg = avg.Add(world.ObjectPool.Components["PositionComponent"][siblingIndex].(components.PositionComponent).Position)         total++      }     if total > 0 {         avg = avg.MultiplyScalar(1.0 / total * cohesionCoef)         avg = avg.Subtract(position)         avg = avg.Normalize().MultiplyScalar(maxSpeed)         avg = avg.Subtract(velocity)         avg = limit(avg, maxForce)         return avg     }     return engine.Vector{X: 0.0, Y: 0.0} }  func separation(world *game.World, siblings []int, velocity engine.Vector, position engine.Vector) engine.Vector {     avg := engine.Vector{X: 0, Y: 0}     total := float32(0)      for _, siblingIndex := range siblings {         siblingPos := world.ObjectPool.Components["PositionComponent"][siblingIndex].(components.PositionComponent).Position         d := position.Distance(siblingPos)         if d < desiredSeperation {             diff := position.Subtract(siblingPos)             diff = diff.Normalize()             diff = diff.DivideScalar(d)             avg = avg.Add(diff)             total++         }     }     if total > 0 {         avg.DivideScalar(total)     }      if total > 0 {         avg = avg.MultiplyScalar(1.0 / total * separationCoef)         avg = avg.Normalize().MultiplyScalar(maxSpeed)         avg = avg.Subtract(velocity)         avg = limit(avg, maxForce)     }     return avg } 

What I am trying to achieve is:

Units not mashing into each other and just positioning themselves in a free spot around their target.

What are my problems :

  1. Make the flow field direct them away from collision rather than just towards closest unit.
  2. Make it work with the current system without adding too many nested loops and awful checks.
  3. I am doing the avoidance correctly? I have a desired direction that I get from the flow field (that directs me towards closest enemy), then I add avoidance to it to avoid any other units in the area.

My units move really well up untill the point of collision/ going to a spot next to a target. I am not sure how to implemenent that behaviour yet.

(This is my forth iteration of the movement system. I went from pure boid, to grid based, to A*, to this. So I tried a lot of variations and this going surrounding behaviour has been bugging me every time.)

Custom engine (server) written in Golang and then dispatched to Godot for the visuals. Performance is not my concern, but this is a server, so I am more mindful of that, I could probably brute force it but I’d rather hear some better take on it.

Any suggestion/article/ video is greatly appreciated !!

Edit: Thinking about it, flow field is currently useless. I can basically just have a vector pointing to the closest enemy for each unit… Would be less costly as well. But the problem of them clumping and not knowing how to surround still stands.

What happens when a Shapechanged Dragon enters an Antimagic Field inside a narrow space? [duplicate]

A rather simple question: if an Ancient Dragon uses it’s Shapechange ability to transform into a medium-sized humanoid, and then has that Shapechange disabled/dispelled inside a narrow tunnel / small underground room, will they get crushed to death by their own size? I have plans on True Poly-ing my spellcaster PC into a Dragon, and i’m worried that a random dispel would instakill me when i go dungeon-delving in the Abyss or somewhere.

Change billing fullname with a custom field in Woocommerce emails

I using Checkout Field Editor for WooCommerce to make 25 custom field. I have problem billing_fullname not show in customer details but show in billing address. So i have thinking about a solution that i create another Name custom field.

I will hide my Name custom field using css in the frontend but i wondering how can i copy value in the billing_fullname into my custom field billing_name in the backend

Beside how can i hide billing details in Emails

I try remove some code in admin-new-order.php But when remove customer details remove too

enter image description here