List files based on changes I am new to programming and need input on how I could've written something better. Not coding on daily basis. The task was to write a script in python, bash or anything. So I mixed python with bash commands using python module os.systems. Some friends recommended lists but I wanted the output to be similar as the example in this task:

Write a script (Bash, Python etc.) that checks for files - in directory X - that have not been
modified in (older than) the last Y days.
The directory and days should be passed to the script as mandatory arguments.
The script shall only look for files in directory X,
not in sub directories. You may assume that none of the filenames contain newlines.
The output of the script should print the file names, and the time for
when the file was last modified, sorted by modification time:
./README.txt                      2019-05-09  17:19:53.193771720  +0200
./README.txt.gpg                  2019-05-09  17:20:21.331833720  +0200
./migratemost-master.zip          2019-05-20  12:52:34.867119547  +0200
./INC177759                       2019-05-23  13:29:47.014557386  +0200

Include a help option, so that if '-h' or '--help' is passed as an optional
argument, a summary of what the program does is printed to stdout.
Also try to handle user errors so the script exits gracefully with an error
message upon incorrect - or missing - input.

My solution that I need help to refactor/improve peer review on:
import os
import sys

days = raw_input("Please enter days: ")
if days.isdigit():
    print "You entered:", days
else:
    sys.exit("Exiting the program, wrong data type.")

dir = raw_input("Please enter path: ")
print "You entered:", dir

stuff_in_string = "find {} -type f -mtime -{}".format(dir, days)
print stuff_in_string

print(os.system('{} | xargs -d \'\n\' ls -lth --full-time'.format(stuff_in_string)))

The output:
$ python main.py
Please enter days: asdf
Exiting the program, wrong data type.
$
$ python main.py
Please enter days: 365
You entered: 365
Please enter path: .
You entered: .
find . -type f -mtime -365
-rw-r--r--. 1 root root 413 2020-09-21 16:43:48.608029286 +0200 ./main.py
-rw-r--r--. 1 root root   0 2020-09-21 09:36:17.072137720 +0200 ./file2.csv
-rw-r--r--. 1 root root   0 2020-09-21 09:35:28.502502950 +0200 ./file1.txt
0
$
$ python main.py
Please enter days: 9999
You entered: 9999
Please enter path: .
You entered: .
find . -type f -mtime -9999
-rw-r--r--. 1 root root 413 2020-09-21 16:43:48.608029286 +0200 ./main.py
-rw-r--r--. 1 root root   0 2020-09-21 09:36:17.072137720 +0200 ./file2.csv
-rw-r--r--. 1 root root   0 2020-09-21 09:35:28.502502950 +0200 ./file1.txt
-rw-r--r--. 1 root root   0 2012-01-01 00:00:00.000000000 +0100 ./goldenfile.xls
0

Don't mix programming language
Try to avoid mixing different languages in one program. You are creating a Frankenstein monster this way, that depends on you having to deal with multiple languages, their interaction with each other, and now your computer needs to have the necessary interpreters and libraries installed for both languages. It is also quite expensive to call os.system(), so performance suffers as well.
For the rest of the review I'm assuming you want to want to continue using Python.
Make sure your script works with Python 3
Python version 2 is obsolete, you should move to Python 3. The most important change in your script though is adding parentheses to the print-statements.
Ensure you implement your program according to the requirements
The requirements you mention say that the directory and number of days should be passed as arguments. That means you should not ask for them while the program is running. The easiest way to parse command line arguments is to use the argparse module. As a bonus, this will also automatically create a help text that will be printed when you specify the --help option on the command line.
The requirements also say you have to sort the output based on modification time. Note that your original shell command did not guarantee that the output was correctly sorted: xargs might call ls multiple times, each time with only part of the input.
Have Python produce a list of files
You can use os.listdir() to get a list of all the elements in a directory. That list might also contain the names of subdirectories, but it will not recurse into them. Use os.stat() on each element to check if it is a file or a directory, and also to get the modification time.
Add a shebang line to the top of your script
Add a shebang line to the top, so you can call your script without having to call the Python interpreter explicitly. This line can look like:
#!/usr/bin/python3

I also recommend you remove the .py extension from your script, as it will be a stand-alone script, and for the user it shouldn't matter if it's writting in Python or any other language. This way, along with the argument parsing, you should be able to call your script like so:
$ ./main . 365
./README.txt                      2019-05-09  17:19:53.193771720  +0200
./README.txt.gpg                  2019-05-09  17:20:21.331833720  +0200
./migratemost-master.zip          2019-05-20  12:52:34.867119547  +0200
./INC177759                       2019-05-23  13:29:47.014557386  +0200

Of course, the name main doesn't really tell what your script does. Give it a better name, like list_recent_files.


Validate parameters within a range Function to use several blocks of if:elif:else: that all take slightly different conditional statements.  I'm trying to format integers into a 2 digit string, adding a leading 0 for single digits.  It is working great, but there has to be DRY way of doing the same thing.  Also, the timezone formatting is a bit of a mess.  After struggling to come up with a more elegant solution, I just went with what was obvious and working.

def rfc_3339_str(minutes = 0, year = 1999, month = 1, date = 1, secs = 0, time_zone = 0):
    '''Takes minutes and builds RFC 3339 timeDate string.
        yyyy-mm-ddTHH:MM:ss[.mmm][+/-HH:MM].  Does not support milliseconds.
        All params optional.  Timezone format is number in range
        [-12:12] (hours only).  All numbers expect integers.
        Minutes > 1439 (23 hours 59 minutes) wrap around to zero,.
        Date defaults to 1/1/1999.  Supported years 1000-2035 CE.  Date allows
        range 0-31 inclusive for all months.  Negative times are not supported.
        Incorrect params return error description'''
    plus = '+'
    minus = '-'
    date_time_split = 'T'
    date_split = '-'
    time_split = ':'
    time_zone_mins = ':00'
    MAX_MINUTES = 1440
    yyyy = None
    mm = None
    dd = None
    HH = None
    MM = None
    SS = None
    zone_sign = plus
    zz = None

    #validate inputs
    if 1000 > year > 2035:
        return 'year_out_of_range'
    else:
        yyyy = str(year)

    if month in range(1,10):
        mm = '0' + str(month)
    elif month in range(10,13):
        mm = str(month)
    else:
        return 'month_out_of_range'

    if date in range(1, 10):
        dd = '0' + str(date)
    elif date in range(10, 32):
        dd = str(date)
    else:
        return 'date_out_of_range'

    if minutes < 0:
        return 'minutes_out_of_range'
    while minutes > MAX_MINUTES:
        minutes = minutes - MAX_MINUTES
    hours_int = int(minutes / 60)
    mins_int = int(minutes % 60)

    if hours_int in range(0,10):
        HH = '0' + str(hours_int)
    elif hours_int in range(10, 100):
        HH = str(hours_int)
    else:
        return 'hours_out_of_range'

    if mins_int in range(0,10):
        MM = '0' + str(mins_int)
    elif mins_int in range(10,60):
        MM = str(mins_int)
    else:
        return 'minutes_out_of_range'

    if secs in range(0, 10):
        ss = '0' + str(secs)
    elif secs in range(10,60):
        ss = str(secs)
    else:
        return 'seconds_out_of_range'

    small = False
    positive = False
    if time_zone in range(-9, 10):
        small = True
    if time_zone in range(-12,0):
        positive = False
    if time_zone in range(0, 13):
        positive = True

    if small:
        zz = '0'
    if positive:
        zz = plus + zz + str(time_zone)
    if not positive:
        zz = minus + zz + str(abs(time_zone))
    else:
        zz = plus + '00'

    print(yyyy + date_split + mm + date_split + dd +
        date_time_split + HH + time_split +
        MM + time_split + ss +
        zz + time_zone_mins)

First off, I would like to point you to the time module which has functions that are similar to what you want to accomplish.

Now as for DRYing your code up a bit. You were right to notice that you have blocks of:

if var in range1:
    func1(var)
elif var in range2:
    func2(var)
else:
    return 'blah_out_of_range'

I don't agree with your else block code. You are returning an error statement, which should actually be an exception such as a ValueError like so:

raise ValueError("blah out of range")

This is more readable, and more Pythonic.

Back to the code block, if we take each of the variant parts as arguments into a super function we get:

def process(var, cond1, func1, cond2, final):
    # ugly code here

This is trying to emulate the functional programming style of Lisp, Scheme, Racket and etc, which something that is generally avoided in Python code due to the final unreadability of the code.

Let's think of something else, such as checking all the conditions ahead of time, before doing any processing. This speeds up execution for failed inputs (as any failing input would fail as fast as possible), and simplifies the logic.

This would look something like this:

if year not in range(1001, 2035):
    raise ValueError("year not in range")
if month not in range(1, 13):
    raise ValueError("month not in range")

and so on. This can also be done via assert statements of the unittest module for even more compact code.

Then afterwards you will have blocks of the form:

if cond1:
    func1
else:
    func2

This is easily wrapped into a ternary operator:

func1 if cond1 else func2

Which will eliminate a lot of lines from your code.


Returning a pseudo-random Gaussian number Is there any ways I can write redundant-less code without this infinite loop? I have also tried putting the conditions and the generating number, but since it has two conditions, the output number will be different.

private static final int PERCENT_97 = 3;
/**
 * Returns returns a pseudo-random Gaussium number. Forumla:
 * {@code (RanGassium * 3) + mean }
 *
 * @param mean
 *            mean of returning value
 * @param min
 *            min bound
 * @param max
 *            max bound
 * @return a pseduo-random Gaussium that is close to the mean.
 */
public static double getRandomGaussium(double mean, double min, double max) {
    double returningNumber = 0;
    double rangeMean=(max-min)/2;
    while (true) {
        returningNumber = (generator.nextGaussian() * rangeMean/PERCENT_97) + mean;
        if (returningNumber > min && returningNumber < max) {
            break;
        }
    }
    return returningNumber;
}

A do while would be an equivalent construct. I don't really think either is more or less preferable, but is an alternative that avoids the appearance of an infinite loop:

do {
    returningNumber = (generator.nextGaussian() * rangeMean/PERCENT_97) + mean;
} while (returningNumber < min || returningNumber > max);
return returningNumber;

