texts:
This is a Leetcode problem -

  Given \$N\$ axis-aligned rectangles where \$N\$ \$>\$ 0, determine if
  they all together form an exact cover of a rectangular region.

  Each rectangle is represented as a bottom-left point and a top-right
  point. For example, a unit square is represented as [1, 1, 2, 2].
  (coordinate of the bottom-left point is (1, 1) and the top-right
  point is (2, 2)).

  Example 1 -

rectangles = [
  [1, 1, 3, 3],
  [3, 1, 4, 2],
  [3, 2, 4, 4],
  [1, 3, 2, 4],
  [2, 3, 3, 4]
]

# Explanation - Return True. All 5 rectangles together form an exact cover of a rectangular region.

  Example 2 -

rectangles = [
  [1, 1, 2, 3],
  [1, 3, 2, 4],
  [3, 1, 4, 2],
  [3, 2, 4, 4]
]

# Explanation - Return False. Because there is a gap between the two rectangular regions.

  Example 3 -

rectangles = [
  [1, 1, 3, 3],
  [3, 1, 4, 2],
  [1, 3, 2, 4],
  [3, 2, 4, 4]
]

# Explanation - Return False. Because there is a gap in the top center.

  Example 4 -

rectangles = [
  [1, 1, 3, 3],
  [3, 1, 4, 2],
  [1, 3, 2, 4],
  [2, 2, 4, 4]
]

# Explanation - Return False. Because two of the rectangles overlap with each other.

Here is my solution to this challenge -

def is_rectangle_cover(rectangles):

    if len(rectangles) == 0 or len(rectangles[0]) == 0:
        return False
    x1 = float("inf")
    y1 = float("inf")
    x2 = 0
    y2 = 0
    rect = set()
    area = 0
    for points in rectangles:
        x1 = min(points[0], x1)
        y1 = min(points[1], y1)
        x2 = max(points[2], x2)
        y2 = max(points[3], y2)
        area += (points[3] - points[1]) * (points[2] - points[0])
        rect.remove((points[0], points[3])) if (points[0], points[3]) in rect else rect.add((points[0], points[3]))
        rect.remove((points[0], points[1])) if (points[0], points[1]) in rect else rect.add((points[0], points[1]))
        rect.remove((points[2], points[3])) if (points[2], points[3]) in rect else rect.add((points[2], points[3]))
        rect.remove((points[2], points[1])) if (points[2], points[1]) in rect else rect.add((points[2], points[1]))
    if (x1, y2) not in rect or (x2, y1) not in rect or (x1, y1) not in rect or (x2, y2) not in rect or len(rect) != 4:
        return False
    return area == (y2 - y1) * (x2 - x1)

Here are the times taken for each example output -

Example 1 -

# %timeit is_rectangle_cover([[1, 1, 3, 3], [3, 1, 4, 2], [3, 2, 4, 4], [1, 3, 2, 4], [2, 3, 3, 4]])

14.9 µs ± 117 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Example 2 -

# %timeit is_rectangle_cover([[1, 1, 2, 3], [1, 3, 2, 4], [3, 1, 4, 2],[3, 2, 4, 4]])

12.5 µs ± 494 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Example 3 -

# %timeit is_rectangle_cover([[1, 1, 3, 3], [3, 1, 4, 2], [1, 3, 2, 4], [3, 2, 4, 4]])

12.4 µs ± 195 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Example 4 -

# %timeit is_rectangle_cover([[1, 1, 3, 3], [3, 1, 4, 2], [1, 3, 2, 4], [2, 2, 4, 4]])

12 µs ± 159 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Here is my Leetcode result for 46 test cases -

Therefore, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts: Keyboard handler to move a shape in response to arrow keys

texts:
I finished Codeacademy and I'm looking to practice and get better at JavaScript. Is this coded correctly or should I have made a function for it somehow?  The purpose of this code is to move a square around the page with arrow keys or buttons.

I have the entire script hosted here.

I mostly want to "Simplify this chain of if statements"  but also the post  about using a map instead of the if statements is something I needed to know.

function anim(e){
    if((e.keyCode === 37)||(e === 37)){
      y = shipLeft;
      shipLeft -= 11;
      y -= 11;
      y.toString();
      y = y + 'px';
      ship.style.left = y;
      changeColor();
    return shipLeft
}
    else if ((e.keyCode === 39) || (e === 39)){
      y = shipLeft;
      shipLeft += 11;
      y += 11;
      y.toString();
      y = y + 'px';
      ship.style.left = y;
      changeColor();
    return shipLeft
    }
    else if ((e.keyCode === 40) || (e === 40)){
      y = shipTop;
      y += 11;
      shipTop += 11;
      y.toString();
      y = y + 'px';
      ship.style.top = y;
      changeColor();
    return shipTop;
    }
    else if ((e.keyCode === 38) || ( e === 38)){
      y = shipTop;
      y -= 11;
      shipTop -= 11;
      y.toString();
      y = y + 'px';
      ship.style.top = y;
      changeColor();
    return shipTop;
    }
 }


texts:
It feels like pagination is one of the most discussed questions on the web, which always ends up with some quick and dirty hacks on how to paginate. I want to paginate a large result set from an SQL query on a website where I use Spring-JDBC for querying and Displaytag for display. I thought about it for a while and eventually came up with implementing a ResultSetExtractor like this:

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.displaytag.pagination.PaginatedList;
import org.displaytag.properties.SortOrderEnum;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.ResultSetExtractor;

public class PaginatingResultMapExtractor implements
        ResultSetExtractor<PaginatedList>
{
    private final int page;
    private final int pageSize;
    private final String sortColumn;
    private final SortOrderEnum sortDirection;

    public PaginatingResultMapExtractor(int page, int pageSize,
            String sortColumn, SortOrderEnum sortDirection)
    {
        super();
        this.page = page;
        this.pageSize = pageSize;
        this.sortColumn = sortColumn;
        this.sortDirection = sortDirection;
    }

    @Override
    public PaginatedList extractData(ResultSet rs) throws SQLException,
            DataAccessException
    {
        final ColumnMapRowMapper mapper = new ColumnMapRowMapper();
        final List<Object> result = new ArrayList<Object>(
                pageSize);
        int i;
        for (i = 0; rs.next(); ++i)
        {
            if (i > (page - 1) * pageSize
                    && i < page * pageSize)
                result.add(mapper.mapRow(rs, i));
        }
        return new PaginatedListImpl<Object>(result, i,
                pageSize, page, sortColumn, sortDirection);
    }
}

PaginatedListImpl is simply stores the values that I pass in the constructor and makes them available with getter-methods, fulfilling the requirements of the PaginatedList interface by displaytag.

I can use this by simply calling:

jdbcTemplate.query("select ... from ...", new PaginatingResultMapExtractor(page, pageSize, sortColumn, sortDirection));

At least this solution is very easy to use. But after all I have to iterate the whole result set. Can this code be improved?


texts: From a string of 3 numbers to 3 integers

texts:
I'm solving some puzzles to learn Rust. A problem I faced is to turn a string of 3 integers into 3 integers. I succeeded with the following example:

fn main() {
    let mut it = "   455   123   42  ".split_whitespace();
    let (a, b, c) = match (it.next(), it.next(), it.next()) {
        (Some(a), Some(b), Some(c)) => {
            (a.parse::<i32>().unwrap(),
             b.parse::<i32>().unwrap(),
             c.parse::<i32>().unwrap())
        }
        _ => panic!("Oops"),
    };

    println!("{:?}", (a, b, c));
}

However, this code appears to have bad quality:

bad error handling
does not scale (works only for 3) with N integers.

How can I improve this code?


texts: Secure CURL to & handle response from Payment Gateway

texts:
I'm using a payment gateway and am trying to implement the post and response handling with CURL so that it all happens on one page.

The following is tested and works but I want to double check it's secure. I'm not storing the card details but I'm essentially posting them to myself (via AJAX) and then curling that through to the gateway. I can't AJAX post it directly to the gateway because of cross domain restrictions.

So, this all happens in https://mysite.com/payment.php:

HTML

<form method="post" action="https://mysite.com/payment.php">
    <input type="hidden" name="Amount" value="1.00">

    <!-- fingerprint is a hash of my gateway passwords and fields on this form -->
    <input type="hidden" name="Gateway_Fingerprint" value="<?php echo $fingerprint ?>">
    <input type="hidden" name="Gateway_ReturnURL" value="https://mysite.com/payment.php">
    <input type="hidden" name="Card_Number" value="">
</form>

PHP

// when payment form is submitted
if(isset($_POST['Card_Number'])){

   // CURL the data to payment gateway
   foreach($data as $key => $value){
       $fields .= $key . '=' . $value . '&';
   }

   rtrim($fields, '&');

   $post = curl_init();

   curl_setopt($post, CURLOPT_VERBOSE, true);
   curl_setopt($post, CURLOPT_URL, 'https://gatewayurlhere');
   curl_setopt($post, CURLOPT_POST, count($data));
   curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
   curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);

   $result = curl_exec($post);

   // output result from gateway as JSON
   header('Content-Type: application/json');

   echo $result;

   curl_close($post);

   exit();
}

// result returned from gateway, this will be the CURL result data
if(isset($_POST['restext']))
{
   echo json_encode($_POST);
   exit();
}


texts:
In the process of trying to build a serializable data structure, I found myself building large strings, which gets very slow because VBA copies a string every time concatenation is performed.

To alleviate this, referring to Dynamic Array and Java's StringBuilder interface, I cobbled together a unicode clsStringBuilder class.

This isn't a very big chunk of code, but I'd be interested in any advice about edge cases that I maybe haven't considered, unexpected copying behavior that VBA might be performing "behind my back" which I could avoid, or corrections to coding style (or lack thereof).

Option Compare Database
Option Explicit

'******
'* v2 *
'******

Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByVal dst As Long, ByVal src As Long, ByVal Length As Long)

Private Const DEFAULT_CAPACITY As Long = &H10
Private m_currLen As Long
Private m_stringBuffer() As Byte

Private Sub Class_Initialize()
    ReDim m_stringBuffer(0 To (DEFAULT_CAPACITY * 2) - 1) 'Each unicode character is 2 bytes
End Sub

Public Function Append(strString As String) As clsStringBuilder
On Error GoTo derp

    If m_currLen + LenB(strString) < UBound(m_stringBuffer) Then
        CopyMemory VarPtr(m_stringBuffer(m_currLen)), StrPtr(strString), LenB(strString)
    Else
        If m_currLen + LenB(strString) < UBound(m_stringBuffer) * 2 Then
            Expand
        Else
            Expand m_currLen + LenB(strString)
        End If
        CopyMemory VarPtr(m_stringBuffer(m_currLen)), StrPtr(strString), LenB(strString)
    End If
    m_currLen = m_currLen + LenB(strString)
    Set Append = Me
    Exit Function

derp:
    Stop
    Resume
End Function

Public Property Get Length() As Long
    Length = m_currLen / 2
End Property

Public Property Get Capacity() As Long
    Capacity = UBound(m_stringBuffer)
End Property

Private Sub Expand(Optional newSize As Long = 0)
    If newSize <> 0 Then
        ReDim Preserve m_stringBuffer(0 To newSize - 1)
    Else
        ReDim Preserve m_stringBuffer(0 To (UBound(m_stringBuffer) * 2) + 1)
    End If
