Short Answer
This looks like a decent attempt.  There are a few minor stylistic issues, but I think the biggest conceptual problem is a bad choice of Parser type.  You should separate ErrorMessage from Leftovers, as these aren't the same sort of thing and so shouldn't share a single field in the algebraic type.  Much clearer is:
type Parser a = String -> Either Error (Maybe a, String)
type Error = String

You've acknowledged that you've never used monads and functors.  Well, there's no time like the present!  Parsers and monads are a match made in heaven.  With the cost of some gnarly monad boilerplate, you can rewrite the bulk of your parsing logic in a much cleaner style, as I show below.  Since you have an interest in programming languages and parsing anyway, I'd suggest reading through some tutorials that show how to write monadic parsers from scratch.  It's a great way to start using monads.  See this article or this blog post for example.  These and other older resources are based on the old version of the Monad class, and you'll get error messages about missing Applicative or Alternative instances.  You can see the notes in the 7.10.x migration guide for how to fix old code so it compiles.
Long Answer
If you want to write a non-monadic parser, this looks like a reasonable first attempt.  A few minor stylistic points.  When writing two guards for the same pattern (or compatible patterns), like here:
case ... of
  (Just x, xs) | x == c -> ...
  (Just x, _)  | x /= c -> ...

it's more usual to chain the guards without repeating the pattern:
case ... of
  (Just x, xs) | x == c -> ...
               | x /= c -> ...

Also, if you have two mutually exclusive guards, it's more usual to use otherwise than write a negated form of the guard.  So, charParser would be written:
charParser :: Char -> Parser Char
charParser c s = case eatParser s of
  (Nothing, e) -> (Nothing, e)
  (Just x, xs) | x == c    -> (Just x, xs)
               | otherwise -> (Nothing, "...")

This has a further advantage that if you turn on the ghc -Wall flag, it'll warn you about case statements and function definitions that don't cover all possible patterns, but mutually exclusive guards will generate false positives unless you use otherwise.  (That is, the compiler isn't willing to assume that it's impossible for both x == c and x /= c to fail.)
Also, this is more personal preference, but I think it makes more sense to make the "success" case more prominent by moving it to the front:
charParser :: Char -> Parser Char
charParser c s = case eatParser s of
  (Just x, xs) | x == c -> (Just x, xs)             -- we succeed
               | otherwise -> (Nothing, "...")      -- or experience various...
  (Nothing, e) -> (Nothing, e)                      -- ...types of failure

It's a big newbie mistake to write functions with lots of head and tail calls.  Pattern matching with x:xs is preferred, since it's not only clearer, but if you turn on -Wall and stamp out any warnings, the pattern matching code is guaranteed not to try to take the head or tail of an empty list.  You've done a good job of using patterns instead of head and tail, but I'd extend this to stringParser, too:
stringParser :: String -> Parser String
stringParser [] s = (Just "", s)
stringParser (u:us) s = case charParser u s of
  (Just x, xs) -> case stringParser us xs of
    (Just x', xs') -> (Just $ x : x', xs')
    (Nothing, e) -> (Nothing, e)
  (Nothing, e) -> (Nothing, e)

The use of x' here is confusing though, since I'd expect it to have the same type as x, but x :: Char and x' :: String have different types.  I guess I'd rename the variables to more consistently identify the "rest" of the stream and differentiate it from what we're trying to parse u:us and what we've actually parsed x:xs:
stringParser :: String -> Parser String
stringParser [] s = (Just "", s)
stringParser (u:us) s = case charParser u s of
    (Just x, rest) -> case stringParser us rest of
        (Just xs, rest') -> (Just (x:xs), rest')
        (Nothing, e) -> (Nothing, e)
    (Nothing, e) -> (Nothing, e)

I think this makes the function a little clearer.  Technically, x:xs isn't needed since it's just a copy of u:us, so you could write:
stringParser :: String -> Parser String
stringParser [] s = (Just "", s)
stringParser (u:us) s = case charParser u s of
  (Just _, rest) -> case stringParser us rest of
    (Just _, rest') -> (Just (u:us), rest')
    (Nothing, e) -> (Nothing, e)
  (Nothing, e) -> (Nothing, e)

Some people think it's important to preserve the value u:us for return with @-syntax:
stringParser :: String -> Parser String
stringParser [] s = (Just "", s)
stringParser uall@(u:us) s = case charParser u s of
  (Just _, rest) -> case stringParser us rest of
    (Just _, rest') -> (Just uall, rest')   -- we return "uall" here
    (Nothing, e) -> (Nothing, e)
  (Nothing, e) -> (Nothing, e)

I don't know if this is clearer, and the @-syntax is pretty repulsive.  I think there's a misguided notion that there's a performance gain here by not re-creating the u:us value right after breaking it apart, but GHC optimizes it and produces equivalent code, so use whichever is clearer.
There seems to be a bug in varParser.  In the case with not (isLetter x), the x token is thrown away, so the following test fails:
> varParser "123"
(Just "","23")

This should either return (Just "", "123") or (Nothing, "expected a letter"), I guess.  You don't notice this bug because the recursive call of varParser compensates for it through an extra case.  If you fix it, then that case becomes redundant and the EOF case can be merged with the not-a-letter case, so you can simplify varParser to something more like:
varParser :: Parser String
varParser s = case eatParser s of
  (Just x, rest) | isLetter x -> case varParser rest of
                     (Just xs, rest') -> (Just (x:xs), rest')
                     (Nothing, e) -> (Nothing, e)
  _ -> (Just [], s)

Technically, the (Nothing, e) case can never be triggered, but you need to keep it in to avoid a -Wall warning.
There are two "big ticket" problems with your code, however.  The first is that your choice of Parser data type is poor:
type Parser a = String -> (Maybe a, String)

In the return type here, you use the first Maybe a component as a flag:  if it's Nothing, the second String component is an error.  If it's Just a, the second String component is the rest of the stream.  However, parse errors and rest-of-streams are not semantically comparable things, and it's pure coincidence that they happen to have the same String type, so they shouldn't be represented by the same field in your algebraic type.  From a practical standpoint, if you decided to refactor your code to parse streams of tokens other than Strings or use a different Error type that includes location information, you'll have to do a lot of unnecessary modification.  You also introduce the potential for dumb programming bugs, where you start parsing error message or printing stream remainders on the console, because they're both String and the bad code will type check.  But these practical concerns are probably not that convincing, and in this simple example probably aren't too serious.  It's really just the theoretical, best-practices issue that this is a bad design when a much more straightforward and idiomatic type is available:
type Parser a = String -> Either String (a, String)

Most Haskell programmers would be confused by your Parser type.  But, every Haskell programmer will understand this new Parser type immediately.  The Either error result convention and the String -> (a, String) pattern, and the combination of the two of them, are hardwired into their brains.  You could make it even more obvious by writing:
type Parser a = String -> Either Error (a, String)
type Error = String

Anyway, the resulting rewritten parsers look about the same, for example:
charParser :: Char -> Parser Char
charParser c s = case eatParser s of
    Right (x, xs) | x == c -> Right (x, xs)
                  | otherwise -> Left $ "Expected " ++ [c] ++ ", but got " ++ [x] ++ " instead."
    Left e -> Left e

