Reducing nested if statements I have a set of rules as follows:

Product One:

If either part is acceptable, update both parts

Product Two:

If either part is acceptable, and one age is > 55, update both parts
If either part is acceptable, and neither age is > 55, then update whichever part needs updating (or both)

I know it's not the most nested if statements you'll see, but it feels like I'm repeating code unnecessary and there should be a simpler version of what I've attempted.

The Code:

 if (this.isAcceptablePartOne || this.isAcceptablePartTwo) {
    if (this.productName.equals(PRODUCT_ONE)) {
        updatePartOne();
        updatePartTwo();
    }
    if (this.productName.equals(PRODUCT_TWO)) {
        if (Math.max(this.ageLifeOne, this.ageLifeTwo) > 55) {
            updatePartOne();
            updatePartTwo();
        } else {
            if (this.isAcceptablePartOne) {
                updatePartOne();
            }
            if (this.isAcceptablePartTwo) {
                updatePartTwo();
            }
        }
     }
 }

From the requirements

  I have a set of rules as follows:

  Product One:

  If either part is acceptable, update both parts

  Product Two:

  If either part is acceptable, and one age is > 55, update both parts

  If either part is acceptable, and neither age is > 55, then update
  whichever part needs updating (or both)

Follows the next, almost literal, straightforward implementation:

Straightforward implementation

So, you could implement this using two Checkers, a Product1Checker and a Product2Checker.

if (this.productName.equals(PRODUCT_ONE))
{
    new Product1Checker().check(this);
}
else if (this.productName.equals(PRODUCT_TWO))
{
    new Product2Checker().check(this);
}

Like this:

class Product1Checker
{

    public check (Product product)
    {
         if (product.isAcceptablePartOne || product.isAcceptablePartTwo)
         {
               product.updatePartOne();
               product.updatePartTwo();
         }
    }
}

Alternative approach

You could have the Checkers implement a ProductChecker interface. Also, each ProductChecker can have a boolean method indicating if this checker applies to a product. Then you can just add all the checkers to a Set, check if they are applicable, and if so, run them on the product

interface ProductChecker
{
    boolean check     (Product p);
    boolean appliesTo (Product p);
}

Set<ProductChecker> checkers = new HashSet<ProductChecker>();
checkers.add(new Product1Checker());
checkers.add(new Product2Checker());

for (ProductChecker checker: checkers)
{
      if (checker.appliesTo(this))
      {
          checker.check(this));
      }
}


How to write this code without using 11 if-statements? if (progressBar1.Value == 1) { progressLabel.Text = "1%"; }
if (progressBar1.Value == 10) { progressLabel.Text = "10%"; }
if (progressBar1.Value == 20) { progressLabel.Text = "20%"; }
if (progressBar1.Value == 30) { progressLabel.Text = "30%"; }
if (progressBar1.Value == 40) { progressLabel.Text = "40%"; }
if (progressBar1.Value == 50) { progressLabel.Text = "50%"; }
if (progressBar1.Value == 60) { progressLabel.Text = "60%"; }
if (progressBar1.Value == 70) { progressLabel.Text = "70%"; }
if (progressBar1.Value == 80) { progressLabel.Text = "80%"; }
if (progressBar1.Value == 90) { progressLabel.Text = "90%"; }
if (progressBar1.Value == 100) { progressLabel.Text = "100%"; }

Why can't you do:

progressLabel.Text = string.Format("{0}%", progressBar1.Value)

As @MNZ pointed out I potentially didn't answer the question exactly how the OP asked.  So here's a slightly modified alternative option:

progressLabel.Text = FormatProgress(progressBar1.Value, progressLabel.Text)

private string FormatProgress(int currentProgress, string progressDisplayed)
{
    if (currentProgress < 0 || currentProgress > 100)
        throw new ArgumentOutOfRangeException("Current progress is not in a valid percentage range of 0 to 100");

    if (currentProgress == 1)
        return FormatProgress(currentProgress);

    return currentProgress % 10 == 0 ?
              FormatProgress(currentProgress) :
              progressDisplayed;
}

private string FormatProgress(int progress)
{
    return string.Format("{0}%", progress);
}

And a unit test to confirm:

[TestMethod]
public void Test()
{
    Assert.AreEqual("1%", FormatProgress(1, "0%"));
    Assert.AreEqual("0%", FormatProgress(0, "5%"));
    Assert.AreEqual("10%", FormatProgress(10, "6%"));
    Assert.AreEqual("80%", FormatProgress(85, "80%"));
    Assert.AreEqual("100%", FormatProgress(100, "90%"));
    Assert.AreNotEqual("75%", FormatProgress(75, "70%"));
}


Partition Equal Subset Sum Challenge LeetCode I solved this problem in LeetCode.

  Given a non-empty array containing only positive integers, find if the array can
  be partitioned into two subsets such that the sum of elements in both
  subsets is equal.

  Note: Each of the array element will not exceed 100. The array size will not exceed 200.

Example 1:

  Input: [1, 5, 11, 5]

  Output: true

  Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

  Input: [1, 2, 3, 5]

  Output: false

  Explanation: The array cannot be partitioned into equal sum subsets.

class Solution {
public:
   bool canPartition(vector<int>& nums) {
        int sum = 0;
        for(auto it = nums.begin(); it != nums.end(); ++it)
        {
            sum += (*it);
        }

        if((sum % 2 != 0) || nums.size() <= 1)
        {
            return false;
        }

        vector < vector < bool > > isValid((sum /2) + 1, vector < bool > (nums.size() + 1, false));

        for(int i = 0; i <= nums.size(); ++i)
        {
            isValid[0][i] = true;
        }

        for(int row = 1; row <= (sum/2); ++row)
        {
            for(int col=1; col<= nums.size(); ++col)
            {
                if(row >= nums[col - 1])
                {
                    isValid[row][col] = isValid[row][col -1] || isValid[row - nums[col - 1]][col-1];
                }
                else
                {
                    isValid[row][col] = isValid[row][col -1];
                }
            }
        }
        return isValid[sum/2][nums.size()];
    }
};

The approach was a pretty straightforward DP implementation which is O(sum * n) in terms of space and time complexity.

My solution took about 1382 ms to execute all the 1183 test cases while I saw solutions which executed in about 200 ms in the same language.

As far as I know there isn't a greedy solution to this problem, only approximations algorithm exist for this.

Can you suggest if there exists a solution with better time complexity for this problem or if my implementation has some redundant initialization or iterations which slow it down.

No need for full matrix
Although your dynamic programming solution works, you are using a matrix of size [sum/2][n] when you only need to allocate a single vector of size [sum/2].  Not only are you using more memory than necessary, but this could also affect performance because of caching.
Use a quick return
Your solution runs the full double loop to completion before determining whether the answer is possible.  It is possible to create a solution that returns as soon as it finds a valid solution.  This could potentially cut down on the time by a lot for inputs that have solutions.
Additionally, I found that sorting the inputs and looping through them from largest to smallest works best in conjunction with the quick return.
Sample rewrite
Here is how I would write the program, using only a single dimensional vector for the DP part, sorting the inputs, and allowing for a quick return:
#include <iostream>
#include <vector>
#include <algorithm>

int main(void)
{
    int n;
    int sum = 0;

    // Read in numbers.
    std::cin >> n;
    std::vector<int> nums(n);
    for (int i=0; i<n; i++) {
        int num;
        std::cin >> num;
        nums[i] = num;
        sum    += num;
    }

    // Quick check to see if sum is even.
    if (sum & 1) {
        std::cout << "false" << std::endl;
        return 0;
    }
    // Cut sum in half.  Sum is now the target to reach.
    sum >>= 1;

    // Sort numbers so we can use the largest ones first.
    sort(nums.begin(), nums.end());

    // Iterate through each number from largest to smallest, updating the
    // possible array and trying to find out if [sum] is possible.
    std::vector<bool> possible(sum);
    possible[0] = true;
    for (int i=n-1; i>=0; i--) {
        int val = nums[i];
        // Quick return if we find we can reach [sum].
        if (sum - val >= 0 && possible[sum - val]) {
            std::cout << "true" << std::endl;
            return 0;
        }
        for (int j=sum-val-1; j >= 0; j--) {
            if (possible[j])
                possible[j + val] = true;
        }
    }

    std::cout << "false" << std::endl;
    return 0;
}


Optional Consumer for ifNotPresent As Optional have only ifPresent and not have another function to be run in false case so I did the below class for that, please check it and give me your feedback:

public class OptionalConsumer<T> {
private Optional<T> optional;

private OptionalConsumer(Optional<T> optional) {
    this.optional = optional;
}

public static <T> OptionalConsumer<T> of(Optional<T> optional) {
    return new OptionalConsumer<>(optional);
}

public OptionalConsumer<T> ifPresent(Consumer<T> c) {
    optional.ifPresent(c);
    return this;
}

public OptionalConsumer<T> ifNotPresent(Runnable r) {
    if (!optional.isPresent())
        r.run();
    return this;
}

}
Then :

