Trying to run a add_action within a function to run a woocomerce function on a ajax request

I am able to get a ajax request to work properly on a woocommerce checkout form page, now I want to update the price of the checkout in that ajax request. My add_action is in the function that is fired by the ajax request.

This is all done in a custom plugin as well

Here is my code this far, it doesn’t seem like the function request_gift_card ever fires

 function gift_card_redeem(){      if(!empty($  _SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($  _SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {     error_log("test !empty");          add_action( 'woocommerce_before_calculate_totals', 'request_gift_card', 99 );      function request_gift_card($  cart_object){       if( !WC()->session->__isset( "reload_checkout" )) {           /* Gift wrap price */           $  additionalPrice = 5;           error_log($  cart_object);           foreach ( $  cart_object->cart_contents as $  key => $  value ) {               if( isset( $  value["embossing_fee"] ) ) {                   // Turn $  value['data']->price in to $  value['data']->get_price()                   $  orgPrice = floatval( $  value['data']->get_price() );                   $  discPrice = $  orgPrice + $  additionalPrice;                   $  value['data']->set_price($  discPrice);               }           }       }     }      $  result['type'] = "success";     $  result = json_encode($  result);     echo $  result;   }   else {     error_log("test else");       header("Location: ".$  _SERVER["HTTP_REFERER"]);   }    die(); } 

How do I adjudicate a player trying to sweep kick an enemy’s legs to knock them down?

I’m new to D&D. I already read both the Player’s Handbook and Dungeon Master’s Guide (I’m mastering) and I would like to know how I could handle this situation:

A player wants to do a sweep kick on an enemy’s legs and knock him down. He rolls a 20 and does the damage, but what about taking the enemy down? There is no rule that covers it.

Following the rules, the player would have to do a specific action to try to push the enemy down, and there would have to be a resisted check to see if the player can actually drop the enemy, so how could I deal with that?

What is my error trying to create a new table in the database?

I tried creating the tables in different ways and I always get the same error: "Error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘( …… at line 1 of the WordPress database for the CREATE TABLE IF NOT query EXISTS"

    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );          global $  wpdb, $  rs_plugin_db_version, $  table_name_clientes, $  table_name_promociones;          $  charset_collate = $  wpdb->get_charset_collate();          $  wpdb->query(         "CREATE TABLE IF NOT EXISTS $  table_name_clientes (             id int(11) NOT NULL,             logo text NOT NULL,             name text NOT NULL,             whatsapp text DEFAULT '' NOT NULL,             instagram text DEFAULT '' NOT NULL,             facebook text DEFAULT '' NOT NULL,             PRIMARY KEY  (id)         ) $  charset_collate ENGINE = InnoDB"     );     dbDelta();          $  wpdb->query(         "CREATE TABLE IF NOT EXISTS $  table_name_promociones (             id int(11) NOT NULL,             img text NOT NULL,             title text NOT NULL,             content text NOT NULL,             owner int(11) NOT NULL,             contact int(11) NOT NULL,             PRIMARY KEY  (id),             FOREIGN KEY  (owner) REFERENCES $  table_name_clientes(id) ON DELETE CASCADE ON UPDATE CASCADE         ) $  charset_collate ENGINE = InnoDB"     );     dbDelta(); 

In one of the tables I need to create a foreign key, if I didn’t misunderstood dbDelta() does not support them and therefore my last attempt was with $ wpdb->query, but with or without foreign key the result is the same.

maybe my mistake is obvious, but honestly I can’t find it

Trying to creating roads from a 2D texture into a 3D map using RoadArchitect

I need help with a complex task I’m trying to creating roads using RoadArchitect: I’m trying to detect all roads from a texture. I have created a model class to store every detected road using a little bit of recursion:

    [Serializable]     public class RoadNode : IPathNode     {         //[JsonConverter(typeof(RoadNodeConverter))]         public ConcurrentBag<int> Connections { get; set; } // TODO: IPathNode<T> + RoadNode : IPathNode<RoadNode> + Connections (ConcurrentBag<RoadNode>), but can't be serialized due to StackOverflow and OutOfMemory exceptions          public Point Position { get; set; }         public bool Invalid { get; set; }         public int Thickness { get; set; }         public ConcurrentBag<int> ParentNodes { get; set; }          public RoadNode()         {             //Connections = new List<RoadNode>();         }          public RoadNode(Point position, int thickness)         //: this()         {             Position = position;             Thickness = thickness;         }          public RoadNode(Point position, bool invalid, int thickness)         //: this()         {             Position = position;             Invalid = invalid;             Thickness = thickness;         }          public RoadNode(int x, int y, int thickness)             : this(new Point(x, y), thickness)         {         }          public void SetThickness(int thickness)         {             // TODO: Call this when needed and thickness == -1             Thickness = thickness;         }          public int GetKey()         {             return F.P(Position.x, Position.y, mapWidth, mapHeight);         }     } 
    public interface IPathNode     {         ConcurrentBag<int> Connections { get; }         Point Position { get; }         bool Invalid { get; }     } 

At every loaded chunk (I’m using SebLeague tutorial to create the chunks), I get all the road points for this chunk. Then, I try to iterare them. But I have problems interpreting the results.

I have part of the task done:

        public static IEnumerable<Road> CreateRoad(this IEnumerable<Point> points, StringBuilder builder)         {             if (points.IsNullOrEmpty())             {                 builder?.AppendLine($  "\tskipped...");                 yield break; // This chunk doesn't contain any road. Exiting.             }              //var dict = points.Select(p => new {Index = p.GetKey(), Point = p}).ToDictionary(x => x.Index, x => x.Point);             //var builder = new StringBuilder();             var roads = GetRoads(points, builder);             foreach (var list in roads)             {                 if (list.IsNullOrEmpty()) continue;                 //var first = road.First();                 //var backIndex = ((Point)CityGenerator.SConv.GetRealPositionOnMap(first)).GetKey();                  var road = CreateIndependantRoad(list);                 builder?.AppendLine($  "\t... finished road ({}) with {list.Count} nodes.");                 yield return road;             }             //Debug.Log(builder?.ToString());         }          private static IEnumerable<List<Vector3>> GetRoads(IEnumerable<Point> points, StringBuilder builder)         {             var model = RoadGenerator.RoadModel;              var queue = new Queue<Point>(points);             int i = 0;              builder?.AppendLine($  "\tcount: {queue.Count}");              var dictionary = new Dictionary<int, List<Vector3>>();              while (queue.Count > 0)             {                 var list = new List<Vector3>();                  var pt = queue.Dequeue();                 var itemIndex = pt.GetKey();                 dictionary.Add(itemIndex, list);                  var node = model.SimplifiedRoadNodes[itemIndex];                  builder?.AppendLine($  "\troad iteration: {i}");                  //var conn = node.Connections;                 var nodes = GetRoadNodes(node, ptVal =>                 {                     if (ptVal.HasValue) queue = new Queue<Point>(queue.Remove(ptVal.Value));                     return queue;                 },                     parentNodeIndex => { return dictionary[parentNodeIndex]; },                     builder);                  foreach (var point in nodes)                     list.Add(CityGenerator.SConv.GetRealPositionOnMap((Vector2)point).GetHeightForPoint());                  yield return list;                 ++i;             }         }          private static IEnumerable<Point> GetRoadNodes(RoadNode node, Func<Point?, Queue<Point>> queueFunc, Func<int, List<Vector3>> parentFunc, StringBuilder builder, int level = -1)         {             if (queueFunc == null) throw new ArgumentNullException(nameof(queueFunc));             if (parentFunc == null) throw new ArgumentNullException(nameof(parentFunc));              var conn = node.Connections;             if (conn.IsNullOrEmpty())             {                 yield return node.Position;                 yield break;             }             if (queueFunc(null).Count == 0) yield break;              ++level;             builder?.AppendLine($  "{new string('\t', 2)}level: {level} -> {queueFunc(null).Count} items");              //if (conn.Count == 1)             //{             //    var firstNode = conn.First().GetNode();             //    ////var firstPoint = conn.First().GetPoint();              //    var list = parentFunc(firstNode.ParentNodes.First()); // TODO: parent nodes should be one...             //    list.Add(CityGenerator.SConv.GetRealPositionOnMap((Vector2)conn.First().GetPoint()).GetHeightForPoint());             //}             //else             {                 foreach (var item in conn)                 {                     var pt = item.GetPoint();                     if (!queueFunc(null).Contains(pt)) yield break;                     yield return pt;                     if (queueFunc(pt).Count == 0) yield break;                      var subnode = pt.GetKey().GetNode();                     var pts = GetRoadNodes(subnode, queueFunc, parentFunc, builder, level);                     foreach (var point in pts)                         yield return point;                 }             }         } 

You can see here the StringBuilder results:

But as you can see I have problems with roads. Some roads only have one node, other roads only have 2 nodes…

I’m thinking that the current implementation I did isn’t right at all, because instead of grouping all nodes into one major road I’m splitting them into road chunks without sense.

By this reason I created this topic, in order to clarify myself because I’m not sure about what I’m doing and which way should I take.

Trying to find a way to play dnd?

So, basically me and my friends wants to play dnd, but I’m in a country where its very hard to get the dnd rule books, and because of an impending lockdown I cant get them shipped to where I am. I’ve played the game a few times and have followed a few campaigns on twitch/youtube so I’m familiar with the basic rules. But, I wanna know if anyone here has any advice as to how I would practically get a game started up.

(worth noting that internet access is fairly limited and is also completely unavailable)

Preferably, I’d like to play 5e. If there’s an easier one I would obviously be open to suggestions

Trying to understand the encryption used at various steps of Tor

So I read up on "Diffie-Hellman" key exchange which to my knowledge is a way for two parties to create a "shared secret" but I don’t really know if this is a public key or a private key or something else entirely.

When I look up how Tor works, many videos use the analogy of the locked box. We establish an entry node, relay node, exit node (call them A, B, C). I send a locked box to A who unlocks it and inside is another locked box with a message included, "send this to B." A sends this box to B, who unlocks it and sees another locked box with a note, "send this to C." B sends the box to C, who unlocks it and sees a message, "Fetch the contents of" (the final request).

I don’t know if this analogy makes sense or if it’s even accurate.

Is this key exchange something that is done with the client and each of the three nodes, and that is how I am able to encrypt the message several times? Or is there some other algorithm used instead? I see that Tor uses RSA but I’m still unclear on how it all works together.

Trying to understand what is going on. It would help to see a minimal example using the actual encryption techniques.

I’m trying to write a randomly patrolling AI for my 2D Platformer

I’m trying to write a randomly patrolling AI for my 2D Platformer. The AI already has a ground checker function which checks if there are tiles nearby or not. What I want to do is randomize its actions and create an illusion of a somewhat "sentient" enemy. What I tried to create below is using the built in RNG to make the enemy either jump, change direction, or keep moving.

The problem is, it doesn’t seem to work properly. The enemy just jumps every second I want it to change behaviour. The change direction functions, however, don’t occur as frequently. I need to know what I’ve done wrong here. Thanks.

void Update() {          //RNG       behaviour = Random.Range(0,3);       jumpSpeed = Random.Range(1,5);         //clock       timer += Time.deltaTime; }    //time     private float waitTime = 2.0f;     private float timer = 0.0f;   void MoveRandomizer() {     if((Mathf.Round(timer%waitTime)) == 0)     {         if(behaviour == 0)         {         movingRight = false;                  }         if(behaviour == 1)         {            movingRight = true;                  }         if(behaviour == 2)         {         rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);         }     }         } 

Trying to identify this adventure

Many years ago (24+) I had a set of 4 warhammer fantasy roleplay adventures split between 2 books.

Each adventure was to try and claim an elemental gem of power, the gems where tremendously powerful and when combined and at the end of the adventure it was suggested the world ended.

At the time I remember being told the adventure had been converted from a famous published D and D campaign.

I am trying to remember both the name of the WFRP adventure and the DnD campaign it may have been based on. If this is better split into 2 questions I am happy to ask B once A is answered.

Trying to understand Kempe’s algorithm for Graph Coloring

I am trying to understand Kempe’s algorithm to $ k$ -color a planar graph. This is what I understand till now:

Trying to 6-color a planer graph ($ k=6$ )

  1. Find a vertex of degree <= 5 ($ k-1$ )
  2. Remove this vertex
  3. Color the rest of the graph using a recursive call
  4. Put the vertex back, since its degree was at most 5 ($ k-1$ ), we still have at least 1 color left to color this vertex

I understand this procedure but I was curious about the first step: finding a vertex of degree at most $ k-1$ . What would happen if there is no such vertex in the graph? For example, all vertices have a degree $ > k$ . In that case will the algorithm fail?