Taking advantage of the falsey and ineffective "" empty string The following code snippets are academic. I was required to make a PHP generated HTML interface for a MySQL database of a movie rental store, and the requirement was filtering the displayed movies by category.

The approach for having the filter persist across all form actions (without using a session) was to have the hidden form input inserted into all the other forms on the page.  And my first approach to this was testing if $_POST['category'] is set, and if so echoing the HTML tag for the hidden input to carry the category variable to the next page.

This was still the method, but, I tinkered with it and decided that instead of testing if a category was selected at every form I could test once, and if not leave the string variable for the HTML tag empty and echo it regardless.

This worked nicely but I'm curious if if in a larger/co-operative project if the possible confusion for the outputting of a variable that is sometimes empty (i.e. ineffectual) and sometimes not will be more confusing than the lines of code and processing time saved.

<?php
$categorySelected = '';
$hiddenCategory = '';

////....................
//conect to databes
//create mysqli object

if( isset($_POST['category']) &&  $_POST['category'] != $Allcats ){
  //<check that catagory still has entries>

  //if there are entries for category filter, set local variable, and html tag for form input
  //hidden input tag is inserted to all forms to carry category selection to next page reload
  if(<videos of that category exist>){
    $categorySelected = $_POST['category'];
    $hiddenCategory = "<input type='hidden' name='category' value='$categorySelected'>";
  } //else //<display message that there are no videos of that category>

}

//database manipulations completed
//html header

//in all forms in html $hiddenCategory is echod
//to add category k/v pair to post
//or '' is echoed with no consequence if category not set
?>
<form id='addvideo' action = <?php echo $SELF; ?> method ='post'>
    <?php echo $hiddenCategory; ?>
    <input type='hidden' name='ACTION' value='addvideo'>
    <input type="submit" value="ADD VIDEO">
    Name:<input type="text" name="name">
    <!--  more fields.... -->
</form>

<?php
//prepare statement for all entries of category filtered
if(!$categorySelected){
  $vidStmt = $mysqli->prepare("SELECT * FROM records");
}else{
  $vidStmt = $mysqli->prepare("SELECT * FROM records WHERE category=?");
  $vidStmt->bind_param("s",$categorySelected);
}

//iterate over all videos in database query, creating <tr> for each
while($vidStmt->fetch()){
echo "<tr>
<td> $name <td> $category <td> $length <td>
<form class='rent' action = $SELF method ='post'>
  $hiddenCategory
  <input type='hidden' name='ACTION' value='rent'>
  .... more fields ..
</form>
";
}
$vidStmt->close();
?>

I wouldn't do it this way, because it does seem confusing. And not just because you are using truthiness (which I really wouldn't do, because it's hard to understand and just screams for bugs). It takes a while to see what happens when there is no POST value, what happens if a categories doesn't exist, etc.

You don't need multiple checks either though, just move all the code that belongs to category-doesnt-exists and category-exists into one block. If you also extract some code to functions, your code might look something like this:

if(!isset($_POST['category']) ||  $_POST['category'] == $Allcats ){
    displayAddForm("", $SELF);
    displayRentForm("", getAll());
} else if (<videos of that category doesnt exist>) {
    // message that video doesn't exist
    displayAddForm("", $SELF);
    displayRentForm("", getAll());
} else {
    $categorySelected = $_POST['category'];
    $hiddenCategory = "<input type='hidden' name='category' value='htmlspecialchars($categorySelected, ENT_QUOTES, 'UTF-8') '>";
    displayAddForm($hiddenCategory, $SELF);
    displayRentForm($hiddenCategory, getByCategoryId($categorySelected));
}

function getAll() {
    $mysqli->prepare("SELECT * FROM records");
    // return array of results
}

function getByCategoryId($id) {
    $vidStmt = $mysqli->prepare("SELECT * FROM records WHERE category=?");
    $vidStmt->bind_param("s",$categorySelected);
    // return array of results
}

function displayRentForm($hiddenCategory, $categories) {
    foreach($categories as $category){
        echo "<tr>
        <td> htmlspecialchars($name, ENT_QUOTES, 'UTF-8') $name <td> htmlspecialchars($category, ENT_QUOTES, 'UTF-8')  <td> htmlspecialchars($length, ENT_QUOTES, 'UTF-8')  <td>
        <form class='rent' action = htmlspecialchars($SELF, ENT_QUOTES, 'UTF-8')  method ='post'>
          $hiddenCategory
          <input type='hidden' name='ACTION' value='rent'>
          .... more fields ..
        </form>
        ";
    }
}

function displayAddForm($hiddenCategory, $SELF) {
    echo "<form id='addvideo' action = <?php echo htmlspecialchars($SELF, ENT_QUOTES, 'UTF-8') ; ?> method ='post'>" .
        $hiddenCategory .
        "<input type='hidden' name='ACTION' value='addvideo'>
        <input type="submit" value="ADD VIDEO">
        Name:<input type="text" name="name">
        <!--  more fields.... -->
    </form>";
}

It's not perfect, but I you get the idea.

XSS

You shouldn't write vulnerable code, even for academic work. It's bad practice, and it normalizes unsecure code; you get used to writing it, and other people get used to reading it.

Always protect against XSS when echoing variable data, eg:

$hiddenCategory = "<input type='hidden' name='category' value='" . htmlspecialchars($categorySelected, ENT_QUOTES, 'UTF-8') . "'>";

And

<form id='addvideo' action = '<?php echo htmlspecialchars($SELF, ENT_QUOTES, 'UTF-8'); ?>' method ='post'>

Misc

