Yet another smart pointer implementation for learning

Main problem with the reference counter:

As it stands right now, your code will eventually leak or try to delete the same pointer more than once. You are keeping a diferent reference count inside each smart pointer, which is not synchronised, so smart pointers sharing the same object can have different counts for the same memory. Take this simple example, similar to your second one:

sp<MyObject> ptr1 = new MyObject(); // ptr1.ref_cnt = 1
sp<MyObject> ptr2 = ptr1; // ptr1.ref_cnt = 1, ptr2.ref_cnt = 2
// Now we have two different counts for the same object!

Once you pass the copy constructor or assignment operator, the reference count of the original pointer is left unaltered. This cannot possibly end well. That's why in the original example you've linked the author used a pointer for the reference counter as well, so that any smart pointer sharing ownership of an object can also point to the same counter. Once the owned object is to be freed, the last pointer also frees the counter.

One cleaver trick to avoid allocating the counter in a separate new call is to allocate both the object and the counter as the same block of raw bytes, then adjust the pointers and construct the object on the remaining memory. This is how some implementations of std::make_shared() work. Once you fix the counter issue, you might want to try this optimization.

Other issues with the code:

This destructor seems broken:

   ~sp() {
     if(ptr_)
       std::cout << "~sp: " << ptr_ << ", ref count: " << ref_cnt_ << std::endl;
       --ref_cnt_;
       if(ref_cnt_ == 0)
         delete ptr_;
   }

Didn't you forget to wrap the first if with curly braces? This seems like a case where the indenting of the code tries to tell the reader one thing, while the code does a different thing. The first if only applied to the cout call. To avoid this confusion, it is a good idea to always provide { } even for single line control statements. So this is how I believe you intended to write, since it wouldn't make sense decrementing the counter if the pointer is null:

~sp() {
    if(ptr_) {
        std::cout << "~sp: " << ptr_ << ", ref count: " << ref_cnt_ << std::endl;
        --ref_cnt_;
        if(ref_cnt_ == 0) {
            delete ptr_;
        }
    }
}

The comparison operators that take a raw pointer should take that pointer by const T*, to make clear that they do not attempt to modify the pointed object.
You'll probably also want to provide overloads of operator * and -> that are const and return const pointer and reference. Otherwise you aren't able to call those on a const sp<T>.
Your class still requires a lot of tuning and polishing to be anywhere near usable. If you plan on taking it a step further, I recommend reading Modern C++ Design. The book has a dedicated chapter on Smart Pointers. It is very detailed and well written and I think it is still one of the best references out there on SPs, even though it was released before C++11.


Canonical Implementation of Move Semantics

One small error: Mark the move constructor as noexcept, otherwise there are situations where it won’t be used. The linked case is different since the class has a copy-constructor, yet I can imagine that there are still situations where it matters, especially since your copycon isn’t deleted, just private and undefined.
Why is the destructor virtual? If the example is supposed to be minimal then this might be distracting.
In generate_it:

return std::move(Moveable(foo));

The std::move here is redundant, since you are returning a temporary. What’s more, the explicit constructor call is redundant too, since the constructor isn’t marked as explicit. Just return foo; will do.
The find_if call could be replaced by vanilla find, using temporary construction again:

auto that = find(v.begin(), v.end(), target);

Finally, in the sort call, why aren’t the arguments declared const&? Granted, makes the line even longer as it stands this is inconsistent with the const-correctness illustrated in the find_if call.


Is this a reasonable way to implement promises in node.js?

Define all your error types globally in some file for convenience, like the built-in errors are defined.

Mixing promises and callbacks is a big anti-pattern, just think in promises and let .nodeify handle the mapping to callback equivalent at the end.

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var Promise = require('bluebird');
var bcrypt = require('bcrypt');
var db = require('./db').db; //users are stored in mongo

//I'm using bluebird.js for promises
var users = Promise.promisifyAll(db.users);
var compare = Promise.promisify(bcrypt.compare);

// This strategy is used by passport to handle logins
module.exports.localStrategy = new LocalStrategy(function(username, password, done) {
  users.findOneAsync({username: username}).bind({})
    .then(function(user) {
        if (!user) {
          throw new NoMatchedUserError('Incorrect username.');
        }
        this.user = user;
        return compare(password, user.password);
    })
    .then(function(isMatch) {
      if (isMatch) {
        return this.user;
      }
      else {
        throw { message: 'Incorrect password.' };
      }
    })
    .nodeify(done);
});


I would tag your struct in addition to, if not instead of, using a typedef:

struct v2
{
    int x, y;
};
// typedef struct v2 v2;

Then you can use struct v2 wherever you are using v2. This makes it clear that v2 is a structure.

I think you should create a symbolic SUBGRID_SIZE instead of using 3 here:

x0 = (pos.x / 3) * 3;
y0 = (pos.y / 3) * 3;

for (i = 0; i < 3; ++i)
    for (j = 0; j < 3; ++j)
        if (board[i + y0][j + x0] == v)
            return 0;

This would make it more obvious about what you're dealing with. I would put GRID_SIZE and SUBGRID_SIZE next to each other, and then use an #if to check if they're valid:

#define GRID_SIZE 9
#define SUBGRID_SIZE 3

#if SUBGRID_SIZE * SUBGRID_SIZE != GRID_SIZE
# error grid size and subgrid size dont match
#endif

You might use printf("\n"); or putchar('\n'); instead of puts("");. The compiler is likely to optimize the former into puts(""); anyway, and the second may be faster.

I like that you've used const everywhere that you're not going to modify a variable. This eliminates chances to make mistakes.

Your formatting is very good. It is consistent, too.

Your code is also well-commented. The only thing that was slightly non-obvious you've commented:

/* 0 represents an empty cell */

Being pedantic with you, your code has zero warnings with -Wall -Wextra -std=c99 -pedantic.


Creating an enumerable by calling a function returning enumerables

There is no need to create lists and add items to the lists when working with enumerables; yield is your new best friend.

As written, GetScheduleList() is messy to unit test so we can push the condition up a level and then use yield

private static IEnumerable<KpiSchedule> GetScheduleList(PlantConfiguration plant, bool includeDaily)
{
    yield return plant.HourlySchedule;
    if (includeDaily)
    {
        yield return plant.DailySchedule;
    }
}

To aggregrate the schedules for each plant we can use SelectMany().

private static IEnumerable<KpiSchedule> GetAllSchedules(IEnumerable<PlantConfiguration> allPlants, bool includeDaily)
{
    return allPlants.SelectMany(p => GetScheduleList(p, includeDaily));
}

We can now revise UpdateValues() to something like

private static void UpdateValues(PlantList plantList)
{
    DateTime utcTopHourDate = GetUtcTopHourDate();
    var includeDaily = CheckIncludeDaily(utcTopHourDate);

    var schedulesToUpdate = GetAllSchedules(plantList.Plants, includeDaily);
    //... Do stuff with the schedule list

}

or even

private static void UpdateValues(PlantList plantList)
{
    DateTime utcTopHourDate = GetUtcTopHourDate();
    var includeDaily = CheckIncludeDaily(utcTopHourDate);

    var schedulesToUpdate = plantList.Plants.SelectMany(p => GetScheduleList(p, includeDaily));
    //... Do stuff with the schedule list
}


#region

#region CreateTenant

Get rid of those. The region encompasses only a single method anyway, and your IDE should already allow you to collapse method scopes. Even if the region had more content, I'd recommend against it. See:

Are #regions an antipattern or code smell?

comments

//open the connection
this.connection.Open();

//start the transaction
this.transaction = this.connection.BeginTransaction();

These comments are about as useful as:
i++; // increment i

Good comments are comments that let the code speak for itself and only show up when there's a need to say why the code is doing what it's doing.
Good comments say why, not what. I would simply remove all comments in your code, because comments that state the obvious are nothing but a distraction and a waste of time.

this.transaction.Dispose();  //Transaction dispose

exceptions
Something hit me in your description of the code:

Finally or Catch Code block gets executed

That's not how finally works. finally blocks get executed regardless of whether or not an exception was thrown - it runs even when the catch block runs.
Speaking of the catch block:

    catch (Exception ex)
    {
        this.transaction.Rollback();
        throw ex;
    }

The problem is that throw ex isn't how you cleanly rethrow an exception. What you've done here destroys the stack trace and as far as client code is concerned, the stack trace begins in the catch block of this CreateUser method, which we all know is a lie.
This would have preserved the precious stack trace with all of its information:
    catch (Exception)
    {
        this.transaction.Rollback();
        throw;
    }

unit of work
A unit of work encapsulates a transaction - you know that.

    private IDbConnection connection;
    private IDbTransaction transaction;

That was a good start!
The problem is that, well..

finally
{
    this.transaction.Dispose();  //Transaction dispose
    this.transaction = null;

    this.connection.Close();
    this.connection.Dispose();
    this.connection = null;
}

You can only ever call the method once in a transaction. You own that transaction and that connection, so you should be disposing them.. and you do... but then if they're only going to be used in the CreateUser method, they shouldn't be instance-level fields, but local variables wrapped in a using block - and then you wouldn't even need that finally block.
Your disposing is overkill. Setting the object reference to null is useless, as is explicitly Close()-ing a connection that you're Dispose()-ing.
Alternatively, take the connection and transaction as a constructor argument, keep the instance-level fields, and implement IDisposable to dispose them.


Optimizing priority queue streaming algorithm in C++

You could create a

struct Element {
   int value;
   std::string id;
};

and store that in the priority queue. Then you don't need the map. Your compare function would of course only look at the value component:

struct compare {
   bool operator()(const Element& l, const Element& r) {
       return l.value > r.value;
   }
};

Note that it is possible to use a naked function as comparator, it doesn't need to be a functor:

bool compare(const Element& l, const Element& r) {
   return l.value > r.value;
}

std::priority_queue<Element, std::vector<Element>, decltype(compare)> heap(compare);


Overall
I think you have too much code in the main method. You should split that into more digestible segments. Perhaps some more methods in your GameLogic class (which probably should be split into one Game class and one GameBot / Player class). (At least) one method for determining the next move, one method for choosing the proper action based on the current tile, etc..
Improving your bot
Assuming the gold never moves once it is placed, you could use a Set of all the tiles you have visited. You could then try to not move to a tile you have already visited.
The tiles themselves could be represented as a Point class that contains x and y, or it could be represented as an int if you do a little mathematics to represent a column and row by one single int (I do recommend the Point class though). Or you could make a Tile class, since each tile also has some content (wall, exit, gold, empty space...)
Random
Random rn = new Random();
int min = 0;
int max = 3;
int n = max - min + 1;
int i = rn.nextInt(n);

