Matrix class with overloaded `operator[]`

Pragma once

Instead of

#ifndef DP2_MATRIX_H
#define DP2_MATRIX_H

consider using

#pragma once

Once is non-standard, but supported by all compilers supporting
C++14 and reduces compilation times.

Includes

On MSVC, #include <stdexcept> is needed for the out_of_range
error. I also think your include lines look tidier if you sort them in
alphabetical order. :)

Bounds checking

Matrix<int>(10, 10, 0)[10][0]

Is an error that will be detected by your bounds checking, but

Matrix<int>(10, 10, 0)[0][10]

is the same type of error, but won't be detected. Consider following
the STL convention described in this Stackoverflow
answer. That
is, you remove bounds checking from operator[] but add a method at
which does bounds checking for both dimensions.

Const correctness

You should add const declared variants of the accessors. You can
also add it to the parameters, but imho, that is not as useful.

Result:

#pragma once

#include <algorithm>
#include <cstdio>
#include <memory>
#include <stdexcept>

template <typename T>
class Matrix {
private:
    size_t row{};
    size_t col{};
    std::unique_ptr<T[]> data;
    void boundscheck(int r, int c) const {
        if (!(0 <= r && r < row && 0 <= c && c < col)) {
            throw std::out_of_range("Can not access out of bound element!");
        }
    }
public:
    // Set all the values of the Matrix
    void setValues(T value) {
        std::fill_n(data.get(), row*col, value);
    }
    explicit Matrix(size_t row, size_t col, T def) {
        // Create a matrix of row X col and initialize
        // each element of the matrix with def
        this->row = row;
        this->col = col;
        this->data = std::make_unique<T[]>(this->row * this->col);
        setValues(def);
    }
    // Overload the [] operator for the 2d array like access
    T* operator[](int r) {
        return &this->data[r * col];
    }
    const T* operator[](int r) const {
        return &this->data[r * col];
    }
    T& at(int r, int c) {
        boundscheck(r, c);
        return this->data[r * col + c];
    }
    const T& at(int r, int c) const {
        boundscheck(r, c);
        return this->data[r * col + c];
    }
    // Overload the << operator for console logging
    friend std::ostream& operator<< (std::ostream& os, Matrix &mObj) {
        auto shape = mObj.shape();
        for(int i=0; i< shape.first; i++) {
            for(int j=0; j<shape.second; j++) {
                os << mObj[i][j] << " ";
            }
            os << "\n";
        }
        return os;
    }
    // Get row and col values
    std::pair<size_t, size_t> shape() const {
        return std::make_pair(this->row, this->col);
    }
};

I don't think it is possible to make a general matrix class consume less memory or run quicker than that. Compilers generate pretty good code for the accessor functions. You probably have to use a different data type such as a sparse matrix to improve performance much.


Function to generate nearly sorted numbers

def nearly_sorted_numbers(n):
    if n >= 100:
        x = (int)(n/10)

