texts: PHP spell checker with suggestions for misspelled words

texts:
I built a simple PHP spellchecker and suggestions app that uses PHP's similar_text() and levenshtein() functions to compare words from a dictionary that is loaded into an array.

How it works is first I load the contents of the dictionary into an
array.
I split the user's input into words and spell check each of the
words.
I spell check by checking if the word is in the array that is the
dictionary.
If it is, then I echo a congratulations message and move on.
If not, I iterate through the dictionary-array comparing each word, in the dictionary-array, with the assumed misspelling.
If the inputted word, in lower-case and without punctuation, is 90%
or more similar to a word in the dictionary array, then I copy that
word from the dictionary array into an array of suggestions.
If no suggestions were found using the 90% or higher similarity
comparison, then I use levenshtein() to do a more liberal comparison
and add suggestions to the suggestions array.
Then I iterate through the suggestions array and echo each
suggestion.

I noticed that this is running slowly. Slow enough to notice. And I was wondering how I could improve the speed and efficiency of this spell checker.

Any and all changes, improvements, suggestions, and code are welcome and appreciated.

Here is the code (For syntax highlighted code, please visit here):

<?php
function addTo($line){
    return strtolower(trim($line));
}
$words = array_map('addTo', file('dictionary.txt'));
$words = array_unique($words);
function checkSpelling($input, $words){
$suggestions = array();
if(in_array($input, $words)){
    echo "you spelled the word right!";
}
else{
    foreach($words as $word){
        $percentageSimilarity=0.0;
        $input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
        similar_text(strtolower(trim($input)), strtolower(trim($word)), $percentageSimilarity);
        if($percentageSimilarity>=90 && $percentageSimilarity<100){
                if(!in_array($suggestions)){
                    array_push($suggestions, $word);
        }
        }
    }
if(empty($suggestions)){
    foreach($words as $word){
    $input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
    $levenshtein = levenshtein(strtolower(trim($input)), strtolower(trim($word)));
    if($levenshtein<=2 && $levenshtein>0){
         if(!in_array($suggestions)){
           array_push($suggestions, $word);
          }
        }
    }
}
    echo "Looks like you spelled that wrong. Here are some suggestions:
";
         foreach($suggestions as $suggestion){
             echo "
".$suggestion."
";
         }
    }
}
if(isset($_GET['check'])){
    $input = trim($_GET['check']);
    $sentence='';
    if(stripos($input, ' ')!==false){
    $sentence = explode(' ', $input);
    foreach($sentence as $item){
        checkSpelling($item, $words);
    }
    }
    else{
         checkSpelling($input, $words);
    }
 }
 ?>
<!Doctype HTMl>

        <meta charset="utf-8" />
        <title>Spell Check</title>

        <form method="get">
             <input type="text" name="check" autocomplete="off" autofocus />
        </form>


texts:
I'm not much of a jQuery coder (more of a PHP coder), except to call a few get values out of class and id and Ajax calls.  However, I need to make a checkout system work and one thing I would like to do is to put a loading wait while I send a form through Ajax.  When it's finished, it would redirect the user.

So on click:

load the loading spinner
fade the background out
Ajax call
when Ajax is done submitting a form which indirectly redirects.

Here is my code, following why I don't like it:

jQuery.fn.center = function () {
            this.css("position","absolute");
            this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
            this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
            return this;
        }

        $( ".buttonFinish" ).on('click', function(event) {
            $('body').fadeOut('slow');
            $('#loader').center();
            $('#loading').center();
            $('#loader').show();
            $('#loading').show();
            //Use the above function as:
            var request = $.ajax({
                url:'{{ URL::route('saveCart') }}',
                type:'POST'
                });

                request.done(function(msg) {
                    $('.order_number').val(msg);
                      $('#summaryForm').submit();
                      event.preventDefault();
                });
            return false;
        });

Let's get a few questions out of the way: {{UR::route('')}} is laravel syntax to call the routing name for URL. loader/loading are two div that I have for the spinner one is text the other is an animation through CSS. (I'd rather CSS it than to load a pix, but I am aware that loader.gif can be small)

My issue (and feeling) that this can be better. I am using CSS with display:none to hide my two div, and then I call fadeOut, show, show, and center center function to center my loading Ajax in order to center things. Is there a compact way to achieve all the 4 steps needed in a clean way?


texts:
Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].

If there is no solution possible, return 0.

Example :

A : [3 5 4 2]

Output : 2
for the pair (3, 4)

My Code :

def maximumGap(self, A):
    if len(A)==1: return  0
    a_list = sorted(([Val,indeX] for indeX,Val in enumerate(A)), reverse=True)

    rest = [indeX for val,indeX in a_list] # rest stores all the index from a_list which is sorted in decreasing order
    len_rest = len(rest)
    del a_list[:]
    results = []

    for i in range(len_rest):
        if i != len_rest-1:
            results.append(rest[i] - min(rest[i+1:]))
        else: continue

    ans = max(results)
    if ans < 0: return 0
    else: return ans

Sample input taken for explanation:

A = [34, 8, 10, 3, 2, 80, 30, 33, 1]

Brief summary of my algorithm:

1. a_list is a list of lists which will store all the numbers from the orginal list (list A) in sorted order along with their indexes.

`a_list = [[80, 5], [34, 0], [33, 7], [30, 6], [10, 2], [8, 1], [3, 3], [2, 4], [1, 8]]`

2. rest is a list which will store all the indexes from a_list.

`rest = [5, 0, 7, 6, 2, 1, 3, 4, 8]`

(After this, a_list is deleted to empty the space)

3. Now, the crux of the logic is:
Since list is sorted in descending order, I need not take care of the constraint: A[i] <= A[j]

I will just iterate the list: rest and in each iteration, say 0th iteration, rest[0] = 5 is subtracted from the smallest remaining elements in list: rest

Each result of the iteration is stored in list: results

4. results = [5, -1, 6, 5, 1, -2, -1, -4]

5. Max of list results will give me the answer.

(It is important to note that while sorting the list we must also store the original index of the values instead of blindly sorting it.)

Now, coming to the actual problem:

On submitting my solution at interviewbit website, my code is giving correct answers to all test cases but time limit is exceeded

I am not able to figure out what how to optimise this further.

Time complexity of my code,correct me if i am wrong, is O(N log N)

Sorting takes O(N log N) time in the worst case when using sort function in python.

My main question is how to optimise this code further?

Found on www.interviewbit.com


texts:
I've written a function to call with the deferred library to generate a large task queue, and at first without the recursion it timed out (deadlineexceeded) so now I'm trying with a recursion but is it safe that the function will terminate? I actually ran it with GAE and it did the correct task - deleted all the empty blobs that were written previously because of a bug. (It seems that empty blobs with 0 bytes get written several times a day and the code is to delete those blobs.)

def do_blobs_delete(msg=None, b=None, c=None):
    logging.info(msg)
    edge = datetime.now() - timedelta(days=750)
    statmnt = "WHERE size < 1" # size in bytes
    logging.debug(statmnt)
    try:
        gqlQuery = blobstore.BlobInfo.gql(statmnt)
        blobs = gqlQuery.fetch(999999)
        for blob in blobs:
            if blob.size < 1 or blob.creation < edge:
                blob.delete()
                continue
    except DeadlineExceededError:
        # Queue a new task to pick up where we left off.
        deferred.defer(do_blobs_delete, "Deleting empty blobs", 42, c=True)
        return
    except Exception, e:
        logging.error('There was an exception:%s' % str(e))


texts: Simpson's method for numerically computing the integration of a function

texts:
I have implemented the Simpson's rule for numerical integration.

Check this video for the implemented function.

namespace Simpsons_method_of_integration
{
    //https://www.youtube.com/watch?v=ns3k-Lz7qWU
    using System;

    public class Simpson
    {
        private double Function(double x)
        {
            return 1.0 / (1.0 + Math.Pow(x, 5)); //Define the function f(x)
        }

        public double Compute(double a, double b, int n)
        {
            double[] x = new double[n + 1];

            double delta_x = (b - a) / n;

            x[0] = a;

            for (int j = 1; j <= n; j++)//calculate the values of x1, x2, ...xn
            {
                x[j] = a + delta_x * j;
            }

            double sum = Function(x[0]);

            for (int j = 1; j < n; j++)
            {
                if (j % 2 != 0)
                {
                    sum += 4 * Function(x[j]);
                }
                else
                {
                    sum += 2 * Function(x[j]);
                }
            }

            sum += Function(x[n]);

            double integration = sum * delta_x / 3;

            return integration;
        }
    }

    public class MainClass
    {
        public static void Main()
        {
            Simpson simpson = new Simpson();
            double a = 0d;//lower limit a
            double b = 3d;//upper limit b
            int n = 6;//Enter step-length n

            if (n % 2 == 0)//n must be even
            {
                Console.WriteLine(simpson.Compute(a, b, n));
            }
            else
            {
                Console.WriteLine("n should be an even number");
            }

            Console.ReadLine();
        }
    }
}

Output:

1.07491527775614

How can I make this source code more efficient?


texts:
I have recently written the program for the Sherlock and The Beast' HackerRank challenge. That's working fine, but the problem is that it takes too much time if a big number is given as a input.  I would like you to help me out in optimizing my code so that it could run under 16 seconds, which is needed.

from collections import Counter
def isDecent(n):
    digits = list(map(int, str(n)))
    if not set(str(n)).issubset('35'): return False
    threes = Counter(digits)[3]
    fives = Counter(digits)[5]
    if threes % 5 == 0 and fives % 3 == 0: return True
    else: return False

inps = []
decents = []
t = int(input())
for i in range(t): inps.append(int(input()))
for inp in inps:
    if inp == 1:
        decents.append(-1)
        continue
    n=2
    while True:
        if(isDecent(n) and len(str(n)) == inp): break
        n+=1
    if n != 2: decents.append(n)
    else: decents.append(-1)
for decent in decents: print(decent)

Is there any thing that could be used to optimize it?


texts: Interop: Return Parameter Method as Void