That still leaves open a possibility of an eternal loop, though. You should probably at least validate your params to guard against that (eg., a min of 1 and max of 1 would run forever). You may also want to put an iteration counter to give up and throw an exception after so many iterations. At that point, a for loop with an early return if one is found may be a better choice than stuffing it all into the where or if conditionals:

for (int i = 0; i < MAX_TRIES; i++) {
    returningNumber = (generator.nextGaussian() * rangeMean/PERCENT_97) + mean;
    if (returningNumber > min && returningNumber < max) {
        return returningNumber;
    }
}
throw new IGiveUpException();


Data structure (Map-like implementation) in C++ I wrote this code to implement a data structure in C++. It works perfectly, however, I am looking to improve its efficiency. Also, I'm just getting started in C++ so using code to explain your suggestions would be incredibly helpful.

Here is the class that implements the data structure:

class key_value_sequences {
public:
// YOU SHOULD USE C++ CONTAINERS TO AVOID RAW POINTERS
// IF YOU DECIDE TO USE POINTERS, MAKE SURE THAT YOU MANAGE MEMORY PROPERLY

// IMPLEMENT ME: SHOULD RETURN SIZE OF A SEQUENCE FOR GIVEN KEY
// IF NO SEQUENCE EXISTS FOR A GIVEN KEY RETURN -1
int size(int key) const
{
    for( int i=0; i<pairs.size(); i++)
    {
        if( pairs[i][0] == key )
        {
            return pairs[i].size() - 1;
        }
    }
    return -1;
}

// IMPLEMENT ME: SHOULD RETURN POINTER TO A SEQUENCE FOR GIVEN KEY
// IF NO SEQUENCE EXISTS FOR A GIVEN KEY RETURN nullptr
const int* data(int key) const
{
    int length = size(key);

    if( length == -1 )
    return nullptr;

    for( int i=0; i<pairs.size(); i++)
    {
        if( pairs[i][0] == key )
        {
        return &pairs[i][1];
        }
    }
    return nullptr;
}

// IMPLEMENT ME: INSERT VALUE INTO A SEQUENCE IDENTIFIED BY GIVEN KEY
void insert(int key, int value)
{
    bool found = false;
    int pos = -1;

    for( int i=0; i<pairs.size(); i++)
    {
        if( pairs[i][0] == key )
        {
            found = true;
            pos = i;
        }
    }

    // insert if found in old vector,
    // else make a new vector

    if( found )
    {
        pairs[pos].push_back(value);
    }
    else
    {
        // insert new value set for the key
        std::vector<int> v;
        v.push_back(key);
        v.push_back(value);
        pairs.push_back(v);
    }
}
private:

// list is stored as a vector and
std::vector< std::vector<int> > pairs;

}; // class key_value_sequences

You should implement a private function find, that returns the index of a key

const int find(const int key) const
{
    for (unsigned i=0; i < pairs.size(); ++i)
    {
        if(pairs[i][0] == key )
        {
            return i;
        }
    }
    return -1;
}

This should simplify your functions considerably

const int size(const int key) const
{
    const int index = find(key);
    if (index == -1)
        return -1;
    return pairs[index].size() - 1;
}

const int* data(const int key) const
{
    const int index = find(key);

    if( index == -1 )
        return nullptr;
    return &pairs[index][1];
}

void insert(const int key, const int value)
{
    const int index = find(key);

    if( index != -1 )
    {
        pairs[index].push_back(value);
    }
    else
    {
        std::vector<int> v = {key, value};
        pairs.push_back(v);
    }
}

Generally i would strongly recommend to split keys and values. One possibility would be to create a std::pair

std::vector<std::pair<int, std::vector<int>>> pairs;

Otherwise you could split it into a map and a vector.


Composing an HTML email body in PHP swiftmailer The following code is what I'm using to send a password reset email. The specific part I'm referring to is how I'm setting $message. Would there be a cleaner way to do this or is this about as clean as you can get?

/**
 * Attempt to send reset link
 * @return bool True if success, false if not
 */
public function try() {
    // Update users email hash
    $this->_updateResetHash();
    $user = $this->_grabUser();

    $resetLink = $_SERVER["HTTP_ORIGIN"] . "/reset/" . $this->_hash . "/" . $user['uid'];

    $message = "Hello, " . ucfirst($user["first_name"]) . ",

";
    $message .= "We received a request to reset your password.

";
    $message .= "Please click here to reset your password
";
    $message .= "
If you did not make this request you do not need to worry. The only way your password can be reset is through the email that is on the account. Unless someone has taken control of you email, your account is safe and no one except you can gain access.
";

    // If email is sent
    if (!Mail::send("Password reset link", $message, ["no-reply@.com" => "No-Reply@"], $this->_email, 'text/html')) {
        return false;
    }

    return true;
}

Also, I'm not too sure how or if it exists but I heard somewhere that Twig / Slim, which I'm using, have a way of using templates for swiftmailer.

As you're using the Twig template engine already, I would recommend to use it for your email-templates as well. It will have all the advantages like:

easy to maintain
easy to localize
template and its content is separated from your logic
all templates are in one place

Symfony has a manual, how to use Twig together with Swiftmailer. This will work also without the Symfony framework.

In your case you can simply store the rendered template in $message and pass it on to Mail::send():

$message = $twig->renderView(
    'resources/views/emails/password_reset.html.twig', [
    'first_name' => $user["first_name"],
    'reset_link' => $resetLink,
]);

In your template you have all the advantages and simplicity of Twig:

Hello {{ first_name }},

Please click here to reset your password

You could take it one step further and include the subject as well in the template:

{% if true == get_subject %}
    {% spaceless %}
        Password reset link
    {% endspaceless %}
{% else %}
    Hello {{ first_name }}
{% endif %}

You need spaceless in this case for the subject, so that Twig will remove all whitespaces, tabs etc. before and after the subject.


animate button presses in a sequence (tkinter) I am attempting to animate the series of button presses in the simon game I am creating with tkinter. The animate method is called for each button that needs to be pressed in the series. It currently presses all of the buttons at the same time rather than in a series as it is meant to.

from tkinter import *
from random import choice
root = Tk()
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
frame = Frame(root)
frame.grid(row=0, column=0, sticky=N+E+S+W)

def animate(btn):
    btn.config(relief=SUNKEN, state=ACTIVE)
    btn.after(200, lambda: btn.config(relief=RAISED, state=NORMAL))

class Game(object):
    def __init__(self):
        self.colors = ["green", "red", "yellow", "blue"]
        self.i = 0
        self.round = 1
        self.moves = []
        self.cpu_moves = []

        self.btns = []
        for row in range(2):
            Grid.rowconfigure(frame, row, weight=1)
            for col in range(2):
                Grid.columnconfigure(frame, col, weight=1)
                btn = Button(frame, width=150, height=150, bg=self.colors[0],
                             command=lambda b=self.i: self.user_select(b))
                btn.grid(row=row, column=col)
                self.btns.append(btn)
                self.colors.remove(self.colors[0])
                self.i += 1

    def user_select(self, btn):
        self.moves.append(btn)
        print(self.moves)
        print(self.cpu_moves)
        if self.moves == self.cpu_moves:
            self.clear_user_moves()
            self.round += 1
            self.cpu_move()
        elif len(self.moves) == len(self.cpu_moves) and self.moves != self.cpu_moves:
            self.clear_cpu_moves()

    def clear_user_moves(self):
        self.moves = []

    def clear_cpu_moves(self):
        self.cpu_moves = []

    def cpu_move(self):
        nums = [0, 1, 2, 3]
        self.cpu_moves.append(choice(nums))
        print(self.cpu_moves)
        for i in self.cpu_moves:
            root.after(200, animate(self.btns[i]))

class App(object):
    def __init__(self, master):
        self.master = master
        game = Game()
        game.cpu_move()

root.geometry("300x300")

app = App(root)
root.resizable(width=False, height=False)
root.mainloop()

Let's look at this code:

for i in self.cpu_moves:
    root.after(200, animate(self.btns[i]))

First, you're not using after correctly. You're doing the equivalent of this:

for i in self.cpu_moves:
    result = animate(self.btns[i])
    root.after(200, result)

You might as well not call root.after at all, since result will be None. If you need to pass parameters to the function you can do so by adding arguments to after itself:

root.after(200, animate, self.btns[i])

Unfortunately, you can only do this with positional parameters, not named parameters. You still need to use lambda the way you are doing it in animate.

Second, this loop is going to end up calling every function at the same time - the first one at "now+200ms", the next one at "now+200ms", the third at "now+200ms" and so on. What you want is the first one to be at "now+200ms", the next at "now+400ms" and so on. A simple solution is to add 200 for each iteration of the loop:

delay=200
for i in self.cpu_moves:
    root.after(delay, animate(self.btns[i]))
    delay += 200


Delete from multiple tables using temp table variable I'm previewing the data I'm about to delete, but this SQL looks a little redundant.  Is there a better way to write this?

declare @history table(pid int)
insert into @history select pid from plans p where p.pidSynergy = 'P0022' and p.pid != 2885

select * from forecast_FTEs where pid in (select pid from @history)
select * from forecast_phases where pid in (select pid from @history)
select * from budget_FTEs where pid in (select pid from @history)
select * from budget_phases where pid in (select pid from @history)
select * from plans where pid in (select pid from @history)

p is a cryptic table alias and that != is not ANSI compliant, you should try and use <> instead. Also, the select * from is inefficient because it has to go back to the information schema and look up every column, you should try and only select the columns you really need.


Closure as UIControlEvents handler I'm expanding the functionality of this SO answer.

Mainly I'm focusing on:

You can add as many handlers as you want.
You can remove (i.e. cancel) the handler.
You can receive the sender parameter in the handler closure.
You can add "oneshot" handler.

import UIKit

extension UIControl {
    private class EventHandler {

        let _cb: (UIControl, UIEvent) -> Void
        let _oneshot: Bool

        init(_ cb: (UIControl, UIEvent) -> Void, oneshot: Bool) {
            _cb = cb
            _oneshot = oneshot
        }

        @objc func invoke(sender: UIControl, event: UIEvent) {
            _cb(sender, event)
            if _oneshot {
                sender.off(unsafeAddressOf(self))
            }
        }
    }

    typealias EventHandlerId = UnsafePointer<Void>

