texts: Inverse Document Frequency (IDF) implementation

texts:
I would like to share my class IDF. Any suggestions/modification?

public class IDFMeasure
{
    private readonly string[] _docs;
    private readonly int _numDocs;
    private int _numTerms;
    private List<string> _terms;
    private float[][] _InverseDocFreq;
    private int[] _docFreq;

    private readonly Dictionary<string, int> _wordsIndex = new Dictionary<string, int>();

    public IDFMeasure(string[] documents)
    {
        _docs = documents;
        _numDocs = documents.Length;
        MyInit();
    }

    private List<string> GenerateTerms(string[] docs)
    {
        return docs.SelectMany(doc => ProcessDocument(doc)).Distinct().ToList();
    }

    private IEnumerable<string> ProcessDocument(string doc)
    {
        return doc.Split(' ')
            .GroupBy(word => word)
            .OrderByDescending(g => g.Count())
            .Select(g => g.Key)
    }

    private int GetTermIndex(string term)
    {
        return _wordsIndex[term];
    }

    private void MyInit()
    {
        _terms = GenerateTerms(_docs);
        _numTerms = _terms.Count;

        _docFreq = new int[_numTerms];

        for (var i = 0; i < _terms.Count; i++)
        {
            _wordsIndex.Add(_terms[i], i);
        }

        GenerateDocumentFrequency();
        GenerateInverseDocfrequency();
    }

    private float Log(float num)
    {
        return (float) Math.Log(num); //log2
    }

    private void GenerateDocumentFrequency()
    {
        _InverseDocFreq = new float[_numDocs][];

        for (var i = 0; i < _numDocs; i++)
        {
            _InverseDocFreq[i] = new float[_numTerms];

            var curDoc = _docs[i];
            var freq = GetWordFrequency(curDoc);

            foreach (var entry in freq)
            {
                var word = entry.Key;

                var termIndex = GetTermIndex(word);

                _docFreq[termIndex]++;
            }
        }
    }

    private void GenerateInverseDocfrequency()
    {
        for (var i = 0; i < _numDocs; i++)
        {
            var curDoc = _docs[i];
            var freq = GetWordFrequency(curDoc);

            foreach (var entry in freq)
            {
                var word = entry.Key;

                var termIndex = GetTermIndex(word);

                _InverseDocFreq[i][termIndex] = Log((_numDocs)/
                                                    (float) _docFreq[termIndex]);
            }
        }
    }

    private Dictionary<string, int> GetWordFrequency(string input)
    {
        return input.Split(' ').GroupBy(x => x)
            .OrderByDescending(g => g.Count())
            .ToDictionary(g => g.Key, g => g.Count());
    }
}


texts:
Any suggestions are welcome.

package je3.io;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IDEA on 31/01/15.
 */
public class DirWalker {
    private List<File> recursiveList = new ArrayList<File>();

    public void walkDir(String pathname) {
        File d = new File(pathname);
        recursiveList.add(d);
        if(d.isDirectory()) {
            for(String f : d.list()) {
                walkDir(f);
            }
        }
    }

    public void reset() {
        recursiveList.clear();
    }

    public List<File> getRecursiveList() {
        return recursiveList;
    }

    public static void main(String[] args) {
        DirWalker dirWalker = new DirWalker();
        dirWalker.walkDir("/tmp");
        dirWalker.getRecursiveList().forEach(System.out::println);
    }
}


texts:
I'm using the following piece of JavaScript to emulate class extending. Is this a valid way to go or does it have some drawbacks which should definitely be fixed?

var Validator = function (inputId) {
    "use strict";

    var self = this;

    self.inputId = inputId;

    window.document.getElementById(inputId).onblur = function () {
        self.check();
    };

};

Validator.prototype.inputId = '';

/**
 * Validator fails by default
 *
 * @returns {Boolean}
 */
Validator.prototype.isValid = function () {
    "use strict";

    return false;

};

/**
 * Check whether the input is valid
 *
 * @returns {Validator}
 */
Validator.prototype.check = function () {
    "use strict";

    // Check and mark whether validation passes
    if (!this.isValid()) {

        this.markInvalid();

    } else {

        this.markValid();

    }

    return this;

};

/**
 * Mark the input as valid
 *
 * @returns {Validator}
 */
Validator.prototype.markValid = function () {
    "use strict";

    var input = window.document.getElementById(this.inputId);

    // Remove "error" class name
    input.className = input.className.replace(
        /(?:^|\s)error(?!\S)/g,
        ''
    );

    return this;

};

/**
 * Mark input as invalid
 *
 * @returns {Validator}
 */
Validator.prototype.markInvalid = function () {
    "use strict";

    var input = window.document.getElementById(this.inputId);

    // Add "error" class when it is not set already
    if (!input.className.match(/(?:^|\s)error(?!\S)/g)) {
        input.className += ' error';
    }

    return this;

};

Than this is used as a concrete validator implementation

// Inherit from validator
var VatCheck = Validator;

/**
 * Validate vat number
 *
 * @note only format is checked, not whether the number is in use
 *
 * @returns {Boolean}
 */
VatCheck.prototype.isValid = function () {
    "use strict";

    var input = window.document.getElementById(this.inputId);

    // Check number by using Vat.js
    return !!checkVATNumber(input.value);

};

The reason I came to this solution is because only one or two methods of the parent class have different behavior, and the use of the strategy pattern seems somewhat over-engineering


texts: Using zip to process widgets flagged as enabled

texts:
This code returns a list of widgets from spreadsheet ranges that are enabled for processing. The code works but it is poorly implemented, especially in terms of proper use of zip and layout.

The code needs to run on various ranges but was initially hard-coded for development. In openpyxl row/column processing is more efficient than coordinate ranges and coordinate range functionality is progressively being depreciated. (The coordinate code is only used for development and will be deleted.)

It's my first list comprehension and getting into zip so I'd also appreciate advice on how to lay out the long single lines of code.

from __future__ import print_function
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
import openpyxl

def do_widgets(ws, col0, col1):
    """ Process each widget. """
    NO_WDGTS = 5
    ENABLE_START_ROW = 6
    ENABLE_END_ROW = ENABLE_START_ROW + NO_WDGTS - 1
    WDGT_START_ROW = 1
    WDGT_END_ROW = WDGT_START_ROW + NO_WDGTS - 1

    # Coordinate code - delete whole block before implementation
    col_letter0 = get_column_letter(col0)
    col_letter1 = get_column_letter(col1)
    wdgos_range = [(col_letter0 + str(ENABLE_START_ROW) + ":" +
                    col_letter0 + str(ENABLE_END_ROW))]
    wdgos_range.append(col_letter1 + str(WDGT_START_ROW) + ":" +
                       col_letter1 + str(WDGT_END_ROW))
    # Delete
    # wdgos = [cell[1][0].value for cell in zip(ws['B6:B10'], ws['C1:C5'])
    #                                          if cell[0][0].value]
    wdgos = [cell[1][0].value for cell in zip(ws[wdgos_range[0]], ws[wdgos_range[1]])
                                             if cell[0][0].value]

    # Row/column code
    wdgts = [cell[1] for cell in zip([cell.value for col
                     in ws.iter_cols(min_row=ENABLE_START_ROW, min_col=col0,
                                     max_row=ENABLE_END_ROW, max_col=col0)
                     for cell in col],
                     [cell.value for col
                     in ws.iter_cols(min_row=WDGT_START_ROW, min_col=col1,
                                     max_row=WDGT_END_ROW, max_col=col1)
                     for cell in col]) if cell[0]]

    # Use list of enabled widgets
    print("Enable range [0], Widget range [1]")
    print(wdgos_range)
    for wdgo in wdgos:
            print(wdgo)
    print()
    print(wdgts, '\n')

wb = Workbook()
ws = wb.active

rows = [
    ['Number', 'Batch 1', 'Batch 2'],
    [2, 40, 30],
    [3, 40, 25],
    [4, 50, 30],
    [5, 30, 10],
    [0, 0, 0],
    [0, 1, 0],
    [1, 1, 0],
    [0, 0, 1],
    [0, 1, 0],
]

for row in rows:
    ws.append(row)
# Worksheet, enable column, widget column
do_widgets(ws, 2, 3)

PEP8 Results:

Check results
=============

E501:25:80:line too long (85 > 79 characters)
E127:26:46:continuation line over-indented for visual indent
E128:30:22:continuation line under-indented for visual indent
E128:34:22:continuation line under-indented for visual indent
E128:36:22:continuation line under-indented for visual indent

Debug output:

Enable range [0], Widget range [1]
['B6:B10', 'C1:C5']
30
25
10

[30, 25, 10]


texts:
How could I make this code more efficient?  Instead of using many if-statements, should I make a function, array, or switch?  How would I do that?

<form method="post" action="trivia2.php">

How many days are in a week? <input type="text" name="daysweek">

How many days are in a year? <input type="text" name="daysyear">

How many weeks are in a year? <input type="text" name="weeksyear">

What color is the sky? <input type="text" name="colorsky">

what is us president name? <input type="text" name="presidentname">

How many sides does a triangle have? <input type="text" name="sidestriange">

What is the first element on the periodic table of elements? <input type="text" name="firstelement">

Bees create what sweet substance? <input type="text" name="beesubstance">

How many stripes are displayed on the American flag?<input type="text" name="stripes">