Since min is zero, there's no need to do - min.
As max is a constant, it'd be easier to declare max as 4 from the start rather than using + 1
As n only is used once, you could just use int i = rn.nextInt(4);
Random objects are meant to be re-used. Initialize your Random object outside the loop. This is because randomization will be different when creating the object over and over again.

Moving
You can move in four directions, this is telling me that you should use a Direction enum and replace your four methods with one move(Direction4 dir); By using this enum, you could also simplify your random process:
Direction4 chosenDirection = Direction4.values()[rn.nextInt(Direction4.values().length)];

This line grabs all the possible directions and randomizes an int from 0 (inclusive) to length (exclusive) and grabs the direction with that index.
When something goes wrong
System.out.println("SOMETHING WENT WRONG!!!");

I can assure you, this will never happen. And even if it would, Exceptions are meant to be for... well, exceptions. throw new AssertionError("Something went wrong."); is what I would have done here. Or rather... I would have removed the entire line, as it will never happen. Especially when you use the Direction4 approach.
Spacing
This is one of the things I mention most often in my reviews probably, but please:
}else if(i == 1){

change to
} else if (i == 1) {

It makes the code more readable with proper spacing.


Port Availability Scanner, written in Java (9)

Why do you create a million element array? (int[] ports = new int[1_000_000]) It'd better to make it as large as the ports in constructor (end-start or ports.length)
Why all of this code?

if(ports.length > 1) {
    for (int port : ports) {
        System.out.println("Available " + port + ": " + Test.isAvailable(port));
    }
} else if(ports.length == 1) {
    System.out.println("Available " + ports[0] + ": " + Test.isAvailable(ports[0]));
} else {
    throw new IllegalStateException();
}

You only really need

for (int port : ports) {
    System.out.println("Available " + port + ": " + Test.isAvailable(port));
}

The result will be equivalent and the code is now more readable
Why did you make ip and instance static? Do you want to make the class a singleton?
The ports label is unnecessary in the first constructor
Use InetAddress instead of String for IPs' as from what I know Sockets convert the strings into InetAdresses anyway. It should somewhat improve performance (change ip variable from String to InetAddress so you don't recreate the address on and on again)
Shouldn't this:

try {
    socket = new Socket(ip, port);
    return false;
} catch (IOException e) {
    return true;
} finally {
    if(socket != null) {
        try {
            socket.close();
        } catch (IOException ignored) { }
    }
}

work the other way round? Why method isAvailable returns true when the
socket throws a exception? Looks like a bug to me I misunderstood what you
meant by available. Your code is correct


Overloading istream>> to read comma-separated input

95 percent of programming is looking for redundancies and eliminating them.

For example, why do you bother with reading strings into accusations[] first, and then later copying them into readable.murderer et cetera? Why not just read them directly into readable.murderer? This would have the bonus of eliminating those "magic number" indices 0, 1, and 2, and replacing them with readable (no pun intended) identifiers.

std::getline(is, readable.murderer, ',');
std::getline(is, readable.weapon, ',');
std::getline(is, readable.place, ',');  // shouldn't this last one be '\n' not ','?

You should test your code and see if it does what you wanted.

std::istringstream iss(
    "Mr Green, lead pipe, conservatory\n"
    "Mrs Peacock, noose, kitchen"
);
accusation acc;
iss >> acc;

This reads 5 items into accusation. Is this what you wanted to happen?

Reduce repetition. You have the following snippet repeated three times:

    for (const auto& THING : THINGS)
        if (accusation[INDEX] == THING)
        {
            valid = true;
            break;
        }

So, first of all, we wrap the loop body in curly braces to protect against goto fail; and then we factor it out into a function.

template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value) {
    for (auto&& elt : vec) {
        if (elt == value) {
            return true;
        }
    }
    return false;
}

And then our main function's code can become simply

bool valid = vector_contains(clue::characters, readable.murderer)
          && vector_contains(clue::weapons, readable.weapon)
          && vector_contains(clue::places, readable.place);
if (!valid) {
    is.setstate(std::ios_base::failbit);
}

The body of vector_contains could also be implemented simply by using an STL algorithm, e.g.

template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value) {
    return std::count(vec.begin(), vec.end(), value);
}

or

template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value) {
    return std::find(vec.begin(), vec.end(), value) != vec.end();
}

or

template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value) {
    return std::any_of(vec.begin(), vec.end(), [&](const auto& elt) {
        return elt == value;
    });
}

I named the function vector_contains, rather than simply contains, because in my estimation there is a very real possibility that C++2a might add std::contains to the library and thus break any code using ADL calls to contains.

Minor nits:

I strongly recommend making all your constructors explicit, to eliminate bugs from unintentional implicit conversions. (Yes, even your multi-argument constructors.)
I strongly recommend making operator>> and operator<< into inline friend functions — define them right inside the body of your class. This will make them findable only via ADL, and is generally what you want. It'll look a lot more reasonable, too, once you've refactored your operator>> to be only five or six lines long! :)

You're also doing something weird with stringstream to remove whitespace from the ends of each piece of the string. You should factor that out into a helper function, and then simplify it. Say,

std::string strip(const std::string& s)
{
    int i = 0;
    while (isspace(s[i])) ++i;
    int j = s.size();
    while (j >= 1 && isspace(s[j-1])) --j;
    return s.substr(i, j-i);
}

https://wandbox.org/permlink/uVSolN0Nepk48Mgm

class accusation
{
private:
    std::string murderer;
    std::string weapon;
    std::string place;
public:
    accusation() = default;
    explicit accusation(std::string, std::string, std::string);
    friend std::ostream& operator<<(std::ostream&, const accusation&);
    friend std::istream& operator>>(std::istream& is, accusation& a) {
        std::getline(is, a.murderer, ',');
        std::getline(is, a.weapon, ',');
        std::getline(is, a.place);
        if (!vector_contains(clue::characters, a.murderer) ||
            !vector_contains(clue::weapons, a.weapon) ||
            !vector_contains(clue::places, a.place)) {
            is.setstate(std::ios_base::failbit);
        }
        return is;
    }
};

Deciding whether your std::transform lowercasing should be removed, kept, or folded into the helper function vector_contains (renaming that function to indicate its new purpose, and using a non-mutating facility such as strcasecmp) is left as an exercise for the reader.


Best way to work out angle between points?

First of all, let's define the problem precisely.  According to your comment, this is the behavior you want:

  You are correct in believing I am expecting it to be relative to 12 o'clock, and for it to move clockwise.

However, your code doesn't actually behave that way.  Your angle() function, as written, computes the orientation of point relative to this, with 6 o'clock being 0°, angles increasing counterclockwise, with return values in the range [0, 360).  (Alternatively stated, your angle() computes the orientation of this relative to point, with 12 o'clock being 0°, angles increasing counterclockwise, with return values in the range [0, 360).)  So, I'm reviewing erroneous code.

As evidenced by the comments, many people had problems understanding what you meant by the "angle between two points".  That's a vocabulary problem.  I suggest that you borrow a term from navigation: bearing.  In this review, I'll use the term "bearing" to refer to your desired behavior: when point is taken relative to this, 12 o'clock is considered to have a bearing of 0°, with values increasing clockwise, up to 360°.  I'll continue to use the term angle to refer to the erroneous behavior of your angle() function.

First of all, let's see how we can calculate the angle without having to do aD -= 270.  We can accomplish this by mapping the axes strategically when calling atan2().  The direction for which we want the arctangent to be 0 is an "x′ axis" of our mapped plane, and the direction for which we want the arctangent to be π/2 we will call our "y′ axis".

Here it is written out:

// Same behavior as angle(), but implemented without aD -= 270.
Point.prototype.nicerAngle = function(point) {
    var delta = point.subtract(this);
    var aR = Math.atan2(delta.x, -delta.y); // Mapped axes!
    var aD = aR * (180 / Math.PI);
    if (aD < 0) {
        aD += 360;
    }
    return aD;
};

Note that your while loop can simply be an if conditional.

Note that Math.atan2() is guaranteed to return a value in the range [-Math.PI, +Math.PI].  (See footnote below.)  We should now ask, is it possible to get rid of the conditional altogether?

One reason to get rid of the conditional is to reduce the number of code paths — fewer code paths means fewer cases to worry about in code-coverage tests.  Another reason is performance — if the CPU can always execute the code sequentially, then it doesn't have to do branch prediction.  When faced with a branch, CPUs speculatively execute code in advance, then throw away the results from the branch not taken.  (That's true for a low-level language like C.  It probably wouldn't matter at all for a naïve JavaScript interpreter.  It might make a difference on a highly optimized JavaScript JIT.  Anyway, the code-path-reduction argument alone should be a good reason to try to eliminate the conditional.)

Well, if we always add π to the value returned by Math.atan2(), then the result would be in the range [0, 2 * Math.PI].  It's a simple matter of mapping the axes to make that work for us.  We want to map the axes such that 12 o'clock yields an atan2 of 0° (our x″ axis), increasing counterclockwise such that 9 o'clock is 90° (our y″ axis).  If we can accomplish that, then adding 180° would map 6 o'clock to 0° and 3 o'clock to 90°.  Here is a diagram:

… and a solution:

// Same behavior as nicerAngle(), but implemented without if-statement.
Point.prototype.unconditionalAngle = function(point) {
    var delta = point.subtract(this);
    var aR = Math.atan2(-delta.x, delta.y);
    return 180 + aR * (180 / Math.PI);
};

So, what about computing bearing?  Once again, we simply have to remap the axes when calling atan2().  Using the same ideas as before,

// Computes orientation of point relative to this, with 12 o'clock being 0 degrees, angles
// increasing clockwise, with return values in the range [0, 360].  Implemented like
// unconditionalAngle().
Point.prototype.bearing = function(point) {
    var delta = point.subtract(this);
    return 180 + 180 / Math.PI * Math.atan2(-delta.x, -delta.y);
};

Of course, if you really wanted top performance, you could make this a one-liner by doing away with the intermediate delta object.

Footnote about unconditionalAngle() and my unconditional implementation of bearing()

Note that I said that Math.atan2() returns values in the range [-Math.PI, +Math.PI], not [-Math.PI, +Math.PI).  Therefore, with the unconditional implementations, it is possible to get a result of 360°, for example, with ORIGIN.unconditionalAngle(new Point(-0, -1)) and ORIGIN.bearing(new Point(-0, 1)).  All I'll say here is that proper IEEE floating point math has a useful concept of negative zero.  I'll leave it to you to decide whether you want to deliberately stamp out this manifestation of that concept.

Here's a jsFiddle of all the code above.


PyLint is a useful tool for checking your code, ensuring good coding habits.  For example, PyLint doesn’t like a lack of spaces around operators or after commas.  Neither do my old weak eyes.  Instead of this:

pos_matrix=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]

