texts:
Just wondering how my code looks, consider it a "professors input" since I'm not taking classes this semester. Also I'd like to note that this will soon be transitioning to a database approach where I use a MySQL database to get the InventoryItems.
Inventory.h
#pragma once

#include <vector>
#include <iostream>

#include "InventoryItems.h"

class Inventory
{
public:
    Inventory();
    ~Inventory();

    void createNewInventoryItem(std::string itemName = "", unsigned int maxQuantity = 0, unsigned int orderThreshold = 0,
                                                                         double price = 0.0, int quantityInInventory = 0);
    void deleteInventoryItem(int posInVector);
    InventoryItems* getItem(int posInVector);
private:
    std::vector<InventoryItems*> m_inventory; //NOTE: does not use a smart pointer, instead the pointer is deleted from the heap in the deleteInventoryItem function
                                              //      if deleteInventoryItem is not called at the end of the inventory objects life cycle the inventory objects deconstructor will
                                              //      loop through all elements in m_inventory and call deleteInventoryItem for each item
};

Inventory.cpp
#include "Inventory.h"

Inventory::Inventory()
{
    std::cout << "Inventory created" << std::endl;
}

Inventory::~Inventory()
{
    for (int i = 0; i < m_inventory.size(); i++) {
        deleteInventoryItem(i);
    }
    std::cout << "Inventory destroyed" << std::endl;
}

void Inventory::createNewInventoryItem(std::string itemName, unsigned int maxQuantity, unsigned int orderThreshold,
                                                                             double price, int quantityInInventory)
{
    InventoryItems* newItem = new InventoryItems;
    newItem->createInventoryItem(itemName, maxQuantity, orderThreshold, price, quantityInInventory);
    m_inventory.emplace_back(newItem);
}

void Inventory::deleteInventoryItem(int posInVector)
{
    delete m_inventory.at(posInVector);
    m_inventory.erase(m_inventory.begin() + posInVector);
}

InventoryItems* Inventory::getItem(int posInVector)
{
    return m_inventory.at(posInVector);
}

The inventory class will really come into it's own, this is just a proof of concept before I incorporate my database (I.E. inventoryItems is acting as a place holder for the DB and queries, hence me not including it here).


texts: jQuery functions to add corresponding entries of lists

texts:
Thanks to this post, I was able to create a working piece of javascript that fits my needs. I have a div/ul/li based table where each "row" has 2 values that I want to have the sum for. Currently the code does exactly what I want, but somehow I have the feeling that the javascript is not coded in the most efficient way since I am repeating a lot of code. Any suggestions?

$(calculateSum1);
 function calculateSum1() {
 var sum1 = 0;
 // searching li for equal class and add the values
 $(".pr1").each(function() {
    var value = $(this).text();
    // add only if the value is number
    if(!isNaN(value) && value.length != 0) {
        sum1 += parseFloat(value);
    }
});
 $('#result1').text(sum1);
};

$(calculateSum2);
 function calculateSum2() {
 var sum2 = 0;
 // searching li for equal class and add the values
 $(".pr2").each(function() {
    var value = $(this).text();
    // add only if the value is number
    if(!isNaN(value) && value.length != 0) {
        sum2 += parseFloat(value);
    }
});
 $('#result2').text(sum2);
};

$(calculateSum3);
 function calculateSum3() {
 var sum3 = 0;
 // searching li for equal class and add the values
 $(".pr3").each(function() {
    var value = $(this).text();
    // add only if the value is number
    if(!isNaN(value) && value.length != 0) {
        sum3 += parseFloat(value);
    }
});
 $('#result3').text(sum3);
};

$(calculateSum4);
 function calculateSum4() {
 var sum4 = 0;
 // searching li for equal class and add the values
 $(".pr4").each(function() {
    var value = $(this).text();
    // add only if the value is number
    if(!isNaN(value) && value.length != 0) {
        sum4 += parseFloat(value);
    }
});
 $('#result4').text(sum4);
};
div.col, div.price {float:left}
div.col {width:25%;margin;none;}
ul {list-style-type: none;margin:0;}

Price

150

199

249

299

+

+

+

+

+

Add costs

27

20

30

39

=

=

=

=

=

Totaal


texts: Throwing exceptions if there is not exactly one box retrieved

texts:
(Note: this is originally posted as this SO question  )

I'm trying to refactor the error logging and exception throwing into a method.

Original code:

private Box retrieveBox() {
    BoxParameter param = new BoxParameter("red", 10, 5, 3);
    List<Long> boxIds = boxDao.retrieveByParameter(param);

    if (boxIds.isEmpty()) {
        // A
        logger.warn("box not found");
        throw new BoxNotFoundException();
    }
    if (boxIds.size() > 1) {
        // B
        logger.warn("multiple boxes found");
        throw new MultipleBoxesFoundException();
    }

    Optional<Box> maybe = boxDao.retrieve(boxIds.get(0));
    if (maybe.isPresent()) {
        return maybe.get();
    }

    // C
    logger.warn("box not found");
    throw new BoxNotFoundException();
}

Refactored code:

private Box retrieveBox() {
    BoxParameter param = new BoxParameter("red", 10, 5, 3);
    List<Long> boxIds = boxDao.retrieveByParameter(param);

    if (boxIds.isEmpty()) {
        // A
        logErrorAndThrowBoxNotFoundException();
    }
    if (boxIds.size() > 1) {
        // B
        logErrorAndThrowMultipleBoxesFoundException();
    }

    Long boxId = boxIds.get(0);
    Optional<Box> maybe = boxDao.retrieve(boxIds.get(0));
    if (maybe.isPresent()) {
        return maybe.get();
    }

    // C-1
//  logger.warn("box not found");
//  throw new BoxNotFoundException();

    // C-2
    logErrorAndThrowBoxNotFoundException();
    return null;  // needs to be here to make it compile
}

private void logWarningAndThrowMultipleBoxesFoundException() throws MultipleBoxesFoundException {
    logger.warn("multiple boxes found");
    throw new MultipleBoxesFoundException();
}

private void logWarningAndThrowBoxNotFoundException() throws BoxNotFoundException {
    logger.warn("box not found");
    throw new BoxNotFoundException();
}

I really dislike the return null part in C-2, but without it, I'll have to go back to C-1, which defeats the purpose of refactoring.

Is there a better way to do it?


texts: Network MAC address conversion to IPv6 link-local address

texts:
One of the ways I learn a new scripting language is to implement a subroutine to convert a network MAC addr into the IPv6 link-local address, as described in RFC 4862. So here is a quick few lines.

My question to you is:

can this code be shrunk any more?
is there a more pythonic way of doing this?
is there anything non-optimal?
is the code future proof to 3.4 python?

Especially with casting a string to an int, and finally back to hex, seems overly weird.

Also, I did recently discover some IP related factory functions, but so far I've not discovered any builtin way of doing this. I'm using python 2.7, but my Linux distro is soon to switch to 3.x.

#!/usr/bin/python
"""
convert mac addr to ipv6 link local (rfc 4862)
"""

# the mac should become: fe80::2177:02ff:fed2:ff9b
mac='23:77:02:d2:ff:9b'

def mac_to_ipv6_linklocal(mac):

  # remove the most common macaddr delimiters, dots, dashes, etc.
  # cast the hex string to an base-16 int for math safety.
  # use xor of 02 on the 2nd most significant hex char.
  # Remove/slice the '0x' off the begining from using hex().

  m = hex(int(mac.translate(None,' .:-'),16)^0x020000000000)[2:]
  return 'fe80::%s:%sff:fe%s:%s' %(m[:4],m[4:6],m[6:8],m[8:12])

print mac_to_ipv6_linklocal(mac)


texts:
I'm writing a code generation library, I've exposed a couple of methods and of course in order to define a member you need to specify it's type, the easiest way is to use typeof(Type), which I later format so that it it's compilable and I can insert it as a code chunk e.g. System.Int32, which for non-generic types is basically concatenating the namespace and the type's name.

That works fine but generic types have the backtick followed by the number of arguments, so I needed a method to format all the types, so that they are always compilable e.g. System.Collection.Generics.List<System.Int32>.

public static class TypeExtensions
{
    public static string FormatTypeName(this Type type)
    {
        if(type == null) { throw new ArgumentNullException(nameof(type)); }

        if (type.IsGenericType)
        {
            var definedArguments = type.GetGenericArguments();
            var genericIdentifier = $"`{definedArguments.Length}";

            if (definedArguments.First().FullName == null)
            {
                var genericBraces = "<".PadRight(definedArguments.Length, ',') + ">";
                return $"{type.Namespace}.{type.Name.Replace(genericIdentifier, genericBraces)}";
            }

            var formattedTypes = definedArguments.Select(definedArgument => definedArgument.FormatTypeName());

            var newGenericArguments = $"<{string.Join(", ", formattedTypes)}>";
            return $"{type.Namespace}.{type.Name.Replace(genericIdentifier, newGenericArguments, StringComparison.InvariantCultureIgnoreCase)}";
        }

        return $"{type.Namespace}.{type.Name}";
    }
}

It supports indefinite amount of nested and linear generic arguments due to the recursion that is in-place.

The way it works is pretty straight forward, there are 2 possible incomes, we have no arguments defined e.g. typeof(Dictionary<,>) or all of the arguments are defined e.g typeof(Dictionary<int, int>).

Since the C# compiler doesn't allow partially defined arguments we can simply check if the first of the arguments has a FullName (note that Name is the name pf the generic argument not the type behind it), if it does we simply concatenate all of the arguments and surround them by <>. if the first argument doesn't have value then it's empty and we just leave the braces with commas separating the arguments.

Since this will be used in a code generation tool, performance is not crucial, but always welcome as long as it doesn't damage the readability and maintainability of the code, which I consider more important in this case.

However since it will be used in a code generation tool, I'm more worried about whether I've missed some edge cases.


texts: Angular - reusing an observable for different queries

texts:
This is just a dummy example, but in my real world application I get a lot of data from the web API and I'd like to manipulate it on the client's side. So, I kind of stored the observable I get from the HTTP request locally and change the values with map:

@Injectable()
export class UsersApiService {

  private readonly baseUrl: string = 'https://reqres.in/api/users';
  resource$: Observable<any>;

  constructor(private http: HttpClient) {
    this.resource$ = this.http.get<IUserDetails[]>(this.baseUrl).pipe(
      tap((data) => {
        console.log('"getUsers" successfully called!');
      }),
      map((data: any) => {
        return data.data;
      })
    ).publishReplay(1).refCount();
  }

  getUsers(): Observable<IUser[]> {
    return this.resource$.pipe(
      map((data: IUserDetails[]) => {
        return <IUser[]>data.map((u) => {
          return {
            id: u.id,
            name: `${u.first_name} ${u.last_name}`
          };
        });
      })
    );
  }

  getUserById(id: number): Observable<IUserDetails> {
    return this.resource$.pipe(
      map((data) => {
        return <IUserDetails>data.find(x => x.id === id);
      })
    );
  }

}

Here's an example plunker

Is this the correct approach at reusing an observable? What would be better? Am I creating any memory leaks and what are the general drawbacks of my approach? Thanks!


texts:
Question-

Generate all prime numbers between two given numbers.

https://www.spoj.com/problems/PRIME1/

My attempt-

I used segmented sieve method.

t=int(input())
import math
def segsieve(x):
    if x==1:
        return False
    for i in range(2,int(math.sqrt(x))+1):
        if x%i==0:
            return False
    return True

