Is my first MVC architecture set up to standards?

MVC approaches differ between languages, platforms and frameworks. They are usually termed "MV* frameworks" because they don't exactly follow strict MVC. But we call them MVC nonetheless.

Separate core logic from configurable logic

The way I understand your code, it looks like you've gone over CodeIgniter (or something similar). I assume all your requests run through index.php where the initial logic runs, like the helper loading, routing etc. For that, I suggest you separate the autoloader list and routing list to different files. You can load them via something like include. That way, you don't accidentally modify the core logic.

// autoload.php
$autoload = array(
  'autoloadCore',
  'autoloadController',
  'autoloadModel'
);

// routes.php
$routes = array(
  '/'       => 'Index',
  '/signup' => 'SignUp',
  '/login'  => 'Login'
);

Additionally, the word "Controller" might not be necessary for the routing. You already know that they always go to controllers. You might want to do that in the underlying logic instead, and keep it easy on the configurable parts.

Route lists cons

One thing to note with this routing strategy is that whenever you add a controller, you always need to list down the route. This approach is not that nice, especially when you are going to be handling a hundred routes (and trust me, it ain't a walk in the park).

Auto-route + custom routes

Why not automatically look for controllers based on a predefined convention (like CodeIgniter). A route of /foobar/bam would route to FoobarController and execute the bam method. As for custom routes, you can map it like so:

$routes = array(
  'autobam' => 'foobar/bam` // A route of `/autobam` executes the same as `foobar/bam`
);

And the flow goes like:

- Parse route
- Check for match under custom
  - If match, convert to equivalent route
- Use non-custom/equivalent route for locating the controller
  - If none, throw error
  - Else, load and execute


Ubuntu kernel update and removal automation script

The only thing I know now is grep -P and everything seems like a nail if you have a hammer.

I hope that's an exaggeration. Otherwise, I don't know how you will understand a review ;-)

Use more here-strings

The script uses here-strings in only one place,
when there are more places where it would be good to use.
For example, instead of this:

LATEST_KERNEL=$(echo "$AVAILABLE_KERNELS" | grep -oPz 'Available Kernels.*?\n=+\n\Kv.+?(?=\s.*?\n)')

This would be better, and eliminate an unnecessary echo call:

LATEST_KERNEL=$(grep -oPz 'Available Kernels.*?\n=+\n\Kv.+?(?=\s.*?\n)' <<< "$AVAILABLE_KERNELS")

Eliminate unnecessary condition

The inner if here can be eliminated:

if ! containsElement "$INSTALLED_KERNEL" "${FALLBACK_KERNELS[@]}"
then
    if ! echo "$INSTALLED_KERNEL" | grep -q "$LATEST_KERNEL"
    then
        echo "${INSTALLED_KERNEL} is not fallback, nor latest. Removing it..."
        ukuu --remove "$INSTALLED_KERNEL"
    fi
fi

You could add "$INSTALLED_KERNEL" to the parameter list of the call to containsElement. Not only the code will be simpler, but it will also eliminate a grep call. (And the echo with the grep, which should have been a here-string anyway, as explained earlier.)

Understand the flags of commands

This call looks strange: grep -oPzq ....
Because of the -q.
Thanks to the -q, the command will produce no output.
Which makes the -o flag unnecessary.
I suggest to review in man grep all the flags you're using,
understand what they do,
and consistently eliminate unnecessary flags.

Naming variables

I and e are too short, they don't help understanding their purpose, and therefore the code.

All capital letters are traditionally used for system variables.
For all local variables in shell scripts,
it's better to use lowercase names to avoid any confusion.

Appending to an array

This statement appends a value to the INSTALLED_KERNELS array:

INSTALLED_KERNELS=( "${INSTALLED_KERNELS[@]}" "$I" )

A simpler way to achieve the same:

INSTALLED_KERNELS+=("$I")

Declare important global variables and constants at the top

Some of the variables are crucial for the behavior of the script,
for example FALLBACK_KERNELS.
What if later you want to change the fallback kernels?
You have to read through the script to find the declaration in the middle.
It would be a lot easier if this was declared at the top,
so you would not need to re-read and re-understand what's going on just to make a simple change.


Seems mostly solid to me. I just have two small remarks:

