Find number of unique paths to reach opposite grid corner I have m x n grid. m >= 1 ; n >= 1

I have item in the top-left corner and need to reach bottom-right corner of the grid.

Item can only move either down or right.

I need to find possible unique paths to do it.

I made two solutions for the problem: recursion (slower than the below one) and the one below.

The problem is that I run out of memory when m and n are big e.g. m == 20 and n >= 15 (more than 4 Gb is used - all free memory I have).

How can I improve my solution or there should be absolutely other way to solve the problem?

def unique_paths(m, n):
    assert isinstance(m, int), "m should be integer"
    assert isinstance(n, int), "n shoudl be integer"
    assert m >= 1, "m should be >= 1"
    assert n >= 1, "n should be >= 1"
    if m == 1 and n == 1:  # border case
        return 1

    ch = [(m, n,)]  # for first start
    s = 0  # number of unique paths
    while True:
        new_ch = []
        while ch:
            i = ch.pop()  # I assumed that if decrease len of list it would decrease memory use
            if i[0] == 1 and i[1] == 1:  # we reached opposite corner
                s += 1

            # all other cases:

            elif i[0] != 1 and i[1] != 1:
                new_ch.append((i[0], i[1] - 1, ))
                new_ch.append((i[0] - 1, i[1]))

            elif i[0] == 1 and i[1] != 1:
                new_ch.append((i[0], i[1] - 1,))

            else:
                new_ch.append((i[0] - 1, i[1],))

            del i  # do not need i anymore

        if not new_ch:
            return s
        del ch
        ch = new_ch
        del new_ch

if __name__ == '__main__':
    print(unique_paths(7, 3))  # = 28 - test case

Edit:

lru_cache is really amazing:

from functools import lru_cache

@lru_cache(128)
def numberOfPaths(m, n):
    if m == 1 and n == 1:  # border case
        return 1

    if m != 1 and n != 1:
        return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1)

    if m != 1 and n == 1:
        return numberOfPaths(m - 1, n)

    if m == 1 and n != 1:
        return numberOfPaths(m, n - 1)

if __name__ == '__main__':
    print(numberOfPaths(100, 100))  # 22750883079422934966181954039568885395604168260154104734000