while t>0:
    f,l=map(int,input().split())
    for j in range(f,l):
        a=segsieve(j)
        if a==True:
            print(j)
    t-=1

Issue-

I am getting time limit exceeded. How can I make it faster?


texts: Can this iterating javascript code be optimized?

texts:
Say I have this type of code I'd like to execute. There's some data encapsulated around a big Javascript object containing methods & properties that I'd like to extract based on comparing some other data in said object. The object includes associative (hash?) arrays where I don't know the array IDs at runtime so I have to do some iteration, this is the working code structure I came up with. But it's bloated and a bit messy to read. Was wondering it it can be optimized for efficiency and readability in general, to minimize iteration and conside the length of the object referencing.

I execute this code from Firebug console (or via Selenium WebDriver's execute javascript command, in which case console.log become "return" to return the desired value).

for(x in MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry){
    if (MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry[x].someObj.displayName == 'some value')
        console.log(MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry[x].someObj.someId);
}


texts: Creating an 2D array using pointer/malloc, and then print it out

texts:
I am trying to write 2 functions, one to read the matrix (2D array) and other one to print it out. So far I have:

/* Read a matrix: allocate space, read elements, return pointer. The
   number of rows and columns are given by the two arguments. */
double **read_matrix(int rows, int cols){

    double **mat = (double **) malloc(sizeof(double *)*rows);
    int i=0;
    for(i=0; i<rows; i++){
    /* Allocate array, store pointer  */
    mat[i] = (double *) malloc(sizeof(double)*cols);
   //what to do after??

     return mat;
}

then the print matrix function, not sure if it is correct

 void print_matrix(int rows, int cols, double **mat){
  for(i=0; i<rows; i++){    /* Iterate of each row */
    for(j=0; j<cols; j++){  /* In each row, go over each col element  */
    printf("%f ",mat[i][j]); /* Print each row element */
}
}}

and here is the main function I am using to run:

#include <stdio.h>
#include <stdlib.h>

double **read_matrix(int rows, int cols);
void print_matrix(int rows, int cols, double **mat);
void free_matrix(int rows, double **mat);

int main(){

  double **matrix;
  int rows, cols;
  /* First matrix */
  printf("Matrix 1\n");
  printf("Enter # of rows and cols: ");
  scanf("%d %d",&rows,&cols);
  printf("Matrix, enter %d reals: ",rows*cols);
  matrix = read_matrix(rows,cols);
  printf("Your Matrix\n");  /* Print the entered data */
  print_matrix(rows,cols,matrix);
  free_matrix(rows, matrix);   /* Free the matrix */

    return 0;}


texts:
I have a method, which outputs multiplication table sized by given maximum number. Also, it visually separates first row and column from the rest table. How my code could be improved or optimized?

public class Example {
    public static void main(String args[]) {
        printMultiplicationTable(15);
    }

    private static void printMultiplicationTable(int max) {
        for (var row = 1; row <= max; row += 1) {
            if (row == 2) {
                for (var column = 2; column <= max; column += 1) {
                    System.out.print("----");
                }
                System.out.println();
                continue;
            }

            for (var column = 1; column <= max; column += 1) {
                int result = row * column;

                if (column == 1) {
                    if (row < 10) {
                        System.out.print(result + " |\t");
                    } else {
                        System.out.print(result + "|\t");
                    }

                } else {
                    System.out.print(result + "\t");
                }
            }

            System.out.println();
        }
    }
}


texts: Manipulating the global address book in Outlook

texts:
I am using VBA to manipulate the global address book in Outlook.  My method takes a contact and returns a complete list of everyone who reports through that person based on the Outlook org structure.

Unfortunately it takes quite some time to run, even for a single manager.  I'm not really sure what is the best way to improve the performance here - it sees the getDirectReports method takes some time, but, I don't see an easy way to determine if a user has reports prior to calling it first.

Public Sub printAllReports()

    Dim allReports As Collection
    Set allReports = New Collection

    Dim curLevelReports As Collection
    Set curLevelReports = New Collection

    Dim nextLevelReports As Collection
    Set nextLevelReports = New Collection

    Dim myTopLevelReport As ExchangeUser

    'this method returns an exchange user from their "outlook name"
    Set myTopLevelReport = getExchangeUserFromString("outlook resolvable name here")

    'add to both the next level of reports as well as all reports
    allReports.Add myTopLevelReport
    curLevelReports.Add myTopLevelReport

    Dim tempAddressEntries As AddressEntries
    Dim newExUser As ExchangeUser
    Dim i, j As Integer

    'flag for when another sublevel is found
    Dim keepLooping As Boolean
    keepLooping = False

    Dim requireValidUser As Boolean
    requireValidUser = False

    'this is where the fun begins
    Do

        'get current reports for the current level
        For i = curLevelReports.Count To 1 Step -1

            Set tempAddressEntries = curLevelReports.item(i).GetDirectReports

            'add all reports (note .Count returns 0 on an empty collection)
            For j = 1 To tempAddressEntries.Count
                Set newExUser = tempAddressEntries.item(j).getExchangeUser

                'isExchangeUserActualEmployee has some short boolean heuristics to make sure
                'the user has at least a title and an email address
                If (isExchangeUserActualEmployee(newExUser) = True Or requireValidUser = False) Then
                    allReports.Add newExUser
                    nextLevelReports.Add newExUser
                    keepLooping = True
                End If

            Next j
            Set tempAddressEntries = Nothing

        Next i

        'reset for next iteration
        Set curLevelReports = nextLevelReports
        Set nextLevelReports = New Collection

        'no more levels to keep going
        If keepLooping = False Then
            Exit Do
        End If

        'reset flag for next iteration
        keepLooping = False

    Loop

    Dim oMail As Outlook.MailItem
    Set oMail = Application.CreateItem(olMailItem)

    'do stuff with this information (currently just write to new email, could do other cool stuff)
    For i = 1 To allReports.Count
        oMail.Body = oMail.Body + allReports.item(i).name + ";" + allReports.item(i).JobTitle
    Next i

    oMail.Display

End Sub


texts: Comparing strings with contents of columns

texts:
I wrote the following lines of code to compare some strings with contents of columns (string) in SQLite database:

void PaymentTransaction::setAttributesBySqliteStmt(sqlite3_stmt * statement)
{
    ZF_LOGD("setAttributesBySqliteStmt\n");
    int columnCnt = sqlite3_column_count(statement);
    for (int i = 0; i < columnCnt; i++) {
        if (strcmp("id", sqlite3_column_name(statement, i)) == 0)
            id = sqlite3_column_int(statement, i);
        else if (strcmp("gas_station_id", sqlite3_column_name(statement, i)) == 0)
            gas_station_id = sqlite3_column_int(statement, i);
        else if (strcmp("nozzle_id", sqlite3_column_name(statement, i)) == 0)
            nozzle_id = sqlite3_column_int(statement, i);
            ................
            //SAME CODES FOR OTHER COLUMNS
            ................
            else {
        ZF_LOGW("Invalid column name(%s) in table name Transaction",
                sqlite3_column_name(statement, i));
           }
      }
  }

   void PaymentTransaction::bindValueToSqliteStmt(sqlite3_stmt* statement)
   {
int paramCnt = sqlite3_bind_parameter_count(statement);
for (int i = 1; i <= paramCnt; i++) {
    if (i == sqlite3_bind_parameter_index(statement, "@id"))
        sqlite3_bind_int(statement, i, id);
    else if (i == sqlite3_bind_parameter_index(statement, "@gas_station_id"))
        sqlite3_bind_int(statement, i, gas_station_id);
    else if (i == sqlite3_bind_parameter_index(statement, "@nozzle_id"))
        sqlite3_bind_int(statement, i, nozzle_id);
    else if ............
     //SAME CODES FOR OTHER COLUMNS
     ..................
     else {
        ZF_LOGW("Invalid param name(%s) in table name Transaction",
                sqlite3_bind_parameter_name(statement, i));
     }
  }
}

Since there are 30 columns in total, there are lots of if else statements and I was wondering whether there is better/shorter way of writing these lines of code?


texts: Analysis of the most common words in a text

texts:
I have been trying to gain more understanding and experience in the NPL area and to get some more practice. I decided to attempt to create a simple high-level analysis program.

Here's what I'm trying to do:

Add a function that allows me to read in a full document (wordpad) instead of Console.Readline(); with CMD input
Improve organization, cleaner, or shorter code
Count words

The Code:

namespace HOMEWORK
{
    class Program
    {
        static void Main(string[] args) //2 foreach() 2 for() 4 if() 28 .methods//
        {
            LinkedList<MatchCounter> matchCounters = new LinkedList<MatchCounter>();
            string[] currentPats = new[] { "the", "in" };
            StringBuilder SB = new StringBuilder();

            for (int i = 0; i < currentPats.Length; i++)
            {
                SB.Append(@"(?=(?<p").Append(i).Append(">").Append(currentPats[i]).Append("))?");
            }

            Regex regexx = new Regex(SB.ToString(), RegexOptions.Compiled);
            Console.WriteLine("CURRENT PATTERN: {0}", regexx);

            string input = Console.ReadLine();
            Console.WriteLine("input: {0} ", input);

            foreach (Match match in regexx.Matches(input).Cast<Match>())
            {
                ;
                for (var i = 0; i < currentPats.Length; i++)
                {
                    Group group = match.Groups["p" + i];

                    if (!group.Success)
                        continue;

                    if (group.Value != "")
                    {
                        bool isFound = false;

                        foreach (MatchCounter copy in matchCounters)
                        {
                            if (copy.GetSyllable() == group.Value)
                            {
                                copy.Increment();
                                isFound = true;
                                break;
                            }
                        }

                        if (!isFound)
                            matchCounters.AddLast(new MatchCounter(group.Value));
                    }

                    Console.WriteLine("Matched pattern #{0}: '{1}' at index {2}", i, group.Value, group.Index);
                }
            }

            Console.ReadKey();
        }
    }

    public class MatchCounter
    {
        int count;
        string syllable;

        public MatchCounter(string Syl)
        {
            count = 1;
            syllable = Syl;
        }

        public string GetSyllable()
        {
            return syllable;
        }

        public void Increment()
        {
            count++;
        }

        public int GetCount()
        {
            return count;
        }
    }
}

I am still a learner and would like my code to be reviewed with feedback. I would greatly appreciate any feedback about the code quality, performance or any other possible corrections or how to do things differently.


texts: Perl script to rename multiple files with vi(m)

texts:
I'm new to Perl, learning on my own. I've wrote many scripts (utilities) for myself but never posted them online. I would really appreciate any feedback on this script before I post it on a forum.

The script takes list of files names on command line, writes the name list in tmp file and opens it with vi(m). After user is done renaming, it reads new names from tmp file and renames files accordingly. Script can also process symlinks, where it lists and renames the target file name and also updates the symlink to point to renamed file afterwards.

#!/usr/bin/perl -w
use strict;
use Getopt::Std;
use File::Temp qw( tempfile );
use File::Basename qw( basename dirname );

# HANDLING CMD ARGS
$Getopt::Std::STANDARD_HELP_VERSION = 1;
my $usage = \&main::HELP_MESSAGE;
my %opts;

sub main::VERSION_MESSAGE {
    print "virename v0.1\n";
}

sub main::HELP_MESSAGE {
    print << "EOF";
Usage:\n virename [OPTIONS] [file_names]

OPTIONS
 -s                act on symlink target (also update symlink)
 -v                be verbose
 --help            pirnt help and exit
 --version         version
EOF
}

if (@ARGV) {
    getopts( 'vs', \%opts ) or $usage->();
}
else {
    print "Not enough arguments!\n\n";
    $usage->();
    exit 1;
}

my ( @names, @new_names, %symlinks );

if ( $opts{s} ) {
    for my $name (@ARGV) {
        if ( my $target = readlink $name ) {
            my $target_name = basename $target;
            $symlinks{$target_name} = { 'symlink', $name, 'target', $target };
            push @names, $target_name;
        }
        else {
            push @names, $name;
        }
    }
}
else {
    @names = @ARGV;
}

die "Nothing to rename!\n" unless @names;

my ( $tmp, $tmp_name ) = tempfile();    # Tmp file

print {$tmp} join "\n", @names;         # Writing names to tmp file
if ( !system "vim $tmp_name 2>/dev/null" ) {
}
elsif ( !system 'vi', $tmp_name ) {
}
else { exit; }

seek $tmp, 0, 0;
chomp( @new_names = <$tmp> );           # Reading new names from tmp file

unlink $tmp_name;                       # Removing tmp file

exit if @names != @new_names;

#Renaming
for ( 0 .. $#names ) {
    my ( $new_name, $old_name );
    my $is_symlink = exists $symlinks{ $names[$_] };
    if ( $opts{s} && $is_symlink ) {
        $old_name = $symlinks{ $names[$_] }->{target};
        $new_name = dirname($old_name) . q{/} . $new_names[$_];
    }
    else {
        $old_name = $names[$_];
        $new_name = $new_names[$_];
    }

    if ( -e $new_name ) {    #Skip if file already exists
        print "'$new_name' already exits!\n" if $opts{v};
    }
    elsif ( rename $old_name => $new_name ) {
        if ( $opts{s} && $is_symlink ) {
            my $symlink = $symlinks{ $names[$_] }->{symlink};
            unlink $symlink;    # Removing old symlink
            symlink $new_name => $symlink    # Creating new symlink
              or warn "symlink: $!\n";
            print "'$symlink': '$old_name' => '$new_name'" if $opts{v};
        }
        else {
            print "'$old_name' => '$new_name'\n" if $opts{v};
        }
    }
    else {
        warn "failed to rename $old_name to $new_name: $!\n";
    }
}
__END__


texts:
My code below ensures that only land animals can be a "representatives" for Land while only ocean animals can be representatives for Ocean, and so forth for Air, Underground, etc...  Just want some feedback about whether this system I've come up with is any good or if there is a better one.  Note:  I'm using structs instead of classes to keep it simple.

#include <iostream>
#include <list>

struct IAnimal { virtual ~IAnimal() = default; };

template <typename T>
struct Animal : virtual IAnimal {};  // Animal<T> can only be pair with T, where T is derived from Place.

struct Place {
    IAnimal* representative;
    virtual bool setRepresentative (IAnimal* a) {
        representative = a;  std::cout << "Done.\n";  return true;
    }
    virtual bool canUse (const IAnimal*) const = 0;
};

template <typename Derived>
struct PlaceCRTP : Place {
    virtual bool setRepresentative (IAnimal* a) override {
        if (canUse(a))
            return Place::setRepresentative(a);
        std::cout << "Cannot be done.\n";
        return false;
    }
    virtual bool canUse (const IAnimal* a) const override {
        return dynamic_cast<const Animal<Derived>*>(a) != nullptr;
    }
};

struct Land : PlaceCRTP<Land> {};
struct Ocean : PlaceCRTP<Ocean> {};

struct Elephant : Animal<Land> {};
struct Moose : Animal<Land> {};
struct Deer : Animal<Land> {};
struct Whale : Animal<Ocean> {};
struct Shark : Animal<Ocean> {};
struct Crab : Animal<Ocean>, Animal<Land> {};  // Note: Crab can represent Ocean or Land!

int main() {
    Land land;
    Elephant elephant;
    Whale whale;
    land.setRepresentative(&elephant);  // Done.
    land.setRepresentative(&whale);  // Cannot be done.

    std::list<IAnimal*> allAnimals, landCandidates;
    for (int i = 0; i < 10; i++) {
        allAnimals.push_back (new Elephant);
        allAnimals.push_back (new Whale);
        allAnimals.push_back (new Moose);
        allAnimals.push_back (new Shark);
        allAnimals.push_back (new Crab);
    }
    for (IAnimal* a : allAnimals)
        if (land.canUse(a))
            landCandidates.push_back(a);
    std::cout << allAnimals.size() << std::endl;  // 50
    std::cout << landCandidates.size() << std::endl;  // 30 (10 Elephants, 10 Moose, 10 Crabs)
}

One drawback I can think of right away, is that the repeated dynamic casts cost performance, but looking up a map might be slower.


texts: Deleting millions of rows from a MSSQL server table

texts:
This SQL query took 38 minutes to delete just 10K of rows. How can I optimize it?

Index already exists for CREATEDATE from table2.

declare @tmpcount int
declare @counter int

SET @counter = 0
SET @tmpcount = 1
WHILE @counter <> @tmpcount
BEGIN
    SET ROWCOUNT 10000

    SET @counter = @counter + 1

    DELETE table1
    FROM table1
    JOIN table2
        ON table2.DOC_NUMBER = table1.DOC_NUMBER
        AND table2.DOC_YEAR = table1.DOC_YEAR
    WHERE YEAR(CREATEDDATE) BETWEEN 2007 and 2009

    IF @@ROWCOUNT = 0
        BREAK
END


texts: A background service that will wait for items to process without busy-waiting

texts:
Problem space: I have the concept of a Job that needs to be processed. Jobs need to be processed sequentially, as one may depend on another. It's possible for a Job to be paused, in which case the next Job should not be started - the Job should either be explicitly continued, or cancelled, in order to get the next one to start.
If the background service doing these Jobs finishes, it should wait for an update to a RESTful resource before trying to start processing again. I don't want the service to busy-wait.
public class ExecutionBackgroundService : BackgroundService
{
    private readonly IJob _job;
    private readonly AutoResetEvent _isRunning = new AutoResetEvent(true);

    public ExecutionBackgroundService(IJob job)
    {
        _job = job;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // Required for the method to be executed asynchronously, allowing startup to continue.
        await Task.Yield();
        while (!stoppingToken.IsCancellationRequested)
        {
            _isRunning.WaitOne(); // blocks the thread, waiting for the event to be set by something else calling the Resume method
            await _job.Process();
        }
    }

    /// <summary>
    /// Notifies the background service to resume processing.
    /// </summary>
    public void Resume()
    {
        _isRunning.Set();
    }
}

Jobs are represented by a DB entity. The IJob implementation looks something like this:
    public async Task Process()
    {
        using var scope = _serviceScopeFactory.CreateScope();
        var database = scope.ServiceProvider.GetService<MyDbContext>();
        var iterator = new DatabaseJobIterator(database);
        var worker = scope.ServiceProvider.GetService<IWorker>();
        while (iterator.HasNext())
        {
            await worker.DoLongRunningWork(iterator.Next);
        }
    }

Where the implementing class is singleton-scoped, and the DB and IWorker are both request-scoped (hence why I'm getting them using the scope factory).
DatabaseJobIterator is basically a simplified IEnumerator that just exposes two methods HasNext and Next, where HasNext will query the database for the oldest job, and assign it to Next. If the job is ready to be processed, it returns true. If the job is paused, it returns false.
An API controller that handles POSTs and PUTs to Jobs will then just call Resume on the background service, indicating that it might have new items to process if it isn't already running.
My question is whether I've used the AutoResetEvent correctly. Is there a more standard way to get the background service to wait without e.g. busy-waiting in a while (true) loop?


texts:
I shall make a JavaScript-function which does the same as PHP's array_diff:
http://php.net/manual/de/function.array-diff.php

Because it is intended to use the function as a (internal) library-function I have tried to catch everything which could possibly go wrong concerning incorrect usage.
Moreover I've tried to document the usage of the function well.

Can one expect that my algorithm works as expected?

How can I improve my documentation and value-checking further?

Should I use different error return-values to signal more precise what has gone wrong?

// ----- TESTING -------------------------------
var arr1 = [1, 3, 2, 1, 2, 7, 9, 2, 6, 5 ];
var arr2 = [1, 9, 6, 11, 0, 17, 4, 22];

var str1 = [1, 9, '6', 11, 0, 17, 4, 22];
var str2 = [1, 9, '6', 11, 'zero', 17, 4, 22];

var not = [1, 9, NaN, 11, 0, 17, 4, 22];
var flt = [1, 9, 2.68, 11, 0.32, 17, 4, 22];

var e1 = {};
var e2 = 31;

console.log(getArrayDiff(arr1, arr2));
// Array empty.
console.log(getArrayDiff([], arr2));
console.log(getArrayDiff(arr1, []));
console.log(getArrayDiff([], []));

// Wrong parameter
console.log(getArrayDiff(arr1, e2));
console.log(getArrayDiff(e1, arr2));
console.log(getArrayDiff(e1, e2));
console.log('String assigned: ', getArrayDiff(arr1, str1));
console.log('String assigned: ', getArrayDiff(str2, arr1));
console.log(getArrayDiff(not, arr1));
console.log('Float assigned: ', getArrayDiff(flt, arr1));

// ----- TESTING - END ----------------------

// The actual function
// ------------------------------------------
// Returns the numbers which are contained in
//  ONE of two arrays.

// 1. Parameter: Array with ONLY integer values.
// 2. Parameter: Array with ONLY integer values.

// Return: Array with the difference set.
//  ! Returns null in case of error.

function getArrayDiff(arr1, arr2) {
  var ret = [];
  var merged = [];
  var current;
  var i;
  var sum;
  var isArray = Array.isArray;

  if (!isArray(arr1) || !isArray(arr2))
    return null;

  if (!arr1.length && arr2.length) {
    return arr2;
  } else if (arr1.length && !arr2.length) {
    return arr1;
  } else if (!arr1.length && !arr2.length) {
    return [];
  }

  merged = arr1.concat(arr2);

  merged.sort(function(a, b) {
    return a - b;
  });

  for (i = 0; i < merged.length; i++) {
    sum = 0;

    if ( isNaN(merged[i]) ||
         typeof merged[i] !== 'number' ||
         merged[i] % 1 !== 0 )
      return null;

    if (merged[i] !== current || i === 0) {
      current = merged[i];
    } else {
      continue;
    }

    if (arr1.indexOf(current) !== -1)
      sum++;

    if (arr2.indexOf(current) !== -1)
      sum++;

    if (sum === 1)
      ret.push(current);
  };

  return ret
}


texts: Implementing a queue using a circular buffer

texts:
I'm working on implementing a queue using a circular buffer problem. Any smarter ideas for better time complexity, any code bug or code style advice are highly appreciated.

class QueueOnCirciularBuffer:
    def __init__(self, max_size):
        self.buffer = [0]*max_size
        self.index = 0 # element to write
        self.size = 0
        self.max_size = max_size
    def push_element(self, value):
        if self.size == self.max_size:
            raise Exception('queue full')
        self.buffer[self.index] = value
        self.index += 1
        self.size += 1
        self.index = self.index % self.max_size
    def pop_element(self):
        if self.size > 0:
            value = self.buffer[(self.index - self.size+self.max_size)%self.max_size]
            self.size -= 1
            return value
        else:
            raise Exception('empty queue')
    def peak_element(self):
        if self.size > 0:
            return self.buffer[(self.index-1+self.max_size)%self.max_size]
        else:
            raise Exception('empty queue')
if __name__ == "__main__":
    q = QueueOnCirciularBuffer(16)
    q.push_element(1)
    q.push_element(2)
    print q.peak_element() # output 2
    q.pop_element()
    print q.peak_element() # output 2

    q2 = QueueOnCirciularBuffer(3)
    for i in range(3):
        print i
        q2.push_element(i)
    for i in range(10):
        print q2.pop_element()
        q2.push_element(i)


texts:
I have php function that compares two different database table. Any suggestion on improving it.

     public function comparePartyTableCandidates()
   {
      $electionCandidates =  ElectionCandidate::all();
      foreach($electionCandidates as $electionCandidate )
      {
         $candidateName = $electionCandidate->CandidateFirstname. " ".$electionCandidate->CandidateLastname ;

         $result = Candidate::where('candidateName' ,'=',$candidateName )->first();

         if(empty($result))
        {

           $electionconstituency= ElectionConstituency::where('ConstituencyID', '=',$electionCandidate->ConstituencyID)->first();
           $constituency = Constituency::where('ConstituencyName', '=',strtolower($electionconstituency->ConstituencyName))->first();
            echo $electionconstituency->ConstituencyName;
            if(empty($constituency))
            {
                if((preg_match("/KINGSTON EAST & PORT ROYAL/",$electionconstituency->ConstituencyName)))
                {
                    $constituency = Constituency::where('ConstituencyName', 'like',"%"."kingston Eastern")->first();
                }
            }

           $electionparty = ElectionParty::where('PartyID', 'like', '%' . $electionCandidate->PartyID)->first();
           $politicalParty = PoliticalParty::where('partyName', 'like', '%' . $electionparty->PartyAbbr)->first();

           $candidate = new Candidate();
           $candidate->candidateName = $candidateName;
           $candidate->constituency_Id = $constituency->id;
           $candidate->party_id = $politicalParty->id;
           $candidate->save();
         }
      }
   }


texts: Process a list of instructions and output the max value reached

texts:
Inputs looks like this

b inc 5 if a > 1
a inc 1 if b < 5
c dec -10 if a >= 1
c inc -20 if c == 10

I am concerned that I need to declare __max__ as global (but not __registers__). Any other recommendation on this Python script for a beginner ?

import sys
import re

steps = 0

__registers__ = []
__max__ = None

class Instruction:
    def __init__(self, string):
        # Group 1 is the register name,
        # Group 2 is inc or dec,
        # Group 3 is the amount to increase or decrease,
        # Group 4 is the full condition
        # Group 5 is the name of register against which the condition is tested,
        # Group 6 is the operand of the condition,
        # Group 7 is the numerical value of the second term of the condition
        regex = "(\w+)\s(inc|dec)\s(-*\d+)\sif\s((\w+)\s([^\w\s]+)\s(-*\d+))"
        regex_string = re.search(regex, string)
        if regex_string:
            self.name = regex_string.group(1)
            __registers__.append(Register(self.name, 0))
            self.oper = regex_string.group(2)
            self.amount = int(regex_string.group(3))
            self.condition = regex_string.group(4)
            self.tested_register = regex_string.group(5)
            self.test_operand = regex_string.group(6)
            self.test_value = int(regex_string.group(7))

    def process_instruction(self):
        # We do the test :
        p =  str(find(self.tested_register).value)
        condition = self.condition.replace(self.tested_register, p)
        if eval(condition):
            # We apply the inc / dec amount :
            reg = find(self.name)
            # print(reg.value)
            if self.oper == "inc":
                reg.value = reg.value + self.amount
            else:
                reg.value = reg.value - self.amount
            # print(reg.value)
            global __max__
            if __max__ is None or reg.value > __max__:
                __max__ = reg.value

class Register:
    def __init__(self, name, value):
        self.name = name
        self.value = value

def find(register_name):
    for register in __registers__:
        if register.name == register_name:
            return register

def get_max():
    max = None
    for regi in __registers__:
        if max is None or regi.value > max:
            max = regi.value
    return max

def main(arguments):
    fileName = sys.argv[1]
    global instructions
    instructions = [Instruction(line.rstrip('\n')) for line in open(fileName)]
    # print(__registers__)
    # print(len(__registers__))
    global __max__
    for instru in instructions:
        instru.process_instruction()
    print(get_max())
    print(__max__)

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


texts:
The problem is (source)...

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?

This is my second attempt at the problem, and gets the correct answer in about a second. I wasn't too unhappy with that until I noticed a C# solution in the PE forum that ran in about 50ms.
Anyone able to suggest how I could improve my code, either in style or in speed?
let nthPrime n =
  let primeInner n =
    let numbers = [2..(int (sqrt (float n)))] // All ints from 2 to the square root of n
    (numbers |> Seq.filter (fun n1 -> n % n1 = 0) |> Seq.sum) = 0
  let rec nthPrimeInner target counter candidate last =
    if counter = target then last
    else if (primeInner candidate) then nthPrimeInner target (counter + 1) (candidate + 1) candidate
    else nthPrimeInner target counter (candidate + 1) last
  nthPrimeInner n 0 2 2

EDIT Following John Palmer's comment, I realised that I forgot to include my prime checking function. I've added it as an inner function in the code above.
Before I get on to caching (which is a good idea, but a second stage), I thought it might be worth trying a slightly different approach for the prime checking function. The code shown above iterates through all numbers from 2 to sqrt n, and then checks to see if the resultant sequence sums to zero. This means that for an even number, where the very first check (dividing by 2) is enough to say the number isn't prime will still result in 3..sqrt n being checked. So, I tried the following instead...
let primeInner n =
  let numbers = seq {for i in 2..(int (sqrt (float n))) -> i}
  numbers |> Seq.forall (fun n1 -> n % n1 = 0)

As far as I understand it, Seq.forall will give up as soon as it finds one element in the sequence for which the function doesn't return true. Thus, in the case of an even number, it would only need to check the very first input. This should have made the computation much faster. However, when I tried timing it by passing it a million numbers to check, it didn't make any noticeable difference. When I tried to use it in my function to answer the original question, it churned away for a long time before I stopped the execution.
Anyone able to explain this? I'm still bothered that the fairly simple C# I saw did the whole thing much faster, without any caching, etc. I'm sure F# could do the same.
EDIT The 2nd The C# code mentioned seems to have disappeared from the PE forum, but here is a very slightly modified version of it, with timing added. You can just copy this as-is into LinqPad...
void Main() {
  Stopwatch sw = new Stopwatch();
  sw.Start();
  int currentPrimePosition = 1;
  long currentPrimeCandidate = 1;
  while (currentPrimePosition < 10001) {
    currentPrimeCandidate++;
    if (IsPrime(currentPrimeCandidate)) {
      currentPrimePosition++;
    }
  }
  sw.Stop();
  Console.WriteLine($"The answer is: {currentPrimeCandidate}, in {sw.ElapsedMilliseconds}ms");
}

public static bool IsPrime(long number) {
  if (number < 2) return false;
  if (number % 2 == 0) return false;
  long boundary = (long)System.Math.Floor(System.Math.Sqrt(number));
  for (long i = 3; i <= boundary; i += 2) {
    if (number % i == 0) return false;
  }
  return true;
}

This runs in about 20ms in my machine, which is still about 10 times faster than the best F# I have (using Veedrac's suggestions lower down).


texts:
I'm new to Java and I want to know if this code is efficient, and if there a shorter and faster way to reverse a string.

package Excercises;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Please enter a string you want to reverse: ");
        String text = scan.next();
        String[] letters = text.split("");
        char[] reversed = new char[letters.length];
        int c = letters.length - 1;
        for(String s : letters) {
            reversed[c] = s.charAt(0);
            c = c - 1;
        }

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


texts:
I wrote a C++ function to calculate the binomial coefficient, trying to avoid overflows as much as possible.

/*!
 * @brief Calculates the binomial coefficient indexed by n and k
 *
 * This implementation is based on the algorithm described here: http://blog.plover.com/math/choose.html
 * and the relevant follow-up: http://blog.plover.com/math/choose-2.html
 *
 * @param n                     The number of elements
 * @param k                     The number of elements in each subset
 * @return                      The number of k-element subsets in a n-element set
 *
 * @throw std::overflow_error   If the computation caused an overflow
 */
uint64_t binomial_coefficient(uint64_t n, uint64_t k)
{
    if (k > n)
        return 0;

    if (n - k < k)
        k = n - k;

    uint64_t r = 1;

    for (uint64_t d = 1; d <= k; d++)
    {
        uint64_t mult = n;

        bool divided = true;

        if (mult % d == 0)
            mult /= d;
        else if (r % d == 0)
            r /= d;
        else
            divided = false;

        const uint64_t r_mult = r * mult;
        if (r_mult / mult != r)
            throw std::overflow_error("Overflow");

        r = r_mult;

        if (!divided)
            r /= d;

        n--;
    }

    return r;
}

I have implemented the algorithm described here with a slight modification (try to divide n or r by d before multiplying n by r) as described in the article follow-up.

I also added an overflow check, which I believe should be reliable, as unsigned arithmetic overflow should not yield undefined behaviour.

Do you see any blatant or subtle bug in my implementation, and/or any room for improvement (besides lookup tables for common values and alike, which I am not willing to pursue at the moment)?


texts: Binary Search Tree implementation using templates

texts:
I wrote this implementation using templates. It works fine and as expected. Just want to know if this can be improved. I have some specific questions too at the end. Please feel free to critique to your heart's content.

#include <iostream>

template <class T>
class Tree
{
    // Internal class which stores only Node related information.
    struct TreeNode
    {
        T data;
        TreeNode * left;
        TreeNode * right;

        TreeNode(T val):data(val),left(NULL),right(NULL)
        {
        }
    };
    TreeNode * root;
    void print(TreeNode*);
    void freeMemory(TreeNode*);

public:
    Tree();
    ~Tree();
    void insert(T);
    void print();
};

template <class T>
Tree<T>::Tree():root(NULL){}

template <class T>
Tree<T>::~Tree()
{
    freeMemory(root);
}

template <class T>
void Tree<T>::freeMemory(Tree::TreeNode *node)
{
    if (node==NULL)
        return;
    if (node->left)
        freeMemory(node->left);
    if (root->right)
        freeMemory(node->right);
    delete node;
}

template <class T>
//make it return value?
void Tree<T>::insert(T val)
{
    TreeNode * treeNode = NULL;
    try
    {
        treeNode = new TreeNode(val); // handle exception necessary?
    } catch (std::bad_alloc &exception)
    {
        std::cerr << "bad_alloc caught: " << exception.what() << std::endl;
        EXIT_FAILURE;
    }
    TreeNode *temp=NULL;
    TreeNode *prev=NULL;

    temp = root;
    while(temp)
    {
        prev = temp;
        if (temp->data < treeNode->data)
            temp = temp->right;
        else
            temp = temp->left;
    }
    if (prev==NULL)
        root = treeNode;
    else
    {
        if (prev->data<treeNode->data)
            prev->right = treeNode;  // use setter function?
        else
            prev->left = treeNode;
    }
}

template <class T>
void Tree<T>::print(TreeNode *root)
{
    if (root==NULL)
        return ;
    print(root->left);
    std::cout << root->data << std::endl;
    print(root->right);
}

template <class T>
void Tree<T>::print()
{
    print(root);
}

int main()
{
    Tree<int> tree;
    tree.insert(14);
    tree.insert(12);
    tree.insert(6);
    tree.insert(17);
    tree.insert(8);
    tree.print();

}

Should I handle possible exceptions that can be thrown from new?
Is it good practice to have a TreeNode class as I've used?  If not, how to make it better?
Should my insert return some value to indicate if insertion was successful?
Any other comments/suggestions?


texts:
I've created a scenario below, in which a user can build a pizza and choose their toppings, then order their pizza:

require 'active_record'
require 'logger'

ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Base.logger = Logger.new $stdout
ActiveSupport::LogSubscriber.colorize_logging = false

ActiveRecord::Schema.define do
  self.verbose = false

  create_table :pizzas do |t|
    t.string :name
  end

  create_table :pizzas_toppings_groups do |t|
    t.integer :pizza_id
    t.integer :toppings_group_id
  end

  create_table :toppings_groups do |t|
    t.string :name
    t.integer :user_id
  end

  create_table :toppings do |t|
    t.integer :toppings_group_id
    t.string :name
  end

  create_table :orders do |t|
    t.integer :user_id
  end

  create_table :ordered_pizzas do |t|
    t.integer :order_id
    t.string :name
  end

  create_table :ordered_pizza_toppings do |t|
    t.integer :ordered_pizza_id
    t.integer :topping_id
  end
end

class Pizza < ActiveRecord::Base
  has_many :pizzas_toppings_groups
  has_many :toppings_groups, through: :pizzas_toppings_groups
  has_many :toppings, through: :toppings_groups
end

class PizzasToppingsGroup < ActiveRecord::Base
  belongs_to :pizza
  belongs_to :toppings_group
end

class ToppingsGroup < ActiveRecord::Base
  belongs_to :user
  has_many :pizzas_toppings_groups
  has_many :pizzas, through: :pizzas_toppings_groups
  has_many :toppings

  validates :name, presence: true
end

class Topping < ActiveRecord::Base
  belongs_to :toppings_group

  validates :name, presence: true
end

class Order < ActiveRecord::Base
  belongs_to :user
  has_many :ordered_pizzas
end

class OrderedPizza < ActiveRecord::Base
  belongs_to :order

  has_many :ordered_pizza_toppings
  has_many :toppings, through: :ordered_pizza_toppings
end

class OrderedPizzaTopping < ActiveRecord::Base
  belongs_to :ordered_pizza
  belongs_to :topping
end

# admin defines pizzas and available toppings groups and related toppings

cheesy_pizza = Pizza.create(name: "cheeeeeeeese")

cheap_cheesy_group = cheesy_pizza.toppings_groups.create!(name: 'basic cheeses')
mozza = cheap_cheesy_group.toppings.create!(name: 'mozzarella')

fancy_cheesy_group = cheesy_pizza.toppings_groups.create(name: 'fancy cheeses')
goat = fancy_cheesy_group.toppings.create!(name: 'goat')
cheddar = fancy_cheesy_group.toppings.create!(name: 'cheddar')

# imagine there is a fancy user interface where the user can choose
# toppings from topping groups, but certain groups
# have min/max limits on the toppings you can choose, etc etc
# for now here's a method that
# just takes in chosen toppings, and ties it to the ordered_pizza:
def create_order(pizza:, chosen_toppings:)
  Order.transaction do
    order = Order.create
    ordered_pizza = order.ordered_pizzas.create(name: pizza.name)
    ordered_pizza.toppings << chosen_toppings # imagine this line is lots of complicated validations
    order
  end
end

# user orders a pizza

jims_order = create_order(pizza: cheesy_pizza, chosen_toppings: [mozza, goat])

jims_order.reload

jims_order.ordered_pizzas

# for business reasons, some toppings are no longer available, and are removed.

mozza.destroy
goat.destroy

jims_order.reload
jims_order.ordered_pizzas.first.toppings

Historical integrity is now compromised! The toppings are missing on Jim's ordered pizza and all other ordered pizzas with those toppings.

A few questions:

Is this an ideal way to saves orders with their customized pizzas?
What's the best way to avoid this historical integrity problem?


texts: Insertion Sort Implementation Efficiency

texts:
Is my approach to insertion Sort in Python efficient?

What can be improved efficiency wise?

def insertion_sort(array):
    sorted_array = []

    for elem in array:
        insertion_index = len(sorted_array) #insert at end of list by default
        for elem_sorted in sorted_array:
            if elem_sorted > elem:
                insertion_index = sorted_array.index(elem_sorted)
                break
        sorted_array.insert(insertion_index, elem)
    return sorted_array

num_elems = int(input('Number Of Elements?: '))
array = [int(input(f'Enter Number#{i+1}: ')) for i in range(num_elems)]
a = insertion_sort(array)
print(a)


texts: Get a collection of child positions for a given parent position

texts:
I am trying to get a complete tree in a single loop using an iterative function. For instance, this is what I have:

var someVariable = GetAllChildPositions(posId) //Method called from a console method.

public ICollection<Position> GetAllChildPositions(int posId)
{
    ICollection<Position> posCollection = new Collection<Position>();
    posCollection= GetChildPos(posId,posCollection);
    return posCollection;
}

public ICollection<Position> GetChildPos(int posId, ICollection<Position> posCollection)
{
    var posObject= serviceRepo.Position.GetById(posId);
    posCollection.Add(posObject);
    if (serviceRepo.Position.GetAll().Where(x => x.ParentPosId == posId).Any())
    {
        var childPositions = serviceRepo.Position().GetAll().Where(x => x.ParentPosId == posId);
        foreach (var childPos in childPositions )
        {
            GetChildRows(childPos.Id, posCollection);
        }
    }
    return posCollection;
}

I am trying to get a list/collection child positions for a given parent position Id. This method works quite well and gets the job done albeit a little slowly. I am interested in knowing if there is a better way of doing this.


texts: Call URL x times where x is in the JSON response after the first call

texts:
I have to make an HTTP POST request by passing header and body. In the body, I need to provide a pageNumber before posting data so I am starting with "1" initially. After that I will post data and I will get a JSON response back as shown below.

{
    "response": {
        "pageNumber": 1,
        "entries": 200,
        "numberOfPages": 3
    },
    "list": [
        {
            // some stuff here
        }
    ],
    "total": 1000
}

Now in the above response numberOfPages are 3 so I need to make a total of three calls to the same URL. Since we already made 1 call I will make 2 more calls with pageNumber "2" and "3" in the body.

The logic is like this but problem here is that I don't know what is the value for numberOfPages and I get to know this value after the first call with pageNumber 1.

for(int i=1; i<=numberOfPages; i++) {
    // call getBody by passing corresponding pageNumber
    // post data with header and body

}

Below is my working code. I just need to call the same URL until numberOfPages times by just changing the body. For each call, it should be made with the corresponding pageNumber.

private void collect() {
  String endpoint = "url_endpoint";
  try {
    final URI uri = URI.create(endpoint);
    int number = 1;
    while (true) {
      HttpEntity<String> requestEntity = new HttpEntity<String>(getBody(number), getHeader());
      ResponseEntity<Stuff> responseEntity =
          HttpClient.getInstance().getClient()
              .exchange(uri, HttpMethod.POST, requestEntity, Stuff.class);
      Stuff response = responseEntity.getBody();
      // do stuff with response here.
      int expectedNumber = (int) response.getPaginationResponse().getTotalPages();
      if (number == expectedNumber || expectedNumber == 0) {
        break;
      }
      number++;
    }
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}

private String getBody(final int number) {
  Input input = new Input(entries, number, 0);
  Body body = new Body("Stuff", input);
  return gson.toJson(body);
}

Is this the right way to do it or is there any better and efficient way?


texts:
Could someone be kind enough to review this Fourier transformation, please? I'm especially interested in going about unit testing the code (I don't really know where to begin, beyond applying the fft twice to retrieve the input), and have left test functions blank.

If you do spot a bug (and no doubt there are some), please don't tell me. I'd like to find them myself.

/*
  A simple radix 2 fast fourier transform.
*/

#include <complex>
#include <iostream>
#include <cassert>
#define _USE_MATH_DEFINES
#include <cmath>

typedef std::complex<double> Complex;

void TestSpike(Complex* data, int length){
   assert( 1.0 == data[1]);
}

//Generates a spike in the DC bin, used for testing the fft
void GenerateSpike(Complex* data, int length){
  for(int i = 0 ; i < length ; i++)
    {
      if(1 == i){
        data[i] = 1.0;
      } else {
        data[i] =  0.0;
      }
    }
  TestSpike(data, length);
}

void TestTwiddle(){
}

void TestButterfly(){
}

Complex w(int bin, int length){
  return (cos(2*M_PI*bin/length), sin(2*M_PI*bin/length));
}

void butterfly(Complex* data, int bin, int stepSize, int fftlength){
  Complex x0 = data[bin];
  Complex x1 = data[bin+stepSize];

  data[bin]          = x0 + w(bin, fftlength)*x1;
  data[bin+stepSize] = x0 - w(bin, fftlength)*x1;
}

//Decimation in time
 void FFT(Complex *data, int length){
  for(int bflySize = 2 ; bflySize < length ; bflySize *= 2)
    {
      int numBflys = length/bflySize;
      for(int i = 0 ; i < numBflys ; i++)
        {
          int stepSize = bflySize/2;
            for(int j = 0 ; j < bflySize ; j+= stepSize)
            {
               butterfly(data, (bflySize*i)+j, bflySize/2, length);
            }
        }
    }
}

int Reverse(unsigned int i, int size){
  int reversed = 0;
  while(size > 1){
    reversed = (reversed >> 1) | (i & 1);
    i >>= 1;
    size >>= 1;
  }
  return reversed;
}

int main(int argv, char** argc){

  int length;
  std::cout << "Please input the length of the FFT" << std::endl;
  std::cin >> length;
  std::complex<double> data[length];
  GenerateSpike(data, length);
  FFT(data, length);
  for(int i = 0 ; i < length ; i++)
     {
       int j = Reverse(i,length);
       std::cout << data[j] << std:: endl;
     }
  return 0;
}


texts:
I have a struct which nests other structs like following:

#[derive(Debug)]
pub struct Rankings {
    conferences: Vec<Conference>,
}

#[derive(Debug)]
pub struct Conference {
    divisions: Vec<Division>,
}

#[derive(Debug)]
pub struct Division {
    teams: Vec<Team>,
}

#[derive(Debug, Clone)]
pub struct Team {
    name: String,
    market: String,
}

What I want to do is converting a Rankings instance to Vec<Team>. Here's my solution:

fn main() {
    let mut rankings = Rankings {
        conferences: vec![
            Conference {
                divisions: vec![
                    Division {
                        teams: vec![
                            Team {
                                name: String::from("Raptors"),
                                market: String::from("Toronto"),
                            },
                            Team {
                                name: String::from("Knicks"),
                                market: String::from("New York"),
                            }
                        ]
                    },
                    Division {
                        teams: vec![
                            Team {
                                name: String::from("Bucks"),
                                market: String::from("Milwaukee"),
                            },
                            Team {
                                name: String::from("Cavaliers"),
                                market: String::from("Cleveland"),
                            }
                        ]
                    },
                ]
            },
        ]
    };

    println!("- rankings:\n{:#?}\n", rankings);

    let mut raw_teams: Vec<Vec<Vec<Team>>> = rankings
        .conferences
        .iter_mut()
        .map(|c| c.divisions.iter_mut().map(|d| d.teams.clone()).collect())
        .collect();

    println!("- raw_teams:\n{:#?}\n", raw_teams);

    let flattened_teams = raw_teams
        .iter_mut()
        .fold(Vec::new(), |mut acc, val| {
            acc.append(val);
            acc
        })
        .iter_mut()
        .fold(Vec::new(), |mut acc, val| {
            acc.append(val);
            acc
        });

    println!("- flattened_teams:\n{:#?}\n", flattened_teams);
}

Playground link

First, I converted Rankings to Vec<Vec<Vec<Team>>> using iter_mut() and map(), then flattened Vec<Vec<Vec<Team>>> to Vec<Team> using iter_mut() and fold().

But I just wrote that code avoiding compile errors, which mean the code could be refactored better using idiomatic patterns. I think I might overuse mutability, and two conversion process can be simplified using appropriate iterator functions. Thanks for any advices.


texts: Python Tkinter countdown app with a freezing GUI

texts:
So I want to create a very basic constantly changing text bvariable with a counter function. I created it, and it is working well, but once I press the "countdown" button, the GUI freezes, and the only way to close the window is from PyCharm.

Any suggestons about what causes the freeze and how to fix it?

The program unfreezes when the countdown is finished, so it's just a hanging interface, not a crash. Written for Python 3.8.

from tkinter import *

class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label = Label(master, textvariable=time)
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Countdown", command=self.countdown)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

    def countdown(self):
        remaining = 100
        for i in range(100):
            time.set(remaining)
            remaining -= 1
            self.master.after(1000)
            self.master.update_idletasks()

root = Tk()
time = StringVar()

my_gui = MyFirstGUI(root)

root.mainloop()


texts:
I have an abstract class which holds a hook method for a template method.  Not all classes which extend this class will need to implement this method (in fact most will not, but a few will).  As such I declared the method this way:

protected void applyExtraCriteria(Object extraCriteria) {

}

Should it instead be declared this way:

protected abstract void applyExtraCriteria(Object extraCriteria);

Which one would be considered better practice?


texts: Add pivot data from the same pivot model

texts:
My project has thee models Cart, Order and Product
Cart and Order have the same fields for pivot model
    class Cart extends Model {
            ...

            public function products() {
                    return $this->belongsToMany(Product::class)->withPivot([
                            'id',
                            'count',
                            'price',
                            'discount',
                            'tax',
                            'created_at',
                            'updated_at'
                    ]);
            }

    }

    class Order extends Model {
            ...

            public function products() {
                    return $this->belongsToMany(Product::class)->withPivot([
                            'id',
                            'count',
                            'price',
                            'discount',
                            'tax',
                            'created_at',
                            'updated_at'
                    ]);
            }

    }

How better create Order with pivot from Cart with pivot?
Now I have next code
    $cart = Cart::getCartFromSession();
    $order = Order::create($request->all());

    foreach ($cart->products as $product) {
        $order->products()->attach($product, [
            'count' => $product->pivot->count,
            'price' => $product->pivot->price,
            'discount' => $product->pivot->discount,
            'tax' => $product->pivot->tax,
        ]);
    }


texts: LRU cache implementation in C++ using unordered_map and doubly linked list

texts:
I have implemented an LRU cache in C++ using a hash table and a doubly linked list. Any kind of feedback is appreciated.

#pragma once
#include<memory>

template<typename Key , typename Value>
class Node {
  public:
    Key key;
    Value val;

    std::shared_ptr<Node> next;
    std::shared_ptr<Node> prev;

Node(Key k,Value v) :
     key(k),
     val(v),
     next(nullptr),
     prev(nullptr)
  {}
};

template<typename Key, typename Value>
class List {
  private:
    std::shared_ptr<Node<Key, Value>> front;
    std::shared_ptr<Node<Key, Value>> rear;

bool isEmpty() {
    return rear == nullptr;
 }

public:
List() : front(nullptr), rear(nullptr) {}

std::shared_ptr<Node<Key, Value>> Insert_Page_At_Front(Key k , Value v) {

    std::shared_ptr<Node<Key, Value>> page = std::make_shared<Node<Key,
    Value>>(k, v);

    if (front == nullptr && rear == nullptr) {
        front = page;
        rear = page;
    }
    else {
        page->next = front;
        front->prev = page;
        front = page;
    }
    return page;
  }

  void Move_Page_To_Front(std::shared_ptr<Node<Key, Value>> page) {
    if (page == front) {
        return;
    }
    if (page == rear) {
        rear = rear->prev;
        rear->next.reset();
    }
    else {
        page->prev->next = page->next;
        page->next->prev = page->prev;
    }

    page->next = front;
    page->prev.reset();
    front->prev = page;
    front = page;
  }

  void remove_Page_From_Rear() {
    if (isEmpty()) {
        return;
    }
    if (front == rear) {
        rear.reset();
        front.reset();
        rear.reset();
    }
    else
    {
        std::shared_ptr<Node<Key, Value>> temp = rear;
        rear = rear->prev;
        rear->next.reset();
        temp.reset();
    }
  }

  std::shared_ptr<Node<Key, Value>> Get_Rear_Page() {
    return rear;
  }

};

#pragma once
#include"List.h"
#include<unordered_map>

template<typename Key, typename Value>
class LRUCache {
private:
    unsigned int m_capacity;
    unsigned int m_currentSize;
    std::unordered_map<Key, std::shared_ptr<Node<Key, Value>> > m_pageMap;
    std::shared_ptr<List<Key,Value>> m_pageList;
public:
LRUCache(int Capacity) {
    m_capacity = Capacity;
    m_currentSize = 0;
    m_pageList = std::make_shared<List<Key,Value>>();
}

Value get(Key key) {
    if (m_pageMap.find(key) == m_pageMap.end()) {
        return -1;
    }
    Value value = m_pageMap[key]->val;

    // move the page to front
    m_pageList->Move_Page_To_Front(m_pageMap[key]);
    return value;
}

void put(Key key,Value value) {
    if (m_pageMap.find(key) != m_pageMap.end()) {
        // if key already present, update value and move page to head
        m_pageMap[key]->val = value;
        m_pageList->Move_Page_To_Front(m_pageMap[key]);
        return;
    }

    if (m_currentSize == m_capacity) {
        //remove rear page
        Key k = m_pageList->Get_Rear_Page()->key;
        m_pageMap.erase(k);
        m_pageList->remove_Page_From_Rear();
        m_currentSize--;
    }

    //add new page to front
    std::shared_ptr<Node<Key, Value>> page = m_pageList
    ->Insert_Page_At_Front(key,value);
    m_currentSize++;
    m_pageMap[key] = page;
  }

 };


texts:
This was the task (I don't know the exact wordings anymore):

  You get a string with operation as input:

  if it is a number push it to stack
  if it is "DUP", then duplicate the one one top and push it to the
  stack
  if it is "POP" then remove the one on top
  if it is "+" add the two numbers on top of the stack and replace
  both with the result of the addition
  if it is "-" then minus the two numbers on top (the second minus
  the first) of the stack and replace both with the result of the
  subtraction
  if an error occurs, e.g. not enough numbers to add/subtract/pop,
  then return -1

Examples:

Input: "3 DUP 5 - -"
Output: -1

Input: "13 DUP 4 POP 5 DUP + DUP + -"
Output: 7

Input: "5 6 + -"
Output: -1

My approach is quite simple. I differentiate between numbers and operations. If it is a number I simply push it to the stack. Otherwise Ill check what kind of operation it is. If a valid operation is recognized, then the mapped function will be executed.

If an error occurs, e.g. no more numbers in the stack to be popped, invalid operation, etc. it will return -1.

My solution

function solution(S) {
    if (!S.length) {
        return -1;
    }
    const stack = new Array();
    const push = n => stack.push(Number(n));
    const pop = () => {
        if (!stack.length) {
            throw new Error('empty');
        }
        return stack.pop();
    }
    const duplicate = () => {
        try {
            const dup = pop();
            push(dup);
            push(dup);
        } catch(e) {
            throw new Error(e);
        }
    };
    const add = () => {
        try {
            const sum1 = pop();
            const sum2 = pop();
            push(sum1 + sum2);
        } catch(e) {
            throw new Error(e);
        }
    };
    const minus = () => {
        try {
            const min1 = pop();
            const min2 = pop();
            push(min1 - min2);
        } catch(e) {
            throw new Error(e);
        }
    };
    const ops = {
        "DUP": duplicate,
        "POP": pop,
        "+": add,
        "-": minus,
    };

    const input = S.split(' ');
    input.forEach(x => {
        if (!isNaN(x)) {
            push(x);
        } else {
            try {
                const sanitzedX = x.toUpperCase();
                if (!ops[sanitzedX]) {
                    return -1;
                }
                ops[sanitzedX]();
            } catch(e) {
                return -1;
            }
        }
    });
    try {
        return pop();
    } catch(e) {
        return -1;
    }
}

console.log(solution("3 DUP 5 - -"));
console.log(solution("13 DUP 4 POP 5 DUP + DUP + -"));
console.log(solution("5 6 + -"));


texts:
I am to compute recurrently (not necessarily recursively) the y, where
$$y = {x}^{2n} + {x}^{2(n-1)} + ... + {x}^{4} + {x}^{2} + x$$

Here is what I am doing:

#include <iostream>
using namespace std;

double polynom(unsigned, double);

int main(void)
{
    cout << polynom(2, 3) << endl;
    return 0;
}

double polynom(unsigned n, double x)
{
    double currentAdd(x);
    double res(0);
    while (n)
    {
        res += currentAdd;
        currentAdd *= currentAdd;
        --n;
    }
    return res;
}

Is it possible to do it better?


texts: Predict new ratings for each user based on their pearson correlation with other users

texts:
I am new to R and programming. I have a set of ratings for 45000 users and 40 odd movies. I need to predict new ratings for each user based on their pearson correlation with other users. I also need to store the set of similar users for each user-movie combination.The code that I have managed to write is this

# Matrix of users and ratings
x <- matrix(rnorm(1:100), nrow = 10 , ncol = 30)
df = list()

# correlation matrix
cor_mat <- cor(x)

# similarity limits
upper = 1
lower = 0.4

# empty matrix to store predicted values
final_x = matrix(NA,nrow = 10,ncol = 30)

for (i in 1:ncol(x)){

for( j in 1:nrow(x)){

sim_user = which(cor_mat[i,] >= lower & cor_mat[i,] < upper)

final_x[i,j] = t(x[sim_user,j]) %*%
      cor_mat[sim_user,j]/sum(cor_mat[sim_user,j])

df[[length(df)+1]] = cbind.data.frame(i,j,sim_user,cor_mat[sim_user,j])

 }
}

Questions:

I am looping over each element of the matrix which works fine but seems pretty novice to me. Can something better be done?
I have heard of the foreach package but read that it adds value only when a single operation takes a long time to execute which is not the case here. Will it still provide me good performance?


texts:
I have multiple products that all have sizes and I need to find the cheapest configuration that meets the minimum required size.

For example, John needs a minimum of 10 litres of storage - it can be more, but not less.

There are 2L, 3L, 5L, 8L and 10L options (but this can change).

As an example, it might be cheaper to get:

1x10L container OR
2x5L containers OR
1x2L, 1x3L and 1x5L OR
4x3L (this one is over 10 L, but it is still possible that it will be cheaper)

So far I've tried looping over and over up to 4 times (because typically the maximum requirement will be 40 L), but in some cases I am running out of memory, and it doesn't seem like the most efficient way of doing it.

// Size is in mL

$available_containers = [
[
  'id' => 22700,
  'price' => 1190,
  'size' => 2000,
],
[
  'id' => 22701,
  'price' => 1245,
  'size' => 3000,
],
[
  'id' => 22702,
  'price' => 1415,
  'size' => 4000,
],
[
  'id' => 22715,
  'price' => 12300,
  'size' => 5000,
],
[
  'id' => 22706,
  'price' => 1740,
  'size' => 5000,
],
[
  'id' => 22703,
  'price' => 1510,
  'size' => 5000,
],
[
  'id' => 22707,
  'price' => 1790,
  'size' => 6000,
],
[
  'id' => 22704,
  'price' => 1770,
  'size' => 6000,
],
[
  'id' => 22708,
  'price' => 2215,
  'size' => 7000,
],
[
  'id' => 22705,
  'price' => 2195,
  'size' => 8200,
],
[
  'id' => 22709,
  'price' => 2660,
  'size' => 8200,
],
[
  'id' => 22710,
  'price' => 2799,
  'size' => 10000,
],
[
  'id' => 22711,
  'price' => 2910,
  'size' => 12500,
],
[
  'id' => 22712,
  'price' => 3260,
  'size' => 15000,
],
[
  'id' => 22713,
  'price' => 4130,
  'size' => 20000,
],
[
  'id' => 22714,
  'price' => 3770,
  'size' => 27000,
]
];

$required_size = 8; // Can change.
$container_install = 5;

foreach ( $available_containers as $v ){
  foreach ( $available_containers as $v2 ){
    foreach ($available_containers as $v3 ) {
      foreach ( $available_containers as $v4 ){

        $all_configs = [
          [
            'size' => $v['size'],
            'configuration' => [ $v['size'] ],
            'price' => $v['price'],
          ],
          [
            'size' => $v['size'] + $v2['size'],
            'configuration' => [ $v['size'], $v2['size'] ],
            'price' => $v['price'] + $v2['price'] + $container_install,
          ],
          [
            'size' => $v['size'] + $v2['size'] + $v3['size'],
            'configuration' => [ $v['size'], $v2['size'], $v3['size'] ],
            'price' => $v['price'] + $v2['price'] + $v3['price'] + $container_install + $container_install,
          ],
          [
            'size' => $v['size'] + $v2['size'] + $v3['size'] + $v4['size'],
            'configuration' => [ $v['size'], $v2['size'], $v3['size'], $v4['size'] ],
            'price' => $v['price'] + $v2['price'] + $v3['price'] + $v4['price'] + $container_install + $container_install + $container_install,
          ],
        ];

        foreach ( $all_configs as $c ){
          if ( $c['size'] >= $required_size ){
            $configuration[] = array(
              'configuration' => $c['configuration'],
              'size' => $c['size'],
              'price' => $c['price'],
            );
          }
        }
      }
    }
  }
}

// Sort by price.
$sorted_configs = array_sort($configuration, 'price', SORT_ASC); // This function simply sorts all permutations by price
```


texts: Plots of prior and posterior distributions for a model

texts:
I have an exercise that ask to plot the prior and posterior distribution in the Poisson-Gamma model. I did it (I think it's correct) inspired
in the answer of this question https://stats.stackexchange.com/questions/70661/how-does-the-beta-prior-affect-the-posterior-under-a-binomial-likelihood

Is there anything that can improve the code?

colors = c("red","blue","green","orange","purple")

n = 10

lambda = .2

x = rpois(n,lambda)
grid = seq(0,7,.01)

alpha = c(.5,5,1,2,2)
beta = c(.5,1,3,2,5)

plot(grid,grid,type="n",xlim=c(0,5),ylim=c(0,4),xlab="",ylab="Prior Density",
     main="Prior Distributions", las=1)
for(i in 1:length(alpha)){
  prior = dgamma(grid,shape=alpha[i],rate=1/beta[i])
  lines(grid,prior,col=colors[i],lwd=2)
}

legend("topleft", legend=c("Gamma(0.5,0.5)", "Gamma(5,1)", "Gamma(1,3)", "Gamma(2,2)", "Gamma(2,5)"),
       lwd=rep(2,5), col=colors, bty="n", ncol=3)

for(i in 1:length(alpha)){
  dev.new()
  plot(grid,grid,type="n",xlim=c(0,5),ylim=c(0,10),xlab="",ylab="Density",xaxs="i",yaxs="i",
       main="Prior and Posterior Distribution")

  alpha.star = alpha[i] + sum(x)
  beta.star = beta[i] + n
  prior = dgamma(grid,shape=alpha[i],rate=1/beta[i])
  post = dgamma(grid,shape=alpha.star,rate=beta.star)

  lines(grid,post,lwd=2)
  lines(grid,prior,col=colors[i],lwd=2)
  legend("topright",c("Prior","Posterior"),col=c(colors[i],"black"),lwd=2)

}


texts: ActiveRecord model for upvotes and downvotes

texts:
How can I make my model DRY and KISS?

class Rating < ActiveRecord::Base
  attr_accessible :item_type, :item_id, :rating, :voters_up, :voters_down
  serialize :voters_up, Hash
  serialize :voters_down, Hash
  belongs_to :ranks, :polymorphic => true

  def self.up(item, user, iteration = 1)
    @rating = Rating.where(item_type: item.class.name, item_id: item.id).first
    @rating = Rating.create(item_type: item.class.name,
                            item_id: item.id,
                            rating: 0,
                            voters_up: {users:[]}, voters_down: {users:[]}) unless @rating

    changed = nil
    if !@rating.voters_up[:users].include?(user.id) && !@rating.voters_down[:users].include?(user.id)
      if changed.nil?
        @rating.increment(:rating, 1)
        @rating.voters_up[:users] << user.id
        changed = true
      end
    end

    if @rating.voters_up[:users].include?(user.id) && !@rating.voters_down[:users].include?(user.id)
      if changed.nil?
        @rating.decrement(:rating, 1)
        @rating.voters_up[:users].delete user.id
        changed = true
      end
    end

    if @rating.voters_down[:users].include?(user.id) && !@rating.voters_up[:users].include?(user.id)
      if changed.nil?
        @rating.voters_up[:users] << user.id
        @rating.voters_down[:users].delete user.id
        @rating.increment(:rating, 2)
        changed = true
      end
    end

    @rating.save
    item.update_attribute(:rating_value, @rating.rating)
  end

  def self.down(item, user, iteration = 1)
    @rating = Rating.where(item_type: item.class.name, item_id: item.id).first
    @rating = Rating.create(item_type: item.class.name,
                            item_id: item.id,
                            rating: 0,
                            voters_up: {users:[]}, voters_down: {users:[]}) unless @rating

    changed = nil
    if !@rating.voters_down[:users].include?(user.id) && !@rating.voters_up[:users].include?(user.id)
      if changed.nil?
        @rating.decrement(:rating, 1)
        @rating.voters_down[:users] << user.id
        changed = true
      end
    end

    if @rating.voters_down[:users].include?(user.id) && !@rating.voters_up[:users].include?(user.id)
      if changed.nil?
        @rating.increment(:rating, 1)
        @rating.voters_down[:users].delete user.id
        changed = true
      end
    end

    if @rating.voters_up[:users].include?(user.id) && !@rating.voters_down[:users].include?(user.id)
      if changed.nil?
        @rating.voters_down[:users] << user.id
        @rating.voters_up[:users].delete user.id
        @rating.decrement(:rating, 2)
        changed = true
      end
    end

    @rating.save
    item.update_attribute(:rating_value, @rating.rating)
  end

end


texts: Working with user input and dictionaries inside of lists

texts:
Coming to the close of week 1 learning a programming language (Python)

Looking for general review, comments, and tips

Objective of Code

The objective here was to practice pulling information from dictionaries within lists and also adding dictionaries created from user input.

Code

def make_album(artist, album, tracks =''):
    catalog = {}
    catalog['artist_name'] = artist
    catalog['album_title'] = album
    catalog['tracks'] = tracks

    return catalog

def ask_user(message):
    user_input =''
    while not user_input:
        user_input = input(message)
    return user_input

riven = make_album('Zeppelin', 'Houses of the Holy', 8)
jax = make_album('Tool', 'Lateralus', 13)
vayne = make_album('Pink Floyd', 'Dark Side of the Moon')

differents = [riven, jax, vayne]

while True:
    print("type q to quit")
    band = ask_user("Enter artist: ")
    if band == "q":
        break
    album = ask_user("Enter album: ")
    if album == 'q':
        break
    numbers = input("Enter number of tracks: ")
    if numbers == 'q':
        break
    fire = make_album(band.title(), album.title(), numbers)
    differents.append(fire)

for i in differents:
    if i['tracks']:
        print('\n' + i['album_title'] + ' by ' \
            + i['artist_name'] + ' it has '\
            + str(i['tracks']) +' tracks.')
    else:
        print('\n' +  i['album_title'] + ' by ' + i['artist_name'] \
            + '.')

Output

vash@localhost:~/pcc/8$ python3 lot2learn.py
type q to quit
Enter artist: circa survive
Enter album: juturna
Enter number of tracks: 11
type q to quit
Enter artist: dance gavin dance
Enter album: happiness
Enter number of tracks:
type q to quit
Enter artist: q

Houses of the Holy by Zeppelin it has 8 tracks.

Lateralus by Tool it has 13 tracks.

Dark Side of the Moon by Pink Floyd.

Juturna by Circa Survive it has 11 tracks.

Happiness by Dance Gavin Dance .
(xenial)vash@localhost:~/pcc/8$


texts: Dynamically adding blocks of information to a page

texts:
I have code that dynamically adds blocks of information to my page. I don't know in advance how many blocks there will be. I want to utilize Twitter Bootstrap (3.x) to layout them in three columns (e.g. I want to use col-xs-4).

Bottom line: is it okay to add col-* elements to a container without wrapping them in row elements?

I currently generate this markup:

.my-box {
  margin: 5px;
  padding: 5px;
  background-color: #fed;
}
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

One

Two

Three

Four

Etc.

I'm looking to get feedback on the above bit of code. (I've omitted the bit that generates the divs for brevity as well as the fact that I'm not necessarily looking for feedback on that bit. Ping me in a comment if you do think the way its generation is important.)

Things I've researched:

This seems to work fine, rendering just the way I want it to. However, this seems to go against common-sense semantics of rows and columns.

So I checked the Grid System documentation for Bootstrap, but it is unclear as to whether it is or isn't required to wrap col-* elements inside a row or not. Nowhere is it stated as an explicit requirement, but on the other hand the examples do wrap column elements in rows without exception.


texts:
This abomination of code creates arrays based off input from the user. Sample input would be something like "S 4 aba bab baa aab" where:

args[0] = array type (Int, Double, String)
args[1] = length of array
args[2...] = contents of the array

The creation of the arrays in my code is horrible, but I am not quite sure how else to do it while incorporating generics. The point of the code is to be able to pass any of the created arrays to the methods at the bottom, hence generics.

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class Prog7a<E> {
public static void main(String[] args) throws FileNotFoundException {

    checkUsage(args);

    //This would be nice, but I get "Cannot make static reference to non-static E"
    //      ArrayList<E> array = new ArrayList<>();
    //
    //      if (args[0].matches("I|i"))
    //          for (int i = 2; i < args.length; i++)
    //              array.add((E) new Integer(args[i]));
    //
    //       else if (args[0].matches("S|s"))
    //           for (int i = 2; i < args.length; i++)
    //                  array.add((E) new String(args[i]));
    //       else
    //           for (int i = 2; i < args.length; i++)
    //                  array.add((E) new Double(args[i]));
    //
    //
    //      System.out.println("Original: " + array);
    //      System.out.println("  Unique: " + removeDuplicates(array));
    //      shuffle(array);
    //      System.out.println("Shuffled: " + array);
    //      System.out.println(" Maximum: " + max(array));

My question is here: I have the loop to fill in the array and call to the methods in each conditional, which makes me think I could rewrite this in such a way that it is not so repetitive.

    if (args[0].matches("I|i")) {
        ArrayList<Integer> iL = new ArrayList<Integer>();
        for (int i = 2; i < args.length; i++) {
            iL.add(Integer.parseInt(args[i]));
        }
        System.out.println("Original: " + iL);
        System.out.println("  Unique: " + removeDuplicates(iL));
        shuffle(iL);
        System.out.println("Shuffled: " + iL);
        System.out.println(" Maximum: " + max(iL));

    } else if (args[0].matches("S|s")) {
        ArrayList<String> sL = new ArrayList<String>();
        for (int i = 2; i < args.length; i++) {
            sL.add(args[i]);
        }
        System.out.println("Original: " + sL);
        System.out.println("  Unique: " + removeDuplicates(sL));
        shuffle(sL);
        System.out.println("Shuffled: " + sL);
        System.out.println(" Maximum: " + max(sL));
    } else {
        ArrayList<Double> dL = new ArrayList<Double>();
        for (int i = 2; i < args.length; i++) {
            dL.add(Double.parseDouble(args[i]));
        }
        System.out.println("Original: " + dL);
        System.out.println("  Unique: " + removeDuplicates(dL));
        shuffle(dL);
        System.out.println("Shuffled: " + dL);
        System.out.println(" Maximum: " + max(dL));
    }

}

public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) {
    new HashSet<E>(list);
    list = new ArrayList<E>(new HashSet<E>(list));
    return list;

}

public static <E> void shuffle(ArrayList<E> list) {
    Collections.shuffle(list);
}

public static <E extends Comparable<E>> E max(ArrayList<E> list) {
    return Collections.max(list);
}

public static void checkUsage(String[] args)
{
    if (args.length < 2)
    {
        System.out.println("Please supply more than 2 arguments");
        System.exit(1);
    }
    if (!(args[0]=="s") && (args[0]=="S") &&
        (args[0]=="d") && (args[0]=="D") &&
        (args[0]=="i") && (args[0]=="I")){
        System.out.println("Incorrect format of command.");
        System.exit(1);
    }
}
}


texts: Creating formatted "[time] [unit] ago" messages from a seconds value

texts:
I have this function which calculates how many seconds, mins, hours etc ago a specific time string was.
However, the way I have done it consists of a massive if statement block, and it goes through each specific time that it can reach.
Is there a better way of writing this code where it's more efficient and doesn't have a massive if statement block?
define('SECS_IN_MIN', 60);
define('SECS_IN_HR', 3600);
define('SECS_IN_DAY', 86400);
define('SECS_IN_WEEK', 604800);   // 7 days
define('SECS_IN_MONTH', 2592000); // 30 days
define('SECS_IN_YEAR', 31536000); // 365 days

// Determines if a number is a plural
// Input: Takes in a number
// Output: Outputs a string which is either "s", if plural
//         OR "" if not plural
function is_plural($num) {
    if ($num != 1) return "s";
    else return "";
}

// Gets a string line x minutes ago
// Input a date
// Output: a string which matches its time ago
function date_to_str($time) {
    $currTime = time();
    $pastTime = strtotime($time);
    $diff = $currTime - $pastTime;

    // Seconds Ago
    if ($diff < SECS_IN_MIN) {
        $plural = is_plural($diff);
        return "$ans few second$plural ago";

    // Minutes Ago
    } else if($diff < SECS_IN_HR) {
        $ans = floor($diff / SECS_IN_MIN);
        $plural = is_plural($ans);
        return "$ans minute$plural ago";

    // Hours Ago
    } else if ($diff < SECS_IN_DAY) {
        $ans = floor($diff / SECS_IN_HR);
        $plural = is_plural($ans);
        return "$ans hour$plural ago";

    // Days Ago
    } else if ($diff < SECS_IN_WEEK) {
        $ans = floor($diff / SECS_IN_DAY);
        $plural = is_plural($ans);
        return "$ans day$plural ago";

    // Weeks ago
    } else if ($diff < SECS_IN_MONTH) {
        $ans = floor($diff / SECS_IN_WEEK);
        $plural = is_plural($ans);
        return "$ans week$plural ago";

    // Months Ago
    } else if ($diff < SECS_IN_YEAR) {
        $ans = floor($diff / SECS_IN_MONTH);
        $plural = is_plural($ans);
        return "$ans month$plural ago";

    // Years Ago
    } else if ($diff > SECS_IN_YEAR * 10) {
        $ans = floor($diff / SECS_IN_YEAR);
        $plural = is_plural($ans);
        return "$ans year$plural ago";
    }

    return "-1";
}

$time = "2020-08-25 13:02:32"
echo( date_to_str($time) );
// Outputs 4 days ago


texts:
First, I am aware that this can be done in sklearn - I'm intentionally trying to do it myself.

I am trying to extract the eigenvectors from np.linalg.eig to form principal components. I am able to do it but I think there's a more elegant way. The part that is making it tricky is that, according to the documentation, the eigenvalues resulting from np.linalg.eig are not necessarily ordered.

To find the first principal component (and second and so on) I am sorting the eigenvalues, then finding their original indexes, then using that to extract the right eigenvectors. I am intentionally reinventing the wheel a bit up to the point where I find the eigenvalues and eigenvectors, but not afterward. If there's any easier way to get from e_vals, e_vecs = np.linalg.eig(cov_mat) to the principal components I'm interested.

import numpy as np

np.random.seed(0)
x = 10 * np.random.rand(100)
y = 0.75 * x + 2 * np.random.randn(100)

centered_x = x - np.mean(x)
centered_y = y - np.mean(y)

X = np.array(list(zip(centered_x, centered_y))).T

def covariance_matrix(X):
    # I am aware of np.cov - intentionally reinventing
    n = X.shape[1]
    return (X @ X.T) / (n-1)

cov_mat = covariance_matrix(X)

e_vals, e_vecs = np.linalg.eig(cov_mat)

# The part below seems inelegant - looking for improvement
sorted_vals = sorted(e_vals, reverse=True)

index = [sorted_vals.index(v) for v in e_vals]

i = np.argsort(index)

sorted_vecs = e_vecs[:,i]

pc1 = sorted_vecs[:, 0]
pc2 = sorted_vecs[:, 1]


texts: Executing multiple steps to handle a purchase using currying

texts:
Is doing something like this utilizing currying in a practical sense?

function processOneClickPurchase(item) {
    let context = { step: 0 }

    let addItemToCart = item => {
        let cart = getSession().cart
        cart.items.push(item)
        log('Cart items', cart.items)
        return cart
    }

    ...

    let purchase = generate([
        addItemToCart,
        makePurchase,
        processBilling,
        setupShipping,
        sendPurchaseAndShippingNotification,
    ], null, cleanup)

    return purchase(item)

    function generate(steps, before, after) {
        const takeStep = (incoming, outgoing) => {
            let message = {
                step: ++context.step,
                incoming: incoming,
                outgoing: outgoing
            };

            log('step #'+(context.step), message)

            return outgoing
        }
        const walk = value => {
            return steps.reduce((from, to) => {
                return takeStep(from, to(from))
            }, value)
        }

        (before && steps.push(before)) + (after && steps.push(after))

        return function invoke(state) {
            const hasItems = Array.isArray(state) || !(state = [state])
            const processed = state.map(walk)
            return hasItems ? processed : processed[0]
        }
    }
}

https://jsfiddle.net/f7mdak6z/25/

I realize there's algebra going on with currying and maybe this is nonsensical, so we're not talking rigid math concepts. However, it seems to me this pattern is rudimentary and it feels like an application of currying over an input to achieve an output. takeStep() almost seems like a monad, etc.

I think it would definitely start to sound like a fit if the methods passed to generate() simply modified the stream, and perhaps the takeStep() function handled side-effects.


texts: Retrieve a number in a webpage and store in a SQLite3 db

texts:
I'm beggining Python. So I wrote a program which is supposed to get a number of connected people on a forum (like this one : http://www.jeuxvideo.com/forums/0-51-0-1-0-1-0-blabla-18-25-ans.htm) and store the number with the datetime in a database file (SQLite3). Every forum has his own table name.

My code is supposed to do this :

  Create object for each forum we want to retrieve with the Forum class.
  Store these objects in a list to put use in a loop For.
  Get a web page .htm (with requests) where the number of connected people is wrote in a span tag with the class "nb-connect-fofo" who looks like this 1799 connecté(s). I'm using BeautifulSoup to get the string and REGEX to get the number  It's supposed to be done for every forum
  Execute a SQLite3 request to store the datetime, number in database file with the same name as the forum which is retrieve

Here's my code :

#!/usr/bin/python3

from bs4 import BeautifulSoup
from time import sleep
import sqlite3
import datetime
import requests
import re

class Forum:

    def __init__(self, forum, url_forum): #initialization all object with there name, URL
        self.forum = forum
        self.url_forum = url_forum

        pattern = '([0-9]{1,5})'
        self.pattern = re.compile(pattern)

    def add_to_database(self): #Add to the SQLite3 database the number of connected people and the datetime to their own table
        connection = sqlite3.connect("database.db")
        c = connection.cursor()
        now = datetime.datetime.today()
        nb_co = self.recup_co()

        text = "INSERT INTO {0}(datetime, nb_co) VALUES('{1}', '{2}')".format(self.forum, now, nb_co)
        c.execute(text)
        connection.commit()
        connection.close()

        print(now, self.forum, str(nb_co))
        sleep(1)

    def recup_co(self): #Retrieving the page and the number of people connected by using REGEX
        r = requests.get(self.url_forum)
        page_html = str(r.text)
        page = BeautifulSoup(page_html, 'html.parser')
        resultat = page.select(".nb-connect-fofo")

        nb_co = re.search(self.pattern, str(resultat))

        return nb_co.group(0)

def main():
    # All forums which are scanned are here
    dixhuit_vingtcinq = Forum("dixhuit_vingtcinq", "http://www.jeuxvideo.com/forums/0-51-0-1-0-1-0-blabla-18-25-ans.htm")
    moins_quinze = Forum("moins_quinze", "http://www.jeuxvideo.com/forums/0-15-0-1-0-1-0-blabla-moins-de-15-ans.htm")
    quinze_dixhuit = Forum("quinze_dixhuit", "http://www.jeuxvideo.com/forums/0-50-0-1-0-1-0-blabla-15-18-ans.htm")
    overwatch = Forum("overwatch", "http://www.jeuxvideo.com/forums/0-33972-0-1-0-1-0-overwatch.htm")

    #All forum name's are stored here to use them with a list
    forums = [dixhuit_vingtcinq, moins_quinze, quinze_dixhuit, overwatch]

    while(True):
        for forum in forums:
            try:
                forum.add_to_database()
            except:
                print("An error occured with the forum '{0}' at {1}".format(forum.forum, datetime.datetime.today()))
                sleep(5)
        sleep(60)

main()

I will use it later to make graphics, make little statistics to improve my skill with Python. Maybe I will retrieve more forum and expand my program to scrap the website and get every post on these forums (If I, I will do this in a lot of time later).

So I'm asking you for some improvements/ideas. As a beginner, there are obviously somes errors that can be very annoying. Because, i really want to improve

Also, my code is running on one of my own server. Isn't it better to buy a cheap VPS for 2€ instead ?

Thanks for reading and thanking you in advance.

PS : If there are somes mistakes relatives to my post about the website tell me