Computing nth Tribonacci number at compile time using C++ template metaprogramming facilities

This is a pretty cool practice project, and your implementation is sound.
First to answer your concern… can you drop the static? The answer is no… and yes.
The way you’ve implemented the solution, no, you really can’t drop the static. The code doesn’t really make sense without it. If you are doing tribonacci<N>::value, and tribonacci<N> is a type (as it is in your code), then value must be a static data member. That’s what the :: means (in this context); tribonacci<N> is a type, and value is a property of the type.
However….
This is how you would implement a constexpr tribonacci sequence generator in C++11. That’s 3 versions old now, and counting. And one of the things that has advanced the most in each new version of C++ is constexpr capability.
If you don’t want value to be a class data member, you could make it a regular data member, like so:
template <std::size_t N>
struct tribonacci
{
    std::int_fast64_t const value = tribonacci<N - 1>{} + tribonacci<N - 2>{} + tribonacci<N - 3>{};

    constexpr operator std::int_fast64_t() const noexcept { return value; }
};

template <>
struct tribonacci<0>
{
    std::int_fast64_t const value = 0;

    constexpr operator std::int_fast64_t() const noexcept { return value; }
};

template <>
struct tribonacci<1>
{
    std::int_fast64_t const value = 0;

    constexpr operator std::int_fast64_t() const noexcept { return value; }
};

template <>
struct tribonacci<2>
{
    std::int_fast64_t const value = 1;

    constexpr operator std::int_fast64_t() const noexcept { return value; }
};

auto main() -> int
{
    constexpr auto sixth_trib_num = tribonacci<6>{}; // to prove it's constexpr

    std::cout << tribonacci<0>{} << '\n';       // will auto-convert to std::int_fast64_t
    std::cout << tribonacci<1>{}.value << '\n'; // or you can manually request the value
    std::cout << tribonacci<2>{} << '\n';
    std::cout << tribonacci<3>{} << '\n';
    std::cout << tribonacci<4>{} << '\n';
    std::cout << tribonacci<5>{} << '\n';
    std::cout << sixth_trib_num << '\n';
}

As you can see, no more static, but now you need to actually create an object (like tribonacci<6>{}) rather than just using the type (like tribonacci<6>), because now value is a property of the object, not the type (like tribonacci<6>{}.value).
Perhaps an even better option is to use variable templates. After all, each tribonacci number is just a number… it doesn’t need to be a type.
template <std::size_t N>
inline constexpr auto tribonacci = tribonacci<N - 1> + tribonacci<N - 2> + tribonacci<N - 3>;

template <>
inline constexpr auto tribonacci<0> = std::int_fast64_t{0};

template <>
inline constexpr auto tribonacci<1> = std::int_fast64_t{0};

template <>
inline constexpr auto tribonacci<2> = std::int_fast64_t{1};

auto main() -> int
{
    std::cout << tribonacci<0> << '\n';
    std::cout << tribonacci<1> << '\n';
    std::cout << tribonacci<2> << '\n';
    std::cout << tribonacci<3> << '\n';
    std::cout << tribonacci<4> << '\n';
    std::cout << tribonacci<5> << '\n';
    std::cout << tribonacci<6> << '\n';
}

With this, tribonacci<6> is a std::int_fast64_t constant. There are no classes to instantiate or any other cruft. This probably the way you want to go in C++14 and beyond; certainly in C++20 and beyond.
So, no, you can’t drop the static if you’re using the design you currently have. But there are other, better, alternatives in more modern versions of C++.
Now for your actual code review….
template<uint64_t N>
struct tribonacci {

First, if you’re going to use uint64_t, it should be spelled std::uint64_t.
But using uint64_t is generally a bad idea. You see, uint64_t is an optional type; it is not guaranteed to exist. And if it does, it is not guaranteed to be an efficient type; it could actually require significant emulation to work, and it could be tragically slow.
Better options are unsigned long long, std::uint_fast64_t, std::uint_least64_t. Which one you choose depends on what you really want:

unsigned long long: This is guaranteed to be at least 64 bits… but could (theoretically) be 128 bits, 256 bits, or anything else. If you only need 64 bits, it could be overkill. However, it will probably be at least as efficient (speed-wise, not space-wise) as any other option, if not more.
std::uint_fast64_t: If you really just need a 64-bit type, this should be your default choice. It will be the fastest type supported by the architecture that is at least 64 bits. So it may be more than 64 bits (like unsigned long long it may be 128 bits, or 256 bits, or whatever). But it may be smaller than unsigned long long, and probably as fast.
std::uint_least64_t: This is what you use when you want a type that is at least 64 bits, but you care more about conserving space than getting maximum speed. This will be the smallest type the platform supports that can hold 64-bit values… even if that type requires lots of code to emulate.

So, in a table, your options are (note that the size and speed are the worst case estimates):

Type
Size
Speed
Notes

std::uint64_t
Bad
Bad
Not guaranteed to exist

unsigned long long
Bad
Excellent
Good choice if you need at least 64 bits, but much more is fine too

std::uint_fast64_t
Good
Good
Best choice if you only need 64 bits

std::uint_least64_t
Excellent
Bad
Best choice for saving space

There is another issue with uint64_t, and that is that it’s an unsigned type. Using unsigned types for general purpose numbers is a bad idea, for a number of reasons. You should only use unsigned numbers if you are doing bit-twiddling, or if you explicitly need modulo arithmetic. Otherwise, signed should be the default choice. The problems unsigned numbers cause are not worth the one extra bit of space.
Of course, you could also let the user pick the type:
template <std::size_t N, typename T = int> // defaults to regular old int
inline constexpr auto tribonacci = T(tribonacci<N - 1> + tribonacci<N - 2> + tribonacci<N - 3>);

// note in c++20, you could also constrain the type, like so:
//  template <std::size_t N, std::integral T = int>

template <typename T>
inline constexpr auto tribonacci<0, T> = T(0);

template <typename T>
inline constexpr auto tribonacci<1, T> = T(0);

template <typename T>
inline constexpr auto tribonacci<2, T> = T(1);

// if you're working with int_fast64_t a lot, then make a handy alias
template <std::size_t N>
inline constexpr auto tribonacci64 = tribonacci<N, std::int_fast64_t>;

auto main() -> int
{
    std::cout << tribonacci<0> << '\n';                 // int(0)
    std::cout << tribonacci<1, long> << '\n';           // long(0)
    std::cout << tribonacci<2, std::int64_t> << '\n' ;  // int64_t(1)
    std::cout << tribonacci64<3> << '\n';               // int_fast64_t(1)
}

Finally, I don’t know if you noticed, but in all the examples I made, I made the index type std::size_t, and the value type something else: int, std::uint_fast64_t or whatever. That’s because when you do auto v = tribonacci<N>, the N has nothing to do with the actual tribonacci number. It’s just the counter to pick which tribonacci number you want. v is the actual tribonacci number. That’s what you want to be at least 64 bits or whatever. N doesn’t need to be 64 bits; you’re going to blow past 64 bits by the 75th tribonacci number, so you only need N to be able to hold 7 bits for 64-bit tribonacci numbers.
std::size_t is the default type in C++ for counting, indexing, sizes, and so on. So it makes sense for N to be std::size_t. As for the value type… that should be whatever the user wants. Above I went with int by default (as you always should).
That’s pretty much it for the review. My recommendations:

Don’t use uint64_t as the value type for the tribonacci number:

Don’t use unsigned types for general numbers.
Don’t use fixed size types. They’re not portable, and even when they are, they might be inefficient.
Let the user pick the type, though you can offer a sensible default (which should probably be int).
It’s std::uint64_t anyway.

Don’t use uint64_t as the index type:

The default index type is std::size_t.

Rather than old-school template meta-programming, using types for each tribonacci number, use variable templates.


Using setInterval() to make data reactive

Use events and callbacks to react to things as they happen instead of repeatedly checking for changes.
You can use the .then function to do whatever needs to be done once the data is received.
You can learn about the <video> element events here: https://www.w3schools.com/tags/ref_av_dom.asp


How to make the end of loop more readable in Ruby

Compare your code to how I'd write it:

require "faker"

real_sn = 2124100000

File.open("lib/tasks/tw_books.txt", "r").each do |line|
# author = Faker::Lorem.words(2..5).join(' ').gsub('-','').gsub('\s+','\s')

  1.upto(1000).each do |x|

    location = Faker::Lorem.words(5)
    book_name, author, publisher, isbn, comment = line.strip.split("|||")

    ap(line)

    isbn = isbn[/\d+/]
    real_sn += 1

    bk = Book.new(
      :author => author,
      :category =>["商業","歷史","體育","政治"].sample,
      :comment => comment,
      :isbn => isbn,
      :location =>location,
      :name => book_name,
      :price => Random.rand(200..5000),
      :publisher => publisher,
      :release_date => rand(10.years).ago,
      :sale_type => [
        :fix_priced,
        :normal,
        :promotion
      ].sample,
      :sn => real_sn,
    )

    if bk.save()

      puts book_name if ((real_sn % 100) == 0)
      Sunspot.commit

    else

      puts real_sn
      puts bk.errors.full_messages

    end
  end
end

Part of writing code is making it readable and maintainable. That means use indentation, vertical alignment, whitespace between operators, vertical whitespace to make changes in logic more obvious, etc.

I sort hash keys alphabetically, such as the parameters for Book.new, especially when there's a lot of them. This makes it a lot easier to see if something is duplicated or missing. Since it's a hash it doesn't matter what order they're in as far as Ruby is concerned; Again this is for maintenance later on.

The editor you use can help you immensely with this. I use gvim and Sublime Text, both of which allow me to easily reformat/reindent code I'm working on, and I take advantage of that often. It's a good first step when you have code from a "foreign source" that makes your eyes bug out. Reindent it, fix long, awkward sections, like your list of hash entries for Book.new, and the code will become more understandable.

Also, your editor needs to have the ability to jump between matching delimiters like (), [], {} and do/end. gvim can do that plus jump through if/else/end plus rescue blocks. That ability to navigate REALLY helps keep your code flow clear.


Ok, here is a smaller scope for $running and do_work() doesn't need to bother with it,

sub do_work {

    my $worker_cv = AnyEvent->condvar;

    $worker_cv->begin;
    fork_call {
        work1();
    } sub {
        $worker_cv->end;
    };

    $worker_cv->begin;
    fork_call {
        work2();
    } sub {
        $worker_cv->end;
    };

    return $worker_cv;
}

my $running;
my $timer = AnyEvent->timer(
    interval => 5,
    cb => sub {
        return if $running;

        $running = 1;
        do_work()->cb(sub{
            $running = 0;
        });
    }
);


Replace ' ' Spaces in a URL with a '%20' - Coding Challenge

From a short review:

If you are going to write your own replace, then you should create a method for it, so that you can call myReplace( string, target, replacement);
Personally I would have checked if args got a String, and only if nothing is provided would I use the hard coded string, that would make it easier to show and test your design
No reason to do this in 2 lines:

str = URLify(str);
System.out.print(str);

you can just write

System.out.print(URLify(str));

Javadoc commenting looks good (but is not actually true?), otherwise there are zero comments
I am pretty you can merge those 2 loops into one if you used a stringbuilder. On the whole the replace algorithm could use work


OK, now it is SOLID :)

