texts: C++ equivalent of Python's deque with maxlen - sliding window

texts:
In Python it is really easy to get sliding window functionality using a deque with maxlen:

from collections import deque
deck = deque(maxlen=4)
deck.append(0x01)
deck.append(0x02)
deck.append(0x03)
deck.append(0x04)
deck.append(0x05)
for item in deck:
    print(item)  # outputs 2, 3, 4, 5

This does two things - it grows until maxsize and then once maxsize has been reached items drop off the deque.

I wanted something similar in C++ and wrote the following (note, I know C++ has a deque, but I couldn't see how to reserve the size):

template <typename T>
auto rotate_push(std::vector<T> &container, const T& val) -> void
{
    if (container.size() < container.capacity()) {
        container.resize(deck.size() + 1);
    }
    else {
        std::rotate(container.begin(), container.begin() + 1, container.end());
    }

    container[container.size() - 1] = val;
}

auto deck = std::vector<int>();
deck.reserve(4);
rotate_push(deck, 1);
rotate_push(deck, 2);
rotate_push(deck, 3);
rotate_push(deck, 4);
rotate_push(deck, 5);

for (auto const &item : deck) {
    printf("%d\n", item); // outputs 2, 3, 4, 5
}

My Questions are:

Are the implementations basically equivalent (If not then why)
Is there a better custom implementation
Is there a easier/pre-existing implementation using STL
Is there a easier/pre-existing implementation using other
Is there a more performant implementation

Answers:

No, they have different push complexity [by Johnbot]
Use a free function or wrap std::deque [by Johnbot]
(Un-answered)
Boost Circular Buffer [by ratchet freak]
Circular Buffer [by ratchet freak]


texts:
I have the following code, written in Python:

if id:
    fields = r.table(cls._tablename)
              .get(id)
              .run(cls.connection())
else:
    try:
        fields = list(r.table(cls._tablename)
                       .filter(**kwargs)
                       .limit(1)
                       .run(cls.connection()))[0]
    except IndexError:
        fields = None

The code acts as a wrapper for getting a document from a RethinkDB datastore. I find all those indents unaesthetic, and I cannot seem to find a way to wrap the lines to look nicer.

So, is there a way I can rewrite (or maybe just rewrap) this code to look better and provide the same functionality?


texts:
UPDATE:  I have posted this question on math.se along with the identification of a new relationship to lattice points on hyperbola.

I have a naive grouping method for factorization.  I am curious as to its novelty and aspects of the code below that will increase its efficiency.

The method is best described with an example:

For \$n = 798,607 \$ if we start with a seed group of \$59\$, we would have \$17\$ groups of \$13,535\$ and \$42\$ groups of \$13,536\$.  Neither the \$17\$ nor the \$42\$ will evenly parse the other grouping totals so we double the seed group.  Now we have \$118\$ groups in total, \$17\$ groups of \$6,767\$ and \$101\$ groups of \$6,768\$.  The \$6,767\$ can be distributed among the \$101\$ groups, resulting in factors of \$101\$ groups of \$7,907\$.

I have found that all seed groups are odd and less than \$\sqrt n \over 2\$ and there exist multiple (unknown quantity) seed groups yielding factors.  The seed groups (\$i\$) are only expanded until the groups are greater than the group counts, or the initial seed group splits do not carry forward (i.e., \$17\$  or \$42\$ groups from seed group \$59\$ needs to be a solution in the \$118\$ groups split.)

#Naive Grouping
NaiveGrouping <- function(number){

  r<- as.integer(sqrt(number)/2)

for (i in seq(3,r,2)){
  for (j in 0:(floor(log2(number)))){

  Seed_Group<-(i*(2^j))

  Counts <- (number/Seed_Group)

  if(Counts%%1==0){
            return(c(Seed_Group=Seed_Group,End_Group=Seed_Group,Factors=Seed_Group,number/Seed_Group))
         }

  count_ceiling <- (ceiling(Counts))
  count_floor <- (floor(Counts))

  initial_group_ceiling <- (number%%i)
  initial_group_floor <- (i - number%%i)

  group_ceiling <- number%%Seed_Group
  group_floor <- (Seed_Group - (group_ceiling))

      if(group_floor==initial_group_floor | group_ceiling==initial_group_ceiling)
      if(group_floor==1 | group_ceiling==1) next
      if(group_floor>count_ceiling | group_ceiling>count_floor) break

      if(count_floor%%group_ceiling==0){
               return(matrix(c(group_floor,count_floor,group_ceiling,count_ceiling,i,group_floor+group_ceiling,group_ceiling,number/group_ceiling),4,2,byrow=TRUE,dimnames=list(c("Group Floor","Group Ceiling", "Seed Group, End Group","Factors"),c("Groups","Counts"))))

              }

      if(count_ceiling%%group_floor==0){
               return(matrix(c(group_floor,count_floor,group_ceiling,count_ceiling,i,group_floor+group_ceiling,group_floor,number/group_floor),4,2,byrow=TRUE,dimnames=list(c("Group Floor","Group Ceiling", "Seed Group, End Group","Factors"),c("Groups","Counts"))))

              }
      }

  }
return("Prime")
}


texts:
I am setting a value to input box and trigger to hear the change. I would also like to always hear the input change, and for that I made this function.

Can any expert please verify the way I did is correct? Or is it further tune-able?

var page = function () {
    return {
        init : function () {
            var input = $("#pNo");
            $(document).on("pageChange", this.onPageChange.bind(this));
            $(input).val(1).trigger({type:'pageChange',element:input});
            $(input).bind("change paste keyup",function() { $.event.trigger({type: "pageChange", element:input})});
        },

        onPageChange : function (e) {
            console.log($(e.element).val());
        }
    }
}();

page.init();

Live Demo


texts:
What I am working on has sets of window controls. Controls are constantly being either destroyed, or created.

void ChangeControl() {

// remove all controls, existing, or not
hwnd = GetDlgItem(hWnd, IDC_BTN_FOOA);
DestroyWindow(hwnd);
hwnd = GetDlgItem(hWnd, IDC_BTN_FOOB);
DestroyWindow(hwnd);
hwnd = GetDlgItem(hWnd, IDC_BTN_FOOC);

// add the control wanted
hwndButton = CreateWindow("BUTTON", "Start", WS_VISIBLE|WS_CHILD|BS_OWNERDRAW|BS_PUSHBUTTON,
        left, top, BUTTON_WIDTH, BUTTON_HEIGHT, hWnd, (HMENU)IDC_BTN_FOOB, GetModuleHandle(NULL), NULL);
}

Test case:

DWORD errorResult;
testHwnd = GetDlgItem(hWnd, IDC_BTN_START);
if (testHwnd) {
    DestroyWindow(hwnd);
}
else {
    errorResult = GetLastError();
}

I am wondering if this method is safe, or if I should be checking if a control exists before calling DestroyWindow().


texts: Rust recursion pattern in simple cat program

texts:
I'm trying to get my head around recursion in Rust. I've put together a basic implementation of cat here to play with the basics.

Here's my recursive version:

use std::env;
use std::fs::File;
use std::fmt::Display;
use std::io;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;

const STDIN: &'static str = "-";
const BUFFER_SIZE: usize = 4096;

enum Method {
    File,
    Line,
}

fn main() {
    // skip the first element as it is the program name
    let args = env::args();
    if args.len() == 1 {
        cat(io::stdin(), "stdin", Method::Line);
    } else {
        for arg in args.skip(1) {
            if arg.eq(STDIN) {
                cat(io::stdin(), "stdin", Method::Line);
            } else {
                let path = Path::new(&arg);
                let display = path.display();
                let file = File::open(path)
                    .expect(format!("cat: failed to open: {}", display).as_str());
                cat(file, display, Method::File);
            }
        }
    }
    io::stdout().flush().unwrap();
}

// Read from `input` and print to stdout.
// `name` is used in error messages.
// `m` selects whether to read line-by-line or to read the entire input.
fn cat<R, N>(input: R, name: N, m: Method) where R: Read, N: Display {
    let mut reader = BufReader::with_capacity(BUFFER_SIZE, input);
    cat_recurse(&mut reader, name, m);
}

fn cat_recurse<R, N>(reader: &mut BufReader<R>, name: N, m: Method) where R: Read, N: Display {
    let mut s = String::new();
    let n = match m {
        Method::Line => reader.read_line(&mut s),
        Method::File => reader.read_to_string(&mut s),
    }.expect(format!("cat: failed to open {}", name).as_str());
    if n > 0 {
        print!("{}", s);
        // recurse
        cat_recurse(reader, name, m);
    }
}

I know passing around the Method enum is a bit ugly but it was the best way I could come up with to get the app to work with stdin properly. I'm interested in feedback on the design of the recursion pattern specifically. Does it seem about right or is there a simpler way to represent this that I haven't thought of yet? I'd also appreciate any more general feedback you can offer, but the recursion bit is where I'm trying to learn right now.


texts: Retrieving a list of patients that have visited certain hospitals

texts:
I have a table of patients that has a field for which hospitals they visited.  I want to retrieve a list of patients that have visited Green Hospital and have also visited other hospitals. Is this query accurate?

SELECT COUNT (DISTINCT PatientID) FROM Patients
WHERE PatientID IN (
        SELECT PatientID FROM Patients WHERE Facility = 'Green'
) AND Facility <> 'Green'

My logic is that the internal statement will get all patients that have visited Green Hospital.  The external will find the intersect of those that visited somewhere else.  I can't think of any way to validate my results which is why I'm posting here.

The DBMS is actually Intersystems Caché.


texts: Calculating speed from a Pandas Dataframe with Time, X, and Y columns

texts:
I'm trying to calculate speed between consecutive timepoints given data that is in a '.csv' file with the following columns: "Time Elapsed", "x", and "y". The ultimate goal is to get the data into a format where I can plot "Time Elapsed" vs. "speed"

I'm fairly sure that my implementation is doing what I want, but it's certainly possible (and likely) that I overlooked something. I'm also wondering whether there are faster/more efficient ways (in Python) to perform these calculations?

import pandas as pd
import numpy as np

def calculate_speeds(path_to_csv):
    data_df = pd.read_csv(path_to_csv)

    xy = data_df[['x', 'y']]

    b = np.roll(xy, -1, axis=0)[:-1]
    a = xy[:-1]
    dxy = np.linalg.norm(a - b, axis=1)

    dt = (np.roll(data_df['Time Elapsed'], -1) - data_df['Time Elapsed'])[:-1]

    speeds = np.divide(dxy, dt)

    speed_df = pd.DataFrame(data={'Time Elapsed':data_df['Time Elapsed'][:-1],'Speed':speeds})

    return speed_df


texts: Passing input parameters correctly to a method

texts:
Below is my Interface:

public interface IDBClient {
    public String read(ClientInput input);
}

This is my implementation of the interface:

public class DatabaseClient implements IDBClient {

    @Override
    public String read(ClientInput input) {

    }
}

Now I have a factory which gets the instance of DatabaseClient like this:

IDBClient client = DatabaseClientFactory.getInstance();
....

Now I need to make a call to read method of my DatabaseClient which accepts the ClientInput parameter and below is the class for the same. This class was not written by me so that is the reason I am having a question on this and I am pretty much sure this is the wrong way of doing it.

public final class ClientInput {

    private Long userid;
    private Long clientid;
    private Long timeout_ms = 20L;
    private boolean debug;
    private Map<String, String> parameterMap;

    public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) {
        this.userid = userid;
        this.clientid = clientid;
        this.parameterMap = parameterMap;
        this.timeout_ms = timeout_ms;
        this.debug = debug;
    }
}