texts:
For interop purpose, this is something that I always do (C#):

 public static extern BigObject InteropWithCPlusPlus();

where BigObject is ( you guess it) a big object, it's not something small like int, or double.

Now, is this a good practice? Or is it better to do the interop in this way:

public static extern void InteropWithCPlusPlus(ref BigObject bigObject);

I prefer the first one as it is easier to read and understand, but I afraid that it comes with performance penalty when the return object is a large, consuming memory one.


texts:
I've implemented a very simple in-memory "database" just as an exercise. I wanted to see if there's anything obvious I should be doing that fits more of the Haskell way of doing things.

import qualified Data.Map as M

type History = [String]

data Result = Result (Maybe String) Bool DB

data Command = Command { name  :: String
                       , key   :: Maybe String
                       , value :: Maybe String
                       }

data DB = DB (M.Map String String)

cmdKey c   = let Just s = key   c in s
cmdValue c = let Just s = value c in s

runSetCmd :: Command -> DB -> IO (Maybe String, DB)
runSetCmd c db@(DB map) = do
    let newMap = M.insert (cmdKey c) (cmdValue c) map
    return $ (Nothing, DB newMap)

runGetCmd :: Command -> DB -> IO (Maybe String, DB)
runGetCmd c db@(DB map) = return $ (M.lookup (cmdKey c) map, db)

execCmd :: DB -> Command -> IO Result
execCmd db c@(Command name key value) = do
    (output,newDB) <- case name of
        "set" -> runSetCmd c db
        "get" -> runGetCmd c db
        _     -> return (Nothing, db)
    return $ Result output end newDB

  where
    end = case name of
              "end" -> True
              _     -> False

getCmd = getLine >>= return . parseCmd

parseCmd :: String -> Command
parseCmd s =
    case words s of
        (name:key:value:_) -> Command name (Just key) (Just value)
        (name:key:[])      -> Command name (Just key) Nothing
        (name:[])          -> Command name Nothing Nothing

displayResult :: Result -> IO Result
displayResult r@(Result (Just s) _ _) = putStrLn s >> return r
displayResult r                       = return r

continue :: Result -> IO ()
continue (Result _ end db) = if end then return () else repl db

repl state = getCmd >>= execCmd state >>= displayResult >>= continue

main = repl (DB M.empty)


texts: Sort and merge list based on another list

texts:
Here I'm merging a list to end of another list after sorting it according to another list.This should sort processdetails list according to the order in routeplans list if any item not present in processdetails list is found it should keep the order and add it to processdetails list. Simply saying it just merging two lists based on another list.The below code works fine, I want to know whether there is cleaner way of doing this.if possible in linq.

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

namespace SortByList
{
public class OnGoingProcess
{
    public long Id { get; set; }

    public string Name { get; set; }
    public string Code { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var processDetails = new List<OnGoingProcess>();
        processDetails.Add(new OnGoingProcess() { Id = 120, Name = "Process 29", Code = "T20" });
        processDetails.Add(new OnGoingProcess() { Id = 100, Name = "Process 2", Code = "A20" });
        processDetails.Add(new OnGoingProcess() { Id = 99, Name = "Process 3", Code = "S20"  });
        processDetails.Add(new OnGoingProcess() { Id = 85, Name = "Process 229", Code = "B20" });
        processDetails.Add(new OnGoingProcess() { Id = 220, Name = "Process 39", Code = "C20" });
        processDetails.Add(new OnGoingProcess() { Id = 15, Name = "Process 20", Code = "D20" });
        processDetails.Add(new OnGoingProcess() { Id = 101, Name = "Process 129", Code = "G20" });

        var routePlans = new List<OnGoingProcess>();
        routePlans.Add(new OnGoingProcess() { Id = 100, Name = "Process 2" });
        routePlans.Add(new OnGoingProcess() { Id = 120, Name = "Process 29" });
        routePlans.Add(new OnGoingProcess() { Id = 222, Name = "Process new" });
        routePlans.Add(new OnGoingProcess() { Id = 85, Name = "Process 229" });
        routePlans.Add(new OnGoingProcess() { Id = 101, Name = "Process 129" });

        var sortedPlans = new List<OnGoingProcess>();

        foreach (var plan in routePlans)
        {
            var selectedDetails = processDetails.Where(x => x.Id == plan.Id).ToList();

            if (selectedDetails.Any())
            {
                sortedPlans.AddRange(selectedDetails);
                processDetails.RemoveAll(x => x.Id == plan.Id);

            }
            else
            {
                sortedPlans.Add(plan);
            }
        }
        processDetails.AddRange(sortedPlans);

        foreach (var sorted in processDetails)
        {
            Console.WriteLine("Id : " + sorted.Id + " Name : " + sorted.Name + " Code : " + sorted.Code );
        }

        Console.ReadKey();

     //Id : 99 Name : Process 3 Code : S20
     //Id : 220 Name : Process 39 Code : C20
     //Id : 15 Name : Process 20 Code : D20
     //Id : 100 Name : Process 2 Code : A20
     //Id : 120 Name : Process 29 Code : T20
     //Id : 222 Name : Process new Code :
     //Id : 85 Name : Process 229 Code : B20
     //Id : 101 Name : Process 129 Code : G20

    }
}
}


texts: Extracting distinct HTML list items into a JavaScript array

texts:
This code is made to generate a list of unique elements of the array made of the other two arrays.
The fact that we need two lists to convert in two different array is part of the task.
This code handles with the task, but there's a lot of global variables. As far as I know, it is not good practice.
Tell me, please, how can I improve it?

Любовь

Надежда

Вера

София

Надежда

Вера

<button id="makeNewArray">Создать новый массив</button>


texts: Send message and wait for receive while using async/await and promises the proper way

texts:
I have this working code, but sendAndReceive function looks ugly/smelly to me. Eslint complains about using await inside a loop, and using true as conditional in while loop. Would there be a more elegant way to achieve this? I mean, "blocking" until a response appears in inbox before returning a response. This is necessary because I need to get each response before sending the next message, otherwise the device firmware complains.
const SerialPort = require('serialport');
const ReadLine = require('@serialport/parser-readline');

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const inbox = [];

// IS THIS FUNCTION OK?
const sendAndReceive = async (message, port) => {
  port.write(message);
  while (true) {
    await sleep(1);
    if (inbox.length > 0) {
      const response = inbox.pop();
      return response;
    }
  }
};

SerialPort.list()
  .then(async portInfos => {
    portInfos.filter(pinfo => pinfo.manufacturer === 'FTDI')
      .forEach(async portInfo => {
        const port = new SerialPort(portInfo.path).setEncoding('ascii');

        const parser = port.pipe(new ReadLine({
          delimiter: '\r\n',
          encoding: 'ascii',
        }));
        parser.on('data', data => {
          inbox.push(data);
        });

        port.open();

        const serialMessage = api.createReadMessage(SERIAL);
        const batteryMessage = api.createReadMessage(BATTERY);

        for await (const m of [serialMessage, batteryMessage]) {
          const response = await sendAndReceive(m, port);
          console.log(m.trim());
          console.log(response);
          console.log();
        }
      });
  });


texts:
I'm looking to remove all magic quotes at the start of my PHP script (if they are turned on). The code I'm using to do this is rather simple, so I was wondering if I was overlooking anything:

if (get_magic_quotes_gpc())
{
    foreach ($_GET as $key => $value)
        $_GET[$key] = stripslashes($value);

    foreach ($_REQUEST as $key => $value)
        $_REQUEST[$key] = stripslashes($value);

    foreach ($_POST as $key => $value)
        $_POST[$key] = stripslashes($value);

    foreach ($_COOKIE as $key => $value)
        $_COOKIE[$key] = stripslashes($value);
}

Am I missing / overlooking anything? Thanks.


texts: PHP Pagination for 1,2,3... vs 1,2,3,4,5,etc

texts:
I am having an issue where I am doing a query and it is coming back with about 100 pages, I was hoping to have it come back with 1,2,3...30,31...99,100 instead of 1,2,3,4,5,6,7,8,etc. please see below for working code that returns back results as unwanted format, I am new here so if this question is written wrong please let me know and I will make necessary changes , thanks in advance:

function getPage($stmt, $pageNum, $rowsPerPage)
{
$offset = ($pageNum - 1) * $rowsPerPage;
$rows = array();
$i = 0;
while(($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC,
 SQLSRV_SCROLL_ABSOLUTE,         $offset + $i)) && $i < $rowsPerPage)
{
array_push($rows, $row);
$i++;
}
return $rows;
}

// Set the number of rows to be returned on a page.
$rowsPerPage = 30;

// Connect to the server.
$serverName = 'test';
$connOptions = array("Database"=>"test");
$conn = sqlsrv_connect($serverName, $connOptions);
if (!$conn)
die( print_r( sqlsrv_errors(), true));

//  Define and execute the query.
// Note that the query is executed with a "scrollable" cursor.
$sql = "select * from info";

$stmt = sqlsrv_query($conn, $sql, array(), array( "Scrollable" => 'static' ));
if ( !$stmt )
die( print_r( sqlsrv_errors(), true));

// Display the selected page of data.
echo "
";
$pageNum = isset($_GET['pageNum']) ? $_GET['pageNum'] : 1;
$page = getPage($stmt, $pageNum, $rowsPerPage);

foreach($page as $row)
echo "
$row[0]	$row[1]	$row[2]	$row[3]
";

echo "
";
?>

<?php
// Get the total number of rows returned by the query.
// Display links to "pages" of rows.
$rowsReturned = sqlsrv_num_rows($stmt);
if($rowsReturned === false)
die( print_r( sqlsrv_errors(), true));
elseif($rowsReturned == 0)
{
echo "No rows returned.";
exit();
}
else
{
// Display page links.
$numOfPages = ceil($rowsReturned/$rowsPerPage);
for($i = 1; $i<=$numOfPages; $i++)
{
 $pageLink = "?pageNum=$i";
 print("$i&nbsp;&nbsp;");
}
echo "

";
}

 sqlsrv_close( $conn );


texts: Matching two lists of dicts, strictly and more loosely

texts:
Two lists of dictionaries. Dicts in A and B can be matched by a particular dict key that may be identical or similar. The result should be a list of the source key from A, the matching key from B, and an additional key from B.

Both lists are constructed using screen-scraping, so you normally don't get to see them (unless you print them explicitly). For clarity though: list A is called stoxlist and looks something like this:

stoxlist = [{'stock': 'Apple',
             'last_price': afloat,
             'some-more': 'value',
             ..
             },
            {'stock': 'Google',
             'last_price': afloat,
             'some-more': 'value',
             ..
             },
             ...
            ]

List B looks like this:

symbollist = [{'name': 'Apple',  'symbol': 'APPLE'},
              {'name': 'Google', 'symbol': 'ALPHABET'},
              ...
             ]

The following does what it should do. Using Python 2.7.

# lookup helpers
def match(this, that):
    ''' returns True if this loosely matches with that '''
    if this.strip('.') in that or this.split()[0] in that:
        return True
    else:
        return False        # this is not necessary, but explicit is better than implicit.

def fetch(name, symbols, key):
    ''' find name by dict[key] in list of dicts symbols  '''
    return next((item for item in symbols if match(name, item[key])), None)

def adddict(entry, symbol):
    dict = {'source'    : entry['stock'],
            'found'     : symbol['name'],
            'symbol'    : symbol['symbol']}
    return dict

def lookup(stox, symbols):
    '''lookup symbol for stock name'''
    hits = []
    misses = []
    for entry in stox:
        # try an exact match first
        sym = next((item for item in symbols if entry['stock'] == item['name']), None)
        try:
            # save a hit, if any
            hits.append(adddict(entry, sym))
        except TypeError:
            # if not, try a looser match
            sym = fetch(entry['stock'], symbols, 'name')
            try:
                hits.append(adddict(entry, sym))
            except TypeError:
                # try yet another possibility
                sym = fetch(entry['stock'].upper(), symbols, 'symbol')
                try:
                    hits.append(adddict(entry, sym))
                except TypeError:
                    # lastly try one of the hardcoded SPECIALS.
                    sym = fetch(entry['stock'], SPECIALS, 'name')
                    try:
                        hits.append(adddict(entry, sym))
                    except TypeError:
                        misses.append(entry['stock'])

    return hits, misses

def main():
    # load_all loads a pickle, made by some other module
    stoxlist = load_all()

    # get_symlist is a screen-scraper, using BeautifulSoup.
    symbollist, nosyms = get_symlist()

    hits, misses = lookup(stoxlist, symbollist)

I think try-except makes for better readability than if-elif. But it's four levels deep, which is not pretty.