Optional<Any> o = Optional.of(...);
OptionalConsumer.of(o).ifPresent(s ->System.out.println("isPresent "+s))
        .ifNotPresent(() -> System.out.println("! isPresent"));

Two things:

Your class only provides a if-else statement, really. If it would also provide all the features in the existing java.util.Optional, it would have been slightly more useful.
private Optional<T> optional; should definitely be marked with final

Okay then, three things:

Your factory method takes an existing Optional<T>, but you don't provide a getter or anything for the Optional<T>, which means that you could also provide an ordinary OptionalConsumer<T> ofNullable(T value)


Choice Decision Maker (Random string from ArrayList) I'm learning about inheritance and polymorphism in my CS class and thought it'd be a good idea to find something I could apply myself to. I have a lot of ideas, and sometimes there's things I want to do and things I don't want to do. Why not leave the decision-making up to Java?

I'm looking for feedback to make my code better: whether it's something I could do with readability or inheritance, or even data structure wise. Or if there's bugs that'd be nice to know too :)

There are multiple classes extending MakeChoice, I just didn't put them here.

import java.util.*;

public class MakeChoice {

    // main
    public static void main(String[] args) {
        makeChoice makerShareChoice = new makeChoiceMakerShare();
        System.out.println(makerShareChoice);
    }

    public static int getChoiceForArrayList(int size) {
        int choice = generateRandomIntRange(0, size - 1);
        return choice;
    }

    public static int generateRandomIntRange(int min, int max) {
        int range = (max - min) + 1;
        int random = (int) (Math.random() * range + min);
        return random;
    }

}

import java.util.*;

public class MakeChoiceMakerShare extends makeChoice {
    private static ArrayList<String> choices = new ArrayList<String>();

    public makeChoiceMakerShare() {
        super();
        choices.add("acrylic LED");
        choices.add("MESA EduPi");
        choices.add("Collage of whiteboard wall");
        choices.add("sponge mitts");
        choices.add("hooks in closet");
        choices.add("10 x 10 LED Matrix");
        choices.add("What should I make? CoMotion addition to matrix");
        choices.add("What should I do this week? Screen");
        choices.add("Lasercraft belt + UW belt buckle + Wallet");
    }

    public String toString() {
        return "Your choice for this week in " + this.getClass() + " is: " + choices.get(getChoiceForArrayList(choices.size()));
    }
}

-For starters, I'm not sure why you needed inheritance for this in the first place, as opposed to passing your choices array into your init function. I'm assuming just to get practice with inheritance?

-I'd move your toString function to your base class if this is functionality you plan on using in most of the children classes. I'd also rename this function to avoid common keywords and to be more descriptive--something like printResult might make more sense, unless your intent is to overload the built-in toString function.


Generation of Prime Numbers I have created this prime number generator. I want it to be as fast as possible, but I am wondering if there is a faster way (there must be).

#include <stdio.h>
#include <stdbool.h>
#include <limits.h>

bool is_prime(const unsigned long long);

int
main(
    void)
{
    puts("2\n3");

    for (unsigned long long n = 5; n < ULLONG_MAX; n+=2) {
        if (is_prime(n)) {
            printf("%llu\n", n);
        }
    }
}

bool
is_prime(
    const unsigned long long n)
{
    if (n < 4) {
        return n > 1;
    } else if (n % 2 == 0 || n % 3 == 0) {
        return false;
    } else {
        for (unsigned long i = 5; i * i <= n; i += 6) {
            if (n % i == 0 || n % (i + 2) == 0) {
                return false;
            }
        }

        return true;
    }
}

Possible slow areas:

usage of printf
usage of bool instead of int (not sure)

Compilation command:

clang -O3 -Weverything -pipe -march=native -o png png.c

Neither printf() nor bool would cause a significant performance impact.  One reason could be that you're looping through a huge number which, depending on the system, could be as low as 18446744073709551615.  Doing so in serial would likely take a long time for such a range, and you can always consider adding parallelization where feasible.

Beyond that, any slowdown would be in is_prime().  Not only are there are a few conditionals, which could involve slowdown from branch prediction, but there's another loop that could take a while.  You may consider looking for pre-existing prime algorithms elsewhere, which could be faster than yours.  That should help improve runtime considerably.


Generate all combinations of length N through M I've started learning programming and as matter of practice I've decided to make a program that will output all possible string combinations and put them in a file.
I've manged to do that and it works perfectly fine. Then I added the option to generate words of different length, so the output looks something like this for words between 2 and 4 characters:

aa
ab
ac
ad
....
zzzz

Now I'm wondering what I can improve and what are different approaches to this problem? For learning purposes I'm trying to do this without using any library facilities, not even the standard library. Looking forward to code review and tips.

#include <fstream>

void gen(std::ofstream& f_out, char* word, int pos=0)
{
    if(!word[pos]) return;
    int length=0;
    for(int i=0; word[++i]; length++);
    while(word[pos]<='z') {
        gen(f_out, word, pos+1);
        if(pos==length) f_out << word << std::endl;
        word[pos]++;
    }
    word[pos]='a';
}

int main()
{
    std::ofstream f_out;
    f_out.open("gen.txt");

    char* word;
    int min=2, max=4;
    for(int i=min; i<=max; i++) {
        char* buffor = new char[i+1];
        for(int x=0; x<i; buffor[x]='a',  x++);
        buffor[i]='\0';
        word=buffor;
        gen(f_out, word);
        delete [] word;
    }

    f_out.close();
    return 0;
}

Let's start with the core premise of what you're trying to do, which is program in C++ without the standard library for "learning purposes". The problem with this is that you're not learning much useful, really. It's a lot like if you were trying to learn to drive a car by manually doing the timing of the crankshaft and spark plugs... a neat trick, sure, but not one that's ever going to be of any practical use when actually driving a car.

Put another way, you can "learn" C++ by re-implementing std::strlen() (poorly)... but your time would be better spent learning to use the actual std::strlen() and all the other wonderful tools in the standard library, for two reasons:

Because any actual, non-trivial program you ever write will have to use those tools, so you might as well learn them.
Because you will learn more about being an actual good C++ programmer by observing how things are done in the standard library... which is a fantastically well-designed library (mostly), designed by the best C++ programmers in the world.

It's also worth noting that you are using the standard library. There is no such thing as "bare bones" in C or C++ - a truly "bare bones" C or C++ program would do literally nothing useful, and be optimized right down to an empty main() function. I'm not even talking about the use of std::ofstream (although that does make the point). I'm talking about all the hidden stuff you're using. Like, when you use new, you're using the global operator new in header <new>. You're also pulling in whatever new handler has been installed by the runtime, plus the exceptions library by virtue of std::bad_alloc, and more. And all that isn't even to mention all the stuff in the runtime that gets initialized before main().

What I'm saying is that "bare bones" C++ is a fantasy. There's no such thing. C++ (like C, and like everything else) needs a runtime - whether you use the standard one or write one yourself (such as for a very limited embedded system). You are using the standard library. You just don't realize it.

So trying to learn C++ without using the standard library is:

not teaching you how to actually write C++
not helping familiarize you with the tools that would actually be useful in writing real C++ programs; and
misleading you into thinking you're doing everything on your own like a bad-ass hacker, when in reality the standard library is secretly holding your hand the entire time.

But alright, you've chosen to do this without visibly using any standard library components, so let's do it.

void gen(std::ofstream& f_out, char* word, int pos=0)

This isn't really part of the meat of what you're doing, but it is part of real C++ programming. Taking any specific stream type (like ofstream) by reference is almost never the right thing to do. What you want to take here is std::ostream&. That allows this function to work with file streams, but also std::cout, string streams, network streams, and anything else.

int length=0;
for(int i=0; word[++i]; length++);

These two lines are std::strlen(). They really should be separated out into its own function. One function; one job. Right now gen() not only generates the next word, it also checks the length of the word - that's at least two jobs. Checking the word length is something useful on its own, so it should be separated into its own function.

However....

There is a questionable design decision here to have the generating function check the string length each time its called. There are two issues with that:

it requires the word to be null-terminated; and
whoever calls the function already knows how long the word is, so the function is just redoing work unnecessarily.

In modern C++ it is increasingly preferred to pass array data along with its size in some way - either as a pair of pointers, or a pointer and a size. This is exactly why std::string_view was added to C++17, and why std::span is coming in C++20.

If gen() took a pointer and a size, then the first few lines of the function could be:

void gen(std::ofstream& f_out, char* const word, int const length, int pos = 0)
{
    if(pos == length) return;
    while(word[pos]<='z') {
        // ...

That avoids the need to check the length and allows you to take non-null-terminated strings. It make the function faster and more flexible to use.

if(pos==length) f_out << word << std::endl;

Never use std::endl. It is basically always wrong. In this case, it should be:

if(pos==length) f_out << word << '\n';

But if you've refactored the function to take a pointer and a size (and thus, non-null-terminated strings), you would have to use:

if(pos==length) f_out.write(word, length) << '\n';

or:

if(pos==length) f_out.write(word, length).put('\n');

Down to main().

You never confirm that the file actually opened. You can either test is_open(), the fail bit, or you can set stream exceptions before trying to open it.

char* word;
int min=2, max=4;

Don't declare variables until they're needed. word is not needed until 5 lines later... and technically not even then.
Don't declare multiple variables on a single line. That causes all kinds of headaches with syntactic quirks, and makes it harder to see where variables come from.

I would also recommend that min and max be constexpr. You should also assert that max >= min, for safety.

If we remove word (because it's unnecessary), your main loop looks like this:

for(int i=min; i<=max; i++) {
    char* buffor = new char[i+1];
    for(int x=0; x<i; buffor[x]='a',  x++);
    buffor[i]='\0';
    gen(f_out, buffor);
    delete [] buffor;
}

If you refactor gen() to take a pointer and length, rather than just an implicitly null-terminated pointer, this simplifies to:

for(int i=min; i<=max; i++) {
    char* buffor = new char[i];
    for(int x=0; x<i; buffor[x]='a',  x++);
    gen(f_out, buffor, i);
    delete [] buffor;
}

The inner for loop is just std::fill_n() or std::memset(). It should be moved into its own function for clarity.

But there's a bigger issue here, and that's exception safety. If any exceptions are thrown after the allocation of buffor, the memory will leak.

There are multiple ways to fix this situation. The easiest way is to simply declare everything between the allocation and deallocation to be noexcept. Easy, but not really a good solution because noexcept implies "cannot fail"... and any output can fail.

A really ugly solution is to do this:

for(int i=min; i<=max; i++) {
    char* buffor = new char[i+1];
    try
    {
        for(int x=0; x<i; buffor[x]='a',  x++);
        gen(f_out, buffor, i);
        delete [] buffor;
    }
    catch (...)
    {
        delete [] buffor;
        throw;
    }
}

But the best solution is to create a RAII class for your buffer. Something like:

class buffer
{
public:
    explicit buffer(int size) :
        ptr_{new char[size]}
        size_{size}
    {}

    ~buffer()
    {
        if (ptr_)
            delete[] ptr_;
    }

    // Move ops are handy:
    buffer(buffer&& other) noexcept :
        ptr_{other.ptr_},
        size_{other.size_}
    {
        other.ptr_ = nullptr;
        other.size_ = 0;
    }

    buffer& operator=(buffer&& other) noexcept
    {
        // no std::swap, so we have to do this dance:

        auto const temp_ptr = ptr_;
        ptr_= other.ptr_;
        other.ptr_ = temp_ptr;

        auto const temp_size = size_;
        size_ = other.size_;
        other.size_ = temp_size

        return *this;
    }

    // Observers:
    auto pointer() const noexcept { return ptr_; }
    auto size() const noexcept { return size_; }

    // No copying.
    buffer(buffer const&) = delete;
    buffer& operator=(buffer const&) = delete;

private:
    char* ptr_ = nullptr;
    int size_ = 0;
};

That simplifies your main loop to:

for(int i=min; i<=max; i++) {
    auto buffor = buffer{i};
    fill_n(buffor.pointer(), i, 'a'); // for(int x=0; x<i; buffor.pointer()[x]='a',  x++);
    gen(f_out, buffor.pointer(), i);
}

and at the same time, gives you proper exception safety.

But here's an interesting observation. There is no point in allocating a buffer for each size between min and max. Why not just allocate a single buffer of max size, and reuse it?

auto buffor = buffer{max};
for(int i=min; i<=max; i++) {
    fill_n(buffor.pointer(), i, 'a');
    gen(f_out, buffor.pointer(), i);
}

That spares you the cost of deallocating and reallocating the buffer multiple times.

f_out.close();
return 0;

Both of these lines are unnecessary.

There are also a few more suggestions I'd make from a design and usability perspective.

The way your code is written, before someone can use gen() they have to prepare the buffer just right. That just makes gen() more difficult to use. It would be easier to use if gen() has a simpler interface, something like:

void gen(std::ostream& out, int min, int max);

and then gen() handled setting up the buffers, and called a helper function to do the actual recursion stuff.

Another thing that would be nice is if you could actually specify the set of characters to use in the generated strings. That would also sidestep a very technical bug in your code: you assume that the characters 'a' through 'z' have contiguous code points... that's not always true.

You could do something like this:

namespace detail_ {
namespace {

constexpr char DEFAULT_CHARS[] = "abcdefghijklmnopqrstuvwxyz";
constexpr auto DEFAULT_CHARS_SIZE = sizeof(DEFAULT_CHARS) - 1;

void gen_impl_(std::ostream& out, char* buffer, int size, char const* chars, int chars_size, int pos = 0)
{
    // algorithm here
}

} // anonymous namepsace
} // namespace detail_

void gen(std::ostream& out, int min, int max, char const* chars, int chars_size)
{
    // verify arguments

    // create the buffer
    for (auto i = min; i <= max; ++i) // could also check that the output stream is still good
    {
        // fill the buffer with the first char, then:
        detail_::gen_impl_(out, buffer, i, chars, chars_size);
    }
}

void gen(std::ostream& out, int min, int max)
{
    gen(out, min, max, detail_::DEFAULT_CHARS, detail_::DEFAULT_CHARS_SIZE);
}

Now I can use gen() like this:

// generate "aa" to "zzzz"
gen(out, 2, 4);

// generate hexadecimal numbers from 0 to FFFF
gen(out, 1, 4, "0123456789ABCDEF", 16);

without worrying about setting up buffers properly.

An even more interesting design would be to use callbacks, rather than having writing to a stream be the only option. For example:

// generate "aa" to "zzzz", and write them to f_out
gen(2, 4, [&f_out](auto ptr, auto size) { f_out.write(ptr, size).put('\n'); });

// generate hexadecimal numbers from 0 to FFFF, and make sure they're all
// valid hex numbers.
auto validate_hex_number(char const* ptr, int size)
{
    auto n = 0u;
    auto res = std::from_chars(ptr, ptr + size, n, 16);
    if (!res.ec)
    {
        if (n > 0xFFFFu || res.ptr != ptr + size)
            res.ec = std::make_error_code(std::errc::invalid_argument);
    }

    if (res.ec)
        throw std::system_error{res.ec};
}

gen(1, 4, "0123456789ABCDEF", 16, &validate_hex_number);

You could even design it so that if the callback returns false, you stop generating. This would be handy for brute force password cracking, for example.

Summary

Avoiding the standard library is a pointless exercise, because you'll end up reimplementing chunks of it anyway. Here you've had to implement crappy versions of std::strlen(), std::fill_n() (or std::memset()), and std::vector<char> (or std::string). There's no real gain from reimplmenting those things; your time would have been better served designing the gen() algorithm better - for example, having it take different character sets, or using a callback.

Use more functions. One function; one job. If you ever see a nested loop, or if a function is more than ~5 lines of functional code (not counting usings, variable declarations, lines with just braces, comments, and so on), that's a sign that it might be possible to break it into simpler functions.
Move work out of loops wherever possible.
Don't throw information away - if you know the size of a buffer before calling a function, there's no need to make the function recalculate it.
Use RAII. If you're writing C++ and you're not using RAII, you're writing garbage C++.


Filtering an object JS I'm making a news aggregator using newsAPI, and have everything working - to begin with. But was wondering if the code I use to filter through an object can be made more efficient - meaning fewer lines of code.

So far, it only returns what I need from the raw JSON file, then filters it using a for loop to ignore objects with blank values.

Any help would be great.

   if (!error && response.statusCode == 200) {

        let data = JSON.parse(body);

        let articles = data.articles.map(article => {
            return {
                "title": article.title,
                "date": article.publishedAt,
                "image": article.urlToImage,
                "description": article.description,
                "link": article.url
            }
        });

        let filtered = []
        for (let i = 0; i < articles.length; i++) {
            if (articles[i].title !== null &&
                articles[i].date !== null &&
                articles[i].image !== null &&
                articles[i].description !== null &&
                articles[i].link !== null) {
                filtered.push(articles[i])
            }
        }

        console.log(filtered)

        res.render("index", { filtered: filtered });

   }

let -> const
Use the Array methods (filter, every)
Use object destructuring
Use object short-hand
Use a method for the null check so you don't have to write it for every property

if (!error && response.statusCode == 200) {
  const data = JSON.parse(body);

  const filtered = data.articles
    .filter(({ title, publishedAt, urlToImage, description, url }) =>
      [title, publishedAt, urlToImage, description, url].every(
        prop => prop !== null
      )
    )
    .map(
      ({
        title,
        publishedAt: date,
        urlToImage: image,
        description,
        url: link
      }) => ({
        title,
        date,
        image,
        description,
        link
      })
    );

  res.render("index", { filtered });
}

Update: filtered first for lower memory consumption as by @FreezePhoenix suggestion.


ImprSimple chat bot written in python I'd like to know if I can improve the performance of my recent bot, and maybe some design patterns too.

So far, it's warning a user if it's using some bad words (which are parsed from bad_words.txt) and it's entertaining the users by posting jokes from jokes.txt.

from selenium import webdriver
import time
import random

def login_to_rst(base_url, username, password):
    xpaths = {
        'usernameTxtField': "//input[@name='auth']",
        'passwordTxtField': "//input[@name='password']",
        'submitButton': "//*[@id='ipsLayout_mainArea']/div/div[2]/div/form/li[5]/div/button"
    }
    FIREFOX_DRIVER.get(base_url)
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['usernameTxtField']).clear()
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['usernameTxtField']).send_keys(username)
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['passwordTxtField']).clear()
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['passwordTxtField']).send_keys(password)
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitButton']).click()
    FIREFOX_DRIVER.get(base_url)

