Moving average algorithm that preserves the integral and number of points

Where you make the window length odd: w += (w % 2) ? 0 : 1; I would prefer the conditional part to be something like ((w % 2) != 0). Others will no doubt disagree with me, but I personally prefer conditionals to be boolean.
But even better, you can get rid of the conditional entirely: w |= 0x1;. Maybe this makes some kind of not-guaranteed-to-be-fully-portable assumptions? But I'd be comfortable using it.

Using the same index i in the multiple consecutive loops makes me think a little. On the one hand, it's really good how it doesn't duplicate code that calculates where the loops start and end. On the other hand, one doesn't normally expect a loop index, particularly one named i, to be used after the end of a loop. What if some future maintainer doesn't realize this, and inserts some other loop in here that uses i as its index? Possibly you could rename i to something else, but that might make your subsequent calculations harder to follow. In the end, I'd probably at least put a comment by the declaration of i warning that it is re-used through multiple loops.

I don't like something that is purely DSP to write to std::cerr. Either return a status value, or throw an exception when you encounter invalid parameters. I think a status return value is preferable, but an exception may be OK if this really is an exceptional case.

You use float to hold the intermediate averagedValue. In most cases this is fine, but depending on the nature of your data and your window size, it is possible that you'd benefit from using double for the intermediate variable.


I'm not sure I follow the code, but I would try removing the repeated calls to GetDuplicates:

foreach (var duplicate in authors.GetDuplicates())
{
    for (int j = 0; j < edge.Count; j++)
    {
        for (int k = 0; k < duplicate.Count - 1; k++)
        {
            if (edge[j] == duplicate[k])
            {
                edge[j] = duplicate[k + 1];
            }
        }
    }
}

I've also replaced the calls to ElementAt with use of the indexer, as I think it's clearer.


Given a Tic-Tac-Toe gamestate return all wins as text

Not sure about whether a solution could be more Pythonic, but I think it can be more efficient.  At present your code is iterating over each cell twice, before anything is printed.
I would suggest using a collection of possible winning strings.  You only need to iterate over the cells once and each time you encounter a 0 that row, col and if applicable, diagonal become invalid as a winning line.
After that, it's a simple matter of iterating over the strings and printing the ones that are valid.


Matchmaking system - sorting musicians by skills, genres, and location

OOP

Why have a get method, if your not going to use it (eg in get_user_by_username)?
It's not clear what the responsibility of your class is. DB suggests that it's some kind of generic wrapper around PDO (with methods such as query and get fitting into it), but then it's also the user dao? That's a bit much for one class. If you separate it into DbWrapper (query and get) and UserDAO (get_by_username and find_user) you should be on the right track.
It's not ok to just dump an exception in a class (the calling code cannot do anything to recover, you have ugly output to the enduser), and it's also not ok to just die inside a class (again, no possibility to recover for the calling class). If you can't recover in the class, just throw the exception upwards.

Misc