    func on<T: UIControl>(events: UIControlEvents, _ callback: (T, UIEvent) -> Void) -> EventHandlerId {
        assert(self.isKindOfClass(T), "The handler must receive \(NSStringFromClass(self.dynamicType)) or UIControl")
        return self._on(events, EventHandler({ callback($0 as T, $1) }, oneshot: false))
    }
    func once<T: UIControl>(events: UIControlEvents, _ callback: (T, UIEvent) -> Void) -> EventHandlerId {
        assert(self.isKindOfClass(T), "The handler must receive \(NSStringFromClass(self.dynamicType)) or UIControl")
        return self._on(events, EventHandler({ callback($0 as T, $1) }, oneshot: true))
    }

    func on(events: UIControlEvents, _ callback: () -> Void) -> EventHandlerId {
        return self._on(events, EventHandler({ _, _ in callback() }, oneshot: false))
    }
    func once(events: UIControlEvents, _ callback: () -> Void) -> EventHandlerId {
        return self._on(events, EventHandler({ _, _ in callback() }, oneshot: true))
    }

    private func _on(events: UIControlEvents, _ handler: EventHandler) -> EventHandlerId {
        let ptr = unsafeAddressOf(handler)
        self.addTarget(handler, action: "invoke:event:", forControlEvents: events)
        objc_setAssociatedObject(self, ptr, handler, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
        return ptr
    }

    func off(identifier: EventHandlerId) {
        if let handler = objc_getAssociatedObject(self, identifier) as? EventHandler {
            self.removeTarget(handler, action: nil, forControlEvents: .AllEvents)
            objc_setAssociatedObject(self, identifier, nil, 0)
        }
    }
}

Usage:

class MyViewController:UIViewController {

    @IBOutlet weak var myButton:UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // add event handler
        let handle = myButton.on(.TouchUpInside) { (sender, event) in
            // `sender` is the control itself.
            // `event` is the UIEvent object.
        }

        // remove event handler
        myButton.off(handle)

        // event handler can be () -> Void type
        myButton.on(.TouchUpInside) { [unowned self] in
            // your work
        }

        // "oneshot" event handler
        myButton.once(.TouchUpInside) {
            // your work
        }
    }
}

It's working OK... But, for example:

let btn = UIButton()
btn.on(.TouchUpInside) { (sender: UISwitch, _) in /* ... */ }
                                  ^^^^^^^^

This compiles, but I want to make this compile time error.

Currently, as a workaround, I'm doing "assertion":

assert(self.isKindOfClass(T), "The handler must receive \(NSStringFromClass(self.dynamicType)) or UIControl")

And, if possible, I wish the compiler could infer the type of the sender, like this:

let btn = UIButton()
btn.on(.TouchUpInside) { sender, _ in
    sender.titleLabel.text = "Pushed !!"
}

Any ideas?

Consider for a moment, if you will, how we typically handle a user tapping a button.  We typically will do so with an @IBAction method.  What are the Apple suggested defaults when we hook up a button this way?

The default is to give us a method that takes an object of type AnyObject as its only parameter.  We can, of course, change the type to specify UIButton (or whatever UIControl subclass our element actually is).  We can also change the sent arguments.  We can choose between None, Sender, and Sender and Event.