... code like this:

pos_matrix = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]

An if statement that does a return or exit doesn’t need to be followed by an else or elif; if the if statement is true, the execution path doesn’t need to skip around the else clause, because execution has already left the function.

For clarity:

if pos_matrix[pos[0]-1][pos[1]-1]!=' ':
    print('Invalid input')
    exit
else:
    pos_matrix[pos[0]-1][pos[1]-1]=symbol

for i in range(0,3):
    # print rows of game grid

After the if-else statement is the code to print out the game grid.  It appears this code belongs to both paths through the if-else, where as it will only execute if the False path is taken.  As such, it should be indented to belong as part of the else: clause:

if pos_matrix[pos[0] - 1][pos[1] - 1] != ' ':
    print('Invalid input')
    exit
else:
    pos_matrix[pos[0] - 1][pos[1] - 1] = symbol

    for i in range(0,3):
        # print rows of game grid

Alternately, the else: can be omitted entirely, and the statement in the else: clause outdented to the same level as the if statement:

if pos_matrix[pos[0]-1][pos[1]-1]!=' ':
    print('Invalid input')
    exit

pos_matrix[pos[0]-1][pos[1]-1]=symbol

for i in range(0,3):
    # print rows of game grid

Invalid input should not unconditionally terminate the program.

if pos_matrix[pos[0]-1][pos[1]-1]!=' ':
    print('Invalid input')
    exit

This code makes it harder to use in a larger program, since an invalid input will terminate the entire program.

Instead, a ValueError exception should be raised:

if pos_matrix[pos[0] - 1][pos[1] - 1] != ' ':
    raise ValueError('Invalid input')

This allows the caller to use a try ... except: structure.  The user could enter an invalid input, the function detects this and raises the error.  The caller catches the error, and request the user re-enter a valid move.

Without the appropriate try ... except: statement, raising the exception will also terminate the program.

You decode pos using [pos[0]-1][pos[1]-1] multiple times.  This is ugly and hard to follow.  Use variable names to avoid repeating the same calculations:

row, col = pos[0] - 1, pos[1] - 1

Then you can write:

if pos_matrix[row][col] != ' ':

Instead of looping over range(0, 3) or [0, 1, 2], just use range(3):

for i in range(3):
    ....

def my_tictactoe(pos,symbol):
    ...
    pos_matrix[pos[0]-1][pos[1]-1]=symbol
    ...
    print('GAME OVER. \n Player with symbol {x} wins!'.format(x=pos_matrix[pos[0]-1][pos[1]-1]))

Why the complex expression to set xin the format statement?  You’ve just assigned symbolto that pos_matrix entry; just use that!

print('GAME OVER. \n Player with symbol {x} wins!'.format(x=symbol))

Or better, if you are using python 3.6 or later, use an f-string:

print(f'GAME OVER. \n Player with symbol {symbol} wins!')

Your is_win code is more complex than needed because you are checking if anyone has won, which means a row, column or diagonal has 3 of the same symbol, which is not a space.  If you passed the symbol to the function, you can check if that player has won, which means checking for 3 of that symbol only, which is slightly shorter & simpler.

def is_win(symbol):
    for i in range(3):
        if all( pos_matrix[i][col] == symbol for col in range(3)):
            return True
        if all( pos_matrix[row][i] == symbol for row in range(3)):
            return True
    if all( pos_matrix[i][i] == symbol for i in range(3)):
        return True
    if all( pos_matrix[i][2 - i] == symbol for i in range(3)):
        return True
    return False

Who's turn is it, anyway?

You call my_tictactoe(...) and pass in the character to place in the grid.  As Hack Saw pointed out, this could be a 'p'!

Instead, it would be better for the game to keep track of who's turn it is, and automatically use the appropriate symbol.

For example, you could set a global symbol variable initially to 'x', and then have it flip between 'x' and 'o' after processing a valid move.

symbol = 'x'

def my_tictactoe(pos):

    # ... existing validation, printing, and win detection code ...

    # Alternate players: 'x' <--> 'o'
    symbol = 'o' if symbol == 'x' else 'x'

As a bonus, after one player wins, the other player will automatically become the first player.