So when customer make a call to read method of DatabaseClient, they will create the ClientInput parameter like this and then use the factory to get the Instance of DatabaseClient and then call the read method accordingly.

Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("attribute", "segmentation");

ClientInput input = new ClientInput(109739281L, 20L, paramMap, 1000L, true);

IDBClient client = DatabaseClientFactory.getInstance();
client.read(input);

Is this the right way of creating the ClientInput and then passing it to the read method? If not, then what's the best way of doing it? Where should I be doing validation check to see whether the customer has passed valid user IDs or valid client ID, etc.?


texts:
Just need to know if I'm doing something wrong in this code. my app seem work fast now with this code. I just want to if i really understant that

   - (void)receive
{

    NSString *post2 = [NSString stringWithFormat:@"expediteur=%@&destinataire=%@",
                       [[expediteurLbl text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                       [[destinataireLbl text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSData *dataToSend2 = [NSData dataWithBytes:[post2 UTF8String] length:[post2 length]  ];

    request2 = [[[NSMutableURLRequest alloc] init] autorelease];
    [request2 setURL:[NSURL URLWithString:@"http:/****************.php"]];
    [request2 setHTTPMethod:@"POST"];
    [request2 setHTTPBody:dataToSend2];
    [request2 setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

    [NSThread detachNewThreadSelector:@selector(displayView) toTarget:self withObject:nil];

    }

    -(void)displayView

    {
        NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
        NSURLResponse *response2;
        NSError *error2;
        NSData *data2 = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&response2 error:&error2];
        reponseServeur2= [[NSMutableString alloc] initWithData:data2 encoding: NSASCIIStringEncoding];

        responseString2 = [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];

        [[reponseServeur2 stringByReplacingOccurrencesOfString:@"\n"  withString:@""] mutableCopy];

        self.messageArray = [responseString2 JSONValue];
        [messTableView reloadData];

        [pool release];

    }

and

- (void)viewDidLoad {
    [super viewDidLoad];

    [self performSelectorInBackground:@selector(receive) withObject:nil];
}


texts: Copying values from one sheet to another

texts:
I am trying to copy values from one sheet to another using loop with two conditions and it is very slow. Removing conditions from code doesn't have any effect on the speed of the execution.
I already have sample sheet where everything is done with functions (if/match/index...) but I would like to remove all functions from this workbook.

Here is the code :

Option Explicit
Private Sub AnalitSample()
    Dim WSS As Worksheet
    Set WSS = Sheets("Source")
    Dim WSD As Worksheet
    Set WSD = Sheets("Dest")

    Dim col As String
    col = "B"

    Dim rCell As Range
    Dim rRng As Range
    Set rRng = WSS.Range("B2:B4000")

    Dim i As Integer
    i = 2

    WSD.Range("B2:G4000").ClearContents

    For Each rCell In rRng.Cells
        If rCell.Value <> "" Then
            If Len(rCell.Value) > 3 Then
            WSD.Range(col & i).Value = rCell.Offset(0, 0).Value
            WSD.Range(col & i).Offset(0, 1).Value = rCell.Offset(0, 1).Value
            WSD.Range(col & i).Offset(0, 2).Value = rCell.Offset(0, 4).Value
            WSD.Range(col & i).Offset(0, 3).Value = rCell.Offset(0, 5).Value
            WSD.Range(col & i).Offset(0, 4).Value = rCell.Offset(0, 6).Value
            WSD.Range(col & i).Offset(0, 5).Value = rCell.Offset(0, 9).Value
            i = i + 1
            End If
            End If
        Next rCell
End Sub

I am asking for a few suggestions on how to speed up this kind of code (for each loop), that I was avoiding in the past because of the speed.


texts:
This code snippet gets the maximum int out of a map's keys

func max(numbers map[int]bool) int {
    var maxNumber int
    for n := range numbers {
        maxNumber = n
        break
    }
    for n := range numbers {
        if n > maxNumber {
            maxNumber = n
        }
    }
    return maxNumber
}


texts: Login System using PHP and PDO Prepared Statement

texts:
vir.php

<?php

require_once '../db.php';

session_start();

if($_SERVER['REQUEST_METHOD'] == 'POST'){

$username = trim($_POST['username']);

try{

  $Query = "SELECT * FROM users WHERE username = :username";
  $statement = $conn->prepare($Query);
  $statement->bindValue(':username', $username);
  $statement->execute();
  $user = $statement->fetch(PDO::FETCH_ASSOC);
  $RowCount = $statement->rowCount();

} catch (PDOerrorInfo $e){

    die('QuerySCD Error '.$e->getMessage());

  }

  if( $RowCount == 0 ){
   // User doesn't exist
    $_SESSION['message'] = "error!";
    header("location: error-login.php");

  } else{ // User exists

      if( password_verify($_POST['password'], $user['password'])){

        $_SESSION['username']  = $user['username'];
        $_SESSION['active']    = $user['active'];

        $_SESSION['logged_in'] = true;

        header("location: riscar.php");

      } else {

          $_SESSION['message'] = "error!";
          header("location: error-login.php");

        }
    }
}

$conn = NULL;

?>

<!DOCTYPE html>

    <title>Login</title>
    <meta charset="UTF-8">

    <form action="vir.php" method="post" autocomplete="off">

        <input type="username" required autocomplete="off" name="username">

        <input type="password" required autocomplete="off" name="password">

        <button name="login">
            Logar
        </button>

    </form>

ir.php

<?php
/* Log out process, unsets and destroys session variables */
session_start();
session_unset();
session_destroy();
?>

<!DOCTYPE html>

    <title>Login</title>
    <meta charset="UTF-8">

<?= 'You have been logged out!'; ?>

error-login.php

<?php
/* Displays all error messages */
session_start();
?>

<!DOCTYPE html>

    <title>Login</title>
    <meta charset="UTF-8">

        <?php
        if( isset($_SESSION['message']) AND !empty($_SESSION['message']) ):
            echo $_SESSION['message'];
        else:
            header( "location: vir.php" );
        endif;
        ?>

Only me will use this login sytem and only me will have the link to this login system, i will use this to insert records on my database.

I don't know if someone could find the link to this login, to i used PDO prepared statement, so prevent against SQL Injection.

How safe is my code?


texts: Translating Dijkstra's Algorithm from Python to C++

texts:
I'm going through the book Grokking Algorithms which is in Python but wanted to write everything in C++. Up to this point everything's been pretty straightforward translation but the code for Dijkstra's algorithm really exploits nested dictionaries and weak typing which I used as an excuse to try out std::optional. I also am playing around with std::set, std::unordered_map, and using typedef to alias ugly types for the first time.

I've retained the original script-like functionality of the original code and have thrown everything into main, and know that a real implementation would be nicely put into a separate function. I am also aware that a real implementation would use a priority queue for finding the minimum cost edge rather than a linear search and wasn't really interested in Dijkstra's but moreso in the C++.

What to Review

Primarily interested in knowing about my usage of typedef in this way, as well as if there was a better way than using std::optional and std::nullopt to handle translating from Python's None type.

C++17 Code

Translated from Python from Grokking Algorithms book.

#include <algorithm>
#include <iostream>
#include <limits>
#include <optional>
#include <set>
#include <unordered_map>

using namespace std;

typedef unordered_map<string, double> CostGraph;
typedef unordered_map<string, optional<string>> ParentGraph;
typedef unordered_map<string, unordered_map<string, double>> WeightedGraph;

auto find_lowest_cost_node(CostGraph costs, const set<string>& processed) {
  auto lowest_cost = numeric_limits<double>::max();
  optional<string> lowest_cost_node = nullopt;
  for (const auto [node, cost] : costs) {
    if (cost < lowest_cost && find(processed.begin(), processed.end(), node) == processed.end()) {
      lowest_cost = cost;
      lowest_cost_node = node;
    }
  }
  return lowest_cost_node;
}

int main() {
  WeightedGraph graph;
  graph["start"] = {};
  graph["start"]["a"] = 6;
  graph["start"]["b"] = 2;

  graph["a"] = {};
  graph["a"]["fin"] = 1;

  graph["b"] = {};
  graph["b"]["a"] = 3;
  graph["b"]["fin"] = 5;

  graph["fin"] = {};

  CostGraph costs;
  costs["a"] = 6;
  costs["b"] = 2;
  costs["fin"] = numeric_limits<double>::max();

  ParentGraph parents;
  parents["a"] = "start";
  parents["b"] = "start";
  parents["fin"] = {};

  auto processed = set<string>{};

  while (const auto node = find_lowest_cost_node(costs, processed)) {
    const auto cost = costs[node.value()];
    const auto neighbours = graph[node.value()];

    for (const auto [n, c] : neighbours) {
      const auto new_cost = cost + c;
      if (costs[n] > new_cost) {
          costs[n] = new_cost;
          parents[n] = node;
        }
    }
    processed.insert(node.value());
  }

  cout << "Costs\n";
  for (const auto [k, v] : costs) {
    cout << k << ": " << v << "\n";
  }

  cout << "Parents\n";
  for (const auto [k, v] : parents) {
    if (v) {
      cout << k << ": " << v.value() << "\n";
    } else {
      cout << k << ": None\n";
    }
  }
}


texts: Counting letters, words, etc. in the input

texts:
I'm trying to learn some coding to broaden my scope of knowledge, and I seemed to have run into a bit of a conundrum.

I'm trying to create a program to output the number of characters, digits, punctuation, spaces, words and lines that are being read in from a file.

Here is the text file I am reading in:

See Jack run. Jack can run fast. Jack runs after the cat. The cat's fur is black. See Jack catch the cat.
Jack says, "I caught the cat."
The cat says, "Meow!"
Jack has caught 1 meowing cat. Jack wants 5 cats, but can't find any more.

Here is my code:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream lab3;
    string word;
    lab3.open("lab3.txt");
    int countletters=0,countnum=0,countpunc=0,countspace=0,words=0,line=0;
    char character,prevchar = 0;
    if(!lab3)
    {
        cout << "Could not open file" << endl;
        return 1;
    }
    while(lab3.get(character) && !lab3.eof())
    {
        if(isalpha(character))
        {
            countletters++;
        }
        if (isdigit(character))
        {
            countnum++;
        }
        if (ispunct(character))
         {
            countpunc++;
            if (isalpha(prevchar))
            {
               words++;
            }
        }
        if (isspace(character))
          {
            countspace++;
            if (isalpha(prevchar))
            {
               words++;
            }
          }
        if(character=='\n')
        {
            line++;
        }
        prevchar = character;
    }
    cout << "There are " << countletters << " letters." << endl;
    cout << "There are " << countnum << " numbers." << endl;
    cout << "There are " << countpunc << " punctuations." << endl;
    cout << "There are " << countspace << " spaces." << endl;
    cout << "There are " << words << " words." << endl;
    cout << "There are " << line << " sentences." << endl;
    lab3.close();
    return 0;
}

Output:

There are 167 letters.
There are 2 numbers.
There are 18 punctuations.
There are 52 spaces.
There are 47 words.
There are 4 sentences.

Some things I am hoping to learn:

Advice for improvements on my code for learning purposes/efficiency.
Explanation for reading information in from a text file: whether it is letters, numbers, punctuation - whatever you may run across doing this type of data-processing.

Some things I am aware of:

using namespace std; is not good practice - what is the best practice for real world applications?
I am a beginner and this may not be (definitely is not) the cream-of-the-crop coding.


texts: Coupon code generator using the strategy pattern in PHP

texts:
Below is the implementation in PHP. I aim to have a different coupon code and a different discount returned, based on the type of book (vintage or new).

<?php

interface BookOffer {
    function generateCoupon();
    function generateDiscount();
}

class VintageBookOffer implements BookOffer {
    function generateCoupon() {
        return "VINTAGECOUPONCODE";
    }

    function generateDiscount() {
        return 10.0;
    }
}

class NewBookOffer implements BookOffer {
    function generateCoupon() {
        return "NEWBOOKCOUPONCODE";
    }

    function generateDiscount() {
        return 5.0;
    }
}

class OfferGenerator {

    function generateOffer($bookType) {

        if($bookType == "vintage") {
            $bookObject = new VintageBookOffer();
        }
        else if($bookType == "newbook") {
            $bookObject = new NewBookOffer();
        }

        return $bookObject;
    }
}

$bookType1 = "vintage";
$bookType2 = "newbook";

$offerGenerator = new OfferGenerator();
$bookOffer1 = $offerGenerator->generateOffer($bookType1);
$bookOffer2 = $offerGenerator->generateOffer($bookType2);

echo "You chose book type " . $bookType1 . ". Your coupon code is " . $bookOffer1->generateDiscount() . ", and your discount is " . $bookOffer1->generateCoupon();

echo "You chose book type " . $bookType2 . ". Your coupon code is " . $bookOffer2->generateDiscount() . ", and your discount is " . $bookOffer2->generateCoupon();

?>

Does this look correct? The only reason I think it might be incorrect is because it does not use type hinting, which is frequently seen in the Strategy Pattern.


texts: Initializing Google APIs serverside in MVC controller

texts:
I have this code in my MVC Controller:
[HttpGet]
[OutputCache(VaryByParam = "*", Duration = 3600, Location =  System.Web.UI.OutputCacheLocation.ServerAndClient)]
public async Task<string> GetAPI(string callback, string libraries)
{
    var location_selector_script = System.IO.File.ReadAllText(Server.MapPath("~/Scripts/nav/locselector.js"));
    var res = await Utilities.API.GetAsync("https://maps.googleapis.com/maps/api/js?key=" + ConfigurationsHelper.GoogleMapsAPIKey
                + "&callback=" + callback + "&libraries=" + libraries);
            return res + location_selector_script;
}

and call it like this:
<script async defer src="/Navigation/GetAPI?callback=initMap&libraries=places"></script>

Is this a good idea to initialize Google APIs in backend?


texts: C++ program to remove duplicate characters from string

texts:
This is a question in the book "Cracking The Coding Interview".

  Design an algorithm and write code to remove the duplicate characters in a string
  without using any additional buffer. NOTE: One or two additional variables are fine.
  An extra copy of the array is not.

  Follow Up

  Write the test cases for this method.  The four test cases are

  String does not contain any duplicates, e.g.: abcd
  String contains all duplicates, e.g.: aaaa
  Null string
  String with all continuous duplicates, e.g.: aaabbb

I want to optimise this code and whether I can use some other function from STL.

#include <iostream>
#include <string>
#include <algorithm>

std::string & removeDuplicate(std::string& str)
{
  int length = str.length();
  for(unsigned int i = 0; i < length; i++)
  {
    char currChar = str[i]; //holds current character
    for(unsigned int j = i+1; j < length; j++)
    {
      if(currChar == str[j])
        str.erase (std::remove(str.begin()+j, str.end(), str[j]), str.end());
    }
  }
  return str;
}

int main()
{
  std::string str;
  std::cout << "Enter string \n";
  std::getline(std::cin, str);
  str = removeDuplicate(str);
  std::cout <<"New String is " << str << "\n";
}


texts: Exception handling with null check in java

texts:
//not an elf file. try PE parser
        PE pe=PEParser.parse(path);
        if(pe!=null)
        {
            PESignature ps =pe.getSignature();
            if(ps==null||!ps.isValid())
            {
                //What is it?
                Toast.makeText(this,"The file seems that it is neither an Elf file or PE file!",3).show();
                throw new IOException(e);
            }
        }
        else
        {
            //What is it?
            Toast.makeText(this,"The file seems that it is neither an Elf file or PE file!",3).show();
            throw new IOException(e);
        }

How can I organize the above code, so that

 //What is it?
          Toast.makeText(this,"The file seems that it is neither an Elf file or PE file!",3).show();
          throw new IOException(e);

Appears  only once, or just be better-looking(easy to read)?

Summary

Please comment or advise on organizing the if statements.


texts: Checking Object keys set with value against another Object keys

texts:
I'm willing to check an an object's values in typescript, based on another object's keys.
The mental model is "the key exists, it's not an object, is the value in obj set, otherwise, it's an object, iterate again".
What would be your recommandations about this simple snippet :
/**
 * Returns an array. If the array is empty, the checked obj is fine.
 * Otherwise it's not.
 *
 * @remarks
 * areValuesSet(obj, rules).length === 0 is the test to make.
 *
 * @param obj {object} - object to verify
 * @param rules {object} - object containing the keys to check against
 * @returns {string[]} - array of incorrect keys
 */
const areValuesSet = (
  obj: { [propKey: string]: any },
  rules: { [propKey: string]: any }
): string[] =>
  Object.keys(rules).reduce((prev, key) => {
    if (typeof rules[key] === "object" && typeof obj[key] === "object") {
      return areValuesSet(obj[key], rules[key]);
    }

    return !obj ||
      !obj[key] ||
      (isEmpty(obj[key]) && typeof obj[key] !== 'boolean')
      ? [...prev, key]
      : [...prev];
  }, []);

I would enhance this with a "validator" function which would call areValuesSet like so :
/**
 * Call `rulesParser` and checks the returned value length equals 0
 *
 * @param obj {object} - object to verify
 * @param rulesObj {object} - object containing the keys to check against
 * @returns {boolean}
 */
export const validateRules = (
  obj: { [propKey: string]: any },
  rulesObj: { [propKey: string]: any }
): boolean => rulesParser(obj, rulesObj).length === 0;

Thank you


texts: Checking if CLI arguments are valid files/directories in Python

texts:
I frequently write Python scripts that require three command line arguments:

config_file — A CSV configuration file
input_dir — The directory containing the input files to be processed
output_dir — The directory where the output files should be stored

I found myself copying/pasting two functions all the time: is_valid_file and is_valid_directory.

Questions

How can I consolidate the is_valid_file and is_valid_directory functions to eliminate duplicate code?
Is there a better way to check that files/directories provided in CLI arguments actually exist?

Code

Here is the code for process_the_data.py:

if __name__ == "__main__":
    # Process the arguments
    import argparse
    import arghelper
    parser = argparse.ArgumentParser(
        description='Process the data.')
    parser.add_argument(
        'config_file',
        help='CSV configuration file.',
        metavar='FILE', type=lambda x: arghelper.is_valid_file(parser, x))
    parser.add_argument(
        'input_dir',
        help='Directory containing the input files.',
        metavar='DIR', type=lambda x: arghelper.is_valid_directory(parser, x))
    parser.add_argument(
        'output_dir',
        help='Directory where the output files should be saved.',
        metavar='DIR', type=lambda x: arghelper.is_valid_directory(parser, x))
    args = parser.parse_args()

Here is the code for arghelper.py:

import os

def is_valid_file(parser, arg):
    if not os.path.isfile(arg):
        parser.error('The file {} does not exist!'.format(arg))
    else:
        # File exists so return the filename
        return arg

def is_valid_directory(parser, arg):
    if not os.path.isdir(arg):
        parser.error('The directory {} does not exist!'.format(arg))
    else:
        # File exists so return the directory
        return arg


texts: Speed up Crawling Every File C:\ and hashing using Java 8

texts:
I am wondering if anyone can help me I am trying to read every file in every directory and create a hash of the file. The code works fine but is extremely slow, I wondering what I can do increase the speed and the performance of the below

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
    Test fw = new Test();
    fw.crawl("c:\\");
}

public void crawl(String path) throws IOException, NoSuchAlgorithmException {

    File root = new File(path);
    File[] list = root.listFiles();

    if (list == null) {
        return;
    }

    for (File f : list) {

        if (f.isDirectory()) {
            crawl(f.getAbsolutePath());
            System.out.println("Name:" + f.getName());
            System.out.println("Dir:" + f.getAbsoluteFile());
        } else {
            System.out.println("Name:" + f.getName());
            System.out.println("File:" + f.getAbsoluteFile());

            InputStream input = new BufferedInputStream(new FileInputStream(f));
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            int tempByte;
            while ((tempByte = input.read()) != -1) {
                md5.update((byte) tempByte);
            }
            System.out.println("Hash:" + Arrays.toString(md5.digest()));
        }
    }
}


texts: Find a Sum of Particles in A Set of Boxes Given a Number of Rows and Columns

texts:
This is a code challenge, from Codewars, the details of the specific challenge in depth can be found here: https://www.codewars.com/kata/magnet-particules-in-boxes/javascript.

The summary of it though is a function which gives a sum of particles in a set of boxes given a number of rows and a number of columns to work with. You are given a specific function that calculates the number of particles in the box based off of the specific box that is being calculated. Here is the equation:

$$ v(k,n) = \frac{1}{k(n + 1)^{2k}} $$

$$
doubles (k_{max}, n_{max}) = \sum_{k=1}^{k_{max}} \sum_{n=1}^{n_{max}} v(k,n)
$$

Here is the function I came up with:

function doubles(maxk, maxn) {

  let total = 0

  for(let k = 1; k <= maxk; k++){
    const twoK = 2*k
    for(let n = 1; n <= maxn; n++){
      total += 1/(k*Math.pow(n+1, twoK))
    }
  }

  return total
}

My function does the job perfectly, and comparing it to other responses marked as 'best practices' it is very similar. But I would like to know if anyone sees obvious ways to improve my function, or I would really love to see something that can improve the time complexity of the function, if that is possible.


texts: Haskell tips/why doesnt this scale linearly?

texts:
My friend wrote a program which compares random arrangements of die faces to find the one with the most evenly distributed faces - especially when the faces are not a mere sequence.

I translated his program into haskell because I've been looking for a reason to talk someone's ear off about how cool haskell is. However, I am not very proficient with haskell (it took me forever to write this and it has undergone a couple giant refactorings) and so I have two problems.

he has been big on optimizing his versions, and this is not very fast, and it does not scale linearly. It goes from 415 checks/s to 97 checks/s when I go from 1000 to 20000 checks. Did I mess up some tail recursion or is it some kind of larger problem?
the code that came out of this isn't actually as elegant as I had predicted. I want this to be a solid showcase of Haskell, if you have any ideas on how to simplify it I am all ears

This is the most relevant code:

-- _CENTERS :: [{ x :: Float, y :: Float, z :: Float}]
-- _VALUES :: [Num]

-- Basically just (repeat $ map rand [0.._SIDES]), but never using a seed twice
randstates from = (take _SIDES (infrand from)) : randstates newseed
    where   infrand seed = seed : infrand (shuffle seed)
            newseed      = (infrand from) !! (_SIDES + 1)

-- yates shuffle
yates _ (last:[]) = [last]
yates (rand:pass) (swap:order) = choice:yates pass rorder
        where   choice = order !! index
                index  = (randfrom rand) `mod` (length order)
                rorder = take (index) order ++ swap : drop (index + 1) order

arrangements seed = map arrange $ randstates seed
        where   arrange rands = yates rands [0.._SIDES - 2]

-- fns comparing arrangements --
arcLength i j = 1 / (1 + _WEIGHT * acos(dot3D / _VEC_LEN_SQUARED))
        where   dot3D    = apply x + apply y + apply z
                apply fn = (fn i) * (fn j)

matrix arr = map crosscmp arr
        where   crosscmp s1  = [ value s1 * (distance s1 s2) | s2  <- arr ]
                distance a b = arcLength (_CENTERS !! a) (_CENTERS !! b)
                value s      = fromInteger $ _VALUES !! s

variance arr = sum $ map perside (matrix arr)
        where   perside s = (sum s - mean) ^ 2
                mean      = (sum (concat $ matrix arr)) / (sides + 1)
                sides     = fromInteger $ toInteger _SIDES

maxDistr = maximumBy (\a b -> variance a `compare` variance b)

Main is basically just

print $ maxDistr $ take _TRIALS $ arrangements seed


texts: Casting base to derived class according to a type flag

texts:
I have been writing an event class for my game engine and I came across to the following problem:

Is casting a base class object to a derived class object given a type flag a good programming design?

Let me give you the following simple example.  I have this enum holding the categories of the events:

enum DisplayEventType
{
    DET_UNSET,
    DET_WINDOW_EVENT,
    DET_KEYBOARD_EVENT,
    DET_MOUSE_EVENT,
    DET_JOYSTICK_EVENT
};

This is the base class of all the events:

typedef std::unique_ptr<DisplayEventData> DisplayEventDataMP;

class DisplayEvent
{
    private:

        // The type of the display event
        DisplayEventType mType;

        // The data of the event
        DisplayEventDataMP mEventData;

    public:

        // Constructor
        DisplayEvent(DisplayEventType type = DisplayEventType::DET_UNSET, DisplayEventDataMP eventData = std::unique_ptr<DisplayEventData>((DisplayEventData*) 0));

        // Retrieves the event type of the current event
        DisplayEventType GetType() const;

        // Sets the event type of the current event
        void SetType(DisplayEventType type);

        // Retrieves a raw pointer to the event data of the current event
        DisplayEventData* GetEventData() const;

        // Sets the event data of the current event
        void SetEventData(DisplayEventDataMP eventData);
};

This is the base class of the event data:

class DisplayEventData
{
    public:

        // Virtual destructor, for the deallocation of the interface implementors to work
        virtual ~DisplayEventData();
};

And these are the derived classes

class WindowEventData : public DisplayEventData
{
    // Window event data specific data and methods
};

class KeyboardEventData : public DisplayEventData
{
    // Keyboard event data specific data and methods
};

class MouseEventData : public DisplayEventData
{
    // Mouse event data specific data and methods
};

class JoystickEventData : public DisplayEventData
{
    // Joystick event specific data and methods
};

Some basic usage would be this:

// Poll for next event in the queue
DisplayEvent ev;
display->PollEvent(ev); // Fills ev with the needed data

if (ev.GetType() == DisplayEventType::DET_KEYBOARD_EVENT)
{
    KeyboardEventData* kev = static_cast<KeyboardEventData>(ev.GetEventData());
    // Do stuff
}

Is the above design viable/correct? If not what would a better alternative be in terms of object oriented or even generic programming?


texts: Sorting an array of numbers in Java with an algorithm

texts:
This is pretty much one of my first programs that I have created in Java and I just wanted to ask if anyone sees some obvious errors or mistakes I made.

The purpose of this program is to sort numbers given by a user using an algorithm.

First off, the program gets an input in form of ints from the user, I have used a popup here, and than creates an array arr1 with that size.
After that, another popup opens that asks the user for the 1st number he wants to sort. Then the 2nd, 3rd, etc, until the array has been filled with ints.

The array gets transferred into the sorting algorithm which, surprise, sorts the numbers into a different array arr2.

This array then gets passed into a method that takes a static frame and puts a text field with the numbers (in correct order) onto it. [+ 1 close and 1 repeat button]

If the repeat method (buttonRetry.addActionListener.actionPerformed) is called / the button is pressed, the frame gets "cleaned" (main_frame.getContentPane().removeAll();) and the main() method is called again.

Is it possible to make the process of this happening (getting input from the user and sorting that input) faster and do you have any additional advice about what and how I did this (Noob errors, graphical tips, etc.).

Here is the code :

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class AWTCounter extends JFrame {

    public static int[] arr1;
    public static JFrame frame = new JFrame("Super Simple Sorting Program");
    public static JFrame main_frame = new JFrame("Super Simple Sorting Program");

    public void main()
    {
        String input_1 = JOptionPane.showInputDialog(frame, "How many numers do you want to sort with SSSP ?");
            if (input_1 == null) {dispose(); System.exit(0);}
        int checksum = Integer.parseInt(input_1);

        arr1 = new int[checksum];

        int logNumber = 0;
        int debug = checksum;
        checksum = 0;

        while (checksum <= debug-1)
        {
            logNumber++;
            String input_2 = JOptionPane.showInputDialog(frame, "Please enter your " + logNumber + " . number.");
            int member = Integer.parseInt(input_2);
            arr1 [checksum] = member ;
            checksum++;
        }

        int[] arr2 = doSelect(arr1);

        print(arr2);
    }

    public int[] doSelect(int[] arr)
    {

        for (int i = 0; i < arr.length - 1; i++)
        {
            int index = i;
            for (int j = i + 1; j < arr.length; j++)
                if (arr[j] < arr[index])
                    index = j;

            int smallerNumber = arr[index];
            arr[index] = arr[i];
            arr[i] = smallerNumber;
        }
        return arr;
    }

    public void print(int[] arr2)
    {
        JTextField t2;

        t2 = new JTextField("Here are your sorted numbers : " + Arrays.toString(arr2));
        main_frame.add(t2, BorderLayout.NORTH);

        JButton buttonEnd = new JButton("Close apllication");
        main_frame.add(buttonEnd, BorderLayout.CENTER);

        JButton buttonRetry = new JButton("Try again !");
        main_frame.add(buttonRetry, BorderLayout.SOUTH);

        main_frame.setLayout(new FlowLayout());
        main_frame.setSize(600,300);
        main_frame.setVisible(true);

        buttonEnd.addActionListener(new ActionListener()
        {

            public void actionPerformed(ActionEvent event)
            {
                dispose();
                System.exit(0);
            }

        });

        buttonRetry.addActionListener(new ActionListener()
        {

            public void actionPerformed(ActionEvent event)
            {
                main_frame.getContentPane().removeAll();
                main();
            }

        });

    }
}


texts:
I love lambdas, and functional programming etc. But sometimes I wonder if I take it too far..

public static T With<T>(this T source, Action<T> action)
{
    action(source);
    return source;
}

public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    return source.Select(x => x.With(action));
}

thoughts?

UPDATE

Some good points, some I agree with, some I don't, but a few details:

I understand that Linq may not be intended to handle side effects, especially since List.ForEach returns void, however I disagree that functional programming can't contain side effects, a monad is simply a chunk of code to execute for a given structure.

The ForEach and With extensions, are meant to be a syntactic sugar.  Perhaps the name is poorly chosen, and it should be something like OnEnumerate, however I wonder if this could get confusing down the line, as its whole point is to invoke side effects at that particular point in the expression, and this could occur multiple times, perhaps I should stick with my With convention and do WithEach.

The comments about using Select internally are probably true, as I'm not really projecting, and yield return saves a method call. (premature optimization anyone?)

public static IEnumerable<T> WithEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach(var x in source)
        yield return x.With(action);
}

To be honest I probably wouldn't use WithEach often, unless its an edge case where I'm passing an IEnumerable<T> that may or may not be enumerated. I can imagine it being effective in generating complex hierarchies. However With I use quite often, usually as a way to chain things together, i.e:

this.SomeObservable = someObservable
    .With(o => o.Subscribe(this.OnNext)
        .With(this._disposables.Add));


texts:
The following code sorts an HTML table with JavaScript (without using any external libraries like jQuery). Are there any shortcomings or possible improvements I could make?

    <meta http-equiv="content-type" content="text/html;charset=Windows-1252">

                Name
                Surname
                Age

                Raja
                Dey
                18

                Mamata
                Sharma
                20

                Avijit
                Sharma
                21

                Sharanya
                Dutta
                26

                Nabin
                Roy
                27


texts: Algorithm for motion detection using ultrasonic sensor on Arduino

texts:
I am using a ultrasonic sensor to detect motion by looking at the variance of the sensor readings, however my algorithm is very prone to give false positives thus erroneously rising a motion event.

Algorithm Background

What I do is send a ping 20 times a second and wait for a pulse to come back using the input capture on arduino. I have a limit of 2 metres because I don't need to detect motion beyond that. Using a modifed version of the NewPing library which has a method check_timer which returns a value greater than 1 if the pulse from the arduino took more than a corresponding wait time for 2 metres and returns 1 if no pulse has been measured yet or 0 if it successfully got a pulse.

The following conditions need to be met to rise a motion event:

If the last measured pulse was a valid pulse (i.e check_timer returns 0) it will save it in an array and wait for
another positive pulse and only then test for the variance of the two
pulses. However if it failed to measure a valid pulse after the first
success it will reset the array.
If a variance greater than or equal to 500 is measured within a time
frame it will rise a motion event.

The code for my algorithm is this:

#include <NewPing.h>

#define TRIGGER_PIN   10 // Arduino pin tied to trigger pin on ping sensor.
#define ECHO_PIN      9 // Arduino pin tied to echo pin on ping sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

unsigned int pingSpeed = 50; // How frequently are we going to send out a ping (in milliseconds). 50ms would be 20 times a second.
unsigned long pingTimer;     // Holds the next ping time.

unsigned long last = 0;
unsigned int samples = 2;
unsigned int distances[2];
unsigned int sum = 0;

void setup() {
  Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results.
  pingTimer = millis(); // Start now.
}

void loop() {
  // Notice how there's no delays in this sketch to allow you to do other processing in-line while doing distance pings.
  if (millis() >= pingTimer) {   // pingSpeed milliseconds since last ping, do another ping.
    pingTimer += pingSpeed;      // Set the next ping time.
    sonar.ping_timer(echoCheck); // Send out the ping, calls "echoCheck" function every 24uS where you can check the ping status.
  }
  // Do other stuff here, really. Think of it as multi-tasking.
}

void echoCheck() { // Timer2 interrupt calls this function every 24uS where you can check the ping status.
  uint8_t rc = sonar.check_timer();
  if(rc==0) { // This is how you check to see if the ping was received.
    sum = sum + sonar.ping_result;
    distances[--samples] = sonar.ping_result;
    if(samples == 0) {
      float avrg = (float)(sum) / 2.0f; // Get the average of the samples we recorded
      float sum1 = 0;
      for(int i=1;i>-1;--i) {
        sum1 = sum1 + pow((distances[i] - avrg),2);
      }
      if((sum1 / 2.0f) >= 500.0f) { // If the variance of the samples is greater than or equal to 500
        unsigned long now = millis();
        if(now-last <= 250) { // To filter out random false positives we want two positves within this time frame
          Serial.print("motion event, variance is ");
          Serial.println(sum1 / 2.0f);
        }
        last = now;
      }
      sum = 0;
      samples = 2;
    }
  }else if(rc>1) { // Was it a faulty reading (e.g it exceeded the maximum waiting time)?
    sum = 0;
    samples = 2;
  }
}

My code works but is very unreliable. How can I improve this algorithm?

(EDIT: FYI the sensor I am refering to is a cheap HC - SR04 Ultrasonic Ranging Module.)


texts: Timer Tick Event only to execute at specific time

texts:
I have a timer that is only supposed to tick between x and x on weekdays.

I have used the following implementation.

 void tmrMain_Tick(object sender, EventArgs e)
    {
        if (!(DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday))
        {
            if ((IsTimeOfDayBetween(DateTime.Now, new TimeSpan(8, 0, 0), new TimeSpan(18, 0, 0))))
            {
                if (pnlAssembly.Visible == true)
                {
                    cmdShed.PerformClick();

                }
                else if (pnlShed.Visible == true)
                {
                    cmdServices.PerformClick();
                }
                else if (pnlWeb.Visible == true)
                {
                    cmdAssembly.PerformClick();
                }
            }
        }
    }
    static bool IsTimeOfDayBetween(DateTime time,
                                  TimeSpan startTime, TimeSpan endTime)
    {
        if (endTime == startTime)
        {
            return true;
        }
        else if (endTime < startTime)
        {
            return time.TimeOfDay <= endTime ||
                time.TimeOfDay >= startTime;
        }
        else
        {
            return time.TimeOfDay >= startTime &&
                time.TimeOfDay <= endTime;
        }

    }

Is this the way to go?


texts: Why does lu-factorization make my program slower?

texts:
I'm trying to calculate the smallest eigenvalue of the matrix A by using the "inverted exponentiation method" (see the code). I manage to find the smallest eigenvalue, but when I try to optimize the algorithm by using both the MATLAB functions sparse and lu it starts to iterate many more times! The matrix A is a big diagonal matrix, so it is sparse. It's only the lu-factorization that messes things up. Sparse works fine, although it doesn't make the program much faster...

reldif = 1;
m0 = 0;
dif0 = 1;
iter = 0;

s = size(A);
x = ones(s(1),1);

C = sparse(lu(A));

while reldif > 1.0*10^(-8)
    t = x/norm(x);
    x = C\t;
    mu = t'*x
    dif = m - m0;
    K = abs(dif/dif0);
    reldif = abs(K/(1-K)*dif/m);
    m0 = m;
    dif0 = dif;
    iter = iter + 1;
end
lambda = 1/m

Can someone help me understand how lu works? I'm not sure if I'm using it right because my program should be faster and not slower with it, right?


texts:
I have a class that delegates some responsibilities to another helper class which is abstract. When instantiating the class the user needs to provide a pointer to a concrete instance of the abstract helper class. I'm wondering who should be responsible for deleting the helper class instance, the user, or the class itself?

It seems to me that it is better for the class to delete the helper since it ensures that the lifetime of the helper class instance is the same as the lifetime of the class thats using it.

P.S. I know shared pointers can help but I'd rather avoid them here.

Specifically which is better, this:

classifier.h

class Classifier {
 public:
  Classifier(const Trainer* trainer);
  Train(const RecordList& training_records);
  ~Classifier();
 private:
  const Trainer* trainer_;
  Vector parameters_;
}

classifier.cpp

Classifier::Classifier(const Trainer* trainer)
    : trainer_(trainer);

Classifier::Train(const RecordList& training_records) {
  parameters = trainer_->UpdateParameters(training_records);
}

Classifier::~Classifier() {
  delete trainer_;
}

main.cpp

int main() {
  Classifier classifier(new SgdTrainer());
}

Or is this better?

classifier.h

class Classifier {
 public:
  Classifier(const Trainer* trainer);
  Train(const RecordList& training_records);
 private:
  const Trainer* trainer_;
  Vector parameters_;
}

classifier.cpp

Classifier::Classifier(const Trainer* trainer)
    : trainer_(trainer);

Classifier::Train(const RecordList& training_records) {
  parameters = trainer_->UpdateParameters(training_records);
}

main.cpp

int main() {
  SgdTrainer trainer();
  Classifier classifier(&trainer);
}


texts: Speed up projection of a bipartitie network for a big file using NetworkX and Pandas

texts:
I have a pretty big file (3 million lines) with each line being a person-to-event relationship. Ultimate, I want to project this bipartite network onto a single-mode, weighted, network, and write it to a CSV file. I'm using NetworkX, and I've tested my code on smaller sample datasets, and it works as it should. However, I need to scale this code up to handle my actual dataset, so I need my code to be as efficent as possible and not just maxes out on memory and spins and spin on this last step like it currently does.

I'm using an AWS EC2 machine with 64GB of memory.

After some sample testing, I've realized that things are getting hung up on the second to last step where the bipartite graph (user-to-event) is being projected into a single-mode (user-to-user, based on shared event) graph.

More information about the original data: Some events have only 1 person attending them, while other events have 5,000 people attending them. Because of this, there will be a huge number of edges (I predict ~50M) created when the bipartite network is folded onto a single-mode network.

In order to hopefully speed things up, I've altered to source code of NetworkX's weighted_projected_graph function to not write the projected graph to a new graph as it typically is done, but instead write those edges to a list, and then write that list to CSV with Pandas.

I'm sure there are other ways to speed up the projection portion of this code.

Code using NetworkX to Project Bipartite Network and Pandas to Write the File:

# import modules
import time
import csv
import networkx as nx
from networkx.algorithms import bipartite
import datetime
import pandas as pd

startTime = datetime.datetime.now()

# rename files
infile = 'release-youtube-links.csv'
name_outfile_pd = infile.replace('.csv', '_nameFolded_pd.csv.')
print 'Files renamed at: ' + str(datetime.datetime.now() - startTime)

# load CSV into a dict
with open(infile, 'rb') as csv_file:
    rawData = list(csv.DictReader(csv_file))
    print 'Files loaded at: ' + str(datetime.datetime.now() - startTime)

for i in rawData:
    i['Name'] = 'Name:' + i['Name']
    i['Event'] = 'Event:' + i['Event']

# create edgelist for Name -x- Event relationships
edgelist = []
for i in rawData:
    edgelist.append(
    (i['Event'],
     i['Name'])
    )
print 'Bipartite edgelist created at: ' + str(datetime.datetime.now() - startTime)

# deduplicate edgelist
edgelist = sorted(set(edgelist))
print 'Bipartite edgelist deduplicated at: ' + str(datetime.datetime.now() - startTime)

# create a unique list of Name and Event for nodes
Event = sorted(set([i['Event'] for i in rawData]))
Name = sorted(set([i['Name'] for i in rawData]))
print 'Node entities deduplicated at: ' + str(datetime.datetime.now() - startTime)

# add nodes and edges to a graph
B = nx.Graph()
B.add_nodes_from(Event, bipartite=0)
B.add_nodes_from(Name, bipartite=1)
B.add_edges_from(edgelist)
print 'Bipartite graph created at: ' + str(datetime.datetime.now() - startTime)

# create bipartite projection graph
name_nodes, event_nodes = bipartite.sets(B)
event_nodes = set(n for n,d in B.nodes(data=True) if d['bipartite']==0)
name_nodes = set(B) - event_nodes

# project graph and write projected graph's edgelist to a list
if B.is_multigraph():
    raise nx.NetworkXError("not defined for multigraphs")
if B.is_directed():
    pred = B.pred
else:
    pred = B.adj
    G = nx.Graph()
G.graph.update(B.graph)
G.add_nodes_from((n,B.node[n]) for n in name_nodes)
n_top = float(len(B) - len(name_nodes))
folded = []
for u in name_nodes:
    unbrs = set(B[u])
    nbrs2 = set((n for nbr in unbrs for n in B[nbr])) - set([u])
    for v in nbrs2:
        vnbrs = set(pred[v])
        common = unbrs & vnbrs
        weight = len(common)
        row = u, v, weight
        folded.append(row)

# write projected graph list to CSV
df = pd.DataFrame(folded)
df.to_csv(name_outfile_pd)


texts: Optimizing a dynamic programming solution for "Oil Well"

texts:
I'm trying to solve the Oil Well problem on Hackerrank using dynamic programming and it works. However, it times out for some of the test cases. I wanted to know how this program can be improved so that it runs faster.

The challenge is, given a matrix \$M\$ of size \$r \times c\$ (at most \$50 \times 50\$), where each \$M_{x,y}\$ is either 0 or 1, find the minimum cost path \$E\$ for a spanning tree that connects all the entries where \$M_{x,y} = 1\$.  The cost metric is based on ACME distance: \$\max(\left|x - x_1\right|, \left|y - y_1\right|)\$ where \$x, y\$ is the position of the existing wells, and \$x_1, y_1\$ is the position of the new well.

My basic idea is:

$$f(\mathrm{vertices}) = \min( \max(v_i \to \{\mathrm{vertices} - v_i\}) + f(\mathrm{vertices} - v_i))$$

for all vertices \$v_i\$.

The Hackerrank editorial shows a different logic but I'm trying to optimize my solution.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
#include <climits>
#include <map>
#include <sstream>

using namespace std;
map<string,int> cache;
map<pair<int,int>,int> pd;
string has(vector<int>& vertices)
{
    ostringstream s;
    for(int i = 0; i < vertices.size(); i++)
    {
        s << vertices[i] << "|";
    }
    return s.str();
}
int dist(vector<int>& vertices)
{
    if(vertices.size() <= 1)
        return 0;
    string h = has(vertices);
    if(cache.count(h) != 0) {
        return cache[h];
    }
    int mind = INT_MAX;
    for(int i = 0; i < vertices.size(); i++) {
        int iv = vertices[i];
        int x = 0;
        for(int j = 0; j < vertices.size(); j++) {
            int ov = vertices[j];
            x = max(x,pd[make_pair(min(iv,ov),max(iv,ov))]);
        }
        vertices.erase(vertices.begin()+i);
        mind = min(x + dist(vertices), mind);
        vertices.insert(vertices.begin()+i,iv);
    }
    cache[h]=mind;
    return mind;
}
int main() {
    int r, c;
    cin >> r >> c;
    vector<pair<int,int>> vertices;
    int a;
    for(int i = 0; i < r; i++) {
        for(int j = 0; j < c; j++) {
            cin >> a;
            if(a) {
                vertices.push_back(make_pair(i,j));
            }
        }
    }
    vector<int> vv;
    for(int i = 0; i < vertices.size(); i++) {
        vv.push_back(i);
        for(int j = i+1; j < vertices.size();j++) {
            pair<int,int> ip = vertices[i];
            pair<int,int> op = vertices[j];
            int d = max(abs(ip.first - op.first),abs(ip.second - op.second));
            pd[make_pair(i,j)] = d;
        }
    }
    cout << dist(vv) << endl;
    return 0;
}


texts: CodeIgniter maintain data through Controllers

texts:
I have a main menu in my application.  It loads depending on the role of the user that I validate from a table in my data base, but I have to recreate this menu every time I call a new controller.

User Controller:

class User extends Ci_Controller {

    function __construct(){

        parent::__construct();

        if (!$this->session->userdata('session_user')) {
            $this->session->set_flashdata("mensaje", 'No cuenta con permisos *');
            redirect();
            $this->session_usuario = 1;
        }

        $session_data = $this->session->userdata('session_user');
        $image        = $session_data['img'];
        $nickname     = $session_data['nick'];
        $res          = "";

        $this->layout->setLayout('layout/admin');
        $this->layout->setImage(base_url().$image);
        $this->layout->setNick($nickname);

        $data['module'] = $this->usuarios_model->seleccionarModulos($session_data['perfil'] );

        for ($i=0; $i < count($data['module']) ; $i++) {
            $info['functionality'] = $this->usuarios_model->seleccionarFuncionalidades(     $session_data['usuario'], $data['module'][$i]['id']);
            $data['module'][$i]['route'] = $this->load->view($data['module'][$i]['route'], $info, true);
        }

        foreach ($data['module'] as $key => $value) {
            $res .= $value['route'];
        }

        $this->layout->setMenu($res);

    }

And exactly the same in the Support Controller:

class Support extends Ci_Controller {

    private $user;
    private $permiso;
    private $order;

    function __construct(){

        parent::__construct();

        if (!$this->session->userdata('session_user')) {
            $this->session->set_flashdata("mensaje", 'No cuenta con permisos *');
            redirect();
            $this->session_usuario = 1;
        }

        $session_data = $this->session->userdata('session_user');
        $image        = $session_data['img'];
        $nickname     = $session_data['nick'];
        $res          = "";

        $this->layout->setLayout('layout/admin');
        $this->layout->setImage(base_url().$image);
        $this->layout->setNick($nickname);

        $data['module'] = $this->usuarios_model->seleccionarModulos($session_data['perfil'] );

        for ($i=0; $i < count($data['module']) ; $i++) {
            $info['functionality'] = $this->usuarios_model->seleccionarFuncionalidades(     $session_data['usuario'], $data['module'][$i]['id']);
            $data['module'][$i]['route'] = $this->load->view($data['module'][$i]['route'], $info, true);
        }

        foreach ($data['module'] as $key => $value) {
            $res .= $value['route'];
        }

        $this->layout->setMenu($res);

    }

I know that it's a wrong way to solve this problem, and I want to improve it and reuse the code.


texts: Oriented-object approach on how to control different classes cleanly

texts:
I'm currently creating a client/server application (using Java) and I want to make it fully controllable by an input stream (currently the console). At the moment only one class have to be controlled, but I want my code to stay easy to develop.

I found a solution but I think I can do better, so that's why I post this message: I want your advices on my method now and how I could improve it or how should it better be.

Here's my solution:

I created an interface CommandControllable like:

import java.util.ArrayList;

public interface CommandControllable
{
    public void execute(Command command);
    public void addCommandManager(CommandManager commandManager);
    public ArrayList<CommandManager> getCommandManagers();
}

A class Command like

public class Command
{
    protected String request;

    public Command(String request)
    {
        this.request = request;
    }

    public String ToString()
    {
        return this.request;
    }
}

A class CommandManager

import java.io.InputStream;
import java.util.Scanner;

public class CommandManager implements Runnable
{
    protected Scanner reader;
    protected CommandControllable toControl;
    protected boolean running = false;

    public CommandManager(InputStream stream)
    {
        this.reader = new Scanner(stream);
    }

    @Override
    public void run()
    {
        this.running = true;
        while(this.running)
            {
                if(this.reader.hasNextLine())
                    {
                        Command c = new Command(this.reader.nextLine());
                        this.toControl.execute(c);
                    }
            }
    }

    public void setControllable(CommandControllable toControl)
    {
        this.toControl = toControl;
    }

    public void stop()
    {
        this.running = false;
    }
}

If I want a class to be controllable I write something like:

public class Server implements CommandControllable
{
    protected ArrayList<CommandManager> commandManagers = new ArrayList<CommandManager>();

    public Server()
    {

    }

    public void stop()
    {
        System.out.println("Server stopped");
    }

    @Override
    public synchronized void execute(Command command)
    {
        switch(command.ToString())
        {
            case "quit":
                stop();
                break;
            default:
                System.out.println("Unrecognized command");
                break;
        }
    }

    @Override
    public void addCommandManager(CommandManager commandManager)
    {
        commandManager.setControllable(this);
        this.commandManagers.add(commandManager);
    }

    @Override
    public ArrayList<CommandManager> getCommandManagers()
    {
        return this.commandManagers;
    }
}

And

public static void main(String[] args)
{
    Server s = new Server();
    CommandManager manager = new CommandManager(System.in);
    s.addCommandManager(manager)

    Thread t_manager = new Thread(manager);
    t_manager.start();
}

Any advices on the current solution and how to improve it?


texts:
I'm building an app that tells you a stock's percentage change in price between two dates by using Yahoo's API. Given a stock ticker and two dates, it currently outputs the percentage return to the console.

I would like to later expand this app to give it a list of stock tickers and dates. For each, it would return the performance relative to another stock between the dates.

I want the app to try to pull stock data from the Yahoo API, but to then try another API if the data for that stock is not available from Yahoo.

Here's what I have so far. I believe I'm using the revealing module pattern (although maybe not correctly). Any advice on how I can structure this code to maintain simplicity and comprehensibility as I add functionality would be appreciated. I'm open to input on whether that should be another design pattern or programming style altogether.

$(function () {

    // This object provides the stock ticker,
    // as well as the dates to compute the percentage
    // change of the stock's price between.
    var stock = {
        ticker: 'fb',
        startDate: '2015-08-06',
        endDate: '2016-04-12'
    };

    yahooFinance.getStockData(stock);
});

var utility = {};
(function () {

    var removeLeadingZero = function removeLeadingZero (strNumber) {
        if (strNumber.charAt(0) === '0') {
            return strNumber.substr(1);
        }else{
            return strNumber;
        }
    };

    var formatForConsole = function formatForConsole (dateString) {

        var dateStringArray = dateString.split('-');

        var month = removeLeadingZero(dateStringArray[1]);
        var day = removeLeadingZero(dateStringArray[2]);
        var year = dateStringArray[0];

        return month + '/' + day + '/' + 'year';
    };

    var getPercentChange = function getPercentChange (startingPrice, endingPrice) {
        return ((endingPrice - startingPrice) / startingPrice) * 100;
    };

    $.extend(utility, {
        formatForConsole: formatForConsole,
        getPercentChange: getPercentChange
    });
}());

var yahooFinance = {};
(function () {

    // Returns the URI to request daily price data for the stock in JSON format.
    var getUri = function getUri (stockObj) {

        return 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo'
            + '.finance.historicaldata%20where%20symbol%20%3D%20%22'
            + stockObj.ticker
            + '%22%20and%20startDate%20%3D%20%22'
            + stockObj.startDate
            + '%22%20and%20endDate%20%3D%20%22'
            + stockObj.endDate
            + '%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
    };

    var getStockData = function getStockData (stockObj) {

        $.getJSON(getUri(stockObj), function (priceData) {

            var startDate = utility.formatForConsole(stockObj.startDate);
            var endDate = utility.formatForConsole(stockObj.endDate);
            console.log(startDate + ' to ' + endDate);

            var pricesArray = priceData.query.results.quote;

            var startingPrice = pricesArray[pricesArray.length - 1].Adj_Close;
            var endingPrice = pricesArray[0].Adj_Close;
            var percentChange = utility.getPercentChange(startingPrice, endingPrice);
            console.log(percentChange);
        });
    };

    $.extend(yahooFinance, {
        getStockData: getStockData
    });
}());


texts:
How would I go about shortening this code?
I'm sure there's a smarter way to write the code.
It's working fine, it's just ugly.

It is a way to scrape the number of items on an e-commerce site.

import requests
from bs4 import BeautifulSoup
import re

url1 = "https://us.pandora.net/en/charms/?sz=30&start={}&format=page-element"
url2 = "https://us.pandora.net/en/bracelets/?sz=30&start={}&format=page-element"
url3 = "https://us.pandora.net/en/rings/?sz=30&start={}&format=page-element"
url4 = "https://us.pandora.net/en/necklaces/?sz=30&start={}&format=page-element"
url5 = "https://us.pandora.net/en/earrings/?sz=30&start={}&format=page-element"

#res = requests.get(link.format(url1),headers={"User-Agent":"Mozilla/5.0"})

soup1 = BeautifulSoup(requests.get(url1.format(0)).text, 'lxml')
soup2 = BeautifulSoup(requests.get(url2.format(0)).text, 'lxml')
soup3 = BeautifulSoup(requests.get(url3.format(0)).text, 'lxml')
soup4 = BeautifulSoup(requests.get(url4.format(0)).text, 'lxml')
soup5 = BeautifulSoup(requests.get(url5.format(0)).text, 'lxml')

total_items1 = ''.join(re.findall(r'\d', soup1.select_one('span.products-count').text))
total_items2 = ''.join(re.findall(r'\d', soup2.select_one('span.products-count').text))
total_items3 = ''.join(re.findall(r'\d', soup3.select_one('span.products-count').text))
total_items4 = ''.join(re.findall(r'\d', soup4.select_one('span.products-count').text))
total_items5 = ''.join(re.findall(r'\d', soup5.select_one('span.products-count').text))

#categories = [tag['title'].strip() for tag in soup.select('.refinement-link[title]')

#total_items_sale1 = ''.join(re.findall(r'\d', soup1.select_one('.grid-tile .price-standard')))
#total_items_sale1
#total_items_sale1
#total_items_sale1
#total_items_sale1

#print('Categories:')

#for category in categories:
    #print('\t{}'.format(category))
print('\nTotal Charms: {}'.format(total_items1))
print('\nTotal Bracelets: {}'.format(total_items2))
print('\nTotal Rings: {}'.format(total_items3))
print('\nTotal Necklaces: {}'.format(total_items4))
print('\nTotal Earrings: {}'.format(total_items5))


texts:
Would this todo list benefit from breaking it down into more components?  What would be the advantages?  Am I breaking any best practices from what is seen here?

var TodoList = React.createClass({
    getInitialState: function(){
        return {
            todos:data,
            text:""
        };
    },
    handleChange: function(event){
        this.setState({text:event.target.value });
    },
    submitHandler: function(event){
        event.preventDefault();
        var todo = this.state.text;
        data.push({task:todo});
        this.setState({text:""});
        $('#input').val("")
    },
    render: function(){
        var rows = [];
        this.state.todos.forEach( function(todo, index){
            rows.push(
{todo.task}
)
        });

        return(

                <form onSubmit={this.submitHandler}>

                        {rows}

                    <input id="input" key={this.state.timestamp} onChange={this.handleChange} type="text" />

                    <button type="submit" className="btn btn-primary" disabled={this.state.text.length === 0}>Submit</button>
                </form>

        )
    }
});

var data = [
    {task:"eat cheese"},
    {task:"go to gym"},
    {task:"do some yoga"},
    {task:"go to sleep"}
];

ReactDOM.render(<TodoList/>, document.getElementById('app') );


texts: Timeout Error in Fraudulent Activity Notification HackerRank

texts:
I am solving this problem: Fraudulent Activity Notifications on HackerRank. I am done with my code and is working, but it is inefficient as well for very large inputs.

  I don't know but after all my efforts, I am able to give out good solution to a problem of a MEDIUM LEVEL but this timeout error happens every time for very large inputs. I have tried optimizing my code and still I get timeout errors.
  My agendas for this question and upcoming questions are:

  How to put efficiency for very large inputs. What kind of intellect it requires.
  How to reach to that level. What should I prepare for this.
  Code optimization

I am open to learning, and I am really desperate to learn how to write a more advanced and optimized code to make myself better. I am open to do hard work.

My Algorithm:

  For this problem we must go from incrementing variable i till len(givenArray)-d
  Take a variable for the next variable to be compared, my case iterate is the variable
  Pass the values to the particular array to the method for counting countFraud()
  Add it to the count variable
  Increment iterate variable

Code:

# this is for counting the trailing array
def countFraud(arr, nextNum):
    count = 0
    median = 0.0
    d = len(arr)
    #for calculating the median correctly
    arr.sort()
    if d%2 != 0:
        median = arr[int(d/2)]
    else:
        n = int(d/2)
        median = (arr[n] + arr[n-1]) / 2

    #now the opeartion for count from the array
    if nextNum >= 2*median: count += 1
    return count

# Complete the activityNotifications function below.
def activityNotifications(expenditure, d):
    count = 0
    iterate = d
    # it will go upto the len of array - d, so that it will go upto the d length
    # leaving the last element everytime for the comparision
    for i in range(len(expenditure)-d):
        count += countFraud(expenditure[i:iterate], expenditure[iterate])
        iterate += 1
    return count

Now previously I was doing two loops, adding the items to the new_array and passing it to the the countFraud(). But now I have optimized it and made it sort of O(N).

I don't know but this code is not getting submitted for all TCs due to Timeout Error. There is no problem in operation part. It is just with the efficiency of the code.

Timeout Error Input Example:

200000 10000

Link for input - Input Data

Expected Output:

633

I have read upon this article: HackerRank Environment to learn about the timing issue. For Python/Python 3 it is 10 seconds. My code is definitely taking more than that for values greater than 10^3 or 4.

My code has successfully passed 3 TCs though.


texts: Wrapping jQuery empty() To Include A Callback

texts:
I needed to write a method to extend the jQuery empty() function to include a callback. Since I didn't want to mess with namespaces, closures, etc, I instead wrote a regular function to wrap empty().

var emptyWithCallback = function(node, callback) {
    console.log('Entered emptyWithCallback()');
    if (typeof callback != 'function') {
        return false;
    }
    var doTheCallback = callbackWrapper();
    var doTheEmpty = myEmpty();

    function callbackWrapper() {
        var deferredCallback = $.Deferred();
        callback();
        deferredCallback.resolve();

        return deferredCallback.promise();
    }

    function myEmpty() {
        var deferredEmpty = $.Deferred();
        $(node).empty();
        deferredEmpty.resolve();

        return deferredEmpty.promise();
    }

    doTheCallback.then(doTheEmpty);
}

I was attempting to use the $.Deferred() in case the callback contained an ajax call, in order to not execute the .empty() until the callback concluded.

Does this code look like it will work? It seems to work on simple callbacks, such as a single alert() or console.log().


texts:
I wanted to give Haskell a try, and I started with a simple exercise I found here.

  Write isPrime :: Integer -> Bool, which determines whether a given
  integer is prime.
  Define primes :: [Integer], the list of all primes.
  Revise isPrime so that it only tests divisibility by prime factors.

My answer to Q1

isPrime :: Integer -> Bool
isPrime v = let maxDiv = floor(sqrt (fromIntegral v))
            in all (\x -> (v `rem` x) /= 0) [2..maxDiv]

This one was easy, except for the explicit numeric types conversions I had a hard time to get right.

My answer to Q2

primes = filter isPrime [0..]

This one was easy, too.

My answer to Q3

It took me several hours to answer this one. I quickly understood that isPrime could leverage the values already computed in the array primes. So, my first attempt was :

isPrime :: Integer -> Bool
isPrime v | v < 2 = False
          | otherwise = all (\x -> (v `rem` x) /= 0) (takeWhile (<v) primes)

isPrime works fine for v=0 and v=1, but hangs forever for v>1. Ok, I get it : the mutual recursion creates an infinite loop, due to takeWhile trying to access a primes element which is not yet computed.

One thing I don't understand though, is why primes !! 0 and primes !! 1 hang forever, too.

I tried many approaches for replacing this (takeWhile (<v) primes) by an expression that would stop before reaching a not-yet-computed value. I came to this solution :

isPrime :: Integer -> Bool
isPrime v | v < 2 = False
          | v == 2 = True
          | otherwise = all (\x -> (v `rem` x) /= 0) (takeWhile' (\t -> t*t<=v) primes)

takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' p (x:xs) = if p x then x : takeWhile' p xs else [x]

This solution works. But I had to define a takeWhile' that works just like takeWhile, but also includes the first non-matching element.

Here are my questions to you :

QA : why do primes !! 0 and primes !! 1 hangs in my first attempt ?

QB : is there a magical takeWhileOnlyForAlreadyComputedElements function ? Or a construct that would prevent the infinite loop of this mutual recursion ?

QC : does takeWhile' already exist in the stdlib ? Or maybe the same effect can be achieved in a simpler way ?


texts:
Background:

I'm a member of my high school's robotics club (and in charge of the
programming team).  The robot is going to be written in C++, but I'm mostly
a Python coder and want to make sure I don't have any fundamental gaps in my
knowledge.

In preparation for the start of the competition in just a few days, I've
quickly written up the bare minimum required for a robot to drive around
(included below).  I was hoping to get feedback and criticism at this stage
to nip any problems/misconceptions I have before they get serious.

As previously stated, I'm unfamiliar with C++ so don't know many of its best
practices/idioms/etc.  What I'm looking for is a bit vague, but in essence,
how can I make my code more professional/better?  Am I making any errors?

Any feedback would be welcome.

There are three files:

MainRobot.h
MainRobot.cpp
typedefs.h

MainRobot.h

#ifndef MAINROBOT_H_
#define MAINROBOT_H_

// 3rd-party modules
#include "WPILib.h"

// Modules created by us
#include "typedefs.h"

class MainRobot : public SimpleRobot
{
public:
    // Required methods (for robot to run)
    MainRobot(void);
    void Autonomous(void);
    void OperatorControl(void);

    // Objects (provided by WPILib.h)
    RobotDrive robotDrive;
    Joystick *leftStick;
    Joystick *rightStick;
    Timer timer;

    // Motor ports (hardware)
    static const UINT32 kLeftFrontMotor = kPWMPort_1;
    static const UINT32 kRightFrontMotor = kPWMPort_2;
    static const UINT32 kLeftBackMotor = kPWMPort_3;
    static const UINT32 kRightBackMotor = kPWMPort_4;

    // Joystick ports (hardware)
    static const UINT32 kRightJoystickPort = kUSBPort_1;
    static const UINT32 kLeftJoystickPort = kUSBPort_2;

    // Delay to prevent spamming motors with input
    static const float kDelayValue = 0.01;
};

#endif /*MAINROBOT_H_*/

MainRobot.cpp

#include "MainRobot.h"

/**
 * The constructor.
 *
 * Initializes the motors, drivetrain, joysticks, safety devices, etc.
 */
MainRobot::MainRobot(void):
    robotDrive(kLeftFrontMotor,
               kRightFrontMotor,
               kLeftBackMotor,
               kRightBackMotor)
{
    MainRobot::GetWatchdog().SetExpiration(0.1);    // In seconds

    MainRobot::leftStick = new Joystick(kLeftJoystickPort);
    MainRobot::rightStick = new Joystick(kRightJoystickPort);

    return;
}

/**
 * Initializes the autonomous period when called
 * (robot performs a task without human intervention)
 *
 * Currently left blank.
 */
void MainRobot::Autonomous(void) {
    while(MainRobot::IsAutonomous()) {
        MainRobot::GetWatchdog().Feed();
        Wait(kDelayValue);
        // Do nothing.
    }
    return;
}

/**
 * Initializes the teleoperated period when called.
 * (robot is driven by humans using two joysticks)
 */
void MainRobot::OperatorControl(void) {
    MainRobot::GetWatchdog().SetEnabled(true);

    MainRobot::timer.Reset();
    MainRobot::timer.Start();

    while(MainRobot::IsOperatorControl()) {
        MainRobot::robotDrive.TankDrive(MainRobot::leftStick,
                                        MainRobot::rightStick);
        MainRobot::GetWatchdog().Feed();
        Wait(kDelayValue);
    }
    return;
}

typedefs.h

#ifndef TYPE_DEFS_H_
#define TYPE_DEFS_H_

// The available ports for any motors
typedef enum {
    kPWMPort_1 = 1,
    kPWMPort_2 = 2,
    kPWMPort_3 = 3,
    kPWMPort_4 = 4,
    kPWMPort_5 = 5,
    kPWMPort_6 = 6,
    kPWMPort_7 = 7,
    kPWMPort_8 = 8,
    kPWMPort_9 = 9,
    kPWMPort_10 = 10
} PWMPorts;

// The available ports for USB drives (for joysticks, etc)
typedef enum {
    kUSBPort_1 = 1,
    kUSBPort_2 = 2,
    kUSBPort_3 = 3,
    kUSBPort_4 = 4
} USBPorts;

#endif


texts: Print input lines longer than 80 characters

texts:
"The C Programming Language" (2nd Edition) by Kernighan and Richie has this exercise:

  Write a program to print all input lines that are longer than 80 characters

I have written the following code for this exercise:

#include <stdio.h>

#define MAXLEN 1000
#define MINLEN 80

int main(void)
{
    int c;
    int index = 0;
    char line[MAXLEN];

    while ((c = getchar()) != EOF)
    {
        if (c != '\n')
        {
            line[index] = c;
            ++index;
        }

        else
        {
            line[index] = '\0';

            if (index >= MINLEN)
            {
                printf("%s\n", line);
            }
            index = 0;
        }
    }

    return 0;
}

This code is shorter than many other suggestions I found on the Internet. The code I wrote seems to be working. Am I missing something, or can I suppose that this code is fine for the exercise?


texts: Simplify JavaScript collision detection with offset

texts:
I am working on a background project that is a little interactive. Now I am using some collision detection to draw some lines and stuff.

The code I have works great but it is very bulky and hard to read.

if (background.allPixels[i].location.x - drawLineBetweenPixelRange < background.allPixels[j].location.x + background.allPixels[j].width &&
    background.allPixels[i].location.x + background.allPixels[i].width + drawLineBetweenPixelRange > background.allPixels[j].location.x &&
    background.allPixels[i].location.y - drawLineBetweenPixelRange < background.allPixels[j].location.y + background.allPixels[j].height &&
    background.allPixels[i].location.y + background.allPixels[i].height + drawLineBetweenPixelRange > background.allPixels[j].location.y)

It comes down to running this for the x and y coordinates:

var result = (x - a < y + b) && (x + b + a > y)

Can this be simplified?

I was hoping if the check itself could be shortened by taking stuff out that might counter eachother.


texts: Naive prime finder, unexpected behavior in Python

texts:
I have verified that both of my following functions successfully find prime numbers. I was pretty sure the function called is_prime_new would be faster than is_prime_old; however, after benchmarking (mainly consisting of generating huge lists of primes), I found this to be significantly false and I'm wondering why this may be.

I had two main reasons for thinking that is_prime_new would be a better algorithm than its counterpart:

is_prime_new does more checks for non-primailty early, thus eliminating numbers before iteration
It iterates in steps of 6, whereas its counterpart iterates in steps of 2, both to the same value sqrt(n)+1

Could anyone explain to me why the newer function is less optimized, and possibly debunk my above assumptions? Thank you.

def is_prime_new(n):
    if n < 2: return False
    if n == 2 or n == 3: return True
    if n%2 == 0 or n%3 == 0: return False
    sqr = math.sqrt(n)
    if sqr == int(sqr): return False

    i = 1
    while i*6 < sqr+1:
        if n % (i*6-1) == 0 or n % (i*6+1) == 0: return False
        i += 1

    return True

def is_prime_old(n):
    if n < 2: return False
    if n == 2: return True
    if n%2 == 0: return False

    for i in xrange(3, int(math.sqrt(n)+1), 2):
        if not n%i: return False

    return True


texts:
Yesterday, I came up with a simple method to predict the next value in a sequence.

The method works like this:

Start with a sequence, say 1,4,9,16,25,36, call it Δ0.
Now, Δ1 is the difference between every adjacent element in Δ0. (The first element is left unchanged). For our chosen sequence, this is 1,3,5,7,9,11.
In general, Δn is the difference between every adjacent element in Δn-1.

┌──────────────────┐
│Δ0: 1,4,9,16,25,36│
│Δ1: 1,3,5,7,9,11  │
│Δ2: 1,2,2,2,2,2   │
│Δ3: 1,2,0,0,0,0   │
│Δ4: 1,1,0,0,0,0   │
│Δ5: 1,0,-1,0,0,0  │
│Δ6: 1,-1,-1,1,0,0 │
│...               │
└──────────────────┘

Now we pick first Δn where the sum of the absolute of each value is less than than sum of the absolute values of Δn+1 . In this case it is Δ5: 1,0,-1,0,0,0. Now we duplicate the last value. (1,0,-1,0,0,0,0). Now we repeatedly take the running sums of this list n times, successfully undoing all the "difference between every adjacent element" function, but because we have an extra element, we will have an extra element in this new sequence. In our chosen sequence, this new sequence is 1,4,9,16,25,36,49.

Another example would be the sequence 2,5,3,9,6,2,3(unlike the previous sequence, this one doesn't follow a clear pattern). The sum of the absolutes of this sequence is 30. Δ1 of this sequence is 2,3,-2,6,-3,-4,1. The sum of the absolutes this time is 21. We continue, Δ2 is 2,1,-5,8,-9,-1,5. The sum of the absolutes is 31. Now, we can see that Δ1 is the first with a smaller absolute sum than the next Δ in the series. Now, we duplicate the last value of Δ1, giving 2,3,-2,6,-3,-4,1,1. Since this is Δ1, we take the running sums 1 time giving 2,5,3,9,6,2,3,4 as a final result.

Here's my code.

def runningSums(lst):
    res = [lst[0]]
    for elem in lst[1:]:
        res.append(res[-1] + elem)
    return res
def antiRunningSums(lst):
    res = [lst[0]]
    for i in range(1,len(lst)):
        res.append(lst[i] - lst[i-1])
    return res
def predict(lst):
    deriv = 0
    while True:
        nxt = antiRunningSums(lst)
        if sum(map(abs, nxt)) > sum(map(abs, lst)):
            break
        lst = nxt
        deriv += 1
    lst.append(lst[-1])
    for i in range(deriv):
        lst = runningSums(lst)
    return lst

# Example call. Correctly gives back [1,4,9,16,25,36,49].
print predict([1,4,9,16,25,36])


texts: Auto-expire key/value database (with different key types) in Haskell using acid-state

texts:
I am making a key-value database using acid-state. It has three similar "pools", one for cookie records, one for email verification of new accounts, and the last for resetting passwords.

There are three Update/Query:
1. insert a new record
2. verify using records in the db
3. delete a record

Initially, I wrote three different functions for each Update/Query, resulting in disgust repetition. Later, I tried to use a type variable to reduce repetitious code.

-- data definition
data VCodeRecord k = VCodeRecord {
    primaryKey :: k
  , vcode      :: VCode
  , expireTime :: ExpireTime
  } deriving (Eq, Ord, Data, Typeable, Show)

$(deriveSafeCopy 0 'base ''VCodeRecord)

instance Indexable (VCodeRecord Email) where
  empty = ixSet [ ixFun $ \bp -> [ primaryKey bp ] ]
instance Indexable (VCodeRecord AccountId) where
  empty = ixSet [ ixFun $ \bp -> [ primaryKey bp ] ]

type VCodePool k = IxSet (VCodeRecord k)

data VCodePools = VCodePools {
    newAccountPool  :: VCodePool Email
  , resetPasswdPool :: VCodePool Email
  , cookiePool      :: VCodePool AccountId
  } deriving (Data, Typeable, Show)
$(deriveSafeCopy 0 'base ''VCodePools)

-- update/query methods
initialVCodePools :: VCodePools
initialVCodePools = VCodePools empty empty empty

updateNewAccountPool  pools pool = pools { newAccountPool  = pool }
updateResetPasswdPool pools pool = pools { resetPasswdPool = pool }
updateCookiePool      pools pool = pools { cookiePool      = pool }

newVCodeRecord
  :: (IxSet.Indexable (VCodeRecord k), Typeable k, Ord k)
  => (VCodePools -> VCodePool k)
  -> (VCodePools -> VCodePool k -> VCodePools)
  -> k -> VCode -> ExpireTime -> Update VCodePools ()
newVCodeRecord extract update key vcode expireTime = do
  let record = VCodeRecord key vcode expireTime
  pools <- get
  let pool = extract pools
  let pool' = IxSet.updateIx key record pool
  put $ update pools pool'

insertNewAccount  = newVCodeRecord newAccountPool updateNewAccountPool
insertResetPasswd = newVCodeRecord resetPasswdPool updateResetPasswdPool
insertCookie      = newVCodeRecord cookiePool updateCookiePool

$(makeAcidic ''VCodePools
  [ 'insertNewAccount
  , 'insertResetPasswd
  , 'insertCookie
  ])

(I only present one method implementation for clarity.)

I would like to know if there is any possible improvement. For example, could I remove those insertXxx and at invocation points use something like this?

insertRecord NewAccountPool arg1 arg2 arg3


texts: Powershell cmdlet authenticating to Aerohive API

texts:
After dipping my toes in PowerShell for over a year i think it is time for creating a real cmdlet. My first mission was creating a regular PS script to take in a .csv and create a wifi account using the Aerohive REST api.

Although it works, i find the script bloated and ugly, and want to swap large code block for proper cmdlets that can also be used by my colleagues.

This is the first step, authenticating against the api. At first i'm only trying to get the basic functions to work. In a later phase i'll add error handling and stuff.

For now i'm also using restsharp. If i ever complete this, i want to swap it for the builtin .net classes so there are no external dependencies.

The next cmdlets will be for creating and deleting wifi accounts. But at first i wanna know if i'm using the correct syntax, proper use of variables, and if everything is secure enough.

using System;
using System.Management.Automation;
using RestSharp;

namespace Aerohive
{
    [Cmdlet(VerbsCommon.New, "Token")]
    [OutputType(typeof(Token))]
    public class NewTokenCmdlet : PSCmdlet
    {
        [Parameter(
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The api key, as provided by the IDManager web interface.")]
        public string apiKey { get; set; }

        [Parameter(
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The username you use to login on the web interace of the IDManager")]
        public string username { get; set; }

        [Parameter(
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The password you use to login on the web interface of the IDManager")]
        public string password { get; set; }

        protected override void BeginProcessing()
        {
            base.BeginProcessing();
        }

        protected override void ProcessRecord()
        {
            WriteVerbose("Authenticating ...");

            var client = new RestClient();
            client.BaseUrl = new Uri("very.long.url/to/authenticate/against");

            var request = new RestRequest("authenticate", Method.POST);
            request.AddHeader("content-type", "application/json");
            request.AddJsonBody(new
            {
                token = apiKey,
                userName = username,
                password = password
            });

            WriteVerbose("response");
            IRestResponse<Token> response = client.Execute<Token>(request);
            WriteObject(response.Data);
        }

        protected override void EndProcessing()
        {
            base.EndProcessing();
        }
    }
    public class Token
    {
        public string token { get; set; }
        public int errorCode { get; set; }
        public string errorMessage { get; set; }
    }
}


texts: Simple PHP Router for home grown MVC framework

texts:
I don't know if you guys get tired of seeing a bunch of requests for review of similar projects, but I was really looking for advice.

My website is designed on the MVC pattern. I have a very simple router that seems to be working just fine! If there is any upgrade I would add to it would be the ability to catch a third parameter (optional ID number, for example).

Any thoughts on the design/execution would be greatly appreciated.

Here is the Router class:

namespace Framework
{
    use App\Controllers;

    class Router
    {
        private $_url = [];

        public function addRoute($route, $dest)
        {
            $this->_url[$route] = $dest;
        }

        public function redirect()
        {
            $url = isset($_GET["url"]) ? $_GET["url"] : "";

            foreach ($this->_url as $route => $dest)
            {
                if("/$url" == $route)
                {
                    $this->parsecommand($dest);
                    break;
                }
            }
        }

        private function parsecommand($dest)
        {
            $goto = explode("@", $dest);

            $controller = $goto[0];
            $action = $goto[1];

            require_once("../app/controllers/$controller.php");

            $class = '\\App\\Controllers\\' . $controller;
            $obj = new $class;

            return $obj->$action();
        }
    }
}

The routes are entered this way:

namespace App
{
    use Framework\Router;

    $routes = new Router;

    $routes->addRoute("/", "HomeController@index");
    $routes->addRoute("/aboutus", "HomeController@aboutus");

    $routes->addRoute("/blog", "BlogController@index");

    return $routes;
}

...which runs as a part of a bootstrap process called from index.

And my controllers look like this:

namespace App\Controllers
{
    use App\Controller as Controller;
    use App\Models\Update as Update;

    class HomeController extends Controller
    {

        public function index()
        {
            $this->view('index', [
                'update' => Update::orderBy('id', 'desc')->first(),
            ]);
        }

        public function aboutus()
        {
            $this->view('aboutus');
        }
    }
}

Rendering the views is handled by Twig in the Controller base class (not really relevant to this question).

Like I said, this works perfectly (for my needs, I wouldn't market it or anything, haha), just wondering if I could get some advice.

EDIT: This does not handle 404 (or any other error for that matter), I realize that would probably the first thing to upgrade.