End Sub

Public Function toString() As String
    toString = Mid(m_stringBuffer, 1, m_currLen / 2)
End Function

Here is a test:

Public Sub Main()
    Dim sb As clsStringBuilder
    Set sb = New clsStringBuilder
    Dim strString As String
    Dim i As Long
    Dim StartTime As Double

    'VBA String
    StartTime = MicroTimer()
    For i = 0 To 100000
        strString = strString + "Hello World;"
    Next
    Debug.Print "The VBA String took: " & Round(MicroTimer - StartTime, 3) & " seconds"

    'StringBuilder
    StartTime = MicroTimer()
    For i = 0 To 100000
        sb.Append "Hello World;"
    Next
    Debug.Print "The Stringbuilder took: " & Round(MicroTimer - StartTime, 3) & " seconds"

    'Are the strings the same?
    Debug.Print StrComp(strString, sb.toString, vbBinaryCompare)
End Sub

Here is Microsoft's MicroTimer function, which can be found here:

Private Declare Function getFrequency Lib "kernel32" _
Alias "QueryPerformanceFrequency" (cyFrequency As Currency) As Long
Private Declare Function getTickCount Lib "kernel32" _
Alias "QueryPerformanceCounter" (cyTickCount As Currency) As Long
Function MicroTimer() As Double
'

' Returns seconds.
    Dim cyTicks1 As Currency
    Static cyFrequency As Currency
    '
    MicroTimer = 0

' Get frequency.
    If cyFrequency = 0 Then getFrequency cyFrequency

' Get ticks.
    getTickCount cyTicks1

' Seconds
    If cyFrequency Then MicroTimer = cyTicks1 / cyFrequency
End Function


texts: Code to print even and Odd number using two threads

texts:
Below I am giving you my code which I wrote to print even number using even thread and odd number using odd thread sequentially.

Could anyone please validate my code whether it is correct way of doing it or not? I am getting correct result, but I just want to make sure whether I am doing it in correct way or not.

public class PrintNumberUsingThread {

    public static void main(String[] args) {
        PrintNumberUsingThread example = new PrintNumberUsingThread();
        PNThread pnThread = example.new PNThread(10);
        new Thread(pnThread).start();
        new Thread(pnThread).start();
    }
    class PNThread implements Runnable {