but I think this new parser type is just a fundamentally better choice.
The second big ticket problem with your code is, as you've acknowledged in the question, the proliferation of nested cases to handle cascading parse failure.  In many types of code, error handling involves handling exceptional situations, and you can usually get away with no more than a few deeply nested cases where the overall "success path" remains clear.  In parsing, failure of parsers is fundamental to the parsing process, and nearly every parser ends up handling multiple failure modes, often (as in your varParser) in ways that involve converting "failure" into "success" or vice versa.
The best way to fix this is to introduce parser combinators.  The combinators themselves can use ugly nested cases in their implementation, but if the combinators have "meaning", they will result in code that's easier to read where it matters.  For example, you could introduce a combinator like:
combine :: (a -> b -> c) -> Parser a -> Parser b -> Parser c
combine f p q s =  case p s of
  Right (x, s') -> case q s' of
    Right (y, s'') -> Right (f x y, s'')
    Left e -> Left e
  Left e -> Left e

Here combine applies two parsers in sequence and -- if they both succeed -- uses a function to combine their results.  With this combinator, you can rewrite stringParser as:
stringParser :: String -> Parser String
stringParser "" s = Right ("", s)
stringParser (u:us) s = combine (:) (charParser u) (stringParser us) s

A satisfy combinator that applies a parser and ensures the result satifies a condition:
satisfy :: (a -> Bool) -> String -> Parser a -> Parser a
satisfy f unexpected p s = case p s of
  Right (x, rest) | f x -> Right (x, rest)
                  | otherwise -> Left unexpected

let's you rewrite charParser as:
charParser :: Char -> Parser Char
charParser c = satisfy (==c) unexpected eatParser
  where unexpected x = "Expected " ++ [c] ++ ", but got " ++ [x] ++ " instead."

These combinators end up being of limited use because not a lot of thought has gone into them.  For example, if you try to rewrite varParser using them, you might try something like:
varParser :: Parser String
varParser s = combine (:) (satisfy isLetter unexpected eatParser) varParser s
  where unexpected x = "Expected a letter, but got " ++ [x] ++ " instead."

but this won't work because the first non-letter character throws an error instead of ending the variable name.
This is why it's worth learning how to use monads for parsers.  A monad is a good fit for the problem of combining parsers together, and it provides a whole host of pre-written combinators that work with any monadic parser.  The combinators have been thoughtfully designed, and you rarely find yourself in the situation where you need to write a combinator from scratch, because you can almost always find one that does what you want.
Anyway, my rewrite of your parser without any combinators would look like this.  It uses the Either-based parser type, reorders the nested cases to put "success" first, and cleans up some variable names and redundant cases:
{-# OPTIONS_GHC -Wall #-}

module MonadlessParser where

import Data.Char

type Parser a = String -> Either String (a, String)

eatParser :: Parser Char
eatParser []     = Left "Unexpected EOF"
eatParser (x:rest) = Right (x, rest)

charParser :: Char -> Parser Char
charParser c s = case eatParser s of
  Right (x, rest) | x == c -> Right (x, rest)
                  | otherwise -> Left $ "Expected " ++ [c] ++
                                 ", but got " ++ [x] ++ " instead."
  Left e -> Left e

stringParser :: String -> Parser String
stringParser [] s = Right ("", s)
stringParser (u:us) s = case charParser u s of
  Right (_, rest) -> case stringParser us rest of
    Right (_, rest') -> Right (u:us, rest')
    Left e -> Left e
  Left e -> Left e

varParser :: Parser String
varParser s = case eatParser s of
  Right (x, rest)
    | isLetter x -> case varParser rest of
                      Right (xs, rest') -> Right (x:xs, rest')
                      Left e -> Left e
  _ -> Right ([], s)

data Expr = Open Expr | Value String deriving (Show, Eq)
exprParser :: Parser Expr
exprParser s = case charParser '(' s of
    Right (_, rest) -> case exprParser rest of
        Right (expr, rest') -> case charParser ')' rest' of
            Right (_, rest'') -> Right (Open expr, rest'')
            Left e -> Left e
        Left e -> Left e
    Left _ -> case varParser s of
        Right (x, rest) -> Right (Value x, rest)
        Left e -> Left e

main :: IO ()
main = do
  print $ eatParser "abc" == Right ('a',"bc")
  print $ charParser 'a' "abc" == Right ('a',"bc")
  print $ charParser 'b' "abc" == Left "Expected b, but got a instead."
  print $ stringParser "abc" "abce" == Right ("abc","e")
  print $ stringParser "abc" "abc" == Right ("abc","")
  print $ stringParser "abc" "axbc" == Left "Expected b, but got x instead."
  print $ varParser "abc" == Right ("abc","")
  print $ varParser "abc2" == Right ("abc","2")
  print $ varParser "abc abc2" == Right ("abc"," abc2")
  print $ exprParser "((aa))bc" == Right (Open (Open (Value "aa")),"bc")
  print $ exprParser "((aa)b)bc)" == Left "Expected ), but got b instead."

Writing a monadic version requires two difficult steps.  First, you have to make your Parser a newtype and write Monad and related instance for it.  This looks like black magic, but you eventually figure out how to do it reliably.  Second, you need to learn about all the applicative and monadic combinators and how to use them.
Once you've done that, the work you put in really pays off.  Here's a full monadic version of your parser with comments that try to explain what's going on.  Setting aside the ugly monadic instances, most of the parsers themselves are straightforward to write and understand.
{-# LANGUAGE DeriveFunctor #-}
{-# OPTIONS_GHC -Wall #-}

module MonadParser where

-- a bunch of combinators
import Control.Applicative
import Control.Applicative.Combinators
import Control.Monad

-- just for `isLetter`
import Data.Char

-- the hardest part, by far, is writing these instances
newtype Parser a = Parser { runParser :: String -> Either String (a, String) }
  deriving (Functor)
instance Applicative Parser where
  pure x = Parser $ \str -> Right (x, str)
  (<*>) = ap
instance Monad Parser where
  p >>= f = Parser $ \str -> case runParser p str of
      Right (x, rest) -> case runParser (f x) rest of
        Right (y, rest') -> Right (y, rest')
        Left e -> Left e
      Left e -> Left e
instance MonadFail Parser where
  fail err = Parser $ \_ -> Left err
instance Alternative Parser where
  empty = fail "<empty>"
  p <|> q = Parser $ \str -> case runParser p str of
    Left _ -> runParser q str
    result -> result
instance MonadPlus Parser

-- we need to rewrite `eatParser` to use a `Parser` newtype
eatParser :: Parser Char
eatParser = Parser go
  where go (x:rest) = Right (x, rest)
        go []       = Left "unexpected EOF"

-- a "satisfy" combinator is helpful; we have pre-written combinators for
-- almost everything else
satisfy :: (a -> Bool) -> Parser a -> Parser a
satisfy f p = do
  x <- p
  guard (f x)
  return x

-- now the hard word pays off...

-- "satisfy" lets us easily write `charParser`
charParser :: Char -> Parser Char
charParser c = satisfy (==c) eatParser

-- `mapM` runs `charParser` for each input character and puts the result
-- together into a list of characters, namely the desired `String`
stringParser :: String -> Parser String
stringParser = mapM charParser

-- this parses a single `letter` using `Data.Char.isLetter`
letterParser :: Parser Char
letterParser = satisfy isLetter eatParser

-- `some` parses one or more of the given parser into a list (in this case,
-- a list of characters, so a `String`)
varParser :: Parser String
varParser = some letterParser  -- non-empty variable name

-- the `between` combinator runs a parser between two other parsers; here
-- `parens p` will run parser `p` between parentheses
parens :: Parser a -> Parser a
parens = between (charParser '(') (charParser ')')

-- Here `<$>` just attaches the desired constructor to the return value
-- from the parsers.  The alternation operator `<|>` tries the first parser
-- and, if it fails, tries the second before giving up.
data Expr = Open Expr | Value String deriving (Show, Eq)
exprParser :: Parser Expr
exprParser = Open <$> parens exprParser
         <|> Value <$> varParser

-- All the tests still pass
main :: IO ()
main = do
  print $ runParser eatParser "abc" == Right ('a',"bc")
  print $ runParser (charParser 'a') "abc" == Right ('a',"bc")
  print $ runParser (charParser 'b') "abc" == Left "<empty>"
  print $ runParser (stringParser "abc") "abce" == Right ("abc","e")
  print $ runParser (stringParser "abc") "abc" == Right ("abc","")
  print $ runParser (stringParser "abc") "axbc" == Left "<empty>"
  print $ runParser varParser "abc" == Right ("abc","")
  print $ runParser varParser "abc2" == Right ("abc","2")
  print $ runParser varParser "abc abc2" == Right ("abc"," abc2")
  print $ runParser exprParser "((aa))bc" == Right (Open (Open (Value "aa")),"bc")
  print $ runParser exprParser "((aa)b)bc)" == Left "<empty>"

I hope that example whets your appetite for trying out monadic parsing.


More efficient way to retrieve data from JSON

There are a few issues with getTextFromJSON involving use of pointers, code
duplication and use of an inappropriate function.

Pointers first.  In this code:

jsontok_t tokens[15];
jsontok_t key;
...
key = tokens[i];

you are copying the token when you could be using a pointer:

jsontok_t *key = &tokens[i];

Copying is obviously more costly than pointing.  Also note that it is often
best to define the variable at its first point of use.

There are two points of duplication, one determining the size of the token
array and one concerned with copying the string.  Instead of this:

jsontok_t tokens[15];
...
parseJson(&p, json, tokens, sizeof(tokens) / sizeof(tokens[0]));
for(unsigned int i = 0; i < sizeof(tokens) / sizeof(tokens[0]); ++i)

I would do either:

#define N_TOKENS 15
jsontok_t tokens[N_TOKENS];
...
parseJson(&p, json, tokens, N_TOKENS);
for(unsigned int i = 0; i < N_TOKENS; ++i)

or

jsontok_t tokens[15];
#define N_TOKENS (sizeof tokens / sizeof tokens[0])  // or const int N_TOKENS inseatd of #define
...etc

The string copying code-duplication is actually unnecessary if you use a
better standard library function...

Instead of using strcmp to compare the string (which involves constructing
the string because it lacks a \0):

    if(!strcmp(keyString, "utterance"))

use memcmp.  And you can use strndup to create a copy of the key.  If you
don't have strndup which is non-standard, you can easily write it (in a
separate function).

These changes wont speed it up much, but are certainly cleaner:

char* getTextFromJSON(const char *json)
{
    if (!json) return NULL;

    json_parser p;
    #define N_TOKENS 15  // this normally would be at the start of the file
    jsontok_t tokens[N_TOKENS];

    initJsonParser(&p);
    int n = parseJson(&p, json, tokens, N_TOKENS);
    for (int i = 0; i < n; ++i) {
        jsontok_t *key = &tokens[i];
        if (!memcmp("utterance", &json[key->start], (size_t) (key->end - key->start))) {
            ++key;
            return strndup(&json[key->start], (size_t)(key->end - key->start));
        }
    }
    return NULL;
}


Naming and underscores

Underscores help to separate long sentences. But variable names should not be long sentences. You should drop the underscores, stick with camelCasing (as per convention), and shorten the names.

bool errorsFound;
bool importFailed;

The underscores in your constants are not as much of an issue. I have generally moved away from the SCREAMCASING for constants and instead just PascalCase them (without underscores); but that's not a globally agreed upon standard.

As an aside, unit and integration test methods often do have long sentences for names, and underscores are actually useful there. So you're definitely allowed to use underscores where appropriate. Local variables with long names are hardly ever appropriate.

Simplifying the logic

if ((result.Count == 2) && (!is_The_Import_Has_Failed_Exist))
{
    result_REJECT = result[1].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
    StatusResult = Properties.Resources.ARGS_RESULT_OK_REJECT;
}

if ((is_The_Import_Has_Failed_Exist) && (result.Count == 2))
{
    result_REJECT = result[1].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
    StatusResult = Properties.Resources.ARGS_RESULT_KO_REJECT;
}

These two evaluations share some commonalities, and their bodies are identical (assuming OK/KO is a typo). This can be merged into a single evaluation:

if(result.Count() == 2 && (!is_The_Import_Has_Failed_Exist || is_The_Import_Has_Failed_Exist) )
{
    result_REJECT = result[1].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
    StatusResult = Properties.Resources.ARGS_RESULT_OK_REJECT;
}

Clear naming

var is_Import_Failed_Exist = ...;
var is_The_Import_Has_Failed_Exist = ...;

For the life of me, I cannot figure out what the difference between them is. The naming of these variables (and the constants after which they are named) is not good, since a reader cant figure out what they represent.

returnObject = new ReturnObject { ... }

ReturnObject is such a vague name that it fails to express anything meaningful. I'll happily admit that I've struggled coming up with names for return DTOs too, but it needs to have some sort of descriptive name, e.g. ImportStatusDto or ImportStatusResult.

Properties.Resources.ARGS_RESULT_OK_REJECT

"OK" and "reject" seemingly contradict one another. Is this a good outcome, or a bad one? It's unclear and needs better naming to make this clear.

else if (is_No_Errors_Found_Exist)
{
    StatusResult = Properties.Resources.ARGS_RESULT_OK;
}
else if (is_Import_Failed_Exist)
{
    StatusResult = Properties.Resources.ARGS_RESULT_OK; // I assume "KO" was a typo
}

As a developer reading your code, it's very confusing why the failure of an import is considered a positive ("OK") outcome. This seemingly contradicts the evaluation above where the existence of errors is clearly not OK.

This may be a bug in your code. In that case, you probably would've spotted the bug easier if your variable names had been easier to read (see the above tips).

If this isn't a bug, then I'm still inclined to conclude that your naming introduces confusion where none should have existed.

CountLines

This sounds like a command or instruction ("Hey, you! Count those lines!"), which is how methods should be named.

Variable names (except for booleans) should be nouns or noun phrases. LineCount is the better name here.

For completeness' sake, boolean names should generally adhere to yes/no questions: isAlive, hasFood, ... or in other cases phrasings that strongly convey a binary result: userWasDeleted, importFailed, ...
In all of these cases, if I were to put a question mark behind the name, it would be bad English but you would understand the question and would easily identify what the meaning of "yes" and "no" is.

Avoid negative variable names

is_No_Errors_Found_Exist

While you can read it now, this can quickly get out of hand. How would you check that errors were found?

if(!is_No_Errors_Found_Exist)

That's a double negative, and really hard to parse. It's much better to stick with "positive" naming and then negate the boolean value

bool errorsFound = ...;

if(!errorsFound) { ... }

if(errorsFound) { ... }

In this example, there's no need to use a double negative, which improves readability.

Your internal voice should read this as "not errors found", which it intuitive and clearly expresses the intention of the evaluation.

Note that when I say "positive", I mean "not negated" instead of "good". A boolean called isFailed is a "positive" naming. Not because failure is good (it clearly isn't), but because it's not negated.
importDidNotFail would be the "negative" naming (because of the "not"), which you should try to avoid to enhance overall readability.

In conclusion

This is more of a review on your question than the code, but there is a common thread here.

  First I have two conditions on the number of list elements,then in one of these conditions I have two others conditons to treat it

Try to read this from the perspective of a StackExchange user who knows nothing about you or your code. Does this explain what your code is trying to achieve?

I think you're explaining things the way they already make sense to you, while not considering how others will (or won't) understand what you write.

I mention this because code readability should be written from the perspective of those who don't know the code. Whenever you name something (a variable, a method, ...) you need to ask yourself a simple question:

  Would a developer who is new to the project understand what this method does/what this variable expresses?

This is by far the biggest issue in your code. Your naming has made it very hard for anyone else to read your code and understand its purpose.

And it's not just about other people. If you start working on another project, and in a few months' time you have to return to this project, you're going to be scratching your head too, because you won't remember all the things you currently know and will have to build up that working knowledge again.

The other minor issues/bugs I've found are actually fairly common in codebases where readability is hampered, because low readability leads to a high likelyhood of making unintentional mistakes.

I suspect that if you work on improving your code readability, you'll automatically start seeing how to improve parts of the code more and more.


You should use shift and push

function rotate( array , times ){
  while( times-- ){
    var temp = array.shift();
    array.push( temp )
  }
}

//Test
var players = ['Bob','John','Mack','Malachi'];
rotate( players ,2 )
console.log( players );

shift removes the first element, push adds an element at the end.
I am not sure whether you are using players_new because you do not know how to modify the original array or because you do not want to modify the original. If you do not want to modify the original array you could:

function rotate( array , times ){
  array = array.slice();
  while( times-- ){
    var temp = array.shift();
    array.push( temp )
  }
  return array;
}

//Test
var players = ['Bob','John','Mack','Malachi'];
console.log( rotate( players ,2 ) );

Finally, if you meant to declare an array, you should have var players_new = [];, not var players_new = {};. Plus players_new is an unfortunate name.

Golfic edition:

while(times--)array.push(array.shift());


Welcome to Code Review. A few basic pointers about programming in python:

Go through the code style guide as documented in PEP-8.
Instead of putting comments, make use of docstrings.
Use test framework for writing a few tests, and use asserts instead of print() for checks and validations.

From the PEP-8 rules:

Convert the comment about Luhn's algortihm into a docstring.
Variables and functions are named using snake_case convention.
No unnecessary blank lines are needed. Keep the code clean and concise.

Your main function can be broken further, into get_provider, valid_card_number and the one your already have check_number. It is completely your choice if you want to raise an exception in case of wrong inputs or whether the functions should return falsy values.

Instead of having an approximately 10 line of code inside if-statement, deal with the else clause first, and return early.

While you didn't actually write the check_number code, I'll just put my views about that as well here.

Using a list comprehension, with the help of % 9 (\$ \mod 9 \$), you can make it quite pythonic. You can then have a sum(<list comprehension>) % 10 == 0 as a one-liner.

sum(digit * 2 % 9 if i % 2 else digit for i, digit in enumerate(map(int, cc_number[::-1]))) % 10 == 0


Scraping IMDB and exporting to JSON or/and CSV

Python uses snake_case, not camelCase for variable and function names. csvFormat for example, should be csv_format.

In two places you do this weird thing:

with open(. . .) as file:
    . . .
file.close

with already closes file, so there's no need to manually close it.
file.close doesn't do anything, and a good IDE would warn you of that. You need to add () to call close: file.close().

Speaking of weird things, you have this in a couple places as well:

try:
    userMessageFormat = input((prompt))
except ValueError:
    print('Input unkown')

input, as far as I know, will never throw. If you had a call to int in there, or if you were using Python 2 (maybe?), this may make sense. I don't think this try does anything, and I don't think 'Input unkown' will ever be printed.

if userMessageFormat != 'csv' and userMessageFormat != 'json':
    . . .
elif userMessageFormat == 'json':
    . . .
elif userMessageFormat == 'csv':

This is written in kind of a "fragile" way. If you ever add more formats, you'll need to make two changes: 1. Add a new elif userMessageFormat == check, and 2. Add to the first condition to validate the format ahead of time. If you forget to update the latter, none of the other cases will be True, and return userMessageFormat will cause a NameError since userMessageFormat will have never been defined.

Just make use of an else case:

if userMessageFormat == 'json':
    . . .
elif userMessageFormat == 'csv':
    . . .
else:
    print('Format unkown')

This is what else is for: to handle when none of the other checks were true.

for i in films:
    x = {
        "position": i[0],
        "title": i[1],
        "year": i[2],
        "imbdRanking": i[3]
    }

This could make use of destructuring to avoid needing to index i:

for position, title, year, rank in films:
    x = {
        "position": position,
        "title": title,
        "year": year,
        "imbdRanking": rank
    }

If the sub-collections in films contain more than 4 elements each, you'll need to change the for line to:

for position, title, year, rank, *_ in films:

The *_ catches all the remaining elements. Without this, you'll get a ValueError.

if userMessageFilm == 'films250':
    . . .
elif userMessageFilm != 'films250':
    . . .

This is redundant. If the first check is false, the second must be true. This can just be:

if userMessageFilm == 'films250':
    . . .
else:
    . . .


Averaging lists of values with duplicate keys

This seems to be the fastest so far:

import numpy
from numpy import newaxis

def avg_dups(genes, values):
    folded, indices, counts = np.unique(genes, return_inverse=True, return_counts=True)

    output = numpy.zeros((folded.shape[0], values.shape[1]))
    numpy.add.at(output, indices, values)
    output /= counts[:, newaxis]

    return folded, output

This finds the unique genes to fold the values into, along with the current index → new index mapping and the number of repeated values that map to the same index:

    folded, indices, counts = np.unique(genes, return_inverse=True, return_counts=True)

It adds the row from each current index to the new index in the new output:

    output = numpy.zeros((folded.shape[0], values.shape[1]))
    numpy.add.at(output, indices, values)

numpy.add.at(output, indices, values) is used over output[indices] += values because the buffering used in += breaks the code for repeated indices.

The mean is taken with a simple division of the number of repeated values that map to the same index:

    output /= counts[:, newaxis]

Using Ashwini Chaudhary's generate_test_data(2000) (giving a 10000x4 array), my rough timings are:

name             time/ms  Author
avg_dups           230    gwg
avg_dups_fast       33    Ashwini Chaudhary
avg_dups_python     45    Ashwini Chaudhary
avg_dups           430    Veedrac
avg_dups             5    Veedrac with Jaime's improvement


Optimizing nested loop in run length encoding function

Output arguments

You currently use a pointer for your output argument. While this is a matter of preference, I found it confusing considering the other pointer argument indicates an array. I would use a reference for pMatchPos instead of a pointer.

const-correctness and immutability

In a pointer-math-heavy function like this, it is especially important to document which values can and cannot be changed within the function body. Use const to specify that a value is not mutable. This allows the compiler to do more error-checking, and makes the code easier to reason about.

Most of your function parameters aren't modified inside the function, so they can be marked const. Note especially src, which has two const modifiers, indicating its value cannot be changed, nor can the data it points to.

Also, startPos is only mutated when it is clamped to zero. You can rewrite this using std::max() (from the algorithm header) to put the initialization on one line, and then make it const as well. Note that using max() requires pos be a signed type, otherwise there will be overflow errors.

An improved beginning of your function would look like this:

uint32_t simpleEnc(uint8_t const * const src, uint32_t const size,
                   int32_t const pos, uint32_t& pMatchPos) // note type changes, cf. above
{
    const int32_t startPos = std::max(0, pos - 0x1000);
    const int32_t diff = size - pos;

Magic numbers

I don't know what 0x1000 is supposed to represent, and neither will anyone else who doesn't intimately understand the algorithm. It would be better to assign it to a named constant. Something like

constexpr uint32_t BACKTRACK_AMOUNT = 0x1000; // Pick a more accurate name, though.

Naming

pMatchPos uses Hungarian notation. Please don't do this. Instead, try to come up with a more descriptive name, or just leave off the prefix.


Catching all exceptions and errors in PHP

I don't think that printing raw errors/data to the users is a good idea:

var_dump($e);

They (usually) can't fix it, so it doesn't help them. (See #3 here) It might also contain sensitive information which could help attackers.

Instead of that you should log the errors to a log file, hide the details from the user (don't forget to print a friendly error message) and fix the errors. Your users might not call/mail you when they found a bug. They just simply use one of your competitor's service.
Instead of using the same function for three more or less different purposes:

set_error_handler("error_handler");
set_exception_handler("error_handler");
register_shutdown_function("error_handler");

I'd use three different functions (with proper signatures) which might call a fourth one. It would be cleaner (easier to read, understand and maintain). It would make unnecessary the internal magic with error_get_last(), func_get_args() and instanceof.

// Only let PHP report errors in dev
error_reporting(ENV === 'dev' ? E_ALL : 0);

It seems to me as a code smell: Test Logic in Production. I'd use php.ini to set this, I guess php.ini is a straightforward place for most of the PHP developers to set this instead of a PHP file.


How to re-factor a common String comparison

It seems data envy. I'd create nameContains method in the Manager class.

public boolean nameContains(final String searchText) {
    if (StringUtils.contains(name, searchText)) {
        return true;
    }
    return false;
}

Instance variables (fields) should be private. See: why instance variables in java are always private


I know it's hard to name things, but try to come up with more descriptive names for your functions. As a general rule, I would avoid using the prefix get... for pure functions. It's just noise and doesn't help the reader understand what the function is. In Haskell we try to describe what things are and less how things are done.

Some names which I think are somewhat better...

zeroPoly :: [Int] -> (Int -> Int)

e.g. zeroPoly [1,2,3] is a polynomial which is zero on 1, 2 and 3.

remove1 :: [a] -> [[a]]

e.g. remove1 as is all the ways of removing one element from the list as. Also, using the polymorphic signature alerts the reader that the function isn't specific to Ints.

I would also introduce a type alias:

type Poly = Int -> Int

so you can write the signature of scalePolynome (and other functions) as:

scalePolynome :: Int -> Int -> Poly -> Poly

which helps to describe better what it is doing. Anywhere you can use the alias  Poly instead of Int -> Int will help the reader.

In fact, I would even write the signature this way:

scalePolynome :: (Int,Int) -> Poly -> Poly

since you use (x,y) tuples elsewhere for points on the function.

You should be careful about using div here. Are you sure that with your basis polynomials you'll always get a integral result? To be safe you might have to perform the calculations with Rationals.

Instead of getBase I would probably call the function basisPolynomials - again, just avoid the prefix get....

Finally, note that your getList and remove functions can be written in terms of the inits and tails functions from Data.List:

import Data.List

remove1 :: [a] -> [[a]]
remove1 as = zipWith (++) (inits as) (tail $ tails as)


Compute and print the sum and mean of name and value pairs

Although it might be a bit longer (I haven't bothered to count lines), I think I'd prefer something on this order:

#include <map>
#include <string>
#include <numeric>
#include <iostream>
#include <utility>
#include <iterator>
#include <algorithm>

typedef std::multimap<std::string, float> vtype;
typedef std::pair<std::string, float> ptype;

namespace std {
std::istream &operator>>(std::istream &is, ptype &v) {
    return is >> v.first >> v.second;
}
}

float add_second(float a, vtype::value_type b) {
    return a + b.second;
}

template <class FwdIt>
float average(FwdIt start, FwdIt end) {
    float total = std::accumulate(start, end, 0.0f, add_second);
    return total / std::distance(start, end);
}

int main() {
    vtype values((std::istream_iterator<ptype>(std::cin)),
                  std::istream_iterator<ptype>());

    vtype::iterator start, end;

    for (start = values.begin(); start != values.end(); start=end) {
        end = values.upper_bound(start->first);
        std::cout << start->first << ": " << average(start, end) << "\n";
    }
    std::cout << "Overall: " << average(values.begin(), values.end()) << "\n";
    return 0;
}

If you preferred, you could use an std::vector instead of an std::multimap. That would require some minor changes to the code (e.g., using std::upper_bound instead of std::multimap::upper_bound, and adding a call to std::sort after reading the data, but would otherwise be pretty similar. It would, however, probably be a bit more efficient (less CPU time and memory).

While I suppose others might disagree, I prefer this for the simple reason that I find it easier to understand. We start by reading in all the data. We then find each run of identical keys, and compute the average for that run and print it out. When we reach the end of the data, we do the same for the overall average.

In fairness, if you were working with huge amounts of data, this probably wouldn't be the best way do do things. It does spend more time walking through the same data than is strictly necessary. At the same time, unless you're going to rewrite the code to overlap reading the data with computing the result, it's unlikely to make much real difference -- almost regardless of how you do the computation, that I/O will almost certainly occupy the vast majority of the overall time.


Text interface for employee management in Rust

At a glance: that function is way too long and deeply nested. Three levels of loop/branch nesting is, in my experience, the most that any function should have; and the more nested it is the shorter it should be.

Consider extracting branch and loop bodies to separate named functions.

Your code structure also seems to be “determine what command to execute” (add / list / etc), then “execute said command”. I’d make this explicit, have the regexp parsing of an input line in a separate function that returns the command type and parameters. Dispatching this would be a natural use for match over your own Command type. (That said, in a realistic CLI you might need the commands available to be extensible so don’t get too married to this pattern. I’m guessing you’ll get to dynamic polymorphism later in the book.)


json2CSV fails because of lack of RAM memory

Before we dive into code, I'd like to ask: Does this CSV really need to be generated on-the-fly/on-demand? If the answer is no, you can probably run a cron job using mongoexport. This way, you avoid Node altogether.

Libraries aren't immune to memory limits. They create objects too! In this case, it starts when you loaded up a lot of Follow entries into follows. This is compounded when you converted all of that data into CSV. Under the hood, you 1) loaded a lot of data into an huge array of objects and 2) you converted that huge array of objects into a huge string.

Now luckily, json2csv has a streaming API. What this means is that, instead of processing all of your results in one go in memory, you have the option to build that CSV by chunk. Since we're dealing with an array of objects instead of strings, buffers and arrays of raw data, you should look at the "object mode".

So what you do is set up a pipeline - a bunch of functions connected together and called one after the other with the output of the previous being the input of the next. Data is streamed into this pipeline, transforming on every transform function it passes through until it reaches the end.

In your case, it would look something like this:

const { createWriteStream } = require('fs')
const { Readable } = require('stream')
const { Transform } = require('json2csv')

// ...somewhere in your controller code...

// With streams, everything starts with and ends with a stream. This is the start.
const input = new Readable({ objectMode: true })
input._read = () => {} // Not sure what this is for, really.

// We set up the transformer, the thing that converts your object into CSV rows.
const json2csv = new Transform ({ fields }, { objectMode: true })

// Create a stream to the file. This is the end of the line.
const output = createWriteStream('./output')

// You can optionally listen to the output when all the data is flushed
output.on('finish', () => { /* all done */ })

// We connect the dots. So this reads like:
// 1. Read data into input.
// 2. Input gets fed into json2csv.
// 3. The output of json2csv is fed into output (which is our file).
const stream = input.pipe(json2csv).pipe(output)

// Start pumping data into the stream. You could use setInterval if you wanted.
follows.forEach(o => input.push(obj))

// Close the input.
input.push(null)

Now I'm not too familiar with Mongoose. But if it has an API that exposes your results as a stream, you can skip object mode and pipe that stream to json2csv instead. This way, the entire thing uses streams and at no point would all data be stored in memory. They get loaded, processed and flushed a few pieces at a time.

const stream = streamFromMongoose.pipe(json2csv).pipe(output)


Do not attempt to put all the test criteria in one test.
Make seperate (small) tests, which each cover one specific scenario.

If all tests pass, you know it is ok.
But make sure the tests do not depend on each other: that they can run in any order.

For the exception assert, it is better to use an Attribute on the test method:

Update:

As Roland Illig mentioned, it is good to check that nothing was modified.

Updated code fragment:

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SetFiles_FilesNotInTheSameFolder_ExpectedException()
{
    // 3rd call to SetFiles. Invalid

    // set to invalid structure (files not in same folder)
    // and expect throw
    // and no change

    var validParentFolder = @"c:\C:\muzică\folder1";
    var validFile1 = @"c:\C:\muzică\folder1\file1.txt";

    var invalidFile1 = @"C:\muzică\folder1\file2.txt";
    var invalidFile2 = @"C:\muzică\folder2\file2.txt";

    var fs = new Files();
    fs.SetFiles(new string[]
    {
        validFile1
    });

    fs.SetFiles(new string[]
        {
            invalidFile1,
            invalidFile2
        });

    // test that fs was not modified

    Assert.AreEqual(1, fs.FileList.Count);
    Assert.AreEqual(validParentFolder, fs.ParentFolder);

    Assert.AreEqual(validFile1, fs.FileList[0].Path);
}

Last remark, if this is working with real files, try to use stubs or mocks.

Update:

Below is compete test file, with the separated tests

[TestClass]
public class UnitTest_Files
{
    private string expectedFile1;

    [TestMethod]
    public void SetFiles_Valid()
    {
        var fs = new Files();

        // 1st call to SetFiles. valid

        var expectedParentFolder = @"C:\work";
        var expectedFile1 = $@"{expectedParentFolder}\file1.txt";
        var expectedFile2 = $@"{expectedParentFolder}\file2.avi";
        var expectedFile3 = $@"{expectedParentFolder}\file3";

        fs.SetFiles(new string[]
            {
                expectedFile1,
                expectedFile2,
                expectedFile3
            });

        Assert.AreEqual(3, fs.FileList.Count);
        Assert.AreEqual(@"C:\work", fs.ParentFolder);
        Assert.AreEqual(expectedFile1, fs.FileList[0].Path);
        Assert.AreEqual(expectedFile2, fs.FileList[1].Path);
        Assert.AreEqual(expectedFile3, fs.FileList[2].Path);
    }

    [TestMethod]
    public void SetFiles_Specialchars_Valid()
    {
        // 2nd call to SetFiles. valid
        var expectedParentFolder = @"C:\muzică\Diabulus in Musica\poze\membri";
        var expectedfile1 = $@"{expectedParentFolder}\Zuberoa Aznárez.jpg";
        var expectedfile2 = $@"{expectedParentFolder}\Gorka Elso.jpg";

        var fs = new Files();
        fs.SetFiles(new string[]
            {
                expectedfile1,
                expectedfile2
            });

        Assert.AreEqual(expectedParentFolder, fs.ParentFolder);
        Assert.AreEqual(2, fs.FileList.Count);

        Assert.AreEqual(expectedFile1, fs.FileList[0].Path);
        Assert.AreEqual(expectedFile2, fs.FileList[1].Path);
    }

    [TestMethod]
    [ExpectedException(typeof(ArgumentException))]
    public void SetFiles_FilesNotInTheSameFolder_ExpectedException()
    {
        // 3rd call to SetFiles. Invalid

        // set to invalid structure (files not in same folder)
        // and expect throw
        // and no change

        var validParentFolder = @"c:\C:\muzică\folder1";
        var validFile1 = @"c:\C:\muzică\folder1\file1.txt";

        var invalidFile1 = @"C:\muzică\folder1\file2.txt";
        var invalidFile2 = @"C:\muzică\folder2\file2.txt";

        var fs = new Files();
        fs.SetFiles(new string[]
        {
            validFile1
        });

        fs.SetFiles(new string[]
            {
                invalidFile1,
                invalidFile2
            });

        // test that fs was not modified

        Assert.AreEqual(1, fs.FileList.Count);
        Assert.AreEqual(validParentFolder, fs.ParentFolder);

        Assert.AreEqual(validFile1, fs.FileList[0].Path);
    }
}


creating a concreate implemetation inside a method

This article is a great overview of Inversion of Control (IoC), and why it makes code easier to work with. But here's an example in the context of the code you posted. Imagine you are working on the SimpleDal class and decide that you have some configuration setting that you need to pass in. So now your constructor looks like this.

public class SimpleDal:IUnImplementedInterface
{
    public SimpleDal(string configSetting)
    {
        ...do something with it
    }

    ...

    public bool ReturnMeTrue(DataTable dt1){...}
}

This is not an issue in itself, except for now your line

IUnImplementedInterface dalInterface = new SimpleDAl();

needs to have that string in the constructor call (or you could add another constructor that called it with a default value). The point here is that in the end all your calling code really cares about is the IUnImplementedInterface.ReturnMeTrue() method. You "should" be able to replace SimpleDal with any other class that implements that interface (polymorphism). So, by deferring the creation of the IUnImplementedInterface instance to a level above the calling code or by using a factory method, you separate the concern of creating a dependency and using that dependency. The two most popular methods of achieving that are Dependency Injection, or Factory methods.


The two functions do not do the same thing so comparing their efficiency is not sensible.  A few comments on the code though (adding to those of @mjfgates)

first read_data_from_file:

path should be const
imgFD should be comapred <0 not <=0
check the return value of fstat instead of checking whether fsz is less than 0.
use perror to print failure reason after detecting open failure
fsz == 0 is valid and should return an empty buffer (ie return data and set *fsz1 to zero)
don't cast the return value of malloc
sizeof(char) is 1 by definition
check whether malloc succeeded.
you allocated fsz+1 bytes, presumably allowing for a terminator but didn't add one (\0)
check whether read succeeded.
check whether close succeeded (if pedantic).
why does data get brackets in return (data) and NULL not in return NULL?  Prefer the latter (no brackets).

second read_data_from_file:

pts should be char * or else you will get a compiler warning.  Are warnings enabled for you?
keywords (if, while, etc) preferred with a space - ie. if (...) instead of if(...)
if you are reading a normal file, the loop is not required. Just one read, as in the first version.
if you are reading something other than a file, then a loop is needed, but your loop is incorrect.  If the read call gave some data, you will get n = number read, if it got to end of file, you will get 0, if there was an error or if reading was interrupted before any daat was received you will get an error (-1) and errno will be set.  In the latter case you must work out whether there was an error or whether the call was interrupted  in which case you can loop.
if count is bigger than the actual file size, your loop never exits.
status is misnamed - it holds the number of bytes read so far.

main:

return EXIT_FAILURE or EXIT_SUCCESS
ok, it is a file you are reading so the loop in the second read_data_from_file is not necessary.
as before, don't cast malloc return and sizeof(char) is 1 by definition


Binary Reflected Gray Code generation recursively

Not Gray Code

The first big issue with this code that I see is naming things. Naming a list list adds absolutely no semantic information. You're duplicating what the "syntax" already tells you. n also doesn't tell us anything. Let's try the following:

public static List<String> generateGray(List<String> currentGrayWords, int targetBitLength) {

public static List<String> generateGrayV2(List<String> currentGrayWords, int wordsToGenerate) {

Note that the semantics of these two methods are not interchangeable. There's quite a few assumptions you make about how parameters are passed in. The first assumption is that you think that the "currentGrayWords" are a valid and complete BRGC (and non-empty). The second assumption is that n is a clean power of two in the first version and positive in both versions.

Check your assumptions. Consider the following invocations that look completely harmless but generate totally unintended results:

generateGray(Collections.emptyList(), 8); // returns empty list
generateGray(Arrays.asList("0", "01", "10", "1"), 4); // returns inconsistent gray code
generateGray(Arrays.asList("0", "1"), 5); // stackoverflow because recursion never terminates
generateGrayV2(Arrays.asList("000", "001", "011", "010", "110", "111", "101", "100"), -4);
// stackoverflow, because it never terminates

Gray Code

As it stands your code isn't even correct. Wikipedia tells me that a binary reflected gray code works by concatenating the original list with each element having 0 prepended and the reflected original list with each element having 1 prepended. That reflection is conspiciously absent in the code you present here.

As such the following is what your code creates:

genGray(Collections.singletonList(""), 8);
"0" "1"
"00" "01" "10" "11" // gray-code property violated
"000" "001" "010" "011" "100" "101" "110" "111"

The correct sequence would've been:

"0" "1"
"00" "01" "11" "10"
"000" "001" "011" "010" "110" "111" "101" "100"

Method

What this code is missing is a comprehensive test-suite that actually checks inputs that you didn't consider when first writing this code. You may want to not expose the List<String> as input parameter. It could (should?) be something internal to what the code does.

Try to break your code! If you don't succeed, try harder. Throw things at it that "nobody would ever think of doing". That way when somebody actually does, the code handles it gracefully.

With recursion it's especially important to think of the "termination condition" in your code. Make sure whatever is thrown into the method, it always terminates. Stack Overflows are not an acceptable result ...


You can select multiple counts from the table based on a condition using a CASE WHEN statement, and when writing SQL or something where formatting helps readability it's normally a good idea to use heredoc.

$getSQL = <<<SQL
SELECT
    COUNT(DISTINCT guid) AS allNum,
    COUNT(DISTINCT CASE WHEN chk='Y' THEN guid END) AS openNum
FROM `{$table}`
WHERE
    1=1
    {$addSQL}
SQL;

$listData = $sql->Select($getSQL);
$arr = $listData['data'][0];

$arr['closeNum'] = $arr['allNum'] - $arr['openNum'];

echo json_encode($arr);
exit;


Here are some things that may help you improve your code.

Use the required #includes

The code uses std::string which means that it should #include <string>.  It might compile on your machine because some other header includes that file, but you can't count on that, and it could change with the next compiler update.

Use only necessary #includes

The #include <stdexcept> and #include <memory> lines are not necessary and can be safely removed because nothing from those headers appears to be used here.

Avoid C-style macros

I'd advise not using C-style macros like the ones in this code, preferring either inline functions or even lambdas.  See ES.31 for details.

Consider thread safety

If multiple threads are using this code, there is likely to be a problem because the single shared instance of the std::vector is not protected by a mutex.  I would also recommend renaming the existing locked variable to something like complete or finished to better distinguish what it's doing.

Avoid singletons

A singleton is basically just another way to create global variables, and we don't like global variables much because they make code linkages much harder to see and understand.  See I.3 for more on that. In this case, since you already have two global variables, much of the complexity can easily be avoided by simply using a namespace instead of a class.  Here's one way to do that which eliminates the need for instance and CREATE_LEAK_DET:

namespace LeakDbg
{
    struct Pair
    {
        std::string name;
        void* ref;
        bool operator==( const Pair &other ) const { return ref == other.ref; }

    };
    static bool locked = false;
    static std::vector<Pair> stack;

    static void addRef(const std::string& nm, void* ptr)
    {
        stack.emplace_back(Pair{ nm, ptr });
    }
    static void remRef(void* ptr)
    {
        if( !LeakDbg::locked ){
            stack.erase(std::remove(stack.begin(), stack.end(), Pair{"",ptr}), stack.end());
        }
    }
    void checkLeakStack()
    {
        std::cout << "There are " << LeakDbg::stack.size() << " leaks ..." "\n";
        for ( LeakDbg::Pair pair : LeakDbg::stack) {
            std::cout << pair.name << " is leaked\n";
        }
    }
    static const bool registered{std::atexit( checkLeakStack ) == 0};
}

Consider the user

The current code requires that the user explicitly instruments the code, which seems a bit intrusive.  Here's an alternative approach the modifies things just slightly, using the Curiously Recurring Template Pattern, or CRTP for short.  First we isolate the leak detector bits into a templated class.

template <typename T>
struct LeakDetector {
    LeakDetector() {
        LeakDbg::addRef(typeid(T).name(), this);
    }
    ~LeakDetector() {
        LeakDbg::remRef(this);
    }
};

Now to use it is much simpler than before.  No ugly macros are required and we only need to add one simple thing to the declaration of the class to be monitored:

struct Test : public LeakDetector<Test>
{
    Test() {
    }
    ~Test() {
    }
};

An even less intrusive approach might be to override new and delete as outlined in this question.

Consider alternatives

Leak detection is a worthwhile thing to do, since many C++ bugs stem from that kind of error.  However, there are already a number of existing approaches to this, some of which may already be installed on your computer.  There is, for example the useful valgrind tool.  If you're using clang or gcc and have the libasan library installed, you can get a very nice runtime printout.  Just compile the code with

g++ -g -fsanitize=address myprogram.cpp -o myprogram

Then at runtime, a memory leak report might look like this:

There are 2 leaks ...
Cls is leaked
Cls is leaked

=================================================================
==71254==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 1 byte(s) in 1 object(s) allocated from:
    #0 0x7fe67c2c69d7 in operator new(unsigned long) (/lib64/libasan.so.5+0x10f9d7)
    #1 0x4057a6 in main /home/edward/test/memleak/src/main.cpp:97
    #2 0x7fe67bcbb1a2 in __libc_start_main (/lib64/libc.so.6+0x271a2)

Direct leak of 1 byte(s) in 1 object(s) allocated from:
    #0 0x7fe67c2c69d7 in operator new(unsigned long) (/lib64/libasan.so.5+0x10f9d7)
    #1 0x405774 in main /home/edward/test/memleak/src/main.cpp:95
    #2 0x7fe67bcbb1a2 in __libc_start_main (/lib64/libc.so.6+0x271a2)

SUMMARY: AddressSanitizer: 2 byte(s) leaked in 2 allocation(s).


Merge sort implementation and improvements

one of the things you can do is pass in the original array to merge and use that as result:

    return merge(sortedLeft, sortedRight, array);
}

and

private int[] merge(int[] first, int[] second, int[] result) {

    int posFirst = 0;
    int posSecond = 0;
    int resultPos = 0;

This reduces the space needed during the merge portion. Though at the cost of modifying the array the user put in.


Your code is fine, but I would suggest some small changes. Instead of head . transpose, I would use concatMap (take 1). This captures your intend to take the first (and therefore largest) number from each allPalindrome.

Next, I would use Int instead of (Integral a, Show a), since 999 * 999 is smaller than maxBound :: Int. Why? Because by default, Integer will be used for Integral types, if they were note specified. Therefore, you end up with maxPalindrome handled as a Integer, which is slower than Int.

And last, but not least, I would stop at 111, since 111 * 111 is a palindrome.

We end up with:

isPalindrome :: Show a => a -> Bool
isPalindrome n = l == reverse l
  where l = show n

maxPalindrome :: Int
maxPalindrome = maximum $ concatMap (take 1) $ allPalindrome <$> [999, 998 .. 111]
  where allPalindrome x = filter isPalindrome $ (x *) <$> [999, 998 .. x]

main :: IO ()
main = print maxPalindrome

Note that you should compile your code if you want to check its performance.

Alternatively, if you want to keep maxPalindrome's type, use :: Int:

maxPalindrome :: (Integral n, Show n) => n
maxPalindrome = maximum $ concatMap (take 1) $ allPalindrome <$> [999, 998 .. 111]
  where allPalindrome x = filter isPalindrome $ (x *) <$> [999, 998 .. x]

main :: IO ()
main = print (maxPalindrome :: Int)


Implementing a SQL like structure in Python, changing values

Column index lookups

If I understand your intentions correctly,
the _get_primary_rowval and _get_row_val_by_ident functions are used to find column indexes.
They iterate over the list of column definitions until they find a match.
Do the columns get reordered often? Or ever?
In a table-like structure, I would expect the columns to not change much,
and so the column indexes should not change either.
Rather than looping to get the indexes,
it would be better to store them in a dictionary,
so that lookups become \$O(1)\$ operations.

Consider for example this use of these methods:

def change_val(self, col_ident, new_val, primary_value):
    for n in self.rows:
        if n.contents[self._get_primary_rowval()] == primary_value:
            n.contents[self._get_row_val_by_ident(col_ident)] = new_val

For every row,
those _get methods are called,
every time looping over the list of columns.
This is very inefficient and an unusual thing to do.

I suggest to rework this logic:
use a dictionary to store the column indexes.
If the columns change, update the dictionary accordingly.

Use boolean values directly

Instead of this:

def check_type(self, applicant_object):
    if type(applicant_object) == self.arg_type:
        return True
    else:
        return False

You can do simply this:

def check_type(self, applicant_object):
    return type(applicant_object) == self.arg_type

Copying a list

Instead of this:

def __init__(self, contents):
    self.contents = []
    for n in contents:
        self.contents.append(n)

Use the .copy method:

self.contents = contents.copy()


Quickly reading the wikipedia link you provided, it sounds like your implementation slightly differ from the theory, especially the initialization part. I’m not expert, however, and will not try to dig it further. Just going for a style review:

Keep spaces consistent

As it currently stand, your spaces around = or , are not consistent and can be quite uncomfortable to read. Some calculus is also pretty dense and could gain some readability by using spaces.

Use functions

You could more easily test your script and figure why you don't get the results you're expecting if you split it in small functions. Reading files, indexing words, initializing computation and performing LDA seems to be the 4 tasks you do out of pretty-printing the results.

Be nice to the memory

Twice in your script, you use more than three times the space needed to store 'corpus.txt': corpus, dic and corpus.split() all contains each word of 'corpus.txt' with additional data. I don't know how big is the file but this is only one file, LDA allows for more (namely I to stay in your code context).

Since you're already reading through the content of the file twice, why not open the files twice and process them line by line each time to avoid overflooding the memory?

And talking about handling more files, your code should allow that more easily. Using functions with variable number of arguments is a way of doing it.

Constants

It is best to define them at the top of the file with an ALL_CAPS name. alpha and beta can qualify (they can be seen as variable since they are parameters of LDA), but more importantly the number of iteration is one of them.

Building data structures

To count elements in an iterable, you can use the collections.Counter class which is a subclass of dict:

words = Counter(data.split())

is more readable and understandable than

words = {}
for w in data.split():
    try:
        words[w] = words[w] + 1
    except KeyError:
        words[w] = 1

As such, it is often recommended to use list-comprehension rather than:

data = []
for elem in other_data:
    data.append(process(elem))

Incomplete improvement

(Based on Rev 2 of the question)

import numpy as np
from collections import Counter

ALPHA = 100
BETA = 5
ITERATIONS = 1000

def read_corpuses(*filenames):
    words = Counter()
    for corpus_file in filenames:
        with open(corpus_file) as corpus:
            words.update(word for line in corpus for word in line.split())
    return words

def compute_image(vocabulary, corpus_filename):
    with open(corpus_filename) as corpus:
        return [vocabulary.index(word) for line in corpus for word in line.split()]

def init_LDA(images, M, V):
    I = len(images)
    Na = np.zeros((I, M)) + ALPHA     # umber of words for each document, topic combo i.e 11, 12,13 -> 21,22,23 array.
    Nb = np.zeros(I) + M*ALPHA        # number of words in each image
    Nc = np.zeros((M, V)) + BETA      # word count of each topic and vocabulary, times the word is in topic M and is of vocab number 1,2,3, etc..
    Nd = np.zeros(M) + V*BETA         # number of words in each topic

    def inner(i, w):
        m = np.random.randint(0, M)
        Na[i, m] += 1
        Nb[i] += 1
        Nc[m, w-1] += 1
        Nd[m] += 1
        return m

    return Na, Nb, Nc, Nd, [[inner(i, w) for w in image] for i, image in enumerate(images)]

def LDA(topics, *filenames):
    words = read_corpuses(*filenames)
    vocabulary = words.keys()

    images = [compute_image(vocabulary, corpus) for corpus in filenames]

    Na, Nb, Nc, Nd, topic_of_words_per_image = init_LDA(images, topics, len(vocabulary))

    #Gibbs Sampling
    probabilities = np.zeros(topics)
    for _ in xrange(ITERATIONS):

        for i, image in enumerate(images):
            topic_per_word = topic_of_words_per_image[i]
            for n, w in enumerate(image):
                m = topic_per_word[n]

                Na[i, m] -= 1
                Nb[i] -= 1
                Nc[m, w-1] -= 1
                Nd[m] -= 1

                # computing topic probability
                probabilities[m] = Na[i, m] * Nc[m, w-1]/(Nb[i] * Nd[m])
                # choosing new topic based on this
                q = np.random.multinomial(1, probabilities/probabilities.sum()).argmax()
                # assigning word to topic
                topic_per_word[n] = q

                Na[i, q] += 1
                Nb[i] += 1
                Nc[q, w-1] += 1
                Nd[q] += 1

    distances = Nc/Nd[:, np.newaxis] #Words by Topic and printing
    return distances, vocabulary, words

if __name__ == '__main__':
    topics = 2
    #Add as many filenames as needed, like LDA(topics, 'corpus1.txt', 'corpus2.txt', 'corpus3.txt')
    distances, vocabulary, words_count = LDA(topics, 'corpus.txt')

    for topic in xrange(topics):
        for word_index in np.argsort(-distances[topic])[:20]:
            word = vocabulary[word_index]
            print "Topic", topic, word, distances[topic, word_index], words_count[word]

Things left to improve

You corpuses might contain words with punctuation and capitalization. You might want to split things according to string.punctuation and lowercase each word to avoid creating several keys for a single word. You may want to filter on the length of the string in doing so, or del words[''] afterward, depending on how you do things.
Naming is not optimal and hard to follow. Better take names of the variables from the LDA theory, like theta, phi instead of Na, Nc. Same goes for loop variables, some are not intuitive to be able to follow your implementation by looking at the theory from your wikipedia link.
As said at the beginning of the post, init_LDA might not compute the correct arrays.


How to refactor this importer to handle validation errors?

It can be as simple as :

  def initialize(path)
    @path = path
    @imported = []
    @errors = []
  end

  def extract sheet_name
    @file.default_sheet = sheet_name

    header = file.row 1
    2.upto(file.last_row) do |i|
      row = Hash[[header, file.row(i)].transpose]
      # row.delete "id"
      model = sheet_name.classify.constantize

      # this is the part that gets the job done.
      object = model.new(row)
      if object.save
        @imported << object
      else
        @rejected << object
      end

    end
  end

... this way you can iterate through @imported or @rejected at the end of the import process (to display errors, or perform additional tasks).

This code can also easily be adapted to only catch exceptions :

  def extract sheet_name
    @file.default_sheet = sheet_name

    header = file.row 1
    2.upto(file.last_row) do |i|
      row = Hash[[header, file.row(i)].transpose]
      # row.delete "id"
      object = sheet_name.classify.constantize
      object.create!(row)
    end
  rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid => error
    # rejected record for these errors can be accessed with :
    error.record
    # to resume processing, just :
    error.continue
  end


MD5 md55 = System.Security.Cryptography.MD5.Create();

Do yourself a favor, an stick using System.Security.Cryptography; at the top of the code file - then you can shorten this line to MD5 md55 = MD5.Create(); - but md55 is a bad name that doesn't mean anything. Perhaps engine, or hashProvider... anything but md55!

char[] words

That is a confusing name - characters aren't words, a better name for this array could be tokens, perhaps.

if (k == 0) return "not found";

What if the password happened to be "not found"? I think this is a situation where you would want to throw an exception of some sort, instead of tweaking the meaning of the return value.

Thread t = new Thread(() => ...

Starting your own thread is rarely a good idea. Look into the Task Parallel Library (TPL) in the System.Threading.Tasks namespace, and let the framework handle all the threading dirtiness for you. Also, starting a new thread incurs some overhead - if I'm not sticking a foot in my mouth here, using the TPL the framework determines if it's a good idea to start a new thread or to let code run sequentially... which may buy you some extra performance right here.

I would extract a method here, the anonymous method isn't buying you anything and contributes to make your click handler look like it's some "God button" that knows everything and does everything.

Thread.CurrentThread.Abort();

That's part of the threading nastiness you get to avoid with tasks. Aborting a thread is rarely a sane thing to do. I don't know much about multithreading, but this definitely rings a "no-no" bell.

        else
        {
        }

Dead code. Don't think, remove.

tajm.Text = (time.Elapsed.TotalSeconds).ToString();

You really need to work on naming. It's not going to make your code run any faster, but tajm doesn't mean anything to anyone maintaining your code. Be descriptive!


Don't abuse inner classes

Both classes DataComparision (beware of the typo here), and EntryData are inner classes of MallTimeWithMaximumPeople. However, those two classes do not access the fields of their enclosing instance. The Java tutorials have:

  Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.

In this case, consider:

Using a static nested class instead. This means declaring both classes static.
Using a top-level class for each of those.

Possible bug

The DataComparision comparator has a subtle corner-case. Currently, it relies on the return value of

data1.epochTime - data2.epochTime

to determine if data1 is greater than, equal to, or less than data2. However, consider the example case of data1.epochTime = Integer.MIN_VALUE and data2.epochTime = Integer.MAX_VALUE:

System.out.println(Integer.MIN_VALUE - Integer.MAX_VALUE); // prints 1

This actually prints a positive number due to integer overflow, so the code would consider the event data1 to be after data2. Of course, this supposes negative values are accepted, which in your case, is probably not wanted (although it is not validated).

Even if it doesn't concern you, it would be best to fix this by just calling Integer.compare instead of relying on the result of this subtraction.

Epoch time is a long

Unless you want your program to crash in 2038, store the number of seconds since the Epoch in a long, and not in an int. The maximum integer value, which is Integer.MAX_VALUE can only represent, in seconds, a date up to January 2038. If you want to be convinced of it, print the following:

System.out.println(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date(1000l * Integer.MAX_VALUE)));

Also, if on Java 8, consider using an Instant instead of directly dealing with long values.

Namings

The method getTimeWithMaximumPeople doesn't actually return the time with the maximum people, despite its name. It also returns additional information, namely, the next Epoch time in the data where that maximum was reached and the maximum count.

You have multiple approach to tackle this:

Only return the time, since this is what is strictly wanted.
Rename that method, and possibly wrap the 3 information in an object, instead of an array. Having an object would make it easier to code since the client can directly invoke descriptive methods like getMaximumCount() on it, instead of accessing a value in an array, which obscures the intent.

Other comments

data.size() == 0

is better expressed with data.isEmpty().
Use curly braces, even for small if / else statements.

if (currentData.getActionType() == ActionType.ENTRY)
    count += currentData.getCount();
else
    count -= currentData.getCount();

It is a best-practice to explicitely add the curly braces, as they prevent future possible issues.


Method header

Your method header can be improved, the generic type E is not necessary, it can instead be written as:

public static <CustomEnum extends Enum & HumanReadableEnum>
    List<String> toHumanReadableCollection(Class<CustomEnum> enumClass){

Type parameters should generally be one-character names, so this would be better as:

public static <E extends Enum & HumanReadableEnum>
    List<String> toHumanReadableCollection(Class<E> enumClass) {

Compiler warning

You're getting a compiler warning here:

String stringRepresentation = ((CustomEnum)value).getHumanReadable();

All you care about is the getHumanReadable method, which is in the HumanReadableEnum interface, so make that:

String stringRepresentation = ((HumanReadableEnum)value).getHumanReadable();

Naming and interface

HumanReadableEnum should instead be HumanReadable, there's no need to keep Enum in the name, there's no need to restrict the interface to only enums either.

Your questions

Reflection? Yes, this line of code is using reflection:

Enum[] values = enumClass.getEnumConstants();

Time complexity? \$O(n)\$, it is linear to the number of enum constants.

Java 8

In Java 8, you could replace your method with this:

List<String> list = Arrays.stream(StatusEnum.values())
   .map(HumanReadableEnum::getHumanReadable)
   .collect(Collectors.toList());

Or, as a general method, and also incorporating the earlier suggestions:

public static <E extends Enum & HumanReadable>
  List<String> toHumanReadableCollection(Class<E> enumClass) {
    Enum[] values = enumClass.getEnumConstants();
    return Arrays.stream(values)
       .map(e -> ((HumanReadable)e).getHumanReadable())
       .collect(Collectors.toList());
}

There's often a benefit of using Streams, I suggest you try to learn the Java 8 Stream API at some point.


If you are using GNU Make, you can simplify

prime: driver.o prime.o asm_io.o
    $(CC) $(CFLAGS) -oprime driver.o prime.o asm_io.o

to

prime: driver.o prime.o asm_io.o

and a generic target building rule

%: %.o
    $(CC) $(CFLAGS) -o $@ $?

Most of the other targets can be similarly simplified.

math : driver.o math.o asm_io.o

first : driver.o first.o asm_io.o

sub1 : driver.o sub1.o asm_io.o

The generic target building rule will take care of building the executables from the dependent .o files.


Comparing and pasting ranges of spreadsheet cells

My solution comes from this post where specifically the answer suggests a function to make an array. That seemed odd to me because it is a very simple matter to define an array from a range, but then the below occurred to me.

Dim myArray As Variant
myArray = Range("A1:A10")
Dim arrayToPaste As Variant
arrayToPaste = MatchArrays(myArray, etc)

Could also be written as:

Dim arrayToPaste As Variant
arrayToPaste = MatchArrays(MakeArray("A1:A10"), etc)

Simply by passing the function as an argument I have removed two additional lines of code and it is still clear what is happening.

Going a step further, we can also integrate the RangeToLastRow function in the OP and finish off the Sub.

Public Sub CompareArrays()

    Dim arrayToPaste As Variant
    arrayToPaste = MatchArrays( _
        MakeArray(RangeToLastRow(ThisWorkbook.Sheet1.Range("A1")), _
        MakeArray(RangeToLastRow(ThisWorkbook.Sheet1.Range("B1"))

    RangeToLastRow(ThisWorkbook.Sheet1.Range("C1")) = arrayToPaste

End Sub

As long as we use descriptive function names, it should still be clear what we are doing to the inputs without having to Dim a whole lot of extra variables.

Edit:

Another method is to move the functions out of the arguments and into the function that is called, for example:

Public Sub CompareArrays()

    Dim arrayToPaste As Variant
    arrayToPaste = MatchArrays( _
        RangeToLastRow(ThisWorkbook.Sheet1.Range("A1"), _
        RangeToLastRow(ThisWorkbook.Sheet1.Range("B1"))

    RangeToLastRow(ThisWorkbook.Sheet1.Range("C1")) = arrayToPaste

End Sub

Sub MatchArrays(ByRef MatchRange As Range, ByRef CompareRange As Range)

    matchArray = MakeArray(MatchRange)
    compareArray = MakeArray(CompareRange)

   '*do stuff '

End Sub


Searching the Foursquare API with Python

Named tuples

Business is nothing short of a tuple where each attribute is named. Rather than going through the verbosity of writing everything out, you can just make it a namedtuple:

Business = namedtuple('Business', 'name address rating rating_count checkin_count')

Managing resources

For make_request, the preferred way to handle resources in Python is to use a context manager. For urlopen, we have contextlib.closing:

def make_request(url):
    with closing(urlopen(url)) as response:
        return json.loads(response.read())

Do you need to wrap it in Request? Not sure that gives you anything.

String formatting

Prefer the format() syntax to the % syntax. That is:

'Hello, {}'.format(name)

is better than:

'Hello, %s' % name


Updating persons in database with newly created addresses

One of variants is to have PersonWithAddress subclass with created addressIp:

    persons
            .stream()
            .map(PersonWithAddress::new)
            .forEach(this::updateDbStatus);

You call updateDbStatus where check the address for null:

void updateDbStatus(PersonWithAddress personWithAddress) {
    if (personWithAddress.getAddressIp() != null) {
        // do the update
    }
}

Model classes like these ones:

class Person{
    Person(final Person original) {
        // copy constructor
    }
}

class PersonWithAddress extends Person {
    private final Integer addressIp;

    PersonWithAddress(final Person person) {
        super(person);
        this.addressIp = createAddress();
    }

    Integer getAddressIp() {
        return addressIp;
    }

    private Integer createAddress() {
        // have a logic to create an address
        return 0;
    }
}


Is there any problem to do that, or exists there any surer way to do that?

Yes, it's completely broken as in setupCamera you're assigning local variables and the fields remain untouched. There are no var parameters in Java. You'd actually need something allowing to return both camera and viewport. This is doable somehow, but too verbose for the little code you're trying to minimize.


Simplify javascript redirecting functions logic

The first thing I see which will cut the file at least in half is making a single redirectToPage function that redirects to a given page. You have many copies of the same basic function which currently looks like this

function functionName(params) {
    StartLoading();
    loading = 0;
    location.href = "someURL"
}

When you see a similar block of code like this being repeated multiple times, it's a good time to refactor, (it's debatable, but I would consider refactoring at 2 repetitions, and definitely refactor at 3). Your new function will be

function redirectToPage(url) {
    StartLoading();
    loading = false; // explained below
    location.href = url;
}

You can now erase most of that file, using this one more generic function and passing the urls as arguments.

You are also using loading as a boolean sometimes, and sometimes as an integer. Your code will be easier to reason about if you stick to one. It looks like you're only using loading as a boolean, so I changed loading = 0 to loading = false. You can make this change throughout the rest of the file as well.

This may be enough changes for you. If not, there are a few other functions that you have that redirect to a page but with slightly different functionality, such as calling AbortPushUpdates or not setting the loading variable. You can extend your new redirectToPage function to handle these cases like so

/**
 * Call this function giving the url to redirect to, and other options
 */
function redirectToPage(url, options) {
   if (!options || !options.hasOwnProperty('startLoading') || options.startLoading == true) {
     // default is to run StartLoading()
     StartLoading();
   }

   if (options && options.hasOwnProperty('abortPushUpdates') && options.abortPushUpdates) {
     // default is to NOT call AbortPushUpdates
     AbortPushUpdates();
   }

   if (!options || !options.hasOwnProperty('setLoading') || options.setLoading == true) {
     // default is to set the loading variable
     loading = false;
   }

   // Always redirect
   location.href = url;
 }

You can now use this function in any of the following ways

redirectToPage('/Administration/AddAccount/' + accountID);
redirectToPage('/Administration/AddCompany', {setLoading: false, startLoading: false})
redirectToPage('/Home/SelectEquipmentCollection', {abortPushUpdates: true})

Good luck with your refactor, and let me know if you have any follow up questions!


Extracting site visit information from a REST API call, including addresses from a MySQL database

Some thoughts:

I honestly don't see how this code "works" as shown.  There are significant problems in your code as I will detail below.
Don't use mysql_* functions.  They have been deprecated in PHP for several years now (since PHP 5.5 in June 2013) and are now totally removed from PHP 7. Consider mysqli or PDO (mysqli being the most similar to mysql in syntax)
It is not clear why you have so many loops here. This will slow down your code if you have large result sets you are working with.  There doesn't seem to be any reason that you couldn't build your SQL query in that first foreach loop after the curl call.
There seems to be a significant mismatch between the variables set in the first foreach loop after the curl call and the foreach loop where you do your DB queries.  There are some variables in the first loop that are not used in the second (so why set them at all?), and there are variable references in the second loop that aren't set in the first.  So either there is more code here that you are not showing, or there is no way this code actually works.
You have very minimal code comments, so it makes it really hard to understand what your intent is in large areas of the code.

Below, I have made some more specific code comments within multi-line comments

<?php
/*
Does your code absolutely need this to run?
If so, this should probably be a require
*/
include 'schedule.php';

/*
After this line you do nothing to check that curl_init() was successful
and continue operationg assuming happy path. What if init fails?
*/
$curl = curl_init();

/*
This could be contributing to your performance problem as you are making these
requests in a loop.  You might consider curl_multi_exec() to make
requests in parallel
*/
foreach ($onsites as $value){

/*
Indent so it is clear this all happens inside above loop
*/
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://portal.-----.com/v4_6_release/apis/3.0/service/tickets?conditions=id%3D$value",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "accept: application/json",
        "authorization: -----",
        "cache-control: no-cache",
        "postman-token: -----",
        "x-cw-usertype: integrator"
    )
));

$response = curl_exec($curl);
$err      = curl_error($curl);

/*
If this is script that is not exposed to users echoing out errors might be OK.
If this is user-facing, you probably want to log errors and give
user-friendly error messaging
*/
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    $response = json_decode($response, true);

/*
There is no way your application is working the way you expect as
you are overwriting most of these variables with each loop iteration
without actually doing anything with them first
*/
    foreach ($response as $ticket) {
        $ticket_number = $ticket['id'];
        $summary[]       = $ticket['summary'];
        $company[]       = $ticket['company']['name'];
        $site[]          = $ticket['siteName'];
        $addressLine1  = str_replace('# D', '#D', $ticket['addressLine1']);
        $addressLine2  = $ticket['addressLine2'];
        $city          = $ticket['city'];
        $state         = $ticket['stateIdentifier'];
        $zip           = $ticket['zip'];
        $contact[]       = $ticket['contact']['name'];
        $resources     = $ticket['resources'];
        if(empty($addressLine2)) {
            $full_address[]   = "$addressLine1, $city, $state, $zip, USA";
        } else {
            $full_address[]   = "$addressLine1, $addressLine2, $city, $state, $zip, USA";
        }
    }
}
}
/*
Don't use mysql_* functions
*/
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("scheduler") or die(mysql_error());

/*
Are you really trying to do an assignment here or a comparison?
You are actually now doing an assignment which is then evaluated
for it's truthiness.
If you are trying to do a comparison, you need to actually use
== or ===
I am not sure why you would be comparing an array ($onsites) against
a single string value ($ticket_number) though.
*/
if ($ticket_number = $onsites) {
/*
Indent everything inside braces
*/
$current_onsites = array();
$i = 0;

/*
Why all the error suppression here?  That is REALLY bad coding practice.
Again since you are overwriting variables in loop above, there is no way
this is working correctly if you have more than one ticket in response.
Querying in a loop should usually be a red flag. You are usually better
off trying to get all the data you need in a single query if possible,
which it appears to be in this case. You could actually build array
of all values you are trying to get from the database and have a
single query such as:
SELECT company, lat, lng FROM xy
WHERE company IN ('company1', 'company2', ...)
*/
for ($i = 0; $i <= count($ticket_number); $i++) {
    @$current_onsites[$i]['id'] = $ticket_number[$i];
    @$current_onsites[$i]['text'] = $summary[$i];
    @$current_onsites[$i]['location'] = $location[$i];
    @$current_onsites[$i]['company'] = $company[$i];
    @$current_onsites[$i]['site'] = $site[$i];
    @$current_onsites[$i]['location'] = $full_address[$i];
    @$current_onsites[$i]['contact'] = $contact[$i];
    @$current_onsites[$i]['start_date'] = date('Y-m-d H:i:s', strtotime($startDate[$i]));
    @$current_onsites[$i]['end_date'] = date('Y-m-d H:i:s', strtotime($endDate[$i]));
    @$current_onsites[$i]['technician'] = $technician[$i];
    @$current_onsites[$i]['hours'] = $hours[$i];
    @$current_onsites[$i]['status'] = $status[$i];
    @$current_onsites[$i]['done'] = $doneFlag[$i];
    @$current_onsites[$i]['ownerFlag'] = $ownerFlag[$i];
    // Retrieve all the data from the db table
/*
Your LIKE is meaningless here since you have no wildcard.  Just use =
or IN if you take above advice and remove query from the loop.
Don't use SELECT *, it is really bad coding habit.  Just specify
the fields you actually need - in this case 'lat' and 'lng'.
*/
    $result = mysql_query('SELECT * FROM xy WHERE company LIKE "'.@$current_onsites[$i]['company'].'";')
        or die(mysql_error());
    // store the record of the "example" table into $row
    $row = mysql_fetch_array( $result );
    @$current_onsites[$i]['lat'] = $row['lat'];
    @$current_onsites[$i]['lng'] = $row['lng'];
}

print "<pre>";
print_r ($current_onsites);
print "</pre>";

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($current_onsites));
fclose($fp);
}
/*
You should close this resource right after you are done working with it.
*/
curl_close($curl);

?>

If you have any desire to leverage curl_multi_exec, feel free to use this simple REST client I have written (either as is, or as inspiration for your own code) - https://github.com/mikecbrant/php-rest-client


Despite already having accepted an answer, I'd like to point out a different way to approach this.

Since you are building the board with JavaScript I'm assuming that you want to modify the content of the board dynamically. (If not then the question would be why you are using JavaScript and not a server-side generation).

In that case it could make sense to separate generation and filling the board. That way you could simply exchange each method without affecting the other.

For generation you could continue to use your solution just with empty or default values, or use DOM generation:

var rowCount = 6;
var colCount = 10;
var board = document.createElement('table');
for (var r = 0; r < rowCount; r++) {
  var row = board.insertRow();
  for (var c = 0; c < colCount; c++) {
    row.insertCell();
  }
}

Or simply use static HTML.

And then you write a function that sets the value of a cell which will work no matter how you created the board. Something like:

function setBoardValue(board, x, y, value) {
   board.rows(y).cells(x).innerHTML = value;
}

And then you can loop over your "map" in anyway you like and call it:

var map="005000200000000008000600000006000700000040000000500030400000".split("");

for (var i=0;i<len;i++){
  setBoardValue(board, i % colCount, Math.floor(i / rowCount), map[i] != 0 ? map[i] : "&nbsp;");
}

In the end this solution if technically slower that your solution, but usually not in an amount that would be noticeable by the user and you have an advantage with the separation of the concerns.


Type signatures

Good job on providing all type signatures. Unfortunately, you forgot one: enter. Always include type signatures on top-level functions.

Remove unused imports

You use neither Data.List, nor System.IO.

Prefer character comparison instead of ord x > n

In getDigit, you compare characters by their ord values. That's not easy on the eye. It's a lot easier to read if you just compare the letter with characters:

getDigit :: Char -> Int
getDigit letter
    | letter >= 'a' && letter <= 'c' = 2
    | letter <= 'f' = 3
    | letter <= 'i' = 4
    | letter <= 'l' = 5
    | letter <= 'o' = 6
    | letter <= 's' = 7
    | letter <= 'v' = 8
    | letter <= 'z' = 9
    | otherwise = 0

There are other ways to write getDigit, but I they differ on personal preference only.

Use the standard library

stripDashes is filter (/= '-') in disguise:

stripDashes xs = [ x | x <- xs, not (elem x  "-")]
               = [ x | x <- xs, x /= '-']
               = filter (/= '-') xs

Therefore use filter instead of a list comprehension:

stripDashes :: String -> String
stripDashes = filter (/= '-')

By the way not (elem x y) is notElem x y.

Prefer local bindings instead of long lines

This is personal preference, but I think that

convertLetters :: String -> String
convertLetters xs = map toDigit xs
  where
    toDigit x
     | isNumber x = x
     | otherwise  = intToDigit $ getDigit $ toLower x

is easier to read.

Use hlint to get rid of redundant brackets

You have a lot of redundant brackets, which can make the code hard to read. hlint can report them to you. It also reports the not (elem x y) == notElem x y hint, by the way.

Prefer pure functions if possible

You have enter for a complete transformation. It would be great if there was a non-IO variant too, e.g.

convert :: String -> String
convert = insertDashes . convertLetters . stripDashes

That way you can export enter, conver and stripDashes.

Use splitAt instead of take/drop combinations

Finally, we have a look at insertDashes. First of all, let's write bindings:

insertDashes :: String -> String
insertDashes xs = group1 ++ ['-'] ++ group2 ++ ['-'] ++ group3 ++ ['-'] ++ group4
   where
      group1 = take 1 xs
      group2 = take 3 (drop 1 xs)
      group3 = take 3 (drop 4 xs)
      group4 = take 4 (drop 7 xs)

That looks like a perfect job for splitAt:

-- do not include this function in your code, it's part of the Prelude
splitAt n xs = (take n xs, drop n xs)

However, if we were to rewrite insertDashes with splitAt, it wouldn't get any better immediately:

import Data.List (intercalate)

insertDashes :: String -> String
insertDashes xs = group1 ++ ['-'] ++ group2 ++ ['-'] ++ group3 ++ ['-'] ++ group4
   where
      (group1,ys1) = splitAt 1 xs
      (group2,ys2) = splitAt 3 ys1
      (group3,ys3) = splitAt 3 ys2
      (group4,_  ) = splitAt 4 ys3

Ugh. Not really any better. So instead let's write another function:

splitAtNs :: [Int] -> [a] -> [[a]]
splitAtNs []     xs = [xs]
splitAtNs (n:ns) xs = as : splitAtNs ns bs
  where (as, bs) = splitAt n xs

Now  insertDashes is

insertDashes :: String -> String
insertDashes xs = group1 ++ ['-'] ++ group2 ++ ['-'] ++ group3 ++ ['-'] ++ group4
   where
      (group1:group2:group3:group4:_) = splitAtNs [1,3,3,4] xs

Which almost looks fine. There is one more improvement, though. The function intercalate from Data.List brings it down to a single line:

insertDashes :: String -> String
insertDashes = intercalate "-" . take 4 . splitAtNs [1,3,3,4]


First of all, splitting the spliterator only makes sense, if both the remainder of the current spliterator and the returned spliterator still have work pending. In your case, this is (almost) not true, as you operate on the complete batches and the current spliterator at most returns its current batch after split. Thus, I'd replace the trySplit() with a simple return null. This also addresses any potential concurrency issues (which I have not looked into in depth.)

Characteristics basically tell the caller the - for lack of a better word - characteristics of your spliterator. :-)

I think for the batch approach you take, ORDERED, NONNULL, IMMUTABLE should be OK.

Apart from that, for more direct utility, I'd rather take the approach not to iterate over the batches, but over their contents, i.e. create a Spliterator which gets initialized with the first ObjectListing  batch and then transparently goes through the underlying collections element-wise and fetches the next batch as needed. This would eliminate the need to flatMap on the result stream and feel more natural for a streaming approach. (In fact, this sounds so useful that I'd like to have it :-))


Constant string literals should be declared as such (const):

const char *filename_r = "xxx.in";
const char *filename_w = "xxx.out";

If you don't do that then you have a char * pointing to a string literal which the compiler will probably put in a read only data segment. Should you ever try to modify it (via the non-const char pointer) you'll run into undefined behaviour (most likely it will crash your program).
Your helper methods should in general not terminate the program (you call exit() in quite a few places). Their return value should indicate that they could not perform the operation they were supposed to leaving it to the caller (in your case main) to take appropriate action (like terminating early).
You should alway places braces around blocks, even one-liners. Things like this:

if(count > MAX || count < MIN)
exit(1); //General application error

are really confusing as it reads like exit() is executed unconditionally and if you ever add another statement to it then you'll run into trouble. Braces make it crystal clear what's intended:

if (count > MAX || count < MIN)
{
    exit(1); //General application error
}

This happens in quite a few places. Readability beats brevity anytime.
You use unsigned short for the count which means it will be unsigned 16bit on most platforms. So if the input sequence is descending like 100000, 99999, 99998, ..., 1 with more than 65535 elements then your count variable will overflow.
Don't leave vowels out of names for functions or variables: chck_tall vs check_tall. If you leave them out and they do not shorten the name sufficiently then why did you leave them out. And if they shorten the name sufficiently then it's likely it will become too garbled to read properly. So in either case leaving them out is not a wise choice.
Your array holds int yet when you check for the max in chck_tall your temporary variables are short which can lead to truncation. Your compiler should have warned you about it. Do not ignore compiler warnings. In fact it is not uncommon in production code to run with an option which treats warnings as errors (most compilers do offer such an option).
Not sure why you think you need to make the loop variable register:

for (register int i = size - 1; i >= 0; i--)

register is just a hint to the compiler which is free to ignore it anyway. Typically you should only use it in specific circumstances when you know if and why it is required. Otherwise it's just adding noise.