be consistent with your SQL: all keywords should be all uppercase (see eg where).
Why do you return false for no results? I think an empty array works just as well (and it's what is returned by PDO, so it means less code).


Setting periodicity in the week in Google Calendar

Use prop() instead of attr().
See the first point.
You're declaring var selectDay = function(idValue, element), your element argument is probably a typo? You don't need it.
See the first point.
Use switch instead of all those if. Or at least cache the $(this).val() result.
See the first point.
You don't need element.find(), you could use the context (somehow cleaner).

Overall, here is some code to give you the idea:

var selectDay = function (idValue) {
    $('select', idValue).change(function() {
        switch ($(this).val()) {
            case '0':
                $('label', idValue).hide();

                // Use prop(), not attr().
                $(this).closest('div').find('input').prop('checked', true);
                break;
        }
    });
};

Now you may notice something: this doesn't have exactly the same behavior as your code. Guess why :-)

A friend of mine says that whenever you use a switch case, you can actually use a mapping object. This might be another way to do it. The mapping object would be something like:

var mapping = {
    '0': {
        'label': 'hide',
        'checked': false
    },
    '1': {
        'label': 'hide',
        'checked': true
    }
};

And then you code accordingly to this object.


Searching for log entries in SQLite that involve a particular IP subnet

Databases are meant for efficient searching: you formulate a query to specify exactly what data you want to retrieve.  What you are doing is retrieving the entire contents of the table, to be filtered in MATLAB.  That defeats the purpose of the database — you might as well have stored the data in a CSV file.

Just write a query that looks like

SELECT *
    FROM IP_logs
    WHERE src_addr LIKE '91.198.174.%' OR dest_addr LIKE '91.198.174.%';

Depending on what your database schema looks like, you might be able to do even better.  Indexes on the relevant columns would help.  Storing IPv4 addresses as 32-bit integers would result in even faster searches.


This should be a little better. I believe joins are faster than nested selects, and that if with nested select may or may not select twice or use cached response.  I can't think of a good way of getting rid of the one nested select.  Otherwise, maybe you could write it as a stored procedure or virtual table.  (Note* any spelling mistakes of table or column names are a result of autocorrect)

SELECT lote.ordem as lote_ordem,
lote.titulo as lote_titulo,
lote.codigo as lote_codigo,
lote.codigo_leilao,
GREATEST(
    (SELECT lance
        FROM lance
        WHERE lote.codigo = lance.codigo_lote
        ORDER BY lance.data DESC
        LIMIT 0,1),
    lote.lance_minimo
) AS lance2,
youtube,
youtube,
-- lance.codigo_cadastro,
lote_album.caminho_imagem as imagem_destaque,
FROM lote
LEFT JOIN lote_album
ON lote_album.codigo_lote = lote.codigo
WHERE lote.excluido <> 1
AND lote.codigo_leilao = 42
AND lote_album.ordem = 1
ORDER BY lote.ordem ASC


Dijkstra's algorithm using priority queue running slower than without PQ

I think the problem is that you have more than one instance of a node in the priority queue at a given time.

In the relax operation:

 if (alt < dist[v.end]) {
     dist[v.end] = alt;
     prev[v.end] = alt;

     vertices.add(new Node(v.end, alt)); //this should have O(logn)
 }

You should remove the vertex before adding it or implement a indexed priority queue with a decreased key operation like this one. I'm not sure if java remove operation is \$O(ln(n))\$ thought. Like this:

if (alt < dist[v.end]) {
     dist[v.end] = alt;
     prev[v.end] = alt;
     Node newNode = new Node(v.end, alt);
     vertices.remove(newNode);
     vertices.add(newNode);
 }

Note: You need to override equals for the node.

With the indexed priority queue you would create and add the new node if the queue doesn't contains it, or do decreased key otherwise.

If you do it like this you will lazily add each vertex to the queue so you don't need to add them all at the beginning here:

   dist[source] = 0;
   for (int i = 0; i < adj.length; i++) {
        if (i != source) {
            dist[i] = Integer.MAX_VALUE;
            prev[i] = Integer.MAX_VALUE;
        }

        vertices.add(new Node(i, dist[i])); // <--here
    }

Also you can remove the inner if in the loop like this:

   for (int i = 0; i < adj.length; i++) {
       dist[i] = Integer.MAX_VALUE;
       prev[i] = Integer.MAX_VALUE;
    }
    dist[source] = 0;
    vertices.add(new Node(source, 0));


Querying a data structure that contains various triples

Your code would be helped by splitting parts of it out into functions.
Your continue statement does nothing
Rather then having a special case for the first time through, initialize bindings to [{}] for the same effect.

My version:

def clause_to_query(clause):
    return tuple(None if term.startswith('?') else term for term in clause)

def compatible_bindings(clause, triples):
     for triple in triples:
        yield { clause_term : fact_term
            for clause_term, fact_term in zip(clause, row) if clause_term.startswith('?')
        }

def merge_bindings(left, right):
    shared_keys = set(left.keys()).intersection(right.keys)

    if all(left[key] == right[key] for key in shared_keys):
        bindings = left.copy()
        bindings.update(right)
        return bindings
    else:
        return None # indicates that a binding cannot be merged

def merge_binding_lists(bindings_left, bindings_right):
    new_bindings = []
    for left, right in itertools.product(bindings_left, bindings_right):
        merged_binding = merge_bindings(left, right)
        if merged_binding is not None:
            new_bindings.append( merged_binding )

    return new_bindings

def query(clauses):
    bindings = [{}]
    for clause in clauses:
        query = clause_to_query(clause)
        new_bindings = compatible_bindings(clause, triples(query))
        bindings = merge_binding_lists(bindings, new_bindings)

    return bindings


An option would be to create two IEqualityComparers; one for DocumentType and one for DocumentTypeVersion. You could then easily call Intersect() and get the correct ones.

public class DocumentTypeIdComparer : IEqualityComparer<DocumentType>
{
    public bool Equals(DocumentType docType1, DocumentType docType2)
    {
        return !(docType1 == null || docType2 == null) && docType1.Id == docType2.Id;
    }
}

public class DocumentTypeVersionComparer : IEqualityComparer<DocumentTypeVersion>
{
    public bool Equals(DocumentTypeVersion docTypeVersion1, DocumentTypeVersion docTypeVersion2)
    {
        return !(docTypeVersion1 == null || docTypeVersion2 == null) && Object.Equals(docTypeVersion1, docTypeVersion2);
    }
}

You will then be able to reduce your code to this;

var equalDocumentsById = documentTypes.Intersect(importDocumentTypes, new DocumentTypeIdComparer());
var equalVersions = documentTypes.Versions.Intersect(importDocumentTypes.Versions, new DocumentTypeVersionComparer());
var equalDocuments = equalDocumentsById.Where(doc => doc.Versions.Intersect(equalVersions, new DocumentTypeVersionComparer()).Any());

And then process equalDocuments as you please. If you want the documents which are not equal, simply switch .Count > 0 with .Count == 0.


HarckerRank 2D Arrays Hourglass challenge

One thing I like about this code is the clear division of role.

You have a section for identifying and extracting the hourglasses. Then you sum the individual hourglasses. Then you find the maximum.

There's a quote by Computer Scientist Tony Hoare that "There are two ways to write code: write code so simple there are obviously no bugs in it, or write code so complex that there are no obvious bugs in it." The clear structure helps make this into the first category. This is the sort of code that I'd like to see, for example, in a reference implementation or test case.

On the other hand, that simplicity comes at a cost. Your implementation requires allocating a bunch of extra memory to hold all the temporary hourglasses, and a bit more still to hold all the sums.

In principle, you could add them up as soon as you identify the elements in an hourglass, and then only store hourglasses_sums instead of my_hourglasses. Furthermore, instead of storing a list of all the sums you have seen, you could just keep track of the highest score you have seen thus far. You'd then have something like this:

max_hourglass_score = -63  # Minimum possible score = -9 * 7
for i in range(0,4):
    for j in range(0,4):
        hourglass = list()
        hourglass += arr[i][j:j+3]
        hourglass.append(arr[i+1][j+1])
        hourglass += arr[i+2][j:j+3]
        hourglass_sum = sum(hourglass)
        max_hourglass_score = max(max_hourglass_score, hourglass_sum)

print(max_hourglass_score)

Of course, the same pattern could be applied to do the sum as you go rather than picking it into an intermediate hourglass list.

max_hourglass_score = -63  # Minimum possible score
for i in range(0,4):
    for j in range(0,4):
        hourglass_sum = 0
        hourglass_sum += sum(arr[i][j:j+3])
        hourglass_sum += arr[i+1][j+1]
        hourglass_sum += sum(arr[i+2][j:j+3])
        max_hourglass_score = max(max_hourglass_score, hourglass_sum)

print(max_hourglass_score)

This only allocates a few primitive variables rather than all the extra arrays you had before.

There are in fact still cleverer algorithms which require fewer arithmetic operations. The key idea is easier to explain with squares rather than hourglasses.
If you look at the square in the top left corner and compare it with the square one place across, many of the entries are the same. Specifically, of the nine entries in a square, six are overlapped. The potential for speeding up the program come from not looking that the overlap squares any more, but starting from the last sum, taking away the values that are no longer in it, and adding the values that are new to it.

That algorithm, however clever, is complicated. It's hard to get right, and even hard to see whether it is right. It's therefore a judgement call how much you value making your code run as fast as possible, and how much you prefer writing it in a way that is easy to understand. There isn't a best answer. It depends on what you want to use it for. If this were running in real time on video frames and were (somewhat appropriately) the biggest bottleneck in your program, then you'd probably prefer faster. If it's trundling along on a small grid, you would want clear code.

A couple of other general comments:

Variable naming is important. Although "hourglass" would usually seem like a fairly specific and helpful word to identify what's going on, when three of your main variables are built around the same word one should wonder whether it actually gets confusing. (Also, "my_" is usually unnecessary.)
I appreciate the use of Python comprehensions. If you only want to use it once, a generator comprehension is often better. In terms of how it's written, just swap the square brackets around sum(item) for item in my_hourglasses for parentheses. In terms of what it does, it avoids actually doing the calculation until you need it, giving space and sometimes time savings.
Beware of magic numbers. I realise that 4 is the width of the big grid, minus 2, which you need because the width of the hourglass is 3 and the overlap is 1. But that's not immediately obvious, so it's worth spelling out what 4 means.


Overall, I can't quite tell how this is supposed to be structured.  It looks like it all belongs to a single function which has been omitted.  In either case, different things are happening here, so they should be separated into additional functions as such.

For instance, each section you've already preceded with a comment should have a function.  They may all do card operations, but their purposes still differ.  If someone needed to find a certain area to examine, then that would take more time to find, even with comments.
Since you're already using C++11, you can change all of your vector::iterators to auto, which will help keep your code simpler.

Better yet, you can just use a range-based for loop:

for (auto& it : cards) {}

This isn't very idiomatic:

(*it)[0]

Since this vector contains std::strings, you can use std::string::front() to acquire the first character from an element:

it.front();

Note: the . operator here may only work if you follow my second suggestion.  Otherwise, you may need to use the -> operator.
This is really hard to read and maintain:

if(cards[0][1] == cards[1][1] && cards[1][1] == cards[2][1] && cards[2][1] == cards[3][1] && cards[3][1] == cards[4][1])rank = 5;

I had to scroll all the way to the right to see that it does indeed perform an action.  While it's okay to have if statements on a single line, doing so with a long line is a bad idea.  In this case, put the rank = 5; on a separate line with curly braces, just like with your other code.
This is also hard to read:

if(vals[0] == vals[1]+1 && vals[1] == vals[2]+1 && vals[2] == vals[3]+1 && vals[3] == vals[4]+1)

With this many conditions, you should at least list them vertically in some way so that each one is clearly visible.

(This advice also applies to the previous bulletpoint.)

Moreover, do keep in mind that long vertical sections aren't as bad as long horizontal sections.  If, say, someone were to read this on a terminal with line-wrapping, then your code's readability for them would decrease even more.


Your code is generally clean, you have accurate comments & variable naming is mostly consistent.

$raw_bytes and $byteArray use two different types of naming. It's best if you choose one style, and stick with it.

With return ($encoded == "AQ==") and return $byteArray[0] == "00000001", you don't have a consistent use of brackets, it's best to stick to one.

Onto code, in getNumber(), you initialise an array, build to it, and then proceed to implode it.
However, in getString(), you initialise a string, build to it, and then return it.

In getNumber(), it'd be better if you just built to the string instead of an array.

$byteArray = array();
foreach(str_split($decoded) as $byte)
{
    $byteArray[] = sprintf("%08b", ord($byte));
}
$raw_bytes = implode(' ', $byteArray);
return bindec($raw_bytes);

into:

$rawBytes = "";
foreach(str_split($decoded) as $byte)
{
    $rawBytes .= ' ' . sprintf("%08b", ord($byte));
}
return bindec($rawBytes);

Also, zDecodeBool() (could have a better name), runs nearly the same code as getString(), you could consider a compromise between the two functions.

Other than that, your code looks nice and clean.


Well done on getting a query that works: that is the hardest part!

I do agree that you have overcomplicated this query: I had to spend quite a long time playing around with it to figure out what it was intended to do.

I also suspect it might not be the best way to achieve what you want. So well done also for seeking feedback here - I'm sorry mine is coming quite late. I'm going to dump a tonne of feedback in this answer: it might seem fairly blunt but don't take it personally, we all learn from experience. :)

I struggled to decide what order to present my feedback in, so it might not be in the most logical order for you. I apologise if so.

How to tackle complex queries

There are two ways one can go about a complex query:

Dive in and try to get something that works by examination of your results, then refine it subsequently, or
Spend time up-front designing the query without actually writing it, and go straight to a simpler (perhaps simplest) solution. Usually this means you can "prove" the query to be correct by reasoning about the design logic, without having to examine the results so much.

I'm a big fan of (2) and believe that it is generally viewed as the "best" option across all schools of programming - but of course it's not always practical.

It seems to me that the biggest problem with this query is that you took approach (1). The query screams "unclear thinking" to me; it is messy and hard to read, with quite a lot of unnecessary bits. Learning to design code well before you write it is a skill of its own, but one well worth practising if you are able to.

High-level algorithm choice

Without any sample data and clear information on the source table structures, it is hard for me to critique your overall approach.

It sounds like what you have is a fairly typical scenario, that the data warehousing world at least refers to as "semi-additive facts". That is, data that are numeric and can in principle be added to each other, but for which adding them only makes sense in certain limited scenarios. Semi-additive facts aren't that uncommon and you might find that a useful search term if you want to read more about dealing with them.

Certainly, a common approach to semi-additive facts is "two pass" cubing (or grouping/aggregation), which is essentially all this query is doing (but it took me far too long to understand that). So your general approach might be just fine.

However I have a niggling feeling that you don't need to bother with the "count the number of records and if it's over 30, use that record" bit. I can't say for sure without seeing some of your data but it feels like you could just DISTINCT your core data set to reduce it to one row per meaningful set of measurements, and then do only one GROUPing operation.

I suspect that if you work on simplifying and clarifying your query, you will be able to see for yourself if this second grouping is necessary or not. When a query is as simple as it can be, wrong logic is usually easy to spot.

Comments, magic numbers and code that won't run

I'm also totally unclear where the magic number 30 comes into things. If you get a measurement per minute, which changes once per hour, I'd have expected the number 60 to feature, not 30.

Your code would benefit from clear comments explaining why constant numbers like this are what they are - more generally, your code would benefit from any comments at all.

The Top 120 bit falls into the same category. Is that 120 days (~4 months)? I'm not sure it is, because of the mysterious @date variable hidden uncommented in your code.

This isn't declared anywhere so as far as I'm concerned, your code is broken and does not run. I presume you forgot to include the declaration, or this code exists within a stored procedure - but you haven't mentioned. If a single date is being passed in, I can't understand how your query will return more than one day of results, so the Top 120 doesn't make sense. Neither does the final ORDER BY DAY ASC - it seems to me that a result set will only ever contain one value of DAY.

CTEs vs sub-queries and incremental problem solving

This bit is both SQL-specific stylistic advice and very general programming advice.

Break any programming problem down into a series of steps, then solve those steps one-by-one. The clearer it is to follow in your code which steps are which, and what order they happen in, the better your code will be.

T-SQL provides a really handy construct for step-by-step problem solving, the common table expression (CTE); you use one of them, named A. The big problem is that you only use one of them. Apart from A you use a variety of subqueries (SELECT query results enclosed in brackets, and treated like tables in their own right).

A bit of history: in the international definition of the SQL language, subqueries have been around a long time, and CTEs are a more recent addition. CTEs were introduced mainly as an improvement on subqueries: they are clearer, more flexible, and reusable (within one query).

In the context of "production" SQL code (code to be written once and used again and again - as against ad-hoc one-off analysis) I do not personally believe there is any situation in which it is better to use a subquery. CTEs are not always the best choice for performance, but in that case other constructs such as temporary tables and table variables are the better choice.

Conclusion: rework your query to use a linear series of CTEs, each of which builds on the one before towards the end result.

Use as few constructs / steps as necessary

Once you do a CTE-focussed overhaul of your code, you will see that multiple steps can be combined into one to simplify (rather than complicate) the overall query.

You have used far more steps than you need to but it's very hard to identify that currently, because you have to skip around the query to follow it.

In a general sense, you need to know/remember that what SQL does best is join tables together. Unless there's a good reason not to (for example to do with cardinality, the number of records in the relationship), do all your joins in one query set: this gives SQL Server more options for optimising how it does them.

You also need to know that GROUP BY clauses work fine in the same query as multiple joins. There's no need to do joins in one set (CTE or subquery) then group the results in a separate set.

Style and layout

Consistency is crucial in any programming task I've come across. Much of the following relates to consistency.

I can't see any patterns of when you start new lines, why/how much you indent your code, where you put commas, and so on. This reduces readability a lot. Choose a style then follow it consistently.
In general, use more indentation and spacing, not less. Bytes are not precious in this day and age. Judicious use of blank lines and reasonably deep indentation make code much easier on the eye.
Capitalise consistently. This applies to table and column names wherever you have control over them (see below for more on that), and to function names and SQL keywords. If you are capitalising keywords like SELECT, Top should also be capitalised.
Unnecessary brackets () in expressions are distracting. Instead of AND    ([ DAY ] = @date), just AND   [ DAY ] = @date.
Your code doesn't convince me that you understand the basic rules of arithmetic as they apply to SQL: for example, that sum(column*100) is the same as sum(column)*100, or that sum(column1) - sum(column2) is the same as sum(column1-column2). If you aren't rock solid on these (which is OK!) I recommend brushing up - it will really help over time. If you are, use one form or the other consistently; it will give any reader of the code additional trust in your ability.
In a production-quality SQL query, never list columns that don't need to be there. It is distracting and can (sometimes) affect performance. For example [ RESET Counter ] is never used directly (only within a COUNT()) so shouldn't be listed. You also generate a ROW_NUMBER() but never refer to or show it, so it shouldn't be there - and removing it reduces the number of sets/steps you need overall.
The SQL * is a useful shorthand when developing queries but it has no place in a final query that will be used in production. It is far better to list explicitly the columns you want to see. This makes the query more robust against changes to underlying table definitions.
Where you list the same/similar set of columns in multiple places (for example in a SELECT then again in GROUP BY, or in a CTE then again in the main SELECT), list them in the same order each time. It's much easier to see if columns have been omitted, deliberately or accidentally.

Object naming

You should qualify table names with which schema they belong to. This makes your code more robust if multiple schemas are used in the future.
You need to familiarise yourself with the rules of regular database identifiers in SQL Server. As you're clearly aware, non-regular identifiers can be used if enclosed in square brackets, but this is bad practice. Wherever possible use regular identifiers, which means no spaces. Use underscores or CamelCase instead. This (and all subsequent advice in this section) applies to aliases as well as actual object names.
While # and $ are valid in general, you shouldn't be using # at the start of anything (e.g. a column alias) because it denotes a temporary table. I would recommend avoiding # and $ altogether if possible: there really isn't any need for them that I'm aware of.
Your underlying table names Main $ and KPI $ (I think that's what they are?) are not enclosed in square brackets: I'm surprised this hasn't caused an error.
You should also be avoiding using SQL Server reserved words for object names. That link is a good one to familiarise yourself with.
If you cannot control the presence of spaces, $ signs, reserved words etc in your underlying table/column names, consider creating some simple views that mask this by renaming all columns to SQL-compliant values that won't need square brackets. This would make your query (and all other queries on the same dataset) much, much more readable.
Always alias every table in a multi-table query and use the aliases consistently to qualify every column reference. This is clearer than having to type out the full table name to qualify columns. By qualifying every column with its table name, it's really obvious which columns come from which tables (without having to refer to an ERD or specification).
Use sensible, meaningful aliases. A is almost always a terrible name for a column, table, CTE or anything else, because it doesn't tell you anything about what it does or what it is for. I always prefix CTE names with cte so I know that's what they are when I refer to them later.
CTE names can afford to be reasonably long (same kind of length as tables) to describe their contents.
Table aliases are best short - I stick to 2 or 3 characters. One is usually too short to be clear. I'd alias Main as MN and KPI as KPI (but still alias it so it's clear!).

A few points related specifically to spacing and choice of column names and aliases:

If at all possible avoid the fancy spaced column aliases in your final results (and throughout).  I think B100_Pulse_Last_Hour is as clear as [ B100 Pulse LAST HOUR ] in a result set - give your data users some credit.
Or, it's possible you're using the wrong technology here - if you really need "pretty" column names perhaps you should be using SSRS or some other technology downstream of the query?
If you really, really need pretty column names at the end of this query, consider the Alias = Expression syntax rather than Expression AS Alias. This makes it easier to align your aliases at the start of the query and let the differing-length expressions run off to the right.

For example (if you've not seen it before)

select [ Building 100 Gal Discharged ] = 100*SUM(B100_Pulse_LAST_HOUR)
from    table

Potential performance / behaviour effects

If I've understood the purpose of your @date variable, you should use it to limit the number of records as early as possible in the query, not as late as possible. Cutting out unnecessary rows early on will speed up later parts of the query.
In CTE A: the DISTINCT keyword is useless because you're also grouping by all the non-aggregate columns.
TOP (100) PERCENT is a useless construct: that means all rows, which is the default behaviour if you remove that bit altogether.
Where you use CONVERT to get [ DAY ]: format 101 outputs 10-character results (mm/dd/yyyy) but you use a CHAR(12) which will cause trailing spaces.
If you're on 2008+ you can use the date data type instead: CAST(Time as date), confusing though that reads, will do essentially the same thing as your CONVERT, but keep it in actual date format.
Although I've said above your ROW_NUMBER() is useless, you should understand that if you do need it, it is pointless to ORDER BY the same expression you PARTITION BY. The partition means that the numbering will restart from 1 for every distinct value of Records. Within a partition, all rows will have the same value of Records, so you cannot useful order on that column. This means the ordering is essentially random - not a good thing.
Instead of getting COUNT([ RESET Counter ]) in one row set and filtering on it in a later row set using WHERE, you can filter directly on the result of a COUNT() function using the HAVING clause. It works the same as WHERE but is intended for working on aggregate functions like COUNT(), SUM() etc. You put it after the GROUP BY clause and before an ORDER BY if you have one. Again, this reduces the number of sets you need.


Hover effects for red, blue, and green boxes

A little shorter:

$(document).ready(function() {
    var red = $(".small-box");
    var blue = $(".small-box2");
    var green = $(".large-box");
    var boxes = red.add(blue).add(green);

    boxes.mouseleave(function() {
        boxes.removeClass("selected-highlight selected-highlight2 selected-highlight3");
    });

    red.mouseenter(
        function () {
            red.addClass("selected-highlight");
            blue.addClass("selected-highlight2");
            green.addClass("selected-highlight3");
        }
    );
    blue.mouseenter(
        function () {
            red.addClass("selected-highlight3");
            blue.addClass("selected-highlight");
            green.addClass("selected-highlight2");
        }
    );
    green.mouseenter(
        function () {
            red.addClass("selected-highlight2");
            blue.addClass("selected-highlight3");
            green.addClass("selected-highlight");
        }
    );
});


Displaying "C++" in ASCII art with user inputting an integer

Graphical representation

From your 'number << number << number' thing it is not immediately obvious what is being drawn, and how to fix it in a specific way when needed.

By using the template where you just replace placeholder characters with what you need, you get more WYSIWYG-like result.

Input validation

Your code assumes that user inputs appropriate value. What if user inputs 1234? (You can get more fancy and guard against inputting non-numbers too)

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::to_string;

const auto ASCII_template = string("\
SSSSSSSSSSS\n\
SSS               SS           SS\n\
SSS               SS           SS\n\
SSS           SSSSSSSSSS   SSSSSSSSSS\n\
SSS               SS           SS\n\
SSS               SS           SS\n\
SSSSSSSSSSS");

string replace_all(const string& base_string, const string& search, const string& replace) {
  string s = string(base_string);
  size_t pos = s.find(search);
  size_t len = replace.size();
  while ( pos != string::npos ) {
     s.replace( pos, len, replace );
     pos = s.find(search);
  }
  return s;
}

unsigned int get_user_digit() {
  unsigned int result;
  do {
    cout << "Please enter a single digit:" << endl;
    cin >> result;
  } while (result >= 10);
  return result;
}

int main() {
  cout << replace_all(ASCII_template, string("S"), to_string(get_user_digit())) << endl;
  return 0;
}

You can try it online here.

I don't remember C++ that much, but something along those lines would work. Depending on how much of С++11 you can use, std::regex_replace would simplify replace_all function. If you can not use std::string, it wouldn't change that much either, although you'd have to use some C-like workaround.


Breadth-first search(BFS) Implementation in Python 3

There are a few PEP8 issues:

In Python3, class definitions have been overhauled a bit, and one can simply do class Node: instead of class Node(object):.
The spacing is a bit all over the place: there should be two blank lines between class definitions, and I find the spacing within def bfs(self, start_node) difficult.
The naming convention is to be snake_cased.

To address this type of issues, have a look at flake8 or black

Node.visited is problematic.
First, if the node is in several trees, you may not visit it if it's already been  visited in another tree, or even in the same tree when doing a second search.

The fact that you have visited a node is part of the algorithm, and not so much a property of a Node.

With a few tweaks you can rely on queue only, or have a second list of visited:

visited = []
for node in current_node.adjacency_list:
   if not node in visited:
        visited.append(node)

The comment #BFS -> queue is not very telling.

Lastly, this is iterating through the tree, and not doing actual search. Where's the exit condition? What's returned? What should I get when searching for node4 from node1? node4 from node3? node3 from node2?

It's not quite done...


Solution to Project Euler Problem #37 in C++: Truncatable Primes

Warnings

It is usually a good idea to compile your code with all warnings enabled to see if anything is wrong. In your case, nothing really worrying but we may as well fix it.

Press ENTER or type command to continue
euler37.cpp: In function ‘std::vector<long long int> primesUpto(long long int)’:
euler37.cpp:16:26: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
     for (size_t i = 0; i < sqrtLimit; ++i)
                          ^
euler37.cpp:20:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
             for (size_t j = (2 * i); j < limit; j += i)
                                        ^
euler37.cpp: In function ‘bool isTruncPrime(long long int, const std::vector<long long int>&)’:
euler37.cpp:39:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
     for (int i = 1; i < numberString.size(); ++i)

You just need to use unsigned integers.

Algorithm

You could use a different approach to solve this problem. Instead of trying to find an efficient way to check if a number is a truncatable prime, you could try to find a way to generate them.
You could use the fact that the all right-truncable-primes of size n can be built easily from the list of right-truncable-primes of size n-1. The same logic applies to left-truncable-primes.

Here is a code example based on Toby Speight's code:

template<std::size_t N>
constexpr bool isLeftTruncPrime(std::size_t n, const std::array<bool,N>& primes)
{
    for (std::size_t x = 10;  x < n;  x*= 10)
        if (!primes[n%x]) return false;
    return true;
}

template<std::size_t N>
constexpr bool isRightTruncPrime(std::size_t n, const std::array<bool,N>& primes)
{
    for (;  n;  n/=10)
        if (!primes[n]) return false;
    return true;
}

template<std::size_t N>
constexpr bool isTruncPrime(std::size_t n, const std::array<bool,N>& primes)
{
    return isRightTruncPrime(n, primes) && isLeftTruncPrime(n, primes);
}

#include <iostream>
int main()
{
    const auto limit = 1'000'000;
    static const auto primes = primesUpto<limit>();
    auto expected_sum = 748317ull;

    if (1)
    {
        auto sum = 0ull;
        // Start at 11, because single-digit numbers aren't truncatable
        // Advance by 2, because even numbers are non-prime (except 2, but 2<11)
        for (std::size_t n = 11;  n < primes.size();  n += 2) {
            if (isTruncPrime(n, primes))
                sum += n;
        }

        std::cout << sum << "\n";
        std::cout << (sum == expected_sum) << "\n";
    }

    if (0)
    {
        auto sum = 0ull;
        std::vector<int> truncprimes;
        truncprimes.push_back(2);
        truncprimes.push_back(3);
        truncprimes.push_back(5);
        truncprimes.push_back(7);

        while (!truncprimes.empty())
        {
            std::vector<int> truncprimes2;
            for (auto tp: truncprimes)
            {
                auto tens = tp*10;
                for (size_t d = 1; d < 10; d+=2)
                {
                    auto n = tens + d;
                    if (n < limit && primes[n])
                    {
                        truncprimes2.push_back(n);
                        if (isLeftTruncPrime(n, primes) /*&& n > 10 */)
                            sum += n;
                    }
                }
            }
            truncprimes = truncprimes2;
        }

        std::cout << sum << "\n";
        std::cout << (sum == expected_sum) << "\n";
    }
}

Then, because of the small amount of prime check we perform, pre-computing a sieve is not worth the pain. Thus, you don't even need to assume a maximum value. You don't even need to assume there will be 11 numbers found.

The new code is way faster than the original code:

bool isPrime(std::size_t num)
{
    if(num <= 1) return false; // <- 1 is not prime
    for (std::size_t i = 2; i * i <= num; i++)
        if (num % i == 0) return false;
    return true;
}

bool isLeftTruncPrime(std::size_t n)
{
    for (std::size_t x = 10; x < n; x*= 10)
        if (!isPrime(n%x)) return false;
    return true;
}

#include <iostream>
int main()
{
    auto expected_sum = 748317ull;
    if (1)
    {
        auto sum = 0ull;
        std::vector<int> truncprimes;
        truncprimes.push_back(2);
        truncprimes.push_back(3);
        truncprimes.push_back(5);
        truncprimes.push_back(7);

        while (!truncprimes.empty())
        {
            std::cout << truncprimes.size() << "\n";
            std::vector<int> truncprimes2;
            for (auto tp: truncprimes)
            {
                auto tens = tp*10;
                for (size_t d = 1; d < 10; d+=2)
                {
                    auto n = tens + d;
                    if (isPrime(n))
                    {
                        truncprimes2.push_back(n);
                        if (isLeftTruncPrime(n))
                            sum += n;
                    }
                }
            }
            truncprimes = truncprimes2;
        }

        std::cout << sum << "\n";
        std::cout << (sum == expected_sum) << "\n";
    }
}

Conclusion

I really like this problem and this solution because it shows that going straight into the Eratosthene sieve is not always the perfect solution.


To start, I have some general tips. Run your code through rustfmt to get consistent formatting and make code easier to read. Run your code through clippy to get tips on common mistakes (clippy had nothing to say about your code, nice!)

One overall thing I'd suggest is to not be afraid to use a custom type in a case like this. Instead of returning a Result<(String, String), String> where the Err has multiple meanings based on value, just go ahead and make an Enum for your commands. I'll show you this in my final example, along with merging the two command sections (which the exercise is kinda fuzzy on whether it cares which way you do it).

Onto specific things:

You can get an iterator over lines of stdin by .lock().lines(), which can make this simpler, but that's a matter of preference over using read_line. If you are going to use read_line, you might as well reuse your input buffer, since that's the whole point of it taking a buffer as a parameter instead of just returning a String. That way you aren't reallocating each time.

let mut stdin = io::stdin()
let mut input = String::new();
loop {
    input.clear();
    stdin.read_line(&mut input).unwrap();
    // ...
}

dissect_input should take a &str instead of a String, since you only need to view it.

Down in the listing part, you do &command.trim().to_string(), which is unneeded in a few ways. .to_string() takes you from a &str to a String, and then the & brings you right back to a &str, so you could just do command.trim(). Also, you can just bind in the match you already have, like dept => employees.get(dept)

Overall, this is a really good first attempt! It can be hard to first wrap your head around the things that make rust different, like lifetimes and slices, but just getting things working is a great step.

Here's how I might choose to do this exercise.

use std::collections::HashMap;
use std::io;

// required trait for .lines()
use std::io::BufRead;

fn main() {
    let mut employees: HashMap<String, Vec<String>> = HashMap::new();
    let stdin = io::stdin();
    println!("Type 'Add <name> to <department>' to add an employee");
    println!("Type 'List <department>' to list the employees of a department");
    println!("Type 'All' to list all employees by department");
    println!("Type 'Quit' to quit");
    for line in stdin.lock().lines() {
        let input = line.expect("error: unable to read user input");
        match Command::from_input(&input) {
            // or_default is just a convenience, does the same as or_insert_with(Vec::default)
            Some(Command::Add { dept, name }) => employees.entry(dept).or_default().push(name),
            Some(Command::List(dept)) => match employees.get(&dept) {
                Some(names) => {
                    for name in names {
                        println!("{}: {}", dept, name);
                    }
                }
                None => println!("I don't recognize that department!"),
            },
            Some(Command::All) => {
                for (dept, names) in &employees {
                    let mut names = names.clone();
                    names.sort();
                    for name in names {
                        println!("{}: {}", dept, name);
                    }
                }
            }
            Some(Command::Quit) => break,
            // consider using eprintln, which prints to stderr
            None => println!("Input error!"),
        }
    }
    println!("Have a nice day!");
}

enum Command {
    // Using named fields instead of Add(String, String) because dept and name
    // are the same type and could get mixed up.
    Add { dept: String, name: String },
    List(String),
    All,
    Quit,
}

impl Command {
    fn from_input(s: &str) -> Option<Self> {
        let words: Vec<&str> = s.trim().split_whitespace().collect();
        // "Slice destructuring / slice pattern matching" for more info
        match words.as_slice() {
            ["All"] => Some(Command::All),
            ["Quit"] => Some(Command::Quit),
            ["List", dept] => Some(Command::List(dept.to_string())),
            ["Add", name, "to", dept] => Some(Command::Add {
                dept: dept.to_string(),
                name: name.to_string(),
            }),
            _ => None,
        }
    }
}


Generic sequence splitter in Common Lisp

It looks okay for a recursion exercise, but it's naive code. Not usable in 'production'.

it conses like mad. It creates a lot of intermediate garbage. Splitting a string involves making lots of smaller strings.
for lists it is not efficient, too
CONCATENATE in loops or recursive functions is a code smell
the recursive implementation with the subroutine is good style in a functional language, but makes it hard to debug in the real world. For example, how do you TRACE the internal function?
Common Lisp does not guarantee tail call optimization (TCO). Individual implementations do support it. Still, for general portable code it might be preferable to code loop.


Properly overriding GetHashCode()

I remember when first learning how to properly override and use GetHashCode(), that there was a rule that stated The integer returned by GetHashCode() should never change. You're violating this rule because Days is not a readonly property.

Bad practices and unnecessary code

Take a look at this snippet:

public int CompareTo(object obj)
{
    if (obj == null)
    {
        throw new ArgumentNullException();
    }
    if (obj is DateOnly)
    {
        DateOnly other = (DateOnly) obj;
        if (other == null)
        {
            throw new ArgumentNullException();
        }
        return (this.Days).CompareTo(other.Days);
    }
    else
    {
        throw new ArgumentNullException();
    }
}

There are 2 problems in this method.

First - you're using the is operator combined with a direct cast, instead of using the as operator.

Second - you have a redundant if statement that will never be triggered - if (other == null), if the cast (DateOnly other = (DateOnly) obj;) fails it will crash your program, it wont return null.

And lastly you don't really need an else statement there as there is flow branching involved if you trigger the if statement you will eventually reach the return statement which will break out of the method, thus not even continuing down your code, making the else redundant.

This is how I would write this method:

public int CompareTo(object obj)
{
    if (obj == null)
    {
        throw new ArgumentNullException();
    }
    var other = obj as DateOnly;
    if (other != null)
    {
        return (this.Days).CompareTo(other.Days);
    }
    throw new ArgumentNullException();
}

In GetDayDiff(DateOnly Date) you perform 2 casts when only 1 is necessary to operate with the proper type:

long getDayDiff = (long) this.Days - (long) Date.Days;

You can just do:

long getDayDiff = this.Days - (long) Date.Days;

I'm not sure why you inherit from object, this is unnecessary, as every type in C# inherits from that class whether it will be explicitly stated changes nothing, it's just few extra letters.

Shortening the code

You can use interpolated strings instead of String.Format():

  return string.Format("{0}/{1}/{2}", Year, Month, Day);

As interpolated string:

return $"{Year}/{Month}/{Day}";

Ternary operator:

You can make use of the ternary operator here:

if (IsLeap(year))
    return 366;
else
    return 365;

Like this:

return (uint) (IsLeap(year) ? 366 : 365);

Overall design

Few concerns here:

I would just use DateTime as a backing field and utilise some of the already written methods there (I'm sure this was a design pattern but I cant think of the name right now, maybe Decorator?).
You lack range checks and overall validation of your public methods.
You're inconsistent with where you use uint and int, if you've decided that it would be good to use uint because x, y, z, why are you not using that everywhere? This will also partially solve point 2.


Formating

Correct indentation and spaces make the code a lot easier to read. Just paste your code in any decent IDE and it should manage this for you automatically.

Spaces before curly brackets
Spaces before and after equals sign
Indentation: closing brackets should be on the same level as the beginning of the opening statement
Indentation: Elements on the same level should be indented the same amount

Variable names

a, b, c, x, sc, ob1, those are all bad variable names. The bigger the scope of the variable, the more important it gets that it has a good name. So while sc for scanner is probably still alright, a, b, and c are definitely not.
shiftNo and shiftDir should better be named shiftAmount and shiftDirection. Or, to make them more reusable: getInputString and getInputInteger.
isValue sounds confusing. Maybe recievedInput or something like it. And then, don't do this: while (recievedInput == false), but this: while (!recievedInput)

Comments

Your code is missing comments. If it is self-documenting code this might be alright. But in this case: What are a, b, and c? Does shiftDir shift something? (Maybe a directory?) No, it gets input. The method name and/or the comment should make this clear.

Class Structure

see the answer of Puneet_Techie

In addition to that, you might also want to extract the actual shifting to their own methods. It makes the code cleaner, and it also makes it easier to handle corner cases and to write unit tests.

Corner Cases / Input validation

What if I want to shift 3 by 100? Is the output still correct? Or if I want to shift -4 by 5? Or if I want to shift 3 by -4?

Make sure that you only allow input that you actually want. And that the result is always what you expect it to be.


Determine if a word can be constructed from list of subsets

Your getPermutations() fails to generate all permutations.  Consider…

public static void main(String[] args) {
    List<String> list = Arrays.asList(args);
    for (String s : getPermutations(list)) {
        System.out.println(s);
    }
}

If you run java StringFromSubSets 0 1 2 3 | sort, the result is:

0123
0132
0312
1023
1203
1230
2130
2301
2310
3012
3021
3201

There should be 4! = 24 permutations, but you have produced only 12.  For example, where is 0321?  In other words,

public static void main(String[] args) {
    // Simpler initialization than the original
    List<String> listOfString = Arrays.asList(new String[] {
        "sachin", "tendulkar", "rahul", "dravid"
    });
    System.out.println("Expected true, Actual " +
        stringGotFromSubSets(listOfString, "drahultendulkars"));
}

… prints Expected true, Actual false.


Well, it's unavoidably quite complex to use, you need to provide 3 arguments to describe the array (start, size, element_size) and a function accepting a single element as a void*-argument:
Writing the loop manually is far simpler.

To top it of, you cannot pass any context to your callback, meaning it can only work on global state. That's all kinds of unfortunate.

Now, let's look at your implementation:
You are far too cast-happy.

The casts to int are wrong, SIZE_MAX can be bigger than INT_MAX. Anyway they are superfluous because yes you can use a size_t for pointer-arithmetic.
The cast to void* is superfluous, it would be implicitly converted.

Incorporating that all gives you:

#include <stddef.h>
void foreach_array(
    void* array,
    size_t size,
    size_t bytes_per_element,
    void (*callback)(void* context, void* element),
    void* context
) {
    for(char* iter = array; iter < (char*)array + size; iter += bytes_per_element)
        callback(context, iter);
}


Convert number from base-10 number system to any number system

I believe the 1st approach is good enough since it personally more readable.

Little suggestions

I'd prefer to store the whole alphabet in the symbols string, instead of only letters. This could simplify the logic.
You can calculate the resulting length of the output string and avoid string insertions.

Summarizing:

public static string ConvertNumber(BigInteger num, int baseNum)
{
    const string symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    if (baseNum < 2 || symbols.Length < baseNum)
    {
        throw new ArgumentOutOfRangeException(nameof(baseNum));
    }

    if (num < 0)
    {
        throw new ArgumentOutOfRangeException(nameof(num));
    }

    var resultLength = 1 + Math.Max((int)BigInteger.Log(num, baseNum), 0);
    var result = new char[resultLength];
    int index = resultLength - 1;
    do
    {
        result[index--] = symbols[(int)(num % baseNum)];
        num /= baseNum;
    } while (num != 0);

    return new string(result);
}

PS. It's recommended to name all classes and all methods in UpperCamelCase regardless of their publicity.


This is really silly:

while(k > avg) //Adds the moves
{
    k-- ;
    cnt++ ;
}

When you can do the same thing in one step:

if (k > avg) cnt += k - avg;

I don't see anything else to make this faster. But there are many many coding style issues.

Limit the scope of variables

Instead of declaring all the variables at the top,
it's better to declare them in the smallest scope, for example:

int avg = sum/t;
for(int i = 0 ; i < t ; i++)
{
    int k = n[i];
    if (k > avg) cnt += k - avg;
}

Use the right types

Why do you read the numbers into a string?
The program won't work if a pocket contains more than 9 candies,
which it might, since the requirement states "less than 1000".
Use an int[] instead.

Misc

You should not using namespace std
You're mixing C++ style input/output using cin/cout and old-style scanf/printf. Since you're in C++, you should use C++ everywhere consistently
It's recommended to use braces even with single-statement ifs and loops
After the break statement, you can simplify a bit by eliminating the else block

Corrected and improved implementation

With the above suggestions, the implementation becomes:

#include <iostream>
#include <stdio.h>

int main()
{
    while(true)
    {
        int t;
        std::cin >> t;
        if (t == -1) {
            break;
        }

        int sum = 0;
        int n[t];
        for(int i = 0 ; i < t ; i++)
        {
            std::cin >> n[i];
            sum += n[i];
        }

        if (sum % t != 0) {
            std::cout << "-1" << std::endl;
            continue;
        }

        int avg = sum/t;
        int cnt = 0;
        for(int i = 0 ; i < t ; i++)
        {
            int k = n[i];
            if (k > avg) cnt += k - avg;
        }
        std::cout << cnt << std::endl;
    }
}

Take special note as to how each variable is declared and initialized right before it's really needed.


Project Euler problem 12: highly divisible triangular number

The program is slow for several reasons:

The triNum function finds all the divisors. It doesn't need to. After you find 500 divisors, you could print the number and return from the function

The function doesn't do what the problem description asked: it prints a number only when it has exactly 500 divisors, but the problem asks for the first number with over 500 divisors. If the first number has 502 divisors
that would be a valid answer but your program will never print that.

Even after finding a number with over 500 divisors, your program would continue running until it checks 100000000 numbers. That's completely unnecessary, it should exit after finding the first appropriate number.
The program doesn't reuse the counts it already calculated. For example, after counting the divisors of 100, that could be reused when counting the divisors of 200. You could greatly benefit from using a map to cache already calculated counts.

The program has several other violations of good practices:

using namespace std is considered bad practice
The expression int i=1;i<100000000;i++ is too compact, it's recommended to put spaces around operators and after semicolons, like this: int i = 1; i < 100000000; i++
triNum is a poor name: it fails to describe what the function does
100000000 and 500 are magic numbers. It would be better to put these values in constants with descriptive names


To use static instances of value types instead of plain enum isn't a strange thing. I can't discuss its merits because each case is different (for sure it's slightly slower but you will hardly notice that) but you can see it often (also in .NET Framework code.) Use it cum grano salis because IMO there aren't many use cases unless you want to emulate more powerful Java's enum.

What's wrong, in my opinion, is that you're mixing too many responsibilities inside the same class. Note that you also have code for representation (abbreviated enum value) which usually doesn't belong to domain.

Second point is to wrap the enum. If you use this pattern then you don't need an enum any more, just drop it and integer value (day of week) will have its own clear name.

Third point is initialization, you don't need a property, because Day is an immutable value type your code may be simplified to a static readonly field.

Let's imagine to declare your struct like this:

public struct Day
{
    public static readonly Day Monday = new Day(1);
    public static readonly Day Tuesday = new Day(2);

    private Day(int dayOfWeek)
    {
        _dayOfWeek = dayOfWeek;
    }

    private readonly int _dayOfWeek;
}

Now we have to make it easy to use during our debugging sessions (and integer value isn't so friendly). We have two options here, adding another field with long name (which eventually might hold also the short one) like this:

public static readonly Day Monday = new Day(nameof(Monday), 1);

Note that the main point is to keep everything in one single point. To add another day (!), for example Sunday, you need to change only one point in your code.

If you need it only for debugging then I'd avoid to override ToString() and I'd go with DebuggerDisplayAttribute but it's a matter of preference. ToString() is sometimes the mandatory choice for type conversion in many poor-designed libraries and I'd avoid to use it as debugging aid when I have better options.

[DebuggerDisplay("{_name}")]
public struct Day { /* */ }

Second option is to write a type ad-hoc for debugging purposes without polluting your value type with unused and heavy strings. Let's introduce DebuggerTypeProxyAttribute:

[DebuggerTypeProxy(typeof(DayDebugView))]
public struct Day { /* */ }

In DayDebugView you can put everything you need for debugging:

internal sealed class DayDebugView
{
    public DayDebugView(Day day)
    {
        _day;
    }

    public string Name
    {
        get
        {
            // Pseudo-code with some Reflection Magic
            // To get the static field name...
            return FindStaticFieldByValue(typeof(Day), _day)?.Name;
        }
    }

    private readonly Day _day;
}

Now you're done (in one way or another) with your debugging aid. If you need a presentation value then get rid of those hard-coded strings (because they're not localization friendly). Note that you might want, it depends on your usage pattern, use/implement IFormatProvider (in a separate class), implement IFormattable, implement a TypeConverter (in a separate class), implement IConvertible or use ValueConverterAttribute and implement IValueConverter. Which one is better/required depends on your UI requirements. For UI ToString() is just an abused handy method...

Add to all the above also code for comparison (at least overriding Equals() and implementing IEquatable<T> but probably also == and !=), eventually type conversions (to/from integers?), parsing to/from strings, serialization and...do you also need flags? Then few test to exercise you did everything correctly and you will ask yourself why you're not using a simple enum (with few lines of validation when it's an input.) Yes, sometimes you will need this structure but less often than you might imagine.


Most elegant approach to writing list renumbering function

I think a sorting-based approach would be simpler than using a map. The basic idea is that we sort the list, assign each item a value based on its position in the list, then undo the sorting and take the value assigned to each item. In order to undo the sorting we have to remember the position each item was at before the sort. So we get the following steps (illustrated using the example input ["a", "c", "b", "c"]):

Annotate each item with its index. So ["a","c","b","c"] becomes [(1, "a"), (2, "c"), (3, "b"), (4, "c")].
Sort the annotated items by their value. So for the example we get [(1, "a"), (3, "b"), (2, "c"), (4, "c")]
Group the sorted annotated items by their values, so that duplicate items get assigned the same number in the next step. In the example: [[(1, "a")], [(3, "b")], [(2, "c"), (4, "c")]]
Now annotate each group with its index again. In the example: [(1, [(1, "a")]), (2, [(3, "b")]), (3, [(2, "c"), (4, "c")])].
Flatten the groups, so that instead of a list of groups we have a list of items again where each item has an old index and new index. In the example: [(1, (1, "a")), (2, (3, "b")), (3, (2, "c")), (3, (4, "c"))].
Now undo the sorting by sorting the items by their old index. In the example: [(1, (1, "a")), (3, (2, "c")), (2, (3, "b")), (3, (4, "c"))].
Lastly map each item to their new index. So for the example we get the output [1,3,2,3].

This leads to the following code:

{-# LANGUAGE TupleSections #-}
import Data.List
import Data.Function (on)
import Data.Ord (comparing)

renumber :: (Ord a) => [a] -> [Int]
renumber = map fst . unsort . number . indexAndSort
    where
      indexAndSort = sortBy (comparing snd) . zip [1..]
      number = concatMap (\(i,xs) -> map (i,) xs) . zip [1..] . groupBy ((==) `on` snd)
      unsort = sortBy (comparing (fst . snd))

Note that I chose 1-based indices instead of 0-based indices because you start numbering at 1 as well and this way my code produces the same results as yours.


Ruby Dynamic Struct - Pattern or AntiPattern?

I have the feeling that your patterns is very similar to the idea behind OpenStruct and similar libraries, such as Hashie::Mash.

So I would say, it's definitely not an anti-pattern in some cases. Such structures are very helpful when parsing and converting structured inputs, for example an API call.


High-level notes:

There are no comments in this code. It would be easier if you provided some explanation for the logic – for example, why do we skip URLs that contain “javascript:” or “reviews” – because it will make the code easier to review and update later.
There’s quite a bit of repetition. Pulling that out will make it easier to read and follow.
This is a moderately complicated and self-contained block of code. It might be worth pulling it out into its own method/function normalise_url that can be tested independently. If you don’t want to use the URL, return None. Then you have:

href = normalise_url(a['href'])
if (href is not None) and (href not in links):
    links.append(href)

And the logic of deciding whether to use the URL, and how much to use, can be managed elsewhere.

Line-specific comments:

Your if branches go:

if href[0] == '/':
    ...
elif href[:4] == 'http':
    ...
elif href[0] != '/' and href[:4] != 'http':
    ...

If we reach the second elif, then we know that both of those conditions are true, so we can reduce it to else:.

Note also that a better way to check if a string starts with a particular substring is to use .startswith().
You’re using str.find() to check whether the URL contains the string ?pid=. The better approach is to use in (and indeed, this is recommended by the docs):

if '?pid=' in href.lower():
    ...

However, it should be noted that on both occasions when you use this, the only thing you do is apply .strip() to a string which has already had .strip()applied. With no arguments, this just removes whitespace – which means the second application does nothing. You could cut out this branch entirely.
When you construct the href with the domain link, you could call .lower() there to save you remembering to call it later; i.e.,

href = (domain_link + href).strip().lower()
...
href = (domain_link + '/' + href).strip().lower()

When you check whether the URL contains javascript: or reviews, you could compress the condition onto a single line without sacrificing readability:

if ('javascript:' in href) or ('reviews' in href):
    continue

When you’re looking for the hash (#) and splitting the string, you’re doing it in quite an unPythonic way. Rather than looking up the index of # in the URL and taking a slice, just take the first part of .split(); i.e.

href = href.split('#')[0].strip()

This works whether or not there's a hash in the string.
I would tidy up the final if condition to check if (href not in links), as it makes the code a little cleaner. It saves you a continue when you’re very close to the end of the loop, and makes it explicit when you’re going to add a URL.

(Alternatively, you could make links a set, and then you could add every URL and trust Python to sift out the duplicates. Of course, that depends on whether order is important.)

With those comments in mind, here’s my final version of your code:

for a in self.soup.find_all(href=True):
    href = a['href']
    if not href or len(href) <= 1:
        continue

    if href[0] == '/':
        href = (domain_link + href).strip().lower()
        if ('javascript:' in href) or ('reviews' in href):
            continue
    elif not href.startswith('http'):
        href = (domain_link + '/' + href).strip().lower()

    href = href.split('#')[0].strip()

    if (href not in links):
        links.append(self.re_encode(href))

I’ve also added some blank lines to break it up into logical units – I think this makes it easier to skim the structure.


The improvement I would like to suggest you deals with the big picture of your program rather than its details: the functions dealer() and gameloop() (which is far from being a good function name) are long. This makes them difficult to test and they certainly, among other things (as explained briefly here), violate the single responsibility principle.


Logs 'Fizz' for multiples of three, 'Buzz', for multiples of 5, and 'Fizz Buzz' for multiples of 3 & 5

A short review;

You don't need the array, you could just use i
Part of the challenge is to realize that you only have to check for 3 and 5
i is a good short variable, I would go for num -> n or even count
I only use fat arrow syntax => for inline functions
Function names ideally follow <verb>Thing syntax so fizzBuzz -> logFizzBuzz

This is my counter proposal;

function logFizzBuzz(count){

  for (let i = 1; i <= count; i++) {
    let out = '';
    if (i % 3 === 0){
      out += 'Fizz';
    }
    if (i % 5 === 0){
      out += 'Buzz';
    }
    console.log(out || i);
  }
};

logFizzBuzz(45);


How can I use object oriented principles in the following scenario?

Assuming all three companies require the same information, create a base class "CarRentalInformation."  This information will store/transmit all pertinent information.

Create serializer/deserializer classes for all types of can rentals you need.  You could probably use the factory pattern effectively here even if you need specialized information for each type you need.

The logic could then be written as

public List<CarRentalInformation> GetCarRentalInformation(string XML)
{
   CarRentalXmlType xmlType = this.DetectCarRentalXmlFormat(XML);
   ICarRentalFactory deserializer = this.GetCarRentalFactory(xmlType);

   return deserializer.Deserialize(XML);
}

public string GetCarRentalXML(List<CarRentalInformation> rentalInfo, CarRentalXmlType xmlType)
{
   ICarRentalFactory serializer = this.GetCarRentalFactory(xmlType);
   return serializer.Serialize(rentalInfo);
}

private CarRentalXmlType DetectCarRentalXmlFormat(string XML)
{
   //do some magic detectivework, and return appropriate type
   return CarRentalXmlType.Budget;
}

private ICarRentalFactory GetCarRentalFactory(CarRentalXmlType xmlType)
{
   switch(xmlType)
   {
       case CarRentalXmlType.Budget:
          return new BudgetCarRentalFactory();
       case CarRentalXmlType.Dollar:
          return new DollarCarRentalFactory();
       default
          return null;
    }
}

public interface ICarRentalFactory
{
    public List<CarRentalInformation> Deserialize(string XML);
    public string Serialize(List<CarRentalInformation> rentalInfo);
}

public class BudgetCarRentalFacotry : ICarRentalFactory
{
   //contains code to serialize/deserialize XML into CarRentalInformation objects
}


Finding a way to obtain some volume of water using a large and small bucket

I found your conditions to be a little confusing. It was hard for me to understand the rules of what is going on by just a quick glance. In this simple case, you don't necessarily need to create more abstraction, just be more clear about presenting the rules.

One way to make your code more readable is to try and avoid an if/else maze if a series of ifs could suffice instead. There's a certain amount of personal preference to that, however, when there are many if/else's, your brain has to stack up and keep track of all the previous conditions. It's better to check a condition, then handle it immediately and return to a higher scope instead of nesting further. By not nesting further, you can "forget" about it and simply move on to the next condition.

A trivial example example:

function describeHeight(person) {
    var height = person.height;
    if (height < 4) {
        console.log('short');
    }
    else if (height >= 4 && height < 6) {
        console.log('average');
    }
    else if (height >= 6 && height < 8) {
        console.log('tall');
    }
    else {
        console.log('giant!!!');
    }
}

Versus:

function describeHeight(person) {
    var height = person.height;
    if (height >= 8) {
        console.log('giant!!!');
        return;
    }
    if (height >= 6) {
        console.log('tall');
        return;
    }
    if (height >= 4) {
        console.log('average');
        return;
    }
    console.log('short');
}

Not the best example, perhaps. But I feel like the second version is easier to read. See how the first example has more nesting, and the second has less?

In your example, I would try to simplify the rules. The logic may not be correct here, because I don't exactly understand your rules, but something like this may be easier to read:

while (step++ <= maxSteps) {
    // Check if container has the appropriate amount of water.
    if (buckets.firstContainer.getCurrentAmount() === waterSize) {
        break;
    }

    // If first container is empty, then fill it.
    if (buckets.firstContainer.isEmpty()) {
        buckets.firstContainer.fill();
        continue;
    }

    // If first container is full, fill up the second container if there's room.
    if (buckets.firstContainer.isFull() && buckets.secondContainer.hasCapacityAvailable()) {
        buckets.firstContainer.transferTo(buckets.secondContainer);
        continue;
    }

    // If second container is full, dump it out, and try to fill up the first container if there's room.
    if (buckets.secondContainer.isFull() && buckets.firstContainer.hasCapacityAvailable()) {
        buckets.secondContainer.empty();
        buckets.firstContainer.transferTo(buckets.secondContainer);
        continue;
    }
}


Answerer's note: I'm moving commentary about NSString versus C-style strings out of this original answer and into their own answer.

The strings we use in creating the error objects, as well as the integers we use for the code in these objects should be defined, named constants (and probably an enum for the integers) all put together in one common place.  This way, if we ever want to reuse any of these, that's simple.  If we ever want to rename, reword, renumber, etc., they're all located in one easy to find location no matter how messy the code in this particular section gets.

The word "and" should be used to indicate that a method performs two distinct actions (and typically should just be two separate methods anyway).  We shouldn't use the word "and" to chain our variables.

Why not make an enumeration for our operation constants?  This will make our Objective-C code slightly more clear, and if someone uses this in a Swift project, they'll really like that they get errors if trying to send an invalid argument for this.

Our enum might look like this:

typedef NS_ENUM(NSInteger, LDAPOperation) {
    LDAPOperationAddUser = LDAP_MOD_ADD,
    LDAPOperationDeleteUser = LDAP_MOD_DELETE
};

And one final note about this code, given that it's Objective-C, we should use YES and NO rather than true or false.  There's no technical difference, but the Objective-C style is to use the YES/NO defines.


Creating and updating link to instagram image or video

addOrUpdateImageLink() and addOrUpdateVideoLink() are essentially the same, therefore it would be better to create just one function that would accept different parameters dependent on whether our media is an image or video;
In createMediaLink() you invoke addOrUpdate………Link() functions before you declare them. It is not wrong, but it worsens readability and code flow;
Setting 50 ms delay is not the best way to achieve what you are trying to do. Since I don't know how the DOM workings look like, I left it unchanged though;
Use strict equality operator (===) wherever possible — it performs no type conversion;
Once you pick which quotes you use ('' or ""), stick to it. Generally, single quotes option is more popular and standard.

Rewrite

const addOrUpdateMediaLink = src => {
  if (!src) { return; }
  console.log(`src: ${src}`);

  let a = document.querySelector('._open_');

  if (!a) {
    a = document.createElement('a');
    [a.className, a.textContent, a.target] = ['_open_', 'Open in new tab', '_blank'];

    // media container
    document.querySelector('._97aPb').appendChild(a);
  }

  a.href = src;
};

const addOrUpdate = (selector, observeSelector, attr, mo) => {
  let media = document.querySelector(selector);

  if (!media) { return false; }

  if (mo) {
    const obj = {};
    obj[attr] = true;
    mo.observe(document.querySelector(observeSelector), obj);
  }

  setTimeout(() => addOrUpdateMediaLink(media.src), 50);

  return true;
};

const createMediaLink = () => {
  const selectors = {
    attributes: ['.tWeCl', '.tWeCl'],
    childList:  ['.FFVAD', '.rQDP3']
  };

  const mo = new MutationObserver(mutations => mutations.forEach(mutation => addOrUpdate(selectors[mutation.type][0])));

  return addOrUpdate(...selectors.childList, 'childList', mo) || addOrUpdate(...selectors.attributes, 'attributes', mo);
};

createMediaLink();


Improving F# conditional assignment with match expression

Thanks to the input provided in the other answers, here's what I've come up with:

let label =
    let (found, value) = this.counters.TryGetValue(t)
    this.counters.[t] <- value + 1
    if found
    then (sprintf "%s (%i)" t.Name (value + 1))
    else t.Name

Or using a match expression

let label =
    let (found, value) = this.counters.TryGetValue(t)
    this.counters.[t] <- value + 1
    match found with
    | true -> (sprintf "%s (%i)" t.Name (value + 1))
    | false -> t.Name

I've also refactored this into a separate function, so the actual assignment is just

let label = getNextLabel(t)

Both of these look better than my original code, though I'm not sure that the match has added any expressiveness to the code, so for now I'm keeping the plain old if / else statement. This is mostly just taking advantage of the built-in behavior of dictionaries in .NET (TryGetValue returns the default value if the key is not found, and the Item property's setter will perform an insert if necessary), but I'm still open to any suggestions on improving this more.


Project Euler # 3 in Haskell: largest prime factor of some number

Naming

findLargestPrimeFactor isn't true to its name. It just returns the first prime number in the given list or 1 otherwise. So firstPrime :: [Int] -> Int might be more apt.

Efficency

At the moment, you check \$ n \$ candidates in listOfFactors. But that's not necessary. First of all, if we found a divisor x, then we also found a second divisor, n `div` x. We also only need to check x up to \$ \sqrt{n}\$:

listOfFactors :: Int -> [Int]
listOfFactors n = concat [[x,d] | x <- [1..nsqrt], let (d,m) = n `divMod` x, m == 0]
  where
    nsqrt = ceiling (sqrt (fromIntegral n))

Now we only need to check \$\left\lceil \sqrt{600851475143}\right\rceil = 775147\$ numbers, which is much, much less. This variant will actually  finish in under one second, whereas I didn't run my program till the end.

However, you now have to sort your list, or use filter isPrime followed by maximum in findLargestPrimeFactor, whose name would be then mostly (beside the Factor) apt.

If you rewrite findLargestPrime so that it returns the largest prime from a given list, we would end up with the following main:

main :: IO ()
main = print (findLargestPrime (listOfFactors 600851475143))

Which seems reasonable.

Another approach

While one can solve this problem in this way, one can also just generate the prime factors of the number:

primeFactors :: Int -> [Int]
primeFactors n = go 2 n
  where
    go _ 1 = []
    go k n = case n `quotRem` k of
               (n', 0) -> k : go k n'
               _       ->     go (k + 1) n'

If k is going to be put in the list, it will always be prime. Note that one can improve this function further, but that's left as an exercise.

Exercises

In the section "efficency", we were able to reduce the runtime by narrowing the search space. However, why is it enough to run up to $\ \sqrt{n} \$ only?
In the section "another approach", one can cut the amount of checked numbers almost by half. How?


Reporting duplicate entry for a given set of data

String.equals() compare their char[] inside, which is slower than simply compare two ints.
String concatenation is slower than creating a Database.
String.hashcode() is just like its equals.

Note that your implementation of Database.equals is incorrect, though you're lucky this time.

@Override
public boolean equals(Object obj) {
    return (obj instanceof Database) && ID == ((Database)obj).ID &&
            SC == ((Database)obj).SC;
}

The hashcode implementation is only a suggestion.

@Override
public int hashCode() {
    return 31 * (31 * 17 + ID) + SC;
}


Project Euler #1: multiples of 3 and 5 Ruby

About your code, a first refactor would include:

n = 0 + until n >=1000 do -> 0.upto(999).each do |n| or (0...1000).each do |n|
total.each { |i| sum += i.to_i}. Why to_i? it's already an integer.

A second refactor would, well, throw away the entire code :) That's how you'd write it in a low-level language (C, for example) but it's not idiomatic Ruby. In Ruby, you use functional constructs with enumerables. It's more concise, more readable, more declarative:

result = (0...1000).select { |n| n % 3 == 0 || n % 5 == 0 }.reduce(0, :+)

That would be perfectly fine but, in the context of the euler project, where you will use the same abstractions over and over, you can do better. What could you abstract here? I'd say: Integer#divisible_by? and Enumerable#sum. Once you've added these methods, the solution can be read out loud (write 0.upto(999) if you want an even more human-readable solution, even though people tend to prefer ranges):

result = (0...1000).select { |n| n.divisible_by?(3) || n.divisible_by?(5) }.sum


Find missing numbers in a range, with duplicate numbers in a sorted array

Firstly there are 2 classes so don't show them as a single code when showing your code. Place a heading with the class name then your code then second class name then your second class's code. That makes it easier to copy paste it into Eclipse when seeing the code.

Why have you named the parameters as x2 and y2 and still using the this keyword? Why are you making the variable names different in the first place? It just adds confusion. Name them as x and y and then use the this keyword. Period.

You are throwing a null pointer exception when a is null and the message is a1 is null. That will become confusing... Also you don't need to throw that explicitly. The assignment to high will throw the exception and give you a proper stacktrace already without any extra code.

The while loop can be made a for loop very easily and will limit the scope and extra variable (i in this case). Note that you are doing i++ in both if as well as else. That shows you didn't take the time to look at your own code.

You passed startOfRange to the function and forgot that it is a variable also. If you have any intention of not changing it then make it explicit and declare the parameter as final in the method's signature.

Also If I am correct then you have used x = 0 only to make it one less than the startRange so that your algorithm works. That means your function will break the moment you decide the startRange to be anything other than 1. Also using such magic numbers and such variable names as x is a bad idea. Really bad idea.

Take some time to refactor the code yourself. It pays if your code is easy to understand by other programmers. Your code can be changed to this and I think now it is much easier to understand the flow of execution of the current program.

public static ExVariables sortedConsecutiveTwoRepeating(int[] a,
        final int startOfRange) {

    int low = startOfRange;
    int high = low + (a.length - 1);

    int x = low - 1;
    boolean foundX = false;

    for (int i = 0; i < a.length; i++) {
        if (a[i] > low) {
            if (foundX) {
                return new ExVariables(x, low);
            }
            x = low;
            foundX = true;
        }
        if (a[i] >= low) {
            low++;
        }
    }

    if (foundX) {
        return new ExVariables(x, high);
    } else {
        return new ExVariables(high - 1, high);
    }
}

I think it should be possible to refactor it more so that the return comes only inside the for loop but I didn't take the time to do that.

Hope this helps.


Bash function to produce variants of images at 2X and 3X resolutions

Double-quote variables used as command line arguments

Instead of this:

convert $1 -crop $2 "two.png"

Write like this:

convert "$1" -crop "$2" "two.png"

This is to protect from word splitting and glob expansion.

Double quote... naturally

This is hard to read and confusing:

Final=$One"X"$Two"+"$Three"+"$Four

I suggest to write like this:

Final="${One}X$Two+$Three+$Four"

Use better variable names

It's really hard to make sense of a program that uses variable names like First, Fourth, Second, Lhs, that don't reveal their purpose.

Also, the convention is to use lowercase names, without capitalizing the first letters.

Chopping off characters case insensitively

Instead of detecting if the delimiter is x or X and storing it in a variable,
you could use the pattern [xX], for example:

width=${spec%%[xX]*}

For example if you have 200x300 or 200X300 in spec, width becomes 200.
(Do take note of the meaningful names.)

Floating point math in the shell

Unfortunately Bash doesn't do floating point math.
It would give you a syntax error if you tried to multiply something by 1.5.
On the other hand, if you want to multiply by 1.5, and you don't mind truncating decimal points (as is the case here), you could multiply by 3 and divide by 2.

That is, instead of this:

width=$(bc <<< "$width * 1.5")

You could write:

((width = width * 3 / 2))

Use here strings

Instead of echo ... | cmd, write cmd <<< "...".


As suggested by Toni, you should use Gulp (or another task runner) to optimize the code shipped to the server and streamline your work. Among other things, task runners can concatenate files, minify/uglify code, transpile ES6 into ES5, serve your app locally, etc.

I strongly recommend Gulp (built on Node.js) because it allows you to create different tasks (such as the ones mentioned above) and stream them via a single pipeline, thus processing code fast and efficiently.

The main Gulp methods are task() (the task you want to create), src() (the source file(s)), pipe() (pipes the plugins that transform your code: pipe(plugin())) and dest()(where Gulp will send the processed file(s)). While Gulp provides a frame to create the "tasks pipeline", you need to use plugins to process/transform your code. Plugins are installed separately from Gulp as they are not part of the Gulp module itself (this means you need to install Gulp and all other plugins you want to use to create tasks).

I created a little tutorial below that will teach you the basics of Gulp. If you follow these steps you will create a simple sass task and have an idea what Gulp can do for you. Note: sass is a ruby gem. Make sure you have sass installed on your computer otherwise this will not work. You also need to have node.js and npm installed (https://nodejs.org/en/):

// First you need to install your node modules on the terminal:

$ npm install --global gulp-cli // gives you access to gulp on the command line

$ mkdir gulp-sass-demo && cd gulp-sass-demo // or any dir name you prefer. Make sure you don't name it "gulp-sass" though, because this is the name of a plugin we are going to use and npm will not allow you to install the plugin in a folder with the same name.

$ npm init // initiates npm on this directory--just hit enter for every question--at the end of the process you should have a "package.json" file, which holds important information about your node project

$ npm install --save-dev gulp gulp-sass // saves these two node modules as dev dependencies, meaning dependencies you need to develop the app but not to run it.

Note about how to install packages: If your project used "jQuery", for instance, you would need to install it as a dependency (not dev dependency) because your app would need jQuery's functionalities to work. In that case you would run this command $npm install --save jquery(this lists the module as a dependency on "package.json") or simply $npm install jquery (this doesn't list the module in package.json but makes it available as well).

After installing gulp and gulp-sass your package.json should look something like this:

{
  "name": "gulp-sass-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-sass": "^3.1.0"
  }
}

That is it for the plugins installation. Now you should create a sass directory and one sass file that we will process via gulp-sass. So:

/gulp-sass-demo
  /sass
    styles.scss

In styles.scss, paste the following sass:

$font-stack: Helvetica, sans-serif;
$primary-color: #fff;

body {
  font: $font-stack;
  color: $primary-color;
}

Now you need to create a gulpfile.js, where you write your tasks:

// on the terminal make sure you are at the root of your project
$ touch gulpfile.js // creates the gulpfile--you can use vim, nano, or any other editor if you want to create and edit the file. i.e vim gulpfile.js

Open gulpfile.js in your IDE (you can do this on command line editors as well if you prefer), copy and paste the code below:

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function() {
  gulp.src('sass/*.scss')
  .pipe(sass())
  .pipe(gulp.dest('css'))
});

gulp.task('default', ['sass']);

This is what the code above does:

1) uses the node.js module loader system to require the "gulp" npm module and the "gulp-sass" npm module and assigns these modules to variables

2) uses these variables to create a "sass" task

3) gets all ".scss" files from the 'sass' directory

4) processes the files using the sass plugin