To test the program, with the automatic player tracking, (expanding on Hack Saw's suggestion a bit) the test code could become:

def main():

    for pos in ((1,1), (2,2), (3,2), (1,3), (2,1), (3,3), (3,1), (1,2)):
        my_tictactoe(pos)

if __name__ == "__main__":
    main()


Thank you for showing your code. You really should show us how to use it, by including unit tests, a reference URL, or with comments. At a minimum the class needs a docstring.

self._state = "unfullfilled"

Typo. Consider using enum.Enum instead of str.

self.value = None

This appears to be just wrong. (Hard to tell, since no docstring describes what valid callers may do.) A fn could choose to return None, yes? The usual approach for such a sentinel is to invoke object() to create a private object, essentially an allocated memory location that other code doesn't know about. Then test equality against that. If, on the other hand, you want your API to prohibit passing None, then you'll want to add some checks for that.

self.errors.remove(i)

That's an odd way to phrase it. The usual idiom for the loop you wrote would be to .pop() the initial element. Consider switching from list to deque if lots of errors might accumulate.


There are a number of typos in your code blocks, that lead me to believe the code wasn't taken from the working code in your IDE. I will assume the following:

IBaseRcovery is really IBaseRecovery
RecoveryPresenter( IBaseRecover model, ... is really RecoveryPresenter(IBaseRecovery model, ...
SqlCommand sqlCommand = new SqlCommand("BEGIN INSERT INTO recovery ; is really SqlCommand sqlCommand = new SqlCommand("BEGIN INSERT INTO recovery ...");

That said, the naming feels awkward with an underscore followed by a capital letter:

this._Model = model;
this._View = view;
this._DataService = dataService;

I would rather see this:

_model = model;
_view = view;
_dataService = dataService;

Or that:

this.model = model;
this.view = view;
this.dataService = dataService;

But not a mixture of both.

The raison d'être of the underscore prefix is to avoid having to use the this qualifier; if you prefix a field name with an underscore and use this, you're cluttering up your code.

Also convention is camelCase (i.e. lowercase first letter) for private fields, local variables and parameters. PascalCase (i.e. uppercase first letter) is for type and member names (classes, interfaces, delegates, enums, events, methods, etc.).

You can declare a variable without initializing it. When it's a reference type, it's set to null until you assign it a reference. Hence, this is perfectly redundant:

IBaseRecovery recovery = null;

You could just do this:

IBaseRecovery recovery;

Looks like generics could come in handy here:

public RecoveryPresenter(IBaseRecovery model, IRecoveryForm view, IDataService dataService)

Can turn into a constructor for a generic class:

public class Presenter<TView, TModel>
    where TView : IView
    where TModel : class
{
    private TModel _model;
    private TView _view;
    private IRepository<TModel> _repository;

    public Presenter(TModel model, TView view, IRepository<TModel> repository)
    {
        _model = model;
        _view = view;
        _repository = repository;
    }

    /* ... */
}

If IBaseRecovery is only a marker interface with no members, get rid of it, it smells.

The key here, is IRepository<TModel>: your DataService has too many responsibilities, its interface will keep getting modified as you add more features to your application (i.e. as you need to deal with more database tables), and that's not very cleanly extensible.

The IRepository<TModel> interface could look something like this:

public interface IRepository<TModel> where TModel : class
{
    void SelectAll();
    void GetById(int id);
    void Insert(TModel model);
    void Update(TModel model);
    void Delete(TModel model);
}

Look into the repository pattern for more information. The idea is that you'll have a family of specialized classes, all presenting the same interface, that perform similar operations on different parts of the underlying database:

public class LoanRepository : IRepository<Loan>

public class FineRepository : IRepository<Fine>

...

You can even derive all these classes from an abstract ReposityBase class (non-generic), and implement the common code only once (i.e. connection set-up & disposal, for example).

Now, if your presenter is going to be dealing with more than a single database table / repository, you have a problem; that problem is solved with a unit of work, which the presenter can depend on:

public class Presenter<TView>
    where TView : IView
{
    private IUnifOfWork _uow;
    private TView _view;

    public Presenter(IUnitOfWork uow, TView view)
    {
        _uow = uow;
        _view = view;
    }

    /* ... */
}

Repository and Unit-of-Work patterns usually go hand-in-hand; here is an example of an implementation I've written in VBA recently. It's another language and an earlier data access technology, but you'll find many similarities - look at the pattern, not the code itself.

And/or read up on repository+UoW design patterns; adding these to your arsenal should greatly simplify your life.


First some stylistic points

nums_d.setdefault(nums[i], []).append(i)

The setdefault is unnecessary here, you can assign a list normally

nums_d[nums[i]] = [i]

When you need both the index and the element use enumerate see PEP279

nums_d = {}
for i in range(len(nums)):
    nums_d.setdefault(nums[i], []).append(i)

nums_d = {}
for i, e  in enumerate(nums):
    nums_d[e] = [i]

Use comprehension when possible (They use the C style looping and is considered to be faster)

nums_d = { e: [i] for i, e  in enumerate(nums) }

Hint

You loop over nums twice, but this can be done in one loop! To make it O(n)

Whenever you visit a new element in nums ->

Check if it's sum complement is in nums_d, else add the target - element to the dictionary with the index as value t - e : i

   nums_d = {}
for i, e in enumerate(nums):
    if e in nums_d:
        return [nums_d[e], i]
    nums_d[target - e] = i


You could just build a dictionary mapping classes to functions to call:

class A:
    pass

class B:
    pass

def func_a(x, y):
    return x + y

def func_b(x, y):
    return x - y

if __name__ == "__main__":
    d = {LinkMessage: link_message,
         PictureMessage: picture_message,
         VideoMessage: video_message,
         StartChattingMessage: chatting_message,
         ScanDataMessage: data_message,
         StickerMessage: sticker_message}
    message = PictureMessage()
    funcs[message.__class__]()

Alternatively, if these classes are controlled by you, you could give them all a method called the same name which will be called, maybe handle_message:

class LinkMessage:
    ...
    def handle_message(self, *args):
        pass

if __name__ == "__main__":
    message = LinkMessage()
    message.handle_message(1, 2)


Template matching program to find an image within an image

This code seems very straightforward and easy to read, making it relatively easy to maintain. Here are some ways you could improve it further.
Naming
I would suggest working a bit on your member variable and local variable names. While in math we often use M and N as matrix width and height, it can be confusing which is which, and it can be difficult to communicate which you're talking about when speaking because they sound so similar. I would recommend using width and height as the variable names instead.
Using i and j for loop counters is a well-understood convention and just fine. I would caution against using ii (or iii and iiii as you had in an earlier version of the code) because it's too easy to confuse it with i or make a typo and end up with a subtle bug in your code. (I've done that before!)
Using const
The arguments to almost all of your methods remain unchanged in the method. When that happens, they should be marked as const to let a reader know they won't change. It also helps the compiler in a number of ways.
Performance
You mentioned that it's taking a long time to run. The best way to figure out why is to profile it and see where the slowdown is. I have a guess that it's probably due to the large numbers of copies that the code makes, particularly in getBlock(). I can see 2 ways to improve them:

Don't make a function-call per element you need to copy. Instead use a block copy function like the standard-C library memcpy() function for each row or sub-row you need to copy. This will be much faster than what you're currently doing.
Don't copy anything at all. You could modify the Matrix class to keep track of the width of a row separate from the number of elements in the row. This would allow you to create a new Matrix that just indexed into a current one. You would also need to make sure not to delete the array from that type of matrix, so you'd need another member variable - a bool that says whether it owns the array or not. It's slightly more housekeeping, but the result is that your copies now become a pointer assignment and a little bit of housekeeping instead of actual copies. They almost disappear!


Coin Change Algorithm - coding challenge

I'll start with a review of your existing code, and then make a suggestion
for a better algorithm.

The first thing to notice is that there are many conversions from arrays
to lists and back to arrays:

In the isPresent() function, the array is converted to a list in order
to check if it contains a given number. But the array is already sorted,
so one can call Arrays.binarySearch instead, which is more also efficient.
The possibleDenominations function “truncates” the given array by conversion
to a list and back to an array.
You could compute the last index to be included instead and then return
a subarray with Arrays.copyOfRange. But I am not sure if this truncating
is needed at all, since your solution algorithm already early returns if
the values become too large.
In the removeAndReturn function, the array is converted to a list
and back to an array in order to get a new array with the first element
removed.

All these conversions can be avoided completely: Either

keep the original array and pass indices (of the first and last
entry to be considered) around, or
store the values in an (Array)List right at the beginning, and use
list.subList() to pass views of a portion of the list around, without
actually copying the elements.

The method

public static boolean isPossible(int toMake, int sum, Integer[] arr) {

can be simplified by taking a single parameter targetSum instead of
toMake and sum:

public static boolean isPossible(int targetSum, Integer[] arr) {
    if (targetSum == 0) {
        return true;
    } else if (targetSum < 0) {
        return false;
    }
    for (int num : arr) {
        if (isPossible(targetSum - num, removeAndReturn(num, arr))) {
            return true;
        }
    }
    return false;
}

Further remarks:

“Test” is a non-descriptive name for a program. Why not name it after the
challenge, for example public class CoinChange?
Why do you call nextByte() if the result is assigned to an int?
The variable name coins does not clearly indicate that this is the
number of coins.
coinsDenominationarray is an array, but there is no need to make the type
part of the variable name, I would call it for example coinDenominations or
coinValues.
Most of the code is done in a separate function, which is good. I would put
the calculation of maxPossible and the sorting into that function as well,
so that I/O and the actual computation are separated completely.
The parameter name arr in the solve function  is non-descriptive.
Why not use the same name as in the main program?
All methods (with the only exception of main) can be private.

Putting it all together, the program could look like this:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class CoinChange {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int numCoins = scan.nextInt();

        ArrayList<Integer> coinValues = new ArrayList<Integer>();
        for (int i = 0; i < numCoins; i++) {
            coinValues.add(scan.nextInt());
        }
        int firstNotPossible = findFirstNotPossible(coinValues);
        System.out.println(firstNotPossible);
    }

    private static int findFirstNotPossible(List<Integer> coinValues) {
        Collections.sort(coinValues);

        // Compute sum of values plus one:
        int maxNotPossible = 1;
        for (int value : coinValues) {
            maxNotPossible += value;
        }

        for (int num = 1; num < maxNotPossible; num++) {
            if (!coinValues.contains(num) && !isSummable(num, coinValues)) {
                return num;
            }
        }
        return maxNotPossible;
    }

    // Check if `targetSum` is representable as a sum of numbers in `values`
    // (which is assumed to be a sorted list of positive numbers).
    private static boolean isSummable(int targetSum, List<Integer> values) {
        if (targetSum == 0) {
            return true;
        } else if (targetSum < 0) {
            return false;
        }
        for (int i = 0; i < values.size(); i += 1) {
            if (isSummable(targetSum - values.get(i), values.subList(i + 1, values.size()))) {
                return true;
            }
        }
        return false;
    }
}

A better algorithm

Your isPossible() function solves the "Subset sum problem"
with “brute force,” i.e. by (recursively) trying all possible combinations.

This problem can be efficiently solved with "dynamic programming", as described in
the Wikipedia article.

But this problem can be solved even simpler:

A number \$ N \$  stores the lowest value which is not
representable as sum of coin values considered so far, initially \$ N = 1 \$.
For all values \$ v \$ in the (sorted) array of coin values:

If \$ v > N \$ then we are done, \$ N \$ is not representable.
Otherwise \$ N \$ is incremented by \$ v \$.

This requires only a single traversal of the array, and no additional storage:

import java.util.Scanner;
import java.util.Arrays;

public class CoinChange {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int numCoins = scan.nextInt();

        int[] coinValues = new int[numCoins];
        for (int i = 0; i < numCoins; i++) {
            coinValues[i] = scan.nextInt();
        }
        int firstNotPossible = findFirstNotPossible(coinValues);
        System.out.println(firstNotPossible);
    }

    private static int findFirstNotPossible(int[] coinValues) {
        Arrays.sort(coinValues);

        int firstNotPossible = 1;
        for (Integer value : coinValues) {
            if (value > firstNotPossible) {
                break;
            }
            firstNotPossible += value;
        }
        return firstNotPossible;
    }
}


JSON.stringify is a dangerous function. It fails, and thus your function too, on cyclic objects, on very deep or big objects, or simply on objects having some forbidden accessor deeply cached.

This object can't be logged by your function, for example :

var a = {}; a.b=a;

A related problem is that you only test the type of the external object. You don't detect the problem on this one :

var a = {parent:window};

What I would suggest is

either the addition of a try/catch (which may not be totally satisfying as some stringifications take time and memory before they fail),
to use or build another stringification function (see related SO question)
or simply to avoid the JSON format (of course it depends on your goal)


Bash script that counts the characters, frequency, and percentage of letters in Spanish sonnets

The right tool for the job

Nice script! But Bash is not well-suited for this kind of computation.
Bash is good as glue code,
connecting different applications, bridging the gap,
doing simple stuff.
The task at hand would have been better written in proper programming language, for example Python.

Usability

When the first argument is missing or empty,
the script exits with an error message: "Script needs an argument.".
What kind of argument? It would be better if it gave a hint, for example:

if [ $# = 0 ]; then
    echo "Usage: $0 file"
    exit 1
fi

This gives a hint that the script requires a file argument.

I also changed the condition from -z "$1" to $# = 0.
The former means "first argument is missing or empty",
the latter means "script has no arguments".
This is probably closer to your intention.

Creating empty files

A simple way to create an empty file:

> "$fname"

Don't use flags of echo

The flags of echo are not portable, for example echo -n.
Try to avoid as much as possible.
You can use printf instead.
On the other hand, echo without any flags is fine.

Counting characters

In your input I don't see multibyte characters.
If you don't need to support such characters,
then you could use native Bash syntax ${#chars} to get the length of $chars,
no need for wc -m.

Writing to "$fname"

The script passes some text to | tee -a "$fname" at multiple places:

header
loop output

inside the loop, blank line after the letter u -> this one looks like a bug

footer

Writing | tee ... multiple times is tedious and error-prone.
You could group commands to simplify:

{
    echo header ...
    for ...
    echo footer ...
} | tee -a "$fname"

Probably you can drop the -a from tee to truncate the file,
and that will also allow you to remove the manual truncation at the beginning of the script.


Naming

Use something shorter and more generic, like a and b, instead of list1 and list2
curry is mispelled -- should be carry

You are repeating yourself a lot.  For example, except in the case where both lists are empty:

In each case, you have three adds that are exactly the same.
All three cases have a very similar structure -- the only difference is basically which numbers are being added

Consider defining a class to represent numbers.  That way, you can easily change the representation in the future.
I don't think your implementation is tail-recursive.  This will lead to stack-overflows for large lists.  This might or might not be a problem, depending on your application.
Use "word-at-a-time" thinking only as a last resort.  In this case, you are directly recursing over the lists -- one element ("word") at a time.  Try to find a higher-level abstraction, such as map, that you can use.

In this particular case, in order to handle the carries, you really need some sort of "map plus accumulator" abstraction.  To my knowledge, there is no such function built-in to Scala.  So you might have to write your own.  Still, I would suggest implementing a generic, higher-order function to do this.  That way, you can reuse that function later for other things.
Try to decompose your problem.  In this case, the problem is already fairly simple.  Still, you might (or might not -- I'm not sure) benefit from drawing inspiration from hardware adders.


Inserting Data in The Database using LINQ TO SQL

Yes. You can use object initializer syntax and bring the amount of text down a bit:

     public void addPatientInformation() {
        using(DbClassesDataContext myDb = new DbClassesDataContext()) {
            myDb.PatientInfos.InsertOnSubmit(new PatientInfo {
                Phy_ID = physcianID,
                Pat_First_Name = txtFirstName.Text,
                Pat_Middle_Init = txtMiddleName.Text,
                Pat_Last_Name = txtLastName.Text,
                Pat_Gender = cmbGender.Text,
                Pat_Marital_Status = cmbMaritalStatus.Text,
                Pat_Date_Of_Birth = dtpDOB.Value,
                Pat_Home_Add = txtHomeAdd.Text,
                Pat_Home_Num = txtPhone.Text,
                Pat_Work_Add = txtWorkAdd.Text,
                Pat_Work_Num = txtWorkPhone.Text,
                Pat_Prim_Physician = txtPrimPhysician.Text,
                Pat_Ref_Physician = txtRefePhysician.Text,
            });
            myDb.SubmitChanges();
        }
    }


Coding style

There is too little white space at many places, for example

sqdict={str(i):i**2 for i in range(10)}

This and other PEP8 coding style
violations (most of them related to spacing and too long comment lines)
can be detected by checking your code at PEP8 online.

Unnecessary comments

There are some comments which add no information to the code and can safely be removed,
such as

#lets define our adder
def adder3(num):

or

i_sum = adder3(num) # storing the value from the adder fucntion to i_sum

Naming

def adder3(num):

Is is impossible to guess from the function name what its purpose might be.
I'd suggest something like square_digit_sum.

def happynum (num, counter):

Here we know what the function is about, what does it do? Compute a happy number,
check for happy number, ...?

Code structure:

The global variable counter = 0 is not used at all and can be removed.

A global variable number = i is used to "remember" the argument of
the inital call to the recursive happynum function, and the function
(as a "side effect") appends to the global happy_numbers array.
This is error-prone and not very elegant.

I'd suggest to define a function is_happy instead, which takes a number and
recursion limit, and returns True or False. The default recursion limit can be
defined as a default parameter value:

def is_happy(num, reclimit=50):
    if num == 1:
        return True
    if reclimit <= 0:
        return False
    return is_happy(square_digit_sum(num), reclimit - 1)

Note also that no else: block is needed if the if: block
has a return statement. This saves indenting levels.

Then you can use list comprehension

happy_numbers = [num for num in range(1000) if is_happy(num)]

or a filter

happy_numbers = filter(is_happy, range(1000))

to create an array with the first 1000 happy numbers.

Also it is a good habit to put add a "main guard" so that the source file can be
imported as a module:

if __name__ == "__main__":
    happy_numbers = filter(is_happy, range(1000))
    print(happy_numbers)

Performance improvements:

Computing the square digit sum can be made slightly faster by using integer
arithmetic only, without string conversions:

def square_digit_sum(num):
    sum = 0
    while num > 0:
        digit = num % 10
        sum += digit * digit
        num //= 10
    return sum

(This makes the sqdict hash obsolete.)

The recursion limit of 50 is somewhat arbitrary, and might not be sufficient for
large numbers. A possible alternative is to remember all numbers seen so far
in a set:

def is_happy(num):
    seen = set()
    while num > 1:
        if num in seen:
            return False
        seen.add(num)
        num = square_digit_sum(num)
    return True

More suggestions:

Add docstring comments to all functions.


Handling of open database connection and calling shared function from WebAPI

According to MSDN:

  "We recommend that you always close the connection when you are finished using it in order for the connection to be returned to the pool. You can do this using either the Close or Dispose methods of the Connection object, or by opening all connections inside of a using statement in C#, or a Using statement in Visual Basic."
   http://msdn.microsoft.com/en-us/library/8xx3tyca(v=VS.80).aspx - Section: "Adding Connections"

The way your code is written, (connection being delivered via a factory method) does look a little risky. However, the way MSDN describes it, at the end of the Using block, the connection object will be automatically closed and disposed.


Readability and cyclomatic complexity of database transaction code

It's obviously subjective, but IMHO inline conditionals make code harder to understand, indentation is very important. So I'd definitely take the second approach, but writing it differently to use only one indentation level:

existing_transaction = database.find_transaction_by_id(transaction.id)
if !existing_transaction
  database.create_transaction(transaction)
elsif !existing_transaction.processed
  database.update_transaction(transaction)
end


You are doing good. You are referencing a good example.
The flow will be as below:

Once the user logs in and have checked "remember me", set the cookie with a unique token for user.
Next time when the user comes back, check the cookie with the token value in DB.
If it matches, allow the user to login.
If the token is missing redirect to login.

Ref:
http://jaspan.com/improved_persistent_login_cookie_best_practice


Rails 5.2 callbacks to trigger score recalculation for relationships

In testing this code it turned out there is a chicken-and-egg situation, and more specific requirements.

In order to know which object (Contact or Mandate) to update the score for, the Activity callbacks need more 'knowledge':

eg. 2 cases:

1 Contact A has 0 activities ->

if an activity is created, recalculate the score for A

2 Contact A has > 0 activities ->

if an activity is created, no need to recalculate the score

if an activity is deleted, recalculate the score only if activities = 0

The same is true for Mandate.

So, I ended up with a cleaner solution, with drier code:

Activity.rb

  before_commit :mark_objects_for_rescoring, on: :create
  before_destroy :mark_objects_for_rescoring
  after_commit :rescore_objects, on: [:create, :destroy]

  after_initialize do
    self.contacts_to_recalculate = []
  end

  private

  def mark_objects_for_rescoring
    contacts.each do |contact|
      contacts_to_recalculate << contact.id if contact.activities.count == 1
    end
    mandates.each do |mandate|
      mandates_to_recalculate << mandate.id if mandate.activities.count == 1
    end
  end

  def rescore_objects
    contacts_to_recalculate.each do |id|
      contact = Contact.find(id)
      contact.calculate_score
      contact.save!
    end
    contacts_to_recalculate.each do |id|
      mandate = Contact.find(id)
      mandate.calculate_score
      mandate.save!
    end
  end


You should definitely follow @Henrik Hansen's suggestion about separating your method into multiple APIs with one exception.

The save method should just save the stream. There is no need for it return any streams. You should already know this stream from the CreateCsv method.

Other things that you can improve are...

String concatenation

csvContent += string.Join("|", arr) + "\n";

I'm pretty sure this is the bottleneck of you application. Strings are immutable so in order to concatenate strings, the runtime has to copy the old one and appaned something new to it. Usually this is not a big issue but since you have about 40 columns and 30k rows of data this is really a lot of copying. And the string is growing, so each copy operation has to handle larger and larger strings.

For frequent string manipulation, especially in loops, you should use the StringBuilder that does not requrie copying. There are numerous pages about this topic so if you are interested in its internals, just google for it.

As far as strings are concerned there is one more piece of code that isn't efficient yet.

arr = ((IEnumerable)objarr).Cast<object>()
             .Select(x => x.ToString())
             .ToList();

You're materializing the objarr by calling ToList. This is not necessary at this point.

string.Join("|", arr)

Join can take of enumerating it later only once. Currently your string is being created twice.

The new code could look this:

var csvBuilder = new StringBuilder();

for (int row_no = 0; row_no < ds.Tables[0].Rows.Count; row_no++)
{
    if (row_no == 0)
    {
        var headers = new List<string>();
        for (int i = 0; i < colCount; i++)
        {
            headers.Add(ds.Tables[0].Columns[i].ColumnName);
        }
        csvBuilder.AppendLine(string.Join("|", headers));
    }
    else
    {
        var items = ds.Tables[0].Rows[row_no].ItemArray;
        var values = ((IEnumerable)items).Cast<object>().Select(x => x.ToString());
        csvBuilder.AppendLine(string.Join("|", values));
    }
}

Always dispose streams

Another bad habit of yours is to not dispose streams. If you call this method a couple of time you'll be wasting a lot of memory. You should always do it at some point either with the using statement or by calling Dispose() in a try/finally block.

Naming

You should pay more attention to your variable names. arr is a terrible name because it can stand for just anything. It harms code readability. Code should document itself. This one doesn't.

You should also be more consistent. If you name most of your variables correctly with camelCase then don't name others with _snake_case_ like row_no.

Use always strong names and as precise as you can. Not too long (if possible) but also not to short, avoid abbreviations. columnIndex is a good example. row_no should be rowIndex. Currently it looks like more then one person was writing this code. Each one with different coding style.

{}

for (var i = 0; i < rowReader.FieldCount; i++)
               headers.Add(Convert.ToString(rowReader.GetValue(i)));

Always use {}. You can save youself hours of debugging because without them it's very easy to make a mistake.

Explicit types vs var

You mix explit types and var. You use them interchangeably. This makes your code look very unprovessional and messy. Pick one and stick to it. (I suggest picking var).


I feel this question is more suited for stack overflow, but I'll answer it anyway. In c++ the preferred way to do this is:
std::array<std::array<int, 10>, 10> arr = {}; // Without the 0

Also remember that static variables are zero-initialised anyway, so you wouldn't need to do that.
Because this is code review, I would suggest using a typedef to replace std::array<std::array<int, 10>, 10> to make your code more readable.
EDIT: As pointed out in the comments, using is much more powerful than typedef and more modern-c++ ish and one should preferably use it rather than typedef. It supports type aliasing templates and all other cool stuff, which is why it is preferable to use. ( Though never use using namespace ...;)


Drawing 800+ circles in a space-themed shoorter game

By looking at documentation, I found another method that is faster at drawing many circles.

I replaced last 2 lines in drawSelf with:

g.fillOval(pos[0],pos[1],tr.xscale,tr.yscale);

and I got a lot less lag. Turns out it did have to do with internals.


I’m not going to have a go at the big problem of “equation variable” (which might be better suited to Stack Overflow), but I do have some comments on your existing code:

Python uses the operator ** for powers; i.e., a ** b means “a to the power b”. You can use this to tidy up your constants at the top of the file:

c = 3.00 * 10 ** 8
E = mass * c ** 2

I think that’s easier to read, and makes it clear where they’re coming from.

I see no reason to define a c2 variable, especially when you use it inconsistently (sometimes you have c2, sometimes c * c.

The scipy.constants module contains lots of these constants built-in to high levels of precision, but that may be inappropriate for your work.
At the point when E is defined, the variable mass hasn’t been defined. In fact, I can’t find any mention of the variable in the script. What’s it doing here?
Something only happens if the user types exactly yes or no when asked “Show work?” You might be better off defining a list of “acceptable” responses which means the user wants their work shown.

For example:

yes_list = ['yes', 'y', 'true', 't', 'yep']
if input('Show work?').lower() in yes_list:
    show_input = True
else:
    show_input = False

Most of the code is duplicated: once in the branch of the if statement which shows the working, and again in the branch which doesn’t. You’d be better off defining a working_print function which only prints anything if the user wants it. Further, you can skip defining a show_input variable, and get it directly from the user input:

yes_list = ['yes', 'y', 'true', 't', 'yep']
if input('Show work?').lower() in yes_list:
    def working_print(x):
        print(x)
        return None
else:
    def working_print(x)
        return None

Then you can replace instances of print() which are optional with working_print(). For example, the branch

print('E=mc^2')
print('m=E/c^2')
print('Mass =', energy_val, '/', 'c^2')
print('Mass =', mass_val)

would become

working_print('E=mc^2')
working_print('m=E/c^2')
working_print('Mass =', energy_val, '/', 'c^2')
print('Mass =', mass_val)

You have lots of nested if statements of the form

elif p_val > 0:
    if volume_val > 0:
        # code goes here

elif something_else

I think you’d be better off combining the elif and the if into a single line, e.g. something like

if p_val > 0 and volume_val > 0
if min(p_val, volume_val) > 0

It makes it easier to see what the conditions for each branch are. It also leaves you open to less unexpected bugs if none of the branches get run correctly.

And why p_val instead of density_val?
Add an else block at the end of the code which lets you know when it got there, even if it prints something as silly as “Uh oh, don’t know how I got here.” It makes life easier when debugging – you can tell whether none of your branches ran, or whether one of the branches ran but aren’t printing anything.
In several places, you’re checking that variables are positive where it doesn’t seem appropriate.

For example, consider the F = ma branch. Both force and acceleration are vectors, so it makes sense for them both to be negative (corresponding to force/acceleration in the opposite direction). When computing mass, all you require is that they both have the same sign. So your if statement should become

if force_val * acceleration_val > 0

Velocity is also a vector, so it can be signed, and I see no reason why energy (or several other quantities) have to be non-zero.
There’s a great app called Pythonista for iOS which can edit and run Python scripts. (It doesn’t do Python 3, but your script is sufficiently simple that converting to run on 2.x shouldn’t cause any problems.) I don’t know enough about other platforms to suggest anything else.


which for loop has better performance in javascript?

Not sure if this is a right fit for this site, as this is clearly not 'real' code, but let me give you an answer anyway.

First, in your test code, the "for" case is clearly set up incorrectly. It should look more like this:

for (let i = 0; i < array1.length; i++) {
  console.log(array1[i]);
}

Second, I don't think you are asking the right question. This is clearly a case of premature optimisation. There will be differences obviously, but in real life situations the difference will probably be marginal. It is much wiser to optimise for readability and developer comfort when writing code. Use the loop that makes most sense for you in your current situation. If you run into performance issues you can start looking at optimising then, but not before.

There are too many variables to draw conclusions from your test case. The size of the array you loop over for instance. On large arrays for will be probably be fastest (probably even a bit slower than a while loop). On small arrays a forEach is possibly faster, unless you do complex operations inside the loop. And all that is dependant on the javascript engine implementation and the hardware it runs on.

So as I said, don't worry about this stuff before you run into performance issues. And when you do, test your performance with real code and real data, not oversimplified testcode.


It looks like you have a good and solid Insert, probably pretty safe, but this still allows a user to enter data into the database that could be run at a later time,  you should still check the input coming in before inserting it into the Database even though it has been "prepared".

The prepare just means that the insert will not break anything, but if you run a SQL Query on the information in that column where someone has entered SQL injection Characters it could still crash the database.

Please make sure the input is safe all the way around.  Alert the user that they cannot enter certain characters but be aware you are asking for an e-mail address there too. The Password should be encrypted, not sure whether you should do that here or in the Database itself, probably in the PHP, but that is another review altogether.


Have you come across the IntStream?  I'd use that for numerical operations rather than the boxed version Stream<Integer>.


begin and end overloads for istream_iterator

Not sure that's how I would have written in.
Its not normal to call std::begin() and std::end() on an iterator.

I would have arranged for a some type to represent the stream as a container:

#include <iostream>
#include <iterator>
#include <fstream>

namespace ThorsAnvil
{
    template<typename T>
    struct StreamAsContainer
    {
        std::istream& str;
        StreamAsContainer(std::istream& str) : str(str) {}
    };

    template <typename T>
    std::istream_iterator<T> begin(StreamAsContainer<T>& c)
    {
        return std::istream_iterator<T>(c.str);
    }

    template <typename T>
    std::istream_iterator<T> end(StreamAsContainer<T>&)
    {
        return std::istream_iterator<T>();
    }

}

int main()
{
    namespace TA=ThorsAnvil;
    for (std::string s : TA::StreamAsContainer<std::string>(std::cin))
    {
        std::cout << s;
    }
}


Thats because in Visual Studio, including winsock2.h to your headers is not enough. You have to tell the Linker your project will need the library wsock32.lib.

You can do that either by editing the properties of your project, or by including this line to your code:

#pragma comment(lib, "wsock32.lib")


Operating multiple columns of one pandas DataFrame using data from another

So, don't tell my boss, but I spent almost an entire day trying to improve this code. I have found a much better solution, but I would still love to hear from anyone who is more experienced than me.

real = nominal.copy()
years = ['year1', 'year2' ... 'year11']
incomes = ['income1', 'income2' ... 'income11']
savings = ['savings1', 'savings2' ... 'savings11']

for i in xrange(len(years)):
    interviewed = real[(real[years[i]].notnull())].copy() # to avoid the NaNs
    interview_years = list(interviewed[years[i]].unique())
    for y in interview_years:
        temp = interviewed[(interviewed[years[i]] == y)].copy()
        temp[incomes[i]] = temp[incomes[i]] *\
                           annual_inflation.loc[int(y), 'ratio to 2014']
        temp[savings[i]] = temp[savings[i]] *\
                           annual_inflation.loc[int(y), 'ratio to 2014']
        interviewed[(interviewed[years[i]] == y)] = temp
    real[(real[years[i]].notnull())] = interviewed

Basically the old block was slow because it assessed each column and then each row, looking for elements to manipulate. This block is a lot faster because it starts by slicing out all of the elements that need to be manipulated, then manipulates them all at once, then puts them back in their original place.


This is such a perfect match for the Replace Conditional with Polymorphism Refactoring that it even looks as if it was specifically designed to demonstrate the Replace Conditional with Polymorphism Refactoring. I mean, the field it is basing its behavior on is even called Type!

interface Person { void DoSomething(); }

class PrivilegedPerson : Person {
    public void DoSomething() {
        // do something
    }
}

class UnprivilegedPerson : Person {
    public void DoSomething() {} // literally do nothing
}

class Employee   : UnprivilegedPerson {}
class Manager    : UnprivilegedPerson {}
class Contractor : UnprivilegedPerson {}
class President  : UnprivilegedPerson {}
class Executive  : UnprivilegedPerson {}


Searching for many different names in a Panda frame

Your code follows this pseudo-code pattern:
if any of these strings are in name:
    do x

The simplest way to express that in Python is to invert the condition:
if name in any of these strings:
    do x

Or as actual Python:
if name in ["Alan", "Mary"]:
    print(name)


Conditionally inserting MySQL entries in a Flask app

def connection():

This is misnamed. Please call it cursor_connection(), as that is the tuple it returns. Some folks would prefer the identifier curs over the rather ambiguous c, as "cursor" and "connection" both start with that letter.

    c, conn = connection()
    c = conn.cursor()

Ok, that 2nd line is just bizarre. Please delete it, as the function already accomplished that task.

Nice little INSERT you have there. Be a shame if some punctuation crept into it:  https://www.xkcd.com/327/

except Exception as e:

What is your concern, here? Might be better to elide the try / catch altogether, since there isn't really any "error recovery code" here.

Rather than having mc_address_exist() return a tuple, it would be more natural to return a (potentially empty) list, or return a scalar that potentially is None (assuming the uid column is declared NOT NULL). It's not clear why you asked the DB to retrieve mc_address, since you just discard it.

In login_exist(), rather than asking for *, it would be a cheaper query to just select count(*).

You're not leaking anything with that cursor, so don't worry about closing it. You are correctly closing the underlying TCP connection. Your try/catch handling appears to be adequate for your needs at present, so no change needed.


Scrape HTML into separate files for each chapter

Don't use globals in this case
To start off, global variables should generally be avoided.  Often times configurations will use global constants, but using global variables can have implications to the namespace.  See pacmaninbw's answer for a little more explanation on that.
With that said,  if you wanted to keep the values global please use constants.
define('FILE', "testing.html");
define('TAG', "/x-berschrift-1--nur-f-r-Header-/");
define('DIRECTORY', "testing");

Define global constants like this at the beginning of your file.

Simplify (and remove) your functions
Next up are your functions:
function checkingMatchTag($line)
{
    return preg_match(TAG, $line);
}

function openWriteFile($directory, $count, $extension)
{
    return fopen($directory . $count . '.' . $extension, 'w');
}

function closeWriteFile($file)
{
    fclose($file);
}

function segmentContent($writeFileHandle, $line)
{
    fwrite($writeFileHandle, $line);
}

As you can see, I simplified your functions for you.  They perform the same, but have less clutter involved. In checkingMatchTag I left in the call to TAG in to show you how to call global constants.
Anyway, the point is each of these functions can be reduced to one simple line.  So why are you making a ton of functions for one line of basic code?  I would advise you get rid of each of these functions and simply use the line of code.

Misc changes
Make sure the directory is not there by using this code:
if (!file_exists(DIRECTORY)) {
    mkdir(DIRECTORY);
}

Use the same naming convention for everything. Look at your perimeters. Look at your spacing.  Look at your {}.  There are differences in all of them.


Non-recursive filter to smoothen saw tooth wave

You need to realize that as you are passing over the input, you will be dividing each input by 8 four times and dividing each input by 4 once. You will also calculate the sum of each adjacent input twice. We can try to get rid of this redundancy.

First lets rewrite the filter:

y[0] = x[-2]/8 + x[-1]/8 + x[0]/4 + x[1]/8 + x[2]/8

like so:

y[0] = (x[-2] + x[-1] + x[0] + x[1] + x[2])/8 + x[0]/8 + (1 if x[0] odd, 0 otherwise)

Multiply both sides by 8:
8*y[0] = (x[-2] + x[-1] + x[0] + x[1] + x[2]) + x[0] + 8*(x[0]&1)

Assuming integers, if the input is floating point, just skipp the odd/even bit.

Notice how you now have a sliding sum? That's effective to compute.

I'm not well versed in assembly but I can give you pseudo C-code which you can translate to assembly:

void computeSample(int slidingSum, int midSample){
   return (slidingSum + midSample + (midSample & 1) * 8)/8;
}

void filter(int *input, int *output, int len) {
    const int width = 2;

    if (len < width*2 + 1) { return; }

    int slidingSum = 0;
    for (int i = 0; i < width*2 + 1; ++i) {
        slidingSum += input[i];
    }

    output[width] = computeSample(slidingSum, input[width]);
    for (int x0 = width + 1; x0 < len - width; ++x0) {
        slidingSum -= input[x0 - (width+1)];
        slidingSum += input[x0 + width];
        output[x0] = computeSample(slidingSum, input[x0]);
    }
}

You need to figure out how to handle the edges of the signal (repeating, zero extending, no-data etc).

Hope this helps!


instead of

if(full == true)

use

if (full)

and instead of

if(age >= 18)
{
   return true;
}
else
{
   return false;
}

use:

return age >= 18


Removing duplicate files in a given directory

To get md5 of large files you can use something like this:

def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

Now here

for f in files:
    if not md5(os.path.join(root,f)) in md5_dict:
        md5_dict.update({md5(os.path.join(root,f)):[os.path.join(root,f)]})
    else:
        md5_dict[md5(os.path.join(root,f))].append(os.path.join(root,f))

I see two things:

You don't need to check if key in your dict, you can use defaultdict instead
md5 is calculated twice per each file, first time to check if it's in dict, second time to actually add it to dict.

Here:

while len(md5_dict[key])>1:
    for item in md5_dict[key]:
        os.remove(item)
        md5_dict[key].remove(item)

You can just use list.pop()

So in the end your code should look like this:

import hashlib
import os
from collections import defaultdict

def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def rm_dup(path):
    """relies on the md5 function above to remove duplicate files"""
    if not os.path.isdir(path):  # make sure the given directory exists
        print('specified directory does not exist!')
        return

    md5_dict = defaultdict(list)
    for root, dirs, files in os.walk(path):  # the os.walk function allows checking subdirectories too...
        for filename in files:
            filepath = os.path.join(root, filename)
            file_md5 = md5(filename)
            md5_dict[file_md5].append(filepath)
    for key in md5_dict:
        file_list = md5_dict[key]
        while len(file_list) > 1:
            item = file_list.pop()
            os.remove(item)
    print('Done!')

if __name__ == '__main__':
    print('=======A simple Python script to remove duplicate files===========')
    print()
    print('============Coded by codereview.stackexchange.com AKA python-scripter===================')
    print()
    print('===========The script counts on the fact the fact=================')
    print('=========that if 2 files have the same md5checksum================')
    print('==========they most likely have the same content==================')
    print()
    path = input(r'Please provide the target path\directory... for example: c: or c:\directory...')
    print()
    rm_dup(path)

however there is one more thing, while in general it's right to first list all the files and then delete them one by one, because maybe in future you will add some option for user to select files he want to delete. In this current case you can just use set to keep md5 checksums in it, and delete files as soon as you fight one with the same chucksum.

P.S. two files with the same checksum are not 100% guaranteed to be the same. Think about adding some additional check.


Count contiguous sub-array whose sum is a perfect square

You don't really use array[].  You store a value in array[index], and then immediately read the value back out, and then never use that value again.  This results in unnecessary memory cycles.

    array[index] = in.nextInt();
    prefixSum[index] = (prefixSum[index-1]+array[index]);

You could replace this with a temporary variable, and remove the array.

    int element = in.nextInt();
    prefixSum[index] = prefixSum[index-1] + element;

As a minor efficiency boost, instead of adding the element to the prefixSum[index-1], which involves an array lookup (another memory cycle), you could keep the running total in a local variable.

int running_total = 0;
for (int index = 1; index <= n; index++) {
    int element = in.nextInt();
    running_total += element;
    prefixSum[index] = running_total;
    ...

You have two different ways of counting the sub-arrays that sum to a perfect square:

count += isPerfectSquare(prefixSum[index]                ) ? 1 : 0;
count += isPerfectSquare(prefixSum[index]-prefixSum[prev]) ? 1 : 0;

The first is used when you are counting from the beginning of the list, the second when you start by excluding one or more elements from the beginning.

You could make the first method look more like the second, by adding a subtraction of 0:

count += isPerfectSquare(prefixSum[index]-      0        ) ? 1 : 0;

By design (or is it by coincidence?), prefixSum[0] actually contains the value 0.

count += isPerfectSquare(prefixSum[index]-prefixSum[ 0  ]) ? 1 : 0;

So if your second loop started with for (int prev = 0; instead of for (int prev = 1;, you could remove your first counting statement completely.

Your outer nested loop runs one more time that necessary.  It runs while prev <= n, where the inner loop starts at index = prev+1 and runs while index <= n.  On the last iteration of the outer loop, prev == n, so index starts at index = n+1 and of course index <= n is immediately false, so the inner loop doesn't run at all, which makes this last iteration of the outer loop pointless.  You could use prev < n as the loop condition.

The count += isPerfectSquare(...) ? 1 : 0; ternary operation isn't saving you much, and could be costing you some performance.  The ternary operation is an if ... then ... else ... statement, and the else part is count += 0, which is a no-op.  The following is clearer, and might even be faster.

        if (isPerfectSquare(...)) {
            count++;
        }

Improved code:

int prefixSum[] = new int[n + 1];
int count = 0;
int running_total = 0
for (int index = 1; index <= n; index++) {
    int element = in.nextInt();
    running_total += element;
    prefixSum[index] = running_total;
}
for (int prev = 0; prev < n; prev++) {
    for (int index = prev+1; index <= n; index++) {
        if (isPerfectSquare(prefixSum[index] - prefixSum[prev])) {
            count++;
        }
    }
}
System.out.println("count = " + count);


Boyer Moore Horspool Search Algorithm in Go

I added

func BenchmarkSearch(b *testing.B) {
    c := "Hello, we want to find word Guru, so this #phrase has the word Guru."
    s := "word Guru"
    for i := 0; i < b.N; i++ {
        Search(c, s)
    }
}

Then i ran

$ go test -v -bench=. -benchmem -memprofile=mem.out

It yielded

goos: linux
goarch: amd64
pkg: test/boyermoor
BenchmarkSearch-4        2000000           780 ns/op         104 B/op          3 allocs/op
PASS
ok      test/boyermoor  2.360s

Now i open pprof to get detailed stats

$ go tool pprof mem.out

(pprof) list Sear
Total: 268.52MB
ROUTINE ======================== test/boyermoor.BenchmarkSearch in /home/mh-cbon/gow/src/test/boyermoor/main_test.go
         0   268.52MB (flat, cum)   100% of Total
         .          .     18:
         .          .     19:func BenchmarkSearch(b *testing.B) {
         .          .     20:   c := "Hello, we want to find word Guru, so this #phrase has the word Guru."
         .          .     21:   s := "word Guru"
         .          .     22:   for i := 0; i < b.N; i++ {
         .   268.52MB     23:       Search(c, s)
         .          .     24:   }
         .          .     25:}
ROUTINE ======================== test/boyermoor.Search in /home/mh-cbon/gow/src/test/boyermoor/main.go
  268.52MB   268.52MB (flat, cum)   100% of Total
         .          .     36:}
         .          .     37:
         .          .     38:func Search(text string, pattern string) []int {
         .          .     39:
         .          .     40:   var indexes []int
  208.52MB   208.52MB     41:   byteText := []byte(text)
         .          .     42:   bytePattern := []byte(pattern)
         .          .     43:
         .          .     44:   textLength := len(byteText)
         .          .     45:   patternLength := len(bytePattern)
         .          .     46:
         .          .     47:   if textLength == 0 || patternLength == 0 || patternLength > textLength {
         .          .     48:       return indexes
         .          .     49:   }
         .          .     50:
         .          .     51:   lastPatternByte := patternLength - 1
         .          .     52:
         .          .     53:   mt := newBadMatchTable(pattern)
         .          .     54:   index := 0
         .          .     55:   for index <= (textLength - patternLength) {
         .          .     56:       for i := lastPatternByte; byteText[index+i] == bytePattern[i]; i-- {
         .          .     57:           if i == 0 {
      60MB       60MB     58:               indexes = append(indexes, index)
         .          .     59:               break
         .          .     60:           }
         .          .     61:       }
         .          .     62:
         .          .     63:       index += mt.table[byteText[index+lastPatternByte]]

You have allocations that are totally superfluous, given current test case, and they could be avoided by changing the input parameters types.

Lets give it a try

The code is updated to

package main

func main() {

}

type badMatchTable struct {
    table   [256]int
    pattern []byte
}

func newBadMatchTable(pattern []byte) *badMatchTable {
    b := badMatchTable{
        pattern: pattern,
    }

    b.table = [256]int{}
    b.table = b.generateTable()

    return &b
}

func (b *badMatchTable) generateTable() [256]int {

    for i := 0; i < 256; i++ {
        b.table[i] = len(b.pattern)
    }

    lastPatternByte := len(b.pattern) - 1

    for i := 0; i < lastPatternByte; i++ {
        b.table[int(b.pattern[i])] = lastPatternByte - i
    }

    return b.table
}

func Search(text, pattern []byte) []int {

    var indexes []int

    textLength := len(text)
    patternLength := len(pattern)

    if textLength == 0 || patternLength == 0 || patternLength > textLength {
        return indexes
    }

    lastPatternByte := patternLength - 1

    mt := newBadMatchTable(pattern)
    index := 0
    for index <= (textLength - patternLength) {
        for i := lastPatternByte; text[index+i] == pattern[i]; i-- {
            if i == 0 {
                indexes = append(indexes, index)
                break
            }
        }

        index += mt.table[text[index+lastPatternByte]]
    }

    return indexes
}

I behncmarked again

$ go test -v -bench=. -benchmem -memprofile=mem.out
goos: linux
goarch: amd64
pkg: test/boyermoor
BenchmarkSearch-4        2000000           669 ns/op          24 B/op          2 allocs/op
PASS
ok      test/boyermoor  2.023s

Those are small improvements.

I change the code again to remove the int slice allocation

package boyermoor

type badMatchTable struct {
    table   [256]int
    pattern []byte
}

func newBadMatchTable(pattern []byte) *badMatchTable {
    b := badMatchTable{
        pattern: pattern,
    }

    b.table = [256]int{}
    b.table = b.generateTable()

    return &b
}

func (b *badMatchTable) generateTable() [256]int {

    for i := 0; i < 256; i++ {
        b.table[i] = len(b.pattern)
    }

    lastPatternByte := len(b.pattern) - 1

    for i := 0; i < lastPatternByte; i++ {
        b.table[int(b.pattern[i])] = lastPatternByte - i
    }

    return b.table
}

func Search(text, pattern []byte, indexes []int) []int {

    // var indexes []int
    indexes = indexes[:0]

    textLength := len(text)
    patternLength := len(pattern)

    if textLength == 0 || patternLength == 0 || patternLength > textLength {
        return indexes
    }

    lastPatternByte := patternLength - 1

    mt := newBadMatchTable(pattern)
    index := 0
    for index <= (textLength - patternLength) {
        for i := lastPatternByte; text[index+i] == pattern[i]; i-- {
            if i == 0 {
                indexes = append(indexes, index)
                break
            }
        }

        index += mt.table[text[index+lastPatternByte]]
    }

    return indexes
}

The benchmark is modified to

func BenchmarkSearch(b *testing.B) {
    indexes := make([]int, 0, 100)
    c := []byte("Hello, we want to find word Guru, so this #phrase has the word Guru.")
    s := []byte("word Guru")
    for i := 0; i < b.N; i++ {
        indexes = Search(c, s, indexes)
    }
}

Now i got

goos: linux
goarch: amd64
pkg: test/boyermoor
BenchmarkSearch-4        3000000           597 ns/op           0 B/op          0 allocs/op
PASS
ok      test/boyermoor  2.402s

That is more substantial.

In the details, you rewrite the generateTable this way to save a few more ops

func (b *badMatchTable) generateTable() [256]int {

    k := len(b.pattern)
    for i := 0; i < 256; i++ {
        b.table[i] = k
    }

    lastPatternByte := k - 1

    for i := 0; i < lastPatternByte; i++ {
        b.table[b.pattern[i]] = lastPatternByte - i
    }

    return b.table
}

At that point, consider that your algorithm is 1/ cpu bound 2/ a bunch of tight loops. So to get much out of the runtime, squeeze as many instructions as possible.

Given the last state of the code, let just get ride of the badTable struct. So the whole thing is contained into one function call.

func Search(text, pattern []byte, indexes []int) []int {

    // var indexes []int
    indexes = indexes[:0]

    textLength := len(text)
    patternLength := len(pattern)

    if textLength == 0 || patternLength == 0 || patternLength > textLength {
        return indexes
    }

    lastPatternByte := patternLength - 1

    table := [256]int{}
    {
        k := len(pattern)
        for i := 0; i < 256; i++ {
            table[i] = k
        }

        lastPatternByte := k - 1
        for i := 0; i < lastPatternByte; i++ {
            table[pattern[i]] = lastPatternByte - i
        }
    }

    index := 0
    for index <= (textLength - patternLength) {
        for i := lastPatternByte; text[index+i] == pattern[i]; i-- {
            if i == 0 {
                indexes = append(indexes, index)
                break
            }
        }

        index += table[text[index+lastPatternByte]]
    }

    return indexes
}

And now it gives us

goos: linux
goarch: amd64
pkg: test/boyermoor
BenchmarkSearch-4        5000000           339 ns/op           0 B/op          0 allocs/op
BenchmarkSearch-4        5000000           340 ns/op           0 B/op          0 allocs/op
BenchmarkSearch-4        5000000           341 ns/op           0 B/op          0 allocs/op
BenchmarkSearch-4        5000000           338 ns/op           0 B/op          0 allocs/op
PASS

Now we have a good 2 times improvement.

But this is not all about performance, it is also about usability for other devs. So the API can be presented this way, which produces a decent trade between the two.

type Horspool struct {
    table   [256]int
    indexes []int
}

func (t *Horspool) Search(text, pattern []byte) []int {

    table := t.table
    indexes := t.indexes
    if cap(indexes) < 1 {
        indexes = make([]int, 0, 100)
    }
    indexes = indexes[:0]

    textLength := len(text)
    patternLength := len(pattern)

    if textLength == 0 || patternLength == 0 || patternLength > textLength {
        t.indexes = indexes
        return indexes
    }

    lastPatternByte := patternLength - 1

    {
        for i := 0; i < 256; i++ {
            table[i] = patternLength
        }

        lastPatternByte := patternLength - 1
        for i := 0; i < lastPatternByte; i++ {
            table[pattern[i]] = lastPatternByte - i
        }
    }

    index := 0
    for index <= (textLength - patternLength) {
        for i := lastPatternByte; text[index+i] == pattern[i]; i-- {
            if i == 0 {
                indexes = append(indexes, index)
                break
            }
        }

        index += table[text[index+lastPatternByte]]
    }
    t.indexes = indexes
    return indexes
}

It gives me a slightly slower program

BenchmarkSearch-4        5000000           370 ns/op           0 B/op          0 allocs/op

I have not tried to understand as to why it is slower because here is a more interesting case involving struct alignment and padding. See this code,

type Horspool struct {
    indexes []int
    table   [256]int
}

And check the results

BenchmarkSearch-4        3000000           480 ns/op           0 B/op          0 allocs/op

read more: https://dave.cheney.net/2015/10/09/padding-is-hard

FTR, consider this is an old algorithm and that it is not utf-8 valid. Go being utf-8 first, this should be improved.

If my understanding of the algorithm is correct, the fix is rather simple

type Horspool struct {
    table   map[rune]int
    indexes []int
}

func (t *Horspool) Search(text, pattern []rune) []int {

    table := t.table
    if table == nil {
        table = map[rune]int{}
    } else {
        for r := range table {
            delete(table, r)
        }
    }
    indexes := t.indexes
    if cap(indexes) < 1 {
        indexes = make([]int, 0, 100)
    }
    indexes = indexes[:0]

    textLength := len(text)
    patternLength := len(pattern)

    if textLength == 0 || patternLength == 0 || patternLength > textLength {
        return indexes
    }

    lastPatternByte := patternLength - 1

    {
        for _, r := range pattern {
            table[r] = patternLength
        }

        for i := 0; i < lastPatternByte; i++ {
            table[pattern[i]] = patternLength - 1 - i
        }
    }

    index := 0
    for index <= (textLength - patternLength) {
        for i := lastPatternByte; text[index+i] == pattern[i]; i-- {
            if i == 0 {
                indexes = append(indexes, index)
                break
            }
        }
        x, ok := table[text[index+lastPatternByte]]
        if ok {
            index += x
        } else {
            index += lastPatternByte
        }
    }
    t.table = table
    t.indexes = indexes
    return indexes
}

But, take care of maps.
https://stackoverflow.com/questions/58475257/map-delete-doesnt-actually-delete-entries

Use a simple counter to free-it-by-allocation regularly.

Finally, as somewhat expected the code is slower by a factor 2

goos: linux
goarch: amd64
pkg: test/boyermoor
BenchmarkSearch-4        2000000           756 ns/op           0 B/op          0 allocs/op
PASS
ok      test/boyermoor  2.282s

Two notes:

There might be more interesting/subtle optimizations that i m not aware of myself, i did the obvious.


Here is a list of things I would improve:

define constants in upper-case (PEP8 reference)
put the main program logic into the if __name__ == '__main__': to avoid it being executed on import
naming according to PEP8 - getLine() to get_line() (or even better name would be something like get_stats())
remove unused sys import
follow the PEP8 import organization guidelines
use _ as a throw-away variable name (instead of num)
use str.format() instead of string concatenation
use more meaningful variable names

The code after the suggested fixes applied:

#!/usr/bin/python
import time

import Adafruit_DHT

SENSOR = Adafruit_DHT.DHT11
GPIO = 4
MEASUREMENTS_COUNT = 5

def get_stats(array):
    average = sum(array) / float(len(array))
    return "{average},{min},{max}".format(average=average, min=min(array), max=max(array))

if __name__ == '__main__':
    date = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

    humidities = []
    temperatures = []
    for _ in range(MEASUREMENTS_COUNT):
        humidity, temperature = Adafruit_DHT.read_retry(SENSOR, GPIO)
        humidities.append(humidity)
        temperatures.append(temperature)

    with open("MainLog.txt", "a") as file:
        file.write("{date}: {th} | {tt}\n".format(date=date, th=get_stats(humidities), tt=get_stats(temperatures)))

By the way, I've done something similar, but using the Particle Photon and both DHT11 and BMP180, getting the average values from both sensors - I was surprised how different the values from these sensors were (may be I did something wrong there).

I was also thinking about improving the way stats are formed and using a namedtuple for it:

from collections import namedtuple

Stats = namedtuple("Stats", ["average", "min", "max"])

Then, the get_stats could be:

def get_stats(measurements):
    return Stats(average=sum(measurements) / float(len(measurements)),
                 min=min(measurements),
                 max=max(measurements))

which will change the way we output to the file:

message_template = "{date}: {th.average}, {th.min}, {th.max} | {tt.average}, {tt.min}, {tt.max}\n"
with open("MainLog.txt", "a") as file:
    file.write(message_template.format(date=date, th=get_stats(humidities), tt=get_stats(temperatures)))

This looks a little bit more pythonic - I like the way we construct a message in a single place and keep the stats in a more cleaner manner.


Sorting an array in different ways with efficient output

There isn't much to say about your code, it's pretty good. You avoided duplication by extracting code to functions, and your code is pretty clean in general.

Some nitpicks:

echo"<br>";: you are missing a space here
your array would also be more readable with an extra space after , and spaces around =>. Putting each array value on it's own line will increase readability even more (the extra space it takes up is well worth it).
your echo needs to be indented a bit more.
$p and $a could be $person and $age for more clarity.

Reviewing code not written by you is off-topic, so I'll be brief about that. But yes, you are right with all your questions. There is a lot of duplication in that code (the duplicate arrays might be explained by them wanting to sort the exact same array each time, instead of one that has already been changed by another sort function; in that case, a getPerson function would avoid duplication), the formatting is pretty bad (unnecessary newlines, no paragraphs, no indentation, lack of spaces, etc), multiple statements on one line, and so on.


Is this home page well organized and what can I do to improve performance here?

your structure looks good.

I am sure you have a reason for nesting so many
s

you know that you  can add classes to Tags as well, and you don't have to add them to only
 tags you can add them to other tags.

it just looks like you are surrounding some tags with Div tags because you think you can only style them that way.

like this

CAD/CAM Digital Dental Restorations

you can change to this

 CAD/CAM Digital Dental Restorations

or

CAD/CAM Digital Dental Restorations


You code seems to contradict your text. You say:

  For example, if he wants to search only with Name, he will write something only in Name textbox. If he wants to search product which name is "Box" and also the productType is "A", then he will write "Box" in name textbox and will choose A type in comboBox.

And yet each method seems to contain multiple Where clauses.

Wouldn't it be more flexible to construct an IQueryable<T>? Something along these lines:

private IQueryable<Product> GetProductsQueryable(Product request)
{
    var queryable = _dbContext.Products.AsQueryable();

    if (!string.IsNullOrEmpty(request.Name))
    {
        queryable = queryable.Where(x => x.Name.Contains(request.Name));
    }

    if (!string.IsNullOrEmpty(request.Code))
    {
        queryable = queryable.Where(x => x.Code.Contains(request.Code));
    }

    if (!string.IsNullOrEmpty(request.Barcode))
    {
        queryable = queryable.Where(x => x.Barcode.Contains(request.Barcode));
    }

    return queryable;
}


Wrapping the classList API to add/remove array of classes

Interesting question,

I've been looking at this for a while, I dont think there is a more succinct way. I've been playing with reconstructing className from the add or remove function calls but it became a less succinct and terrible hack.

The core reason for that is default JS does not have enough convenience methods for arrays. If you were open to use something like LoDash, you could do this:

var addClass = function addClass(element /*, classes... */){
  element.className = _.uniq( element.className.split(' ').concat( _.flatten( _.rest( arguments ) ) ) ).join(' ');
};

var removeClass = function removeClass(element /*, classes... */){
  element.className = _.difference( element.className.split(' '),  _.flatten( _.rest( arguments ) )  ).join(' ');
};

Other than that I really like your code; proper naming, indenting, size of functions, etc.

Update on illegal invocation, you are passing element as this to a function that is attached to classList, if you pass classList, then there will be no exception.

var classMethod = function(method) {
    return function(element /*, classes... */) {
        var classList = element.classList;
        element.classList[method].apply(classList,flatten(Array.prototype.slice.call(arguments, 1)));
    };
};

And then that works.. My mind is still boggling at that, but there you go.