def write_to_chat(chat_url):
    FIREFOX_DRIVER.get(chat_url)

    bad_words = [line.rstrip('\n') for line in open('bad_words.txt')]

    time.sleep(5)
    message = "Please use a decent language !"
    xpaths = {
        'textArea': "//*[@id='ipsTabs_elChatTabs_chatroom_panel']/div[1]/div[1]/textarea",
        'submitMessage': "//*[@id='ipsTabs_elChatTabs_chatroom_panel']/div[1]/div[1]/div[3]/button"
    }

    parsed_messages, rst_messages_list = [], []
    keep_running = True
    while keep_running:
        divs = FIREFOX_DRIVER.find_elements_by_xpath('//ul[@class="ipsList_reset cChatContainer"]/li/div')
        for div in divs:
            rst_messages_list = []
            if div.id not in parsed_messages:
                rst_messages_list.append(div.text)
                print(rst_messages_list)
                parsed_messages.append(div.id)

                for unique_message in rst_messages_list:
                    for word in bad_words:
                        if word in unique_message:
                            FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
                            FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys(message)
                            FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()

                    if '/message1' in unique_message or '/Message1' in unique_message:
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys("text to be sent")
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()
                    if '/message2' in unique_message or '/Message2' in unique_message:
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys("2016 © me")
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()
                    if '/message3' in unique_message:
                        line = random.choice(open('jokes.txt').readlines())
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys(line)
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()

if __name__ == "__main__":
    FIREFOX_DRIVER = webdriver.Firefox()

    login_to_rst('https://link-login', 'user', 'pass')
    write_to_chat('https://link-final-url')

I accept any constructive critiques as long as they are followed by a rational explanation.

Avoid using open when you can. with is a keyword for using a context manager, which will automatically ensure that files are always properly closed, which you don't ensure when you just call open in a list comprehension.

with open('bad_words.txt') as f:
    bad_words = [line.rstrip('\n') for line in f]

keep_running is always True, so why not just use while True.

To reduce nesting levels, I'd flip the condition from this:

rst_messages_list = []
if div.id not in parsed_messages:
    rst_messages_list.append(div.text)

to this

rst_messages_list = []
if div.id in parsed_messages:
    continue

rst_messages_list.append(div.text)

continue moves onto the next iteration, so it is effectively the same as before except that your code isn't as deeply nested.

When testing unique_message, you should really make it lowercase for ease of testing. That way you can match regardless of case. Also when you're testing if any word in bad_words is in unique_message, there's a Python function that does that, called any:

for unique_message in rst_messages_list:
    unique_message = unique_message.lower()
    if any(word in unique_message for word in bad_words):

This does the same as you had before, but now the if and for statements are combined in one line. The one main difference, is that your old code would message the user repeatedly if they used multiple bad words, which I assume was not the intention.

You repeatedly call these lines:

FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys(message)
FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()

Make this a function:

def send_message(message, xpaths):
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys(message)
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()

That reduces your code drastically:

if any(word in unique_message for word in bad_words):
    send_message(message, xpaths)
elif '/message1' in unique_message:
    send_message("text to be sent", xpaths)
elif '/message2' in unique_message:
    send_message("2016 © me", xpaths)
elif '/message3' in unique_message:
    line = random.choice(open('jokes.txt').readlines())
    send_message(line, xpaths)

Worth noting that since these are all if commands, you might send every one of these messages, for a message like "/message1 /message2 /message3 smeg" (assuming that smeg is on your list of bad_words). You should all but the first one elifs, so that they're mutually exclusive and only one (or none) will run.

Last point, unless calling webdriver.Firefox() is a lot of work for the script, I'd put that at the top instead of in if __name__ == "__main__", as it's easier to spot when it's near the top of the page, after imports. That's the convention for where constants should go.

FIREFOX_DRIVER = webdriver.Firefox()


Implementation of getUsersWithStatuses based on getUsersWithStatus In my code I have method which gets users from database with concrete status. And now I have to add new method which gets users from database with list of statuses. I don't know, is it better to create new repository method or reuse existing code.

I created example method "getUsersWithStatuses" which reuse old method "getUsersWithStatus". But, is it good that this method read data from database in loop?

@Transactional(readOnly = true)
public List<UserDTO> getUsersWithStatus(Long locationId, UserDTO.Status status) {
    List<User> userList = userRepository.findByLocationWithStatus(locationId, orderStatus);
    return userMapper.asDTOs(userList);
}

//new functionality
@Transactional(readOnly = true)
public List<UserDTO> getUsersWithStatuses(Long locationId, EnumSet<UserDTO.Status> statuses) {
    List<UserDTO> result = new LinkedList<>();
    statuses.forEach(status -> result.addAll(getUsersWithStatus(locationId, status)));
    return result;
}

I would say that in your case it is not a good idea because you will execute the same query many times.

However you can change you calls to have the method with a single status calling the one with many satuses.

List<UserDTO> getUsersWithStatus(Long locationId, Status status) {
  return getUserWithStatuses(EnumSet.of(status));
}

List<UserDTO> getUsersWithStatuses(Long locationId, EnumSet<Status> statuses) {
  // SELECT * FROM users WHERE status IN (..)
}


Retrieving collections from a database I have two collections that I want to retrieve from the database and associate with each other. My solution works, however I know it isn't the most elegant one. Do you have any suggestions on how to improve the algorithm?

Classes:

 public class JobAnnouncement : IDbEntity
{
    public int Id { get; set; }
    public JobAnnouncementPosition Position { get; set; }
    public int PositionId { get; set; }
    public DateTime From { get; set; }
    public DateTime To { get; set; }
    public bool IsDeleted { get; set; }
    [Required]
    public string PositionNameAdvertised { get; set; }
    public int? PortalId { get; set; }
    public JobAnnouncementPortal Portal { get; set; }
    public string OtherPortal { get; set; }
    public int? UserId { get; set; }
    public PragisUser User { get; set; }
    [Required]
    public DateTime From { get; set; }
    [Required]
    public DateTime To { get; set; }
    public int ReceivedCvCount { get; set; }
    public int InterviewedCount { get; set; }
    public int RecruitedCandidatesCount { get; set; }
    public string Comment { get; set; }
}
public class JobAnnouncementPosition
{
    public int Id { get; set; }
    public ICollection<JobAnnouncement> JobAnnouncements { get; set; }
     public ICollection<JobAnnouncementDocumentInfo> DocumentsInfo { get; set; }
    public PragisUserType PragisUserType {get;set;}
    [Range(1, int.MaxValue)]
    public int? TeamId { get; set; }
    public Team Team { get; set; }

    [Range(1, int.MaxValue)]
    public int? TechnologyId { get; set; }
    public JobAnnouncementTechnology Technology { get; set; }
    public string OtherTechnology { get; set; }

    [Range(1, int.MaxValue)]
    public int? LevelId { get; set; }
    public JobAnnouncementLevel Level { get; set; }
    public bool IsDeleted { get; set; }
     [NotMapped]
    public int JobAnnouncementsCount
    {
        get
        {
            return JobAnnouncements != null ? JobAnnouncements.Count : 0;
        }
    }
    }

Repository returning all positions that are not deleted with all associated announcements that are not deleted. I was not able to return all data on one database call as the condition of IsDelted for child entity announcements was not checked and I always got all announcements back, no matter if they were or weren't deleted.

I made two calls and then iterated over them assigning announcements to positions again:

 public IEnumerable<JobAnnouncementPosition> GetForListActive()
    {
        var announcements = _context.JobAnnouncements
            .Include(a => a.Portal)
            .Where(a => a.To.Day >= DateTime.Now.Day)
            .Where(a => a.IsDeleted == false)
            .ToList();

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

        foreach (var announcement in announcements)
        {
            foreach (var position in positions)
            {
                if (announcement.PositionId == position.Id)
                {
                    position.JobAnnouncements.Add(announcement);
                }
            }
        }

        var result = new List<JobAnnouncementPosition>();
        for (var i = 0; i < positions.Count; i++)
        {
            if (positions[i].JobAnnouncements != null)
            {
                result.Add(positions[i]);
            }
        }

        return result;

    }

Two comments -

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

So if you do ...

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

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

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

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

But there's more.

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

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

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

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

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

I think this library is a gem.

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


Polyglot array_extend() function for Javascript and PHP This is a polyglot function I've made out of fun.

The goal is to grab n arrays (or Javascript Objects) and 'extend' them in order to obtain a single array with all the values.