I don't think it's useful to allow objects that aren't of type UIControl as the parameter.  But, I do feel like we're missing methods to accept a handler that just passes the Sender argument.  For me, this is the most common way I hook up methods (mostly because it's the default, but sometimes because I want the sender).  Meanwhile, I don't think I've ever cared about the Event argument.

But moreover, I actually think it'd also be useful if we also had the option of passing a reference to the handler itself (the EventHandlerId returned when the handler is added) so that potentially we could then remove the event conditionally and without having to keep track of the handler reference on our own.  (Although admittedly, I haven't played too terribly much with this aspect of your code, so I'm not sure how possible or manageable that might be.)

I'd change your typealias to this:

typealias EventHandlerRef = UnsafePointer<EventHandler>

and remove the private access modifier from your EventHandler class, and add version of all your methods that take an EventHandler argument.

For starters, I'd do this because even though the version you've implemented is easier, there's not a particularly good reason for this aspect of the implementation to be private.

But moreover, by making the EventHandler class private, you've tricked yourself into writing the off function in a not-so-great way.  The off function takes an EventHandler pointer, finds the event, then removes it as a target of the UI element.  And that's fine for everything you've done... except for your "oneshot" implementation... where the EventHandler object finds its own reference to pass to the control's off method so that method can use the pointer to find the object (which we already knew) and remove it.

Instead, we should have a method that accepts an EventHandler object.  The method that accepts the EventHandlerRef grabs the EventHandler that the reference points to and calls the method that accepts the EventHandler.

The reason, by the way, I prefer EventHandlerRef to EventHandlerId is two-fold.  First of all, the value it holds is hardly an id in the sense that one might think in a database sense, but most importantly, suffixes pointer typedefs with Ref is just how Apple does it throughout their own libraries.  Any other iOS developer will see EventHandlerRef and know that this is a pointer to an EventHandler thing, even if they don't know what sort of thing EventHandler is.  Meanwhile, EventHandlerId seems slightly arbitrary.

Other than these two observations, my main complaint here would be naming.  Large, descriptive variable names don't make your compiled program take up any more space on the disk, or any more RAM, or run any slower.  The only drawback to large, descriptive variable names is that it makes your code more readable.  Wait... that's not a drawback.

Moreover, this isn't Objective-C.  Something declares as private truly is private in Swift.  The underscores just make things look weird here.  So, here's my take on your code, including the name changes I'd make:

Well, I was going to post some sample code... but now I'm going to be distracted with writing a bug report because the compiler keeps crashing trying to figure out the sample I wrote.  And that means there's something wrong with it, but the compiler doesn't feel like telling me, so I can't figure it out...


trying out possible combinations of varying formula with recursion I wrote a program in c what looks for integer solutions of different formulas. The program asks the user for a dimension which defines the formula. For example, the formula of the third dimension has three variables, the formula of the second dimension has two variables. The formulas look similar to the following:

dim     formula
2       a + b
3       a + b + c
4       a + b + c + d

and so on. Next step, the program asks the user for a maximum value of all the variables. For a given dimension, 3 for instance, the code could look like:

for(int a = 1; a <= max; a++)
{
    for(int b = 1; b <= max; b++)
    {
        for(int c = 1; c <= max; c++)
        {
            do_sth();
        }
    }
}

Of course, this would be a bad algorithm. It checks each possible combination up to 6 times, just in different order. The better alternative would be:

for(int a = 1; a <= max; a++)
{
    for(int b = 1; b <= a; b++)
    {
        for(int c = 1; c <= b; c++)
        {
            do_sth();
        }
    }
}

To make that work for all dimensions, I had to find a way to stack multiple loops depending on the users input. I wrote a recursive loop function:

int number[100];
int dim, max;

void loop(int depth)
{
    for(number[depth] = 1; number[depth] <= number[depth-1]; number[depth]++)
    {
        if(depth == dim - 1)
        {
            do_sth();
        }
        else
        {
            loop(depth+1);
        }
    }
}

int main(void)
{
    printf("Enter a dimension: ");
    scanf("%d", &dim);
    printf("Enter a maximum value: ");
    scanf("%d", &max);
    for(number[0] = 1; number[0] <= max; number[0]++)
    {
        loop(1);
    }
}

Notes:

It is not important, what do_sth() does. It builds the actual formula I don't want to show here.
To be able to calculate the runtime, I wrote a program what calculates the number of combinations to try. I posted it on this question.

My code works fine but I would like to know if there's a better way to do this.

Can be done without recursion
You can do the same thing without recursion, by simply adding one to the rightmost dimension, and then "carrying over" when that number exceeds the one to its left.
Here is a sample implementation:
void loop()
{
    int i = 0;

    for (i = 0; i < dim; i++) {
        number[i] = 1;
    }
    do {
        do_sth();
        for (i = dim - 1; i > 0; i--) {
            if (number[i] < number[i-1]) {
                number[i]++;
                break;
            }
            number[i] = 1;
        }
        if (i == 0) {
            if (number[0] < max) {
                number[i]++;
            } else {
                return;
            }
        }
    } while (1);
}


Conditional async validation function We have the following validation function:

    var result = scope.CurrentUser.Surname.length > 0;
    var d = $q.defer();

    if (result) {
        apiService.UniqueEmailCheck(scope.CurrentUser.PersonId, scope.CurrentUser.Email)
            .success(function (response) {
                if (response) {
                        apiService.GetSelectetExistent(scope.CurrentUser.FirstName, scope.CurrentUser.Surname, scope.CurrentUser.DOB)
                        .success(function (response) {
                                    $scope.SelectExistent = response;
                                    d.resolve($scope.SelectExistent.length > 0);
                        });

            }
            else {
                d.resolve(false);
            }
        })
}
else
    d.resolve(false);

return d.promise;

If the incoming result is true, we have to check one or two async conditions.

It works as expected but we are not sure if we can do better. Any suggestions?

Consider having your APIs return a promise instead. By the looks of it, success indicates that it's a Q promise which means it should be able to do then. This means we can throw away the "outer deferred" and use the promise directly.

Both requests don't necessarily need to be in sequence. The second API call doesn't seem to require the first one other than the fact that it checks for uniqueness and bails out if not unique. You can fire both in parallel, with a minor tradeoff that it will fire 2 in all cases. But then, 2 in parallel vs 2 in sequence. Time-wise, I'd prefer the former.

If you have native promises available or are able to polyfill it, then use native instead. Also, instead of resolving to a boolean, use the promise state as your boolean. Resolve or reject accordingly.

Your code can then be simplified to:

var result = scope.CurrentUser.Surname.length > 0;

var uniquenessRequest = apiService.UniqueEmailCheck(scope.CurrentUser.PersonId, scope.CurrentUser.Email);

var existenceRequest = apiService.GetSelectetExistent(scope.CurrentUser.FirstName, scope.CurrentUser.Surname, scope.CurrentUser.DOB).then( response => {
  $scope.SelectExistent = response;
  return response;
});

return !result ? Promise.reject() : Promise.all([
  uniquenessRequest,
  existenceRequest
]).then(results => {
  var pass = response[0] && response[1].length > 0;
  return Promise[ pass ? 'resolve' : 'reject' ]();
});


Caesar Cipher in Haskell I've come up with this simple implementation of the Caesar cipher. It takes an integer argument and a file to produce the cipher text like so:

./caesar 4 < text.raw

Here's the code:

import System.Environment
import Data.List
import Data.Maybe

alnum = ['A' .. 'Z'] ++ ['a' .. 'z'] ++ ['0' .. '9']
anlen = length alnum

rotChar :: Int -> Char -> Char
rotChar r c
    | elem c alnum = alnum !! (mod (r + fromJust (elemIndex c alnum)) anlen)
    | otherwise = c

rotStr :: Int -> [Char] -> [Char]
rotStr 0 s = s
rotStr r s = (map (rotChar (mod (anlen + r) anlen)) s)

main :: IO ()
main = do
    args <- getArgs
    contents <- getContents
    putStrLn $ rotStr (read $ head args) contents

I'm new to Haskell and I'd like some opinions on the:

global "variables"
use of parentheses
argument parsing

Could any of this be improved? Any other tips will be appreciated.

Global "variables"

I would not worry about global variables. Assuming that this code will be properly placed inside its own module, those would probably not be global anyway.

Use of parentheses

Some parentheses are superfluous. For example, the whole body of the second rotStr equation is enclosed in parentheses and those can be removed.
Regarding the other cases, you can probably avoid parens (and get slightly easier to digest code) if you define subexpressions in a let or where clause.

Argument parsing

I'm not sure what you mean by that. If you mean the getArgs part, that looks OK.

Here are some other notes about the code:

The rotStr 0 s = s line is superfluous. You can remove it and everything will work just fine. I assume it is just an optimization, so that's OK.
It might not be obvious for small inputs, but the performance of the code can be improved. Things like elemIndex c alnum and alnum !! run in linear time in the size of alnum. This means that the expression elem c alnum = alnum !! (mod (r + fromJust (elemIndex c alnum)) anlen) will go through the list 2 times. Again, this might not matter much, but you could use Data.Maps for lookup in order to get better performance.

Here's a possible implementation using Maps:

import Data.List
import Data.Maybe
import qualified Data.Map as M (Map, empty, insert, lookup)

alnum = ['A' .. 'Z'] ++ ['a' .. 'z'] ++ ['0' .. '9']
anlen = length alnum

indices = foldr add M.empty $ zip alnum [0..]
  where add (c, i) m = M.insert c i m

charsByIndex = foldr add M.empty $ zip alnum [0..]
  where add (c, i) m = M.insert i c m

rotChar :: Int -> Char -> Char
rotChar r c = case M.lookup c indices of
                   Just i  -> fromJust $ M.lookup (newIndex i) charsByIndex
                   Nothing -> c
              where newIndex i = (i+r) `mod` anlen

rotStr :: Int -> String -> String
rotStr r s = map (rotChar r) s

Also note that the last line can be reduced to:

rotStr = map . rotChar


Checking a one-dimensional numpy array in a multidimensional array without a loop Input

array([[10, 11, 12, 13, 26, 28, 11],
       [ 4,  9, 19, 20, 21, 26, 12],
       [ 1,  7, 10, 23, 28, 32, 16],
       [ 4,  6,  7, 10, 13, 25,  3],
       [ 4,  6, 15, 17, 30, 31, 16]])

test = np.array([10, 11, 12, 13, 26, 28, 11])

Trying

def check(test,array):
    for i in array:
        if np.array_equal(i,test):
            print('in')
            break
    print('not in')

Is there any simple method without using for...in...if...else structure?

If you don't like the looping and the if ... statements you could use solely NumPy methods:

def is_row_in_array(row , arr):
    return np.any(np.sum(np.abs(arr-row), axis=1) == 0)


Multiple string replacement (with similarity) using a dictionary I'm trying to replace a number of keywords with other corresponding values. I started with this method:

Dictionary<string, string> keywords = GetKeywords();
foreach (var pair in keywords)
{
    var re = new Regex($@"\b{pair.Key}\b");
    if (re.IsMatch(text))
        text = re.Replace(text, pair.Value);
}

..which becomes slower and slower when the number of keywords increases. So, I used a different method (by only scanning the string once and checking each word against the dictionary):

text =
    Regex.Replace(text, @"\w+", delegate (Match m)
    {
        string word = m.Value;
        string value;
        if (keywords.TryGetValue(word, out value))
            return value;
        else
            return word;
    });

..which worked great for the original requirement. However, I was forced to switch back to the first method because I need to match/replace keywords that are not 100% equal to what's in the dictionary. For example, in the first method, I would do something like this:

string keyword = pair.Key.Replace("e", "[eé]")
var re = new Regex($@"\b{keyword}\b");

Is there a way around this using the second method? Or any other methods faster than the first one?

Notes:

It's not just accented letters, so something like IgnoreNonSpace will not work.
Both regex patterns are a little bit more complicated, that is, they both have a negative lookahead ((?![^<]*>|[^&]*;)) but I don't think that affects the outcome as the pattern is essentially just matching single words.

The only solution I could think of is to "normalize" the keywords before adding them to the dictionary (e.g., replace "[eé]" with "e") and then "normalize" each word before passing it to TryGetValue() but I'd like to see if there's a better solution first because this one will be a little bit messy.

I can be wrong, but it seems that the problem is that if you have a large number of keywords, you are defining a lot of regular expressions in vain. How about creating a single regex and replacing values only for found keywords?

var words = string.Join("|", keywords.Keys);
text = Regex.Replace(text, $@"\b({words})\b", delegate (Match m)
{
    return keywords[m.Value];
});


Decorator to measure execution time of a function This decorator adds the elapsed time to a function's attributes when applied.
My concerns:

Is the code pythonic?
Could this code be useful?
Should I just use the timeit module?
Is the code easy to read and understand?

The code:
'''
:Date: 7/21/17
:Version: 1
:Authors:
    - Ricky L Wilson
'''

import datetime

def time_func(function):
  """ This decorator calculates the amount of time a function takes to execute.

  When time_func is applied to a function it records how long the function takes to
  finish and add the elapsed time to the functions attributes.

  - **parameters**
  :param function: The function you want to add the elapsed time attribute to.

  :Example:
  @time_func
  def example(name, **kwargs):
    meta = type(name, (object,), kwargs)
    return meta

  example('foo')
  print example.elapsed
  0:00:00.000052

  """
  def new_func(*args, **kwargs):
    # Start the clock.
    start = datetime.datetime.now()
    # Execute the function and record the results.
    function_result = function(*args, **kwargs)
    # Calculate the elapsed time and add it to the function
    # attributes.
    new_func.elapsed = datetime.datetime.now() - start
    # Returned the function with the added elapsed attribute
    return function_result
  return new_func

I'd recommend the timeit module when measuring the execution time of functions. AFAIK, timeit disables the garbage collector for the duration of the test, which might give you better results overall.

From here:

  timeit is more accurate, for three reasons:

  it repeats the tests many times to eliminate the influence of other tasks on your machine, such as disk flushing and OS scheduling.
  it disables the garbage collector to prevent that process from skewing the results by scheduling a collection run at an inopportune
  moment.
  it picks the most accurate timer for your OS, time.time or time.clock, see
  timeit.default_timer.

On the other side, a timing decorator is really useful because you can use annotations to sprinkle the timing around your code rather than making your code messy with timing logic everywhere. So yes, related to one of your questions, the code is useful.

Now, on the pythonic question, IMO:

you have too many comments which unfortunately didn't add any value to your code. Remove them.
your inner function could also be renamed to something more intuitive like wrapper.
function is also not the best choice when it comes to naming conventions as it might shadow the built-in function
use 2 newlines between imports and methods
the indentation should be a multiple of 4 (spaces)
use triple double quotes for your module docstring

In Python, there're already some useful modules to help you with this. For example, in functools you have the wraps decorator. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since wraps is itself a decorator I guess it'll make things a lot easier.

Code:

from functools import wraps
from time import time

def timing(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        start = time()
        result = f(*args, **kwargs)
        end = time()
        print 'Elapsed time: {}'.format(end-start)
        return result
    return wrapper

Usage:

@timing
def f(a):
    for _ in range(a):
        pass

print(f(2000000))

Result:

  Elapsed time: 0.0971460342407


OdeToCode Refactoring Kata I saw this article that proposes a refactoring exercise and thought I'd give it a try.

Spoiler alert: I'm going to show my solution to the Kata below. You might want to attempt the Kata yourself before you look at this code, so this will not influence you in any way.

I ended up with the following three classes:

Person.cs

public class Person
{
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }

    public bool IsOlderThan(Person person2)
    {
        return BirthDate > person2.BirthDate;
    }
}

Pair.cs

public class Pair
{
    public Person Person1 { get; set; }
    public Person Person2 { get; set; }
    public TimeSpan AgeDifference { get { return Person2.BirthDate - Person1.BirthDate; } }

    public Pair(Person person1, Person person2)
    {
        if (person1.IsOlderThan(person2))
        {
            Person1 = person2;
            Person2 = person1;
        }
        else
        {
            Person1 = person1;
            Person2 = person2;
        }
    }

    public Pair()
    {
        Person1 = Person2 = null;
    }
}

Finder.cs

public class Finder
{
    private readonly List<Person> _person;

    public Finder(List<Person> person)
    {
        _person = person;
    }

    public Pair FindClosestAgeInterval()
    {
        return Find(pairs => pairs.OrderBy(p => p.AgeDifference).FirstOrDefault());
    }

    public Pair FindFurthestAgeInterval()
    {
        return Find(pairs => pairs.OrderByDescending(p => p.AgeDifference).FirstOrDefault());
    }

    public Pair Find(Func<IEnumerable<Pair>, Pair> pairSelectionLambda)
    {
        var availableDistinctPairs = GetDistinctPairs();

        return pairSelectionLambda(availableDistinctPairs) ?? new Pair();
    }

    private IEnumerable<Pair> GetDistinctPairs()
    {
        for (var i = 0; i < _person.Count - 1; i++)
            for (var j = i + 1; j < _person.Count; j++)
                yield return new Pair(_person[i], _person[j]);
    }
}

The test class basically remained the same (except that I have updated it with the new class/method names).

Overall I think this code is OK (it passes the tests and I could easily understand it 6 months from now).

However, I'm interested to hear your critic opinions, to find out how it can get better.

My $0.02. Your solution is quite good as it stands. Just putting my thing down too.

I'm a fan of interface-based development with factory methods, so I extracted out an interface for the Person class called IPerson:

public interface IPerson
{
    string Name { get; }

    DateTime BirthDate { get; }
}

and then implemented Person as a sealed immutable class (using readonly and a parametrized private constructor) which has a factory method:

public sealed class Person : IPerson
{
    private readonly string name;

    private readonly DateTime birthDate;

    private Person(string name, DateTime birthDate)
    {
        this.name = name;
        this.birthDate = birthDate;
    }

    public string Name { get { return this.name; } }

    public DateTime BirthDate { get { return this.birthDate; } }

    public static IPerson Create(string name, DateTime birthDate)
    {
        return new Person(name, birthDate);
    }
}

I did similarly with the class you called Pair, but I called it PersonBirthdayDifference (I'll freely admit I can't think up a useful name at all). Also note the static Empty property which I put to use in the Finder algorithm rather than just newing up one with no properties set.

public interface IPersonBirthdayDifference
{
    IPerson YoungerPerson { get; }

    IPerson ElderPerson { get; }

    TimeSpan AgeDifference { get; }
}

and

public sealed class PersonBirthdayDifference : IPersonBirthdayDifference
{
    private static readonly IPersonBirthdayDifference empty = Create(null, null);

    private readonly IPerson youngerPerson;

    private readonly IPerson elderPerson;

    private readonly TimeSpan ageDifference;

    private PersonBirthdayDifference(IPerson youngerPerson, IPerson elderPerson)
    {
        this.youngerPerson = youngerPerson;
        this.elderPerson = elderPerson;
        this.ageDifference = (youngerPerson == null) || (elderPerson == null)
            ? default(TimeSpan)
            : elderPerson.BirthDate - youngerPerson.BirthDate;
    }

    public static IPersonBirthdayDifference Empty { get { return empty; } }

    public IPerson YoungerPerson { get { return this.youngerPerson; } }

    public IPerson ElderPerson { get { return this.elderPerson; } }

    public TimeSpan AgeDifference { get { return this.ageDifference; } }

    public static IPersonBirthdayDifference Create(IPerson p1, IPerson p2)
    {
        return new PersonBirthdayDifference(p1, p2);
    }
}

Finally, I update the Finder class by some of the same methods as above, plus introduce a couple more helper classes called GreaterThanComparer and LessThanComparer (not posting that code, it's rather trivial) to keep the switch from executing every iteration of the loop. There's also a healthy dose of LINQ to help declare intent where I can:

public sealed class Finder : IFinder
{
    private readonly IList<IPerson> people;

    private Finder(IEnumerable<IPerson> people)
    {
        this.people = people.ToList();
    }

    public static IFinder Create(IEnumerable<IPerson> people)
    {
        return new Finder(people);
    }

    public IPersonBirthdayDifference Find(FinderType finderType)
    {
        var peopleInOrder = this.PopulateListInOrder();

        return peopleInOrder.Any() ? GetAnswer(peopleInOrder, finderType) : PersonBirthdayDifference.Empty;
    }

    private static IPersonBirthdayDifference GetAnswer(
        IEnumerable<IPersonBirthdayDifference> peopleInOrder,
        FinderType finderType)
    {
        IPersonDifferenceComparer comparer;

        switch (finderType)
        {
            case FinderType.LessThan:
                comparer = LessThanComparer.Create();
                break;
            case FinderType.GreaterThan:
                comparer = GreaterThanComparer.Create();
                break;
            default:
                return PersonBirthdayDifference.Empty;
        }

        var answer = peopleInOrder.First();

        foreach (var person in peopleInOrder)
        {
            if (comparer.Compare(person.AgeDifference, answer.AgeDifference))
            {
                answer = person;
            }
        }

        return answer;
    }

    private IEnumerable<IPersonBirthdayDifference> PopulateListInOrder()
    {
        IList<IPersonBirthdayDifference> peopleInOrder = new List<IPersonBirthdayDifference>();

        for (var i = 0; i < this.people.Count - 1; i++)
        {
            for (var j = i + 1; j < this.people.Count; j++)
            {
                var isYounger = this.people[i].BirthDate < this.people[j].BirthDate;
                var youngerPerson = isYounger ? this.people[i] : this.people[j];
                var elderPerson = isYounger ? this.people[j] : this.people[i];

                peopleInOrder.Add(PersonBirthdayDifference.Create(youngerPerson, elderPerson));
            }
        }

        return peopleInOrder;
    }
}


Find the highest prime factor for given number My code works for some smaller inputs but larger numbers causes it to hang (when running with node)

// The prime factors of 13195 are 5, 7, 13 and 29.
// What is the largest prime factor of the number 600851475143 ?

function factorsOf(n) {
    var factors = [];
    for (var i = 1; i <= n; i++) {
        if (n % i === 0) {
        factors.push(i);
        }
    }
   return factors;
}

function isPrime(number) {
    for (var i=2; i < number; i++) {
    if (number % i === 0) {
        return false;
    }
  }
  return number > 1;
}

function primes(factors) {
    var primes = [];
    for (var i=1; i<factors.length; i++) {
    if (isPrime(factors[i])) {
        primes.push(factors[i]);
    }
  }
  return primes;
}

var factors = factorsOf(13195);
var arr = primes(factors);
console.log(arr[arr.length-1]);

Minor Changes

In factorsOf:

1 is not a proper factor. Start the loop with var i = 2.
n isn't either. Stop the loop with i < n.

Prime Factors

Here is a simple optimization for testing the 'primeness' of a factor. The key is that you have already found a array of factors. Instead of testing every i such that i<n, you can simply test it against the array of factors.

For example, 65 is a factor of 13195. Instead of testing 1 through 64, check to see if any of 13195's other factors divide 65. 65's factors have to also be a factor of 13195 so if it is not prime, there has to exist another factor of 13195 that divides 65.

// Takes a array of proper factors for some number, n,
// and returns a array of the prime factors of n.
// [descriptive function names are a good practice]
function factorsToPrimes(factors) {
    var primes = [];
    // Go through each factor
    for (var i=0; i<factors.length; i++) {
        var iIsPrime = true;
        // Check to see if any other factor divides it
        for (var j=0; j<factors.length; j++) {
            if (factors[i]%factors[j] == 0 && i != j)
                iIsPrime = false;
        }
        // If no other factor divides it, it must be prime
        if (iIsPrime)
            primes.push(factors[i]);
    }
    return primes;
}

Finding Factors

At this point, factorsOf(n) is the choke point. So if we need to go faster (and we do), we need to fix this.

Factors come in pairs. By definition, a is a factor of n if there is a b such that a*b == n. We also know that the smaller factor is always less than or equal to sqrt(n).

Thus instead of looping from 2 to n, we can loop from 2 to sqrt(n).

// Takes a number, n, and returns a array of
// all the factors of n.
function factorsOf(n) {
    var factors = [];
    for (var i = 2; i <= Math.sqrt(n); i++) {
        if (n % i === 0) {
            factors.push(i);
            factors.push(n/i);
        }
    }
    return factors;
}

The factor array and the prime factor array aren't necessarily sorted, so the final step is to find the largest prime factor. Here is a concise way to do that using max.

console.log(Math.max.apply(Math, primeFactors)); // Node.js
console.log(Math.max(...primeFactors)); // Or with ECMAScript 6 support

[Note: these changes allow you to get the correct solution (to PE #3) in about a second]

Big O Analysis

[WARNING: Unnecessary technical jargon]

Here is a Big O analysis of you code and these changes. Big O can be useful for finding performance choke points and it is a great tool for "it-works-for-small-input-but-hangs-on-large-input" problems.  So here is a breakdown of your code:

Factors -> O(n)

factorsOf -> O(n)

Prime Factors -> O(n * lg(n))

primes -> O(lg(n))
isPrime -> O(n)

Overall -> O(n * lg(n))

The time spent on finding prime factors grows the fastest. So if we want to go fast, we need to fix this. Then if we want to go faster, we need to improve our factorization. The Big O of these two changes is:

Factors -> O(sqrt(n))

factorsOf -> O(sqrt(n))

Prime Factors -> O(lg(n)^2)

factorsToPrimes -> O(lg(n)^2)

Overall -> O(sqrt(n))


Checking for an existing word in a file This piece of code basically just asks for a word and sees if it exists in a file. If not, the user is asked if it should be added to the file.

I am new to C programming and I want to know what you think about my code: things to change, things to remove, what not to do.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
    //Declarations
    //**********************************************************
    char wordContainer[20],wordFinder[20],ans[2];
    int wordChecker=0;
    FILE* filePtr=NULL;
    //**********************************************************
    filePtr=fopen("wordDic.dic","a+");//opening the file with the a+ option
    printf("please enter the word you want to look for : ");
    fgets(wordContainer,20,stdin);//entering the word we want to look for
    if(filePtr==NULL)
    {
        printf("error while trying to open the dictionnary file");//allways good to check
    }

    /*while we haven't reach the end of the file see if the current word matchs the word we are looking for*/
    while(fgets(wordFinder,20,filePtr)!=NULL)
    {
        if(strcmp(wordContainer,wordFinder)==0)
        {
            printf("this word was found in the dictionnary , would you like to perform another search ? y/n... ");
            fgets(ans,2,stdin)
            wordChecker++;//when the word is matched increase wordChecker and quit the while
            break;
        }
    }
    if(wordChecker==0)//if no match is found ask to enter this new word
    {
        printf("we couldn't find the word %s would you like to add it ? y/n ... ",wordContainer);
        fgets(ans,2,stdin);
        if(strcmp(ans,"y")==0 || strcmp(ans,"Y")==0)
        {
            fprintf(filePtr,"%s",wordContainer);
            fflush(filePtr);//not exactly sure what it does exept that it clear the output buffer maybe ?
            printf("this word has been added");
        }
        else
        {
            printf("thank you for using this program,bye");
            exit(0);
        }
    }
    fclose(filePtr);
    return 0;
}

Your code looks quite neat, although note that formatting, including spaces
around operators etc, line lengths, defining multiple variable per line, should follow a conventional style.

There are some issues, the main one being that compiling and running the code,
it does not work.  The problem is that

fopen(filename, "a+");

opens the file for  reading and writing but leaves the stream pointer at the
end of the file.  So any subsequent read will fail.   You need a rewind();
or equivalent (fseek etc) after checking that the file opened successfully.

After fixing the rewind, another issue is that fgets returns the input word
with a trailing newline, \n.  Your code ignores this and manages to work
because the strings that are written to and read from the dictionary also have
a trailing \n.  But this fails when a user enters a string that fills your
buffers, 19 characters or more.  In this case, the fgets call cannot read
the whole string and reads just the 1st 19 chars (and adds a terminating \0),
leaving the remaining chars in the input stream.  In this case there is no
trailing \n in the buffer.  The next time you read from stdin the 20th and 21st chars are
read and treated as the y/n answer.  Even if these chars happen to be "y", the
19-char word is written to the dictionary without a trailing \n, corrupting
the dictionary (try looking up abcdefghijklmnopqrsy - notice the 'y' at the end)

There are ways to fix these problems, for example you could try using
getline() to get the input string instead of fgets, although getline is
more tricky to use correctly.   Alternatively (as it is just an exercise)
just check the input string to confirm that there is a trailing \n (meaning
that the whole line was read) and reject the word and fflush the input if not.   To do things
properly you really need to remove the trailing \n from the user input string and
from the string read from the dictionary before comparing, and add \n back when writing to the
file.

Another issue is poor comments.  Comments must be useful; otherwise they are
just noise (and hence make reading the code more difficult than it need be).
All of your comments are just noise.

Note also that when opening the dictionary fails you should exit. There are numerous other issues, but I'll leave it at that for now...

EDIT

As no reviewers have commented on other issues, here are some other things I
spotted:

avoid use of constants such as 20.  Instead, define the buffer size with a
define and use sizeof where you need the buffer size. For example:

#define BUF_SIZE 20
...
char buf[BUF_SIZE];
fgets(buf, sizeof buf, stdin);

by using sizeof you guarantee that the size is correct - but note that
if you use it on a pointer, then you get the wrong value:

char *buf = malloc(BUF_SIZE);
fgets(buf, sizeof buf, stdin); // WRONG!!

in the latter case, sizeof returns the size of the pointer (typically 4
or 8 bytes) - you need to pass BUF_SIZE to fgets
define the file name in a constant or a #define and use the file name in the
error message on failure to open.  The message should be produced with
perror

const char *dict = "wordDic.dic";
...
FILE *file = fopen(dict,"a+");
if (file == NULL) {
    perror(dict);
    exit(EXIT_FAILURE);
}

notice that I exited immediately on failure (your code continues).
perror will produce a short error message on stderr that says why the file
could not be opened, not just that it couldn't.  Also note that I checked
the file pointer immediately, not after prompting the user, as you do.
you ask the user whether she would like to perform another search
(on success) but then ignore the answer.
the call to fflush is strictly unnecessary.  Buffered output like
fprintf (and printf) writes to file when it sees a \n in the buffer.  In
this case, your strings have \n embedded (from the fgets call) and so
fprintf will flush the buffer; the buffer is empty when fflush is
called.  The normal thing would be for the word in wordContainer to have
no \n and for fprintf to use a format containing \n - fprintf(filePtr,
"%s\n", word); - and again, no fflush is needed.
your

else
{
    printf("thank you for using this program,bye");
    exit(0);
}

exits before the final closing of the file and zero return.   Closing the file is good practice, although it will happen when the
program exits anyway.
I don't really like your variable names - three variables starting with
'word' is confusing.  I'd go for something like word for the user-entered
word, entry for the dictionary entry read from file and found to
indicate that the word was found in the dictionary.  That is a rather
personal preference though...
remember to put a \n on the end of lines that are printed, eg on exiting the
program.


Ruby Exercise: Implement your own "#group_by" method Task:

"Implement a method 'gruppiere', in a way that it can be invoked on all enumerable objects (Enumerable). The method receives a block and returns a hash. The items of the enumerable a grouped within the hash according to the return-value of the block."

What they like to have is an own implementation of Ruby's "#group_by"-method: Ruby-Docs Enumerable

My solution:

module Enumerable
    def gruppiere()
        ret = {}

        self.each { |item|
            key = yield item

            if ret[key] == nil
                tmp = []
                tmp << item
                ret[key] = tmp
            else
                ret[key] << item
            end
        }

        ret
    end
end

puts [1, 2, 3, 4].gruppiere { |i| i % 2 == 0 } # Result: {false=>[1, 3], true=>[2, 4]}

Works well. But I'm sure it could be done better.

Is there a less verbose way to solve the task?

Is my code written in a good way and manner? What could be improved?

Linting
You should run some sort of linter or static analyzer on your code. Rubocop is a popular one, but there are others.
Rubocop was able to detect almost all of the style violations I am going to point out (and even some more), and was able to autocorrect almost all of them.
Testing
There is no automated testing in your code. Apart from the single example at the very end (which is not automated), there is no testing at all.
You should always strive to have as close to 100% test coverage as possible. It doesn't really matter if you have unit tests, functional tests, integration tests, end-to-end tests, or a mix of them, but you should have tests, and they should be automated.
In this particular case, since you are implementing a Ruby core method, there are already plenty of tests written for you in the Ruby/Spec project as well as the YARV test suite.
Running the Ruby/Spec tests against your code yields 3 errors, 1 failure, and only 3/7 passing tests.
The YARV test suite has 1/2 passing assertion and 1 error.
Indentation
The standard indentation style in the Ruby community is 2 spaces, not 4.
Empty parameter list
When you define a method without parameters, don't write out an empty parameter list. Just leave out the parameter list completely.
Instead of
def gruppiere()

you should have
def gruppiere

Naming
ret and tmp aren't really good variable names. Try to make them more expressive so that they reveal their intent. Okay, so it's a temporary variable, but what does it do, what is it for, why is it there?
Normally, the reason to introduce a temporary variable is to give an intention-revealing name to some sub-expression. But tmp is not very intention-revealing.
At least, spell them out. You are not going to wear out your keyboard by writing temp instead of tmp, I promise.
Unnecessary self
self is the implicit receiver in Ruby if you don't explicitly provide one. There is no need to explicitly provide self as the receiver (except in some very limited special circumstances).
Instead of
self.each

just write
each

Block delimiters
The standard community style for block delimiters is to use { / } for single-line blocks and do / end for multi-line blocks.
There is a small minority that follows a different style: { / } for functional blocks and do / end for imperative blocks
Whichever style you follow, your block should use do / end since it is both multi-line and imperative.
Explicit equality check against nil
You should not check for equality with nil. There is a method Object#nil? which returns false for all objects, and the only override of this method is NilClass#nil?, which returns true. In other words: the only object that will ever respond with true to nil? is nil.
Instead of
ret[key] == nil

you should write
ret[key].nil?

Unnecessary array mutation
In this piece of code:
tmp = []
tmp << item

You assign an empty array to tmp, then immediately append item to the empty array. That's exactly the same as assigning an array with one item to tmp in the first place:
tmp = [item]

Unnecessary temporary variable
Once we have made the above change, this piece of code:
tmp = [item]
ret[key] = tmp

doesn't really need the temporary variable anymore:
ret[key] = [item]

See? The reason why you didn't find a good name for that variable, is that it shouldn't even be there!
Hash default value
Actually, we can get rid of that whole conditional expression by instead making sure our result hash automatically initialized non-existent keys with an empty array the first time the key is accessed:
def gruppiere
  ret = Hash.new {|hash, key| hash[key] = [] }

  each do |item|
    key = yield item
    ret[key] << item
  end

  ret
end

This, by the way, also gets rid of one of the things Rubocop was complaining about but was unable to auto-correct: the method was too long.
Higher-level iteration methods
each is a very low level iteration method. It is usually barely needed in Ruby. As a general rule, in Ruby

When you are writing a loop, you are definitely doing something wrong.
When you use each, you are very likely doing something wrong.

The pattern you use in your code looks like this: you create a result object, then accumulate results in this object, and at the end return it. This pattern is actually a Fold. In Ruby, fold is provided by Enumerable#inject (and its alias Enumerable#reduce) and Enumerable#each_with_object.
Here is what the method would look like using Enumerable#each_with_object:
def gruppiere
  each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |element, result|
    key = yield element
    result[key] << element
  end
end

Iteration protocol
It is standard that iterator methods return an Enumerator when called without a block. We can use the Object#enum_for method to create an Enumerator for our method. We just put the following code as the first line of our method:
return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?

This actually fixes all of the test errors we had.
Test failures
Unfortunately, we have introduced one new test failure with our refactoring to auto-initialize the hash. group_by should not return a Hash that has default_proc set.
We have two choices:

Set default_proc to nil.
Create a new hash.

I opted for the latter, to create a new empty hash and Hash#merge onto it, to be 100% sure that the default_proc as well as any internal flags are reset to defaults:
def gruppiere
  return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?

  {}.merge(
    each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |element, result|
      key = yield element
      result[key] << element
    end
  )
end

Hash#fetch
There is actually a better option than using a default_proc. Hash#fetch will get the value corresponding to the key if the key exists and otherwise return a value of our choosing:
def gruppiere
  return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?

  each_with_object({}) do |element, result|
    key = yield element
    result[key] = result.fetch(key, []) << element
  end
end

Monkey patching core classes / modules
Monkey patching core modules is generally frowned upon. If you do it, it is good practice to put your monkey patches in a separate mixin with a clear name, and mix that into the class or module you want to monkey patch. That way, it shows up in the inheritance chain, and people can use the name in the inheritance chain to make a guess at the filename, when they find this strange method in their array that they have no idea where it comes from.
Refinements
NOTE! This advice is controversial.
When monkey patching, it is a good idea to wrap your monkey patch into a Refinement, so that consumers can only pull it in when they need it, and it doesn't pollute other parts of your code.
Unfortunately, most Ruby implementations don't implement Refinements, so as nice as the benefits are, it essentially makes your code non-portable.
The Result
If we put all of the above together, we end up with something roughly like this:
module EnumerableGruppiereExtension
  def gruppiere
    return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?

    each_with_object({}) do |element, result|
      key = yield element
      result[key] = result.fetch(key, []) << element
    end
  end
end

module EnumerableWithGruppiere
  refine Enumerable do
    include EnumerableGruppiereExtension
  end
end

using EnumerableWithGruppiere

puts [1, 2, 3, 4].gruppiere(&:even?)
#=> { false => [1, 3], true => [2, 4] }

Addendum: Functional Programming
You tagged your question with functional-programming, but there is nothing functional about your code. There's looping, there is mutation, there are side-effects.
It is, however, not easy to program in a functional way in Ruby. Neither the core and standard library data structures nor the core and standard library algorithms really lend themselves to Functional Programming.
Here is a purely functional version that does not use mutation, side-effects, or looping:
def gruppiere
  return enum_for(__callee__) { size if respond_to?(:size) } unless block_given?

  inject({}) do |result, element|
    key = yield element
    result.merge({ key => result.fetch(key, []) + [element] })
  end
end

Now, you might ask yourself: that actually doesn't look that bad. Why did I say that Ruby is not amenable to Functional Programming?
The reason for this is performance.
Because Hash and Array are mutable, operations such as Hash#merge and Array#+ can only be implemented by copying the entire data structure. Whereas if Hash and Array were immutable, as they are in a collections library for a functional language, these operations could be implemented by what is called structural sharing, which means that Hash#merge and Array#+ would not return a full copy of the original but rather would return only the updated data and a reference to the old version. This is much more efficient.
For example, here is what the same code would look like in Scala:
def [A, B](seq: Iterable[A]).gruppiere(classifier: A => B): Map[B, Iterable[A]] =
  seq.foldLeft(Map.empty[B, IndexedSeq[A]]) {
    (result, element) => {
      val key = classifier(element)
      result updated(key, result.getOrElse(key, IndexedSeq.empty[A]) :+ element)
    }
  }

Iterable(1, 2, 3).gruppiere { _ % 2 == 0 }
//=>Map(false -> Iterable(1, 3), true -> Iterable(2))

As you can see, it looks more or less identical. Some names are different (e.g. foldLeft instead of inject, getOrElse instead of fetch, etc.), and there are some static type annotations. But other than that, it is the same code. The main difference is in the performance: Map.updated does not copy the map, it returns a map which shares all its data except the one updated key-value-pair with the original. The same applies to IndexedSeq.:+ (an alias for IndexedSeq.append).


Where to databind a GridView? Something that bothers me a lot when coding is best practice. I am completely self taught and I find it difficult to know whether I am doing things in the 'right way'.

Let's say I have a Gridview on a page which displays data from the following list:

(from foo in someContext.foobars select foo).ToList

Regardless or how simple or complex the query is, can I just bind the Gridview in the page code behind file as below (in Page.Load or wherever else I want it to run):

gvSomeGridview.DataSource = (from foo in someContext.foobars select foo).ToList();
gvSomeGridview.DataBind();

Or, should I have a class elsewhere that performs the query and returns a list and then bind the Gridview like:

gvSomeGridview.Datasource = helperClass.GetGridviewData
gvSomeGridview.DataBind()

Perhaps go one further and also pass the GridView to the helper class as such:

helperClass.BindGridView(gvSomeGridview)

If I am going to require this list elsewhere in my application or bind a different Gridview with the same data then clearly a class is the way forward, however if I do not, is it fine to just bind the GridView using the query in the code behind as per the first example, or is it recommended to keep all such operations in separate classes regardless?

First, you should separate the UI logic (with terms like GridView, databinding etc.) from the business and/or data logic (with terms like queries, DbContext etc.). So your second approach with a helper class is the more correct approach. In general this kind of helper classes are called the Repository pattern.

You should not pass the UI controls like GridView to your business and/or data logic layer.

About where to put GridView.DataBind() - there are few approaches each useful in certain cases:

Set the .DataSource and call .DataBind() in your Page_Init() method - this way the controls created will not all go in the ViewState. This is not always possible but should be used whenever possible.
Set the .DataSource and call .DataBind() in GridView_PreRender() event - this event is only called when GridView.Visible == true so if you show/hide the grid, you will not end up going for the data if it is not displayed.

Also always experiment if setting EnableViewState=false works for you - since by default GridView will always store everything in the ViewState. If this does not work, you should only call .DataBind() when the data is initially retrieved or the view changed (such as Page.IsPostBack == false or when clicking a search button etc.


Generate SQL UPDATE from Excel CSV file I must write updates in a database from a flat file (CSV).  I want to do that in the shell, with tools such as AWK.

#!/bin/bash

cat in.csv | sed -e '1d' | awk -F';' -v q=\' '{               # For each line.
    print "DECLARE @v_trmID varchar(16) = " q $1 q
    print "DECLARE @v_trmNom varchar(6) = " q $3 q
    print "DECLARE @v_trmNbrTrav smallint = " $4
    print "IF EXISTS (SELECT 1 FROM trimestre WHERE trmID = @v_trmID AND trmNom = @v_trmNom)"
    print "    BEGIN"
    print "        UPDATE trimestre"
    print "        SET trmNbrTrav = @v_trmNbrTrav"
    print "        WHERE trmID = @v_trmID AND trmNom = @v_trmNom"
    print "    END"
    print "ELSE"
    print "    BEGIN"
    print "        PRINT " q "The script execution FAILED for record " NR " (pfiID " q " + @v_trmID + " q ", trimestre " q " + @v_trmNom + " q ")." q
    print "    END"
    print "go"
    print ""
}'

Though, there a 2 things I don't like:

The way quotes are inserted; it becomes really difficult to follow, even if I choose for the simpler way I found to write quotes inside an AWK string (instead of multiple escape sequences).  Still, not that readable.
The fact that every SQL line is not readable as is.  Code is not highlighted as SQL.  I'd like to find a "here doc" solution, where I wouldn't have to prefix lines with printf.

Do you have any pieces of advice or better ideas on the way to write robust (because more readable / easily modifiable) code?

You can turn this into "here doc" solution by using wrapping it in a process substitution <(...), like this:

awk -f <(cat << "EOF"
{
    ... // awk script, as if in a file
}
EOF
)

This way, you can write ' directly, as if in a .awk script file,
because there ' is no longer an enclosing character.

Note that cat << "EOF" is necessary instead of simply cat << EOF to avoid variable expansion of $1, $3 and $4.

Also, to avoid multiple print statements,
you will have to embed newlines with \n, and end lines with \ to continue the same print statement on the next line.

Finally, you don't need the sed -e 1d, because awk can do this alone, using a NR > 1 filter. However, to account for the extra line in the input, whenever you use NR in the awk script, you would have to change that to NR - 1.

Putting the above together, this script is equivalent to yours (produces same output):

awk -F';' -f <(cat << "EOF"
NR > 1 {
print "\
DECLARE @v_trmPfiID_fk varchar(16) = '"$1"'\n\
DECLARE @v_trmNom varchar(6) = '"$3"'\n\
DECLARE @v_trmNbrTrav smallint = "$4"\n\
IF EXISTS (SELECT 1 FROM trimestre WHERE trmPfiID_fk = @v_trmPfiID_fk AND trmNom = @v_trmNom)\n\
    BEGIN\n\
        UPDATE trimestre\n\
        SET trmNbrTrav = @v_trmNbrTrav\n\
        WHERE trmPfiID_fk = @v_trmPfiID_fk AND trmNom = @v_trmNom\n\
    END\n\
ELSE\n\
    BEGIN\n\
        PRINT 'The script execution FAILED for record " (NR - 1) " (pfiID ' + @v_trmPfiID_fk + ', trimestre ' + @v_trmNom + ').'\n\
    END\n\
go\n\
"
}
EOF
) < in.csv


File-exclusion based on an array of prefixes I am trying to remove files based on an array of prefixes, from files present in sourceDirectory. I am using prefixFileFilter to get the list of files with the prefixes. After that I am removing these from the original list.

Is there any better approach?

package sriram;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.filefilter.PrefixFileFilter;

public class FileFilterExample {
public static void main(String[] args) {
excludeFiles();
}

private static List<String> excludeFiles() {
String[] filesToBeExcluded = { "sri", "agnew" };
File sourceDirectory = new File(
        "C:\\Users\\sriram\\workspace1\\sample\\src");
String[] fileNames = sourceDirectory.list(new PrefixFileFilter(
        filesToBeExcluded));
List<String> listOfFiles = Arrays.asList(fileNames);
List<String> totalFiles = Arrays.asList(sourceDirectory.list());
totalFiles.removeAll(listOfFiles);
return totalFiles;
}
}

you can use java.io.FilenameFilter like:

    final List<String> excludedFiles = Arrays.asList(filesToBeExcluded);
    File[] totalFiles = sourceDirectory.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return !excludedFiles.contains(name);
        }
    });


Querying nearest city with a given shop using latitude and longitude is slow I am using the following query to search for the nearest city to my location from the cities table using latitude and longitude. The query also checks whether the nearest cities to my location have more than 1 shops of a given category. Only then a city is selected.

The query works fine but it takes more than 5 seconds to execute. Is there any way this query can be optimised to consume less time.

SELECT id,city,city_url,
(SELECT count(shop) FROM shops JOIN
shop_categories ON shop_categories.shop_id = shops.id WHERE
city_id=cities.id && shop_categories.category_id = :catId LIMIT 1) as
totalshops,
(6371 * 2 * ASIN(SQRT( POWER(SIN(( :latitude - latitude) *
pi()/180 / 2), 2) +COS( :latitude * pi()/180) * COS( :latitude *
pi()/180) * POWER(SIN(( :longitude - longitude) * pi()/180 / 2), 2) )))
as distance
from cities
having totalshops > 1
order by distance ASC
LIMIT 1

I think there's three big things you might be able to do to improve the performance of this.

Write your query such that it doesn't need to execute the subquery for each line and/or have a HAVING clause by using an inner join which will automatically exclude those with no match.
Use ST_Distance_Sphere(POINT(:longitude, :latitude), POINT(cities.longitude, cities.latitude) to get the distance using a built in function that'll probably be faster than anything you can calculate outside of one.
If you're looking for the singular closest entry it may be worth using half of the maximum distance between two points as a cut off and excluding anything by default where the long or lat is outside of the given range and would thus never be the closest entry.
For example if the largest distance between two cities is 1,600 km you know for sure that no city outside of 800 km in any direction can ever be the closest; At 70N about the north end of Canada that equates to ~21 points of longitude anything outside of your passed in longitude +- 22 can be immediately ignored. The same rule can be applied to latitude to ignore everything outside of +/- 7.

You'll still have to check everything in those ranges, but it'll be very quick to run and if it reduces the amount of slow work required to be run it's worth it.

SELECT
    cities.id,
    cities.city,
    cities.city_url,
    COUNT(DISTINCT shops.id) AS totalshops,
    ST_Distance_Sphere(POINT(:longitude, :latitude), POINT(cities.longitude, cities.latitude) AS distance
FROM cities
JOIN shops
    ON
    shops.city_id = cities.id
JOIN shop_categories
    ON
    shop_categories.shop_id = shops.id
WHERE
    shop_categories.category_id = :catId
    AND
    cities.longitude BETWEEN :longitude - :max_long_distance AND :longitude + :max_long_distance
    AND
    cities.latitude BETWEEN :latitude - :max_lat_distance AND :latitude + :max_lat_distance
GROUP BY
    cities.id
ORDER BY
    distance ASC
LIMIT 1
;

PS: I assumed for the GROUP BY clause you're not running with the strict grouping mode enabled. If that's not the case you'll need to add the other columns from cities that are references like the cities.city, cities.city_url, cities.longitude and cities.latitude.


Filewatcher compiler for watching different files I'm trying to create a filewatcher program that can watch different files. The files might have subfiles that are being imported into the main file, which is being represented by the file object. I'm feeling the code is a little messy and I would like to know how I can improve it.

The input_watcher() is not there to stay, it is being replaced by a GUI eventually, but it's just there for testing.

import multiprocessing
import threading
import os
import time

file_lock = threading.Lock()
update_interval = 0.1

class FileMethods(object):
    def a_import(self):
        # do some sort of file manipulation

    # all different kinds of filewatching / compiling types
    # will be added as methods and also added to the compiler_methods

class FileObject(FileMethods):
    def __init__(self, full_name, compiler):

        self.full_name = os.path.abspath(full_name)
        self.file_name = os.path.basename(self.full_name)
        self.path_name = os.path.dirname(self.full_name)

        name, exstention = os.path.splitext(full_name)
        self.concat_name = name + '-concat' + exstention

        self.compiler = compiler
        self.compiler_methods = {'aImport': self.a_import}

        self.last_updated = os.path.getatime(self.full_name)

        self.subfiles = []
        self.last_subfiles_mod = {}

    def exists(self):
        return os.path.isfile(self.full_name)

    def mod_check(self):
        if self.last_updated < os.path.getmtime(self.full_name):
            self.last_updated = os.path.getmtime(self.full_name)
            print '%s updated' % self.file_name
            return True
        else:
            return False

    def sub_mod_check(self):
        for s in self.subfiles:
            if self.last_subfiles_mod.get(s) < os.path.getmtime(s):
                self.last_subfiles_mod[s] = os.path.getmtime(s)
                return True

        return False

files = []

def input_watcher():
    while True:
        input_file = os.path.abspath(raw_input('Input file name: '))
        compiler = raw_input('Choose compiler: ')

        if os.path.isfile(input_file):

            obj = FileObject(input_file, compiler)

            with file_lock:
                files.append(obj)

            print 'Adding %s with %s as compiler' % (obj.file_name, obj.compiler)
        else:
            print 'File does not exists'

def file_manipulation():
    for f in files:
        p = multiprocessing.Process(target=f.compiler_methods.get(f.compiler)())
        p.start()

def file_watcher():
    while True:
        with file_lock:
            file_manipulation()
        time.sleep(update_interval)

if __name__ == '__main__':
    iw = threading.Thread(target=input_watcher)
    fw = threading.Thread(target=file_watcher)

    iw.start()
    fw.start()

Sort your imports alphabetically. Make it easier to find.  - Core libs first, then 3rd party.

import multiprocessing
import threading
import os
import time

Constants are typically in all caps.

file_lock = threading.Lock()
update_interval = 0.1

If you have some TODOs, a common practice is to use code tags.

# FIXME:
# TODO:

It's not a must standard, but it is something that is easily recognizable.

class FileMethods(object):
    def a_import(self):
        # do some sort of file manipulation

Ditto on the docstring. Include a desc of your attributes as well.

class FileObject(FileMethods):
    def __init__(self, full_name, compiler):

I would change

self.concat_name = name + '-concat' + exstention

self.concat_name = ''.join([name, '-concat', extension]) # Assuming extension was a typo.

I don't see this method being used anywhere. You also have an if statement further down
in your code. I would remove this if your not using it. Also, I probably wouldn't create a method for this unless I had to write this out more than 2 times. I only see one instance in your code.

def exists(self):
    return os.path.isfile(self.full_name)

Is this script meant to run interactively? If so, I would suggest adding an interactive flag.

So you can run this in automated fashion (maybe with a config file), or a -i so I can be prompted for input. Also, I would change your print statements to the nicer print statements. They
also add more flexibility. Consider using argparse for this.

print '%s updated' % self.file_name

print '{} updated'.format(self.file_name)

Docstrings

def sub_mod_check(self):

Ditto on the print statements:

Use .format

        print 'Adding %s with %s as compiler' % (obj.file_name, obj.compiler)
    else:
        print 'File does not exists'

Consider using a main function or method to wrap your logic into when calling your script.

if __name__ == '__main__':
    iw = threading.Thread(target=input_watcher)
   s fw = threading.Thread(target=file_watcher)

if __name__ == '__main__':
    main()


Creating two dictionaries to lookup values into an array In my attempt to help improve Using Array to store calculations in VBA, I figured a good way to do it would be to create two dictionaries of values to lookup.

So this was my attempt at creating two dictionaries from two sheets and then gathering data from a third sheet into an array and looking up the items in the array based on a condition as to which dictionary to use.

My sample is pretty small and the last line of printing was just to see it worked. I actually struggled with this for a little while, so I'm thinking there are some improvements to be made. Also - is this sufficiently made to be scaled up to millions of data points? What about more than one dictionary - should that be refactored? What if there are more criteria needed for the lookup?

Option Explicit

Public Sub ArrayLookupAndPopulate()
    Dim firstTable As Object
    Set firstTable = CreateObject("Scripting.Dictionary")
    Dim secondTable As Object
    Set secondTable = CreateObject("Scripting.Dictionary")
    Dim rowNumber As Long
    Dim myKey As String
    Dim lookupArray As Variant
    Dim myIndex As Long

    For rowNumber = 1 To 10
        firstTable.Add CStr(Sheet1.Cells(rowNumber, 1)), Sheet1.Cells(rowNumber, 3)
        secondTable.Add CStr(Sheet2.Cells(rowNumber, 1)), Sheet2.Cells(rowNumber, 3)
    Next

    Dim lastRow As Long
    lastRow = Sheet3.Cells(Rows.Count, "A").End(xlUp).Row
    Dim lastColumn As Long
    lastColumn = Sheet3.Cells(1, Columns.Count).End(xlToLeft).Column + 1

    ReDim lookupArray(1 To lastRow, 1 To lastColumn)
    lookupArray = Sheet3.Range(Cells(1, 1), Cells(lastRow, lastColumn))

    For myIndex = 1 To 9
        myKey = lookupArray(myIndex, 2)
        If lookupArray(myIndex, 1) = "First" Then lookupArray(myIndex, 3) = firstTable.Item(myKey)
        If lookupArray(myIndex, 1) = "Second" Then lookupArray(myIndex, 3) = secondTable.Item(myKey)
    Next

    Sheet3.Range("F1:H9") = lookupArray

End Sub

I don't want to edit the code, but I just realized I don't need to redim.

This is pretty sound, although I never like just creating objects. I normally import the library I want to reference right off the bat. Dictionary and most of those scripting objects are (I believe) in the Microsoft Scripting Runtime library. So just add that reference and you can change

Dim firstTable As Object
Set firstTable = CreateObject("Scripting.Dictionary")
Dim secondTable As Object
Set secondTable = CreateObject("Scripting.Dictionary")

to:

Dim firstTable as Dictionary
Dim secondTable as Dictionary
Set firstTable = new Dictionary
Set secondTable = new Dictionary

The only other critique I would have is to split up those If Statements, but that's all a matter of taste in my opinion (There are some that would have gripes about the formatting of If and Then on the same line)

Overall it's pretty solid code. Kudos!


Reducing cyclomatic complexity I ran a sonar analysis on my code and it told me the cyclomatic complexity is too high (sonar's limit is ten branches).

Here is my code:

public void myMethod(){
  try{
  // do something
  catch(SomeException e){
    throw new WrappingException("issue when doing something " + e.getMessage(), e);
  }
  catch(AnotherException e){
    throw new WrappingException("issue when doing something " + e.getMessage(), e);
  }
  // lots of other Exceptions
}

Basically, I want to catch a large set of Exceptions, (maybe always processing the same behaviour). I read the question Catching multiple types of exceptions when writing JSON but I don't use Java 7 (with which I could have all Exceptions in one catch statement) and I do not really want to catch ALL Exceptions, since I want my code to fail in a case I did not expect.

Is there any alternative that would involve fewer branches?

NOTE: What I want to achieve here is not to recover from any Exception, but to categorize the Exceptions. An upper layer is in charge of handling Exceptions, but for this purpose, Exceptions need to be properly categorized.

As JohnMark13 stated in the comments above, if the exceptions you want to catch share a common supertype (possibly besides the basic Exception class), then you could catch the supertype instead of all the subtypes. If you have created the SomeException and AnotherException classes yourself, then I strongly suggest that you make them extend a common custom exception type.

Also, I think that since you rethrow the exceptions (or at least most of them), then catching the general Exception is OK. Or, you could first catch all RuntimeExceptions, rethrow them directly, and then check the rest and possibly throw your WrappingException. Consider this:

public void myMethod() {
    try {
        // do something
    }
    catch (RuntimeException e) {
        // We don't need to wrap these, so we just throw the same exception again
        throw e;
    }
    catch (YourCommonSuperException e) {
        throw new WrappingException("issue when doing something " + e.getMessage(), e);
    }
    catch (Exception e) {
        // All other excpetions, such as `IOException` and stuff will be caught and wrapped and throwed here.
        throw new WrappingException("issue when doing something " + e.getMessage(), e);
    }
    // No need for any other Exceptions
}

Perhaps you get some extra cyclomatic complexity from the // do something part. If so, then you could split that part into multiple methods and possibly declaring to throw the exception from the method if needed so that it will get caught in this myMethod() (or catch within the method and throw some kind of YourCommonSuperException.

Depending on the specific // do something part, you might want to overlook which kind of exceptions that are thrown there. If you throw them yourself, it might be possible to change to IllegalArgumentException, IllegalStateException (which both extend RuntimeException) or some exception that extends YourCommonSuperException.