const spiralMatrix = (n) => {

I'm not a big fan of using the arrow syntax here. The arrow syntax is (mostly) used for inline functions. For a "top level" function I'd prefer a normal, more readable (and hoisted) function declaration:

function spiralMatrix(n) {

The only disadvantage I see is that const prevents accidental overwriting, which I don't see as an serious problem in this case.

And .fill(0) during initialization of the arrays is unnecessary.


The first check in the try block is not needed at all. It just checks if the value is string, and it's unlikely to be something else. If this validation is attached to a control, who's value is not a string, then this is an error, and I would throw an exception "Bad values", so the code is corrected.

Then, if the value is null or empty, you have an error, why would you inspect all the other possibilities?

Also - where you use the control itself? Why you pass it, if you do not use it?

Anyway, if I was to check the string for valid formatting, I would do this:

        var str = value as String;

        var letter = (selectedItem == Constants.Item1) ? "D" : "B";
        var errText = String.Format("The correct form is: FA{0}-Zxxx oder FA{0}-Zxxx-x !", letter);

        if (str == null
            || str.Length < 8
            || !(str.Length >= 10 && str.Length <=12))
        {
            this.ErrorType = ErrorType.Critical;
            this.ErrorText = errText;
            return false;
        }

        var regExString = @"([F][A][" + letter + @"][-][Z]\d{3})";
        Regex shortRegEx = new Regex(regExString);
        Regex longRegEx = new Regex(regExString + @"[-][0-9]+$)");

        var isMatch = (shortRegEx.IsMatch(str) || longRegEx.IsMatch(str));
        if (!isMatch)
        {
            this.ErrorText = errText;
        }

        return isMatch;


File to String Pattern for uploading to a server

I'm not familiar with Android at all, so just some generic Java notes:

I'd rename bm to bitmap. A little bit longer variable names are usually easier to read and maintain.
The constructor should validate its input parameters. Does it make sense to call it with null or empty string as path or a less than zero timestamp? If not, check it and throw a NullPointerException or an IllegalStateException. (Effective Java, Second Edition, Item 38: Check parameters for validity)
It is a bad idea to use printStackTrace() in Android exceptions.
I don't know if it differs from general Java or not but closing a ByteArrayOutputStream in Java has no effect. You might be able to omit it.


Counting the minimum number of blocks to remove to form a triangular temple

Your code is not working for some cases.
Consider for example input 1 1 2 2 4.
The answer should be 6, but your code returns 1.


For the "official" answer, you can go straight to the GHC source for nub:

nub                     :: (Eq a) => [a] -> [a]
nub l                   = nub' l []
  where
    nub' [] _           = []
    nub' (x:xs) ls
        | x `elem` ls   = nub' xs ls
        | otherwise     = x : nub' xs (x:ls)

Some of the differences that stand out are:

Use a where clause to scope your helper function, and name it with a "prime" symbol.  In your case, I guess the helper would be nub''.  The helper's type can then be automatically inferred.
Use pattern matching instead of if-then-else.
Your contains helper is just the elem builtin.  They chose to write x `elem` ls instead of elem x ls, probably to read more smoothly.
It's more natural / efficient to prepend than to append elements to a list.  Instead of building acc as the result as a list of wanted elements, they build ls as the list of elements to exclude in future encounters.


Am I using the "right" type for the Add subnodes (i.e. Rc)?

No. You probably don't want to do that. Just use AST. Good Rust code rarely actually needs Rc. Instead of using Rc<> in the definition of AST, use Box.

#[derive(Debug)]
pub enum AST<T> {
    ConstInt(isize, Rc<T>),
    Add(Box<AST<T>>, Box<AST<T>>, Rc<T>),
}

Now Rc does give you the ability to reuse branches of the AST. For example, you use x twice. However, I've not seen a real case of ASTs where that needs to happen. As it stands you are paying the costs of RC (both in programmer effort, execution time, and memory overahead) for no good reason.

You should also get rid of the Rc<> for the T. Just store a T. In cases where you need to be able to copy the T for some reason (which is probably never), take a <T: Clone> so you can call the clone method. The client code can then put in Rc<> in place if it wants, or if the data is trivial just allow it to be copied.

I would also question the usefulness of a generic type here at all. Are you really going to annotate the same AST with different additional data in different places? I rather doubt it.

  Is it possible to create eval as an AST method instead of a function? I kept fighting the borrow checking if x in eval was self : &AST (within the impl block, of course)

You'll find that if you don't try to pass ASTs in Rc<> that this will work much better. The problem is that you can't take self to be an Rc<>, so you don't get access to the reference counter itself which makes it difficult to do anything useful.

Even if you use RC, you can define a static method in the impl (just don't have a self parameter. Then you can use syntax like AST::eval(ast).

pub fn eval<T>(x: &RAST<T>) -> RAST<T> {

This function is pretty strange. Why does an evaluation function return an AST. Shouldn't it return a value? If instead this function were to return isize it would be a much simpler function.

However, the logic of the function makes more sense if it is a optimization function. That is, it seeks to produce a more optimized version of the AST rather than evaluate the AST. But if that's the idea, your function takes the wrong type. It might make sense for the optimization function to take ownership of the AST, consuming the old AST reusing peices of it for the new AST. Or it might make sense to take a mutable reference to the AST, modifying the AST to make a more optimized version.

  Is there any way to make this program more concise/cleaner? I think I understand why all the additional wrapping and sprinkling of Rc::clone/new and lots of reference taking is needed, but was wondering if I was perhaps missing something that might make this code cleaner to read.

Yes, if you follow my advice aboev you'll find the code a lot more concise and cleaner.


if(addresses.length == 1)
    from = addresses[0].toString();
else
{
    for(int num = 0; num < addresses.length - 1; num++)
        from += addresses[num].toString() + ", ";
    from += addresses[addresses.length].toString();
}

Concatenations of strings in a loop should be done using a StringBuilder like so

StringBuilder builder = new StringBuilder(1024);
for(int i = 0; i < addresses.length ; i++)
{
    builder.append(addresses[i].toString())
           .append(", ");
}
int builderLength = builder.length();
if(builderLength > 2)
{
    // removing the last appended ", "
    builder.setLength(builderLength - 2);
}
String from = builder.toString();

if(contentType.contains("TEXT/PLAIN"))
{
    Object content = message.getContent();
    if(content != null)
        body += content.toString();
}
else if(contentType.contains("TEXT/HTML"))
{
    Object content = message.getContent();
    if(content != null)
        body += Jsoup.parse((String)content).text();
}

here it would be sufficient to just assign the content.toString() or Jsoup.parse((String)content).text() to the body variable. There is no need to use +=.

else if(contentType.contains("multipart"))
{
    Multipart mp = (Multipart)message.getContent();
    int numParts = mp.getCount();
    for(int count = 0; count < numParts; count++)
    {
        MimeBodyPart part = (MimeBodyPart)mp.getBodyPart(count);
        String content = part.getContent().toString();
        if(MimeBodyPart.ATTACHMENT.equalsIgnoreCase(part.getDisposition()))
            attachments.add(part);
        else if(part.getContentType().contains("TEXT/HTML"))
            body += Jsoup.parse(content).text();
        else
            body += content;
    }
}

As mentioned above if you are using a loop for concatenations of strings this should be done using a StringBuilder.

You will only need the String content if the execution steps into the else if or else part and because one should declare variables as near to its usage, you could use continue; after the attachment is added like so

else if(contentType.contains("multipart"))
{
    StringBuilder bodyBuilder = new StringBuilder(1024);
    Multipart mp = (Multipart)message.getContent();
    int numParts = mp.getCount();
    for(int count = 0; count < numParts; count++)
    {
        MimeBodyPart part = (MimeBodyPart)mp.getBodyPart(count);
        if(MimeBodyPart.ATTACHMENT.equalsIgnoreCase(part.getDisposition()))
        {
            attachments.add(part);
            continue;
        }

       String content = part.getContent().toString();
        if(part.getContentType().contains("TEXT/HTML"))
        {
            bodyBuilder.append(Jsoup.parse(content).text());
        } else {
            bodyBuilder.append(content);
        }
    }
    body = bodyBuilder.toString();
}


Passing C++ objects by reference for participants in a simulated battle

I have a couple of issues with how you are doing this (it is very Java like not C++ like).

Constructors

After the constructor finishes your object should be in a valid consistent state. Having to call multiple "setters" to finish initialization is a big red flag.

Entity constructE(float damage, float health, float regen) {
    Entity Entity;
    Entity.setDamage(damage);
    Entity.setHealth(health);
    Entity.setRegen(regen);

    return (Entity);
}

Why not just have a "constructor" that takes these arguments.

Entity Player = constructE(10, 100, 10);

// Should look like:
Entity Player(10, 100, 10);

Passing an object to itself?

Player.playerAttack(Player, Monster);

You are passing player as an argument? As you are calling a method on the object "player" you already have access to the player (via this). So there is no need to pass the player here.

player.attack(monster);

Identifier conventions.

One thing I notice about your code is that everything starts with a capitol letter. This makes it hard to tell the difference between types and objects. One of the most important things in C++ is type.

So the usual convention is that "User Defined Types" have an initial capitol letter. While objects (variables) have an initial lower case letter.

player.attack(monster);
^ Object      ^ Object

While:

Player.attack(monster);
|             ^ object
^ Looks like a type.
  So attack looks likes a static member function (ie a class method).

Getters/Setters

Getters and Setters break encapsulation. They expose the internal implementation details of the class. If you see the pattern

 auto x = object.getValue();
 auto y = performSomeAction(x);
 object.setValue(y);

Then this is usually an indication that you have not designed your class well as you expose internal details to calculate a value. A better design would be to provide a method that performs an ACTION on the class.

 object.someAction();   // internally it can update its own state.

Re-Design

class Entity
{
public:
     Entity(int damage, int helath, int regen)
         : damage(damage)
         , health(health)
         , healAbility(regen)
    {}
    // Destructor not needed.

    // Check if an entity is alive.
    operator bool() const
    {
        return health > 0;
    }
private:
    // Internal use only by attack()
    int weaponDamage() const
    {
        return myRandomNumber() % 10;  // Damage in the range 0..9
    }

    // Take damage
    Entity& takeDamage(int amount)
    {
        // Can not go below zero.
        health = max(0, health - amount);
        return *this;
    }
public:

    // Attack an Enemy
    void attack(Entity &enemy)
    {
        std::cout << "Player:     " << *this
                  << "Attacking:  " << enemy;

        // Damage the enemy and check if he is alive in one line.
        if (enemy.takeDamage(weaponDamage()) {
            // Enemy Alive
            cout << "E. Status: " << enemy;
        }
        else {
            // Enemy Dead
            cout << "Enemies is Dead" << "\n";
            cout << "P: Status: " << *this;
        }
    }

    virtual std::ostream& print(std::ostream& str) const
    {
        return str << "health: "       << health
                   << " damage: "      << damage
                   << " healAbility: " << healAbility
                   << "\n";
    }
    friend std::ostream& operator<<(std::ostream& str, Entity const& data)
    {
        return data.print(str);
    }
private:

private:
    float health;
    float damage;
    float healAbility;
};


Do you need UtcTimeOfDay at all? DateTime already has useful methods for working with paramterized times.

The disadvantage that using a raw DateTime has is that you have no compile-time guarantee that you won't get an invalid DateTime (e.g. one with a Day component above 0). However, you can get the best of both worlds by having your class wrap a DateTime:

public class UtcTimeOfDay
{
    public readonly DateTime Value;

    public UtcTimeOfDay(int hour, int minute, int second)
    {
        Value = new DateTime(0,0,0,hour,minute,second);
    }
}

Now you get all the advantages of the rich functionality of DateTime, along with the guarantees provided by your original class.

Regarding your original UtcTimeOfDay, the names aren't great. Shouldn't MinuteOfDay be MinuteOfHour, and likewise shouldn't SecondOfDay be SecondOfMinute?

This also reveals another problem: there's no guarantee that these values are valid (they could be negative, or above the maximum possible). This could be done with validation in a constructor, making the setters private.

The name UtcTimeInterval doesn't make any reference to the fact that it's specifically for a time interval within a day. Why not UtcTimeOfDayInterval?

While you can use StartInclusive and EndInclusive, a normal technique to deal with exclusive time spans is simply to add or subtract a tick to your time. So for example, if the inclusive start time was startTimeInclusive, then if you want an exclusive version, that would be startTimeExclusive = startTimeInclusive.AddTicks(1);

Being able to do this so simply is another benefit of using a DateTime rather than trying to roll your own structure to represent the same thing.

So what I would do is remove the StartInclusive and EndInclusive properties, and do one of the following:

Just let whoever sets the start and end UtcTimeOfDay take responsibility for adding or subtracting a tick if they need to.
Add a constructor with boolean startInclusive and endInclusive parameters, as well as the start and end UtcTimeOfDays which itself does the tick adding/subtracting when needed.

Update

As a couple of people have noted in comments, using a TimeSpan instead of a DateTime may be preferable, as it is more in fitting with the meaning of these structures. This makes the add/subtract tick logic slightly more verbose, but not prohibitively.


Code duplication for just an if condition

Just add a parameter boolean incrementOnAnyDepth and in your if condition write

if ( x.getDestination() == e && (incrementOnAnyDepth || currentDepth == maxDepth) )
{
    counter++;
}`


Return the longest word (or words) in a string

Why do you have more parenthesis than needed in this statement?

if (((words[j] >= 'A' && words[j] <= 'Z') || (words[j] >= 'a' && words[j] <= 'z')))

if ((words[j] >= 'A' && words[j] <= 'Z') || (words[j] >= 'a' && words[j] <= 'z'))

Similarly:

if (l == (s.Length - 1))

Should be written as:

if (l == s.Length - 1)

As well:

for (int n = (indexList[m] - maxLength); n < indexList[m]; n++)

Should be:

for (int n = indexList[m] - maxLength; n < indexList[m]; n++)

Using j, k and l as a variable in this manner is frowned upon. These should only ever be used with local iterators. (I.e. where you have i.)

Some of your names are not idiomatic.

char[] words = s.ToCharArray();

Should be:

char[] characters = s.ToCharArray();

The string s parameter should be string input (et. al.).

You can take some of your operations to functions, delegates, Lambdas, etc.

if (((words[l] >= 'A' && words[l] <= 'Z') || (words[l] >= 'a' && words[l] <= 'z')))

Can more easily be written as a delegate, function, etc.

if (IsAlphaChar(words[l])

Use a foreach loop in place of:

for (int m = 0; m <= k - 1; m++)

Should be:

foreach (int index in indexList)

Then just use index in place of indexList[m].

Never do this:

int j = 0, k = 0, l = 0, tempLength = 0, maxLength = 0;

That is a readability nightmare. Break each variable to it's own line. (And don't declare all of them in one spot. Declare them when you need them.)

You shouldn't declare iterators outside a for loop. (I'm looking at you, j and l.)

Doing words[i] four times is slower than char currentCharacter = words[i];. (Of course, the location that is used should be a method instead.)

You don't use j or l after their respective loops, so don't define them as the first thing in the method. Instead, define them as:

for (int j = i; j <= s.Length; j++)
for (int l = i; l <= s.Length; l++)


Personally I would combine the two @IBActions into a single one and identify the pressed button from the sender object.

I would also recommend you to look into the Ternary Conditional Operator, which can make your simple if statements much cleaner, like the following:

if currentQuestion.answer == true {
    answerLabel.text = "correct"
} else if currentQuestion.answer == false {
    answerLabel.text = "Incorrect"
}

// The previous is exactly the same as the following:
answerLabel.text = (currentQuestion.answer == true) ? "correct" : "Incorrect"

You can read more about the Ternary Conditional Operator here.

You can see my result from trying to recreate your current setup as inspiration (FYI, my buttons have the titles "True" and "False", which I make use of to turn them into booleans):

//
//  ViewController.swift
//  TrueFalseQuiz
//
//  Created by Stefan Veis Pennerup on 06/06/15.
//  Copyright (c) 2015 Kumuluzz. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    // MARK: - Question models
    // Notice: This is not the best practice for storing the model in terms of the MVC pattern,
    // this is just for illustration purposes.
    let questions = [
        QuizQuestion(question: "Do I like coffee?", answer: true, explanation: "Because it's awesome!"),
        QuizQuestion(question: "Is bacon god's gift to mankind?", answer: true, explanation: "Because it's awesome!"),
        QuizQuestion(question: "Should I take a nap right now?", answer: false, explanation: "You gotta review some code!")]
    var currentQuestionIndex = 0

    // MARK: - Storyboard outlets

    @IBOutlet weak var questionLabel: UILabel!
    @IBOutlet weak var answerLabel: UILabel!

    // MARK: - Lifecycle methods

    override func viewDidLoad() {
        super.viewDidLoad()

        // Initializes the first question
        self.answerLabel.text = ""
        self.questionLabel.text = questions[currentQuestionIndex].question
    }

    // MARK: - Storyboard actions

    /**
    The target action for both the true false buttons
    */
    @IBAction func answerPressed(sender: UIButton) {
        // Exits if there aren't any questions left
        if currentQuestionIndex >= questions.count { return }

        // Retrieves the user's answer and figures out if it correct
        let userAnswer = sender.currentTitle
        let isAnswerCorrect = userAnswer?.toBool() == questions[currentQuestionIndex].answer

        // Prints appropiate message
        answerLabel.text = (isAnswerCorrect) ? "Correct" : "Incorrect"

        // Updates with a new question
        currentQuestionIndex++
        let isThereAnyQuestionsLeft = currentQuestionIndex < questions.count
        questionLabel.text = (isThereAnyQuestionsLeft) ? questions[currentQuestionIndex].question : "No more questions"
    }
}

// Extends the standard String class to convert a string to a boolean
extension String {
    func toBool() -> Bool? {
        switch self {
        case "True", "true", "yes", "1":
            return true
        case "False", "false", "no", "0":
            return false
        default:
            return nil
        }
    }
}

Could you describe a bit more about the "previous question" button? Should it replace the current question? Should it show the user's answer or just start over with the question?

UPDATE 1:

This update is concerning the "previous question" funcionality outlined by OP in the comments of this answer.

Regarding next and back:

I would add two new buttons (a "next" and "back" button, surprise, surprise) and create two separate storyboard actions for each of them. Each method would respectively increment or decrement the current question index. Both of the methods would then update the currently displayed question.

// MARK: - Next/back methods

@IBAction func nextPressed(sender: UIButton) {
    currentQuestionIndex++
    if currentQuestionIndex == questions.count { currentQuestionIndex = 0 }
    updateCurrentQuestion()
}

@IBAction func backPressed(sender: UIButton) {
    currentQuestionIndex--
    if currentQuestionIndex < 0 { currentQuestionIndex = questions.count - 1 }
    updateCurrentQuestion()
}

func updateCurrentQuestion() {
    answerLabel.text = ""
    questionLabel.text = questions[currentQuestionIndex].question
}

Regarding submitting all:

In the code outline aboved there are 2 main varibles related to your questions model:

let questions: [QuizQuestion]
var currentQuestionIndex: Int

To handle the feature for storing the user's answers, then I would add another property to your QuizQuestion model to hold the user's answers. This means your model would look something similar to the following:

//
//  QuizQuestion.swift
//  TrueFalseQuiz
//
//  Created by Stefan Veis Pennerup on 06/06/15.
//  Copyright (c) 2015 Kumuluzz. All rights reserved.
//

import Foundation

class QuizQuestion {

    let question: String!
    let answer: Bool!
    let explanation: String!
    var usersAnswer: Bool?

    init(question: String, answer: Bool, explanation: String) {
        self.question = question
        self.answer = answer
        self.explanation = explanation
    }
}

Since usersAnswer is an Optional, then it will initially be nil. Whenever the method answerPressed is called, then you should add the following line to store the answer, thus overwriting nil:
    let userAnswer = sender.currentTitle
    questions[currentQuestionIndex].usersAnswer = userAnswer?.toBool()

I would then add a new button called "finish" or "submit all" and connect the following storyboard action, which determines if all the questions have been answered before continuing.

// MARK: - Finishing

@IBAction func submitAll(sender: UIButton) {
    let hasAnsweredAllQuestions = questions.reduce(true) { (x, q) in x && (q.usersAnswer != nil) }
    println("has user answered all questions?: \(hasAnsweredAllQuestions)")
}

UPDATE 2:

Explanation of reduce for OP.

reduce can be quite hard to grasp initially, but once you understand it, then it can be super powerful. In short, it takes all the values of an array and compute it into a single value (could be an Int, Bool or something else). You can read more about it here: https://stackoverflow.com/questions/28283451/ios-swift-reduce-function.

The line

let hasAnsweredAllQuestions = questions.reduce(true) { (x, q) in x && (q.usersAnswer != nil) }

could be expanded to something similar the following:

var hasAnsweredAllQuestions = true
for q in questions {
    if (q.usersAnswer != nil) {
        hasAnsweredAllQuestions = true
    }
    else {
        hasAnsweredAllQuestions = false
        break;
    }
}

As you can see it simply loops over all the questions and checks if the user has given an answer (if the answer is not nil).

Other functions which are equally powerful as reduce are map and filter which you can try to do more research on.

Regarding checking the user's answer with the correct answer, then you could consider using map, but I'll leave you with that hint for now ;)


Get count of credit cards that are expired

If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/private-constructors

Make your constructor public.

There is an obvious bug in GetCountOfExpiredCreditCards  A card that expires in 01/19(January, 2019) will show up as expired if checked today.  Check for both year and month.


The pattern

match some_result {
    Ok(v)  => v,
    Err(e) => panic!("message: {:?}", e),
}

is exactly what expect does for you. We can get a somewhat leaner main if we use that instead:

fn main() {
    let self_posts = get_posts(20).expect("Failed to fetch new posts");

    let redis_client =
        redis::Client::open("redis://127.0.0.1").expect("Unable to create the store client");

    let redis_conn = redis_client
        .get_connection()
        .expect("Unable to retrieve the connection to the store");

    match add_posts_to_store(redis_conn, self_posts) {
        Ok(n) => println!("Stored {} posts.", n),
        Err(e) => panic!("Could not store posts: {:?}", e),
    };
}

Somewhat, because the error messages lead to long lines and rustfmt doesn't like that.

However, keep in mind that while panic is great for developers, it's a system that should be used for unrecoverable errors, bugs that you cannot handle or anticipate. When you panic!, you generate an error message that's helpful for programmers, but not for users:

thread 'main' panicked at 'Unable to retrieve the connection to the store: .......', src/main.rs:.....
note: Run with `RUST_BACKTRACE=1` for a backtrace.

Instead, stderr should get used. The Rust Book contains a section for error handling in its example I/O project which you can use for inspiration. But if you never intend to distribute your reddit/redis updater, feel free to use panic! or .expect("...").

Other than that, the turbofish syntax at collect::<Vec<Post>>() isn't necessary, since its inferred by the return type. Also, you can traverse p in posts instead of &p in &posts since you don't want to use the Vec afterwards, you just have to save the posts.len() beforehand.

However, you probably want to use store : &redis::Connection in add_posts_to_store if you want to reuse the connection. Also, you usually want to derive some of the standard traits, for example Debug. Again, that depends on whether you will use your structs in another context, but if you ever publish your package it's very recommended to derive all possible standard traits (Debug, PartialEq, Eq, PartialOrd, Ord, Clone and maybe Hash in your case).


WCF general response validation for multiple services

Peter - a couple of observations:

Since you say "Each response object from the service inherits from a base class ResponseBase" the gut reaction is to just use ResponseBase and let the inheritance model in C# handle everything. As you go on to explain, however, ResponseBase is not really the same base class across services, as they vary from service to service with generated code. In this case, you know exactly what the shape of the object is, but don't know its type. This is an example of 'duck typing' - if it looks like a duck, walks like a duck, and quacks like a duck, then we might as well treat it like a duck. This is exactly what dynamic typing is good for and seems to me an excellent use of this feature of C# 4.0.
The two exception conditions in your code are not created equal. The first seems to flag an incorrect use of the method, while the second is the method doing its job. So consider replacing the first one with a Code Contract if you are on .NET 4. (See Dino Esposito's articles in MSDN Magazine - 3 months in a row - for a good overview, starting here. Note especially that Code Contracts can be turned off for runtime, and they may be off already in your project. See Dino's articles for an explanation.)

Here is pseudocode:

public static void VerifyResponse(dynamic response)
{
   Contract.Requires(response != null);
   // or perhaps: Contract.Requires<ArgumentNullException>(response != null, "response");
   // or: if (response == null) throw new ArgumentNullException("response");

   if (response.ErrorCode < 0)
      throw new InvalidServiceResponseException(response.ErrorCode, response.ErrorMessage);
}


Deck and Card classes and member-accessing with one header

I see some things that may help you improve your code.

Consider using an enum class

Instead of using constructs such as char suit, use the superior safety of an enum class.  You can read this question for an overview of when to use one, but I think this would be a better way to do things for this case:

enum class suits : char {HEART = 'H', DIAMOND = 'D', CLUB = 'C', SPADE = 'S'};
enum class ranks : char {ACE=1, TWO, THREE, FOUR, FIVE, SIX, SEVEN,
                         EIGHT, NINE, TEN, JACK, QUEEN, KING };

This allows the small storage size of a char, the convenience of an enum and the type-safety of a class.

Force only valid cards to be created

With the existing default constructor, and with the constructor that takes arguments, any enforcement on validity of initialized values becomes part of the detail of the constructor rather than part of the interface.  By using the enum class types mentioned above, we can make it very clear from the interface that it's not going to be possible to create invalid cards:

Card(ranks r, suits s);

Delete unhelpful autogenerated operators

Duplicating cards will get you kicked out of most casinos.  It's probably better to avoid such trouble before it begins by making it a little harder to do:

Card() = delete;
Card(Card&) = delete;

Wrap all of your objects inside a name

Rather than putting just the constants in a namespace, put your whole interface into a namespace.  In some future use in which your code is used within an electronic poker game cruise ship simulator, your Card could then be distinguished from a circuit Card that might be part of the electronic game classes, and your Deck could be distinguished from the Decks of a cruise ship.

Reconsider your class design

The Deck class is really just a collection of Card objects.  While you may have ideas on how to use your Deck class, it's very likely that you're going to want to have many other kinds of Card collections such as Hand or DiscardPile or Shoe (if you're simulating casino blackjack).  In addition, even the notion of Deck can change if you're using it for, say, Pinochle which uses a 48-card deck rather than a 52-card deck.  For that reason, it may be better to define a generic Card collection and then specialize that for the various uses.

Reconsider your comparison operators

The comparison operators for the Card class may well be valid for your particular use, in which case, you should certainly use them, but comparisons and relative valuations tend to change by the particular rules of each card game.  In some games the Ace is low, and in others high.  In some, such as blackjack, it can take on the values of 1 or 11.  For that reason, it is likely that the comparison operators are likely to need to be changed.  This suggests that they could be made virtual so that derived Card classes can override them.


Using decorator pattern to validate an entity

Unfortunately ecmascript-6 does not have support for interfaces yet. What this means is that Group does not quite make sense and that DefaultGroup should be your Group instead. No matter how I look at it I don't really see any kind of usefulness on having both of those classes existing.

If we extrapolate the decorator pattern to one of the most common examples in C# present in Stream classes (StreamReader, BufferedStream, ...) you will clearly see that there is no DefaultStream.

It doesn't even exist a common interface. I am not saying that is the best and that is always what you should do. What you should do is to think about what makes sense on your language and in your requisites.

Keep going with this conversation you are doing your architecture. But did you reach to the conclusion that decorator pattern was really the best choice?

Could strategy pattern, together with composite pattern be a better alternative?

If I had to answer this question I would probably answer: Yes it would.

Let me explain why:

The decorator exists in order to add some kind of functionality that your class didn't have before. It's true that in your use case you are adding validation, a thing that you didn't have before. However what you really want to do is to have multiple kind of validations (strategies). You then could use all strategies you wanted by putting them on a list, iterating over them and call the validation method (this is the composite pattern)

Not to say that Group now becomes ignorant about which kind of validation is being made. Which might be a good thing or a bad thing. If you really want your group to be aware of validation it should take a parameter on the constructor to tell him how the validation should be made.

I could keep going by asking why you have hard-coded values for the minimum and maximum length (3 and 12 respectively). And also why do you have a getLength method that does getName().length?

In case you were wondering all of this that I said would translate in the following implementation

class Group {
  constructor(name) {
    this.name = name;
  }

  getName() {
    return this.name;
  }

  toString() {
    return `Group: ${this.name}`;
  }
}

class Validation {
  constructor() {
  }

  validate(value) {
    return true;
  }
}

class OnlyUpCaseValidaton extends Validation {
  constructor() {
    super();
  }

  validate(value) {
    let REGEX_UP_CASE = /^[A-Z]*$/g;
    return REGEX_UP_CASE.test(value);
  }
}

class LengthValidation extends Validation {
  constructor(minLength, maxLength) {
    super();
    this.minLength = minLength || 3;
    this.maxLength = maxLength || 12;
  }

  validate(value) {
    let len = value.length;
    return len >= this.minLength && len <= this.maxLength;
  }
}

let g = new Group('FOOOBAAAR');
//poor man's composite...
var validations = [new LengthValidation(), new OnlyUpCaseValidaton()];
console.log(validations.every(function(validation){
    return validation.validate(g.getName())
}));


You could use the native Array.map method in modern browsers (see MDN)

const newNames = ['John', 'Jim', 'Joe'].map( name => `${name} ${name}`);
console.log(newNames);


Is there anything I need to add or is that the best security im looking at?

There really isn't much that you can do wrong here. You correctly tell the browser to delete the cookie, and there isn't more that you can do.

But if this is all your logout code, you are vulnerable to CSRF logout. It is debatable if this is a security issue; some argue that it is not, as cookies may be forcefully deleted by overflowing the cookie jar, but that's really a browser issue that may or may not exist on the client side, so to be on the save side, you should add CSRF protection.

As a matter of best practice, you should also always die after a header redirect, as a client doesn't have to follow the redirect and code afterwards will be executed. This doesn't seem to be an issue now, but it may be in the future.

Other than that, your code is fine, but I would remove all your comments, they are just repeating what the code already says. If you want structured and named code blocks, just add functions.


General Remarks

Well done. While there are some points of improvement, you created a functional program, with proper naming of arguments, and even some basic error handling. Asking for feedback is the best way to learn, so here you get some :). Keep up the good work.

Repeating/LineWidth logic

The repeating of the value 100 is suspicious, there probably is a better solution.

   while(i < 100) {
                for(int j = 0; j < wordsOnOneLine && i < 100; j++) {

If you see this, think more and try to approach the problem differently.

The main idea (that vp_arth already posted) is to keep track of the available space in the line, no need to calculate the wordsOnOneLine

Also, you can count-down the number of words you still have to output.

You will end up with two simple counters repetitions and availableSpace. See below for more detail.

Cleanness of output

While not really enforced, you should not add a space at the end of the line if not needed. Trailing spaces are a general pain in the ass, because you can't see them and might give adverse effects.

Validating arguments

And you need to take care your user does not apply an argument that will break your program (what if the user enters an 1000 character String?), so you need to check for that too.

Java conventions

You already follow most of the java conventions (casing, bracing, etc). But you are missing a package for your class. While not needed, it is good practice.

Exit codes

While not THAT interesting, it is good practice to let you program end with an error code (integer greater than zero) if it could not run succesfully.

Proposed solution

package hundred;

/**
 * Program to print command line argument 100 times Words are never split up. Assuming that the console is 80 characters
 * wide.
 **/
public class Hundred
{
    private static final int LINE_WIDTH = 80;

    public static void main( String[] args )
    {
        if ( args.length == 0 )
        {
            System.err.println( "Argument missing" );
            System.exit( 1 ); //error status
        }
        else
        {
            String word = args[0];
            int availableWidth = LINE_WIDTH;

            if ( word.length() > availableWidth )
            {
                System.err.println( "Argument too long for the line width" );
                System.exit( 1 ); //error status
            }

            int repetitions = 100;

            while ( repetitions > 0 )
            {
                if ( availableWidth < word.length() )
                {
                    System.out.println();
                    availableWidth = LINE_WIDTH;
                }
                System.out.print( word );

                availableWidth -= word.length();

                //We might need a space, but only if the word + space still fits
                if ( availableWidth > word.length() + 1 )
                {
                    System.out.print( " " );
                    availableWidth--;
                }

                repetitions--;
            }
        }
    }
}


Is this use of (let ... and ...) in OCaml poor style?

It's not idiomatic OCaml indeed.

"and" is an effective way to say "watch out for mutual recursion".
OCaml encourages you to use nested functions instead! As The Structure of OCaml programs says: "Nested functions are, however, very useful and very heavily used in OCaml."

You would write this code as follows:

let important_operator a b =
  let foo a b = ... in
  let bar x = ... in
  let baz a b = ... in
  let merge a b = ... in
  let a', b' = foo a b in
  let a', b' = iterate_until_convergence (=)
                 (fun (a, b) -> bar (baz a b))
                 (a', b') in
  merge a', b'

Of course, you don't need to only use nested functions, you can also define bar or baz before defining important_operator. OCaml tends to only use functions that were defined "earlier", so using and for this is abusing the system.


Procedure to determine minimum number of stamps to make up a given monetary value

Let me start by saying that a while True: loop with a return embedded is a bad idea. It works, yes, but the train of logic becomes more complicated to follow the more branches are within the loop. Now if you had, say, 10p, 20p & 50p coins, this would become more and more complicated until it reached a point where you would want to rewrite it in a more sensible way.

With that out of the way, let's get on with the review.

Hard-code as little as possible. Try to use more parameters. All those 5's are for a specific use-case. Try accepting them as parameters in your function.
Return a dict instead of a tuple - it associates each price with a count of stamps of that price and makes the returned value more general with respect to prices.
while True: is a bad idea, as explained above.
Your code style and formatting is OK as per the PEP8 style guide for Python.

The way you do it - you are reimplementing division and remainder from scratch with a loop. This is, well, useless.

The way you're doing it right now is OK if you can't use the above (course restrictions?), which would have helped a lot in this case - you could have used it to get rid of the while loop altogether, just looping over the allowed prices.

What can be done for your code is moving out the part which reimplements division and remainder into functions and using them, but then there remains no difference between the way I do it and the way I suggest for you to do it here.

(Note that the extraction into functions is necessary for reducing code duplication and extending your code to support more prices).

Here is my take:

def stamps(targetValue, prices):
    currentValue = targetValue
    sortedPrices = list(reversed(sorted(prices)))
    stampCounts = []
    for price in sortedPrices:
        stampCounts.append(currentValue // price) # note floor division
        currentValue = currentValue % price # remainder
    return dict(zip(sortedPrices, stampCounts)) # return a dict for caller's convenience


Add active class to current menu with extension method or jQuery

Regardless of whether you use jQuery or C# to handle the operation it won't have a dramatic effect on page load speed, the only difference will be latency perceived by the user. Because of the manner in which JavaScript operates, you will likely find that the button does not appear as 'active' when the user first loads the page for 0.25 to 0.5s, which may not  be a big deal to you, but a user would potentially see that flicker and wonder what they did.

The only changes I would make for you is to rewrite your method just a little to read a bit cleaner:

public bool Is(string controller, string action = null)
{
    if (ViewContext.RouteData.Values["Controller"].ToString().ToLower() == controller.ToLower()
        && (action == null ||
         ViewContext.RouteData.Values["Action"].ToString().ToLower() == action.ToLower()))
        return true;
    return false;
}

To something like the following:

public bool Is(string controller, string action = null)
{
    var routeData = ViewContext.RouteData;
    var actController = routeData.Values["Controller"].ToString();
    var actAction = routeData.Values["Action"].ToString();

    return actController.ToLower() == controller.ToLower() && (action == null || actAction.ToLower() == action.ToLower());
}

Same number of LoC, but it's a little more clear what's happening.

As far as performance, I don't see any obvious bottlenecks. I think the biggest bottleneck you'll end up having is in the LINQ (this is all speculation, but we're talking microseconds, not even nanoseconds). You shouldn't be concerned of your performance until there's a measurable performance issue.


Using homogeneous coordinates to rotate an image

Rather than looping over all x and y values you could put them into a vector, that should speed things up considerably.

y=repmat(1:cols,rows,1)
x=repmat((1:rows)',cols,1)

M=[x(:) y(:) ones(rows*cols,1)];

Now you just need to multiply M or M' with T or T' and you have subsitituted that part of the code.


Project Euler 4 - Largest palindrome product

We don't need a List

        List<Integer> palindromes = new ArrayList<>();

This could be just

        int largest = -1;

As we just need to determine the largest one.

        System.out.print(Collections.max(palindromes));

This just becomes

        System.out.print(largest);

Work down, not up

        for (int i = 100; i <= 999; i++) {
            for (int j = 100; j <= 999; j++) {

This does more work than necessary.  Instead, consider

        for (int i = 999; i >= 100; i--) {
            for (int j = i; j >= 100; j--) {

You want to find the maximum.  So start with the largest possible candidate and work your way down.

Also, you don't have to check \$999\cdot 998\$ and \$998\cdot 999\$.  It's enough to test one.  So we can start j as i.

There will be more that we can do later.

Convert after calling isPalindrome

                if (isPalindrome(Integer.toString(i * j)))
                    palindromes.add(i * j);

Consider

                int product = i * j;
                if (product <= largest) {
                    break;
                }

                if (isPalindrome(product)) {
                    largest = product;
                }

If product is smaller than the largest palindrome found so far, we don't need to check these values anymore.  Also, we only update largest if product is larger.  So we don't need to do the Collections.max after.

We don't repeatedly calculate the same product (compiler probably fixes that for you anyway, but I find this easier to follow).

You said

  I have to obviously convert int to String to check is given number is palindrome.

But it is not obvious to me that we have to convert to a String to check if it is a palindrome.  That's a conceptually simple way, but we could do it more efficiently with math.  And this way, we can drop in a math-based replacement without altering this method.

And to fix the mismatched parameters without using a replacement, we could just write

    private static boolean isPalindrome(int candidate) {
        return isPalindrome(Integer.toString(candidate));
    }

And as I said, we can replace that method with a more efficient one without changing the caller.


Print the next smallest and next largest number that have the same number of 1 bits in their binary representation

You are solving this the "mathematical" way.

what about the "lego" way?

Your number consists of a string with "1"s and "0"s.

[edit]
thanks to @graybeard who pointed that the method must be changed to fulfill the requirement:

The next bigger number is when you switch the position of the most right "0" that is followed by a "1" with that following "1".

int nextBigger(int number){
  char[] binaryDigits = BigIntger.valueOf(number).toString(2).toCharArray();
  int lastZeroFollowedByIndex = findLastZeroFollowedByOneIn(binaryDigits);
  binaryDigits[lastZeroFollowedByIndex]    = '1';
  binaryDigits[lastZeroFollowedByIndex +1] = '0';
  return new BigInteger(new String(binaryDigits),2).intValue();
}


Boolean expressions evaluate to boolean. That means that can be used interchangeably with true and false.

if (numbers.get(index) == true)

is the same as

if (numbers.get(index))

if (i < 2) numbers.add(false); else numbers.add(true);

is the same as

numbers.add(i>=2);

It is also much easier to read and edit. Collapsing an if/else into one line is bad form. It forces the reader to look carefully at what is actually happening. Where as separate it across multiple lines, as you do with your other if statements allows each part to stand on its own. Additionally, dropping the curly braces means you will need to do extra work if you want to add another statement. Or, if you forget, the second line will execute unconditionally.

Why are you using a while loop for the main body? It does exactly what a for loop is designed to do and your code shows that you understand how to use them.

You should extract 2000000 into a constant. The name will make it clearer what the meaning of the number is. The constant will mean that the value clearly means the same thing in both places.

Comments are best used for describing why something is happening. Code is best for stating what is happening. If you feel that the code is complicated enough that you need to explicitly say  what is happening, that is an indication that extracting that piece of code into a function with a descriptive name would be helpful.


Nodejs functions to load and save RSA keys

require style

I (and most of the Node developers I've worked with) prefer the style where require is put on top. As stated in the guide you linked, it gives a clearer overview of what are dependencies of the module/file you're writing. No one likes to see that if some condition is successful, then a new module will be loaded. It's just unnatural.

On the other hand, you shouldn't look at const foo = require('bar') as just another variable assignment and treat it as such when you're writing Node or any other JS code. Calling require function will load a file (if not previously loaded, read more here) and make its exported object available through the variable in the file you're writing. This same thing in some other language like C/C++ would be expressed as #include <foo>, which exposes the whole file to another file.

Other things I've noted

Usage of fs module

I see that you have helper functions that wrap fs.readFile and fs.writeFile in promises. I'm not sure if you are aware of 2 things:

There is a promisify method which can do this for you.
There already exist promisifed versions of this functions.

My suggestion is to use fs.readFileSync and fs.writeFileSync instead of wrapping them yourself.

Line 55

I'm not sure what was your intention here, but you've just called a function which returns a promise without waiting for the promise to be resolved. Since you're writing to the disk, this operation might not finish once a function from your returned object gets called. I'd just add await here.

Line 73

First, add a space between the ) and ? to be consistent with the style you have for : and stuff around it.
Second, break that long condition into either a function, or to a several variables. I'd personally go here with functions:

const notInvalidated = (invalidations, payload) => !invalidations[payload.userUuid] || payload.invalidationCounter === invalidations[payload.userUuid]
const hasValidIat = (invalidBefore, payload) => payload.iat >= invalidBefore

And then your condition could be written as:

notInvalidated(invalidationByUserUUID, payload) && hasValidIat(invalidBefore, payload) ? payload : false

Still long, but more readable.

module.exports mess

My personal preference is to have module.exports either export a function or an object, so make it as short as possible. But from your code on pastebin, it looks like your core logic is put there. For me, this is unreadable and I would look how to refactor this into something which will return either a single function or just a simple object.
In your case, I'd first move that function to a new named function, something like this:

const myJwt = async (keyPath) => { /* the rest */ }

module.exports = myJwt

From there, I'd move the functions in the object you are returning to the file level:

const generateNewKeyPair = async () => { /* ... */ }
/* also for sign, verify and invalidateOldUserToken */

const myJwt = async (keyPaht) => {
  /* whatever goes here */
  return {
    generateNewKeyPair,
    sign,
    verify,
    invalidateOldUserToken,
  }
}

module.exports = myJwt

This refactoring will be a bit tricky, because you have these two variables invalidationByUserUUID and invalidBefore which should be shared with the functions that I suggested extracting. You should maybe consider to wrap this in a class and return the class instead of a function. Either that, or you'll have to pass invalidationByUserUUID and invalidBefore with every function call.

Hope my comments make sense. I didn't do a whole code refactoring since I'm not 100% sure what you wanted to achieve, but if needed, I can give it a try.


Logging into WebAPI 2 site from c# desktop application

I was going to make a very large post with altered code, but I don't fully understand what your code is doing so all I will suggest is that

You need to use a consistent code style. camelCase for variables/arguments, PascalCase for runtime constants (types/constants) and properties, and _camelCase for private fields on an object.
Your methods are simply doing way too much. Your 2 methods there are connecting to two different web pages, composing two URLs, parsing JSON into a POCO (and then back out again), and doing authentication on top of all of that.
You aren't managing the lifecycle of HttpClient. There is a general consensus that creating and disposing HttpClients is not the best use of a class. At the very least you should be Disposing of your HttpClients but all you're doing in your current code is letting your HttpClients leak. Consider that your functions do not need to know how to create a HttpClient, they just need to know how to connect to a Url - let the caller of the function do the heavy lifting for you.

Once again I'd give you a code sample but I just don't understand what your code is trying to do, which is my own fault, because I haven't really used much HTTP in .NET.

Here are the responsibilities of your two methods so far:

Create a HttpClient
Decode JSON into a POCO
Create authentication token
Compose url from base url, secondary url and a query string
Apply authentication token to HttpClient
Handle the response of one of the HttpClients
Prepare HttpClient headers

The majority of these should be in their own function.


Expressing positive integers as the sum of different charming numbers

Your to_base_10(x) function may be easily rewritten as:

def to_base_10(base_3):
    return int(base_3, 3)

However, you are only using the function to convert base 3 numbers of the forms '1' followed by n zeros, and '12' followed by n zeros.  These can be directly computed as:

to_base_10('1' + '0'*n) -->  3 ** n
to_base_10('12' + '0'*n) --> 5 * 3**n

The output of the to_base_3(x) function is only used to produce 2 values: len(base_3_value) and digit = base_3_value[0].  These can also be directly computed.

if number > 0:
    len_base_3_value = int(math.log(number, 3)) + 1
    digit = number // (3 ** (len_base_3_value - 1))
else:
    len_base_3_value = 1
    digit = 0

Note: digit is now an int (0, 1, or 2), not a str ('0', '1', or '2')

You recursively call and then return the value of find_charming_components(number, charming_components).  Python does not do tail recursion optimization, so this should be replaced with a simple loop, instead of recursion.


Extracting numeric values from a string containing key:value pairs

You usually want a zero-width word boundary \b on either end of the regex, to avoid matching things like 1a:1a.

There's no need to capture [a-z]+ since you are throwing it away.

You can use lookbehind (?<=…) assertions to require a match to be preceded by whatever, without including the whatever in the match result.  This means no need for capturing parenthesis, only the integer is included in the match, and the final map is simply _.toInt. Variable-width lookbehind was introduced in Java 9; older versions have only fixed-width lookbehind.

Finally, removing the variable makes braces unnecessary.

def numericValues(text: String): List[Int] = """(?<=\b[a-z]+\s*:\s*)\d+\b""".r.findAllIn(text).toList.map(_.toInt)

With only fixed-width lookbehind, you could postprocess the matches to remove non-numerics:

….map(_.replaceAll("[^0-9]", "").toInt)

Or, more idiomatically and less hacky, just capture the digits and extract the capture groups:

"""\b[a-z]+\s*:\s*(\d+)\b""".r.findAllIn(text).matchData.toList.map(_.group(1).toInt)


A crude clojure progress reporting function

I will point out stuff that I'd do differently, though I am by no means a clojure expert, I do have some experience in it. Numbered items will reappear inside the code as comments.

no DEF inside defn body

def will define the var for your entire namespace as such, you will pollude your namespace with temporaries
use LET instead

no DO necessary inside the body of IF

furthermore, I find it more idiomatic to use WHEN in the case that no else branch exists

using @ instead of DEREF could reduce verbosity
by using UPDATE-IN instead of INC, you can simply pass a transformation function

note the vector notation however: UPDATE-IN takes a vector of keywords

You can pass a partial function, i.e. a function which is
partially applied as the transformation function to update the total-time-taken
No need to nest LETs, you can write all definitions into a single let

Code:

(defn run-with-reporting [sequence-function-maps stop-time]
  (let [beginning-time (java.util.Date.) ;; 1.
        seq-counts (map #(count (:sequence %)) sequence-function-maps)
        total-sequence-counts (reduce + seq-counts)
        prog-rpt-ref (ref {:todo total-sequence-counts, :done 0, :total-time-taken 0})]
    (println (str "total counts = " total-sequence-counts))
    (doseq [sequence-function-map sequence-function-maps]
      (let [sequence (:sequence sequence-function-map),
            function (:function sequence-function-map)]
        (loop [loop-seq sequence]
          (if (and stop-time (clj-time/after? (clj-time/now) stop-time))
            (println "stopped at " (clj-time/now) ". Requested stop at " stop-time)
            (when loop-seq ;; 2.
              (let [item (first loop-seq)
                    start-time (java.util.Date.)]
                (function item)
                (let [end-time (java.util.Date.)
                      time-delta (- (.getTime end-time) (.getTime start-time))
                      derefd-rpt @prog-rpt-ref]         ;; 3.
                  (dosync (alter prog-rpt-ref update-in ;; 4.
                                 [:done] inc,
                                 [:total-time-taken] (partial + time-delta))) ;; 5.
                  (let [derefd-rpt @prog-rpt-ref ;; 3. & 6.
                        average-time (/ (:total-time-taken derefd-rpt) (:done derefd-rpt))]
                    (println "Avg time / each = " (hrs-min-sec average-time)
                             ", Estimated total time left = "
                             (hrs-min-sec (* average-time (- (:todo derefd-rpt) (:done derefd-rpt)))))))
                (recur (next loop-seq))))))))
    (let [derefd-rpt (deref prog-rpt-ref)]
      (println "Total time taken = " (hrs-min-sec (- (.getTime (java.util.Date.)) (.getTime beginning-time))) ", Done = " (:done derefd-rpt) "/" (:todo derefd-rpt))))
  )

I would try to reduce verbosity and increase readability (in the
literate sense) by utilising descriptive helper functions -
current-time instead of (.getTime (java.util.Date.))
Personally I like to keep the amount of variables as low as
possible.  Variables are great for producing side-effects,
describing complex results or for when you need a result several
times. In the case of the ref, writing @ instead of using a
temporary seems more natural to me.

As such:

I would try to reduce the amount of side-effects and
use descriptive functions to calculate complex results and place them where they belong
without temporary variables

You can use destructring for maps

(let [{:keys [key1 key2]} mymap] ...) will let-bind key1 and key2 by extracting :key1 & :key2 from mymap

Code:

(defn current-time
  "Return the current time. Same as (.getTime (java.util.Date.))."
  []
  (.getTime (java.util.Date.)))

(defn run-with-reporting [sequence-function-maps stop-time]
  (let [beginning-time (current-time) ;; 1.
        seq-counts (map #(count (:sequence %)) sequence-function-maps)
        total-sequence-counts (reduce + seq-counts)
        prog-rpt-ref (ref {:todo total-sequence-counts, :done 0, :total-time-taken 0})]
    (println (str "total counts = " total-sequence-counts))
    (doseq [sequence-function-map sequence-function-maps]
      (let [{:keys [sequence function]} sequence-function-map] ;; 9.
        (loop [loop-seq sequence]
          (if (and stop-time (clj-time/after? (clj-time/now) stop-time))
            (println "stopped at " (clj-time/now) ". Requested stop at " stop-time)
            (when loop-seq ;; 2.
              (let [item (first loop-seq)
                    start-time (current-time)] ;; 7.
                (function item)
                (dosync (alter prog-rpt-ref update-in ;; 4.
                               [:done] inc,
                               [:total-time-taken] (partial + (- (current-time) start-time)))) ;; 5., 7. & 8.
                (let [average-time (/ (:total-time-taken @prog-rpt-ref) (:done @prog-rpt-ref))] ;; 8.
                  (println "Avg time / each = " (hrs-min-sec average-time)
                           ", Estimated total time left = "
                           (hrs-min-sec (* average-time (- (:todo @prog-rpt-ref) (:done @prog-rpt-ref)))))) ;; 8.
                (recur (next loop-seq))))))))
    (println "Total time taken = " (hrs-min-sec (- (current-time) beginning-time))
             ", Done = " (:done @prog-rpt-ref)
             "/" (:todo @prog-rpt-ref))))

Now, lets take a look at the function itself. In general, when
writing in clojure you should try to keep your functions generic
and simple. By keeping them simple and focusing on only a single
task, they are usually easier to compose and reuse.
I would thus recommend splitting up your function.

In your case what you want to do is really:

map a function over a sequence: clojure already provides a function for that, namely MAP.
stop the mapping operation if a specified time has been reached.
print out the average time per call
print out total time taken

The first point is trivial.

For the second point, we can exploit the fact that clojure has lazy
sequences. This allows us to use the built-in TAKE-WHILE function
with a predicate which checks the time and stops when it has passed
your stop-time:

(defn take-until
  "Returns a lazy seq of items from coll util the STOP-TIME has been reached."
  [stop-time coll]
  (take-while
   (fn [item]
     (if (not (> (current-time) stop-time))
       true
       (do (println "stopped at " (current-time) ". Requested stop at " stop-time)
           false)))
   coll))

The third point can be achieved by simply mapping over a collection
and printing out the necessary information. This again is really
just what you did, but refactored into a function that works on any
sequence:

(defn measure-coll-retrieval
  "Returns a lazy seq of items from coll. Will print to stdout the
  average time between element extractions."
  ;; you can use destructuring inside the argument list as well, here
  ;; we're additionaly specifying some defaults for when the caller
  ;; does not provide a value
  [coll & {:keys [start-count total-count] :or {start-count 0 total-count nil}}]
  (let [beginning-time (current-time)]
    (map-indexed
     (fn [index item]
       (let [index (+ start-count index 1)
             average-time (/ (- (current-time) beginning-time) index)]
         (print "Avg time / each = " (hrs-min-sec average-time))
         (if total-count
           (println ", Estimated total time left = "
                    (hrs-min-sec (* average-time (- total-count index))))
           (println))
         item))
     coll)))

Before writing the reporting function, a little helper so we can
get around seq-chunking in clojure:

(defn unchunk
  "takes a chunked sequence and turns it into an unchunked sequence"
  [s]
  (lazy-seq
   (when-let [[x] (seq s)]
     (cons x (unchunk (rest s))))))

Now we can write the actual reporting function:

(defn run-with-reporting [sequence-function-maps stop-time]
  (let [beginning-time (current-time) ;; 1.
        seq-counts (map (comp count :sequence) sequence-function-maps)
        total-sequence-counts (reduce + seq-counts)
        intermed-count (atom 0)]
    (println (str "total counts = " total-sequence-counts))
    ;; note how it is possible to immediately destructure the map
    (doseq [{:keys [sequence function]} sequence-function-maps]
      (swap! intermed-count
             +
             (count
              ;; this is where everything happens: apply function,
              ;; take-until stop-time reached & measure average time
              (measure-coll-retrieval
               (take-until stop-time (map function (unchunk sequence)))
               :start-count @intermed-count
               :total-count total-sequence-counts))))
    (println "Total time taken = " (hrs-min-sec (- (current-time) beginning-time))
             ", Done = " @intermed-count
             "/" total-sequence-counts)))

(defn test-run-w-reporting [stop-clj-time]
  (def testing-func (fn [item] (. java.lang.Thread sleep (rand 1000))))
  (let [sequence-function-maps [{:sequence (range 30), :function testing-func},
                                {:sequence (range 15), :function testing-func}]]
    (run-with-reporting sequence-function-maps stop-clj-time)))

I hope this has helped you some.

Kind regards,
Thomas


Optimize way of reading and writing file in node.js

Interesting question,

there is really not much to optimize from a speed perspective. From a code organization perspective you should really investigate libraries that help with asynchronous coding.

From a pure coding perspective, fs.mkdirSyn will ignore the callback function you provide.

From a reliability perspective, your code will try to write to the output folder if that folder could not be created. That is not good. Also where would response be defined in that callback function?

You can apply this to multiple files by providing filePath as a parameter to readContent. readContent is by the way a terrible function name, it misleads the reader in thinking it just reads content whereas it reads contents, checks directories, optionally creates directories, processes content and writes out content. You get my point..

I am also not sure why you call the callback in readContent before all the work is done, an error might occur in creating a directory or in writing out the new content and the callback would never know..

Update:
This code works and organizes the functionality into steps without using a 3rd party library for handling asynchronous calls:

var path = require('path'),
    fs   = require('fs');
    outputDir = "output/";

function readFile( path, callback )
{
  fs.readFile( path, {encoding: 'utf-8'}, callback );
}

function verifyFolder( folderName , callback )
{
  if( fs.existsSync(outputDir) )
    return callback(true);
  fs.mkdir( outputDir, 0766, function(err){
    callback( err ? false : true );
  });
}

function processContent( content , callback ){
  callback( undefined, content.toUpperCase() );
}

function writeContent( path, content , callback )
{
  fs.writeFile( path, content, function (err) {
    if (!err)
      console.log( 'Content written to '+ path );
    callback( err, content );
  });
}

function processFile( filePath, callback) {

  var content;

  readFile( filePath, readFileCallback );

  function readFileCallback( err, data ){
    if(err)
      return callback( err, data );
    content = data;
    verifyFolder( outputDir , verifyFolderCallback );
  }

  function verifyFolderCallback( exists ){
    exists ? processContent( content , processContentCallback ) : callback( outputDir + ' does not exist' );
  }

  function processContentCallback( err, content )
  {
    if(err)
      return callback( err, content );
    writeContent( outputDir + path.basename(filePath) , content, callback );
  }
}

function logResult( err, result ){
  console.log( err || result );
}

processFile( path.join('killme.js') , logResult );


Reading columns of a delimited text file

General Remarks
The code checks incoming parameters, and throws an IllegalArgumentException when they are out of bounds (except nthCol; see later).  This is a good thing.  It would be even better if you could include the faulty indices in the error message so that I don't have to pop out the debugger. ;-)
The class seems to work with 1-based indices rather than 0-based, the latter being more common in Java[1].  As you commented about this within your code (but not in your public documentation), you've felt there's a mismatch; it may be better to use 0-based indices for consistency with the rest of the JDK.
You're going through hoops to work with arrays in the public interface while using streams and collections behind the scenes.  Consider returning lists instead of arrays, or maybe even streams if you're so inclined.
Constructors
Character encodings are important, too important to force the default encoding on your users, for any definition of 'default encoding'.  Many of the classes and methods deprecated in java.io were so because they assumed about encodings, which I've seen lead to subtle but no less spectacular breakage.[2]  Allow/force your users to specify the encoding.  If they make it be this fangled default encoding, then on their heads be it.  (A simular argument could be made for Paths.get.)
For your class, it doesn't matter how it gets its stream of strings, as long as it gets it.  Make this clear in your constructor:
Txt(Supplier<? extends Stream<String>> stream, Pattern delimiter) {
    this.stream = stream;
    this.delimiter = delimiter;
}

No fuss about encodings, file paths, IOExceptions, invalid patterns...  Just the bare needs to function.  Any other constructors or static factory methods you desire are then for convenience, and should delegate to this one.
Specifics
nthCol(int) breaks with the other methods in that it tries to fix an erroneous input parameter.  This leads to the oddness of nthCol(0) succeeding but cols(0, 0) failing.  Consistency is king in library usage: nthCol should fail, or cols should succeed.[3]
[!] cols(int[]) changes the contents of the incoming array.  You don't really need to sort this array, anyway: I'd consider it a feature if the columns returned are in the same order that I requested them.
Txt is not a very descriptive name. ;-)  Consider names such as LineSplitter or TextTable.

[1] Oh, how sweetly I loathe you, java.sql, for your 1-based indexing.
[2] Fixed record length + multi-byte encoding + JNI.  It was glorious.
[3] Personally, I lean towards "fail early, fail hard," (i.e. throw) but this depends on your intended audience.


TinyMVC Model / Plugin how to implement?

Sorry you had to wait so long, answers here tend to take some time and I've been on vacation the last week, so I wasn't keeping up with this site the way I usually do. So, here we go...

Q: "Any improvements to the code?"

First off, I don't think you quite understand inheritance. If you are extending one class from another it automagically inherits all properties and methods of the parent class. Therefore, there is no need for you to recreate a __construct() method if all you are going to do with it is call the parent one. The only reason to do it the way you have is if you had called additional code in the new constructor before or after calling the parent one. Example:

public function __construct() {
    $changedParentVar = 'new value';
    parent::__construct();
    echo 'we changed the "changedParentVar" inside the parent constructor method before running it';
}

Clarification: I'll be honest, I'm not quite sure if this stands true for deep inheritance. Say I have three classes, each inherits from the previous, and only the first has a constructor. I don't know if the third will still have the original constructor. I know it will still have all the other methods, but for some reason I want to say that magical methods are different, yet I can't find anything at the moment to prove this one way or another. So this statement is here to cover my ass :)

I'd find some way of combining your "list" methods, something like...

public function list($from, $where, $and = '') {
    if( ! empty($and)) { $and = "AND $and"; }

    return $this->db_query_all("
        SELECT *
        FROM $from
        WHERE $where
        $and
        ORDER BY position
    ");
}

If you are not going to be reusing a variable ($this->listMenu or $this->listCategorys or a foreach variable) there is no need to make them properties. The only reason you should make a variable a property is so that it can be used outside the current method. That being said, take a look at that foreach loop... There is no need to set the key/value pair as a class property as they will not be reused before they are reset, and I doubt you will reuse just the last one. This also stands true for those other two properties I mentioned, they should be variables, not properties. So the buildMenu() method should be rewritten like so.

public function buildMenu() {
    $listMenu = $this->listMenu(); //Keep this line how you have it if you are using listMenu in another method you did not include here...
    foreach($listMenu as $key => $value) {
        $listCategorys = $this->listCategorys($value['menuLinkId']);//BTW its categories not categorys... been bothering me...
        if( ! empty($listCategorys)) { $listMenu[$key]['child'] = $listCategorys; }
    }

    return $listMenu;
}

By the way, please, for everyone's sanity, always use braces {} around any statements, even if they are only one line. Its so much easier to read.

Q: How should I implement it in the view and use it on every page that is required without breaking the ideea of MVC and without rewriting again and again for each controller?

You should not implement it in the view, only in the controller. Views should only contain minimal PHP that helps output data.

I'm not sure what you mean about having to rewrite it, please clarify. In the mean time here are a few examples of how I would implement it.

If my controller is a class:

class Controller extends Menu_Model { }
//OR
class Controller {
    public function __construct() {
        include 'path/to/Menu_Model.php';
        $this->Menu_Model = new Menu_Model();
    }
}

If my controller is just a list of PHP functions or procedural:

include 'path/to/Menu_Model.php';
$Menu_Model = new Menu_Model();

Since you are using MVC, I would also suggest that you take a look at autoloading.

Q: For the following code should I keep it as Model or as a Plugin?

Not sure what you mean by plugin. Model should be fine though.


Desktop Notifications for Queue Items - Updated Code

Haven't actually tested the code, just writing JavaScript from the top of my head. Here's some notable changes:

Using what I call "return early". That way, it avoids nested ifs and your code looks flat.
Renamed a few variables so that they have more meaning, especially DELAY which is very generic and because you have 2 timeouts. Long names don't matter, readability should always be considered.
Instead of using Math.abs, why not reverse the equation? Current time is always larger than time in the past. You'll always get a positive value.
Replaced your loop with reduce because it was designed for that, an aggregator of values.
You can always use the unary + as a shorthand for converting strings into numbers. In most cases, it acts similar to parseFloat. If the string is potentially not a number, guard yourself with isNan.
Replaced your currentTime to just Date.now(). By now, browsers should at least be ES5-compliant. Anything less... you still rolling with IE6 or sumthin'?
Notification title moved down nearer to notification and after the two early-return if. That way, you don't actually generate the title if the script bails out on either of the two returns.
Inlined your notification details object. Assigning to a variable just took up space, only to be used once.

And the end result:

Notification.requestPermission();

var KEY_NEXT = 'NextReload';
var NOTIFICATION_AUTODISMISS_TIMEOUT = 100000;
var RELOAD_DELAY =  120 * 1000; //120,000 milliseconds = 2 Minutes

var currentTime = Date.now();
var lastTime = GM_getValue(KEY_NEXT, 0);
var timeDiff = currentTime - lastTime;
var nextTime = currentTime + RELOAD_DELAY;

GM_setValue(KEY_NEXT, nextTime);

setTimeout(window.location.reload, RELOAD_DELAY);

if (timeDiff > RELOAD_DELAY * 2) return;

var reviewItems = document.getElementsByClassName('dashboard-num');
var reviewItemsArray = Array.prototype.slice.call(reviewItems);
var reviewCount = reviewItemsArray.reduce(function(count, reviewItem){
    return +reviewItem.getAttribute('title').replace(',', '') + count;
}, 0);

if (reviewCount <= 0)  return;

var notificationTitle = (document.title.split(' - ')[1] + ' Review Queue').replace(' Stack Exchange', '.SE');
var n = new Notification(notificationTitle, {
    body: reviewCount + ' Review Items',
    icon: 'https://github.com/malachi26/ReviewQueueNotifier/raw/master/Resources/Icon2.jpg'
});

n.onclick = function(){
    window.focus();
    this.cancel();
};

setTimeout(n.close.bind(n), NOTIFICATION_AUTODISMISS_TIMEOUT);


I tried hard but I couldn't find anything faster than the native array_intersect_key. It runs 30-50% faster than your function in my tests. Tried with PHP 7.0 and this array generator for test data:
function randomArr($size, $max) {
  $res = [];
  for ($i = 0 ; $i<$size; $i++) {
    $r = random_int(1, $max);
    if (!isset($res[$r])) {
      $res[$r] = true;
    }
    else {
      $i = $i-1;
    }
  }
  ksort($res);
  return $res;
}

Try with 10 Mio entries and $max=100000000 and I'd be really surprised if your function was faster. Maybe the densitiy of your arrays plays a role?
However, I found one little optimization for your function: If you don't require the result to have the form [3 => true, 7 => true, 23 => true, ...], but you can work with [0 => 3, 1 => 7, 2 => 23, ...] as well, it's a bit faster to just push the intersection keys onto the result array: $intersection[] = $chave1;. But this only saved me at most 10%.


Accepting user input for tickets and tips

There's no such thing as an "If" loop, but perhaps you meant a While loop? That is exactly what you need. Otherwise this looks like a pretty good start.

Next you might consider:

adding some error checking:

is the value entered a number?
What happens if the user includes currency signs?
what happens if the user enters nothing?
Is the employee number a real employee number?
what happens if the user enters a sentence instead of a number?

Are there always exactly 4 tickets or can there be more/less?


Well, your code is correct and mostly ok. Except for two things:

You have 1-based indexing? Follow the principle of least suprise, and use zero-based indexing like all other data structures as well.
Your variable names could be more obvious.

N seems to be the length or size of your list – use this longer name instead. Also, the name N does not adhere to the best practice that variables and members should start with lowercase characters.
k is an index – the traditional abbreviation for that is i.
deleteIndex is not the index which you want to delete. Rather, it is some iteration variable. I'd call it position.

Then there are some minor style issues.

It is advisable to always use if with braces, as it tends to improve readability. If you do not use braces, I would recommend to put the body of the if on the same line. You do this with your isEmpty guards, but not at if (first.next == null).
You have very long lines. I recommend using 80–100 characters. Your longest line seems to be 104 characters long with this intendation, which is too long. (Incidentally, your lines get shorter if you use the if with curlies…).
Instead of an NoSuchElementException you should consider an IndexOutOfBoundsException.

Some parts of your code could be made more obvious, or structured differently:

In delete, you have the test if (first.next == null), where you actually want to test if (size == 1).
Finding a node at a certain position is so useful that it should have a method of its own. You want a Node previous = nodeAt(i - 1); ... instead of the for loops.
If you don't do that, your for loops still have the problem that they do three things between iterations: previous = node; node = node.next; position++. You have put one of these at the end of the loop body, the rest in the increment statement of the for loop. It would have been better to group these together.


Two comments -

Entity Framework already does what you do in the first loop. If you load entities into a context, for example by querying them, EF populates navigation properties by a process called relationship fixup.

So if you do ...

var announcements = _context.JobAnnouncements
    .Include(a => a.Portal)
    .Where(a => a.To.Day >= DateTime.Now.Day)
    .Where(a => a.IsDeleted == false)
    .ToList();

var positions = _context.JobAnnouncementPositions
    .Include(a => a.Team)
    .Include(a => a.Level)
    .Include(a => a.Technology)
    .Include(a => a.DocumentsInfo.Select(d => d.Document))
    .Where(p => p.IsDeleted == false)
    .ToList();

... You'll notice that both JobAnnouncement.JobAnnouncementPosition and JobAnnouncementPosition.JobAnnouncements are populated as far as their entities are available.
The second loop isn't necessary. You can return positions. It won't contain null objects.

That would leave you with the two queries and a return statement.

But there's more.

As you say, if you use Include, you get all data, including deleted items. It's because of this annoying inability of EF to filter Includes why such elaborate workarounds are necessary. But there is a third-party library that makes this a lot easier: EntityFramework.DynamicFilters.

This library offers a simple API to define global filters that can be switched on and off. In you case it could look like:

modelBuilder.Filter("ActiveJobAnnouncements",
                        (JobAnnouncement a) => !a.IsDeleted);
modelBuilder.Filter("ActiveJobAnnouncementPositions",
                        (JobAnnouncementPositions p) => !p.IsDeleted);

Having these filters added to the model builder in OnModelCreating, you'll see that whenever you query any of these entities, the filter !IsDeleted will be part of the SQL query. Also when using Includes. If you want deleted items as well, just disable the filters in a context instance:

context.DisableFilter("ActiveJobAnnouncements");
context.DisableFilter("ActiveJobAnnouncementPositions");

I think this library is a gem.

One more thing: I my opinion, repositories, if you decide to use them, should be generic repositories. That means, for each entity class they do exactly the same thing. Your GetForListActive() method doesn't belong in a repository, rather in a service (that uses repositories).


General Remarks

For the most part, this code is quite good if it's truly one of the first programs you've written. I've seen experienced coders with a University degree do much worse things. Congrats.
Avoid: while True:, catch Exception, raise Exception in the future. These should only be used in rare cases, and yours wasn't one.
KISS. That try..except block where you raise and catch an exception is just too complex for what can simply be achieved with an if statement.
Consider the control flow. There's a couple of bugs that I found because some of the conditions were incomplete. I've annotated and fixed some of them in the line-by-line review, and will put them rest as "exercises" at the end.
Avoid the use of quit() (or even sys.exit()) and opt for an early return instead.

Personal Remarks and Hints

Consider adopting type hinting. A small program like this is ideal to explore Python type hinting, and tools such as mypy can make your life a lot easier once you get the hang of it.
I would've liked to see some docstrings in your module and functions.
Variable names and functions names were okay for the most part, although there's room for improvement. Always make them indicative of the variable/function's purpose, and avoid confusion.
Consider the visibility of your functions, and mark functions that should not be visible outside of your module as "private" by prefixing them with an underscore. Although unnecessary for this code, it's good practice for the future.

Line-by-Line Review

Without further ado, here's a line-by-line review with some inline comments and personal suggestions for improvement I've made while reading your code.

import random

# EXERCISES:
# - What if I win, but I want to play another round?
# - What happens if I guess the same character twice? What *should* happen?
#   Maybe it's already okay.

# COMMENT: Putting this list in the `pick_random_word` function will constantly
# reconstruct the list, which is redundant. Instead, moving it to the global
# scope will only construct it once.
# NOTE: Putting variables into the global scope is also considered bad
# practice, but in this simple case there's not a lot wrong with it. There's
# other options that I won't go into detail on.
# COMMENT: You removed "javascript" because @Gloweye correctly pointed out a
# bug in your program. We'll instead fix this bug here.
_WORD_LIST = [
        "python", "c", "java", "swift", "html", "css", "go", "ruby",
        "javascript"]

# COMMENT: Magic constants are a bad practice to have in your source code. I've
# extracted the maximum attempts to a global variable, so if you want to
# provide more attempts at a later date, you just have to change this, and not
# search for the number in the code.
_MAX_FAILED_ATTEMPTS = 7

# COMMENT: I've prefixed all function definitions with an underscore. This is
# mostly just a convention to denote names that should be kept internal. In
# case of modules, this signifies a user of the module that this is not a
# function they should be concerned with. In your case, this is probably
# redundant, but it's good practice for the future.
def _pick_random_word():
    # COMMENT: Don't assign and immediately return, instead, return without
    # assignment. This makes your code clearer.
    return random.choice(_WORD_LIST)

def _make_word_classified(word):
    # COMMENT: Again, immediately return instead of assigning to a variable
    # first. Secondly, lists can be "multiplied". This replicates the contents,
    # just like your list comprehension did previously.
    # Note: Mind the brackets so it's a list, not a string. Strings can be
    # multiplied too, but are immutable so won't work for the remainder of the
    # code.
    return ["_"] * len(word)
    # return classified_list

# COMMENT: A better name would be in order here. Something along the lines of
# `play_guessing_game` would be better, but still not ideal. `guess` feels like
# the wrong name to me.
def guess():
    # COMMENT: Confusing variable names are one of my pet peeves, so I changed
    # `word` to `target_word`. This way, when writing the code, you won't get
    # confused.
    target_word = _pick_random_word()
    classified_word = _make_word_classified(target_word)
    print(*classified_word)
    # COMMENT: Let's count the how many attempts are left, since that's what
    # we use more often: In printing as well as (now) the condition of the loop
    attempts_left = _MAX_FAILED_ATTEMPTS

    # COMMENT: I don't like `while True:`, unless it's really necessary.
    # I've changed it to iterate with a condition on the number of attempts
    # instead. This will also simplify our loop body.
    # COMMENT: We could simplify this to `while attempts_left` and use the fact
    # that 0 is equivalent to `False`, but this is more explicit.
    while attempts_left > 0:
        # COMMENT: The `try..except` block is over-engineered, it could've
        # been done with a simple `if` statement.
        answer = input("Guess a letter (Write only one letter)>: ").lower()
        # COMMENT: What happens if I don't enter anything? Should it really be
        # counted as an attempt? Thus I check if there's exactly one character.
        if len(answer) != 1:
            print("Exactly one letter is expected!")
            # COMMENT: I like the use of `continue` instead of an `else` block.
            # Both are viable, but for a large `else` body it gets hard on the
            # eyes. Well done.
            continue
        # COMMENT: Before I forget: You raised and caught `Exception`. In the
        # future, create your own custom exceptions instead, or use a specific
        # exception that's already provided by Python. `Exception` is the
        # superclass of almost all exceptions in Python, and by catching
        # exceptions, you would've suppressed different errors as well, such
        # as `IndexError`, `KeyError`, `AttributeError`, `TypeError`, ...

        # COMMENT: We'll only increment the attempt counter on mistakes, so
        # that words of arbitrary length are possible.
        # total_attempts += 1

        # COMMENT: We don't have to check this anymore, it's already checked
        # in the loop condition. Instead. we'll move the handling of running
        # out of attempts to after the loop.
        # if total_attempts >= _MAX_ATTEMPTS:
        #     print("Sorry but you lost!")
        #     try_again = input("Wanna play again? (write y or n) >: ")
        #     if try_again == 'y':
        #         guess()
        #     elif try_again == 'n':
        #         print("Goodbye!")
        #         quit()

        attempt_correct = False
        # COMMENT: Use enumerate(word) rather than range(len(word)) to get both
        # the value and the index.
        for char_idx, target_char in enumerate(target_word):
            # I've reindented this code to be 4 spaces rather than 8. New
            # blocks should always have 4 spaces.
            if answer == target_char:
                classified_word[char_idx] = answer
                attempt_correct = True

        # We still need to decrement the attempt counter if the attempt was
        # incorrect. This is why we maintain a boolean and set it to True only
        # if the attempt is correct.
        if not attempt_correct:
            attempts_left -= 1

        # COMMENT: Let's move this out of that loop, so we only compare the
        # words once, rather than every time we access a character.
        # COMMENT: Instead of turning the classified word into a string, let's
        # instead check whether it still contains an underscore to check if
        # we're done. This is more elegant.
        if "_" not in classified_word:
            print("You won!")
            # COMMENT: Instead of calling `quit()`, we'll return. I'm
            # `quit()` is not really an elegant way to exit a program,
            # and is not necessary here. Returning early will simply
            # break out of the function (and thus also the loop) and
            # thus stop the game.
            # COMMENT: Exercise for you: What if I wanted to continue
            # to play another round?
            return

        # COMMENT: You could move this to the top of the loop, and do away
        # with the initial print before the loop, and then you'd have the
        # "Total attempts left" from the start.
        print(*classified_word, f"\nTotal attempts left: {attempts_left}")

    # If we reach the end of this loop, we've lost, since if we've won,
    # we'd already have returned from the function.
    print("Sorry but you lost!")
    try_again = input("Wanna play again? (write y or n) >: ")
    # COMMENT: Python makes no distinction between strings and characters, so
    # single quotes and double quotes are equivalent. "y" and "n" here were
    # single quotes while the rest of your strings are double quotes.
    # Be consistent. Choose one and stick with it.
    if try_again == "y":
        # Okay, but what if I play millions of times? It's likely never going
        # to be an issue, but if I play millions of times, this will cause a
        # stack overflow because of the recursion. Prefer iteration (with a
        # `for` or `while` loop) instead. Python does not have tail-call
        # optimization: https://stackoverflow.com/q/13591970/10973209
        guess()
    # We still need the `else` to print the goodbye, otherwise it would print
    # goodbye multiple times if we recursively call ourselves. I've changed it
    # to `else` so that it prints goodbye even if I didn't say 'n'.
    # This would previously cause a bug when it was still in the loop. If I
    # entered 'a', it would just continue the game and I'd have an infinite
    # number of attempts.
    else:
        print("Goodbye!")
        # Now that this is moved outside of the loop, we don't need to return
        # or quit anymore, the function will just end.

if __name__ == "__main__":
    guess()

Exercises

There's still room for improvement, and I'll give you a few pointers on where to start:

Consider the case where I'm forgetful, and I've typed the same character twice. How should this be handled? How is this currently handled? Is that okay?
I've won the game. Now what? I'd like to play again, please and thank you.
I already mentioned in the code the possibility of stack overflow because Python doesn't perform so-called tail-call optimisation. I doubt you'll ever run into issues with this program because of this, but it's still a good exercise to 1) look into what tail-call optimisation is and why your program could crash without it, and 2) fix the program so that it wouldn't have that problem.


Query to compare execution performance metrics for the three most recent months

You might want to use Common Table Expression or Should use meaningful table alias in Join.

You might also want to use indexes on your date column with <= and >= operator instead of between.

Surround your column names in [] instead of single quotes.


The following looks like it is much simpler and most of the way there:

func countLetters (string:String) -> String {
  var dict : [Character:Int] = [:]
  for letter in string {
    dict[letter] = 1 + (dict[letter] ?? 0)
  }

 //  dict -> array of tuples -> sort based on tuple .0
 var dictSorted = map(dict) { $0 }.sorted { $0.0 < $1.0 }

 // your string to return.
 return " ".join (dictSorted { (key,val) -> String in return "\(key):\(val)" })
}