Don't mix " and ' so much. Something like <input type='hidden' name='ACTION' value='addvideo'><input type="submit" value="ADD VIDEO"> is hard to read, and harder to change than uniformly quoted code (you can see this in my code example above, where I didn't bother to correct it).
Your indentation is off, making your code harder to read.


'join' MongodDB collections with a for loop This is a very simplified version of my query. Is it acceptable to join the two collections for the client with the use of for loops?

There could be up to 2,000 books, which also means there could be an equal number of favorite books per user in the favoriteBooksCollection.

return favoriteBooksCollection
.find({user: current_userId})
.then(function(favorites){

    var bookIds = favorites.map(function (a) {
        return a.bookId
    };

    return BooksCollection
    .find({_id : {$in: bookIds}})
    .sort({timestamp: -1})
    .then(function(books){

     for(var i = 0; i < books.length; i++){
        for(var j = 0; j < favorites.length; j++){
          if(favorites[j].bookId  == books[i]._id){

           //'join' user's myRating to book document here
            books[i].userRating = favorites[j].myRating;

           };
        };
    };

      // return books array of objects with newly added UserRating property
      return books;

    });

});

The nested loops perform books.length * favorites.length iterations (up to 4 million).

Instead build a dictionary of id -> rating, so total iterations max is a sum of lengths.

var favRatings = {}, i, len;

for (i = 0, len = favorites.length; i < len; i++) {
    var fav = favorites[i];
    favRatings[fav.bookId] = fav.myRating;
}

for (i = 0, len = books.length; i < len; i++) {
    var book = books[i];
    var rating = favRatings[book._id];
    if (rating !== undefined) {
        book.userRating = rating;
    }
}


Efficiency of a recursive implementation of the Sieve of Erasthotenes in Python I implemented the Sieve of Erasthotenes recursively using filter and I was wondering how efficient this implementation is and wether a non-recursive implementation or something without filter would be better. If someone wants to get into micro-optimization etc. - that would be fun too I suppose :)

This is my code:

def sieve (iterable, container):
    if len(iterable) != 1:
        container.append(iterable [0])
        iterable = [item for item in iterable if item % iterable [0] != 0]
        print("Filter call:", iterable, container, '\n')
        return sieve(iterable, container)
    else:
        container.append(iterable[0])
        print("Return container:", container)
        return container

An example I/O (with the print-Statements) would be:

#Input
lst = list(range(2, 20))
primes = []

print(sieve(lst, primes)

#Output
Filter call: [3, 5, 7, 9, 11, 13, 15, 17, 19] [2]

Filter call: [5, 7, 11, 13, 17, 19] [2, 3]

Filter call: [7, 11, 13, 17, 19] [2, 3, 5]

Filter call: [11, 13, 17, 19] [2, 3, 5, 7]

Filter call: [13, 17, 19] [2, 3, 5, 7, 11]

Filter call: [17, 19] [2, 3, 5, 7, 11, 13]

Filter call: [19] [2, 3, 5, 7, 11, 13, 17]

Return container: [2, 3, 5, 7, 11, 13, 17, 19]

#Return
Out: [2, 3, 5, 7, 11, 13, 17, 19]

Algorithm

This is not quite the Sieve of Eratosthenes. The true sieve touches only the multiples of each prime, so it has complexity \$n \log \log n\$. Filtering copies the whole list repeatedly, which is equivalent to a different algorithm, trial division, with different complexity (probably \$n^2 / (\log n)^2\$). That's a dramatic difference, which led Melissa O'Neill to write a slightly famous academic rant about this.

But that's not a problem for an educational program. The rest of this review is about your implementation.

Recursing on each prime has depth \$\pi(n) \approx n / \log n\$, which will overflow the stack for any large \$n\$. Can you do it iteratively instead?

Names

iterable is a misleading name: the function uses len(iterable), but iterables don't necessarily support len. So it doesn't work on all iterables.

iterable is also an uninformative name: it doesn't say what the argument means. It isn't just any iterable, it's a list of candidate primes, so it could be called candidates.

Similarly, container isn't just any container, it's a list of primes, so it should be called primes. Also, sieve modifies it, which is unusual enough that it requires a comment, and it could even appear in the name: it could be called output_primes.

Interface

Modifying an argument is confusing and error-prone. Why not build a list and return it?

Why does the caller need to provide a list of candidates? Wouldn't it be simpler to just pass n and have sieve take care of building the candidates?

If the recursive function needs a different interface from the caller, you can use one function to do the recursion, and wrap it with another that presents a clean interface to the caller.

Innards

Repetition: container.append(iterable[0]) appears in both branches of the if. It could be moved before the if.

The program checks len(iterable) != 1, so what happens if len(iterable) == 0? Oops: it tries to use iterable[0] and crashes. It's generally safest to check for 0, not 1. This would also get rid of the repetition.

Optimization

Improving the algorithm will help a lot more than micro-optimizing. If you switch to the true Sieve of Eratosthenes and it still isn't fast enough, there are algorithmic improvements like the Sieve of Sundaram.

Before optimizing, measure performance! Optimization is hard and it's easy to get it wrong, so let measurements guide you.

Other

This function should have a docstring saying what it does: "Prime number sieve: Given a list of candidates, append the primes to output_primes."

Your question says the program uses filter, but it actually uses a list comprehension to do the same thing. This is not a problem with the program, just slightly confusing.


Writing an anagram efficiently I know this question has been asked before now but in Python. Recently, I set out to write an anagram in C#. For instance, orchestra can be rearranged into carthorse and the anagram should not have more repeated than the original. The function is meant to check if the two words are the same and return true in this case. I started with putting the two words in two separate dictionaries with the letters as a key and the count as value.

The idea is using a dictionary ensures the keys can not be repeated. Then I looped through the second dictionary (secondString) and checked if each letter existed as a key in the first dictionary (firstString). Additionally, if the letter existed, the code checks if they have the same count. The rest of the code is self-explanatory.

using System;
using System.Collections.Generic;

public class AreAnagrams
{
    public static bool AreStringsAnagrams(string a, string b)
    {
        Dictionary<char,int> firstString = new Dictionary<char,int>();
        Dictionary<char,int> secondString = new Dictionary<char,int>();

        foreach(char character in a)
        {
            if(firstString.ContainsKey(character)== true)
            {
                firstString[character]+=1;
            }
            else
                firstString[character]=1;
        }
        foreach(char character2 in b)
        {
            if(secondString.ContainsKey(character2)== true)
            {
                secondString[character2]+=1;
            }
            else
                secondString[character2]=1;
        }

        foreach(KeyValuePair<char,int> letterValue in secondString)
        {
            if(firstString.ContainsKey(letterValue.Key))
            {
                if(firstString[letterValue.Key] != secondString[letterValue.Key]){

                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        //throw new NotImplementedException("Waiting to be implemented.");
        return  true;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(AreStringsAnagrams("momdad", "dadmom"));
    }
}

But I scored 75% and I feel this can be improved on. Also, is there any easy conversion from string to dictionary?

I took your new code and cleaned it up a bit by

adjusting bracket location
removed unnecessary nesting of if statements
gave some operations some breathing room
fixed some odd indentations

I took your code

using System;
using System.Collections.Generic;

public class AreAnagrams
{
    public static bool AreStringsAnagrams(string a, string b)
    {
      Dictionary<char,int> firstString = new Dictionary<char,int>();
      Dictionary<char,int> secondString = new Dictionary<char,int>();

      foreach(char character in a)
      {
          if(firstString.ContainsKey(character))
          {
              firstString[character]+=1;
          }
          else{
              firstString[character]=1;
              }
      }

      foreach(char character2 in b)
      {
          if(secondString.ContainsKey(character2))
          {
              secondString[character2]+=1;
          }
          else{
              secondString[character2]=1;
              }
      }

      if(firstString.Count !=secondString.Count){
          return false;
      }
      else   {
              foreach(KeyValuePair<char,int> letterValue in secondString)
                  {
                      if(firstString.ContainsKey(letterValue.Key))
                      {
                          if(firstString[letterValue.Key] != secondString[letterValue.Key]){

                              return false;
                              }
                      }
                      else
                      {
                          return false;
                      }
                  }
              }
      return  true;
  }

  public static void Main(string[] args)
  {
      Console.WriteLine(AreStringsAnagrams("momdad", "dadmom"));
  }
}

and refactored it to this (there is an issue with the if then statement inside last for loop, which I address later)

public class AreAnagrams
{
    public static bool AreStringsAnagrams(string a, string b)
    {
        Dictionary<char,int> firstString = new Dictionary<char,int>();
        Dictionary<char,int> secondString = new Dictionary<char,int>();

        foreach(char character in a)
        {
            if(firstString.ContainsKey(character))
            {
                firstString[character] += 1;
            }
            else
            {
                firstString[character] = 1;
            }
        }

        foreach(char character2 in b)
        {
            if(secondString.ContainsKey(character2))
            {
                secondString[character2] += 1;
            }
            else
            {
                secondString[character2] = 1;
            }
        }

        if(firstString.Count != secondString.Count)
        {
            return false;
        }
        else
        {
            foreach(KeyValuePair<char,int> letterValue in secondString)
            {
                if(firstString.ContainsKey(letterValue.Key)
                    && (firstString[letterValue.Key] != secondString[letterValue.Key]))
                {
                    return false;
                }
                else
                {
                    return false;
                }
            }
        }
        return  true;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(AreStringsAnagrams("momdad", "dadmom"));
    }
}

I also decided to change this so that there are two separate if statements, this will reduce the O(n) in the optimistic case
(Your code cleaned up)

foreach(KeyValuePair<char,int> letterValue in secondString)
{
    if(firstString.ContainsKey(letterValue.Key))
    {
        if(firstString[letterValue.Key] != secondString[letterValue.Key]){
            return false;
        }
    }
    else
    {
        return false;
    }
}

New Code with less complexity

foreach(KeyValuePair<char,int> letterValue in secondString)
{
    if (!firstString.ContainsKey(letterValue.Key))
    {
        return false;
    }
    if (firstString[letterValue.Key] != secondString[letterValue.Key])
    {
        return false;
    }
}

You could merge these into a single if statement, but for the sake of reading I left them separate here.

If one doesn't contain the key of the other one, you want to return false, no need to check the other condition.

Another overall thing that you could do to reduce the O(n) is to evaluate if the strings are the same length, immediately and return false if they are not, because you already know they cannot be anagrams of each other.

like this

using System;
using System.Collections.Generic;

public class AreAnagrams
{
    public static bool AreStringsAnagrams(string a, string b)
    {
        if (a.Length != b.Length) {
            return false;
        }

        Dictionary<char,int> firstString = new Dictionary<char,int>();
        Dictionary<char,int> secondString = new Dictionary<char,int>();

       /// ...

then you can remove the check later in the code.

I did that, and also changed += 1 to ++ twice in your code.  I also made it case insensitive, but sentences will not work.

Here is the code that works, I tested with your example and with Joker and JReko

if (a.Length != b.Length)
{
    return false;
}

Dictionary<char, int> firstString = new Dictionary<char, int>();
Dictionary<char, int> secondString = new Dictionary<char, int>();

foreach (char character in a.ToLower())
{
    if (firstString.ContainsKey(character))
    {
        firstString[character]++;
    }
    else
    {
        firstString[character] = 1;
    }
}

foreach (char character2 in b.ToLower())
{
    if (secondString.ContainsKey(character2))
    {
        secondString[character2]++;
    }
    else
    {
        secondString[character2] = 1;
    }
}

foreach (KeyValuePair<char, int> letterValue in secondString)
{
    if (!firstString.ContainsKey(letterValue.Key)
        || (firstString[letterValue.Key] != secondString[letterValue.Key]))
    {
        return false;
    }
}

return true;


Meta-circular interpreter for lambda calculus in Haskell For learning purpose, I've written a simple lambda calculus interpreter (plus 'Add'). I would like it to be the cleanest and most idiomatic possible.

Bonus question: how would you use deriving (Show) for Val, just having to define show for Fun (Val -> Val)?

-- Lambda calculus interpreter example.

import qualified Data.Map.Lazy as Map

data Val = Num Integer | Fun (Val -> Val) | Wrong
data Term = Cons Integer | Var String | Lam String Term | App Term Term | Add Term Term
type Env = Map.Map String Val

add :: Val -> Val -> Val
add (Num x) (Num y) = Num (x+y)
add _ _ = Wrong

apply :: Val -> Val -> Val
apply (Fun f) v = f v
apply _ _ = Wrong

instance Show Val where
  show (Num x) = show x
  show (Fun f) = "function"
  show Wrong = "Wrong"

interp :: Term -> Env -> Val
interp (Cons x) e = Num x
interp (Var s) e = Map.findWithDefault Wrong s e -- Equivalent to:
-- interp (Var s) e = maybe Wrong id (Map.lookup s e)
interp (Lam s t) e = Fun (\v -> interp t (Map.insert s v e))
interp (App f t) e = apply (interp f e) (interp t e)
interp (Add a b) e = add (interp a e) (interp b e)

expr = App (Lam "x" (Add (Var "x") (Var "x"))) (Add (Cons 10) (Cons 11))
res = interp expr Map.empty

main = putStrLn (show res)

I wanted to give a more full answer, but I can't fully commit to it, so here are a few things:

Instead of having Wrong built into the result type, you would rather want Maybe Val, or better yet, Either String Val or Either Error val, since there are multiple possible causes for failure.
I'm a little skeptical about Fun (Val -> Val): This seems to serve two purposes:

The final result of interp could be a lambda.

Theoretically it must always be, but for a practical purpose, perhaps, you've decided that integers are different from functions. And that if one were to return a value that hasn't reduced to an integer, then rather produce a Haskell function that can resume evaluation later.

The drawback is that you can't further transform the structure hidden away in a Fun (Val -> Val) in the same way as you can with a Term; you can only reduce it further using interp. For example, you can only pretty-print the result if it's an integer, or a failure.
As an intermediate representation of a term being evaluated. But since any lambda reduction rule provides another term, Term should be an excellent intermediate representation.

When you express an intermediate state as Fun (Val -> Val), it also contains an implicit Env, which is in some sense a reader monad pattern. Typically you might represent this with Control.Monad.Reader instead.
I think keeping an Env might be neat - I've seen several examples of people building quite advanced lambda calculus interpreters that do this. But when I first thought how I'd make it myself, I thought of

interp (App (Lam x body) arg) = subst x body arg
interp (App (Var x) _arg) = Left ("Free variable " ++ show x)

since, if I encountered a Var x on the left-hand side of an application, I'd know that it hadn't been substituted by an outer reduction. But I'm not wise enough to say which is better here, that was just my first thought.
I'd rename Cons to Num or Int: Cons seems a bit contrived for constant, and Const is a bit vague, since you really mean integer constant. But what constant is there about a lambda term? I mean, theoretically it could also be a function if the interpreter allowed it.
If your intermediate representation was Term and not Val, and your interpreter was monadic (e.g. for handling errors) you could merge add into apply, since Add is just a special-case function application:

interp (App (Lam x body) arg) = subst x body arg
interp (App (Var x) _arg) = Left ("Free variable " ++ show x)
interp (Add e1 e2) = add <$> interp e1 <*> interp e2

add (Int m) (Int n) = return (Int (m + n))
add x y = Left ("Cannot add non-integers " ++ show x ++ " and " ++ show y)

Pretty-printing m and n here is possible because Term's structure is not hidden within a Haskell -> function.
You have two things that could be expressed in terms of monads: Making Env implicit using a reader monad, and handling errors using Either. This could be expressed as

type Env = Map Var Term
type Interpreter = Env -> Term -> Either String Term

or rather using Control.Monad.Trans.Reader:

type Env = Map Var Term
type Interpreter a = ReaderT Env (Either String) a

which is equivalent under the hood, but it means you can do stuff like:

interp (Add e1 e2) = add <$> interp e1 <*> interp e2

  I don't care about alpha renaming

I'm not sure how to interpret this, but the following thought comes to mind:

It is idiomatic to model your data type as close to the domain, so the fact that Lam "x" (Var "y") passes type-check but can not evaluate (unless there's some kind of initial environment that catches free variables) is a problem. One way to address this I've seen is e.g. de Bruijn indexing as performed e.g. by James Fisher which is one way to say that he also doesn't care about alpha renaming by never having the need. One could even convert freely between one interpretation with variables and another without, depending on which representation is most convenient for a given purpose.


Date range validator I have some code which works fine. First, it checks that dates format are valid and then, checks that first date is lower than second date. I had to use free input text and custom validator because multiple date formats are supported such as quarter number (2014 Q1) etc.

But I find my code too long for what it's doing. Any advice on code improvement ?

DEMO

function check_handler(){
var from = $('#zeDateFrom').val(), to = $('#zeDateTo').val();

if(adu_date_format(from) && adu_date_format(to)){
    if( check_date_period(from.trim(), to.trim()) ){
        alert('OK');
    }
    else alert('Start Date must be lower then End Date.');
}
else{
    alert('Please use a valid date format. For your information, valid formats are:\ndd/mm/yyyy  (e.g 11/12/2011)\n yyyy  (e.g 2010)\n mm/yyyy  (e.g 11/2009)\n and yyyy qq (e.g 2012 Q2).');
}

}

function check_date_period(from, to){
  var result = false;
  var yearFrom, yearTo, monthFrom, monthTo, dayFrom, dayTo;

  // 0) If something to compare...
  if(from==""||to=="") return true;

  // 1) Test if input is type year only
  if(from.length==4){
      yearFrom = from; monthFrom = 1; dayFrom = 1;
  }
  if(to.length==4){
      yearTo = to; monthTo = 12; dayTo = 0; // 0 for last day of month
  }

  // 2) Test if input is type year[space] quarter

  var mySplit = from.split(" ");
  if(mySplit.length == 2){
    yearFrom = mySplit[0];
    dayFrom = 1;
    if(mySplit[1]=='Q1'){
        monthFrom = 1;
    }
    if(mySplit[1]=='Q2'){
        monthFrom = 4;
    }
    if(mySplit[1]=='Q3'){
        monthFrom = 7;
    }
    if(mySplit[1]=='Q4'){
        monthFrom = 10;
    }
  }
  mySplit = to.split(" ");
  if(mySplit.length == 2){
    yearTo = mySplit[0];
    dayTo = 0;
    if(mySplit[1]=='Q1'){
        monthTo = 3;
    }
    if(mySplit[1]=='Q2'){
        monthTo = 6;
    }
    if(mySplit[1]=='Q3'){
        monthTo = 9;
    }
    if(mySplit[1]=='Q4'){
        monthTo = 12;
    }
  }

  // 3) Test if input is type month/year
  mySplit = from.split("/");
  if(mySplit.length == 2){
    yearFrom = mySplit[1]; monthFrom = mySplit[0]; dayFrom = 1;
  }
  mySplit = to.split("/");
  if(mySplit.length == 2){
    yearTo = mySplit[1]; monthTo = mySplit[0]; dayTo = 0; // 0 for last day of month
  }

  // 4) test if input is type dd/mm/yyyy
  mySplit = from.split("/");
  if(mySplit.length == 3){
    yearFrom = mySplit[2]; monthFrom = mySplit[1]; dayFrom = mySplit[0];
  }
  mySplit = to.split("/");
  if(mySplit.length == 3){
    yearTo = mySplit[2]; monthTo = mySplit[1]; dayTo = mySplit[0];
  }

  // FINALLY: Compare dates
  // Note: 00 is month i.e. January
  monthFrom--;
  if(dayTo!=0) monthTo--;
  var dateOne = new Date(yearFrom, monthFrom, dayFrom); //Year, Month, Day
  var dateTwo = new Date(yearTo, monthTo, dayTo); //Year, Month, Day
  //alert(dayFrom+'/'+(monthFrom-1)+'/'+yearFrom+'---------'+dayTo+'/'+(monthTo-1)+'/'+yearTo)
  //alert(dateOne+'-'+dateTwo);
  if (dateOne < dateTwo) {
    result = true;
  }

  return result;
}

function adu_date_format(text){
  var result = false;

  // 0) If something to test...
  if(text=="") return true;

  // 1) Test if input is type year only
  if(text.length == 4){
    if(text >= 2000 && text <= 2030)
      result = true;
  }

  // 2) Test if input is type year[space] quarter
  var mySplit = text.split(" ");
  if(mySplit.length == 2){
    if((mySplit[0] >= 2000 && mySplit[0] <= 2030) && (mySplit[1].length == 2 && mySplit[1] >= 'Q1' && mySplit[1] <= 'Q4'))
      result = true;
  }

  // 3) Test if input is type month/year
  mySplit = text.split("/");
  if(mySplit.length == 2){
    if((mySplit[0] >= 1 && mySplit[0] <= 12) && (mySplit[1] >= 2000 && mySplit[1] <= 2030))
      result = true;
  }

  // 4) test if input is type dd/mm/yyyy
  mySplit = text.split("/");
  if(mySplit.length == 3){
    if(mySplit[2] >= 2000 && mySplit[2] <= 2030)
      result = true;
  }
  return result;
}

What jumps me most about this code is that all you do is in 2 functions.

consider moving your "parsing" operations to separate functions, one for validating the format required for parsing and one for the actual parsing:

function isValidQuarterInput(datestring){
   return datestring.split(" ").length == 2;
}

function parseQuarterInputToMonth(datestring){
    var mySplit = datestring.split(" ");
    //move your Q1,Q2,... mapping here
}

then in check_date_period() you can just call the following

if(isValidQuarterInput(from)){monthFrom = parseQuarterInputToMonth(from);}
// this is the alternative ternary operator
monthTo = isValidQuarterInput(to) ? parseQuarterInputToMonth(to) : monthTo;

your var result = false is unnecessary, as you never use it elsewhere, you can just do the following for return:

return dateOne < dateTwo;

I personally would set a boolean wasParsed to be set to true on correct parsing of one input to jump to the new Date() part. This can potentially save execution time, but that's minor. You would have to move the parsing in the following order though:

var wasParsed = false;
if(from.length==4){
  yearFrom = from; monthFrom = 1; dayFrom = 1;
  wasParsed = true;
}

if(!wasParsed){
   if(isValidQuarterInput(from)){
      wasParsed = true;
      monthFrom = parseQuarterInputToMonth(from);
      yearFrom = from.split(" ")[0];
      dayFrom = 1;
   }
}

if(!wasParsed){
  //here is the full date parsing
}
var dateOne = new Date(yearFrom, monthFrom, dayFrom);
wasParsed = false;
//repeat with to


Find the smallest distance between any two given words in a string The task:

  Find an efficient algorithm to find the smallest distance (measured in
  number of words) between any two given words in a string.

  For example, given words "hello", and "world" and a text content of
  "dog cat hello cat dog dog hello cat world", return 1 because there's
  only one word "cat" in between the two words.

const s = "dog cat hello cat dog dog hello cat world";

My imperative solution:

function smallestWordDistance2({str, word1, word2}) {
  if (!str.match(word1) || !str.match(word2)) { return 0; }

  const strArr = str.split(" ");
  let iStart, iEnd, min;
  let count = 0;
  for (let x in strArr) {
    if (!iStart) {
      if (strArr[x] === word1) {
        iStart = word1;
        iEnd = word2;
      } else if(strArr[x] === word2) {
        iStart = word2;
        iEnd = word1;
      }
    } else {
      count++;
      if (strArr[x] === iStart) {
        count = 0;
      } else if (strArr[x] === iEnd) {
        if (count === 1) { return 0; }
        if (!min || min > count) {
          min = count;
        }
        [iStart, iEnd] = [iEnd, iStart];
        count = 0;
      }
    }
  }
  return min - 1;
}
console.log(smallestWordDistance2({str:s, word1:"hello", word2:"world"}));

My "functional" solution:

const smallestWordDistance3 = ({str, word1, word2} )=> {
  if (!str.match(word1) || !str.match(word2)) { return 0; }

  const strArr = str.split(" ");
  return strArr.reduce((acc, x, i) => {
    if (!acc.iStart) {
      if (x === word1) {
        acc.iStart = word1;
        acc.iEnd = word2;
      } else if(x === word2) {
        acc.iStart = word2;
        acc.iEnd = word1;
      }
    } else {
      acc.count++;
      if (x === acc.iStart) {
        acc.count = 0;
      } else if (x === acc.iEnd) {
        if (!acc.min || acc.min > acc.count) {
          acc.min = acc.count;
        }
        [acc.iStart, acc.iEnd] = [acc.iEnd, acc.iStart];
        acc.count = 0;
      }
    }
    return acc;

  }, {iStart: null, iEnd: null, count: 0, min: null}).min - 1;
};

console.log(smallestWordDistance3({str:s, word1:"hello", word2:"world"}));

At first I thought this was a good task for a regex solution, but the following code is the best I could do. It works with the given sample string. However a slight variance in the given string would make the code unusable, because it doesn't take into consideration that word1 and word2 can be swapped (the following code would return 2 instead of 1):

const s = "dog cat hello cat dog dog hello cat dog world dog hello";

const smallestWordDistance = ({str, word1, word2} )=> {
  if (!str.match(word1) || !str.match(word2)) { return 0; }
  const reg = new RegExp(`.*\\b${word1}\\s+(.*?)\\s+${word2}\\b`);
  const match = str.match(reg);
  return match ? match[1].split(" ").length : 0;
};

console.log(smallestWordDistance({str:s, word1:"hello", word2:"world"}));

I'm now not so sure anymore whether regex is the right approach. But if anyone got a good regex (JS flavor) solution, then I'd be very much interested.

After staring at your code for some time,

You are using Hungarian notation, that is not a JavaScript practice

Related to that, strArr probably should have been arrStr if the code was consistent

It seems odd that you would return 0 when either word is not present, 0 would indicate that the words are neighbours. I would return -1 in that case.
You seem to track too much state in acc, you can get away with just tracking the last matched word, the location of the last matched word and what the best distance has been thus far
There are no comments whatsoever, I think your code could have used some

This is my functional approach:

const s = "dog cat hello cat dog dog hello cat dog world dog hello";

function smallestWordDistance(s, w1, w2) {

  function analyze(acc, word, index) {

    if (word == w1 || word == w2) {

      if (acc.word && acc.word != word) {
        const distance = index - acc.index - 1;
        acc.out = acc.out == -1 ? distance : Math.min(acc.out, distance);
      }
      acc.index = index;
      acc.word = word;
    }
    return acc;
  }

  return s.split(' ').reduce(analyze, { out: -1 }).out;
}

console.log(smallestWordDistance(s, "hello", "world"));


TextRenderer class for rendering text with OpenGL I'm writing a class called TextRenderer to render text with OpenGL.

Here's my TextRenderer.hpp file

class TextRenderer
{
public:
    void renderText(std::string text, int x, int y);
private:
    void setup();
    GLuint program;
};

Here's my TextRenderer.cpp file:

#include "TextRenderer.hpp"
#include <string>
#include <GL/glew.h>

void TextRenderer::setup()
{

}

Here's my main file:

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include "TextRenderer.hpp"

int main()
{
    //Init GLFW
    glfwInit();
    //Set OpenGL version to 3.2
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);

    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    //Make window un-resizable
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    //Create GLFW window in fullscreen mode
    GLFWwindow* window = glfwCreateWindow(800, 600, "MOBA", glfwGetPrimaryMonitor(), nullptr);
    glfwMakeContextCurrent(window);

    //Init FreeType
    FT_Library ft;
    if (FT_Init_FreeType(&ft)) {
        fprintf(stderr, "FATAL: Could not init FreeType");
        return 1;
    }
    //Init Arial FreeType Face
    FT_Face arial;
    if (FT_New_Face(ft, "Arial", 0, &arial))
    {
        fprintf(stderr, "FATAL: Could not init font \"Arial\"");
        return 1;
    }

    //Main loop
    while (!glfwWindowShouldClose(window))
    {
        glfwSwapBuffers(window);
        glfwPollEvents();

        //Close on Esc key press
        //TODO: Bring up quit dialog
        if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        {
            glfwSetWindowShouldClose(window, GL_TRUE);
        }
    }
    //Terminate GLFW
    glfwTerminate();
    return 0;
}

Notice how I have a private GLuint, program. To do this I have to #include <GL/glew.h> (in TextRenderer.cpp), and I already have GL/glew.h included in my main.cpp file. What's the best way to do this?

Most include files are written so that they are safe to be included multiple times. So, if your TextRenderer.h needs types from glew.h, you include it. Writing your own include files so that they include everything needed to use them (types, enums, ...) is usually a good thing.

You might write your TextRenderer.hpp something like this:

#ifndef TEXTRENDERER_HPP
#define TEXTRENDERER_HPP

#include <GL/glew.h> // For GLuint

class TextRenderer
{
    ...
}
#endif

The define TEXTRENDERER_HPP is there to make the header safe to be included multiple times. You may choose any unique identifier you like, but usually people use file names with some amounts of underscores at start and end.


Monte Carlo Integration Optimization The code below is my shot at trying to do monte carlo integration of the function sin(x) from 0 to pi in Python 3.
I sample randomly 10000 times a floating number from 0 to pi and do the standard procedure of the monte carlo integration and also take the average of ten results for an even better approximation,i was wondering if there is anything i can do to optimize my code from a time or accuracy standpoint.
import random
import math

def func(n):
    return math.sin(n)

integralres=0

for t in range(10):
    resf=0
    for i in range(10000):
        u=random.uniform(0,math.pi)
        resf+=func(u)
    integralres+=(math.pi)*resf/10000

print(integralres/10)

Style
PEP8 is the Python style guide and is worth a read to keep your code clear and understandable.
Naming
You're not using your loop indicies, t and i, it's customary to replace them with _ to indicate this.
The name func for a function doesn't tell you what it does. Names should be as descriptive as possible, in this case sin seems sensible
def sin(x):
    return math.sin(x)

Functions
The function sin doesn't actually give you anything, as is now clearer, and I'd remove it altogether.
The calculation of you integration is discrete, and might be used separately. I would put that inside a function
def monte_carlo(n):
    resf = 0
    for _ in range(n):
        uniform_rand_no = random.uniform(0, math.pi)
        resf += math.sin(uniform_rand_no)
    return math.pi * resf / 10000

Note that I've:

Allowed you to pick the number of iterations
Added spaces around operators

I'm not really sure what resf means, otherwise I would have renamed that too.
Main
All your code will execute when you import your file. If you use the following you can gate execution solely to when the file is run:
if __name__ == "__main__":
    for _ in range(10):
        ...

Everything
Putting all this together you would get:
import random
import math

def monte_carlo(n):
    resf = 0
    for _ in range(n):
        uniform_rand_no = random.uniform(0, math.pi)
        resf += math.sin(uniform_rand_no)
    return math.pi * resf / 10000

if __name__ == "__main__":

    integral = 0
    n = 10000

    for _ in range(10):
        integral += math.pi * monte_carlo(n) / n

    print(integral / 10)


Project Euler: Longest Collatz Sequence The Collatz Sequence is an iterative sequence that is defined for all positive integers as such:

n → n/2 (n is even)

n → 3n + 1 (n is odd)

If 13 were to be entered into this sequence, the result would be as follows:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

And the total number of terms in the chain would be 10. The sequence always ends with 1.

You must create a program that will calculate for a value in the range of 2 <= x < 1000000. This value must give the longest chain of terms when inputted into the Collatz Sequence.

I will now post my solution. Any criticism would be greatly appreciated. Did I use too many if/else statements? Was recursion not the best thing to use? Anything you have to say.

File Main.cpp

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

  namespace coll {
    int counter(1);

    long long doEven(long long numb) {
      if (numb != 1) {
        if (numb % 2 == 0) {
          counter++;
          return doEven(numb / 2);
        } else
          return doOdd(numb);
      } else
        return counter;
    }

    long long doOdd(long long numb) {
      if (numb != 1) {
        if (numb % 2 != 0) {
          counter++;
          return doOdd((3 * numb) + 1);
        } else
          return doEven(numb);
      } else
        return counter;
    }

    int chainLength(0);
    int temp(0);
    int theBestInput(0);

    int longestChain(int input) {
      if (input < 1000000) {
        if (input % 2 == 0)
          temp = doEven(input);
        else
          temp = doOdd(input);
        counter = 1;
        if (temp > chainLength) {
          chainLength = temp;
          theBestInput = input;
          input++;
          return longestChain(input);
        } else {
          input++;
          return longestChain(input);
        }
      } else {
        return theBestInput;
      }
    }

    void printResult() {
      std::cout << "LONGEST SEQUENCE: " << longestChain(2) << std::endl;
    }
  }

File Main.h

#pragma once
namespace coll {
  extern int counter;
  extern int theBestInput;
  extern int chainLength;
  extern int temp;
  long long doEven(long long numb);
  long long doOdd(long long numb);
  int longestChain(int input);
  void printResult();
}

File Test.cpp

#include "Main.h"
int main() {
  coll::printResult();
  return 0;
}

I think that you are writing similar functions to make very similar things. You can take advantage of ternary operator ? and make a simpler function instead:

int Collatz( int &len, int number )
{
    std::cout << number << " - ";
    len++;

    if( number == 1 )
        return 1;

    int NextNumber = number % 2 ? number*3+1 : number/2;

    return Collatz( len, NextNumber );
}

int main()
{
    int len = 0;
    Collatz( len, 13);

    std::cout << "Lenght: " << len << std::endl;

    return 0;
}

The output is:

13 - 40 - 20 - 10 - 5 - 16 - 8 - 4 - 2 - 1 - Lenght: 10


Representation graph as Adjacency List in JavaScript I feel quite slow in the understanding of graph representations. So, please, I'd like you to verify that I did understand, at least, the Adjacency List correctly.

So here I'm trying to implement unweighted graph, that supports parallel edges. Whether graph is directed or not, I don't understand how that might affect an implementation, as I will still add edges by pair (start, end) in any case.

-- Update:

To be more specific, I'd like to get a review, of possible problems that my implementation might have, eg:

1) extra operations

2) extra memory

3) incorrect data structure

... and so on, thank you.

--

Here is my code in JavaScript:

1) data format. Below, in the implementation, you'll see a util formatDataToAdjacencyList. Just assume that it returns such shape of the data (from tests):

const result = formatDataToAdjacencyList(data)

            expect(result).toEqual({
                edges: [
                    ['0', '4'],
                    ['1', '2'],
                    ['1', '3'],
                    ['1', '4'],
                    ['2', '3'],
                    ['3', '4'],
                    ['3', '3'],
                    ['0', '1'],
                    ['1', '2'],
                    ['2', '0'],
                ],
                vertices: [
                    '0',
                    '4',
                    '1',
                    '2',
                    '3',
                ]
            })

2) implementation

function GraphAdjacencyList(data) {
    if (data) {
        const formattedData = formatDataToAdjacencyList(data)
        this.adjacencyList = formattedData.edges
        this.vertices = formattedData.vertices
    } else {
        this.adjacencyList = []
        this.vertices = []
    }
}

GraphAdjacencyList.prototype.addVertex = function(nodeLabel) {
    if (this.vertices.indexOf(nodeLabel) !== -1) {
        throw new Error('vertex already exist')
    }

    this.vertices.push(nodeLabel)
}

GraphAdjacencyList.prototype.removeVertex = function(nodeLabel) {
    const index = this.vertices.indexOf(nodeLabel);

    if (index === -1) {
        throw new Error('vertex not found')
    }

    this.vertices.splice(index, 1)
}

GraphAdjacencyList.prototype.addEdge = function(startLabel, endLabel) {
    this.adjacencyList.push([startLabel, endLabel])
}

GraphAdjacencyList.prototype.removeEdge = function(inputStartLabel, inputEndLabel) {
    const index = this.adjacencyList.findIndex(([startLabel, endLabel]) => {
        return startLabel === inputStartLabel || endLabel === inputEndLabel
    })

    if (index === -1) {
        throw new Error('edge doesn\'t exist')
    }

    this.adjacencyList.splice(index, 1)
}
```

Strictly speaking, the list of vertices is not neccessary because the adjacency list already contains all (connected) vertices and disconnected ones can be represented as [x, null]. If you prefer to keep vertices, you'll have to synchronize them with edges:

in removeVertex you not only remove the vertex but also all edges connected to it
in addEdge you add input labels to the vertices list, if not already there (which makes one think that vertices should be a Set)

Minor notes:

In general, as of 2018, it's cleaner to use the class syntax to define classes.

In removeEdge you'd probably want &&, not ||: return startLabel === inputStartLabel && endLabel === inputEndLabel. If the graph is undirected, you also have to check for reversed edges (start == inputEnd && end == inputStart)

You didn't share the input data format and formatDataToAdjacencyList, but anyways, it would look better as a class member, not as an extra function.


Monte Carlo estimation of the Hypergeometric Function I am trying to implement the algorithm described in the paper Statistical Test for the Comparison of Samples from Mutational Spectra (Adams & Skopek, 1986) DOI: 10.1016/0022-2836(87)90669-3:

$$p = \dfrac{\prod\limits_{i=1}^{N}(R_i!)\prod\limits_{j=1}^{M}(C_j!)}{T!\prod\limits_{i=1}^{N}\prod\limits_{j=1}^{M}(X_{ij}!)}$$

The math is easy to follow in this script although very large numbers will be generated. Would using the mpmath module be my best bet for accuracy? I notice that many of my long numbers have an excessive amount of 0s possibly due to rounding errors? I want to optimize this function to generate the p-value as accurately as possible. Speed is important but not the priority. I would prefer to implement the algorithm myself although I understand there may be hypergeometric probability functions in SciPy and PyMC. I have yet to find this specific algorithm implemented in a Python module.

How can I improve the precision of the very large numbers? Would working with log computations be ideal?
Are there any module hypergeometric functions available for this specific algorithm flavor?
Am I using the decimal module appropriately?

data.dat

dsum    csum
1   0
1   2
3   9
2   1
2   1
1   0
1   0
10  0
2   3
3   0
15  0
1   28
etc.

hyperg.py

from __future__ import division   # Division is now float not integer
import numpy as np
import pandas as pd
from math import factorial as fctr
from decimal import Decimal

def factorfunc(num):
    """Returns factorial of x"""
    return Decimal(fctr(num))

def main():
    """Return the Monte Carlo Hypergeometric probability"""
    frame = pd.read_csv(r'c:\dev\hyperg\data.dat', sep='\t', header=0)

    colsum_1 = sum(frame['dsum'])
    colsum_2 = sum(frame['csum'])
    full_sum = colsum_1 + colsum_2
    length = len(frame)

    frame.index = frame.index + 1
    frame2 = pd.DataFrame(frame.apply(np.sum, axis=1)).applymap(factorfunc)
    frame3 = frame.applymap(factorfunc)

    binner = 1
    for index in xrange(length):
        binner*= frame2.iloc[index]
    numerator = long(binner) * fctr(colsum_1) * fctr(colsum_2)

    binner = 1
    for index in xrange(length):
        first, second = frame3.iloc[index]
        binner *= int(first) * int(second)
    denominator = long(binner) * fctr(full_sum)
    return numerator / denominator

if __name__ == '__main__':
    HYPERGP = main()
    print HYPERGP

I am the Adams of Adams-Skopek.  I want to point out a couple of things:

You get some truncation error when you sum or multiply a series of values in different orders.  You need to estimate this and account for it.
There is a lower limit on sparsity of the data, you need to address this.
If you can get a copy of the Pagano and Halverson program (cited in Adams and Skopek), it is useful for comparing it's results with your results.   It does the exact hypergeometric test very efficiently.
There is a PC version here. You might need to ask the authors for the code.
The computer department here can probably locate the original Fortran code for the original version of the Adams Skopek program and give you a copy (which I don't have).


Simulate Tic Tac Toe game using C language I made a Tic Tac Toe game using C. Here two players, player1 and player2, can participate and play. Please rate my code and suggest improvements.

#include<stdio.h>
#include<conio.h>
void board(char t[]);
int cheak(char T[]);

void main()
{
int i=0,n,r=100,p=1;
char TOT[9]={'1','2','3','4','5','6','7','8','9'};
char a='X';
for(;i<9;i++)
    {
    clrscr();
    board(TOT);
    printf("\n\n\n Player1=X\nPlayer2=O");
    printf(" \n player %d tern:-",p);
    printf("\nEnter number");
    scanf("%d",&n);
    TOT[n-1]=a;
    if(a=='X')
        {
        a='O';
        }
    else
        {
        a='X';
        }
    r=cheak(TOT);
    if(r==1)
        {
        clrscr();
        board(TOT);
        printf("\nPlayer 1 win");
        break;
        }
    if(r==2)
        {
        clrscr();
        board(TOT);
        printf("\nPlayer 2 win");
        break;
        }
    if(p==1)
        {
        p=2;
        }
    else
        {
        p=1;
        }
    if(i==8)
        {
        clrscr();
        board(TOT);
        printf("\n\nMatch Draw");
        break;
        }
    }
getch();
}
void board(char t[])
{
printf("_________________");
printf("\n|| %c || %c || %c ||",t[0],t[1],t[2]);
printf("\n|---------------|");
printf("\n|| %c || %c || %c ||",t[3],t[4],t[5]);
printf("\n|---------------|");
printf("\n|| %c || %c || %c ||",t[6],t[7],t[8]);
printf("\n|---------------|");
}

int cheak(char T[])
{
int i=0,n=0;
for(;n<3;n++)
    {
    if(T[i]=='X'&&T[i+1]=='X'&&T[i+2]=='X')
        {
        return 1;
        }
    i=i+3;
    }

i=0;
for(n=0;n<3;n++)
    {
    if(T[i]=='X'&&T[i+3]=='X'&&T[i+6]=='X')
        {
        return 1;
        }
    i++;
    }
if(T[0]=='X'&&T[4]=='X'&&T[8]=='X')
    {
    return 1;
    }
if(T[2]=='X'&&T[4]=='X'&&T[6]=='X')
    {
    return 1;
    }

i=0;
for(n=0;n<3;n++)
    {
    if(T[i]=='O'&&T[i+1]=='O'&&T[i+2]=='O')
        {
        return 2;
        }
    i=i+3;
    }

i=0;
n=0;
for(;n<3;n++)
    {
    if(T[i]=='O'&&T[i+3]=='O'&&T[i+6]=='O')
        {
        return 2;
        }
    i++;
    }
if(T[0]=='O'&&T[4]=='0'&&T[8]=='O')
    {
    return 2;
    }
if(T[2]=='O'&&T[4]=='O'&&T[6]=='O')
    {
    return 2;
    }
return 0;
}

void main() is not portable

Although it "works" in a lot of cases, the only two portable definitions of main are:

int main(void)

and

int main(int argc, char **argv)

Error checking

You don't check the return value of scanf.

This would be better:

if(scanf("%d", &n) != 1)
{
    fputs("Error; enter a number.", stderr);
    return EXIT_FAILURE; /* entering a letter will cause infinite loop so error out here */
}

Note that EXIT_FAILURE requires stdlib.h to be included.

Out-of-bounds write

If a user enters a 0 or a number greater than 9 in the scanf mentioned above, this line will write outside of the array bounds:

    TOT[n-1]=a;

This can cause a segmentation fault.

Spelling

There are a couple spelling errors in this code:

  cheak -> check
  tern -> turn

Formatting

There are a few issues with formatting here; first of all, each line in a function should be indented by at least 4 spaces. In addition, you should put spaces after commas  in function calls, and around most (if not all) operators.

Portability

Although clrscr and getch work with Windows and DOS, I would suggest simply removing clrscr and replacing getch with getchar. This makes your code portable to the point where it can run on most other systems.

Non-descriptive variable names

At first glance, I don't know what t, T, TOT, a, i, n, r, or p are for. The variable names should describe what they contain.

Spacing

Although the board is nice, the prompt to the user isn't. I would suggest something like this:

    printf("\n\n\nPlayer 1 = X\nPlayer 2 = O");
    printf("\nPlayer %d's turn.",p);
    printf("\n\nEnter a number: ");

...

    if(r == 1 || r == 2)
    {
        board(TOT);
        printf("\nPlayer %d wins!", r);
        break;
    }

Misc.

p is already 1 here. You don't need to set it again:

    else
        {
        p=1;
        }


Script that parses the Chase.com page for my recent payments I wrote this code earlier to parse Chase.com's online transactions page. It's written in WinForms.

stepBtn is a button that starts this.
wb is a WebBrowser that is already navigated to the page.

Can you give me advice? I'm primarily looking for optimizations, but any other advice would be great.

private void stepBtn_Click(object sender, EventArgs e)
{
    List<string> date = new List<string>();
    List<string> desc = new List<string>();
    List<double> amt = new List<double>();
    //Parse for date
    var links = wb.Document.GetElementsByTagName("span");
    foreach (HtmlElement link in links)
    {
        if (link.InnerText != null)
        {
            string inner = link.InnerText.Trim();
            if (inner == "Pending" || Regex.IsMatch(inner, @"^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d$"))
            {
                date.Add(inner);
            }
        }
    }

//Parse for description
links = wb.Document.GetElementsByTagName("td");
foreach (HtmlElement link in links)
{
    if (link.GetAttribute("classname") == "cellStyle")
    {
        desc.Add(link.InnerText);
    }
}

//Parse for amount
//Assuming I never make a $1000+ purchase, every number < 1000 will be shown. That way, the balance is not included.
links = wb.Document.GetElementsByTagName("td");
int times = 0; //There are two $xxxx.xx before what I want to parse, the present and available balance.
foreach (HtmlElement link in links)
{
    if (times > 2 && link.InnerText != null && link.InnerText.Trim().Length >= 5)
    {
        string inner = link.InnerText.Trim();
        if (inner.Substring(0, 1) == "$" && Convert.ToDouble(inner.Substring(1)) < 1000)
        {
            amt.Add(Convert.ToDouble(inner.Substring(1)));
        }
    }
    times++;
}

//Check to make sure all lists have the same length
if (date.Count != amt.Count || amt.Count != desc.Count)
{
    MessageBox.Show("The three arrays do not have the same length.\n\nDate: " + date.Count + "\nAmt: " + amt.Count + "\nDesc: " + desc.Count, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
    return;
}

//Output the arrays to the first checklist
for (int i = 0; i < date.Count; i++)
{
    firstCheck.Items.Add(date[i] + ": " + desc[i] + " (" + amt[i] + ")");
}
}

Single responibility principle

You method violates the SRP because it does to many things.

it parses HtmlElements for 3 different types
it validates the resulting List<T>
updates the UI

If you need comments like

//Parse for date
//Parse for description
//...

then it is a clear sign that these parts should be extracted to separate methods.

A much cleaner way would be

private const string dateRegexPattern = @"^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d$"
private List<string> ParseForPurchaseDates(HtmlDocument document)
{
    var purchaseDates = new List<string>();

    var links = document.GetElementsByTagName("span");

    foreach (HtmlElement link in links)
    {
        if (link.InnerText == null) { continue; }

        string inner = link.InnerText.Trim();
        if (inner == "Pending" || Regex.IsMatch(inner,dateRegexPattern ))
        {
            purchaseDates.Add(inner);
        }

    }
    return purchaseDates;
}

if you do this for the other parsings too, your click eventhandler could look like

private void stepBtn_Click(object sender, EventArgs e)
{
    List<string> date = ParseForPurchaseDates(wb.Document);
    List<string> desc = ParseForPurchaseDescriptions(wb.Document);
    List<double> amt = ParseForPurchaseAmounts(wb.Document);

    if (ListCountIsValid(date, desc, amt))
    {
        // update the UI
        return;
    }

    MessageBox.Show("The three arrays do not have the same length.\n\nDate: " + date.Count + "\nAmt: " + amt.Count + "\nDesc: " + desc.Count, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}

private bool ListCountIsValid(List<string> purchaseDates, List<string> purchaseDescriptions, List<double> purchaseAmounts)
{
    return purchaseDates.Count == purchaseAmounts.Count
        && purchaseDescriptions.Count == purchaseAmounts.Count;
}

For the parsing of the amount I would like to suggest to add a second parameter which should be optional to replace the hardcoded value 1000.

private List<double> ParseForPurchaseAmounts(HtmlDocument document, double maxAmount = 1000d)
{
    //....
}

Naming

Naming is a very important part of programming. Using abbreviations instead of the complete word will reduce readability and makes it hard to maintain. So give Bob the maintainer a chance to do his/her job easy and fast by using proper names.

amt should be e.g amounts or purchaseAmounts ...


Get letter grade using eval() I understand that using eval is extremely dangerous as it can execute deadly commands as an input by the user.

I'm trying to write a code to get a letter grade from a number between 0 to 1. I was trying to write it in the most elegant way. Is this safe?

try:
    score = float(raw_input('Enter score: '))
except Exception as ex:
    print 'Score must be a number!'
    quit()

if score > 1:
    print 'Score must be less than 1'
    quit()

grades = {
    'A': str(score) + '>= 0.9',
    'B': str(score) + '>= 0.8',
    'C': str(score) + '>= 0.7',
    'D': str(score) + '>= 0.6',
    'F': str(score) + '< 0.6',
}

for key in sorted(grades):
    if eval(grades[key]):
        print key
        quit()

You're right to suspect that using eval stinks: it really does.

You can define the values of grades as tuples of functions and a parameter:

def greater_than_or_equal(score, x):
    return score >= x

def less_than(score, x):
    return score < x

grades = {
    'A': (greater_than_or_equal, 0.9),
    'B': (greater_than_or_equal, 0.8),
    'C': (greater_than_or_equal, 0.7),
    'D': (greater_than_or_equal, 0.6),
    'F': (less_than, 0.6),
}

Now you can write a get_grade function that returns the correct grade using the evaluator and a parameter:

def get_grade(score):
    for key in sorted(grades):
        evaluator, param = grades[key]
        if evaluator(score, param):
            return key

I converted the code that just prints the key and quits to a function,
so that you can verify the correct behavior using assertions:

assert 'F' == get_grade(0.1)
assert 'F' == get_grade(0.5)
assert 'D' == get_grade(0.6)
assert 'D' == get_grade(0.61)
assert 'C' == get_grade(0.7)
assert 'B' == get_grade(0.8)
assert 'A' == get_grade(0.9)
assert 'A' == get_grade(0.91)
assert 'A' == get_grade(1)

Actually, using a dictionary for grades doesn't make a lot of sense.
It could be just a list of tuples in the correct order so that you can even skip the sorting step:

grade_evaluators = (
    (greater_than_or_equal, 0.9, 'A'),
    (greater_than_or_equal, 0.8, 'B'),
    (greater_than_or_equal, 0.7, 'C'),
    (greater_than_or_equal, 0.6, 'D'),
    (less_than, 0.6, 'F'),
)

def get_grade(score):
    for evaluator, param, grade in grade_evaluators:
        if evaluator(score, param):
            return grade


2D lattice with fixed boundary condition I am writing code for the following equation with fixed boundary condition on a 2 dimensional lattice of \$L\times L\$ sites:

$$\begin{align}
x_{i+1} =&\ (1-\varepsilon)r\, x_i (1-x_i) + \\
         &\ 0.25\varepsilon\left((r\,x_{i-1}(1-x_{i-1}) + r\,x_{i+1}(1-x_{i+1}) + r\,x_{i-L}(1-x_{i-L}) + r\,x_{i+L}(1-x_{i+L})\right)
\end{align}$$

Fixed boundary condition means for end sites there are no neighboring sites beyond boundary.

Is there a simpler or more sophisticated way to write following code for the above equation with fixed boundary condition ?

def CML2d(x):
    eps = 0.3
    r = 3.9
    xn = np.zeros(N+1, float)
    for i in range(1, N+1):
        if i>L and i<=(L-1)*L:
            if i%L==1:
                xl, xr = 0., x[i+1]
                xu, xd = x[i-L], x[i+L]
            elif i%L==0:
                xl, xr = x[i-1], 0.
                xu, xd = x[i-L], x[i+L]
            else:
                xl, xr = x[i-1], x[i+1]
                xu, xd = x[i-L], x[i+L]
        elif i>1 and i<L:
            xl, xr = x[i-1], x[i+1]
            xu, xd = 0., x[i+L]
        elif i>(L-1)*L+1 and i<L*L:
            xl, xr = x[i-1], x[i+1]
            xu, xd = x[i-L], 0.
        elif i==1:
            xl, xr = 0., x[i+1]
            xu, xd = 0., x[i+L]
        elif i==L:
            xl, xr = x[i-1], 0.
            xu, xd = 0., x[i+L]
        elif i==(L-1)*L+1:
            xl, xr = 0., x[i+1]
            xu, xd = x[i-L], 0.
        elif i==L*L:
            xl, xr = x[i-1], 0.
            xu, xd = x[i-L], 0.
        xn[i] = (1-eps)*r*x[i]*(1-x[i]) + 0.25*eps*( r*xl*(1-xl) + r*xr*(1-xr) + r*xu*(1-xu) + r*xd*(1-xd) )
    return xn

L = 10 #side of 2d lattice
N = L*L #number of sites in 2d lattice
x0 = numpy.random.uniform(0.1, 0.9, N+1) #initial values for x

xf = [] # store iterate x
x = x0
for nt in np.arange(0.005, 50.005, 0.005):
    x = CML2d(x)
    xf.append(x)

Testing script from a few days ago:

import numpy as  np

original:

def CML2d(x):
    eps = 0.3
    r = 3.9
    xn = np.zeros(N+1, float)
    for i in range(1, N+1):
        if i>L and i<=(L-1)*L:
            if i%L==1:
                xl, xr = 0., x[i+1]
                xu, xd = x[i-L], x[i+L]
            elif i%L==0:
                xl, xr = x[i-1], 0.
                xu, xd = x[i-L], x[i+L]
            else:
                xl, xr = x[i-1], x[i+1]
                xu, xd = x[i-L], x[i+L]
        elif i>1 and i<L:
            xl, xr = x[i-1], x[i+1]
            xu, xd = 0., x[i+L]
        elif i>(L-1)*L+1 and i<L*L:
            xl, xr = x[i-1], x[i+1]
            xu, xd = x[i-L], 0.
        elif i==1:
            xl, xr = 0., x[i+1]
            xu, xd = 0., x[i+L]
        elif i==L:
            xl, xr = x[i-1], 0.
            xu, xd = 0., x[i+L]
        elif i==(L-1)*L+1:
            xl, xr = 0., x[i+1]
            xu, xd = x[i-L], 0.
        elif i==L*L:
            xl, xr = x[i-1], 0.
            xu, xd = x[i-L], 0.
        value = (1-eps)*r*x[i]*(1-x[i]) + 0.25*eps*( r*xl*(1-xl) + r*xr*(1-xr) + r*xu*(1-xu) + r*xd*(1-xd) )
        xn[i] = value
    return xn

partial attempt to work with 2d x; the intention was to replace all the uses of L with 2d array indexing tests.

def CML2d_1(x):
    eps = 0.3
    r = 3.9
    L,_ = x.shape
    N = L*L
    # xn = np.zeros((L,L), float)
    xn = (1-eps)*r*x*(1-x)
    x = x.flat
    #for i in range(N):
    for j in range(L):
      for k in range(L):
        i = k+L*j
        i1 = i+1
        if i1>L and i1<=(L-1)*L:
            if i1%L==1:
                xl, xr = 0., x[i+1]
                xu, xd = x[i-L], x[i+L]
        ....
        #value = (1-eps)*r*x[i]*(1-x[i])
        value = 0.25*eps*( r*xl*(1-xl) +
                            r*xr*(1-xr) +
                            r*xu*(1-xu) +
                            r*xd*(1-xd) )
        #xn.flat[i] = value
        xn[j,k] += value
    return xn

But I then realized that I don't need to iterate over all points.  Instead I could just sum subarrays  (similar to the array of taking a 1d diff, x[1:]-x[:-1]:

# x[i+1] = (1-eps)*   r*x[i]*(1-x[i]) +
#          0.25*eps*( r*x[i-1]*(1-x[i-1]) +
#                     r*x[i+1]*(1-x[i+1]) +
#                     r*x[i-L]*(1-x[i-L]) +
#                     r*x[i+L]*(1-x[i+L]) )

def CML2d_2(x):
    eps = 0.3
    r = 3.9
    x2 = r * x * (1-x)
    xn = (1-eps) * x2
    xn[1:,:]  += 0.25 * eps * x2[:-1,:]
    xn[:-1,:] += 0.25 * eps * x2[1:,:]
    xn[:,1:]  += 0.25 * eps * x2[:,:-1]
    xn[:,:-1] += 0.25 * eps * x2[:,1:]
    return xn

then making use of a covolve2d function in scipy.signal:

from scipy import signal
def CML2d_3(x):
    eps = 0.3
    r = 3.9
    in2 = np.zeros((3,3))
    in2[1,:] = 0.25 * eps
    in2[:,1] = 0.25 * eps
    in2[1,1] = (1-eps)
    print(in2)
    x2 = r * x * (1-x)
    res = signal.convolve2d(x2, in2, mode='same', boundary='fill', fillvalue=0)
    return res

testing:

L = 10 #side of 2d lattice
#L = 4
N = L*L #number of sites in 2d lattice
x0 = np.random.uniform(0.1, 0.9, N+1) #initial values for x
x0[0]=np.nan  # test if this is used
res=CML2d(x0.tolist())
print(res)

x2d = x0[1:].reshape(L,L)
res1=CML2d_1(x2d)
print(x0.shape)
print(res1.shape)
print(np.allclose(res1.flatten(), res[1:]))

print(np.allclose(res1, CML2d_2(x2d)))
print(np.allclose(res1, CML2d_3(x2d)))


BASH Script to Configure Monitors on Linux via xRandR My main computer is a laptop which I run i3wm atop Arch Linux. As such, my monitor situation sometimes changes, so I wanted to code a script to configure my monitors based on which ones are connected to the system. The script runs on startup of i3wm.

As for the monitors, sometimes I may not have an external display connected, sometimes I may have an HDMI and a DP display connected, and sometimes I may be at another location with an HDMI and DP display connected but the DP appears as a different output.

The monitors are as follows:

eDP-1 - Internal Display.
HDMI-2 - Either of my secondary displays, which have the same resolution and placement
DP-1 or DP-1-8 - Either of my primary displays, which are the same monitor and placement, but appear as different outputs.

The code is as follows:

#!/usr/bin/env bash

# The xRandR names of my monitors, including the internal laptop monitor / display
readonly MON_INTERNAL='eDP-1'
readonly MON1='DP-1'
readonly MON1_FALLBACK='DP-1-8'
readonly MON2='HDMI-2'

# The resolutiond of the given xRandR monitors / displays. NOTE: $MON1 and $MON1_FALLBACK are the same display, so only one res is needed
readonly MON_INTERNAL_RES='1920x1080'
readonly MON1_RES='2560x1440'
readonly MON2_RES='1680x1050'

main_mon=''
sec_mon=''

# Store a count of how many monitors are connected
mon_count=$(xrandr -q | grep -w 'connected' | wc -l)

# Configure the monitors via xRandR
config_monitors() {
    if [[ "$#" -eq "2" ]]; then
        xrandr --output $1 --primary --mode $2 --rotate normal --pos 0x0
    elif [[ "$#" -eq "4" ]]; then
        xrandr --output $MON_INTERNAL --off --output $1 --mode $2 --pos 1680x0 --right-of $3 --output $3 --mode $4 --pos 0x0 --left-of $1
    fi
}

# Determine which main monitor is available
if [[ $mon_count -gt 1 ]]; then
    # The name of which main monitor is connected (either $MON1 or $MON1_FALLBACK)
    main_mon=$(xrandr -q | grep -w 'connected'| grep "^$MON1\|^$MON1_FALLBACK" | awk '{ print $1 }')
else # fallback to laptop display $MON_INTERNAL because the hardcoded displays aren't connected
    main_mon=$MON_INTERNAL
fi

# Determine whether the secondary HDMI monitor, $MON2 is connected
if [[ $mon_count -gt 1 ]] && [[ $(xrandr -q | grep $MON2 | awk '{ print $2 }') -eq connected ]]; then
    sec_mon=$MON2
fi

# Configure both external monitors if they're set or use the internal display
# TODO: Actual fallback logic for when HDMI display is connected but not the primary DP-x..
if [[ -n $main_mon ]] && [[ -n $sec_mon ]]; then
    config_monitors "$main_mon" "$MON1_RES" "$sec_mon" "$MON2_RES"
else
    config_monitors "$MON_INTERNAL" "$MON_INTERNAL_RES"
fi

Any suggestions on how I could improve the functionality and/or readability of this script are greatly appreciated. This is my first true foray into writing a Bash script that actually serves a usable real-world purpose to me.

for a problem like this, it helps to break down the possible states and map out what you want to do for each, and then construct a data model that lets you minimize duplication.

Here is my approach to your problem:

hardcoded array of monitors by order of preference, allowing wildcards
hardcoded assoc. array of screen resolutions for each preference
hardcoded assoc. array of options templates for each possible configuration
construct array of actual available monitor names from (1) and xrandr output
construct array of resolutions from (2) and (4)
get options template from (3) and (4)
fill template using (4) and (5)

__

#!/usr/bin/env bash

# each PRIORITY entry must have matching entry in MODE; $displays will be sorted in priority order
declare -ar PRIORITY=( "DP-1*" HDMI-2 eDP-1 )
declare -Ar MODE=(
        [eDP-1]=1920x1080
        [DP-1*]=2560x1440
        [HDMI-2]=1680x1050
    )

# options corresponding to each possible config.  sorted in PRIORITY order.
# left hand side is matched against space-separated list of actual monitor labels from xrandr
# template values like <D2> are zero-based
declare -Ar OPTS=(
            [DP-1* HDMI-2 eDP-1]='--output <D2> --off --output <D0> --mode <M0> --pos 1680x0 --right-of <D2> --output <D1> --mode <M1> --pos 0x0 --left-of <D0>'
            [HDMI-2 eDP-1]='--output <D1> --off --output <D0> --mode <M0> --pos 0x0'
            [eDP-1*]='--output <D0> --primary --mode <M0> --rotate normal --pos 0x0'
        )

declare -ar ALL_CONNECTED=( $( { xrandr -q || exit 1; } | awk '$2 == "connected" {print $1}' ) )

[[ ${#ALL_CONNECTED[@]} = 0 ]] && {
    echo no monitors connected
    exit 1
}

declare -a displays=()
declare -a modes=()

# populate displays and modes in preference order from ALL_CONNECTED
for (( i=0; i<${#PRIORITY[@]}; i++ )); do
    for (( j=0; j<${#ALL_CONNECTED[@]}; j++ )); do
        if [[ ${ALL_CONNECTED[$j]} == ${PRIORITY[$i]} ]]; then
            displays+=( ${ALL_CONNECTED[$j]} )
            modes+=( ${MODE[${PRIORITY[$i]}]} )
            break
        fi
    done
done

echo "
ALL_CONNECTED: ${ALL_CONNECTED[@]}
displays: ${displays[@]}
modes: ${modes[@]}
"

for i in "${!OPTS[@]}"; do
    if [[ "${displays[@]}" == $i ]]; then
        opts=${OPTS[$i]}
        opts=${opts//<M/\$\{modes\[}
    opts=${opts//<D/\$\{displays\[}
        opts=${opts//>/\]\}}
        set -x
        xrandr $( eval echo $opts )
        exit $?
    fi
done
echo "no OPT setting found for connected display combination of ${ALL_CONNECTED[@]} [ ${displays[@]} ]"
exit 1


Code Review for Hangman in C++ I have the following C++ program:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

void printVector (std::vector<int>& vec)
{
    for (int a = 0; a < vec.size(); a++)
        std::cout << (char)vec[a] << ", ";
}

int main ()
{
    const std::string HANGMAN[] = {"\n------+",
                                  "\n      |\n      |\n      |\n      |\n      |\n------+",
                                  "\n   ---+\n      |\n      |\n      |\n      |\n      |\n------+",
                                  "\n   ---+\n   |  |\n      |\n      |\n      |\n      |\n------+",
                                  "\n   ---+\n   |  |\n   O  |\n      |\n      |\n      |\n------+",
                                  "\n   ---+\n   |  |\n   O  |\n   |  |\n      |\n      |\n------+",
                                  "\n   ---+\n   |  |\n   O  |\n  /|  |\n      |\n      |\n------+",
                                  "\n   ----\n   |  |\n   O  |\n  /|\\ |\n      |\n      |\n-------",
                                  "\n   ----\n   |  |\n   O  |\n  /|\\ |\n  /   |\n      |\n-------",
                                  "\n   ----\n   |  |\n   O  |\n  /|\\ |\n  / \\ |\n      |\n-------"};
    const std::string WORDS[] = {"zigzagging", "wigwagging", "grogginess", "beekeeping", "mummifying",
                                 "fluffiness", "fulfilling", "shabinness", "revivified", "kobnobbing",
                                 "beekeepers", "wheeziness", "shagginess", "sleeveless", "parallaxes",
                                 "woolliness", "chumminess", "skyjacking", "grubbiness", "wobbliness",
                                 "feebleness", "jaywalking", "alkalizing", "blabbering", "overjoying"};
    srand(time(0));
    std::string compWord = WORDS[rand() % 25];
    char compHiddenWord[] = "----------";
    int hangmanPos = 0;
    std::vector<int> guessed;
    char userGuess;
    bool letterCorrect;
    while (hangmanPos != 9)
    {
        std::cout << "\nThis is your hangman:\n" << HANGMAN[hangmanPos] <<
                     "\n\nThese are the letters you've already guessed:\n\n";
        printVector(guessed);
        std::cout << "\n\nThis is my word:\n\n" << compHiddenWord <<
                     "\n\nGuess a letter: ";
        std::cin >> userGuess;
        guessed.push_back(userGuess);
        letterCorrect = false;
        for (int a = 0; a < compWord.size(); a++)
            if (compWord[a] == userGuess)
            {
                if (letterCorrect == false)
                {
                    std::cout << userGuess << " is in my word!\n\n\n";
                    letterCorrect = true;
                }
                compHiddenWord[a] = userGuess;
            }
        if (letterCorrect == false)
        {
            std::cout << "Oops! " << userGuess << " is not in my word.";
            hangmanPos++;
        }
        else
            for (int a = 0; a < compWord.size(); a++)
                if (compWord == compHiddenWord)
                {
                    std::cout << "Well done, " << compWord << " was my word!";
                    return 0;
                }
    }
    std::cout << "\nOh Dear! Looks like you've been hanged. My word was actually " << compWord << ".";
}

Which is supposed to replicate the classic game of hangman visually. Is the code fully optimized? Is there an other way I could improve it?

I'm by far no expert, and I might be wrong on some of my statements, so take them as a basis for discussion. Anyway, I am trying to learn about code quality in C++ myself, so I'm giving it a shot.

printVector should take the argument as const-ref, because the vector is not supposed to be changed in the function call.
Consider using an iterator to loop through the vector in printVector. However, in a small-scale program like this I don't see this as a big issue. In larger programs, it might help you to make a function more general. And thanks to C++11's auto, it will be very readable -- even more so if you use a range-based for loop.
You're using the vector<int> guessed to store the chars from userGuess. Why not a vector<char> to store char? Would also make the type cast to (char) in printVector unnecessary.
Also you're mixing C-arrays and STL's std::vector, C-strings (char *) and std::string. Try to stick to the STL versions throughout. If you are using a C++11 capable compiler, you can even initialize the std::vector the same way as you're doing with the C-array now.
You are using curly braces {} in for loops and if/else statements only when absolutely required. Most style guides encourage using braces for every for/if/else block, or at most allow omitting them for one-line "blocks". The reason is readability (you can always expect to find a } where a longer block ends) and editability (It's easy to forget adding the braces when adding a line to the supposed for/if/else block).
It doesn't look like idiomatic C++ to compare a bool variable with == as in if(letterCorrect == false). You should use something like if (! letterCorrect) instead.
You should add a return 0; statement when the user is hanged. As far as I know it isn't required for the main function, but as you're already returning with return 0; when the user guesses the word, you should also do so at the end of the function.
The condition if (compWord == compHiddenWord) is wrong. You're looping over the array elements, but then you're comparing the pointer to the 0th element of the array to the std::string, instead of comparing the array elements. If you follow my suggestion above and change compHiddenWord to std::string, then you can omit the loop and simply write if(compWord == compHiddenWord) (Edit: As I learned, it also works correctly for comparisons of char* and std::string, so I deleted my example for by-character comparison)
You're using a as a loop index. While this isn't wrong, C++ programmers would typically use i or j for this purpose.
Edit: Your hangman array goes from 0 to 9 -- but in the while loop you never reach the 9 thanks to the hangManPos != 9 condition. Therefore, you will never print the completely hanged hangman.

Let me know what you think!


Like system with MySQL on multiple types of pages I want to have a like system on my website on multiple pages like "news", "comments", "forum posts" etc. So I was wondering what was the best way to do it between:

having like tables for each of my "modules" (news, comments...)
having one table like :

table: likes
id (int) | page_id (varchar) | user_id (int)

which would have those datas:

5 | news_5576    | 676
6 | comment_6564 | 676
7 | forum_656    | 787

And I would get the number of likes of a module with his id and type:

$type = 'comment';
$id = 6564;
$query = "SELECT COUNT(*) FROM likes WHERE page_id = '$type_$id'";

What do you think is the best idea?

This design violates first normal form, which is a concept that states that each data field should contain an atomic value (using type and ID together makes this a composite value).

This makes certain types of queries more difficult, and you'll use more database space and suffer query performance.

Store the type in one column, and the ID in another. If you have many tables, you might consider breaking it out so each module type has a corresponding "likes" table (e.g. news and news_likes. This uses significantly less space and makes maintenance easier, but makes some queries harder (such as "show me all my likes").

Using a single-table notation is acceptable, but by breaking the type and ID out, you can use an enum and an int instead of a var char, which will improve query speed on full-table scans, and use less space on disk.


Performance Issue on css and javascript styling I make some ui custom controls.  Typically my controls have themes to them so it can be changed.  I dont use css files for each themes.  What I do instead is hava a javascript file that contains the different themes for that particular control. Example of my button control (Note i took the rest of the css off the other colors just so this wont be so long in the post)

(function ($) {

    $.fn.buttonTheme = function () { };
    $.buttonTheme = {

        newButtonTheme: function(){
            $.buttonTheme.rules = {
                "button" :
                {
                    "nonrounded": "cursor: pointer; cursor: hand;display:inline-block;zoom:1;*display:inline;" +
                                  "vertical-align:baseline;margin:0 2px;outline:none;text-shadow:0 1px 1px rgba(0,0,0,.3);" +
                                  "-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.2);" +
                                  "-moz-box-shadow:0 1px 2px rgba(0,0,0,.2);box-shadow:0 1px 2px rgba(0,0,0,.2);",
                    "rounded": "cursor: pointer; cursor: hand;display:inline-block;zoom:1;*display:inline;vertical-align:baseline;margin:0 2px;" +
                               "outline:none;text-shadow:0 1px 1px rgba(0,0,0,.3);-webkit-border-radius:.4em;-moz-border-radius:.4em;" +
                               "border-radius:.4em;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.2);-moz-box-shadow:0 1px 2px rgba(0,0,0,.2);" +
                               "box-shadow:0 1px 2px rgba(0,0,0,.2);"
                },
                "light_gray":
                {
                    "enabled": "" +
                                "",
                    "disabled": "",
                    "hover": "",
                    "text": ""
                },
                "black":
                {
                    "enabled": "",
                    "disabled": "",

                    "hover": "",
                    "text": ""
                },
                "gray":
                {
                    "enabled": "",
                    "disabled": "",

                    "hover": "",
                    "text": ""
                },
                "white":
                {
                    "enabled": "",
                    "disabled": "",

                    "hover": "",
                    "text": ""
                }

            };
        }
    };

})(jQuery);

So in the control javascript file I build the control by assigning the particular elements the particular style it needs based on the selected theme like ligh_gray.  I find this method to be easy to maintain and update to other themes because the underlying samples are there and its not hard coded in the script. So I can just create another theme like aqua for example and just change the colors, etc. Also I can dynamically change the theme easier without having to do a page refresh

What I wanted to know from others is there thoughts on this.  Is there a performance issue in this method? Does it seem like its a maintenance headache?

Yes! This looks like a maintenance head ache ( nightmare ).

CSS belongs to CSS files ( you can apply csslint to CSS files, CSS files also have syntax highlighting, plus most developers rightfully dislike maintaining CSS in JavaScript ).

If you must support different styles at run-time, you can create styles in your stylesheet for each theme and then assign the right class when themes get switched.

To your points:

I find this method to be easy to maintain and update to other themes because the underlying samples are there and its not hard coded in the script. I am not sure what you mean by "not hardcoded", but you are most likely wrong.

So I can just create another theme like aqua for example and just change the colors, etc. You can do the same with CSS files
Also I can dynamically change the theme easier without having to do a page refresh. You can do the same by changing the class dynamically

As for performance, you are using extra bandwidth by sending over all style-sheets, to be avoided on mobile.


Command to measure CPU time and RAM usage of process while making sure it does not go over certain ressource limitation I found some old code of mine and am trying to see if it can be improved. The goal is to write a command that measures a process's CPU time and RAM peak usage and kills the process if it exceeds a specified amount of CPU time and RAM usage.

This command is meant to be used on both MAC OSX and Linux.

# Get arguments
MaxMemory="$1"
MaxTime="$2"
Command="$3"
for (( i=4 ; i<="$#"; i++)); do
    Command="${Command} ${!i}"
done

echo -e "MaxMemory = ${MaxMemory}\nMaxTime = ${MaxTime}\nCommand = ${Command}"

#### run the command in the background
${Command} &

#### Get pid
pid=$!
echo "pid = ${pid}"

#### Monitor resources
MemoryPeak=0
timeBefore=$(date +"%s")
while true;do
    # Get memory
    mem=$(ps -o rss= -p $pid)

    # Break if the process has stopped running
    if [[ ${mem} == "" ]]; then
        break
    fi

    # Set the MemoryPeak of memory
    if [ "${mem}" -gt "${MemoryPeak}" ]; then
        MemoryPeak=$mem
    fi

    # If it consumed too much memory, then kill
    if [ "${MemoryPeak}" -gt "${MaxMemory}" ];then
        #echo "process consumed too much memory"
        kill ${pid}
        break
    fi

    # If it consumed too much CPU time, then kill
    timeAfter=$(date +"%s")
    timeUsage=$((timeAfter - timeBefore))
    if [ "${timeUsage}" -gt "${MaxTime}" ];then
        #echo "process consumed too much time"
        kill ${pid}
        break
    fi

    # sleep
    sleep 0.1
done

timeAfter=$(date +"%s")
timeUsage=$((timeAfter - timeBefore))

echo "MEM ${MemoryPeak} TIME ${timeUsage}"

How can this be improved?

Command="$3"
for (( i=4 ; i<="$#"; i++)); do
    Command="${Command} ${!i}"
done
# …
${Command} &

Much cleaner to just reference the end of the $@ array directly.  Since you're running the commands later, and would like to keep quoting intact, use an array:
declare -a Command=( "${@:3}" )

"${Command[@]}" &

# Break if the process has stopped running
if [[ ${mem} == "" ]]; then
    break
fi

The idiomatic way to test for process existence is with kill -0, as in:
 kill -0 $pid || break

Since $mem is a number, or empty, an arithmetic test is good too:
(( mem )) || break

if [ "${mem}" -gt "${MemoryPeak}" ]; then
    MemoryPeak=$mem
fi

if [ "${MemoryPeak}" -gt "${MaxMemory}" ];then
    #echo "process consumed too much memory"
    kill ${pid}
    break
fi

Prefer parentheses over single brackets (or double brackets) for arithmetic operations:
 (( MemoryPeak = ( mem > MemoryPeak ? mem : MemoryPeak ) ))

 if (( MemoryPeak > MaxMemory )); then # etc.

 # If it consumed too much CPU time, then kill

You're measuring wallclock time, not CPU time.  There's also some slop:  timeBefore is recorded when the script collects it, which might not be close to the binary invocation time.  Better to read the times and cputimes values from ps, and calculate with those:
 MaxElapsed= # …
 MaxCPU= # …
 # …
 read mem dt ct <<< $( ps --no-headers -o rss,etimes,cputimes -p$pid )
 # …
 if (( dt > MaxElapsed || ct > MaxCPU )); then # …

timeAfter=$(date +"%s")
timeUsage=$((timeAfter - timeBefore))

See timing comments above.  If you make the outer loop condition kill -0 $pid, you can simply reference $dt here.

Putting it all together:
 MaxMemory=$1 MaxElapsed=$2 MaxCPU=$3 Command=( "${@:4}" ) MemoryPeak=0
 "${Command[@]}" & pid=$!
 while kill -0 $pid; do
    read mem dt ct <<< $( ps --no-headers -o rss,etimes,cputimes -p$pid )
    (( mem )) || break
    (( MemoryPeak = ( mem > MemoryPeak ? mem : MemoryPeak ) ))
    (( MemoryPeak > MaxMemory || dt > MaxElapsed || ct > MaxCPU )) && kill $pid && wait $pid  # loop conditional will break for us
done
echo "MEM $MemoryPeak ELAPSED $dt CPU $ct"


Count frequencies of symbols in a list I'd like to find a more elegant solution to the following.

Below appears correct, but it's hard to read.

Is my first use of the map function below poor in stylistic terms?

It feels that way, and I'd like to pin down why.

I wonder what is a nicer way to achieve this.

;; ANSI Common Lisp ex 3.3, p56.
;; "Define a function that takes a list and returns a list indicating
;;  number of times each (eql) element appears, sorted from most common
;;  element to least common"
;; > (occurrences '(a b a d a c d c a))
;; ((A . 4) (C . 2) (D . 2) (B . 1))

(defun occurrences (lst)
  (labels ((build-flist (lst res)                                                            ; [1]
            (if (null lst)
                res
                (build-flist (cdr lst) (mapcar #'(lambda (x) (if (eql (car x) (car lst))     ; [2]
                                                                 (cons (car x) (1+ (cdr x))) ; [3] ; rtn inc'd freq entry
                                                                 x))                               ; rtn unchanged freq entry
                                               res))))
           (remove-dups (lst)                               ; [4]
            (if (null lst)
                nil
                (adjoin (car lst)
                        (remove-dups (cdr lst))))))

    (sort (build-flist lst (mapcar #'(lambda (x) (cons x 0)) (remove-dups lst))) ; [5]
          #'> :key #'cdr)))

;;[1] build-flist builds a frequency list. it is called like:
;;    (build-flist '(a b a d a c d c a) '((A . 0) (B . 0) (C . 0) (D . 0))
;;[2] map over entire res assoc list, incrementing frequency if it equals
;;    the el just removed from head of list, else just keep entry as is (inefficient).
;;[3] inelegant. in map, is there some kind of when form.                 ;; <<< STILL TENSION HERE, CODE IS HARD TO READ
;;[4] remove-dups uses adjoin, (set-based operator). this will help us    ;; --------------------------------------------
;;    build an zero-initialised freq list, to get us started.
;;[5] Finally, our actual function builds the frequency list, then sorts the result.
;;    We pass it a frequency list initialised to zero to get started.

;; Discussion
;; It doesn't always help to encapsulate helper functions in labels.
;; If the functions are simple, perhaps they could be global, if they're complex, perhaps they could be simplified.
```

This is the typical situation where a hash table that maps elements to their frequency count is particularly well suited.

(defun occurrences (lst)
  (let ((table (make-hash-table)))                   ; [1]
    (loop for e in lst
          do (incf (gethash e table 0)))             ; [2]
    (sort (loop for k being the hash-key of table    ; [3]
                  using (hash-value v)
                collect (cons k v))
          #'>= :key #'cdr)))                         ; [4]

We create the hash table: the key will be an element of the list, the value will be the frequency count. Note that it is not necessary to initialize it because the gethash function provide an initialization of the value for a key not already present in the table.
For each element of the list we increment (incf) the frequency value associated to it. This value is obtained by gethash, and if it is not yet in the table, it is initialized by default to 0 (the last parameter of gethash).
At the end, we use the “loop over hash table” syntax to collect all the pairs (key count) in a list, and we sort the list over the second element.

This solution is simple, very efficient and elegant.

If you want to use only lists, here is a solution that has the same complexity of the sorting algorithm:

(defun occurrences (lst)
  (if (null lst)                                            ; [1]
      nil
      (let ((sorted (sort (copy-list lst) #'string<=)))     ; [2]
        (do ((c 1)                                          ; [3]
             (l (cdr sorted) (cdr l))                       ; [4]
             (el (car sorted) (car l))                      ; [5]
             (res nil))                                     ; [6]
            ((null l)                                       ; [7]
             (sort (cons (cons el c) res) #'>= :key #'cdr)) ; [8]
          (if (eql (car l) el)
              (incf c)                                      ; [9]
              (progn
                (push (cons el c) res)                      ; [10]
                (setf c 1)))))))

If the list is empty return nil.
Sort the element by their names (assuming they are atoms), so that equal elements are contiguous.
Start a loop. The variabile c count how many equal elements are found (the frequency).
l is used to scan the sorted list. It starts from the second element of sorted.
el is the current element, while (car l) is the second one.
res is used to accumulate the result.
The iteration stops when l reaches the end of the list.
The result is obtained by adding the last couple (element, frequency) to the result, and sorting it by frequency.
The body of the loop: if the first element is equal to the second one increment the counter and continue to iterate.
Otherwise, a new element is found. So push the old one with its frequency on the result, and reset the counter to 1.