        private int number = 0;
        private int maxNumber;
        public PNThread(int maxNumber) {
            this.maxNumber = maxNumber;
        }
        @Override
        public void run() {

            while (number <= maxNumber) {
                synchronized (this) {

                    String threadName = Thread.currentThread().getName();
                    if (number <= maxNumber) {

                        boolean even = threadName.contains("0") && number % 2 == 0;
                        boolean odd = threadName.contains("1") && number % 2 != 0;
                        if (even || odd) {

                            System.out.println(threadName + "-" + number++);
                            this.notifyAll();
                        } else {
                            try {
                                this.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}


texts:
I'm pretty new to Ruby, and working in the IT security field, I thought to make something useful to my work while I learn the language (even though I'm reinventing the wheel).

The script is working fine and doing what I wanted it to, first checking connectivity thanks to ICMP and then bruteforcing through a wordlist to see if the SSH connection is accepted or not, and move on until it is (or the end of the file).

The usage is as follows:

./ssh_brute.rb IP_ADDRESS USER PATH_TO_WORDLIST

My first concern is that I like learning a language properly and writing in its particular style, not having code that "just works". Also the code seems pretty slow to similar programs I have used before, and I would like to know if it had anything with the way it was written or if Ruby is just slower as C for example.

require 'net/ssh'
require 'net/ping'

#Checking arguments and setting them into variables
if ARGV.length != 3
    puts "Please RTFM !"
    exit
end

target = ARGV[0].to_s
user = ARGV[1].to_s
wordlist_file=ARGV[2].to_s

#Checking network connectivity is good enough (more than 3/5 pings)
icmp = Net::Ping::ICMP.new(target)
network = 0
(1..5).each do
    if icmp.ping
        network += 1
    end
end

if network >= 3
    puts "Network connectivity with the target is OK !"
else
    puts "Network connectivity with the target seems poor, please check it then try again ! "
    exit
end

#Counting lines to give progression + opening wordlist file
File.foreach(wordlist_file) {}
total_lines = $.
wordlist = open(wordlist_file, "r")
linecounter = 0

#Main part, each pass tries to connect to the target using the supplied user + the current line of the list as a password. If it succeeds it exits the program
while pass = wordlist.gets.chomp()
    linecounter += 1
    print "\rTrying password #{pass}, progress : #{linecounter}/#{total_lines} !"
    begin
        result1 = Net::SSH.start(target,
                                user,
                                :password => pass,
                                :auth_methods => ["password"],
                                :number_of_password_prompts => 0
                                )
    rescue Net::SSH::AuthenticationFailed => auth
    else
        puts "\nThe password is #{pass}"
        exit
    end
end

puts "\nThe password wasn't found in the list !"


texts:
I am trying to open two CSV files, one for reading and one for writing. The script should continue only if both files were successfully opened. My code seems to accomplish that but it seems like it could be improved further.

My questions are:

Should I consider a different approach?
My code feels a bit bloated inside the try statement (imagine 100 additional lines of code). Is there a "cleaner" approach?
If the files were opened successfully, but a different error occurs later on that is not an IOError, this code will not catch it, correct?

Code:

input_file = 'in_file.csv'
output_file = 'out_file.csv'

def main():

    try:
        with open(input_file, 'rb') as in_csv, open(output_file , 'wb') as out_csv:
            writer = csv.writer(out_csv, delimiter='\t')
            reader = csv.reader(in_csv, delimiter='\t')
            for row in reader:
                # many lines of code...
    except IOError as e:
        print "Error: cannot open file"
        if e.errno == errno.EACCES:
            print "\tPermission denied."
            print "\tError message: {0}".format(e)
            sys.exit()
        # Not a permission error.
        print "\tDoes file exist?"
        print "\tError message: {0}".format(e)
        sys.exit()

if __name__ == '__main__':
    main()


texts: HNews "ask section" page scraping Python script

texts:
Here is a small script I wrote to get the HNews ask section and display them without using a web browser.  I'm just looking for feedback on how to improve my style/coding logic/overall code.

#!/usr/bin/python

'''This script gets the headlines from hacker news ask section'''

import urllib2
import HTMLParser
import re

class HNParser(HTMLParser.HTMLParser):
def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.data=[]
    self.recording=0

def handle_starttag(self, tag, attribute):
    if tag!='a':
        return
    elif self.recording:
        self.recording +=1
        return
    for name, value in attribute:
        if name=='href' and value[0]=='i':
            break
    else:
        return
    self.recording=1

def handle_endtag(self, tag):
    if tag=='a' and self.recording:
        self.recording-=1

def handle_data(self, data):
    if self.recording:
        self.data.append(data)

HOST='http://news.ycombinator.com/ask'
parser=HNParser()
f=urllib2.urlopen(HOST)
rawHTML=f.read()
parser.feed(rawHTML)
i=0
for items in parser.data:
    try:
        print parser.data[2*i]
        i+=1
    except IndexError:
        break
 parser.close()


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

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

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

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

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

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

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

The HTML is:

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


texts: Longest Increasing Sub-Sequence using Dynamic Programming in Python

texts:
I wrote the following function to find the longest increasing sub-sequence in an array (tuple, it doesn't work for a list since a list is mutable and it stores the results in a dictionary.). It uses Top Down dynamic programming approach.

def LIS(seq, memo={}):
    if len(seq) == 1:
        return seq

    elif seq in memo:
        return memo[seq]

    else:
        longest = (seq[-1],)
        for index in range(1, len(seq)):
            till_index = LIS(seq[:index], memo)
            till_index += (seq[-1],) if till_index[-1] < seq[-1] else ()
            longest = max(longest, till_index, key=len)
        memo[seq] = longest
        return memo[seq]

It works correctly for all the test cases I've tried. Could you please suggest some changes which can help me reduce its time and memory consumption?


texts: Optimised solution for implementing a queue with two stacks

texts:
I need help to optimise the following code in C++, which implements a queue with two stacks. Unfortunately, it's not passing some of the test cases @ the following link: https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks The (hidden) test cases yield "Terminated due to timeout 2s". How can I make my implementation faster?

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;

class MyQueue {
    public:
        stack<int> stack_newest_on_top, stack_oldest_on_top;
        void push(int x) {

            /* Check if the stack_oldest_on_top is empty..
                if it is not empty, push all the elements onto
                stack_newest_on_top */
            while(true != stack_oldest_on_top.empty()) {
                stack_newest_on_top.push(stack_oldest_on_top.top());
                stack_oldest_on_top.pop();
            }
            /* When you want to push a value on to the que,
                it should be stack_newest_on_top*/
            stack_newest_on_top.push(x);
        }

        void pop() {
            /* Check if the stack_newest_on_top is empty.. */
            while(true != stack_newest_on_top.empty()) {
                /* Access the top of the newest stack */
                stack_oldest_on_top.push(stack_newest_on_top.top());
                /* After acessing the top, just pop it off */
                stack_newest_on_top.pop();
            }
            if (true != stack_oldest_on_top.empty()) {
                /* Pop the elem at the top of oldest stack. */
                stack_oldest_on_top.pop();
            }
        }

        int front() {
            int rt_value = 0;
            while(true != stack_newest_on_top.empty()) {
                stack_oldest_on_top.push(stack_newest_on_top.top());
                /* After acessing the top, just pop it off */
                stack_newest_on_top.pop();
            }
            if (true != stack_oldest_on_top.empty()) {
                /* Get the top element of the stack */
                rt_value = stack_oldest_on_top.top();
            }
            return rt_value;
        }
};

int main() {
    MyQueue q1;
    int q, type, x;
    cin >> q;

    for(int i = 0; i < q; i++) {
        cin >> type;
        if(type == 1) {
            cin >> x;
            q1.push(x);
        }
        else if(type == 2) {
            q1.pop();
        }
        else cout << q1.front() << endl;
    }
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    return 0;
}


texts: Basic PHP MVC setup for form submissions

texts:
I'd like your thoughts on this basic implementation of MVC. The view outputs a form, and when the page is loaded, the controller checks for a form submission and then updates the model accordingly. Finally, the view outputs the form again, grabbing the new values from the model.

One problem with this is that if the user refreshes the page, a submission will still happen because the $_POST['submitted'] flag is still sent. Ideally, I'd like to avoid this - is there a suggestion for using AJAX to make this work?

<?php

class EntryModel {
        public $date;
        public $amount;

        public function update_date($date) {
                $this->date = $date;
        }

        public function update_amount($amount) {
                $this->amount = $amount;
        }
}

class EntryController {
        private $model;

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

        public function get_submission() {
                if (!isset($_POST['submitted']))
                        return;

                foreach ($_POST as $g => $k)
                {
                        if ($g == 'form_date')
                                $this->model->update_date($k);
                        elseif ($g == 'form_amount')
                                $this->model->update_amount($k);
                }

                echo ("Sucessful submission");
        }

}

class EntryView {
        private $model;
        private $controller;

        public function __construct(EntryController $controller, EntryModel $model) {
                $this->controller = $controller;
                $this->model = $model;
        }

        public function output() {
                $form_output =
                '<form action="index.php" method="POST">

Date: <input type="date" name="form_date" value="' . $this->model->date . '">

Amount: <input type="number" name="form_amount" value="' . $this->model->amount . '">

                        <input type="hidden" name="submitted" value="yes">
                        <input type="submit">
                </form>';

                return $form_output;
        }
}

$model = new EntryModel();
$controller = new EntryController($model);
$view = new EntryView($controller, $model);

$controller->get_submission();

echo $view->output();

?>


texts:
I'm working on a JavaScript plugin that makes font-sizes flexible (for a responsive layout). The code works well so far, but I'm sure that it's capable of improvement (especially if you look at the global variable).

(function () {
    var extend = function (obj, ext) {
        for (var key in ext) {
            if (ext.hasOwnProperty(key)) {
                obj[key] = ext[key];
            }
        }
        return obj;
    };

    window.txt = function (el, k, c) {
        var s = extend({
            n: Number.NEGATIVE_INFINITY,
            x: Number.POSITIVE_INFINITY
        }, c);

        var fit = function () {
            var a = k;

            var i = function () {
                el.style.fontSize = Math.max(Math.min(el.clientWidth / a, parseFloat(s.x)), parseFloat(s.n)) + "px";
            };
            i();
            window.addEventListener("resize", i);
            window.addEventListener("orientationchange", i);
        };

        if (el.length) {
            for (var i = 0; i < el.length; i++) {
                fit(el[i]);
            }
        } else {
            fit(el);
        }

        return el;
    };
})();

DEMO

Meaning of the used variables:

n = minFontSize
x = maxFontSize
s = settings
c = config
el = element
i → running the function
a or k = fontRatio/compressor

window.txt(document.getElementById("title"), 10);

↑ executes the JavaScript Plugin on an element.


texts:
Here is the solution I've written for Hacker Rank Candies challenge.
It uses dynamic programming (memoization in a boxed array).
I'm interested on what could be done to improve this code in term of style and performance (although it passes all the testcases of the challenge)
For example, I wonder if the bunch of guards I used could be made prettier

import System.IO
import Data.Array

main = do
    contents <- getContents
    print $ runTest contents

runTest :: String -> Int
runTest = sum . candies . map read . tail . lines

candies :: [Int] -> [Int]
candies rs = elems candies where
    go i
        | n ==1 = 1
        | i == 1 = if (ri > riplus) then candies ! (2) + 1 else 1
        | i == n = if (ri > riminus) then candies ! (n - 1) + 1 else 1
        | ri > riminus  && ri > riplus = max (candies! (i-1)) (candies! (i+1)) + 1
        | ri > riminus = candies! (i-1) + 1
        | ri > riplus = candies! (i+1) + 1
        | otherwise = 1
        where
            ri = ratings!i
            riplus = ratings!(i+1)
            riminus = ratings!(i-1)
    ratings = listArray (1,n) rs
    candies = listArray (1,n) [go i | i <- [1..n]]
    n = length rs


texts:
I am working through the online materials for CIS 194, a upenn haskell class (not taking the class). This exercise is to parse an error log, and it gives a few function signatures to implement, ending with the very last one whatWentWrong. Please help me make the code more idiomatic, particularly whatWentWrong. My haskell level is: understood LYAH but have not written much code.

{-# OPTIONS_GHC -Wall #-}
module LogAnalysis where

import Log -- https://github.com/dustingetz/sandbox/tree/master/cis194/hw2

parseMessage :: String -> LogMessage
parseMessage s = case words s of
  -- I 5053 pci_id: con ing!
  ("I":t:msg) -> LogMessage Info (read t) (unwords msg)

  -- W 3654 e8] PGTT ASF!
  ("W":t:msg) -> LogMessage Warning (read t) (unwords msg)

  -- E 47 1034 'What a pity it
  ("E":sev:t:msg) -> LogMessage (Error $ read sev) (read t) (unwords msg)

  _ -> Unknown s

parse :: String -> [LogMessage]
parse s = map parseMessage $ lines s

insert :: LogMessage -> MessageTree -> MessageTree
insert (Unknown _) node = node
insert m Leaf = Node Leaf m Leaf
insert m@(LogMessage _ t _) (Node l' m'@(LogMessage _ t' _) r')
  | t <= t' = Node (insert m l') m' r'
  | t > t' = Node l' m' (insert m r')

build :: [LogMessage] -> MessageTree
build ms = foldl (flip insert) Leaf ms

inOrder :: MessageTree -> [LogMessage]
inOrder (Node l m r) = inOrder l ++ [m] ++ inOrder r
inOrder Leaf = []

--fmap ((take 10) . inOrder . build) $ testParse parse 100 "error.log"

whatWentWrong :: [LogMessage] -> [String]
whatWentWrong ms = map (\(LogMessage _ _ s) -> s) $
                   filter (\(LogMessage msgType _ _) ->
                            case msgType of
                             Error sev -> sev >= 50
                             _ -> False) $
                   inOrder $ build ms


texts:
Here is my solution in Haskell for the Euler problem #101. It relies on building a specific base of polynomes given the values we want to fit (memories of my linear algebra courses from a long time ago). The algorithm is quite fast but as a new Haskell programmer, I'd like your opinion on what could be done to improve this code, be it either Haskell conventions, style or optimization.

module Polynome.Optimal where

-- given a list, returns a polynome of degree length xs which is zero on all element of the list
getPolynome :: [Int] -> Int -> Int
getPolynome = foldr f (const 1) where
    f x acc n = (n-x) * acc n

getLists :: [Int] -> [[Int]]
getLists xs = zipWith (const . ($ xs)) (map remove [0..]) xs

remove :: Int -> [Int] -> [Int]
remove n = go 0
    where go _ [] = []
          go i (y:ys) | i == n = ys
                       | otherwise = y: go (i+1) ys

getBase :: [Int] -> [Int -> Int]
getBase xs = map getPolynome $ getLists xs

scalePolynome :: Int -> Int -> (Int -> Int) -> Int -> Int
scalePolynome x y p t = (p t * y) `div` p x

getPolyFit :: [(Int,Int)] -> Int -> Int
getPolyFit vs = foldr f (const 0) ls where
    (xs, _) = unzip vs
    bs = getBase xs
    ls = zipWith (\ (x,y) b -> scalePolynome x y b) vs bs
    f b acc t = b t + acc t

exValues :: [(Int,Int)]
exValues = [(i, u i) | i <- [1..], let u t = 1- t + t^2 - t^3 + t^4 - t^5 + t^6 - t^7 + t^8 - t^9 +t^10]

getPartialFit :: Int -> [(Int,Int)] -> Int -> Int
getPartialFit n = getPolyFit . take n

getFit :: [(Int,Int)] -> (Int -> Int) -> Int
getFit vs p = snd (head (dropWhile predicate $ zip vs ps)) where
    ps = map (\(x, _) -> p x) vs
    predicate ((x, y), p) = p == y

-- result 10 exValues returns the solution to problem 101
result :: Int -> [(Int,Int)] -> Int
result n values = sum fits where
    bops = map (($ values) . getPartialFit) [1..n]
    fits = map (getFit values) bops


texts: Rotate a linked list to the right by k places

texts:
The task

  Given a linked list and a positive integer k, rotate the list to the
  right by k places.

  For example, given the linked list 7 -> 7 -> 3 -> 5 and k = 2, it
  should become 3 -> 5 -> 7 -> 7.

  Given the linked list 1 -> 2 -> 3 -> 4 -> 5 and k = 3, it should
  become 3 -> 4 -> 5 -> 1 -> 2.

My solution

class LinkedNode {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;
  }
}

const n4 = new LinkedNode(5);
const n3 = new LinkedNode(3, n4);
const n2 = new LinkedNode(7, n3);
const n1 = new LinkedNode(7, n2);

let n = n1;

const rotate = (l, k) => {
  let p = l;
  const first = l;
  let last;
  let res;
  let i = 0;
  while(p) {
    i++;
    if (!p.next) { last = p; }
    p = p.next;
  }
  const size = i;
  if (!(k % size)) { return l; }
  const aim = size - (k % size) - 1;
  p = l;
  i = 0;
  while (p) {
    if (i++ === aim) {
      res = p.next;
      p.next = null;
      last.next = first;
      return res;
    }
    p = p.next;
  }
};

n = rotate(n, 0);
while (n) {
  console.log(n.value);
  n = n.next;
}


texts:
I have a PL/SQL stored procedure which searches for a row in 3 different tables (not all columns are the same).

The logic goes as follows:

Search for the item in the first table
  If item was found
      select the details of it from the first table
  If item was not found
      search for the item in the second table
          If Item was found
              Select the details of it from the second table
          If item was not found
              Select the item from the third table (returning blank if it's not found here neither)

Here's the actual code (actual symbol names modified for security):

PROCEDURE GETREQUEST(REQUESTID IN NUMBER, request OUT pkg_request.refcur)
 IS
requestFound NUMBER := 0;
BEGIN

            -- Search for the request ID in the first table
            SELECT COUNT(REQ_ID) INTO requestFound FROM FIRSTTABLE
            WHERE FIRSTTABLE.REQ_ID = REQUESTID
            AND (REQ_STATUS = 'D' OR REQ_STATUS = 'A');

            IF(REQUESTFOUND > 0) THEN
                    -- Select the request details
                    OPEN REQUEST FOR
                    SELECT REQ_ID, REQ_TYPE_STATUS FROM FIRSTTABLE
                    WHERE FIRSTTABLE.REQ_ID = REQUESTID
                    AND (REQ_STATUS = 'D' OR REQ_STATUS = 'A');
            ELSE
                    -- Search for the request from the second table
                    SELECT COUNT(REQ_ID) INTO REQUESTFOUND FROM SECONDTABLE
                    WHERE SECONDTABLE.REQ_ID = REQUESTID;

                    IF(REQUESTFOUND > 0) THEN
                              -- Select the request details from second table
                              OPEN REQUEST FOR
                              SELECT REQ_TYPE, '-' AS REQ_TYPE_STATUS FROM SECONDTABLE
                              WHERE SECONDTABLE.REQ_ID = REQUESTID;
                      ELSE
                              -- Get the request from third table (will return as blank if nothing found)
                              OPEN REQUEST FOR
                              SELECT REQ_TYPE, '-' AS REQ_TYPE_STATUS  FROM THIRDTABLE
                              WHERE THIRDTABLE.REQ_ID = REQUESTID;
                      END IF;
            END IF;
END GET_REQUEST

My issues with this are as follows:

It's not very concise, with a lot of nesting.
It's not very efficient, since it needs to perform a count, then if it exists it selects the details. That's two operations. How can I modify it to have a single operation for each search?

Also, the REQ_TYPE_STATUS column doesn't exist in the second and third table, so as you can see I have just assigned the value '-' to the returned result, indicating a blank value. I'm not really sure if there's a better or more standard way of doing this.


texts: Testing class that transforms JSON into a spreadsheet

texts:
I am creating unit tests but the class uses objects that have long JSON. What can I do to improve the readability of this?

In tests, only insert those JSON really needed for the test. The class I tested is responsible in turn that JSON in a modified spreadsheet (xlsx) and it seems difficult to maintain the code.

@Test
public void testBuildSheet_validSheet_NoMedia() throws Exception {
    BasicDBObject specPlanilha = (BasicDBObject) JSON.parse("{\"spec_veiculo\" : \"BuscaDescontos\" , \"spec_canal\" : \"Homepage\" , \"spec_formato\" : \"SuperBanner\" , \"spec_linha-criativa\" :  null  , " +
            "\"spec_tamanho\" : \"728x90\" , \"spec_extensao\" : \"jpg/png\" , \"peca_peso\" : \"50kb\" , \"imagem_peso\" : \"50kb\" , " +
            "\"peca_flash\" : \"4 até 10\" , \"peca_clicktag\" : \"on (release) {\\n  getURL(_root.clickTAG, '_blank');\\n}\" , " +
            "\"peca_framerate\" : \"24fps\" , \"peca_tempo\" : \"30s\" , \"spec_observacoes\" :  null  , " +
            "\"peca_nome\" : \"Whirlpool_LinhaBranca_BuscaDescontos_Homepage_SuperBanner_-.jpg\" , \"extras\" : " +
            "{ \"linha\" : \"10\" , \"Rich Media\" : \"Não\" , \"Link Especificação\" : \"http://portal.agenciaclick.com.br/midiaSP/Midia/Lists/Tabela%20de%20Especificao%20e%20Formato%20de%20Peas/DispForm.aspx?ID=3405&Source=http%3A%2F%2Fportal%2Eagenciaclick%2Ecom%2Ebr%2FmidiaSP%2FMidia%2FLists%2FTabela%2520de%2520Especificao%2520e%2520Formato%2520de%2520Peas%2FSites%2Easpx\" ," +
            " \"Data Entrega Mídia\" :  null  , \"Data Disparo/Subida\" :  null }}");
    List<BasicDBObject> listSpec = new ArrayList<>();
    listSpec.add(specPlanilha);
    BasicDBObject specFields = (BasicDBObject) JSON.parse("{\"peca_nome\": \"Whirlpool_LinhaBranca_BuscaDescontos_Homepage_SuperBanner_-.jpg\",\n" +
            "      \"extras\": {\n" +
            "        \"linha\": \"10\",\n" +
            "        \"Rich Media\": \"Não\",\n" +
            "        \"Link Especificação\": \"http://portal.agenciaclick.com.br/midiaSP/Midia/Lists/Tabela%20de%20Especificao%20e%20Formato%20de%20Peas/DispForm.aspx?ID=3405&Source=http%3A%2F%2Fportal%2Eagenciaclick%2Ecom%2Ebr%2FmidiaSP%2FMidia%2FLists%2FTabela%2520de%2520Especificao%2520e%2520Formato%2520de%2520Peas%2FSites%2Easpx\",\n" +
            "        \"Data Entrega Mídia\": null,\n" +
            "        \"Data Disparo/Subida\": null\n" +
            "      }}");

    ValidacaoResultado myValidation = new ValidacaoResultado().setId("123")
            .setResultadoConsolidado("NO_MEDIA")
            .setResultado(new BasicDBObject())
            .setSpec(specFields);
    oknok.validacao.entities.Planilha planilha = new Planilha()
            .setPath(PlanilhaWorkbook.class.getClass().getResource("/planilhaWorkbook/T001.xlsx").getPath())
            .setNomeHash("noMediaTest.xlsx")
            .setSpec(listSpec);

    List<ValidacaoResultado> myList = new ArrayList<>();
    myList.add(myValidation);

    File actual = planilhaWorkbook.buildSheet(myList, planilha);
    SoftAssertions soft = new SoftAssertions();

    soft.assertThat(actual.getName()).isEqualTo(planilha.getNomeHash());
    soft.assertAll();
}


texts: Concatenate two containers, e.g. vector or strings

texts:
I'd like to create a function that can concatenate vectors or strings. It must

Keep correct order
Be optimal

This is the solution I came up with:

template<typename V>
V concatenate( V&& v )
{
  return v;
}

template<typename V1, typename V2, typename... Rest>
V1 concatenate( V1 v1, V2&& v2, Rest&&... rest)
{
  v1.insert( v1.end(), v2.begin(), v2.end() );
  return concatenate( std::move(v1), std::forward<Rest>(rest)... );
}

// usage:
std::vector<int> v1 = { 1, 2, 3 };
std::vector<int> v2 = { 4, 5, 6 };
std::vector<int> v3 = { 7, 8, 9 };
std::vector<int> v12 = concatenate( v1, v2 );
std::vector<int> v123 = concatenate( v1, v2, v3 );
std::vector<int> vm12 = concatenate( std::move(v1), v2 );
std::vector<int> vm23 = concatenate( v2, std::move(v3) );

Is my argument forwarding correct here? Is this the simplest solution?


texts: Calculating the circumference and area of a circle

texts:
This simple program uses Scanner to obtain a radius from the user, then calculates and outputs the circumference and area.

Questions:

Is it customary in Java to place a function call inside of a println(), or is it better to put the returned value into a separate variable and then display that?
Should I consider implementing input-validation for practice as this is a toy program?
Am I correct in making the calculation functions static?

import java.util.Scanner;
import java.lang.Math;

public class Circle {

    public static double getCircumference(double radius) {
        return 2 * Math.PI * radius;
    }

    public static double getArea(double radius) {
        return Math.PI * radius * radius;
    }

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

        double radius = sc.nextDouble();

        System.out.println("Circumference: ");
        System.out.println(getCircumference(radius));
        System.out.println("Area: ");
        System.out.println(getArea(radius));

        sc.close();
    }
}

Sample output:

5.5
Circumference:
34.55751918948772
Area:
95.03317777109123


texts: fetch() with status code checking and re-routing

texts:
In examples for fetch() I don't see many example for status code checking.

(1) I'm expecting to catch 403 unauthorised responses and push the login path to React router to render the login page. Haven't seen this elsewhere, but seems to work alright.

(2) Is it alright to nest the second .then the way I did or it should it somehow be outside the first .then?

loadData() {
    fetch(new UrlAssembler().template(this.props.endpoint).query(queryObject.get()).toString())
        .then(response => {
            if (response.status !== 200) {
                this.props.history.push( APP_LOGIN_PATH )
            } else {
                response.json().then(data =>
                    this.setState({
                        data: data,
                        loaded: true,
                        isModalActive: false,
                        selectedElement: null,
                        selectedId: null,
                    }))
                }
        })
}


texts: Request for help to tidy up code involving arrays and loops

texts:
I posted the following code on here a few days ago:

public class Practical4_Assessed
{
    public static void main(String[] args)
    {

        Random numberGenerator = new Random();
        int[] arrayOfGenerator = new int[100];
        int[] countOfArray = new int[10];
        int count;

        for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
        {
            count = numberGenerator.nextInt(10);
            countOfArray[count]++;
            arrayOfGenerator[countOfGenerator] = count + 1;
        }

        int countOfNumbersOnLine = 0;
        for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
        {
            if (countOfNumbersOnLine == 10)
            {
                System.out.println("");
                countOfNumbersOnLine = 0;
                countOfOutput--;
            }
            else
            {
                if (arrayOfGenerator[countOfOutput] == 10)
                {
                    System.out.print(arrayOfGenerator[countOfOutput] + "  ");
                    countOfNumbersOnLine++;
                }
                else
                {
                    System.out.print(arrayOfGenerator[countOfOutput] + "   ");
                    countOfNumbersOnLine++;
                }
            }
        }

        System.out.println("");
        System.out.println("");

        for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
            System.out.println("The number " + (countOfNumbers + 1)
                    + " occurs " + countOfArray[countOfNumbers] + " times.");

        System.out.println("");

        for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
        {
            if (countOfNumbers != 9)
                System.out.print((countOfNumbers + 1) + "   ");
            else
                System.out.print((countOfNumbers + 1) + "  ");

            for (int a = 0; a < countOfArray[countOfNumbers]; a++)
            {
                System.out.print("*");
            }
            System.out.println("");
        }

        System.out.println("");

        int max = 0;
        int test = 0;
        for (int counter = 0; counter < countOfArray.length; counter++)
        {
            if (countOfArray[counter] > max)
            {
                max = countOfArray[counter];
                test = counter + 1;
            }
        }

        System.out.println("The number that appears the most is " + test);

    }
}

I posted it for help on how to tidy it up - the suggestion I got was to add methods to break the code down into more manageable, testable sections.
However, despite spending the best part of two days trying, I can't get my head around how to do this. Everytime I try, I either generate compile-time or run-time errors.

Would anyone mind showing me even one or two of the methods I could use, so I can work from that?


texts:
This is a fully functional implementation of a program to ask the user for a location on Pascal's Triangle, but I kind of cheated by expanding the base case to include row 0 and the 1st and last columns. I feel like this isn't a great approach, but I'm not quite sure why. (Note: I'm not a complete beginner, but I'm definitely not an experienced programmer by any definition)

import java.util.Scanner;
public class Pascal {
    public static void main(String[] args) {
        int r, c;
        Scanner sc = new Scanner(System.in);
        System.out.println("Row #");
        r = sc.nextInt();
        while (r != -1)
        {
        System.out.println("Column #:");
        c = sc.nextInt();
        System.out.println("\n" + calcPascal(r, c));
        //Just here for the while loop
        System.out.println("\nRow #");
        r = sc.nextInt();
        }
    }

    public static int calcPascal(int row, int column)
    {
        int pasVal;
        if (column == 0 || column == row || row == 0)
        //
        {
            pasVal = 1;
        }
        else
        {
            pasVal = calcPascal(row - 1, column - 1) + calcPascal(row - 1,
            column);
        }
        return pasVal;
    }
}


texts: Assigning entire column of data to specific column of an array in VBA

texts:
The below code I have written is to allow me to Sum the results data for every year from 1 to 1000 over a range of 5000 locations. although a 1000 years seems extreme, for the application I am using this makes sense. Column K in the Class Calculation Sheet calculates the Data size for every year for a specific class. I have created the classArray so that the value in D1, which is where the class is defined, can be updated without having to switch back to the original results sheet where the classes are initially defined.

The Script as it stands works, but takes a very long time to run. I am dealing  with 1000 rows and roughly 5000 columns. I have defined the array "arr" which contains the Data size for every year for every class. This 2D array is basically every iteration of column K in the "Class Calculation Sheet" next to each other. At the moment it adds them together row by row as can be seen in the part of code that reads

'creates array of column of Data sizes

 arr(i, r) = ws1.Cells(6 + i, 11)

I was wondering if it is possible to assign the entire column "K" to a specific column within the pre defined array of pre defined size? This would mean that the code does not need to iterate through the 1000 rows, only the 5000 columns.

I realise this is a long winded explanation so please let me know if further clarification is required.

Sub UpdateData()

'Speed
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False

Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim lastcol3 As Integer
Dim classArray As Variant
Dim numRows As Integer
Dim i As Long
Dim r As Long
Dim j As Long
Dim k As Long
Dim arr

Set wb = ThisWorkbook

Set ws1 = wb.Worksheets("Class Calculation Sheet")
Set ws2 = wb.Worksheets("Data")
Set ws3 = wb.Worksheets("Results")

'MANUAL
Application.Calculation = xlCalculationManual

'Number of Rows of data to be entered
numRows = 1000

'Gives value for number of columns of data to be entered
lastcol3 = ws3.Cells(4, ws3.Columns.Count).End(xlToLeft).Column - 1

'Defines 2 dimensional array
ReDim arr(1 To numRows, 1 To lastcol3)

'creates array from list of classes
classArray = ws3.Range(ws3.Cells(4, 2), ws3.Cells(4, lastcol3 + 1))

'AUTO
Application.Calculation = xlCalculationAutomatic

    For r = 1 To lastcol3

    'Makes value in D1 in Class calculation sheet equal to the Class name
    ws1.Range("D1") = classArray(1, r)

    'MANUAL
    Application.Calculation = xlCalculationManual

        For i = 1 To numRows

        'creates array of column of Data sizes
        arr(i, r) = ws1.Cells(6 + i, 11)

        Next

    'AUTO
    Application.Calculation = xlCalculationAutomatic

    Next

    'MANUAL
    Application.Calculation = xlCalculationManual

    For k = 1 To lastcol3

        For j = 1 To numRows

        If arr(j, k) = 15 Then
        ws2.Cells(6 + j, 4) = 1 + ws2.Cells(6 + j, 4)
        ElseIf arr(j, k) = 28 Then
        ws2.Cells(6 + j, 5) = 1 + ws2.Cells(6 + j, 5)
        ElseIf arr(j, k) = 50 Then
        ws2.Cells(6 + j, 6) = 1 + ws2.Cells(6 + j, 6)
        End If

        Next

    Next

    'AUTO
    Application.Calculation = xlCalculationAutomatic

'Speed
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
ApplicationEnableEvents = True
ActiveSheet.DisplayPageBreaks = True

End Sub


texts:
Here's my lock-free channel impl lfchan,

I didn't want to copy/paste the code here since it is multiple files.

I'm trying to get an idea of what can be improved or if there are any bugs in it.

chan.go

type innerChan struct {
    q       []aValue
    sendIdx uint32
    recvIdx uint32
    slen    uint32
    rlen    uint32
    die     uint32
}

// Chan is a lock free channel that supports concurrent channel operations.
type Chan struct {
    *innerChan
}

// New returns a new channel with the buffer set to 1
func New() Chan {
    return NewSize(1)
}

// NewSize creates a buffered channel, with minimum length of 1
func NewSize(sz int) Chan {
    if sz < 1 {
        panic("sz < 1")
    }
    return Chan{&innerChan{
        q:       make([]aValue, sz),
        sendIdx: ^uint32(0),
        recvIdx: ^uint32(0),
    }}
}

// Send adds v to the buffer of the channel and returns true, if the channel is closed it returns false
func (ch Chan) Send(v interface{}, block bool) bool {
    if !block && ch.Len() == ch.Cap() {
        return false
    }
    ln, cnt := uint32(len(ch.q)), uint32(0)
    for !ch.Closed() {
        if ch.Len() == ch.Cap() {
            if !block {
                return false
            }
            runtime.Gosched()
            continue
        }
        i := atomic.AddUint32(&ch.sendIdx, 1)
        if ch.q[i%ln].CompareAndSwapIfNil(v) {
            atomic.AddUint32(&ch.slen, 1)
            return true
        }
        if block {
            if i%250 == 0 {
                pause(1)
            }
        } else if cnt++; cnt == ln {
            break
        }
        runtime.Gosched()
    }
    return false
}

// Recv blocks until a value is available and returns v, true, or if the channel is closed and
// the buffer is empty, it will return nil, false
func (ch Chan) Recv(block bool) (interface{}, bool) {
    if !block && ch.Len() == 0 { // fast path
        return nilValue, false
    }
    ln, cnt := uint32(len(ch.q)), uint32(0)
    for !ch.Closed() || ch.Len() > 0 {
        if ch.Len() == 0 {
            if !block {
                return nilValue, false
            }
            runtime.Gosched()
            continue
        }
        i := atomic.AddUint32(&ch.recvIdx, 1)
        if v, ok := ch.q[i%ln].SwapWithNil(); ok {
            atomic.AddUint32(&ch.rlen, 1)
            return v, true
        }
        if block {
            if i%250 == 0 {
                pause(1)
            }
        } else if cnt++; cnt == ln {
            break
        }
        runtime.Gosched()
    }
    return nilValue, false
}


texts: Making a property virtual to cause EF to load the property

texts:
I am walking through a sample MVC4 ASP.NET tutorial available on PluralSight.com, by Scott Allen.  I am in a section #5, Working with Data (part 2), "Listing Reviews".
This application has a database of restaurant reviews.  I'm following a section right now in which Scott shows how to add links in the Restaurant view that will display a list of reviews for the selected restaurant.
There was a problem when clicking the link to display the reviews, encountered in the following cshtml file.  The problem was that Model.Reviews in the parameters for Html.Partial method was null by default.
Index.cshtml
@model OdeToFood.Models.Restaurant

@{
    ViewBag.Title = "Index";
}

Reviews for @Model.Name

@Html.Partial("_reviews", Model.Reviews)

    @Html.ActionLink("Create New", "Create")

Scott explained that the Model class Restaurant, listed below, will load all the properties except for Reviews, which are stored in another table somewhere else.  He said there are many ways to fix the problem, but the easiest way to make EF load the reviews is to make the Reviews property virtual.
Model class Restaurant
public class Restaurant
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public ICollection<RestaurantReview> Reviews { get; set; }
}

He said that at run time, the EF creates a "wrapper" for the restaurant class that will  intercept calls (I don't understand this) to the Reviews property so that when you get to the reviews in the view, The EF will load them up instead of being null.
My concern is that making a property virtual when you don't intend to override it, is bad coding practice. If so, what is the best coding practice here? I'm also wondering if the simplest solution is the best solution here.


texts:
I got this from a practice problem set, and looking for feedback on my approach.

  Suppose you're given a binary tree represented as an array. Write a function that determines whether the left or right branch of the tree is larger. The size of each branch is the sum of the node values. The function should return the string "Right" if the right side is larger and "Left" if the left side is larger. If the tree has 0 nodes or if the size of the branches are equal, return the empty string.

My logic is that each "breadth" of the tree is 2^depth wide, and we start the work on the second "depth". I can use that to establish how to slice the array to get each "breadth" out of the array (ie, first round is arr[1:3], second is arr[3:7], etc). From there I sum the left/right slices of that slice.

I think my solution uses \$O(n)\$ time and \$O(1)\$ space and should handle unbalanced trees, but parsing trees as arrays is new to me, so wondering about edge cases I should be considering.

def solution(arr):
    breadth = 2
    floor = 1
    left = 0
    right = 0

    while floor < len(arr):
        level = arr[floor:(floor+breadth)]
        pivot = breadth / 2

        left += sum(level[:pivot])
        right += sum(level[pivot:])

        floor += breadth
        breadth *=2

    if left < right:
        return 'Right'
    elif right < left:
        return 'Left'
    else:
        return ''

import unittest

class Test(unittest.TestCase):

    def test_function(self):
        self.assertEqual(solution([3,6,2,9,-1,10]), 'Left')
        self.assertEqual(solution([1,4,100,5]), 'Right')
        self.assertEqual(solution([1,10,5,1,0,6]), '')
        self.assertEqual(solution([]), '')
        self.assertEqual(solution([1]), '')

t = Test()
t.test_function()

One alternate I can think of is evaluating each value. Could this be better than my current solution?

for i in range(len(level)):
    if i < pivot:
        left += level[i]
    else:
        right += level[i]


texts: Importing database of 4 million rows into Pandas DataFrame

texts:
I am using the following code to import database table into a DataFrame:

def import_db_table(chunk_size, offset):
    dfs_ct = []
    j = 0
    start = dt.datetime.now()
    df = pd.DataFrame()

    while True:
        sql_ct = "SELECT * FROM my_table limit %d offset %d" % (chunk_size, offset)
        dfs_ct.append(psql.read_sql_query(sql_ct, connection))
        offset += chunk_size

        if len(dfs_ct[-1]) < chunk_size:
            break

        df = pd.concat(dfs_ct)

        # Convert columns to datetime
        columns = ['col1', 'col2', 'col3','col4', 'col5', 'col6',
                   'col7', 'col8', 'col9', 'col10', 'col11', 'col12',
                   'col13', 'col14', 'col15']

        for column in columns:
            df[column] = pd.to_datetime(df[column], errors='coerce')

        # Remove the uninteresting columns
        columns_remove = ['col42', 'col43', 'col67','col52', 'col39', 'col48','col49', 'col50', 'col60', 'col61', 'col62', 'col63', 'col64','col75', 'col80']

        for c in df.columns:
            if c not in columns_remove:
                df = df.drop(c, axis=1)

        j+=1
        print('{} seconds: completed {} rows'.format((dt.datetime.now() - start).seconds, j*chunk_size))

    return df

I am calling it with:

df = import_db_table(100000, 0)

This seems to be very slow - it starts with importing 100000 rows in 7 seconds but later after 1 million rows the number of seconds needed grows to 40-50 and more. Could this be improved somehow? I am using PostgreSQL, Python 3.5.

7 seconds: completed 100000 rows
17 seconds: completed 200000 rows
30 seconds: completed 300000 rows
47 seconds: completed 400000 rows
69 seconds: completed 500000 rows
92 seconds: completed 600000 rows
121 seconds: completed 700000 rows
153 seconds: completed 800000 rows
188 seconds: completed 900000 rows
228 seconds: completed 1000000 rows
271 seconds: completed 1100000 rows
318 seconds: completed 1200000 rows
368 seconds: completed 1300000 rows
422 seconds: completed 1400000 rows
480 seconds: completed 1500000 rows
540 seconds: completed 1600000 rows
605 seconds: completed 1700000 rows
674 seconds: completed 1800000 rows
746 seconds: completed 1900000 rows


texts: Converting enum values to strings in C++

texts:
Question 1: functionxxx_as_string() is used below.  How else could it be more elegantly named?

Question 2: Is the static char* array method adopted below the only solution?  Best solution?  Any suggestions?

Generally, I have this issue where my list of enums will be from 3 - say 50 items, mostly less than 20 items and they are fairly static.

   #include <iostream>

   enum thing_type
   {
      DTypeAnimal,
      DTypeMineral,
      DTypeVegetable,
      DTypeUnknown
   };

   class thing {
   public:
      thing(thing_type type) : type_(type) {}
      const thing_type get_state() const { return type_; }
      const char* get_state_as_string() const {
         static const char* ttype[] = {
               "Animal",
               "Mineral",
               "Vegetable",
               "Unknown"
         };
         return ttype[type_];
      }

   private:
      thing_type type_;
   };

   int main() {
      thing th(DTypeMineral);
      std::cout << "this thing is a " << th.get_state_as_string() << std::endl;

      return 0;
   }

I am preferring to remove all the printing stuff from the class interface and use the operator<< overloading idea in 200_success answer like this:

#include <iostream>

enum thing_type
{
   DTypeUnknown,
   DTypeAnimal,
   DTypeMineral,
   DTypeVegetable
};

const char* type2string(thing_type ttype) {
   static const char* thtype[] = {
      "Unknown",
      "Animal",
      "Mineral",
      "Vegetable"
   };
   return ttype < sizeof(thtype) ? thtype[ttype] : thtype[0];
}

std::ostream& operator<<(std::ostream& os, const thing_type type) {
   os << type2string(type);
   return os;
}

class thing {
public:
   thing(thing_type type) : type_(type) {}
   const thing_type get_type() const { return type_; }

private:
   thing_type type_;
};

std::ostream& operator<<(std::ostream& os, const thing& th) {
   os << "This is a " << type2string(th.get_type());
   return os;
}

int main() {
   thing th(DTypeMineral);
   std::cout << th << std::endl;

   return 0;
}


texts:
Just wondering if you guys think this is a good way to shuffle a deck or a bad way. Updated to show the GetRandom function as requested.

Private Sub DeckShuffle()
        ' shuffles the deck 4 times.
        For shufflingCards As Integer = 0 To 3
            ' goes through each card and changes position once each time it goes through shufflingCards
            For shuffleEachCard As Integer = 0 To 51
                ' gets a random number 0 - 51
                Dim placeHolder As Integer = GetRandom(0, 51)
                ' creates a temporary card for swapping cards
                Dim tempCard As Card = deck(placeHolder)
                ' makes the random number card now the card we were shuffling
                deck(placeHolder) = deck(shuffleEachCard)
                ' replaces the card we were shuffling with the one we were saving as a temporary
                deck(shuffleEachCard) = tempCard
            Next
        Next
    End Sub

' Gets a random number for shuffling.
Private Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
    Static Generator As System.Random = New System.Random()
    Return Generator.Next(Min, Max)
End Function


texts: Loading KML files into leaflet Javascript map

texts:
This is working code for input KML files into leaflet map

// Load kml file
fetch('lotA.kml')
      .then( res => res.text() )
      .then( kmltext => {

            // Create new kml overlay
            parser = new DOMParser();
            kml = parser.parseFromString(kmltext,"text/xml");

            console.log(kml)

            const track = new L.KML(kml)
            map.addLayer(track)

            // Adjust map to show the kml
            const bounds = track.getBounds()
            map.fitBounds( bounds )

      })

fetch('lotB.kml')
      .then( res => res.text() )
      .then( kmltext => {

            // Create new kml overlay
            parser = new DOMParser();
            kml = parser.parseFromString(kmltext,"text/xml");

            console.log(kml)

            const track = new L.KML(kml)
            map.addLayer(track)

            // Adjust map to show the kml
            const bounds = track.getBounds()
            map.fitBounds( bounds )

      })

fetch('Schematic.kml')
      .then( res => res.text() )
      .then( kmltext => {

            // Create new kml overlay
            parser = new DOMParser();
            kml = parser.parseFromString(kmltext,"text/xml");

            console.log(kml)

            const track = new L.KML(kml)
            map.addLayer(track)

            // Adjust map to show the kml
            const bounds = track.getBounds()
            map.fitBounds( bounds )

      })

fetch('LotC.kml')
      .then( res => res.text() )
      .then( kmltext => {

            // Create new kml overlay
            parser = new DOMParser();
            kml = parser.parseFromString(kmltext,"text/xml");

            console.log(kml)

            const track = new L.KML(kml)
            map.addLayer(track)

            // Adjust map to show the kml
            const bounds = track.getBounds()
            map.fitBounds( bounds )

      })

fetch('LotD.kml')
      .then( res => res.text() )
      .then( kmltext => {

            // Create new kml overlay
            parser = new DOMParser();
            kml = parser.parseFromString(kmltext,"text/xml");

            console.log(kml)

            const track = new L.KML(kml)
            map.addLayer(track)

            // Adjust map to show the kml
            const bounds = track.getBounds()
            map.fitBounds( bounds )

      })

Is there a way to write this code shorter? I would like to use it for multiple KML layers.


texts:
Create a class called Stack for storing integers. The data members are
  an integer array for storing the integers and an integer for storing
  the top of stack (tos). Include member functions for initializing tos
  to 0, pushing an element to the stack and for popping an element from
  the stack. The push() function should check for “stack overflow” and
  pop() should check for “stack underflow”.

#include<iostream>
using namespace std;
#define SIZE 50
class Stack {
    int stackArray[SIZE];
    int tos;
public:
    Stack() {
        tos = 0;
    }
    void push(int);
    int pop();
    void set(int);

};

void Stack::push(int value) {

    if (tos < SIZE) {
        stackArray[tos++] = value;
    }
    else
        cout << "Stack overflow" << endl;

}
void Stack::set(int a) {
    tos = a;

}
int Stack::pop() {
    if (tos == 0) {
        cout << "Stack underflow " << endl;
    }
    else {
        return stackArray[--tos];
    }

}
int main() {
    Stack s;
    for (int i = 0; i < 50; i++) {
        s.push(i);
    }
    for (int i = 0; i < 51; i++) {
        cout << s.pop() << " " << i << endl;
    }
}


texts: Function figuring out which close-by value comes from which input value

texts:
I would like to optimize the below traceback function. This function is part of an elementary step of the program and is called a lot...

import numpy as np

def traceback(tuple_node, tuple_node_alt):
    """
    Compute which value from tuple_node_alt comes from which value from tuple_node.
    Return a dictionnary where the key are the values from tuple_node and the values are the idx at which
    the value may be located in tuple_node_alt.
    """
    # Compute the tolerances based on the node
    tolerances = [0.1 if x <= 100 else 0.2 for x in tuple_node]

    # Traceback
    distance = dict()
    alt_identification = dict()
    for k, x in enumerate(tuple_node):
        distance[k] = [abs(elt-1) for elt in [alt_x/x for alt_x in tuple_node_alt]]
        alt_identification[x] = list(np.where([elt <= tolerances[k]+0.00001 for elt in distance[k]])[0])

    # Controls the identification and corrects it
    len_values = {key: len(val) for key, val in alt_identification.items()}

    if all([x <= 1 for x in len_values.values()]):
        return alt_identification
    else:
        for key, value in alt_identification.items():
            if len(value) <= 1:
                continue
            else:
                other_values = [val for k, val in alt_identification.items() if k != key]
                if value in other_values:
                   continue
                else:
                    for val in other_values:
                        set1 = set(value)
                        intersec = set1.intersection(set(val))
                        if len(intersec) == 0:
                            continue
                        else:
                            alt_identification[key] = [v for v in value if v not in intersec]

    return alt_identification

The input is composed of 2 tuples which do not need to have the same size. e.g.

tuple_node = (40, 50, 60, 80)
tuple_node_alt = (87, 48, 59, 39)

The goal is to figure out which value from tuple_node_alt may come from which value from tuple_node. If the value from tuple_node_alt is within a 10% margin from a value from tuple_node, it is considered that it comes from this value.

e.g. 39 is within a 10% margin of 40. It comes from 40.
This aprt is perform in the "Traceback" section, where a distance dictionnary is computed and where the idx are computed. With the example above, the output is:

Out[67]: {40: [3], 50: [1], 60: [2], 80: [0]}

However, because of a potential overlapping of the tolerance band, 3 scenarios exists:

Scenario 1: each value has been identified to one alternative value. That's the case above.

Scenario 2:

tuple_node = (40, 50, 60, 80)
tuple_node_alt = (42, 55, 54)

55 and 54 are both in the tolerance band of both 50 and 60. Thus, the output is:

Out[66]: {40: [0], 50: [1, 2], 60: [1, 2], 80: []}

Scenario 3:

tuple_node = (40, 50, 60)
tuple_node_alt = (42, 55, 59)

This is when the control part comes in play. With this input, alt_identification becomes: Out[66]: {40: [0], 50: [1], 60: [1, 2], 80: []}. However, the 55 can not come from 60 since 50 only has one possibility: 55. Thus, this number being already taken, the correct output which is provided through the control & correct section is:

Out[66]: {40: [0], 50: [1], 60: [2], 80: []}

I would really like to optimize this part and to make it a lot more quicker. At the moment, it takes:

# With an input which does not enter the control & correct part.
node = (40, 50, 60, 80)
node_alt = (39, 48, 59, 87)
%timeit traceback(node, node_alt)
22.6 µs ± 1.04 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

# With an input which need correction
node = (40, 50, 60, 100)
node_alt = (42, 55, 59, 89)
%timeit traceback(node, node_alt)
28.1 µs ± 1.88 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)


texts: Performance Issue on css and javascript styling

texts:
I make some ui custom controls.  Typically my controls have themes to them so it can be changed.  I dont use css files for each themes.  What I do instead is hava a javascript file that contains the different themes for that particular control. Example of my button control (Note i took the rest of the css off the other colors just so this wont be so long in the post)

(function ($) {

    $.fn.buttonTheme = function () { };
    $.buttonTheme = {

        newButtonTheme: function(){
            $.buttonTheme.rules = {
                "button" :
                {
                    "nonrounded": "cursor: pointer; cursor: hand;display:inline-block;zoom:1;*display:inline;" +
                                  "vertical-align:baseline;margin:0 2px;outline:none;text-shadow:0 1px 1px rgba(0,0,0,.3);" +
                                  "-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.2);" +
                                  "-moz-box-shadow:0 1px 2px rgba(0,0,0,.2);box-shadow:0 1px 2px rgba(0,0,0,.2);",
                    "rounded": "cursor: pointer; cursor: hand;display:inline-block;zoom:1;*display:inline;vertical-align:baseline;margin:0 2px;" +
                               "outline:none;text-shadow:0 1px 1px rgba(0,0,0,.3);-webkit-border-radius:.4em;-moz-border-radius:.4em;" +
                               "border-radius:.4em;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.2);-moz-box-shadow:0 1px 2px rgba(0,0,0,.2);" +
                               "box-shadow:0 1px 2px rgba(0,0,0,.2);"
                },
                "light_gray":
                {
                    "enabled": "" +
                                "",
                    "disabled": "",
                    "hover": "",
                    "text": ""
                },
                "black":
                {
                    "enabled": "",
                    "disabled": "",

                    "hover": "",
                    "text": ""
                },
                "gray":
                {
                    "enabled": "",
                    "disabled": "",

                    "hover": "",
                    "text": ""
                },
                "white":
                {
                    "enabled": "",
                    "disabled": "",

                    "hover": "",
                    "text": ""
                }

            };
        }
    };

})(jQuery);

So in the control javascript file I build the control by assigning the particular elements the particular style it needs based on the selected theme like ligh_gray.  I find this method to be easy to maintain and update to other themes because the underlying samples are there and its not hard coded in the script. So I can just create another theme like aqua for example and just change the colors, etc. Also I can dynamically change the theme easier without having to do a page refresh

What I wanted to know from others is there thoughts on this.  Is there a performance issue in this method? Does it seem like its a maintenance headache?


texts:
I'm pretty sure there's no better way to do this but I thought a consensus on here might be nice. Let me know what you think.

public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue = default(TValue))
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}


texts:
I built an allsky camera with a temperature sensor and a heater. The heater is supposed to turn when the sensor (measure_temp()) return a temperature below 8, which is checked every 15 minutes. However, about every 4th measurement fails and so I included an error handler that returns 7, so that the heater turns on if the sensor returns an error, but it seems like a bad solution. Is there a better way to handle the error like run the function until no error occurs?
import RPi.GPIO as GPIO
import time
import datetime
import time
import board
import adafruit_dht

def measure_temp():
    dhtDevice = adafruit_dht.DHT22(board.D18)