Use int(n//10), the // explicitly request integer division and python doesn't have casts

    elif n >= 10:
        x = 9
    else:
        x = 4

I wouldn't name the variable x, as it gives no hint as to what it means. I'd also wonder whether it wouldn't be better as a parameter to this function. It seems out of place to be deciding that here.

    numbers = []
    for i in range(1,n):
        if i%x==0:
            numbers.append(random.randint(0,n))
        else:
            numbers.append(i)
return numbers


How to refactor a method with many prameters that sets a bit array

You could use a params array to pass the parameters
public void SetConfiguration(params bool[] modes)
{
    var setBits = new BitArray(8);

    for (int i = 0; i < modes.Length; i++)
    {
        setBits.Set(i, modes[i]);
    }

    byte[] byteSet = new byte[1];
    setBits.CopyTo(byteSet, 0);
    _mode = byteSet[0];
}

You might want to add tests to ensure modes is not longer than 8 or you could expand the code to automatically set more than one byte in such cases. Shorter should be okay.
You can call it with individual parameters or with a bool array.
SetConfiguration(false, true, true, false, true, true, true, false);

var modes = new bool[] {false, true, true, false, true, true, true, false};
SetConfiguration(modes);


Getting the square of the difference between many points in a NumPy array

Python slow, C fast
By having the loops in Python you're basically cutting one of your legs off. It should come as no surprise that the one legged human will lose to the two legged human.
The question we should be asking is how can we slice pox1 to get what we want.

We should split the for loop into two comprehensions so we can see how we'd do it in numpy.
a = [pox1[i]       for i in range(num, len(pox1))]
b = [pox1[i - num] for i in range(num, len(pox1))]
z = (a - b) ** 2

a is very simple we just slice with the values of the range. But b is a bit harder, we can just move the - num into the range and we'll be able to do the same.
a = [pox1[i] for i in range(num, len(pox1))]
b = [pox1[i] for i in range(0, len(pox1) - num)]
z = (a - b) ** 2

Convert it to slices
a = pox1[num : len(pox1)]
b = pox1[0 : len(pox1) - num]
z = (a - b) ** 2

Use some slice sugar
a = pox1[num :]
b = pox1[: len(pox1) - num]
z = (a - b) ** 2

Put back in your code
for num in range(len(time) - 1):
    y[num] = np.mean((pox1[num :] - pox1[: len(pox1) - num]) ** 2)

I changed the size to 4000 and this cut it from 5.04s to 0.07s. To get 40000 changes with the updated code takes 3.30s.
import numpy as np
import time as t

SIZE = 4000
pox1 = np.random.randint(1000, size=SIZE)
time = np.arange(SIZE)

y=np.zeros(len(pox1))
w=np.zeros(len(pox1))

start = t.time()

for num in range(len(time)-1):
    y[num] = np.mean((pox1[num :] - pox1[:len(pox1) - num]) ** 2)

endtime = t.time() - start
print(y, endtime)


I am very sure it is thread safe.

Actually, it's not because the done is not in happens-before relations with the result.

But you can reach the desired behavior without extending anything: just check isDone() and call get() only if it was true.


Basically your algorithm looks correct, however:

You should use unsigned ints or have some treatment for the signs, otherwise I guess (didn't check it though) that your results for negative numbers will be wrong
Don't test for 0 explicitly, i.e. just write while(m) and if(m & 1)


Struggling to unit test Angular, was this module the best approach?

Injecting the $injector service can help by facilitating the use of optional dependencies:

app.factory('templateRepository', [ '$injector', function($injector) {
  function lookupUrlFor(contentType) {
   // Do your translation here
  }

  return {
    getTemplate: function(contentType) {
      var templateCache = $injector.get('$templateCache');
      return templateCache.get(lookupUrlFor(contentType));
      }
    }
}])

That way the unit tests only needs to inject $injector and mocks can be avoided.

References

Optional Dependencies in Angular.js
Avoid circular dependencies with AngularJS Directives | endjin blog
ngMock / $httpBackend


Reposition vertices at the origin of a coordinate system

I would create a separate method for calculating averages and use variables for them, so that the code is more legible.

I don't personally like the use of arrays such as sum[] and avg[] because looping over them makes it hard to tell what you are trying to access. If you do want to use them, I would save their indices (or offsets) in static final fields so that the accesses looks like this:

    sum[i + X_OFFSET] = ...;
    sum[i + Y_OFFSET] = ...;
    sum[i + Z_OFFSET] = ...;

I used the stream API for convenience - a loop would be fine too.

private static final int X_OFFSET = 0;
private static final int Y_OFFSET = 1;
private static final int Z_OFFSET = 2;

public static void centerVertices(FloatBuffer buf) {

    float[] objVertices = new float[buf.capacity()];
    buf.get(objVertices);

    float xAvg = (float) getAverage(objVertices, X_OFFSET);
    float yAvg = (float) getAverage(objVertices, Y_OFFSET);
    float zAvg = (float) getAverage(objVertices, Z_OFFSET);

    for (int i = 0; i < objVertices.length; i += 3) {
        objVertices[i + X_OFFSET] -= xAvg;
        objVertices[i + Y_OFFSET] -= yAvg;
        objVertices[i + Z_OFFSET] -= zAvg;
    }

    for (int i = 0; i < objVertices.length; i++) {
        buf.put(i, objVertices[i]);
    }
}

/**
 * Get the average of every third element in the array (with offset)
 */
private static double getAverage(float[] arr, int offset) {
    return IntStream //
            .range(0, arr.length) //
            .filter(i -> i % 3 == offset) //
            .mapToDouble(i -> arr[i]).average() //
            .getAsDouble();
}
```


Iterative implementation of K of N variations

Your code is wrong: if I test it with n=3, k=3 I get

  (1 1 1), (1 1 2), (1 1 3), (1 2 2), (1 2 3), (1 3 3), (2 5 4), (3 7 6)

However, you're on the right lines. Assuming that you want (or at least don't mind) to return each combination in ascending order, the way that I find intuitive to think about it is as a set of k nested loops:

for (combination[0] = 1; combination[0] <= n; combination[0]++)
    for (combination[1] = combination[0]; combination[1] <= n; combination[1]++)
        ...
            for (combination[k] = combination[k-1]; combination[k] <= n; combination[k]++)
                PrintCombination(combination);

To turn that into an iterative approach, you count but when you overflow then instead of resetting to 0 you reset to the final value which doesn't overflow. I agree with Kore's now deleted answer that you should use Enumerable.Repeat to initialise, and I also think you should make the generation method generate rather than print, so it comes down to

    private static IEnumerable<int[]> FindCombinations(int n, int k)
    {
        var combination = Enumerable.Repeat(1, k).ToArray();
        while (true)
        {
            // generate current combination
            yield return (int[])combination.Clone();

            // find index which isn't going to overflow
            int index = k - 1;
            while (combination[index] == n)
            {
                if (--index < 0) yield break;
            }

            // increment and fill right
            for (int finalDigit = combination[index] + 1; index < n; index++)
            {
                combination[index] = finalDigit;
            }
        }
    }

The performance is O(n) per combination returned, and that is optimal (just cloning the answer to return it is already O(n), and even if we don't clone and guarantee elsewhere that we won't modify the array, we'll still surely want to use it).


From a once over:

dst stands for daylight saving time, you should comment that
offset I assume is the offset to the UTC (Greenwich time), you should comment that as well
I am ambiguous about declaring rawOffset, dstOffset, timeoutId. I can see the value of self documenting code, but is it worth it ? Not sure. The code works fine if you delete those 3 statements.
Consider falsy evaluations

if (typeof dst !== "undefined") {
  LiveTime.dstOffset = dst * 1000;
}

compared to

if (dst) {
  LiveTime.dstOffset = dst * 1000;
}

or even (a bit hacky)

LiveTime.dstOffset = dst ? dst * 1000 : 0;

Do not declare variables twice like here:

var now = new Date();
var now = new Date(

You can get the timestring this way:

now.toTimeString().substring(0,8);

This basically keeps only the first 8 (hh:mm:ss) characters of the time string
You can get the UTC date value this way:

new Date((new Date()).toUTCString().slice(0,-4) )

This gets the UTC date, strips off the timezone part and re-creates the date
document.getElementById("current-time"); <- This should be a parameter
As @Pinoniq mentioned, ideally you should write your class/code so that you can run multiple instances.
LiveTime is not a constructor (yet), so it should be called liveTime

This would be my counter proposal:

function liveTime(elementId, offsetSeconds, dayLightTimeSavingSeconds) {
    "use strict";

    var timeZoneOffset = 0,
        daylightTimeSavingOffset = 0,
        element = document.getElementById(elementId),
        timeoutId;

    if( offsetSeconds ){
      setTimeOffset( offsetSeconds, dayLightTimeSavingSeconds );
    }

    function setTimeOffset(offsetSeconds, dayLightTimeSavingSeconds) {
        //Convert to milliseconds
        timeZoneOffset = offsetSeconds * 1000;
        daylightTimeSavingOffset = (dayLightTimeSavingSeconds || 0) * 1000;
    }

    function start() {
        if( timeoutId ){
          return; //We already started
        }
        (function increment() {
            //Set the time to UTC time
            var now = new Date((new Date()).toUTCString().slice(0, -4));
            //Add the configured offsets
            now.setTime(now.valueOf() + timeZoneOffset + daylightTimeSavingOffset);
            //Update the HTML
            element.innerHTML = now.toTimeString().substring(0, 8);
            //Come back again
            timeoutId = setTimeout(increment, 50);
        })();
    }

    function stop() {
        clearTimeout(timeoutId);
        timeoutId = 0;
    }
    return {
        setTimeOffset: setTimeOffset,
        start: start,
        stop: stop
    };
}

//usage example
liveTime('current-time',-9 * 3600, 3600).start();
liveTime('current-time2', 4 * 3600 ).start();
Alaska time:

Moscow time:


I can't be sure of this (I need to foster my XNA knowledge), but I would probably derive that class from DrawableGameComponent so that the Update and Draw methods would be overrides (not just methods that happen to be named "Update" and "Draw"), but deriving from that class might have other consequences that I'm not aware of; again, my XNA is fairly basic - it just seems natural to me for a class that has Update and a Draw methods, to derive from DrawableGameComponent: these method names are not an accident.
Update
Your Update() method is looping through each GameScreen and calling Update() on them all:

foreach (GameScreen screen in gameScreens)
{
    screen.Update(gameTime);
}

I think doing this incurs non-necessary processing: why would you bother updating the splash screen and pause screen at every single iteration? You're wasting cycles here.
Draw
Your Draw() method is more selective:

public void Draw(SpriteBatch spriteBatch)
{
    switch (ScreenState.Instance.CurrentState)
    {
        case State.Splashscreen:
            gameScreens[0].Draw(spriteBatch);
            break;
        case State.Menu:
            gameScreens[1].Draw(spriteBatch);
            break;
        case State.Play:
            gameScreens[2].Draw(spriteBatch);
            break;
        case State.Pause:
            gameScreens[3].Draw(spriteBatch);
            break;
    }
}

I like that you're using an enum here, but I don't like that you've hard-coded the gameScreens indices. Let's see.. you're storing the screens in a List, here:

List<GameScreen> gameScreens = new List<GameScreen>();

public ScreenManager()
{
    gameScreens.Add(new Splashscreen());
    gameScreens.Add(new Mainscreen());
    gameScreens.Add(new Playscreen());
    gameScreens.Add(new Pausescreen());
}

Allow me to open a nitpicking parenthesis here:

Nitpick
Instead of List<GameScreen> gameScreens = new List<GameScreen>(); and then adding the screens in the list at construction, I would have used an interface here, and initialized everything in a single statement:
private readonly IList<GameScreen> _gameScreens;

public ScreenManager()
{
    _gameScreens = new List<GameScreen>
                           {
                               new SplashScreen(),
                               new MainScreen(),
                               new PlayScreen(),
                               new PauseScreen()
                           };
}

This allows the _gameScreens private field to be readonly, which prevents the list's reference to be tampered with.

The mechanics work, but could work better if you leveraged IDictionary and turned List<GameScreen> gameScreens into a IDictionary<State, Action<SpriteBatch>>:
private readonly IDictionary<State, Action<SpriteBatch>> _gameScreenRenderer;
private readonly GameScreen _splashScreen = new SplashScreen();
private readonly GameScreen _mainScreen = new MainScreen();
private readonly GameScreen _playScreen = new PlayScreen();
private readonly GameScreen _pauseScreen = new PauseScreen();

public ScreenManager()
{
    _gameScreenRenderer = new Dictionary<State, Action<SpriteBatch>>
                            {
                                { State.SplashScreen, sb => _splashScreen.Draw(sb) },
                                { State.MainScreen, sb => _mainScreen.Draw(sb) },
                                { State.PlayScreen, sb => _playScreen.Draw(sb) },
                                { State.PauseScreen, sb => _pauseScreen.Draw(sb) }
                            };
}

An Action<SpriteBatch> is a delegate that points to any method that returns void and takes a SpriteBatch parameter; here the method is anonymous.
Each GameScreen becomes a field of the ScreenManager class, there's no need to have them in a list of any kind. Doing this turns your Draw implementation into something like this:
private void Draw(SpriteBatch spriteBatch)
{
    _gameScreenRenderer[ScreenState.Instance.CurrentState](spriteBatch);
}

Implement a similar mechanism for your Update method and you'll only be updating and rendering the screen for your CurrentState.


Ruby on Rails Method ActiveRecord Query Optimizations

You could benchmark and see if a INNER JOIN would be faster on the Expiration model w/ the User model. I'm assuming they are not one to one, since you are grabbing multiple expirations per user.

How big is the Users table? If it's relatively small, and not growing exponentially you might not need to use a join.

If it has millions of records, you are essentially doing a million SELECTs:

Benchmark.realtime  { User.all.each { |x| Expiration.where(:user_id => x.id) }

Which can be bad for performance and cause your MySQL server to be overloaded.

There is also something to look out for is the N + 1 problem, which is a very similar problem to what might be happening to you:

https://www.codemy.net/posts/optimizing-your-rails-app-part-1-n-1-queries

Edit:

N+1 queries occur when you write a piece of code that executes a SQL query many times (N times depending on the code), where one query would have been appropriate. It occurs commonly in loops, maps, and places where lazy loading is not enabled. It's very common in views that display tabular info that uses other tables, and is not noticeable in a development environment where you're not testing a ton of data.


Improving LINQ expression with inner method call and switch statement

public override Func<LocationContext, LocationDataContract> Resource
{
    get
    {
        return
            c =>
            c.Locations.Select(
                l =>
                new LocationDataContract
                {
                    Id = l.Id,
                    Coordinates = l.Coordinates,
                    Description = l.Description,
                    Name = l.Name,
                    Type = l.Type,
                    Details = this.GetDetails(l.Type, c)
                }).SingleOrDefault(i => i.Id == this.Identifier);
    }
}

This code is inefficient, because the body of your Select is being executed for every value in Locations. This is because SingleOrDefault checks every item in an enumerable for duplicates. Since you're only checking an id and the id is not changed in your Select perform your SingleOrDefault call first.

public override Func<LocationContext, LocationDataContract> Resource
{
    get
    {
        return c =>
        {
            var location = c.Locations.SingleOrDefault(i => i.Id == this.Identifier);
            return location == null ?
                null :
                new LocationDataContract
                {
                    Id = location.Id,
                    Coordinates = location.Coordinates,
                    Description = location.Description,
                    Name = location.Name,
                    Type = location.Type,
                    Details = this.GetDetails(location.Type, c)
                });
        }
    }
}

This way, the LocationDataContract is only created if there is a single location in c that matches the identifier.

Structurally, I'm wondering why you have a public read-only property returning a Func. I can see no good reason why this shouldn't be a method, although obviously the motivation for this depends on the implementation in the base class, which we cannot see in your question.

If you can modify the base class, I would recommend replacing this property with a virtual or abstract method. This property syntax instead is more obtuse for a maintenance programmer to read and is over-complex. Consider this instead:

public override LocationDataContract Resource(LocationContext context)
{
    var location = context.Locations.SingleOrDefault(l => l.Id == this.Identifier);
    return location == null ?
        null :
        new LocationDataContract
        {
            Id = location.Id,
            Coordinates = location.Coordinates,
            Description = location.Description,
            Name = location.Name,
            Type = location.Type,
            Details = this.GetDetails(location.Type, context)
        });
}

Additionally, the name Resource gives me no information. It might as well be called Foo. It looks like a function that grabs a location data contract from a location context based on the currently stored Id, so a name like "LocationContractForCurrentId" would make more sense.

Lastly, your usage of SingleOrDefault everywhere concerns me. If it's truly acceptable that nothing happens when no identifiers can be found, including in your context set methods, then fine, keep it that way, but if this is a way to hide from exceptions caused by invalid data or incorrect programming and to avoid Failing Fast, then that is a serious issue that would be better dealt with than hidden from.


This isn't complete code. We have no idea what's happening with row; it seems to be a loop index, but we have no idea what else is happening in the loop.

Anyway, here's my take on things:

Create compiled regexes and move their creation out of the loop, creating Regex instance variables instead of using the static methods. This gets you a speed boost and simplifies the code.
Do the .Replace()s unconditionally; there's no harm in doing so.
Extract the common code into a new function/method. Don't repeat yourself. If you decided you wanted to use the English spelling "Number" instead of Dutch "Nummer" you don't want to have to fix it in two places.

So here it is:

string Standardize(string input)
{
  static var regexJobNumber = new Regex(@"(\d{4})", RegexOptions.Compiled);
  static var regexTimeStamp = new Regex(@"(\d{8}_\d{6})", RegexOptions.Compiled);
  string intermediate = regexTimeStamp.Replace(input, "<TimeStamp>");
  return regexJobNumber.Replace(intermediate,"<JobNumber>");
}

//...

  if (row < comparedFile.Count)
  {
    if (Standardize(removeJobnumber) != Standardize(removeJobnumber2))
    {
       var rowcount = row + 1;
       differenceList.Add("Difference found on rownumber: " + rowcount);
    }
    row++;
  }

My suggestion is to go through the documentation for Regex and see how each method is used.


Searching for repeated characters in a sequence of characters

I'd start bottom-up on this one if you want to do it in a slightly more idiomatic / functional style. Also it's good to get the data in Clojure sequences rather than strings as it makes it a bit easier to manipulate.

You're trying to work on groups of five adjacent characters so I'd set up a sequence of such adjacent groups:

; define some source data, right answer is "1235"
(def char-seq (seq "dfyfgvbufi12345idvdfhopshbsopgeobvufpdhbugphp123a5ghauoyhewqojbvrbon"))

; now partition into adjacent overlapping groups of five (with a step of 1)
(def char-groups (partition 5 1 char-seq))

; prove it works
(take 3 char-groups)
=> ((\d \f \y \f \g) (\f \y \f \g \v) (\y \f \g \v \b))

Now we want to define what a valid match means: in this case 4 characters should be the same in two groups being compared.

; helper function to count the number of true values in a collection / sequence
(defn count-true [coll]
  (reduce
    #(+ %1 (if %2 1 0))
    0
    coll))

; function to determine if exactly four characters are equal in two groups
(defn matches? [group1 group2]
  (= 4
    (count-true (map = group1 group2))))

Finally you just need to run the matches? function over all possible groups:

(def results
  (distinct
    (keep identity
      (for [group1 char-groups
            group2 char-groups]
        (if (matches? group1 group2)
          (filter identity (map #(if (= %1 %2) %1 nil) group1 group2))
          nil)))))

results
=> ((\1 \2 \3 \5))


Extract day.title() to  a separate method. In this case, if you wanted to change how you store the days of the weeks (e.g. Monday, Tuesday ... -> monday, tuesday...), you would have to change day.title() to day.lower() only in one place*.
Implement set_start_and_end() by calling set_start() and set_end(). Identically for getters. The rationale is similar to the previous point: if you decided to change the data structure where you store the time slots, you would have to change less code*.
Magic numbers. e.g. 11. First of all extract such number into a constant with a meaningful name. Btw, is this value really a constant? Will you still want to use this value if the names of the days of the week change (e.g. you decide to use Mon, Tue etc., or names in another language)
Do not do formatting in calculate_*** methods. You have display_** methods responsible for that. Let all the formatting be done there. Btw, maybe format_*** would be a better name?
Another question is how you initialize your days_dict. Maybe you would want to pass a dictionary with some already existing values as an argument to the constructor. Possibly make it optional, and if we don't pass anything initialize it with default values as you do now:

def __init__(self, worker, company, days_dict=None):
    self.worker = worker
    self.company = company
    # This can be a JSON file or a SQL DB
    self.days_dict = days_dict or DEFAULT_DAYS_DICT

Also, maybe it would be nicer to have default values like "Monday": {"start": "0000", "end": "0000"}?
How about having a fluent API?

wt = WorkingTime('Maffaz', 'IT Circle Consult')
        .set_start_hour("monday", "0730")
        .set_end_hour("monday", "1800")
        ...
        .set_start_and_end("FrIDAY", "", "")

For that you would need to return self object from every setter/getter:

def set_start_hour(self, day, hour):
    ...
    return self

* I wrote about situations where you would have to change a lot of code. The problem is actually not with changing it. The problem is that in some situations you might forget to do it and your program will start working incorrectly.


Have you tried not using explicit chunk sizes? Parallel.For does some fancy chunking (range-splitting) and load-balancing under the hood, which usually gives very good performance on it's own.

In other words, try a simpler solution first, e.g.,:

let mapInPlace (mapping : 'T -> 'T) (array : 'T[]) : unit =
    Parallel.For (0, array.Length, fun i ->
        array.[i] <- mapping array.[i])
    |> ignore

Another point -- if you're iterating over lists of 10000 elements, you should convert those lists to an array once, then call your iterative function however many times you need to. I suspect you're losing a non-trivial amount of performance from doing the list-to-array conversion repeatedly.


A baby monitor using a Raspberry Pi to send push notifications when triggered by noise

Bash

    arecord --device=hw:1,0 --format S16_LE --rate 44100 -d 2 /dev/shm/tmp_rec.wav ; sox -t .wav /dev/shm/tmp_rec.wav -n stat 2>&1 | grep "RMS     amplitude" | tail -c 9

You can use newlines instead of ; and after | to make it easier to see the separate commands:

    arecord --device=hw:1,0 --format S16_LE --rate 44100 -d 2 /dev/shm/tmp_rec.wav
    sox -t .wav /dev/shm/tmp_rec.wav -n stat 2>&1 |
        grep "RMS     amplitude" |
        tail -c 9

It's not clear to me why you're using /dev/shm rather than a pipe. Since you say you're not very familiar with bash, I wonder whether it's because you saw in the man page that sox requires a filename and didn't know that it's common for - to be used as a special filename to signify stdin. Untested, but on my reading of the man pages the following should work:

    arecord --device=hw:1,0 --format S16_LE --rate 44100 -d 2 |
        sox -t .wav - -n stat 2>&1 |
        grep "RMS     amplitude" |
        tail -c 9

I think the extraction of the amplitude could be more robust in two ways:

As a minor point, I suggest changing the regex to "RMS *amplitude" as a future-proofing precaution against the stats gaining a new stat with a longer name.
More importantly, tail -c 9 is a very bold assumption. The Python program uses strip(), so you don't care about leading whitespace. I propose replacing the tail with cut -d: -f2.

Final version of the bash script if you agree with all of my suggestions:

    arecord --device=hw:1,0 --format S16_LE --rate 44100 -d 2 |
        sox -t .wav - -n stat 2>&1 |
        grep "RMS *amplitude" |
        cut -d: -f2

Python

I don't have much to say here except that count and suppress looks to me to be at least one variable too many. If you replace with e.g. lines_to_suppress then if suppress becomes if lines_to_suppress <= 0 and instead of incrementing count you decrement lines_to_suppress.

However, it might be clearest to just eliminate them both and replace

            count = 0
            suppress = True

with

            for _ in range(0, 5):
                sys.stdin.readline()
                print("Suppressing output")


Here are some observations:

no meaningful comments or docstrings (they are not always needed, but imagine there is that "violent psychopath, who knows where you live" will be reading the code)
PEP8 violations and making things Pythonic:

blank line between class methods, two blank lines between top-level functions and classes (source)
correct import organization
the inline comments formatting
variable naming, if defining a constant, there has to be an underscore between words:

BOARDLENGTH -> BOARD_LENGTH
BOARDHEIGHT -> BOARD_HEIGHT

a space between arguments after a comma:

ship.show(board, hasprevious=False)
            HERE^

no need for extra () after the class definition
if intersection == []: can be rewritten as if not intersection:
simplify the if condition inside the rotate() method, replace:

if newy >= 0 and newx >= 0 and newy <= BOARDHEIGHT-1 and newx <= BOARDLENGTH-1:

with:

if 0 <= newx <= BOARDLENGTH - 1 and 0 <= newy <= BOARDHEIGHT - 1:

other improvements:

looks like you don't need to make the size an instance variable - you only need it in the constructor
what if instead of multiple repetitive if/else blocks inside the choose_locations(), you would create a mapping between action keys and the shift directions, e.g.:

ACTION_KEYS = {
    'w': 'U',
    's': 'D',
    'a': 'R',
    'd': 'L'
}

Then, we can improve the part determining the shift direction:

key = getch.getch()
if key in ACTION_KEYS:
    ship.shift(ACTION_KEYS[key])
    board = ship.show(board)


I would not say I am any more proficient but I would make these changes if I wrote it.

skip(1) first arg.
join(" ") instead of iterate though args.

You do not need a mutable value.

use std::env;

fn main() {
    let args: Vec<String> = env::args().skip(1).collect();

    if args.len() == 0 {
        println!("");
    } else {
        println!("{}", args.join(" "));
    }
}

I would do one more thing and send to stdout since your mimicking echo, but maybe much for this answer.


If you prefer programming in C-style, I suggest to use C.
If you want to use any part of C++, I suggest to embrace it fully.

I'll review only the main method for now,
I'm sure a lot more reviews will come from others.

You don't need the \n here. You can just drop it, it will work the same way:

  scanf("%s\n%s", a, b);

The C++ equivalent:

std::cin >> a >> b;

This generates a compiler warning, for good reason:
the arguments of scanf should be pointers, but it's an int.
Why is this line there at all? I suggest to remove it.

  scanf("%d", 1);


Generating and using a list of prime numbers

for one thing, (eq nil p) is usually written (not p).

the variable p participating only in that do should be declared inside it, not outside it in the enclosing let. Everything should be in its proper place. Same with result - make do your last form and use the return clause of do to return the result:

(defun plist (n)
  (let (
        (arr (make-array (+ n 1) :element-type 'boolean :initial-element t))
       )
    (setf (aref arr 0) nil)
    (setf (aref arr 1) nil)

    (do ( (p 3)
          (result (list 2)))
        ( (not p)  (nreverse result))

      (push p result)   ; and what if n==2 ??
      ....
      )))

Don't mix arefs and svrefs, be consistent. Again, the test (when (eq t (svref arr i)) ...) would normally be written just as (when (svref arr i) ...).

Your do loop is a little buggy: it adds 3 unconditionally, even if n < 3. Reorganize. Or, and since you don't inspect them, no need to mark 0 and 1 as non-primes, just like we don't bother with the evens. Which means we get to declare the array inside the do's scope too:

(defun plist (n)
  (do ((arr (make-array (+ n 1) :element-type 'boolean :initial-element t))
       (result (list 2))
       (p      3        (+ p 2)))
      ((> p n)
       (nreverse result))       ; return form
    (when (aref arr p)
        (push p result)
        (if (<= p (/ n p))
          (loop for i from (* p p) to n by (* 2 p)
            do (setf (aref arr i) nil))))))

An algorithmic improvement, though you didn't want one: start eliminating multiples of p from (* p p), not from (+ p p), and increment by steps of (* 2 p) among odds only, for twice the speed.

Now that the code is short and compact, we see one more possibility for improvement: if we hit the termination condition, no need to recheck it. Finally, add the documentation string there too:

(defun plist (n)
  "return the list of primes not greater than n.
   build it by means of the sieve of Eratosthenes."
  (do ((arr (make-array (+ n 1) :element-type 'boolean :initial-element t))
       (result (list 2))
       (p      3        (+ p 2)))   ; a candidate possible prime
      ((> p (/ n p))
       (nconc (nreverse result)
              (loop for i from p to n by 2 if (aref arr i) collect i)))
    (when (aref arr p)              ; not marked as composite: p is prime
        (push p result)
        (loop for i from (* p p) to n by (* 2 p)  ; mark the multiples
            do (setf (aref arr i) nil)))))

I don't find micro-commenting adding much clarity (even the opposite), but YMMV. Variable names like arr and result are self-documenting.


Selecting which variables to read from file

Interesting: The object reads the data, but the data is not returned anywhere nor is it exposed. Is it by design, I guess not ;)

Peculiar function: read_list() returns an int. I believe the function was in the main() before becoming part of a class, but the return has no effect, since the result is discarded by the caller. No exceptions, just the error printed out. Since the code doesn't perform any error handling anyway, the vectors construction could look much better:

Read_Data::Read_Data():
        int_list(std::istream_iterator<int>(std::ifstream("ints.txt")), {}),
        string_list(std::istream_iterator<std::string>(std::ifstream("strings.txt")), {})
{}

But the std::istream_iterator has constructor that only takes non-const lvalue reference to the stream (not that const version would be useful), which leads me to the next point:

The object is an object, but pretends to be an algorithm: I think that the class should be refactored to be a function which accepts two vectors (with int and string list) and a parsed json. Object has different properties than algorithm, and in current situation clearly algorithm is desired and needed.

Usually I make bare bones interface which has greatest power and doesn't take usability into account. Then I make some higher level functions which delegate to lower level functions with simplicity of use in mind:

auto separate_info(const nlohmann::json& content,
                      const std::vector<std::string>& int_list,
                      const std::vector<std::string>& string_list)
{
    std::map<std::string, int> int_list;
    std::map<std::string, std::string> string_list;

    /*populate them*/

    return std::pair{int_list, string_list};
}

auto read_info() //some defaulted parameters if needed
{
    std::ifstream int_parameter_list{"..."};
    std::ifstream string_parameter_list{"..."};

    template <typename T>
    using isiter = std::istream_iterator<T>;

    std::vector<std::string> int_attributes(isiter<int>{int_parameter_list}, {});
    std::vector<std::string> text_attributes(isiter<std::string>{string_parameter_list}, {});

    //parse the json

    return separate_info(j, int_attributes, text_attributes);
}

Then on the call site:

auto [int_list, string_list] = separate_info(...);

The names could've been better: naming is hard. May be there is something in common between them? What do they refer to? I guess it is something related to a person. The maps could be packed into person_info if my guess was right. It won't be that significant, but maybe pair won't be a good choice if the read data is used in many places.

struct person_info
{
     std::map<...> int_info;
     std::map<...> text_info;
}

And the last, not so important point:

Premature optimization, or ignorance: I don't mean to be offending, but returning vector from a function is probably very cheap. One thing is NRVO, which will probably kick in since it is gonna be created on the first line and returned from one point. If NRVO will fail, move constructor will kick in, so it is gonna be something like copying/swapping of 3 pointers. Although standard doesn't require this, most compilers do it. If you're on mainstream, e.g. gcc/clang/vc++, then returning vector shouldn't be a problem.


Simulating a scale, balancing weight from lists

Write functions. Make this a balance_scale function, that returns the minimum.
Your variable names are pretty poor, single letter variable names leave people guessing at what they mean.
You should change cc = cc = ... to just one assignment.

Since you can use a maximum of two spare weights the solution can be a lot simpler than you've produced.

\$W_1\$ is the smaller weight in weights and \$W_2\$ is the larger.
If \$W_1 = W_2\$ then you return an empty list.
We can determine what weight is needed when only one weight can be used.

\$S = W_2 - W_1\$

Therefore if \$S\$ is in spare_weights then we can return \$S\$.
For each \$S_1\$ in spare_weights we can determine the weight needed, \$S_2\$.

\$S_2 = |W_2 - W_1 - S_1|\$

We take the absolute as this weight can be on either side of the scale. If the non-absolute value of \$S_2\$ is positive then we add it to \$W_1 + S_1\$ if it's negative then we add it to \$W_2\$.

If we add \$0\$ twice to spare_weights, then we can see that (4), (3) and (2) are all roughly the same equation.

We don't need to check if \$S_1\$ and \$S_2\$ both exist in spare_weights, as the only time they are the same is if \$W_1 = W_2\$, and so they would both be 0. We however have to assign \$S_1\$ to 0 first.

def balance_scale(scale, spares):
    w1, w2 = sorted(scale)
    spare_set = set(spares) | {0}
    for s1 in [0] + spares:
        s2 = abs(w2 - w1 - s1)
        if s2 in spare_set:
            return [i for i in [s1, s2] if i]
    return None

print(balance_scale([4, 3], [1, 2, 7, 7]))

[1]


Making backtracking Sudoku solver more functional

A purely functional solution would be to get rid of the mutable array and instead use an immutable type like Map<int * int, int>. Your recursive backtracking function would then fill it and return it, instead of modifying a global array. Something like:

let rec solvePosition position sudoku =
    let x,y = position/9, position%9
    if position = 9*9 then
        Some sudoku
    else if Map.containsKey (x,y) sudoku then
        solvePosition (position+1) sudoku
    else
        let isValid n = isValidNumber (x,y) n sudoku
        let solveCurrentCase n =
            if isValid n then
                let newSudoku = Map.add (x, y) n sudoku
                solvePosition (position+1) newSudoku
            else
                None
         Array.tryPick solveCurrentCase [|1..9|]


Parse a substring out of string, allocate memory accordingly

A 0-ary function (swd_parseUsrPass) calling another 0-ary function (swd_getURLaddr) hints that there are global variables lurking around. Using globals is not recommended; if they are unavoidable, at least limit their visibility. Consider char swd_parseUsrPass(char * url_addr), and let the caller provide the argument.
sizeof(char) is guaranteed to be 1.
*(endIndx + 1) = '\0' modifies the source string, while usr_pass remains not terminated. I presume you meant

usr_pass[str_len] = '\0';


Implementation of Prim's minimum spanning tree

Generally speaking, it seems to be coded pretty well. I can just find one or two things that could be improved:

else
{
    continue;
}

This piece of code at the end of a while seems fairly useless. I guess it would be the same without it.

void visitVertex(size_t index)
// helper method marks vertex as visited and adds all it's
// edges to priority queue
{
    visited.insert(index);
    for(size_t other : graph.getVertexNeighbors(index))
    {
        pq.push(EdgeWithPriority(index, other, graph));
    }
}

Here, you can replace pq.push(EdgeWithPriority(index, other, graph)); by pq.emplace(index, other, graph);. The function emplace will construct the object directly in the priority_queue with the given parameters.

You could also probably replace visited.insert(index); by visited.emplace(index); but I don't think it will change anything.

Graph* result = new Graph(impl->graph.verticesCount());
for(Graph::EdgeKey element : impl->edges)
{
    double weight = impl->graph.distance(element.first, element.second);
    result->connect(element.first, element.second, weight);
}

I don't know what the methods distance and connect do, but depending on what they really do, it could be better to for your for loop to take const references instead of values. But, well... it depends on distance and connect.

You should use std::unique_ptr instead of std::shared_ptr to hold the pointer to the implementation. Since std::unique_ptr cannot be copied, that means that PrimGraphMst cannot be copied either, but that's probably fine since std::shared_ptr was not copying your data either but merely doing an alias to the implementation.

You can also improve the constructor of PrimGraphMst by using a constructor initiaization list instead of a late memory allocation:

PrimGraphMst::PrimGraphMst(const Graph& graph):
    impl{ new PrimGraphMstImplementation{graph} }
{}

You may have noted it: I used curly braces in the initialization list of the constructor in the previous section of this review. Contrary to plain parenthesis, curly braces prevent any implicit narrowing type conversion. Using them can help to catch the small errors that are sometimes linked to narrowing conversions.

Style: your indentation often seems off and makes the code quite difficult to review. You should indent your code evrytime you introduce a new scope.

You are placing the comments of your function right after their point of declaration. Generally speaking, comments about a function are placed right before the function declaration.


I guess it depends a bit on what kind of input text you have but if you wanna do exact match per line

^(\+27|0)\d{9}$

would work well. If you wanna be liberal what comes before and after then

.*(\+27|0)\d{9}.*

I agree with st88 that negative lookahead makes it confusing. Better to provide your expectation before and after the main pattern (like above)


There are several modules on CPAN that are made for this task. They all reside in the Getopt namespace. Getopt::Long even comes with the standard distribution. So coming to your question: Yes, there are better ways.

If you are interested in something more fancy, you could have a look at Getopt::Declare where you can write the usage page and fill your variables in the same place. It has a downside, though since it introduces another DSL.

What I definitely would recommend is that you take a look at <<HERE docs for printing longer texts. Some people dislike them,because of their strange syntactic properties, but they are the usual way to express multiline strings in perl.


Drawing on a pixel in blocks and diagonally

Naming

Names of methods should describe the purpose they have. If a comment is needed to describe what a method does //Change to nextPixel() for block, nextPixel2 for diagonal, one should think about another more meaningful name.
What would Mr.Maintainer think at reading this code ?

@Override
public void paint(Graphics g) {
    super.paint(g);
    while(true) {
        nextPixel2(); //Change to nextPixel() for block, nextPixel2 for diagonal
        g.setColor(randomColor);
        g.drawLine(x, y, x, y);
        pixels++;
    }
}

He would get the conclusions

I need to dig into the netxPixel2() method
Inside this method the value of randomColor and a location (defined by x and y) will maybe be changed.
What does the nextPixel2() do and why does it change 2 things
There is another method nextPixel() involved, and I need to dig into this too
This is a never ending while loop

Decoupling
As the pixel manipulation code only relies on a Graphics, there is no need for this code to be inside a JFrame extending class. You should better use composition over inheritence.

Style

The indention of the code can be improved a lot. Maybe some of this came from pasting here but for sure not this

if(i < changeColor){
    i++;
}else{
generateColor();
i=0;
}

Ok, let us dig into nextPixel2()

What do we see ?

Neither xStart nor yStart will be changed ever (after a quick glance into nextPixel()), so we should make them final and also give them a new name like e.g xBorderPosition

for(int i = 0;i < timer;i++){
   i++;
   System.out.println("Pixels drawn: "+pixels);
 }

This is just boilerplate code, as pixels isn't increased anywhere in the method, it stays at the initial value of 0, this should be removed, also because the responsibility of this method does not involve output of any data, but manipulating some values.

Algorithm

The x value will be decremented and the y value will be incremented. This will happen until

x < xStart or in other words until x == 2. At this point xLock will be incremented, x = xLock and y = 25 = yLock = yStart.

or

y > height which will be true after xLock == 699 so this will be the case we need to dig into

If the first condition is true and xLock will be incremented to xLock == 699 we start again with y = 25 = yLock = yStart and x = xLock = 699. After some iterations of the while(true) of the paint() method we will reach at the entrance to nextPixel() with the values x == 4 and y == 720 and after incrementing and decrementing we have x == 3 and  y == 721.  Se let us see what the following striped code will do then

while(x < xStart || y > height){
    xLock++; // now 700
    x=xLock; // now 700
    y=yLock; // now 25
    while(x > width) { // still false
        xLock--;
        x=xLock;
        yLock++;
        y=yLock;
    }
}

So the xLock == 699 border doesn't change anything as x is still <= width. But what we see is, if xLock would reach the value 1281 then x > width will be true and something will happen.

yLock will be incremented by one and xLock will become 1280 and the x > width won't be true again.

So as there is always only one iteration, we can replace this while loop with an if statement. So if anytime x > width we need to increment yLock by one and set xLock == width. And as we set x = xLock we can check if xLock > width and assign then the xLock and yLock values to x and y

Refactoring

while(x < xStart || y > height){
    xLock++;
    if (xLock > width) {
        yLock++;
        xLock = width;
    }
    x = xLock;
    y = yLock;
    if(y == height && x == width){
        xLock = xStart;
        x = xLock;
        yLock = yStart;
        y = yLock;
    }
    if(i < changeColor){
        i++;
    }else{
        generateColor();
        i=0;
    }
}

As we have seen x == width will only be true, if xLock > width, we can check y == height inside this if statement.

Refactoring again

while(x < xStart || y > height){
    xLock++;
    if (xLock > width) {
        yLock++;
        xLock = width;
        if(yLock == height){
            xLock = xStart;
            yLock = yStart;
        }
    }
    x = xLock;
    y = yLock;
    if(i < changeColor){
        i++;
    }else{
        generateColor();
        i=0;
    }
}

If we look at the remaining while conditions we see, that after this condtions will be true the first time, neither x < xStart will be true nor y > height will be true. So there is no need for a while loop. To save an additional indention, we also revert the condition to be a guard condition. Additional we extract the check for generating a random color to a separate method isColorChangeNeeded(), rename the class variable i to colorCheckCounter and the changeColor variable to colorCheckLimit which should be final also. And finally we will rename the method to assignDiagonalPixelLocation

public void assignDiagonalPixelLocation(){
    x--;
    y++;
    if (x >= xStart && y <=height) { return; }

    xLock++;
    if (xLock > width) {
        yLock++;
        xLock = width;
        if(yLock == height){
            xLock = xStart;
            yLock = yStart;
        }
    }
    x = xLock;
    y = yLock;
    if(isColorChangeNeeded()){
        generateColor();
    }
}

private boolean isColorChangeNeeded() {
    colorCheckCounter++;
    if (colorCheckCounter <= colorCheckLimit){ return false; }

    colorCheckCounter=0;
    return true;
}


Whether a simpler solution exists depends on what your motivation is.

Let's look inside the implementation of Gem::Commands::WhichCommand#find_paths.

  def find_paths(package_name, dirs)
    result = []

    dirs.each do |dir|
      Gem.suffixes.each do |ext|
        full_path = File.join dir, "#{package_name}#{ext}"
        if File.exist? full_path and not File.directory? full_path then
          result << full_path
          return result unless options[:show_all]
        end
      end
    end

    result
  end

That's the code you need.  If there were a simpler way, find_paths would have used it.

However, there is a way to cheat: Kernel#require needs to do a very similar thing when it actually tries to load a module:

  require(name) → true or false

  Loads the given name, returning true if successful and false if
  the feature is already loaded.

  If the filename does not resolve to an absolute path, it will be
  searched for in the directories listed in $LOAD_PATH ($:).

  If the filename has the extension “.rb”, it is loaded as a source
  file; if the extension is “.so”, “.o”, or “.dll”, or the default
  shared library extension on the current platform, Ruby loads the
  shared library as a Ruby extension. Otherwise, Ruby tries adding
  “.rb”, “.so”, and so on to the name until found. If the file named
  cannot be found, a LoadError will be raised.

  For Ruby extensions the filename given may use any shared library
  extension. For example, on Linux the socket extension is “socket.so”
  and require 'socket.dll' will load the socket extension.

  The absolute path of the loaded file is added to $LOADED_FEATURES
  ($"). A file will not be loaded again if its path already appears in
  $". For example, require 'a'; require './a' will not load a.rb
  again.

Or, it might be more accurate to say that find_paths simulates what require would do.

Therefore, if you are willing to let Ruby actually load the file first, then you could ask Ruby after the fact:

require 'rubygems'
$LOADED_FEATURES.grep /\/rubygems\./


getfloat, the floating point analog of getint

It obviously does not handle NAN and INF.  Maybe outside code's goals.
Surprisingly does not handle exponential notation such as 1.23e+56.
if(!isdigit(c) && c != '.') { returns a 0 implying "not a number" and ungets the offending c.  But a potential + or - was all ready consumed and not available for alternative parsings.  Not sure best way to handle, but maybe consider that once a non-white-space char is irrevocable consumed, this function should not return a error signal and should set *pf to _something_like 0 or NAN.
Minor: The *pf /= power; approach fails with input such as 123.00000...(300+ zeros) as power or *pf already became INF.
This is a pedantic point: Once you get about 17 (depends on double) decimal digits, the addition of (c - '0') to *pf * 10 becomes moot.  To get a more accurate significand, forming the number right-to-left has precision advantages.
The return c; could return 0 indicating "not a number" .  Recommend an alternative return value scheme.
ungetch is not in the C spec.  Consider ungetc().
With ungetc() "If the value of c equals that of the macro EOF, the operation fails and the input stream is unchanged." thus negating the need for the if(c != EOF).  Still not bad to have there.
The decimal point . is locale sensitive and could be , or something else.  Use locale sensitive routines to determine the current decimal point.
You are commended for for taking in "-0" and rendering -0.0 rather than 0.0.
[Edit] IEEE_754-2008 Character_representation discusses the maximum number of non-zero leading digits to use when converting from text to a number.  double is often a IEEE_754 binary64, so a maximum number to use is 17+3.  This goes into point #3 above.  Its a bit deep on how this affects things, but I'll just note it for those who want to delve into a portable robust solution.


Change Task Edit form of workflow in SharePoint 2010

Give your code some room to breathe.

Empty space costs nothing in C#, so add some gaps to group together similar concepts.

 public void createTask1_MethodInvoking(object sender, EventArgs e)
    {
        createTask1_TaskId1 = Guid.NewGuid();
        createTask1_TaskProperties1.Title = "Test Title";
        createTask1_TaskProperties1.AssignedTo = "i:0#.w|directory\approver";

        var taskList = workflowProperties.TaskList;
        var wfContentType = taskList.ContentTypes["Workflow Task"];

        TaskTitle = workflowProperties.Item["Title"].ToString();

        wfContentType.DisplayFormUrl = "_Layouts/SharePointProject4/ApplicationPage1.aspx";
        wfContentType.EditFormUrl = wfContentType.DisplayFormUrl;
        wfContentType.Update();

        taskList.NavigateForFormsPages = false;
        taskList.Update();
    }

Secondly, when naming variables, be explicit. There's no need to abbreviate anything, once again, extra characters are free.

  public void createTask1_MethodInvoking(object sender, EventArgs e)
    {
        createTask1_TaskId1 = Guid.NewGuid();
        createTask1_TaskProperties1.Title = "Test Title";
        createTask1_TaskProperties1.AssignedTo = "i:0#.w|directory\approver";

        var taskList = workflowProperties.TaskList;
        var workFlowContentType = taskList.ContentTypes["Workflow Task"];

        TaskTitle = workflowProperties.Item["Title"].ToString();

        workFlowContentType.DisplayFormUrl = "_Layouts/SharePointProject4/ApplicationPage1.aspx";
        workFlowContentType.EditFormUrl = wfContentType.DisplayFormUrl;
        workFlowContentType.Update();

        taskList.NavigateForFormsPages = false;
        taskList.Update();
    }

Next, onto design. You've named a task createTask1, which is concerning, because that means it's possible you've created a lot of these with different numbers. Pop them in a collection named createTasks instead and try to refactor your MethodInvoking event handler to be abstracted across all createTasks. If there's something about createTask1 that means the event handler logic cannot be applied to the other createTask instances, then you should name createTask1 based on this unique property.

It's hard to tell what this method handler is meant to be doing since it's just named after the event that calls it. Give it a better name, or extract this functionality into its own method with a sensible name and call it from createTask1_MethodInvoking.

Lastly, I'm seeing an absolute ton of magic strings, which make it very hard indeed to sensibly refactor, because you'll have to change things in so many places, and they also hamper the understandability of the code. Make pretty much all of those strings into constant fields with sensible names.


Adding Reversed Numbers - ADDREV on SPOJ

A few notes:

Why do you have a bunch of extra headers at the top?  This extra cruft (such as the vector class), is going to cost you a bit of extra compile time for nothing plus it adds to the length of your code.  Cut back on the stuff you don't need; I found you only needed two of the headers out of the seven you have in your code.
Here are the woes of using namespace std;.  Please try to get into the habit of not using it.
Your #define's are interesting, but I found them a bit useless really.  They somewhat obscure the readability of the program as well, and should be removed IMO.
Your getReverseNum() function really just reverses a std::string object... but there's a standard library function std::reverse() that does this task for you (it's likely that this function is more efficient as well).
In C++, you should almost never use out parameters (variables taken by reference and used to return a value from a function), you can read this excellent article by Eric Niebler. There are few cases where out parameters can make sense:

When you want your return to be fast. And even then, return value optimization and move semantics may still be faster.
When you have several output values. For example, you want to assign a value to a function and return whether it succeeded:

bool assign(int from, int& to)
{
    if (from != 0)
    {
        to = from;
        return true;
    }
    return false;
}

But even for this situation, there are better solutions such as boost:optional to return both a value and whether it succeeded or not. And if you need several error values, use exceptions. And if you need to actually return several values, you general want to pack them into a dedicated struct or a std::tuple.
Input-output parameters: sometimes, you want to take a parameter, read from it, and then write to it again. That is still a valid use case (but these are not strict out parameters anymore).

Overall, for your case it would be better to remove the reference parameters as they serve no purpose really and could be hurting performance.
Your addNumbers() function could be simplified with the use of the standard functions std::stoi, std::to_string, and std::string::erase, along with our old friend std::reverse.
Your variable N in your main() function is somewhat confusing as to what it's purpose is at first.  I found it better named as cases.

Final Code:

#include <string>
#include <iostream>

std::string getReversedSum(std::string num1, std::string num2)
{
    // first we reverse the two numbers
    std::reverse(std::begin(num1), std::end(num1));
    std::reverse(std::begin(num2), std::end(num2));

    // convert the strings to ints so we can add them, then back to a string
    std::string sum = std::to_string(std::stoi(num1) + std::stoi(num2));

    // reverse the string and erase the leading zeros
    std::reverse(std::begin(sum), std::end(sum));
    sum.erase(0, sum.find_first_not_of('0'));
    return sum;
}

int main()
{
    int cases = 0;
    std::cin >> cases;

    // clear the input stream
    std::cin.ignore();

    while(cases--)
    {
        std::string num1;
        std::string num2;
        std::cin >> num1 >> num2;
        std::cout << getReversedSum(num1, num2) << std::endl;
    }
}


Producing excerpts from a file at specified positions within long lines (>1 M characters)

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

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  It's not explicitly in your question, but the lack of std:: in the code leads me to suspect it.

Use consistent variable naming

We have variables named OUT_FILE, subsetString, IN_file_StringName with no discernable consistent style.  Pick a form, say, camel case such as subsetString and use it consistently.  Also, all caps names such as OUT_FILE should only be used for macros (and you probably don't really need macros much with modern C++).

Provide a complete interface

This is partly to do with getting good reviews, but also has a lot to do with good design.  The code as posted leaves a lot out.  It's not a complete function, and so reviewers have to guess as to what the missing variables are.  So in attempting to turn the code into a function which could be tested, I encapsulated it like this:

int original(std::ifstream &IN_file, std::ofstream &OUT_FILE,
            const std::string &IN_file_StringName, const std::string &flagArray01String)
{
    std::string headerFileOriginal;
    std::string idOriginal;
    std::string longString;
    int numbIdsOriginal{0};
    std::string subsetString;

    // original code here

    return numbIdsOriginal;
}

I actually deleted the line containing myfileLog for reasons I'll describe later.  Note that there are a number of variables passed in and a number which can be local to the function.

Don't store what you don't need

Because we don't have the full context, it's not clear if headerFileOriginal is ever used or is just discarded.  If the latter, I'd suggest this instead:

IN_file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Rethink error handling

As the code is currently written, the processing is done within a loop inside an is_open() call.  I'd refactor that to pull the processing into a separate function and write it like this:

std::ifstream in{inputFileName};
if (!in) {
    // log errors and quit
}
processMask(in, out, maskString);

All opening/closing/flushing should be done outside the function that does the line processing.

Prefer std::istream to std::ifstream

One could concievably get input from any kind of input stream and not just a file.  The same is true of output, so for that reason and to preserve maximum flexibility in the interface, I'd write the function with a prototype like this:

int processMask(std::istream &in, std::ostream &out, const std:string &maskString);

This allows for flexibility in input/output and also, by declaring the maskString asconst` makes clear that it will not be altered by the function.

Use a standard function

The standard template library has a lot of handy stuff in it, much of which is highly optimized for performance.  For that reason, it's often better to use an appropriate STL function rather than writing your own.  In this case, I'd suggest using std::copy_if.  Here's how a loop might be implemented using this:

while (in >> id >> longString)
{
    out << id << '\t';
    ++count;
    auto it{flagstring.cbegin()};
    auto end{flagstring.cend()};
    std::copy_if(longString.cbegin(), longString.cend(),
        std::ostream_iterator<char>(out),
        [&it,&end](const char){
            return it != end && *it++ == '1';
        });
    out << '\n';
}

This works by using a lambda as a predicate function.  It has the effect of copying each character from the input to the output as long as the condition is true, and the condition simply iterates through the flag string.

Don't use std::endl if you don't really need it

The difference between std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.

Don't explicitly flush the stream unless needed

When a std::ofstream iterator goes out of scope, the file is automatically flushed and closed by the destructor.  So for that reason, rather than explicitly calling flush() or close(), I'd recommend simply limiting the scope of the variable to only what is needed and rely on the destructor to do all of that.

Understand the limits of performance

I strongly suspect this program is I/O bound.  That is, I think it's very likely that almost all of the full duration required by this program is not in processing the data, but in simply reading and writing from files.  One simple test is to compare a simple line-at-a-time C++ copy function with the whole program.  The difference between the running of those two is likely to be an approximation of the maximum time you can trim by optimizing the algorithm.  I created a sample file with 10,000 data lines, each of which has a little over one million characters in the second field.  It takes about 1:03 (minutes:seconds) on my machine to process this 9.4 Gb file no matter what I do with for processing.


MySQLi-extension class (parameterized queries)

You use a very complicated way to extract the first element of an array.  Just use array_shift instead.

$query = array_shift($arguments);

Use foreach instead of a for loop:

foreach ($params as $param) {
    $lp = explode(":", $param); //I changed preg_split to explode, because you use a static delimiter
    $queryTypes[] = $lp[1];
    $queryParams[] = &$arguments[$lp[0]];
}


You're representing the cells mainly using a dictionary of coordinates, converting to a two-dimensional array only for the purposes of printing the output.  That is a good representation for sparse boards, but not so much for crowded boards.

The algorithm that you use, though, is cumbersome, particularly illustrated by these few lines:

for item in cells.keys():
    checking = [ x for x in list_to_check(item[0],item[1]) if x not in to_check and x not in cells ]
    to_check += checking

In other words, make a list of the neighbors of each cell, but make sure that each coordinate is listed just once.  Then, once you have that list to_check, what do you do with it?

for item in to_check:
    if neighbors_count(item[0],item[1],cells) == 3:
        to_add[(item[0],item[1])] = 1

You count each cell's neighbors!  But the number of neighbors is precisely the amount of overlapped processing that would have occurred had you not bothered to deduplicate the to_check list to begin with!  So, instead of drawing a list of interesting cells and counting their neighbors, why not just have each existing cell increment the neighbor count of each neighboring coordinate?

In addition to the change in algorithm, I also recommend:

Take advantage of list/set/dict comprehensions more.
Represent the board as a set of live cells, rather than a dict.
Rename list_to_check() to neighbors().
Rename print_grid() to grid(), since it actually doesn't print anything.
Construct the next state from scratch rather than by mutation: test_array_dict = tick(test_array_dict)

I'd rewrite three functions as follows (and eliminate neighbors_count(), next_state(), and add_to_grid_alive():

def tick(live_cells):
    """ Takes a set of coordinates of live cells, and returns a set of
    coordinates of the live cells in the next generation. """
    neighbor_count = {}
    for xy in live_cells:
        for neighbor in neighbors(*xy):
            neighbor_count[neighbor] = 1 + neighbor_count.get(neighbor, 0)
    return set(xy for xy in neighbor_count
                   if neighbor_count[xy] == 3
                   or xy in live_cells and neighbor_count[xy] == 2)

def grid(size, cells):
    return [[int((x, y) in cells) for x in range(size)] for y in range(size)]

def load_list(inputs):
    return set(inputs)

Actually, tick() would be even better written using a collections.Counter.  I don't know if you consider that "using an object".


Function to find two prime numbers that sum up to a given even number

You are doing an \$O(n^2)\$ search over a sorted list, which very often implies an affirmative answer to the infamous "can we do better?" question. For this particular problem, you can get \$O(n)\$ performance by simultaneously scanning from the front and back of the list of primes:

def prime_sieve(n):
    # returns all primes smaller than n
    sieve = [True] * n
    sieve[:2] = [False, False]  # 0 and 1 are not primes
    primes = []
    for prime, is_prime in enumerate(sieve):
        if not is_prime:
            continue
        primes.append(prime)
        for not_prime in range(prime*prime, n, prime):
            sieve[not_prime] = False
    return primes

def sum_of_primes(value):
    primes = prime_sieve(value)
    lo = 0
    hi = len(primes) - 1
    while lo <= hi:
        prime_sum = primes[lo] + primes[hi]
        if prime_sum < value:
            lo += 1
        else:
            if prime_sum == value:
                yield primes[lo], primes[hi]
            hi -= 1

Notice that, since generating all primes below n can be done in \$O(n \log \log n)\$ time, it is now the prime generation that dominates the total time, i.e. using this faster algorithm makes finding the pairs virtually free (when compared to finding the primes themselves).

A sample run:

>>> list(sum_of_primes(42))
[(5, 37), (11, 31), (13, 29), (19, 23)]


Being as big an advocate of prepared statements as I am, I cannot find any way for the SQL injection here, so your code should be safe.

I could only do the usual routine of making this code less bloated:

$query = "SELECT * FROM `table` WHERE `status` = '0' ";

if(!empty($_POST['codes'])) {
    preg_match_all("/\d{6}/", $_POST['codes'], $codes_array);
    $codes_array = array_unique($codes_array[0]);
    $codes_list = implode(",", $codes_array);
    $codes_add = $codes_list ? " AND `code` IN ($codes_list)" : "";
    $query .= $codes_add;
}
$result = mysqli_query($link, $query);

basically, PHP already has a function to glue array values together called implode() and, based on my understanding of the SQL, I decided to change REGEXP for IN. If I am wrong, then you could simply change it back to regexp.


Processing a list to build an ip in a string format

There is a string.Join() method which would exactly do what you want like so

string ip = string.Join(".", ipList);

btw,  you don't need to call ToList() on a List<T>.


C# program which measures the distance between the average and maximum/minimum temperature

If you want to see how performance is you need to get the user input out of the loop.  I'm assuming you don't want to measure the time it takes someone to type in or paste in the data elements.

You don't need the variable how_many as it will always be the same as the Count of which, which by the way isn't a good name for a variable even something like results would be better name.

You also don't need the context array variable. Just need to store the current value not save each element as it loops through.

The variables i, y, max, average, min can all be declared in the loop scope and not need to be reset.

Calling Count() on  which.Count() is the Linq Count method, should just call the list Count property

I'm also assuming this is a beginner question and won't get into Console as input and validating the data coming from it is valid.

I personally didn't want to type in all the data so I made the computer generate random data, if in debug mode

    static void Main(string[] args)
    {
#if DEBUG
        var random = new Random();
        var inputs = "1000 1000".Split();
#else
        var inputs = Console.ReadLine().Split();
#endif
        var cities = Convert.ToInt32(inputs[0]);
        var days = Convert.ToInt32(inputs[1]);

        var data = new List<int[]>(cities);
        for (var i = 0; i < cities; i++)
        {
#if DEBUG
            var cityData = Enumerable.Range(0, days)
                .Select(_ => random.Next(100))
                .ToArray();
#else
            var cityData = Console.ReadLine()
                .Split()
                .Select(x => Convert.ToInt32(x))
                .ToArray();
#endif
            if (cityData.Length != days)
            {
                Array.Resize(ref cityData, days);
            }
            data.Add(cityData);
        }

        var timer = new Stopwatch();
        timer.Start();
        var results = new List<int>();
        for (var i = 0; i < cities; i++)
        {
            float max = float.MinValue;
            float average = 0;
            float min = float.MaxValue;
            for (var y = 0; y < days; y++)
            {
                var content = data[i][y];
                average += content;
                if (content > max)
                {
                    max = content;
                }
                if (content < min)
                {
                    min = content;
                }
            }
            average = average / days;

            if (max - average > average - min)
            {
                int position = i + 1;
                results.Add(position);
            }
        }

        Console.Write(results.Count + " ");
        Console.WriteLine(string.Join(" ", results));
        timer.Stop();
        Console.WriteLine();
        Console.WriteLine($"Total Processing Time: {timer.Elapsed}");
        Console.ReadKey();
    }

This code runs in less than a second on my machine.  I assume waiting for user input was what was taking the longest time in pervious one and not actually the processing of the data.


So far what I see is you aren't either casting nor sanitizing your $_POST variables but simply placing them into your SQL statement - it's better you perform some sort of filtering on those arguments (e.g. remove whitespaces, fixing invalid characters like '\' to '\\', etc.) and ensure you are passing numbers (according to your example you'd maybe use intval()), not a string or NULL value (unless that's intended, which I doubt).

In addition, the server-end should separate the database calls from parsing and filtering content - either as separate functions, files and/or both; if you were going the OOP route, then you'd set up a class(es) for either activity and use a layering system like MVC, N-Tier, MVVC.

All of this goes into making your code more reusable and easier to manage plus adds a layer of security via "Abstraction".


Passing an object to the view in CodeIgniter

I would like to add something to @Dukeatcoding comment in the question.  What is the point of passing the whole object? Thinking on it as a part of the main controller, you should only pass the data as an array to the model:

$data = array(
    'id_user'     => $usuario,
    'id_category' => $soporte->getCategoria
    'message'     => $soporte->getMensaje
)
$this->helpdesk_model->createSupport( $solicitud );

Although, as you are getting all these properties so often, what about a general getter in your soporte class?

public function getValue( $var ){
    return $this->{$var};
}

And you'd have something like:

$data = array(
    'id_user'     => $soporte->getVar( 'usuario'),
    'id_category' => $soporte->getVar( 'categoria'),
    'message'     => $soporte->getVar( 'mensaje' )
)

From your code, I would take care of the validation of your values, as it looks like you don't validate if they're numeric, if they exists on your DDBB, etc. Maybe you're doing it, because I suppose the code you posted is just a excerpt (due to some method are missed in Solicitud, as setSolicitante($nuevo) ), but I prefer to write it, just in case.

Also, I won't assign to a var the values you take directly, just call them an take the value:

//Instead of:
$session_data = $this->session->userdata('session_user');
$usuario      = $session_data['usuario'];
// Better
$usuario      = $this->session->userdata('session_user');

Off topic, you could check Doctrine, http://www.doctrine-project.org/projects/orm.html, is an ORM that maybe could help you, and it has its own CI recipe:
http://docs.doctrine-project.org/en/2.0.x/cookbook/integrating-with-codeigniter.html

Have fun!


Your approach vs PDO

First of, you take perfectionally acceptable exceptions, and transform them into error strings, which are harder to handle.

And I'm also not sure if all your the methods really make things easier.

Let's take insert as an example:

// with your code:
$result = $db->queryInsert("myTable", "key1, key2, key3", ":value1, :value2, :value3", ["value1", "value2", "value3"]);
if ($result == "well, what do I even check here?") {
    // handle error
}

// without your code:
$prepare = $db->prepare("INSERT INTO myTable (key1, key2, key3) VALUES (:value1, :value2, :value3)");
try {
    $prepare->execute(["value1", "value2", "value3"]);
} catch(PDOException $e) {
    // handle error
}

Without your code, it's not that much more to write, and it is a lot clearer what is actually happening.

Improving your approach

Now, I'm not generally a fan of wrapping/extending PDO like this, but you can improve your methods to make it a bit more usable.

First of, documentation. It is completely unclear from the outside how to use your code. This can also easily lead to security issues, as $insertKey and $insertData should not be user-supplied.

Secondly, it's really not needed that a user passes $insertData themselves. It makes your method harder to use, it doesn't provide any additional functionality for a user, and as said above, it can easily lead to vulnerabilities.

Thirdly, as mentioned, use exceptions instead of error strings.

A better method signature might be this:

public function queryInsert($tableName, $insertKey, $insertData) throws PDOException

Now it can be used like this:

try {
    $db->queryInsert("myTable", "key1, key2, key3", ["value1", "value2", "value3"]);
} catch(PDOException $e) {
    // handle error
}

That's already a bit nicer, but really not that much simpler than the original query (and harder to use, as it's not really clear what the passed values need to be), so I'm not sure if it's worth it.

I would probably stick to the well-known and simple PDO interface. If you want to simplify it, or don't like to write plain SQL queries, something like a query builder or an orm might be worth looking into.

Security

Your approach completely disguises which values are safe and which are not, which will lead to security issues.

Basically, only $executeData may contain user input.

For some of the other values, a user may not expect it to be secure (such as $tableName), but just to be safe, I would still validate it.

For some values, this is devestating. Having such an interface as yours, I would completely expect eg $insertWhereValue to be secure.

Misc

Bug: $insertWhere doesn't exist.
You have a couple of spelling mistakes, such as sellect or mysel.


Asynchronously accepting multiple client connections without impacting main thread

Some quick remarks:

Always add access modifiers.
You're not using string[] args, so remove it.
I'm not a fan of private properties, certainly not when they could be fields (and thus they should not have getters/setters). private TcpListener server { get; }, private ConcurrentBag<TcpClient> _clients { get; set; }
Be consistent in naming: _clients starts with an underscore, which is a naming convention usually used for fields, but server doesn't start with an underscore.
Properties should be PascalCase: public List<TcpClient> clients. I feel the same applies to private ones (previous remark).
No underscores in names (with the exception of an underscore prefix for fields, of course): Game_Server.


Interfacing between workbooks (Exporting data Table and key properties)

Just looking at your function there 2 ways to improve it:

Public Function GetDataArrayFromSheetByCodename(ByVal strCodeName As String) As Variant
  Dim ws As Worksheet
  For Each ws In ThisWorkbook.Worksheets
    If ws.CodeName = strCodeName Then
      Set GetDataArrayFromSheetByCodename = GetTableRange(ws)
      Exit Function
    End If
  Next ws
  GetDataArrayFromSheetByCodename = CVErr(2042) '/ #N/A error
End Function

When having LOTS of sheets, this may be faster, but uses an error:

Public Function GetDataArrayFromSheetByCodename(ByVal strCodeName As String) As Variant
  On Error Resume Next
  If Len(ThisWorkbook.VBProject.VBComponents(strCodeName).Name) = 0 Then
    GetDataArrayFromSheetByCodename = CVErr(2042)
  Else
    Set GetDataArrayFromSheetByCodename = GetTableRange(ThisWorkbook.VBProject.VBComponents(strCodeName))
  End If
End Function

Also as a quick-inprove just add Exit For after your wsWasFound = True to not loop all sheets that are left after you found a match.

For the second version of the function: I use the fact that errors inside of conditions inside of If-statements are always true when using On Error Resume Next. Len(....Name) = 0 Then normally NEVER can be true when there is a need of a name. But having an error inside will act like the whole statement is true. So it simply tries to catch the item. If it exists, it also has a name this way Len will be >0 and be false (now your calculation will be done), else (it doesn't exist) it will act like If is true and the = CVErr(2042) will be set.
For the Subs: they doesn't make sense to me. What do they do? As it looks to me, they do simply nothing.

Last hint: You may change the function to As Range. When set a variable to it, you later could simply check by If Variable Is Nothing then. So there would be no need for = CVErr(2042).

EDIT
just to show the way i would hand over the values (while im pretty sure you will not use it)

Public Function GetDataTableHeaders() As Variant
GetDataTableHeaders = Array("Client Name", "Client Name", "Income", "Frequency", _
  "Date Paid", "Base Month", "Wrapper", "Ascentric Acc #", "Account to pay from?")
End Function

then simply set a variable to it or directly use GetDataTableHeaders(2) to get "Income"... as it looks, you may want to output the values to a sheet as headers and this way it would be much easier. However, you want to make it "not understandable" in some way, and for that it will be better to stay as it is right now :)


Thanks for your fast response guys, after reading your messages I tried to solve it different:

public static void reverse(String phrase, char delimiter) {
        char[] newPhrase = new char[phrase.length()];
        int start = 0, i = 0, currentPos = newPhrase.length;
        while (i < phrase.length()) {
            if (phrase.charAt(i) == delimiter || i == phrase.length() - 1) {
                char[] word = phrase.substring(start, i).toCharArray();
                currentPos = currentPos - word.length;
                System.arraycopy(word, 0, newPhrase, currentPos, word.length);
                if (i != phrase.length() - 1) {
                    newPhrase[--currentPos] = delimiter;
                }
                start = ++i;
            } else {
                i++;
            }
        }

        System.out.println(new String(newPhrase));
    }


Printing a heartbeat (heart star) animation

Welcome to CodeReview! The program doesn't look too bad, however there are some ways to improve it:
Naming things
The biggest issue with your code is that there is a bunch of single-letter variable names (i...k), some magic constants (2, 3, 4, 17 and 99), and nested while-loops. If I wasn't told what this program would do and didn't run it for myself, I would have no clue reading this code what it is going to do. However, if you would give (better) names to things, it might explain what everything means to the reader. That includes you yourself in the future!
Let's start with the outer loop:
int main() {
    for (int i = 0; i < 99; i++) {
         int size = i % 3;
         clear_screen();
         draw_heart(size);
         usleep(200000);
    }
}

Keeping i as a generic loop counter is OK, as this is so commonplace that a longer name is not going to make this more readable. But I renamed h to size. Then I assume you have created two functions, one for clearing the screen, and another for drawing a heart of a given size. If you now read this code, you can very quickly see that you are repeatedly drawing a heart of a varying size, without requiring any comments.
Here is the function to clear the screen:
void clear_screen(void) {
    // Use ANSI escape codes to clear the screen
    printf("\e[1;1H\e[2J");
    printf("\e[?25l");
}

The name of the function alone is already enough to know what the function tries to do, the comment here is to explain the weird characters that are printed. Someone who doesn't recognize these escape codes now knows what these are, and can search for "ANSI escape codes" to find out more about them.
The constants you have in your code could be given names, like so:
void draw_heart(int size) {
    static const int top_size = 3;
    static const int bottom_size = 9;
    ...
}

And then used consistently in the calculations you use, such that if you want to change the size of the heart, you can just change these constants.
Use for-loops where appropriate
You are using a lot of while-loops in cases where you can more clearly write for-loops. Any time you initialize a variable, run while the variable satisfies some condition, and then update that variable, use for, like so:
void draw_heart(int size) {
    // Draw two small upward pointing triangles
    for (int i = 0; i < 3; i++) {
        for (int j = 0; i < (2 - i) * 2 + size; j++) {
           printf(" ");
        }

        ...
    }

    // Draw one large downward pointing triangle
    for (int i = 0; i < 9; i++) {
        ...
    }
}

The advantage is that in one line you combine all this information, so just from reading that line you can see what the start condition is, what the end condition is and how the variable is updated every step.


There's two things that I'm seeing right off the bat.

Don't use "magic integers" where you can be using Enums.  GetDiscounts should probably receive an enum, not an int:

var discVal = GetDiscounts(items, RecordEnums.ProductClassification.Service);
You don't need to Select then Max.  Just using Max will give you the desired outcome.

decimal highestContractTerm = items.Where(x => x.ProductTypeId == (int)RecordEnums.ProductClassification.Service).Max(y => y.RecurringTerm ?? 0;


This works but feels clunky

This seems fine. It does the job well. I don't see how this can be done simpler, and I'm not aware of other existing method in the SDK that can help simplify this.

  any suggestions for improvement?

I have only minor suggestions:

The method uses depth first search to find a view. Depending on the actual tree of views in the application, this might be slow, for example when you have very deep trees but the class you're looking for is at a shallow level. In such case a breadth first search would perform better. This is not something to "fix", just something to keep in mind, and adjust to your actual application as necessary
Another point to keep in mind is that the method will return the first view with matching class. When there are multiple views of the same class, a user might not get the one expected
As with any utility method, it's good to add a nice javadoc. That will be a good place to mention about the previous points (search algorithm used, returns first match).
A common name for Class instances is clazz. I suggest to use that name to make the code look more familiar to other developers, and it's shorter too than classReference
The "ByClassReference" in the method name is redundant, because this is implied by the method signature
The formatting could be slightly more readable if you apply auto reformat in Android Studio


You're most of the way there, so I'll give you a hint to avoid spoiling the problem:

Your function triangular shows that you know that the formula for the \$ n \$th triangular number is $$ T(n) = { n(n+1) \over 2 }. $$ What numbers can possibly be divisors of \$ T(n) \$? Take a look at some small values of \$ n \$ and see if there is a pattern.

As far as code review goes, some quick points:

Better choice of variable names would make the code easier to read. For example k and a are essentially the same thing (each is the power of a prime in the factorization of x) so why do they have such different names?
y loops over the odd numbers, but if you're solving lots of Project Euler problems then you have probably written a prime number sieve and so you could use that here (and avoid the special case for 2 while you're about it).
Use augmented assignment to make the code shorter and simpler, for example, z=z*(a+1) can be written z *= a + 1.


Another way to find the nearest neighbor points in a 2D plane

Your algorithm looks (and works) great, but I found two problems with part of code responsible for finding closest pair within band.

Wrong pair of points is returned as result

The closest distance in d variable is correctly updated, but first_point and second_points are updated even if d < dist(*p, *last), which leads to returning wrong pair of points. You can reproduce the problem on following set of points: {-1, 10}, {0, 10}, {0, 9}, {0, 8}, {0, 7}, {0, 6}, {0, 5}, {0, 4}, {0, 3}, {0, 2}, {0, 1}, {0, 0}, {0.99, 0.99}

You can fix that by replacing your for loop with the following one:

for (auto p = begin; p != end; ++p) {
    if (d > dist(*p, *last)) {
        first_point = *p;
        second_point = *last;
        d = dist(first_point, second_point);
    }
}

for loop is not executed when there is only one point in band

If there is only one element in band, then both lower_bound and upper_bound return iterator pointing to the same element in band, which means that for loop will not be executed, because the condition p != end is not met. You can reproduce the problem on following set of points: {-1, 0}, {0 ,0}, {0.1, 0.1}


Use descriptive variable names
No need to add one to x and then use range(1, w)  - get used to using zero-based numbering
By convention in Python you can use _ as the name for a loop variable when you won't actually be referring to that variable anywhere.
As you develop this into a full programme, structure code under functions.
use blank lines sparingly

So:

def main():
    number_of_times = int(input("Choose the number of times you want to spam. "))
    message = input("What message do you want to spam? ")
    for _ in range(number_of_times):
        print(message)

Alternatively:

print((message + '\n') * number_of_times)


I'm not sure what you're using this for, but my advice: Don't bother validating the filename.  Just open the file.  The system knows the rules better than you do, and by adding too much validation you can cause problems down the line.

On Windows these rules are especially complex.  Frankly you will never find them all.  Here's a few you missed, off the top of my head:

Filenames may contain unicode characters.  You are using char*.  Unless you're using UTF-8 and passing all your filenames to MultiByteToWideChar before they reach a file API, you're ruling out a lot of potential valid paths based on that.  (Not to mention the way these filenames get mapped to Unicode is now subject to the user's language settings, which one can argue is a bad thing in its own right...)
MAX_PATH.  You're assuming that all paths will fit in a buffer of that size.  On Windows you can actually have a path longer than MAX_PATH if it starts with \\?\; also things like \\?\C:\foo are valid paths.
Names containing trailing spaces or dots, which you seem to be filtering on, are also valid and distinct if the path begins with \\?.  Without that prefix, trailing dots and spaces get truncated.
Paths under \\.\, \\?\GLOBALROOT.

Not to mention, these rules could potentially be subject to change.  Note that Win9X had different rules than NT.  What if such a change occurs again and breaks your logic?  Don't bother duplicating these rules in your code; don't second-guess the filesystem either.  Just pass the name to CreateFile.

(Aside: If your filename happens to come from an untrusted source, then it probably is fair to be overly restrictive...)


Storing hierarchical data into a data structure

There are actually a couple of issues with that approach, so we will step through them one by one.

Let's start with with revising what a tree is. A tree is coherent, undirected graph with a single root node and no loops.

Let's compare that with your sample data (and the implementation based on it):

There are no loops - Check
There is exactly one root node - No, there are two. And the graph isn't coherent either.

So what you have in your database isn't a tree to start with.

Add a new node which is the only root to your graph, and attach all of the previously created root nodes to this new node. This makes it much easier to work with the data.

Now let's have a look at your code. There are a couple of oddities which strike immediately:

Using == for comparisons

You got to be careful with with == in PHP, it's not typesafe. What this specifically means for you, in your case, it that 0 == NULL is actually true, while the typesafe === operator correctly yields false.

This is an important difference for you, since you are using NULL as a special value, but there might also exist an entry with the perfectly valid numerical ID 0.

Having an $accum variable

This is a direct consequence of not having a single root node. Half of your code revolves around deciding whether a node you visited is a root node or not. Specify a root node explicitly prior to entering the recursion, and this problem is void.

Scanning the result set multiple times instead of indexing it

You don't actually need to iterate over the result set over and over again to find the rows you want. Index it once, and you are good to go:

index = []
foreach(rows as row) {
    index[row->id] = row
}

That's one of the benefits of PHP, you have always a hashmap at hand when you need one ;)

Supporting only a single level of nesting

Let's see what happens if we add another generation of children. $items suddenly lists the child with grandchildren as another regular root.

Ups, that did not go as expected, did it?

Not using the return statement in a recursion

This points out that you have a rather weird understanding of recursion. When you do a recursion, your goal is always to to break the problem down into smaller problems, and to return a partial solution.

In this case, respectively for a tree in general, your goal is always to completely construct a single sub-tree, starting at the current node, prior to passing the current tree back to the parent context.

So in short, for traversing a tree, the recursion function looks something like (pseudo code):

TreeObject build_tree(id, index) {
    tree = new TreeObject(index[id]);
    foreach(index as node) {
        if(node->parent == id) {
            tree->children[] = build_tree(node->id, rows);
        }
    }
    return tree;
}

Notice a difference? There is nothing modified by reference. In a recursion, there is no global state, each single recursion step only reads the data.

A strange way to sort children

There is nothing wrong with wanting to define an order on children of a node, but make sure you are aware what it actually means. It's still a tree, so the same construction applies. But in addition, you want to be able to sort the children of a node. Or even better, already have them sorted, e.g. in a linked list.

A linked list just what you constructed with prev_id, except that you got it linked backwards, not forwards. If you really want to use this structure (I will cover alternatives later), do yourself a favor and use next_id instead. This at allows to traverse the list of children in a more natural way.

Furthermore, if you want to be able to use the linked list half way efficient, make sure that you always store an entry point to the linked list. This means in addition to next_id, also store a first_child on the parent node.

Let's just extend the code sample for better comprehension:

TreeObject build_tree(id, index) {
    tree = new TreeObject(index[id]);

    next_child = tree->first_child;
    while(next_child_id != NULL) {
        tree->children[] = build_tree(next_child, index);
        next_child = index[next_child]->next;
    }
    return tree;
}

Still rather comprehensible, isn't it? Unfortunately, the drawback of using next and first_child references is that updating the database just got slightly more complicated.

It's generally better to just use a index which can be sorted by. So best drop next_id and first_child again, and instead just add an sort_index field which contains a unique number for each entry. You can then just fetch the rows in the correct order from the database, and the previous algorithm already yields the children in the correct order.

(Bonus round: Ensure that sort_index is not only ascending for all children of a single node, but also when traversing the tree in pre-order. Now the previous algorithm can be modified to traverse the result set from the database only a single time, treating it as a queue which only supports the pop and peek functions. If you got that working, congratulations. Your algorithm has just reached O(n) runtime.)

Reinventing the wheel. While it is possible to fix the flaws in the design to get the recursion working properly, storing a tree with a fixed order in a database is actually a standard problem. A problem to which much better solutions than explicitly storing parent-child relations are known.

Before we go ahead, ask yourself a question: Given that the database actually contains a much larger tree, and you only want to fetch a sub-tree starting at a given node, how would you do that?

Right, you couldn't, at least not without modifying the algorithm slightly. You would always have to fetch the whole table content.

There is actually a model which provides that, and also gives the sort order of children for free: Nested set model

Have a read for yourself, knowing how these structures work can never hurt.