This function runs both in Javascript and PHP.

Please, try to ignore some kludges on my code.

Here is my 'art':

function array_extend() {

    //Detects if we are running in Javascript or PHP
    //In PHP, this will be false because PHP only parses
    //escape sequences in double-quoted strings (except the sequence \')
    $javascript = '\0' == "\0";

    //PHP arrays support 'key=>value' pairs, JS arrays don't.
    $result = $javascript ? new Object() : array();

    $arguments = $javascript? arguments : func_get_args();

    $get_keys = function($elem){
        if('\0' == "\0")//PHP complains if I use the var $javascript
        {
            $object = Object;
            return $object['keys']($elem); //PHP doesn't like the Object.keys syntax
        }
        else
        {
            return array_keys($elem);
        }
    };

    for($j = 0, $length_args = $javascript? $arguments['length']: count($arguments); $j < $length_args; $j++)
    {
        $keys = $get_keys( $arguments[$j] );

        for($i = 0, $length_keys = $javascript? $keys['length']: count($keys); $i < $length_keys; $i++)
        {
            $result[$keys[$i]] = $arguments[$j][$keys[$i]];
        }
    }

    return $result;
}

Example of usage:

array_extend([1,2,3,4,5],[9,8,7,6,5,4,3,2,1,0]);
//should return the last elements in the array:

array_extend({'a':1, 'b':2, 'c':3},{test:'nice'});
//Javascript: returns {'a':1, 'b':2, 'c':3, test:'nice'}

array_extend(array('a'=>1, 'b'=>2, 'c'=>3), array('test'=>'nice'));
//PHP: returns array('a'=>1, 'b'=>2, 'c'=>3, 'test'=>'nice')

What do you guys think?

What can I improve? Where should I have done something better?

You may want to replace object key access notation with dot notation.

For example, instead of the following.

$object['keys']($elem);

Write this.

Object.keys($elem);

This works, because Object is interpreted as a constant, dot as concatenation, and keys($elem) as function call. Use of undefined constant doesn't warn if the code with it is not executed. Unknown functions don't error if they aren't called.


Searching through a contact list for given criteria I have been staring at this code for awhile now and I am thinking there is a way to optimize it (namely the if-else statement with the for-loops).

Additionally, this needs to be done with an array list as that is my assignment requirement. I have all my code working, and it is not due for a few days, so I am looking for ways to improve it while extending my learning beyond the classroom.

The numberOfContacts variable is fed into the method from the main method, which gets the count from another method that reads through a text file to get the number of contacts.

/**
 * search method searches through the contact list for a given criteria
 * and displays all results.
 * @param searchString is type String.
 * @param type is type String.
 * @param numberOfContacts is type int.
 * @param contacts is type Person[].
 */
public static void search(String searchString, String type, int numberOfContacts, Person[] contacts) {
    // Initialize variables for results
    int found = 0;
    int[] results = new int[numberOfContacts];

    // Determine the type of search
    if (type.equals("name")) {
        // Search by name
        for (int x = 0; x < numberOfContacts; x++) {
            if (contacts[x].getName().contains(searchString)) {
                results[found] = x;
                found++;
            }
        }
    } else {
        // Search by phone
        for (int x = 0; x < numberOfContacts; x++) {
            if (contacts[x].getPhone().contains(searchString)) {
                results[found] = x;
                found++;
            }
        }
    }

    // Display the search results
    System.out.println("\n\t**************");
    System.out.println("\tSearch Results");
    System.out.println("\t**************");
    System.out.println("Found " + found + " results containing \"" + searchString + "\":");
    System.out.println();

    if (found > 0) {
        for (int x = 0; x < found; x++) {
            System.out.println(contacts[results[x]].getName() + "\t" + contacts[results[x]].getPhone());
        }
    }

    System.out.println("\n\n\n");
}

If you are limited to use only Arrays, you can create a interface like this

public static interface Checker {
    public boolean check(Person p, String searchString);
}

Create a Checker for every type of comparison you want.

And compare with the Checker

for (int x = 0; x < numberOfContacts; x++) {
    if (checker.check(contacts[x], searchString)) {
        results[found] = x;
        found++;
    }
}

You can see a working example here (with your classes and methos): http://ideone.com/2C6kei

Note:
With this method is easy to expand the search criteria (as you see in the example, with a anywhere Checker).


Using extension methods in the decorator pattern After reading an exceptional article here about the decorator pattern applied to functions, I saw an opportunity to reduce a lot of boilerplate code in a console application project I've been working lately.

The app gathers information about the workstation it is run from, and saves that data to a central database. So, I have a lot of string methods, and most of them can throw an exception. Currently, a lot of them look like this:

public string GetDescription()
{
    try
    {
        Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\LanmanServer\\Parameters", "srvcomment", "").ToString();
    }
    catch(Exception ex)
    {
        return "ERROR" + ex.ToString()
    }
}

NOTE: There are a lot of methods just like this one.

So I ended up with this extension method:

public static GetValueOrException(this Func<string> method)
{
    try{ return method(); }
    catch(Exception ex){ return "Error: " + ex.ToString(); }
}

this allows me to get rid of the try...catch clauses in every method (there are 15+ of them)

Now, I have two options to consume my new extension method:

Change my string methods to instead return Func<string> like so:

public Func<string> GetDescription()
{
    return ()=> { return Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\LanmanServer\\Parameters", "srvcomment", "").ToString(); };
}

This might look awkward but it does allow for chained invocation (Linq style - I love it) E.G.:

bar.GetDescription().ValueOrException();

Leave my string method as is, and cast to Func<string> every time I need the extension method

((Func<string>)bar.GetDescription).ValueOrException();

Option 1 feels more natural to use, however option 2 feels more natural to write. Which option is best, and why do you think so? I should mention that it is very unlikely for another people besides myself  to also work on this code.

public static GetValueOrException(this Func<string> method)
{
    try{ return method(); }
    catch(Exception ex){ return "Error: " + ex.ToString(); }
}
public Func<string> GetDescription()
{
    return ()=> { return Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\LanmanServer\\Parameters", "srvcomment", "").ToString(); };
}
bar.GetDescription().ValueOrException();

Why is this a horrible idea?

Because you just successfully eliminated the function the exceptions had originally: Error handling.

The premise when using LINQ like notations, is that you have a valid set of data in a fixed formate at each step of execution.

By intercepting the exception too early, and mangling it into the same format as a valid output, you are breaking with that premise. Instead of the valid input, you are now passing the error message down to subsequent operations.

With no way to distinguish the error case from a valid result.

But this mistake isn't just new to your addition - it was already present on your original code:

public string GetDescription()
{
    try
    {
        Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\LanmanServer\\Parameters", "srvcomment", "").ToString();
    }
    catch(Exception ex)
    {
        return "ERROR" + ex.ToString()
    }
}

That return "ERROR" + ex.ToString() is a problem. Because that is not how to properly handle an error case. You literally can't distinguish at all whether this supposed error message was generated by this function, or if it was actually read from the registry.

Whenever you encounter an Exception, there are only 3 valid approaches:

Swallow the exception, and continue with a fail safe default.
Capture and encapsulate the exception in a more generic exception.
Translate the exception into a different, dedicated and distinguishable channel for error reporting. (E.g. encoding function success status in an enum return value, while the actual results are returned by reference.)
(optionally) Report the error to a logging component, before continuing with one of the 3 options above.

What you did was neither. You mixed the error state into the run time state of your application, tainting it and making the behavior of all subsequent functions depending on that value undefined.

Even if you expect that the result of the command chain eventually shows up on screen in text form, just because your application happens to be that simple, and these functions are not used in any other scope, it's still not safe to do it.

One more problem with your approach: It only "works" at all for string type functions. What with more complex datatypes, e.g. collections and alike?

For these, you can't trivially encode the error case in the return value. Simply because there isn't a solution with potentially different semantics, inevitably leading to undefined behavior later on.

How to capture exceptions correctly?

You only capture and swallow an exception ever, if you know that you can safely recover.

That means e.g. in the case of operations chained in LINQ style, you wrap no less than the whole chain into a try clause. The exception is supposed to interrupt the execution of the chain, to avoid undefined behavior.

And if the behavior of the surrounding scope still isn't in and can't be brought into a defined state in case of an exception, you let it bubble. As long until you can restore a sound state.

The completely broken error handling aside, decorating your functions to get a stream like semantic is perfectly legit.

Just be wary that this breaks with the coding style given by the .Net run time and most libraries. So the maintainability when enforcing such fundamentally different patterns is going to suffer. For one because that style is unexpected (-> principle of least surprise). For the other part because you can't trivially interface with 3rd party code, but you would always need either a wrapper, or break your own patterns.

You should try to stick to the patterns and interfaces already present in your run time, if possible.


What are the draw backs, if any, in using C and C++ together? Is doing so considered correct by the large? I have written code exclusively in both C and C++. I see clear advantages in both and therefore have recently began using them together. I have also read, what I would consider,          outrageous comments claiming that to code in C is outright dumb, and it is the language of past generations. So, in terms of maintenance, acceptance, common practice and efficiency; is it something professionals on large scale projects see/do?

Here's an example snippet:
I obviously need to #include both <stdio.h> and <iostream>.

#define STRADD ", "
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include "Struct.h"
#include "Rates.h"
#include "Taxes.h"
using namespace std;

And later I utilize functions like...

void printHeading(FILE * fp)
{
    fprintf(fp, "Employee            Pay        Reg Hrs     Gross       Fed        SSI        Net\n");
    fprintf(fp, "Name                Rate       Ovt Hrs     Pay         State      Defr       Pay\n");
    fprintf(fp, "==================================================================================\n");
    return;
}

and..

void getEmpData(EmpRecord &e)
{
    cout << "\n Enter the employee's first name: ";
    getline(cin, e.firstname);
    cout << " Enter the employee's last name: ";
    getline(cin, e.lastname);
    e.fullname = e.lastname + STRADD + e.firstname; //Fullname string creation
    cout << " Enter the employee's hours worked: ";
    cin >> e.hours;
    while(e.hours < 0)
    {
        cout << "  You did enter a valid amount of hours!\n";
        cout << "  Please try again: ";
        cin >> e.hours;
    }
        cout << " Enter the employee's payrate: ";
        cin >> e.rate;

    while(e.rate < MINWAGE)
    {
        cout << "  You did enter a valid hourly rate!\n";
        cout << "  Please try again: ";
        cin >> e.rate;
    }
    cout << " Enter any amount to be tax deferred: ";
    cin >> e.deferred;
    while(e.deferred < 0)
    {
        cout << "  You did enter a valid deferred amount!\n";
        cout << "  Please try again: ";
        cin >> e.deferred;

    }
    cin.ignore(100, '\n');
    return;
}

Thanks in advance!

You can't write exclusively in both C and C++.
You can write

exclusively in C
exclusively in C++
or using a combination of the two different languages.

to code in C is outright dumb, and it is the language of past generations.

C may be an old language but it is still heavily used and has its place.
It is practically the only glue language that is universal so great for writing effecient modules for other languages or gluing languages together.
It is also great for low level coding where you want/need to get close to the hardware.
But there are downsides to writing in C (but saying it is dumb to do so is stretching it a bit). But you should be able to justify your choice of choosing C over an alternative.

So, in terms of maintenance, acceptance, common practice and efficiency; is it something professionals on large scale projects see/do?

Are there large code bases writing in C that need maintenance: Yes.
Is it common practice to use C: That is entirely dependent on what you are doing it is imposable to generalize.
Personally I write exclusively in C++.
There is nothing I can do in C I can't do in C++ so I don't write C anymore (In fact I have dropped it from my resume (especially since I don't want to write C)). The advantage of C++ is I can get code written to as low a level as C but I also have higher level constructs (though not as high as modern scripting languages).
Code Review:
I see no advantage of using frpintf(). In situations like this C++ std::ofstream is much more flexible,
printHeading(FILE * fp)
{
    fprintf(fp, "Employee            Pay        Reg Hrs     Gross       Fed        SSI        Net\n");

// I would always use C++ stream.
// It can be more than just a file.
printHeading(std::ostream& stream)
{
     stream <<  "Employee            Pay        Reg Hrs     Gross       Fed        SSI        Net\n";

Also if you are doing anything complex it is TYPE SAFE. *Unlike C code using fprintf(). This is one major area that C falls down in and is the cause of some of the major bugs in C code.
You check for an invalid number. But you are not checking for completely invalid input. What happens if somebody typed "Fred"
cin >> e.hours;
while(e.hours < 0)
{
    cout << "  You did enter a valid amount of hours!\n";
    cout << "  Please try again: ";
    cin >> e.hours;
}

You expect that there is never more than 100 bad characters in the input?
cin.ignore(100, '\n');

What happens if I accidentally paste in a paragraph of text.
And last but worst of all:
using namespace std;

Never do this. It is OK if you are writting a ten line toy project. But once you get past anything more than a toy it causes more problems (in name clashes) than it is worth. The reason standard library is shortened to std:: is to make it easy and quick to type.


random team distributer Any idea how to shorten and improve the program?
it's going to take a list included of 22 people and split them into two teams and return the names and teams
import random
# list of teams
teams = ['A', 'B']
# list of players which is inculded of 22 people
players = ['a', 'b', 'c', 'd', 'e',
           'f', 'g', 'h', 'i', 'j',
           'k', 'l', 'm', 'n', 'o',
           'p', 'q', 'r', 's', 't',
           'u', 'v']

# takes the list of names

class Human:
    def __init__(self, name):
        self.name = name

# distribure names and people to teams randomly and it inherits names from Human class

class Player(Human):
    def get_team(self):
        teams = dict()
        random.shuffle(self.name)
        teams['A'] = self.name[0::2]
        teams['B'] = self.name[1::2]
        return teams

my_team = Player(players)
my_team = my_team.get_team()
for team, name in my_team.items():
    print(team, name)

The concept is good, but there is room for improvement. Here are some problems I see:
Misleading names
Clear names are very important in coding, because they make it easy or hard for other people (including your future self) to understand what you have written. Some of the names you have used do not match what the code actually does, which is confusing.

Based on the name of the Human class, I'd expect an instance of this class to represent one human, but that is not how it is used (see below).
Based on the name of the Player class, and the way it extends Human, I'd expect an instance of this class to represent one player; if so, then there should be 22 instances of the class, or one object for each name in the players list. Instead, it seems to represent all the players at once, which its name does not imply.
I would expect the name attribute of Human to store a single name, but Player stuffs an entire list of player names into that attribute.

At minimum, these names should be made plural (Humans, names, Players, etc.) to reflect their contents. It would be even better to give Player a name that describes what it actually does, or what it is responsible for within the program.
Unnecessary hierarchy, part 1: only one subclass
You mentioned in a comment that you are trying to practice your OOP skills, so "[you] want to force [yourself] to use classes even if it sounds silly". Practice is good, but part of good OOP is understanding why and how to use classes and objects effectively...and that includes knowing when not to use them, or when not to use certain parts of them.
For example: why do you need both a Human class and a Player subclass? In the program that you have now, the only humans are players; therefore there is no advantage to having two classes. You could do everything in the Player class and drop the Human class altogether, or vice versa. On the other hand, if you already have plans to expand your program to include non-player humans (e.g. coaches, referees), then a Human superclass might make sense. The structure of the code should fit your use case.
Unnecessary hierarchy, part 2: superclass does nothing
A subclass is supposed to have a "type of" or "kind of" relationship to its superclass, e.g. a Square is a kind of Rectangle, or a Dog is a kind of Animal. The problem is that your code does not gain much from defining Player as a kind of Human. Since Human has no defined behaviors and barely any data, inheriting from it doesn't provide many benefits. It would be simpler and more flexible to use composition instead of inheritance, by creating or importing a Human object inside the Player object.
Unnecessary use of internal state / object attributes
One of the nice things about objects is that they can create and maintain an internal state--a little chunk of data that it hides away from the rest of the program. (Keeping separate things separate is called encapsulation or separation of concerns, and it makes programs much easier to think about and easier to debug.) In Python, internal state is stored in object attributes, like Human's self.name. But you have to know when to use internal state and when not to use it. Keeping multiple copies of the same data in different places, or multiple references to the same data object, can cause confusion and lead to bugs.
Your get_team() method takes a list of players, splits the players between two known teams, and then returns a dict() with that information. This method is called only once in your entire program. So, what is the advantage of having the Player object store the list of player names inside itself? In the current code, there is no advantage. You could easily change get_team() to a class method (which can be called without instantiating an object) that takes the player names as a parameter.
Hardcoded assumptions
# list of teams
teams = ['A', 'B']

Since you defined this teams list at the top of the code, I would assume that editing that list would change the program output. But when I look closer, I can see that this list is not even used. Your get_team() method is explicitly written to split the players into two teams named 'A' and 'B', regardless of what is in the list above.
        teams['A'] = self.name[0::2]
        teams['B'] = self.name[1::2]
        return teams

This is not very flexible, especially if you want to import the team names from outside the program (e.g. from user input, or from a config file). A better method would take a list of teams as an input, count the number of teams, and then split the players accordingly.

Here's how I might write it:
TEAMS = ('A', 'B')  # Replaced mutable list with immutable tuple.
                    # Names of constants should be in all-caps.
PLAYERS = ('a', 'b', 'c', 'd', 'e',
           'f', 'g', 'h', 'i', 'j',
           'k', 'l', 'm', 'n', 'o',
           'p', 'q', 'r', 's', 't',
           'u', 'v')

class TeamAssigner:
    def assign_players_to_teams(teams, players):
        players_on_teams = dict()
        randomized_players = random.sample(players, len(players))  # changed to .sample because .shuffle doesn't work on tuples / immutable sequences
        for i, team in enumerate(teams):
            players_on_teams[team] = randomized_players[i::len(teams)]
        return players_on_teams

my_teams = TeamAssigner.assign_players_to_teams(TEAMS, PLAYERS)
for team, name in my_teams.items():
    print(team, name)

Of course, this is only what I would write if I was not planning to expand the program in the future. If you have plans to make the program bigger and make it do more things, then some of these decisions might be the wrong ones. For instance, if you wanted the ability to move players from one team to another after the initial split, then you would need a class that did keep an internal state of who is on which team...


Determinant using Gauss Elimination We had a question in examination to compute determinant of general square matrix.
Now I had made the normal program using Laplace Formula of determinant, ie, recursive solution.

Now I was thinking of reducing it into Upper Triangle Matrix and then the product of diagonal elements gives the determinant.

The code is following.

#include <iostream>
using namespace std;

const int N = 5;
int main()
{
    double array[N][N], det = 1;

    // initialise
    cout << "Enter " << N << "*" << N << " matrix:\n";
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            cin >> array[i][j];
        }
    }

    for (int i = 0; i < N; ++i)
    {
        bool flag = false; // flag := are all entries below a[i][i] including it zero?
        if (array[i][i] == 0) // If a[i][i] is zero then check rows below and swap
        {
            flag = true;
            for (int j = i; j < N; ++j)
            {
                if (array[j][i] != 0) {
                    det *= -1;
                    for (int k = 0; k < N; ++k) {
                        double t = array[i][k]; // swapping
                        array[i][k] = array[j][k];
                        array[j][k] = t;
                        flag = false;
                    }
                }
            }
        }

        if (flag == true) {
            det = 0;
            break;
        }

        else {

            for (int j = i+1; j < N; ++j)
            {
                double store = array[j][i];
                for (int k = i; k < N; ++k) {
                    array[j][k] -= (array[i][k]*store)/array[i][i];

                }
            }
            det *= array[i][i];
        }
    }

    cout << "Determinant: " << det;
    return 0;
}

The problems with this approach is that matrix needs to be of floating point datatypes. Worse, it gives wrong result for least significant place (ones digit) for all integral entries if I use datatype of entries as float. To overcome that, we can use double.

But still I :

need tips on improving performance of this method
need to know whether this method is better than Simple Laplace Formula?

Some general remarks:

Don't use namespace std;, see for example Why is “using namespace std;” considered bad practice?.
Don't put all the code into main(). Computing the determinant in a separate
function increases the overall clarity of the program and makes it easier to add
test cases. In addition, that gives you a function which can be reused in other
programs.
Swapping two values can be done in C++ simply with std::swap.
return 0; at the end of the main program can be omitted.

At some places your code does unnecessary work:

If the diagonal element a[i][i] is zero then all subsequent rows
with array[j][i] != 0 are swapped with the ith row. It suffices to
swap one row with a non-zero leading element.
When swapping rows i and j, it suffices to swap the elements starting
at column i because the preceding elements are not used anymore.
Similarly, when adding a multiple of row i to row j, it suffices to
update elements starting at column i + 1, because all values of column
i will not be read anymore.

As already said in the comments, the Gaussian elimination is faster than the
Laplace expansion for large matrices (\$ O(N^3) \$ vs \$ O(N!) \$ complexity).
However, the “pivoting” (i.e. which rows to swap if an diagonal element is zero)
can be improved. A common choice is “partial pivoting”:

  In partial pivoting, the algorithm selects the entry with largest absolute value from the column of the matrix that is currently being considered as the pivot element. Partial pivoting is generally sufficient to adequately reduce round-off error. ...

Using a (nested) std::vector for the matrix storage makes it
easier to pass it an argument to another function.
In addition, it allows to swap two rows in constant time with vector::swap.

Putting it all together, the determinant function could look like this:

#include <vector>
#include <cmath>

double determinant(std::vector<std::vector<double>> &matrix) {
    int N = static_cast<int>(matrix.size());
    double det = 1;

    for (int i = 0; i < N; ++i) {

        double pivotElement = matrix[i][i];
        int pivotRow = i;
        for (int row = i + 1; row < N; ++row) {
            if (std::abs(matrix[row][i]) > std::abs(pivotElement)) {
                pivotElement = matrix[row][i];
                pivotRow = row;
            }
        }
        if (pivotElement == 0.0) {
            return 0.0;
        }
        if (pivotRow != i) {
            matrix[i].swap(matrix[pivotRow]);
            det *= -1.0;
        }
        det *= pivotElement;

        for (int row = i + 1; row < N; ++row) {
            for (int col = i + 1; col < N; ++col) {
                matrix[row][col] -= matrix[row][i] * matrix[i][col] / pivotElement;
            }
        }
    }

    return det;
}


Multiple Google Maps using V3 API I have several Google Maps on one page and each has its own set of Lat/Lng co-ordinates. As a result I have added in the JavaScript options for each one individually as follows:

function initialize() {
   var myLatlng1 = new google.maps.LatLng(49.18589, -2.19917);
   var myLatlng2 = new google.maps.LatLng(101.1986, -50.2445);
   var myLatlng3 = new google.maps.LatLng(29.125285,-82.048823);

  var mapOptions1 = {
     zoom: 17,
     center: myLatlng1
  };
  var mapOptions2 = {
     zoom: 17,
     center: myLatlng2
  };
  var mapOptions3 = {
     zoom: 17,
     center: myLatlng3
  };

  location_1 = new google.maps.Map(document.getElementById('map-canvas1'), mapOptions1);
  location_2 = new google.maps.Map(document.getElementById('map-canvas2'), mapOptions2);
  location_3 = new google.maps.Map(document.getElementById('map-canvas3'), mapOptions3);

  marker1 = new google.maps.Marker({
     position: myLatlng1,
     map: location_1
  });

  marker2 = new google.maps.Marker({
     position: myLatlng2,
     map: location_2
  });

  marker3 = new google.maps.Marker({
     position: myLatlng3,
     map: location_3
  });
}

The HTML is:

This just feels like a really long-winded way of doing things seeing as everything has a similar identifier - is there a better way of doing this?

Have you considered an array?

You can then create multiple objects, having each object the values per point.

Like this:

var coords = [
    {lat: 49.18589, lng: -2.19917, zoom: 17},
    {lat: 101.1986, lng: -50.2445, zoom: 17},
    {lat: 29.125285, lng: -82.048823, zoom: 17}
];
var markers = [];
var maps = [];

function initialize() {
    for(var i = 0, length = coords.length; i < length; i++)
    {
        var point = coords[i];
        var latlng = new google.maps.LatLng(point.lat, point.lng);

        maps[i] = new google.maps.Map(document.getElementById('map-canvas' + (i + 1)), {
            zoom: point.zoom,
            center: latlng
        });

        markers[i] = new google.maps.Marker({
            position: latlng,
            map: maps[i]
        });
    }
}

Here's what I did:

Created a few variables at the top, with needed information.
Created a loop to go through all the elements
Reduced the number of local variable to the bare minimum
Removed global variables being declared inside the function

Notice that I have this for loop:

for(var i = 0, length = coords.length; i < length; i++)

I'm not accessing the length property directly because it may decrease performance. Accessing a local variable is always faster than a property in an array/object.

Also, since i starts in 0 and your elements' id starts in 1, I had to add 1 to i, to match the right element.

Using an array, you also don't need to re-re-re-repeat everytime you need to add a point: just add a new element inside the array coords.

I hope you can understand everything and hope it is clear enough for you. And hope it really helps you.


ActiveRecord Query for many to many association I have two Models in my Rails 6 / PostgreSQL application which have a many to many relation; Car and Driver. The goal is to get all records (Cars) which have no association at all (Drivers). At the moment this is done using Ruby (2.6.3) like this:

result = []
Car.all.each do |car|
  result << car.id if car.drivers.empty?
end

Is there an ActiveRecord expression which avoids instantiating each record?

To produce the set of records only in cars, but not in drivers, you perform a left outer join, then exclude the records you don't want from the right side via a where clause.

In Rails 6 you do this in this way:

Car.left_outer_joins(:drivers).where(car_drivers: { id: nil })

Take a look at this article: A Visual Explanation of SQL Joins. It may help you figure out how to do some queries.

Aside from this, a good way to iterate over an array to select some elements according to a condition is to use the select method. Using select your code would be like this:

result = Car.all.select { |car| car.drivers.empty? }

But that is not the way to go here, I'm just showing how to use select.

Also, if you want only the id from the cars, you can add pluck(:id) at the end of the query. This is going to get only the id field from the database. Or you just use the method ids but the pluck method works for any field.


Parsing JSON using jsoncpp I left questions in the comments strategically, since I think it's easier to answer questions this way.

Basically what my small class does is abstracts away functionality that was originally in a function.

This class reads json form a file and creates an object which I can use to traverse the json. I understand that if something can be made into a function it shouldn't be made into a class, but I need to practice.

Below I outlined things I'm looking for. Choose one or choose all.

Looking for:

Did I use references "&" correctly
#include header files correctly
A way to initialize object like so: Root rate("test.json", ["query"]["results"]["rate"]) (syntax can be different)
Best practice advice

Not looking for (at least not yet):

Exceptions and Error handling
Advice form C programmers

root.h

#ifndef ROOT_H
#define ROOT_H

// Should header files always be included in root.h as opposed to root.cpp?
#include <fstream>
#include <string>   // Seems like I do not need to include this string container, why?
                    //is it because json/json.h contains it?

#include "json/json.h" // Would I ever create a class with a dependency like this one?
                       // jsoncpp.sourceforge.net/annotated.html

class Root
{
private:
    std::ifstream m_json;

public:
    Json::Value m_root;
    Json::Value m_query;

    Root(const std::string&);
    ~Root();
};

#endif // ROOT_H

root.cpp

#include "root.h"

Root::Root(const std::string & filename) : m_json(filename, std::ifstream::binary)
// Is std::ifstream::binary ok to put it in here like this ^?
// It's working, but would that be good practice?
{
    m_json >> m_root;
    m_json.close();  // Do I need .close() here?

}
Root::~Root(){}

main.cpp

#include <iostream>
#include "root.h"

int main()
{

    Root rate("test.json");
    rate.m_query = rate.m_root["query"]["items"]; // Is it ok to assign member to a member like so,
                                                  // as opposed to just a variable?

    // How can I instantiate my object like the line below?
    // Root rate("test.json", ["query"]["results"]["rate"]);
    // Syntax does not have to match precisely?

    for(const auto & it : rate.m_query)
    {
        std::cout << it << std::endl;
    }
}

test.json

{
  "query": {
    "count": 3,
    "items": [
      {"item": "4"},
      {"item": "3"},
      {"item": "2"}
    ]
  }

// Should header files always be included in root.h as opposed to

You should include all header files that are required (no more than are required).

In your case you use the following types in the header file.

std::ifstream
std::string
Json::Value

So you should include the appropriate header file for these types.

#include <fstream>
#include <string>
#include "json/json.h"

The only curve ball is that if you only use a type reference then you can technically get away with a forward declaration (rather than including the header file). So you could use a forward declaration of std::string, unfortunately its not your class and you don't actually know how to forward declare it because that is not defined in the standard, so you have to include the header file.

  // Seems like I do not need to include this string container, why?

It may be included indirectly via <fstream> or "json/json.h". BUT you should still include the <string> header file because these dependencies may not always hold (on different platforms or different versions of the compiler it may including things differently). So do not assume because it worked on this platform it will always work. Think worst case and explicitly include <string>

The include guard seems a bit too generic:

ROOT_H

Seems like somebody else may use this. You need to make sure your guards are unique. I always use guards that include the namespace

// I own the domain name thorsanvil.com
// and I put all my classes in the namespace ThorsAnvil
// So my include guards go like this.
#define THORSANVIL_<Optional Nested Namespace>_ROOT_H

  // Is std::ifstream::binary ok to put it in here like this ^?
  // It's working, but would that be good practice?

Sure. That's totally fine.

You just have to understand what it mean and the difference between binary and text mode (the default). In Text mode: => "Platform Specific" "End of Line Sequence" is converted into '\n' when reading from a file. In Binary mode: no conversion is performed and you get the raw bytes.

So in the constructor:

Root::Root(const std::string & filename) : m_json(filename, std::ifstream::binary)

{
    m_json >> m_root;
    m_json.close();  // Do I need .close() here?

                     // Yes probably.
                     // Closing it releases the related OS resources.
                     // If you don't the resource will be held until
                     // the whole object is destroyed.

}

I don't see the need for the m_json object to be part of the object. It is only every going to be used inthe constructor. Once the data is loaded it will never be used again. So just declare it as an automatic variable that is local to the constructor.

Root::Root(const std::string & filename)
{
    std::ifstream  m_json(filename, std::ifstream::binary)

    m_json >> m_root;
}
// Now we don't need `close()` because the object goes out of scope
// and the `std::ifstream` destructor calls close for us.

  // Is it ok to assign member to a member like so,
  // as opposed to just a variable?

It is. But why. It seems much more logical to use a local variable.

Json::Value query = rate.m_root["query"]["items"];

Prefer '\n' over std::endl

The difference is that std::endl forces the buffer to flush. The buffer will flush automatically when it needs to. Forcing it to flush is only going to make your code inefficient.

  // How can I instantiate my object like the line below?
  // Root rate("test.json", ["query"]["results"]["rate"]);

You can define the operator[]. You can make it take a string as an argument.

class Root
{
    public:
        JsonValue operator[](std::string const& index)
        {
            return m_root[index];
        }
        // Other stuff in your class.
};

Now it can be used:

Root    json("file.name");
Json::Value = json["query"]["results"]["rate"];


Remote control: receiving the command I want to create a web app that should let users remotely make a device do a variety of things simply using any other device, anywhere, without installing anything. To do that, the device which performs tasks should receive commands as fast as possible, and, possibly, using few Internet data.

This is the code I'm going to use to receive the commands. Obviously, a login system still needs to be implemented.

index.php (the device which receives commands must keep it opened in the web browser)

<?php
$lastModified=filemtime(__FILE__);
$etagFile = md5_file(__FILE__);
$ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false);
$etagHeader=(isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
header("Etag: $etagFile");
header('Cache-Control: public');
if (strtotime($ifModifiedSince)==$lastModified || $etagHeader == $etagFile){
    header("HTTP/1.1 304 Not Modified");
    exit;
}
else{
?>
<!DOCTYPE html>
<html>
<head>
<script>
function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
 if (window.ActiveXObject){
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
   }
  }
 }
 else if (window.XMLHttpRequest)
  return new XMLHttpRequest()
 else
  return false
}
</script>
<style>
body{
    font-family:Arial,Verdana,Geneva;
}
</style>
<title>Remote control</title>
</head>
<body>
<div id="content">
Hey there! It seems that you turned Javascript off. Turn it back on in order to make this site work.
</div>
<script>
function carica(){
    document.getElementById("content").innerHTML="I\'m ready to receive remote commands"
    var request=new ajaxRequest()
    request.onreadystatechange=function(){
     if (request.readyState==4){
      if (request.status==200 || window.location.href.indexOf("http")==-1){
       document.getElementById("content").innerHTML=request.responseText
      }
      else if(request.status==204){
          carica()
      }
      else{
       document.getElementById("content").innerHTML='An error occurred!';
      }
     }
    }
    request.open("GET", "content.php", true)
    request.send()
}
carica();
</script>
</body>
</html>
<?php
}
?>

content.php

<?php
$maximumAttempts = 30;
$sleepTime = 10;
$totalTime = $maximumAttempts * $sleepTime;
ini_set('max_execution_time', $totalTime);
for($i=1;$i<$maximumAttempts;$i++){
    if(file_exists("command.txt")){ //a different check will be performed once the login system will be implemented
        echo 'New command for this device received!'; //commands still need to be implemented
        $commandReceived = 1;
        break;
    }
    else{
        sleep($sleepTime);
    }
}
$commandReceived = isset($commandReceived) ? $commandReceived : 0;
if($commandReceived!=1){
    http_response_code(204);
}
?>

Is this method to receive commands good? Does it overload the server? Is it fast enough for the client?

it's a bit hard to comment on your question as it's really very general.
You say that the device should receive commands as fast as possible and with very few data and than you ask "Does it overload the server? Is it fast enough for the client?", but you don't mention what kind of operations would be actually performed and in what way. The process of receiving and parsing command is usually much faster than the process of executing parsed command.

As for the code itself, the client side looks a bit like reinventing the wheel - why don't you try jQuery?
As for the server code (content.php), it's hard to tell what it does other than it obviously tries to read a file from disk serveral times, but even if succeeds - it still does nothing...

Maybe if you'd ask more specific questions, I could be more of a help.


Project Euler #3 In C++ The question for reference:

  The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143?
  answer: 6857

I'm looking for general feedback as to style and particularly usage of the STL.  Efficiency is a concern but a simple link to a better algorithm will suffice.

#include <list>
#include <algorithm>
#include <iostream>

template <class T>
std::list<T> TrialFactorization(T n) {
    std::list<T> base_factors;
    if(n == 1 || n == 2)
        base_factors.push_back(n);
    for(T p = 2; p < n; ++p) {
        while(n % p == 0) {
            n /= p;    // <~~ Shortens outer for-loop.
            base_factors.push_back(p);
        }
    }
    if(n != 1)
        base_factors.push_back(n);
    return base_factors;
}

int main() {
    typedef long long my_type;
    my_type my_int = 600851475143LL;
    std::list<my_type> my_base_factors = TrialFactorization<my_type>(my_int);
    // std::cout << *std::max_element(my_base_factors.begin(), my_base_factors.end());
    // Exploit sorted.
    std::cout << (* --my_base_factors.end());
}

You can improve the performance of the inner divisibility test by using std::div to do the division and modulo operations in one step. The following should work:

    for (;;) {
        auto r = std::div(n, p);
        if (r.rem != 0) {
            break;
        }
        n = r.quot;
        base_factors.push_back(p);
    }

The return value of std::div is a type such as std::lldiv_t (the exact return type ultimately depends on the template type parameter T).