    try:
        temperature = dhtDevice.temperature
        error_test = ""
    except RuntimeError as error:
        temperature = 7
    except:
        temperature = 7
    return temperature

if __name__ == '__main__':

    while True:
        if  measure_temp() < 8:
            GPIO.setmode(GPIO.BCM)
            RELAIS_1_GPIO = 17
            GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
            GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)
            print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
            print('Heating on')
            print()
            time.sleep(900)
            GPIO.cleanup()
        else:
            GPIO.setmode(GPIO.BCM)
            RELAIS_1_GPIO = 17
            GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
            GPIO.output(RELAIS_1_GPIO, GPIO.LOW)
            print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
            print('Heating off')
            time.sleep(900)
            GPIO.cleanup()


texts: Arduino code for multi button state change detection

texts:
I created state change detection for multiple buttons, which is intended to run on my Arduino for a touchpad project. In a nutshell, the code makes sure that the Arduino only reacts to button presses and not to holding in the buttons.

My code:

unsigned int buttonStates[] = {0, 0, 0};
unsigned int previousButtonStates[] = {0, 0, 0};
//The Arduino pins for detecting a button press.
const unsigned int buttonPins[] = {A3, A4, A5};

void setup() {
    //Start communication with the serial monitor (console).
    //9600 is the data transfer speed of USB.
    Serial.begin(9600);
    //Wait until the serial port is open, before continuing.
    while(!Serial);
    //Defining the buttons as input.
    for (int i = 0; i < 3; i++) {
    pinMode(buttonPins[i], INPUT);
  }
}

void buttonStateChangeDetect() {
  for (int i = 0; i < 3; i++) {
    //Read the button states.
    buttonStates[i] = digitalRead(buttonPins[i]);
    //Determines if a button has been released after a press.
    if (buttonStates[i] != previousButtonStates[i]) {
      //Checks if the button is pressed. If pressed, the state will change from 0 to 1.
      if (buttonStates[i] == HIGH) {
        //The variable i represent a button. 0 is the first button.
        if (i == 0) {
          Serial.println("Button 1 is pressed.");
        }
        else if (i == 1) {
          Serial.println("Button 2 is pressed.");
        }
        else if (i == 2) {
          Serial.println("Button 3 is pressed.");
        }
      }
    }
    previousButtonStates[i] = buttonStates[i];
    delay(10);
  }
}

void loop() {
  buttonStateChangeDetect();
}

Currently, the code works fine but I still see some flaws in my implementation:

A lot of if-statements need to be added if the Arduino uses more buttons.
Example:if(i==3), if (i==4), if(i==5)..
The responsiveness of the buttons is dependent on the number of buttons.
Example: When 30 buttons are used, the for loop will have to loop 30 times and it could be that a button press isn't registered. The higher the index of the button, the higher the chance is that a button press will not be registered or it will take longer to register.

The only idea that came to my mind for improving my code was instead of using if-statements, I could use switch cases. Any other suggestions would be more than welcome.

Extra detail:
The official documentation with a example and my inspiration for writing this code.
Arduino - StateChangeDetection
I created an online example with code. No need for physical hardware if someone wants to try out my code.
Online Arduino Simulation


texts:
For practicing/learning object orientation, I made a Card class and am practicing doing stuff with it such as shuffling decks and dealing hands etc...

I have a method that receives a list item which essentially is a hand of 5 cards then tells the user how about the hand such as pairs and three of a kind however it feels incredibly sloppy and would like to know if it's improvable.

private static string CheckHand(List<Card> hand)
{
    string[] tempnames = { hand[0].Face, hand[1].Face, hand[2].Face, hand[3].Face, hand[4].Face };
    int sameCardCount = 0;

    for (int i = 0; i < hand.Count; i++)
    {
        for (int k = 0; k < hand.Count; k++)
        {
            if (k == i) { }
            else if (tempnames[i] == hand[k].Face)
            {
               sameCardCount++;
            }
        }
    }
    switch (sameCardCount)
    {
        case 12:
        return "you have four of a kind!";
        case 6:
        return "you have three of a kind!";
        case 4:
        return "you have two pairs!";
        case 2:
        return "you have a pair!";
        default:
        return "nothing special here..";
    }
}

The card object and enum suit is like so:

class Card
{
    public string Face { get; set; }
    public Suit Suitc { get; set; }
    public Card(Suit suit,string face)
    {
        Face = face;
        Suitc = suit;
    }

