texts:
This is not really a question but I'd like to obtain some opinions about this simple class. For an old project I had the necessity to load some php template files that includes some foreach() and for() loops and other variables loaded from a database. I was start thinking how to obtain this using a templating class and this is what I wrote to achieve the objective, I've reworked a templating class that works well with html and php files that doesn't need to load data from variables. I know that I can also use simply the include, require or include_once and require_once but writing a reusable class was the solution that seemed to me more reliable. Can this class to be considered useful? Is it possible to improve it by using magic methods like __set() and __get() to output the desired data to a loop? In the usage example I will not post the $data variable that is an array of data loaded from database, this choiche is because I don't want to write a long post.

<?php

class Template{

    private $tpl;
    private $fileName;
    private $templatePath;

    public function __construct($templatePath){
        $this->templatePath = $templatePath;
    }

    public function loadTemplate(string $tpl){
        $this->fileName = basename($tpl.'.php');
        if(file_exists($this->templatePath.'/'.$this->fileName)){
             return $this->templatePath.'/'.$this->fileName;
        } else {
            throw new Exception('Template not found.');
        }
    }

}

?>

Usage example:

<?php

require_once 'Template.class.php';
//$data = array(); this array comes from a db
//$results = array(); this is an handmade array
$template = new Template('path/to/template/file');

include($template->loadTemplate('demo'));
?>

Template file that is loaded

            <?php for($i = 0; $i < count($data); $i++): ?>
              <?php echo $data[$i]['h']; ?>
              &nbsp;-&nbsp;
              <?php echo $data[$i]['a']; ?>

<?php echo $results[mt_rand(1,12)]; ?>

            <?php endfor;?>


texts:
I'm trying to do this:

Getting user's ID based on his email name.
Using that user_id to check all his emails that have been sent for him so far.

// db connection here
$sth = $dbh_conn
->prepare("SELECT id FROM users WHERE email = ?")
->execute(array($email));
$num_rows = $sth->fetch(PDO::FETCH_ASSOC);

if($num_rows) {

    $user_id = $num_rows['id'];

    $stmt = $dbh_conn
    ->prepare("SELECT 1
               FROM ( SELECT count(*) AS num_week,
                             sum(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1  day))) as num_day,
                             sum(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1  hour))) as num_hour,
                             sum(date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 minute))) as num_1min
                       FROM resend_pass
                      WHERE user_id   = ?
                        AND date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 WEEK))
                    ) a
                WHERE num_week < 12 AND num_day < 6 AND num_hour < 4 AND num_1min < 1;")
    ->execute(array($num_rows['id']));
    $result = $stmt->fetchColumn();

    if ( $result ) {
        echo 'send email';
    } else {
        echo 'you have sent lot of requests to reset your password. try it later';
    }

} else {
    echo 'invalid email address';
}

My code works as well. I guess it can be better.

Here is my table's structure:

// users
+----+--------+----------------------+------------+
| id |  name  |         email        | date_time  |
+----+--------+----------------------+------------+
| 1  | Jack   | jack012@gmail.com    | 1467911301 |
| 2  | John   | J_mx@ymail.com       | 1467920198 |
| 3  | Peter  | Matrix_P@yahoo.com   | 1467933196 |
+----+--------+----------------------+------------+

// resend_pass
+----+---------+-----------------+------------+
| id | user_id |      token      |  date_time |
+----+---------+-----------------+------------+
| 1  | 3       | 8u2934hfr43...  | 1467922396 |
+----+---------+-----------------+------------+

And I'm trying to follow this rule:

  Basic rule of thumb: anytime you have nested queries in a loop, and inner loop is using data from the outer loop, you should re-write as a single joined query.

Do you have any advice?


texts:
While profiling parts of my code, I noticed that my Split( ... ) function is rather slow, (about 50% of the time).
I was wondering if there was a more efficient way of Splitting a string into a vector.

My subject string can be anything between 2 words to well over 1000 words, hence the reason why I would like to speed it up.

Here is an example program with the function.

#include <iostream>
#include <string>
#include <cstring>
#include <vector>

void Split(const std::string& subject, std::vector<std::string>& container)
{
  container.clear();
  size_t len = subject.length() + 1;
  char* s = new char[ len ];
  memset(s, 0, len*sizeof(char));
  memcpy(s, subject.c_str(), (len - 1)*sizeof(char));
  for (char *p = strtok(s, " "); p != NULL; p = strtok(NULL, " "))
  {
    container.push_back( p );
  }
  delete[] s;
}

int main()
{
  std::vector<std::string> container;
  Split( "Hello World", container );

  for( std::vector<std::string>::const_iterator it = container.begin(); it != container.end();++it)
  {
    std::cout << *it << "!\n";
  }
}

Any suggestions on how I could speed it up.

Of course any other general comments are more than welcome.

Edit profiling is very simple.

...
clock_t t = clock ();
std::vector<std::string> container;
Split( "actus non facit reum nisi mens sit rea", container );
t = clock() - t;
std::cout << (((float)t)/CLOCKS_PER_SEC) << "ms\n";
...


texts: Refactoring ViewModel and mapping from multiple sources

texts:
I need to refactor and tidy the following controller below, it's my first MVC application. I've successfully used AutoMapper as I began refactor controllers but I am not sure how to approach a scenario where the data for the ViewModel comes from multiple service calls. And that scenario seems to often present itself in slightly heavier view models where I have all kind of information to present.

Calling multiple mapping calls on top of the same view model seemed counter-intuitive and it feels like I am missing some good practice or common approach to the situation. Or maybe I am wrong and it's commonly used approach.

0) Thought of generally using AutoMapper somehow but as I said I cannot find a proper way to implement it, I'd like to keep the controller relatively thin but I also don't want to have too much unneeded/overkill abstraction.

1) Thought of having some build method on the view model and to pass needed data.

2) Thought of having a model between my database entities and the view model but I am not sure how to execute that either, I think I seen somewhere by examples that people return "Models" from service calls that contain complex data and then map those Models to the ViewModel with Automapper, instead of mapping service calls directly into the ViewModel like others are doing.

3) Saw people use a facade of sorts in one example and thought of that too.

It's just my first project under MVC and I would like to learn a robust general approach that is considered well written and good practice so I can use it to fully refactor this and continue to improve from there.

        BKQEventCustomData BKQEventData = BKQHelper.ParseBase64EventData(Server.UrlDecode(Request.Url.Query));
        var cutomData = JsonConvert.DeserializeObject<NopOrderData>(BKQEventData.custom.data.ToString());

        var model = new TaskEventViewModel();
        if (BKQEventData != null)
        {
            AuthenticateRequest(BKQEventData.xcm.clid, BKQEventData.xcm.opid);

            model.PlacesList = new SelectList(_placesService.GetPlacesByClientId(BKQProfile.ClientId).Where(p => p.Active), "PlaceId", "Name");
            model.ServicesList = new SelectList(_serviceService.GetServicesByClientId(BKQProfile.ClientId).Where(s => s.Active), "ServiceId", "Name");
            model.ContractorsList = new SelectList(_contractorService.GetContractorsByClientId(BKQProfile.ClientId), "ContractorId", "BKQFullName");
            model.StatusList = new SelectList(_statusService.GetStatusByClientId(BKQProfile.ClientId), "StatusId", "Name");

            model.TaskEvent = new TaskEvent();
            model.TaskEvent.Title = string.Empty;
            model.TaskEvent.BKQCustomData = BKQEventData.custom.data.ToString();
            model.TaskEvent.BKQCustomDataType = BKQEventData.custom.type.ToString();
            model.TaskEvent.BKQClientId = BKQEventData.xcm.clid;
            model.TaskEvent.BKQOperatorId = BKQEventData.xcm.opid;
            model.TaskEvent.BKQInfProductId = BKQEventData.xcm.iprodid;
            model.TaskEvent.BKQEventHistoryId = BKQEventData.xcm.evnhid;
            model.TaskEvent.BKQEventTypeId = BKQEventData.xcm.evntype;
            model.TaskEvent.BKQEventCaseId = BKQEventData.xcm.caseid;
            model.TaskEvent.BKQQuota = BKQEventData.xcm.quotaid;
            model.TaskEvent.BKQLangId = BKQEventData.xcm.langid;
            model.TaskEvent.BKQContactId = BKQEventData.xcm.contid;
            model.TaskEvent.CreatedBy = BKQEventData.xcm.opid;
            model.TaskEvent.ModifiedBy = BKQEventData.xcm.opid;
            model.BKQContact = BKQFramework.Contact.GetById(BKQEventData.xcm.contid);
        }
        else
        {
            return RedirectToActionPermanent("Login", "Login");
        }


texts:
I've got a simple sinatra webapp that pulls data from Pinboard's RSS api, parses the info, and re-displays it. There are 4 tasks I need to perform with the data:

I need to remove all instances of a specific tag from all items (in this case, want)
I need to create a list of all unique tags across all the items returned
I need to dynamically remove certain tags from the list if they are already being used to filter the list
I need to add an attribute to each item that is the host of the url associated with that item (i.e. amazon.com for whatever long amazon url may have been added)
I need to return a list of unique locations across all the items returned

Here is the way I am currently handling this:

items = []
tags = []
locations = []
begin
  JSON.parse(data).each do |item|
    # Remove the tag want from the list of tags,
    # strip any extra whitespace, and add a location attribute
    item['t'].each { |t| t.strip! }
    item['t'].delete_if { |tag| tag == 'want' }

    # Try like hell to parse the url. Assign an error string as a last resort
    begin
      item['l'] = /https?:\/\/(?:[-\w\d]*\.)?([-\w\d]*\.[a-zA-Z]{2,3}(?:\.[a-zA-Z]{2})?)/i.match(item['u'])[1]
    rescue
      item['l'] = "URL Parse error"
    end

    # Add the item's tags
    item['t'].each do |tag|
      tags << tag unless tags.include? tag or filter_tags.include? tag
    end

    locations << item['l'] unless locations.include? item['l']

    items << item
  end
rescue
end
return items, tags.sort, locations.sort

I really don't like this. It just doesn't feel clean to me, what with the creation of the empty arrays, and adding stuff in, etc. But my thought was that it's better to do a single iteration over the data returned than to do multiple loops. But now I am considering this instead:

items = JSON.parse(data)
# Remove the want tag from all items
items.each { |i| i['t'].delete_if { |t| t == 'want' }}

#generate a list of tags
tags = items.map { |i| i['t']}.flatten.uniq.sort
tags.delete_if { |t| filter_tags.include? t }

# Parse the url
re = /https?:\/\/(?:[-\w\d]*\.)?([-\w\d]*\.[a-zA-Z]{2,3}(?:\.[a-zA-Z]{2})?)/i
items.each { |i| i['l'] = re.match(i['u'])[1] }

# Generate a list of locations
locations = items.map { |i| i['l']}.flatten.uniq.sort

return items, tags, locations

It feels cleaner, and seems like it's easier to read, but I'm not sure if the nested delete_if in the first bit is going too far. I'm also not sure how I feel about iterating over the items multiple times, or chaining flatten.uniq.sort for both tags and locations


texts:
Learning Go and trying to get a grip of the various concepts it uses. Following is my implementation of Quicksort (choosing last element as pivot). It takes the length of the array and the subsequent array to be sorted as user input.

package main

import "fmt"