Let's do not mix infrastructure and application code. Unfortunatly a lot of stuff is missing in .NET, so infrastructure first.

AsyncStream:

public interface IAsyncStream
{
    Task WriteAsync(
        byte[] buffer,
        int offset,
        int count,
        CancellationToken cancellationToken);

    Task FlushAsync(CancellationToken cancellationToken);
}

BufferedAsyncStream:

public class BufferedAsyncStream : IAsyncStream
{
    public BufferedAsyncStream(IAsyncStream inner, long bufferSize = 8192)
    {
        Inner = inner;
        Buffer = new byte[bufferSize];
        BufferStream = new MemoryStream(Buffer);
    }

    public async Task WriteAsync(
         byte[] buffer,
         int offset,
         int count,
         CancellationToken cancellationToken)
    {
        if (FreeSpace < count)
            await FlushAsync(cancellationToken)
                .ConfigureAwait(false);

        BufferStream.Write(buffer, offset, count);
    }

    public async Task FlushAsync(CancellationToken cancellationToken)
    {
        await Inner.WriteAsync(Buffer, 0, Allocated, cancellationToken)
            .ConfigureAwait(false);

        await Inner.FlushAsync(cancellationToken)
            .ConfigureAwait(false);

        BufferStream.Seek(0, SeekOrigin.Begin);
    }

    int FreeSpace => (int)BufferStream.Length - (int)BufferStream.Position;
    int Allocated => (int)BufferStream.Position;
    IAsyncStream Inner { get; }
    byte[] Buffer { get; }
    MemoryStream BufferStream { get; }
}

AsyncWriter:

public class AsyncWriter
{
    public AsyncWriter(IAsyncStream stream)
    {
        Stream = stream;
    }

    public Task WriteAsync(ulong value, CancellationToken cancellationToken)
    {
        var buffer = BitConverter.GetBytes(value);
        return Stream.WriteAsync(buffer, 0, buffer.Length, cancellationToken);
    }

    public Task FlushAsync(CancellationToken cancellationToken)
    {
        return Stream.FlushAsync(cancellationToken);
    }

    IAsyncStream Stream { get; }
}

Now application code. ISocket being adapted to IAsyncStream:

class SocketStream : IAsyncStream
{
    public SocketStream(ISocket socket)
    {
        Socket = socket;
    }

    public Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
    {
        return Socket.WriteAsync(buffer, offset, count, cancellationToken);
    }

    public Task FlushAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    ISocket Socket { get; }
}

So, we can construct writer in the following way:

var writer = new AsyncWriter(
    new BufferedAsyncStream(
        new SocketStream(socket)));

UPDATE
You could use this overload to remove "noise":

public class AsyncWriter
{
     ...
    public async Task WriteAsync(
        CancellationToken cancellationToken, params ulong[] values)
    {
        foreach (var value in values)
            await WriteAsync(value, cancellationToken)
                .ConfigureAwait(false);
    }

Now it is this way:

  await writer
     .WriteAsync(
         cancellationToken,
         obj.Member1, obj.Member2, obj.Member3, obj.Member4)
     .ConfigureAwait(false);


Add the first non-null item from one list to another list

I agree with @RickDavin that the first function expresses its intent in a more obvious way.

My main concern, though, is that neither function provides feedback as to whether the operation actually resulted in any change.  The function should return a boolean.  It's easy to modify the first function to return a boolean, but not the second.


Regex
I think your String.replaceAll(String, String) is fine, as regular expressions don't fall afoul of any of the rules. :) Just watch out for @Bastien Aracil's comment, that you will be removing literal "null" values.
With that said...
Break the rules...?

DO NOT use arrays
DO NOT use StringBuffer or any other type of optimized String variants

These are going to be nearly impossible to conform, since a String is fundamentally a char array, and even a simple "a" + "b" uses an underlying StringBuilder for the concatenation. If one can partially 'hand-wave' the implicit StringBuilder away when using the + operator, I suppose one can also do a smaller 'hand-wave' of the implicit char array modification with String.concat(String):
private static String join(String first, String second) {
    if (first == null || first.isEmpty()) {
        return second == null ? "" : second;
    }
    return second == null ? first : first.concat(" AND ").concat(second);
}

What we do here is to codify our logic as such:

If the first string is either null or empty, we either return second or an empty one.
Afterwards, if the second string is null, we return first, i.e. no concatenation done, or actually perform the concatenation with " AND ".

We then just need to 'recursively' call this with the five arguments, and a null or "" as a 'starter' with a:
private static String joinWithAnd(String a, String b, String c, String d, String e) {
    return join(join(join(join(join(null, a), b), c), d), e);
}

Java 8
Going further, we can just rely on streams (not collections) and StringJoiner (technically not a String 'variant', whatever that means) to get the same output:
private static String joinWithAnd(String a, String b, String c, String d, String e) {
    return Stream.of(a, b, c, d, e)
                .filter(Objects::nonNull)
                .collect(Collectors.joining(" AND "));
}

And, if one is being extra pedantic with the question's language, we can replace Stream.of(T...), technically an array, with multiple Stream.concat(Stream, Stream) calls:
// return Stream.of(a, b, c, d, e)
return Stream.concat(Stream.concat(Stream.concat(Stream.concat(
                Stream.of(a), Stream.of(b)), Stream.of(c)), Stream.of(d)), Stream.of(e))


Header file for accessing components globally in library

As noted by commenters, you will get multiple definition errors if you try to include this header in multiple translation units. The functions must be marked inline, or the header file reduced to the declarations, with the definitions placed in a separate source file.
The std::string format argument is copied unnecessarily as it is passed by value. It should be passed by const& instead. (Or replaced with std::string_view).
The difference between all these functions is the format string. As such, we don't really need the functions at all. We can define the format strings as constants, and the user can pass the one they need to get_chrono.
get_chrono is probably not the best name for the function. Maybe format_time_now, or format_time.
The function would be much less restrictive if the time were passed as an argument. It can then be used for formatting other times than now.
Note also that in the original code, if we wanted to call get_second and get_minute for one point in time (say for some custom output format), we can't! Because now will have changed between the calls, and we might end up with incorrect output.


A palindrome checker has to have a worst case of \$O(n)\$ because you have to check each character to verify that it is a palindrome.

I would expect your first solution to be slower than your second solution, as it checks each character twice.  Unless your compiler's optimization is really brilliant, this should be slower.  But the proof's in the pudding.  If you really want to know, test it on a million strings and see.  Analysis is great but testing is better.

        if (s.length()%2==0) {
            for (int i = 0; i<(s.length()/2); i++) {
                if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
                    return false;
                }
            }
        }
        else {

            for (int i=0; i<(s.length()/2); i++) {
                if (s.charAt(i)!=s.charAt(s.length()-1-i)) {
                    return false;
                }

            }

        }

You notice anything about the two loops?  They're identical.  You can just do one loop with no outer if/else:

        for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }

This works because you start from the ends and work your way to the middle.  It will also work if you say i <= j (which checks the middle character if there is one), but that's not necessary.  The middle character will always equal itself.  You don't need to check it.

The thing that I don't like about s.length()-1-i is that it puts the burden on the compiler to realize that s.length() - 1 is constant relative to the loop.  Also, it's conceivable that decrement is faster than subtraction in some implementations.  Doing it this way means that we know that s.length() - 1 would only be calculated once.  The other way we're relying on the compiler to optimize it.

I don't know how the StringBuilder reverse is implemented, but it's possible to implement it without changing the underlying data at all.  Just index in the opposite direction.  Even if they do copy it to a new structure, that can be done in \$O(n)\$ time.  The comparison is also \$O(n)\$, so asymptotically that doesn't matter.


Determine if requested documents exist and if they do, whether they match requested revision number

When you have code that starts to look like this, it's a sign that you need to write more functions to abstract some things away. You might put the code inside the two for loops into its own function, for example.


Faking a pass method when building an array

What it looks like you really want is:

beverage_links = beverage_info.select{|bvg| self.is_menu_item?(bvg)}.map{|bvg|bvg["href"]}

This might be a bit confusing, so to break it down

beverage_info.select { |bvg| self.is_menu_item?( bvg ) }

This returns an array of items in beverage_info that return true* for is_menu_item?

  .map { |bvg| bvg["href"] }

This translates each of the items in the array returned in the previous into their "href" value. Finally you assign that to beverage_links.

If beverage_info is an array of beverages, I recommend you rename it to beverages. It is obvious that if you have a beverage, you have the info of that beverage.

If beverages are a custom class, give it the method is_menu_item? because nothing else will use that (unless you have, say, burgers that are also menu items. In that case, both Beverages and Burgers should extend some Food class that has the is_menu_item? method).  The way you have it now, it doesn't look like you need to be using the self keyword, but it's hard to tell without context.

* Actually, it returns all items that return ANYTHING that isn't false or nil for is_menu_item?


Algorithm is incorrect

The algorithm you are using is incorrect because you do not find the proper range of primes to use for your segmented sieve.  You are currently finding and using primes in the range 0..(n-m+1).  But you actually need to be finding primes in the range 0..sqrt(n).  Here is a trivial test case that demonstrates the problem:

1
9 9

For this test case, you find primes in the range 0..1, which finds no primes, which leads to an incorrect result where you print 9 as a prime.  The correct range of primes should be 0..3 for this test case.

Find primes once

Given the maximum \$n\$ of \$10^9\$, you should do a single sieve to find all the primes under \$\sqrt {10^9}\$.  There should be 3401 primes under 31623.  In fact, you could even hardcode this list of primes into your program to avoid performing the sieve at runtime.  It should only take 14KB to hardcode that list (7KB if you store them as short).