```

Solution: recursion with memoization works really well! Many thanks to Samwise and vnp.

With the help of python lru_cache decorator:

@lru_cache(128)
def number_of_paths(m, n):
    if m == 1 and n == 1:  # border case
        result = 1

    elif m != 1 and n != 1:
        result = number_of_paths(m - 1, n) + number_of_paths(m, n - 1)

    elif m != 1 and n == 1:
        result = number_of_paths(m - 1, n)

    elif m == 1 and n != 1:
        result = number_of_paths(m, n - 1)

    else:
        raise Exception("Something went wrong!")

    return result

With the help of dictionary to store results:

storage = {}
def number_of_paths_no_lru(m, n):
    if storage.get((m, n,)):
        return storage[(m, n)]

    if m == 1 and n == 1:  # border case
        result = 1

    elif m != 1 and n != 1:
        result = number_of_paths_no_lru(m - 1, n) + number_of_paths_no_lru(m, n - 1)

    elif m != 1 and n == 1:
        result = number_of_paths_no_lru(m - 1, n)

    elif m == 1 and n != 1:
        result = number_of_paths_no_lru(m, n - 1)

    else:
        raise Exception("Something went wrong!")

    storage[(m, n, )] = result
    return result

Tests:

if __name__ == '__main__':
    print(number_of_paths(100, 100))
    print(number_of_paths_no_lru(100, 100))
    # Answers:
    # 22750883079422934966181954039568885395604168260154104734000
    # 22750883079422934966181954039568885395604168260154104734000


Game boot to some operations every second I am building game, like Ogame, or Ikariam where you can play with other users in real-time. You train some soldiers, and build some vehicles or buildings. Every building or vehicle has some level. If a building has a higher level you must wait longer to use it etc. I will be grateful for any comments, especially about Scala language.

import java.text.SimpleDateFormat
import java.util.Date

import com.redis._

object worker extends App {

    override def main(args: Array[String]): Unit = {
        println("Worker start...")
        val r = new RedisClient("localhost", 6379)
        var i: Int = 0

        while (true) {
            Thread.sleep(1000)
            i = i + 1
            val numbers: List[Int] = getUsers(r)
            checkQueue(r, numbers)
        }
    }

    private def checkQueue(r: RedisClient, numbers: List[Int]): Unit = {
        val d1 = new Date()
        val format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val now = new Date()
        for (nr <- numbers) {
            val ranges = r.hkeys("user_" + nr + ":soldier:queue_time")
            ranges match {
                case Some(ss) => for (range <- ss) {
                    val added_time = r.hget("user_" + nr + ":soldier:queue_time", range)
                    val saved = format.parse(added_time.get)
                    val diff = (now.getTime - saved.getTime) / 1000 // diff in sec
                    val interval = r.hget("user_" + nr + ":soldier:interval", range)
                    val modulo = diff % interval.get.toInt
                    if (modulo == 0) {
                        val queue_amount = r.hget("user_" + nr + ":soldier:queue_amount", range)
                        if (queue_amount.get.toInt >= 1) {
                            r.hincrby("user_" + nr + ":soldier:amount", range, 1)
                            r.hincrby("user_" + nr + ":soldier:queue_amount", range, -1)
                        }
                    }
                }
                case None =>
            }
        }
        val d2 = new Date()
        println("loop time: " + (d2.getTime - d1.getTime) + " milliseconds")
    }

    private def getUsers(r: RedisClient): List[Int] = {
        val list = r.keys("*user_*:soldier:interval*")
        var numbers = List[Int]()

        list match {
            case Some(s) => for (k <- s) {
                val key = k.get
                val nr = key.replaceAll("[^0-9?]", "")
                numbers = nr.toInt :: numbers
            }
            case None =>
        }
        numbers
    }
}

The first problem with this code is that there is too little explanation for anything. There is no documentation. There is a referenced class RedisClient for which there is no explanation of what it is and how it is being used. The variable names tend to be undescriptive. When asking other people to read code, then it is the author's responsibility to make it so that they actually can read and follow the code.

The next major problem is a classic issue for newer programmers (and something I have been guilty of myself) - big monolithic procedures, specifically checkQueue. When the size of a procedure exceeds a reasonable size (definition of reasonable vary from person to person, but certainly no more than 10 lines), then the developer should look very hard for ways to refactor it and extract out pieces of discrete functionality. In this code, everything inside the for (range <- ss) block should almost certainly be extracted into a function of its own (with a descriptive function name).

I would recommend fixing these two issues and then post a new question asking for a new review of the modified code.


Row-wise mean imputation in R Someone on SO asked how to fill in the NA's with row means. His example code was:

cancer1 <- read.table("cancer.txt", stringsAsFactors = FALSE, quote='', header=TRUE,sep='\t')

Since he didn't provide the data I think we can simulate it with:

cancer1 <- data.frame(a=rep(c(1,2,3,NA),10),b=rep(c(1,2,3,4),10), c=seq(1,40,1))

Just bear in mind that the example data is an arbitrary simulation.

My answer was:

for(i in 1:nrow(cancer1)){
  for(n in 1:ncol(cancer1)){
    if(is.na(cancer1[i,n])){
        cancer1[i,n]  <-  mean(t(cancer1[i,]), na.rm = T)# or  rowMeans(cancer1[i,], na.rm=T)
    }
    }
}

I know that this can be vectorized and otherwise improved, but I'm just not sure how.

You can use rowMeans with indexing.

k <- which(is.na(cancer1), arr.ind=TRUE)
cancer1[k] <- rowMeans(cancer1, na.rm=TRUE)[k[,1]]

Where k is an indices of the rows with NA values.


Site creation file with PHP Here is something I've been working on today..

I been trying to determine how to build a website, that has a form, and that form allows a user to make a simple URL to give out. In the future it will also create a website, or possible websites (based off of varying templates that I have built for it).

I just started trying to understand this today, so bear with me...

So far, as far as I am aware, all of the code works and accomplishes the following:

Allows a user to input a Website name.. I keep both a version with spaces, and a version without spaces.
It creates a directory for that name with no spaces, and it creates a index.php in that directory.
It then displays the link to said directory(will not work on this code because I use a generic primary domain name).

Example Test Domain:

  www.PrimaryDomain.com/Test/

Example User Input:

$_POST['Dir'] = 'Test User Domain';

<?php
//Make sure server is in post mode
if($_SERVER['REQUEST_METHOD'] != 'POST')
    {
        //display form
        echo'<form name="" action="" method="post" class="wpcf7-form" >';
            echo'<input name="Dir" type="text" placeholder="Username" required autofocus>';
            echo'<input type="submit" value="Start" class="wpcf7-form-control wpcf7-submit">';
        echo'</form>';
    }
else
{
    //Specify the URL
    $Name = mysql_real_escape_string($_POST['Dir']); //form data
    $CurrentDir = getcwd(); //current directory
    $URL = ''.$CurrentDir.'/'.$Name.'/'; //New url to create

    //Speciy the file to create
    $Index_file = ''.$URL.'index.php'; //location of new index.php file

    //Remove the spaces, and make each it's own variable
    $Index_file = str_replace(' ', '', $Index_file); //the location of index.php
    $Dir_No_Space = str_replace(' ', '', $URL); //the main directory
    $Name_No_Space = str_replace(' ', '', $Name); //the form data the user entered

    mkdir('/'.$Dir_No_Space.'', 0777, true); //make the directory
    $handle = fopen($Index_file, 'w') or die('Cannot open file:  '.$Index_file); //Create the index.php File

    //Source code of the File: index.php
    $index_data = '

This is an example

    ';

    fwrite($handle, $index_data); //write the source code to the index.php file

    //Check the Document Creation
    if(!fwrite)//if error
        {
        echo'Error
';
        echo mysql_error(); //debugging
        }

    else//if not error
        {
        //tell the user how to access the new page
        echo'
This is a test in progress for '.$Name.' View @ www.PrimaryDomain.com/Test/'.$Name_No_Space.'/.';
        }
}
?>

What do you guys/gals think? Is there a better method for this?

It's bizarre that you are calling mysql_escape_string() and mysql_error() for code that has nothing to do with MySQL.  Why are you calling arbitrary escaping functions?  You should always know why you are escaping a string.

The most severe problem is that you don't validate the $_POST['Dir'].  If the file path contains ../, then the script will overwrite any file of the attacker's choosing, subject only to the permissions of the webserver process.

The space/no-space scheme is baffling.  Why are you doing that?  You should either eliminate all characters that fall outside a safe set (e.g. A-Z, a-z, 0-9, dot, hyphen, and underscore), or diligently apply percent-encoding to URLs.


AES encryption/decryption using pure .NET and streams I'm trying my hand at simple encryption and decryption.  Ideally I'd like to be doing it the 'right' way, ie something secure without doing it in a way that will have a serious hole.  I'd prefer to do this using just the standard .NET libraries, rather than utilising an external library.  If what I'm doing is horrendously wrong, and simply isn't possible without a third-party library, please let me know!

Anyway, I've done a bit of research online, found various different examples (including on Stackoverflow), and found myself confused as to the best way to go about doing things.

I want to take advantage of streams if possible, ie CryptoStream, etc.  This way I can then take say, a FileStream or a MemoryStream and encrypt/decrypt them as desired.

This code is intended mainly 'proof of concept and how I should go about doing things'.  It's got a generated key, a generated iv, and it seems to work with the example string I have there.

It's all one simple application.  However, in theory, rather than encrypting a string, I'd be encrypting a file that is on some webserver, and sending the encrypted file over a web-service, and decrypting it client-side.  That's the idea.

I've read that it's good practice to generate a random key.  If I do that, then both the server and the client would need to know the same key.  I assume this would then mean that I'd need to transmit the key in the call to the web-service from the client.  Is that correct?  Is that secure?  I'd assume that the call to it would be done via HTTPS, but is there anything else I'd need to be aware of in that scenario?

The code I've provided is in VB.NET, and is below.  Be brutal!  If there is need of any further information, ask in the comments and I will try to provide it!

Module Module1

    Sub Main()
        Using   aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create()

            Dim unencryptedValue As String = "My test string"
            Console.WriteLine("Unencrypted: " & unencryptedValue)

            Dim encryptedData As Byte() = Encrypt(aes.Key, System.Text.UTF8Encoding.UTF8.GetBytes(unencryptedValue))
            Dim decryptedData As Byte() = Decrypt(aes.Key, encryptedData)
            Dim decryptedValue As String = System.Text.UTF8Encoding.UTF8.GetString(decryptedData)

            Console.WriteLine("Decrypted: " & decryptedValue)
            Console.ReadKey()
        End Using
    End Sub

    Public Function Encrypt(key As Byte(), unencryptedData As Byte()) As Byte()
        Using   aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create(),
                ms_unencrypted As New IO.MemoryStream(unencryptedData),
                ms_encrypted As New IO.MemoryStream()

            Using cs As New Security.Cryptography.CryptoStream(ms_encrypted, aes.CreateEncryptor(key, aes.IV), Security.Cryptography.CryptoStreamMode.Write)
                ms_encrypted.Write(aes.IV, 0, aes.IV.Length)
                ms_unencrypted.CopyTo(cs)
            End Using

            Return ms_encrypted.ToArray()
        End Using
    End Function

    Public Function Decrypt(key As Byte(), encryptedData As Byte()) As Byte()
        Using   aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create(),
                ms_encrypted As New IO.MemoryStream(encryptedData, 0, encryptedData.Length, False, True),
                ms_decrypted As New IO.MemoryStream()

            Dim iv(15) As Byte
            ms_encrypted.Read(iv, 0, 16)

            Using cs As New Security.Cryptography.CryptoStream(ms_encrypted, aes.CreateDecryptor(key, iv), Security.Cryptography.CryptoStreamMode.Read)
                cs.CopyTo(ms_decrypted)

            End Using

            Return ms_decrypted.ToArray()

        End Using
    End Function

End Module

Let's talk about your code then we'll talk about that paragraph of text you have.

First off:

Using   aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create(),
        ms_unencrypted As New IO.MemoryStream(unencryptedData),
        ms_encrypted As New IO.MemoryStream()

This is largely not pleasant to read. You have ms_ hungarian (IIRC) notation, and you have everything aligned funky, and it's just visually unpleasant. Let's fix that:

Using aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create(),
    unencryptedStream As New IO.MemoryStream(unencryptedData),
    encryptedStream As New IO.MemoryStream()

Alright, that doesn't do much but it does start pushing things into motion.

You state in your question:

  I want to take advantage of streams if possible

But the API doesn't use any streams! It requires you to pass a byte[], why not allow streams to be used? Then you eliminate that unencryptedStream in Encrypt and the encryptedStream in Decrypt entirely. Let the caller deal with the stream mechanics.

Next, why not allow the caller to get a Stream back out? You still force the caller to deal with a byte[] in the end, we could eliminate that.

Public Sub Encrypt(key As Byte(), unencrypted As MemoryStream, encrypted As MemoryStream)
    Using aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create()
        Using cs As New Security.Cryptography.CryptoStream(encrypted, aes.CreateEncryptor(key, aes.IV), Security.Cryptography.CryptoStreamMode.Write)
            encrypted.Write(aes.IV, 0, aes.IV.Length)
            unencrypted.CopyTo(cs)
        End Using
    End Using
End Function

Now you have no responsibility for the streams, but once we see this we could also build a version that takes a byte[] and returns a byte[] to wrap this version. Then our API is clear, concise, and robust.

And then there's this paragraph:

  I've read that it's good practice to generate a random key. If I do that, then both the server and the client would need to know the same key. I assume this would then mean that I'd need to transmit the key in the call to the web-service from the client. Is that correct? Is that secure? I'd assume that the call to it would be done via HTTPS, but is there anything else I'd need to be aware of in that scenario?

While HTTPS is good and all, using AES to encrypt data between a server/client is not really a great idea. Encryption has the concept of a 'public key' and a 'private key', some algorithms use both, some only use one. In the case of AES, it uses one key: a private key.

The names themselves should give things away, but I'll be explicit anyway:

public key: This key can be shared with anyone, and should be available for all persons wishing to use the system.
private key: This key should be kept as secret as possible, and not shared unless absolutely required. This is the key that, without which, attackers cannot easily reverse encryption.

Now AES uses only a private key as both encryption and decryption. This is known as symmetric encryption or a symmetric encryption algorithm. What you are discussion requires something else, known as asymmetric encryption or an asymmetric encryption algorithm.

These algorithms come it two major variants: those that use the public key for encryption and the private key for decryption, and those that use the private key for encryption and the public key for decryption.

The option you pick depends on your use-case. In the case of something being shared from server -> client, you would pick an algorithm that uses the private key for encryption, since the server is entirely under your control. You can keep things on it a secret. You cannot keep things on the client a secret, so it should get a public decryption key. Then to send data back you should have a second algorithm that does the opposite, and uses the public key for encryption.

The next option is to have the client establish a connection to the server, then use a public key encryption algorithm (such as RSA - where the public key is the encryption key) to send it's AES key. Then you can use AES for the remaining communication between the server and the individual clients. This is the most common type of scenario with RSA, as it's very expensive to use for encryption and decryption.

If you're using HTTPS, however, there's no need to build a sophisticated mechanism to further encrypt your information. HTTPS already provides a secure communication session between client/server, though it doesn't hurt to add more security in general, it can have drastic performance impacts if done wrong or 'over the top'.


Getting items with overlapping DateTime using Linq I have a live chat database and I am trying to get an idea of how many concurrent chats staff are taking. I'm not sure of the best way to report it so I have decided to get a list of chats for a given period then for each one display a count of chats that overlapped that one in some way.

I am querying 2 tables across a join but this is just to get the Operators name. The fields that have the relevant dates are:

DateTime? ChatRequests.Answered
DateTime? ChatRequests.Closed

I think I have everything covered. I just want to see if anyone can tell me if I'm missing anything, or if there is a better approach to it.

ChatRequests
.Where (cr => (cr.Created.AddHours (10).Date == DateTime.Now.AddDays (-1).Date))
.Where (cr => cr.OperatorID.HasValue)
.Join (
    Operators,
    chat => chat.OperatorID.Value,
    op => op.ID,
    (chat, op) =>
        new
        {
            chat = chat,
            op = op
        }
)
.Select (
    g =>
        new
        {
            Operator = g.op.FullName,
            Answered = g.chat.Answered.Value.AddHours (10),
            Closed = g.chat.Closed.Value.AddHours (10),
            Duration = (Decimal)((g.chat.Closed.Value - g.chat.Answered.Value).TotalMinutes),
            Company = g.chat.AccountName,
            Contact = g.chat.ContactName,
            OtherChatsInSamePeriod = ChatRequests
                        .Where (cr => (cr.OperatorID == g.chat.OperatorID))
                        .Where (cr => (cr.ID != g.chat.ID))
                        .Where (
                           cr =>    (cr.Answered.Value >= g.chat.Answered.Value && cr.Answered.Value <= g.chat.Closed.Value)
                                     || (cr.Closed.Value >= g.chat.Answered.Value && cr.Closed.Value <= g.chat.Closed.Value)
                                     || (cr.Answered.Value < g.chat.Answered.Value && cr.Closed.Value > g.chat.Closed.Value)
            )
            .Count ()
        }
)

A faster version of your final where clause is:

cr.Answered.Value <= g.chat.Closed.Value && cr.Closed.Value >= g.chat.Answered.Value

If you do not want to count end points as overlapping (e.g. a call ending exactly at 9:59 and a call beginning exactly at 9:59 do not overlap) then use:

cr.Answered.Value < g.chat.Closed.Value && cr.Closed.Value > g.chat.Answered.Value

You can also remove the .Where (cr => (cr.ID != g.chat.ID)) condition and subtract 1 from the total count since it should be guaranteed that there is only one call taking place by the same operator during the same time period in question.


Finding overlaps between two lists of axis-aligned rectangles I am trying to find an efficient solution for finding overlapping of n rectangles where rectangles are stored in two separate lists. We are looking for all rectangles in listA that overlap with rectangles in listB (and vice versa). Comparing one element from the first list to second list could take immensely large amount of time. I am looking for an efficient solution.

I have two lists of axis-aligned rectangles:

rect = Rectangle(10, 112, 56, 15)
rect2 = Rectangle(0, 0, 1, 15)
rect3 = Rectangle (10, 12, 56, 15)

listA = [rect, rect2]
listB= [rect3]

which is created from the class:

import numpy as np
import itertools as it

class  Rectangle(object):
    def __init__(self, left, right, bottom, top):
        self. left = left
        self.bottom = bottom
        self.right = right
        self.top = top

    def overlap(r1, r2):
        hoverlaps = True
        voverlaps = True
        if r1.left > r2.right or r1.right < r2.left:
            hoverlaps = False
        if r1.top < r2.bottom or r1.bottom > r2.top:
            voverlaps = False
        return hoverlaps and voverlaps

I need to compare rectangle in listA to listB the code  goes like this which is highly inefficient - comparing one by one

for a in it.combinations(listB) :
    for b in it.combinations(listA):
        if a.overlap(b):

Any better efficient method  to deal with the problem?

Dec. 10, 2018

The simple answer is to use a 2-d segment tree.

Given that we have low value for dimension (i.e. two), an appropriate approach would be to use a 2-d segment tree. We use what is known as stabbing query or intersection query. Let list one be the list that is smaller. Store all rectangles from list one in such a tree. Query using rectangles from list two. Time to construct and query are \$O(n_1 \cdot \log^2(n_1))\$ and \$O(\log^2(n_1) \cdot k)\$, respectively, s.t. \$k\$ is number of matches to report. If we use fractional cascading and interval tree, times become \$O(n_1 \cdot \log(n_1))\$ and \$O(\log(n_1) \cdot k)\$, respectively. Assuming these better times, time for all queries is \$O(\textrm{max}(n_2, k_\textrm{overall}) \cdot \log(n_1))\$. Overall time becomes \$O((\textrm{max}(n_2, k_\textrm{overall}) + n_1) \cdot \log(n_1))\$. Given that \$k_\textrm{overall}\$ is in \$O(n_1 \cdot n_2)\$, time could be loosely \$O((n_1 \cdot n_2) \cdot \log(n_1))\$.

If rectangles are not axis-aligned, one might wish to have bounding boxes and then use a tree. In principle we then could use a segment tree again, but a natural alternative (though we usually do not have good guaranteed theoretical running time for it unless we use "look-ahead") could be an R-tree.


Given a list of integers, write a function that returns the largest sum of non-adjacent numbers? Numbers can be 0 or negative Given a list of integers, write a function that returns the largest
  sum of non-adjacent numbers. Numbers can be 0 or negative.

  For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and
  5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.

  Follow-up: Can you do this in O(N) time and constant space?

class DailyCodingProblem9 {

    public static void main(String args[]) {

        int arr[] = { 2, 4, 6, 2, 5, 13 };
        int res = solution(arr);
        System.out.println(res);

        int arr1[] = { 1, 0, 3, 9, 2, 14 };
        res = solution(arr1);
        System.out.println(res);
    }

    static int solution(int[] arr) {
        int n = arr.length;
        int[] maxArr = new int[n];
        int max = 0;
        for (int i = n - 1; i > 0; i--) {
            maxArr[i] = findLargestSum(arr, i, n, maxArr);
            max = Math.max(max, maxArr[i]);
        }
        return max;

    }

    static int findLargestSum(int[] arr, int i, int n, int[] max) {
        System.out.println(i);
        if (max[i] != 0) {
            return max[i];
        }
        if (i == 0 || i == 1) {
            return arr[i];
        }
        if (i - 2 == 0) {
            return arr[i] + findLargestSum(arr, i - 2, n, max);
        }
        return arr[i] + Integer.max(findLargestSum(arr, i - 2, n, max), findLargestSum(arr, i - 3, n, max));

    }

}

How do I solve it in constant space? I found an answer here, but could not understand the logic.

What you implemented is the recursive solution:

sum(k)
  | k < 0 = 0
  | otherwise = max( sum(k-1), sum(k-2) + arr[k] )

You can also implement it iteratively using an O(n) extra space:

sum = int[n]
sum[0] = max(      0, arr[0] )
sum[1] = max( sum[0], arr[1] )
for (int k = 2; k < n; k++)
{
    sum[k] = max( sum[k-1], sum[k-2] + arr[k] )
}

You may notice that nothing but the two rightmost values will ever be used in the next iteration. We can get rid of the array entirely and store only those values instead, which leads to O(1) space usage.

s2 = max(  0, arr[0] )
s1 = max( s2, arr[1] )
for (int k = 2; k < n; k++)
{
    s0 = max( s1, s2 + arr[k] )
    s2 = s1
    s1 = s0
}


C# Convert BLOB to jpg, resize, then back to BLOB I am trying to convert a BLOB that is stored in a database to a JPG and then I need to display it on an html form in a C# application.
A little backstory first - this is an older web app that was designed to take a JPG (photo) that was stored as a path in the database, resize it, then show as a BLOB. This functionality needs to stay in place, but now one of the systems is changing and the photo is going to be stored in the database as a BLOB instead of a path to a photo (\servername\images\xyz.jpg).
One system still needs the image to be resized then sent back as a BLOB to display. The other systems that call this web-app will need the BLOB converted to a JPG to display.
The code below works, but I think it might have put an unnecessary load on the server, because this morning the system was laggy and some features were impossible to use. I have a feeling that the .Save is the troublemaker here since I am calling it twice. I know the image doesn't need to be saved anywhere physically, as long as the web-app can call and have it display to the site. Is there anything I can change here to skip saving an image on the server and just display it so it doesn't use up a ton of resources?
protected void Page_Load(object sender, EventArgs e)
{
   byte[] byteImage = null;
    string ID = Request.QueryString["id"];
    string imageFile = "\\\\server\\c$\\inetpub\\wwwroot\\web-app\\images\\" + ID+ ".jpg";
    string server = Request.ServerVariables["server_name"];
    var serverNameList = db.Servers.Select(x => x.ServerName).ToList();

    connection.Open();
    SqlCommand sqlCommand = new SqlCommand("sp", connection);
    sqlCommand.Parameters.Add("@ID", SqlDbType.VarChar);
    sqlCommand.Parameters["@ID"].Value = ID;
    sqlCommand.CommandType = CommandType.StoredProcedure;
    SqlDataReader dr = sqlCommand.ExecuteReader();

    while (dr.Read())
    {
        byteImage = (byte[])dr["BLOB"];
    }

    if (byteImage != null)
    {
        using (MemoryStream ms = new MemoryStream(byteImage))
        {
            //saving to jpg image
            Image img = new Bitmap(ms);
            img.Save(imageFile, ImageFormat.Jpeg);

            Response.Clear();
            Response.CacheControl = "public";
            Response.Cache.SetExpires(DateTime.Now.AddDays(1.0));
            Response.ContentType = "Image/jpeg";

            if (serverNameList.Contains(server)) // if user is coming from a specific server, resize the image then send back
            {
                byte[] resizedImage = GetResizedImage(imageFile, 300, 400);
                Response.OutputStream.Write(resizedImage, 0, resizedImage.Length);
            }
            else // skip resize and show image as jpg
            {
                Response.BinaryWrite(byteImage);
            }
        }
    }
    else // image is null
    {
        imageFile = HttpRuntime.AppDomainAppPath + "PERSON.GIF";
    }
}

private byte[] GetResizedImage(string path, int width, int height)
{
    Bitmap bitmap1 = new Bitmap(path);
    double height1 = bitmap1.Height;
    double width1 = bitmap1.Width;
    double num = 1.0;
    if (width > 0)
        num = width / width1;
    else if (height > 0)
    num = height / height1;
    MemoryStream memoryStream = new MemoryStream();
    Bitmap bitmap2 = new Bitmap((int)(width1 * num), (int)(height1 * num));
    bitmap2.SetResolution(150f, 150f);
    Graphics graphics = Graphics.FromImage(bitmap2);
    graphics.CompositingQuality = CompositingQuality.HighQuality;
    graphics.Clear(Color.White);
    graphics.DrawImage(bitmap1, new Rectangle(0, 0, (int)(num * width1), (int)(num * height1)), new Rectangle(0, 0, (int)width1, (int)height1), GraphicsUnit.Pixel);
    bitmap2.Save(memoryStream, ImageFormat.Jpeg);
    return memoryStream.ToArray();
}

Welcome to CodeReview! I hope you get some good feedback.
Absolute paths
string ID = Request.QueryString["id"];
string imageFile = "\\\\server\\c$\\inetpub\\wwwroot\\web-app\\images\\" + ID+ ".jpg";

This has a few issues. First, it's typical for a server to be in a "jail" where it shouldn't have access to the filesystem at large, and should only access data from its own local directory. This is for security purposes. Though I haven't done this in a long time, it seems the ASP.NET way of safely accessing such paths is MapPath.
Second: it's crucially important that you do some validation on ID. In its current state a hacker could easily construct a path navigation exploit where the ID contains ..\..\.. (etc) to explore the rest of the filesystem if the server is misconfigured.
Managing your connection
If connection is an SqlConnection, it implements IDisposable, and as such you should put it in a using. The same is true of SqlCommand.
Add-with-value
You should prefer AddWithValue over a separated Add/.Value assignment here;
sqlCommand.Parameters.Add("@ID", SqlDbType.VarChar);
sqlCommand.Parameters["@ID"].Value = ID;

Read-in-loop
This:
while (dr.Read())
{
    byteImage = (byte[])dr["BLOB"];
}

should probably not use a loop. Since it seems you expect only one row returned,

Read() once;
assert that it returned true;
assign byteImage;
Read() again;
assert that it returned false.

Streamed image creation
GetResizedImage creates a memory stream. It should not. Response already has an OutputStream, and you should be writing to that directly. The one thing to double-check with this approach is that Content-Length is still set correctly, which is probably only possible if BufferOutput is enabled.
Avoiding files
As to your original question, which I never really addressed:

Is there anything I can change here to skip saving an image on the server and just display it so it doesn't use up a ton of resources?

Yes! As long as you get an image from the database, you always Save() it to the disc. However, this file is only used if the server name is approved. Move your save within the name check, and fewer cases will require disc I/O.
Even further: if this is the only code that touches that file, that file should not exist at all and you should not be doing a round trip to the disc. Once you have your img, pass that to GetResizedImage instead of a path string.
Bug?
There is a mechanism here:
imageFile = HttpRuntime.AppDomainAppPath + "PERSON.GIF";

which looks like it's supposed to substitute a default image if none is returned from the database. However, that file is never used. This logic needs to be rearranged so that it is. If you get back a null from the database, load this file into your byteImage.


Test runner for Scala problems I'm learning Scala and could use another set of eyes on the code below. I'm creating a test runner for the 99 scala problems set. I figure between actually solving the problems and working through the pains of setting up a new IDE (trying IntelliJ from Eclipse), using new build tools (trying SBT from Maven), new testing tools etc, I'll have the language down pat. The code below is a runner that grabs all the solution files in a given directory and executes them. While the code works, I can't help but feel as though I'm doing this in the 'Java' way and not the 'Scala' way (ie - I'm not being very 'functional' in my implementation). Does anyone who knows Scala pretty well have any comment on what I've written thus far?

runner:

import java.io.File
import org.apache.commons.io.FilenameUtils

/**
 * boodstraps program
 */
object bootStrap {

    def main(args: Array[String]): Unit = {

      // go through solution files and execute
      for (fName <- getSolutionFiles(new File("./src/main/scala"))) {
        val fNameNoExtS = FilenameUtils.removeExtension(fName.getName)
        solutionRunner(fNameNoExtS)
      }

    }

    def solutionRunner(name: String): Unit = {
      println(name)
      val classLoader = this.getClass.getClassLoader
      val clazz = classLoader.loadClass(name)
      val solutionMethod = clazz.getDeclaredMethod("solution")
      solutionMethod.invoke(clazz.newInstance)
    }

  /**
   * trolls through working directory and all sub directories in search of files
   * with names starting with "sp_" ('sp' for 'scala problem'). thanks to
   * stack overflow for base code: http://stackoverflow.com/questions/2637643/
   * how-do-i-list-all-files-in-a-subdirectory-in-scala
   *
   * @param f - java File object
   * @return targetFileList - Array[java.io.File] - list of file objects
   *         that have names starting with "sp_"
   */
    def getSolutionFiles(f: File): Array[File] = {
      // create lists of files, directories, and target files
      val fullFileList = f.listFiles
      val targetFileList = fullFileList.filter(_.getName.matches("^sp_.*"))
      val dirList = fullFileList.filter(_.isDirectory)

      // recursively append target files located in sub directories to list.
      // return populated list to caller.
      targetFileList ++ dirList.flatMap(getSolutionFiles)
    }

}

simple 'sp' file:

class sp_01 {

  def solution(): Unit = {
    println("in sp_01, baby!")
  }

}

Idiomatic Scala Style

Class, object, and trait names follow camelCase style with the first letter capitalized. One example where you don't follow this rule is abstract class spMeta extends logging.

For a few reasons, it is considered bad practice to user underscores in names. Applying the convention from the bullet point above with this we'd make the following transformation to your code: class sp_01 extends spMeta => class Sp01 extends SpMeta.

The above rules also extend to types that you define. Consequently I'd change type inputT to type InputT, etc.

Methods which act as accessors should be declared without parenthesis (unless they have side effects). In particular this applies to your def getSolution(): SolutionT = ... which should just be plain old parenthesis-less def getSolution: SolutionT = ...

If you ever have any style questions check out this documentation.

Code Suggestions
A modified version of your getSolutionFiles method with explanations below.
    def getSolutionFiles(dir: File): Array[File] = {
        val dirContents = dir.listFiles
        val targetFiles = dirContents filter(x => x.getName.startsWith("sp_") && !x.isDirectory)
        val childDirs   = dirContents filter(_.isDirectory)
        targetFiles ++ childDirs flatMap(d => getSolutionFiles(d))
    }

I renamed the method paramter to dir from file.
All of the operations in this method are on the container type Array.  So I renamed some of the values to remove any mention of List.
Overall I think the renaming of these values make this method much easier to to immediately comprehend.
Just to show you 'another way' and not because I thought anything was wrong with your original choice, I replaced your use of a regular expression for finding the correct files with startsWith(...). Note there is also a method endsWith(...).
A bug could occur if the name of a file passed your filter predicate but is in fact a directory. I added a condition to to eliminate that possibility.

Cheers :)


Node refactor if/else mess I'd love some pointers on how to refactor this

async function validate_request_args(req, request_type) {
    let problem_id;
    const errors = [];
    switch (request_type) {
        case "post":
            if (req.body.id == null) {
                errors.push({
                    msg: "Missing id of the problem",
                    param: "id"
                });
            } else {
                problem_id = req.body.id;
            }
            break;

        case "get":
            if (req.query.id == null) {
                errors.push({
                    msg: "Missing id of the problem",
                    param: "id"
                })
            } else {
                problem_id = req.query.id;
            }
            break;
    }
    if (errors.length === 0) {
        const problem = await models.Problem.findByPk(problem_id);
        if (problem == null) {
            errors.push({
                msg: `Problem with id ${problem_id} does not exist `,
                param: "id"
            });
        }
        return monet.Validation.success(problem)
    }
    return monet.Validation.fail(errors);
}

To start with, I see what's likely to be a logic error. At the bottom, you do:

if (problem == null) {
    errors.push({
        msg: `Problem with id ${problem_id} does not exist `,
        param: "id"
    });
}
return monet.Validation.success(problem)

If the problem isn't found, you push an error object to the errors array, but then you return .success anyway and don't use the errors array again. In such a case, I think you want to call monet.Validation.fail with the error object instead, and not call .success.

Once that's done, note that you only ever have at most one element in the errors array, which .fail gets called with. It would be less repetitive to immediately call .fail and return when an error is encountered. Also, since the fail calls are all similar (monet.Validation.fail([{ msg: SOME_MESSAGE, param: 'id' }])), you can make the code DRY by putting that into a helper function:

const fail = msg => monet.Validation.fail([{ msg, param: 'id' }]);

Also, switch is almost never the right tool for the job IMO - it's quite verbose and can be error-prone when one forgets to break (which is surprisingly common). If the request type will be either post or get, use the conditional operator to figure out the property to look up on req instead:

const { id } = req[requestType === 'post' ? 'body' : 'query'];

I'd highly recommend against using loose equality ==. It requires an expectation that any reader of the code understands its strange rules. Better to use strict equality. Or, if the id or problem, if it exists, will be truthy (which sounds likely), it would look even nicer to use a truthy test:

if (!id) {
    return fail('Missing id of the problem');
}

If you actually need the logic you're implementing with == to check that the expressions aren't null and aren't undefined (but could be anything else, including other falsey values), then best to test both of those explicitly:

if (id === null || id === undefined) {
    return fail('Missing id of the problem');
}

I think it would also be useful to follow the standard Javascript naming conventions and use camelCase for variable names in most cases.

All together:

const fail = msg => monet.Validation.fail([{ msg, param: 'id' }]);
async function validateRequestArgs(req, requestType) {
    const { id } = req[requestType === 'post' ? 'body' : 'query'];
    if (!id) {
        return fail('Missing id of the problem');
    }
    const problem = await models.Problem.findByPk(id);
    if (!problem) {
        return fail(`Problem with id ${id} does not exist`);
    }
    return monet.Validation.success(problem);
}


Count the frequency of words in a text file #!/usr/bin/python
file=open("C:/python27/python operators.txt","r+")

wordcount={}

for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1

for k,v in wordcount.items():
    print k, v

Use a Context Manager

When dealing with something like a file, it's safer to write:

with open(filename) as file:
    ## code ##

That will automatically handle file closing correctly in case of exceptions and the like. I also find it clearer. Also, why r+?

Prefer Generators

file.read() reads the entire file into memory. Prefer to just go a line at a time by iterating through it.

wordcount.items() gives you a full list of all the items. But you don't need them all at once, you just need to iterate through them. For that there's iteritems().

Use the tools at your disposal

You have:

if word not in wordcount:
    wordcount[word] = 1
else:
    wordcount[word] += 1

That's a lot of code for a simple operation. What are you doing here? You're counting the incidence of word. But there's an app for that: collections.Counter:

wordcount = collections.Counter()
for line in file:
    for word in line.split():
        wordcount[word] += 1

Furthermore, we also have Counter.update, which lets us do:

for line in file:
    wordcount.update(line.split())

Full solution:

#!/usr/bin/python
import collections

wordcount = collections.Counter()
with open("C:/python27/python operators.txt") as file:
    for line in file:
        wordcount.update(line.split())

for k,v in wordcount.iteritems():
    print k, v


convertToHHMM function Can someone help me make a more elegant solution to this function?

function convertToHHMM(info) {
var suffix='AM';
var hrs = parseInt(Number(info));
var min = Math.round((Number(info)-hrs) * 60);
if (hrs >12) { hrs = hrs - 12; suffix='PM'; }
if (min < 10) {min='0'+min;}
return hrs + ':' + min + ' ' + suffix;
}

It's kinda hard to make it "more elegant", but it can certainly be made more correct.

Since you use Math.round, you can get a time like "3:60 PM" if you pass it 15.999. And I'm preeeetty sure there's no such thing.

There's also another bug. If you pass a value like 0.5, you should get "12:30 AM". But you don't. You get "0:30 AM".

And some nitpicking: First off, info is not a very descriptive name. It looks like you're trying to format a number of hours, with minutes as the decimals, so hours would be a better name. (Edit: or better yet fractionalHours as rolfl suggests, and which I forgot to credit.)

Also, instead of using parseInt (which is meant to turn a string into an integer), use Math.floor, which is what you actually mean: The number without any decimals. For the minutes, you could use the modulo operator (%) to get the remainder of dividing by 1 (i.e. the decimals) instead of subtracting. But either one works.

By the way, even if your input is a string like "12.3231" JavaScript's type coercion will treat it as a number, so you don't really need Number() anywhere, but it's fine to add it.

You can also do something slightly tricky by using modulo 12 on the hours, and default to 12 if the result it zero. That fixes the 0/12 bug mentioned above.

Also, fewer lines do not make things better/faster/more elegant. In this case, it just hurts readability. So use some linebreaks instead of having a line like if (hrs >12) { hrs = hrs - 12; suffix='PM'; }.

Lastly, use some indentation. It may just be a copy/paste thing when you created the question, but still.

I might do something like this, first converting everything to minutes and rounding that, then breaking it into hours and minutes afterward:

function convertToHHMM(fractionalHours) {
  var totalMinutes = Math.round(fractionalHours * 60) % (24 * 60),
      hours = Math.floor(totalMinutes / 60) % 12 || 12,
      minutes = totalMinutes % 60,
      suffix = totalMinutes >= 12 * 60 ? 'PM' : 'AM';

  if(minutes < 10) minutes = '0' + minutes;

  return hours + ':' + minutes + ' ' + suffix;
}

totalMinutes rolls over after rounding, so passing in 23.999 is equivalent to passing in 0, and 27 becomes 3, etc.
hours also roll over but start at 12 instead of zero, then 1, 2, 3 and so on.
minutes should be straight-forward, and
suffix basically looks at whether the totalMinutes are greater than or equal to noon-in-minutes.

Snippet with some test cases below (format borrowed from rolfl).

function original(info) {
var suffix='AM';
var hrs = parseInt(Number(info));
var min = Math.round((Number(info)-hrs) * 60);
if (hrs >12) { hrs = hrs - 12; suffix='PM'; }
if (min < 10) {min='0'+min;}
return hrs + ':' + min + ' ' + suffix;
}

function reviewed(fractionalHours) {
  var totalMinutes = Math.round(fractionalHours * 60) % (24 * 60),
      hours = Math.floor(totalMinutes / 60) % 12 || 12,
      minutes = totalMinutes % 60,
      suffix = totalMinutes >= 12 * 60 ? 'PM' : 'AM';

  if(minutes < 10) minutes = '0' + minutes;

  return hours + ':' + minutes + ' ' + suffix;
}

var testCases = [
  ["12:00 AM", 0],          // midnight
  ["12:30 AM", 0.5],
  ["1:00 AM",  0.99999999],
  ["11:30 AM", 11.5],
  ["12:00 PM", 11.9999999], // noon
  ["12:00 PM", 12],
  ["11:30 PM", 23.5],
  ["12:00 AM", 23.9999999],
  ["12:00 AM", 24],
  ["1:00 AM",  25]
];

var data = "
";
data += "
Input	Expected	Review func	Original func
";
for(var i = 0, l = testCases.length ; i < l ; i++) {
  data += "
";
  data += "" + testCases[i][1] + "	";
  data += "" + testCases[i][0] + "	";
  data += "" + reviewed(testCases[i][1]) + "	";
  data += "" + original(testCases[i][1]) + "	";
  data += "
";
}
data += "
";

document.body.innerHTML = data;
body { font-family: monospace }
table { border-collapse: collapse }
td, th {
  padding: 0.2em 0.5em;
  border: 1px solid #ccc
}


Long running operation with timeout I have a long running operation that I need to wait for or timeout.
I have working code, but I would like your opinion on improving it.

public bool RegisterEquipmentListUpdate(int ID)
{
    if (Authentication.CheckSession(Session))
    {
        var wcfmonitoring = new WCFMonitoring.MonitoringDatabaseClient();
        try
        {
            bool timeout = false;
            DateTime start = DateTime.Now;
            //loop as long as the time isn't reached (600 seconds)
            while (!timeout)
            {
                if (wcfmonitoring.CheckForEquipmentUpdate(Authentication.GetSessionID(Session), Authentication.GetPTO(Session), ID))
                {
                    wcfmonitoring.Close();
                    //sleep before returning true, this is set so the importer can finish multiple files without the client refreshing on the first one
                    Thread.Sleep(2000);
                    return true;
                }
                else
                {
                    //sleep for 10 seconds before trying again
                    Thread.Sleep(10000);
                    //if the elapsed time is more than 10 minutes return false
                    if (start < DateTime.Now.AddSeconds(-600))
                    {
                        wcfmonitoring.Close();
                        return false;
                    }
                }
            }
        }
        catch
        {
            wcfmonitoring.Abort();
        }
    }
    //return false in case of error
    return false;
}

This is a rough draft, since I do not know the overall picture of your project. Some design might be improved to not even use this code (events, semaphores, mutexes, and other more predictable synchronization mechanisms). I rarely use this pattern for code that I control, more for code I cannot that I know is blocking. This approach is risky, as it can lead to undesired state and data loss. You have been warned! (http://thedailywtf.com/articles/My-Tales) for reference!)

If you stay on this path, I recommend A separate class/method be responsible for this sort of behaviour, to favour reuse, this also includes the possibility of having a CancellationToken passed in, just in case you change your mind about the request:

public async Task<T> WaitForActionCompletionOrTimeout<T>(Func<T> action, int timeout, CancellationToken? globalCancellation = null)
{
   var result = default(T); //return default for error

   var localCancellation = new CancellationTokenSource();
   var localAndGlobalCancellation =
            CancellationTokenSource.CreateLinkedTokenSource(localCancellation.Token,
                                                            globalCancellation.HasValue ?
                                                            globalCancellation.Value :
                                                            CancellationToken.None);

   Task cancelationTask = null;
   Task actionTask = null;

   try
   {
     cancelationTask = Task.Delay(timeout, localAndGlobalCancellation);
     actionTask = Task.Factory.StartNew(() =>
     {
       result = action.Invoke();
     }, localAndGlobalCancellation);
   }
   catch (Exception ex)
   {
     Trace.WriteLine(ex.Message);
     localCancellation.Cancel();
     return null;
   }

   await Task.WhenAny(actionTask, cancelationTask).ContinueWith(t => localCancellation.Cancel());
   return result;
}

Change the work method to return true or false, something like:

public bool CheckForUpdate()
 {
     using (var wcfmonitoring = new WCFMonitoring.MonitoringDatabaseClient())
     {
          var sw = new SpinWait();
          while (!wcfmonitoring.CheckForEquipmentUpdate(Authentication.GetSessionID(Session), Authentication.GetPTO(Session), ID)) //maybe  something shorter would work :) some variables are nice for debugging
          {
              sw.SpinOnce();  //magic Thread.Sleep(5) replacement with lots of goodies :) nice class to look at
          }

          Thread.Sleep(2000); //for the importer
          return true;
    }
}

And then:

var success = WaitForActionCompletionOrTimeout(() => CheckForUpdate, 600000 ); //I would so like 6.minutes.in.miliseconds.... ah dreams

This sort of approach (cancelling the worker)  could also be done with threads in a much shorter and brute-forcier way for a slow performance increase in case of very low timeouts.

I would also advise using using and if WcfMonitoring is not IDisposable, to make it IDisposable.

One more question: What is the intent/difference between calling Abort and Close in your code?


Convert scalar arguments to arrays, and check that lengths are equal I've got a Python function that takes two arguments, lat and lon. These arguments can be either scalar values (52.3) or any sort of iterable (e.g. a list or a NumPy array).

At the beginning of my function I need to check what I've been given, and convert both arguments to arrays (if needed) and check that both arguments are the same length.

# Deal with scalar values
try:
    lat_count = len(lat)
except:
    lat = [lat]
    lat_count = 1

try:
    lon_count = len(lon)
except:
    lon = [lon]
    lon_count = 1

if lat_count != lon_count:
    raise ValueError("lan and lon arrays must be the same length")

lat = np.array(lat)
lon = np.array(lon)

It feels horribly messy, but I can't work out how to make it better. Any ideas?

np.atleast_1d handles the conversion in one step.  It's doc reads:

  Scalar inputs are converted to 1-dimensional arrays, whilst
  higher-dimensional inputs are preserved.

In [217]: np.atleast_1d(1)
Out[217]: array([1])
In [218]: np.atleast_1d([1,2,3])
Out[218]: array([1, 2, 3])

So your code simplifies to:

lat = np.atleast_1d(lat)
lon = np.atleast_1d(lon)
if lat.shape != lon.shape:
    <raise error>

Look at the code for atleast_1d; it's instructive.  Bascially it does:

lat = np.array(lat)
if len(lat.shape)==0:
   lat = lat.reshape(1)

Check for yourself what np.array(1) produces.

I could simplify it further with just one call to atleast_1d, since it takes multiple inputs:

lat, lon = np.atleast_1d(lat, lon)


Find unique variants of a product I am writing a piece of code that returns all the unique variants that a product is available in for an ecommerce app.  For example, a shirt product can be available in different colors, sizes, and linen. If the available attributes are red, green, L, XL, Cotton, and Polyester, then a list of the unique variants should be eventually returned as:

[{red; L; Cotton} ; {red; L; Polyester} ; {red; XL; Cotton} ; {red; XL; Polyester} ; {green; L; Cotton} ; {green; XL; Cotton} ; {green; L; Polyester} ;

{green; XL; Polyester}]

This would be the unique variants available for the product.

The code below works and eventually returns a string list of IDs representing each variant available for the product. The only problem that I am having with this is that it generates a duplicate of each variant. I can easily take care of that with a Set.ofList function after this code runs, but would like to solve that problem here internally.  I'm new to F#, so what can I do to optimize this code?

type NewProductAttributeInfo = {
    AttributeId : string;
    AttributeCategoryId : string
}

let rec private returnVariant (curIdx: int) (listLength: int)
    (attList: (int * NewProductAttributeInfo * NewProductAttributeInfo) list)
    (curList: NewProductAttributeInfo list) =

    match curList with
    | x when x.Length = listLength -> curList
    | x ->
        let attTup =
            attList
            |> List.filter (fun x' ->
                                let idx1,att1,att2' = x'
                                idx1 >= curIdx && not(curList
                                                        |> List.exists (fun x'' ->
                                                                            x'' = att2'))
                            )
        let idx1,att1,att2 = attTup |> List.head
        let newList = curList @ [att2]
        returnVariant idx1 newList.Length attList newList

let rec calculateVariants (attList: NewProductAttributeInfo list)
    (currentList: (int * NewProductAttributeInfo * NewProductAttributeInfo) list) =

    // group attribute list by category id
    let attGrouped = attList |> List.groupBy (fun x -> x.AttributeCategoryId)
    let (firstGroupCatId,firstGroupDetails) = attGrouped.[0]

    match currentList with
    | [] ->
        let rawVariants = [for nxt in 0 .. (attGrouped.Length - 1) do
                            if nxt > 0
                            then
                                // begin iteration
                                for d in firstGroupDetails do
                                    let _,det = attGrouped.[nxt]
                                    for det' in det do
                                        yield (nxt, d, det')
                        ]
        calculateVariants attList rawVariants
    | x ->
        let groupLength = x |> List.groupBy (fun (idx,d0,nxtD) -> idx)
                        |> List.length |> ((+)1)
        let sortedGroup = x |> List.sortBy (fun (x,y,z) -> x)
        if groupLength > 2
        then // below is the block that generates the duplicates
            [for att in sortedGroup do
                for attCompare in sortedGroup do
                    let idx1,att1,att2 = att
                    let idx2,attC1,attC2 = attCompare
                    if idx2 > idx1 && att2 <> attC2
                    then
                        let idString =
                            returnVariant idx2 groupLength x [att1; att2; attC2]
                            |> List.map (fun nl -> nl.AttributeId)
                        yield String.concat "," idString
            ]
        else
            [
                for att in sortedGroup do
                    let idx1,att1,att2 = att
                    let idString =
                            returnVariant idx1 groupLength x [att1; att2]
                            |> List.map (fun nl -> nl.AttributeId)
                    yield String.concat "," idString
            ]

If I understand correctly, you're looking for the Cartesian product of the attributes in each attribute category.

To get the Cartesian product, I've adapted* Eric Lippert's solution from his blog post Computing a Cartesian product with LINQ.

let cartesianProduct xs =
    Seq.fold (fun acc xs -> seq {
        for accSeq in acc do
        for x in xs do
        yield Seq.append accSeq (Seq.singleton x)
    }) (Seq.singleton Seq.empty) xs

Then we need to group by the attribute category, and pull out just the attributes**.

let variants (attributes : seq<NewProductAttributeInfo>) =
    attributes
        |> Seq.groupBy (fun attribute -> attribute.AttributeCategoryId)
        |> Seq.map (snd >> Seq.map (fun attribute -> attribute.AttributeId))
        |> cartesianProduct

Here is a test on the sample data you provided

let attributes = [
    { AttributeId = "red"; AttributeCategoryId = "Color" };
    { AttributeId = "L"; AttributeCategoryId = "Size" };
    { AttributeId = "XL"; AttributeCategoryId = "Size" };
    { AttributeId = "Cotton"; AttributeCategoryId = "Material" };
    { AttributeId = "green"; AttributeCategoryId = "Color" };
    { AttributeId = "Polyester"; AttributeCategoryId = "Material" }
]

for variant in variants attributes do
    printfn "%A" variant

Which gives:

seq ["red"; "L"; "Cotton"]
seq ["red"; "L"; "Polyester"]
seq ["red"; "XL"; "Cotton"]
seq ["red"; "XL"; "Polyester"]
seq ["green"; "L"; "Cotton"]
seq ["green"; "L"; "Polyester"]
seq ["green"; "XL"; "Cotton"]
seq ["green"; "XL"; "Polyester"]

* Hopefully without introducing errors.

**
This is a little bit nicer in C# since we have the overload of GroupBy that takes an elementSelector parameter:

return attributes.GroupBy(attribute => attribute.CategoryId, attribute => attribute.Id)
    .CartesianProduct();


Creating json objects with undefined properties I have the following snippet code which, within a loop, creates a JavaScript object where some of the properties maybe undefined:

reader.on('record', function(record) {

    let p = record.children;
    let player = {};

    // below we create a dynamic key using an object literal obj['name'], this allows use to use
    // the id as the firebase reference id.
    player[p[0].text] = {
        id: parseInt(p[0].text, 10) || "",
        name: p[1].text || "",
        country: p[2].text || ""
    };
};

My question therefore; is there a better way for creating this object via a 'Map' for example? If the properties are undefined then do not add them to the object.

Note: This data is being sent to a Firebase DB, so any undefined values throw an error -- my crude (but working) approach is to add them as an empty string.

Here is a sample of the JSON I would like to see (notice country is not missing from the second player):

{
 "players" : {
    "100001" : {
      "id" : 100001,
      "name" : "Matt Webb",
      "country" : "ENG"
    },
    "100002" : {
      "id" : 100002,
      "name" : "Joe Bloggs",
    }
}

To make your code a bit more accurate you could run a function before every call to firebase (this is the main reason you need it) and create a new object with only defined props

function getDefinedProps(obj) {
  var o = {}
  for (key in obj) {
    if (obj[key] !== undefined)
      o[key] = obj[key]
  }

  return o;
}


Insert into table class This class should function as a simple insert into table. What do you think about it? How can I make my code better?

class addProfile{
private $profileName;
private $profileEmail;
private $profileFromName;
private $profileReplaytToEmail;

public function __construct($profileName,$profileEmail,$profileFromName,$profileReplayToEmail){
    $this->profileEmail = $profileEmail;
    $this->profileFromName = $profileFromName;
    $this->profileName = $profileName;
    $this->profileReplaytToEmail = $profileReplayToEmail;
}

public function postProfile($profileName,$profileEmail,$profileFromName,$profileReplayToEmail){
    $stmt = $this->mysqli->prepare("INSERT INTO SendingProfiles (fromemail,Fromname,Profilename,replaytoemail)
    VALUES ('$profileName','$profileEmail','$profileFromName','$profileReplayToEmail')");
    $stmt->bind_param($profileName,$profileEmail,$profileFromName,$profileReplayToEmail);

    if ($stmt->execute()){
        echo "the record added";
    }else{
        echo "Failed";
    }

    $stmt->close();

}

public function __destruct(){
    $this->mysqli->close();
}

}

$profileName = $_POST['profilename'];
$profileEmail = $_POST['fromemail'];
$profileFromName = $_POST['fromname'];
$profileReplayToEmail = $_POST['replaytoemail'];

$var = new addProfile();
$var->postProfile($profileName, $profileEmail, $profileFromName, $profileReplayToEmail)

There's very little to review.

Variable Names

Use full names for variables, avoid short forms of those words/abbreviations. For example, you wrote, $stmt, instead you could write $statement to increase the readability of the code.

Class Names

Your class name, addProfile is not really suitable to give the image of the class. Why not name it, CreateUserProfile since that is what it does?

Also, class names should be declared StudlyCaps.

Validation Checks

Why not perform validation checks for what user has input? For example check if the variables are empty or not.

Coding Standards

Your coding style does not meet the coding standards.

Working Code

You have not provided us with a working code, as there would be an error with bind_param() because you haven't used any '?' and directly injected the variables like this, which is vulnerable to SQL injection.

$stmt = $this->mysqli->prepare("INSERT INTO SendingProfiles (fromemail,Fromname,Profilename,replaytoemail)
    VALUES ('$profileName','$profileEmail','$profileFromName','$profileReplayToEmail')");

Instead, do this:

$stmt = $this->mysqli->prepare("INSERT INTO SendingProfiles(fromemail, Fromname, Profilename, replaytoemail) VALUES(?, ?, ?, ?)");


Console calculator, takes a string as input (like: 2+3*4-1+3) and outputs the result I am a beginner programmer(solo learning). I know the basics of c/c++, but I would not consider myself too experienced. Recently I decided to make this calculator which takes an array of characters as input and then decodes the operations. I would like to know if I can improve it in any way and an overall review.

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;

int main()
{
    char v[20];
    int sign, n, i;
    float result, nr, aux, c;
    while (1)
    {
        cout << "insert the expression:" << endl;
        scanf("%s", v);
        n = strlen(v);
        result = 0, nr = 0, aux = 0, c = 0;
        sign = 1, n, i = 0;
        while (i<n)//loops only once through the array
        {
            while (v[i] >= '0'&&v[i] <= '9')//builds the number
            {
                nr = nr * 10 + (v[i] - '0');
                i++;
            }
            switch (v[i])//identifies the operations
            {
            case '+': {

                if (!(v[i - 1] == '*') && !(v[i - 1] == '/'))//if a*-b or a/-b occurs it does nothing
                {
                    if (c == 1)// * was found before: 2*2+1
                    {
                        result += aux*nr*sign;// updates the end result
                        aux = 0;//aux is reseted
                    }
                    else if (c == 2)// / was found before: 2/2+1
                    {
                        result += aux / nr*sign;
                        aux = 0;
                    }
                    else
                    {
                        result += nr*sign;
                    }
                    nr = 0;
                    c = 0;
                }

                sign = 1;

                break;
            }
            case '-': {
                if (!(v[i - 1] == '*') && !(v[i - 1] == '/'))
                {
                    if (c == 1)
                    {
                        result += aux*nr*sign;
                        aux = 0;
                    }
                    else if (c == 2)
                    {
                        result += aux / nr*sign;
                        aux = 0;
                    }
                    else
                    {
                        result += nr*sign;
                    }
                    c = 0;
                    nr = 0;
                }
                sign = -1;
                break;
            }
            case '*': {
                if (!aux)
                {
                    aux = nr*sign; // aux hold the result from * and / operations
                }
                else if (c == 2)
                {
                    aux /= nr*sign;
                }
                else
                {
                    aux *= nr*sign;
                }
                c = 1;
                nr = 0;
                sign = 1;
                break;
            }
            case '/': {
                if (!aux)
                {
                    aux = nr * sign;
                }
                else if (c == 1)
                {
                    aux *= nr*sign;
                }
                else
                {
                    aux /= nr*sign;
                }
                c = 2;
                nr = 0;
                sign = 1;
                break;
            }
            default:;
            }
            if (i >= (n - 1))// updates the result because there is no + or - at the end of the string.
            {
                if (c == 1)
                {
                    result += aux*nr*sign;
                }
                else if (c == 2)
                {
                    result += aux / nr*sign;
                }
                else
                {
                    result += nr*sign;
                }
            }
            i++;
        }
        cout << "=" << result << endl;
        system("pause");
        system("cls");

    }

}

Some quick observations:

Don't use using namespace std
Prefer using \n over std::endl
Prefer prefix over postfix
You're mixing C and C++ here. Use <cstring>/<string> (depending on what you need) instead of string.h. For input have a look at the C++ I/O library
Some of your code is windows only ( system("pause") and system("cls") )
Don't define more than one variable per line
Comparing floats with ==/!= might be unsafe
There are several (probably unwanted) type conversions which you can catch by enabling warnings in your compiler of choice
Putting all the code into the main function makes this hard to read. It's better to split it up into functions
Try to avoid overly short variable names. They should always express intent to make reading the code easier.


Converting bits to decimal (integer) string is so slow I am implementing myself a BigInteger class. It can natively handle very very big digits in very short time.

2 ^ 200000 == Time Elapsed : 12.343
Number of binary digits : 200001

The only problem is, when I do std::cout << foo;, I have to wait for very very long. Because my BigInteger class has to perform a std::string multiplication and a std::string increment on very single bit. As the number of bits increases, it might even take ages to finish.

Printing foo took 160.485 second(s) // It is so so long!!!

I have actually optimized my outputting algorithm to the best of my abilities. Some tricks include using reference, using array temp variables for fast caching. But for very very big numbers, it is still not fast enough.

Here is my code :

void BigInteger::doubleNumberString_1A63(std::string &string_input, std::string &string_tmp)
{
    int64_t i;
    int32_t t, t_1 = 0, t_2;

    string_tmp = "";

    char buffer[1024];
    int32_t n = 0;

    for(i = string_input.size() - 1; i >= 0; i--)
    {
        t = t_1 + (string_input[i] - '0') * 2;

        t_1 = t / 10;
        t_2 = t % 10;

        buffer[n++] = (char)('0' + t_2);
        if(n == sizeof(buffer)){string_tmp.append(buffer, n); n = 0;}
    }

    if(t_1 >= 1) buffer[n++] = (char)('0' + t_1);
    if(n) string_tmp.append(buffer, n);
}

void BigInteger::incrementNumberString_1A63(std::string &string_input, std::string &string_tmp, int32_t inc_val = 1)
{
    int64_t i;
    int32_t t, t_1 = 0, t_2;

    string_input = "";

    char buffer[1024];
    int32_t n = 0;

    for(i = 0; i < string_tmp.size(); i++)
    {
        t = t_1 + (string_tmp[i] - '0') + inc_val;

        t_1 = t / 10;
        t_2 = t % 10;

        inc_val = 0;

        buffer[n++] = (char)('0' + t_2);
        if(n == sizeof(buffer)){string_input.append(buffer, n); n = 0;}
    }

    if(t_1 >= 1) buffer[n++] = (char)('0' + t_1);
    if(n) string_input.append(buffer, n);

    std::reverse(string_input.begin(), string_input.end());
}

void BigInteger::printRawBinaryToDecimal(std::ostream &os) const
{
    const BigInteger &num = (*this);

    int64_t i;
    int64_t num_sz = num.size();

    if(BIG_INTEGER_INTEGER_DIGIT_BASE_A8F23ABC == 2)
    {
        std::string buf_base10 = "0";
        std::string buf_basetmp;

        // num.operator[](i) // --> Access each bit
        for(i = num_sz - 1; i >= 0; i--)
        {
            doubleNumberString_1A63(buf_base10, buf_basetmp);
            incrementNumberString_1A63(buf_base10, buf_basetmp, BigInteger::IntegerUnit::toDigit(num.operator[](i)));
        }

        os << buf_base10;
    }
}

std::ostream &operator << (std::ostream &os, const BigInteger &num)
{
    num.printRawBinaryToDecimal(os); return os;
}

Here we go, for each bit, the BigInteger class has to call doubleNumberString_1A63 and incrementNumberString_1A63, and it is the traditional method (and slow of course). Could anyone greatly improve it or suggest even a faster algorithm? I would really appreciate it.

You are trying to do arithmetic with strings, that is bound to be expensive.

Here is a naive algorithm to output a BigInteger in decimal:

std::stringstream output;
BigInteger num = the_number;
while(num != 0) {
    output << static_cast<int>(num%10);
    num = num/10;
}
std::string output_str = output.str();
std::reverse(output_str.begin(), output_str.end());
return output_str;

of course you need to implement the operators %, / and cast to int first.

This can also be easily improved by chunking to the maximal power of 10 holdable in an unsigned int or unsigned long.

However this naive algortithm still has quadratic time complexity in the length of the number. I am not sure whether there is a linear time algorithm. Another quadratic, but possibly faster algorithm is Double dabble.

In the GMP documentation there is a short explanation of a subquadratic algorithm. Maybe this can give you some directions. You may want to look at its source anyway as a reference of a mature BigInteger implementation.

I am also quite confused by your function names. What is _1A63 supposed to mean? I doubt the end of the function name is the correct place for whatever it is. Is it representing the container element types? If so that should belong into a template parameter.


Generating prime numbers within a range in C++ I was given a problem to find out all the prime numbers within a range. Just after I wrote the program I found numerous other codes to solve the problem. I am interested to know is my algorithm efficient? Is it like sieve filtration? (before writing this code I had no clear idea on sieve filtration method) or the algorithm I used is bad?

#include<iostream.h>
#include<math.h>

prime_gen

void prime_gen(int a,int b)
{
    int array[4]={2,3,5,7},holder[1000000]={0},count=0,flag=0,length=0,number_count=0;

    for(int i=0;i<b;i++)
    {
        for(int j=0;j<4;j++)
        {
            if(i==array[j])
            {
                break;
            }
            else
            {
                if(i%array[j]==0)
                {
                    count++;
                }
            }
        }
        if(count==0)
        {
            if(i>1)
            {
                holder[length++]=i;
            }
            else
            {
                length=0;
            }
        }
        count=0;
    }

    if(length==0)
    {
        cout<<"No prime numbers exist within the range";
        cout<<"\n";
    }
    else
    {
        cout<<"Prime numbers are:";

        for(int i=0;i<length;i++)
        {
            int t=holder[i];

            for(int check=0;check<sqrt(length);check++)
            {

                if(t!=holder[check])
                {
                    if(t%holder[check]==0)
                    {
                        t=0;
                    }
                }
            }

            if(t!=0&&t>=a)
            {
                number_count++;
                cout<<t<<"\t";
            }
        }

        cout<<"Total count:"<<number_count<<endl;
    }
}

main

int main()
{
    int a,b;

    cout<<"Put the first integer:";
    cin>>a;

    cout<<"Put the second integer:";
    cin>>b;

    prime_gen(a,b);
}

Stylistic notes:

Use more spaces around punctuation (for(int i=0;i<b;i++) wants to breeze), don't sprinkle your code with blank lines in random places, and use consistent indentation.
Declare your variables on separate lines; use the blank space on the right to write a comment explaining what the variable is for.
Use meaningful variable names. Come on, array? The reader can see that it's an array, but what does it contain?

Also, make up your mind: you're writing C++, not C. Some parts (such as the use of C arrays) are not idiomatic C++ though; you should pick one, either C (and use stdio, not iostream) or C++ (and use new and the STL). Since I'm a C programmer but don't know much C++, I'm going to comment on the C-ish parts and not say anything about idiomatic C++.

The array variable isn't useful here. The small primes will appear in the holder array anyway, so put them in directly. Even if you were handling small primes specially, your count variable is useless: you don't need to count how many small primes divide i, you only need to know whether some small prime divides i.

Also, you might as well use unsigned integers for your variables, since they're not going to contain negative numbers.

unsigned holders[1000000]; /* list of prime numbers */
unsigned length = 0;
holders[length++] = 2;
holders[length++] = 3;
holders[length++] = 5;
holders[length++] = 7;

You do not need to fully initialize holders, since you'll be only looking at the first length elements. While you could write unsigned holders[1000000] = {3, 5, 7}; and the compiler would fill the rest with zeroes, with typical implementations, this would result in the full array (zeroes included) being written into your executable, which is a huge waste.

You should be allocating the holders dynamically anyway, and checking its size. If someone passes such a large value for b that the holders array overflows, your code will overwrite some arbitrary memory. Either compute the size of the holders array so that it's large enough given b, or keep track of its size and extend it if length becomes too large.

Even numbers are never prime. So instead of looping over all integers, loop over all odd integers.

There's no reason to fill holders with non-prime numbers. Your whole first loop can be eliminated.

for (x = 11; x < b; x += 2) {
    bool is_prime = true;
    // start j at 1.
    // As holders[0] is 2 and no value of x is divisible by 2.
    for (j = 1; j < length && holders[j] <= sqrt(x); j++) {
        if (x % holders[j] == 0) {
            is_prime = false;
            break;
        }
    }
    if (is_prime) {
        holders[length++] = x;
    }
}

Now, to find the number of primes between a and b, traverse the holders array from the first value that's larger or equal to a. When you write a complete program, take care of the boundary conditions; in particular, make sure to count 2 if a ≤ 2.

for (j = 0; j < length; j++) {
     if (holders[j] >= a) break;
}
return length - j;


Insertion Sort implementation in Java I have implemented Insertion sort in Java.  Please review it.

public class InsertionSort {

public static void main(String[] args) {
        int[] values = new int[args.length];
        for (int i = 0; i < args.length; i++) {
            values[i] = Integer.parseInt(args[i]);
        }

        for (int i = 0; i < values.length; i++) {
            if (i!=0 && values[i] < values[i - 1]) {
                for (int j = i; j >= 1; j--) {
                    System.out.println(" j"+j);
                    if (values[j] < values[j-1]) {
                        int temp = values[j - 1];
                        values[j - 1] = values[j];
                        values[j] = temp;
                    } else {
                        break;
                    }
                }
            }
        }
        System.out.println(" sorted numbers");
        for (int i = 0; i < values.length; i++) {
            System.out.println(" "+values[i]);
        }
    }
}

Consider this:

for (int i = 0; i < values.length; i++) {
    if (i!=0 && values[i] < values[i - 1]) {

i starts from 0, and then right after you use a condition i!=0. You could simplify to:

for (int i = 1; i < values.length; i++) {
    if (values[i] < values[i - 1]) {

Consider this:

if (values[i] < values[i - 1]) {
    for (int j = i; j >= 1; j--) {
        if (values[j] < values[j - 1]) {
            // ...
        } else break;

Notice that j starts from i, and you have the same if immediately inside the loop, otherwise break. In other words, you don't need that outer if, because you run the same thing immediately inside the loop.

Consider this:

for (int j = i; j >= 1; j--) {
    if (values[j] < values[j - 1]) {
        ...
    } else break;

an equivalent but shorter and more traditional way to write the same thing:

for (int j = i; j >= 1 && values[j] < values[j - 1]; j--) {
    ...
}

Putting it all together:

for (int i = 1; i < values.length; i++) {
    for (int j = i; j > 0 && values[j] < values[j - 1]; j--) {
        int temp = values[j - 1];
        values[j - 1] = values[j];
        values[j] = temp;
    }
}

We have arrived at the pseudo algorithm of insertion sort in wikipedia ;-)

I recommend using unit tests to check your implementations instead of printing text to the console and checking with your eyes. For example:

public Integer[] sort(Integer[] orig) {
    Integer[] values = orig.clone();
    for (int i = 1; i < values.length; i++) {
        for (int j = i; j > 0 && values[j] < values[j - 1]; j--) {
            int temp = values[j - 1];
            values[j - 1] = values[j];
            values[j] = temp;
        }
    }
    return values;
}

@Test
public void testExamples() {
    Assert.assertArrayEquals(new Integer[]{3, 4, 5}, sort(new Integer[]{5, 4, 3}));
    Assert.assertArrayEquals(new Integer[]{3, 4, 5}, sort(new Integer[]{5, 3, 4}));
    Assert.assertArrayEquals(new Integer[]{3, 4, 5}, sort(new Integer[]{3, 5, 4}));
}

Running this is just as easy as running a main method. This approach also encourages decomposing your problems to elementary operations. In this case I had to extract the sorting logic to its own method to be easier to test. In the end, you will naturally have multiple methods, which is a good thing, at virtually no extra cost.


Convert a Hex value string to an ASCII Text String We had a little bit of fun in the 2nd Monitor this morning, one user greeted another with a hex string. It turned out that the user being greeted deals with Hex Dumps enough that they were able to read the string, but I wasn't so I created this converter.

What could I have done to reduce the dependency on cstring?

How could I have made this more C++17 and less C Programming language.

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

class HexStringToAsciiStringConverter
{
    std::vector<unsigned> HexValues;

    const char* Remove0x(const char* hxv)
    {
        if (std::strstr(hxv, "0x") == hxv)
        {
            hxv += 2;
        }

        return hxv;
    }

    void ConvertStringToUnsigned(std::string HexStringToConvert)
    {
        const char *hxv = Remove0x(HexStringToConvert.c_str());
        while (*hxv && *(hxv+1))
        {
            char hxva[3] = {'\0'};
            std::strncpy(hxva, hxv, 2);
            HexValues.push_back(std::strtol(hxva, nullptr, 16));
            hxv += 2;
        }
    }

public:
    HexStringToAsciiStringConverter::HexStringToAsciiStringConverter(std::string Original)
    {
        ConvertStringToUnsigned(Original);
    }

    std::string HexStringToAsciiStringConverter::ConvertHexToString()
    {
        std::vector<unsigned char> tmpcarray;
        for (auto HexValue: HexValues)
        {
            tmpcarray.push_back(HexValue);
        }

        std::string output(tmpcarray.begin(), tmpcarray.end());

        return output;
    }
};

int main() {
    std::string Original = "0x486920446f6e2c20686f7727732073706163653f";

    HexStringToAsciiStringConverter Converter(Original);
    std::cout << Converter.ConvertHexToString() << std::endl;

    return EXIT_SUCCESS;
}

I'm surprised that, according to your code, C++ doesn't have a strip_prefix or without_beginning or skip_start function to skip over the initial "0x". If there were one, you should definitely use that instead of implementing your own. Do a little search, I'm sure such a function exists.

Even though this is C++, there is no need to write a class for a simple conversion function like this. In my experience, this task can be solved in less than 20 lines of code, and there is no state that you need to save between method calls, therefore a class is unnecessary. Just write an ordinary std::string hex_to_bytes(const std::string_view &hex) function.

As far as I remember, std::string has a push_back method, therefore there's no need to use an intermediate vector for building up the string.

My rough idea is:

std::string hex_to_bytes(const std::string_view &hex) {
    std::size_t i = 0, size = hex.size();
    if (size >= 2 && hex[0] == '0' && hex[1] == 'x')
        i += 2;

    std::string result;
    for (; i + 1 < size; i += 2) {
        char octet_chars[] = { hex[i], hex[i + 1], '\0' };

        char *end;
        unsigned long octet = std::strtoul(octet_chars, &end, 16);
        if (end != octet_chars + 2)
            throw std::some_exception();

        result.push_back(static_cast<char>(octet));
    }

    if (i != size)
        throw std::some_exception();

    return result;
}

I didn't test the above code.
It also doesn't look very C++-like to me because it accesses the character array directly. But probably, for this kind of functions, there is no high-level way of expressing the code.

By the way, instead of writing all this code, you could also write a Perl one-liner:

perl -pe '$_ = pack("H*", $1) if /([0-9a-f]+)/i'


Generic XHR caching function I've made a simple caching function for my jQuery ajax calls.

I know about the $.ajax() cache setting, but I don't use it for various reasons. One of the most important one is it being limited to GET (and perhaps HEAD?) requests.

If a cached value is found, and is a reference type, I'm returning a deep copy rather than a reference to the actual object.

var cache = {};
function getData(cacheKey, getPromise) {

    var dfd = $.Deferred(),
        cachedValue = cache[cacheKey];

    if (!cachedValue) {

        getPromise().done(function (response) {

            console.log('got data from XHR', response);

            cache[cacheKey] = response;
            dfd.resolve(response);

        }).fail(dfd.reject);

    } else {

        console.log('got data from cache', cachedValue);

        if ($.type(cachedValue) === 'object')
            dfd.resolve($.extend(true, {}, cachedValue));
        else if ($.type(cachedValue) === 'array')
            dfd.resolve($.extend(true, [], cachedValue));
        else
            dfd.resolve(cachedValue);
    }

    return dfd.promise();
}

Sample use case:

var getter = $.ajax.bind(this, {
    url:'/echo/json/',
    data: data,
    type: 'POST'
});

getData('foo', getter).done(function(){
    getData('foo', getter);
    getData('foo', getter);
});

http://jsfiddle.net/rg5ntyt5/

Please share your thoughts regarding possible improvements

jQuery already has a caching mechanism - and I'm not just talking cache: true (which as you say, only works for HEAD/GET, and relies on the browser's built-in caching).

What I'm talking about is promises. Promises are caches themselves, and $.ajax returns a promise. Once resolved or rejected, it'll stay that way, and you can keep calling done/fail/then/always on it, being passed the same arguments every time. The request isn't repeated.

So to start, your example code can be written as just:

var xhr = $.ajax.bind(this, {
    url:'/echo/json/',
    data: data,
    type: 'POST'
})();

xhr.done(function (response) { ... });
xhr.done(function (response) { ... });
xhr.done(function (response) { ... });
// etc...

As long as you have a reference to xhr, the request and response is cached.

The only difference from yours is that the response is passed as-is without the deep copy. But if your requests are JSON, you can always get a pristine response by re-parsing the response yourself:

xhr.done(function (response, status, xhr) {
  var pristineResponse = JSON.parse(xhr.responseText);
});

Incidentally, your example didn't make much sense. You called getData a couple of times but didn't actually do anything with those calls. Besides, calling it from inside the done callback, seems redundant to me:

getData('foo', getter).done(function (response) { // <- the response is right there, no caching necessary
    // do stuff with response. For instance, a deep copy.
});

Not to be harsh, but your current implementation is just kinda pointless, it seems to me. You have to create the getter function, and then manually pass it to getData. Then, if you want to use the cache... you have to pass the getter function again? Shouldn't that just be getData('foo') without the getter if you want the cache? As mentioned, if you have the request's promise, you have a cache already.

However, even if you just call getData('foo'), you have to be prepared to handle a failure, if nothing's been cached. Which, in turn, means that you have to always be ready to perform the request, so you code will be littered with something like this:

getData('foo')
  .done(function (response) {
    // with no existing cache, this won't be called
  })
  .fail(function () {
    // instead we'll have to create the cache
    var getter = $.ajax.bind(something, { // oops, what "this" should we bind to?
      url:'/echo/json/',
      data: data,
      type: 'POST'
    });
    getData('foo', getter).done(function (response) {
      // finally! We can get our response
    });
  });

And you'd have to do this every time, because you don't know if you have a cache or not.

Finally, there's a risk of a race condition. You only set the cache when the request is completed successfully, so if you were to do this:

var getter = $.ajax.bind(this, {
    url:'/echo/json/',
    data: data,
    type: 'POST'
});

// This performs a request. It's asynchronous, so the code here just continues on immediately...
getData('foo', getter);

// ... so this performs *another* request, because nothing's been cached yet
getData('foo', getter);

// Time passes, and the first request completes. A cache is finally created.
// Then the second request completes, and overwrites the just-created cache.

I imagine that's why your example only tried using the cache inside the first done handler. But that's the one place where you don't need the cache, since you have the response.

So, really, I see little benefit in using your code. The only thing it seems to add is the deep copy.

If you want a simpler caching mechanism, I'd suggest something like this:

  var cache = {};
  function cachedAJAX(options) {
    if(!options.cacheKey) {
      return $.ajax(options); // no caching requested; just pass through
    }

    if(!cache[options.cacheKey]) {
      cache[options.cacheKey] = $.ajax(options); // create and cache a new request
    }

    // return the request
    return cache[options.cacheKey];
  };

Now, instead of calling $.ajax, you'd call cachedAJAX, but you'd use all the same options (url, type, data, etc.). There's just one extra option: cacheKey. If that's set, cachedAJAX won't perform a new request if it has a cached one. And it caches immediately, meaning you might cache a soon-to-be-failed request. But there's no race condition.


parse date and number from API results I'm slurping up fields from an API that returns an array of fields. Each field in the array is a String that actually contains two separate fields (a number and a date). The number is enclosed in parentheses and the date is following this and a space. The following is an example of the format.
const data = [
            "(2) 2020-09-15", "(3) 2020-09-16"
        ];

I'm parsing this field and then storing the data separately in my app. I have my own numbers and dates fields that will be a String in which each number and date is separated by a newline.
I'm achieving this by doing the following.
let numbers = '', dates = numbers;

        for (let datum of data) {
            datum = datum.split(/[() ]/);
            numbers += `${datum[1]}\n`;
            dates += `${datum[3]}\n`;
        }

See an example here.
I don't particularly like this and am wondering if there's a more efficient and cleaner way to write this.

Rather than declaring the variables with let (you should always prefer const) and concatenating and reassigning, consider creating arrays of numbers and dates instead, eg:
[2, 3] and ["2020-09-15", "2020-09-16"]
Then after the loop is done, join all elements by newlines.
For the regular expression, rather than split, I think match would be more appropriate. You can use \((\d+)\) (\S+):

\( - literal (
(\d+) - 1st capturing group, composed of digits
\) - literal )
  - literal space
(\S+) - 2nd capturing group, composed of non-spaces

Then extract the 1st and 2nd capturing groups.

const data = [
  "(2) 2020-09-15", "(3) 2020-09-16"
];
const numbers = [];
const dates = [];
for (const item of data) {
  const [, number, date] = item.match(/\((\d+)\) (\S+)/);
  numbers.push(number);
  dates.push(date);
}
console.log(numbers.join('\n'));
console.log(dates.join('\n'));