func main() {
    var n int

    fmt.Print("Enter Size: ")
    fmt.Scan(&n)

    var slice = make([]int, n)

    for i := 0; i < n; i++ {
        fmt.Print("arr[",i,"]: ")
        fmt.Scan(&slice[i])
    }

    fmt.Print("Array: ", slice, "\n")
    quickSort(slice, 0, n - 1)
    fmt.Print("Sorted Array: ", slice)
}

func quickSort(a []int, low int, high int) {
    if(low < high) {
        p := partition(a, low, high)
        quickSort(a, low, p - 1)
        quickSort(a, p + 1, high)
    }
}

func partition(a []int, low int, high int) int {
    pivot := a[high]
    i := low
    for j := low; j < high; j++ {
        if(a[j] <= pivot) {
            swap(&a[i], &a[j])
            i += 1
        }
    }
    swap(&a[i], &a[high])
    return i
}

func swap(a, b *int) {
    temp := *a
    *a = *b
    *b = temp
}

Comments on coding style, following/avoiding language convention, use of pointers, use of slices, and overall correctness of the program will be appreciated.


texts: Pascal's Triangle without using combinations

texts:
I wrote this code for Pascal's Triangle using recursion. Can someone please help me to review it for better performance?

# argument count is number of rows which is entered from terminal.
def pascal_t(count,input_list=0):

    if not count: exit() # if count is 0 program will exit.

    if not input_list: # to print first element as 1 when there is no input list.
        created_array=[1]
        print (count*"   "),"    ".join(map(str,created_array))

        pascal_t((count-1),created_array) # recursive call; created array will be taken as input list.

    created_array=[] # initializing list

    # for loop to insert numbers in created_array
    for index in range(len(input_list)):
        if not index: # when index is 0 then first value will be inserted in created_ array
            if (index+1)==len(input_list): # if there is only 1 element in the list, this condition will insert first element again in created_array
                created_array.append(input_list[index])
            created_array.append(input_list[index])

        elif (index+1)==len(input_list):    # when index is second last, it will insert two elements in created_array
            created_array.extend((input_list[index-1]+input_list[index],input_list[index]))

        else:
            created_array.append(input_list[index-1]+input_list[index])

    # list formatting for proper pattern printing.
    formatted_list = [str(num)+"   " if num>9 and num<=99 else str(num)+"  " if num>99 and num<=999 else str(num)+" " if num>999 and num<=9999 else str(num)+"" if num>9999 else str(num)+"    " for num in created_array]

    # Creating and printing string from created_array
    string_to_print = " ".join(formatted_list)
    print count*"   ",string_to_print
    pascal_t((count-1),created_array) # recursive call; created array will be taken as input list.

# function call with user input from terminal
pascal_t(int(raw_input("Enter Number of Rows(1-20) for Pascal's Triangle: ")))


texts:
The parameters list contain the array that is passed to and the size of the array respectively. Is there anywhere I could improve my code?