<input type="submit" value="Done!"/>
</form>
<?php
$daysweek=$_POST['daysweek'];
$daysyear=$_POST['daysyear'];
$weeksyear=$_POST['weeksyear'];
$colorsky=$_POST['colorsky'];
$presidentname=$_POST['presidentname'];
$sidestriangle=$_POST['sidestriange'];
$firstelement=$_POST['firstelement'];
$beesubstance=$_POST['beesubstance'];
$stripes=$_POST['stripes'];
$wrong=0;
if($daysweek==7){
echo "1. you got the right answer: $daysweek
";
}else {
    $wrong++;
    echo "number 1 is wrong
";}

if($daysyear==365){
echo "2. you got the right answer: $daysyear
";
}else {
    $wrong++;
    echo "number 2 is wrong
";}

if($weeksyear==52){
echo "3. you got the right answer: $weeksyear
";
}else {
    $wrong++;
    echo "number 3 is wrong
";}

if($colorsky=='blue'){
echo "4. you got the right answer: $colorsky
";
}else {
    $wrong++;
    echo "number 4 is wrong
";}

if($presidentname=='obama'){
echo "5. you got the right answer: $presidentname
";
}else {
    $wrong++;
    echo "number 5 is wrong
";}

if($sidestriangle==3){
echo "6. you got the right answer: $sidestriangle
";
}else {
    $wrong++;
    echo "number 6 is wrong
";}

if($firstelement=='hydrogen'){
echo "7. you got the right answer: $firstelement
";
}else {
    $wrong++;
    echo "number 7 is wrong
";}

if($beesubstance=='honey'){
echo "8. you got the right answer: $beesubstance
";
}else {
    $wrong++;
    echo "number 8 is wrong
";}

if($stripes==13){
echo "9. you got the right answer: $stripes
";
}else {
    $wrong++;
    echo "number 9 is wrong
";}
echo "
You have $wrong wrong answers
";
?>


texts: Count distinct primes, discarding palindromes, in under 2 seconds

texts:
Problem Statement

  Generate as many distinct primes P such that reverse (P) is also prime
  and is not equal to P.

  Output:
  Print per line one integer( ≤ 1015 ). Don't print more than
  106 integers in all.

  Scoring:
  Let N = correct outputs. M= incorrect outputs. Your score
  will be max(0,N-M).

  Note: Only one of P and reverse(P) will be counted as correct. If both
  are in the file, one will be counted as incorrect.

  Sample Output
  107 13 31 17 2

  Explanation
  Score will be 1. Since 13,107,17 are correct. 31 is
  incorrect because 13 is already there. 2 is incorrect.

  Time Limit
  2 sec(s) (Time limit is for each input file.)

  Memory Limit
  256 MB

  Source Limit
  25 KB

My Problem

I have tried quite hard to optimize the solution, but the min possible time this program took was : 16.452 secs

My question is, is it possible to optimize the following code further, is it possible to reduce execution time to 2 secs, if we are given that we have to use the Python language.

from time import time
start = time()
lsta=[]   # empty list used to hold prime numbers created by primes function
LIMIT = pow(10,6)

# binary search function
def Bsearch(lsta,low,high,search):
    if low>high:
        return False
    else:
        mid=int((low+high)/2)
        if search<lsta[mid]:
            return(Bsearch(lsta,low,mid-1,search))
        elif search>lsta[mid]:
            return(Bsearch(lsta,mid+1,high,search))
        elif search==lsta[mid]:
            return True
        else:
            return False

# prime number creating function using sieve of Eras** algorithm
def primes(LIMIT):
    dicta = {}
    for i in range(2,LIMIT):
        dicta[i]=1
    for i in range(2,LIMIT):
        for j in range(i,LIMIT):
            if i*j>LIMIT:
                break
            dicta[i*j]=0
    for i in range(2,LIMIT):
        if(dicta[i]==1):
            lsta.append(i)

final = [] # used to hold the final output values
primes(LIMIT)
for i in range(len(lsta)):
    # prime number compared with reversed counterpart
    if(int(str(lsta[i])[::-1])<=lsta[len(lsta)-1]):
        if Bsearch(lsta,i+1,len(lsta)-1,int(str(lsta[i])[::-1])):
            if not(int(str(lsta[i])[::-1])==lsta[i]):
                final.append(str(lsta[i]))

for i in range(len(final)-1,0,-1):
    print(final[i])
print(13)
end=time()
print("Time Taken : ",end-start)


texts: Is this use of (let ... and ...) in OCaml poor style?

texts:
In other languages, I prefer to arrange source files so that simpler and more widely useful concepts are introduced before implementation details, and I try where possible to make complex implementation details top-level functions so that I can separate them out and let the main function read like a high-level algorithm description.

OCaml obviously has an interface/source distinction, but even with a sparse well-documented interface like

type t
(** Blah blah blah *)

val important_operator : t -> t -> t
(** Blah blah blah *)

I've been tempted to do things like

let rec important_operator a b =
  let a', b' = foo a b in
  let a', b' = iterate_until_convergence (=)
                 (fun (a, b) -> bar (baz a b))
                 (a', b') in
  merge a', b'

(* Implementation details *)

and foo a b = ...

and bar x = ...

and baz a b = ...

and merge a b = ...

Is this poor style?  Does it affect the ability of IDE-users to navigate source files?


texts:
I'm pretty new to Java and I've been trying to use top-down design and make my code very readable, so I would appreciate any comments as to the clarity and efficiency of this program.

Looking for feedback on: readability (spacing, comments, etc) and just overall quality of code!

The task is to produce a histogram that shows how many times a certain letter appears in a string.

import java.util.Scanner;

/** This class creates a histogram of the letters in a string. Ie outputs
 ** how many times the letter a appears in the string, the letter b... and so on
 ** until z. Extra challege: only traversing the string once
 **/

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

    Scanner kb = new Scanner(System.in);
    final int LETTERS_IN_ALPHABET = 26;
    int[] letterCounter = new int[LETTERS_IN_ALPHABET]; //holds info on how many
    //times a letter appears. eg letterCounter[0] -> how many times a appears

    System.out.print("Enter string: ");
    String string = kb.nextLine();

    for(int i = 0; i < string.length(); i++){//traversing string
      char letterThere = string.charAt(i);//reads what character is at index
      int placeInLetterCtr = whereInLetterCtr(letterThere);//determining where it should go in array

      letterCounter[placeInLetterCtr] ++;//increasing corresponsing index
    }

    printNumbers(letterCounter);
    printLetters();

  }//end main

/* given a char, determines at what index of the character storage array the
 * char belongs to. Eg, if given the char 'c', it should return int 2
 */
  public static int whereInLetterCtr(char letter){
    int i =0 ;
    for(char comparisonLetter = 'a'; comparisonLetter <= 'z'; comparisonLetter++){
      if(letter == comparisonLetter){
        return i;
      }
      i++;
    }
    return i;
  }//end whereInLetterCtr

/* prints row of numbers */
  public static void printNumbers(int[] array){
    for(int i=0; i<array.length; i++){
      System.out.printf("%4d", array[i]);
    }

    System.out.println();
  }//end printNumbers

/* prints row of letters */
  public static void printLetters(){

    for(char letter ='a'; letter <='z'; letter++){
      System.out.printf("%4c", letter);
    }
  }//end printLetters

}//end class


texts: Use a standard stream, and restore its settings afterwards

texts:
I sometimes find myself changing stream settings (e.g. to output hexadecimal, or to change fill character), and needing to change those settings back afterwards, to avoid perturbing subsequent output.  This gets tedious, so I wrote a short class to act as a scope guard, restoring the settings when it is destructed.

Now we can "borrow" an input or output stream, and give it back in the condition we found it.

#include <ios>
#include <iomanip>

// Members are all public and mutable, so if we really don't want
// to restore any particular part of the state, we can override.
template<class CharT, class Traits = typename std::char_traits<CharT>>
struct save_stream_state
{
    std::basic_ios<CharT,Traits>& stream;
    std::ios_base::fmtflags flags;
    std::locale locale;
    std::streamsize precision;
    std::streamsize width;
    CharT fill;

    save_stream_state(std::basic_ios<CharT,Traits>& stream)
        : stream{stream},
          flags{stream.flags()},
          locale{stream.getloc()},
          precision{stream.precision()},
          width{stream.width()},
          fill{stream.fill()}
    {}

    // deleting copy construction also prevents move
    save_stream_state(const save_stream_state&) = delete;
    void operator=(const save_stream_state&) = delete;

    ~save_stream_state()
    {
        stream.flags(flags);
        stream.imbue(locale);
        stream.precision(precision);
        stream.width(width);
        stream.fill(fill);
    }
};

It's not strictly necessary to delete operator=, as the compiler won't generate one for a class with a non-static reference member, but I think it's better to be explicit there.

Here's a simple test program that shows how it's used.  If you are using an old standards version, the template type deduction won't work - you'll need to specify the guard type in full (save_stream_state<char> and save_stream_state<wchar_t>).

#include <iostream>
int main()
{
    auto test = []() {
        std::cout << std::setw(15) << "Foo" << ' '
        << true << ' ' << 123456 << '\n';
    };
    {
        test();
        const save_stream_state guard{std::cout};
        std::cout << std::setfill('_') << std::left << std::uppercase
                  << std::boolalpha << std::hex << std::showbase;
        test();
    } // stream restored here
    test();

    std::cout << std::endl;

    // Now with wide-character stream:
    auto wtest = []() {
        std::wclog << std::setw(15) << L"Foo" << L' '
        << true << L' ' << 123456 << L'\n';
    };
    {
        wtest();
        // AAA style initialization - and guard multiple streams
        auto const guard = { save_stream_state{std::wclog},
                             save_stream_state{std::wcin} };
        std::wclog << std::setfill(L'_') << std::left << std::uppercase
                   << std::boolalpha << std::hex << std::showbase;
        wtest();
    } // stream restored here
    wtest();
}


texts:
The code loops to display "Hello, World!" ten times. I would like someone to criticize it. I know that's far from being good assembly but I only started learning it a few days ago and I would like to improve.

Would it be better to use the %rax registers and syscall instead of int $0x80 ?

.section .data
  hello: .string "Hello, world!\n"
  len = . -hello

.section .bss

  .macro write str, len
    movl $WRITE, %eax
    movl $STDOUT, %ebx
    movl \str, %ecx
    movl \len, %edx
    int $0x80
  .endm

  .macro exit code
    movl $EXIT, %eax
    movl \code, %ebx
    int $0x80
  .endm

.section .text
  .globl _start

  .equ EXIT, 1
  .equ WRITE, 4
  .equ STDOUT, 1

  _start:
    mov $1, %esi
    l:
      write $hello, $len
      inc %esi
      cmp $10, %esi
      jle l

   exit $0

Also, if someone could explain len = . -hello, that's the only thing I couldn't understand and copied online.


texts:
I was doing this exercise from here.  I made a solution work but can't help feel it could have been done in fewer lines.  I'm quite new to python so I'm not too sure of the little shortcuts.

def shift(S, n):
   word = ''
   for i in S:
      if ord(i) == 32:
         word += ' '
      elif ord(i)+n > 90:
         a = n-(90-ord(i))+64
         word += chr(a)
      else:
         word +=chr(ord(i)+n)
   return word
def TGS(x): # Total goodness of string
   TGC = 0 # Total goodness of character
   for i in x:
      if ord(i) == 32:
         continue
      TGC += letterGoodness[ord(i)-65]
   return TGC
A = input()
LOSS = [shift(A,n) for n in range (1,27)] # List of shifted strings
LOTG = [TGS(x) for x in LOSS]
a = LOTG.index(max(LOTG))
print(LOSS[a])


texts: Laravel 4 clean code review of users controller and model, trying to maintain MVC structure

texts:
I'd like you to review my attempt at creating an authorization class and let me know if there is re-factoring to be done and/or how I can make the code cleaner and abide by the MVC structure.

UsersController.php

<?php

    class UsersController extends BaseController {

    protected $user;

    public function __construct(User $user)
    {
        $this->beforeFilter('csrf', array('on' => 'post'));
        $this->user = $user;
    }

    public function getRegister()
    {
        return View::make('admin.register');
    }

    public function postRegister()
    {
        try
        {
            $this->user->insertUserIntoDatabase(Input::all());
        }
        catch (ValidationError $e)
        {
            return Redirect::to('admin/register')
            ->with('message', 'Something went wrong')
            ->withInput()
            ->withErrors($e->getErrors());
        }

        return Redirect::to('admin/login')
                ->with('message', 'Thank you for creating a new account');
    }

    public function getLogin()
    {
        return View::make('admin.login');
    }

    public function postLogin()
    {
        if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password') ))){
            return Redirect::to('admin/dashboard')->with('message', 'Thanks for logging in');
        }

        return Redirect::to('admin/login')->with('message', 'Your email/password combo failed.');
    }

    public function getLogout()
    {
        Auth::logout();
        return Redirect::to('admin/login')->with('message', 'You have been logged out.');
    }

    public function getDashboard()
    {
        return View::make('admin/dashboard');
    }
}

Users.php (Model)

<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    /**
    * The database table used by the model.
    *
    * @var string
    */
    protected $table = 'users';

    /**
    * The attributes excluded from the model's JSON form.
    *
    * @var array
    */
    protected $hidden = array('password');

    protected $fillable = array('firstname', 'lastname', 'email');
    /**
    * Get the unique identifier for the user.
    *
    * @return mixed
    */
    public function getAuthIdentifier()
    {
        return $this->getKey();
    }

    /**
    * Get the password for the user.
    *
    * @return string
    */
    public function getAuthPassword()
    {
        return $this->password;
    }

    /**
    * Get the e-mail address where password reminders are sent.
    *
    * @return string
    */
    public function getReminderEmail()
    {
        return $this->email;
    }

    public function insertUserIntoDatabase($input)
    {
        $validation = new Services\Validators\Users;

        if ($validation->passes()) {

            $user = new User;
            $user->firstname = Input::get('firstname');
            $user->lastname = Input::get('lastname');
            $user->email = Input::get('email');
            $user->password = Hash::make(Input::get('password'));
            $user->save();
        }

        else {
            $this->errors = $validation->errors;
            throw new ValidationError($validation->errors);
        }
    }
}


texts: Comparison of 2 values based on custom operator

texts:
I am working on a library that parses query strings and evaluates the result for a given context. The query has the format FIELD OPERATOR VALUE (AND|OR) .... The list of operators is constant, but the field's type can be customized (default primary types are supported right now - other types can be added).

To enable the user of the library to overwrite the behavior of the operators, there is a FieldComparer class that evaluates 2 values for a given operator. It uses the default comparer of the type, but can be extended to provide specialized behavior.

The StringFieldComparer is such a specialized comparer for fields of type string. It adds support for wildcards and regex.

Operators

public enum Operator
{
    Equals,
    LessThen,
    LessThenOrEquals,
    GraterThan,
    GraterThanOrEquals,
    NotEquals,
    Matches,
    NotMatches,
}

FieldComparer

public class FieldComparer<TFieldValue>
{
    protected FieldComparer()
    { }

    public virtual bool Compare(Operator op, TFieldValue left, TFieldValue right)
    {
        var comparer = Comparer<TFieldValue>.Default;
        switch (op)
        {
            case Operator.Equals:
                return comparer.Compare(left, right) == 0;
            case Operator.NotEquals:
                return comparer.Compare(left, right) != 0;
            case Operator.GraterThan:
                return comparer.Compare(left, right) < 0;
            case Operator.GraterThanOrEquals:
                return comparer.Compare(left, right) <= 0;
            case Operator.LessThen:
                return comparer.Compare(left, right) > 0;
            case Operator.LessThenOrEquals:
                return comparer.Compare(left, right) >= 0;
            default:
                throw new NotSupportedException($"Operator '{op}' is not supported for type '{typeof(TFieldValue)}'");
        }
    }

    internal static FieldComparer<TFieldValue> Default { get; } = new FieldComparer<TFieldValue>();
}

StringFieldComparer

public class StringFieldComparer : FieldComparer<string>
{
    private readonly Dictionary<string, Regex> myRegexes = new Dictionary<string, Regex>();

    public override bool Compare(Operator op, string left, string right)
    {
        switch (op)
        {
            case Operator.Matches:
            case Operator.NotMatches:
                var regex = GetRegex(left);
                var match = regex.IsMatch(right);
                return op == Operator.Matches ? match : !match;
            case Operator.Equals:
            case Operator.NotEquals:
                regex = GetWildcardRegex(left);
                match = regex.IsMatch(right);
                return op == Operator.Equals ? match : !match;
            default:
                return base.Compare(op, left, right);
        }
    }

    private Regex GetWildcardRegex(string left)
    {
        var pattern = Regex.Escape(left)
            .Replace(@"\*", ".*")
            .Replace(@"\?", ".");

        pattern = "^" + pattern + "$";

        return GetRegex(pattern);
    }

    private Regex GetRegex(string left)
    {
        Regex regex;
        if (!myRegexes.TryGetValue(left, out regex))
        {
            regex = new Regex(left, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            myRegexes.Add(left, regex);
        }
        return regex;
    }
}

Usage

var comparerStr = new StringFieldComparer();
comparerStr.Compare(Operator.Equals, "Hello*", "Hello World"); // true
comparerStr.Compare(Operator.Matches, "He.lo.*", "Hello World"); // true

var comparerInt = FieldComparer<int>.Default;
comparerInt.Compare(Operator.Equals, 1, 1); // true
comparerInt.Compare(Operator.LessThan, 1, 4); // false

I am not really happy with the method StringFieldComparer.Compare because the op will be checked twice for Equals/NotEquals and Match/NotMatch. Is there a way to realize it with only one check without creating the regex unnecessarily?

As always, any feedback is welcome! :)


texts: CodeEval solutions to find trailing strings

texts:
This is a problem in CodeEval, moderate level. The problem is very easy for this level. But I am not able to get more than 60 points for any solution I submit. (Moderate levels highest score is 65 and they take speed and memory into consideration.)

The problem statement is:

  There are two strings: A and B. Print 1 if string B occurs at the end
  of string A. Otherwise, print 0.

  Input

  Hello World,World
  Hello CodeEval,CodeEval
  San Francisco,San Jose

  Output

  1
  1
  0

import java.io.*;

public class Main {
    public static void main (String[] args) throws IOException {
        File file = new File(args[0]);
        BufferedReader buffer = new BufferedReader(new FileReader(file));
        String line;
        String[] words;
        while ((line = buffer.readLine()) != null) {
            System.out.println(trailingStrings(line));
        }
    }

    public static int trailingStrings(String line) {
        int indexOfComma = line.indexOf(",");

        int secondStringLength = line.length()-indexOfComma-1;

        int firstStringLength = indexOfComma;

        if(firstStringLength < secondStringLength) {
            return 0;
        }
        int i = indexOfComma+1;
        int j = indexOfComma - secondStringLength;
        while(j<indexOfComma) {
            if(line.charAt(j) != line.charAt(i)) {
                return 0;
            }
            j++; i++;
        }
        return 1;
    }
}

Memory Usage: 4784128 (bytes)
Speed: 644 ms

If I instead split the line with "," and get the words and use String.endsWith(), I am getting better memory usage. This surprises me because in my first solution I am not creating new String objects, I just use one String.

import java.io.*;
public class Main {
    public static void main (String[] args) throws IOException {
        File file = new File(args[0]);
        BufferedReader buffer = new BufferedReader(new FileReader(file));
        String line;
        String[] words;
        while ((line = buffer.readLine()) != null) {
            words = line.split(",");
            String s1 = words[0];
            String s2 = words[1];
            if(s1.endsWith(s2)){
                System.out.println("1");
            } else {
                System.out.println("0");
            }
        }
    }
}

Memory Usage: 413696 (bytes)
Speed: 1047 ms

Why is my first solution taking up so much memory? Is it because of the int declarations? If I remove int declarations and use the values directly, memory usage reduced by half to 2412544 bytes but still way higher compared to second solution.


texts: Speedup for Project Euler 44 - pentagon numbers

texts:
I'm trying to solve the problems of Project Euler with Haskell within less than 10s with optimized code (ghc -O2). Unfortunately, I'm struggling to find a correct algorithm for Problem 44, which proves the correctness of the solution without setting a predefined upper limit (setting a limit and omitting the proof yields a fraction of a second... unfortunately, you'll almost only find this solution while searching the web, which might be due to a slightly different wording of the question in the past).

  Pentagonal numbers are generated by the formula, \$P_n=n(3n−1)/2\$. The first ten pentagonal numbers are:

  \$1, 5, 12, 22, 35, 51, 70, 92, 117, 145, \ldots\$

  It can be seen that \$P_4 + P_7 = 22 + 70 = 92 = P_8\$. However, their difference, \$70 − 22 = 48\$, is not pentagonal.

  Find the pair of pentagonal numbers, \$P_j\$ and \$P_k\$, for which their sum and difference are pentagonal and \$D = |P_k − P_j|\$ is minimised; what is the value of \$D\$?

The way I want to go is straightforward. Check every possible difference D, till a solution is found. Unfortunately, this means, that a total of around \$1.2\cdot10^{9}\$ checks for pentagonal numbers have to be made.

My solution is the following:

-- calculate the n-th pentagonal number
pn :: Int -> Int
pn n = n*(3*n-1) `quot` 2

-- check if number is pentagonal
ispn :: Int -> Bool
ispn x = x == pn n
       where n = round $ (\x -> 1/6 * (1 + sqrt(1+24*x))) $ fromIntegral x

-- solution finder
-- l  > difference index
-- m  > prior limit of list with relevant pentagonal numbers
-- pl > list of pentagonal numbers
finder :: Int
finder = finder' 1 0 []
finder' :: Int -> Int -> [Int] -> Int
finder' l m pl = if length fpl /= 0
                   then l
                   else finder' (l+1) nm npl
                     where pnl = pn l
                       nm = (pnl - 1) `div` 3 + 1 -- +1 as backup
                       npl = (map pn [(m+1)..nm]) ++ pl
                       -- pnl     -> difference
                       -- x       -> smaller number
                       -- x+pnl   -> larger number
                       -- 2*x+pnl -> sum
                       fpl = filter (\x -> ispn (x+pnl) && ispn (2*x+pnl)) npl

main = print finder

As you can see, the code goes through every pentagonal difference \$D=P_l\$ and checks all relevant numbers by calculating the upper limit for the smaller of both numbers (index nm; above, the distance between two pentagonal numbers is larger than \$D\$) and testing the resulting larger number and sum for their pentagonality.

Profiling with

ghc -O2 -fforce-recomp -rtsopts -prof -fprof-auto main.hs
./main +RTS -sstderr -p

yields an increase of runtime by 200% (from 34s to 103s) and reports the following costs:

COST CENTRE   MODULE  %time %alloc

finder'.fpl.\ Main     30.7    0.0
ispn          Main     23.7    0.0
ispn.n        Main     22.5    0.0
ispn.n.\      Main     12.6    0.0
finder'.fpl   Main     10.0    0.0
finder'.npl   Main      0.1   99.9

I already tried to convert the check for pentagonality to a set lookup, but this didn't really help because this will grow up to 2 million elements. Also, converting the to-be-filtered list to an array or set didn't work as expected.

For a given difference \$D\$ (given by the pentagonal number \$P_l\$ which is pnl = pn l in the code), we know that starting with a given \$k\$ (nm in the code) the difference between \$P_k\$ and \$P_j\$ (\$j > k\$) will always be larger than \$D\$. This starting index can be calculated as \$k = \lfloor\frac{D-1}{3}\rfloor + 1\$.

Is there any way to squeeze some additional time out of this code, preferably while sticking to base libraries?


texts:
I'm doing an easy problem in codechef. Here's the problem statement for maxcount:

  Given an array A of length N, your task is to find the element which
  repeats in A maximum number of times as well as the corresponding
  count. In case of ties, choose the smaller element first.

OK, I cheated. I used std:map because I want to play with it. Please review my code:

#include<iostream>
#include<map>

int main() {
    int test_cases{};
    std::cin >> test_cases;
    for (auto i = 0; i < test_cases; ++i) {
        std::map<int,int> count;
        std::size_t size{};
        std::cin >> size;
        int x{};
        for (std::size_t i = 0; i < size; ++i) {
            std::cin >> x;
            count[x] = ++count[x];
        }
        int number{};
        int numberCount{};
        for (auto& i : count) {
            if (i.second > numberCount) {
                number = i.first;
                numberCount = i.second;
            } else if (i.second == numberCount) {
                if (i.first < number) {
                    number = i.first;
                }
            } else {
                continue;
            }
        }
        std::cout << number << " " << numberCount << '\n';
    }
}

How can I make this better and faster?


texts:
I am new to Go and wrote program to download and save bulk URLs concurrently. It is working correctly, but I would like to make it more efficient and follow best practices.

package main

import (...)

// Connection String
const connectionString = "connectionString"

// Declare Channels
var wg sync.WaitGroup
var ch = make(chan *item) // For success item(s)
var errItems = make(chan *item) // For error item(s)

type item struct {
    id      int
    url     string
    path    string
    content []byte
    err     error
}

func main() {
    start := time.Now()
    var basePath = os.Args[1]
    var from, to = os.Args[2], os.Args[3]
    db, err := sql.Open("sqlserver", connectionString)
    if err != nil {
        log.Fatal(err.Error())
    }
    rows, err := db.Query("SELECT [ImageID],[AccommodationlID],[Link],[FileName] FROM [dbo].[AccomodationImage] where AccommodationlID between @from and @to and FileName not like '%NoHotel.png%'", sql.Named("from", from), sql.Named("to", to))
    if err != nil {
        log.Fatal(err.Error())
    }
    defer db.Close()
    for rows.Next() {
        var item = item{}
        var accId, name string
        _ = rows.Scan(&item.id, &accId, &item.url, &name)
        item.path = fmt.Sprintf("%s\\%s\\%s", basePath, accId, name)
        wg.Add(1)
        go downloadFile(&item)
        go func() {
            select {
            case done := <-ch:
                wg.Add(1)
                go saveAndUpdateFile(db, done)
            case errorItem := <-errItems:
                wg.Add(1)
                go printResult(errorItem)
            }
        }()
    }
    wg.Wait()
    fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
}
func downloadFile(item *item) {
    defer wg.Done()
    resp, err := http.Get(item.url)
    if err != nil {
        item.content, item.err = nil, err
    } else if resp.StatusCode != http.StatusOK {
        item.content, item.err = nil, errors.New(resp.Status)
    } else {
        item.content, item.err = ioutil.ReadAll(resp.Body)
    }
    if item.err != nil {
        errItems <- item
    } else {
        ch <- item
    }
}
func saveAndUpdateFile(db *sql.DB, item *item) {
    defer wg.Done()
    if item.content == nil {
        item.err = errors.New("Content is empty.")
    } else {
        dir := filepath.Dir(item.path)
        err := os.MkdirAll(dir, os.ModePerm)
        if err != nil {
            item.err = err
        } else {
            item.err = ioutil.WriteFile(item.path, item.content, 0644)
        }
    }
    if item.err == nil {
        result, err := db.Exec("UPDATE [dbo].[AccomodationImage] SET IsRead = 1 WHERE ImageID = @id", sql.Named("id", item.id))
        if rows, _ := result.RowsAffected(); rows <= 0 || err != nil {
            item.err = errors.New("Update status failed.")
        }
    }
    if item.err != nil {
        errItems <- item
    }
}
func printResult(item *item) {
    defer wg.Done()
    fmt.Println(item.toString())
}

I use a select statement to implement event so that when errItems or ch channels receive, save or print items. I also surrounded select statement with goroutine to prevent blocking.


texts: Traversing a Binary Search Tree in Swift

texts:
I'm implementing the Binary Search Tree data structure in Swift. It looks like this:

class BinarySearchTree<Key: Comparable, Value> {

    let key: Key
    var value: Value
    var left, right: BinarySearchTree<Key, Value>?

    init(key: Key, value: Value) {
        self.key = key
        self.value = value
    }

    // irrelevant methods for constructing a tree

}

To be able to traverse through it using for (key, value) in myTree { }, BinarySearchTree has to implement SequenceType. This is my first attempt:

extension BinarySearchTree: SequenceType {

    func generate() -> AnyGenerator<(Key, Value)> {
        let leftGenerator = left?.generate()
        let rightGenerator = right?.generate()

        let (key, value) = (self.key, self.value)
        var generatedSelf = false

        return AnyGenerator {
            if generatedSelf { return rightGenerator?.next() }
            else if let next = leftGenerator?.next() { return next }
            else {
                generatedSelf = true
                return (key, value)
            }
        }
    }

}

It works fine, but when I run benchmarks, it's just not as fast as I'd like. Can my traversal algorithm be improved, or is this the fastest way to do it?


texts:
I have the working code but it is pretty dirty. The goal is to input a number  in an application. If it satisfies the min/max logic then jump to the authorization part. Afterwards we can confirm it or reenter it or cancel it. If fails then re-input it. So totally we can only input twice.

 public virtual CallerAuthorization GetCallerAuthorizationResult(decimal debitBalance)
    {
        bool success;
        try
        {
            _debitBalanceAmount = debitBalance;
            GetFundAmountToTransfer();
            success = BuildAmountMinMaxLogicLoop();
        }
        catch (HangupException)
        {
            throw new CallHangupException();
        }
        if (!success)
        {
            success = ReenterAmount();
        }
        if (!success)
            return null;
        AuthorizeTransfer();
        var result = GetProceedInstruction();
        if (result == "1")
            return _callerAuthorization;
        if (result == "2")
        {
            success = ReenterAmount();
            if (!success)
            {
                CancelAuthorization();
                return null;
            }
            AuthorizeTransferReenterAmount();
            return _callerAuthorization;
        }
        if (result == "3")
        {
            CancelAuthorization();
            return null;
        }
        return null;
    }

The other methods:

 public virtual bool BuildAmountMinMaxLogicLoop()
    {
        var isContainingSpecialChars = CheckWhetherInputContainingSpecialChars();
        var isNotAuthorizable = IsNotAuthorizable();
        if (isNotAuthorizable)
        {
            if (isContainingSpecialChars)
            {
                PlayTransferAmountLogicError();
                return false;
            }
            PlayTransferAmountLogicError();
            return false;
        }
        return true;
    }

Also:

public virtual bool ReenterAmount()
    {
        PlayFundAmountToTransferPrompt();
        GetFundAmountToTransfer();
        var isNotAuthorizable = IsNotAuthorizable();
        if (isNotAuthorizable)
        {
            PlayGoodByeMessagePrompt();
            return false;
        }
        return true;
    }

    private void AuthorizeTransferReenterAmount()
    {
        GetAuthorizationResult();
        if (ResultInfo.Code == 0 && AuthorizationInfo.ResultInfo.Code == 0)
        {
            _callerAuthorization.AuthCode = AuthCode;
            _callerAuthorization.FundsTransferInfo = FundsTransferInfo;
        }
    }


texts: Code Smell in Unit Testing Serialized Classes

texts:
I can feel that something is wrong with my code. Here's an excerpt where I think the code smell is...

    internal Hazen(IRawDataReceiver rawDataReceiver) : base(rawDataReceiver)
    {
        SerialPortConnection = rawDataReceiver as SerialPortConnection;
    }
    private SerialPortConnection _serialPortConnection;
    [DataMember] private SerialPortConnection SerialPortConnection
    {
        get
        {
            return _serialPortConnection;
        }
        set
        {
            if(value != null)
            {
                _serialPortConnection = value;
                RawDataReceiver = value;
            }
        }
    }

So basically, Hazen inherits from an abstract class. Notice how I pass the rawDataReceiver to its base class when Hazen's constructor is called. But during deserialization, the constructor is bypassed, thus I included the RawDataReceiver = value to the set accessor of the DataMember property. That is where the code smell is. Is there a better way to do it and am I violating any good practices (such as DRY)?

As regards to unit testing. As you can see, Hazen has a property of type SerialPortConnection as opposed to having it as IRawDataReceiver since you can't serialize an interface. Now, I can still test this class since the base class exposes everything I need for testing. But going back to the previous paragraph, I feel like I'm doing something wrong here.

EDIT: Here's a snippet of the base class

    internal TideDevice(IRawDataReceiver rawDataReceiver)
    {
        RawDataReceiver = rawDataReceiver;
    }
    private IRawDataReceiver _rawDataReceiver;
    protected internal IRawDataReceiver RawDataReceiver
    {
        get
        {
            return _rawDataReceiver;
        }
        protected set
        {
            _rawDataReceiver = value;
            RawDataReceiver.RawDataReceived += RawDataReceiver_RawDataReceived;
        }
    }

EDIT: I have extracted the Task to another method to remove the responsibility of the set accessor. But I'm still in a roadblock on fixing the code smell I initially stated. I editted the code to reflect what I have now.

EDIT2: This code is working really fine whether in unit test and integration test, so I'll leave it as is until someone points out that there is something wrong here or until a problem arises. Thank you very much!


texts:
I need to convert an amount to an Indian currency format:

import decimal
def currencyInIndiaFormat(n):
  d = decimal.Decimal(str(n))
  if d.as_tuple().exponent < -2:
    s = str(n)
  else:
    s = '{0:.2f}'.format(n)
  l = len(s)
  i = l-1;
  res = ''
  flag = 0
  k = 0
  while i>=0:
    if flag==0:
      res = res + s[i]
      if s[i]=='.':
        flag = 1
    elif flag==1:
      k = k + 1
      res = res + s[i]
      if k==3 and i-1>=0:
        res = res + ','
        flag = 2
        k = 0
    else:
      k = k + 1
      res = res + s[i]
      if k==2 and i-1>=0:
        res = res + ','
        flag = 2
        k = 0
    i = i - 1

  return res[::-1]

def main():
  n = 100.52
  print "INR " + currencyInIndiaFormat(n)  # INR 100.52
  n = 1000.108
  print "INR " + currencyInIndiaFormat(n)  # INR 1,000.108
  n = 1200000
  print "INR " + currencyInIndiaFormat(n)  # INR 12,00,000.00

main()

Is there a way to make my currencyInIndiaFormat function shorter, more concise and clean? Is there a better way to write my currencyInIndiaFormat function?

Indian Currency Format:

For example, numbers here are represented as:

1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000

Refer: Indian Numbering System


texts:
I have a string like this:

char buffer[] = "blablabla$GPTXT->SOME CODES HERE<-\r\n$GPRMCblablabla";

It is sent from an external device and changes every 1 second.

The string length is over 1000 bytes and consisted of some standard sentences beginning with "$GPXXX" and ending with CRLF. I've written the following function to extract a specific sentence:

int findString(char *src, char *dst, int desLen, char *what2find, char termChar)
{
    char *temp;
    temp = strstr(src, what2find); ;
    if (temp == NULL)
        return 0;
    else
        temp += strlen(what2find);
    int j = 0;
    while (j<(desLen-1))
    {
        if (temp[j]==termChar)
            break;
        dst[j]= temp[j];
        j++;
    }
    dst[j] = '\0';
    return 1;
}

So:

 int main()
 {
  char buffer[] =
  "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n
  $GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39\r\n
  $GPGSV,2,1,08,01,40,083,46,02,17,308,41,12,07,344,39,14,22,228,45*75\r\n
  $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A\r\n
  $GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48\r\n";

  char dst[50];
  findString(buffer,dst,50,"$GPTXT",'$');
 }

finds and return the desired sentence.

But this code has the following problems:

It is very heuristic. I wonder if there exists some better solutions.
It depends on a character (i.e. '$') for termination. It may terminate after finding a '$' but not "$GPXXX". The optimal solution may find the characters between two strings, e.g. "$GPTXT" and "$GPRMC". I don't know if it is optimally achievable.

Note that the host processor is a 4Mhz ARM MCU!

P.S: The above-mentioned function works fine in my project. I just want to widen my C programming knowledge!

P.S. 2: Both answers from Lundin and David C. Rankin are nice. Unfortunately I can not accept both of them as answer!


texts: React with Typescript - stopwatch component

texts:
I've been trying to learn React and I'm currently building a time-tracking application. The-end goal of the app will be for users to be able to track time against different tasks from different projects.

This is the stopwatch component I have built, with a start, end and reset button, and I would like to get a code review to see if I'm on the right path in terms of clean code and the use of React hooks.

import * as React from "react";
import styled from "styled-components";
import { useState, useEffect } from "react";

export interface IStopwatchProps {}

export interface IStopwatchState {}

const StartButton = styled.button`
  background: green;
  border-radius: 3px;
  border: 2px solid;
  color: white;
  margin: 0 1em;
  padding: 0.25em 1em;
`;

const StopButton = styled.button`
  background: red;
  border-radius: 3px;
  border: 2px solid;
  color: white;
  margin: 0 1em;
  padding: 0.25em 1em;
`;

const ResetButton = styled.button`
  background: white;
  border-radius: 3px;
  border: 2px solid;
  color: black;
  margin: 0 1em;
  padding: 0.25em 1em;
`;

const Stopwatch: React.FunctionComponent<IStopwatchProps> = (
  props
): React.ReactElement => {
  const [seconds, setSeconds] = useState(0);
  const [minutes, setMinutes] = useState(0);
  const [hours, SetHours] = useState(0);
  const [displaySeconds, setDisplaySeconds] = useState("00");
  const [displayMinutes, setDisplayMinutes] = useState("00");
  const [displayHours, setDisplayHours] = useState("00");
  const [isStopWatchRunning, setStopwatchState] = useState(false);
  const toggleState = () => setStopwatchState(!isStopWatchRunning);
  const resetStopwatch = () => {
    setSeconds(0);
    setMinutes(0);
    SetHours(0);
    setDisplaySeconds("00");
    setDisplayMinutes("00");
    setDisplayHours("00");
    setStopwatchState(false);
  };

  const setDisplayValue = (timeValue: number): string => {
    return timeValue > 9
      ? "" + timeValue.toString()
      : "0" + timeValue.toString();
  };

  useEffect(() => {
    let interval: number = 0;
    if (isStopWatchRunning) {
      interval = window.setInterval(() => {
        let displayValueSeconds = setDisplayValue(seconds);
        setDisplaySeconds(displayValueSeconds);
        let displayValueMinutes = setDisplayValue(minutes);
        setDisplayMinutes(displayValueMinutes);
        let displayValueHours = setDisplayValue(hours);
        setDisplayHours(displayValueHours);
        setSeconds(seconds + 1);
        if (seconds === 59) {
          setSeconds(0);
          setMinutes(minutes + 1);
        }
        if (minutes === 59) {
          setMinutes(0);
          SetHours(hours + 1);
        }
      }, 1000);
    } else if (!isStopWatchRunning && seconds !== 0) {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, [isStopWatchRunning, seconds, minutes, hours]);
  return (

      <StartButton onClick={toggleState}>Start</StartButton>
      <StopButton onClick={toggleState}>End</StopButton>
      <ResetButton onClick={resetStopwatch}>Reset</ResetButton>

        {displayHours} : {displayMinutes} : {displaySeconds}

  );
};

export default Stopwatch;
```


texts:
My goal was to create a function that could check for duplicates in an array no matter what the data type was, given that the size of the data type was provided. This was done by using the \$\mathcal{O}(n^2)\$ algorithm and casting to char because of its 1 byte property.

/**
 * Returns count of duplicates in an array
 * @param  a     array to check in
 * @param  items how many entries in array
 * @param  size  size of each entry
 * @return       returns amount of duplicates/conflicts
 */
int dubCount(void *a, size_t items, size_t size){
    int i,j;
    int conflicts = 0;
    char *x = (char *)a;

    for (i = 0; i < items - 1; i++){
        for (j = i + 1; j < items; j++){
            /* Check if chunks are equal, if so count */
            if(memcmp(&(x[i*size]), &(x[j*size]), size) == 0){
                conflicts++;
            }
        }
    }

    return conflicts;
}

The code has been confirmed to work with many data types.
As I'm quite new to the C world, I'd like for someone to point out anything wrong or dangerous in this function.


texts:
I have these 3 methods for ATM mock program.
    public decimal CheckBalance(BankAccount account)
    {
        return account.AccountBalance;
    }

    public void Deposit(BankAccount account, BankTransaction bankTransaction)
    {
        account.AccountBalance += bankTransaction.TransactionAmount;
    }

    public void Withdraw(BankAccount account, BankTransaction bankTransaction)
    {
        if(bankTransaction.TransactionAmount > account.AccountBalance)
        {
            throw new Exception("Withdraw failed. Transaction amount is more than account balance.");
        }

        account.AccountBalance -= bankTransaction.TransactionAmount;
    }

And here are my xUnit unit test methods. The test data is in-memory for this version.
    [Theory, MemberData(nameof(CheckBalanceShouldReturnValidBalanceAmount_Data))]
    public void CheckBalanceShouldReturnValidBalanceAmount(BankAccount account, decimal accountBalance)
    {
        // Act
        var balance = _atm.CheckBalance(account);

        // Assert
        Assert.Equal(accountBalance, balance);
    }

    [Theory, MemberData(nameof(DepositShouldPass_Data))]
    public void DepositShouldPass(BankAccount account, BankTransaction bankTransaction, BankAccount accountExpected)
    {
        // Act
        _atm.Deposit(account, bankTransaction);
        var balance = _atm.CheckBalance(account);

        // Assert
        Assert.Equal(accountExpected.AccountBalance, balance);
    }

    [Theory, MemberData(nameof(WithdrawShouldPass_Data))]
    public void WithdrawShouldPass(BankAccount account, BankTransaction bankTransaction, BankAccount accountExpected)
    {
        // Act
        _atm.Withdraw(account, bankTransaction);
        var balance = _atm.CheckBalance(account);

        // Assert
        Assert.Equal(accountExpected.AccountBalance, balance);
    }

    [Theory, MemberData(nameof(WithdrawAmountMoreThanBalanceShouldFail_Data))]
    public void WithdrawAmountMoreThanBalanceShouldFail(BankAccount account, BankTransaction bankTransaction)
    {
        // Assert and Act
        var exception = Assert.Throws<Exception>(() => _atm.Withdraw(account, bankTransaction));
        Assert.Equal("Withdraw failed. Transaction amount is more than account balance.",
            exception.Message);
    }

All tests passed successfully. Any comments on coding style of unit test?
Edited After Answer with extra class:
namespace XUnitSample.ClassLib.Models
{
    public class BankAccount
    {
        public int Id { get; set; }
        public int BankAccountNo { get; set; }
        public decimal AccountBalance { get; set; }
    }
}

namespace XUnitSample.ClassLib.Models
{
    public class BankTransaction
    {
        public int Id { get; set; }
        public decimal TransactionAmount { get; set; }
        public TransactionTypeEnum TransactionType { get; set; }
    }

    public enum TransactionTypeEnum
    {
        Deposit, Withdraw, ThirdPartyTransfer
    }
}


texts: DRY the throwing of ArgumentNullException("ParameterName")?

texts:
I am using this code in a lot of places:

if (ParameterName == null)
{
    throw new ArgumentNullException("ParameterName");
}

But I think this is not DRY. The only difference here is ParameterName. Is it ok to use these lines everywhere, or is there a way to make it DRY?


texts:
I want to create a function that filters a list with the following criteria:

Strings containing numbers should be removed
Strings containing only one word and first letter of the word is not uppercase should also be removed.
Strings containing more than one word and first letter of each words except first word is not uppercase should also be removed.

The amount of code I am using for this task seems excessive. Can I produce the same results with something more compact? If yes, how?

def list_filter(str_list):
    filtered = []
    is_end = False
    for string in str_list:
        words = string.split(' ')
        for i, word in enumerate(words):
            if i > 0:
                if word[0].isupper():
                    continue
                else:
                    is_end = True
                    break
            if word.isdigit():
                is_end = True
                break
            if len(words) == 1 and not word[0].isupper():
                is_end = True
                break
        if is_end:
            break
        else:
            filtered.append(string)
    return filtered


texts: Wrapper for commonly used database classes

texts:
The main idea behind this class is to create a wrapper for commonly used Database classes. I'm new to SOLID principles and I'm trying to implement them in this library. Does this code adhere to SOLID principles?

//This is the opens the SQL Connection and is placed in DbConnectionSetup.cs

 public interface IConnectionProvider
{
    SqlConnection OConnection(string ConnectionString);
}

public abstract class DatabaseAttributes
{
    private string _connectionString = null;

    private string _command = null;

    public virtual string ValidateConnectionString
    {
        get
        {
            return this._connectionString;
        }
        set
        {
            if (!String.IsNullOrEmpty(value))
            {
                _connectionString = value;
            }
            else
            {
                throw new Exception("No Connection String property detected.");
            }
        }
    }

    public virtual string ValidateSqlCommand
    {
        get
        {
            return this._command;
        }
        set
        {
            if (!String.IsNullOrEmpty(value))
            {
                _command = value;
            }
            else
            {
                throw new Exception("No Command String detected.");
            }
        }
    }
}

[Description("This opens the Sql Connection")]
public class SqlOpenConnection : DatabaseAttributes, IConnectionProvider
{
    public SqlConnection OConnection(string ConnectionString)
    {
        ValidateConnectionString = ConnectionString;

        var _dbConConnection = new SqlConnection(ValidateConnectionString);

        try
        {
            if (_dbConConnection.State != System.Data.ConnectionState.Open)
            {
                _dbConConnection.Open();
            }
        }
        catch (SqlException ex)
        {
            throw new Exception("SqlException thrown", ex);
        }

        return _dbConConnection;
    }
}

/* I have a different class called SqlOps.cs which has the following code:*/

public interface ICommandWithParams
{
    int ExecuteCommandWithParams(string ConnectionString, string Command, Dictionary<string, SqlParameter> Params);
}

//have one function to Insert,Update and delete

public class ExecuteComplexCud : DatabaseAttributes, ICommandWithParams
{
    public int ExecuteCommandWithParams(string ConnectionString, string Command, Dictionary<string, SqlParameter> Params)
    {
        int rc;
        IConnectionProvider _dbCon = new SqlOpenConnection();//Get OConnection from DbConnectionSetup.cs

        ValidateSqlCommand = Command;//Check for Empty Command
        try
        {
            using (SqlCommand _sqlCmd = new SqlCommand(ValidateSqlCommand, _dbCon.OConnection(ConnectionString)))
            {
                _sqlCmd.CommandType = CommandType.Text;
                foreach (var keyValuePair in Params)
                {
                    _sqlCmd.Parameters.Add(keyValuePair.Value);
                }
                rc = _sqlCmd.ExecuteNonQuery();
            }
        }
        catch (SqlException)
        {
            throw;
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            //Close the connection and dispose the object
            IConnectionProvider _dbCloseCon = new SqlCloseConnection();
            _dbCloseCon.OConnection(ConnectionString);
        }

        return rc;
    }
}


texts: Getting better speed from adjusting rows in a DockableToolBar

texts:
I've been using FlexLib for its dockable toolbar feature.  When you shrink the window, it will try to wrap rows if the stage width is less than the row width.  Unfortunately, it won't reverse the process when you expand the window.  To get around that, I wrote the following method to add to the class (the caller is responsible for looping through all current toolbar rows and calling this method on them).

It does the job, but it's not quite as fast as I'd like.  I'm hoping for suggestions to improve both performance and code style, if possible.

/**
 *  @private
 *  Moves ToolBars to the previous row if there is sufficient space in that row to display
 *  another ToolBar properly.
 */
private function unwrapRow(row:HBox, rowIndex:int, toolbar:VBox):void
{
    if (rowIndex == 0) {
        return;
    }
    var prevRow:HBox = HBox(toolbar.getChildAt(rowIndex-1));
    var prevRowW:int = 0;
    var totalW:int = 0;

    //First, get the width of the previous row
    for (var j:int = 0; j < prevRow.numChildren; j++)
    {
        var ch:DockableToolBar = DockableToolBar(prevRow.getChildAt(j));
        prevRowW += ch.measuredWidth;
    }
    //Second, cycle through the children of the "row of interest", moving them
    //up to the previous row if there's room.
    for (var k:int = 0; k < row.numChildren; k++)
    {
        var child:DockableToolBar = DockableToolBar(row.getChildAt(k));
        if ((prevRowW + child.measuredWidth) >= toolbar.width) {
            break;
        }
        //Move child.
        child.parent.removeChild(child);
        prevRow.addChild(child);
        prevRowW += child.measuredWidth;
        --k;
    }
    if (row.numChildren == 0) {
        toolbar.removeChild(row);
    }
}

You can see the rest of this class here (that listing doesn't include my code; I plan to submit this as a patch once it's in good enough shape).


texts:
I have just started learning C# and decided to do some problems from Project Euler. I wrote a code to find 10 001st prime and I thought it would be cool optimize it to make it as fast as possible. How could I improve this to make it even faster?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace primes
{
    class Program
    {
        static void Main(string[] args)
        {
            long prime = 2;
            long largestprime = 2;
            long potentialprime = 3;
            Console.WriteLine("Enter the prime you want to find: ");
            long primenum = Convert.ToInt64(Console.ReadLine());
            long[] primearray = new long[primenum + 1];
            primearray[1] = 2;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            while (prime <= primenum)
            {
                bool isprime = true;
                for (long x = 1; x < prime; x += 3)
                {
                    if (primearray[x] * primearray[x] > potentialprime)
                         break;
                    if (prime > 3 && (potentialprime % primearray[x] == 0 || potentialprime % primearray[x+1] == 0 || potentialprime % primearray[x+2] == 0))
                         isprime = false;
                    if (prime <= 3 && potentialprime % primearray[x] == 0)
                         isprime = false;

                 }
                 if (isprime)
                {
                    primearray[prime] = potentialprime;
                    prime += 1;
                    largestprime = potentialprime;
                }
                potentialprime += 2;
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds + "ms to find ");
            Console.WriteLine(largestprime);
            Console.ReadKey();
         }
    }
}


texts:
I have tried to write a function like memcpy. It copies sizeof(long) bytes at a time.

What surprised me is how inefficient it is. It's just 17% more efficient than the naivest implementation with -O3. With optimizations off it's a lot faster than the naivest, so perhaps the compiler is doing this automatically?

It will copy 1 byte at a time until one of the addresses is aligned, then it will copy sizeof(long) and then 1 byte at a time to avoid writing beyond the bounds.

How can I make this faster?

#include <stdlib.h>

#define THRESHOLD sizeof(long)

static size_t min(size_t a, size_t b)
{
    return (a > b) ? a : b;
}

static void big_copy(void *dest, const void *src, size_t iterations)
{
    long *d = dest;
    const long *s = src;

    size_t eight = iterations / 8;
    size_t single = iterations % 8;

    while(eight > 0){
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        *d++ = *s++;
        --eight;
    }

    while(single > 0){
        *d++ = *s++;
        --single;
    }
}

static void small_copy(void *dest, const void *src, size_t iterations)
{
    char *d = dest;
    const char *s = src;

    while(iterations > 0){
        *d++ = *s++;
        --iterations;
    }
}

void *copy_memory(void *dest, const void *src, size_t size)
{
    //Small size is handled here
    if(size < THRESHOLD){
        small_copy(dest, src, size);
        return dest;
    }

    //Start copying 8 bytes as soon as one of the pointers is aligned
    size_t bytes_to_align = min((size_t)dest % sizeof(long), (size_t)src % sizeof(long));
    void *position = dest;

    //Align
    if(bytes_to_align > 0){
        small_copy(position, src, bytes_to_align);
        position = (char *)position + bytes_to_align;
        src = (char *)src + bytes_to_align;
        size -= bytes_to_align;
    }

    //How many iterations can be done
    size_t safe_big_iterations = size / sizeof(long);
    size_t remaining_bytes = size % sizeof(long);

    //Copy most bytes here
    big_copy(position, src, safe_big_iterations);
    position = (char *)position + safe_big_iterations * sizeof(long);
    src = (char *)src + safe_big_iterations * sizeof(long);

    //Process the remaining bytes
    small_copy(position, src, remaining_bytes);

    return dest;
}


texts:
I made an AsyncLock implementation due to a comment on Hacker News saying JavaScript was missing such a necessary idea. I honestly am not terribly familiar with Threaded programming and the concept of Locks (other than what I've taken in my OS and Concurrency class on USU campus.) I know JavaScript is not threaded but the idea of needing only one thing touching a datastructure still applies. I was wondering if any one could give me some tips to improve this implementation if there are any gaping holes.

I decided to use ESNext features that currently only work in a browser that supports async iterators like Chrome 63 (Chrome Canary). Basically you lock by creating a for await of loop and it will generate one value so you can do some changes then it will unlock the lock once the loop section of the code is finished. Using async generators greatly changed the design and allowed me to automatically unlock a lock if the locked section of code throws an error or breaks out of the loop.

Tell me what you think or what can be improved.

There are 3 files below concatenated if you prefer to look at them individually you can look at the bl.ock or gist link below. The 3 files are: gtor.js, AsyncLock.js, and test.js.

/**
gtor.js
this is an esnext version of part of kriskowal's gtor
*/
function deferred() {
  const def = {}
  def.promise = new Promise((resolve, reject) => {
    def.resolve = resolve
    def.reject = reject
  })
  return def
}

class PromiseQueue {
  constructor (values) {
    this.ends = deferred();
    if (values) {
      values.forEach(this.put, this);
    }
  }

  put(value) {
    const next = deferred();
    this.ends.resolve({
      head: value,
      tail: next.promise
    });
    this.ends.resolve = next.resolve;
  }

  get () {
    var result = this.ends.promise.then(node=>node.head);
    this.ends.promise = this.ends.promise.then(node=>node.tail)
    return result;
  };
}

/**
AsyncLock.js
Contains the main lock mechanism
*/

// private variable work-around
var lengths = new WeakMap();
var setLength = key => lengths.set(key,0);
var incLength = key => lengths.set(key,lengths.get(key)+1);
var decLength = key => lengths.set(key,lengths.get(key)-1);
class PromiseQueueLength extends PromiseQueue {
  constructor () {
    super();
    setLength(this);
  }

  put () {
    super.put();
    incLength(this);
  }

  get () {
    return super.get().then(()=>decLength(this));
  }

}

// private variable work-around
var locks = new WeakMap();
var getLock = (key)=>locks.get(key);
var setLock = (key, val)=>locks.set(key, val);
var lock = (key)=>getLock(key).get();
var unlock = (key)=>{
  var lock = getLock(key);
  if(length == 0) {
    lock.put(true);
  }
}
/**
 * Provides a Async Single-threaded lock mechanism.
 */
class AsyncLock {

  constructor () {
    setLock(this, new PromiseQueueLength());
    getLock(this).put(true);
  }

  async * [Symbol.asyncIterator] () {
    try {
      yield lock(this);
    } finally {
      unlock(this);
    }
  }
}

/**
test.js
*/

var sleep = (ms)=>new Promise(res=>setTimeout(res, ms));

var lock1 = new AsyncLock();

(async () => {
  for await(var _ of lock1) {
    console.log("here 1a");
    await sleep(1000);
    console.log("here 1b")
  }
})();

(async () => {
  for await(var _ of lock1) {
    console.log("here 2a");
    await sleep(1000);
    console.log("here 2b")
  }
})();

/*
When Lock is working should print:
here 1a
here 1b
here 2a
here 2b
*/

If you prefer to look at it as a gist or bl.ock here are the links.


texts:
I wrote a Heap, but the judge system reports "time limit exceeded" in some tests.  I use a sift_down to build, so I don't know why.

Maybe I can improve the build?  Or do I have a bad sift_down?

  Input:

  n commands

  Commands:

  0 xxx, where xxx is a number to add to heap
  1 - extract maximum from heap

#include <iostream>
using namespace std;
int j = 0;

int sift_down(long long int *a, int i, int n){
    int l = 2 * i;
    int r = 2 * i + 1;
    int largest = i;
    if (l <= n && a[l] > a[i])
        largest = l;
    else
        largest = i;
    if (r <= n && a[r] > a[largest])
        largest = r;
    if (largest != i){
        long long int x = a[i];
        a[i] = a[largest];
        a[largest] = x;
        sift_down(a, largest, n);
    }
    return largest;
}

void sift_up(long long int *a, int i){
    long long x = a[i];
    while (i > 1 && a[i / 2] < x){
        a[i] = a[i / 2];
        i /= 2;
    }
    a[i] = x;
 //   cout << i << endl;
}

void Extract_Max(long long int *a, int *n){
    long long int z = a[1];
    a[1] = a[*n];
    (*n)--;
    sift_down(a, j = 1, *n);
    cout << z << endl;
}

int main(){
    int n = 0;
    int k = 0;
    int l = 0; //len
    int command = 0;
    cin >> k;

    long long int *a = new long long int[k + 1]; // n <= k
    for (int i = 0; i < k; i++){
        cin >> command;
        if (command == 0){
            cin >> a[++n];
        }
        else {
                for(int i = n - 1; i >= 1; i--)
                    sift_down(a, i, n);
                Extract_Max(a, &n);

        }
    }

    delete []a;

    return 0;
}


texts:
Following is the piece of code which is working fine, but somehow it looks bit odd to me to have a function inside a render method and using it in both conditions. Let me know how can I improve this react code as showContainer is only adding a wrapper to the function JSX.
Code -
render () {

  const childJsx = () => (<>
Random Child JSX
</>)

  return (
            <>
            { showContainer ?
             <Modal>
                {childJsx()}
             </Modal>
             :

                {childJsx()}

            }
            </>
        )

}


texts: Dynamically generating a HTML option list using Angular.js

texts:
I used step 4 from the Angular tutorial to do some tinkering of my own. In that particular step of the tutorial, a option list is created that determines how a list is sorted (Alphabetically, by age). I tweaked the code to dynamically generate these sorting options from the data set.

Essentially, it takes the first element of the JSON data and creates a option for each of the keys:

<select ng-model="orderProp">
   <option value="{{opt}}" ng-repeat="(opt,value) in phones[0]">{{opt}}</option>
</select>

Any remarks or suggestions?

This is the full index.html file. The example is reproducible by installing the Angular tutorial.

<!doctype html>

  <meta charset="utf-8">
  <title>Google Phone Gallery</title>
  <link rel="stylesheet" href="css/app.css">
  <link rel="stylesheet" href="css/bootstrap.css">

        Search: <input ng-model="query">
        Sort by:
        <select ng-model="orderProp">
            <option value="{{opt}}" ng-repeat="(opt,value) in phones[0]">{{opt}}</option>
        </select>

 Now ordered by {{orderProp}}

            {{phone.name}}

{{phone.snippet}}

and the JSON data:

  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.',
     'age': 1},
    {'name': 'Motorola XOOM™ with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.',
     'age': 2},
    {'name': 'MOTOROLA XOOM™',
     'snippet': 'The Next, Next Generation tablet.',
     'age': 3}
  ];


texts: Division safe from overflow for fixedpoint

texts:
So I was investigating overflow safe division for a class that uses an int64 member with a given RESOLUTION ( 10000 ) for the fractional part. To preserve precision in the fractional part during an easy division you would multiply by the resolution first, which if the number is large enough results in an overflow. I came up with an algorithm to divide without overflow but I think it could probably be optimized better, I just can't see at first glance how:

int64 divideOverflowSafe( const int64 Lhs, const int64 Rhs ) const
{
    // The idea here is simple, split Lhs * RESOLUTION / Rhs into two separate divisions to avoid the multiplication by RESOLUTION and thus avoid the overflow
    const int64 FracPart = Lhs % RESOLUTION;
    const int64 DecPart = Lhs - FracPart;

    // Just dividing the integral part means there's already an inherent resolution buffer for precision. We then need to also calculate the remainder, which is small enough that it can be multiplied by RESOLUTION ( and needs to be, to maintain precision )
    const int64 Res1 = DecPart / Rhs;
    const int64 Res1Remainder = ( DecPart % Rhs ) * RESOLUTION / Rhs;

    // The fractional part is small enough to be multiplied by RESOLUTION, again for precision reasons
    const int64 Res2 = FracPart * RESOLUTION / Rhs;

    // At the end we add everything back together to obtain the result
    const int64 Res = Res1 * RESOLUTION + Res1Remainder + Res2;
    return Res;
}


texts:
I've been learning about Monte Carlo simulations on MIT's intro to programming class, and I'm trying to implement one that calculates the probability of flipping a coin heads side up 4 times in a row out of ten flips.

Basically, I calculate if the current flip in a 10 flip session is equal to the prior flip, and if it is, I increment a counter. Once that counter has reached 3, I exit the loop even if I haven't done all 10 coin flips since subsequent flips have no bearing on the probability. Then I increment a counter counting the number of flip sessions that successfully had 4 consecutive heads in a row. At the end, I divide the number of successful sessions by the total number of trials.

The simulation runs 10,000 trials.

def simThrows(numFlips):
    consecSuccess = 0   ## number of trials where 4 heads were flipped consecutively
    coin = 0  ## to be assigned to a number between 0 and 1
    numTrials = 10000
    for i in range(numTrials):
        consecCount = 0
        currentFlip = ""
        priorFlip = ""
        while consecCount <= 3:
            for flip in range(numFlips):
                coin = random.random()
                if coin < .5:
                    currentFlip = "Heads"
                    if currentFlip == priorFlip:
                        consecCount += 1
                        priorFlip = "Heads"
                    else:
                        consecCount = 0
                        priorFlip = "Heads"
                elif coin > .5:
                    currentFlip = "Tails"
                    if currentFlip == priorFlip:
                        consecCount = 0
                        priorFlip = "Tails"
                    else:
                        consecCount = 0
                        priorFlip = "Tails"
            break
        if consecCount >= 3:
            print("Success!")
            consecSuccess += 1
    print("Probability of getting 4 or more heads in a row: " + str(consecSuccess/numTrials))

simThrows(10)

The code seems to work (gives me consistent results each time that seem to line up to the analytic probability), but it's a bit verbose for such a simple task.  Does anyone see where my code can get better?


texts:
I have to reverse the string "He is the one" to "one the is He".  I have written some programs in Java but am looking for other best solutions.  Suggest any possible ways to minimize the current program.

First approach:

class StringRev{
    public static void main(String args[]){
    String str = "He is the one";
    String temp = "";
    String finalString = "";
        for(int i =str.length()-1;i>=0;i--){
            temp +=i!=0?str.charAt(i):str.charAt(i)+" ";
            if(str.charAt(i) == ' '||i==0){
                for(int j=temp.length()-1;j>=0;j--){
                    finalString += temp.charAt(j);
                }
                temp = "";
            }
        }
            System.out.println(finalString);
    }
}

Second approach:

class StringRev2{
    public static void main(String args[]){
    String str[] = "He is the one".split(" ");
    String finalStr="";
        for(int i = str.length-1; i>= 0 ;i--){
            finalStr += str[i]+" ";
        }
        System.out.println(finalStr);
    }
}


texts: Stopwatch exception implementation in C#

texts:
I'm new to C# programming and has been following a certain intermediate tutorial that has asked me to write a stopwatch simulation code that includes an exception system:

  Exercise 1: Design a Stopwatch

  Design a class called Stopwatch. The job of this class is to simulate a stopwatch. It should provide two methods: Start and Stop. We call the start method first, and the stop method next. Then we ask the stopwatch about the duration between start and stop. Duration should be a value in Timespan. Display the duration on the console.

  We should also be able to use a stopwatch multiple times. So we may start and stop it and then start and stop it again. Make sure the duration value each time is calculated properly.

  We should not be able to start a stopwatch twice in a row (because that may overwrite the initial start time). So the class should throw an InvalidOperationException is it's started twice.

  Educational tip: The aim of this exercise is to make you understand that a class should be always in a valid state. We use encapsulation and information hiding to achieve that. The class should not reveal its implementation detail. It only reveals a little bit, like a black box. From the outside, you should not be able to misuse a class because you shouldn't be able to see the implementation detail.

Transcribed from:

I have implemented code that does this exactly, however, I want to learn how to optimize my code to use fewer lines and make it more readable.

using System;

namespace Stopwatch_Training
{
    class Program
    {
        public class Stopwatch
        {
            private DateTime _startTime;
            private DateTime _stopTime;
            private TimeSpan _duration;
            public DateTime StartTime()

            {
                _startTime = DateTime.Now;
                return _startTime;
            }

            public DateTime Stoptime()

            {
                _stopTime = DateTime.Now;
                return _stopTime;
            }
        }

        static void Main(string[] args)

        {
            var stopwatch = new Stopwatch();
            int input1;
            DateTime starTime;
            DateTime endTime;
            double duration;
            int counter = 0;

            while (true)

            {
                Console.Write("1-Start Timer\n2-Stop Timer\n");
                input1 = Convert.ToInt32(Console.ReadLine());
                if (input1 == 1)
                {
                    starTime = stopwatch.StartTime();
                    counter = 1;
                }
                else
                {
                    throw (new InvalidOperationException("Please Start the timer with 1"));
                }

                Console.WriteLine("Please enter '2' to stop the timer whenever you want");
                input1 = Convert.ToInt32(Console.ReadLine());
                if (input1 == 2)
                {
                    endTime = stopwatch.Stoptime();
                    counter = 0;

                }

                else
                {
                    throw (new InvalidOperationException("Please end the timer with 2"));
                }
                if (counter == 1)
                {
                    throw (new InvalidOperationException("stuff"));
                }
                duration = (endTime - starTime).TotalSeconds;
                if (duration > 60.0)
                {
                    duration = (endTime - starTime).TotalMinutes;
                    Console.WriteLine(duration + "m");
                }
                else
                {

                    Console.WriteLine(duration + "s");
                }

            }
        }
    }
}


texts: Preventing SQL Injection in user registration routine

texts:
At the moment is my code secure for SQL injections and so forth? I still need to hash passwords and make sure fields are valid and so forth.

<?php

try{
    $handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e){
    echo $e->getMessage();
    die();
}

$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];

$sql = "INSERT INTO userinfo (name ,username, email, password) VALUES (:name,:username,:email,:password)";
$query = $handler->prepare($sql);

$query->execute(array(
    ':name' => $name,
    ':username' => $username,
    ':email' => $email,
    ':password' => $password
));

?>


texts: Rspec unit test for updating a property of a model

texts:
I know how to write simple RSpec tests and unit tests. I just want to know if this is good enough or if there are any improvements I can make.

I intend to test the the toggle_property method of the TaskItemUserReference model which updates the property, completed from false to true or vice versa.

Relationships

User has many Tasks through TaskUserReference
Task has many Users through TaskUserReference

TaskItem has many Users through TaskItemUserReference
User has many TaskItem through TaskItemUserReference

#Factories

FactoryGirl.define do
  factory :task do
    name Faker::Lorem.sentence(2)
  end
end

FactoryGirl.define do
  factory :task_user_reference do
    user
    task
  end
end

FactoryGirl.define do
  factory :task_item do
    name Faker::Lorem.sentence(3)
    task
  end
end

FactoryGirl.define do
  factory :task_item_user_reference do
    task_item
    user
    active true
    completed false
  end
end

# RSPEC test
require "rails_helper"

RSpec.describe Task, type: :model do

  let(:owner) { create(:user) }
  let(:task) { create(:task, owner: owner) }
  let(:user) { create(:user) }
  let(:task_item) { create(:task_item, task: task) }

  before do
    user.tasks << task
    user.task_item_user_references.create(
      user_id: user.id,
      completed: true,
      task_item: task_item
    )
  end

  describe "task_items" do
    it "updates status" do
      task_item_user_reference = user.task_item_user_references.first
      task_item_user_reference.toggle_property(:completed)

      expect(task_item_user_reference.completed).to eq(false)
     end
  end
end


texts: Parsing users from a list of commands for email notifications

texts:
I want to make a list of the last words on each line of a file that looks like this:

casper@casper-PC ~/scripts -> cat /tmp/foo
update PTMM_ARCHIVE.FASTTRACK_USER set user_name = 'monohajoxx' where user_name = 'monohajo'
update PTMM_ARCHIVE.FASTTRACK_USER set user_name = 'wuemxx' where user_name = 'wuem'
update PTMM_ARCHIVE.FASTTRACK_USER set user_name = 'taraziemxx' where user_name = 'taraziem'
update PTMM_ARCHIVE.FASTTRACK_USER set user_name = 'mullankexx' where user_name = 'mullanke'
update PTMM_ARCHIVE.FASTTRACK_USER set user_name = 'fernanjaxx' where user_name = 'fernanja'casper@casper-PC ~/scripts ->

As you can see, the file lacks a newline at the end: 'fernanja'casper@casper-PC ~/scripts ->. I hate that when the prompt gets mixed in with the data -or the output. It's a minor point, but it makes the text on the terminal jumbled and confusing.

Also, I use tr all the time to fix my one-liners. I am looking for another way to print out the names in a horizontal line instead of a vertical list.
I echo'd a new line but it printed it out literally.

09:38 PM Tue Dec 01$ awk '{print $NF}' /tmp/foo | tr -d "'" | tr "\n" ", \s" ; echo  "\n"
monohajo,wuem,taraziem,mullanke,fernanja,\n
walt@walt-PC ~/scripts ->
09:55 PM Tue Dec 01$

I do not want this:

monohajo
wuem
taraziem
mullanke
fernanja

I want this:

monohajo, wuem, taraziem, mullanke, fernanja

These are minor points, but when you do this 20 or thirty times a day, it gets tiring. It would be great just to do this in pure bash, with a while loop. Instead of vertical lists, I need horizontal lists which can be cut and pasted into emails, so I can tell bosses that I performed updates on this list of people.


texts: Am I optimally closing this modal window?

texts:
I have a modal window that needs to be closed, obviously.  I've created this piece of code that works okay. But is there a way to optimize it?

// close the modal window
$('.modal-close').click(function(e) {
    $('#modal').hide();
    $('#modal-overlay').hide();

    e.preventDefault();
});

$(document).keydown(function(e) {
    if (e.keyCode == 27) { // if Esc key is pressed
        $('#modal').hide();
        $('#modal-overlay').hide();
    }

    if (e.keyCode == 9) { // cancel the Tab key
        return false;
    }
});


texts: Portably get one character from standard input using standard library only

texts:
While translating an old Basic game to C, I found myself needing a function to get one character from the keyboard.  You can't do this with common standard C library functions like getchar() because the standard input stream is line-buffered (i.e. it will store whole line of input, including the terminating \n, in its internal buffer although getchar() only uses its first character. Subsequent calls to getchar() will consume buffer's remaining characters until exhausted and only then will it resume accepting user's new inputs).  This causes problems because if you need inputting twice, the second time you will get some unexpected value instead of letting user entering second character.

Now, I know the way around this is to use operating system calls such as ioctl and read to set input to an unbuffered state and read a character (or better yet use a library like Curses which abstracts away all this in a cross-platform way.) but I started wondering if it was possible to do this entirely via the standard C library.

My first attempt was to empty out the remaining characters in stdin's buffer by adding a call to:

fflush(stdin);

...after calling getchar() but this didn't do anything.

My next attempt was to try and take stdin out of line buffer mode like this:

setvbuf(stdin, NULL, _IONBF, 0);

I had high hopes this would work but actually it seems calling setvbuf on stdin is undefined behavior.  It certainly does not work on Linux.

So finally I came up with this function.  It works but I have a nagging feeling it could be improved.  What do you think?

int getkey(const char* prompt = "") {
    /* Print the prompt message if there is one */
    if (strcmp(prompt, "") != 0) {
        puts(prompt);
    }

    /* Get a character and examine it.  If it is a newline from a previous
       call to this function eat it otherwise put it back in the buffer. */
    int c = getchar();
    if (c != '\n') {
        ungetc(c, stdin);
    }

    /* This is the character we really want. */
    c = getchar();

    /* Drain the input buffer so any extra characters which were pressed are
       discarded except for newline which is needed to actually send the input
       to stdin. */
    int next;
    while(!feof(stdin) && next != '\n') {
        next = getchar();
    }

    return c;
}


texts: How can I clean up (DRY) this verbose jQuery code?

texts:
I had posted this on StackOverflow — someone pointed me here.

My code is working, but it's incredibly verbose and I know that it can be made more compact. I just don't know how :-)

I'm building an audio portfolio. When a button is clicked, a sequence of events happens. When another button is clicked, all other active buttons are killed and the sequence for that specific button runs.

The buttons are invisible and are placed on a visualisation of a switch. When clicked, an image of the switch flicked into its "activated" state has its class of "display: none" removed. That should give the user the impression that actually flicking a switch starts playing audio.

Like so:

$(function(){

  // FIRST BUTTON
  $('.button01').click(function() {
    if ($('.switch01').hasClass('activated')){

    // So if button.button01 is clicked and img.switch01 has class "activated"

      // Kill all audio
      $('audio').each(function(){ this.pause(); this.currentTime = 0; });

      // Turn this switch off
      $('.switch01').removeClass('activated');

      // Kill all info cards showing the playback controls
      $('.audio-info-card').addClass('d-none');
    } else {

    // If button.button01 is clicked and img.switch01 DOESN'T have class "activated"

      // Turn all other switches off
      $('.switch02, .switch03').removeClass('activated');

      // Kill all info cards
      $('.audio-info-card').addClass('d-none');

      // Activate this switch and info card
      $('.switch01').addClass('activated');
      $('.audio-info-card#card01').removeClass('d-none');

      // Kill all audio
      $('audio').each(function(){ this.pause(); this.currentTime = 0; });

      // Start this audio
      $('#audio01-player')[0].play();
    }
  });

  // SECOND BUTTON
  $('.button02').click(function() {
    if ($('.switch02').hasClass('activated')){

    // So if button.button02 is clicked and img.switch02 has class "activated"

      // Kill all audio
      $('audio').each(function(){ this.pause(); this.currentTime = 0; });

      // Turn this switch off
      $('.switch02').removeClass('activated');

      // Kill all info card showing the playback controls
      $('.audio-info-card').addClass('d-none');
    } else {

    // If button.button02 is clicked and img.switch02 DOESN'T have class "activated"

      // Turn all other switches off
      $('.switch01, .switch03').removeClass('activated');

      // Kill all info cards
      $('.audio-info-card').addClass('d-none');

      // Activate this switch and info card
      $('.switch02').addClass('activated');
      $('.audio-info-card#card02').removeClass('d-none');

      // Kill all audio
      $('audio').each(function(){ this.pause(); this.currentTime = 0; });

      // Start this audio
      $('#audio02-player')[0].play();
    }
  });

There are 16 buttons. I realize this code is stupid but JS / jQuery isn't my strong suit :-D

Fortunately, the code works, but any help making this simpler would be greatly appreciated!


texts: Base class for subclasses that can track their own instances

texts:
I'm new to Python, with some background in Java and C# from a while ago, and more recently in scripting worlds like Bash and AppleScript.

I wanted to be able to create classes that could

report their instances
limit their number of instances.

Synthesizing various answers from Stack Overflow and general trial and error, I developed the following base class that can be inherited from when creating new classes. I'd like feedback on:

Could I be doing it better/more elegantly/more efficiently?
Does the code style follow PEP 8?
Anything else you think a Python noob should be considering?

#! /usr/bin/env python

# for Python 2.6/2.7; omit for Python 3.x
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division

# technique for instance-tracking class is adapted from:
#   http://stackoverflow.com/a/23844406/3531387
class SelfTrackingClass(object):
    """Use as base class for classes that can report their instances.

    Subclass.instances: get list of object instances.
    Subclass.max: get/set max number of instances; default is unlimited.
    """

    # set in Subclass to limit number of instances of Subclass
    max = None

    # key: class name as string, value: list of weakrefs to instances
    _classnames = {}

    # technique for "class properties" is adapted from:
    #   http://stackoverflow.com/a/7864317/3531387
    class ClassProperty(property):
        def __get__(self, cls, owner):
            return self.fget.__get__(None, owner)()
    @ClassProperty
    @classmethod
    def instances(cls):
        """Return tuple of instances for this class, or None if none."""
        try:
            return tuple(
              [instance() for instance in cls._classnames[cls.__name__]])
        except KeyError:
            return None

    def __new__(cls):
        """Create instance, if not over limit, and store ref to it."""
        import weakref
        if (cls.__name__ not in cls._classnames):
            cls._classnames[cls.__name__] = []
        # enforce maximum number of instances
        if ((cls.max is not None) and (len(cls.instances) >= cls.max)):
            raise Exception("Too many instances of class: " + cls.__name__)
        instance = object.__new__(cls)
        cls._classnames[cls.__name__].append(weakref.ref(instance))
        return instance

    def __del__(self):
        """Remove ref to dead instance from list of instances."""
        for instance in self.__class__._classnames[self.__class__.__name__]:
            if (instance() is None):
                self.__class__._classnames[
                  self.__class__.__name__].remove(instance)
        if (len(self.__class__._classnames[self.__class__.__name__]) == 0):
            del self.__class__._classnames[self.__class__.__name__]

Example:

class MyClass1(SelfTrackingClass):
    pass

class MyClass2(SelfTrackingClass):
    pass

a = MyClass1()
b = MyClass1()
print(MyClass1.instances)
c = MyClass2()
print(MyClass2.instances)
del a
print(MyClass1.instances)
del b
print(MyClass1.instances)
MyClass1.max = 2
d = MyClass1()
e = MyClass1()
f = MyClass1()

Output:

(<__main__.MyClass1 object at 0x10e61c4d0>, <__main__.MyClass1 object at 0x10e61c7d0>)
(<__main__.MyClass2 object at 0x10e61c810>,)
(<__main__.MyClass1 object at 0x10e61c7d0>,)
None
Traceback (most recent call last):
  File "./tst2.py", line 78, in <module>
    f = MyClass1()
  File "./tst2.py", line 46, in __new__
    raise Exception("Too many instances of class: " + cls.__name__)
Exception: Too many instances of class: MyClass1


texts: Find the kth prime and all the primes below it

texts:
It works by finding 2n+1 with n from 1 to k, but not where 2n+1 would be divisible by one of the already known primes. I'd like to know if the program can find every prime, and if so, how it compares to the efficiency of other algorithms.

n=1
k=input()
primes=[2]
def f(n):
   b, a = 1, 1
   for i in primes:
      a=((2*n+1)%i)
      b=b*a
   return b
while k > n:
   if f(n) >= 1:
      primes.append((2*n)+1)
      n=n+1
   else:
      n=n+1
      k=k+1
print primes