There are four full iterations over list B (symbols) for every entry in list A (stox). That's not pretty either. Yet I can't think of any better way, because it is necessary to first try an == on all items in B, then a looser match on all items in B, and so on.

I'm not really bothered by performance yet. The lists aren't big, less than 100 items each. But perhaps it could all be done much more efficiently/elegantly/Pythonically if I chose a different data structure than list of dicts?

Please comment.


texts:
I have made two SQL statements as I was unable to figure out how to solve my problem. One is called Product_GetID and the other Product_SaveRecord.  I wanted the save record to read and see if there was an ID entered in a field in a VB front end and if there was not, it would assign one for it, but I was unable to figure this out.  It works, but I know there should be a better way to do this.

  ALTER PROCEDURE [dbo].[Product_GetID]

AS
BEGIN
DECLARE @NewProductID as int
/* Get New Record */
SET @NewProductID = (SELECT ISNULL(MAX(ProductID) + 1, 1) FROM Product)
SELECT ISNULL(MAX(ProductID) + 1, 1) AS NewIDNo FROM Product
INSERT INTO Product (ProductID, CategoryID, Description, Price)
VALUES        (@NewProductID, 0, '', 0)
END

ALTER PROCEDURE [dbo].[Product_SaveRecord]
-- Add the parameters for the stored procedure here
@ProductID as int, @CategoryID as tinyint, @Description as varchar(80),       @FullDescription as         varchar(240), @Price as decimal(8, 2), @MarkupPer as   decimal(8, 2), @LabourHours as decimal(8, 2), @LabourRate as decimal(8, 2), @Stock as integer

AS
BEGIN

/* Update Record */
UPDATE Product SET CategoryID = @CategoryID,
Description = @Description,
FullDescription = @FullDescription,
Price = @Price,
MarkupPer = @MarkupPer,
 LabourHours = @LabourHours,
LabourRate = @LabourRate,
 Stock = @Stock
 WHERE ProductID = @ProductID
END


texts: Is this a correct use of using protocols and delegate pattern in Swift?

texts:
I am trying to grasp the concept of delegates and protocols in Swift. So I have implemented my own PlayableMedia protocol with two concrete classes BlueRayMedia and DVDMedia like so:

protocol PlayableMedia {
    func play()
    func stop()
}

class BlueRayMedia:PlayableMedia {

    func play() {
        println("BlueRayMedia is playing")
    }

    func stop() {
        println("BlueRayMedia has stopped playing")
    }

}

class DVDMedia:PlayableMedia {

    func play() {
        println("DVD is playing")
    }

    func stop() {
        println("DVD has stopped playing")
    }

}

and then in my controller I use it like this:

class DVDPlayer {

    var media:PlayableMedia // delegate property

    init(media:PlayableMedia){
        self.media = media
    }

    func didStartPlaying() {
       media.play()
    }

    func didStopPlaying() {
        media.stop()
    }

}

Then I try to use it like this:

var dvdPlayer:DVDPlayer = DVDPlayer(media: BlueRayMedia())

dvdPlayer.didStartPlaying()

Is this use of delegate pattern correct? Can this be improved?


texts: Validate the set accessors in a simple Triangle class

texts:
I have the following sample Triangle class and I want to validate the set accessors' values, obviously I cannot have a zero side or height Triangle. But while I am writing the validation rules for each property I found myself repeating the same code over and over again. Is there a more concise way to write these properties or to group them together? You can assume how newbie to C# I am.

    //  The Shape class
    abstract class Shape
    {
        // Shape's Methods
        abstract public double GetArea();
        abstract public double GetPerimeter();
    }

    //  The Triangle class
    class Triangle : Shape
    {
        private double sideA;
        private double sideB;
        private double baseT;
        private double height;

        public double SideA
        {
            get { return sideA; }
            set
            {
                if (value > 0)
                {
                    sideA = value;
                }
            }
        }

        public double SideB
        {
            get { return sideB; }
            set
            {
                if (value > 0)
                {
                    sideB = value;
                }
            }
        }

        public double BaseT
        {
            get { return baseT; }
            set
            {
                if (value > 0)
                {
                    baseT = value;
                }
            }
        }

        public double Height
        {
            get { return height; }
            set
            {
                if (value > 0)
                {
                    height = value;
                }
            }
        }

        // Triangle's constructor.
        public Triangle(double sideA, double sideB, double baseT, double height)
        {
            this.sideA = sideA;
            this.sideB = sideB;
            this.baseT = baseT;
            this.height = height;
        }

        // Get Triangle's area.
        public override double GetArea()
        {
            return (this.baseT * this.height) / 2;
        }

        // Get Triangle's perimeter.
        public override double GetPerimeter()
        {
            return sideA + sideB + baseT;
        }
    }


texts: NodeJS broker between MongoDB and RabbitMQ

texts:
I wrote a small program that aims to take some data from the MongoDB database and put them in the RabbitMQ queue.

I tried to use only promise style but I am a beginner in JavaScript. Could you please help me to improve my first draft?

var mongo = require('mongod');
var amqp = require('amqplib');
var _ = require('underscore');

var TaskBroker = function () {
  this.queueName = 'task_queue';
  this.rabbit = {};
  this.mongo = {};
};

TaskBroker.prototype.connectRabbit = function() {
  return amqp.connect('amqp://localhost')

    .then(function (connection) {
      this.rabbit.connection = connection;
      return connection.createChannel()
    }.bind(this))

    .then(function(channel) {
      this.rabbit.channel = channel;
      return channel.assertQueue(this.queueName, {durable: true});
    }.bind(this))
};

TaskBroker.prototype.connectMongo = function(){
  return function() {
    this.mongo.db = mongo('mongodb://127.0.0.1:27017/test', ['test']);
    return this.mongo.db;
  }.bind(this);
};

TaskBroker.prototype.connect = function () {
  return this.connectRabbit()
    .then(this.connectMongo());
};

TaskBroker.prototype.disconnect = function() {
  this.mongo.db.close();
  this.rabbit.channel.close();
  this.rabbit.connection.close();
};

TaskBroker.prototype.get_url_array = function(_data) {
  return _.chain(_data).pluck('probes').flatten().pluck('url').uniq().value();
};

TaskBroker.prototype.getTask = function() {
  return function () {
    return this.mongo.db.test.find({ 'status': 'ONGOING' }, { 'probes.url':1, '_id':0})
      .then(function(results) {
        var url_array = [];
        if (results != null && results.length > 0) {
          url_array = this.get_url_array(results);
        }
        return this.mongo.db.test.find({ 'probes.url' : { $nin: url_array } });
      }.bind(this))

      .then(function(results) {
        if (results.length > 0) return results[0];
        return null;
      });
  }.bind(this);
};

TaskBroker.prototype.produceTask = function() {
  return function(_message) {
    if(_message != null) {
      _message.status = 'ONGOING';
      this.rabbit.channel.sendToQueue(this.queueName, new Buffer(JSON.stringify(_message)), { deliveryMode: true });
      return this.mongo.db.test.update({_id: _message._id}, { $set: { 'status': _message.status }}).then(function() {
        return _message;
      });
    }
    return null;
  }.bind(this);
};

var taskBroker = new TaskBroker();

taskBroker.connect()
  .then(function() {
    setInterval(
      function () {
        taskBroker.getTask()()
          .then(taskBroker.produceTask())
          .then(function(result) {
            if(result == null) {
              console.log('No job to produce');
            } else {
              console.log('Produce', result);
            }
            //console.log('Disconnected');
            //taskBroker.disconnect();
          }
          , function(error) {
            console.log('ERROR', error.stack);
          }
        );
      }
      , 10000
    );
  });


texts: Implementing a Stack with Templates and Smart pointers

texts:
I'm trying to understand the concepts of smart pointers and templates. To get a better understanding of these, I tried to implement these two concepts on Stack. I have created a Stack which can hold objects of any type. For dynamic memory allocation, I have used smart pointers.

Please suggest how I could improve the code. Am I missing any cases while using smart pointers and templates? Since I'm using smart pointers, can I rest assure that free store (heap) memory will be deleted once the Stack variable goes out of scope?

#include "stdafx.h"
#include<iostream>
#include<string>
#include<memory>

using namespace std;

// Template Node
template <typename T>
struct Node
{
    T data;
    shared_ptr<Node> next;
    Node(T d, shared_ptr<Node> n) : data(d), next(n) {}
};

// Template Stack
// Note: T type is used to set the Node type
template <typename T>
class Stack {
private:
    shared_ptr<Node<T>> head;
public:
    Stack() : head(NULL) {}
    Stack(const Stack<T> &rhs) = delete;
    Stack& operator=(const Stack<T> &rhs) = delete;
    void push(const T&);
    void pop();
    T top() const;
    void print() const;
};

// Notice <T> after the class name, it is the syntax requirement
template <typename T>
void Stack<T>::push(const T &data) {
    shared_ptr<Node<T>> temp = make_shared<Node<T>>(data,nullptr);
    if (head == nullptr) {
        head = temp;
    }
    else {
        temp->next = head;
        head = temp;
    }
}

template <typename T>
void Stack<T>::pop() {
    //shared_ptr<Node<T>> temp = head;
    head = head->next;
}

template <typename T>
T Stack<T>::top() const {
    return head->data;
}

template <typename T>
void Stack<T>::print() const {
    // shared_ptr<Node<T>> temp;
    for (auto temp = head; temp != nullptr; temp = temp->next)
        cout << temp->data << '\n';
}

int main()
{
    cout << "String data" << '\n';
    {
        Stack<string> strStack;
        strStack.push("Test1");
        strStack.push("Test2");
        strStack.push("Test3");
        strStack.print();
        strStack.pop();
        strStack.print();
    }
    cout << "Integer data" << '\n';
    {
        Stack<int> intStack;
        intStack.push(10);
        intStack.push(20);
        intStack.push(30);
        intStack.print();
        intStack.pop();
        intStack.print();
    }
    return 0;
}


texts: Calculate amount of mugs StackExchange should give away so I'll receive one

texts:
Description

Calculate how many mugs StackExchange should give away(for graduation) to top reputed users on codereview.stackexchange.com so I'll also receive one. (output is divisible by 50).

Code

DECLARE @mugs INT,@rounded_mugs INT,@inc INT,@remainder INT;
SELECT  @mugs = COUNT(1) FROM Users WHERE Reputation >=
  (SELECT Reputation FROM Users WHERE DisplayName='JaDogg');
SET  @remainder = @mugs%50;
IF (@remainder = 0) SET @inc = 0 ELSE SET @inc=50-@remainder;
SELECT  @mugs+@inc AS 'AMOUNT OF MUGS TO GIVE AWAY';

Link

Calculate amount of mugs to give away so I'll receive one


texts:
I just learned Go (yesterday in fact) and today I made this solution to Project Euler #2.  The problem is to sum the even Fibonacci numbers.  My program uses the matrix representation of the linear relation between consecutive Fibonacci numbers to calculate the coefficients for an equation.  This equation will generate the next even Fibonacci number and the one before it from an even one and the one before it.  However, it skips n - 1 even Fibonacci numbers where n is the number of cores so each core has its own set of data to work with.  So the problem and implementation are rather mathematical.