void bubbleSort(int a[], int s) {
    for (int i = 1; i < s; i++) {
        for (int j = 0; j < s - i; j++) {
            if (a[j] > a[j + 1]) {
                int temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
}


texts: F#unctional Immutable Trie (Prefix Tree)

texts:
I've created the following implementation of a trie in F# as an effort to learn the language. I would like to know what could be done to make it more idiomatic. Any other pointers are welcome as well.

Of particular interest are:

Are my tests sufficient? Is there a better way to construct the tests?
Can the logic for insert be made cleaner?
To constrain type or not for functions and parameters?
What remains to be done to classify this as a proper collection?

type Trie<'T when 'T : comparison> = {
    IsTerminal: bool;
    Children: Map<'T, Trie<'T>>;
}

module Trie =
    let empty = {
        IsTerminal = false;
        Children = Map.empty;
    }

    let rec insert branch trie =
        match branch with
        | [] ->
            { trie with IsTerminal = true; }
        | el::els ->
            let child =
                match Map.tryFind el trie.Children with
                | Some t -> t
                | None -> empty
            let child' = insert els child
            let children =
                if Map.containsKey el trie.Children
                then Map.remove el trie.Children
                else trie.Children
            let children' = Map.add el child' children
            { trie with Children = children' }

    let rec contains branch trie =
        match branch with
        | [] -> trie.IsTerminal
        | el::els ->
            match Map.tryFind el trie.Children with
            | Some t -> contains els t
            | None -> false

    let rec toSeq trie =
        seq {
            for KeyValue(label, trie) in trie.Children do
                if trie.IsTerminal then yield [label]
                let children = toSeq trie
                for child in children do
                    yield label :: child
        }

    module Test =
        let ``insert can insert char into root`` =
            let result = empty |> insert ['a']
            Map.containsKey 'a' result.Children
        do assert ``insert can insert char into root``

        let ``insert can insert char into multiple levels`` =
            let result = empty |> insert ['a'..'d']
            Map.containsKey 'd' (((result.Children |> Map.find 'a').Children |> Map.find 'b').Children |> Map.find 'c').Children
        do assert ``insert can insert char into multiple levels``

        let ``contains finds branches that exist in tree`` =
            let result = empty |> insert ['a'..'d']
            contains ['a'..'d'] result
        do assert ``contains finds branches that exist in tree``

        let ``contains does not find incomplete branches`` =
            let result = empty |> insert ['a'..'d']
            result |> contains ['a'..'c'] |> not
        do assert ``contains does not find incomplete branches``

        let ``contains does not find extended branches`` =
            let result = empty |> insert ['a'..'d']
            result |> contains ['a'..'e'] |> not
        do assert ``contains does not find extended branches``


texts:
Should I leave the Default Route in if it's not adding any benefit?

I have a RouteConfig.cs file that looks like this:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Dashboard",
        url: "{controller}/{action}",
        defaults: new { controller = "JobDashboard", action = "Index" }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "JobDashboard", action = "Index", enumDigit = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "Login",
        url: "{controller}/{action}",
        defaults: new { controller = "Account", action = "Login" }
    );
}

If I only have the Default and Login Routes and the user goes to the root of the site (eg www.sitename.com), then the user always goes to the Login page. I don't want them going to the Login page after they've logged in, and after a little bit of digging I discovered that MVC4 always sorts Route Order Importance by Custom Route first, and then the Default Route.

I created the Dashboard route, and everything is working fine. I then took out the Default route because it didn't seem needed. Nothing seems to be affected by removing the Default Route, and that leads me to the question, should I leave the Default Route in there?

I seem to recall that having a Default Route is good practice, but if it's not adding anything to the solution, is there a good reason to keep it around?


texts: Displaying unique objects generated by Raphael.js in FancyBox

texts:
I'm using Raphael.js to generate objects which are unique but do basically the same thing. I'm also using Fancybox to display a unique image after a click on a generated object.

Is there a way to write this more concise?

//OBJECT 101
    var p1_101 = p1.path("M361,146.773 366.25,192.94 365.917,196.606 366.583,199.69 387,197.773 392.417,179.023 387.75,178.273 395.833,146.106 397.583,145.94 398,143.023 374,145.273z").attr({"fill":"#d3ae6b", "stroke-width": 0, "fill-opacity": .5, "stroke": "transparent","cursor": "pointer", "title": "101"}).click(function () {
        $.fancybox.open([
            {
                href : 'img/rzuty/p1/101.jpg',
                openEffect : 'elastic',
                openSpeed  : 150,
                closeEffect : 'elastic',
                closeSpeed  : 150,
                padding: 2,
            }
        ], {
            beforeShow : function() {
                $('').appendTo(".fancybox-inner");
            }
        });
    }).mouseover(
        function () {
            this.animate({"fill-opacity": .8}, 200);
        }).mouseout(function () {
            this.animate({"fill-opacity": .5}, 200);
    });

    //SETTING CLASS AND ID
    p1_101.node.setAttribute('class','reserved'); // CLASS 'reserved' OR 'sold'
    p1_101.node.id = 'p1_101';

    //OBJECT 102
    var p1_102 = p1.path("M337.583,149.023 342.667,196.69 342.333,197.023 342.833,202.107 365.667,199.857 365.167,194.523 364.667,194.357 359.917,150.357 356,150.773 355.75,147.19z").attr({"fill":"#d3ae6b", "stroke-width": 0, "fill-opacity": .5, "stroke": "transparent","cursor": "pointer", "title": "102"}).click(function () {
        $.fancybox.open([
            {
                href : 'img/rzuty/p1/102.jpg',
                openEffect : 'elastic',
                openSpeed  : 150,
                closeEffect : 'elastic',
                closeSpeed  : 150,
                padding: 2,
            }
        ], {
            beforeShow : function() {
                $('').appendTo(".fancybox-inner");
            }
        });
    }).mouseover(
        function () {
            this.animate({"fill-opacity": .8}, 200);
        }).mouseout(function () {
            this.animate({"fill-opacity": .5}, 200);
    });

    //SETTING CLASS AND ID
    p1_102.node.setAttribute('class','sold'); // CLASS 'reserved' OR 'sold'
    p1_102.node.id = 'p1_102';

    //OBJECT 103
    var p1_103 = p1.path("M314.5,155.107 319.167,197.607 319.167,199.19 318.667,199.44 319.25,204.357 342,202.273 341.583,197.023 340.833,196.607 340.833,195.357 335.917,149.357 331.833,149.607 316.5,151.107 316.75,154.607z").attr({"fill":"#d3ae6b", "stroke-width": 0, "fill-opacity": .5, "stroke": "transparent","cursor": "pointer", "title": "103"}).click(function () {
        $.fancybox.open([
            {
                href : 'img/rzuty/p1/103.jpg',
                openEffect : 'elastic',
                openSpeed  : 150,
                closeEffect : 'elastic',
                closeSpeed  : 150,
                padding: 2,
            }
        ], {
            beforeShow : function() {
                $('').appendTo(".fancybox-inner");
            }
        });
    }).mouseover(
        function () {
            this.animate({"fill-opacity": .8}, 200);
        }).mouseout(function () {
            this.animate({"fill-opacity": .5}, 200);
    });

    //SETTING CLASS AND ID
    p1_103.node.setAttribute('class','reserved'); // CLASS 'reserved' OR 'sold'
    p1_103.node.id = 'p1_103';


texts: Defines and prints shortest word in set, sorts the rest by length, and gives average word length

texts:
I need to clean up and simplify this code (I am a beginner in Python):

print ("Type in four inputs.")
word_first = raw_input("What is your first input? ")
word_second = raw_input("What is your second input? ")
word_third = raw_input("What is your third input? ")
word_fourth = raw_input("What is your fourth input? ")

list_of_words = [word_first, word_second, word_third, word_fourth]
print
print sorted(list_of_words, key=len)

def average(numbers):
    return sum(numbers)/len(numbers)

all_words = word_first, word_second, word_third, word_fourth
words_total = word_first, word_second, word_third, word_fourth.split()
length_words = [len(word) for word in words_total]

word_first_length = len(word_first)
word_second_length = len(word_second)
word_third_length = len(word_third)
word_fourth_length = len(word_fourth)
total_letters = word_first_length + word_second_length + word_third_length +
word_fourth_length
average_length = total_letters / 4
print
print ("Shortest input is: ") + (min((word for word in list_of_words if word), key=len))
print ("Average length is %.1f.") %(average_length)


texts:
I am building a GUI to display a digital clock face (four seven-segment displays), and I have a selector to switch between 12/24-hour formats. I have working code to show both formats, but it is messy. I am looking for a better solution for this section.

The obvious repetition is the section that displays the AM/PM indicator. The only difference is that the fill color of the AM and PM switch.

Note that the time comes in as three integers, one each for hours, minutes, and seconds. These integers are in 24-hour format.

The drawDigits method takes the value to be displayed (0-9, 10=all off), and the (x,y) location of the top-left corner. It then uses a lookup to determine which segments to "turn on."

// 24 hour mode, draw time as reported
if (toggle.isSelected()) {
  drawDigit(hour/10, 20, 100);
  drawDigit(hour%10, 110, 100);
}
// 12 hour mode, display
else {
  if (hour % 12 == 0) {
    drawDigit(1, 20, 100);
    drawDigit(2, 110, 100);
  } else {
    if ((hour % 12)/10 == 1) {
      drawDigit(1, 20, 100);
    } else {
      drawDigit(10, 20, 100);
    }
    drawDigit((hour % 12)%10, 110, 100);
  }
  // show AM/PM indicator
  if (hour >= 12) {
    fill(75);
    rect(40, 230, 10, 10);
    text("AM", 55, 240);
    fill(255, 0, 0);
    rect(40, 245, 10, 10);
    text("PM", 55, 255);
  } else {
    fill(255, 0, 0);
    rect(40, 230, 10, 10);
    text("AM", 55, 240);
    fill(75);
    rect(40, 245, 10, 10);
    text("PM", 55, 255);
  }
}
drawDigit(minute / 10, 224, 100);
drawDigit(minute % 10, 314, 100);
if (second % 2 == 0) fill(240, 0, 0);
else fill(75);
ellipse(200, 145, 10, 10);
ellipse(200, 175, 10, 10);

This code was written in Processing, so the rect, ellipse, text, and fill methods are the ones built-in to Processing.


texts: Using a function to find the average for number of letters and words

texts:
This is my code:

#include <stdio.h>
#include <ctype.h>
int average_of_let_wor();
int main(void)
{
    double answer;
    answer = average_of_let_wor();

    printf("%.2lf", answer);
    return 0;
}

int average_of_let_wor()

{
    double numberOfLetters = 0;
    double numberOfWords = 0;
    int userInput;
    double answer;
    printf("please enter your input:\n");
    while ((userInput = getchar()) != EOF)
    {

        if (userInput == ' ' || userInput == '\t' || userInput == '\n')
        {
            numberOfWords++;
            continue;
        }

        else
           numberOfLetters++;

    }
    answer = numberOfLetters/numberOfWords;
    return answer;
}


texts: Simple color flooding game in Javascript/HTML5 canvas area

texts:
I'm learining JS. I have prepared a simple color flooding game, like Pixelated.

The engine below works, though scoring is not implemented.  Please help me find out how this code could be made better, more idiomatic JavaScript, or more efficient.

// global variables
var canvas = document.getElementById("game");
var context = canvas.getContext("2d");
var colors = ["#FF7F34", "#FF4D79", "#FFEF42", "#78E853", "#64C4FF", "#954FFF"];
var squareSize = 20;
var canvasSize = 14;
var buttonSize = 30;
var spaceSize = 15;
var board = [];
var currentColor = 0;

// draw 14x14 board of randomly coloured squares and add each square to 2d array 'board'
function drawBoard(colors) {
    // draw main board
    for (var i = 0; i < canvasSize; i++) {
        var boardColumn = [];
        for (var j = 0; j < canvasSize; j++) {
            colorId = Math.floor((Math.random() * 6)) + 1;
            context.fillStyle = colors[colorId - 1];
            context.fillRect(i*squareSize, j*squareSize, squareSize, squareSize);
             if (i == 0 && j == 0) {
                currentColor = colorId;
                colorId = 0;
            }
            boardColumn.push(colorId);
        }
        board.push(boardColumn);
    }
    // draw controls
    colors.forEach(function (value, i) {
        context.fillStyle = value;
        context.fillRect(i * (buttonSize + spaceSize) + spaceSize, squareSize * canvasSize + spaceSize, buttonSize, buttonSize);
    });
    expandOcean(currentColor);
    redrawBoard();
}
// click handler
function clickToColor(event) {
  var color = 0;
  var x = event.x;
  var y = event.y;
  x -= canvas.offsetLeft;
  y -= canvas.offsetTop;
  var controlsOffsetTop = squareSize * canvasSize + spaceSize;
  colors.forEach(function(value, i) {
    if (x > (spaceSize + i * (spaceSize + buttonSize)) && x <= ((i + 1) * (spaceSize + buttonSize)) && y > controlsOffsetTop && y <= (controlsOffsetTop + buttonSize)) color = i + 1;
  });
    if (color != 0 && color != currentColor)
        {
            currentColor = color;
            expandOcean(currentColor);
            redrawBoard();
        }
}
// flooding with chosen color
function expandOcean(color) {
    var touched = false;
    board.forEach(function(column, i) {
        column.forEach(function(value, j) {
            if (j + 1 < canvasSize && ((column[j] == 0 && column[j+1] == color) || (column[j] == color && column[j+1] == 0))) {
                board[i][j+1] = 0;
                board[i][j] = 0;
                touched = true;
            }
        });
    });
    board.forEach(function(column, i) {
        column.forEach(function(value, j) {
            if (i + 1 < canvasSize && ((column[j] == 0 && board[i + 1][j] == color) || (column[j] == color && board[i+1][j] == 0))) {
                board[i + 1][j] = 0;
                board[i][j] = 0;
                touched = true;
            }
        });
    });
    if (touched == true) expandOcean(color);
}

function redrawBoard() {
    board.forEach(function(column, i) {
        column.forEach(function(value, j) {
            if (board[i][j] == 0) {
                context.fillStyle = colors[currentColor - 1];
            } else {
                context.fillStyle = colors[board[i][j] - 1];
            }
            context.fillRect(i*squareSize, j*squareSize, squareSize, squareSize);
        });
    });
}

drawBoard(colors);
canvas.addEventListener('click', clickToColor, false);
<!DOCTYPE html>
<html>
<body>
    <canvas id="game" width="280" height="400"></canvas>
    <script type="text/javascript" src="game.js"></script>
</body>
</html>


texts:
A class that matches the rendered objects shader and render function(sets shader resources) based on its typeid hash.

#include <unordered_map>

#include <glm/glm.hpp>

#include "gl_func.h"
#include "gl_buffer.h"
#include "shader.h"
#include "log.h"

class Renderer
{
private:

    typedef void (*RenderFunctionPointer)();

    typedef std::unordered_map< size_t, Shader* >::iterator ShaderIterator;
    typedef std::unordered_map< size_t, RenderFunctionPointer >::iterator
        FunctionIterator;

    std::unordered_map< size_t, Shader* > Shaders;
    std::unordered_map< size_t, RenderFunctionPointer > RenderFunctions;

    glm::mat4 ProjectionMatrix;
    glm::mat4 ViewMatrix;

public:

    // Sets the given matrices for all shaders
    void SetProjectionMatrix( glm::mat4 p );
    void SetViewMatrix( glm::mat4 v );

    /*! \brief Tells the renderer how to render object of type T
     *  \param shd Shader to use for rendering.
     *  \param f Pointer to a function that takes a shader and a T& argument. */
    template< typename T >
    void AddObjectType( Shader* shd, void (*f)(Shader*, T& ) )
    {
        size_t type = typeid( T ).hash_code();
        Shaders[type] = shd;
        RenderFunctions[type] = (RenderFunctionPointer)f;
    }

    /*! \brief Renders the given object.
     *  The object type has to be registered before this call.
     *  \param obj Object to Render */
    template< typename T >
    void Render( T& obj )
    {
        size_t type = typeid( T ).hash_code();

        ShaderIterator i = Shaders.find( type );

        if( i == Shaders.end() )
        {
            LOG_WARNING() << "Couldn't find shader for object: "
                << typeid( T ).name();
            return;
        }

        Shader* shd = i->second;
        shd->SetModelMatrix( obj.GetTransform() );
        shd->Bind();

        FunctionIterator f = RenderFunctions.find( type );
        if( f == RenderFunctions.end() )
        {
            LOG_WARNING() << "Couldn't find renderfunction for object: "
                << typeid( T ).name();
            return;
        }

        RenderFunctionPointer rp = f->second;
        reinterpret_cast< void(*)(Shader* shd, T& t) >(rp)( shd, obj );
    }
};

Here is some usage to clarify why is a reinterpret_cast necessary(this is not code to be reviewed, just rough example of usage):

// Init
DeferredRenderer->AddObjectType<Asset>(AssetShader.Get(),
   RenderFunctions::Deferred::RenderAsset );

// Somewhere passing a Asset to external C code( lua )
void* genericRenderable = MyAsset;
PassToLua( genericRenderable );

// Lua code calling entity system.
SetComponent( DeferredRenderable, genericRenderable );

// The render system processing entities
static_cast<Renderable*>(genericRenderable)->Render( DeferredRenderer );

// This calls
void Asset::Render( Renderer* r ) // where r is DeferredRenderer
{
    r->Render( *this );
}


texts: Improving performance of Ruby socket programming

texts:
Server:

require 'socket'
require 'time'
require 'ap'

server = TCPServer.open(1026)

def process_the_request req, client # not important, disk-related process
  sleep 2
  req.to_s + ' ' + client.peeraddr[3].to_s + ' ' + Time.now.to_s
end

loop do

  Thread.start(server.accept) do |client|

    request = ''
    ch = ''

    begin

      ch = client.getc
      print ch

      if (ch.nil? or ch.ord == 13 or ch.ord == 10)

        if request.length < 1
          break if client.eof?
          next
        end

        ap "request: " + request
        response = process_the_request request, client
        ap "response: " + response
        client.puts response
        request = ''
        break if client.eof?

      else
        request += ch
      end

    end while true

    #ap "thread closed"
    client.close

  end # Thread

end # loop

Client:

nn='nc 127.0.0.1 1026'
echo -n '1' | $nn &
echo '2' | $nn &
echo -n '3' | $nn &
echo '4
5
6
7' | $nn &


texts: Obtaining information about the logged in user

texts:
I currently have a special service to obtain information about the logged in user. I have an interface

/**
 * The service operates on the data of an authorised user.
 */
public interface AuthorizationService {
    User getUser();
    String getUserId();
    String getUsername();
    boolean isLogged();
}

and implementation

@Service("authorizationService")
public class AuthorizationServiceImpl implements AuthorizationService {
    private final UserSearchService userSearchService;
    /**
     * {@inheritDoc}
     */
    @Override
    public User getUser() {
        return userSearchService.getUserByUsername(this.getUsername());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getUserId() {
        return userSearchService.getUserByUsername(SecurityContextHolder.getContext().getAuthentication().getName()).getId();
    }
...
}

and for example, when I use the method to create messages, I do so

@Override
public String createMessage(
        @NotNull @Valid final SendMessageDTO sendMessageDTO
) throws ResourceNotFoundException, ResourceConflictException {
    log.info("Called with sendMessageDTO {}", sendMessageDTO);

    final UserEntity user = this.findUser(this.authorizationService.getUserId());
    final MessageEntity message = this.sendMessageDtoToMessageEntity(sendMessageDTO);

    message.setSender(user);

    ...
}
    private UserEntity findUser(final String id) throws ResourceNotFoundException {
        return this.userRepository
                .findByUniqueIdAndEnabledTrue(id)
                .orElseThrow(() -> new ResourceNotFoundException("No user found with id " + id));
    }

However, I do not know if this is a good way to obtain information about the logged-in user?
Instead of a DTO User object, I could return an entity(I have a rule that I do not return entity service methods) and then I would not have to use the findUser () method to search for a user. What do you think about it?
Is my way of getting a DTO User logged in user or ID a safe way?


texts:
I wrote this script for a code challenge on TreeHouse. I already submitted my code, but I am looking for an after the fact feedback.

The challenge was to open a file of text, remove specific words (provided in another file) and do the following:

  Output to the screen in a readable fashion
  1. total word count after filtering
  2. highest occurring word
  3. longest word(s) and its / their length
  4. sort the list from most occurring to least occurring then output that data to the screen as an unordered list
  5. Bonus: Return the word list in JSON.

I decided to split the solution into two classes:

One class to sanitise the string into words only
Another class to do the analysis

This is the sanitiser class. Given text it should return a string of words only. It should remove anything that is not a letter or an apostrophe, and compress all white space into a single space character.

I accept that this has problems. For example, I found an instance of an apostrophe as a word. Perhaps it was a leading or a trailing one. But defining the boundaries of a word is a tricky proposition.

class WordsOnlySanitizer
  # Allow for diacritics, hence p{Alpha} and not \w
  # We should not split words on apostrophes either
  WORDS_ONLY_REGEX = /[^\p{Alpha}']/i

  # We want to reduce all white space into a single space
  SPACE_ONLY_REGEX = /\s+/

  def self.to_words(text)
    text.gsub(WORDS_ONLY_REGEX, ' ').gsub(SPACE_ONLY_REGEX, ' ')
  end
end

This is the analyser class. It's self explanatory. There is duplication in the longest_words and highest_occuring_words methods. But I'm not sure how to remove this duplication without making the code less readable.

The html_list method also looks a little suspect, but I can't tell why.

require 'json'

class Analyser
  def initialize(text, filter)
    @words = text.split
    @filter = filter.split
  end

  def word_count
    filtered_words.size
  end

  def word_occurrences
    @word_occurrences ||= filtered_words.inject(Hash.new(0)) do |result, word|
      result[word] += 1
      result
    end
  end

  def highest_occurring_words
    word_occurrences.group_by { |key, value| value }.max_by { |key, value| key }.last
  end

  def longest_words
    filtered_words.inject({}) do |result, word|
      result[word] = word.length
      result
    end.group_by { |key, value| value }.max_by { |key, value| key }.last
  end

  def html_list
    list = ""
    word_occurrences.sort_by { |key, value| value }.reverse.each do |key, value|
      list << "
#{key}: #{value}
\n"
    end
    "
\n" + list + "
"
  end

  def json_list
    JSON.parse(word_occurrences.to_json)
  end

private

  def filtered_words
    @filtered_words ||= @words.reject do |word|
      # Downcase so that Hello and hello count as two occurrences
      word.downcase!
      @filter.include?(word)
    end
  end
end

Usage

Here's how you would use this:

text = WordsOnlySanitizer.to_words(File.read('words.txt'))
filter = WordsOnlySanitizer.to_words(File.read('filter_words.txt'))
analyser = Analyser.new(text, filter)

puts "Word count after filtering is: #{analyser.word_count}"
puts "\n"

puts "The most frequent words are:"
analyser.highest_occurring_words.each do |key, value|
  puts "  - #{key}: #{value} occurences"
end
puts "\n"

puts "The longest words are:"
analyser.longest_words.each do |word|
  puts "  - #{word.first}: #{word.last} characters"
end
puts "\n"

puts "Word list:"
puts analyser.html_list

puts "JSON object:"
puts analyser.json_list

Here's a gist with all the files. Warning: There are large text files.


texts:
I'm preparing for a job as a junior/intermediate JS developer. I'm comfortable with my ability to think in higher-order functions, but less confident in my syntax and style (I have more experience in Clojure, ClojureScript). This is simple but I welcome your comments.

import { Map } from 'immutable';

const coinChanger = (d, m) => { // d for denominations, m for money
  const denoms = d.sort((a,b) => b-a)
  const coinCounter = (coin, amount) => {
    const coins = Math.floor(amount / coin);
    const remainder = amount % coin;
    return Map({}).set(coin, coins).set("remainder", remainder);
  };
  const coinMap = denoms.reduce((result, coin) => {
    const amount = result.get("remainder");
    const coinCount = coinCounter(coin, amount);
    return result.merge(coinCount);
  }, Map({"remainder": m}));
  return coinMap;
};

console.log(coinChanger([1, 5], 11));
console.log(coinChanger( [25, 10, 5, 1], 192 ));
console.log(coinChanger([25, 2], 105));


texts: Fast Factorisation (Python Implementation)

texts:
An algorithm for finding prime factors of a number given a list of all primes up to the square root of the number. It's worst case time complexity is \$O(n^{1/2})\$, the best case would be \$O(\log(n))\$, and I don't know how to calculate average case or amortised worst case. I am aware that this is not strictly optimal, but I think it is easier to understand and implement, than say Pollard's rho algorithm for prime factorisation (I suspect it works better if the number is composite with many prime factors as well). Suggestions for improvements are welcome.

FastFactorise.py

def fact(n):
    """
        *   Function to factorise a given number given a list of prime numbers up to the square root of the number.

        *   Parameters:
            *   `n`: The number to be factorised.
        *   Return:
            *   `res`: A dict mapping each factor to its power in the prime factorisation of the number.
        *   Algorithm:
            *   Step 1: Initialise `res` to an empty dictionary.
            *   Step 2: If `n` > 1.
            *   Step 3: Iterate through the prime number list.
            *   Step 4: If ever the current prime number is > the floor of the square root of `n` + 1 exit the loop.
            *   Step 5: If the current prime number is a factor of `n`.
            *   Step 6: Assign 0 to `e`.
            *   Step 7: While the current prime number is a factor of `n`.
            *   Step 8: Increment `e`.
            *   Step 9: Divide `n` by the current prime number.
            *   [End of Step 7 while loop.]
            *   Step 10: Map the current prime number to `e` in the result dictionary.
            *   [End of step 5 if block.]
            *   Step 11: If `n` is not 1 (after the repeated dividings) map `n` to 1 in the result dictionary.
            *   Step 12: Return the result dictionary.
            *   [Exit the function.]
    """
    res = {}
    if n > 1:
        for p in primes:
            if p > int(sqrt(n)) + 1:    break
            if n%p == 0:
                e = 0
                while n%p == 0:
                    e += 1
                    n //= p
                res[p] = e
        if n != 1:      res[n] = 1
    return res


texts: Optimize Javascript function with many (maybe?) loops inside

texts:
I have the following function using in my application:

applyFormSectionIdsToControls: function(formSections) {
    if (!formSections.length) return;

    var formSectionIds = [];

    for (var i = 0, ii = formSections.length; i < ii; i++) {
        formSectionIds.push(parseInt(formSections[i].id));
    };

    for (var i = 0, ii = formSections.length; i < ii; i++) {
        var affectedWidgets = $.grep(application_widgets, function(item) {
            return (($.inArray(item.widget_key, ['nextbutton', 'dropdown', 'radiobuttons']) >= 0) && (item.parent_id == formSections[i].id));
        });

        for (var j = 0, jj = affectedWidgets.length; j < jj; j++) {
            if (affectedWidgets[j].widget_key == 'nextbutton' && (typeof affectedWidgets[j].settings.default_next_step != 'undefined' && affectedWidgets[j].settings.default_next_step > 0)) {
                var _next_step = parseInt(affectedWidgets[j].settings.default_next_step);

                if ($.inArray(_next_step, formSectionIds) == -1) {
                    affectedWidgets[j].settings.default_next_step = formSectionIds[_next_step - 1];
                }
            }
            if (affectedWidgets[j].widget_key == 'radiobuttons' || affectedWidgets[j].widget_key == 'dropdown') {
                for (var k = 0, kk = affectedWidgets[j].settings.answers; k < kk; k++) {
                    var _next_step = parseInt(affectedWidgets[k].settings.answers[k].next_step);

                    if ($.inArray(_next_step, formSectionIds) == -1) {
                        affectedWidgets[k].settings.answers[k].next_step = formSectionIds[_next_step - 1];
                    }
                }
            }
        }
    };
}

I'm looking for any hints how to refactor it, as I think there are too many for loops.


texts: Spawning two threads and if any of the threads returns true, let the main thread ignore the other and move on

texts:
Exact problem statement:

A main thread spawns 2 new threads, the main thread waits on this
threads with these conditions:

if any of the threads returns True, then main thread moves on and prints the thread_id and timestamp of the thread.
if both threads return false, finish execution and don't print anything

My attempt:
public static void main(String[] args) throws InterruptedException, ExecutionException{
        FutureTask<Boolean> futureTask = new FutureTask<>(() -> {
          System.out.println("Hello, World 1!");
          return true;
        });
        FutureTask<Boolean> futureTask2 = new FutureTask<>(() -> {
          System.out.println("Hello, World 2!");
          return true;
        });

        Thread t1 = new Thread(futureTask);
        Thread t2 = new Thread(futureTask2);
        t1.start();
        t2.start();

        // Wait for either to be done.
        while (!futureTask.isDone() && !futureTask2.isDone());

        if (futureTask.isDone()) {
          if (futureTask.get()) {
            System.out.println("1 - " + t1.getId() + " " + System.currentTimeMillis());
            return;
          }
        }

        if (futureTask2.isDone()) {
          if (futureTask2.get()) {
            System.out.println("2 - " + t2.getId() + " " + System.currentTimeMillis());
            return;
          }
        }
    }
}

When I run this a few times, sometimes thread 1 wins, sometimes 2, which seems to make sense to me. Appreciate any room for improvement or advice.


texts:
I'm writing a program to print binary string of a hardcoded word. Here is how it looks like currently:

main.asm

section .text
    global _start
    extern _print_binary_content

_start:
    push word [word_to_print] ; pushing word. Can we push just one byte?
    call _print_binary_content

    mov rax, 60
    mov rdi, 0
    syscall

section .data
    word_to_print: dw 0xAB0F

printer.asm

SYS_BRK_NUM equ 0x0C
BITS_IN_WORD equ 0x10
SYS_WRITE_NUM equ 0x01
STD_OUT_FD equ 0x01
FIRST_BIT_BIT_MASK equ 0x01
ASCII_NUMBER_OFFSET equ 0x30

section .text
    global _print_binary_content

_print_binary_content:
    pop rbp

    xor ecx, ecx ;zeroing rcx
    xor ebx, ebx ;zeroing rbx
    pop bx  ;the word to print the binary content of

    ;sys_brk for current location
    mov rax, SYS_BRK_NUM
    mov rdi, 0
    syscall
    ;end sys_brk

    mov r12, rax ;save the current brake location

    ;sys_brk for memory allocation 16 bytes
    lea rdi, [rax + BITS_IN_WORD]
    mov rax, SYS_BRK_NUM
    syscall
    ;end sys_brk

    xor ecx, ecx
    mov cl, byte BITS_IN_WORD - 1; used as a counter in the loop below

    loop:
        mov dx, bx
        and dx, FIRST_BIT_BIT_MASK
        add dx, ASCII_NUMBER_OFFSET
        mov [r12 + rcx], dl
        shr bx, 0x01
        dec cl
        cmp cl, 0
        jge loop

    mov rsi, r12
    mov rax, SYS_WRITE_NUM
    mov rdi, STD_OUT_FD
    mov rdx, BITS_IN_WORD
    syscall

    push rbp ; pushing return address back
    ret

If I compile link and run this program it works. But the question is about performance and maybe conventions of writing assembly programs. In the file printer.asm I cleaned ecx twice which looks kind of not optimal. Maybe some registers were used not by their purpose (I used intel-manual).

Can you please help me to improve this very simple program?


texts:
I am fetching a list of messages from some JSON and appending each message as an LI within a UL. I have created the message template within jQuery to append each message to the document. My code works well but I can't help but feel it could be improved (I am a beginner JS programmer). From what I have seen online moving the templating to handlebars.js would be a better solution but I can't be sure.

$(document).ready(function() {
  var broadcastMessagesJsonURL = "https://api.myjson.com/bins/sadap";
  $.getJSON(broadcastMessagesJsonURL, function(data) {
  $.each(data.broadcastMessages, function(i, item) {

  //All items from the json
  var broadcastMessageID = (item.ID);
  var checkBroadcastMessageRead = (item.read ? " broadcast__message__read__state--unread" : "");
  var broadcastMessageSubject = (item.subject);
  var broadcastMessageGroup = (item.group);
  var broadcastMessageDateSent = (item.dateSent);
  var checkBroadcastFeatureImage = (item.featureImage ? " broadcast__message__image--active" : "");
  var checkBroadcastForm = (item.form ? " broadcast__message__form--active" : "");
  var checkBroadcastAttachments = (item.attachments ? " broadcast__message__attachment--active" : "");
  var broadcastMessageContent = (item.content);

  var broadcastMessageTemplate = ('
 \

 \

 \

' + broadcastMessageSubject + '
 \

' + broadcastMessageGroup + '
 \

' + broadcastMessageDateSent + '
 \

' + broadcastMessageContent + '
 \

 \

');
  $(".broadcast__messages__list").append(broadcastMessageTemplate);
});
  }).fail(function() {
    console.log("broadcastMessages json cannot be loaded");
  });
});

CODEPEN LINK


texts: Parsing and converting DMS Coordinates from String to Double

texts:
I have some coordinates looking like

  N47° 15' 36.75",E011° 20' 38.28",+001906.00

and I've created a class to parse and convert them to Double:

struct PLNWaypointCoordinate {
    var latitude: Double = 0.0
    var longitude: Double = 0.0

    init(coordinateString: String) {
        self.latitude = convertCoordinate(string: coordinateString.components(separatedBy: ",")[0])
        self.longitude = convertCoordinate(string: coordinateString.components(separatedBy: ",")[1])
    }

    private func convertCoordinate(string: String) -> Double {
        var separatedCoordinate = string.characters.split(separator: " ").map(String.init)

        let direction = separatedCoordinate[0].components(separatedBy: CharacterSet.letters.inverted).first
        let degrees = Double(separatedCoordinate[0].components(separatedBy: CharacterSet.decimalDigits.inverted)[1])
        let minutes = Double(separatedCoordinate[1].components(separatedBy: CharacterSet.decimalDigits.inverted)[0])
        let seconds = Double(separatedCoordinate[2].components(separatedBy: CharacterSet.decimalDigits.inverted)[0])

        return convert(degrees: degrees!, minutes: minutes!, seconds: seconds!, direction: direction!)
}

    private func convert(degrees: Double, minutes: Double, seconds: Double, direction: String) -> Double {
        let sign = (direction == "W" || direction == "S") ? -1.0 : 1.0
        return (degrees + (minutes + seconds/60.0)/60.0) * sign
    }

}

Is there a better and safer way to perform this conversion?

Last method I've picked up here. Sorry, but I can't find the link to reference it.


texts: Refactoring my simple model-view-presenter architecture

texts:
My application uses a simple Model-View-Presenter architecture and uses the following classes and interface:

Presenter:

public abstract class Presenter<V> {

    private V view;

    public final void setView(V view) {
        this.view = view;
    }

    protected final V getView() {
        return this.view;
    }
}

View

public abstract class View<V, P extends Presenter<V>> implements ViewAdapter<V> {

    private final P presenter;

    public View(P presenter) {
        this.presenter = presenter;
    }

    protected final P getPresenter() {
        return this.presenter;
    }

    void initialize() {
        this.getPresenter().setView(this.asView());
    }
}

ViewAdapter

interface ViewAdapter<T> {
    T asView();
}

The application is then wired up like this:

A concrete Presenter is created.
A concrete View is created, passing in the concrete Presenter as a constructor parameter.
The View is initialised. During initialisation, the View calls the asView method to pass a view instance to the presenter.

Each concrete presenter in the application is parameterised with a view interface. Each concrete view class implements a view interface and can then pass itself to the presenter during initialisation and it is in this area that I am looking for advice.

The ViewAdapter interface exists solely to allow the concrete view to pass itself to the presenter via the asView method whilst maintaining type safety. My concrete views which derive from the View class are then forced to provide an implementation of the asView method in order to provide a view instance to the presenter that is of the correct type.

Every implementation looks the same:

@Override
public FooView asView() {
    return this; // this implements the FooView interface.
}

All this basically does is force 'this' to implement FooView as I am unable to express something like this:

// Example, not valid code, won't compile!
public abstract class View<V, P extends Presenter<V>> implements V {
}

Which would allow me to remove the ViewAdapter interface and pass the view to the presenter in the abstract View class like this, removing the redundancy:

void initialize() {
    this.getPresenter().setView(this);
}


texts:
Here's my implementation of Generic Factory using Function library.

It was created using Function library because I understand that the newInstance method is costly (as it uses reflections in the background[not sure about it]) and mostly because our teacher have decided :-).

I wonder about how can it be more generic from the ARGS perspective. As you can understand: this implementation limits the Factory only to one type of functions (ones with Void args in this Main example).

I will be happy to hear any opinions about this or any other aspect of the code.

import java.util.HashMap;
import java.util.function.Function;

public class Factory<Key, Type, Args> {

    HashMap<Key, Function<Args, ? extends Type>> map;

    public Factory(){
        map = new HashMap<>();
    }

    public void add(Key key, Function<Args, ? extends Type> func){
        map.put(key, func);
    };

    public Type create (Key key, Args args){
        return map.get(key).apply(args);
    }
}

class Pizza{

    public Object bake(Void v){

        System.out.println("baking");
        return new Object();
    }

    public static Pizza getInst(Void v) {
        return (new Pizza());
    }
}

public class Main {

    public static void main(String[] args) {

        Factory<String, Object, Void> pizzaFactory = new Factory<>();
        pizzaFactory.add("Pizza", Pizza::getInst);

        Pizza slice = (Pizza)pizzaFactory.create("Pizza", null);
        pizzaFactory.add("bake", slice::bake);
        pizzaFactory.create("bake", null);
    }
}


texts: Remove every occurence of the number 13 and the next number from a list, then sum the result

texts:
This function takes a list, deletes every occurrence of the number 13 and deletes the number present after 13 in every instance and then prints the sum of the list.

How can I shorten it?

def average(nums):
  thirteen_idx = []
  bad_idx = []
  final_list = []
  num_length = len(nums)-1

  #list of indexes where 13 resides
  for i in range(len(nums)):
    if nums[i] == 13:
      thirteen_idx.append(i)

  #make list of indexes where 13 resides and the index after it (bad_idx)
  for i in range(len(thirteen_idx)):
    bad_idx.append(thirteen_idx[i])
    bad_idx.append(thirteen_idx[i]+1)

  #delete any index from bad_idx that is greater than the highest index in nums
    if bad_idx[-1] > num_length:
        bad_idx.pop(len(bad_idx)-1)

  #we now have a list of all bad indexes (bad_idx)

  #iterate thru nums and move any non bad index into a final_list
  for i in range(len(nums)):
    if i not in bad_idx:
      final_list.append(nums[i])

  print (sum(final_list))


texts: Synchronized implementation of a bank account in Java

texts:
I am trying to implement a bank account with Java in a thread safe way. My code looks like:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Class to represent an account, it also provides with methods to add and withdraw amount from the account.
 *
 * @author Karan Khanna
 * @version 1.0
 * @since 3/17/2019
 */
public class Account {

    private ReadWriteLock accountLock;

    private BigDecimal balance;

    private String accountNumber;

    private String accountHolder;

    public Account(String accountNumber, String accountHolder) {
        this.balance = new BigDecimal(0);
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
        this.accountLock = new ReentrantReadWriteLock();
    }

    public double getBalance() {
        this.accountLock.readLock().lock();
        double balance = this.balance.setScale(2, RoundingMode.HALF_DOWN).doubleValue();
        this.accountLock.readLock().unlock();
        return balance;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public String getAccountHolder() {
        return accountHolder;
    }

    public ReadWriteLock getAccountLock() {
        return accountLock;
    }

    public void addAmount(double amount) {
        this.accountLock.writeLock().lock();
        this.balance.add(new BigDecimal(amount));
        this.accountLock.writeLock().unlock();
    }

    public void withdrawAmount(double amount) {
        this.accountLock.writeLock().lock();
        this.balance.subtract(new BigDecimal(amount));
        this.accountLock.writeLock().unlock();
    }
}

I am looking for feedback for the implementation.


texts: Finding the kth to last element of a singly linked list

texts:
I'm not sure if this code is industry-standard or not. Please review it and let me know if any improvement is required.

class Node(object):
   def __init__(self,data,next):
        self.data=data
        self.next=next

class getLinkRest():
       head = None
       tail= None

   def insert(self,data):
      node=Node(data,None)
     if self.head is None:
       self.head=self.tail=node
     else:
       self.tail.next=node
     self.tail=node

 def showFromItem(self,data):
     curr_node=self.head
     flag=None
     while curr_node is not None:
          if curr_node.data == data or curr_node.data > data:
            print curr_node.data
            flag =1
            curr_node=curr_node.next
    if(flag is None):
       print "Not exist"

  s= getLinkRest()
  s.insert(1)
  s.insert(2)
  s.insert(3)
  s.insert(4)
  s.insert(5)
  s.showFromItem(3)
  s.showFromItem(7)


texts:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
  Find the sum of all the multiples of 3 or 5 below 1000.

Could someone point out if there is something wrong with the code; where I should optimize/modify it?

import java.util.Scanner;

public class SumBelowN {

    private double getSum(int N) {
        int n1 = 3;
        int next_n1 = 3;
        int n2 = 5;
        int next_n2 = 5;
        double sum = 0;

        while (next_n1 < N || next_n2 < N) {
            if (next_n1 == next_n2) {
                sum += next_n1;
                next_n1 += n1;
                next_n2 += n2;
                continue;
            } else if (next_n1 < next_n2) {
                sum += next_n1;
                next_n1 += n1;
                continue;
            } else {
                sum += next_n2;
                next_n2 += n2;
                continue;
            }
        }

        return sum;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int i = sc.nextInt();

        // print the sum of all the numbers below 'i'
        // which are divisible by both 3 and 5.
        SumBelowN sumBelowN = new SumBelowN();

        System.out.println("Sum: " + sumBelowN.getSum(i));
        sc.close();
    }
}


texts:
Please review my code and let me know how I can possibly improve it.

#include<iostream>

using namespace std;

class node
{
    private:
                    int data;
    public:
                  node *next;
                    node(int element)
                    {
                            data=element;
                            next=NULL;
                    }
                    int getdata()
                    {
                        return(data);
                    }
};

class stack
{
    private:
                    node *start;
    public:
                    void push(int element);
                    int pop();
                    void traverse();
                    stack()
                    {
                        start=NULL;
                    }
};

inline void stack::push(int element)
{
    node *ptr;
    node *temp=start;
    ptr=new node(element);
    if(start==NULL)
    {
        start=ptr;
        ptr->next=NULL;

    }
    else
    {
            while(temp->next!=NULL)
            {
                temp=temp->next;
            }
            temp->next=ptr;
            ptr->next=NULL;
    }
}

inline int stack::pop()
{
    node *temp=start;
    node *top=start;
    while(temp->next!=NULL)
    {
        temp=temp->next;
    }
    while(top->next!=temp)
    {
        top=top->next;
    }
    top->next=NULL;
    int item=temp->getdata();
    delete (temp);
}

inline void stack::traverse()
{
    node *temp=start;
    while(temp!=NULL)
    {
        cout<<"data is"<<temp->getdata();
        temp=temp->next;
    }
}

int main()
{
  stack a;
    for(int i=0;i<10;i++)
    {
        a.push(i);
    }
    a.traverse();
    for(int i=0;i<5;i++)
    {
        a.pop();
    }
    a.traverse();
    return(0);
}


texts: TCPListener server to discover clients on a network

texts:
I am currently writing a program to sync files (music, photos, etc) from my PC to an Android device. In order to do this, I have 2 application: one that is running on my PC, and one that shall be running on the Android device. When the Android app will open, it will try to connect to a specified IP:port on the PC application, which has a server just listening for requests in order to show the clients in a WPF list style view. This server is written in F#.

Here is the server implementation I have come up with:

type TCPListenerServer(discoveryPort:int) =
    let server = new TcpListener (IPAddress.Loopback, discoveryPort)

    let activeConnections = new List<TcpClient>()

    let serverLoop () =
        let rec loop (pendingConnection:Task<TcpClient>) = async {
            let newPendingConnection, client =
                match pendingConnection.Status with
                | TaskStatus.Created | TaskStatus.WaitingForActivation | TaskStatus.WaitingToRun | TaskStatus.Running  ->
                    (None, None)
                | TaskStatus.Faulted | TaskStatus.Canceled ->
                    raise (new System.NotImplementedException())
                | TaskStatus.RanToCompletion ->
                    let connectionTask = server.AcceptTcpClientAsync ()
                    (Some connectionTask, Some pendingConnection.Result)
                | _ ->
                    raise (new System.NotImplementedException())

            // Add the new client to the list
            Option.iter (fun c -> activeConnections.Add c) client

            // Switch the new pending connection if there is one
            let connectionAttempt = defaultArg newPendingConnection pendingConnection

            Async.Sleep 1000 |> Async.RunSynchronously
            return! loop connectionAttempt
        }

        try
            server.Start ()

            let connectionTask = server.AcceptTcpClientAsync ()

            loop connectionTask
        finally
            server.Stop ()

    member x.Start () =
        serverLoop () |> Async.Start

    member x.Stop () =
        server.Stop ()

    member x.ActiveConnections =
        activeConnections

I wanted to know if my implementation was acceptable. I am unsure what is best: using a .NET List, or using a mutable variable that holds an F# list for activeConnections.

Also, usually I would keep the state of my object encapsulated in the serverLoop and just passing the updated list to each iteration, but doing this I cannot expose it so that I may have access to it from the outside (to bind on it in my WPF for example). Is there a better way to do this?


texts: Node.js configuration object based on environment variables

texts:
In the code below, I am building a NODE_ENV-sensitive config object from environment variables.

let username
let password
let cluster
let hosts
let databaseName
let replicaSet

if (process.env.NODE_ENV === 'production') {
  username = process.env.ATLAS_HUB_USERNAME
  password = process.env.ATLAS_HUB_PASSWORD
  cluster = process.env.ATLAS_CLUSTER
  hosts = process.env.ATLAS_HOSTS
  databaseName = process.env.ATLAS_DATABASE
  replicaSet = process.env.ATLAS_REPLICA_SET
} else {
  username = process.env.MONGO_HUB_USERNAME
  password = process.env.MONGO_HUB_PASSWORD
  cluster = process.env.MONGO_CLUSTER
  hosts = process.env.MONGO_HOSTS
  databaseName = process.env.MONGO_DATABASE
  replicaSet = process.env.MONGO_REPLICA_SET
}
const config = { username, password, cluster, hosts, databaseName, replicaSet }

In this new age of fancy spread and rest operators, I hate polluting my files with code like this which repeat the same variable name multiple times and uses let instead of const for the wrong reasons, all for something simple and frequent. I could use the ternary operator to get something way better:

const config = {
  username:     process.env.NODE_ENV === 'production' ? process.env.ATLAS_HUB_USERNAME : process.env.MONGO_HUB_USERNAME,
  password:     process.env.NODE_ENV === 'production' ? process.env.ATLAS_HUB_PASSWORD : process.env.MONGO_HUB_PASSWORD,
  cluster:      process.env.NODE_ENV === 'production' ? process.env.ATLAS_CLUSTER : process.env.MONGO_CLUSTER,
  hosts:        process.env.NODE_ENV === 'production' ? process.env.ATLAS_HOSTS : process.env.MONGO_HOSTS,
  databaseName: process.env.NODE_ENV === 'production' ? process.env.ATLAS_DATABASE : process.env.MONGO_DATABASE,
  replicaSet:   process.env.NODE_ENV === 'production' ? process.env.ATLAS_REPLICA_SET : process.env.MONGO_REPLICA_SET
}

But even this seems one step short of what modern js should be able to do. I'd now like to get rid of the repeated process.env.NODE_ENV, I just can't figure out how (apart from creating a new const with a shorter name). If I had a magic wand, I'd write something along the following lines:

const config = ({
  username: [process.env.MONGO_HUB_USERNAME, process.env.ATLAS_HUB_USERNAME],
  password: [process.env.MONGO_HUB_PASSWORD, process.env.ATLAS_HUB_PASSWORD],
  cluster: [process.env.MONGO_CLUSTER, process.env.ATLAS_CLUSTER],
  hosts: [process.env.MONGO_HOSTS, process.env.ATLAS_HOSTS],
  databaseName: [process.env.MONGO_DATABASE, process.env.ATLAS_DATABASE],
  replicaSet: [process.env.MONGO_REPLICA_SET, process.env.ATLAS_REPLICA_SET]
}).*[new Number(process.env.NODE_ENV === 'production')]

But I don't, and it's not even all that great, sooo, any suggestions?

I thought of using a function, like below, but this just introduces another dependency you need to internalize for a simple batch conditional assignment operation... And if the function is in-line, there is duplication across files and it's frankly just confusing.

function fromEach (obj, key) {
  const final = {}
  Object.keys(obj).forEach((k) => {
    final[k] = obj[k][key]
  })
  return final
}
const config = fromEach({
  username: [process.env.MONGO_HUB_USERNAME, process.env.ATLAS_HUB_USERNAME],
  password: [process.env.MONGO_HUB_PASSWORD, process.env.ATLAS_HUB_PASSWORD],
  cluster: [process.env.MONGO_CLUSTER, process.env.ATLAS_CLUSTER],
  hosts: [process.env.MONGO_HOSTS, process.env.ATLAS_HOSTS],
  databaseName: [process.env.MONGO_DATABASE, process.env.ATLAS_DATABASE],
  replicaSet: [process.env.MONGO_REPLICA_SET, process.env.ATLAS_REPLICA_SET]
}, new Number(process.env.NODE_ENV === 'production'))

Note: I use new Number(process.env.NODE_ENV === 'production') in these examples, but I don't like it, feel free to propose something better!


texts: Project Euler Problem #3 in Java - Largest Prime Factor

texts:
I have solved the problem and it gives me the right output when the BigInteger has the smaller value, however it kept running for more than 20 minutes with the larger value without printing out an answer. So I'm thinking that there should be a faster algorithm for this program.

The problem states:

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143 ?

Main Method:

printPrimeFactors(new BigInteger("13195"));

Output:

  29 13 7 5

  BUILD SUCCESSFUL (total time: 0 seconds)

But when I change the value:

Main Method

printPrimeFactors(new BigInteger("600851475143"));

The program keeps running for a long time (more than 20 minutes), I didn't wait for an answer and stopped it.

Here is the rest of the program:

public static boolean isPrime(BigInteger n) {
    if(n.compareTo(new BigInteger("2")) == -1) return false;
    if(n.equals(new BigInteger("2")) || n.equals(new BigInteger("3"))) return true;
    if(n.remainder(new BigInteger("2")).equals(BigInteger.ZERO) || n.remainder(new BigInteger("3")).equals(BigInteger.ZERO)) return false;
    BigInteger sqrtN = bigIntSqRootFloor(n).add(BigInteger.ONE);

    for(BigInteger i = new BigInteger("6"); i.compareTo(sqrtN) == 0 || i.compareTo(sqrtN) == -1; i = i.add(new BigInteger("6"))){
        if(n.remainder(i.subtract(BigInteger.ONE)).equals(BigInteger.ZERO)) return false;
        else if(n.remainder(i.add(BigInteger.ONE)).equals(BigInteger.ZERO)) return false;
    }
    return true;
}

public static void printPrimeFactors(BigInteger number){

    for(BigInteger i = BigInteger.ZERO.add(number);!i.equals(new BigInteger("1")); i = i.subtract(BigInteger.ONE)){
        if(isPrime(i) && number.remainder(i).equals(BigInteger.ZERO)){
            System.out.print(i + " ");
            number = number.divide(i);
            printPrimeFactors(number);
            break;
        }
    }
}

public static BigInteger bigIntSqRootFloor(BigInteger x)
    throws IllegalArgumentException {
    if (x.compareTo(BigInteger.ZERO) < 0) {
        throw new IllegalArgumentException("Negative argument.");
    }

    if (x .equals(BigInteger.ZERO) || x.equals(BigInteger.ONE)) {
        return x;
    }

    BigInteger two = BigInteger.valueOf(2L);
    BigInteger y;

    for(y = x.divide(two);
            y.compareTo(x.divide(y)) > 0;
            y = ((x.divide(y)).add(y)).divide(two));
    return y;
}


texts: Generating three-letter strings from five-letter words

texts:
I am looking for feedback on a solution to the following problem posed from a book that I'm working through (Java: How To Program, 9th Edition):

  Write an application that reads a five-letter word from the user and produces every possible three-letter string that can be derived from the letters of that word.  For example, the three-letter words produced from the word "bathe" include "ate," "bet," "tab," "hat," "the," and "tea."

I have a sneaking suspicion that I've over complicated things.  Is my code easy to understand?  I'm a rookie coder still going over the basics.

import java.util.Scanner;

public class ThreeLetterStrings {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner( System.in );
        System.out.println( "Please enter a five letter word" );
        String userInput = sc.nextLine();           // get input
        int wordLength = userInput.length();       // get length of string in question
        char[] charArray = new char[ wordLength ];
        int stem = 0;       // stem being the 2nd letter after the first - b(a)the or ba(t)he
        int scan = 0;       // scan count for while loop
        boolean stamp;

        for( int i = 0; i < charArray.length; i++ )     // feed string into char array
        {
            charArray[ i ] = userInput.charAt( i );
        }

        for( int startLetter = 0; startLetter < wordLength; startLetter++ )
        {
            for( int stemLetter = 1; stemLetter < wordLength; stemLetter++ )
            {
            stem = startLetter + stemLetter;
            if( stem >= wordLength )
                stem = stem - wordLength;
            scan = 0;       // reset scan count after walk for loop
                for( int walk = 0; walk < wordLength - 2; walk++ )
                {
                    System.out.printf( "%c", charArray[ startLetter ] );
                    System.out.printf( "%c", charArray[ stem ] );
                    stamp = false;      // determines whether a character was printed

                    while( stamp == false )
                    {
                        if( scan == startLetter || scan == stem  )
                        {
                            scan++;
                        }
                        else
                        {
                            System.out.printf( "%c", charArray[ scan ] );
                            stamp = true;
                            System.out.println();
                            scan++;
                        }
                    } // end while
                } // end walk for
            } // end stemLetter for
        } // end startLetter for
    }
}


texts: Calculating revenue from roller coaster rides

texts:
Problem description:

  The task is to calculate the amount of money earned from roller
  coaster rides on any given day.  There is a queue in front of the
  attraction.  Visitors might be alone or in groups. All members of
  the same group will want to ride together.  The ride begins once
  the roller coaster runs out of sufficient space for the next group.
   Once a ride is over, passengers go back to the end of the queue
  in the same order.
  Each passenger pays one dirham to ride the roller coaster once.
  The roller coaster can only operate a limited number of times each day.

Here is my code:

public static class RollerCoaster
{
    private static int CountDirhamsEarnedInOneOperation(int numAvailablePlaces, LinkedList<int> numPeopleInEachGroup)
    {
        //Each passenger pays one dirham to take the ride once.
        int dirhamsEarned = 0;
        int numGroupsInQueue = numPeopleInEachGroup.Count();

        while (numPeopleInEachGroup.First() <= numAvailablePlaces && numGroupsInQueue > 0)
        {
            dirhamsEarned += numPeopleInEachGroup.First();
            numAvailablePlaces -= numPeopleInEachGroup.First();
            numPeopleInEachGroup.AddLast(numPeopleInEachGroup.First());
            numPeopleInEachGroup.RemoveFirst();
            numGroupsInQueue--;
        }

        return dirhamsEarned;
    }

    public static long CalculateDirhamsEarned(int numAvailablePlaces, int numOperationsPerDay, LinkedList<int> numPeopleInEachGroup)
    {
        long dirhamsEarned = 0;

        while (numOperationsPerDay > 0)
        {
            dirhamsEarned += (long)CountDirhamsEarnedInOneOperation(numAvailablePlaces, numPeopleInEachGroup);
            numOperationsPerDay--;
        }

        return dirhamsEarned;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter:\nThe number of places available;\nThe number of times the attraction can function per day;\nThe number of groups in the queue.");
        string[] inputs = Console.ReadLine().Split(' ');

        int numAvailablePlaces = int.Parse(inputs[0]);
        int numOperationsPerDay = int.Parse(inputs[1]);
        int numGroupsInQueue = int.Parse(inputs[2]);
        LinkedList<int> numPeopleInEachGroup = new LinkedList<int>();

        Console.WriteLine("Please enter, line by line, the number of people in each group: ");
        for (int i = 0; i < numGroupsInQueue; i++)
        {
            int numPeopleInGroup = int.Parse(Console.ReadLine());
            numPeopleInEachGroup.AddLast(numPeopleInGroup);
        }

        long dirhamsEarned = RollerCoaster.CalculateDirhamsEarned(numAvailablePlaces, numOperationsPerDay, numPeopleInEachGroup);
        Console.WriteLine(dirhamsEarned.ToString());
    }
}

I'm a C# beginner, so I'd appreciate any kind of advice, though I am specifically looking for suggestions that help me improve the time-complexity of my algorithm. My program takes way too long to run when numOperationsPerDay is, say, 10,000,000.


texts: Parsing version number from a Java source file

texts:
I'm extracting the version number from a file like this one. It works, but I find it clumsy and longer than probably needed.
I'd also appreciate some sanity checks as long as they don't make the code noticeably longer (It's just a script, no full Java parser. Something similar to Guava's getOnlyElement would be nice).
version = {->
    def lines = file('src/main/org/h2/engine/Constants.java').readLines();
    def extract = {name ->
        lines.grep {it =~ /public static final int $name =/}[0].replaceFirst(/.*=\s*(\d+);.*/, '$1')
    }
    extract('VERSION_MAJOR') + '.' + extract('VERSION_MINOR') + '.' + extract('BUILD_ID')
}()


texts:
The Collatz Sequence is an iterative sequence that is defined for all positive integers as such:

n → n/2 (n is even)

n → 3n + 1 (n is odd)

If 13 were to be entered into this sequence, the result would be as follows:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

And the total number of terms in the chain would be 10. The sequence always ends with 1.

You must create a program that will calculate for a value in the range of 2 <= x < 1000000. This value must give the longest chain of terms when inputted into the Collatz Sequence.

I will now post my solution. Any criticism would be greatly appreciated. Did I use too many if/else statements? Was recursion not the best thing to use? Anything you have to say.

File Main.cpp

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

  namespace coll {
    int counter(1);

    long long doEven(long long numb) {
      if (numb != 1) {
        if (numb % 2 == 0) {
          counter++;
          return doEven(numb / 2);
        } else
          return doOdd(numb);
      } else
        return counter;
    }

    long long doOdd(long long numb) {
      if (numb != 1) {
        if (numb % 2 != 0) {
          counter++;
          return doOdd((3 * numb) + 1);
        } else
          return doEven(numb);
      } else
        return counter;
    }

    int chainLength(0);
    int temp(0);
    int theBestInput(0);

    int longestChain(int input) {
      if (input < 1000000) {
        if (input % 2 == 0)
          temp = doEven(input);
        else
          temp = doOdd(input);
        counter = 1;
        if (temp > chainLength) {
          chainLength = temp;
          theBestInput = input;
          input++;
          return longestChain(input);
        } else {
          input++;
          return longestChain(input);
        }
      } else {
        return theBestInput;
      }
    }

    void printResult() {
      std::cout << "LONGEST SEQUENCE: " << longestChain(2) << std::endl;
    }
  }

File Main.h

#pragma once
namespace coll {
  extern int counter;
  extern int theBestInput;
  extern int chainLength;
  extern int temp;
  long long doEven(long long numb);
  long long doOdd(long long numb);
  int longestChain(int input);
  void printResult();
}

File Test.cpp

#include "Main.h"
int main() {
  coll::printResult();
  return 0;
}


texts: A custom Pandas dataframe to_string method

texts:
Oftentimes I find myself converting pandas.DataFrame objects to lists of formatted row strings, so I can print the rows into, e.g. a tkinter.Listbox. To do this, I have been utilizing pandas.DataFrame.to_string. There is a lot of nice functionality built into the method, but when the number of dataframe rows/columns gets relatively large, to_string starts to tank.

Below I implement a custom pandas.DataFrame class with a few added methods for returning formatted row lines. I am looking to improve upon the get_lines_fast_struct method.

import pandas

class DataFrame2(pandas.DataFrame):
    def __init__( self, *args, **kwargs ):
        pandas.DataFrame.__init__(self, *args, **kwargs)

    def get_lines_standard(self):
        """standard way to convert pandas dataframe
            to lines with fomrmatted column spacing"""
        lines = self.to_string(index=False).split('\n')
        return lines

    def get_lines_fast_unstruct(self):
        """ lighter version of pandas.DataFrame.to_string()
            with no special spacing format"""
        df_recs = self.to_records(index=False)
        col_titles = [' '.join(list(self))]
        col_data = map(lambda rec:' '.join( map(str,rec) ),
                         df_recs.tolist())
        lines = col_titles + col_data
        return lines

    def get_lines_fast_struct(self,col_space=1):
        """ lighter version of pandas.DataFrame.to_string()
            with special spacing format"""
        df_recs = self.to_records(index=False) # convert dataframe to array of records
        str_data = map(lambda rec: map(str,rec), df_recs ) # map each element to string
        self.space = map(lambda x:len(max(x,key=len))+col_space,  # returns the max string length in each column as a list
                         zip(*str_data))

        col_titles = [self._format_line(list(self))]
        col_data = [self._format_line(row) for row in str_data ]

        lines = col_titles + col_data
        return lines

    def _format_line(self, row_vals):
        """row_vals: list of strings.
           Adds variable amount of white space to each
           list entry and returns a single string"""
        line_val_gen = ( ('{0: >%d}'%self.space[i]).format(entry) for i,entry in enumerate(row_vals) )  # takes dataframe row entries and adds white spaces based on a format
        line = ''.join(line_val_gen)
        return line

Here I make some test data

import random
import numpy

#SOME TEST DATA
df = DataFrame2({'A':numpy.random.randint(0,1000,1000),
                 'B':numpy.random.random(1000),
                 'C':[random.choice(['EYE', '<3', 'PANDAS', '0.16'])
                      for _ in range(1000)]})

Method outputs

df.get_lines_standard()
#[u'   A         B       C',
# u' 504  0.924385      <3',
# u' 388  0.285854    0.16',
# u' 984  0.254156    0.16',
# u' 446  0.472621  PANDAS']
# ...

df.get_lines_fast_struct()
#['   A                 B      C',
# ' 504      0.9243853594     <3',
# ' 388    0.285854082778   0.16',
# ' 984    0.254155910401   0.16',
# ' 446    0.472621088021 PANDAS']
# ...

df.get_lines_fast_unstruct()
#['A B C',
# '504 0.9243853594 <3',
# '388 0.285854082778 0.16',
# '984 0.254155910401 0.16',
# '446 0.472621088021 PANDAS']
# ...

Timing results

In [262]: %timeit df.get_lines_standard()
10 loops, best of 3: 70.3 ms per loop

In [263]: %timeit df.get_lines_fast_struct()
100 loops, best of 3: 15.4 ms per loop

In [264]: %timeit df.get_lines_fast_unstruct()
100 loops, best of 3: 2.3 ms per loop


texts: Random alphanumeric password generator with GOTOs

texts:
I was inspired after this thread on Stack Overflow to create a random 8 character alphanumeric password generator.

Sadly, it is closed, so I cannot provide an answer there. Anyway, here is the code. Let me know if there are any bugs/bias going on.

using System.Collections.Generic;
using System.Security.Cryptography;

public class AlphanumericGen
{
    public virtual string Generate(byte length)
    {
        ICollection<char> chars = new LinkedList<char>();
        var buffer = new byte[1];
        short counter = 0;
        using (var rng = new RNGCryptoServiceProvider())
        {
            while (counter < length)
            {
                rng.GetBytes(buffer);
                var nextChar = (char)buffer[0];

                if (nextChar >= '0' && nextChar <= '9')
                {
                    goto addChar;
                }

                if (nextChar >= 'A' && nextChar <= 'Z')
                {
                    goto addChar;
                }

                if (nextChar >= 'a' && nextChar <= 'z')
                {
                    goto addChar;
                }

                continue;

            addChar:
                chars.Add(nextChar);
                ++counter;
            }
        }

        return string.Concat(chars);
    }
}


texts:
I have a dictionary that looks like this:

Counter({(1, 9): 3, (4, 2): 2, (3, 0): 1, (5, 4): 1})

I would like to convert it to an array that would look like this:

[[1, 9, 3], [4, 2, 2], [3, 0, 1], [5, 4, 1]]

Help appreciated!

import itertools
import collections
import numpy as np

a = [1,5,1,1,3,4,4] # First column
b = [9,4,9,9,0,2,2] # Second column
ind = np.lexsort((b,a)) # Sort by a, then by b
print (ind)
c= [(a[i],b[i]) for i in ind]
d =np.array(c)

counts = collections.Counter()
list_of_items = d
for sublist in list_of_items:
    counts.update(itertools.combinations(sublist, 2))


texts: Given table of values, find rows that match a predicate

texts:
I'm working on the following problem:

We have a Row Java type that roughly represents that of database table row (meaning it has a set of fields and is identified by complete set of values in those fields). Number and types of all fields are known up-front.

Given a collection of these Row objects, I need to construct a query into database that would tell me which of these objects are "locked" (pass a predicate). The query will be against a table that has additional fields to those inside Row class (it has more columns). The predicate is the following:

where locked = 1

There, locked column is the emulation of a bool column in Oracle.

My problem is: almost all of the fields in Row class (and, consequently, in table I will be querying against) are nullable. Example fields in Row class (names are made up to not disclose our actual design):

CATEGORY - foreign key into categories table, the only non-nullable field
PRODUCT_ATTRIBUTE - foregn key into product_attributes table
EXTERNAL_ATTRIBUTES - varchar(64), this value and product_attribute are mutually exclusive in our setup.
STAGE - foreign key into stages
CREATION_DATE - timestamp by design, however, our business rules dictate that value should be trunc()'ed when comparing to something.
FREEFORM_ATTRIBUTES - varchar(4000)

Simplest way to achieve what I want to construct a single query using single Row instance for parameters. Since this is dynamic query, I can change query to contain is null where appropriate, for example:

select
  category,
  product_attribute,
  external_attributes,
  stage,
  creation_date,
  freeform_attributes
from rows
where locked = 1
  and category = ?
  and product_attribute is null
  and <etc...>

However, since database and appserver are not on same machine, I'd like to query in bulk.

Best I could come up with so far is the following query:

with dataset
(category, product_attribute, external_attributes, stage, creation_date, freeform_attributes) as (
  select ?, ?, ?, ?, ?, ? from dual
  union all
  select ?, ?, ?, ?, ?, ? from dual
  <etc...>
  /* this is the part in query that gets generated in Java */
)

select
   category, product_attribute, external_attributes, stage,
   trunc(creation_date), freeform_attributes
from rows
where locked = 1
  and category in (?,?,?/*...values of all categories since they are guaranteed to not be null ...*/)

intersect
select * from dataset

This approach, however, doesn't seem like it will be processed by database and produce good performance, since query part that constructs dataset table will be changing frequently, which I think will throw off optimizers.

More info about setup:

rows table contains a lot of rows, up to several millions
collection that I'm receiving in Java can vary in size from 1 to ~500
it can be reasonably assumed that reach set of field values in rows table is distinct
nulls can be substituted for foreign key field values with -1. Unfortunately, I don't think there's realistically any "safe" values for varchar columns, and timestamps can also pose problems


texts: Operating multiple columns of one pandas DataFrame using data from another

texts:
I have a DataFrame of data from a survey that was repeated over several years, asking people about their income and how much money they had in savings. For simplicity, let's pretend it looks like this:

In [1]: nominal.head()
Out[1]:
  year1   ... year11  income1 ... income11    savings1 ... savings11
0 1992    ... NaN     600     ... NaN         100      ... NaN
1 1992    ... 2012    0       ... 100         0        ... 1000
2 1993    ... 2013    155000  ... 211000      490500   ... 60000
3 1993    ... 2013    155000  ... 211000      490500   ... 60000
4 1994    ... 2014    7000    ... 1000        90200    ... 100000

I also have a DataFrame that includes the annual rates of inflation.

In [2]: annual_inflation.head()
Out[2]:
    period    value   ratio to 2014
year
1992  M13 140.300 1.687356
1993  M13 144.500 1.638311
1994  M13 148.200 1.597409
1995  M13 152.400 1.553386

So my goal is to correct all of the income and savings columns for inflation, using the year that each survey was conducted. Therefore generating a DataFrame of the same dimensions as nominal, but with corrected values. (Rounded floats for clarity).

In [*]: real.head(2)
Out[*]:
  year1   ... year11  income1 ... income11    savings1 ... savings11
0 1992    ... NaN     1012.41 ... NaN         168.74   ... NaN
1 1992    ... 2012    0       ... 103.11      0        ... 1031.10

I am able to do this with the following code, but with nested for-loops and a conditional, it is exceptionally slow. Is there a better way? I feel like a .groupby() and/or .apply() should work, but I can't figure it out.

real = nominal.copy()
study_waves = range(11)
years = ['year1', 'year2' ... 'year11']
incomes = ['income1', 'income2' ... 'income11']
savings = ['savings1', 'savings2' ... 'savings11']

for wave in study_waves:
    for row in xrange(len(nominal)):
        year = nominal.loc[row, years[wave]]
        if 1992 <= year <= 2014: # sometimes year is NaN
            old_income = nominal.loc[row, incomes[wave]]
            old_savings = nominal.loc[row, savings[wave]]
            adjustment = annual_inflation.loc[int(year), 'ratio to 2014']
            new_income = old_income * adjustment
            new_savings = old_savings * adjustment
            real.loc[row, incomes[wave]] = new_income
            real.loc[row, savings[wave]] = new_savings


texts:
This is a small socket library I made to avoid complicated C boilerplate code and several #includes for connecting sockets, bind, listening etc.

Please note that socket_create() does not support bind to specific IP addresses and that the IP parameter is ignored.

The only C++11 feature I am using is constexpr. Even though it is C++11, I decided not to wrap everything in a class, but to work with standard int.

In the future, I might add Unix domain socket in a way similar to  socket_create() and / or SSL support, but at the moment I do not need those.

sockets.h

#ifndef NET_SOCKETS_H_
#define NET_SOCKETS_H_

#include <cstdint>

namespace net{

constexpr int SOCKET_NONBLOCK   = 0x01;
constexpr int SOCKET_TCPNODELAY = 0x02;

// ===========================

constexpr int SOCKET_DEFAULTOPT = SOCKET_NONBLOCK & SOCKET_TCPNODELAY;

// ===========================

int socket_create(const char *ip, uint16_t port, uint16_t backlog = 0, int options = SOCKET_DEFAULTOPT) noexcept;

bool socket_makeNonBlocking(int fd) noexcept;
bool socket_makeTCPNoDelay(int fd) noexcept;

int socket_accept(int fd) noexcept;

void socket_close(int fd) noexcept;

bool socket_check_eagain() noexcept;

}

#endif

sockets.cc

#include "sockets.h"

#include <sys/socket.h>     // EAGAIN
#include <arpa/inet.h>      // AF_INET
#include <netinet/tcp.h>    // TCP_NODELAY
#include <fcntl.h>      // fcntl

#include <unistd.h>     // close

#include <errno.h>      // errno

namespace net{

bool socket_check_eagain() noexcept{
    return errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK;
}

bool socket_makeNonBlocking(int const fd) noexcept{
    if (fd >= 0)
        return fcntl(fd, F_SETFL, O_NONBLOCK) >= 0;

    return false;
}

bool socket_makeTCPNoDelay(int const fd) noexcept{
    int const opt = 1;
    return (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, & opt, sizeof opt) >= 0);
}

void socket_close(int const fd) noexcept{
    if (fd >= 0)
        ::close(fd);
}

int socket_accept(int const fd) noexcept{
    if (fd >= 0)
        return ::accept(fd, NULL, NULL);

    return -1;
}

int socket_create(const char *ip, uint16_t const port, uint16_t const backlog, int const options) noexcept{
    int fd = socket(AF_INET , SOCK_STREAM , 0);

    if(fd < 0)
        return -1;

    int const opt = 1;
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, & opt, sizeof opt) < 0){
        ::close(fd);
        return -2;
    }

    if (options & SOCKET_NONBLOCK)
    if (! socket_makeNonBlocking(fd) ){
        ::close(fd);
        return -3;
    }

    if (options & SOCKET_TCPNODELAY)
    if (! socket_makeTCPNoDelay(fd) ){
        ::close(fd);
        return -4;
    }

    struct sockaddr_in address;

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(port);

    if (bind(fd, (struct sockaddr *) & address, sizeof address) < 0){
        ::close(fd);
        return -5;
    }

    if (listen(fd, backlog ? backlog : SOMAXCONN) < 0){
        ::close(fd);
        return -6;
    }

    return fd;
}

} // namespace


