For starters, consider making Connect() and Retrieve() non-public. runApp() doesn't seem to have a good reason to know about the operations that Model needs to perform to be usable here. Can the constructor (or, possibly more appropriately, a static factory method) hide those methods?

Introducing state to objects is an easy way to make things complicated. If a View or Controller were somehow able to be passed a Model that had been, say, Connect()ed but not Retrieve()d, what would happen? It's simpler to factor that possibility out when that is an option.


Multithreaded web scraper with proxy and user agent switching

Performance

Each call to scrape_results_page will also call check_proxy.
As such, the check_proxy will get called for the same proxies multiple times, and I'm wondering if there's a reason for re-checking the proxies.
If not, then you can save time by checking the list of proxies once at the beginning of the program,
and remove the check from scrape_results_page.

Once you have a set of verified proxies,
instead of selecting them randomly,
it would be better to use them round-robin style,
to balance the load.
Admittedly this tip may not make any visible difference whatsoever.

Other improvements

There are a lot of parameters buried in the implementation,
for example the ebay url, canihazip.com, the number of threads and page numbers, and possibly others.
It would be better to define such values at the top,
in variables with descriptive names, all upper-cased to follow the convention for "constants".


First I must disclose that I have no experience about programming in Ruby, I hope that the following is applicable.

In a comment I suggested Unix time stamps because they represent a continuous flow of time (integer number of seconds since 1.1.1970), and are therefore easy to use in time arithmetics and comparisons. Hopefully Ruby has support for Unix timestamps.

I also suggest that you store open hours in a db table, regardless of whether they extend over midnight, as a start time and an end time.

Define Unix30min = 30 x 60

Fetch UnixCurrentTime

Fetch a record from the db where (UnixOpenHoursOpen < UnixCurrentTime) and (UnixOpenHoursClose > UnixCurrentTime)

The logic is then simplified to three if statements, without nesting. As you, I dislike deeply nested if, then elseif else end statements, they make my head hurt. If possible I split complex logic into simple statement, readability and maintainability improves significantly.

if nothing was returned (from the db), the shop is closed

if ((UnixCurrentTime > UnixOpenHoursOpen) and (UnixCurrentTime < (UnixOpenHoursClose - Unix30min)))
{
  exit(ShopIsOpen)
}

if ((UnixCurrentTime > (UnixOpenHoursClose - Unix30min)) and (UnixCurrentTime < UnixOpenHoursClose))
{
  exit(ShopIsClosing)
}

The above is pseudocode


Interesting discussion!

@AdamTuttle Regarding the behavior in Underscore that you've highlighted:
I did some quick tests and found that the same behavior exists in Ruby and native JS (Chrome and FF). This confirmed my suspicions that this seemingly weird behavior is just a product of the reduce algorithm itself.

In the algorithm, "memo" represents the current state of the fold operation. If you don't pass in an initial value, you're implying that the first element of the collection represents the initial state of the fold. From that perspective, the behavior you've shown is exactly what I'd expect.

If you want to remove uppercase letters from a collection and convert that to a string in a functional way, it would make more sense to call filter() to and then reduce(). Example:

adamArr = ['A','d','a','m'];
damArr = _.filter(adamArr, function (letter) {
    var asciiCode = asc(letter);
    return asciiCode >= 97 && asciiCode <= 122;
};
damString = _.reduce(damArr, function (memo, letter) {
    return memo & letter;
};


How can I refactor this method so I don't use it in multiple places?

For this, I'll be addressing the second code snippet you've given, as it seems to be heading in the right track.

I'm assuming QueryContext is custom code, because I couldn't find any reference to it in the MSDN and you haven't provided any other tags. In a case like this it would probably be useful to see the code for this class to better optimize your usage, however I do still have a few points. The same goes with what the dataAccess variable is.

Naming

I don't like the name you've given to your second foreach loop's variable. 'p' is confusing and will be even more so if you ever expand the body of your loop. I recommend something like queryParameter.

Implicit Typing

This tends to be a personal thing, but I strongly prefer the use of 'var' when the RHS of the variable declaration makes it obvious what the type is. It saves you having to change the type in two places when refactoring. However you use it half of the time, go all in or not at all.

Out parameters

Always a sign that you should probably make a class and return it.

If you still want an explicit number of results and you don't fancy going to that effort of making a custom class, then you could always use Tuple but a custom class is preferable.

Separation of Concerns

Seems this one function is doing 2 things: building a query, and executing a query. This would be better if they were separate, which allows you more flexibility.

Results

With all this on board, your code becomes:

public class QueryResult
{
    public DataTable Data {get; set;}

    public int RecordCount {get; set;}

    public QueryResult(DataTable data, int recordCount)
    {
        this.Data = data;
        this.RecordCount = recordCount;
    }
}

public QueryResult GetRecords(Query query)
{
    DataSet results = dataAccess.ExecuteQuery(query.statement, query.parameters);
    return new QueryResult(results.Tables[0], results.Tables[1].Rows[0][0]);
}

public class Query
{
    public string Statement {get; set;}
    public Dictionary<string,string> Parameters {get; set;}

    public Query(string statement, Dictionary<string,string> parameters)
    {
        this.Statement = statement;
        this.Parameters = parameters;
    }
}

public Query BuildQuery(StringBuilder statement, string[] orderByParams, QueryContext queryContext)
{
    var parameters = new Dictionary<string, string>();

    if (queryContext.OrderByColumns.Count == 0)
    {
        foreach(var orderbyParameter in orderByParams)
        {
            queryContext.OrderByColumns.Add(param);
        }
    }

    if (queryContext.Parameters.Count > 0)
    {
        foreach (var queryParameter in queryContext.Parameters)
        {
            dataAccess.paramAdd(parameters, statement, queryParameter.ColumnName, queryParameter.Value.ToString());
        }
    }

    // Order By Clause
    statement.Append(queryContext.OrderByColumns.GetSqlClause());

    // Apply Limit
    if (queryContext.ApplyLimit)
    {
        query.AppendFormat(" LIMIT {0},{1}", queryContext.Offset, queryContext.Limit);
    }

    return new Query(statement.ToString(), parameters);
}

You may also want to make the properties in QueryResult readonly depending on what you're hoping to do with them later.


First very important thing: Good/clear code without comments is better than bad code with comments. I say this because you are using comments to make up for vague variable and method names. For instance:

 //n is the number of vertices in graph
 Graph(int n)
 {
     ....

Then why not rename n to numberOfVerts?

Other instances:

 //# of vertices
 int Vertices() { ... }

 //# of Edges
 int Edges() { ... }

Would be more clear about their intent if named getNumOfVertices() or getVertexCount(). Conversely, getNumOfEdges() and getEdgeCount().

Still talking about naming, the members N and E are also very poor names. One is the number of vertices (N) and the other the number of edges (E). Single letter variable names should generally be avoided, as they are very ambiguous and unclear. One exception to this rule is in loop counters, which historically have been named with i, j, k, and so on, and thus have become a known idiom in programming.

You don't need to and should not use a loop to initialize the adjList vector.

 for(;n > 0; n--)
 {
     std::vector<int> row;
     adjList.push_back(row);
 }

That is a very inefficient way of initializing it. push_back() might grow the vector several times, incurring a few expensive memory re-allocations. Just construct the vector with its size, using the constructor initialization list:

 Graph(int numVerts)
     : numOfVerts(numVerts)
     , numOfEdges(0)
     , adjList(numVerts)
 { }

Also worth noting that C++11 allows you to replace the ( ) in the constructor call for the member variables with { }. This is the so called uniform initialization syntax.

Be const correct. Add const to methods that don't mutate member data. Get* methods are the common candidates:

int Edges() const { return E; }
            ^^^^^

Don't use endl unless you are meant to flush stdout. Otherwise, a "\n" should be used. Flushing at every print call can significantly bring performance down at no benefit.


Parsing date strings, inferring the year such that the date is not in the future

Obtaining a date that is in the future is in no way a "syntax error", and it would be inappropriate to raise a SyntaxError.  Instead of abusing the exception-handling mechanism, you should just use a conditional.

for date_str in text:
    try:
        date = datetime.strptime(date_str + str(this_year), "%b %d %Y").date()
        if date <= today:
            print("+", date)
        else:
            date = datetime.strptime(date_str + str(last_year), "%b %d %Y").date()
            print("-", date)
    except ValueError:
        print("abnormality")

Note that you might be misinterpreting some ValueErrors as abnormalities.  For example, "Feb 29 2021" would cause a ValueError, but then you would never get a chance to try "Feb 29 2020", which is a valid day in a leap year.


#pragma once

Don’t use #pragma once. It’s non-standard, it breaks silently and unexpectedly and when it does all hell breaks loose, and the standard solution (include guards) are just as efficient in practice.
const int g_MaxNumberOfObjectsInPool = 2;

There doesn’t seem any good reason why this should be a global variable. It would be better as a static data member of ObjectPool.
It should probably also be constexpr.
But the most important issue is that you are using (signed) int for a size type. That will cause problems if you’re not very careful, because most sizes in C++ use unsigned integers. Yes, this was a mistake, but you can’t fix it by stubbornly ignoring it and insisting on using signed types for sizes instead. “When in Rome” and all.
The correct type to use here is probably std::size_t.
template<typename T>
class DefaultAllocator {
public:
    T* operator()() {
        return new T{};
    }
    void operator()(T* p) {
        delete p;
    }
    void reset() {
        std::cout << "reset function called from default allocator" << std::endl;
    }
};

… why?
There is a standard allocator interface in C++, and it already does everything you need it to do (and more! it’s actually possible to build what is functionally an object pool using any container type(s) with the right allocator… and the right allocator comes built-in with the standard). It makes zero sense to just ignore that and reinvent your own, incompatible allocator interface. (Especially one with a nonsensical, hobbled interface. What does reset() even do?)
Not to mention that you’re already using the standard allocator interface anyway! std::vector<T> is actually std::vector<T, std::allocator<T>>. So when you do:
auto newObj = allocator();
poolObjects.push_back({ true, newObj });

You are using two allocators: your allocator in the first line, and the vector’s standard allocator in the second.
All-in-all, making your own, incompatible allocator regime when a perfectly good standard regime exists (and you even use it!) just seems remarkably silly. And it will get worse….
class ObjectPool

You have made everything in this class static, presumably to hack a singleton-like interface. That’s a bad idea for a number of reasons.
First, singletons are an anti-pattern. In rare circumstances, they are genuinely useful, but even then it should be opt-in… not forced by the type… because that makes testing extremely difficult. And you are testing your code, aren’t you? Hm?
In addition to making testing difficult, forcing a singleon design makes your object pool less useful. What if I want multiple object pools? What if, for example, I’m making a engineering modelling program, and I want to put all the points for the current model in a pool… but then I want to allow a split-screen view of two models side-by-side, so I now need two pools? Why would you punish users of your object pool by denying them the ability to create more than one? What’s the sense in that?
If you made your object pool in the normal, sensible way—that is, not making everything static—then if you really wanted a singleton object pool later, you could always make a trivial wrapper:
template <typename T, typename Allocator>
class SingletonObjectPool
{
    static ObjectPool<T, Allocator> _pool;

public:
    static auto getObject() { return _pool.getObject(); }

    static auto releaseObject(T* p) { return _pool.releaseObject(); }

    static auto destroy() { return _pool.destroy(); }
};

But you can’t go the other way; if you make ObjectPool with everything static, you can’t make a non-static object pool.
struct ObjectInfo {
    bool isInUse{};
    T* ptrObject{};
};
static inline std::vector<ObjectInfo> poolObjects{};

This is really kinda defeating the whole purpose of std::vector.
First of all, ObjectInfo is a dangerous type, because that T* in there is an owning pointer… but it’s not a smart pointer. For that sin alone I’d refuse the whole thing from any project I was in charge of.
The result of this sin is that your object pool leaks all kinds of memory if you don’t manually call destroy()… which not only defeats the purpose of std::vector, it defeats the whole purpose of C++!
The standard first fix to this kind of problem is to replace pointers with the objects themselves; C++ is a value-semantic language, after all:
struct ObjectInfo
{
    bool isInUse = false;
    T object;
};

But if you do this, then you run into problems due to the fact that you’re using a std::vector as your actual pool. Every time you add a new object, it may trigger an internal reallocation of the vector’s array, which would change the addresses of all the objects… and you’re using object addresses as handles, so it would completely break your object pool.
There are two options to fix this problem: don’t use vector as your pool, or don’t store the pooled objects directly in the vector. Your solution is option 2, which, with smart pointers gives:
struct ObjectInfo
{
    bool isInUse = false;
    std::unique_ptr<T> ptrObject = nullptr;
};

Is that the best solution? Eeeh. But we’ll get back to that.
static T* getObject() {
    for (auto& currObj : poolObjects) {
        if (!currObj.isInUse) {
            currObj.isInUse = true;
            std::cout << "Existing Object returned" << std::endl;
            return currObj.ptrObject;
        }
    }

    if (poolObjects.size() == g_MaxNumberOfObjectsInPool) {
        std::cout << "Pool is full " << std::endl;
        return nullptr;
    }

    std::cout << "Creating a new object" << std::endl;
    //auto newObj = new T{};
    auto newObj = allocator();
    poolObjects.push_back({ true, newObj });
    return newObj;
}

This function is way too complex. It does way too much work for a single function:

First it finds the first not-in-use object, if any.
Then it checks whether the pool is full.
Finally, it creates a new object in the pool.

Each one of those steps could be its own function. And some of them could even be public functions, because they might be useful to users. For example, the first step, finding the first not-in-use object could be handy for an algorithm that would like a T, but if it can’t get one, can do something else instead.
So you might do:
template<typename T, typename Allocator>
class ObjectPool
{
    // ... [snip] ...

public:
    // tries to get an available object, and if that fails, tries to create one
    auto getObject() -> T*
    {
        if (auto p = getAvailableObject(); p)
            return p;

        return newObject();
    }

    // gets an object only if one is available, never creates one, never fails
    auto getAvailableObject() noexcept -> T*
    {
        if (auto p_info = _findAvailableObjectInfo(); p_info)
        {
            p_info->isInUse = true;
            std::cout << "Existing Object returned\n";
            return (p_info->ptrObject).get();
        }
        else
        {
            return nullptr;
        }
    }

    // always creates an object (unless the pool is full)
    auto newObject() -> T*
    {
        if (poolObjects.size() == g_MaxNumberOfObjectsInPool)
            throw std::runtime_error{"pool is full"};

        std::cout << "Creating a new object\n";

        auto newObj = std::unique_ptr{allocator()};
        poolObjects.emplace_back(true, std::move(newObj));
        return newObj;
    }

private:
    auto _findAvailableObjectInfo() noexcept -> ObjectInfo*
    {
        auto is_in_use = [](auto&& p_info) { return p_info->isInUse; };

        if (auto p = std::find_if_not(poolObjects.begin(), poolObjects.end(), is_in_use); p != poolObjects.end())
            return *p;
        else
            return nullptr;
    }

    // ... [snip] ...
};

Some additional notes:

Don’t write naked loops. Use standard algorithms. In this case, that loop is obviously a std::find_if(_not)().
Don’t use std::endl. Every time you use it, it flushes the output stream, which can slow things down tremendously.
Don’t return nullptr when an object can’t be gotten. That just gives users of the object pool headaches, because now they have to check every single call to getObject(). If the point is to get an object, and an object can’t be gotten, then throw an exception to indicate failure. (OR, if you really want to avoid relying on exceptions, look in to an “expected” type, like the proposed std::expected, or boost::outcome.)

static void releaseObject(T* ptrSo) {
    for (auto& currObj : poolObjects) {
        if (currObj.ptrObject == ptrSo) {
            currObj.isInUse = false;
            return;
        }
    }
}

This loop is another std::find_if().
static void destroy() {
    for (auto& currObj : poolObjects) {
        if (currObj.isInUse) {
            std::cout << "WARNING! this object is still in use" << std::endl;
        }
        allocator(currObj.ptrObject);
    }
    allocator.reset();
    poolObjects.clear();
}

There is no single standard algorithm that could cleanly replace this loop. Part of the problem is that it does multiple things… which is bad. You could replace it with a single std::for_each(), of course, but it might make more sense to break it into two steps—one to check for still-in-use, and one to do the deallocation.
This becomes especially important if you use smart pointers, in which case the deallocation step becomes completely unnecessary. And, given that allocator.reset() seems to serve no purpose, the whole thing could boil down to:
static void destroy()
{
    auto is_in_use = [](auto&& p_info) { return p_info->isInUse; };

    std::for_each(
        std::remove_if(poolObjects.begin(), poolObjects.end(), is_in_use),
        poolObjects.end(),
        [] (auto&&) { std::cout << "WARNING! this object is still in use\n"; }
    );

    poolObjects.clear();
}

But frankly, a destroy() function is silly in C++. We have built-in destroy() functions; they’re called destructors, and they’re awesome precisely because you don’t have to call them… they work automatically. If the object pool weren’t a hacky-singleton due to everything being static, then the whole function (except for the warning about unreleased objects part) would become obsolete due to the destructor.
An alternative design
Let me propose an alternative design, that doesn’t use std::vector.
The primary purpose of using std::vector is that it packs its data altogether in a tight space, which is fantastic for performance. However, you lose all the benefits of that when you store pointers in a vector, because even though the pointers are all nicely packed together, your data can be all the hell over the place. A vector of pointers to stuff has more-or-less no real benefit over any other container type… and in fact is usually worse than other containers because you have to do this two-stage allocation dance: first allocate the actual stuff, then allocate the pointer to the stuff in the vector.
Instead of using a vector, how about using std::forward_list. And let’s throw away ObjectInfo, and just store the Ts directly in the forward list. So how do we know which ones are in use and which aren’t? Simple: two forward lists; one for in-use objects, one for not-in-use objects.
And of course, let’s use standard allocators rather than reinventing the wheel.
So:
template <typename T, typename Allocator = std::allocator<T>> // or std::pmr::allocator<T>, if you prefer
class ObjectPool
{
    std::forward_list<T> _objects;
    std::forward_list<T> _available_list;

public:

    ObjectPool() = default;

    // this constructor allows you to provide a stateful allocator
    explicit ObjectPool(Allocator const& alloc) :
        _objects(alloc),
        _available_list(alloc)
    {}

    // moveable
    ObjectPool(ObjectPool&&) noexcept = default;
    auto operator=(ObjectPool&&) noexcept -> ObjectPool& = default;

    // non-copyable
    ObjectPool(ObjectPool const&) = delete;
    auto operator=(ObjectPool const&) -> ObjectPool& = delete;

    // need to declare this for sanity, because the copy ops are deleted
    ~ObjectPool() = default;

    // ... [snip] ...
};

Now how would we implement getObject()? Well, let’s take it one step at a time. First, how would we implement newObject()? That’s easy:
template <typename... Args>
auto newObject(Args&&... args) -> T*
{
    if (/* check whether there is capacity left - depends on how you want to handle capacity */)
        throw std::runtime_error{"pool is full"};

    std::cout << "Creating a new object\n";
    return &(_objects.emplace_front(std::forward<Args>(args)...));
}

What about getAvailableObject()? The first part—checking whether anything is available—is not hard:
auto getAvailableObject() noexcept -> T*
{
    if (_available_list.empty())
        return nullptr;

    // ???
}

If the available list isn’t empty, we want to take an object out of it, and put it into the active objects list. We’ll put it at the very front of the active objects list, because it’s easiest to access it there:
auto getAvailableObject() noexcept -> T*
{
    if (_available_list.empty())
        return nullptr;

    // take the first object in available list (_available_list.begin()), pull
    // it out of the available list, and splice it into the active list before
    // the first object (_objects.before_begin())
    _objects.splice_after(_objects.before_begin(), _available_list, _available_list.begin()).

    return &(_objects.front());
}

And that makes getObject() the same as before:
auto getObject() -> T*
{
    if (auto p = getAvailableObject(); p)
        return p;

    return newObject();
}

What about releaseObject()? Also simple. All we have to do is find the object in the list, then splice it out of _objects and into _available_list:
auto releaseObject(T const* p) -> void
{
    auto it = std::find_if(_objects.begin(), _objects.end(), [p](auto&& o) { return &o == p; });
    if (it != _objects.end())
    {
        _available_list.splice_after(_available_list.before_begin(), _objects, it);
    }
    else
    {
        // tried to release an object that wasn't active in the pool
        //
        // report an error?
    }
}

As for destroy(), it’s completely unnecessary. If you really want to check for any in-use objects when destroying or clearing the pool, you just need to see if _objects is not empty.
This isn’t the only alternative design, and may not even be the best. (The best, if you want a fixed-size object pool, might be to allocate a raw buffer and construct objects in-place as needed, with a bitset to keep track of which positions are available. If you want a growable pool, then maybe the same but with multiple buffers, added as needed… but a growable pool generally makes little sense.) But this design is simple, efficient, and easy to extend. For example, you could pre-allocate a bunch of objects (just create them in _available_objects). You could compact the pool (just clear _available_objects). And if you wanted locality, you could use a std::pmr::monotonic_buffer_resource.
This satisfies your 4 pool requirements:

“Create a pool”: auto pool = ObjectPool<T>{};
“Allocate an object from this pool”: auto* p_obj = pool.getObject();
“Deallocate an object from this pool”: pool.releaseObject(p_obj);
“Destroy this pool”: /* nothing */ (automatic)

Your main() becomes:
int main() {
    auto pool = ObjectPool<int>{};

    auto int1 = pool.getObject();
    auto int2 = pool.getObject();
    auto int3 = pool.getObject();

    pool.releaseObject(int1);

    auto int4 = pool.getObject();

    // pool will now contain 3 objects: int2, int3, and int4
    //
    // int1 will have been released, and replaced with int4

    // the rest is no longer necessary
    // integer::destroy();
    // return 0;
}

As for the question… I don’t understand the confusion. You could already pool all the types you listed even with your original code.


This conversion can be done by simple apps from the Dos2Unix package.
However, if you insist on writing your own converter, I'd suggest making fewer function calls. The function str_replace() can accept arrays, so there is no need for embedded calls.
$contents = str_replace(
    array("\r", "\n", "[%LINEBREAK%][%LINEBREAK%]", "[%LINEBREAK%]"),
    array("[%LINEBREAK%]", "[%LINEBREAK%]", "[%LINEBREAK%]", "\r\n"),
    fread($this->fp, filesize($this->filename))
);

However, you ought to be careful. For example, if your file has two Unix-standard newlines, i.e., \n\n, then your code will replace this with \r\n, which is only one Windows-standard newline.
This regex (see about its syntax here) would probably do the trick:
preg_replace('#(?<!\r)\n|\r(?!\n)#', "\r\n", fread($this->fp, filesize($this->filename)));

But I still think it's better to use already existing and proven software, like the one from the beginning of this answer, or simply turn on the auto_detect_line_endings setting, as suggested in the comments by 200_success.
By the way, if your files are huge, your fread will still (try to) read them whole at once, which is not pleasant for the computer memory and performance.


Symfony rest endpoint for get a number products of one user

$productListUser = $this->em->getRepository(ProductAdmin::class)
                             ->findProductsUser(...

Than

public function findProductsUser(UserInterface $user, int $number) :?array
    {

        $listProductUser = $this->em->getRepository(ProductAdmin::class)->findBy(...

seems to me that findProductsUser is method of whatever is returned by $em->getRepository(ProductAdmin::class) why is that method retrieving itself from entity manager? Shouldn't it be just $this->findBy(...?

Further, the responsibility of formatting the entity should not be done by the repository. You need to either wrap the repository with the formatter into another class, or do it in the controller. Also there is no reason why the formatter must be a trait. Make it a service and inject it to the entire controller through contructor if all methods of the controller need it, or have it injected in an action method, like you do with Security, BeamAPI, etc...


Do not do actual rotation.

k rotations (from your code I understand that all rotations are to the right by 1) map an i'th element to an (i + k) % n position. At the time of printing, do some math to figure out which element was mapped to the position m.

The math is trivial, and I intentionally do not spell it out.


Reverse a linked list from position m to n, in-place and in one pass

This is hard to read and follow:

    ListNode *pre=NULL, *cur=head, *front=NULL, *rear=NULL,*follow=head->next;

One variable per line:

This is really hard to read:

while(cur!=NULL&&subLoop-->=0)

Not sure what the --> operator does :-(

Your code could really do with a lot more white space between operators to make it readable.

To be honest I can not follow the logic of this function. Especially since I have not idea what the input parameters are supposed to represent:

ListNode *reverseBetween(ListNode *head, int m, int n)

What are m and n for?


Fastest way to clamp an integer to the range 0-255

Try
 int x=n>255?255:n;
 ... x<0?0:x ...

I'd expect this to produce something like:
 mov     ebx, 255
 mov     eax, n
 cmp     eax, ebx
 cmovg   eax, ebx ; conditional mov instruction
 test    eax, eax
 mov     ebx, 0
 cmovl   eax, ebx

If you are using MSVC SIX, you may not get the conditional move instruction. Try switching to a modern version of visual studio.


Attempting to make my properties an enum based singleton

Property-enum

An enum can have a constructor, allowing us to shorten the code to setup all the enum values.

public enum Property {
    BROWSER("browser"),
    TESTENVIRONMENT("env.baseurl"),
    ... // add more here.
    ;

    private final String key;

    Property(String key) {
        this.key = key;
    }

    public String getKey() {
        return this.key;
    }

    @Override public String toString() {
        return getKey();
    }
}

Do not have any logic based on toString. That method is mainly meant for debugging purposes. Using a getKey() instead (as above) allows you to use getKey() for your application logic.

Is a singleton really necessary?

Ask yourself if you really really NEED a singleton (Hint: Answer is most likely "no"). You might be able to use dependency injection to pass the object to the classes that needs it.

You might even not need a single instance, is there anything wrong with having multiple instances? All it does is read from a resource file, so worst case scenario is that you might spend a few nanoseconds reading a resource file from different places?


If your namespaces match your directory structure you would not need to fetch the class name. You could just append it to the base path and append the .php file extension.

I would argue the class. file prefix is unnecessary. I think of such prefixes from a time when namespaces was not available. If you are concerned with the ease of locating correct files I can recommend the following method. I have used for several projects and are quite happy with it.

classes/
    interfaces/
        interfaceName.php
    abstracts/
    traits/
    class.php
    anotherclass.php

I hope you get the idea. If you follow this you can use this.

spl_autoload_register(function($class) {

    $filename = __DIR__ . '\\' . $class . '.php';

    if(!file_exists($filename)) {
        return false; // End autoloader function and skip to the next if available.
    }

    include $filename;
    return true; // End autoloader successfully.

});

This is pretty much it. You should of course check that __DIR__ equals your base path. If you store your base path inside a variable and you are using a closure as callback, you can inject the path into the closure using this:

$path = 'This is your base path.';

spl_autoload_register(function($class) use ($path) {...});

If your file system uses forward-slashes (for some reason), you could wrap the $class variable in a str_replace() function call.

$class = str_replace('\\', '/', $class);

Happy coding!


There are a number of problems with your code. Let's go through the more important ones:

you should close the PreparedStatement before you return the connection to the pool.... should be:

finally{
    closeStatement (preparedStmt);
    releaseConnection (myCon);
}

you should be closing the ResultSet in addition to the Statement!
but, this is all somewhat pointless because you only use your prepared statement once.... A prepared statement is useful for two reasons only:

they separate issues in syntax from issues in data (you get syntax errors early) ... but, your SQL Query code will not have syntax errors... right?
they improve performance IF THEY ARE REUSED, but you are not reusing them.

If you are using Java 7 you should be using try-with-resources logic on your objects. This will remove the need for the finally block.

JDBC Connection pools are relatively complicated 'animals'. I strongly recommend you leverage the functionality that others have built. For example, Tomcat, WebSphere and I am sure other applications servers have good connection-pooling processes. Additionally, stand-alone applications can (re)use things like the Apache DBCP component (which also supports PreparedStatement connection pools)


Disposing the Context in the Repository pattern

Reusing the same context could have some benefits if you need entities to be cached but you could also end up with contexts with a large memory sizes.

Depending on the requirements, I have usually created a new context on every call and in the case of database contexts, played it safe by forcing a ToList() within the function, before returning the entities.

This ensures that the database connection is only open for just enough time to retrieve the rows and the context is destroyed without holding on to the entities retrieved.

The approach to take here, really depends on your requirements.


Checking for Null before adding into List

This is a bit neater:

List<Option> ListOption = new List<Option> { };
Action<string> add = x => { if (!String.IsNullOrEmpty(x)) ListOption.Add(new Option { Name = x }); }
add(Option1);
add(Option2);
add(Option3);
add(Option4);
return ListOption;

This is perhaps even better:

return (new string[] {Option1, Option2, Option3, Option4})
       .Where(x => !String.IsNullOrEmpty(x))
       .Select(x => new Option { Name = x })
       .ToList();


Dependency Injection with classes which are created often

Am I better off just importing an instantiated version of Convert into Person.js and referencing it directly? I know that will work, but I was trying to avoid coupling the two classes without a nice way to override. I definitely don't like what I have written here, since Convert will be defined on each Person, which is worse than coupled classes in my opinion.

There is nothing wrong with requiring a data conversion service. The problem is coupling the conversion service with the Person class. This coupling should occur in the Factory class instead.

Furthermore, you haven't coupled the classes together. ECMA Script is a dynamically typed language. At worst you've coupled the Person class to an object supporting the same public interface as the Convert class.

Solving this dilemma is pretty simple. The data conversion should happen in the factory:

factory.js

import {Person} from './person.js';

export class Factory {

    constructor({ convert }) {
        this.convert = convert;
    }

    person(obj) {
        obj.first = this.convert.toString(obj.first);
        obj.last = this.convert.toString(obj.last);

        return new Person(obj);
    }
}

person.js

export class Person {
    constructor({ first, last }) {
        this.first = first;
        this.last = last;
    }
}

This keeps your Person constructor clean and straight forward. The messiness of converting data types is encapsulated in the Factory class where it belongs, and the Person class no longer has a dependency on the Convert class.


Displaying a CSV file as an HTML table in a CRUD page

The biggest problem with this code is not so much the CSV formatting, but the fact that you have a "Delete" link like this:

<a class="btn btn-danger" href="actions/delete_band.php?linenum=$i">

The fact that a deletion can be triggered by an HTTP GET request exposes you to a Spider of Doom situation:

  Things went pretty well for a few days after going live. But, on day six, things went not-so-well: all of the content on the website had completely vanished and all pages led to the default "please enter content" page. […]

  A user [had] copied and pasted some content from one page to another, including an "edit" hyperlink to edit the content on the page. Normally, this wouldn't be an issue, since an outside user would need to enter a name and password. But, the CMS authentication subsystem didn't take into account the sophisticated hacking techniques of Google's spider. Whoops.

Moreover, GET requests are generally cacheable, so clicking on the link might not reliably cause the row to be deleted.

For requests that trigger a state change on the server, what you want is an HTTP POST.  POSTs are not cacheable, and will not be triggered by web crawlers.  To change the link to perform a POST, you could either make it a button in a form or do something using JavaScript.


Simple timer start and stop from console

Why aren't you inheriting from Timer it's not a sealed class and is disposable (and I believe must be disposed).

public class PokerTimer : Timer
{
    public PokerTimer() : this(2000)
    {

    }

    public PokerTimer(double interval) : base(interval)
    {
        AutoReset = true;
        Elapsed += OnTimedEvent;
    }

    protected override void Dispose(bool disposing)
    {
        //clean up anything you need to here or remove this override.
        base.Dispose(disposing);
    }
}

All that being said, you said this is for a game where you want to time out players so you might want to look a bit into game loops and managing state in such a loop.


in general, I believe it would be better if you included this in some sort of chain. What I mean here:

don't return void, rather an Observable
don't show the progress dialog in the function, rather delegate it to the part responsible for UI. Same with displayData()
where's the whole function called? What calls it? Where is it located, in an Activity?

doOnNext() can be gotten rid of - there's no action in here
Are you getting just one result at a time? I mean, is the function called perpetually on and on and on, and you just evaluate the result each time? Perhaps you could use Single or Maybe, which is better suited for single results.

Good luck and hope we'll both learn something along the way.


Multiplying binary numbers digit by digit and carry method in Python

Python style

Style is important! Will you be able to read this code after a few months? I have a really hard time understanding this at first sight.

Use a if __name__ == '__main__'
Use built-ins like this bn(n):   return list(map(int, bin(n)[:1:-1]))] as suggested by @Coal_ with some changes to reverse the bin representation and change it a an integer
Use indentation of 4 spaces, this will make your code alot more readable. Currently you have mixed 4 indent with 2 indent, my eyes don't like this :)
Use more descriptive names, _(c, d, e, f, g) what do they mean? It is not clear for a Code reviewer.
Don't try to shorten lines as much as possible. For instance,

return [0] if is_zero(a) or is_zero(b) else \
        b if is_one(a) else \
        a if is_one(b) else _(a, b.pop(0), [], [], [])

This is short I agree, but not really nice to read or discriptive what it does at first sight.

if is_zero(a) or is_zero(b):
    return [0]
elif is_one(a):
    return b
elif is_one(b):
    return a
else:
    ....

Reads alot better in my opinion.

I would suggest to read up on PEP which has alot of nice pointers for Python style.

Algo

This should be possible without recursion, when I choose a big value you will get an error:

print(multiply2(bn(100000000000), bn(100000000000)), bn(100000000000*100000000000))
RecursionError: maximum recursion depth exceeded in comparison

You could avoid this by increasing the recursion depth but this is more of a hack then a solution.

How about a stack based approach to avoid the recursion?

Alternative approach

Using a stack based approach

def bn(n):
    return list(map(int, bin(n)[:1:-1]))

def is_zero(n):
    return not n[1:] and not n[0]

def add_lists(first, second):
    n = max(len(first), len(second))
    first += [0] * (n - len(first))
    second += [0] * (n - len(second))
    return [first[i] + second[i] for i in range(n)]

def carry_over(first_num, second_num):
    stack, overflow = [], 0
    for i in range(len(second_num)):
        if second_num[i] == 1:
            stack = add_lists(stack, [0] * i + first_num)

    for i in range(len(stack)):
        stack[i] += overflow
        overflow = stack[i] // 2
        stack[i] %= 2

    while overflow > 0:
        stack.append(overflow % 2)
        overflow //= 2

    return stack

def multiply2(first_num, second_num):
    if is_zero(first_num) or is_zero(second_num):
        return [0]
    else:
        return carry_over(first_num, second_num)

if __name__ == "__main__":
    # test cases
    for i in range(101):
        for j in range(101):
            print(f"{multiply2(bn(i), bn(j))}, {bn(i*j)}")


Convert hours and minutes to total minutes

OP's Questions

Is there specifically any way I could improve the argument/input parsing blocks?
See #3 far below
Would it be more consistent to ask the user for minutes if they supply an hours command line argument?
Could go either way on that.  #3 far below does that.
Should I offer the variety of options at all, or should I stick to command line arguments only or "dynamic" input only?

Break the needed input into 2 groups: required and optional.  An optional parameter may be the format to print the result another way - it is not required to run the core function of code.  A required one is the hours.  Minutes could go in either group.

If none of the required parameters are supplied, use interactive mode.

If all of the required parameters are supplied, proceed without asking.

If partial required parameters are supplied, error out.

Are there any meaningful names that could be assigned to the 1, 2, and 3 in the parsing blocks that would make the code more readable?

Not really.  Alternatively  the argument should be paired with a prefix one.  Sample code invocation:

    MBM_Minutes -hour 12 -minute 33
    same result as
    MBM_Minutes -minute 33 -hour 12

Optional arguments could be "-help" "-format AMPM", etc.

Other observations

argv[]

Should code trust that the string will convert to a valid int number of hours?  Look to strtol() or sscanf() if in doubt (or experienced).

// hours = atoi(argv[1]);

if (sscanf(argv[1], "%d", &hours) == 1) Success();
else Handle_Failure();

// better strtol() example down below

The last should be a catch-all else.

// else if(argc != 3) {
else {
  printf("Usage: %s (int hours) (int minutes)\n", argv[0]);

From a code layout, often is is best to qualify variables first, then proceed to the normal flow of code.  Note: argc == 0 is possible, though rare.

if (argc < 1 || argc > 3) {
  printf("Usage: %s (int hours) (int minutes)\n", argv[0]);
  // or send to stderr
  fprintf(stderrr, "Usage: %s (int hours) (int minutes)\n", argv[0]);
  return -1;
}

int hours;
if (argc < 2) {
  GetInt("Enter hours:", &hours, 0, 24);
} else {
  hours = atoi(argv[1]);
}

int minutes;
if (argc < 3) {
  GetInt("Enter minutes:", &hours, 0, 59);
} else {
  hours = atoi(argv[1]);
}

User Input

When dealing with user input, avoid being a hacker target.  Step 1: check user input function results.

puts("Enter the number of hours:");
if (scanf("%d", &hours) != 1) {
  perror("Number not entered\n");
  eixt(-1);
}

To be certain the output is truly outputted and not buffered, make certain the output is flushed before attempting input.

puts("Enter the number of hours:");
fflush(stdout);
if (scanf("%d", &hours) != 1) {

Input values should be qualified to the accept range.

if (scanf("%d", &hours) != 1) {
  ...
}
if (hours < 0 || hours > 24) {
  Handle_Range_Error(hours, 0, 24);
  ...
}

Take user input in a string and then parse it.  Easier to cope with bad input.  Suggests avoiding scanf() and use fgets().
Common code should exist in a helper function.  Putting the above ideas together results in a not-so-simple code and it is certainly overkill for a simple exercise.  Yet it is here to give you ideas of what it takes to handle general user input.

// return 0 on success
int GetInt(const char *prompt, int *dest, int min, int max) {
  long number;
  do {
    fputs(prompt);
    fflush(stdout);
    char buf[100];
    if (fgets(buf, sizeof buf, stdin) == NULL) return EOF;
    char *endptr;
    errno = 0;
    long number = strtol(buf, &endptr, 10);
    if (endptr == buf) continue;  // no conversion
    if (errno) continue; //overflow in conversion
    if (number < min || number > max) continue; // out of range
    while (isspace(*endptr)) endptr++;
  } while (*endptr); // extra junk at the end of the string
  *dest = (int) number;
  return 0;
}

int main(...

   if (GetInt("Enter hours:", &hours, 0, 24)) {
     Handle_EOF();  // Maybe post an error message and exit
   }

Constants

Alternatives to declaring a global object.  There are various pros and cons to these.  What is best is to code to your group's coding standards.  In doubt, go with the last, simplest one.

    const unsigned short MinutesPerHour = 60;
    // or full width to avoid promote to `int`
    const unsigned MinutesPerHour = 60;
    // or
    #define MinutesPerHour 60
    // or insure unsigned-ness
    #define MINUTES_PER_HOUR 60u
    // or classically
    #define MINUTES_PER_HOUR 60

Minor

Spelling: hourss --> hours


Selecting a random student from a class list

First off, things I like about this code:

you don't use StringVars for your Entry widgets. Lots of tutorials seem to use them, but they are largely unnecessary
I like that you grouped all of your grid commands together.

Now, the things I think need improving:

from Tkinter import Tk,Button,StringVar,Entry,Label

Best practices suggest you import the whole library with a shorthand name such as tk. You then can reference each of the widgets by the short name to make it absolutely clear where the code is coming from. Otherwise, if you were to use both Tkinter and ttk widgets at some point, it becomes  unclear if you're referencing a Tkinter widget or a ttk widget since they both export similar class names.

I suggest changing your import to this:

import Tkinter as tk

Then, change all references to Button to be tk.Button, etc. This extra little bit of typing will make your code much easier to read and maintain over time.

It's great that you grouped all of your grid statements together.  However, the rest of your code is oddly interleaved. You have functions intermixed with code.

Instead of doing this:

addKidName=Entry(...)
def addkid(): ...
addKid=Button(...)
def choosekid(): ...

group all of your functions together, and all your widgets together.

def addkid(): ...
def choosekid(): ...
def loadfile(): ...
def savetofile(): ...
...
addKidName=Entry(...)
addKid=Button(...)
...

If you use grid  you should always do three things:

1) explicitly declare a sticky attribute for each widget
 2) always use rowconfigure to give at least one row a positive, non-zero weight (even if it's an invisible row below all other rows)
 3) always use columnconfigure to give at least one column a positive, non-zero weight (even if it's an invisible column to the right of all other columns)


DataTable runtime grouping on user defined criteria

Honestly, I am not sure if a dictionary is the right data structure for realizing composed keys. At least for me it is not directly obviously how the data are grouped. I think the main issue that confuses me is, that the grouping key contains not just the values to group by, but also the column headers which is absolutely irrelevant for grouping. Additionally I have to understand the comparer.

For your example, you could easily use a tuple which provides build-in comparison of each item:

var rowGroups = dataTable.AsEnumerable()
    .GroupBy(x => Tuple.Create(x["FirstName"], x["LastName"]))
    .ToList();

Another more flexible approach could be to create a string value to be used as grouping key:

var rowGroups = dataTable.AsEnumerable()
    .GroupBy(x => string.Join(":", keyColumns.Select(key => x[key])))
    .ToList();


Removing duplicated code

The same code seems to be duplicated in various places. You can easily define a generic function that you'll be able to reuse in all your definitions.

Here's what I have done (not so tested) :

def generic_compare(self, command, func, error):
    if command[1] == self.st_brace and command[3] in self.OPERATORS and command[5] == self.end_brace:
        try:
            print self.OPERATORS[command[3]](
                func(command[2]), func(command[4]))
        except ValueError:
            print error
    if command[3] not in self.OPERATORS:
        print self.OpError

# Compare two integers
def compareint(self, command):
    self.generic_compare(command, int, self.IntError)

# Compare two strings
def comparestr(self, command):
    self.generic_compare(command, eval, self.StrError)

# Compare two lists
def comparelst(self, command):
    self.generic_compare(command, eval, self.LstError)

# Compare two booleans
def comparebool(self, command):
    self.generic_compare(command, eval, self.BoolError)

You don't need a class

I suggest you have a look at this Python talk called "Stop Writing Classes ".
In your situation, there is no need for a class at all :

Your code could be written :

from operator import *

OpError = "OpError: Invalid operator or brace.\n"
IntError = "IntError: Invalid integers.\n"
StrError = "StrError: Invalid strings.\n"
LstError = "LstError: Invalid list.\n"
BoolError = "BoolError: Invalid boolean.\n"
st_brace = "["
end_brace = "]"
OPERATORS = {
        ">=": ge,
        "<=": le,
        "==": eq,
        "!=": ne,
        ">": gt,
        "<": lt}

def generic_compare(command, func, error):
    if command[1] == st_brace and command[3] in OPERATORS and command[5] == end_brace:
        try:
            print OPERATORS[command[3]](
                func(command[2]), func(command[4]))
        except ValueError:
            print error
    if command[3] not in OPERATORS:
        print OpError

# Compare two integers
def compareint(command):
    generic_compare(command, int, IntError)

# Compare two strings
def comparestr(command):
    generic_compare(command, eval, StrError)

# Compare two lists
def comparelst(command):
    generic_compare(command, eval, LstError)

# Compare two booleans
def comparebool(command):
    generic_compare(command, eval, BoolError)

# Dict containing commands
COMMANDS = {
    "cmpbool": comparebool,
    "cmplst": comparelst,
    "cmpint": compareint,
    "cmpstr": comparestr,
}

# Read the inputted commands
def read_command(prompt):
    command = raw_input(prompt)
    split_cmd = command.split(" ")
    if split_cmd[0] in COMMANDS:
        COMMANDS[split_cmd[0]](split_cmd)
    if split_cmd[0] not in COMMANDS:
        print "CmdError: Invalid command.\n"

# Run the program
if __name__ == "__main__":
    while True: read_command(">}}>")

Use the logic and the usual programming structure

Instead of writing :

    if split_cmd[0] in COMMANDS:
        COMMANDS[split_cmd[0]](split_cmd)
    if split_cmd[0] not in COMMANDS:
        print "CmdError: Invalid command.\n"

Write :

    if split_cmd[0] in COMMANDS:
        COMMANDS[split_cmd[0]](split_cmd)
    else:
        print "CmdError: Invalid command.\n"

Also, you could rewrite :

    if command[1] == st_brace and command[3] in OPERATORS and command[5] == end_brace:
        try:
            print OPERATORS[command[3]](
                func(command[2]), func(command[4]))
        except ValueError:
            print error
    if command[3] not in OPERATORS:
        print OpError

in a way that hilight that sometimes something will be printed, sometimes not.

Define "pure" functions

By defining your functions in such a way that they have no side-effects (printing results for instance), you make them easier to test. In your case, it's quite simple, you can just return instead of printing.

Separe the concerns

You should split the part handling user input/output and the part computing results. This does hand in hand with previous comment.

At this stage, after adding simple tests in the main :

from operator import *

OpError = "OpError: Invalid operator or brace.\n"
IntError = "IntError: Invalid integers.\n"
StrError = "StrError: Invalid strings.\n"
LstError = "LstError: Invalid list.\n"
BoolError = "BoolError: Invalid boolean.\n"
st_brace = "["
end_brace = "]"
OPERATORS = {
        ">=": ge,
        "<=": le,
        "==": eq,
        "!=": ne,
        ">": gt,
        "<": lt}

def generic_compare(command, func, error):
    if command[3] in OPERATORS:
        if command[1] == st_brace and command[5] == end_brace:
            try:
                return OPERATORS[command[3]](
                    func(command[2]), func(command[4]))
            except ValueError:
                return error
    else:
        return OpError

# Compare two integers
def compareint(command):
    return generic_compare(command, int, IntError)

# Compare two strings
def comparestr(command):
    return generic_compare(command, eval, StrError)

# Compare two lists
def comparelst(command):
    return generic_compare(command, eval, LstError)

# Compare two booleans
def comparebool(command):
    return generic_compare(command, eval, BoolError)

# Dict containing commands
COMMANDS = {
    "cmpbool": comparebool,
    "cmplst": comparelst,
    "cmpint": compareint,
    "cmpstr": comparestr,
}

def evaluate_command(command):
    split_cmd = command.split(" ")
    if split_cmd[0] in COMMANDS:
        return COMMANDS[split_cmd[0]](split_cmd)
    else:
        return "CmdError: Invalid command.\n"

# Read the inputted commands
def read_command(prompt):
    print(evaluate_command(raw_input(prompt)))

# Run the program
if __name__ == "__main__":
    assert evaluate_command('cmpbool [ True == True ]')
    assert not evaluate_command('cmpbool [ True == False ]')
    assert evaluate_command('cmplst [ [""] == [""] ]')
    assert not evaluate_command('cmplst [ [""] == ["a"] ]')
    assert evaluate_command('cmpint [ 2 == 2 ]')
    assert not evaluate_command('cmpint [ 2 == 3 ]')
    assert evaluate_command('cmpstr [ "Hello" == "Hello" ]')
    assert not evaluate_command('cmpstr [ "Hello" == "HelloW" ]')
    #while True: read_command(">}}>")

Make things cleaner

It could be a good idea to feed the comparison functions only the information they need : the first element of the list is not relevant anymore at this stage.

You can just write :

def evaluate_command(command):
    split_cmd = command.split(" ")
    func, args = split_cmd[0], split_cmd[1:]
    if func in COMMANDS:
        return COMMANDS[func](args)
    else:
        return "CmdError: Invalid command.\n"

and then, you need to re-index generic_compare :

def generic_compare(command, func, error):
    if command[2] in OPERATORS:
        if command[0] == st_brace and command[4] == end_brace:
            try:
                return OPERATORS[command[2]](
                    func(command[1]), func(command[3]))
            except ValueError:
                return error
    else:
        return OpError

Don't import *

Import * is bad. You can just as easily write :

import operator
OPERATORS = {
        ">=": operator.ge,
        "<=": operator.le,
        "==": operator.eq,
        "!=": operator.ne,
        ">":  operator.gt,
        "<":  operator.lt}

Style

In Python, the good there is a style guide called PEP 8. You'll find various tools to check your code if you want : pep8, pylint, pychecker, pyflakes, etc.

Misc

Usually, using eval in any programming language is quite dangerous. What if I was to evaluate a massive chunk of code with unpredicted side-effects (removing files from my file system for instance) ?
Also, you should perform a lot more checks before accessing random elements from split_cmd as it might be shorter than you expect.


Its a very tight coupling between HTTP and your domain.
However I do not like classic layered architecture. I often utilizes CQS for my service API's

Your example would look like

public class GetProductQueryHandler: IQueryHandler<GetProductQuery, Product>
{
   private readonly DbContext db;

   public GetProductQueryHandler(DbContext db) {
      this.db = db;
   }
   public async Task<Product> Handle(GetProductQuerycommand query) {
      if (!query.Id.HasValue) throw new ArgumentExpection("Id is required"); //Not accepting null for a Nullable is a bit strange

      var product = await db.Products.FindAsync(id);
      if (product == null) throw new NotFoundExcpetion("Product");

      return product;
   }
}

You can then translate the errors into HTTP codes using a Exception filter, here is an example from my current project

    public class ExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnException(actionExecutedContext);

            var message = "Server error";
            var details = "Please contact support if the problem persists";

            var code = HttpStatusCode.InternalServerError;

            if(actionExecutedContext.Exception is ArgumentException)
            {
                code = HttpStatusCode.BadRequest;
                message = "Bad Arguments";
                details = actionExecutedContext.Exception.Message;
            }

#if DEBUG
    details =   string.Format("{0}: {1}", actionExecutedContext.Exception.Message, actionExecutedContext.Exception.StackTrace);
#endif

            var response = new
            {
                Message = message,
                Details = details
            };

            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(code, response);
        }
    }


What is truthmap trying to achieve? I can't quite figure it out, sorry.

contains by nature will always be O(N) in your implementation, so yes, it's speed is equal to the number of elements in your table.

count should probably be renamed to countOf to better signify it's intent. Better yet, you could rename it where, have it take a function, and then allow the user to use the standard # operator on the resultant table.

removePerValue seems unnecessary with a where function. Users can simply filter the table rather than remove values from the table.

equalsAll in my opinion again should take a function as an argument and not an object.

You should change your loops from for k, v in pairs(tbl) do to for _, v in pairs(tbl) do if you are not using k.

I'm sure there's things to be said about the implementation of equalsAll but I don't have time to point that out at the moment.

Do you know about the # operator? appending # to the front of a table will return a value of the size of the table (more precisely, it will return the highest indexed number in the table, so it will be incorrect for sparse arrays).

You should ideally not need comments to explain the purpose of code - your functions should describe themselves ;-)


Applying EF core in Universal Windows Apps using a large database

In this tutorial, it shows the usage of a dbcontext derived class inside a function called Page_Loaded in MainPage.xaml.cs. Is this a bad design?

Yes, I think it is a bad design and implementing a repository the way you did it is the right approach.

  Another thing: if I add many tables, my Repository.cs will grow so large that it might reach thousands of lines, how do you break this one? I might add 30 more tables inside so I could imagine how it will look cluttered inside Repository.cs file.

Let's talk about it later when you have that many tables but for now in order to avoid a file with thousands of lines (which is highly unlikely) you should already start with different repositories. Now you have only the Respository which is not that bad by itself but it can be better. In your case it should be a PersonRepository. So now you have one for people. When you add more tables later I'm pretty sure you can come up with another repository for them. It doesn't have to always be one repo for a table. You have have repositories that are all about people and work internally with mutliple person-related tables. Then there might be repositories that work with other data like files etc.

Just don't put all your code in a single file. Group the talbles together by what makes more sense.


"okay" in programming often depends on context.
You chose to perform error handling by throwing exceptions, so there is no point in having a boolean return value - there will be no case where false is returned.
If you are asking whether it is better to return false rather than throw exception, that largely depends on the situation.
Your current error handling is already more granular than just success / failure - you want to detect different types of errors and respond differently, so the exception method is more appropriate.
Note that if you were to switch to return and maintain same granularity, you would need to use an Enum of possible results.
As for "Is error handling ok" - again, that depends.
How much 'some stuff' do you have around the API call?
What kind of stuff is it?
You may want to limit the amount of code in the catch block, and have separate catch blocks for other parts of code that may fail independently of any server errors.
Then again, how granular do you want to make your error handling?
Usually, the more precise the error and the more information user of the function has regarding why it failed the better, but if there are some constraints or type of errors that are not important they may be omitted, consolidated, or handled silently.


If you want to avoid passing $billId argument down the chain within Bills class - "stub" chain of those methods.
Let the getPaymentServiceId() method do all the "processing" work. Remove calculatePaymentServiceId and createPaymentServiceIdFromCompanyCode methods.  The final result should look like the following:

class Bills {

    private $typeAndPaymentServiceIdMap = [
        0 => 13,
        1 => 4, // water
        2 => 1, // electricity
        3 => 5, // gas
        4 => 2, // landline
        5 => 3, // cellphone
        6 => 6, // municipality due
        7 => 6, // municipality due type 7
        9 => [
            'default' => 24, // traffic due
            '001' => 38, // traffic fine
            '002' => 38, // traffic fine
        ],
    ];
    private $logger;

    public function __construct($logger = "") {
        $this->logger = $logger;
    }

    public function getType($billId = "") {
        return substr($billId, -2, 1);
    }

    public function getAmount($paymentId = "") {
        $paymentId = str_pad($paymentId, 13, '0', STR_PAD_LEFT);
        $amount = ltrim(substr($paymentId, 0, 8), '0') . '000';

        return $amount;
    }

    public function getCompanyCode($billId = "") {
        return substr($billId, -5, 3);
    }

    public function getPaymentServiceId($billId = "") {
        if (!$billId) {
            $this->logger->errorLog('billId is required!');
            return;
        }
        $type = $this->getType($billId);
        $companyCode = $this->getCompanyCode($billId);

        if (key_exists($type, $this->typeAndPaymentServiceIdMap)) {
            $paymentServiceId = $this->typeAndPaymentServiceIdMap[$type];
            if (is_array($paymentServiceId)) {
                return (key_exists($companyCode, $paymentServiceId))? $paymentServiceId[$companyCode] : $paymentServiceId['default'];
            } else {
                return $paymentServiceId;
            }
        } else {
            $this->logger->errorLog('Type ' . $type . ' is not defined in the $typeAndPaymentServiceIdMap.');
        }
    }
}

// $logger object
$bill = new Bills($logger);

var_dump($bill->getPaymentServiceId("00190"));  // int 38
var_dump($bill->getPaymentServiceId("00390"));  // int 24


Ternary search tree implementation in python 3

Data structure-wise, it seems okay, and does what you're after.

Code-style wise, I see a few things:

It's not quite PEP8, the coding style. Whilst you can read it, which is always good, there are tools to automatize the process, such as flake8, black. Most likely, your editor will have a plugin.

This is include things like underscore_names in lieu of camelCasing.

Note that this standard is a living document, and gets updated once in a while.
None is a singleton in Python, and thus you can use the is keyword instead.
Python relies on its id() function to get a hash of an object, and compare them.
As None is a singleton, the hash is the same.

So your line if node == None: could be if node is None.
Going further this way, None evaluates to False in a test, so you could go if not node: (edit: as discussed with @Gloweye, it's indeed clearer and preferred to use the first variant).
Python returns None when no value is being explicitly returned, whether you have no return in a function, or do a blank return.

These two lines taken together could then be:

if node is None:
    return

and would be considered idiomatic.

Lastly, in Python3 (which you ought to be using), class definition have been revamped. The way you do it:

class TST(object):

is now:

class TST:

If you were inheriting from something, though, it would indeed be:

class TST(ParentClass):

Maybe what you could try next is to implement unit tests with unittest or pytest and see whether your structure holds on with more convoluted cases.


The whole idea behind decorators, proxies and drapers is that they encase a single object. Yours seems to be serving two masters and has far too much knowledge of the different objects in your system.

It hard to get a picture of your models from the question - but it seems like you are missing a key relationship since you are passing binder and
credential around together.

Also instead of creating your own proxying methods you can simply extend the Delegator class but first you have to figure what you are actually proxying and stick to that object.


Looping to update article codes on one server based on queries on another server

if you can access the second database from the same connection

use this query

UPDATE articles a1 inner join YOURDB.articles a2 on a1.id=a2.id
set a2.artcode = a1.artcode

but if your database is in another server i'm afraid you can't make it in one query


Checking if a string has all unique characters

Looks good to me from a big-O point of view.

C++wise, you have some misconceptions:

//setting all values to false (0)
bool check[256] = {false};

This explicitly initializes only the first element to false; the remaining 255 elements are value-initialized, which in layman's terms means zero-initialized, which means yes they're initialized to false as well in this case; but your comment is misleading, in that

bool uncheck[256] = {true};

would not initialize all 256 elements to true — it would explicitly initialize the first element to true and then value-initialize the other 255 elements (to false).

for (int i = 0; i < user.length(); i++)
    {
    int value = user.at(i);
        if (check[value] == true)
        {
            return false;

This indentation is all screwed up. You should indent whenever you enter a new scope, and dedent when leaving a scope. So for example it would be sensible to write

for (int i = 0; i < user.length(); i++)
{
    int value = user.at(i);
    if (check[value] == true)
    {
        return false;

but actually most programmers would just write

for (int i = 0; i < user.length(); ++i) {
    int value = user[i];
    if (check[value]) {
        return false;

(notice the cuddled braces, the removal of the explicit test-for-equality with true, the default preference for ++i over i++, and the preference for fast operator[] over slow .at() when the index is statically known to be in-bounds).

bool checkString (string user)

This function signature tells the function to take the parameter user by value, which means "make a copy." Since you don't need a copy for any reason, you should by default prefer to take a reference:

bool checkString(const string& user)

(and notice the removal of the extra space in between the function name and its parameter list; we don't write f (x) in C++ for the same reason you don't write “f  (x)” in math class).

It might be an interesting research project for you to figure out what you'd have to change to make // Assuming ASCII no longer required.


Multi-tiered sorting using custom IComparer

You can use types from ComparerExtensions to make your code more maintainable:

IComparer<SurveyResponse> comparer = KeyComparer<SurveyResponse>
    .OrderBy(sr => sr.Question.Survey.Feature.Application.Name)
    .ThenBy(sr => sr.Question.Survey.Feature.Name)
    .ThenBy(sr => sr.Question.Survey.TimeTaken)
    .ThenBy(sr => sr.Question.Survey.ID)
    .ThenBy(sr => sr.Question.Position);

But I don't think you can actually make your comparer more efficient, it should be already very fast (it's just a few simple instructions). Are you sure your performance problem is caused by this comparer?


Should a piece of code only ever called once be a separate method?

I think the answer here is no, it shouldn't be a separate method, as long as the piece of code in question is short. That way, when you read the code, you immediately see what the code does, you don't have to go elsewhere for that. But if the piece of code was too long, it would make the whole method less readable, so in that case, I think you should put it into a separate method.

Few more notes:

You don't need the new WaitCallback() in either case, the compiler can create the delegate automatically.

Also, it might make sense to use Task instead of ThreadPool, assuming you're on .Net 4+.


Some time is lost by having to traverse the p list for each product. For large data, you could preprocess the p list, and create a dict that is keyed by the part, and which provides a list of sub parts for it. Then the lookup for a given product will be faster.

Secondly, the second part of the code will find deeper nested parts, but will fail to find them all when the nesting is deeper.

Here is suggested improvement:

def bom_build(o,p):
    # Create a hash keyed by parts, providing their sub parts as list
    d = dict()
    for [part, subpart] in parts_h:
        if part in d:
            d[part].append(subpart)
        else:
            d[part] = [subpart]

    bom = []

    def recurse(bom, d, serial, part, path, required):
        if part in d:
            for subpart in d[part]:
                nextpath = path + '/' + subpart
                bom.append([serial, part, subpart, nextpath])
                recurse(bom, d, serial, subpart, nextpath, False)
        elif required: # when there are no sub parts
            bom.append([serial, part, None, path])

    for [serial, part] in order:
        recurse(bom, d, serial, part, part, True)

    return bom

See it run on repl.it

Alternative: Breadth First Search

As an alternative you could also use a BFS algorithm -- the first part is the same:

def bom_build_bfs(o,p):
    # Create a hash keyed by parts, providing their sub parts as list
    d = dict()
    for [part, subpart] in parts_h:
        if part in d:
            d[part].append(subpart)
        else:
            d[part] = [subpart]

    # add start elements to bom, which later will be removed
    bom = [[serial, None, part, part] for [serial, part] in order]
    i = 0
    # treat it as a queue, adding to it while looping
    while i < len(bom):
        [serial, parent, part, path] = bom[i]
        i += 1
        if part in d:
            for subpart in d[part]:
                bom.append([serial, part, subpart, path + '/' + subpart])
        elif i < len(order): # when there are no sub parts
            bom.append([serial, part, None, path])

    # return the part without the starter elements
    return bom[len(order):]

In my limited tests this ran slower than the DFS solution, but it might depend on how the input data is distributed and how deeply nested it is.


This question is highly specific to the Autodesk Inventor SDK.

While it's not really nice way to check if a property exists, it's documented by Autodesk
Inventor as the way to do it, since there's not a simple "Check if a property exists" method on the property set (which is very stupid).

The sample in VBA (not VB.Net) that Autodesk Provides can be found there

The main reason being that catching an Exception can be slower than checking if a method exists.

So in theory if you use this a lot (e.g. 1000 times in a loop), it may be theoreticaly be cleaner/faster/better, to first check which properties are defined, using the method:

PropertySet.PropertyInfo()

And check if the property exists.

That being said, Inventor may or may not use a COM+ interface which is not too fast.

If performance is not an issue, a practical advice can be to try to set the property and otherwise add it, if it does not exist.


Python program to remove invalid parentheses

Test, consistent behavior & data structure

Trying to add tests for the code based on the example of input/output provided led to the following result: the behavior is not consistent : in particular the order of the elements in the returned list is not always the same.

The root cause for this is that we are using sets in the logic only to convert to list at the end.

A solution would be to return sorted(results) at the end. An alternative would be to just return a set instead of trying to convert to list.

Then, we get the following automated tests:

print(remove_invalid_parentheses("()())()") == {"(())()", "()()()"})
print(remove_invalid_parentheses("(a)())()") == {"(a())()", "(a)()()"})
print(remove_invalid_parentheses(")(") == {""})

It would make sense to try to rewrite it as unit-tests using a proper unit-test framework but I will stop here as this is enough for me to keep working.

More explicit loop

I tend to find loops based on for ii in range(ll - 1, -1, -1) very error-prone/hard to understand because of the number of tweaks on both sides of the range. I'd suggest a much more explicit alternative: for ii in reversed(range(ll)):.

Similar indices

As ii will go over ]ll, 0] which is ]len(s) - removed, 0], i will go over ]len(s), removed].

The difference between the indices is always removed, we have ii + removed == i: we can get rid of the i variable. We can take this chance to rename ii into i.

At this stage, we have:

def remove_invalid_parentheses(s):
    removed = 0
    results = {s}
    count = {"(": 0, ")": 0}
    for i, c in enumerate(s):
        if c == ")" and count["("] == count[")"]:
            new_results = set()
            while results:
                result = results.pop()
                for j in range(i - removed + 1):
                    if result[j] == ")":
                        new_results.add(result[:j] + result[j + 1:])
            results = new_results
            removed += 1
        elif c in count:
                count[c] += 1
    count = {"(": 0, ")": 0}
    ll = len(s) - removed
    for i in reversed(range(ll)):
        c = s[i + removed]
        if c == "(" and count["("] == count[")"]:
            new_results = set()
            while results:
                result = results.pop()
                for j in range(i, ll):
                    if result[j] == "(":
                        new_results.add(result[:j] + result[j + 1:])
            results = new_results
            ll -= 1
        elif c in count:
                count[c] += 1
    return results

print(remove_invalid_parentheses("()())()") == {"(())()", "()()()"})
print(remove_invalid_parentheses("()())))()") == {"(())()", "()()()"})
print(remove_invalid_parentheses("(a)())()") == {"(a())()", "(a)()()"})
print(remove_invalid_parentheses(")(") == {""})

(I took this chance to add a new test case)

More explicit loop again

We want to iterate in reversed order over the beginning of the s string. Here again, we can try to make things more explicit and remove some computation as we go:

    for i, c in enumerate(reversed(s[removed:])):
        if c == "(" and count["("] == count[")"]:
            new_results = set()
            while results:
                result = results.pop()
                for j in range(len(s) - i - removed - 1, ll):
                    if result[j] == "(":
                        new_results.add(result[:j] + result[j + 1:])
            results = new_results
            ll -= 1
        elif c in count:
                count[c] += 1

In order to test this more throughly, I took this chance to add the following test case:

print(remove_invalid_parentheses("((((((((()(") == {"()"})

More beautiful loops

Instead of using a combination of while and pop to iterate over the elements of a set, you can just use for:

        for result in results:

Work in progress: I have to go. I may continue in the future.


; alien-at-edge?: alien --> boolean
(define (alien-at-edge? an-alien)
(or (alien-at-right-edge? an-alien)
(alien-at-left-edge? an-alien)))

Not much to do here but don't forget about indentation to make your code readable.

; any-alien-at-edge?: loa --> boolean
(define (any-alien-at-edge? a-loa)
(cond [(empty? a-loa) false]
[else (or (alien-at-edge? (first a-loa))
      (any-alien-at-edge? (rest a-loa)))]))

This pattern occurs a lot in functional programming: produce a value (a boolean here) by applying a function (or here) to your list. You can rewrite your function as:

; any-alien-at-edge?: loa --> boolean
(define (any-alien-at-edge? a-loa)
  (foldl or false a-loa)

You can also use ormap if foldl is hard to understand.

;alien-at-left-edge?: alien --> boolean
(define (alien-at-left-edge? an-alien)
 (<= (- (posn-x an-alien) ALIEN-DELTA-X) alien-half))

;alien-at-right-edge?: alien --> boolean
(define (alien-at-right-edge? an-alien)
(>= (+ (posn-x an-alien) ALIEN-DELTA-X) (- WIDTH alien-half)))

Watch out for indentation and trailing spaces.

;any-alien-at-right-edge?: loa --> boolean
(define (any-alien-at-right-edge? a-loa)
(cond [(empty? a-loa) false]
[else (or (alien-at-right-edge? (first a-loa))
      (any-alien-at-right-edge? (rest a-loa)))]))

;any-alien-at-left-edge?: loa --> boolean
(define (any-alien-at-left-edge? a-loa)
(cond [(empty? a-loa) false]
[else (or (alien-at-left-edge? (first a-loa))
      (any-alien-at-left-edge? (rest a-loa)))]))

Those ones can also be implemented using foldl. Try it out!


Optimizing python code for big data sets

Your code contains a mix of tabs and spaces. This caused your code to display incorrectly before I edited it. The most common way in python is to use only spaces. You should be able to configure your editor to insert spaces instead of tabs when you push the tab key.

import sys
import json
import re

def findRecord(key, records):

Python convention is to name function lowercase_with_underscores

    for r in records:
        if r[0] == key:
            return r

It is going to be inefficient to loop over records looking for things like this. Instead, you use a dictionary and look them up by key.

def average_records(records):
    for r in records:

Rather than indexing r all over the place, I suggest using:

    for k, new_value, new_count, old_neg_value, old_neg_count in records:

Then you can access those names directly. It'll be easier to read and probably marginally faster.

        if r[1] > 0:
            avg = r[1] / r[2]
            print r[0] + ' ' + str(avg)
        else:
            avg = r[3] / r[4]
            print r[0] + ' ' + str(avg)

In this case, you can do: print r[0], avg for the same result.

def hw(sent_file, tweet_file):

I have no idea what hw means

    scores = {}

    sent_file = open(sent_file, 'r')

    for line in sent_file:
        term, score = line.split("\t")
        scores[term] = int(score)

This scores bit is a nicely self contained section. I suggest making it a separate function.

    recored_affin = []

    #print scores.items()

Don't keep dead code, just remove it. If you think you might need it back look into version control.

    data = []

    with open(tweet_file, 'r') as f:
        for line in f:
            data.append(json.loads(line))

        #print data[4]['text']

You're finished with the file now, you should really drop out of the with block.

        for tweet in data:

There isn't really much point in storing the json objects in a list just to process them. Just process them as you get them.

            total = 0
            if 'text' in tweet:
                for k, v in scores.iteritems():

                    #print tweet['text']
                    num_of_aff = len(re.findall(k, tweet['text']))
                    if num_of_aff > 0:
                        #print "Number is: " + str(num_of_aff)
                        #print "Word is: " + k
                        #print "Tweet is: " + tweet['text']
                        total += (v * num_of_aff)
                        #print "Score is: " + str(total)

                        #while count < len(recorded_affin):

Don't leave commented code in there

                        foundRow = findRecord(k, recored_affin)

                        if foundRow != None:

Use is None to check for foundRow

                            index = recored_affin.index(foundRow)

That's going to be expensive, it scans through the whole list again.

                            quick_rec = recored_affin[index]

Isn't this just foundRow again?

                            if v > 0:
                                new_value = quick_rec[1] + v
                                new_count = quick_rec[2] + 1
                                old_neg_value = 0
                                old_neg_count = 0
                                recored_affin.append([k, new_value, new_count, old_neg_value, old_neg_count])
                                recored_affin.remove(foundRow)

Expensive, has to scan through again.
                                elif v < 0:

                                old_pos_value = 0
                                old_pos_count = 0
                                new_value = quick_rec[3] + v
                                new_count = quick_rec[4] + 1
                                recored_affin.append([k, old_pos_value, old_pos_count, new_value, new_count])
                                recored_affin.remove(foundRow)

You've got some duplication here, you should move the common logic out of the if blocks.

                        else:
                            if v > 0:
                                recored_affin.append([k,v,1,0,0])
                            elif v < 0:
                                recored_affin.append([k,0,0,v,1])

                            #print recored_affin

                        ##print foundRow

                ##print total
    average_records(recored_affin)

def lines(fp):
    print str(len(fp.readlines()))

def main():
    sent_file = open(sys.argv[1])
    tweet_file = open(sys.argv[2])

Why do you open these file but never do anything with them?

    hw(sys.argv[1], sys.argv[2])
    #lines(sent_file)
    #lines(tweet_file)

if __name__ == '__main__':
    main()

Your speed issues are probably the result of using a list and constantly searching over the whole list instead of using a dictionary. Make recorded_affin a dictionary, and your code should be simpler and faster.


Sliding window to solve "longest substring, no repeating chars"

Summary: stay with your implementation.

I don't think a re-usable sliding window fits well to your algorithm.

What are the operations that come to one's mind with both a generic sliding String window and with your algorithm (I'll stay with your terminology of head and tail, although personally I'd name them just the other way round)?

advanceHead() generic op, not used by your algo (see jumpHead())
advanceTail() generic op, used by your algo
jumpHead(int newPos) only specific to your algo
getSubstring() generic op, not used by your algo
findInSubstring(char ch) maybe generic op, not really used by your algo (see below method)
lastOccurrenceBeforeTail(char ch) used by your algo, but I wouldn't expect such a method in a generic sliding window

So, there's hardly any overlap between your algo's sliding window and operations one would expect from a re-usable generic sliding window.

If you'd extract a sliding window from your algorithm, it would be burdened by quite specific methods that no-one else would ever use.

If you were to use a generic sliding window in your algorithm, you'd still have to maintain the character-positions storage and do the head-jumping individually.

One optional refactoring of your code could be to extract a NonRepeatingSlidingWindow with two public methods:

advance() increments the tail, jumps the head if necessary and returns a "finished"-flag
getLength() returns the current size of the sliding window.


The good

Your code will handle any type of browser, is pretty easy to follow.

The bad

Pub.removeEvent will not work. That's because you define Priv.proto.removeEvent twice, whereas you probably want to define Priv.proto.removeEvent and Priv.removeEvent.

The ugly

You are using doc.createEvent which is deprecated, you should look into event constructors.

Furthermore

Because IE decided to do things differently for many event related things, a lot of people check as you do for the existence of a function and go from there, however your approach could be a little DRYer.

Priv.addEvent = (function () {
    if (win.addEventListener) {
        return function (type, callback) {
            $A.someKey(this, function (val) {
                val.addEventListener(type, callback);
            });
        };
    }
    if (win.attachEvent) {
        return function (type, callback) {
            $A.someKey(this, function (val) {
                val.attachEvent('on' + type, callback);
            });
        };
    }
    return Priv.functionNull;
}());

can be done as

Priv.addEvent = (function () {
  var addFunction = win.addEventListener ? 'addEventListener' : 'attachEvent',
      prefix      = win.addEventListener ? '' : 'on';

  return function (type, callback) {
    $A.someKey(this, function (val) {
      val[addFunction]( prefix + type, callback);
    });
  };
  return Priv.functionNull;
}());

This approach can be applied to addEvent, removeEvent and perhaps to 'createEvent'.

Finally, as always, you should steer away from someKey, just stick to the standard Array.


Extract a method.

class Task implements Runnable {

    ...
    private completeStatement (CallableStatement stmt, Strung userId)
    {
        callableStatement.setString(1, String.valueOf(userId));
        ...
    }

    @Override
    public void run() {
        dbConnection = getDbConnection();
        callableStatement = dbConnection.prepareCall(Constants.UPSERT_SQL);
        completeStatement(callableStatement,userId)

    }
}

private Connection getDBConnection() {
    ...
}

But find a more suitable name for what your statement is doing.


Rearrange elements in two-dimensional array spiral order

I'm not sure what exactly about your code made it a "show-stopper." Your use of tmpArray has a bit of a smell to it. There are issues of readability (why does the line for(var i=c1;i<=c2;i++) only have one space in it??). Your core algorithm (getUpperCorner and getLowerCorner) isn't documented and is fairly hard to read.

Personally, though, I would have approached this as a straight recursion problem. So you have the following matrix:

 1  2  3  4
 5  6  7  8
 9 10 11 12

Your "spiral" begins with the the top row, 1 2 3 4. So chop that off and save it.

   1  2  3  4
✂ ┄┄┄┄┄┄┄┄┄┄┄┄
   5  6  7  8
   9 10 11 12

Now you'll notice that the rightmost column of the remaining part, 8 12, is the next part of the spiral. But what if we turn it 90º counter-clockwise?

 5  6  7  8  =>   8 12
 9 10 11 12       7 11
                  6 10
                  5  9

Now 8 12 the top row! Chop it off and repeat:

   8 12
✂ ┄┄┄┄┄┄
   7 11  =>  11 10  9  =>    11 10  9
   6 10       7  6  5     ✂ ┄┄┄┄┄┄┄┄┄┄
   5  9                       7  6  5  =>  5  =>   5
                                           6    ✂ ┄┄┄
                                           7       6  =>  6  7  (end!)
                                                   7

By now you've seen the pattern. To get a matrix's "spiral" you just take off the top row, rotate what's left, then get its spiral, and so on.

Def Spiralify( Matrix )
  If( Matrix has only one row )
    Return( the row )

  Else
    FirstRow     := first row of Matrix
    RestOfMatrix := all of Matrix except the first row

    NextMatrix := RotateLeft( RestOfMatrix )

    NextSpiral := Spiralify( NextMatrix )

    Result := JoinArrays( FirstRow, NextSpiral )

    Return( Result )

RotateLeft will actually make up the most lines of code, but it's just a straightforward nested loop, and the rest basically writes itself.

Update

I had some time to write up an actual implementation. Rather than paste it here you can check it out on jsFiddle.


Sure, use String.replace. As an added bonus, it doesn't fail when there is no match:

'
this is a $test
'.replace(/(\$\w+)/g, '
$1
')


A method that returns an array with no duplicates

Wouldn't it be easier to just use:
public static class IntArrayProcessor {

    private Integer[] arr;

    public IntArrayProcessor(Integer[] arr) {
        this.arr = arr;
    }

    public Integer[] unique() {
        final Set<Integer> uniqueSet = new HashSet<Integer>(Arrays.asList(this.arr));
        return uniqueSet.toArray(new Integer[uniqueSet.size()]);
    }
}

I changed the method name from getSet() to the more descriptive unique().
This simply generates a hash set, which contains only the unique values of the array. The hash set (uniqueSet) is then converted from Set to Integer[], and returned.
Given that this is using built-in methods and objects, it would likely be faster than most custom implementations.
Notice that HashSet:

makes no guarantees as to the insertion order of the set; in particular it does not guarantee that the order will remain constant over time.
— HashSet documentation

If you need to keep insertion order, use LinkedHashSet as suggested in @mrblewog's comment. If you want to have the internal Set sorted, use SortedSet or TreeSet.
I also changed int[] to Integer[] so that it can be used with generics (generics do not support primitive types).


Profiling script for gathering a lot of data from an API

Here are some of the improvements to the current "synchronous" approach:

maintain an instance of the requests.Session() - this would improve performance:

  ..if you're making several requests to the same host, the underlying TCP
  connection will be reused, which can result in a significant
  performance increase

with requests.Session() as session:
    r = session.get(url + current_hash)

use the .json() method to get the JSON object directly out of a response (you would first need to adjust the "json model" to use ujson, source):

requests.models.json = ujson
# ...
block = r.json()

don't open/close files in the main loop - collect the data into memory and dump after. If the data does not fit the memory, use pagination - write to the output file(s) in chunks.
the parse_transactions_in_block() may be rewritten using str.join() and str.format():

def parse_transactions_in_block(block):
    return ''.join("{time},{index},{total}\n".format(time=transaction['time'],
                                                     index=transaction['tx_index'],
                                                     total=calc_total_input(transaction))
                   for transaction in block['tx'])

the calc_total_input() can be rewritten using sum():

def calc_total_input(transaction):
    return sum(input['value'] for input in transaction['out'])

try the PyPy interpreter - can give you a performance boost with no changes to the code (well, I doubt ujson will still work, but simplejson might be a good alternative in this case)

That said, given the information provided in the question, the bottleneck feels to still be the blocking nature of the script. See if you can switch to, for example, Scrapy web-scraping framework, or use the grequests library.


Binary Search Tree insert method (map interface)

The algorithm looks fine. Some other notes:

I would use longer variable names than r, k, e etc. Longer names would make the code more readable since readers/maintainers don't have to decode or memorize the abbreviations.

new MyBSNode<E>(null)

Consider creating a default contructor, a named factory method or an explanatory local variable for null. Currently readers have to check the MyBSNode constructor to figure out what's that null supposed to mean.
MyBSNode does not seem to have a good name. Try to find something more descriptive.
n.setElement(k, e); // only modifies e

Creating a setValue(E value) method would make the comment unnecessary and would be cleaner.
I'd consider moving isLeaf to BSPosition since it seems data envy. I guess its only task is to check that both left and right children are nulls.
treeInsert does not do any insertion, its name is a little bit misleading, it just searches the parent of the new node or a node with the same key. I'd call it according to that. (searchInsertionPoint for example.)


Destructively appending one list to another

Your temporary variable names are horrible and give a false impression of what they are doing.

ilist tmp = iempty();   // Is this really a temporary and a temporary of what.
                       // Looks like you are building a copy of il1 onto this list.

ilist clone = il1;      // This is not a clone of il1
                       // It is basically a pointer at the same head node as il1.
                       // I would have called this one il1Iter or loop1 then changed this
                       // value in the loop below thus leaving il1 pointing at the head.

ilist tmpclone = tmp;   // Same comment as for clone.

// Looks like you are copying the copy you just made onto the end of il2.
// This seems like a waste as you are doing two copies of each node.
while(tmp != NULL){
    il2 = icons_destroy(tmp->first, il2);
    tmp = tmp->rest;
}
// A deeper inspection of icons_destroy() finds that when you are
// actually making a copy of the list in reverse order by always inserting
// to the front.

// Thus copying il1 (to reverse it) and then copying it again (to put it back
// in the correct order) with il2 actually puts a copy of il1 in-front of il2.
// Not a very obvious way of implementing the append and as such I would
// suggest you find a way to re-write that so it is obvious what is happening.

// Seems correct but because of the bad naming convention it is hard to tell
// we actually need to go back and read the rest of the code to make sure this
// is correct in context.
idelete(tmpclone);
idelete(clone);


I use a string to avoid the inner loop. The problem here is the printf() inside. A 3000-row triangle redirected to /dev/null takes 50ms, but now only 4ms.
I reformatted the output. And I left dots as fillers to see what is going on.
$ ./a.out
...*...
..***..
.*****.
*******

It starts with one * in the so-called middle, and every row-iteration only sets two more bytes to * before it prints.
The complicated part is preparing the string i.e. array of chars. You can use calloc() to clear the right side, but it still takes a step to put blanks on the left side.
#include <stdio.h>
#include <string.h>

int trihi = 4;
char PIX = '*';

int main(void){

    int width = trihi * 2 - 1;
    char s[width + 1];
    memset(s, '.', width);
    s[width] = '\0';

    int mid = trihi - 1;
    s[mid] = PIX;
    printf("%s\n", s);

    for (int i = 1; i < trihi; i++) {

        s[mid - i] =
        s[mid + i] = PIX;
        printf("%s\n", s);
    }
}

This should add up. s[mid + i] runs up to 2*mid = 2*(trihi-1).
The '\0' sits at width = 2*trihi - 1 which is one higher, and is the highest legal index for s.
It is very easy to make a small mistake and not have the \0 at the correct place.
It also works with a triangle height of 1:
$ ./a.out
*

And by setting ... = --PIX; in the loop:
$ ./a.out
.....*.....
....)*)....
...()*)(...
..'()*)('..
.&'()*)('&.
%&'()*)('&%

The So-Called Middle
This is how a triangle of height 4 is laid out. Size is 8. The middle is s[3]; there are 3 spaces to the left.
01234567  --- "offset", "index"
...*...0
|  |   |
|  |   +-- s[width]  (width = 2*trihi - 1)
|  +------ s[mid]    (mid   = trihi - 1)
+--------- s[0]

You start with trihi=4, but what you need is mostly 3 and 7...the geometrical base width is also 7.

Just any Triangle
If this is enough (with original height = 3):
$ ./a.out
*
**
***

then the code gets much simpler:
#include <stdio.h>
#include <stdlib.h>

int trihi = 3;
char PIX = '*';

int main(void){

    char *s = calloc(trihi+1, 1);

    for (int i = 0; i < trihi; i++) {
        s[i] = PIX;
        printf("%s\n", s);
    }
}

I kicked everything out except the basic idea: re-using a prepared string/array. Here the calloc-zeroes are only after the PIXes. No need for a filler like space or dots via memset() anymore. But it is also not the same user experience...and the triangle is half the size.
Overiq.com has a double-loop version of a C Program to print Half Pyramid pattern using *. It takes much longer than the above (tri2.c below).
$ gcc -O2 over.c
$ time ./a.out |wc -l
3001

real    0m0.029s
user    0m0.020s
sys     0m0.014s
$ gcc -O2 tri2.c
$ time ./a.out |wc -l
3000

real    0m0.006s
user    0m0.000s
sys     0m0.011s


I don't see why you need to special case n == 0. The

def fib(....):
    for _ in range(n):
        f0, f1 = f1, f0 + f1
    return f0

seems cleaner, even though it does one extra addition.
The Fibonacci are well defined in the negative domain as well. For example, \$F_{-1}\$ can be derived from the same recurrence (\$F_1 = F_0 + F_{-1}\$), etc, so handling negative n in this particular problem is a bit trickier.
Performance wise, yes it is possible to compute the nth number in \$O(\log{n})\$ time, either by matrix exponentiation, or by exploiting the

\$F_{2n-1}=F_{n}^{2}+F_{n-1}^{2}\\F_{2n}=(F_{n-1}+F_{n+1})F_{n}\$

identities.


If LIST were a two-dimensional numpy array, you could use
LIST[i,:] to get the ith row,
LIST[:,i] to get the ith column,
numpy.diagonal(LIST, i) to get the diagonal i places above the main diagonal (where -17 < i and i < 17 in order to restrict to diagonals containing at least four cells),
and numpy.diagonal(numpy.flipud(LIST), i) to get the left diagonal i places below the main left diagonal.

Each of the four operations in the previous paragraph returns either an array or an array view.
Every set of four numbers that you wanted to look at will show up as four consecutive values in one of these arrays or array views,
so you just need to look at each product of four consecutive integers
within each array or array view.