The program worked perfectly the first time I ran it, however, it is slower than a nonparallel C implementation.  I think this is because on my computer using 4 goroutines, each goroutine runs about 3 loops so the overhead from creating the goroutines and calculating the coefficients (which involves matrix math, but only at startup) is not offset.  The only matrix calculation is raising a matrix to the power of 4, which I did using this Go matrix library which I believe uses BLAS under the hood.

/* p2.go
 * by hacatu
 *
 * This program solves Project Euler problem 2, to find the sum of the even Fibonacci numbers under 4000000.
 * The Fibbonacci number F[k + 2] = F[k + 1] + F[k].  This leads to the linear transformation matrix ((1, 1), (1, 0))
 * (F[k + 2], F[k + 1]) = ((1, 1), (1, 0))*(F[k + 1], F[k]).  Every third Fibonacci number is even, so cube the matrix
 * and get ((3, 2), (2, 1))
 * (F[k + 4], F[k + 3]) = ((3, 2), (2, 1))*(F[k + 1], F[k]).  To parallelize this, raise the matrix to the power of the number
 * of cores and start each core at an offset from (F[k + 1], F[k]) = (2, 1) by applying the ((3, 2), (2, 1)) transformation
 * repeatedly.
 * (F[k + 3*n + 1], F[k + 3*n]) = ((3, 2), (2, 1))^n*(F[k + 1], F[k]).  See https://en.wikipedia.org/wiki/Fibonacci_number.
 */
package main

import (
    "fmt"
    "runtime"
    "github.com/gonum/matrix/mat64"
)

func round(f float64) int {
    return int(f + 0.5)
}

/* Calculates the appropriate power of the next-even transformation matrix
 * and returns the coefficients in the linear equation it represents.
 */
func calcTMat(n int) (aa, ab, ba, bb int) {
    t1Mat := mat64.NewDense(2, 2, []float64{3, 2, 2, 1})
    tMat := new(mat64.Dense)
    tMat.Pow(t1Mat, n);

    return round(tMat.At(0, 0)),
           round(tMat.At(0, 1)),
           round(tMat.At(1, 0)),
           round(tMat.At(1, 1))
}

func main() {
    cpus := runtime.NumCPU()
    fmt.Printf("Running on %d cores.\n", cpus)

    sums := make(chan int, cpus)

    aa, ab, ba, bb := calcTMat(cpus)

    fmt.Printf("Using transformation a, b = %d*a + %d*b, %d*a + %d*b.\n", aa, ab, ba, bb)

    for a, b, i := 2, 1, 0; i < cpus; a, b, i = 3*a + 2*b, 2*a + b, i + 1 {
        go func(a, b int){
            sum := 0
            for a < 4000000 {
                sum += a
                a, b = aa*a + ab*b, ba*a + bb*b
            }
            sums <- sum
        }(a, b)
    }

    sum := 0
    for i := 0; i < cpus; i++ {
        sum += <-sums
    }

    fmt.Println("The sum of the even Fibonacci number under 4000000 is", sum);
}

Is this code good Go (understandable considering what it does, efficient, and idiomatic), and how can I make it faster (redesign or compiler flags)?


texts: Anchor Text String Transformation in Swift

texts:
I need to convert a string using these rules:

Downcase the string
Replace spaces, a blacklist of "invalid" chars, and non-ascii letters (like é) with -
Replace repeated hyphens (ie --) with one hyphen (-)

For example, Is my résumé good enough? should convert to is-my-r-sum-good-enough-.

This Swift function converts the string. I'm looking for help making it shorter. Also, if there's a way to avoid import Foundation (by replacing containsString and stringByReplacingOccurrencesOfString), I'd like to do that. I know I could use an NSRegularExpression but I don't want to use Foundation classes.

Here's what I have so far:

extension Character {
    static let invalidSet = Set(" -&+$,/:;=?@\"#{}|^~[]`\\*()%.!'".characters)

    var invalid: Bool {
        return Character.invalidSet.contains(self)
    }

    var isAscii: Bool {
        guard let number = String(self).utf16.first else { return false }
        return (65..<127) ~= number
    }
}

func anchor(header: String) -> String {
    var output = String(header.lowercaseString.characters.map {
        $0.invalid || !$0.isAscii ? "-" : $0
    })

    while output.containsString("--") {
        output = output.stringByReplacingOccurrencesOfString("--", withString: "-")
    }

    return output
}

Usage:

let input = "Is my résumé good enough?"
let expectedResult = "is-my-r-sum-good-enough-"

print(anchor(input)) //prints is-my-r-sum-good-enough-
print(anchor(input) == expectedResult ? "" : "") //prints


texts:
I'm new to Lisp and I'm yet to wrap my head around the lisp way of writing programs. Any comments regarding approach, style, missed opportunities appreciated:

In particular, please advice if I build results list correctly ((setf merged-list (append merged-list (list a)))).

;;;; Count inversions
(defun small-list (list)
  (or (null list) (null (rest list))))

(defun split-in-half (list)
  (let ((mid (ceiling (length list) 2)))
    (values (subseq list 0 mid)
            (subseq list mid))))

(defun count-inversions (list)
  (if (small-list list) (list list 0)
    (multiple-value-bind (lower upper) (split-in-half list)
      (merge-inversions
        (count-inversions lower)
        (count-inversions upper)))))