texts:
Is there an easier way of importing data into an Excel array or other data structure? I've tried researching collections but I have found the documentation hard to comprehend.

MSDN

The code I have opens a select file and searches for the column header and then loops through each row storing the data according to header and row variables. I've done this method for many macros in the past but now I am dealing with many many columns and I'm looking for a more advanced way.

Sub Import_NAVRec()

MyPath = Range("b2")                                'Defines cell that contains path to source file
Workbooks.Open (MyPath)                             'Opens file
Set tempbook = ActiveWorkbook                       'Names workbook
LR = Range("A65000").End(xlUp).Row                  'finds last row in sourcefile

ReDim aNavRec(1 To LR, 1 To 4)                      'Defines NAV Rec array
nRow = 0

 cName = "Accounting Basis"
 CA = Cells.Find(What:=UCase(cName), After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Column
 cName = "Accounting Date"
 cB = Cells.Find(What:=UCase(cName), After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Column
 cName = "Asset Currency"
 cC = Cells.Find(What:=UCase(cName), After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Column

     For r = 2 To LR
        'If Cells(r, cB) = "Trading Gain Loss" Then
         nRow = nRow + 1
         aNavRec(nRow, 1) = Cells(r, CA) 'Fund Number
         aNavRec(nRow, 2) = Cells(r, cB) 'Ledger
         aNavRec(nRow, 3) = Cells(r, cC) 'Balance change
        'End If

     Next r

tempbook.Close
End Sub

Sub Print_output()

Sheets("Output").Select
Set Destination = Range("a2")
Destination.Resize(UBound(aNavRec, 1) + 1, UBound(aNavRec, 2)).Value = aNavRec

End Sub


texts:
Small project i made to practice my c++, im a beginner and want to know all about optimizing code.
Enemy starts off with 10 HP and we can damage them for 1 HP by pressing F1,
If their HP is below their max they regenerate 1 point each second.
#include <time.h>
#include <Windows.h>
#include <iostream>
using namespace std;

int main()
{
    int maxHP = 10;
    int enemyHp = maxHP;
    cout << "Enemy HP: " << enemyHp << '\n';
    while (enemyHp > 0)
    {
        if (GetAsyncKeyState(VK_F1) & 1)
        {
            enemyHp--;
            system("CLS");
            cout << enemyHp << '\n';
        }
        static int sec = time(NULL);
        int secNew = time(NULL);
        int* secPtr = &sec;

        if (sec != secNew)
        {
            if (enemyHp < maxHP)
            {
                enemyHp++;
                system("CLS");
                cout << enemyHp << '\n';
            }
            *secPtr = secNew;
        }

        if (enemyHp == 0)
        {
            system("CLS");
            cout << "Enemy has died.\n";
        }
    }
    return 0;
}
```