Mysql multiple queries from one PHP file I'm running the below code to populate a HTML table using several calls to mysqli_query(). The below snippet only shows three however I'm running ten in my file for various other date columns and may need more over time. I've attached a file below showing the basic database layout and required output.

The required output is basically just a list of times from various columns

The below code works fine, however it is probably not the most efficient and other options like MySQL JOIN or UNION don't seem to work.

Do we have any another options to perform the desired output?

 $result = mysqli_query($con,"SELECT * FROM livescores WHERE actualstart >= '$datefilter'");
 $resulthalf = mysqli_query($con,"SELECT * FROM livescores WHERE actualhalftime >= '$datefilter'");
 $actualft = mysqli_query($con,"SELECT * FROM livescores WHERE actualft>= '$datefilter'");

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['actualstart'] . "	";
echo "" . $row['League'] . "	";
echo "KO	";
echo "" . $row['HomeTeam'] .' v '. $row['AwayTeam'] . "	";
echo "	";
echo "
";
}
while($row = mysqli_fetch_array($resulthalf))
{
echo "
";
echo "" . $row['actualhalftime'] . "	";
echo "" . $row['League'] . "	";
echo "HT	";
echo "" . $row['HomeTeam'] .' v '. $row['AwayTeam'] . "	";
echo "	";
echo "
";
}
while($row = mysqli_fetch_array($actualft))
{
echo "
";
echo "" . $row['actualft'] . "	";
echo "" . $row['League'] . "	";
echo "FT	";
echo "" . $row['HomeTeam'] .' v '. $row['AwayTeam'] . "	";
echo "	";
echo "
";

Many Thanks

I can't say how the queries should be built for the other 7 that you haven't posted, but I think I've identified enough commonalities in your design intent to exercise the D.R.Y. principle.

While it is always best to minimize total calls to the database, it seems you are struggling to package all of the queries into one.  I'll suggest implementing mysqli_multi_query() for your case with the noticeable benefit being maintainability.  I am assuming that your $datefilter value is 100% validated/secure and is safe to place into your queries (versus being a raw user input).  I should also note that if any of your queries experience a syntax error, the loop will break, the html table will close early, and you will see details about the erring query.

The following method can be modified to allow blank rows and/or group headings withing the html table -- just write that portion between the do{ and if($result... lines.

Untested Code:

// $datefilter MUST be validated/trustworthy as prepared statements are not in use.
$queries['KickOff']="SELECT actualstart AS `Time`,League,'KO' AS Label,HomeTeam,AwayTeam FROM livescores WHERE actualstart>='$datefilter'";
$queries['HalfTime']="SELECT actualhalftime AS `Time`,League,'HT' AS Label,HomeTeam,AwayTeam FROM livescores WHERE actualhalftime>='$datefilter'";
$queries['Fulltime']="SELECT actualft AS `Time`,League,'FT' AS Label,HomeTeam,AwayTeam FROM livescores WHERE actualft>='$datefilter'";
// ... ~7 more queries entries here

echo "
";
if(mysqli_multi_query($mysqli,implode(';',$queries))){
    do{
        if($result=mysqli_store_result($mysqli)){
            while($row=mysqli_fetch_assoc($result)){
                echo "
{$row['Time']}	{$row['League']}	{$row['Label}	{$row['HomeTeam']} v {$row['AwayTeam']}
";
            }
            mysqli_free_result($result);
        }
    } while(next($queries) && mysqli_more_results($mysqli) && mysqli_next_result($mysqli));
}
echo "
";
if($mysqli_error=mysqli_error($mysqli)){
    echo "
Error occurred on ",key($queries);
    // echo " Query: ",current($queries),"Syntax Error:
$mysqli_error
";  // developer-only details
    echo "
";
}

A link to my previous work that I am leveraging for this answer.


Interleaving values from several iterables I am new to Python and am trying to see if there is a cleaner way to write my code. The following code take iterables as parameter it produces the first value from the first parameter, then the first value from the the second parameter, ..., then the first value from the last parameter; then the second value from the first parameter and so on.If any iteratable produces no more values, this generator produces no more values.

If I do:

for i in skip('abcde','fg','hijk'):
  print(i,end='')

produces the values 'a', 'f', 'h', 'b', 'g', 'i', and 'c'. The code I've written is as under(which works):

def skip(*args):
  itrs = [iter(arg) for arg in args]
  while itrs != []:
     temp = []
     for i in range(len(itrs)):
        try:
          yield next(itrs[i])
          temp.append(itrs[i])
        except StopIteration:
          pass
      itrs = temp

Is there a cleaner/ concise way to write the code(without using any external libraries)?

First off, I think there is an error in the original code. The code produces afhbgicjdke instead of the expected afhbgic. I think the intention was to return instead of pass in the stop iteration block, the answer below work under this assumption.

Let's look at the for loop in the middle

for i in range(len(itrs)):
    try:
        yield next(itrs[i])
        temp.append(itrs[i])
    except StopIteration:
        return

No where in the body operate on the index, so every itrs[i] can be replaced with just i with a simpler for i in iters. This gives us

for i in itrs:
    try:
        yield next(i)
        temp.append(i)
    except StopIteration:
        return

Now lets look at the while body

while itrs != []:
    temp = []
    # ... the for loop that includes an append to itrs
    itrs = temp

This basically gives the code a way to exit when everything is finished. However, if you think about how the code works, the only time itrs has a lower length than args is when one of the itrs reaches StopIteration. In that case, we would have returned already!

So the while loop can become a while True loop and temp and it's usage can be ommited.

def skip(*args):
    itrs = [iter(arg) for arg in args]
    while True:
        for i in itrs:
            try:
                yield next(i)
            except StopIteration:
                return

Now we need to convince ourselves that the code will actually return at some point. This isn't too hard, as long as one of the iterable passed in is finite i.e. has an end, we will reach StopIteration at some point. And in the case that every iterable is infinite, the original code would run forever too. So we are good there.

But there is another problem. What if skip is called with no argument? This will result in us never returning from the function, since there is no iterable for us to trigger StopIteration! In the original code, this is dealt with implicitly through temp being empty. Since we don't have that anymore, we have to handle it explicitly.
This gives us the final code:

def skip(*args):
    if len(args) == 0:
        return
    itrs = [iter(arg) for arg in args]
    while True:
        for i in itrs:
            try:
                yield next(i)
            except StopIteration:
                return

With this

for i in skip('abcde','fg','hijk'):
    print(i,end='')

outputs afhbgic and

for i in skip():
    print(i,end='')

is a noop

As an aside, the indentation in the original code is inconsistent, which makes it un-runnable. Please be sure to post usable code next time


Convert mixed-format phone numbers to pure numbers I am just getting started with C# and wanted to make sure that I am aware of any errors/inefficiencies in my code.

For this specific project, I wanted to prove to someone that a "bot" could easily understand phone numbers from Craigslist that are mixed (ex. 9eight7six54three2one0).

Here is what I have right now - it successfully outputs a string of numbers when fed a phone number such as the one above.

using System;

namespace Phone_Decoder
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter your mixed-format phone number:");

            string phone = Console.ReadLine();

            char[] b = new char[phone.Length];

            b = phone.ToCharArray();

            string finalphone = string.Empty;

            string number = string.Empty;

I am wondering if this "number" string should be a character array or not. It seems much easier to append a string than to add characters to an array, but I thought I read that strings are more memory-intensive.

            foreach (char c in b)
            {
                if (char.IsDigit(c))
                    finalphone += c;
                if (!char.IsDigit(c))
                {
                    number += c;
                    switch (number.ToLower())
                    {
                        case "zero":
                            finalphone += '0';
                            number = string.Empty;
                            break;
                        case "one":
                            finalphone += '1';
                            number = string.Empty;
                            break;
                        case "two":
                            finalphone += '2';
                            number = string.Empty;
                            break;
                        case "three":
                            finalphone += '3';
                            number = string.Empty;
                            break;
                        case "four":
                            finalphone += '4';
                            number = string.Empty;
                            break;
                        case "five":
                            finalphone += '5';
                            number = string.Empty;
                            break;
                        case "six":
                            finalphone += '6';
                            number = string.Empty;
                            break;
                        case "seven":
                            finalphone += '7';
                            number = string.Empty;
                            break;
                        case "eight":
                            finalphone += '8';
                            number = string.Empty;
                            break;
                        case "nine":
                            finalphone += '9';
                            number = string.Empty;
                            break;
                    }

I am a bit concerned with this switch statement, because there are many repeated lines ("number = string.Empty"). Could I make it more compact somehow?

                }
            }
            Console.WriteLine(finalphone);
            Console.ReadLine();
        }
    }
}

You can extract that logic to a simple dedicated method.

Your solution is over-complicated for such a simple task so I will offer an alternative solution.

Let's inspect the problem -

You get some string as an input. This string might contain digits and it might also contain words that represent numbers. If there are such words we want to replace them with the respective digit.

We humans know that 'Zero' means 0 and 'One' means 1 because this is part of our vocabulary, if we are uncertain of some word we can look it up in the dictionary right? The human dictionaries are structured mostly in the following way - Word - Meaning.

Well luckily C# also has such data type. Conveniently enough it's called Dictionary! Using this data type we can construct much more readable and extendable code.

Let's start by declaring a Dictionary:

private static readonly Dictionary<string, int> numbers = new Dictionary<string, int>
{
    ["Zero"] = 0,
    ["One"] = 1,
    ["Two"] = 2,
    ["Three"] = 3,
    ["Four"] = 4,
    ["Five"] = 5,
    ["Six"] = 6,
    ["Seven"] = 7,
    ["Eight"] = 8,
    ["Nine"] = 9,
};

From here it's trivial to write a short method that does the job utilizing the dictionary numbers:

private static string ConvertFromMixedToStandardNumbers(string input)
{
    string result = input;
    foreach (var number in numbers)
    {
        result = result.Replace(number.Key.ToLower(), number.Value.ToString());
    }
    return result;
}

Or even shorter with LINQ:

private static string ConvertFromMixedToStandardNumbers(string input)
{
    return numbers.Aggregate(input,
        (current, number) => current.Replace(number.Key.ToLower(), number.Value.ToString()));
}

As you can see it's extremely easy to write short and humanly understandable code when you use the proper data structures and C# techniques.

You can even add an enum to the mix and create the dictionary from it:

private enum Number
{
    Zero,
    One,
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
}

private static readonly Dictionary<string, int> numbers = MapEnum(typeof(Number));

private static Dictionary<string, int> MapEnum(Type enumType)
{
    return Enum.GetValues(enumType).Cast<object>()
        .ToDictionary(value => value.ToString(), value => (int) value);
}


Graph represented by an adjacency matrix in C++ I'm working on my data structures knowledge and wanted to create a graph with a small DFS driver which simply prints the nodes as it visits them. Here's my graph class:

#ifndef GRAPH_H_
#define GRAPH_H_

#include <stack>
#include <random>
#include <iterator>
#include <unordered_map>
#include <unordered_set>

template <typename T>
class Graph {
  public:
    Graph(bool directed) : directed{directed}, adj_matrix{} {}
    ~Graph() {}
    void add_edge(const T& start, const T& end) {
      adj_matrix[start][end] = true;
      adj_matrix[start][start] = false;
      adj_matrix[end][end] = false;
      adj_matrix[end][start] = directed ? false : true;
    }

    void DFS(T const *start=nullptr) const {
      if(!adj_matrix.size())
        return;
      if(start==nullptr) {
        DFS_helper(get_random_node());
      } else {
        DFS_helper(*start);
      }
    }

    void DFS_helper(const T& start) const {
      std::unordered_set<T> visited;
      std::stack<T> s;
      s.push(start);
      while(!s.empty()) {
        T top = s.top();
        s.pop();
        // If top is unvisited
        if(visited.find(top) == std::end(visited)) {
          // visit it
          visited.insert(top);
          std::cout << top << ' ';
          for(const auto& adj_node: get_adjacent_nodes(top)) {
             s.push(adj_node);
          }
        }
      }
      std::cout << '\n';
    }

  private:
    std::vector<T> get_adjacent_nodes(const T& v) const {
        std::vector<T> adj;
        for(const auto& pair: adj_matrix.at(v)) {
            T neighbor = pair.first;
            bool is_neighbor = pair.second;
            if(is_neighbor) {
                adj.push_back(neighbor);
            }
        }
        return adj;
    }
    T get_random_node() const {
      auto random_it = std::next(std::begin(adj_matrix), std::rand() % (adj_matrix.size()-1));
      return random_it->first;
    }
    const bool directed;
    std::unordered_map<T, std::unordered_map<T, bool>> adj_matrix;
};

#endif //GRAPH_H_

And here's my driver (inspired from this Wikipedia image):

#include <iostream>
#include "graph.h"

int main() {
  bool directed = false;
  Graph<char> g(directed);
  g.add_edge('A', 'B');
  g.add_edge('B', 'D');
  g.add_edge('A', 'E');
  g.add_edge('E', 'F');
  g.add_edge('A', 'C');
  g.add_edge('C', 'G');
  g.add_edge('B', 'F');

  char a = 'A';
  g.DFS(&a);
}

I'm interested in any tips or recommendations!

Your code looks reasonable, yet I have one suggestion: decouple algorithms from output:

std::vector<T> DFS(T const *start=nullptr) const {
    if(!adj_matrix.size())
        return std::vector<T>();
    if(start==nullptr) {
        return DFS_helper(get_random_node());
    } else {
        return DFS_helper(*start);
    }
}

std::vector<T> DFS_helper(const T& start) const {
    std::unordered_set<T> visited;
    std::unordered_map<T, T*> parents {{start, nullptr}};
    std::stack<T> s;
    std::vector<T> nodes;
    s.push(start);
    while(!s.empty()) {
        T top = s.top();
        s.pop();
        // If top is unvisited
        if(visited.find(top) == std::end(visited)) {
            // visit it
            visited.insert(top);
            nodes.push_back(top);
            for(const auto& adj_node: get_adjacent_nodes(top)) {
                s.push(adj_node);
                parents[adj_node] = &top;
            }
        }
    }
    return nodes;
}

Suppose what happens if your friend needs to run your DFS on a large graph. Most definitely, he or she will be overwhelmed with all the output. So, let the DFS return silently a list of visited nodes; only after that print the nodes if need be.


Armor and Weapon classes for a game I have a 2 classes Armor and Weapon in my game, that inherit from the abstract class Gear:

public class Gear {
    public int price;
    // Other common attributes between armors and weapons
}

public class Weapon : Gear {
    public int damage = 10;
    public int weight = 10;
    public int range = 10;
}

public class Armor : Gear {
    // Defense against different kinds of attack
    public int blunt, slash, ranged;
}

Then I have a class GearButton which is nothing more than a button, with a piece of gear associated. I inherit from this class to create Buttons to Buy, Equip or Upgrade this items, for instance.

This is 2 examples of it:

BuyArmorButton.cs

public class BuyArmorButton : GearButton {

    // ...

    void BuyItem() {
        bool bought = GameSession.Buy((Armor) this.gear);
        if (bought) this.ShowMessage('Buy successful');
    }

    void Update() {
        bool can_buy = GameSession.CanBuy((Armor) this.gear);
        this.EnableButton(can_buy);
    }

    // ...
}

BuyWeaponButton.cs

public class BuyWeaponButton : GearButton {

    // ...

    void BuyItem() {
        bool bought = GameSession.Buy((Weapon) this.gear);
        if (bought) this.ShowMessage('Buy successful');
    }

    void Update() {
        bool can_buy = GameSession.CanBuy((Weapon) this.gear);
        this.EnableButton(can_buy);
    }

    // ...
}

I have added the methods from GameSession, which probably might also need to be tweaked, for this to work.

public static bool Buy(Armor armor) {
    if (!CanBuy(armor)) return false;

    data.money -= armor.price;
    data.armorsPurchased.Add(armor);
    return true;
}

public static bool Buy(Weapon weapon) {
    if (!CanBuy(weapon)) return false;

    data.money -= weapon.price;
    data.weaponsPurchased.Add(weapon);
    return true;
}

public static bool CanBuy(Armor armor) {
    if (data.armorsPurchased.Contains(armor))
        return false;

    if (armor.price > data.money)
        return false;

    return true;
}

public static bool CanBuy(Weapon weapon) {
    if (data.weaponsPurchased.Contains(weapon))
        return false;

    if (weapon.price > data.money)
        return false;

    return true;
}

It kinda feels like a lot of the code duplication, and I thought it could be merged into a BuyGearButton class, but I am not sure how to go about it, because of the up-casting of the Gear classes.

I have pasted the whole files here:

Gear.cs
Weapon.cs
Armor.cs
GameSession.cs
BuyArmorButton.cs
BuyWeaponButton.cs

Once various responsibilites (functionality) is separated into appropriate classes, inheritance and using subclasses is not a problem.

Rethink your core classes. Don't make client code do the work - that's a guarantee of duplication. A good class hides state and exposes functionality. Even basic functionality like overriding Equals pays off. "Do not make client code do the work for that class". Repeat this a million times. Oh, I expect you will also avoid tons of debugging.

Some methods are overloaded. The point is when you see a need for something different put that in the proper class. Don't be lazy and write it in the calling class because it's easy and quick.

SPOILER: gear and gear collections are just data structures. Abstract things. A Warrior has his personal stuff (a gear collection) and an Armory (a really big gear collection) is where he buys his stuff.

Gear enum

Looks like you care only if some gear is a weapon, armor, etc. not a specific object.

public enum GearType { undefined, Weapon, Armor }

Make Gear abstract

And give it all the common gear behavior.

public abstract class Gear {
    protected decimal price { get; set; }
    public GearType Type { get; protected set; } // set only in a constructor

    public virtual bool IsSameKind( Gear otherGear ) {
        return this.Equals( otherGear );
    }

    // I thought of this as I was working on the collection class below
    public virtual bool IsSameKind( GearType thisKind ) { return this.Type == thisKind; }

    // any armor is armor. any weapon is weapon....
    /// <summary>
    /// Equates on Type property.
    ///</summary>
    public override Equals( Object otherGear ) {
       if( otherGear == null ) return false;

       otherGear = otherGear as Gear;
       if( otherGear == null ) return false;

       return this.Type == otherGear.Type;
    }
}

Use Constructors

To guarantee valid, complete, correct objects.

public class Armor : Gear {
   protected int blunt { get; set; }
   protected int slash { get; set; }
   protected int range { get; set; }

   public Armor ( decimal price, int blunt, int slash, int range ) {
      this.Type = GearType.Armor;
      // set other properties here
   }
}

Custom Collections

Solves your upcast issue.

Also higher level code will make more sense, is cleaner, clearer, and simpler.

publc class GearCollection {
   protected List<Gear> Armory { get; set; }

   public GearCollection() { Armory = new List<Gear>(); }

   public void Add ( Gear thing ) {
       if ( thing == null ) return;
       Armory.Add( thing );
   }

   // Passing in a Gear reference. The OBJECT itself will be
   // a "Weapon", "Armor", etc.
   public bool Contains( Gear otherThing ) {
       if ( otherThing == null ) return false;
       if ( Armory.Contains( otherThing ) ) return true;  // uses equals override.
       return false;
   }

   public bool Contains( GearType thisGear ){
      bool gotIt = false;

      foreach( var item in Armory ) {
         if( item.IsSameKind( thisGear ) {
            gotIt = true;
            break;
         }
      }
      return gotIt;
  }

   public GearCollection GetAll( GearType thisKind ){
      GearCollection sameGear = new GearCollection();

      foreach( var item in Armory ) {
         if( item.IsKind ( thisKind ) {
            sameGear.Add( item );
         }
      }
      return sameGear;
   }

   // this method makes THIS collection object mutable.
   // a discussion for another time.
   public GearCollection GetAll( Gear likeThis ){
      GearCollection sameGear = new GearCollection();

      foreach( var item in Armory ) {
         if( item.Equals( likeThis ) ) sameGear.Add( item );
      }
      return sameGear;
   }
}

Separation of concerns

Why would a button have its own gear? That's a code smell to me. I'd expect event handlers to call methods on domain objects like Warrior or AmmoDump or WeaponCache. Those are things I expect to have Gear, not the UI controls.

public class Warrior {
    protected GearCollection MyGear { get; set; }
    public Warrior() { MyGear = new GearCollection(); }
    public Warrior( GearCollection standardIssue ) {
       MyGear = standardIssue?? new GearCollection();
    }
}

// The Armory is where you buy your gear. A gear collection is just
// a data structure => separation of concerns.
public class Armory {
   protected GearCollection Inventory { get; set; }

   // optional parameter so I don't have to write
   // a contructor overload.
   public Armory( GearCollection newInventory = null ){
      Inventory = newInventory ?? new GearCollection();
   }

  // renamed "CanBuy".
   public bool IsInStock( GearType gearKind ) {
       return Inventory.Contains( gearKind );
   }

   public bool IsInStock( Gear likeThis ) {
      return Inventory.Contains( likeThis ) {
   }

   public Gear Buy( GearType something, decimal cashOnly ) {
      if( !IsInStock( something ) )  return null;

      Gear newBling = Inventory.Remove( something );  // didn't write that method yet.
      if( cashOnly < newBling.Price ) return null;

      return newBling;
   }

   public void AddInventory ( GearCollection newShipment ) {
      if( newShipment == null ) return;
      Inventory.AddRange( newShipment );
   }
}

P.S. Now that we defined the Armory class, I'd go back and rename the GearCollection.Armory property. Make it more general, more abstract sounding because it is. The collection is a data structure. We want names appropriate for the class they are in.

The methods defined in Armory class is what brings the armory concept to life - not it's properites.

Edit

  could you write an answer with your suggestion of "type checking". Id love to see how you would do it.

It depends on how specific you want to be. The keyword is:

  An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

If everything derives from Gear, that won't help too much looking into a GearCollection.

Keyword typeof returns a System.Type that you can compare to the typeof of other objects in a GearCollection. This is the specific type of your object.

Type Checking: typeof, GetType, or is?

end Edit


Rewrite of Sokoban using State I watched this live coding of Sokoban in Haskell and thought I'd take a crack at writing it using State and lenses, since I've never tried that before. My problem is that the control flow seems to be complicated by isWall and friends now being monadic values that I need to unwrap, so I can't use the otherwise obvious approach of guards etc. Any suggestions? I did not focus very much on not making partial functions or handling IO properly, what interests me is how to manage the data and control flow cleanly. Note that I should have also not set default values for _wWorker and _wMax.

The worst culprits are move, toChar and setMaxCoords.

EDIT: Because of the way values are in State, I have a series of functions:

isWall :: MonadState World m => Coord -> m Bool
isWall    c = use $ wWalls.contains c

isCrate :: MonadState World m => Coord -> m Bool
isCrate   c = use $ wCrates.contains c

isStorage :: MonadState World m => Coord -> m Bool
isStorage c = use $ wStorage.contains c

isWorker :: MonadState World m => Coord -> m Bool
isWorker  c = uses wWorker (==c)

These, I feel, are all fine, but they end up being less than useful in practice, because of the fact that the Bool is wrapped. The unwrapping process becomes very tedious in several functions:

move :: MonadState World m => Direction -> m ()
move dir = do
    newCoord  <- uses wWorker (moveCoord dir)
    let newCoord' = moveCoord dir newCoord
    wall      <- isWall  newCoord
    wall'     <- isWall  newCoord'
    crate     <- isCrate newCoord

    case () of
        () | wall  -> return ()
           | crate -> if wall' then return () else
                        do
                            wWorker ^= newCoord
                            wCrates %= delete newCoord
                            wCrates %= insert newCoord'
           | otherwise -> wWorker ^= newCoord

toChar :: MonadState World m => Coord -> m Char
toChar c = do
    wall    <- isWall    c
    crate   <- isCrate   c
    storage <- isStorage c
    worker  <- isWorker  c
    return $ case () of
        () | wall      -> '#'
           | worker    -> '@'
           | crate     -> 'o'
           | storage   -> '.'
           | otherwise -> ' '

The lenses themself also come with a certain cost

setMaxCoords :: StateT World IO ()
setMaxCoords = do
    xMaxWall           <- uses wWalls   $ fold (max . fst) 0
    yMaxWall           <- uses wWalls   $ fold (max . snd) 0
    xMaxCrate          <- uses wCrates  $ fold (max . fst) 0
    yMaxCrate          <- uses wCrates  $ fold (max . snd) 0
    xMaxStorage        <- uses wStorage $ fold (max . fst) 0
    yMaxStorage        <- uses wStorage $ fold (max . snd) 0
    (xWorker, yWorker) <- use wWorker
    wMax ^= (
        maximum [xMaxWall, xMaxCrate, xMaxStorage, xWorker],
        maximum [yMaxWall, yMaxCrate, yMaxStorage, yWorker]
            )

I feel like I must be missing some obvious abstractions, because all these operations seem trivial and necessary, but the wrapping adds a lot of boilerplate.

The full code is here: http://hpaste.org/73124

I think the is* functions are a bad idea - Haskell has pattern matching for this.

Also you can 'unwrap' your World when necessary and get unwrapped data from it.

data Cell = Wall | Crate | Storage | Worker | Empty

cellContents coords world = bar where
    f x = S.member coords (x ^$ world)
    bar | f wCrates = Crate
        | f wWalls = Wall
        | f wStorage = Storage
        | coords == (wWorker ^$ world) = Worker
        | otherwise = Empty

With this approach toChar can be just

toChar :: World -> Coord -> Char

toChar2 coords world = case cellContents coords world of
      Wall      -> '#'
      Worker    -> '@'
      Crate     -> 'o'
      Storage   -> '.'
      _ -> ' '

If you have already unpacked current world, you can use

let char = toChar2 coords world

If you don't have world you can just do

char <- toChar2 coord <$> get

The only place where you use toChar is printWorld, so it becomes simpler (no need for evalState):

let out = [[ toChar2 (x,y) w | x <- [0 .. maxX]] | y <- [0 .. maxY]]

setMaxCoords can be rewritten as:

setMaxCoords :: StateT World IO ()
setMaxCoords = do
    w <- get
    wMax .= maxCoords w

maxCoords = foldr (app2 max) (0, 0) . allCoords where
    allCoords w = (wWorker ^$ w) : concatMap (\x -> S.toList $ x ^$ w) [ wWalls, wCrates, wStorage ] where
    app2 f (x1, y1) (x2, y2) = (f x1 x2, f y1 y2)

move can be rewritten the same way as toChar2:

move dir w = move2 (cellContents newCoord w) (cellContents newCoord' w) where
    oldCoord = wWorker ^$ w
    newCoord = moveCoord dir oldCoord
    newCoord' = moveCoord dir newCoord

    move2 Wall _ = return ()
    move2 Crate Wall = return ()
    move2 Crate _ = do
        wWorker .= newCoord
        wCrates %= delete newCoord
        wCrates %= insert newCoord'
    move2 _ _ = wWorker .= newCoord

It should be used in the loop as get >>= move dir.


HashTable implementation I have been trying to implement the Hash Table function in Java and here is what I came up with. I would just like to get an opinion on this work. Would there be a better way or any improvement to make to this code ?

HashTable.java : basically contains all the hastable functions to create the table, add a node and retrieve a node

import java.math.BigInteger;

public class HashMap {
      // Srtting table size to a max of 32, value used to modulus for hash value.
      private final static int TABLE_SIZE = 32;

      HashEntry[] table;

      HashMap() {
            table = new HashEntry[TABLE_SIZE];
            for (int i = 0; i < TABLE_SIZE; i++)
                  table[i] = null;
      }

      /* function to retrieve value from the table according to key */
      public int get(String key) {
            int hash = new BigInteger(toAscii(key)).mod(new BigInteger(((Integer)TABLE_SIZE).toString())).intValue();
            while (table[hash] != null && table[hash].getKey() != key)
                  hash = (hash + 1) % TABLE_SIZE;
            if (table[hash] == null)
                  return -1;
            else
                  return table[hash].getValue();
      }

      /* function to add value to the table */
      public void put(String key, int value) {
            //creating hash code using key value given as a string
            int hash = new BigInteger(toAscii(key)).mod(new BigInteger(((Integer)TABLE_SIZE).toString())).intValue();
            while (table[hash] != null && table[hash].getKey() != key)
                  hash = (hash + 1) % TABLE_SIZE;
            table[hash] = new HashEntry(key, value);
      }

      /* value to create the Hash code from he name entered, basically converting name to ASCII */
      public static String toAscii(String s){
          StringBuilder sb = new StringBuilder();
          long asciiInt;
          // loop through all values in the string, including blanks
          for (int i = 0; i < s.length(); i++){
              //getting Ascii value of character and adding it to the string.
              char c = s.charAt(i);
              asciiInt = (int)c;
              sb.append(asciiInt);
          }
          return String.valueOf(sb);
  }
}

HashEntry.java: an object taking the entry contains setter and getters

public class HashEntry {
      private String key;
      private int value;

      HashEntry(String key, int value) {
            this.key = key;
            this.value = value;
      }

      public String getKey() {
            return key;
      }

      public int getValue() {
            return value;
      }
}

HasheTable.java: just testing my implementation

import java.io.IOException;

public class HashTable {
    public static void main(String[] args) throws IOException
    {
        HashMap entry = new HashMap();
        entry.put("Wasif", 36100);
        entry.put("Stephen Hughes", 22100);
        System.out.println(entry.get("Stephen Hughes"));
    }
}

Implementing a hash table

This hash table implementation is a bit limited: it supports only String keys and int values. It would be good to generalize it.

When getting a value of a key not in the table, the common expected behavior is null. Since you're using int as the type of values, this is not possible, but -1 just doesn't seem special enough to be commonly understood as "missing value".

The toAscii method is very bad:

It's only used internally, so it shouldn't be public
The name doesn't describe very well what it does: converting a string to ascii sounds more like an encoding transformation than a hash code calculation. It would have been better to call it calculateHashCode, and make it return a BigInteger
Even better would have been to use String's very own hashCode, rather than reimplementing your own

Naming

    HashMap entry = new HashMap();

"entry" is an inappropriate name for a map. "map" would seem the obvious choice.

General coding issues

The HashEntry class is an implementation detail of your hash table.
As such, it would be best to hide this class,
by making it a private static class inside the hash table.

Instead of this:

new BigInteger(((Integer)TABLE_SIZE).toString());

A much better and simpler way:

BigInteger.valueOf(TABLE_SIZE);

Limit variables to the smallest scope possible,
to prevent accidental changes outside their intended purpose.
For example in this code:

      long asciiInt;
      // loop through all values in the string, including blanks
      for (int i = 0; i < s.length(); i++){
          //getting Ascii value of character and adding it to the string.
          char c = s.charAt(i);
          asciiInt = (int)c;
          sb.append(asciiInt);
      }

asciiInt should have been declared inside the loop.

This code looks very confused:
you get a char, cast it to an int to store in a long variable.
This could have been simply:

    for (int i = 0; i < s.length(); i++){
        sb.append((int) s.charAt(i));
    }

And even simpler with a for-each loop:

    for (char c : s.toCharArray()) {
        sb.append((int) c);
    }

        table = new HashEntry[TABLE_SIZE];
        for (int i = 0; i < TABLE_SIZE; i++)
              table[i] = null;

When iterating over all elements of an array,
I recommend using the array's length as the limit.
It's safer. Like this:

        table = new HashEntry[TABLE_SIZE];
        for (int i = 0; i < table.length; i++) { ... }

But since you're only using this loop to assign the values to null,
the entire loop is pointless, you can safely delete it.

It's highly suspicious when you compare objects using != like you do for the keys in this code:

    while (table[hash] != null && table[hash].getKey() != key)
        hash = (hash + 1) % TABLE_SIZE;

For example, what do you think this code will print:

    String key1 = new String("Jack");
    String key2 = new String("Jack");
    entry.put(key1, 11);
    entry.put(key2, 21);
    System.out.println(entry.get(key1));
    System.out.println(entry.get(key2));

It will print 11 and 21. I suggest to replace != on objects everywhere with .equals(...). Then these two keys will be considered equal, as usually expected from a hash map, and the print statements will return 21 and 21.

Other coding style issues

I suggest using braces { ... } even for single-statement blocks
Instead of comments like /* function to retrieve value from the table according to key */, use proper JavaDoc, for example:

/**
 * Retrieve value from the table according to key
 *
 * @param key the key to look for
 * @return the value of the key, or null if doesn't exist
 */

Since the fields of HashEntry never change, you can make them final
This code block appears twice:

while (table[hash] != null && !table[hash].getKey().equals(key))
    hash = (hash + 1) % TABLE_SIZE;

Avoid code duplication. Extract to a private helper method,
or refactor your implementation in a way that you don't have to duplicate code.

Same note for this code:

int hash = new BigInteger(toAscii(key)).mod(new BigInteger(((Integer)TABLE_SIZE).toString())).intValue();

Improved implementation

Taking some of the suggestions above,
the implementation can be simplified and improved:

private int calculateHashCode(String key) {
    int mod = key.hashCode() % TABLE_SIZE;
    return mod < 0 ? mod + TABLE_SIZE : mod;
}

private int findIndex(String key) {
    int index = calculateHashCode(key);
    while (table[index] != null && !table[index].getKey().equals(key)) {
        index = (index + 1) % TABLE_SIZE;
    }
    return index;
}

public int get(String key) {
    int index = findIndex(key);
    return table[index] == null ? -1 : table[index].getValue();
}

public void put(String key, int value) {
    table[findIndex(key)] = new HashEntry(key, value);
}


Simple haschange event I did a little function which is listening to hashchanges.

What do you think about?

var onhashchange = function(code) {
    var checkHash = function(oldHash, code) {
        var hash = window.location.hash;
        var hashObject = hash.replace('#/','').split('/');

        if (hash !== oldHash)
            code(hashObject);

        setTimeout(function(){checkHash(hash, code);},100);
    }

    var oldHash = window.location.hash;

    setTimeout(function(){checkHash(oldHash, code);},100);
}

onhashchange(function(evt) {
    console.log(evt[0]); // Pagename after #/ - subcategories evt[1]... after slashes /
});

First of and maybe a bit off-topic. The is this feature in all modern browsers now: https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange and the support is good: http://caniuse.com/hashchange

Then the function. Perosnally I would use an anonymous function without storing it in a var first. I would pass in the hs 'unparsed' and simply pass the hash to the function instead of an array. It is snipplet that checks or the hash changes and should thus not be concerned on what the symbols in the hash mean.

Also, instead of using the setTimeOut and calling it allover your code. Simply use the setInterval function.


Perform BFS on a Binary Tree Task:  Perform Breadth first traversal on a Binary Search Tree and print the elements traversed.

class Node(object):
    def __init__(self, value,left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

class BinarySearchTree(object):
    def __init__(self, value):
        self.root = Node(value)

    def insert(self, value):
        current = self.root
        while current:
            if value > current.value:
                if current.right is None:
                    current.right = Node(value)
                    break
                else:
                    current = current.right
            else:
                if current.left is None:
                    current.left = Node(value)
                    break
                else:
                    current = current.left

    def Breadth_first_search(self,root):
        """In BFS the Node Values at each level of the Tree are traversed before going to next level"""

        visited = []
        if root:
            visited.append(root)
            print root.value
        current = root
        while current :
            if current.left:
                print current.left.value
                visited.append(current.left)
            if current.right:
                print current.right.value
                visited.append(current.right)
            visited.pop(0)
            if not visited:
                break
            current = visited[0]

t = BinarySearchTree(100)
t.insert(12)
t.insert(92)
t.insert(112)
t.insert(123)
t.insert(2)
t.insert(11)
t.insert(52)
t.insert(3)
t.insert(66)
t.insert(10)

print "Output of Breadth First search is "
t.Breadth_first_search(t.root)

The code runs acceptably and gives the correct output. Is there better solution to this problem?

PEP-0008: your method names should follow snake_case style, and there should be a space between arguments. So change your method singature to:

def breadth_first_search(self, root):
    # remaining code

You maintain a list called as visited, however the nodes added in it are ones which are yet to be visited. Call it to_visit instead. One should use the variable name visited to keep track of nodes that are visited already.

to_visit = []
if root:
    to_visit.append(root)
    print( root.value)
# remainig code with to_vist replacing visited

You assign the node at the end, and pop the current node just before that. Better to do this in the beginning of the loop, and iterate over the existence of elements within the list. This way, your code gets much concise and clean:

while to_visit:
    current = to_visit.pop(0)
    if current.left:
        print( current.left.value)
        to_visit.append(current.left)
    if current.right:
        print( current.right.value)
        to_visit.append(current.right)

You pre-check and print the value of the left and right child, and that of root as well. It would be better if these statements could be reduced:

while to_visit:
    current = to_visit.pop(0)
    print( current.value)
    if current.left:
        to_visit.append(current.left)
    if current.right:
        to_visit.append(current.right)

So now, your function looks like

def breadth_first_search(self, root):
    """In BFS the Node Values at each level of the Tree are traversed before going to next level"""

    to_visit = []
    if root:
        to_visit.append(root)
    while to_visit:
        current = to_visit.pop(0)
        print( current.value)
        if current.left:
            to_visit.append(current.left)
        if current.right:
            to_visit.append(current.right)

But this gets called as t.Breadth_first_search(t.root), since root is already present, we can use a default value here. Also, the list can be initialized with an element, so we save the append call:

def breadth_first_search(self, root=None):
    """In BFS the Node Values at each level of the Tree are traversed before going to next level"""

    root = self.root if root is None else root
    to_visit = [root]
    while to_visit:
        current = to_visit.pop(0)
        print(current.value)
        if current.left:
            to_visit.append(current.left)
        if current.right:
            to_visit.append(current.right)

And now, you can call it as t.breadth_first_search().
But wait, if it is breadth_first_search, shouldn't you be searching for something? Well no, your question states to do a breadth first traversal, so you should rename your method to:

def breadth_first_traversal(self, root=None):
    # remaining code as above


Sorting Nested Array Recently on SO there was this question

i am trying to get sequence index of each array of array like I have
an element of the array and that 5 arrays have multiple elements and I
want to get the first index of each array then the second and so.
below is my array data const arrData = [[1,2,4,6],[3,8,7],[12,13],[],[9,10]];
and my expected outout [1,3,12,9,2,8,13,10,4,7,6]

This is very basic but I found it interesting and tried to solve it.
I solved it like this, I thought it is easy to understand and to read but in reasons that I go in every nested array through all elements maybe it is not the best solution.
For example if I have one array with length 100 and all the other ones are just have length 1.
What do you think about my code?

const arr = [
  [1, 2, 4, 6],
  [3, 8, 7],
  [12, 13],
  [],
  [9, 10]
];

let biggestLength = Number.MIN_VALUE;
for (let i = 0; i < arr.length; i++) {
  if (arr[i].length > biggestLength) {
    biggestLength = arr[i].length;
  }
}

let result = [];
for (let l = 0; l < biggestLength; l++) {
  for (let k = 0; k < arr.length; k++) {
    if (arr[k][l] !== undefined) {
      result.push(arr[k][l])
    }
  }
}

console.log(result)

Overall your code is readable and it seems reasonably clear what it does. As you said, the code is somewhat inefficient if one of the arrays is much larger than the rest, but for your example (and honestly, even if you had a thousand items in one array), the time cost would probably be negligible, unless the number of arrays in arr is very very large.
Number.MIN_VALUE
Number.MIN_VALUE is not what you think it is. It represents the smallest positive number that can be represented, not the most negative number. As a result, if you use let arr = []; you end up with a biggestLength that is slightly more than 0 and run your second loop... only to figure out that you do not have items. Or arrays, This in itself does not break anything, but you could just initialise biggestLength to 0 and things would work out fine.
Optimising
As I said earlier, the amount of time it takes to do this operation is negligible, even if you have 100 items in the first array. With 11 items over 4 arrays (16 operations) it takes me 0.010ms, and with 107 items over 4 arrays (400 operations) it takes me 0.025ms.

const arr = [
  [1, 2, 4, 6],
  [3, 8, 7],
  [12, 13],
  [],
  [9, 10]
];

function getUnfoldedArray(arr) {
  let biggestLength = Number.MIN_VALUE;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].length > biggestLength) {
      biggestLength = arr[i].length;
    }
  }

  let result = [];
  for (let l = 0; l < biggestLength; l++) {
    for (let k = 0; k < arr.length; k++) {
      if (arr[k][l] !== undefined) {
        result.push(arr[k][l])
      }
    }
  }

  return result;
}

console.time('First run is always slower');
getUnfoldedArray(arr);
console.timeEnd('First run is always slower');

console.time('time1');
const result = getUnfoldedArray(arr);
console.timeEnd('time1'); // 0.010ms

arr[0] = [];
for (let i = 0; i < 100; i++) {
  arr[0].push(i);
}

console.time('time2');
const result2 = getUnfoldedArray(arr);
console.timeEnd('time2'); // 0.025ms

console.log(result);
console.log(result2);

If you don't mind destroying the array you are doing stuff on, you can potentially use Array.shift(). You could also splice out any empty arrays then, but keep in mind that loops will mess up when you do that. Overall your code would probably get more complicated for not a lot of gain.


A representation of the Mandelbrot Set I've written up some code that represents the Mandelbrot set in an, admittedly, quite inefficient way. It probably looks awful due to the fact that I did this completely solo, without any external sources aside from the wiki page. What I was wondering is, how can I, without rewriting it completely, fix my code so that it either runs faster, or is higher definition?

Final image:

import turtle
x = -200
y = 99
RN = -2
i = float(1.0)
c = complex(RN+i)
win = turtle.Screen()
win.setup(400,400)
t = turtle.Turtle()
t.speed(0)
t.penup()
t.ht()
pattern = []

#this calculates what the color hex value each pixel will be. if the 10th
#iteration results in a number greater than 2, then that pixel is outside
#of the set.
def set_color(RN,pattern,z,c):
    for v in range(10):
        z = z**2 + c
        pattern.append(z)
    if abs(z) > 3.7918623e+90:
        t.color("#191970")
    elif abs(z) > 1.9472705e+45:
        t.color("#16167F")
    elif abs(z) > 4.4127888e+22:
        t.color("#13138F")
    elif abs(z) > 210066388901:
        t.color("#10109F")
    elif abs(z) > 458330:
        t.color("#0D0DAF")
    elif abs(z) > 677:
        t.color("#0B0BBF")
    elif abs(z) > 26:
        t.color("#0808CF")
    elif abs(z) > 5:
        t.color("#0505DF")
    elif abs(z) > 2:
        t.color("#0202EF")
    elif abs(z) > 1.75:
        t.color("yellow")
    elif abs(z) > 1.5:
        t.color("gold")
    elif abs(z) > 1.25:
        t.color("goldenrod")
    elif abs(z) > 1:
        t.color("darkgoldenrod")
    else:
        t.color("black")

#draws the set
def Mandelbrot(RN,pattern,precision,check_rate,move_rate,x,y,i,c):
#draws line by line, 100 times
    for e in range(100):
        t.pendown()
#draws one line
        for e in range(precision):
            z = 0
            set_color(RN,pattern,z,c)
            pattern = []
            RN = float(RN + move_rate)
            c = complex(RN,i)
            x = x + check_rate
            t.setposition(x,y)
#sets up values you'll need next row
        RN = -2.0
        i = i-.02
        t.penup()
        x = -200
        y = y - 2
        t.setposition(x,y)
    t.penup()

#purely decorative black background for the set
def borders():
    t.color("black")
    t.setposition(-200,200)
    t.pendown()
    t.begin_fill()
    for i in range(4):
        t.forward(400)
        t.right(90)
    t.end_fill()

precision = 400
check_rate = float(400 / precision)
move_rate = float(check_rate/100)

t.penup()
borders()
t.setposition(x,y)
Mandelbrot(RN,pattern,precision,check_rate,move_rate,x,y,i,c)

Wow!  That is really slow.  I changed range(100) to range(5), just to get some timing numbers without dying of boredom.  So with that as my baseline, let's work on speeding it up.

set_color

def set_color(RN,pattern,z,c):
    for v in range(10):
        z = z**2 + c
        pattern.append(z)
    if abs(z) > 3.7918623e+90:
        t.color("#191970")
    elif abs(z) > 1.9472705e+45:
        t.color("#16167F")
    elif abs(z) > 4.4127888e+22:
        t.color("#13138F")
    elif abs(z) > 210066388901:
        t.color("#10109F")
    elif abs(z) > 458330:
        t.color("#0D0DAF")
    elif abs(z) > 677:
        t.color("#0B0BBF")
    elif abs(z) > 26:
        t.color("#0808CF")
    elif abs(z) > 5:
        t.color("#0505DF")
    elif abs(z) > 2:
        t.color("#0202EF")
    elif abs(z) > 1.75:
        t.color("yellow")
    elif abs(z) > 1.5:
        t.color("gold")
    elif abs(z) > 1.25:
        t.color("goldenrod")
    elif abs(z) > 1:
        t.color("darkgoldenrod")
    else:
        t.color("black")

The first argument, RN, is not used in this function.  So we can omit that, and save a little time not passing a useless argument.

        z = 0
        set_color(RN,pattern,z,c)
        pattern = []

The second argument, pattern, is being accumulated, and then discarded.  So busy work involving memory allocation for extending a list who's value is never used.  We can remove that argument and pattern.append(z).

The third argument, z, is always coming in as zero.  No point passing it as an argument; just initialize it inside the set_color function, which will save a little bit of time because we don't pass the extra argument.

Which just leaves passing in the argument c.  Getting better.

Then, you have a long string of if abs(z) > # checks.  How many times are you computing abs of a complex number?  How many times will the result be different?  Maybe we can compute it just once?

    abs_z = abs(z)
    if z > 3.7918623e+90:
        t.color("#191970")
    elif abs_z > 1.9472705e+45:
        ...

Unfortunately, that still leaves an ugly long string of if/elif/elif/else statements.  With 14 possibilities, you take an average of 7 tests to determine the correct value; with a binary search, this would reduce to 4.  We just need to put the values in a list, and use bisect.bisect to determine where the abs(z) would be inserted in the list.

import bisect

MAG = (1, 1.25, 1.5, 1.75, 2, 5,
       26, 677, 458330, 210066388901, 4.4127888e+22, 1.9472705e+45,
       3.7918623e+90)

COLOR = ("black", "darkgoldenrod", "goldenrod", "gold", "yellow", "#0202EF",
         "#0505DF", "#0808CF", "#0B0BBF", "#0D0DAF", "#10109F", "#13138F",
         "#16167F", "#191970")

def set_color(c):
    z = 0
    for _ in range(10):
        z = z**2 + c
    t.color(COLOR[bisect.bisect(MAG, abs(z))])

My timing hasn't shown a significant impact in speed yet, but I certainly like the set_color function much better now.  If you want to add more colours, it is simply a matter of filling in additional values in the arrays.

Mandelbrot

def Mandelbrot(RN,pattern,precision,check_rate,move_rate,x,y,i,c):
#draws line by line, 100 times
    for e in range(100):
        t.pendown()
#draws one line
        for e in range(precision):
            set_color(c)                 # Note: modified for new set_color
            RN = float(RN + move_rate)
            c = complex(RN,i)
            x = x + check_rate
            t.setposition(x,y)
#sets up values you'll need next row
        RN = -2.0
        i = i-.02
        t.penup()
        x = -200
        y = y - 2
        t.setposition(x,y)
    t.penup()

This looks backwards.  You pass in RN, but RN is computed in the loop.  You pass in x, but x is initialize to -200 each time through the loop.  You pass in c, but c is computed in the loop.  And most things seem to be computed just after they've been used for the next loop iteration!

Let's re-work this, moving calculation to before they are used, and see what it looks like.  Along the way, variable = variable + adjustment will be replaced with variable += adjustment, because it results in one less variable lookup in the Python interpreter.  Also, RN + move_rate is already a float, so we can omit the redundant float() call.  When looping over a range of values (y starting at 99, and going down by two 100 times, a for y in range(...) construct is used:

def mandelbrot(precision, check_rate, move_rate):
    i = 1.0
    t.penup()

    for y in range(99, 99 - 2 * 100, -2):
        rn = -2.0
        x = -200
        t.setposition(x, y)

        t.pendown()
        for _ in range(precision):
            c = complex(rn, i)
            set_color(c)

            rn += move_rate
            x += check_rate
            t.setposition(x, y)

        i -= 0.02
        t.penup()

Several PEP-8 changes: commas are followed by a space, variable names and method names are lowercase (technically, snake_case).  _ is used as the unused variable.  Operators have a space on each side.

Main

Again, float( ) calls are unnecessary.

if __name__ == '__main__':
    precision = 400
    check_rate = 400 / precision
    move_rate = check_rate / 100

    t.penup()
    borders()
    mandelbrot(precision, check_rate, move_rate)

Speed Up?

Despite my initial efforts, my very rough timing measurements don't show I've sped things up any.  But I do think the code has been cleaned up significantly.

Next step in my efforts will be to split this up into two parts:

computing a grid of Mandelbrot colour index values
drawing the image (using the computed grid of colour index values) with turtle graphics

Then, I can get more accurate timing information for each section.

Step 1 is open to parallel processing (Python threads won't help, due to the Global Interpreter Lock (GIL), but using processes should help), but that will only help if it is the large consumer of time.  I fear it is the turtle graphics.


Program based on Vigenère’s cipher I would like to get some helpful thoughts on this and if there is a way to break it. Is there any point to not use fgets in that form?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define GETNAME_SIZE 100

char *getPhrase() {

    int size;
    char phrase[GETNAME_SIZE];
    char *phraseHolder;
    printf("Enter a phrase:");

    fflush(stdout);

    if (fgets(phrase,sizeof phrase,stdin) == NULL ) {
        return NULL;
    }

    size = strlen(phrase)+1;
    phraseHolder = malloc(size);
    if (phraseHolder == NULL) {
        return NULL;
    }
    strcpy(phraseHolder,phrase);
    phraseHolder[strcspn(phraseHolder,"\n")] = '\0';
    printf("The phrase you introduced is: <%s>\n", phraseHolder);

    return phraseHolder;

}

char *getChangedPhrase(char *phrase) {

    int size,i,codeSize;
    int j = 0;
    char *code;
    int pace;
    size = strlen(phrase)+1;
    if(size <2) {
        printf("Enter a bigger phrase!");
        return NULL;
    }

    code = malloc(size);
    if (code == NULL) {
        return NULL;
    }
    fflush(stdout);
    printf("Enter the code that you want to be used with your phrase!(only letters)\n");

    if (fgets(code,size,stdin) == NULL) {
        return NULL;
    }
    code[strcspn(code,"\n")] = '\0';
    codeSize = strlen(code);
    for(i = 0 ; i < size ; i++) {
            if(phrase[i] < 65 || (90 < phrase[i] && phrase[i] < 97) || 122<phrase[i] ) {
                continue;
            }
            else {
                while(code[j] < 65 || (code[j] > 90 && code[j] < 97) || code[j] > 122 ) {
                    j++;
            }
                pace = code[j];

            if(code[j] > 96 && code[j] < 123) {
            pace = pace - 97;

            if(phrase[i] + pace > 122 )
                phrase[i] = phrase[i] + pace - 26;
            else
                if( phrase[i] + pace > 90 && code[j] < 90)
                phrase[i] = phrase[i] + pace - 26;
            else
                if(phrase[i] + pace > 90 && code[j] > 96 && phrase[i] < 91 ) {
                   phrase[i] = phrase[i] + pace - 26;
                }
            else
                phrase[i] = phrase[i] + pace;

        }
            else if ( code[j] > 64 && code[j] <91 ) {
                pace = pace - 65;

                if((phrase[i] < 91 && (phrase[i] + pace) > 90) || (phrase[i] + pace) > 122 )
                    phrase[i] = (phrase[i] + pace - 26);

                else
                    phrase[i] = phrase[i] + pace;
            }

            j++;

            if(j == codeSize) {
                j = 0;
            }
        }

    }
    free(code);
    phrase[strcspn(phrase,"\n")] = '\0';
    return phrase;
}

int main() {
    char *phrase = getPhrase();
    char *modifiedPhrase = getChangedPhrase(phrase);
    printf("The changed phrase is: \n <%s> \n", modifiedPhrase);
    //free(phrase);
    printf("Press ENTER key to Continue\n");
    getchar();
    getchar();
}

Your code is pretty clean and well-formed, but I do have several critiques.
Unexpected behavior
Your program will exhibit unexpected behavior if the phrase entered by the user is longer than GETNAME_SIZE - 2 chars.  In that cases, the fgets() call in getPhrase() will leave the tail of the line unread, and reading should be expected to pick up there in the subsequent getChangedPhrase() call (to terminate no later than the end of that line).  The user will no doubt expect the phrase to be encoded according to the next line they enter, not the tail of the first.
To fix that, you should either arrange in getPhrase() to keep reading through the end of the line.  You can discard characters after the GETNAME_SIZE - 1th if you like, or you can arrange to append them to the phrase (you'll need realloc()).  Just don't leave a tail of the line unread.
getChangedPhrase() behaves similarly when it reads the key, which again could be surprising.  It is not certain to be sufficient to limit the input key length to the message length because you don't necessarily use all of the key characters (you skip those that aren't ASCII letters).  Cutting off the tail of the key can therefore change the result.
This fragment looks wrong:
                if( phrase[i] + pace > 90 && code[j] < 90)
                phrase[i] = phrase[i] + pace - 26;

I think you mean
                if( phrase[i] + pace > 90 && phrase[i] < 91)
                phrase[i] = phrase[i] + pace - 26;

See also below.
Flawed implementation
Your code can easily be made to overrun the bounds of the code array.  In fact, that will happen if the number of usable key characters is smaller than the number of letters in the message.  To (partially) fix this, you need to wrap around the end of the key inside the while loop, rather than at the end of the for loop where you now do that.
That will, however, expose another flaw in your implementation: it does not handle the case where there are zero usable key characters.  Your current implementation will just immediately run off the end of the array in that case; after the fix, it will loop infinitely.  See below for a suggestion that will help.
Error handling
getPhrase() does a decent job of noticing when memory allocation fails or nothing is read from the input.  It helpfully returns NULL in those cases.  main(), however, ignores those signals and unconditionally passes the result to getChangedPhrase().  For its part, getChangedPhrase() assumes that its argument is always valid.  Either main()'s behavior or getChangedPhrase()'s could be ok in isolation, but together they constitute a flaw producing undefined behavior under some circumstances.
Similarly, getChangedPhrase() returns NULL in some failure conditions, but main() pays no attention, assuming that the return value is a valid pointer, in attempting to print it.
Implementation improvement
If you have strdup() (which is standardized by POSIX, not C itself) then it is a convenient alternative to strlen() + malloc() + strcpy().
getChangedPhrase() calls fflush(stdout); before prompting for the encoding key.  This is useless.  Move the flush after the prompt, or remove it altogether.  Since the prompt ends with a newline, it is probably unnecessary to flush even after printing the prompt.
I remarked above on problems with your key handling.  I observe also that you handle your key inefficiently if it is short relative to the phrase to encode.  You shouldn't need to check on each pass through the key which characters are usable.  You shouldn't need to account for upper- vs. lowercase on each pass, either, if indeed you make them behave the same way.  Instead, process the key once, before the encoding loop: remove characters other than letters, and convert all the letters to a standard case.  Then it's also easy to validate result to ensure that there is at least one (or two, or whatever) key characters.
It doesn't make sense to me that your encoding code is not parallel for upper- and lowercase key characters.  The code for uppercase keys looks equally applicable to lowercase keys except the computation of pace, but you use a more complicated and difficult to follow scheme for lowercase key characters.  Indeed, one of the alternatives for lowercase keys cannot even be exercised, because code[j] < 90 and code[j] > 96 cannot be true at the same time.
Design improvement
Your function getChangedPhrase() modifies the input string in-place, but also returns a pointer to it.  On the other hand, the function's name suggests that it will create a new phrase.  I suggest changing that function's signature to
void encodePhrase(char *);

to clarify what it's doing.  If you wish to have the ability to signal an error, then you could consider using an int return value to signal the status, following the model of many standard library functions.


Passing listener to customized extended View in Android I extended NumberPicker with several methods needed in my application. When I came to defining a OnValueChangeListener this is how I did it:

import android.widget.NumberPicker;

interface ValueChangeCallback {
    public void execute(RemListView list, int oldVal, int newVal);
}

public class RemListView extends NumberPicker  {
    ValueChangeCallback mValueChangeCallback;
    RemListView thisList = this;

    public void setValueChangeCallback(ValueChangeCallback callback) {
        mValueChangeCallback = callback;

        setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                mValueChangeCallback.execute(thisList, oldVal, newVal);
            }
        });
    }
}

This code works fine but I'm new to Android and somehow I'm not sure I did it the proper way so I'm asking for a code review.

Do I have to save the callback in member variable?

I couldn't access this from within callback so I introduced thisList variable. Can it be avoided?

I think you have missed the point with the NumberPicker here. There is no need to add in a new level of abstraction for your application.

Right now your 'calling' code needs to implement a ValueChangeCallback class, and call setValueChangeCallback(callback). The ValueChangeCallback needs to implement the execute() method.

Sure, this works, but, the design is supposed to be a whole lot simpler, just do:

Make your calling code implement a NumberPicker.OnValueChangeListener and the onValueChange() method. Then, it can call setOnValueChangedListener directly.

Basically, your code should be simplified to:

import android.widget.NumberPicker;

public class RemListView extends NumberPicker  {

}

and your calling class should be changed to have a NumberPicker.OnValueChangeListener instance instead of a ValueChangeCallback instance, and, well, that's it.

Oh, and since your RemListView class is now empty, unless you have other stuff in there, you may as well delete the class and use NumberPicker directly.


Game inventory system I've been trying to figure out the best way to create a inventory system in Python. I like the way this one works but what I was wondering was if there was a better way to write it.

inv = ['Sword','Armor']
item_values = {'Sword':['Sword',5,1,15,2],
               'Armor':['Armor',0,10,25,5]}
print('Name\tAtk\tArm\tLb\tVal')
print(item_values[inv[0]][0],'\t',item_values[inv[0]][1],'\t',item_values[inv[0]][2],'\t',item_values[inv[0]][3],'\t',item_values[inv[0]][4])
print(item_values[inv[1]][0],'\t',item_values[inv[1]][1],'\t',item_values[inv[1]][2],'\t',item_values[inv[1]][3],'\t',item_values[inv[1]][4])

The items and the inventory can be modelled intuitively with classes:

You can define an Item class that has attributes like name, weight, attack
You can define an Inventory class that has a collection of items, and knows how to print them

Something like this:

class Item(object):
    def __init__(self, name, attack, armor, weight, price):
        self.name = name
        self.attack = attack
        self.armor = armor
        self.weight = weight
        self.price = price

class Inventory(object):
    def __init__(self):
        self.items = {}

    def add_item(self, item):
        self.items[item.name] = item

    def print_items(self):
        print('\t'.join(['Name', 'Atk', 'Arm', 'Lb', 'Val']))
        for item in self.items.values():
            print('\t'.join([str(x) for x in [item.name, item.attack, item.armor, item.weight, item.price]]))

inventory = Inventory()
inventory.add_item(Item('Sword', 5, 1, 15, 2))
inventory.add_item(Item('Armor', 0, 10, 25, 5))
inventory.print_items()

UPDATE

Based on a suggestion by @jonrsharpe you could move the printing logic from print_items to the __str__ method:

def __str__(self):
    out = '\t'.join(['Name', 'Atk', 'Arm', 'Lb', 'Val'])
    for item in self.items.values():
        out += '\n' + '\t'.join([str(x) for x in [item.name, item.attack, item.armor, item.weight, item.price]])
    return out

This way, instead of inventory.print_items(), you can print the inventory more intuitively with print(inventory).


Implementation of glass filter for images This is exercise 3.1.39. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:

Write a program that takes the name of an image file as a command-line
argument and applies a glass filter: set each pixel p to the color of
a random neighboring pixel (whose pixel coordinates both differ from
p’s coordinates by at most 5).

Here is my program:
import java.awt.Color;

public class test
{
    public static int[] chooseRandomNeighbor(int i, int j)
    {
        int[] chosenNeighbor = new int[2];
        double r = Math.random();
        if      (r < 1.0/8.0)
        {
            chosenNeighbor[0] = i-1;
            chosenNeighbor[1] = j-1;
        }
        else if (r < 2.0/8.0)
        {
            chosenNeighbor[0] = i-1;
            chosenNeighbor[1] = j;
        }
        else if (r < 3.0/8.0)
        {
            chosenNeighbor[0] = i-1;
            chosenNeighbor[1] = j+1;
        }
        else if (r < 4.0/8.0)
        {
            chosenNeighbor[0] = i;
            chosenNeighbor[1] = j+1;
        }
        else if (r < 5.0/8.0)
        {
            chosenNeighbor[0] = i+1;
            chosenNeighbor[1] = j+1;
        }
        else if (r < 6.0/8.0)
        {
            chosenNeighbor[0] = i+1;
            chosenNeighbor[1] = j;
        }
        else if (r < 7.0/8.0)
        {
            chosenNeighbor[0] = i+1;
            chosenNeighbor[1] = j-1;
        }
        else if (r < 8.0/8.0)
        {
            chosenNeighbor[0] = i;
            chosenNeighbor[1] = j-1;
        }
        return chosenNeighbor;
    }
    public static Picture filter(Picture picture)
    {
        int width = picture.width();
        int height = picture.height();
        Picture filteredPicture = new Picture(width,height);
        // the following four for-loops make the dead frame
        for (int row = 0; row < height; row++)
        {
            Color color = picture.get(0,row);
            filteredPicture.set(0,row,color);
        }
        for (int row = 0; row < height; row++)
        {
            Color color = picture.get(width-1,row);
            filteredPicture.set(width-1,row,color);
        }
        for (int col = 0; col < width; col++)
        {
            Color color = picture.get(col,0);
            filteredPicture.set(col,0,color);
        }
        for (int col = 0; col < width; col++)
        {
            Color color = picture.get(col,height-1);
            filteredPicture.set(col,height-1,color);
        }
        // the real filtering takes place here
        for (int col = 1; col < width-1; col++)
        {
            for (int row = 1; row < height-1; row++)
            {
                int[] chosenNeighbor = chooseRandomNeighbor(row,col);
                Color color = picture.get(chosenNeighbor[1],chosenNeighbor[0]);
                filteredPicture.set(col,row,color);
            }
        }
        return filteredPicture;
    }
    public static void main(String[] args)
    {
        Picture picture = new Picture(args[0]);
        Picture filteredPicture = filter(filter(filter(filter(picture))));
        filteredPicture.show();
    }
}

Picture is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it:
Input (picture of James McAvoy taken from Wikipedia who played in the movie Glass):

Output:

Is there any way that I can improve my program?
Thanks for your attention.

Interesting exercise and nice implementation, few suggestions on my side:

The method chooseRandomNeighbor is only used by filter, so it can be set to private
The name filter is too general for a method, a better name might be applyGlassFilter
In Java the name of a class starts with a capital letter

Optimization

random neighboring pixel (whose pixel coordinates both differ from p’s
coordinates by at most 5).

The method chooseRandomNeighbor picks an adjacent random neighbor (which differ by at most 1) and then gets called 4 times. That implies creating 4 full images in memory. Wouldn't be better to directly pick a neighbor with maximum distance 5?
To do that the method chooseRandomNeighbor needs to accept the width or height:
int neighborColIndex = chooseRandomNeighbor(col,width);
int neighborRowIndex = chooseRandomNeighbor(row,height);

And this is chooseRandomNeighbor refactored:
private static int chooseRandomNeighbor(int index, int max) {
    // Random delta between -5 and +5
    int randomDelta = (int) ((Math.random() * (10)) - 5);
    // Add delta to index without overflowing the limit
    int neighborIndex = (index + randomDelta) % max;
    // If index is negative return 0
    return neighborIndex < 0 ? 0 : neighborIndex;
}

Now the method filter can be called only once and only the new image will be created in memory.
Side note: you are getting better and better, keep up the good work!
Code Refactored
public class Test {

    public static Picture applyGlassFilter(Picture inputPicture) {
        int width = inputPicture.width();
        int height = inputPicture.height();
        Picture outputPicture = new Picture(width, height);
        for (int col = 0; col < width; col++) {
            for (int row = 0; row < height; row++) {
                int neighborColIndex = chooseRandomNeighbor(col,width);
                int neighborRowIndex = chooseRandomNeighbor(row,height);
                Color c = inputPicture.get(neighborColIndex,neighborRowIndex);
                outputPicture.set(col, row, c);
            }
        }
        return outputPicture;
    }

    private static int chooseRandomNeighbor(int index, int max) {
        // Random delta between -5 and +5
        int randomDelta = (int) ((Math.random() * (10)) - 5);
        // Add delta to index without overflowing the limit
        int neighborIndex = (index + randomDelta) % max;
        // If index is negative return 0
        return neighborIndex < 0 ? 0 : neighborIndex;
    }

    public static void main(String[] args) {
        Picture inputPicture = new Picture(args[0]);
        Picture outputPicture = applyGlassFilter(inputPicture);
        outputPicture.show();
    }
}


Sanitisation function: any holes? I've come up with this small function to make user submitted strings safe for MySQL. I'd be grateful if someone could point out any security holes in this. I've tested it out, and it happily replaces quotes and the like. The only issue I can see is the lack of escaping ampersands, but this shouldn't matter right?

$keywords = array("delete from", "drop table", ";", "=");
$safeKeywords = array("delete&nbsp;from", "drop&nbsp;table", "&#59;", "&#61;");

function dbSanitise($field)
{
    global $keywords, $safeKeywords;

    $sanitised = str_ireplace($keywords, $safeKeywords, $field);
    $sanitised = htmlentities($sanitised, ENT_QUOTES);
    $sanitised = mysql_real_escape_string($sanitised);

    return $sanitised;
}

Putting this string into the function above:

Hello world delete from DELETE FROM ; = " ' ''

Yields this:

Hello world delete&amp;nbsp&amp;#59;from delete&amp;nbsp&amp;#59;from &amp;#59; &amp;#61; &quot; &#039; &#039;&#039;

Which I can only see as being perfectly acceptable for a MySQL insert operation.

If I'm wrong, do let me know! Thanks for any help.

You shouldn't try to think of all the bad things that could be in the query, you'll never think of them all.

As it stands, your replacement is useless (as some of your commentors have noted). You can have any text you want inside of the string, its characters which might cause the string to be escaped which are a problem.

mysql_real_escape_string does everything you need. You don't need to implement your own function. Better yet use prepared statements.


Solve quadratic equation in standard form The first code I ever wrote, sorry that the prints are in German.
I tried to do some code improvements myself but well whenever I do I fail.
Hopefully somebody can help me improve my coding skills.

while True:
    print(" ")
    print("ax^2+bx+c ausrechen UwU, Bitte Achte!!! Bei Kommazahlen . benutzen, nicht , Beispiel: 0.5 0.7 1.6")
    import time

    print("Auf ein Neues?")

    U1 = input("input a ")
    I1 = input("input b ")
    O1 = input("input c ")
    if (U1.isalpha() or I1.isalpha() or O1.isalpha()) is False:
        print("doing some math")
        a = float(U1)
        b = float(I1)
        c = float(O1)
        if ((b * b) - (4 * a * c)) > 0:
            q = float(((b * b) - (4 * a * c)) ** (1 / 2))
            x = float(2 * a)
            y = float(-1 * b)
            z = float(q * (-1))
            result1 = str((y + q) / x)
            result2 = str((y + z) / x)

            print("Nullstelle1=" " " + result1 + "")
            print("Nullstelle2=" " " + result2 + "")

            abc = float((-1 * b) / (2 * a))
            Moo = float((4 * a * c) - (b ** 2)) / (4 * a)

            cba = str(abc)
            oom = str(Moo)

            print("Scheitelpunkt: (" + cba + "|" + oom + ")")

            if (a > 0) is True:
                print("Nach oben geöffnete Funktion")
                print("Schnittpunkt mit der Y-Achse ist" " " + O1 + " ")

            else:
                print("Nach unten geöffnete Funktion")
                print("Schnittpunkt mit der Y-Achse ist" " " + O1 + " ")

        else:
            print("sorry, geht nicht da eine negative zahl unter der wurzel sein würde")
            time.sleep(3)
    else:
        print("nur Zahlen bitte")

welcome to code review!

The first thing I want to do, is to put the code into a function. This separates it from anything else you might run, and allows you more control. I've used the name quadratic_solver and instead of taking input(), it now takes three arguments which are the coefficients. I've also added a docstring which briefly explains the function's purpose.

My German's not very good so I've just left your comments in; apologies if they're now incorrect. As per PEP8 (python's style guide), I've put your import before the function at the start of the file.

import time

def quadratic_solver(a, b, c):
    """
    Solves quadratic equations of the form ax**2 + bx + c
    """

    print("ax^2+bx+c ausrechen UwU, Bitte Achte!!! Bei Kommazahlen . benutzen, nicht , Beispiel: 0.5 0.7 1.6")

...

Now, if you want to check the type of your arguments you can do a simple:

type(val) is int or type(val) is str for example.

To loop over several values we can use a generator. Here, we loop over all values in a list [a, b, c] and ensure they are NOT all ints:

if not all(type(coeff) is int for coeff in [a, b, c]):

I'm not 100% sure why you're checking the type but perhaps your inputs are delicate in some way.

The rest of the code is fairly unchanged. I have however removed a lot of the casting to floats and strings.

If you want to concatenate strings with variables, you can use an fstring. This is of the form:

print(f"Nullstelle1= {result1}")

Where any variables are given in {} and an f at the start of the string denotes to put the variable inside the string as a string.

fstrings can also contain code, so I've used a ternary operator instead of your if else statement:

print(f"Nach {'oben' if a > 0 else 'unten'} geöffnete Funktion")

I've eliminated a few extra variables and brackets too, just for neatness. I'd recommend changing your variable names perhaps to something clearer, and adding a few comments to show what's going on.

Putting this all together, we get:

import time

def quadratic_solver(a, b, c):
    """
    Solves quadratic equations of the form ax**2 + bx + c
    """

    print("ax^2+bx+c ausrechen UwU, Bitte Achte!!! Bei Kommazahlen . benutzen, nicht , Beispiel: 0.5 0.7 1.6")

    if not all(type(val) is int for val in [a, b, c]):
        print("doing some math")

        numer = b * b - 4 * a * c
        if numer > 0:
            q = numer ** (1 / 2)

            result1 = (-b + q) / (2 * a)
            result2 = (-b - q) / (2 * a)

            print(f"Nullstelle1= {result1}")
            print(f"Nullstelle2= {result2}")

            abc = -b / (2 * a)
            moo = (4 * a * c - b ** 2) / (4 * a)

            print(f"Scheitelpunkt: ({abc}|{moo})")

            print(f"Nach {'oben' if a > 0 else 'unten'} geöffnete Funktion")
            print(f"Schnittpunkt mit der Y-Achse ist {c}")

        else:
            print("sorry, geht nicht da eine negative zahl unter der wurzel sein würde")
            time.sleep(3)
    else:
        print("nur Zahlen bitte")

Finally, to call your function, you can now put the following:

if __name__ == '__main__':
    quadratic_solver(1.0, 2.0, 3.0)

Wrapping the function in the if __name__ == '__main__': ensures the function is being run from the right place and not externally. 1.0, 2.0 and 3.0 are just some example coefficients.

I would also consider removing the time.sleep(3); what is it for?

EDIT:

For the type checking, per @AlexV's comment, if you're checking an input is of a valid type, it's better to check it IS that type, rather than ISN'T another type. So the condition would actually become:

if all(type(coeff) is float for coeff in [a, b, c]):

You could even use Python's new type hinting if you like:

def quadratic_solver(a: float, b: float, c: float):
    ...

```


UltimateTicTacToe - ActionScript Style! In an effort to complete this month's code challenge, I've started off with the basics. Below I have for review, a class that I can call to create the square/button a user would click to mark a spot on a Tic Tac Toe board. I haven't done any game logic, so I could very easily be forgetting something my buttons need to have.

Would this package stand up to any future additions?
How is my objected orientation here?
Is there anything I can do to compact it?
Am I following common practices?

package
{

    import flash.display.MovieClip;
    import flash.events.MouseEvent;

    public class SquareSpace extends MovieClip
    {

        public static const SQUARE_LENGTH:int = 30;
        public static const PLAYER_A_OWNED_SQUARE:int = 0;
        public static const PLAYER_B_OWNED_SQUARE:int = 1;
        public static const NEUTRAL_SQUARE:int = 2;
        public static const AVAILABLE_SQUARE:int = 3;
        public static const STATE_COLORS:Array = [0xFF3333,0x3333FF,0xDDDDDD,0x33FF33];

        private var _state:int = AVAILABLE_SQUARE;
        private var _square:MovieClip;

        public function SquareSpace(boxX:int, boxY:int)
        {
            _square = formSquare();
            _square.x = boxX;
            _square.y = boxY;
            _square.buttonMode = true;
        }

        public function addSquare():MovieClip
        {
            _square.addEventListener(MouseEvent.CLICK, sendClick);
            return _square;
        }

        private function sendClick(event:MouseEvent):void
        {
            dispatchEvent(new MouseEvent(MouseEvent.CLICK));
        }

        public function changeSquareState(sqrState:int):void
        {
            if (sqrState >= PLAYER_A_OWNED_SQUARE && sqrState <= AVAILABLE_SQUARE) {
                _state = sqrState;
                _square.graphics.beginFill(STATE_COLORS[sqrState]);
                _square.graphics.drawRect(0,0,SQUARE_LENGTH,SQUARE_LENGTH);
                _square.graphics.endFill();
            } else {
                throw new ArgumentError('State not acceptable.');
            }
        }

        public function getState():int
        {
            return _state;
        }

        private function formSquare():MovieClip
        {
            var mvclp:MovieClip = new MovieClip();
            mvclp.graphics.beginFill(STATE_COLORS[NEUTRAL_SQUARE]);
            mvclp.graphics.drawRect(0,0,SQUARE_LENGTH,SQUARE_LENGTH);
            mvclp.graphics.endFill();
            return mvclp;
        }
    }
}

Here is some calling code. I dispatch that click event (sendClick()) so my actual SquareSpace variable can handle clicks, rather than having the event listeners for the movieclip square outside of the class.

private function setUpBlankSubBoard (xOffset:int, yOffset:int, topBoard:int):void
        {
            for (var boxIndX:int = 1; boxIndX <= BOARD_LENGTH; boxIndX++) {
                for (var boxIndY:int = 1; boxIndY <= BOARD_LENGTH; boxIndY++) {
                    var newSqr:SquareSpace = new SquareSpace(
                     xOffset + (SquareSpace.SQUARE_LENGTH * 1.2) * boxIndX,
                     yOffset + (SquareSpace.SQUARE_LENGTH * 1.2) * boxIndY);
                    newSqr.addEventListener (MouseEvent.CLICK, squareChosen); // Called an unrelated function
                    addChild (newSqr.addSquare());
                }
            }
        }

Overall this is looking pretty. I do have a few questions and suggestions based on what I see.

Constructor
Your class extends MovieClip therefore it IS a Movieclip. What is the purpose of the inner _square class variable? Is SquareSpace meant to be purely a logic controller class with _square being the visual representation of the square? If so there is no need for SquareSpace to extend MovieClip. I would look at EventDispatcher or just plain Object.
addSquare/sendClick
I'm not sure I'm understanding the purpose of these methods. Can you explain your thought behind them?
changeSquareState
For state control/detection you generally want to use a switch statement. That way adding more states in the future is much easier.
The State Constants
This is more of a cosmetic comment but I usually prepend any constants with the word STATE_ so that you/other developers can easily tell that those are values intended to be used for state control and passed into changeSquareState.
Argument Error
A really minor comment but I like to include the state which is not acceptable in the error statement. Makes debugging in the future easier. Not a big deal though.
Future Design
As you build out this game do you plan on using the Flash timeline to position and configure your assets or are you going pure AS3?
Package
Generally you want to organize each of your classes into a package. If you're not using a proper IDE like FlashBuilder, FlashDevelop, or FDT this will be a bit of a pain but it's good practice none the less. Packages generally look like reversed domain names so for example your SquareSpace class might be in the following package com.alex.ultimatetictactoe.square


User agent classification using switch (true) I've seen usage of switch(true) multiple times and have used it myself today instead of multiple elseif`s. Here is the case I used it for:

var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') != -1;
var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') != -1;
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') != -1;
var browser = null;
switch (true) {
    case isChrome:
        {
            browser = "chrome";
            break;
        }
    case isSafari:
        {
            browser = "safari";
            break;
        }
    case isFirefox:
        {
            browser = "firefox";
            break;
        }
}

My view is that much more explicit than multiple else ifs. Do you think it's a good approach?

Assuming that you bad a bunch of boolean variables already defined, I think a chained ternary conditional expression would be even better, because it's more compact, and also emphasizes that the goal is to assigning something to browser.

var browser = isChrome ? "chrome" :
              isSafari ? "safari" :
              isFirefox ? "firefox" :
              null;

Also consider defining a userAgentContains(…) function to reduce redundancy.


Demonstration of Pentagonal Number Challenge

  Using the C++ language, have the function PentagonalNumber(num) read num which will be a positive integer and determine how many dots exist in a pentagonal shape around a center dot on the Nth iteration. For example, in the image below you can see that on the first iteration there is only a single dot, on the second iteration there are 6 dots, on the third there are 16 dots, and on the fourth there are 31 dots.

  Your program should return the number of dots that exist in the whole pentagon on the Nth iteration.

  Sample Test Cases

Input:2
Output:6

Input:5
Output:51

I found it weird that Coderbyte called this a hard challenge. It works, but is this the right approach?

Header File

#ifndef PentagonalNum_hpp
#define PentagonalNum_hpp

#include <stdio.h>

class PentagonalNum
{
public:
    PentagonalNum(int N);
    unsigned long long int num_Of_Dots();
private:
    int iteration;
};
#endif /* PentagonalNum_hpp */

CPP File

#include "PentagonalNum.hpp"

PentagonalNum::PentagonalNum(int N)
: iteration(N)
{
}

unsigned long long int PentagonalNum::num_Of_Dots()
{
    int result = 1;
    int num = 5;

    for (int i = 1; i < iteration; ++i)
    {
        result += num;
        num += 5;
    }
    return result;
}

It seems a little peculiar to use a class to solve this problem. It's not like there's any need to maintain state. All you're doing, in the end, is making it more difficult to use - instead of:

auto result = pentagonal_number(n);

you have to write:

auto pentagonal_number = PentagonalNum{n};
auto result = num_Of_Dots();

or:

auto result = PentagonalNum{n}.num_Of_Dots();

You could throw out the whole class and just keep the num_Of_Dots() member function, let it take iteration as a parameter, and you'd be done. It would be much easier to use, too.

As for the code itself:

#include <stdio.h>

This is not valid in C++ anymore (though it used to be). You need <cstdio>, or better yet, use actual C++ I/O.

unsigned long long int PentagonalNum::num_Of_Dots()
{
    int result = 1;
    int num = 5;

    for (int i = 1; i < iteration; ++i)
    {
        result += num;
        num += 5;
    }
    return result;
}

It seems like this function can be both noexcept and constexpr (and, if it's going to be a class member, also const). Note that the function requires iteration to be greater than or equal to 1; if you're not checking that here so the function can be noexcept, then you should check it in the constructor.

The big question I have is why result is only an int if you intend to return a unsigned long long. Seems a bit of a waste of all that integer range.

You use some magic numbers and variables with mysterious names (num?). Your code would be clearer and easier to understand with more explicit variable names, like:

constexpr unsigned long long int PentagonalNum(int iteration)
{
    // might want to assert that iteration >= 1

    constexpr auto NUMBER_OF_SIDES = 5uLL;

    auto result = 1uLL; // start with 1 point
    auto points_to_add_on_next_iteration = NUMBER_OF_SIDES;

    for (auto i = 1; i < iteration; ++i)
    {
        result += points_to_add_on_next_iteration;
        points_to_add_on_next_iteration += NUMBER_OF_SIDES;
    }

    return result;
}

As an aside, I suspect the reason this challenge was marked as "hard" is because you are supposed to try and solve it without iterating. In other words, you are supposed to stop and think about the problem and derive an equation for the number of dots at iteration n, rather than just charging in and doing an iterative solution.


Binary converter and sufficient tests I just finished writing a basic binary conversion class in Ruby. I'm curious to see if anyone has suggestions for improvements. In particular, I'm looking for the cleanest, shortest, most succinct code possible, while staying away from hacky shortcut stuff.

In creating this I wanted to use a minimum of functions that come with Ruby by default, as that would sort of defeat the purpose of this as a practice program. For instance, the entire thing could have been summed up with a quick line like this.

"101".to_i(2) ##> 5

But I wanted to do most of the math by hand, so to speak.

There is one place in the get_bits method I did use a string, and I'm not too happy about it. However it was the only way I could think of to get the bits into an array. If there's another way to do so without splitting a string, I'd be glad to hear it.

Here's the class.

class Converter
  def initialize binary_number
    @binary = binary_number
    @bits = get_bits
    @total = 0
    self
  end

  def to_base_ten
    validate_binary
    @bits.reverse.each_with_index do |bit, power|
      append_to_total bit_value(bit, power)
    end
    get_total
  end

  private
  def get_bits
    @binary.to_s.split('').map do |bit|
      bit.to_i
    end
  end

  def validate_binary
    @bits.each do |bit|
      raise "Invalid binary!" unless bit == 0 || bit == 1
    end
  end

  def bit_value bit, power
    is_set?(bit) ? two_to_power_of(power) : 0
  end

  def two_to_power_of power
    total = 1
    power.times do
      total = total * 2
    end
    total
  end

  def is_set? bit
    bit == 1
  end

  def append_to_total amount
    @total = @total + amount
  end

  def get_total
    @total
  end
end

I also used RSpec to test it as best I could, but I won't post the specs here, just because they're long and not directly related to the class itself. If you want to inspect those too, they can be found on GitHub.

So there ya have it. Any thoughts are greatly appreciated. Clean code forever!

The name Converter is pretty ambiguous. It could mean anything.
I'd suggest doing less work in the initializer, and more lazy evaluation.
Skip that self line in the initializer - it's an initializer; it'll always return self (or, technically, it doesn't matter what the initializer returns, since you'll be calling new and that will return the new instance. Point is, skip that line)
Use Enumerable#inject to do the sum
Use String#chars instead of String#split
It'd probably be better to raise right away in the initializer if the string isn't a binary number. Also better to raise an ArgumentError while you're at it.
You can check the string with a simple regular expression: /^[01]*$/
Your #two_to_power_of method can be replaced with 2 ** n
Don't use prefixes like is_ and get_ in your method names (specifically, is_set?, get_bits and get_total); it's not Ruby's style. For instance, the nil? method isn't called is_nil?, and the chars method mentioned above isn't called get_chars.
All methods return something so a get_ is redundant, and a ? suffix is a substitute for an is_ prefix, just like a = suffix is a substitute for a set_ prefix.
Favor accessor methods over directly accessing instance variables. Such indirections allow for better internal decoupling. That is, as soon as you start accessing a value through a method, you make your class more flexible. You can begin with simple attr_reader-synthesized methods, which will of course not do anything special, but should you ever need or want to  add more logic, you need only change the accessor method(s). In this case, however, a first step would be to simply use fewer instance variables (see #2)
A class method might be nice for quick conversions, so you don't always have to deal with instantiating an object. E.g. a class method could allow you to say Converter.convert("101010") and get 42 directly. It'd just be a shortcut for Converter.new("101010").to_base_ten, but that's still a nice shortcut to have.
Might be nice if you could specify endianness of the binary number, instead of assuming it's always little endian.

In the end, I get something like this, if we want memoization of the converted values:

class BinaryNumberConverter
  attr_reader :binary

  def self.convert(string, little_endian = true)
    self.new(string).base_ten(little_endian)
  end

  def initialize(binary)
    if binary =~ /^[01]*$/
      @binary = binary
    else
      raise ArgumentError.new("'#{binary}' is not a valid binary number")
    end
  end

  def base_ten(little_endian = true)
    little_endian ? little_endian_value : big_endian_value
  end

  private

  def little_endian_value
    @little_endian ||= convert(binary.reverse)
  end

  def big_endian_value
    @big_endian ||= convert(binary)
  end

  def convert(string)
    string.chars.each_with_index.inject(0) do |sum, digit|
      char, index = digit
      sum += char == "1" ? 2 ** index : 0
    end
  end
end

Usage:

instance = BinaryNumberConverter.new("101010")
instance.base_ten        # => 42
instance.base_ten(false) # => 21

BinaryNumberConverter.convert("101010")        # => 42
BinaryNumberConverter.convert("101010", false) # => 21

Of course, it'd be a lot simpler to just extend String rather than make an entire class:

class String
  def bin_to_dec(little_endian = true)
    raise "'#{self}' is not a valid binary number" unless self =~ /^[01]*$/
    digits = little_endian ? reverse.chars : chars
    digits.each_with_index.inject(0) do |sum, digit|
      char, index = digit
      sum += char == "1" ? 2 ** index : 0
    end
  end
end

And you get

"101010".bin_to_dec        #=> 42
"101010".bin_to_dec(false) #=> 21

No memoization, but I'd call that pretty clean.

Took a quick look at your tests, and it's a bit overkill (also, you should use the expect syntax of rspec; the should syntax is old-school).

I'd actually just do something like

number = rand(12345) # can be anything really
string = number.to_s(2)
expect(string.bin_to_dec).to eq(number)

And call it good. You'll note I'm using to_s(2) above, but here it makes sense. We have to assume that Ruby works anyway, so in this case, it's a perfect yardstick. Similarly, to check big endian conversion, we can use to_i(2) with a clear conscience

string = rand(12345).to_s(2).reverse
expect(string.bin_to_dec(false)).to eq(string.to_i(2))

Add a test for the exception raising, and you've tested everything.

On another note, you say you "wanted to use a minimum of functions that come with Ruby by default as that would sort of defeat the purpose of this as a practice program". But I'd recommend you use as much built-in functionality as possible, especially in your practice programs (in this case stopping short of using String#to_i, of course).

Learning any language is usually less about learning the language itself (as in syntax), as it is about learning the conventions, idioms, and the built-in goodies. Intentionally doing things "the hard way" will probably teach you the wrong lessons. And the code you write won't teach you conventions and idioms, because it's unconventional to make things hard for yourself and no idioms exist for it.

Besides, at first, the easy solution will actually be the difficult one, because the easy solution is the one that requires experience. But brute-forcing your way though a problem won't earn you that experience and will actually teach you a lot less than trying to use the language to your advantage.