5) sends the resulting css from the processed .scss files to a css directory--if you don't have that directory Gulp creates it for you

6) registers the task 'sass' to run after the task 'default'. To run a gulp task you need to use the gulp command + the task name on the terminal. In this case you would run $ gulp sass since the name of your task is "sass". When you register a "default" task, you can simply run gulp without specifying any task name and gulp will look for tasks registered in the second argument (in this case ['sass'] only) and run that task for you. You can register other tasks in the array when you have them and have something like this: gulp.task('default', ['sass', 'js', 'html']);

So if you go to your terminal window and run $ gulp (the default task) it will then run the 'sass' task automatically. You can still run $ gulp sass if you want to run the task directly (watch Gulp messages as it runs the task).

Once the task is finished, go back to your IDE. Your directory should look like this now:

/gulp-sass-demo
  /css
    styles.css
  /node-modules // the modules you installed via npm
  /sass
    styles.scss

Gulp just created a css file that you can link on your HTML.
Your styles.css should look like this:

body {font: Helvetica, sans-serif;
      color: #fff; }

There is much more to Gulp but I hope this provides a good introduction to it.


OutputStream class for use with subprocess.Popen

I don't know enough about threading to help with that part, but it looks like your class could benefit from implementing the __enter__ and __exit__ functions that would allow it to be used with the with keyword.

There's a short section in the docs about it as well as an entry in the PEP from when it was added to Python. with allows you to instantiate an object that involves some connection or file that needs to be closed and will always ensure that even if errors arise, the object will be closed accordingly regardless of those errors. It's like wrapping your document with try: finally: stream.close(), but without needing to add that every time you call the stream.

Here's how it might look in your object:

def __enter__(self):
    # Theoretically could be used to set up things not in __init__
    return self

def __exit__(self, exc_type, exc_val, exc_tb):
    self.close()

The parameters that __exit__ takes will be passed to it are just exception information, you could use them if you wanted to but they have to be included in the definition as they'll be passed as part of the with syntax.

Now you could use the object like this:

with OutputStream() as stream:
    proc = subprocess.Popen(['ls', '-l'], stdout=stream, stderr=subprocess.STDOUT)

    while proc.poll() is None:
        time.sleep(0.05)


AngularJS constants depending on other constants - any established patterns?

Using an IIFE seems to be the tidiest way I've found to do it. This allows you to define your constant as a function (that is immediately invoked) that returns your constant object so you can use it as normal, i.e: LABELS.appName

.constant('LABELS', (function () {
    var self = {};
    self.appName = 'MyApp';
    self.companyName = 'MyCompany';
    self.appHeader = self.appName + ' | ' + self.companyName;
    return self;
})());//function is immediately invoked here

References:

SO answer
Use functions (IIFE) to define AngularJS constants and values


Converting decimal integers to a string representation in an arbitrary base between 2 and 26

The cardinal sin

An assignment tmp_string[tmp_string_i] = remainder; may write beyond an allocated memory. Consider a case of buffer_size being equal to 0. You must test tmp_string_i before the assignment. I don't know what exactly someone had in mind, but you are definitely committing one.
Unnecessary variables

decimal_number is passed by value; you can mutilate it as much as you want. There is no need to have dividend.

Reversal can be done in-place. There is no need for tmp_string at all. tmp_string_i shall also be gone.
Finding digits

Executing division dividend / base twice per iteration looks wrong; special-case of the last digit looks also wrong. Using do-while solves both wrongs:

    do {
        output[output_i++] = int_to_char(dividend % base);
        number = number / base;
    } while (number != 0);

No raw loops

Most loops represent an important algorithm, which deserves to be factored out in a function of its own, for further reuse and for giving it a name. In your case, the loop under the //copy tmp_string to output in reverse order comment implements an algorithm known as reverse.

All that said, this is

Misc

The returned string should be terminated by '\0', or its actual length be returned.
The code happily converts numbers to a base up to 36 (10 digits and 26 letters). I see no reason to limit a base to 26.
Return codes 0,-1,-2 should be defined as named constants.
Size variables (e.g. buffer_size) should be unsigned, or better yet of type size_t.
The decimal_number parameter is not decimal. It is just number. Need to be renamed accordingly.


I'll give you a hint. Think of a && b && c as a 3 digit binary number

So all possibles values will be:

a | b | c
0 | 0 | 0
0 | 0 | 1
0 | 1 | 0
0 | 1 | 1
1 | 0 | 0
1 | 0 | 1
1 | 1 | 0
1 | 1 | 1

As you can see, you want to flip c every time and check the value of a and b to determine what they will be. b will change any time c is 1 and a will change any time b and c are 1. This should be enough to give you a better implementation.


Instead of saving len(total), just use:

if len(total) > 58:
     print("\nHolly Shit!!! You broke my record!!! with %d." % (length))

elif len(total) == 58:
    print("\nWow, Nice!!! 58 is my highest Palindromic number (too).\nThat's a draw")
    # Since you hardcoded your -highscore-, there's no need to use a variable to print the highscore.

Use whitespace more efficiently, especially in your palindrome() function.
Instead of converting n to str() in your palindrome() function, use numbers.append(str(x)). This way you can reuse palindrome() and have it take n as a string by default (or use an assertion / try: except: statement).

Rewritten:

from random import randint

numbers = []
palindromes = []
dice = randint(1000, 50000)

while len(numbers) < dice:
    x = randint(100000, 1000000)
    numbers.append(str(x))

def palindrome(n):
    for i in n[::-1]:
        if i == i[::-1]:
            palindromes.append(i)
    return palindromes

palindromes = palindrome(numbers)
print(palindromes) # To check this works

if len(palindromes) > 58:
    print("\nHoly shit! You broke my record with %d!\n" % (length))

elif len(palindromes) == 58:
    print("\nWow, nice! 58 is my highest palindromic number too!\n")


Simple blog engine for educational purposes

The common code is about updating the post, so I'd extract this into it's own method:

private bool UpdatePost(Post post)
{
    // convert the title to a slug (Hello World becomes hello-world for example)
    post.Slug = SlugConverter.Convert(post.Title);
    post.Summary = Summarize(post.Content);

    AttachTags(post);

    // check whether the slug is occupied.
    if (repository.Posts.Any(p => p.Slug == post.Slug))
    {
        ModelState.AddModelError("", "title in use");
        return false;
    }

    repository.Posts.Add(post);
    repository.SaveChanges();
    return true;
}

With that your Edit and Add methods can be reduced to:

[HttpPost]
public ActionResult Add(PostInputModel model)
{
    if (!ModelState.IsValid) return View(model);

    // map the input model to an entity model using AutoMapper (extension method).
    var post = model.MapTo<Post>();
    post.PublishedAt = DateTime.Now;

    if (!UpdatePost(post))
    {
        return View(model);
    }

    // indicates that a "post published. available here." message should be displayed.
    TempData["newPost"] = true;
    // redirect the user to the edit page
    return RedirectToAction("Edit", new { slug = post.Slug });
}

[HttpPost]
public ActionResult Edit(PostInputModel model)
{
    if (!ModelState.IsValid) return View("Edit", model);

    var post = repository.Posts.SingleOrDefault(p => p.Slug == model.Slug);
    // if the post does not exist return an error
    if (post == null) return HttpNotFound("you cannot edit a post that doesn't exist");
    repository.Posts.Remove(post);
    repository.SaveChanges();

    // map the input model to an entity model using AutoMapper (extension method).
    model.MapPropertiesToInstance(post);

    if (!UpdatePost(post))
    {
        return View(model);
    }
    return Edit(post.Slug);
}