    public override string ToString()
    {
        string card = "(" + Face + " " + Suitc + ")";
        return card;
    }
}
enum Suit
{
    CLUB, DIAMOND, HEART, SPADE
}

As far as I can test, it works as intended. But with the double loop, the return values are a bit messy in my opinion. How would you have done it?

Note: you do not have to provide extracts of code if you don't wish to. I'm just trying to help myself improve my problem solving.


texts:
I'm new to Hibernate so I need some advice/direction on doing Transactions.

I have a DAO like

public class MyDao extends HibernateDaoSupport implements IMyDao {

 @Override
 public Foo getFoo(int id) {

  return (Foo)getHibernateTemplate().load(Foo.class, id);

 }
}

With this setup (using HibernateDaoSupport), will Hibernate/Spring handle transactions for me? Some of the examples I see say yes, others show using

Transaction tx = getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction();

to get a Transaction in every DAO method.

Right now I'm assuming my minimal DAO is correct but I want to do a "larger" transaction that includes a couple of Hibernate calls in one method. Would I use the manual Transaction method there? Do I have to use it everywhere? Thanks.


texts: Insert array items into jQuery / JavaScript variable

texts:
This code exists in my view; it makes use of a model passed through from the controller.

$("#email").emailautocomplete({
domains: [@foreach (var organisation in Model.Organisations)
             {
                @Html.Raw("\"") @organisation.EmailDomain
                @Html.Raw("\", \r\n")
             }
                @Html.Raw("]")
});

Which renders as:

$("#email").emailautocomplete({
domains: ["domain1.gov.uk",
"domain2.com",
"domain3.gov.uk",
"domain4.gov.uk",
]
});

This achieves what I want but I feel the razor syntax is messy and wonder if there is a cleaner way of passing the email domain strings into the JavaScript, to achieve the same rendered result.

I understand an ajax call is an option however I don't want to call the database again to get the list of organisations as the data has already been retrieved by the controller and passed into the view, and is used elsewhere in the view to populate a combo box.


texts:
I'm taking my first ever CS class and I have an assignment due Friday. I just wanted someone to check my code.

Instructions:

  Write a program that:

  gets the name of a text file of numbers from the user. Each number in the file is on its own line.
  reads in those numbers one at a time
  writes the even numbers to a file named even.txt
  writes the odd numbers to a file named odd.txt
  displays to the user the sum of the positive numbers and the count of the negative numbers.

Here is what I have:

def main():
    #Open text file for reading
    fileName   = input('Enter name of a file of numbers (include the whole path): ')
    numberFile = open(fileName, 'r')

#Priming read
    number = numberFile.readline()

#Setting up loop to continue reading until
#an empty line is reached
    total = 0
    count = 0
    while number != '':
        number = float(number)                  #convert from string to number
        if number%2 == 0:
            evenNumber = open('even.txt', 'w')  #writes even numbers into a file
            evenNumber.write(number + '\n')
        else:
            oddNumber  = open('odd.txt', 'w')   #writes odd numbers into a file
            oddNumber.write(number + '\n')

        for number in numberFile:
            number = float(number)      #convert from string to number

            if number <= 0:             #identify negative numbers
                count += 1              #count negative numbers

            if number >= 0:             #identify positive numbers
                total += number         #sum of positive numbers
        number = numberFile.readline()

    numberFile.close()                  #close file after program is complete

    print('The count of the negative numbers is: ', count)
    print('The sum of the positive numbers is: ', total)

main()

Example of a "file of numbers" (each number in a new line):

25
18
-7
4.2
99
103
-100


texts:
I have written the following code for doing a reverse dns lookup. I'm not sure if there are any errors in it. Please have a look:

#include <stdio.h> //for printf()
#include <stdlib.h> //for exit()
#include <arpa/inet.h> //for inet_pton()
#include <netdb.h> // for NI_MAXHOST, getnameinfo() and gai_strerror()
#include <errno.h> // for errno
#include <string.h> // for strerror()

int main(int argc, char** argv) {
  if(argc<2) {
    printf("\n%s [IP]\n",argv[0]);
    printf("For e.g. %s 10.32.129.77\n",argv[0]);
    exit(-1);
  }
  struct sockaddr_in sa;
  int res = inet_pton(AF_INET, argv[1] , &sa.sin_addr);
  switch(res) {
    case 0: printf("\nInput address is not a valid IPv4 address.\n");
    case -1: if(res == -1)
               printf("\nError(%s)\n",strerror(errno));
             int n_res = inet_pton(AF_INET6, argv[1] , &sa.sin_addr);
             switch(n_res) {
               case 0: printf("\nInput address is not a valid IPv6 address.\n");
               case -1: if(n_res == -1)
                          printf("\nError(%s)\n",strerror(errno));
                        exit(-1);
               case 1: sa.sin_family = AF_INET6;
             }
    case 1: sa.sin_family = AF_INET;
  }

  printf("\nsa.sin_addr.s_addr[%d]\n",sa.sin_addr.s_addr);

  char node[NI_MAXHOST];
  memset(node,0,NI_MAXHOST);
  res = getnameinfo((struct sockaddr*)&sa, sizeof(sa), node, sizeof(node), NULL, 0, 0);
  if (res) {
    printf("%s\n", gai_strerror(res));
    exit(1);
  }

  printf("\nIP[%s]\n",argv[1]);
  printf("HOSTNAME[%s]\n", node);

  return 0;
}


texts:
I'm working on this code for exam in an MIT Python course. It's working but I'm trying to improve it. What could I do, and what should I avoid?

aDict = {   0: 1,
     1: 2,
     2: 2,
     4: 2,
     5: 2,
            6: 3,
     7: 2}

values=list(aDict.values())
keys=list(aDict.keys())
value_copy=values[:]
uniqe=[]

m=0

for value in value_copy:
    m+=1
    if value in value_copy[m:]:
        while(values.count(value)):
            try:
                values.remove(value)
            except:
                pass

for val in values:
    uniqe.append(keys[value_copy.index(val)])

uniqe.sort()

print (uniqe)


texts: Code to remove columns in a (fasta) file with more than 90% '-' characters in that column

texts:
Context:

This script reads in a fasta file, counts the number '-' characters, alphabetic characters and total characters for each sequence (sequence descriptions are on lines marked with '>'), and then prints out a processed file with columns where 90% (or more) of '-' characters are removed.

I've tested it with smaller alignments and it worked fine, but it's currently been running for around 4 hours on one alignment (220Mb), which seems slow and probably inefficient.

The script:

import sys
from Bio import AlignIO

alignment = AlignIO.read(open(sys.argv[1]), "fasta")
length =  alignment.get_alignment_length()

tofilter = []

for i in range(length):
    counterofgaps=0
    counterofsites=0
    counteroftotal=0
    for record in alignment:
        for site in record.seq[i]:
            if site == '-':
                counterofgaps +=1
                counteroftotal +=1
            elif site.isalpha():
                counterofsites +=1
                counteroftotal +=1
    Fractionofgaps = counterofgaps/counteroftotal * 100
    if Fractionofgaps >=90:
        tofilter.append(i)

for record in alignment:
    print ('>' + record.id)
    for i in range(length):
        if i not in tofilter:
            print (record.seq[i], end ='')
    print()


texts:
I would like to design an elegant yet efficient circular buffer of integers.
I have designed a FIFO type circular buffer in C++(11)- starting with the class header (declaration) as follow:

[cyclicBuffer.hpp]:

#ifndef __CyclicBuff_HPP
#define __CyclicBuff_HPP
#pragma once

class CyclicBuffer
{
public:
    CyclicBuffer(int buffSize);
    ~CyclicBuffer();
    void setChar(char c);
    char getChar();
    void clearCycBuff(int buffSize);
private:
    char *buffer;
    int bufferSize;
    int head;   // index for the top of the buffer
    int tail;   // indes for the bottom of the buffer
};

#endif

implementation of the class is as following:
[cyclicBuffer.cpp]:

#include "stdafx.h"
#include "cyclicBuffer.hpp"
#include <iostream>

//using namespace std;

CyclicBuffer::CyclicBuffer(int buffSize)
{
    head = 0;
    tail = 0;
    bufferSize = buffSize;
    buffer = new char[bufferSize];
    std::cout << "Buffer initated successfully\n";

/*
    {
        std::cout << "Buffer was not created\n driver exiting...\n";
//      return -1;
    }*/
}

CyclicBuffer::~CyclicBuffer()
{
    delete buffer;
    std::cout << "Buffer destroyed successfully\n";
}

void CyclicBuffer::clearCycBuff(int buffSize)   //not used , has no meaning to set '0'

{
    head = 0;
    tail = 0;
    for (int i = 0; i <= buffSize; i++)
        buffer[i] = '0';
}

void CyclicBuffer::setChar(char c)
{
    //std::cout << "head: " << head << '\n';
    head %= bufferSize;
    buffer[head] = c;
    head++;
}

char CyclicBuffer::getChar(void)
{
    //std::cout << " tail:" << tail<<'\n';
    tail %= bufferSize;
    return buffer[tail++];

}

Finally, testing the class by an instance as follow:

// CyclicBufferMain.cpp : Defines the entry point for the console
// application.

#include "stdafx.h"
#include <iostream>
#include "cyclicBuffer.hpp"

#define SIZE    32

int main(void)
{
    CyclicBuffer aBuffer(SIZE);

    for (int i = 0; i < SIZE*1.5; i++)
        aBuffer.setChar((char)(i+45));

    for (int i = 0; i < SIZE ; i++)
        std::cout << aBuffer.getChar() << ' ';

    std::cout << '\n';

    return 0;
}

for the given main function the result will be like this:

My question: is this class is efficient enough for low-rate uC ? (targeting to Atmel, RISC type or low performance ARM uC)

Regarding @Toby Speight: Thanks for your helpful comments and advices - few questions for you:

(1) when I did delete instead delete [], did I make a 'memory leak'? why MS VStudio (2015) didn't warn me?

(2) I would change the CyclicBuffer::clearCycBuff() member function to use buffer[i] = 0; (instead buffer[i]='0';) to clear the buffer's values.

(3) Why need to drop the commented-out code?

(4) You used uniform initializer at the constructor - is it big difference as to what I did using regular variable assignments at the constructor ?

(5) I know 'size_t' is it a specialize typedef that exists at the GNU and MS compilers but would have a problem using it when porting the code to a specific target which could not have such typedef ?

Thanks.


texts:
So i read about simple series for Pi named Leibniz Series for Pi. Here is its Link:-
Series . I made a program for it and soon realised that it converges very slows . So i did Euler accelerate for Alternating Series https://en.wikipedia.org/wiki/Series_acceleration#Euler's_transform and made this recursive program:-
import functools
import decimal
def LebniezTerm(n):
  return 1/(2*n + 1)

@functools.lru_cache(maxsize = 12800)
def ndiffrence(n,depth):
  if depth == 0:
    return LebniezTerm(n)
  a = ndiffrence(n,depth-1)
  b = ndiffrence(n+1,depth-1)
  return (a - b)

def EulerAccelerate(n):
  i = decimal.Decimal(1)
  pi = decimal.Decimal(0)
  while (i <= n):
    pi = pi + decimal.Decimal(ndiffrence(0,i-1))/decimal.Decimal(2**i)
    i+=1
  return pi

4*EulerAccelerate(600)

Here i did and optimisation using Functools but it is still slow. So can it become more optimised ?
How can the accuracy get more increased ?


texts: Updating height of the rows in tables with jQuery

texts:
Does it make any sense and how to modify the JavaScript/jQuery code below to increase the performance? The working code is:

var rightTr = $(".superBlock div.right tr:visible");

$(".superBlock div.left tr:visible").each(function(i){
    if ($(this).height() != rightTr.eq(i).height()){
        if ($(this).height() > rightTr.eq(i).height()){
            rightTr.eq(i).height($(this).height());
        } else {
            $(this).height(rightTr.eq(i).height());
        }
    }
});

The logic is to update the respective rows within two tables - to assign the bigger height to smaller height if the heights of respective rows are different.

The eq(i)s are needed in this code as the actual problem is a bit more complicated than described here.

Most of the cells are expected to be equivalent so the first thing I do is checking if the cells are equivalent. That condition should exclude most of comparisons if it is more or it is less (one comparison instead of two).


texts: Find all strings in list which have keywords in it from another list

texts:
I a list of strings A and a list of keywords B. Now I want to return all strings from list A which have all keywords from B in it as a new list.

def string_search(strings, keys):
    res = []
    for s in strings:
        full = True
        for k in keys:
            if not(k in s):
                full = False
                break
        if full == True:
            res.append(s)
    return res

In which way could I improve this code? I ask purely out of curiosity, since it works perfectly fine and it is not the bottleneck of my processing chain.


texts:
This is my first experiment that uses a network API and connects to the internet.
I tried to write a program that gives you an article of wikipedia directly by typing the name.

You can get an article like this:

java ArticleSupplier computer science
java ArticleSupplier captain underpants

If you have tips for me how to improve the performance or how to make a better structure, I would be thankful!

import java.util.Scanner;
import java.io.InputStream;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;

public class ArticleSupplier {
    private String nameOfArticle; // will be the name of the created document
    private String urlName;
    private URL url;
    private String article;

    public ArticleSupplier(String[] urlComponents) {
        // initialize article
        article = "";

        // initialize urlName and nameOfArticle
        urlName = "https://en.wikipedia.org/wiki/";
        nameOfArticle = "";
        for(int i = 0; i < urlComponents.length; i++) {
            urlName += urlComponents[i];
            urlName += "_";

            nameOfArticle += urlComponents[i];
            nameOfArticle += " ";
        }
        urlName = urlName.substring(0, urlName.length() - 1);
        nameOfArticle = nameOfArticle.substring(0, nameOfArticle.length() - 1);

        // initialize url
        try {
            url = new URL(urlName);
        } catch(MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public void getArticle() {
        try(InputStream inputStream = url.openStream(); Scanner scanner = new Scanner(inputStream)) {
            while(scanner.hasNext()) {
                article += scanner.next() + "\n";
            }
        } catch(IOException e) {
            System.out.println(e);
        }
    }

    public void saveAsHTML() {
        String filename = nameOfArticle + ".html";
        try(FileWriter fileWriter = new FileWriter(filename);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
            bufferedWriter.write(article);
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ArticleSupplier as = new ArticleSupplier(args);
        as.getArticle();
        as.saveAsHTML();
    }
}


texts:
I have been doing some Code School classes on jQuery, and I needed a image slider for my site. Right now, there are only two responsive states, but that will most likely change (and/or become fluid later).

I was just wondering if there are any best practices or general clean up I can do to the code.  I'm still a newbie with jQuery, so any advice would be helpful.

Plugins used: Fastclick and hammer.js

$(function() {

FastClick.attach(document.body);

var slide = $(".ImgSection li");
var ImgSec = $(".ImgSection").hammer();
var CrntPos = 0;
var Width;
var Time;
var PlusPos;

$(window).on("load resize", function(e) {
    Width = slide.outerWidth(true);
 });

ImgSec.on("dragleft dragright", "li", function(ev) {
    ev.gesture.preventDefault();
});

function changeImg (e){
    CrntPos = $(this).index();
var ClkWth = Width * .1;
var NewPos =  (CrntPos * Width) - ClkWth;
    slide.css("transform", "translate3d(-"+ NewPos +"px,0,0)");
    if (CrntPos === 1 ){
        $("li:eq(0)").on("click", function() {
            slide.css("transform", "translate3d(0,0,0)");
        });
    }
}
slide.click(changeImg);

ImgSec.on("swipe", "li", function(ev) {
  if(ev.gesture.direction == 'left'){
    slide.eq(CrntPos + 1).trigger("click");
        }
  if(ev.gesture.direction == 'right'){
    slide.eq(CrntPos - 1).trigger("click");
        }
 if($(this).is(':last-child') && ev.gesture.direction == 'left'){
    slide.eq(0).trigger("click");
        }
});

 $(window).resize(function() {
    clearTimeout(Time);
    Time = setTimeout(Resize, 100);
 });

function Resize(){
    if ($('img', slide).css('max-width') == '245px' ){
        slide.eq(CrntPos).trigger('click');
    }
    else {
        slide.eq(CrntPos).trigger('click');
    }
}
  });


texts: Converting minutes and seconds in seconds

texts:
I have 2 input fields to input the duration of a CD song. The first input is for minutes and the second is for seconds

When submitting the form, I must insert in the db the duration either in seconds (minutes + seconds) or NULL.

Here's my validation formula:

$warning = array();

function val_duration($min, $sec, $required = false) {
    global $warning;

    if (!empty($min) || !empty($sec)) {

        if (!empty($min) && (!is_numeric($min) || !ctype_digit($min) || $min > 60)) {
            $warning['min'] = 'The minutes must contain a positive numeric value between 1 and 60';
        } else {
            $min_in_sec = $min * 60;
        }

        if (!empty($sec) && (!is_numeric($sec) || !ctype_digit($sec) || $sec > 59)) {
            $warning['sec'] = 'The seconds must contain a positive numeric value between 1 and 59';
        } else {
            $tmpsec = $sec;
        }

        $value = $min_in_sec + $tmpsec;

    } else {

        if ($required) {
            $warning['duration'] = "The duration is a required field";
        }

        $value = NULL;
    }

    return $value;
}

// HTML
<input id="min" name="min" type="text" value="...">
<input id="sec" name="sec" type="text" value="...">

// validate
$min = ltrim(trim($_POST['min']), '0');
$sec = ltrim(trim($_POST['sec']), '0');

$duration_in_secs = val_duration($min, $sec, true); // duration

// mySQL
enter $duration_in_secs in db (either seconds or NULL)