Read strings from a standard input, and find the most duplicated word

Nothing awful here.
If this was production code then putting things in named functions would be nice to help with self documenting code.

Don't particularly like this.
    using std::cin; using std::cout; using std::endl;
    using std::string;

But I am not going to complain about it very much.

Using snake case is unusual but not unheard of in C++.
    string most_duplicated_str;
    int most_duplicated_count = 0;

Like the long descriptive names and the grouping of you variables into logical combinations.

I would note that:
      cin >> new_str

Reads a white space separated word. For college and learning purposes this will be fine. But in real life you would have to consider punctuation and other non alphabetical content and what to do with it.

Not a very useful comment.
I would either make it more descriptive (more words) or remove it.
    // loop variables

and
            // update prev_str

These three lines can be simplified:
            new_duplicate_count = 1;
            prev_str = new_str;
            continue;

to:
            new_duplicate_count = 0;

It will have the same effect and the loop will feel more logical as the same action happens every loop. But that's just my opinion on readability. If you did not change it I would not oppose it being merged into mainline.

If any words are read: Can the value ever be zero?
    // print result
    if(most_duplicated_count == 0)
        cout << "# No Duplicated Words #\n";
    else

If you only have a duplicate count of 1 were there any duplicates?
What happens if there are ties in the number of duplicate counts?
These are good questions to ask your customer! :-)


Switch case reviews, finding days of the week that coresponds to a number given

I would add to forsvarir's good answer: start thinking now about the power of abstraction.  Programming is all about building abstractions.  Make your abstractions solve one problem and solve it well.  For instance, here's a problem to solve:

static string Ordinal(int n)
{
    // You fill this in. The method takes an integer and returns
    // 1st, 2nd, 3rd, 4th, etc.
}

Heres another one:

static string WeekdayName(int w)
{
  // To do: Return the name of the day of the week.
}

And here's another:

static int GetIntegerFromConsole(int low, int high)
{
    // to do: prompt the user, sit in a loop until they give
    // a response in the right range, and return it.
}

Once you have those methods then your program becomes trivial.

int weekdayNumber = GetIntegerFromConsole(1, 7);
string weekdayName = WeekdayName(weekdayNumber);
string ordinal = Ordinal(weekdayNumber);
Console.WriteLine($"{weekdayName} => {ordinal} day of the week");

You know what I like? Four-line-long programs, that's what I like. Move the mechanisms to their own helper methods, debug those methods, and then rely on them to do their jobs.


Your direct definition of tree-map looks good.

The version using map may be written more succinctly (with the recursive portion factored out) as follows:

(define (tree-map f tree)
  (define (rec tree)
    (map (lambda (subtree)
           ((if (pair? subtree) rec f) subtree))
         tree))
  (rec tree))


Haskell: Draw tabulated data given header and rows as lists

It might make sense to use a pretty-printing library to do this.  You can use pretty along with the extension pretty-ncols package; or possibly boxes would work as it's aimed at more 2D textual information.


TCP server in Android to continuously listen to an RFID reader

You should be implementing Runnable, not extending Thread. You are not creating a new generally-useful extension of thread that can be used as an API class by multiple clients. You just want a normal thread to run some code.

Classes not designed to be extended should be marked final. Variables not designed to be reassigned should be marked final.

None of stream, serverSocket, and clientSocket should be visible outside your class. Only expose methods when necessary. Only expose member variables when really, really necessary.

In idiomatic Java, underscores are only used in constants. In other cases, they should not be used.

Prefer primitives to objects where it's reasonable to do so. There's no reason to give loop_count the overhead of being an object.

loop_count is never read and can be removed.

a is a poor variable name. Variable names should clearly indicate the value they're holding. serverPort would be highly preferable. This change would make your comment noise, and it could be removed.

The two log messages could be joined. Also, you're logging the port as being open before it's open.

In idiomatic java, ALL_CAPS are reserved for constants. Other variables should begin with a lowercase letter, even if they are acronyms. ip is preferable to IP.

If you have an error opening the socket, your code busy-loops forever inside the while (run) block until something interrupts it. If the server can't be started, the run method should return, since your code isn't trying to recover from that failure. This will also let you remove the while (serverSocket != null) line, since it will never be null.

When creating the server socket, you're consuming the stack trace. You should always log stack trace. It would also be nice if your message logged the ip and port that could not be opened.

If this code is interrupted or an exception occurs, your open resources will not be closed. Prefer the use of try-with-resources blocks to ensure resources are closed.

Logging the start of every time through the loop is going to result in a lot of meaningless log messages.

The first try block inside the while (run) block does nothing and can be removed.

You dereference clientSocket immediately before you check if it's null. If it could ever be null (it can't), you'd get a NullPointerException before the null check.

Variables should be declared to minimize their scope where possible. This makes code more readable and allows for more aggressive reclamation of memory.

10 is a magic number in your code. Declare a constant whose name explains what the logical meaning of 10 is and use that in your code, so a reader understands the intent, not just that a 10 is going over the wire.

It is a bad practice to catch Exception. You are inadvertently handling any checked or unchecked exceptions that may be added in the future. If you don't know what to do with a specific exception, let it percolate up the stack. Likewise, catching RuntimeException is generally ill advised.

You have a try block that's always throwing an exception. That should obviously be removed.

The stream instance variable is never used, but then closed in the closeServer method. You create stream instances inside run and then don't close them.

The proper term is "millis", not "mills".

It would be nice to extract some of your code into a separate method so run looks less like a giant >.

With proper use of try-with-resources blocks, the closeServer method is not required.

abort should not be firing interrupt(). Include checks inside your run method to see if the thread has been interrupted, and halt gracefully if it has.

If you were to make all these changes, your code might look more like:

public class TcpServer implements Runnable {

    private static final String TAG = "TcpServerThread";
    private static final byte RECEIVED_MESSAGE_PART = 10;

    private boolean running = true;

    public TcpServer() {
        super();
    }

    @Override
    public void run() {
        final int port = 1025;
        final String ip = MiscUtilities.getIpAccess();

        try (final ServerSocket serverSocket = new ServerSocket(port)) {
            Log.d(TAG, "Server started, accepting connections to " + ip + ":" + port);

            while (running && !Thread.currentThread().isInterrupted()) {
                final long started = System.currentTimeMillis();
                try (final Socket clientSocket = serverSocket.accept()) {
                    clientSocket.setKeepAlive(true);

                    final long established = (System.currentTimeMillis() - started);
                    Log.d(TAG, "[Connection made at]:" + clientSocket.getRemoteSocketAddress() + " in mills :" + established);

                    this.handleData(clientSocket);

                } catch (final IOException e) {
                    Log.d(TAG, "Failure handling inbound connection to " + ip + ":" + port, e);
                    continue;
                }
            }
        } catch (final IOException e) {
            Log.d(TAG, "Unable to open socket " + ip + ":" + port, e);
            return;
        }
    }

    public void abort() {
        this.running = false;
    }

    private void handleData(final Socket clientSocket) throws IOException {
        try (final DataInputStream stream = new DataInputStream(clientSocket.getInputStream());
                final DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream())) {

            final byte[] inBytes = new byte[200];
            int input = 0;
            while ((input = stream.read(inBytes)) != -1) {
                Log.d(TAG, "Size read in bytes: " + input);
                Log.d(TAG, "Data is: " + MiscUtilities.bytesToHex(inBytes));

                outToServer.writeByte(RECEIVED_MESSAGE_PART);
            }
        }

    }

}


Pythons magic methods are there to make your life easier, not harder. They allow custom classes to use built-in functionality. They are not there so you have to use long names with built-in types.

The __contains__ method is called under the hood whenever you use the in keyword.

In addition, you do the same thing for all four operations: See if it is present, split by the operator and apply it. This can be simplified using a loop over a dictionary, mapping the string of the operator to the operator itself (using the operator module which gives you functions for most operations).

And so your code can be simplified to:

import operator

OPERATIONS = {"+": operator.add,
              "-": operator.sub,
              "*": operator.mul,
              "/": operator.div}

while True:
    calculation = input("Calculation: ")
    for name, op in OPERATIONS.items():
        if name in calculation:
            a, b = map(float, calculation.split(name))
            print(op(a, b))

And at that point you should ask yourself how to modify this to allow multiple operations or even grouping expressions with parenthesis.

You should also probably add some error handling (what happens if the user tries to enter multiple operations? What happens if they do not enter a number?).


The switch is awkward, and the nextIndex != 2 special case is cumbersome.  It would be a bit simpler if you regularized everything:

function makeCanvasBundleIterator(canvasBundle) {
  var i = 0, j = 0;
  var items = [
    [canvasBundle.grid],
    [canvasBundle.axes],
    canvasBundle.functions,
    [canvasBundle.overlay],
  };
  return {
    next: function() {
      if (i >= items.length) {
        return {done: true};
      }
      if (j >= items[i].length) {
        i++;
        j = 0;
      }
      return {done: false, value: items[i][j++]};
  };
}

But that could be simplified further by linearizing the list up front using Array.concat():

function makeCanvasBundleIterator(canvasBundle) {
  var i = 0;
  var items = [].concat(
    canvasBundle.grid,
    canvasBundle.axes,
    canvasBundle.functions,
    canvasBundle.overlay
  );
  return {
    next: function() {
      return (i >= items.length) ? {done: true}
                                 : {done: false, value: items[i++]};
  };
}

For that matter, why bother making an iterator at all?  Just return the linearized array.  The caller can iterate through it conventionally using a for loop or Array.forEach().

Note that the behaviour of these alternate solutions is different from the original if the canvasBundle is modified during iteration.  (You wouldn't want to do that, I hope?)


I would change your setup code to take a list of lists, where the inner lists are lists of subjects on that day and the outer list collects all these lists:

schedule = [['Spanish', 'Spanish', 'Music', 'Music', 'English Literature', 'English Literature', 'History', 'History'],
            ...]

def format_day(day_schedule):
    return "\n" + "\n".join("{}       {}".format(i, subject)
                            for i, subject in enumerate(day_schedule, 1))

today = date.datetime.today().weekday()

try:
    the_day = format_day(schedule[today])
except IndexError:
    the_day = ''
try:
    tomorrow = format_day(schedule[today + 1])
except IndexError:
    tomorrow = format_day(schedule[0])

This could actually be moved into the class, which could just take the schedule and day as parameters (which would make it a lot easier to run this, e.g for two different schedules):

import datetime
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QHBoxLayout, QApplication, QWidget, QLabel)
from PyQt5.QtGui import (QIcon, QPixmap)

def format_day(day_schedule):
    return "\n" + "\n".join("{}       {}".format(i, subject)
                            for i, subject in enumerate(day_schedule, 1))

class Timetable(QWidget):

    def __init__(self, schedule, day):
        super().__init__()
        self.schedule = schedule
        self.day = day
        self.init_UI()

    def init_UI(self):
        try:
            today = format_day(self.schedule[self.day])
        except IndexError:
            today = ''
        try:
            tomorrow = format_day(self.schedule[self.day + 1])
        except IndexError:
            tomorrow = format_day(self.schedule[0])

        if self.day <= 5:
            today_header = '<b>Today\'s Timetable:<\b>'
            tomorrow_header = '<b>Tomorrow\'s Timetable:<\b>'
        else:
            today_header = ''
            tomorrow_header = '<b>Monday\'s Timetable:<\b>'

        if self.day in (4, 5, 6):
            lbl = QLabel(self)
            pixmap = QPixmap('weekend.jpg')
            smaller_pixmap = pixmap.scaled(160, 300, Qt.KeepAspectRatio, Qt.FastTransformation)
            lbl.setPixmap(smaller_pixmap)
            if self.day == 4:
                lbl.move(-3, 162)
            else:
                lbl.move(-3, 0)
            lbl.show()

        title0 = QLabel(today_header, self)
        title0.move(5, 5)
        schedule0 = QLabel(today, self)
        schedule0.move(5, 16)

        title1 = QLabel(tomorrow_header, self)
        title1.move(5, 150)
        schedule1 = QLabel(tomorrow, self)
        schedule1.move(5, 160)

        self.setGeometry(7, 30, 150, 287)
        self.setFixedSize(self.size())
        self.setWindowTitle('Timetable')
        self.setWindowIcon(QIcon('icon.png'))
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    schedule = [['Spanish', 'Spanish', 'Music', 'Music', 'English Literature', 'English Literature', 'History', 'History'],
                ...]
    today = date.datetime.today().weekday()
    ex = Timetable(schedule, today)
    ex.show()
    sys.exit(app.exec_())
    #created with PyQt5 using Python 3.5

Note that I also renamed some of your variables (there is now a today and a today_header and a tomorrow and tomorrow_header.


Arrange three integers from least to greatest

Input/output

You need to output a space between the numbers, otherwise they will look like one long number.  It's also customary to finish the output with a newline.

You should verify that you actually received three inputs successfully.

Lint

using namespace std; is considered a bad habit.

Your code would be more readable if you put some spaces with your operators.  For example, cin>>x>>y>>z; would look better as std::cin >> x >> y >> z;

Only initialize what you need to initialize.  For example, int x, y, z; is enough — in fact it's safer, because the compiler can then warn you if you subsequently use one of those variables without assigning a value.

Strategy

You've basically manually written out all the possible comparisons that a sorting algorithm would do, the long way.  I suggest the following short solution (which doesn't generalize beyond three numbers).

#include <algorithm>
#include <iostream>

int main()
{
    int x, y, z;
    std::cout << "Enter three integers to be arranged from least to greatest.\n";
    if (!(std::cin >> x >> y >> z))
    {
        std::cerr << "Error in input.\n";
        return 1;
    }

    int first = std::min({x, y, z});
    int third = std::max({x, y, z});

    // Toss x, y, z into a bag, and take out the min and max.
    // What's left is the middle number.
    int second = x ^ y ^ z ^ first ^ third;

    std::cout << first << ' ' << second << ' ' << third << std::endl;
}

Note that std::min({x, y, z}) uses C++11.  For older compilers, you can use std::min(x, std::min(y, z)).


Assigning a numerical value to each alphabet in corresponding order and then summing any inputted word

Honestly, the initial words_to_marks function is full of "anti-patterns/bad smells".

When reviewing in steps:

instead of iterating over string.ascii_lowercase and generating/filling a dictionary of letter indices on each function call with:

for index, letters in enumerate(string.ascii_lowercase, 1):     # creates the dictionary
    values[letters] = index

create a predefined top-level dict lowercase_indices_map at once:

import string

lowercase_indices_map = {c:i for i, c in enumerate(string.ascii_lowercase, 1)}

converting each letter of the word with:

for letter in s:
   letter_lower = letter.lower

is completely redundant as the whole word can be lowercased at once s = s.lower()
and the "magic" like:

values_of_words.append(sum(final))  # sums all the values in the list
submit = str(values_of_words)       # converts into string so I can remove the brackets around the list
return submit[1:-1]

is just an unnecessary thing that you should avoid doing in future. The sum of letter indices is simply calculated with a single sum(...) call.

The whole idea fits in few lines of code:

import string

lowercase_indices_map = {c:i for i, c in enumerate(string.ascii_lowercase, 1)}

def sum_letters_indices(word):
    word = word.lower()
    return sum(lowercase_indices_map[char] for char in word)

Sample usage:

print(sum_letters_indices("hello"))    # 52
print(sum_letters_indices("friends"))  # 75


Using different instances of an object to lock threads

Your code would do just fine, in terms of functionality.

However, note that such design holds as long as everybody knows that they should acquire the lock before performing any process on the person object.

Perhaps you should consider re-design your data objects (such as the person class) so that there's an explicit method for any update process. Perhaps something like BeginEdit and EndEdit, or, even better, a method that returns an IDisposable object that acquires the lock and releases it in its Dispose implementation. Example:

public class Person {
    public IDisposable AcquireLock() {
        // ...
    }

    // ...
}

// usage:
var aPerson = GetPerson(1234);
using (aPerson.AcquireLock()) {
    aPerson.LastName = "abcd";
    SavePerson(aPerson);
    // ...
}

This way the locking is made more explicit.

Just a suggestion, though...


I suggest the following:

public class ErrorController : Controller
{
    private const string RedirectLoopCounterName = "RedirectLoopCounter";
    private const int MaxRedirectLoopCount = 1;

    private int RedirectLoopCounter
    {
        get { return ((int?)TempData.Peek(RedirectLoopCounterName)) ?? 0; }
        set { TempData[RedirectLoopCounterName] = value; }
    }

    private int IncreaseRedirectLoopCounter()
    {
        return ++RedirectLoopCounter;
    }

    [ActionName("500")]
    public ActionResult InternalServerError(string aspxerrorpath = null)
    {
        var isRedirectLoop = IncreaseRedirectLoopCounter() > MaxRedirectLoopCount;
        if(isRedirectLoop)
        {
            return Redirect("/GeneralError.htm");
        }

        // Check if user is admin or running locally and display error if so
    }
}

Create a constant for the counter's name as already mentioned by @BCdotWEB
Create a property for getting and setting its value
Create a method for actually increasing the counters value
Additionaly you could replace the 1 by a constant
Finally you can replace the condition by a helper variable to document it better
I would also invert the if


You can do it in an "one-liner". Although one-liners are frequently associated with less readability, I honestly believe this is not the case. Something like this would work:

I18n.locale = params[:locale] ||
              request.preferred_language_from(AVAILABLE_LANGUAGES) ||
              I18n.default_locale

I see a few advantages in this solution:

Your code will be a bit cleaner, since you can collapse 9 lines of code filled with if/else conditions into 3 (or 1, if you don't break the line);
You won't need to allocate preferred_language in case params[:locale] is nil;
And the biggest advantage of them all: clarity. The precedence of the options is much more explicit.


Insert k copies of each element in ArrayList

You have double the indenting that you should inside your method.

Rather than calling s.get(i) every time, store it in a variable and use from that instead. Incidentally, this means that you can use an advanced for instead of a simple one.

I'd recommend renaming limit to originalSize, so that it's clear what it is.

s isn't descriptive. Why not call it source? Ditto with k -- why not call it copies?

Why are you making it specific to Strings, when it's almost just a find-and-replace away from being a generic method? If you make it generic, it'll work with any type, not just the one.

Aside from that, there's not much. Your code is pretty short, and there isn't much to say. Here's your code with these tips applied:

public static <E> void copyStrings(ArrayList<E> source, int copies) {
    if (copies <= 0) {
        source.clear();
    } else {
        int limit = source.size();
        for(E element : source) {
            for( int j = 0; j < copies; j++) {
                source.add(element);
            }
        }
        for( int i = 0; i < limit; i++) {
            source.remove(0);
        }
    }
}


Web scraper for Football (Soccer) data with BeautifulSoup and Requests

Major Issues

Here are some major things that require attention:

indentation (PEP8 reference). Use 4 spaces for indentation
avoid using global variables. (Why are global variables evil?). If you need to share variables between functions of your program, you can pass them as arguments, or define these functions as method of a "scraper" class which would share instance variables
variable naming. The code is much more often read than written - by choosing descriptive variable names, you are improving the readability of your program. Variables like s, ext, t, z, l, l1 etc were bad choices

Next things to address

remove redundant parenthesis. For example, if (ext[0] == "/"): can become if ext[0] == "/":
address other PEP8 code style violations, in particular:

grouping imports
the use of whitespaces around operators in expressions
blank lines between top-level functions

use if __name__ == '__main__': for the main execution block of the program
since base_url and ligen are constants, name them properly

Web-scraping improvements

since you are sending requests to the same domain multiple times, you can improve on the performance by using session.get() instead of a requests.get() where session is initialized as session = requests.Session() once and re-used (reference)
you can use SoupStrainer to let BeautifulSoup HTML-parse only the relevant part of the page
think of using CSS selectors instead of find() and find_all(). For instance, soup.find("select", attrs={"name": "saison"}) can become soup.select_one("select[name=saison]"). It is not necessarily a better way to locate elements but it is quite handy to have it in your toolbox
have you tried to use pandas.read_html() to parse the table HTML block in the get_games() function? It might work to get the table in a dataframe(s) directly

Some simplified code constructs

here is a more concise and readable way to define seasons in the get_seasons() function using a list comprehension:

seasons = [
    [season.get_text(), season.get("value")]
    for season in soup.select("select[name=saison] option")
]

Overall, though, I think it would be a good idea for this code to go through several rounds of code reviews.

Also, consider using a linting tool like flake8 or pylint, or/and a modern smart IDE like PyCharm - would help to catch a ot of stylistic and other mistakes.


Looking for a better solution than a bunch of switch statements in my JavaScript

Use an object, with the keys being the letters, and then you can just do:

function incCriteriaStats(exp) {
        if(exp in obj)
             obj[exp]++;
}


What happens if this is called by something that hasn't captured the object?

public void Release()
{
    lock (_lock)
        IsCaptured = false;
}

Honestly, I don't see what this is giving you that you don't get from:

Monitor.TryEnter(lockObj)

and

Monitor.Exit(lockObj);

Unless you want to release the capture from a different thread, in which case it seems like you're more likely to run into the 'Released by wrong thing` problem.

Why do you need to know if it's captured?  Try to capture the lock and if it fails, you know that it's captured... What purpose does the property really serve?

  The problem here comes when multiple of such object has to be captured at the beginning of method, then it will looks like dozens of nested if/try/finally

If you're going to be capturing groups of objects then you're going to need to be very careful about the order that you capture those objects in order to prevent deadlocks where one method performs:

Capture A, B, C

And another method performs

Capture C, A

One of the things you've indicated is that you don't like the idea of the nested try/finally blocks to ensure that all captured items are released.  You could consider writing some utility functions to help make this cleaner.  Something like this:

static bool TryCaptureAll(params Capturable[] capturables)
{
    List<Capturable> capturedItems = new List<Capturable>();

    foreach(var capturable in capturables)
    {
        if(!capturable.TryCapture())
        {
            // Failed to capture one of the items, release the ones
            // we did capture and return failure.
            foreach(var captured in capturedItems)
            {
                captured.Release();
            }
            return false;
        }

        capturedItems.Add(capturable);
    }

    return true;
}
static void ReleaseAll(params Capturable[] capturables)
{
    foreach (var capturable in capturables)
    {
        capturable.Release();
    }
}

Would allow you to lock and release groups of objects like this:

if (CaptureList.TryCaptureAll(a, b, c))
{
    try
    {
        a.SomeMethod();
        b.SomeMethod();
        c.SomeMethod();
    }
    finally
    {
        CaptureList.ReleaseAll(a, b, c);
    }
}


Feedback on a programming practice problem in C

Roughly 50% of all programming is about dealing with errors. You say your code works, but it doesn't handle errors and therefore doesn't work.

Example 1:

How many feet of steel was received today:  four

Program doesn't say "Error, try again". Instead it displays all prompts without waiting for any user input and exits.

Example 2:

How many feet of steel was received today:  3.7

Program doesn't say "Error, try again". Instead it displays all prompts without waiting for any user input and exits.

Example 3:

How many feet of steel was received today:  3 4

Program doesn't say "Error, try again". Instead it assumes 3 feet of steel; displays "How many ball bearings" and doesn't wait for user input and assumes 4 ball bearings.

Example 4:

Would you like to run the program again? ('1' for yes, '2' for no): yes

Program doesn't say "Error, try again". Instead it exits.

Example 5:

How many feet of steel was received today:               -99
How many ball bearings were received today:              -99
How many pounds of bronze was received today:            -99

Program decides you can make -89 bells and -198 whistles.

Example 6:

How many feet of steel was received today:               999999999999999999
How many ball bearings were received today:              999999999999999999
How many pounds of bronze was received today:            999999999999999999

Program decides you can make -1351471477 bells and -2147483648 whistles.

Example 7:

How many feet of steel was received today:               200
How many ball bearings were received today:              100

Program decides you can make 0 whistles. Note: unlike the previous examples, this is not a "failed to check for invalid input" problem.


Simplified board for X's and O's using Tkinter

Is it possible to have one listener for all the cells?

You still have to bind to each canvas but we can bind to one function that can handle all your conditions. The best way to do this is to put your canvas widgets into a list and then reference them by index.

  How could I avoid repeat so much code?

Its good to try and reduce your code. Try to keep it DRY (Don't Repeat Yourself) is something to strive for and in this case the bast way to do this is to build a single function that can handle all your conditions based on the event being passed and an index value.

Another helpful way to stay DRY is to know when to use a for loop to managed creations of widgets or variables needed. Here I have changed your code to use a for loop to build a list with your canvas widgets and apply the binds and pack all at once.

I have also added a check to see if something has already been written to your canvas so it cannot be overwritten.

By utilizing a list to and building our functionality around that list we can reduce the amount of code we need and at the same time make the boxes infantry scalable.

I have added a variable called np_tuple. All you have to do is change the numbers to change the size of your game.

I have combined all your code into one .py file but you can easily move your Tablero class back out.

from tkinter import *
import numpy as np

class Tablero:
    def __init__(self, np_tuple):
        self.tablero = np.zeros(np_tuple)

    def poner_ficha(self, x, y, tipo_ficha):
        if self.tablero[x][y] == 0:
            self.tablero[x][y] = tipo_ficha
            # print(self.tablero)

root = Tk()
clist = []
np_tuple = (3, 3)
juego = Tablero(np_tuple)

def create_circle(x, y, r, canvas_name):
    canvas_name.create_oval(x - r, y - r, x + r, y + r)

def click(event, xdex, ydex):
    if clist[xdex][ydex][1] == '':
        if event.num == 1:
            clist[xdex][ydex][1] = 'X'
            clist[xdex][ydex][0].create_line(0, 0, 50, 50)
            clist[xdex][ydex][0].create_line(0, 50, 50, 0)
            juego.poner_ficha(xdex, ydex, 1)

        else:
            clist[xdex][ydex][1] = 'O'
            create_circle(24, 24, 20, clist[xdex][ydex][0])
            juego.poner_ficha(xdex, ydex,  2)

box_frame = Frame(root)
box_frame.pack()

for x in range(np_tuple[0]):
    prep_list = []
    for y in range(np_tuple[1]):
        prep_list.append([Canvas(box_frame, width=50, height=50), ''])
        prep_list[y][0].create_line(50, 50, 0, 50)
        prep_list[y][0].create_line(50, 50, 50, 0)
        prep_list[y][0].bind("<Button-1>", lambda e, xdex=x, ydex=y: click(e, xdex, ydex))
        prep_list[y][0].bind("<Button-3>", lambda e, xdex=x, ydex=y: click(e, xdex, ydex))
        prep_list[y][0].grid(row=x, column=y)
    clist.append(prep_list)

root.mainloop()


DRY for rendering same header table for different content

You might try building a slightly more complex datastructure to be passed in.  If you built a list like:

violations = [ ("Resolved", resolved_violations),
               ("Open", unresolved_violations) ]

Then you could write a template like:

{% for vtype, vlist in violations %}
    {% if vlist %}

{{ vtype }} Violations

        #
        IDENTIFIER

        {% for violation in vlist %}

        {{ forloop.counter }}

            {{ violation.identifier }}

        {% endfor %}

    {% endif %}
{% endfor %}


Copying a file hash to clipboard without PowerShell

All zero-sized files will have the same checksum using the same given hash algorithm. Hence, use the following batch-script:

@ECHO OFF
SETLOCAL EnableExtensions
for /f %%G in ("%~1") do set "_len=%%~zG"
if %_len% EQU 0 (
  echo MD5 hash of %1
  echo D41D8CD98F00B204E9800998ECF8427E
  echo CertUtil bypassed for zero file size
  echo D41D8CD98F00B204E9800998ECF8427E|clip
) else (
  for /f "tokens=*" %%a in ('certutil -hashfile "%~1" MD5') do (
    echo %%a
    for /f "delims=" %%b in ('echo %%a^|findstr /r /i /x ^[0-9A-F]*[0-9A-F]$') do (
      if "%%b" neq "" echo %%b|clip
    )
  )
)
pause

Note that %%~zG expands %%G to size of file (read call /?).

if "%%b" neq "" echo %%b|clip seems to be superfluous then. Simple echo %%b|clip should suffice.

Sample output:

==> D:\bat\CodeReview\179105.bat out.txt
MD5 hash of out.txt
D41D8CD98F00B204E9800998ECF8427E
CertUtil bypassed for zero file size
Press any key to continue . . .

==> D:\bat\CodeReview\179105.bat D:\bat\CodeReview\179105.bat
MD5 hash of D:\bat\CodeReview\179105.bat:
c2a4cabffac79a26ee5ed7c97cefb44b
CertUtil: -hashfile command completed successfully.
Press any key to continue . . .

==>


To avoid repeating code, you could have used:

done <- FALSE
while(!done){
  done <- round(as.double(difftime(Sys.time(), t0, u = units))) >= interval
}

Note however that a for loop is quite taxing on your CPU. Instead, you should use the friendlier Sys.sleep function. It takes a number of seconds as input:

timer <- function(num_sec) {
   Sys.sleep(num_sec)
   if (require(beepr)) beep(2) else message("DONE!")
}

Notice how I improved your code regarding the use of require, since you had not accounted for the possibility that your user does not have the beepr package installed. If you want to make the beepr package a requirement, then calling library(beepr) is prefered to require(beepr), the blog here https://yihui.name/en/2014/07/library-vs-require/ offers a nice explanation.

If you absolutely want your function to allow to pass "minutes", "days", etc. (though I would stay away from it), you can do:

timer <- function(interval, units = c("secs", "mins", "hours", "days", "weeks")) {
   units <- match.arg(units)
   num_sec <- interval * switch(units, secs = 1, mins = 60, hours = 3600,
                                       days = 86400, weeks = 604800)
   Sys.sleep(num_sec)
   if (require(beepr)) beep(2) else message("DONE!")
}


Design/Architecture for MVC WinForms Dialog Control/Use

I am not sure what exactly do you archive with that architecture.
In the example code above, the controller doesn't have any logic - so you can just drop it and use the dialog directly.

However, if that is just an example and you add more logic to the controller lets take a short look to the following method:

public DialogResult ShowDialog(IWin32Window owner, IEnumerable<string> items)
{
    view.LoadItemList(items);
    using ((Form)view)
    {
        var result = ((Form)view).ShowDialog();
        Log.Trace($"SaveDialogController.ShowDialog(): " +
            "DialogResult.{result.ToString()} returned from view");
        return result;
    }
}

If the mehtod ShowDialog is called, the view (instance variable) will be disposed (because: using ((Form)view)) . If the method is called again, it works on a disposed view. If the controller will be disposed later, it tries to dispose the view again. So you dont need the using here.
If you cast your abstraction against the concrete class (((Form)view)), the abstraction is valueless because you can not mock it in unit tests. To avoid casting, add all needed methods (in that case ShowDialog) to your abstraction.
The instance variable view should be readonly because it is initialized once in constructor.


Simple JavaScript precondition checking implementation

function requires(conditions)
{
    for (var cond in arguments)

Don't use for-in. The problem with for-in is that it runs over prototype properties as well. You might loop through more properties than you expect. Either use a regular loop or convert your iterable into an actual array to access array method.

If you can write in ES6, you can use the rest operator. What it does is put the rest of the arguments into an array. Much like arguments but it's a real array. You have access to all array methods.

function requires(...args){
  args.forEach(...)

if (typeof cond !== "boolean") throw "Preconditions must be boolean expressions {" + cond + "}";
if (cond !== true) throw "Precondition failed {" + cond + "}";

The second condition is overly verbose. The first check weeds conds that are not boolean. Therefore, if it passes that part, cond is a boolean. That means you can simplify if (cond !== true) as if (!cond).

requires(
    typeof message === "string",
    typeof index === "number",
    index >= 0,
    index < message.length);

If you go on with this route of manual type checks, at least hide away the complexity by abstracting the checks away. The following would be more like it. Checks the arguments against the type, and in that order.

require(args, ['string', 'number']);

Additionally, the last 2 checks there are not type checks but more like app-specific logic. Your type checker should not concern itself with those anymore.

Runtime type checks should be avoided as they incur performance penalties as well as cause bloated code. Common practice is to offload this responsibility to development-time and/or build-time tools.

TypeScript and Flow are typed supersets of JS that will let you write in a typed language and whose compilers do type checks for you.

If you prefer vanilla JS, using an editor or IDE that utilizes JSDoc to do basic checks is also an option. I know Visual Studio's Intellisense or Intellij IDEA with the right plugins do this.


Improving readability and logic on "re-indexing" method

I have the following comments and recommendations:

The try/catch is too general: if anything goes wrong anywhere, you return false. This may mask errors. Catch more specific exceptions and narrow the scope of your try/catch to where you are okay with things going wrong. (If you don't EXPECT anything to ever go wrong in certain parts of the code, you probably want to "fail fast" and catch that exception at a higher level. This could hide lots of kinds of errors during dev/test.)
Name mismatch: requiredIndex does not match .SortOrder (I'm not saying they need to be same exact name, but these seem to describe different concepts to me)
Does .SortOrder need to be optional? Consider enforcing that it be set by changing the orginal OutputTemplatePage class to require it. Is it an enum? If so, perhaps the default value could be Default (as in "use the default sort order")
Name choice: Boolean boolHasBeenAdded might be better as Boolean pageHasBeenAdded (prefix notation has been out of vogue for years - since .NET, certainly). Also, I usually prefer language types (bool) to the .NET types, but that's just style/preference.
This block could go away if you invert the next conditional (since this block happens anyway at the end):

    if (items.Count() == 0)
    {
        Add(page);
        boolHasBeenAdded = true;
    }
    else

... to ...

        if (items.Count() != 0)

Consider moving the following code into a well-named helper method to make its intent more apparent:

            OutputTemplateRepository repo = new OutputTemplateRepository();
            OutputTemplatePage pg = repo.GetOutputTemplatePageById(template.Id);
            pg.SortOrder = ctr;
            repo.Save();

It is unclear to me what repo.Save() does - seems like it might have side-effects. All the more reason for prior suggestion.
Rename ctr to something more descriptive. Is it the sort index? Of course, setting SortOrder = ctr makes me wonder if SortOrder is named correctly. "Sort order" makes me thing of high level approach to sorting - like ascending vs. descending? Not clear. Makes it hard to grok.

[Edit] Actually, this largest problem might be that this code is not in the right class which might be the source of some awkwardness. Consider making ReIndexOutputTemplatePages a method on OutputTemplateRepository to clean up the code leading up to rep.Save.

Hope that helps!


Have a class that holds all the interfaces

Of corse you could do that, but I think that it breaks some ideas of dependency injection:

You can see the dependencies of a class by looking of the constrcutor (in your case, that is not possible)
You can test classes by mock the dependencies passed to the contructor (in your case you have to mock more because the dependencies are not evident)
You decople dependencies by passing only what you need (also not given in your case)

Instead of creating some granular dependencies of needed objects, your proposal is to create lots of dependencies from a container object that provides a set of objects. I see also the risk, that such a container object tends to grow so it makes the life easier (but conflicts with the idea behind DI).


I am not a big VB person, but I would think that if you give your class a Dispose method you should use it rather than setting it to nothing, I know this is kind of the same thing, but if you aren't going to use the Method don't create the method, it's extra stuff.  if you are going to use it in the future, comment to that effect.

'This Method is for future development
Private Sub Dispose()
End Sub

OR

'TODO: Implement!
Private Sub Dispose()
End Sub

my comment syntax is probably off a little bit.


In general, this looks ok, i.e. it works.
I will put some notes on the lines of your method and will provide my suggestion after this.

Spelling: procent is not an English word. Well, the compiler does not care, but the next programmer probably will.

public int discreteRV(final int[] values, final int[] procents) throws Exception {

To throw a exception of type Exception does not provide any help. The purpose of exceptions is to communicate errors.
Noone knows the type of error from Exception and can do anything about it. They should be avoided in throw statements.

    if (values == null || procents == null)
        throw new Exception("Input parameters are null");

While checking your contract is a good idea, you do not gain anything here.
Java will throw a Nullpointer error with nearly the exact same message anyway if you try to access them.
As long as there are no plans to do any special things, I would not waste lines on this.

    if (values.length != procents.length)
        throw new Exception("Input parameters length mismatch");

I would throw a runtime exception. IllegalArgumentException looks suitable here.

    int sumProcents = 0;
    for (final int procent : procents) {
        if (procent < 0)
            throw new Exception("Negative procents are not allowed");
        sumProcents += procent;
    }

For exception: same as above.
For check: This is not valid for all input.
Consider (and/or try:) final int[] procents = { 1234567890, 1234567890, 1825831616 };
If you want to check the input, check for both sides.

    if (sumProcents != 100)
        throw new Exception("Sum of procents is not 100");

For exception: same as above.

    final int rand = new Random().nextInt(100);

If you use this method frequently, make it static (and/or even ThreadLocalRandom)

    int left = 0, right = 0;
    for (int i = 0; i < procents.length; i++) {
        right += procents[i];
        if (rand >= left && rand < right)
            return values[i];
        left = right;
    }

The left check is not needed.
If you check for something in between, support your readers:
Instead of rand >= left && rand < right try to read left <= rand && rand < right

    throw new Exception("");

For exception: same as above. A IllegalStateException looks suitable here.

}

Suggestion:

public int discreteRV(final int[] values, final int[] percentages) {
    if (values.length != percentages.length)
        throw new IllegalArgumentException("values.length != percentages.length");

    int sumPercentages = 0;
    for (int i = 0; i < percentages.length; ++i) {
        if (percentages[i] < 0)
            throw new IllegalArgumentException("Negative percentages are not allowed: percentages[" + i + "] = " + percentages[i]);
        sumPercentages += percentages[i];
        if (sumPercentages > 100)
            throw new IllegalArgumentException("Sum > 100");
    }

    if (sumPercentages != 100)
        throw new IllegalArgumentException("Sum of percentages is not 100");

    final int randomIntUpTo100 = random.nextInt(100);
    int threshold = 0;
    for (int i = 0; i < percentages.length; i++) {
        threshold += percentages[i];
        if (randomIntUpTo100 < threshold)
            return values[i];
    }
    throw new IllegalStateException("No value found. rand:" + randomIntUpTo100);
}

More ideas:
The arguments (arrays) could be replaced by an Object. This could make the handling easier. Depends on the use case.
The two loops could be combined into one loop. You will loose the check for sum == 100 then.


Use comments to guide the reader through the major phases of the algorithm.
Imagine returning to this code to fix a bug or add a feature. Simple comments
can help you zero in on the needed location to do that work.
Centralize the creation of literal parameters (see space, wood, branch).
This makes it easy to quickly change stylistic details.
Let you code breath: add space around operators. This can help a lot with
readability and thus maintainability.
As a general rule (there are exceptions), don't reuse variable names for
different concepts. The first part of the function uses fir for uncentered
rows. Then you replace that fir with one having centered rows. Prioritize
code clarity by using different variable names. The same point can be made when
you create the trunk: do it in another variable.
Create convenience variables to eliminate repeated calculations, as shown in
max_width.
Invest more in laying out the code for readability, as shown in the list
comprehenion to create centered.
Take advantage of floor-division if you want an integer result (//).
When iterating i and j are conventional variable names when dealing with
indexes. Your code follows that convention. But it also uses i when iterating
over other things (like the rows). Less ambiguous is a short name that has
a conceptual connection to the thing you are iterating over: for example, if
iterating over rows, use r as the loop variable.
Separate computation from reporting. This is better for debugging and
automated testing. The firtree() function is where computation happens.
Do the printing at a higher level in the call stack.
Put orchestration code inside a function, as shown in main(). Also
better for testing and debugging.
Here's your code with those suggestions applied. Note this this edit does not
fix the bug in your code related to the width of the next top section (width
of next section is supposed to be width of previous section minus 2).
import sys

def main(args):
    size = int(args[0])
    fir = firtree(size)
    for row in fir:
        print(row)

def firtree(tree_size):
    # Setup.
    width = 1
    minus = 2
    foot_width = 1
    space = ' '
    wood = '|'
    branch = '*'

    # Create the top of the tree, first as uncentered rows.
    rows = []
    for i in range(1, tree_size + 1):
        for j in range(1, i + 4):
            rows.append(branch * width)
            width = width + 2
        if i % 2 == 0:
            minus += 1
        width -= minus
        if i % 2 == 0:
            foot_width += 2

    # Convert the rows to centered rows.
    max_width = len(rows[-1])
    centered = [
        space * (max_width // 2 - len(r) // 2) + r
        for r in rows
    ]

    # Build the trunk.
    trunk = [
        space * int(max_width / 2 - foot_width // 2) + wood * foot_width
        for i in range(1, tree_size + 1)
    ]

    # Profit.
    return centered + trunk

if __name__ == '__main__':
    main(sys.argv[1:])

But those types of suggestions only help so much. At the end of the day, this
kind of code is annoying because its so tediously algorithmic: too much math,
too much fine-grained list-indexing, etc. An easier way to solve the problem
can be found taking fuller advantage of an insight in your current code: focus
first on making uncentered rows, like this:
*
***
*****
*******
*******
*********
***********
*************
***************
|||
|||

Then let Python format-strings do all of the grubby work of centering the rows.
We can also improve code readability a bit more by delegating sub-calculations
to helper functions, each doing a very small thing. That approach keeps
the primary function fairly readable.
def firtree(tree_size):
    # Setup.
    wood = '|'
    branch = '*'

    # Rows for the tree branches, which are organized in sections.
    top = []
    row_len = 1
    for n_rows in range(4, 4 + tree_size):
        sect, row_len = section(n_rows, row_len, branch)
        top.extend(sect)

    # Rows for the tree trunk.
    is_even = not tree_size % 2
    width = tree_size + is_even
    height = tree_size
    trunk = [wood * width for _ in range(height)]

    # Return those rows, but centered.
    return centered(top + trunk)

def section(n_rows, init_len, marker):
    # Returns a (ROWS, NEXT_LEN) tuple for a tree section.
    # Handling the next-length calculation here, where it happens to be
    # easy to do, helps keep the primary function simpler.
    end_len = init_len + n_rows * 2
    next_len = end_len - 4
    rows = [marker * n for n in range(init_len, end_len, 2)]
    return (rows, next_len)

def centered(rows):
    # Takes rows. Returns centered rows.
    fmt = '{:^{}}'
    width = max(len(r) for r in rows)
    return [fmt.format(r, width) for r in rows]


Implementation of tree with different node types and faux-polymorphism in C

Remarks for beginners:

Never hide a pointer behind a typedef! Never! It makes the code confusing and very hard to read and maintain.
You can't unfortunately use a generic Node pointer like in your code, because this isn't well-defined by the language. There are ways around it, but they are a bit controversial (see advanced reply below).
Generally, when doing any kind of polymorphism, you might want to have an "abstract base class". In this case it would have been NodeType, but it should be a struct of its own and each inherited class should contain an instance of the base class as first member. Not a pointer to it.
Avoid calling functions in the controlling statement of a for loop like you do in for (size_t i = 0; i < get_num_children(tree); i++). This will often produce needlessly slow code. Instead call the function once before the loop, then store the result in a variable.

Remarks for veterans (beginners ignore):

One advanced trick which is supposedly fully supported by the standard (but might have diverse quality of implementation on different compilers) is the "union common initial sequence" trick.

There's a rule stating that if you expose a union containing all those structs to the same translation unit as where those structs are used, type punning between the structs is well-defined. In your case something like this:

union type_punning
{
  struct VariableNode_ a;
  struct ConstantNode_ b;
  struct OperatorNode_ c;
};

This union just needs to sit there; you don't need to use it, or even show it to the caller. This tells the compiler that since these struct share a common initial sequence, the NodeType member, we can type pun between them and it is well-defined, as long as we only access shared members of that initial sequence.

Meaning that suddenly we can do this:

void func (struct VariableNode_* vn)
{
  if(vn->type == NTYPE_CONSTANT)
  {
    struct ConstantNode_* cn = (struct ConstantNode_*)vn;
    cn->const_value = something; // well-defined!
  }
}

There's also exceptions to the strict aliasing rule allowing this use.

Source: C17 6.5.2.3

  One special guarantee is made in order to simplify the use of unions: if a union contains
  several structures that share a common initial sequence (see below), and if the union
  object currently contains one of these structures, it is permitted to inspect the common
  initial part of any of them anywhere that a declaration of the completed type of the union
  is visible. Two structures share a common initial sequence if corresponding members
  have compatible types (and, for bit-fields, the same widths) for a sequence of one or more
  initial members.


A few minor notes:

    Have the function StringReduction(str)

strictly speaking, the parameter name is different:

function StringReduction(s)

:-)

var original, key;

I'd put the variable declarations to separate lines. From Code Complete 2nd Edition, p759:

  With statements on their own lines, the code reads from top to bottom, instead
  of top to bottom and left to right. When you’re looking for a specific line of code,
  your eye should be able to follow the left margin of the code. It shouldn’t have to
  dip into each and every line just because a single line might contain two statements.

It could prevent some diff/merge conflicts (you modify the first variable, a coworker the second one at the same time).
key could be declared inside the while loop.

JavaScript variables declare outside or inside loop?
Effective Java, Second Edition, Item 45: Minimize the scope of local variables

As @konijn pointed out in his comment, that may confuse maintainers. Anyway, extracting it out into a separate function solves the issue (#6).
The name original could be lastString or lastValue since it's not the original string, it's the result of the last loop.
Indentation is not consistent. Most of the places it's two spaces but the while loop is only one space indented, the body of the for loop has three spaces.
I'd extract out the for loop to a string translate(string, replacements) function for better readability.


A quick look shows the only difference with your FiniteAutomaton types is that the transition either takes a string or string List.  So genericize it!

type FiniteAutomaton<'a> = {
    InitialState: string
    FinalStates: Set<string>
    Transitions: Map<string * char, 'a>
}
type DeterministicFiniteAutomaton = FiniteAutomaton<string>
type NondeterministicFiniteAutomaton = FiniteAutomaton<string List>

The rest pretty much falls in place:

let private nextState symbol state fa =
    fa.Transitions |> Map.tryFind (state, symbol)

let rec private haltState (input:string) index state fa =
    match index with
    | i when i = input.Length -> state
    | _ ->
        match nextState input.[index] state fa with
        | None -> null
        | Some state -> haltState input (index+1) state fa

let accepts input fa =
    fa.FinalStates |> Set.contains (haltState input 0 fa.InitialState fa)

I try to remove as much type annotations as possible.  Just let F#'s type inference do its magic. Also, it was convenient to pass around the fa instead of fa.Transitions.  Finally, the code compiles, but I have no idea if it works.

Edit:

If you want to be totaly generic you can do this:

type FiniteAutomaton<'STATE, 'TOKEN when 'STATE:comparison and 'TOKEN:comparison> = {
    InitialState: 'STATE
    FinalStates: Set<'STATE>
    Transitions: Map<'STATE * 'TOKEN, 'STATE List>
}

Also 'STATE should be a 'TOKEN List.


You have a lot of undescriptive magic numbers and code repetition whilst retrieving the contents of a field. You could eliminate the repetition and make those numbers a little more meaningful by introducing a single method:
protected string GetFieldContent(string content, string field,
    int padding, int length)
{
    var location = content.indexOf(field);
    padding += field.Length;

    var fieldVal = content.Substring(location + padding, length);
    fieldVal = fieldVal.Trim();
    return fieldVal;
}

Use it like so:
internal string GetGameMaximumPlayers(string content)
{
    var maxPlayers = GetFieldContent(content, "maxNumPlayers", 3, 2);
    return maxPlayers;
}

Something to note here is the padding value has changed. You no longer need to include the length of the field name itself and can just describe the number of junk characters afterwards.
Padding length
Upon examining your code I noticed one peculiarity - the fields have inconsistent, magical padding lengths:

gameID padding: 2
gameLength padding: 3
mapId padding: 3
maxNumPlayers padding: 3
creationTime padding: 2

As a symptom of these being magic numbers I have no idea why this is the case. This is one of the many reasons to avoid magic numbers like the plague: it's difficult to understand their meaning. I'll trust you to evaluate whether varying padding lengths is necessary, or whether you can just assume a constant padding for all fields.
If we can assume a constant padding amount for all fields then we can change the code further a little bit to make your life easier. There are two steps to this change.
First, give your LogParser class a private field:
private const var defaultPadding = 2
Second, GetFieldContent can be refactored to produce this:
protected string GetFieldContent(string content, string field, int length)
{
    var location = content.indexOf(field);
    var padding = defaultPadding + field.Length;

    var fieldVal = content.Substring(location + padding, length);
    fieldVal = fieldVal.Trim();
    return fieldVal;
}

Then getting the contents of a field becomes simpler:
var maxPlayers = GetFieldContent(content, "maxNumPlayers", 2);


Comma Code - Automate the Boring Stuff with Python

You've got an odd bug with your code.

Given the 8th menu item from the greasy spoon café:

spam = ["Spam", "Spam", "Spam", "egg", "Spam"]

You will get:

  and Spam
  and Spam
  and Spam
  egg, and Spam

since you are not testing whether you are at the last item in your list, but rather if the current item is the same as the last item in the list.

Testing for a length 1 list should not be done inside the loop of all items; it should be done exactly once, outside the loop.  Ie (but still with the above bug):

if len(list) == 1:    # Test outside of loop
   print(list[0])
else:
    for item in list:
        if item != list[-1]:
            print(item + ', ', end='')
        else:
            print('and ' + list[-1])

Want you really want to do is print all but the last item in the list one way, and the last item a different way:

# If there are more than 1 items in the list...
if len(list) > 1:

    # Print all but the last item, with a comma & space after each
    for item in list[:-1]:
        print(item + ', ', end='')

    # with "and " printed at the very end, just before ...
    print("and ", end='')

# print the last (or only) item in the list.
print(list[-1])

although this still assumes at least one item in the list.

Alternately, you could join() all but the last item, and then add ", and " along with the final item.

msg = list[-1]
if len(list) > 1:
    msg = ", ".join(list[:-1]) + ", and " + msg
print(msg)

You are doing import sys, but not using sys anywhere.  You can remove the import.


Looking at your first code example, it's somewhat sensible. The synchronized method creates a "happens before" memory barrier, and as a result, all threads see the same version of the data at that point in the code.

There is a vulnerability in that code, though. The synchronized method means that your lock is publicly accessible. Anyone can synchronize on your wrapper, and create a conflicting lock, perhaps creating a "denial of service" situation, where you can never get in to your method because some other thread has your instance locked. This is rare, but it does happen in some programs.

About your second block of code.... this is just plain broken from a multi-threaded perspective:

public Option<T> nextNonBlocking() {
    try {
         return Option.of(iter.next());
    } catch (NoSuchElementException nsee) {
        if(iter.hasNext()) {
            // Oops, exception was thrown for reason other than end-of-iterator.
            // Rethrow that exception.
            throw nsee;
        }
    }
    return Option.none();
}

That code will seldom produce what you expect in an actual multi-threaded situation. For a start, it reverses the logic of the hasNext() and next() calls. You should call hasNext first. Secondly, in an actual multi-core, especially in a multi-memory-controller computer (multi-socket), you will run in to stale memory accesses. It is possible for all threads to iterate through all members of the iterator, as they will all be seeing different "caches" of the iterator.

The second block is just "plain wrong".

As an aside, Java 8 now has an Optional class. You should use it.


Polyglot function to sum all the numbers in an array in Javascript and PHP

Interesting question.

You are trying to avoid poisoning the window object.. Now consider writing several functions like this. You just moved the poisoning from window to $vars. I would not do this because it reduces readability a lot.

$vars['args'][$vars['i']] should be in a helper variable to increase readability. (Regardless of whether you keep $vars)

I would have put this in a function called get_array_length:
$javascript ? $vars['args'][$vars['i']].length : count($vars['args'][$vars['i']]);

Then I would change the top to

if( $javascript = '\0' == "\0" )
{
    $vars = new Object();
    $vars['args'] = arguments;
}
else
{
    $vars = Array();
    $vars['args'] = func_get_args();
}
$vars['l'] = get_array_length($vars['args'])

Still, all in all because you need to maintain compatibility this is okay as an art excercise but this is by no means (because of  it's nature) production or high quality code.


Your j and i variables are pretty plain and won't make this code fun to maintain (especially if it were a big block of code)

You should use more descriptive variables.

you should create a collection that groups the Jobs by their Industry and then select from that collection the industry name and the count of jobs in the collection with that name.

from job in dbConnection.jobs
join industry in dbConnection.industries on job.industryId equals industry.id
group new {industry, job} by industry.Name
into jobsByIndustry

select new {
    industryName = jobsByIndustry.Key.Name,
    jobscount = jobsByIndustry.Count()
}


Replacing all occurrences of a substring in a string without using regex

Using a StringBuilder should always be your preferred choice when doing String manipulation. It does not always make sense, but almost always.

Additionally, indexOf takes a 'from' location, and it makes the whole thing easier.... Convert both inputs to lower-case, then do the matching using the lower-case versions, but the substrings using the unknown-case.

The complicated assign-in-where-condition logic makes the loop conditions easier, but you do need to understand what this does:

while ((find = lcbase.indexOf(lcremove, previous)) >= 0) {

it searches for thelower-case remove from the previous position, saves the value to find, and checks that the result is 'positive'.... all in the condition of a while loop.

The full code is:

public static String withoutString(String base, String remove) {

    final String lcbase = base.toLowerCase();
    final String lcremove = remove.toLowerCase();
    int find = 0;
    int previous = 0;
    StringBuilder result = new StringBuilder(base.length());
    while ((find = lcbase.indexOf(lcremove, previous)) >= 0) {
        result.append(base.substring(previous, find));
        previous = find + remove.length();
    }
    result.append(base.substring(previous));
    return result.toString();

}

See this running inideone


Loose string matching for words in postal addresses

You'd better use another strategy:

Find a table of all usual abbreviations used in postal addresses.
Create a new column normalized_street in your original dataframe by replacing all occurrences of abbreviations in column Street by the corresponding full words.
Perform an exact self-join on your original dataframe, by Zip and normalized_street.

Why I think it's better:

It will allow you to avoid false positives like cat street / catfish street
The exact self-join will be very efficient
Your code will be simpler, cleaner, and entirely vectorized

There are lots of things to say about your current code. I'll just point out a few mistakes so that you can avoid them next time:

matched is not initialized
as.vector(props[props$Zip == postal_code,]["Street"]) can be written in a simpler way: props[props$Zip == postal_code, "Street"]
Since streets is a vector, you get its length using length(streets)
For the same reason, you have to use streets[i] instead of streets[[1]][i]
You should use grepl() instead of any(grep())


#define or NSString * const - Benefits and drawbacks of string literal constant syntax?

Actually, they are completely equal (obviously sans the extern keyword on the constant define).  When literal strings are declared @"", the compiler expands them out to a compile-time constant expression, which looks familiar to us all: (static) NSString *const; -albeit with a lot more compiler magic thrown in.

Nearly the same process occurs with macros, but with one extra step: replacement.  Macros are placeholders, which the compiler replaces with the value you #define at compile-time, which is why CLANG can show you errors and warnings.

Where the difference lies is how much work the compiler has to do to replace your abstractions, not in the "memory overhead" they will incur (which means there is absolutely no speed or performance to squeeze out).  Besides, NSString* is a brilliant class cluster that's been optimized over the years, especially with literal constants, where a sort of caching occurs in the binary itself.  That way, literals used over and over again don't get reallocated over and over again.  Though, to make one thing perfectly clear: #define'd literals do NOT reduce memory overhead!


Custom strcat() with different arguments

char* cat(char *dest, char *a, char*b)

Interface critique: You should have the caller specify a maximum size for the destination buffer, and error out when there is not enough space.  The mark of a good C programmer is to create interfaces which make this sort of condition unambiguous, rather than blasting away on the buffer, potentially past the allocation size.

for(i = 0; i < len_a; i++)
{
    dest[i] = a[i];
}

Strictly speaking this is fine, but it is rather un-C-like.  I would prefer:

while (*a)
   *dest++ = *a++;

With this you do not need to call strlen, either.

Assuming you added the parameter you should add in my interface critique (let's call the new parameter destsz), you could make sure you don't write more than this size with something like:

int cat(char *dest, size_t destsz, const char *a, const char *b)
{
    while (*a && destsz)
    {
       *dest++ = *a++;
       --destsz;
    }

    while (*b && destsz)
    {
       *dest++ = *b++;
       --destsz;
    }

    if (!destsz)
       return -1; // ran out of buffer; error condition

    *dest = 0;   // we have space, so write NUL
    return 0;
}


this.async() tells grunt that you're doing something async and that it should wait until you call the done method. Usually it just goes to the next grunt task when the execution is done. Since you're using the async module you can call the done method in the third argument to async.eachLimit which is supposed to be a function that is called when all the work is done.

// tell grunt we're doing something async
var done = this.async();

async.eachLimit(['unicorn', 'rainbows'], 10, function(file, cb) {
    // do something async
    cb(); // tell `async` we're done doing work for this item
}, function (err) { // called when all the items have called their `cb()`
    if (err) {
        grunt.warn(err);
    }

    // all the items are done, let's tell grunt we are done
    done();
});


Find numbers with same number of divisors

You are not interested in the divisors themselves, only how many there are.
This can be calculated if the prime factors are known. For example, 12 has two 2' s and one 3 (12 = 2*2*3). The divisors are the product of 0,1 or 2 2's and 0 or 1 3's. So six divisors. The primes themselves are irrelevant, what matters is how many of each there are.

If only Ruby shipped with a method to do this prime division...

require 'prime' # delivers the prime_division method

class Integer
  def tau
    self.prime_division.map(&:last).inject(1){|prod,i| prod *= i+1}
  end
end

def count_pairsInt(diff,  nMax )
  (1..nMax-diff).count{|n| n.tau == (n+diff).tau}
end

Note: Probably this can be faster by memoizing (storing) the last diff tau (divisor count) calculations, to avoid calculating them twice.


Decode string with hex character codes to UTF-8 characters

Are you willing to use % instead of =?

If so Uri.UnescapeDataString shall be sufficient. if not you can always Replace("=", "%") and use UnescapeDataString anyway.

Uri.UnescapeDataString("Test =64 =C2=AE =E1=A6=92 test".Replace("=", "%"))
//Test d ® ᦒ test


Implementing a fast 'split' function on a stream of characters in Java

There are more-sophisticated algorithms you can use, depending on the input and the search string. Even keeping the "one character at a time" interface though, there are optimizations to the implementation. Someone linked to KMP in a comment to your question - that's a good way to go if you can do some initial setup and buffer an arbitrary amount of the incoming stream.

I think you're on the right track with a state machine, but the implementation in addChar2 looks kind of heavyweight, with the MutableInteger class and a linked list, and an iterator-driven loop, and all. If you want this to be fast, you'll likely want to use primitive types (ints and arrays of ints) rather than OO wrappers around the primitive types.


Use English language for naming. .NET uses English for naming. You have mix of languages, and code looks like obfuscated for those who don't speak German.
Use descriptive names. I don't know German, but wvl, wek1, wek2 is definitely not very descriptive.
You have mix of presentation-related and data access code. You should split this code.

So, the first part is your controller code. It should look like technical specification when you read it. Let's try to do that

var methods = GetMethods(selectedGroupId, model.selectedParameterItem);
var model = ConvertMethodsToModel(methods);
return View(model);

Pretty clean. Now lets think about GetMethods method. It's purpose is returning some methods depending on what was found in methods group and parameter methods. Btw it can be method of another class (e.g. some service)

private IEnumerable<Method> GetMethods(int groupId, IEnumerable<int> parameterIds)
{
   var none = Enumerable.Empty<Method>();
   var groupMethods = (groupId == 0) ? none : GetMethodsByGroup(groupId);
   var parameterMethods = (parameterIds == null) ? none : GetParameterMethods(parametrIds);

   if (!parameterMethods.Any())
       return groupMethods;

   if (!groupMethods.Any())
       return parameterMethods;

   var parameterMethodsFromGroup =
        from pm in parameterMethods
        join gm in groupMethods on pm.Id equals gm.Id
        select pm;

   return parameterMethodsFromGroup;
}

And last part - those GetMethodsByGroup and GetParameterMethods (which could be moved to corresponding repositories):

private IEnumerable<Method> GetMethodsByGroup(int groupId)
{
    return db.Methods.Where(m => m.MethodGroupID == groupId).ToList();
}

Getting parameter methods:

private IEnumerable<Method> GetParameterMethods(IEnumerable<int> parameterIds)
{
    var parameterMethods = db.ParametersMethods.Where(pm => parameterIds.Contains(pm.ID));
    return methodlogicclass.GetMethodFromParameters(parameterMethodss).ToList();
}


Producer consumer with threads and using boost ring buffer

/* can we do better than this? */

In a circular buffer context, the standard way to avoid busy waiting is to have two semaphores. First to block a producer when a buffer is full, and second to block a consumer when the buffer is empty. Once a process passes its semaphore, and does its job, it should signal the peer.

The circular buffer is good when the consumer is only sometimes late and you cannot afford loosing data. In your situation it looks like a wrong solution: the producer becomes throttled by the rate of consumption, and the consumer is a presented with the stale data.

A typical answer is to let the producer run at full speed, and triple-buffer the production (at least, it guarantees that the consumer would get the most recently produced data). Please forgive the shameless self promotion.


Converting from Celsius to Fahrenheit and vice versa

I'm not excited about the repetition in this sequence:

 if(type!='c' && type!='C' && type!='f' && type!='F')
    {
         System.out.println("Error! You've entered an invalid conversion type!");
         System.out.println("Please enter a valid selection (Type C for celsius and F for fahrenheit");
         type = scan.next().charAt(0);
    }
 if (type == 'F' || type =='f')
    {
         result = fahrenheitToCelsius(degree);
         System.out.println("The conversion of "+ degree+"°F "+ "to Celsius is: " + result + "°C");

    }
 if (type == 'C' || type =='c')
    {
         result = celsiusToFahrenheit(degree);
         System.out.println("The conversion of "+ degree+"°C "+ "to Fahrenheit is: " + result + "°F");
    }

I think I'd prefer:

if (type == 'c' || type == 'C')
     // ...
else if (type == 'f' || type == 'F')
     // ...
else
    // Error

Although it conflicts somewhat with the preceding, I'm also less than excited about your error handling. You check for a valid input ([cCfF]), and get the next character of input if the first is invalid, but then you don't check whether that's valid or not. I'd rather do something like:

system.out.println("Please enter the conversion (C or F)");
do {
    type = scan.next().charAt(0);
} while (type != 'c' && type != 'C' && type != 'f' && type != 'F');

I'd also consider using a case statement instead of if statements:

switch (type) {
    case 'F':
    case 'f':
        result = fahrenheitToCelsius(degree);
        break;
    case 'c':
    case 'C':
         result = celsiusToFahrenheit(degree);
         break;
    default:
         // handle error
}

I'm also a little less than excited about the wording you used. It's not immediately apparent (at least to me) that: For Celsius, type 'C'. For Fahrenheit, type 'F' means that "C" of "F" designates the type of the input rather than the type of the intended result.

If at all possible, I'd prefer to support command line input. Something like "convert 10c" seems a lot easier to use (and script, etc.) than having to read and respond to a couple of prompts to tell it what I want.


Return or Output

I feel like FillKnapsack should either (a) simply tell you the max value or (b) give you the items that it used. Right now, you're returning (a) and logging, incompletely, (b). (Incomplete because if you use a fractional amount of an item, that's not indicated).

I suggest you pick one or the other. If the former, basically just drop the couts. If the latter, you'll want to return something like a:

std::vector<std::pair<Item, double>>

or:

struct ItemWithFraction {
    Item item;
    double fraction;
};
std::vector<ItemWithFraction>

Avoid single-letter variables

What is c? What is v?

Move the break into the branch

We have two cases per item: either we can fit the whole item and have room to spare, or we can't. If we can't, then we break. So that can become:

for (const auto& item : Items) {
    if (capacity + item.size < MaxCap) {
        value += item.value;
        capacity += item.size;
    }
    else {
        // last little bit left
        value += (MaxCap - capacity) / item.size * item.value;
        break;
    }
}
return value;

Don't need to assign capacity in the else case either.

Take items by copy

The idea of the algorithm suggests that given this set of items, find me a value. It doesn't suggest to me that you should reorder the items I pass in just because that happens to make it easier to solve the problem. To avoid being destructive, I'd write the signature as:

uint32_t FillKnapsack(std::vector<Item> Items, const uint32_t MaxCap)

If the user doesn't care, they can always move() the items in and avoid the copy.

Naming

Typically, UpperCase naming are used for classes (e.g. Item). Functions and variables are typically either camelCase (with the first letter lower) or snake_case. So I'd prefer

fillKnapsack(std::vector<Item> items, const uint32_t maxCapacity);

and

fill_knapsack(std::vector<Item> items, const uint32_t max_capacity);

to what you have.


Implementing a stack using a linked-list

Redundant Code

In your push() function, you have these two cases which are redundant:

// if stack is empty
if (head == NULL)
{
    strcpy(temp -> string, element);
    temp -> next = NULL;
    return temp;
}

strcpy(temp -> string, element);
temp -> next = head;
return temp;

You can just remove the special case for head == NULL and be left with this, which handles both cases:

strcpy(temp -> string, element);
temp -> next = head;
return temp;

Better to iterate than recurse

Your destroy_stack() function is recursive, and that could be a problem if the stack has millions of elements because it could cause your program stack to overflow.  It is easy enough to write an iterative version of that function instead, like this:

void destroy_stack(node *p)
{
    while (p != NULL)
    {
        node *next = p->next;
        free(p);
        p = next;
    }
}

Minor issues

In push(), using strcpy() is unsafe because element might exceed 20 characters and you will overflow your buffer.
In push(), if malloc() returns NULL, you return NULL and thus destroy/leak the rest of the stack.  Perhaps you should just return head instead, to preserve the rest of the stack.
In pop(), you might want to check for head == NULL, otherwise you must depend on the caller to never pass NULL to your function.


1. Bug

If you pass the empty list to Sort_and_Count, it recurses until it runs out of stack:

>>> Sort_and_Count([], 0)
Traceback (most recent call last):
  File "cr107928.py", line 67, in test_Sort_and_Count
    Sort_and_Count([],0)
  ... many lines omitted ...
  File "cr107928.py", line 49, in Sort_and_Count
    if n==1:
RecursionError: maximum recursion depth exceeded in comparison

2. Review

The code omits spaces around operators. This makes it hard to read. It is better to follow the Python style guide (PEP8):

  Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not). [...] If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies).

The names do not follow the Python style guide. This recommends:

  Class names should normally use the CapWords convention.

so TestSortAndCount would be better than TestSort_and_Count.

  Function names should be lowercase, with words separated by underscores as necessary to improve readability.

so merge_and_count_inversions would be better than Merge_and_CountSplitInv.

It's not compulsory to follow the Python style guide, but it makes it easier for other Python programmers to read your code.
Python's documentation uses the term "sequence" to refer to indexable collections, not "array". There's less risk of confusion if you stick to the standard term.
The docstring says, "Merges two similar length pre-sorted sub-slices", but in fact the function works fine even if the subsequences are not of similar length. I know that when called from Sort_and_Count the subsequences will be equal in length or differ by one, but it's better to document the actual behaviour of the function.
Instead of index_1st and index_2nd, I would use i and j. These variables are used many times, so using short names reduces the amount of code and make it easier to read.
The arguments len_1st and len_2nd are only used within the expressions start_index+len_1st and start_index+len_1st+len_2nd. This suggests that the arguments to the function should be start, middle and end instead.
Instead of updating A one element at a time:

write_index=start_index
for value in temp_array:
    A[write_index]=value
    write_index +=1

update all elements at once using a slice assignment:

A[start_index:start_index + len(temp_array)] = temp_array

This is efficient (in CPython, anyway) because the replacement is the same length as the slice being assigned.
In Sort_and_Count, the caller is expected to pass in the length of the sequence. It would be simpler if Sort_and_Count called len instead. This could easily be done using a helper function; see updated code below.
The test case doesn't try the empty list (see "Bug" above).
The test cases only test that the inversion count is correct, but don't actually test that the sequence is sorted! You need something like:

self.assertEqual(A, sorted(A))

The test cases have hard-coded counts of inversions. But it is easy to count the inversions in a sequence, using itertools.combinations:

sum(j < i for i, j in combinations(seq, 2))

This is inefficient (it's \$ Θ(n^2) \$), but clearly correct, and so a good comparison for the efficient, but not clearly correct, counts produced by the function under test.
The test cases are very repetitive. This could be avoided with a helper method, something like this:

def check(self, seq):
    expected = sum(j < i for i, j in combinations(seq, 2))
    found = sort_and_count_inversions(seq)
    self.assertEqual(expected, found)
    self.assertEqual(seq, sorted(seq))

The test cases are not very thorough. You could easily test many more cases using random test generation:

for _ in range(100):
    self.check([randrange(100) for _ in range(randrange(100))])

3. Revised code

from itertools import combinations
from random import randrange
from unittest import TestCase

def merge_and_count_inversions(seq, start, middle, end):
    """Merge two adjacent sorted sub-sequences of seq and count
    inversions.

    Arguments:
    seq -- sequence to sort
    start -- index of beginning of first sorted subsequence
    middle -- end of first, and beginning of second, sorted subsequence
    end -- end of second sorted subsequence

    Result: number of inversions (cases where i < j, but seq[i] > seq[j]).

    Side effect: seq is sorted between start and end.

    """
    assert 0 <= start < middle < end <= len(seq)
    inversions = 0
    temp = []
    i = start
    j = middle
    while i < middle and j < end:
        if seq[i] <= seq[j]:
            temp.append(seq[i])
            i += 1
        else:
            temp.append(seq[j])
            j += 1
            inversions += middle - i
    if j == end:
        # Second subsequence is complete: process remainder of first.
        temp.extend(seq[i:middle])
    else:
        # First subsequence is complete: no need to process
        # remaininder of second, since it does not move.
        pass
    # Insert sorted results into original sequence.
    seq[start:start+len(temp)] = temp
    return inversions

def sort_and_count_inversions(seq):
    """Sort a sequence and count inversions.

    Argument: seq -- a sequence

    Result: number of inversions (cases where i < j, but seq[i] > seq[j]).

    Side effect: seq is sorted.

    """
    def sort_and_count(seq, start, end):
        if end - start < 2:
            return 0
        middle = (start + end) // 2
        return (sort_and_count(seq, start, middle)
                + sort_and_count(seq, middle, end)
                + merge_and_count_inversions(seq, start, middle, end))
    return sort_and_count(seq, 0, len(seq))

class TestSortAndCount(TestCase):
    def check(self, seq):
        expected = sum(j < i for i, j in combinations(seq, 2))
        found = sort_and_count_inversions(seq)
        self.assertEqual(expected, found)
        self.assertEqual(seq, sorted(seq))

    def runTest(self):
        self.check([])                    # empty sequence
        self.check([1])                   # single element
        self.check([1, 3, 5, 2, 4, 6])    # even length
        self.check([1, 3, 5, 2, 4, 6, 3]) # odd length, duplicate value
        for _ in range(100):              # random test cases
            self.check([randrange(100) for _ in range(randrange(100))])


First things first:

import java.lang.*;

This import is superfluous. Java by default imports the java.lang package, you don't have to specify any further things.

You seem to be using consistent two newlines between last } and the next opening brace. I personally find this to take a lot of space and I'd reserve "large" vertical distance to signify sectioning or similar, it's consistent ;)

public static void main (String args[]) {

While this is a perfectly valid declaration for main, I'd prefer to have the array declaration behind the type and not behind the argument name for consistency's sake:

public static void main (String[] args) {


The simple solution is to add a j loop.

void array_print(const int *ptr) {
  for (int j = 0; j < 10; j++) {
    for (int i = j; i < SIZE; i=i+10) {
      printf("%10d", ptr[i]);
    }
    printf("\n");
  }
}

Also look to a wider than "%10d" to cope with "1234567890" running together as well as 11 character "-1234567890".  Perhaps " %11d"?

Better code would pass in int columns, int rows, int size than hard code them.


This will give you the same result as your sql.

select distinct ProductColour, null as ProductSize
from shoptransfer

union all

select distinct null as ProductColor, ProductSize
from shoptransfer

You don't actually need the "as" clause on the second select, but I find it good for readability.

Ultimatly, sql server will mostly be doing the same thing, but by removing the explicit temporary table and putting it all into one command, you give sql server a better chance of doing the two selects in parallel.


I want a nice design pattern for "All", "many" or "one"

Why would you want a single method to do three logically different things? Each method you make should really only perform one task. What's the problem in just having the consumer choose the method of selection based upon their need, instead of having a one method fits all sort of thing? If having three methods really isn't what you want, perhaps you could pass a Command pattern object to a database object, to execute the desired functionality?


Logic Gate Simulator - Proper Encapsulation

You are mixing up lots of different responsibilities in your classes. For instance, AndGate has to handle both the And part and all the pin input parts. It is weird that an AndGate doesn't actually take references to its input pins. Furthermore, how in this model do we connect gates to each other? By your design, a "pin" is a value comparable to an integer. What if I wanted to model something like (picking a random circuit from google):

How would I do that in your system? The Connectors confuse the logic, since in your example you're creating a bunch of gates that are floating around - and then just to see that G1 and G2 go into G3 is split across several lines, rather than ideally:

g3 = OrGate('G3', g1, g2)

As a first go, gates should know their inputs and be able to perform logic to determine their outputs:

class NandGate(LogicGate):
    def __init__(self, name, a, b):
        LogicGate.__init__(self, name)
        self.a = a
        self.b = b

    @property
    def output(self):
        return not (self.a.output and self.b.output)

This separates the concern of input handling (determining the pins) from the concern of actually emulating the gates (determining the outputs) - and is what will let us have NandGates as input to other NandGates:

A = ConstantPin('A', True)
B = ConstantPin('B', False)
N1 = NandGate('N1', A, B)
N2 = NandGate('N2', A, N1)
N3 = NandGate('N3', N1, B)
N4 = NandGate('N4', N2, N3)
N5 = NandGate('N5', N4, N4)
Q = N5.output


Case insensitive string to replace custom comparers

Creating a throw-away object just to perform == comparison is ugly,
and likely inefficient:

public static bool operator ==(CaseInsensitiveString left, CaseInsensitiveString right) => new CaseInsensitiveString(left).Equals(right);

I suspect you wanted to avoid a tedious null-check, but I don't think you have a choice:

public static bool operator ==(CaseInsensitiveString left, CaseInsensitiveString right) => !ReferenceEquals(left, null) && left.Equals(right);

But there's a more serious problem.
As it stands, two null instances of CaseInsensitiveString are not equal, and it should be.


To sum up what this script does, just for the sake of simplicity:

Declare a result set table variable @tablefinal.
Declare variables for a counter, and for courses, and a commented out @STUDENT_ID (likely for testing purposes).
Declare another result set table variable @tableCourse to hold course IDs and course names during the transaction. This seems to be to filter out courses with no students or not on the schedule.
Set the counter start = 1 and end = total number of rows.
Begin to cycle through @tableCourse at row 1 using WHILE. I noticed that @student_id is not declared or set (other than the instance which is commented out) even though it's being used in multiple WHERE clauses. May be worth your while to look into why it is that way.
Count records for @@pre
Count records for @@courses
Count records for @@post
Count records for @@feedback
Count records for @@final
Declare @per for precentage
Calculate @per with a simple arithmetic operation
Shove everything into your results table @tablefinal and then select from it to see the result set.

To me this really seems like overkill, like a SQL programmer trying to show that he knows how to use variables. I think this could be much more simple, I won't rewrite the whole script but here are some ideas. If you decide to try that approach you will need to start from the ground up, you are welcome to post your new script in a new Code Review if you would like.

DECLARE @pre INT = (Count(*) FROM DLC_ASSESSMENT_RESULT WHERE RESULT_STATUS='Pass'  AND RESULT_ASSESSMENT_TYPE=2);
-- Repeat DECLARE (Count(*)) for @post, @feedback, @final

SELECT
    C.COURSE_ID,
    C.COURSE_NAME,
    @pre AS 'Pre',
    @post AS 'Post',
    @feedback AS 'Feedback',
    @final AS 'Final',
    ((ISNULL(@Pre,0) + ISNULL(@@post,0) + ISNULL(@Final,0) ) / 3.00   * 100) AS 'Pre'

FROM DLC_COURSE C
WHERE COURSE_ID IN
-- Taken from the script, seems to be the only important JOIN
(
    SELECT CS.COURSESHD_COURSE_ID
    FROM DLC_COURSE_SCHEDULE CS
    INNER JOIN DLC_STUDENT_PAYMENT SP ON
        CS.COURSESHD_ID = SP.STUDENT_PAYMENT_COURSESHD_ID
    WHERE CS.COURSESHD_STATUS=1
)
AND C.COURSE_STATUS=1
-- This will aggregate the result set by course
GROUP BY C.COURSE_ID;


Project Euler Problem 6: Sum square difference

I don't know about the difference between sumOfTheSquares += i*i and Math.pow() but the sum of squared of first n natural numbers is as follows

\$ 1^2 + 2^2 + 3^2 + 4^2 = \dfrac{n(n+1)(2n+1)}{6}\$

So its faster than using a for loop

Edit: General way to prove this is to use mathematical induction
Here's a link!


Building on Henrick's answer, using Ling to return the IEnumerable:

return Directory.GetFiles(root, "*", SearchOption.AllDirectories)
              .Select(p => p.Remove(0, rootLength));


iOS: prettify random color for debugging

I've had a look, and think it should be possible to trim down the ColorCluster-logic quite a bit, mostly by tightening up the get(: function a bit. Avoiding some if-elsing and only manipulating the index and count once.
struct ColorCluster {
    static var shared = ColorCluster()
    private init() { }

    private let colors: [UIColor] = [.blue, .magenta, .red, .green, .brown, .purple, .cyan]
    private var colorRegister = [String: Int]()
    private var count = 0

    mutating func getColor(for key: String) -> CGColor {
        let countIsOutOfBounds = count >= colors.count
        let nextAvailableIndex = countIsOutOfBounds ? 0 : count

        let index = colorRegister[key] ?? nextAvailableIndex
        count = countIsOutOfBounds ? 0 : count + 1

        return colors[index].cgColor
    }
}

I also had a quick look at the debug-extension. I haven't actually tested it, but the gist is to go down the functional route when creating the array of method-names:
extension CALayer {
    func debug() {
        // call stack trace, remove methods of the system
        let libs: Set<String> = ["UIKitCore", "QuartzCore", "CoreFoundation"]

        let methodNames = Thread.callStackSymbols.reduce([String]()) { names, symbol in
            let containingSymbol = libs.filter({ symbol.contains($0) })
            if containingSymbol.isEmpty {
                return names
            }
            return names + [symbol]
        }

        var edgeColor = UIColor.black.cgColor // color place holder
        if let name = methodNames.last {
            edgeColor = ColorCluster.shared.getColor(for: name)
        }
        borderColor = edgeColor
        borderWidth = 1
    }
}


Copying into two different folders on a machine simultaneously

I am trying to see is there any better way of doing the same thing using GNU Parallel instead of using &.

Essentially you have two different commands and two different parameter lists:

Copy to PRIMARY, these files: 550 274 2 546 278
Copy to SECONDARY, these files: 1643 1103 1372 1096 1369 1568

These are two file-sets, two distinct operations. I don't think there's an easy way to do this with a single parallel process. A not-so-easy way can be:
organize the inputs in pairs, like this:

parallel -N2 do_Copy {1} {2} ::: 550 $PRIMARY 274 $PRIMARY 1643 $SECONDARY  # and so on

This way it will work with one command.
But constructing the argument list dynamically from your list of filenames will be tricky and potentially error prone.
The original solution is simple and easier to understand,
which are preferable properties.

Exporting variables

You don't need to export PRIMARY and SECONDARY.

You only need to export FILERS_LOCATION_1 and FILERS_LOCATION_2,
because these will be used by do_Copy,
which will be called by parallel (and also needs to be exported, as you correctly did).

Notice that the read-only FILERS_LOCATION array is pointless.
You could just as well set the FILERS_LOCATION_* variables directly:

export FILERS_LOCATION_1=machineB
export FILERS_LOCATION_2=machineC

Improving do_Copy

In this method,
you have two scp commands that are almost duplicates,
except the destination part.
To avoid the duplication,
you could just loop over the possible destinations,
and break out of the loop as soon as a copy was successful:

do_Copy() {
  el=$1
  PRIMSEC=$2
  for host in $FILERS_LOCATION_1 $FILERS_LOCATION_2; do
      echo "scp david@$host:$dir3/new_weekly_2014_"$el"_200003_5.data $PRIMSEC/." && break
  done
}

If the destination files might be exactly the same as the local files,
then you'll be better off using rsync -u instead of scp,
to avoid unnecessary file transfers.


Here's how I'd do it:

In your view, simply call a recursive method on each category:

  <% Category.roots.map do |category| %>
     <%= draw_tree(category) %>
  <% end %>

And now in a helper file (app/helpers/category_helper.rb?), this is the "right" place to put HTML helpers. First, in pseudo-code:

def draw_tree(category)

    <%= category.name %>
    <% category.children.each do |child| %>

      <%= draw_tree(child) %>

    <% end %>

end

Now, to actually make this work, rather than writing a string and calling #html_safe, a much cleaner (and generally safer) approach is to use content_tag. The end result is:

def draw_tree(category)
  content_tag(:li, class: "col-md-2") do
    link_to('#', category.name)
    category.children.map do |child|
      content_tag(:ul, draw_tree(child))
    end
  end
end

I haven't actually run the above code, so apologies if there's some small mistake. But hopefully you get the idea :)


Deque implemented using a circular array

I do not see any problems with addCount as long as we add a disclaimer that this solution is not thread safe.

The presented solution is a collection that can only accept int items. You can expand this if you add generic parameter to the class. Note that in this case, the internal array is of Object[] type and you let the compiler enforce type safety and also do auto-boxing to support primitive data items, just like in Java collections library. And while we mentioned that, you might want to consider making your solution implement the Deque interface from Java collections so that clients will work with a familiar API (of course you will want to change the name of the class to reflect that it is a concrete implementation of a Deque)