Optimizing the segmented sieve

Let's take a look at your main loop:

  for (const auto &prime : primes) {
    for (int i = (m / prime) * prime; i <= n; i += prime) {
      if (i >= m && i != prime) {
        is_prime[i - m] = false;
      }
    }
  }

There are several things I notice that are suboptimal:

The loop increments by prime.  You could achieve 2x speeds if you only handled odd numbers and incremented by 2*prime instead.  The only even prime is 2 and you can check for that as a special case outside the sieve.
You have a if (i >= m) check which could be removed if you just started the loop from the right starting value.
You have a if (i != prime) check which could be removed if you just started the loop from the right starting value.
You do a subtraction i-m on every iteration.

So what is the correct starting value?  You were close in your (m / prime) * prime) expression.  The problem is that your expression could result in a value smaller than m.  You should just round up like this:

int start = ((m + prime - 1) / prime) * prime;

This gets rid of the i >= m check.  But also, start should be at least prime * prime, because any multiple of prime less than that will already have been handled by a lower prime.

start = max(start, prime * prime);

This gets rid of the case where you might reach i == prime.  Thirdly, start should be odd, because if you are doing #1 above, you should start at an odd index and increment by an even increment.

if ((start & 1) == 0)
    start += prime;

Lastly, by subtracting m from start and making your loop go until n-m, you can get rid of the subtraction inside the loop.

start -= m;

Rewrite

Here is a rewrite of your whole program using the above ideas:

#include <cmath>
#include <cstdio>
#include <vector>

using namespace std;

#define MAX        1000000000

typedef vector<bool> VB;
typedef vector<int> VI;

// This holds the primes from 3..sqrt(MAX)
VI primes;

// Finds the primes from 3..n and stores them in the global "primes".
static void findPrimes(int n)
{
    int i;
    int sqrtn = sqrt(n);
    VB  is_prime(n+1, true);

    for (i = 3; i <= sqrtn; i += 2) {
        if (is_prime[i]) {
            int increment = i+i;
            primes.push_back(i);
            for (int j = i * i; j <= n; j += increment) {
                is_prime[j] = false;
            }
        }
    }
    for (; i <= n; i += 2) {
        if (is_prime[i])
            primes.push_back(i);
    }
}

// Finds the primes in the range [m..n] and prints them.
void segmented_sieve(int m, int n)
{
    int range = n - m;
    VB is_prime(range + 1, true);

    for (int prime : primes) {
        int increment = prime + prime;
        // Start should be the first multiple of prime >= m, or prime^2,
        // whichever is larger.  Also make sure start is odd.
        int start = max(((m + prime - 1) / prime) * prime, prime * prime);
        if ((start & 1) == 0)
            start += prime;
        // Adjust to range so we don't have to subtract m in the loop.
        start -= m;
        for (int i = start; i <= range; i += increment) {
            is_prime[i] = false;
        }
    }

    if (m <= 2 && n >= 2)
        printf("2\n");
    for (int k = (m & 1) ? 0 : 1; k <= range; k += 2) {
        if (is_prime[k]) {
            printf("%d\n", m + k);
        }
    }
}

int main()
{
    int t;
    scanf("%d", &t);

    findPrimes(sqrt(MAX));
    while (t--) {
        int m, n;
        scanf("%d%d", &m, &n);
        if (m == 1) m++;
        segmented_sieve(m, n);
    }
    return 0;
}


Who am I?

When skimming the code, it's not obvious to a reader what the significance of checking whether a string starts with the letter "c".

if(*whoAmI == "c") {
    ...
} else {
    ...
}

In addition, this construct introduces bugs – what if the user were to type something other than "c" or "s"?

I think you should instead parse the argument once and define an enum to be tested against.

enum running_mode { SERVER, CLIENT };
enum running_mode running_mode;

// ...