(defun merge-inversions (lower-pair upper-pair)
  (let ((lower (first lower-pair))
        (upper (first upper-pair))
        (merged-list '())
        (num-inversions 0))
    (loop while (not (and (null lower) (null upper)))
          do (cond
               ((null lower) (let ((a (first upper)))
                               (setf merged-list (append merged-list (list a)))
                               (setf upper (rest upper))))
               ((null upper) (let ((a (first lower)))
                               (setf merged-list (append merged-list (list a)))
                               (setf lower (rest lower))))
               ((< (first lower)
                   (first upper)) (let ((a (first lower)))
                   (setf merged-list (append merged-list (list a)))
                   (setf lower (rest lower))) )

               (t (let ((a (first upper)))
                    (setf merged-list (append merged-list (list a)))
                    (setf upper (rest upper))
                    (incf num-inversions (length lower))))))
    (list merged-list (+ (second lower-pair) (second upper-pair) num-inversions)))


texts:
I have the following query which brings back a list of items which fall into a particular category:

SELECT i.id, ir.range_name, it.item_type, i.item_value
FROM items i
LEFT JOIN item_types it ON it.id = i.item_type
LEFT JOIN item_ranges ir ON ir.id = i.item_name
LEFT JOIN menu m ON m.id = it.menu_link
WHERE m.menu_title =  'vehicles'
AND i.item_live = 1
ORDER BY ir.range_name

I was wondering whether the m.menu_title column needs to be indexed.  Currently, there are only about 10 rows in the menu (m) table and this is unlikely to change that much.

However, with the joins, the above query will potentially bring back over 1000000 rows.  There are foreign keys on all the joins.

I am trying to avoid filling the database with dummy data to test the query.


texts:
Just checking if I could still do it:

#include <iostream>
#include <algorithm>

std::size_t getParent(std::size_t n)
{
    return (n - 1) / 2;
}

template<typename I>
void heapify(I begin, I end)
{
    std::size_t size    = std::distance(begin, end);
    for(std::size_t loop = 1;loop < size; ++loop)
    {
        std::size_t current = loop;
        std::size_t parent  = getParent(current);
        while(current != 0 && *(begin + parent) < *(begin + current))
        {
            std::swap(*(begin + parent), *(begin + current));
            current = parent;
            parent  = getParent(current);
        }
    }
}

template<typename I>
void heapPop(I begin, I end)
{
    I   last = end - 1;
    std::swap(*begin, *last);

    std::size_t size    = std::distance(begin, last);
    std::size_t current = 0;
    while(current < size)
    {
        std::size_t child1  = current * 2 + 1;
        std::size_t child2  = current * 2 + 2;
        std::size_t goodChild = current;

        if (child2 < size)
        {
            goodChild   = (*(begin + child1) > *(begin + child2)) ? child1 : child2;
        }
        else if (child1 < size)
        {
            goodChild   = child1;
        }
        if (*(begin + current) < *(begin + goodChild))
        {
            std::swap(*(begin + current), *(begin + goodChild));
            current = goodChild;
            continue;
        }
        break;
    }
}

template<typename I>
void heap_sort(I begin, I end)
{
    heapify(begin, end);
    while(begin != end)
    {
        heapPop(begin, end);
        --end;
    }
}

int main()
{
    int  data[] = {6,5,3,1,8,7,2,4};
    heap_sort(std::begin(data), std::end(data));
    std::copy(std::begin(data), std::end(data), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << "\n";
}


texts:
I would love some feedback on the following code for BFS traversal in a binary tree. Is there a cleaner way to write this?

abstract class Tree[+T]
case class Node[T](value:T,var left:Tree[T],var right:Tree[T]) extends Tree[T]
case object End extends Tree[Nothing]

def bfs_v2[T](node:Node[T]):List[T] = {
    def enQueueNext(queue: Queue[Node[T]], aNode: Tree[T]) {
      aNode match {
        case internalNode: Node[T] => queue += internalNode
        case End => {}
      }
    }
    def bfs_visit(queue:Queue[Node[T]],visited:List[T]):List[T] = {
      if(queue.isEmpty){
        visited
      }
      else{
        val currentNode = queue.dequeue()
        enQueueNext(queue, currentNode.left)
        enQueueNext(queue,currentNode.right)
        bfs_visit(queue,currentNode.value :: visited )
      }
    }
    val aQueue = new mutable.Queue[Node[T]]()

    bfs_visit(aQueue += node,List[T]()).reverse
  }


texts: Simple code that checks if you're old enough to drive

texts:
I made this small system that checks if you're old enough to drive. I'm new to C#, but I do know most of the basics since I also know Java. I'm trying to make my code more efficient. Any suggestions or help would be appreciated.

using System;
using System.Threading;

class EfficientCode
{

  static int age = 0;

    static void Main(string[] args)
    {
        Console.WriteLine("This is just a simple project that takes simple and small information from you and uses it to process the information and checks whether you're allowed to drive or not. It also tells you how long is left till you drive.");

        Thread.Sleep(8000); // adds a 8 second delay so that the user could first read the introduction

        Start(); // after the 8 second delay it starts the system
    }

    static void Start()
    {
        Console.WriteLine("Enter your first name");
        String firstName = Console.ReadLine();

        Console.WriteLine("Enter your middle name");
        String middleName = Console.ReadLine();

        Console.WriteLine("Enter your last name");
        String lastName = Console.ReadLine();

        Console.WriteLine("Enter your age");

        try
        {
            age = Convert.ToInt32(Console.ReadLine());
        }
        catch
        {
            Console.WriteLine("ERROR: Input AGE must be a number!");
            Console.WriteLine("Reinitializing questions.");

            Thread.Sleep(3000); // this adds a delay of 3 seconds

            Start(); // restarts the questions
        }

        if (ConfirmInformation(firstName, middleName, lastName, age))
        {
            if (age >= 18)
            {
                Console.WriteLine("Congratulations! You're already old enough to drive.");

                Environment.Exit(0); // Ends the system
            }
            else if (age == 17)
            {
                Console.WriteLine("You're almost there! You can get a learners permit.\nYou have 1 more year left to get an official drivers license!");

                Environment.Exit(0); // Ends the system
            }
            else
            {
                Console.WriteLine("You'll get there. You're not old enough to have a license.");

                int yearsLeft = 18 - age; // gets the years left to drive

                Console.WriteLine("You still have " + yearsLeft + " years left to get a license.");

                Environment.Exit(0); // Ends the system
            }
        }
        else
        {
            Console.WriteLine("Reinitializing questions.");

            Thread.Sleep(3000); // this adds a delay of 3 seconds

            Start(); // restarts the questions
        }
    }

    static bool ConfirmInformation(String firstName, String middleName, String lastName, int age)
    {
        Console.WriteLine("======================================");
        Console.WriteLine("INFORMATION CHECK:");
        Console.WriteLine("");
        Console.WriteLine("FIRST NAME: " + firstName);
        Console.WriteLine("MIDDLE NAME: " + middleName);
        Console.WriteLine("LAST NAME: " + lastName);
        Console.WriteLine("AGE: " + age);
        Console.WriteLine("");
        Console.WriteLine("Are all those information correct? (Y/N)");
        Console.WriteLine("======================================");

        String booleanInput = Console.ReadLine();

        if (booleanInput.Equals("yes", StringComparison.OrdinalIgnoreCase) || booleanInput.Equals("y", StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }
        else if (booleanInput.Equals("no", StringComparison.OrdinalIgnoreCase) || booleanInput.Equals("n", StringComparison.OrdinalIgnoreCase))
        {
            return false;
        }
        else
        {
            Console.WriteLine("ERROR: Input must be either YES or NO.");

            return false;
        }

        return false;
    }

}


texts:
I've recently helped fellow SOFer to answer his question here: Routing in my PHP MVC framework

Then I thought

  Hey, why not improve this code and put in my snippets library.

This is what I came up with:

/**
 * @author Gajus Kuizinas <g.kuizinas@anuary.com>
 * @copyright Anuary Ltd, http://anuary.com
 * @version 1.0.3 (2011 12 07)
 * @param array $routes e.g., array('page/:id' => array('controller' => 'page', 'parameters' => array('id' => 1)));
 */
function ay_dispatcher($url, $routes)
{
    $url            = array
    (
        'original'  => $url,
        'path'      => explode('/', parse_url($url, PHP_URL_PATH))
    );

    $url['length']  = count($url['path']);

    foreach($routes as $filter => $data)
    {
        // reset the parameters every time in case there is partial match
        $parameters     = array();

        $filter         = array
        (
            'original'  => $filter,
            'path'      => explode('/', $filter)
        );

        $filter['length']   = count($filter['path']);

        // this filter is irrelevent
        if($url['length'] <> $filter['length'])
        {
            continue;
        }

        foreach($filter['path'] as $i => $key)
        {
            if(strpos($key, ':') === 0)
            {
                $parameters[substr($key, 1)]    = $url['path'][$i];
            }
            // this filter is irrelevent
            else if($key != $url['path'][$i])
            {
                continue 2;
            }
        }

        if(!array_key_exists('parameters', $data))
        {
            $data['parameters'] = array();
        }

        $data['parameters'] = array_merge($data['parameters'], $parameters);

        return $data;
    }

    return FALSE;
}

The 1.0.2 version https://gist.github.com/68bcb1e087237bde76ea.

I'd like to hear comments on the code logic. It is most certainly better in terms of performance than any regex dispatcher. Did I forget any essential features, though?


texts:
I was learning a bit about about observers. Ruby has an Observable module, but I decided to make my own with a few tweaks.

The first important feature is that this module calls one or more observer methods when the observed object's state is changed. When you add an observer, you also have to specify the method that will be called (by using a symbol). You can add the same observer again specifying yet another method (so if you add an observer twice (two different methods), when the object's state changes, both methods will be called).

Ruby's Observable module seems to call the #update method on the observer. I prefer to choose the method to be called, so I did that change.

The freedom to associate multiple methods to the same observer (so it is called multiple times per state change) is something I'm unsure if it is useful in any way, though. What do you think about that?

The second important feature is the ability to choose which instance variables (using symbols) will be passed to the observer when it is notified of a state change. This way, when the observer is notified, it won't have to manually read the object's instance variables, since such variables will be passed as arguments to its method.

module Observable

  def add_observer(observer,method,*instance_variables)
    @observers ||= {}
    @observers[observer] ||= []
    entry = [method,instance_variables]
    @observers[observer] << entry unless @observers[observer].include?(entry)
  end

  def remove_observer(observer)
    return unless @observers
    @observers.delete(observer)
  end

  def state_changed
    return unless @observers
    @observers.each do |observer,entries|
      entries.each do |entry|
        variables = []
        entry[1].each do |symbol|
          variables << instance_variable_get("@#{symbol}")
        end
        observer.send(entry[0],*variables)
      end
    end
  end

  def count_observers
    return @observers.size
  end

  alias_method :changed , :state_changed

end

Example:

observableObject.add_observer(self,:somethingChanged,:instanceVar1,:instanceVar2)

When observableObject's state changes, self's method #somethingChanged will be called. And two instance variables from observableObject (instanceVar1 and instanceVar2) will be passed to the method.

What do you think of this implementation? I like the fact that it seems to be more flexible (being able to choose which method to be called and, optionally, what instance variables to pass).


texts: C++ Fixed-size general-purpose thread pool

texts:
I've been reading about thread pools in C++ for a few days now and decided to roll out my own. I mainly intend to use it to learn how to implement parallel algorithms at some point in the future but before that I have to know if there's something I can do to make it more efficient.

These are all the variables I'm using. I decided to put everything inside its own namespace and make the std::condition_variable (responsible for pausing the main thread) static because there's really no need for every thread_pool object to have a copy of it.

namespace async {

    static std::condition_variable main_thread_cv;

    template <size_t Size>
    class thread_pool {

        private:
            std::mutex mutex_m;
            std::atomic<int> busy_m;
            std::condition_variable pool_cv_m;
            std::array<std::thread, Size> workers_m;
            std::queue<std::function<void()>> task_queue_m;
            bool should_terminate_m;
            void thread_loop();

        public:
            thread_pool();
            ~thread_pool();
            thread_pool(const thread_pool& other) = delete;
            thread_pool(const thread_pool&& other) = delete;
            thread_pool& operator=(const thread_pool& other) = delete;
            thread_pool& operator=(const thread_pool&& other) = delete;
            void wait();
            template <typename Fn, typename... Args> void enqueue(Fn&& function, Args&&... args);

    };
...
}

This is the thread loop executed by all of the worker threads.

template<size_t Size>
void thread_pool<Size>::thread_loop() {

    thread_local std::function<void()> task;

    for (;;) {
        { std::unique_lock<std::mutex> lock(mutex_m);
            pool_cv_m.wait(lock, [this]() { return !task_queue_m.empty() || should_terminate_m; });
            if (should_terminate_m) {
                break;
            }
            task = task_queue_m.front();
            task_queue_m.pop();
        }
        busy_m++;
        task();
        busy_m--;
        main_thread_cv.notify_one();
    }

}

ctor and dtor:

template<size_t Size>
thread_pool<Size>::thread_pool() {

    busy_m = 0;
    should_terminate_m = false;

    for (auto& thread : workers_m) {
        thread = std::thread([this]() { thread_loop(); });
    }

}

template<size_t Size>
thread_pool<Size>::~thread_pool() {

    busy_m = 0;
    should_terminate_m = true;

    pool_cv_m.notify_all();

    for (auto& thread : workers_m) {
        thread.join();
    }

}

The wait and enqueue functions:

template<size_t Size>
void thread_pool<Size>::wait() {

    { std::unique_lock<std::mutex> lock(mutex_m);
        main_thread_cv.wait(lock, [this]() { return busy_m == 0 && task_queue_m.empty(); });
    }

}

template<size_t Size>
template<typename Fn, typename ...Args>
void thread_pool<Size>::enqueue(Fn&& function, Args&& ...args) {

    { std::scoped_lock<std::mutex> lock(mutex_m);
        task_queue_m.push(std::bind(std::forward<Fn>(function), std::forward<Args>(args)...));
        pool_cv_m.notify_one();
    }

}


texts: Maybe with a structural pattern matching interface

texts:
With a reference implementation for PEP 622 now available in a Jupyter playground, I decided to copy over my favourite feature of Rust in full to Python.
Note: this won't be released until Python 3.10 but there is a reference implementation available.
Given that I do a lot of interacting with JSON through the web, having a somewhat safe but hacky solution using Some is helpful. And so I've diverged from Rust's Some in that you can get items from the underlying datatype by indexing or through attribute lookup.
This is useful if I just want the first phone number from the user.
match user.phones[0]:
    case Some(phone):
        print(f"No  : {phone}")
    case _:
        print("No phone number provided")

To allow for this interface I've built a Null class that returns Null through indexing or attribute lookup. This is only needed if you're using these additional interfaces, and so None can be used otherwise.
maybe.py
from __future__ import annotations

from typing import Any, Generic, Type, TypeVar, Union, cast

__all__ = [
    "NSome",
    "Null",
    "Some",
]

T = TypeVar("T")

class _Null(type):
    def __getattr__(self, key: Any) -> Type[Null]:
        return Null

    def __getitem__(self, index: Any) -> Type[Null]:
        return Null

    def __repr__(self) -> str:
        return f"Null"

class Null(metaclass=_Null):
    pass

class Some(Generic[T]):
    __slots__ = __match_args__ = ("_value",)
    _value: T

    def __init__(self, value: T) -> None:
        self._value = value

    def __repr__(self) -> str:
        return f"Some({self._value})"

    def __getattr__(self, key: Any) -> Union[Type[Null], Some[Any]]:
        try:
            return Some(getattr(self._value, key))
        except AttributeError:
            return Null

    def __getitem__(self, index: Any) -> Union[Type[Null], Some[Any]]:
        try:
            return Some(cast(Any, self._value)[index])
        except IndexError:
            return Null

NSome = Union[None, Type[Null], Some[T]]

Usage takes advantage of PEP 622 allowing for somewhat long but very customizable usage.
import collections
import math

from maybe import NSome, Null, Some

def divide(numerator: int, denominator: int) -> NSome[float]:
    if denominator == 0:
        return None
    else:
        return Some(numerator / denominator)

def display(value: NSome[float]) -> None:
    match value:
        case Some(x):
            print(f"Result: {x}")
        case _:
            print("Cannot divide by zero")

User = collections.namedtuple("User", "name age phones")

def display_user(user: NSome[User]) -> None:
    match user.name:
        case Some(name):
            print(f"Name: {name}")
        case _:
            print("No name provided")
    match user.age:
        case Some(age):
            print(f"Age : {age}")
        case _:
            print("No age provided")
    match user.phones[0]:
        case Some(phone):
            print(f"No  : {phone}")
        case _:
            print("No phone number provided")

def main() -> None:
    display(divide(2, 3))
    display(divide(2, 0))

    display_user(Some(User("name", 123, ["123456789"])))
    display_user(Some(User("name", 123, [])))
    display_user(Null)

if __name__ == "__main__":
    main()

This outputs the following in the playground.
Result: 0.6666666666666666
Cannot divide by zero
Name: name
Age : 123
No  : 123456789
Name: name
Age : 123
No phone number provided
No name provided
No age provided
No phone number provided


texts: Search for the biggest amplitude in an array

texts:
I have a assignment to find which season has the biggest temperature amplitude. Input par is the int array with temperatures:

int T[]= {-1,-10,10,5,30,15,20,-10,30,10,29,20}

which means:

winter: -1,-10,10 spring: 5,30,15 summer: 20,-10,30 autumn: 10,29,20

temp is always an int,
int[] T - T.length%4 is equal to 0 (same number of temperatures for every season, could be 2, 3 etc.)

{

    public String solution(int[] T){
    int length = T.length;
    int count = length/4;
    int i=0,j=0,indx=0;
    String name="";
    int maxAmpl;

    int[] winter = new int[count];
    int[] spring = new int[count];
    int[] summer = new int[count];
    int[] autumn = new int[count];
    int[] diff = new int[4];

    for(j=0,i=0;j<count; j++,i++){
        winter[i] = T[j];
    }

    for(j=count,i=0;j<count*2; j++,i++){
        spring[i] = T[j];
    }

    for(j=count*2,i=0;j<count*3; j++,i++){
        summer[i] = T[j];
    }

    for(j=count*3,i=0;j<count*4; j++,i++){
        autumn[i] = T[j];
    }

    Arrays.sort(winter);
    Arrays.sort(spring);
    Arrays.sort(summer);
    Arrays.sort(autumn);

    diff[0] = winter[count-1]-winter[0];
    diff[1] = spring[count-1]-spring[0];
    diff[2] = summer[count-1]-summer[0];
    diff[3] = autumn[count-1]-autumn[0];

    maxAmpl=diff[0];

    for(int k=1; k<4; k++){
        if (diff[k]>maxAmpl){
            maxAmpl = diff[k];
            indx = k;
        }
    }

    switch(indx){
        case 0:
            name = "WINTER";
            break;
        case 1:
            name = "SPRING";
            break;
        case 2:
            name = "SUMMER";
            break;
        case 3:
            name = "AUTUMN";
            break;
    }
    return name;
}


texts: Print which CPU flags are set at the start of the program

texts:
This is my first "real" x86 program developed from scratch. Please critique:

format PE console
entry start

include 'win32a.inc'

section '.text' code executable
start:  pushf
        push hello
        call [printf]
        pop ecx
        pop eax
check_carry_flag:
        mov dx, ax ; ax has flags reg
        test ax, 1h
        jnz carry_flag_set
        mov esi, edx
check_parity_flag:
        mov eax, esi
        test ax, 4h
        jnz parity_flag_set
        mov esi, edx
check_aux_flag:
        mov eax, esi
        test ax, 10h
        jnz aux_flag_set
        mov esi, edx
check_zero_flag:
        mov eax, esi
        test ax, 40h
        jnz zero_flag_set
        mov esi, edx
check_sign_flag:
        mov eax, esi
        test ax, 80h
        jnz sign_flag_set
        mov esi, edx
check_dir_flag:
        mov eax, esi
        test ax, 400h
        jnz dir_flag_set
        mov esi, edx
check_OF_flag:
        mov eax, esi
        test ax, 800h
        jnz OF_flag_set
jmp endme

carry_flag_set:
        mov esi, edx
        push carry_flag
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_parity_flag
parity_flag_set:
        mov esi, edx
        push parity_flag
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_aux_flag
aux_flag_set:
        mov esi, edx
        push aux_flag
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_zero_flag
zero_flag_set:
        mov esi, edx
        push zero_flag
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_sign_flag
sign_flag_set:
        mov esi, edx
        push sign_flag
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_dir_flag
dir_flag_set:
        mov esi, edx
        push dir_flag_set
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_OF_flag
OF_flag_set:
        mov esi, edx
        push OF_flag
        call [printf]
        pop ecx
endme:
        push p
        call [system]
        pop ecx

        push 0
        call [ExitProcess]
section '.rdata' data readable
        hello db 'The flags are: %X', 10, 0
        p db 'pause>nul'
        carry_flag db 'Carry flag set', 0
        parity_flag db 'Parity flag set', 0
        zero_flag db 'Zero flag set', 0
        sign_flag db 'Sign flag set', 0
        dir_flag db 'Direction flag set', 0
        OF_flag db 'Overflow flag set', 0
        aux_flag db 'Aux flag set', 0

section '.idata' data readable import
        library kernel32, 'kernel32.dll', \
                msvcrt,   'msvcrt.dll'
        import kernel32, ExitProcess, 'ExitProcess'
        import msvcrt, printf, 'printf', \
        system, 'system'


texts:
I was searching the internet for some Python exercises, and I've found a lab assignment from University of Toronto. Here's the major of it:

  Question 1.
  Welcome Message In the if __name__ == "__main__" block, write code that displays the following: Welcome to the calculator program. Current value: 0

  Question 2.
  Displaying the Current Value Write a function whose signature is display_current_value(), and which displays the current value in the calculator. In the if __name__ == "__main__" block, test this function by calling it and observing the output.

  Question 3.
  Addition Write a function whose signature is add(to_add), and which adds to_add to the current value in the calculator, and modifies the current value accordingly. In the if __name__ == "__main__" block, test the function add by calling it, as well as by calling display_current_value().
  Hint: when modifying global variables from within functions, remember to declare them as global.

  Question 4.
  Multiplication Write a function whose signature is mult(to_mult), and which multiplies the current value in the calculator by to_mult, and modifies the current value accordingly. In the if __name__ == "__main__" block, test the function.

  Question 5.
  Division Write a function whose signature is div(to_div), and which divides the current value in the calculator by to_div, and modifies the current value accordingly. In the if __name__ == "__main__" block, test the function. What values of to_div might cause problems? Try them to see what happens.

  Question 6.
  Memory and Recall Pocket calculators usually have a memory and a recall button. The memory button saves the current value and the recall button restores the saved value. Implement this functionality.

  Question 7.
  Undo Implement a function that simulates the Undo button: the function restores the previous value that appeared on the screen before the current one.

Here's my solution:

current_value = 0
memory = current_value
memo = [current_value]

def is_divisible(x, y):
    """Return whether x is divisible by y. """
    return x % y == 0

def update_list(lst, value):
    """Updates a list with an item. """
    lst.append(value)

def display_current_value():
    """Prints the current value of the calculator. """
    print('Current value:', current_value)

def add(to_add):
    """Adds a number to the current value of the calcalutor. """
    global current_value

    current_value += to_add

    update_list(memo, current_value)

def mult(to_mult):
    """Multiplies the current value of the calcalutor by a number. """
    global current_value

    current_value *= to_mult

    update_list(memo, current_value)

def div(to_div):
    """Divides the current value of the calcalutor by a number. """
    global current_value

    if is_divisible(current_value, to_div):
        current_value //= to_div
    else:
        current_value /= to_div

    update_list(memo, current_value)

def store():
    """Stores the current value. """
    global memory

    memory = current_value

def recall():
    """Recalls the saved value. """
    return memory

def undo():
    """Restores the previous value. """
    global memo

    if len(memo) >= 2:
        global current_value

        current_value = memo[-2]

        memo.pop(-2)

def main():
    print('Welcome to the calculator program.' )
    display_current_value()

    add(6)
    display_current_value()

    mult(2)
    display_current_value()

    div(3)
    display_current_value()

    for iteration in range(3):
        undo()
        display_current_value()

if __name__ == '__main__':
    main()

Is it possible to implement undo without dealing with other functions such as add? Is the code well-documented?

Please point out any bad practice or any bug I've made. Please point out how somethings can be done better. And please note that I'm a beginner and a hobbyist.


texts: My implementation of the repository pattern

texts:
I'm using this pattern since a few months and I was wondering if I can make it any better.

The one thing I am not satisfied about is the dispose method. In every repository I have to add a dispose method that calls the base dispose method. Is there a way to get rid of the dispose method in every repository and just let it (automatically) call the base dispose method?

I'm using Linq2Sql.

Interface:

  public interface IRepository<TEntityType> where TEntityType : class
{
    TEntityType GetById(int id);

    IQueryable<TEntityType> GetAll();

    void Delete(TEntityType item);

    void Add(TEntityType item);
}

Base:

  public class BaseRepository<TEntityType> where TEntityType : class
{
    private readonly DataClassesDataContext _dataContext;

    protected BaseRepository()
    {
        _dataContext = new DataClassesDataContext();
    }

    protected Table<TEntityType> GetTable()
    {
        return _dataContext.GetTable<TEntityType>();
    }

    protected void SaveChanges()
    {
        _dataContext.SubmitChanges();
    }

    protected virtual void Dispose()
    {
        if (_dataContext != null)
        {
            _dataContext.Dispose();
        }
    }
}

Repository class:

  public class FirstClassRepository : BaseRepository<FirstTable>, IRepository<FirstTable>, IDisposable
{
    public FirstTable GetById(int id)
    {
        return GetTable().FirstOrDefault(x => x.Test == id);
    }

    public IQueryable<FirstTable> GetAll()
    {
        return GetTable();
    }

    public void Delete(FirstTable item)
    {
        GetTable().DeleteOnSubmit(item);
    }

    public void Add(FirstTable item)
    {
        GetTable().InsertOnSubmit(item);
    }

    public new void Dispose()
    {
        base.Dispose();
    }
}


texts:
I've just finished this function and wanted to know if anyone know another way to do the same:

function findtext(archivo,Delimit1, Delimit2 :String) :String;
var
  Buffer      :AnsiString;
  ResLength   :Integer;
  i           :Integer;
  PosDelimit  :Integer;
begin
  Buffer := read_file_z(archivo);
  if Pos(Delimit1, Buffer) > Pos(Delimit2, Buffer) then
    PosDelimit := Length(Buffer)-(Pos(Delimit1, Buffer)+Length(Delimit1))
  else PosDelimit := Length(Buffer)-(Pos(Delimit2, Buffer)+Length(Delimit2));
  Buffer := Copy(Buffer, (Length(Buffer)-PosDelimit), Length(Buffer));
  ResLength := Pos(Delimit2, Buffer)-(Pos(Delimit1, Buffer)+Length(Delimit1));
  for i := 0 to (Reslength-1) do
    Result := Result+Buffer[Pos(Delimit1, Buffer)+(Length(Delimit1)+i)];
end;

The auxiliary function read_file_z is this:

function read_file_z(const FileName: String): AnsiString;
var
  F: File;
  DefaultFileMode: Byte;
begin
  DefaultFileMode := FileMode;
  try
    FileMode := 0;
    AssignFile(F, FileName);
    {$I-}
    Reset(F, 1);
    {$I+}
    if IoResult=0 then
      try
        SetLength(Result,FileSize(F));
        if Length(Result)>0 then begin
          {$I-}
          BlockRead(F,Result[1],LENGTH(Result));
          {$I+}
          if IoResult<>0 then Result:='';
        end;
      finally
        CloseFile(F);
      end;
  finally
    FileMode := DefaultFileMode;
  end;
end;

The function finds text between two tags. An example would [hi]hi world[hi] and the function will respond "hi world".

Example:

findtext('test.exe','[hi]','[hi]');

The way seek to do the function is the "uses" default.

What alternatives do I have to make the function "findtext"?


texts: My implementation of a for_each function that traverses a std::container by some step size integer N

texts:
As my answer to Iterating over an odd (even) elements only in a range-based loop, I wrote this function, with the following driver program and output:

#include <array>
#include <vector>
#include <iterator>

// Forward iteration from begin to end by step size N.
template<typename Container, typename Function>
void for_each_by_n( Container&& cont, Function f, unsigned increment_by = 1) {
    if ( increment_by == 0 ) return; // must check this for no op

    using std::begin;
    auto it = begin(cont);

    using std::end;
    auto end_it = end(cont);

    while( it != end_it ) {
        f(*it);
        for ( unsigned n = 0; n < increment_by; ++n ) {
            if ( it == end_it ) return;
            ++it;
        }
    }
}

int main() {
    std::array<int,8> arr{ 0,1,2,3,4,5,6,7 };
    std::vector<double> vec{ 1.2, 1.5, 1.9, 2.5, 3.3, 3.7, 4.2, 4.8 };

    auto l = [](auto& v) { std::cout << v << ' '; };

    for_each_by_n(arr, l); std::cout << '\n';
    for_each_by_n(vec, l); std::cout << '\n';

    for_each_by_n(arr, l, 2); std::cout << '\n';
    for_each_by_n(arr, l, 4); std::cout << '\n';

    for_each_by_n(vec, l, 3); std::cout << '\n';
    for_each_by_n(vec, l, 5); std::cout << '\n';

    for_each_by_n(arr, l, 8); std::cout << '\n';
    for_each_by_n(vec, l, 8); std::cout << '\n';

    // sanity check to see if it doesn't go past end.
    for_each_by_n(arr, l, 9); std::cout << '\n';
    for_each_by_n(vec, l, 9); std::cout << '\n';

    return 0;
}

Output

 0 1 2 3 4 5 6 7
 1.2 1.5 1.9 2.5 3.3 3.7 4.2 4.8
 0 2 4 6
 0 4
 1.2 2.5 4.2
 1.2 3.7
 0
 1.2
 0
 1.2

I did my best to check for possible bugs, corner cases etc.

What I would like to know about my function above:

Does this follow modern C++ standards?
Is there any room for improvements?
Did I miss any possible bugs that I might have overlooked?
Would this be considered readable, reliable, generic, portable, cross-platform and reusable?
Do I have to worry about any const correctness, type deduction, cache misses and the like?
-Note-: I know the above function is not in a designated namespace; that is not of concern here. I can do that without hassle or trouble.

Let me know what you think; I'm looking forward to any and all feedback.

I would like to know ahead of time for I am thinking about adding a second unsigned integer parameter to this function. It would allow the user to choose the index location they want to use for their starting position. This parameter would default to 0.


texts:
Again, out of fun on Saturday night, I decided to solve the following problem from CodeEval.

  The challenge is finding the index of the lowest unique number.

  There is a game where each player picks a number from 1 to 9, writes
  it on a paper and gives to a guide. A player wins if his number is the
  lowest unique. We may have 10-20 players in our game.

  Input sample:

  Your program should accept as its first argument a path to a filename.

  You're a guide and you're given a set of numbers from players for the
  round of game. E.g. 2 rounds of the game look this way:

3 3 9 1 6 5 8 1 5 3
9 2 9 9 1 8 8 8 2 1 1

  Output sample:

  Print a winner's position or 0 in case there is no winner. In the
  first line of input sample the lowest unique number is 6. So player 5
  wins.

5
0

  Suppose you're given a set of numbers from players for the round of
  game. E.g. 2 rounds of the game look this way:

3 3 9 1 6 5 8 1 5 3
9 2 9 9 1 8 8 8 2 1 1

  The output is the winner's position, or 0 in case there is no winner.
  In the first line of input sample the lowest unique number is 6, so
  player 5 wins (it was player number 5 who threw number 6). And in the
  second set there is no unique number, so the output will be 0.

  So, the overall output will be:

5
0

I solved this problem correctly using Linq in the following code, but the performance is not that great at 255 ms for about 100 data points. Any suggestion for improving performance or perhaps another novel solution? The data have to be read from a text file in CodeEval, so my code is structured around that way.

static void Main(string[] args)
{
   using (StreamReader reader = File.OpenText(args[0]))
        {
            while (!reader.EndOfStream)
            {
                var linevalue = reader.ReadLine();
                if (!string.IsNullOrEmpty(linevalue))
                {
                    var numbers = linevalue.Split(' ');
                    var groups = numbers.GroupBy(x => x).Select(g => new
                    {
                        number = g.Key,
                        freq = g.Count()
                    });

                    var nonRepeated = groups.Where(x => x.freq == 1).ToList();
                    if (nonRepeated.Count() != 0)
                    {

                            var singles = nonRepeated.Select(x => x.number).ToList();
                            var smallest = singles.Min();
                            var playerNumber = Array.IndexOf(numbers, smallest);
                            Console.WriteLine(playerNumber + 1);

                    }
                    else
                    {
                        Console.WriteLine("0");
                    }
                }
            }
        }
}


texts:
I have been studying C#, and I am trying to model the Tic Tac Toe game. Is my program reasonable or is there anything I need to improve?

 enum Result
{
    None,
    Win,
    Draw
}

public class TicTacToe
{
    static char[] board = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    char player = 'O';
    Result result = Result.None;

    public void PlayGame()
    {
        Intro();
        do
        {
            Console.Clear();
            Console.WriteLine("Player 1 : O Player 2 : X");
            DrawBoard();
            Console.WriteLine($"\nPlayer {player}'s Turn \nPlease Enter the empty number");

            label:
            int choice = 0;

            while (!int.TryParse(Console.ReadLine(), out choice))
            {
                Console.WriteLine("Enter the num please");
            }
            if (choice >= 10)
            {
                Console.WriteLine("Please enter btw 1 - 9");
                goto label;
            }

            if (board[choice] != 'X' && board[choice] != 'O')
            {
                board[choice] = player;
                ChangeTurn();
            }

            CheckWin();
        } while (result != Result.Draw && result != Result.Win);

        Console.Clear();
        DrawBoard();
        GameResult();
        Console.ReadKey();

    }

    void ChangeTurn()
    {
      if (player == 'X')
          player = 'O';
      else if (player == 'O')
          player = 'X';
    }
    void GameResult()
    {
        if (result == Result.Win)
        {
            ChangeTurn();
            Console.WriteLine("Player {0} has won", player);
        }
        else if(result == Result.Draw)
        {
            Console.WriteLine("Draw");
        }
        Console.ReadLine();
    }
    void Intro()
    {
        Console.WriteLine("Welcome to TieTacToe");
        Console.WriteLine("Press any Key to continue");
        Console.ReadKey();
        Console.Clear();
    }
    void DrawBoard()
    {
        int x = 1;
        Console.WriteLine();
        for (int row = 0; row < 3; row++)
        {
            Console.Write("| ");
            for (int col = 0; col < 3; col++)
            {
                Console.Write(board[x]);
                Console.Write(" | ");
                x++;
            }
            Console.WriteLine();
        }
    }
    void CheckWin()
    {
        // horzontial
        if (board[1] == board[2] && board[2] == board[3])
        {
            result = Result.Win;
        }
        else if (board[4] == board[5] && board[5] == board[6])
        {
            result = Result.Win;
        }
        else if (board[7] == board[8] && board[8] == board[9])
        {
            result = Result.Win;
        }
        // vertical
        else if (board[1] == board[4] && board[4] == board[7])
        {
            result = Result.Win;
        }
        else if (board[2] == board[5] && board[5] == board[8])
        {
            result = Result.Win;
        }
        else if (board[3] == board[6] && board[6] == board[9])
        {
            result = Result.Win;
        }
        // X
        else if (board[1] == board[5] && board[5] == board[9])
        {
            result = Result.Win;
        }
        else if (board[3] == board[5] && board[5] == board[7])
        {
            result = Result.Win;
        }
        else if (board[1] != '1' && board[2] != '2' && board[3] != '3' && board[4] != '4' && board[5] != '5' && board[6] != '6' && board[7] != '7' && board[8] != '8' && board[9] != '9')
        {
            result = Result.Draw;
        }
        else
        {
            result = Result.None;
        }
    }
}


texts:
I've been experimenting with Perl and MySql and wrote this code for connecting and writing to a database:

#   MySQL DDL to create database used by code
#
#   CREATE DATABASE sampledb;
#
#   USE sampledb;
#
#   CREATE TABLE `dbtable` (
#     `id`  int(11) NOT NULL AUTO_INCREMENT,
#     `demo` longtext,
#     PRIMARY KEY  (`id`)
#   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

# PERL MODULES
use strict;
use warnings;
use DBI; #http://dbi.perl.org

# CONFIG VARIABLES
my $platform = "mysql";
my $database = "sampledb";
my $host = "localhost";
my $port = "3306";
my $username = "root";
my $password = "password";

# DATA SOURCE NAME
my $dsn = "dbi:$platform:$database:$host:$port";

# PERL DBI CONNECT
my $connect = DBI->connect($dsn, $username, $password);

# VARS for Examples
my $query;
my $query_handle;
my $id;
my $demo;

# Example 1 using prepare() and execute() INSERT

    # SAMPLE VARIABLE AND VALUES TO PASS INTO SQL STATEMENT
    $id = 1;
    $demo = "test";

    # INSERT
    $query = "INSERT INTO dbtable (id, demo) VALUES ('$id', '$demo')";
    $query_handle = $connect->prepare($query);
    $query_handle->execute();
    undef $query;

# Example 2 using do() UPDATE

    # SAMPLE VARIABLE AND VALUES TO PASS INTO SQL STATEMENT
    $id = 1;
    $demo = "test 2";

    # UPDATE
    $query = "UPDATE dbtable SET demo = '$demo' WHERE id = $id";
    $query_handle = $connect->do($query);
    undef $query;

Is this the correct/idiomatic way to access a database in Perl? Are there any other improvements I could make?


texts: Count solutions of a equation with a constraint

texts:
How to count the solutions of the equation \$x \cdot y + x \cdot z + y \cdot z = n,  (0 \leq n \leq 10^4)\$ with the constraint that \$x \geq y \geq z \geq 0\$ ?

To solve this i've isolated the z value and brute-forced the values of x and y. If the values x,y,z satisfy the constraint and equation than its a valid solution.

#include <stdio.h>

int main () {
    int x,y,z,n,counter;
    while ( scanf("%d", &n), n != -1 ) {

        counter = 0;

        for ( x = n ; x >= 0; --x ) {
            for ( y = x ; y > 0 ; --y ) {
                z = (n - x*y);

                //negative z isn't valid
                if(z < 0)
                    continue;

                z /= (x + y);

                if( z <= y && y <= x && x*y + x*z + y*z == n ) {
                    ++counter;
                }
            }
        }

        printf("%d\n",counter);
    }
    return 0;
}

The input contains several lines with one value for n. The program must stop when this value is -1.

The output is the number of solutions of the equation in separated lines.

Sample Input:

20
1
9747
-1

Sample Output:

5
1
57

How to make this code faster ?


texts:
I have an existing overloaded set of functions that I cannot change and need to be tested:

object Validator {
    fun validateRange(min: Int, max: Int): Boolean = true
    fun validateRange(min: Long, max: Long): Boolean = true
    fun validateRange(min: Double, max: Double): Boolean = true
    fun validateRange(min: String, max: String): Boolean = true

    fun validateRangeInput(min: Int, max: Int, input: Int): Boolean = true
    fun validateRangeInput(min: Long, max: Long, input: Long): Boolean = true
    fun validateRangeInput(min: Double, max: Double, input: Double): Boolean = true
    fun validateRangeInput(min: String, max: String, input: String): Boolean = true
}

The test data for validateRange() contain each of the various types. Here is a sample of the input data:

val inputs = listOf(
        Pair("1", "1"),
        Pair(1, 1),
        Pair(1L, 1L),
        Pair(1.0, 1.0)
)

Of course, I cannot simply do this:

inputs.forEach { (min, max) -> Validator.validateRange(min, max) }

My current solution implements a helper using generics and a when block with the is operator and smart casting:

fun <T> validateRangeHelper(min: T, max: T): Boolean {
    return when {
        min is Int && max is Int -> Validator.validateRange(min, max)
        min is Long && max is Long -> Validator.validateRange(min, max)
        min is Double && max is Double -> Validator.validateRange(min, max)
        min is String && max is String -> Validator.validateRange(min, max)
        else -> throw UnsupportedOperationException()
    }
}

inputs.forEach { (a, b) -> validateRangeHelper(a, b) }

This approach grows cumbersome with each additional argument, such as for the validateRangeInput() functions.

fun <T> validateRangeHelper(min: T, max: T, input: T): Boolean {
    return when {
        min is Int && max is Int && input is Int -> Validator.validateRangeInput(min, max, input)
        min is Long && max is Long && input is Long -> Validator.validateRangeInput(min, max, input)
        min is Double && max is Double && input is Double -> Validator.validateRangeInput(min, max, input)
        min is String && max is String && input is String -> Validator.validateRangeInput(min, max, input)
        else -> throw UnsupportedOperationException()
    }
}

Is there a way I can improve the helper or avoid it all together without changing Validator?


texts: Summing all numbers that can be formed from a list of integers

texts:
Following a challenge on HackerRank, I want to find the sum of all numbers that have no more than x 4's, y 5's, and z 6's module 10^9 + 7. I'd like to know how I could improve this code below both for style and performance. Also, what's the canonical way to get unique permutations of a list that can include repeated elements?

import itertools
import sys
import collections

#create initial list based on input
x, y, z = map(int, sys.stdin.readline().split(' '))
permute_list = [4]*x + [5]*y + [6]*z

# collect iterators to permutations of all possible lengths
permuted = []
for i in range(1,(x+y+z+1)):
    permuted.append(itertools.permutations(permute_list, i))

# collect unique permutations from iterators
# there will be many repeats, anyway to avoid this inefficiency?
dynamic_table = collections.defaultdict(lambda: 0)
mod_var = (10**9 + 7)
for it in permuted:
    for i in it:
        new_sum = ''.join(map(str, i))
        if not dynamic_table[new_sum]:
            dynamic_table[new_sum] = int(new_sum)

print(sum(dynamic_table.values()) % mod_var)

I tried a few ways of doing this. What most surprised me is that implementing with a dictionary, as above, seems to beat a set implementation by about 30%, time-wise. Why is this? Also, what are some better ways to implement this and/or tweaks to the above code?


texts: Dynamically build tagged union and helper that allows its instantiation and calling of its static methods

texts:
I am working on a typescript react/redux app that provides a visual interface for the code editor with a predefined set of instructions. It's basically a tree structure of objects that I call Handlers and these can be nested. All these handlers implement a simple IHandler interface and common functionality is implemented in HandlerBase class.

export default interface IHandler {
    id: Id;
    type: string;
    isDisabled?: boolean;
    isExpanded?: boolean;
    codeTemplate: CodeTemplate;
    toJson: () => string;
    toCode: () => string;
}

export default class HandlerBase<Type extends string, T extends HandlerBase<Type, T>> implements IHandler {
    id: Id<T>;
    type: Type;
    isDisabled?: boolean;
    isExpanded?: boolean;
    codeTemplate: CodeTemplate<T>;
}

The Id type is a strongly typed string that makes it easier to save the types of handlers under the ids.

export type Id<T extends IHandler = IHandler> = string & { __type: T["type"] };

All the handlers are saved in a redux store by their keys and refer to other handlers that are nested under them also by the Id type. Also, each handler has it's own unique Type which is a string literal type.

class ExampleHandlerModel extends HandlerBase<"Example", ExampleHandler> {
    child: Id<ExampleHandlerModel>;
}

What I would like to achieve is to strongly type the IHandler.type attribute, which right now is just a string type, automatically as a union of all implemented handlers in my codebase. I looked into class decorators, but since I've never worked with them, I wasn't able to come up with any solution, nor am I sure that this problem can be solved by decorating the deriving classes (my inspiration was C# attributes that can do similar kind of type registration).

Another problem I would like to also solve is that these implementations of handler class at some point in my code need to be instantiated and they also have static methods that should be able to be called based on the type property. The really ugly and unmaintainable way I'm doing it now is a function that takes an IHandler argument and then just runs it through a switch statement that I manually maintain and update every time I implement a new handler type.

export const HandlerGetStatic = <T extends IHandler>(handler: T, attr: string): any => {
    switch (handler.type) {
        case "Example": return (ExampleHandlerModel)[attr];
        case "Foo": return (FooHandlerModel)[attr];
        // etc.
    }
}
export const InstantiateHandler = <T extends HandlerBase<string, T>>(model: Model<T>): IHandler => {
    switch (model.type) {
        case "Example": return new ExampleHandlerModel(model);
        case "Foo": return new FooHandlerModel(model);
        // etc.
    }
}

Here I would also like to remove the need for manual updating of these helpers.


texts: Sliding window over a 2D vector, implementation of Marching Squares algorithm

texts:
I have not used C++ in quite a while and looking for advice/feedback, the code below implements the Marching Squares Algorithm which is detailed here.
While the implementation appears correct and gives the same result as the example on the Wikipedia page, I think that some of the code could be improved and I'm looking for general feedback on how.
In particular,

how I handle vectors
the 2x2 sliding matrix that moves across the test data
where I OR in a value

#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <vector>
using std::vector;

void ApplyThreshold(vector<vector<int>> &Matrix2D, int threshold);
vector<vector<int>> CreateContourMatrix(vector<vector<int>> &pMatrix);

int main()
{

    const int cutOff = 2;//The value on which to base the creation of contours
    vector<vector<int>> matrix;
    //Setup test data
    matrix.push_back(vector<int> { 1, 1, 1, 1, 1 });
    matrix.push_back(vector<int> {1, 2, 3, 2, 1, });
    matrix.push_back(vector<int> {1, 3, 3, 3, 1, });
    matrix.push_back(vector<int> {1, 2, 3, 2, 1, });
    matrix.push_back(vector<int> {1, 1, 1, 1, 1, });

    vector<vector<int>> pMatrix = matrix;

    ApplyThreshold(pMatrix, cutOff);//Establishthe contours
    auto contourMatrix = CreateContourMatrix(pMatrix);//Build contour shapes
    //Print the result
    for (auto contour_row : contourMatrix)
    {
        for (int element : contour_row)
        {
            std::cout << element << '\t';
        }
        std::cout << std::endl;
    }
    return 0;
}
/*
 * Move a 2x2 window across a 2d matrix, calculating contour shapes
 */
vector<vector<int>> CreateContourMatrix(vector<vector<int>> &pMatrix)
{
    vector<vector<int>> contourMatrix;
    //vector<int> rows[5];
    for (int i =0;i<pMatrix.size() - 1;i++)
    {
        vector<int> row;//Should this allocation be moved out of the for loop?

        for (int j=0;j<pMatrix[0].size() - 1;j++)//Assume that all rows of the image are the same size
        {
            int shape = 0;
            if (pMatrix[i][j] == 1)
                shape = shape | 8;
            if (pMatrix[i][j + 1] == 1)
                shape = shape | 4;
            if (pMatrix[i+1][j] == 1)
                shape = shape | 1;
            if (pMatrix[i+1][j+1] == 1)
                shape = shape | 2;
            row.push_back(shape);
        }
        contourMatrix.push_back(row);
    }
    return contourMatrix;
}

void ApplyThreshold(vector<vector<int>> &Matrix2D, int threshhold)
{
    for (auto rowVector : Matrix2D)
    {
        for (auto vectorValue : rowVector)
        {
            if (vectorValue >= threshhold)
                vectorValue = 1;
            else
                vectorValue = 0;
        }
    }
}

This isn't supposed to be a complete implementation, i.e. I don't deal with ambiguous cases or actually create an image of the contours. Any advice appreciated.


texts:
This is a simple binary search tree implementation written with C++'s templates feature I wrote to learn C++. What improvements would make this cleaner and better as far as C++ practices go, and are there any problems with implementing the algorithm?

#include <iostream>
#include <string>

using namespace std;

template <class T, class V>
class BinarySearchTree {

    struct t_node {
        t_node * parent;
        t_node * left;
        t_node * right;

        T data;
        V value;
        // Sorted by Value
    };

    t_node * root;

    t_node* getMin() {
        return getMin(root);
    }
    t_node* getMin(t_node * x) {
        while (x->left !=nullptr) {
            x = x->left;
        }
        return x;
    }

    t_node* getMax() {
        t_node * x = root;
        while (x->right != nullptr) {
            x = x->right;
        }
        return x;
    }

    t_node* sucessor(t_node* x) {
        if (x->right != nullptr) {
            return getMin(x->right);
        }
        t_node * y = x->parent;
        while (y!=nullptr && x==y->right) {
            x = y;
            y = y->parent;
        }
        return y;
    }

public:

    void inOrderTreeWalk() {
        inOrderTreeWalk(root);
    }

    // Needs Stream Overload on template T type to work.
    void inOrderTreeWalk(t_node * x) {
        if (x != nullptr) {
            inOrderTreeWalk(x->left);
            cout << x->data;
            inOrderTreeWalk(x->right);
        }
    }

    T search(V keyword) {
        t_node * x = root;
        while (x!=nullptr && keyword != x->value) {
            if (keyword < x->value) {
                x = x->left;
            }
            else x = x->right;
        }
        return x->data;
    }

    void insert(V keyword, T object) {
        // Create t_node;
        t_node * z = new t_node;
        z->value = keyword;
        z->data = object;

        t_node * y = nullptr;
        t_node * x = root;

        while (x!= nullptr) {
            y = x;
            if (z->value < x->value) {
                x = x->left;
            }
            else x = x->right;
        }
        z->parent = y;
        if (y == nullptr) {
            root = z;
        } else if (z->value < y->value) {
            y->left = z;
        } else y->right = z;
    }
};

// Demo Code
int main(int argc, const char * argv[]) {

    string Charles = "Charles Finny";
    string CharlesD = "Personal Assistant";
    string Bob = "Bob of Yorkshire";
    string BobD = "Unkown";
    string Sam = "Sam Smith";
    string SamD = "Programmer";
    string Mary = "Mary Jane";
    string MaryD = "Manager";

    BinarySearchTree<string, string> EmployeeRecords;
    EmployeeRecords.insert(Charles, CharlesD);
    EmployeeRecords.insert(Bob, BobD);
    EmployeeRecords.insert(Sam, SamD);
    EmployeeRecords.insert(Mary, MaryD);

    string result = EmployeeRecords.search("Sam Smith");
    cout << result << "\n" ;
    EmployeeRecords.inOrderTreeWalk();

    return 0;
}