if (0 == strcmp(argv[1], "c") {
    running_mode = CLIENT;
} else if (0 == strcmp(argv[1], "s") {
    running_mode = SERVER;
} else {
    printf("Argument must be 'c' or 's'\n");
    exit(1);
}

// ...

if (running_mode == CLIENT) {
    // handle client case
} else {
    // handle server case
}

You should also provide a more helpful message if there are not 2 arguments to the program. "0==Server; 1==client" seems a bit misleading.

Commented out code

I consider leaving commented out lines in your code without explanation a bad practise. Let me quote @nhgrif in this answer:

  Source control should help you keep track of code that used to be there, so there's not a real good excuse to leave it there for any historical reason.

  Arguably, you might want to leave it in if it's something you're frequently uncommenting for some sort of testing purposes, but if that's the case, perhaps leave a comment above the line, something to the effect of:

// Uncomment the following line to ...

Because you use source control, right?

Indentation

The indentation in the posted code is a mess. I don't know if that's a consequence of copy-pasting the code or if it actually looks that way on your machine. To get any kind of grip on your code I had to run it through an auto-indent program first.

If you don't know the common practices, here is a general rule of thumb: whenever there is a {, increase indentation by one, and whenever there is a }, decrease indentation again. Other lines in the code should use the same level of indentation as the previous line.

Complex main

The main function is quite long and complex. You have acknowledged this yourself by leaving the comments "start of server", "end of server" etc in the code. Instead of this, I recommend refactoring the server and client specific code into separate functions. Any common data could then be passed to these functions by main.

Void main

You declare main as returning void, and then use exit(1) to signal an unsuccessful result to the OS. I think you should instead declare int main and use a return statement instead of exit.

Signal handler

The behavior of INThandler is undefined, because only very specific standard library functions can be called from signal handlers (Cppreference).

  If the signal handler is called NOT as a result of abort or raise (in
  other words, the signal handler is asynchronous), the behavior is
  undefined if the signal handler calls any function within the standard
  library, except

  abort
  _Exit
  quick_exit
  signal with the first argument being the number of the signal currently handled (async handler can re-register itself, but not other
  signals).
  atomic functions from stdatomic.h if the atomic arguments are lock-free
  atomic_is_lock_free (with any kind of atomic arguments)

The program might still work on your machine, but is not guaranteed to do so on any box.

On the other hand, you don't need this signal handler at all. When a program terminates on modern operating systems, resources like open files are automatically released by the OS. The only purpose I see the handler serving is printing out "Closing all sockets", which seems a bit useless to me.

Implicit delcarations

You've forgot to include some header files.

unistd.h containing close.
arpa/inet.h conataing inet_ntop and inet_addr.

Global variables

Use of global variables is generally frowned upon. They make programs much harder to read and reason about. Of course they are sometimes required, but in your case they could just as easily be local variables passed around as function parameters.

Type correctness

The type of len should be socklen_t, not int. If not that, at least an unsigned integer type.

Buffer size

You define a macro BUF_SIZE with an arbitrary value (I assume). There's no need to do this as stdio.h already has a macro specifically for this purpose called BUFSIZ. The value of the macro "is chosen on each system so as to make stream I/O efficient" (GNU Manual).

Conclusion

I think this is a great beginner project! Writing network code is always interesting. To summarize most of my points above, code is read more times than written, so think about the reader!


Naming

Your variable names are polyglot, cryptic, and inconsistent.  Don't mix Italian with English — stick with English if you can.  Instead of s1…s3, pick more meaningful names.  Instead of p, q, and k, it would have been better to use p1, p2, and p3 — but again, more meaningful names would be even better.

Function signatures

In modern C, you should mark strings as const if you're not going to write to them.

It is customary to put main() at the end, so that you don't need to declare your functions.

Approach

You aren't writing a '\0' terminator character to out, so your function won't work if the buffer is unclean.

Your solution is not robust to unexpected input, such as extra spaces at the end of s1.

Character-by-character manipulation isn't very readable.  You wouldn't want to write code like this in a larger project.  Instead, make use of the existing library functions for working with strings.  (You have already written #include <string.h>, so why not?)

char *makeNickname(const char *names, const char *nickname, char *out) {
    const char *firstSpace = strchr(names, ' ');
    const char *lastName = firstSpace + strspn(firstSpace, " ");
    sprintf(out, "%.*s (%s) %s", (int)(firstSpace - names), names, nickname, lastName);
    return out;
}

Note that this solution, like yours, doesn't check for buffer overflow.  It would be good practice to also pass the size of the buffer to enable such a check.


My strongest objection is to your use of recursion as a kind of goto:

if input("Play again (y/n)\n") == "y":
    print()
    tic_tac_toe()

I suggest changing the tic_tac_toe() function to play just one game, then calling it in a loop.

You do some similar recursive calls in p1() and p2().

Board layout

Your board layout is

1 2 3
4 5 6
7 8 9

For a better user experience, I suggest flipping it upside-down to mimic a computer number keypad.

I think that the code would be less confusing if the board labels matched the list indices.

Handling two players

The p1() function resembles p2(), and the main loop contains two copies of code that is mostly the same.  check_board() also has some repetition.  The root cause is the need to associate Player 1 with the symbol X and the verbal description "cross", and Player 2 with the symbol O and the verbal description "nought".  The code would be easier to generalize if you just called them "Player X" and "Player O", and I think that the user experience would be enhanced as well.  (You could also generalize the code without such a simplification by using, say, a namedtuple to represent each player.)

p1() and p2() could be simplified by moving the validation into choose_number(), especially if you didn't care to distinguish between the "You can't go there" and "That's not on the board" error messages.

Implementation details

In choose_number(), there is no need for a nested while True.  You also don't need to write continue.
Renaming check_board() to is_game_over() would make its purpose more obvious
win_commbinations contains a misspelling, and would be better as WIN_COMBINATIONS to indicate that it is a constant.  board[a[0]] == board[a[1]] == board[a[2]] is ugly, and would be better expressed as

for a, b, c in WIN_COMBINATIONS:
    if board[a] == board[b] == board[c] …

In check_board(), you used the variable a for two different purposes, which is confusing.  I would just rewrite the second half of the function entirely as

if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
    print("The game ends in a tie\n")
    return True

There is no need for the end variable.  (In general, such flag variables should be eliminated.)

Suggested solution

def tic_tac_toe():
    board = [None] + list(range(1, 10))
    WIN_COMBINATIONS = [
       (1, 2, 3),
       (4, 5, 6),
       (7, 8, 9),
       (1, 4, 7),
       (2, 5, 8),
       (3, 6, 9),
       (1, 5, 9),
       (3, 5, 7),
    ]

    def draw():
        print(board[7], board[8], board[9])
        print(board[4], board[5], board[6])
        print(board[1], board[2], board[3])
        print()

    def choose_number():
        while True:
            try:
                a = int(input())
                if a in board:
                    return a
                else:
                    print("\nInvalid move. Try again")
            except ValueError:
               print("\nThat's not a number. Try again")

    def is_game_over():
        for a, b, c in WIN_COMBINATIONS:
            if board[a] == board[b] == board[c]:
                print("Player {0} wins!\n".format(board[a]))
                print("Congratulations!\n")
                return True
        if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
            print("The game ends in a tie\n")
            return True

    for player in 'XO' * 9:
        draw()
        if is_game_over():
            break
        print("Player {0} pick your move".format(player))
        board[choose_number()] = player
        print()

while True:
    tic_tac_toe()
    if input("Play again (y/n)\n") != "y":
        break


We've had bad experiences in our company for RequireJS. IMO, it has been marketed somewhat wrongly.

RequireJS becoming a script loader - somewhat wrong

True, it does the duties of a script loader. For small apps, this is fine. But when your application begins to grow, as in our case, It's another story. You'll easily end up with a lot of HTTP requests which will choke the static server to the point that you will get script timeout errors. There'll be unnecessary delay in your app due to all the loading and waiting.

RequireJS as a build-tool - better

So what we did was just settle for RequireJS being a build tool. For a dev setup, we allowed it to run as script-loader, a lot of module requests hitting the server. But when it came to deployment, we optimize using the r.js optimizer. This meant grabbing all the needed modules into one machine, let the r.js optimizer run, and end up with one file which you'll use on your page. In addition, we'll be using Almond instead of RequireJS as we don't need the full functionality of RequireJS after it is compiled.

Conclusion

Small scale, it's fine. Large scale, I'd think of something better.


Importing data into PostgreSQL from remote text file using ftplib class

In this line i don't want to write the actual details,i want that to be hidden from my script.How can i do that? ftp = FTP('server.com','user_name','password')

You may want to declare constants, either at the beginning of your file or in a Credentials class that would be used as an enum:

SERVER = 'server.com'
USER_NAME = 'Linu'
PASSWORD = 'CR.SEisGreat'

ftp = FTP(SERVER, USER_NAME, PASSWORD)

You may also want to encrypt your password, with base64 or something alike. Storing passwords in files isn't a good idea anyway, so if you're using this file as a script you're going to call via bash or something alike, I would use a placeholder like argparse that would prompt your password when calling the script:

parser = argparse.ArgumentParser(description='Reading a file from a distant FTP server.')
parser.add_argument('--passwd', dest='password', type=str,
                   help='password required for FTP connection')

  The script downloads the file to my local system and process it as it
  is a local file, Is there anyway too read and process it without
  downloading it to the source server(there might be permission issues
  also)?

I don't know much about FTP manipulation with Python so I'm not sure there is a way to read a file without having to download it.

  If there is no way rather than downloading it to the source, shall I
  able to mention specific path where this file would be downloaded
  rather than the way i have written?

Again, you may place the path into a class constant (or in a separate class):

FILE_PATH='''/path/to/file/'''

  Is there anything which i can do to improve this code?

Imports

import psycopg2
import time
import os

I would edit this to import only the parts you need, e.g.

from psycopg2 import connect, sql
from time import perf_counter

There is no need to import the whole module if you only use a couple of functions, so whenever you can, I'd suggest you only import what you will actually use.

Raising exceptions

try:
    # ...
except:
    print ("Error")

I would raise an exception here, since it's a undesired behaviour:

 try:
    # ...
except Exception as e:
    print ("Error: {}".format(e))

You may want to do the same with your psycopg and FTP errors, I see you catch them but don't read their value. It may provide a more helpful message than the prints, which just indicate you encountered an error but don't tell more about what actually happened.

SQL placeholders

SQL="""DROP TABLE IF EXISTS """+  table + """;CREATE TABLE IF NOT EXISTS """+ table + """
(created_date TEXT, product_sku TEXT, previous_stock TEXT, current_stock TEXT );"""

Should you want to make your code more generic, you could transform the above mentioned statement into:

sql.SQL="""DROP TABLE IF EXISTS {table_name} ; CREATE TABLE IF NOT EXISTS {table_name}
 (created_date TEXT, product_sku TEXT, previous_stock TEXT,
 current_stock TEXT );""".format(
    table_name = sql.Literal(table)
)

That way you may reuse the query on other tables. You may do the same on the table attributes, i.e.

keys = ['created_date', 'product_sku', 'previous_stock', 'current_stock']
sql.SQL("""CREATE TABLE IF NOT EXISTS {} ({});""").format(
    sql.Identifier(table),
    sql.SQL('{} TEXT,').join(map(sql.Identifier, keys))
)

It alleviates the query and makes it more generic and reusable. By the way, I don't think you need to add IF NOT EXISTS after CREATE since you already deleted the table in the first part of your query.


Transform Bitmap object into jagged array of RGB tuple values

By convention, F# function names are camelCase, for example transform2D instead of Transform2D.

Hungarian notation is dead and buried. For example, use bitmap instead of pBitmap.

If ImageSearch is a top-level module, declarations do not have to be indented.

Your for...in expressions can be written without brackets. For example, instead of

for tHeightIndex in [ 0 .. tHeight - 1] do

write

for heightIndex in 0 .. height - 1 do

Similarly, instead of

for tWidthIndex in [tStart .. 3 .. tFinish] do

write

for widthIndex in start .. 3 .. finish do

This is not just a style issue, the different versions actually compile to different IL.

The final expression of a function is its return value, so instead of

let tHeight = ...
let tImageArray = [| ... |]
tImageArray

you can write

let height = ...
[| ... |]

In type annotations, it's conventional to have a space on either side of the :, for example instead of

let Transform2D ( (pArrayWidth:int), (pArray:byte[]) ) =

write

let transform2D (width : int, array : byte[]) =

I can't actually back up this last point. MSDN and FSharp.Core don't seem to stick to one style, even in the same function

let isProperSuperset (x:Set<'T>) (y: Set<'T>) = SetTree.psubset x.Comparer y.Tree x.Tree


Home page (TravelAgency)

Looks correct.

Note that you could (if you want) use this item on every page of your website, not only on the home page.

Typically, you could always use this item for marking up the header of each page. By using its url property, you always link back to the same URL (i.e., your home page’s URL), so consumers can understand that it’s always the same TravelAgency entity.

Product page (MedicalWebPage)

Your use of the properties specialty, aspect, name, description, and image is correct.

author property

The value of the author property needs to be the URL of the author, not the URL of the Schema.org type.

Schema.org expects an Organization/Person as value, so you could make this explicit by using:

  <link itemprop="url" href="HOME PAGE URL" />

If you don’t want to use so "much" markup, you could also simply link directly:

<link itemprop="author" href="HOME PAGE URL" />

However, most sites have a link to the home page anyway (i.e., in the logo or the navigation), so you could reuse this link instead of duplicating it with link.

url property

The value of the url property would have to be the URL of this MedicalWebPage, not the URL of your homepage.

It doesn’t hurt to have it, but it isn’t really needed in the first place (as it’s just the URL of the current document anyway).

You could, if you want, combine this with a possible rel-canonical in your head.

offers property

Using the offers property on MedicalWebPage would mean that you are offering this web page (e.g., for sale), as its definition says (bold emphasis mine):

  An offer to provide this item […]

This is probably not what you want to say, or is it?

Offer

itemOffered property

The itemOffered property expects a Product as value. This is not required (using text, like you do, is allowed), but if you want to go the extra mile, make it a Product item:

  NAME OF TREATMENT

span element can’t have a content attribute

In HTML5/Microdata, only the meta element can have a content attribute, so it’s not allowed on span.

Instead of €, you might want to use:

<meta itemprop="priceCurrency" content="EUR">€

And instead of 600.00:

600.00


If what you want is to call the same function with the same array and obtain random numbers from that array every time, but without them repeating, well, that's almost literally the definition of "shuffle".

Have a look at this answer on stackoverflow. The idea in your case is that you shuffle the array and pick the first (or last) n elements.

That means something like (almost entirely copied from linked answer):

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var arr = [];
for (var i = 10; i <= 20; i++) {
   arr.push(i);
}
shuffle(arr);
console.log(arr.slice(0,3));
console.log(arr.slice(3,6));

The advantage is that you need to randomize only once, no need to loop through the array and generate random numbers every time.

The disadvantage is that if you want different numbers, you'll have to keep track of the index by yourself, because requesting arr.slice(0,3) will always return the same numbers.
But considering that you'd have to keep track of which numbers have already been used anyway, this should not be a problem.

Also, this may actually not be a disadvantage depending on what you use the function for.
(Of course you could shuffle every time, but that would lose any speed benefit of shuffling).

Another approach would be to shuffle once and then having a function that returns the first n numbers but also removes them from the list.
The obvious disadvantage in that case would be that you have to keep a copy of your original array, and when the shuffled array is empty, copy it and shuffle it again.

If you still want to use your approach (which works anyway), at least make sure to use meaningful variable names. In my opinion not is probably the worst possible name for a variable.


Types have to be known at compile time. Unfortunately to be flexable you need to look up arbitory types at runtime for a DB. So either you need to use some form of template-meta programming or you can use a variant type. I would go for something like boost Any object or boost variant this will allow you to return arbitrary types.

I don't think you want to return the result from the DB after creating the Query. You want to return a query object that will allow you to bind things and execute the query at a latter stage. This is because in most DB systems creating the query is relatively expensive.

And when you do execute the query you want to use the concept of the cursor (iterator) to move over the result set rather than generating the full result in one go (as this could potentially be huge).

int main();
{
    Database   db("Bla", "Passowrd", true);
    Query      getName = db.query("SELECT Name,Address,Phone "
                                  "FROM Users Where Age=%d and Sex=%s");

    // Allow user to bind values to the query and execute.
    // As building the query can be expensive. So you want to re-use it.
    Result     age25   = getName.execute(bind() % 25 % "M"));

    // Re-use the Query object for the next query   (Note bind should allow multiple param)
    Result      age31   = getName.execute(bind() % 31 % "F"));

    // Rather than returning all the results from the query in one go
    // Have the result object provide an `input iterator` allowing you to retrieve the
    // the rows as required. That way you do not need to copy out huge objects all in
    // one go. You can scan over the input until you get the bit you want (potentially)
    // only copying selected parts out of the result.

    if (!age25) // convert object to boolean to test for OK
    {           // Like a std::stream object. This way if the query has
                // an error you can quickly an easily test for it.

        std::cout << age25.error() << "\n";
    }
    else
    {
        for(RowIter row = RowIter(age25); row != RowIter(); ++row)
        {                                 //     ^^^^^^^^^  like std::istream_iteator
                                          //                an empty object is end()

            std::cout << db_cast<std::string>(row->get("Name")) << " "
                      << db_cast<std::string>(row->get("Address")) << " "
                      << db_cast<int>(row->get("Phone")) << "\n";
                     //  ^^^^^^^^^^^^
                     //  Convert the object into the correct type
                     //  using a cast like syntax.

        }
    }
}

Also do not limit it to sqlite.
Make it so it is easily expandable to other DB types.

I would go with a prefix Notation on the DB name:

DataBase    db1("sqlite://FileName1", "OptionalPassword", flags);
DataBase    db2("mysql://db@host.bob.com", "Password", flags);
Database    db3("oracle://plop.foo.bar");

Internally you can then use the PIMPL design pattern to abstract the different types of DB. For now you just implement the sqlite version make the others generate an exception.


you can avoid stuffing everything in a one-liner:

private static int mapDoubleToInt(double value, double min, double max)
{
    long intRange = 1L << 32; // ==((long)int.MaxValue - int.MinValue)
    double inputRange = max - min;
    return (int)(intRange * (value - min) / inputRange + int.MinValue);
}

private static double mapIntToDouble(int value, double min, double max)
{
    long intRange = 1L << 32; // ==((long)int.MaxValue - int.MinValue)
    double inputRange = max - min;
    return inputRange * ((double)value - int.MinValue) / intRange + min;
}

After reordering the operations it's now clearer that they are opposites. Especially after extracting the range as variables.


Spring AOP Log4j Logger example, improvement

Use StringBuilder instead of StringBuffer since the latter is synchronized and you're not sharing the instances in a multi-threading manner. So use of StringBuilder would be a bit faster.
Narrow down the scope of retVal. Generally speaking, your variables should be as close to the use places as possible. Note that you can move the retVal declaration and the return statement to the try block entirely.
A matter of style, but I would use final as much as possible.
Concatenate the @Around expression into a single constant if possible and if it's not disallowed by your code convention.
Split your single method into smaller ones. First off, you separate different responsibilities and improve the readability. Note that the message formatting methods return String (why should the call site know what's behind the scenes?). You can shorten the behind-the-scenes object names to simple builder as there are no name conflicts. These methods are declared static, and they use JoinPoint instead of ProceedingJoinPoint just because it's enough to accept an instance of the first class. And getPostMessage is better to accept long and not StopWatch -- what if you would use System.currentTimeMillis()?
StringBuilder is a perfect example of the fluent interface concept, so you might want even use it more (and even discard its variables: see getPostMessage with a single return but multiple chained appends).
Joining a sequence of items using a separator is a trivial problem, and you could eliminate use of deleteCharAt. Just ignore the very first "imaginary" separator and not append it. Or use Guava Joiner.appendTo(StringBuilder,Object[]) if possible (can't recall if there is a Java 8 StringBuilder-friendly collector). Note that appendTo() from the answer is really an utility-candidate method so you might want to reuse it elsewhere if it's justified.
targetClass is introduced, because I don't know if getting the target is cheap (I believe it's extremely cheap, but this is a particular case -- but this is an interface, and what if you mock your JoinPoint to unit-test the logger and don't want the getTarget code behind to happen twice?). However, having a variable named targetClass is a good self-describing hint.
Also, usually, a try/catch block can cover the whole method, thus className can be moved into it safely without changing the semantics (but not logger because it's used in separate blocks).
Static imports may improve readability, so maybe just getLogger(...) instead of Logger.getLogger(...)?
And one more thing that I'm not sure about, and it would require more investigation: StringBuilder can be replaced with string concatenation. At least for simple cases like https://gist.github.com/lyubomyr-shaydariv/ffdc40df722ca489e14364da8a8c4e30 (those two methods produce the same Java byte-code). See more at https://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java .

@Aspect
public class SpringAOPLogger {

    @Around("execution(* com.sample.dao.*.*(..)) || execution(* com.sample.service.*.*(..)) || execution(* com.sample.controller.*.*(..))")
    public Object logMethod(final ProceedingJoinPoint joinPoint)
            throws Throwable {
        final Class<?> targetClass = joinPoint.getTarget().getClass();
        final Logger logger = getLogger(targetClass);
        try {
            final String className = targetClass.getSimpleName();
            logger.debug(getPreMessage(joinPoint, className));
            final StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            final Object retVal = joinPoint.proceed();
            stopWatch.stop();
            logger.debug(getPostMessage(joinPoint, className, stopWatch.getTotalTimeMillis()));
            return retVal;
        } catch ( final Throwable ex ) {
            logger.error(getErrorMessage(ex), ex);
            throw ex;
        }
    }

    private static String getPreMessage(final JoinPoint joinPoint, final String className) {
        final StringBuilder builder = new StringBuilder()
                .append("Entered in ").append(className).append(".")
                .append(joinPoint.getSignature().getName())
                .append("(");
        appendTo(builder, joinPoint);
        return builder
                .append(")")
                .toString();
    }

    private static String getPostMessage(final JoinPoint joinPoint, final String className, final long millis) {
        return new StringBuilder()
                .append("Exit from ").append(className).append(".")
                .append(joinPoint.getSignature().getName())
                .append("(..); Execution time: ")
                .append(millis)
                .append(" ms;")
                .toString();
    }

    private static String getErrorMessage(final Throwable ex) {
        return ex.getMessage();
    }

    private static void appendTo(final StringBuilder builder, final JoinPoint joinPoint) {
        final Object[] args = joinPoint.getArgs();
        for ( int i = 0; i < args.length; i++ ) {
            if ( i != 0 ) {
                builder.append(", ");
            }
            builder.append(args[i]);
        }
    }

}


Functional method for storing a query string as a simple key-value object

For this simple use case, you are correct that you could do all this work in a reduce step saving yourself an additional iteration over the array created by the split() operation.   Now whether this is enough of a performance impact for your expected use cases to move away from the (probably clearer-to-understand) map-reduce pattern is something that perhaps you would need do some testing to decide how you want to approach the problem.

If for example, you ever foresee yourself adding a filter() step, then perhaps keeping separation between map - filter - reduce steps makes sense.

I do think there are some edge cases around your basic query-split approach which might not be handled well here.  For example, what about parameters with array notation (i.e. param[]=foobar)?  You can certialny do plenty of search on the internet to gets lots of ideas on how to approach the basic query string parsing logic.


I do not speak TI-BASIC, so I cannot review the style, coding conventions etc. But there are two possible optimizations:

If a number A is composite then it must have a factor that is less than or
equal to sqrt(A). So you can replace

:While I<A and not(B

with (and I am just guessing the syntax):

:sqrt(A) -> S
:While I<=S and not(B

This  reduces the number of trial divisions substantially  if the input is a prime number.
Check the divisibility by 2 first, and then loop just over the odd numbers
I = 3, 5, 7, .... This saves you from checking

:If I=4
:3->I

in each loop iteration.


ffmpeg batch script for video resizing - improved

Is it intended that date is executed separately for each input, or should all converted files have consistent names (for that use of the script)?  It's certainly worth a comment explaining your choice.

I'm not a fan of the big space in the redirection >     /dev/null - that makes it harder to parse.

This if/else chain looks a little clumsy:

if [ "${rotation}" -eq 0 ] || [ "${rotation}" -eq 180 ]
then
    scaling="-1:720"
elif [ "${rotation}" -eq 90 ] || [ "${rotation}" -eq 270 ]
then
    scaling="720:-1"
else
    fail "-> Unhandled rotation"
    return
fi

When testing a single value against various possibilities, it tends to be neater using case:

case "$rotation" in
    0|180) scaling="-1:720" ;;
    90|270) scaling="720:-1" ;;
    *) fail "-> Unhandled rotation '$rotation'"; return ;;
esac

(I also added extra information in the failure case, that may help diagnose problem input files).


WorkGroup Data Service with JSON / Web based API

Naming Conventions

Private instance fields should be lowercase:

private ObservableCollection<IWorkgroup> groups;

Local variables should also be lowercase:

List<TestSession> test = JsonConvert.DeserializeObject<List<TestSession>>(jsonText1);

Also, where you are doing the same thing with the clients and URIs, you are adding numbers to the second of those variables, e.g. client1. Try to think of something more descriptive, those two clients are serving two different purposes so try something like purposeClient where purpose is replaced by a word for it's purpose. At this point, extracting the functionality out into separate methods is probably a good idea.

Improvements

If you're going to use an async method, then you should await it:

var jsonText = await response.Content.ReadAsStringAsync().GetResults();

Structure

Similarly, given that this variable doesn't look like it needs to be shared amongst methods (unless you haven't included the rest of your class), I'm not really sure why you've made it an instance field and can quite comfortably be declared inside your GetAllWorkGroups() method.

You seem to assign a value to Groups twice in that method, you don't need to do the second one:

groups = groups.OrderByDescending(x => x.Test.Count);

You also seems to double wrap the OrderByDescending clause in brackets which was unnecessary

You seem to be switching between using var and, for example string. A lot of people do switch, using var where the type inferred is obvious and using the type when it is not immediately obvious to make it more readable (this is what I do), but a lot of people will exclusively use var. In terms of style, I'd definitely go one way or the other because currently your switching just seems messy.

I find that object initializers make the code more readable so here:

IWorkgroup group = new Workgroup();
group.GroupState = (int)groupObject["GroupState"].GetNumber();
group.WorkgroupName = groupObject["WorkgroupName"].GetString();
group.WorkgroupSecretary = groupObject["WorkgroupProba"].GetString();
group.ObjectID = groupObject["ObjectID"].GetString();

Can be:

IWorkgroup group = new Workgroup
{
    GroupState = (int)groupObject["GroupState"].GetNumber(),
    WorkgroupName = groupObject["WorkgroupName"].GetString(),
    WorkgroupSecretary = groupObject["WorkgroupProba"].GetString(),
    ObjectID = groupObject["ObjectID"].GetString()
};

After this point, you then start a new using, but from the code it seems that you are in fact finished using your previous client so you can move it around to be more like this:

public async Task<ObservableCollection<IWorkgroup>> GetAllWorkGroups()
{
    var groups = new ObservableCollection<IWorkgroup>();
    JsonArray jsonArray;

    using (var client = new Windows.Web.Http.HttpClient())
    {
        var dataUri = new Uri(WebApiUri + "api/workgroup/");
        var response = await client.GetAsync(dataUri).AsTask();

        var jsonText = await response.Content.ReadAsStringAsync().GetResults();
        jsonArray = JsonArray.Parse(jsonText);
    }

    foreach (var groupValue in jsonArray)
    {
        var groupObject = groupValue.GetObject();
        IWorkgroup group = new Workgroup
        {
            GroupState = (int)groupObject["GroupState"].GetNumber(),
            WorkgroupName = groupObject["WorkgroupName"].GetString(),
            WorkgroupSecretary = groupObject["WorkgroupProba"].GetString(),
            ObjectID = groupObject["ObjectID"].GetString()
        };

        var dataUri = new Uri(WebApiUri + "api/etest/" + group.ObjectID);
        using (var client = new Windows.Web.Http.HttpClient())
        {
            var response = await client.GetAsync(dataUri).AsTask();
            if (response.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
            {
                var jsonText = await response.Content.ReadAsStringAsync().GetResults();
                var test = JsonConvert.DeserializeObject<List<TestSession>>(jsonText);
                group.Test = test;
            }
        }

        if (group.Test.Count > 0)
        {
            groups.Add(group);
        }
    }

    return groups.OrderByDescending(x => x.Test.Count);
}


Determine the number of factors of a large numbers efficiently

Your program actually gives the wrong output for every number. You're forgetting that n is a factor of n! The easy fix is to simply initialize num to 1. Even better to initialize num to 2 and start your loop at i=2. Once you fix that, your program is fine. It's just that you can just do a lot better performance-wise.

Let's start with the general formula. Any number can be expressed as the product of primes raised to some power: \$n = \prod_i p_i^{k_i}\$. The number of factors of \$n\$ in this case is \$\prod_i(1+k_i)\$. So what we need to do is find all the prime factors.

How do we do that? We can actually reduce n as we go. Everytime we find a factor, if we do it right, we can be sure it's prime, so we reduce it as far as possible:

exp = 0;
while (n%i == 0) {
    ++exp;
    n /= i;
}

So if we're doing 80, as an example, we will divide by 2 until we're no longer divisible by 2 (that is, n == 5). All we have to do then is multiply out all the exps:

long numOfFactors(long long n)
{
    long num_factors=1;
    long i;
    long exp;

    for(i=2; i*i<=n; ++i)
    {
        exp=0;
        while (n%i == 0) {
            ++exp;
            n /= i;
        }
        num_factors *= (exp + 1);
    }

    return num_factors * (n > 1 ? 2 : 1);
}

The last check is there because if n>1 at the end, we know it's prime and we haven't counted it yet, so that's another doubling of factors.


Handling game states for an online RPG game

Your variables and functions should either be in camelCase or another naming convention that differentiates them from user-defined types (such as Game here), which are capitalized.
If a parameter is not supposed to be modified, and it's not a primitive type (such as an int), pass it by const-reference in order to avoid an unnecessary copy.

In both AddToLoadQueue() and PushState(), you're passing a raw pointer to an object that will not be modified within the function.  This is also discouraged as you should refrain from passing raw pointers to functions in C++, mostly due to issues such as dangling pointers.  If you still need to pass around pointers, pass smart pointers instead (if you have C++11).

Argv in AddToLoadQueue() should also be passed by const-reference, not by value.
Prefer not to cast the C-way in C++:

Packet = WorldPacket((uint16)MSG_NULL);

Cast the C++ way, with static_cast<> in this case:

Packet = WorldPacket(static_cast<uint16>(MSG_NULL));

See this answer for more information on different types of casts.
It's not exactly clear how StateStack is supposed to be used here.  You use delete on its elements in PopState(), so it's assumed that push() uses new to add new elements, which then means it's a dynamic container.  Either way, this implementation should be provided here.

However, if this is entirely identical to a regular dynamic stack, then just use std::stack.  It will also handle all the memory-management for you (no new and delete necessary).

std::stack<GameState> stateStack;

You'll also no longer need to use a separate top() and pop() when popping a state:

stateStack.pop();

If PopAllStates() is just done in the destructor, then you can just put that code there instead of defining a separate function.

It also calls empty() twice (PopState() also calls empty()), which isn't necessary.  If this is only needed in the destructor, put that code (with just one check) into it:

Game::~Game()
{
    while (!StateStack.empty())
    {
        delete StateStack.top();
        StateStack.pop();
    }
}

If you use std::stack, you'll just need a call to pop(), not top().


Yes. It is perfectly acceptable.

This Stack Overflow post demonstrates that the header is simply used for naming the file.


In Python you usually want to avoid having a recursive solution, because of the maximum recursion depth. Here this will probably not be a problem, because it is 1000 by default (so unless you directory hierarchy is 1000 levels deep, you are fine).

However, I would at least make your functions generators. They have the advantage that you don't need to generate the whole list in one go, but one element at a time. For this, Python 3 has even an additional nice feature, yield from. Note that you will have to call list on the result if you need the whole list at once (which negates any positive effect of using a generator), but that you can directly iterate over the output of a generator

So, your second function would become:

def atDirList(startDir, maxDepth=0, minDepth=0, curDepth=0):
    if curDepth >= minDepth:
        for item in os.listdir(startDir):
            fullItem = os.path.join(startDir, item)
            try:
                if os.path.isfile(fullItem) and curDepth >= minDepth:
                    yield fullItem
                elif os.path.isdir(fullItem) and curDepth + 1 <= maxDepth:
                    yield from atDirList(fullItem, maxDepth, minDepth, curDepth + 1)
            except OSError:
                continue

Note that I also added a try..except block to skip over files for which you don't have enough permissions to check if they are a file or directory.

As an alternative solution, I would propose to use glob, which basically shell expands a string like "/home/graipher/*/*" to a list of all files and directories matching this pattern. This has two caveats, first we still need to filter out the files from the directories (easily achieved with filter) and second, this ignores files which start with a . (hidden files).

import glob
import os

def glob_list(start, max_depth=0, min_depth=0):
    # start out at least `min_depth` levels deep
    current_dir = os.path.join(start, *"*" * min_depth)
    for depth in range(min_depth, max_depth + 1):
        # go one level deeper
        current_dir = os.path.join(current_dir, "*")
        # print(current_dir)
        yield from filter(os.path.isfile, glob.iglob(current_dir))

if __name__ == "__main__":
    for file_name in glob_list(os.path.expanduser("~"), max_depth=2, min_depth=1):
        print(file_name)

Here I changed the parameter names to conform to Python's official style-guide, PEP8, by using lower_case instead of camelCase.

The *"*" * min_depth part is probably slightly complicated, because of all the stars. Let's break it down:

An iterable (like a list or a string) multiplied with an integer is just the iterable repeated n times:

>>> "a" * 3
"aaa"
>>> min_depth = 2
>>> "*" * min_depth
"**"

A * can be used to unpack a tuple into function arguments, like in this function that takes an arbitrary number of parameters:

>>> def f(*args):
...  print(args)
...
>>> f(*"aaa")
('a', 'a', 'a')
>>> f(*"**")
('*', '*')

Putting this together, this just joins the base path with min_depth + 1 levels of stars:

>>> os.path.join("/home/graipher", *"*" * min_depth)
'/home/graipher/*/*'

Possible bug:

After having written this alternative implementation I noticed some strange behavior of your (second, I did not check the first) function. When minDepth is greater than zero, you would not expect any files from the base directory. However, they are still included (note that you need to start with a curDepth = minDepth, otherwise your script will never run).

This is what I would write with the additional constraints of having to return a list and possibly have a simple pattern (simple enough to be expressed with wildcard characters or an additional filter function):

def glob_list(start, max_depth=0, min_depth=0, pattern="*", func=os.path.isfile):
    output = []
    for depth in range(min_depth, max_depth + 1):
        path = os.path.join(start, *("*" * depth), pattern)
        output.extend(filter(func, glob.iglob(path)))
    return output


Guard from the missing and invalid function params

What you have done is generally the approach I take; however, if these guards are used a lot throughout the application, perhaps you could refactor them into separate functions:

deliveryForCategory(code, category, dateStart, dateEnd) {
    VerifyCode(code);
    VerifyCatergory(category);
    VerifyDate(dateStart);
}

Potentially name it something like ThrowErrorIfCodeInvalid(code) so it's super clear what it does.


Here are a few comments on your function:

Firstly, read_line seems a more accurate name, as you read up until the next \n.
Reading 10 chars at a time is an odd. Unless that is part of the requirement I think you should allocate a bigger buffer and read as many chars as fit, extending the buffer each time round the loop by doubling its size (instead of adding 11).
As you have it, your fgets call overwrites the char after the end of the buffer with \0.  You should pass the actual size of the buffer to fgets.
Your fgets/strcat/strlen sequence is inefficient.  You should be reading directly into the target buffer rather than reading and then copying. And the strcat call has to traverse the whole length of the accumulated string to concatenate the new part.

char *p = buf;
size_t len = 0;

while (fgets(p, size - len, stdin) != NULL) {
    len += strlen(p);
    if (buf[len-1] == '\n') {
        buf[len-1] = '\0';
        break;
    }
    ...
}

Your reallocation call leaks memory if it fails to allocate - you need a temporary variable to hold the return value from realloc:

size *= 2;
if ((p = realloc(buf, size)) == NULL) {
    break; // and then return an error if `p == NULL` or `ferror`
}
buf = p;
p += len;

Your loop exits when fgets returns NULL, but you do not check for an error.
You must call ferror to be sure that an error did not occur.
And your looping at the end to find the \n seems wasteful when you have already located the end of line/string in the main  loop.
From the task statement you posted, copying the dynamic string is not required.

Note that reading character at a time is not necessarily a slower solution.  As you are doing it (with all that the copying and string traversal), I would expect a well written character-at-a-time function to be faster.  I encourage you to try both and compare the execution speed (using a very big test file as input).


Deaf grandma doesn't allow me to leave until I say bye three times

There are a few small changes that I would make:

Indent the bodies of if/else blocks.
Moving the bye = 0 line to the top of the else block reduces code duplication, and it'll make your code more clear, because it will read like: 'if the input is "BYE", increase the 'bye' counter, else, reset it to 0'.
Ruby has a += operator: bye += 1 is shorthand for bye = bye + 1.
The name bye isn't very accurate, something like bye_shouts_in_a_row is probably better. Picking accurate, meaningful names is often difficult, but it can make code (much) easier to understand, and that makes working with it easier as well.

Applying these gives the following result:

puts "say hi to grandma"

bye_shouts_in_a_row = 0

while bye_shouts_in_a_row < 3 do
  input = gets.chomp

  if input == "BYE"
    bye_shouts_in_a_row += 1
    puts "HEH?!"
  else
    bye_shouts_in_a_row = 0
    if input == input.upcase
      puts "NO, NOT SINCE " + rand(1930..1950).to_s + "!"
    else
      puts "HUH?! SPEAK UP SONNY!"
    end
  end
end

puts "EH?! OH, BYE DEAR!"


I'm practicing turning for loops into recursive functions. what do you think?

but I wonder if it's okay there's no "return" line under "else:"

Yes, that's OK. You don't need to return anything from your function if you don't want to. In fact, in the interest of consistency, you may as well remove the thing returned in the if block too:

def printElement(inputlist):
        newlist=inputlist
        if len(newlist)==0:
                return
        else:
                removedElement=newlist[len(inputlist)-1]
                newlist=newlist[:len(inputlist)-1]
                Element=printElement(newlist)
                print(removedElement)

collection = ['hey', 5, 'd']

printElement(collection)

  Is it better code with or without the newlist?

Assigning new things to inputlist won't modify it outside of the function, so there's no harm in doing so. May as well get rid of newlist.

def printElement(inputlist):
        if len(inputlist)==0:
                return
        else:
                removedElement=inputlist[len(inputlist)-1]
                inputlist=inputlist[:len(inputlist)-1]
                Element=printElement(inputlist)
                print(removedElement)

collection = ['hey', 5, 'd']

printElement(collection)

you don't use Element after assigning it, so you may as well not assign it at all.

def printElement(inputlist):
        if len(inputlist)==0:
                return
        else:
                removedElement=inputlist[len(inputlist)-1]
                inputlist=inputlist[:len(inputlist)-1]
                printElement(inputlist)
                print(removedElement)

collection = ['hey', 5, 'd']

printElement(collection)

You don't really need to modify inputlist, since you only use it once after modifying it. Just stick that expression straight into the printElement call. And now that inputlist is never modified, you can get rid of removedElement too, and just inline its expression in the print function.

def printElement(inputlist):
        if len(inputlist)==0:
                return
        else:
                printElement(inputlist[:len(inputlist)-1])
                print(inputlist[len(inputlist)-1])

collection = ['hey', 5, 'd']

printElement(collection)

Fun fact: for any list x, x[len(x)-1] can be shortened to x[-1]. Same with x[:len(x)-1] to x[:-1].

def printElement(inputlist):
        if len(inputlist)==0:
                return
        else:
                printElement(inputlist[:-1])
                print(inputlist[-1])

collection = ['hey', 5, 'd']

printElement(collection)

Since the first block unconditionally returns, you could remove the else and just put that code at the function level, without changing the code's behavior. Some people find this less easy to read. Personally, I like my code to have the least amount of indentation possible.

def printElement(inputlist):
        if len(inputlist)==0:
                return
        printElement(inputlist[:-1])
        print(inputlist[-1])

collection = ['hey', 5, 'd']

printElement(collection)

That's about as compact as you can get, with a recursive solution. You should probably just stick with the iterative version, for a few reasons:

Fewer lines
More easily understood
Doesn't raise a "maximum recursion depth exceeded" exception on lists with 200+ elements


updateMapPF :: (Ord k, Num a) => k -> a -> Map k a -> Map k a
updateMapPF = Map.insertWith (+)

λ> updateMapPF 1 1 $ Map.singleton 1 100
fromList [(1,101)]
λ> updateMapPF 2 1 $ Map.singleton 1 100
fromList [(1,100),(2,1)]
λ> updateMapPF 1 33 $ Map.singleton 1 100
fromList [(1,133)]

Process:

Notice the use of Map.insert

Notice that you are mapping (+) over the possibility of having or not having a value

Notice that Data.Map has a function for applying functions to values, called Data.Map.insertWith. It's extremely common for collections to have a helper function for "insert data with a helper function / default value"

Notice the shared structure of the types of your function and insertWith

insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a

updateMap  :: (Ord k, Num v) =>         k -> v -> Map k v -> Map k v

Realize that applying (+) to insertWith will make the types identical

λ> :t insertWith

insertWith
  :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a

λ> :t insertWith (+)

insertWith (+) :: (Ord k, Num a) => k -> a -> Map k a -> Map k a

Validate assumptions with specific examples, more rigor is available with the use of QuickCheck.

λ> updateMapPF 1 1 $ Map.singleton 1 100
fromList [(1,101)]

λ> updateMapPF 2 1 $ Map.singleton 1 100
fromList [(1,100),(2,1)]

λ> updateMapPF 1 33 $ Map.singleton 1 100
fromList [(1,133)]

This is a practically golden opportunity to demonstrate how eta reduction can simplify code and kill off redundant logic.


Circular doubly linked list in JavaScript

the main observation I have is that if you know the length, and you have the tail and head, then you should use that in getItem(index) (meaning that if you want the 8th element out of 10, you should start from the head and go down, 2 operations instead of 8)

Other than that:

Contains can return a string, a number, or a boolean. That is bad design. In my mind it should return only a boolean. If you wanted to return the index, it should have been called indexOf
The shortcuts you take in contains are probably not worth the code, by that I mean that unless you know that more often than not the target value is in the first or last node, I would not code exceptions for those cases.
It is not intuitive that the caller must first add a node before turning the list into a circular one. Not to mention that makeCircular fails quietly when it does not make an empty list circular
You should probably check _isCircular in removeAt(0), it seems as if you assume the list is circular now.

Personally, I would make the list always circular or never circular and optimize the code accordingly instead of checking this property and coding accordingly in 1 list.


Sharing data with another thread using lock_guard

Yes, that all looks correct to me!

You don't use anything from <unistd.h> (non-standard) or <initializer_list> (obscure), so I recommend removing those includes.

You sigil the mutex_ data member with an underscore, but you don't sigil the v member. I recommend being consistent:

std::mutex mutex_;
std::vector<int> v_;

Personally I would spell the member's name mtx_, but that's just a personal habit; I don't know if that naming convention is widespread. (cv_ for a condition variable certainly is, though!)

Consider that your Check and dump methods don't need to mutate the object, so they should be declared const. This means that your mutex_ data member will need to be declared mutable so that you can still lock and unlock it inside your const member functions.

Also, consider picking a capitalization rule and sticking to it. Why Check and Update but dump (not Dump)?

Check's parameter x is marked const but that marking serves no purpose: eliminate it. (Const is a contract.)

for (int i = 0; i < v.size(); i++) {
    if (!g_c.Check(v[i])){
        std::cout <<  v[i] << " ";
    }
}

This could be rewritten more concisely as

for (int vi : v) {
    if (!g_c.Check(vi)) {
        std::cout << vi << " ";
    }
}

Your multithreading stuff all looks great!


Improving rendering performance of 2D Tile Game

I'm not sure if these would be optimized out by the compiler but

Tile.TILESIZE * SCALE
Tile.TILESIZE * Game.SCALE

are done more than once, why not just keep them as variables and...

for (int y = startY; y < finishY; y++) {
 for (int x = startX; x < finishX; x++) {
   map.tile.get((y*map.getMapWidth())+x).render(g);

...why do a multiplication for every y? you could just have a variable and increment it

int yLoc = startY * map.getWidth();
for (int y = startY; y < finishY; y++) {
 for (int x = startX; x < finishX; x++) {
   map.tile.get(yLoc+x).render(g);
 }
 yLoc += map.getMapWidth();
}

then you only need to do one multiplication and one addition for each y step instead of a multiplication for every y


I don't know if this is the complete script, but the absence of use strict; use warnings is pretty noticeable. Always use these as a basic safety net, no matter how small or simple your program.

Your usage of the regex /(.*)\|(.*)\|(.*)/ can be improved in some ways:

Don't use a regex to extract the data. Instead: my @cols = split /[|]/, $_, 3;. This really is the correct way to go, the following points however deal with normal regex usage.
Some guides recommend putting special characters into a character class [|] instead of escaping them \|. It's my experience that this makes complicated regexes easier to read.
Immediately after matching, assign the values of the captures to permanent variables. Otherwise, they could be modified by a subroutine you call – the next match can clear those values. Note also that ways exist to booby trap such an innocent-looking operation like incrementing an integer to clear the last match.

So we either write code such as:

if (/(.*)[|](.*)[|](.*)/) {
  my @fields = ($1, $2, $3);
  ...
}

or we don't use the capture variables at all, and use the regex in list context instead:

if (my @fields = /(.*)[|](.*)[|](.*)/) { ... }

Technically, this isn't absolutely equivalent (e.g. in case you aren't using any captures, or if some captures are conditional, or …), but it's far better style.

If course, you'd assign to a list of names rather than an array:

my ($name_a, $name_b, $text) = ...

The substitution s/\s+//g might be considered slightly silly, as it's equivalent to s/\s//g. The former variant has the advantage of less substitution operations, so it might actually be preferable. But why are you sanitizing the $outname rather than the parts of which it's made up? Note that you can apply a substitution to multiple variables like

 s/\s+//g for $x, $y;

If you don't want to remove all space in those strings (remember that most filesystems can deal with spaces in filenames all right) but only at the start or beginning of the string, you might want to split with a different separator instead:

split /\s*[|]\s*/, ...

The expression "$1_$2_$count.txt" does not contain a bug, but this is accidental. For example, "$foo_$bar" is equivalent to $foo_ . $bar – underscores can be part of variable names, but variables can't start with numbers, so the problem isn't visible here (variable names can consist solely of numbers, and all such variables are reserved for capture groups).

As a fix, use curly braces to delimit the variable names: "${1}_${2}_$count.txt", or use sprintf:

sprintf '%s_%s_%d.txt', $1, $2, $count

The line my $outfile = new IO::File("> $outname"); is a big no-no for two reasons:

Don't use the “indirect object notation” method $object @arglist. Instead use $object->method(@arglist). The former variant may look nicer, but is often ambiguous, has rather confusing precedence, and widely considered to be a syntactic mistake.

If you need help to get rid of that habit, you may enjoy the no indirect pragma.
What you're doing is basically open my $outfile, "> $outname". Use the three-argument form of open:

open my $outfile, ">", $outname

or in the object-oriented wrapper: IO::File->new($outname, '>').

The next problem here is that you aren't doing any error handling! Check the return value of the constructor to assert that you could actually open the file. Well, calling a method on an undefined value will die, but checking manually allows you to output a sensible error message.

The $outfile->print("$text") would usually be written print { $outfile } $text. For one thing, the object-oriented interface to file handles is used very rarely. You can use the normal interface directly. Also, you are unnecessarily stringifying the $text. If it isn't already a string, that will be managed by print. Note that explicit stringification creates a copy of that value, something which you would usually (but not always) want to avoid.

Then, you are using print, not say. This means (together with the fact that in a regex, . does not match newlines), that you won't end your output to the file with a newline. This is probably an oversight.

Another aspect that just came to my mind is that your input file could contain slashes, allowing a filename like /you/were/pwned/_key2_1234.txt to be created (assuming the path already exists). Let's put in a bit of validation.

The script now looks like:

use strict;
use warnings;
use autodie;  # easier than explicit, manual error handling
use feature qw/say/; # say is like print, but appends newline

my $count = 0;
while (my $line = <>) {
    chomp $line;
    my ($name_a, $name_b, $text) = split /[|]/, $line, 3
      or next;
    for ($name_a, $name_b) {
        s/\s+//g;
        die qq(The first two columns in "$line" may not contain slashes) if m[/];
    }
    my $filename = sprintf '%s_%s_%d.txt', $name_a, $name_b, ++$count;
    open my $fh, ">", $filename;
    say { $fh } $text;
}

How did this solve your problems?

Use sprintf to format a string with a variable you want to increment at the same time
Assigning captures to variables is a best practice, and should always be done.

As 200_success mentioned, it is rather suspect that you are using a command-line tool to interface with a database. Perl has the excellent DBI modules which provides a common frontend for various SQL databases. The docs have some simple examples which should get you rapidly started. Using such a module is safer (less escaping levels) and faster (no extra process, no tempfiles, prepared statements, …). Have fun exploring all the great DBI features!


Not sure about its efficiency or whether or not it improves your algorithm, but since you want to use streams, this would be an option:

public static void main(String[] args) {
        String sentence = "ala ma kota, kot koduje w Javie kota .kota";
        String sanitizedSentence = sentence.replaceAll("[^A-Za-z ]", "").toLowerCase();
        String[] words = sanitizedSentence.split(" ");
        Map<String,List<String>> result = sanitizedSentence
            .chars()
            .filter(Character::isAlphabetic)
            .distinct()
            .sorted()
            .mapToObj(c->(char)c)
            .map(Object::toString)
            .collect(Collectors.toMap(
                Function.identity(),
                c->Stream.of(words).distinct().filter(word -> word.contains(c)).sorted().collect(Collectors.toList()),
                (a,b)->a,
                LinkedHashMap::new // <- to ensure they are shown in order when printing
            ));
        System.out.println(result);
    }


Array initialization inside function to be called repeatedly

In your function myFunction, you are initializing the vectors arrayIn* with values that depend on all the input parameters a, b, c, d, so it is unclear why you claim that you are needlessly "reinitializing" them at each call. If the function is true to its name, as it should, one would assume that the input parameters would change from call to call, in which case recomputing arrayIn* is not optional.
If, on the other hand, the parameters a, b, c, d are indeed invariant from call to call, but the result of the function changes nonetheless due to some hidden dependencies, then you should:

make the dependencies explicit ("despaghettify" your code)
initialize arrayIn* separately from the function call, e.g., through a call to an init subroutine.

For example:
MODULE myFunctionCollection

  USE bigFatPackage
  IMPLICIT NONE
  private

  DOUBLE COMPLEX :: arrayIn1(7), arrayIn2(7), arrayIn3(7)
  public :: myFunction

CONTAINS

  subroutine myInit(a,b,c,d)
    DOUBLE COMPLEX, INTENT(IN) :: a,b,c,d
    arrayIn1(1:7) = (/a, a+b, c, c+d, a+d, c+d, d**2/)
    arrayIn2(1:7) = (/a**2, a-b, c, c-d, a-d, dcmplx(0d0,0d0), d**2/)
    arrayIn3(1:7) = (/a**2, (a+b)**2, c, c, c, dcmplx(0d0,0d0),dcmplx(0d0,0d0)/)
  end subroutine myInit

  DOUBLE COMPLEX FUNCTION myFunction( FormerlyHiddenParameter )
    DOUBLE COMPLEX, INTENT(IN) :: FormerlyHiddenParameter
    CALL bigFatSubroutine(arrayOut1, arrayIn1, 7, 7, FormerlyHiddenParameter )
    CALL bigFatSubroutine(arrayOut2, arrayIn2, 7, 7, FormerlyHiddenParameter )
    CALL bigFatSubroutine(arrayOut3, arrayIn3, 7, 7, FormerlyHiddenParameter )
    myFunction = arrayOut1(6) + 2d0*arrayOut2(7) + (1/2d0)*arrayOut3(2) + !... more
  END FUNCTION myFunction

end MODULE myFunctionCollection

Finally, the operations that you are trying not to repeat are computationally very cheap, and it is unclear if you save much time, compared to the time required to execute bigFatSubroutine [sic!]. Chances are that the speed up would be negligible. To identify the real bottlenecks in your code, you should measure the duration of its parts. The rest of the code should be improved for readability, maintainability, extensibility, usability, etc. etc. Any change that increases complexity with no real gain in efficiency should be avoided.
PS: For readers not familiar with the simple syntax of modern Fortran, I suggest the following quick modern Fortran tutorial.


The actions I'm wondering about are members, add_student, and remove_student. They work just fine, but they aren't RESTful [...]

True, they're not part the usual CRUD actions that can be expressed with HTTP verbs. But then neither are the default new or edit actions, so it's not like going beyond CRUD is automatically illegal.

Even so, associations do always present a bit of challenge. Are you adding the student to the class, or the class to the student?

However, in this case it appears that you already have a join model: ClassroomMembership. So going back to the CRUD actions, consider what you're creating when you call add_student: A membership.

So what you might want to do is simply make a ClassroomMembershipsController, since that's the resource you're manipulating. Said controller can then have the usual RESTful CRUD actions, keeping StudentsController or ClassroomController pretty clean.

This is just an idea, though. Again, if it's simpler to keep your actions on the ClassroomController then do that. But conceptually what you're doing is manipulating the association model.


Create a binary search tree from a sorted array (increasing order)

Space and indentation

Your indentation and use of spaces is terrible. This document may help you improve your Java coding style.

Possible overflow

You solution may cause overflow and unexpected results for big enough inputs in this line:

int mid = (start + end) / 2;

changing it to this will solve the problem:

int mid = start + (end - start) / 2;

Also returning null early looks cleaner IMO

public static Node getBST(int[] sortedArray, int start, int end) {
    if(start > end) {
        return null;
    }
    int mid = start + (end - start) / 2;
    Node root = new Node(sortedArray[mid]);
    root.left = getBST(sortedArray, start, mid - 1);
    root.right = getBST(sortedArray, mid + 1, end);
    return root;
}


Build object with different input, using super-class and sub-class style, Python 3

As you yourself have noted, the inheritance isn't benefiting you at all. Just write one class.

Passing meta as a dict is unidiomatic. Use **kwargs or parameters with defaults instead.

Consider dropping the get_… prefix.

Also consider passing the formula as code (e.g. a lambda) rather than referencing a module by name.

from script.interpolate import interp1d
from importlib import import_module

class Air:
    def __init__(self, city, **kwargs):
        self.city = city
        self.temperature = (
            lambda time: kwargs['temperature'] if 'temperature' in kwargs else
            interp1d(kwargs['times'], kwargs['temperatures']) if 'times' in kwargs else
            import_module(kwargs['file_of_formula'] + '.my_function') if 'file_of_formula' in kwargs else
            kwargs['formula']
        )


Your code is essentially fine, but stylistically, I would nitpick a few of your patterns.
Merging the declaration with the assignment of variables
You declare (almost) all of your variables at the start of your method, and then assign them later.  In general, it's better to declare the variable as late as possible, as it makes it more clear when the variable is actually relevant.  (of course, this is a matter of opinion)  Furthermore, it makes the code more concise with no sacrifice in readability, which makes it easier to reason about the code later.
Standard C# naming conventions
For variables in C#, the convention is camcelCasing.  Yet all of your variables are strictly lowercase even when they clearly represent multiple words.  For example, stepby ought to be stepBy, etc.
Using the built-in keywords when applicable
When using static methods on the int primitive, prefer to use the reserved word. Instead of:
Int32.Parse(xyvals[1]);

Prefer:
int.Parse(xyvals[1]);

If, for the sake of discussion, you prefer Int32, then be consistent and avoid using int to declare your variables.  It makes it more clear when you reference the same type consistently in your code.
Use string interpolation if using C# 6
String interpolation is a new feature in C# 6 and in general I would recommend you prefer it to string concatenation (there are performance caveats, but you should focus on that only when that performance becomes an issue over readability).  Instead of:
Parser.Parse("y =" + yval.ToString()).Execute();

Use string interpolation:
Parser.Parse($"y = {yval}").Execute();

The code becomes more concise, and (I believe) a little easier to read.  Also, the .ToString() is unnecessary as that call will be performed implicitly if the type of the variable is not already a string. (as a side-note, for some reason you format x = ... differently than y =... -- it should probably be consistent.)

I admit a lot of this guidance is somewhat subjective, but I hope you find it helpful. :)


Do use descriptive name for the variables and parameters, all those n, temp, newNode do not tell anything.

Reversing the list using recursion should not rely on 'external' variables as you do with Node n = null;. Given that linked list after reversal should have the last element at its head, I would suggest to pass it through the recursive chain hierarchy as a return value.

Having a loop while (TempNode.nextNode != null) makes recursion useless, as you walk through the list via loops instead of recursion. Try to come up with the approach where you do not need loops to get the head of the resulting linked list.


Determine if a std::string has all of the same character

You could simply use find_first_not_of

bool string_has_all_of_the_same_chars(const std::string& s) {
    return s.find_first_not_of(s[0]) == std::string::npos;
}

Update:

This works only, when the string is not empty. A complete version would also test empty

bool string_has_all_of_the_same_chars(const std::string& s) {
    return s.empty() || s.find_first_not_of(s[0]) == std::string::npos;
}

Instead of s[0], one could also use s.front() or *s.begin().