texts:
Given two strings, for example

  s1 = "Valentino   Rossi" (which may contain as many spaces between the 2 words as I like)
   s2 = "Vale"

I have to create a function that requests these two strings and that it outputs another one like this one: "Valentino (Vale) Rossi".

So for example if I have

  s1 = "Mario       Belli"
  s2 = "Mar"

the returned string must be "Mario (Mar) Belli".

#include <stdio.h>
#include <string.h>
#define STR_LEN 32

char *makeNickname(char *s1, char *s2, char *s3);

int main() {
    char nomeCognome[] = "Corrado     Righetti";
    char nickname[] = "Cora";
    char nameNickname[STR_LEN];
    makeNickname(nomeCognome, nickname, nameNickname);
    printf("%s\n\n", nameNickname);
}

char *makeNickname(char *s1, char *s2, char *s3) {
    char *p = s1, *q = s2, *k = s3;
    while (*p) {
        if (*p != ' ') {
            *k++ = *p++;
        } else {
            *k++ = *p;
            *k++ = '(';
            while (*q) {
                *k++ = *q;
                q++;
            }
            *k++ = ')';
            *k++ = *p;
            while (*p == ' ') p++;
        }
    }
    return s3;
}


texts:
Given an unique string that represents a sequence of characters, the class should implement three methods (getNextChar, getNextString and the genSequence generator).

How it works

We give a sequence of characters. For example: "abc"
We give a starting string. For example: "a"
The generator yields the following strings infinitely.

The next string of an existing string works like a dictionary, only the length doesn't change as long as there are still characters to fulfill.

a
b
c
aa
ab
ac
ba
..
cc
aaa
aab

This is not homework, but a user in Stack Overflow chat presented the challenge and I considered taking it to a higher level.

class SeqString {

    constructor (sequence) {

        this._sequence = sequence;
        this._first    = sequence[0];
        this._last     = sequence.slice(-1);

        return this;
    }

    getNextChar (char) {

        let seq   = this._sequence,
            index = (seq.indexOf(char) + 1) % seq.length;

        return seq[index];
    }

    getNextString (str) {

        let last = str.slice(-1),
            init = str.slice(0, str.length - 1),

            lastOfSeq  = this._last,
            firstOfSeq = this._first;

        // If it is overflowing
        if (last === lastOfSeq) {

            let trail = 1,
                i     = init.length;

            // Look for an index that won't overflow
            while (i-- && init[i] === lastOfSeq) ++trail;

            // If there is no such index, then the result is a new sequence
            // with an increased length
            if (i === -1) return firstOfSeq.repeat(trail + 1);

            // If there is, change the matching character at the index
            // and reset every character after that
            str = init.slice(0, i) + this.getNextChar(init[i]) +
                  firstOfSeq.repeat(trail);

            return str;

        }

        return init + this.getNextChar(last);
    }

    *genSequence (str) {

        let newStr = this.getNextString(str);

        yield newStr;
        yield* this.genSequence(newStr);
    }

}

Specific questions

How can I improve my class functions, while maintaining a balance between performance and readability?
Tips on how I could make the code more readable for others.

Test cases

I have made a function test, to help debugging.

function test (sequence, startStr, times = 10) {

    let it = new SeqString(sequence).genSequence(startStr);

    while (times--)
        console.log(it.next().value);
}

Examples of output

Alphaset tests

const lowerAlpha = "abcdefghijklmnopqrstuvwxyz";
const alpha      = lowerAlpha + lowerAlpha.toUpperCase();

test(alpha, 'abc', 1); // abd
test(alpha, 'BZZ', 1); // Caa
test(alpha, 'Z', 1); // aa
test(alpha, 'ZZ', 1); // aaa

A long sequence for test(alpha, "Stack"): http://lpaste.net/137336

Other tests

test("pen", "p", 10);

  e  n  pp  ..  np

test("0123456789", "5", 10);

  6  7  8  9 00 01  02 ..

It should

Use ES6 features
Expose a generator
Handle every kind of unique sequence
Be readable


texts: Is this circular linked list better than the fast & slow pointer method?

texts:
I have a faster way to find if a list is circular linked list, in contrast to the solution that Cracking the Coding Interview has offered:

In the below algorithm, fast-pointer will either hit null (in case of linear list) or hit starting point/origin (in case of circular) quicker than conventional (fast & slow pointer approach).

Reason: because in fast & slow pointer approach, we wait for the fastPointer == slowPointer condition to determine if it's a circular list. But fastPointer would reach its origin/starting point first before hitting slow pointer. (what's the point of crossing over the starting point and continuing the hunt for slowPointer?)

Isn't the below example a better algorithm?  If so, then why have a fast & slow pointer approach?

(I didn't consider starting point as "node outside of loop" scenario while asking question.)

public boolean findCircular(Node someRandomNodeOfList) {

    Node fast = someRandomNodeOfList;
    while (true) {
        if ((fast.next == null) || (fast.next.next == null)) {
            return false;
        }
        else if (fast.next == someRandomNodeOfList|| fast.next.next == someRandomNodeOfList) {
            return true;
        }
        else {
            fast = fast.next.next;
        }
    }
    return false;
}


texts: Cross-browser double form submit prevention

texts:
We developed a potential solution for the double form submit prevention and we need some review on it. To be able to execute this code on asp.net we needed to add our function call directly into the onsubmit event of the form. This cannot be handled by jQuery because asp.net use a dopostback function and called form.submit(). If onsubmit attribute of the form is empty then it will not execute the code. We don't want to depend on a bloq-UI or disabled button actions.

This is our form tag

 <form id="form1" runat="server" onsubmit="return preventDoubleSubmit(event);">

And this is our javascript that handles the double submit prevention:

//Double submit preventions
var _preventDoubleSubmit = false;

function preventDoubleSubmit(e) {

    if (_preventDoubleSubmit) {
        return cancelDoubleSubmit(e);
    }
    else {
        _preventDoubleSubmit = true;
        return true;
    }
}

function cancelDoubleSubmit(e) {
    if (!e) {
        e = window.event;
    }

    if (e.returnValue != undefined) {
        e.returnValue = false;
    }

    if (e.cancelBubble != undefined) {
        e.cancelBubble = true;
    }

    if (e.stopPropagation) {
        e.stopPropagation();
    }

    if (e.stopImmediatePropagation) {
        e.stopImmediatePropagation();
    }

    if (e.preventDefault) {
        e.preventDefault();
    }

    return false;
}
//END - Double submit prevention

Any review on this would be appreciated.


texts:
I implemented the group function:

group' :: (Ord a) => [a] -> [[a]]
group' [] = []
group' xs = takeWhile (== head' xs) (sorted xs) :
                           (group' $ dropWhile (== head' xs) (sorted xs))
                    where sorted ys   = mergesort' (ys)
                          head' (x:_) = x

Note - please assume mergesort is implemented properly.

Its signature is: [a] -> [a] where the latter list is sorted.

How's it look? Is head''s pattern matching exhaustive? It seems to me it is since group xs will only be reached if group's argument is non-empty, i.e. it'll always have a head.


texts:
I have installed Geekworm x735 on my Raspberry Pi, it uses the script below with an infinite loop to determine if the power button has been pressed. I know there are some Linux utils that watch for file changes (inotifywait, watch, fswatch to name a few), I wonder if they are more efficient than this solution or if under the hood they apply the same logic.

while [ 1 ]; do
  shutdownSignal=$(cat /sys/class/gpio/gpio$SHUTDOWN/value)
  if [ $shutdownSignal = 0 ]; then
    /bin/sleep 0.2
  else
    pulseStart=$(date +%s%N | cut -b1-13)
    while [ $shutdownSignal = 1 ]; do
      /bin/sleep 0.02
      if [ $(($(date +%s%N | cut -b1-13)-$pulseStart)) -gt $REBOOTPULSEMAXIMUM ]; then
        echo "X735 Shutting down", SHUTDOWN, ", halting Rpi ..."
        sudo poweroff
        exit
      fi
      shutdownSignal=$(cat /sys/class/gpio/gpio$SHUTDOWN/value)
    done
    if [ $(($(date +%s%N | cut -b1-13)-$pulseStart)) -gt $REBOOTPULSEMINIMUM ]; then
      echo "X735 Rebooting", SHUTDOWN, ", recycling Rpi ..."
      sudo reboot
      exit
    fi
  fi

Thank you.


texts: Implementation of system() function in Linux using fork() , exec() and waitpid() system calls

texts:
I have written the code for implementation of  system() function using fork(), exec() and waitpid(). Could someone please review this code and provide feedback. Thanks a lot.

#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<error.h>
#include<errno.h>
#define size 30

char *get_command(int argc, char *argv[]);
int my_system(const char *command);

int my_system(const char *command)
{
    pid_t pid;
    int wstatus  = 0;
    int ret = 0;

    if (command == NULL)
        return 1;
    pid = fork();
    if (pid == -1) {
        return -1;
    } else if (pid == 0) {
        ret = execle("/bin/sh", "sh", "-c",command, (char *)NULL);
        if (ret == -1)
            return wstatus;

    } else {
        ret = waitpid(-1, &wstatus, 0);
        if (ret == -1)
            return -1;
    }
    return wstatus;
}

char *get_command(int argc, char **argv)
{
    int i = 0;
    static char command[size];

    if (argc == 1)
        return NULL;

    strcpy(command, argv[1]);
    for (i = 2; i < argc; i++) {
        strcat(command, " ");
        strcat(command, argv[i]);
    }
    return command;
}

int main(int argc, char *argv[])
{
    int ret;
    char *command;

    command = get_command(argc, argv);
    ret = my_system(command);
    if (ret == 1)
        printf("Command is NULL, shell is available\n");
    else if (ret == -1)
        printf("Child process could not be created or error in the wait system call\n");
    else if (ret == 127)
        printf("The Child process could not be executed in the shell\n");
    else
        printf("The status of the child process is :%d\n", ret);
    return 0;
}
```


texts: Optimise Division function using divide and conquer, (and multiplication only)

texts:
I have the following code I am working on, but I think it can be optimised further probably by improving the min/max variable selection, (see below).

The idea is to not use actual division, ('/'), to get the quotient and remainder.

I think there could be a way to improve performance by further minimising the number of loops.

NB The idea is not to have a function faster than Num/Den but rather to have the function running as efficiently as possible.

void DivisionDivideAndConquer(const unsigned int Num, const unsigned int Den, unsigned int& Quo, unsigned int& Rem)
{
  //  short cuts
  if (Num < Den)
  {
    Quo = 0;
    Rem = Den;
    return;
  }

  // R = N - D * Q where 0 <= R < |D|

  // getting us started
  unsigned int min = 0;
  unsigned int max = Num;

  for (;;)
  {
    unsigned int number = static_cast<unsigned int>((min + max) * 0.5);
    int possibleRemainder = (Num - (Den * number));

    // if too small then we have a new max
    if (possibleRemainder < 0) {
      if (number == max) {
        max = max - 1;
      }
      else {
        max = number;
      }
    }
    // too big we have a new min
    else if(possibleRemainder >= static_cast<int>(Den) )
    {
      if (number == max) {
        min = min + 1;
      }
      else {
        min = number;
      }
    }
    else
    {
      //  got it!
      Quo = number;
      Rem = static_cast<unsigned int>(possibleRemainder);
      break;
    }
  }
}

int main(int argc, char** argv)
{
  unsigned int Quo = 0;
  unsigned int Rem = 0;
  DivisionDivideAndConquer(12, 4, Quo, Rem); // Q=3, R=0

  // ...

  DivisionDivideAndConquer(12, 9, Quo, Rem); // Q=1, R=3

}


texts:
I have the following code which return some text in different fonts (for the moment only TimesNewRoman and Arial).
It works fine but if I want to make it work for 20 or more fonts (but not necessarily font, also for font-size, or color, etc) I would have to declare a ton of variable and a very long Js code. Not to speak about CSS code.

I am wondering if there is another way to do this in an easier way and more closed to a deliverable code.

var field, theDivTNR, theDivA;

function init() {
  console.log("page loaded and DOM is ready");
  field = document.querySelector("#inputField");
  theDivTNR = document.querySelector("#theDivTNR");
  theDivA = document.querySelector("#theDivA");
}

// The next function is called each type a key has been
// typed in the input field
function showWhatITyped() {
  // fill the div with the content of the input field
  theDivTNR.innerHTML = field.value;
  theDivA.innerHTML = field.value;
}
#theDivTNR{
 font-family: timesnewroman;
 font-size: 20px;
}
#theDivA{
 font-family: arial;
 font-size: 20px;
}

 <title>JavaScript Course</title>

 <link rel="stylesheet" type="text/css" href="style.css">

Type text here: <input type="text" oninput= "showWhatITyped();" id="inputField" >

What you typed:

TimesNewRoman

Arial


texts: Submit form additions or changes using AJAX, and display result

texts:
I am submitting my form using ajax. Here is the actual code:

// generic ajax caller
function ajaxHandler(url, data, options)
{
    return $.ajax($.extend({
            type: 'POST',
            url: url,
            dataType: 'json',
            data: data,
            success: function (data) {
                return data;
            },
            error: function (xhr, textStatus, error) {
                return error;
            },
        }, options))

};

   // This code handles course submission form

     $('#add-course').on('submit', function (e) {
    e.preventDefault();

    var form = $(this);

    ajaxHandler(form.url, form.serialize()).then(function (result) {

        console.log('#############');

        $('.field-error, .success, .error').remove();
        if(result.errorType == "fieldErrors")
        {
            // handle field errors
            $.each(result.data, function (key, value) {
                console.log(key, value);
                $(' ' + value.msg + '').insertBefore('#' + value.param);
            });
        }

        else if(result.errorType == "formErrors")
        {
            // handle form errors
            $('
' + result.message + '
').insertBefore(form);
        }

        else
        {
            // success
            form[0].reset();
            $('
' + result.message + '
').insertBefore(form);
        }

    })
    .fail(function (error) {
        $('
Error connecting server
').insertBefore(form);
    });

});

// Here is code which handles update course form
$('#change-course').on('submit', function (e) {
    e.preventDefault();

    var form = $(this);

    ajaxHandler(form.url, form.serialize()).then(function (result) {

        $('.field-error, .success, .error').remove();
        if(result.errorType == "fieldError")
        {
            // handle field errors
            $.each(result.data, function (key, value) {
                console.log(key, value);
                $(' ' + value.msg + '').insertBefore('#' + value.param);
            });
        }

        else if(result.errorType == "formError")
        {
            // handle form errors
            $('
' + result.message + '
').insertBefore(form);
        }

        else
        {
            // success
            $('
' + result.message + '
').insertBefore(form);
        }

    })
        .fail(function (error) {
            $('
Error connecting server
').insertBefore(form);
        });
});

As you can see the structure of add/update form is almost the same. How can I refactor all this?


texts: Retrieve file and other input fields from JavaScript to send to ASP.NET Core

texts:
I am currently developing an e-commerce website where users can upload their photos to customise their products. The use case begins when the user selects a product from our website (e.g. shirt). After that, they will select the quantity and upload their photos. The client-side will then append the following fields to the using FormData: productId, productName and imageBlob. The imageBlob is the user uploaded images. I will then send these data over to my server-side (asp.net core) for sanitisation by checking the productId received with the database. I feel that there is a lot of improvement that can be done to my code but I just do not have the knowledge to do so. Is there anyone that can give feedback or help to improve my code?

Client-side (JavaScript)

function b64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || "";
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (
      var offset = 0;
      offset < byteCharacters.length;
      offset += sliceSize
    ) {
      var slice = byteCharacters.slice(offset, offset + sliceSize);

      var byteNumbers = new Array(slice.length);
      for (var i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      var byteArray = new Uint8Array(byteNumbers);

      byteArrays.push(byteArray);
    }

    var blob = new Blob(byteArrays, { type: contentType });
    return blob;
  }

  function imagetoblob(base64Image) {
    // Split the base64 string in data and contentType
    var block = base64Image.split(";");
    // Get the content type of the image
    var contentType = block[0].split(":")[1]; // In this case "image/gif"
    // get the real base64 content of the file
    var realData = block[1].split(",")[1]; // In this case "R0lGODlhPQBEAPeoAJosM...."

    // Convert it to a blob to upload
    return b64toBlob(realData, contentType);
  }

  const formData = new FormData();

  for (var i = 0; i < userProducts.length; i++) {
    formData.append("arr[" + i + "]", userProducts[i].productId);
    formData.append("arr[" + i + "]", userProducts[i].productName);
    formData.append(
      "arr[" + i + "]",
      imagetoblob(userProducts[i].base64Image)
    );
  }

Server-side (ASP.NET Ccore)

[AllowAnonymous]
[HttpPost("sanitizeUserCart")]
public async Task<IActionResult> sanitizeUserCart([FromForm] IFormCollection inFormData)
{

    List<Task<Product>> productTasks = new List<Task<Product>>();

    try
    {
        foreach (var key in inFormData.Keys)
        {
            if (key.Contains("arr"))
            {
                int i = 0;
                var id = int.Parse(inFormData[key][0]);
                var name = inFormData[key][1];
                var image = inFormData.Files[i];
                productTasks.Add(_productService.GetUserCart(id, name));
                i++;
            }

        }
        var productResults = await Task.WhenAll<Product>(productTasks);
        return new JsonResult(productResults);
    }
    catch (Exception ex)
    {
        // return error message
        return BadRequest(new { message = ex.Message });
    }
}


texts:
I've written the code below to do some work on machine learning in R. I'm not overly happy with some bits of it, and I suspect I could improve it quite a bit. Bits I'm specifically interested in looking at are how to deal with appending to vectors in the loop, and whether I can combine all of the functions kf.knn, kf.svm etc into one function with various arguments.

library(class)
library(nnet)
library(epibasix)
library(CVThresh)
library(e1071)

df <- read.table("semeion.data.data")
df$digit <- replicate(nrow(df), 42)

df$digit[which(as.logical(df$V266), arr.ind=TRUE)] = 9
df$digit[which(as.logical(df$V265), arr.ind=TRUE)] = 8
df$digit[which(as.logical(df$V264), arr.ind=TRUE)] = 7
df$digit[which(as.logical(df$V263), arr.ind=TRUE)] = 6
df$digit[which(as.logical(df$V262), arr.ind=TRUE)] = 5
df$digit[which(as.logical(df$V261), arr.ind=TRUE)] = 4
df$digit[which(as.logical(df$V260), arr.ind=TRUE)] = 3
df$digit[which(as.logical(df$V259), arr.ind=TRUE)] = 2
df$digit[which(as.logical(df$V258), arr.ind=TRUE)] = 1
df$digit[which(as.logical(df$V257), arr.ind=TRUE)] = 0

data <- df[,c(0:256,267)]

squareTable <- function(x,y) {
    x <- factor(x)
    y <- factor(y)

    commonLevels <- sort(unique(c(levels(x), levels(y))))

    x <- factor(x, levels = commonLevels)
    y <- factor(y, levels = commonLevels)

    table(x,y)

}

kf.knn <- function(data, k, nearest)
{
  N <- nrow(data)
  data <- data[sample(1:N),]

  folds.index <- cvtype(N, cv.bsize=1, cv.kfold=k, FALSE)$cv.index

  total = 0

  for (i in 1:k)
  {
    test <- data[folds.index[i,], 0:256]
    test.labels <- data[as.array(folds.index[i,]), 257]

    rest <- as.array(folds.index[-i,])

    train <- data[rest, 0:256]
    train.labels <- data[rest, 257]

    knnpredict <- knn(train, test, train.labels, nearest)
    t <- table(as.factor(test.labels), as.factor(knnpredict))

    kap <- epiKappa(t)
    total <- total + kap$kappa
  }

return(total / k)
}

kf.nnet <- function(data, k, hidden)
{
  N <- nrow(data)
  data <- data[sample(1:N),]

  folds.index <- cvtype(N, cv.bsize=1, cv.kfold=k, FALSE)$cv.index

  total = 0

  for (i in 2:k)
  {
    test <- data[folds.index[i,], 0:256]
    test.labels <- data[as.array(folds.index[i,]), 257]

    rest <- as.array(folds.index[-i,])

    train <- data[rest, 0:256]
    train.labels <- data[rest, 257]

    train$label <- as.factor(train.labels)

    nnetwork <- nnet(label ~ ., data=train, size=hidden, MaxNWts = 10000, maxit=200, linout=TRUE)
    nnetpredict <- predict(nnetwork, test, "class")

    table <- squareTable(as.factor(test.labels), as.factor(nnetpredict))

    print(table)
    kap <- epiKappa(table)
    total <- total + kap$kappa
  }

return(total / k)
}

kf.svm <- function(data, k)
{
  N <- nrow(data)
  data <- data[sample(1:N),]

  folds.index <- cvtype(N, cv.bsize=1, cv.kfold=k, FALSE)$cv.index

  total = 0

  for (i in 2:k)
  {
    test <- data[folds.index[i,], 0:256]
    test.labels <- data[as.array(folds.index[i,]), 257]

    rest <- as.array(folds.index[-i,])

    train <- data[rest, 0:256]
    train.labels <- data[rest, 257]

    train$label <- as.factor(train.labels)

    svmmodel <- svm(label ~ ., data=train, cost=8, gamma=0.001, cross=2)
    svmpredict <- predict(svmmodel, test)

    t <- table(as.factor(test.labels), as.factor(svmpredict))
    print(t)
    kap <- epiKappa(t)
    total <- total + kap$kappa
  }

return(total / k)
}

result <- vector("numeric", 1)
n <- vector("numeric", 1)

for (i in 2:10)
{
  avg <- kf.nnet(data, 5, i)
  result <- append(result, avg)
  n <- append(n, i)
  cat("!!!!!!!", i, avg, "\n")
}

result <- result[2:length(result)]
n <- n[2:length(n)]

df <- data.frame(kappa = result, n=n)
plot(df$n, df$res)

print(df)


texts: Accessing MySQL to make queries and scalars

texts:
I've developed my own class in ASP.NET project to access MySQL and make queries and scalars, and read the results from it.

I want you to review my class and tell me where I've made a mistake.

Here are some questions that are important for me:

Do I use a reference correctly for the connector class of MySQL in methods?
Is it correct to make it NON-static class as it is? For the GC, memory reasons?
Do I need to add some events, delegate for the autoclose for the MySQL connection, or is there no need in it, because out of scope it will be auto freed from memory?

public class MySQLGear
{
    private const string connStr = "Server = localhost; Database = self; Uid = someuser; Pwd = 1234;";

    public MySqlConnection CreateConnection()
    {
        MySqlConnection connMysql = new MySqlConnection(connStr);
        connMysql.Open();

        if (connMysql.State == ConnectionState.Open)
        {
            return connMysql;
        }
        else return null;
    }

    public MySqlDataReader GetReader(ref MySqlConnection connMysql, string queryMysql)
    {
        MySqlCommand cmdMysql = new MySqlCommand(queryMysql, connMysql);
        MySqlDataReader readerMysql = cmdMysql.ExecuteReader();
        return readerMysql;
    }

    public int MakeQuery(ref MySqlConnection connMysql, string queryMysql)
    {
        MySqlCommand cmdMysql = new MySqlCommand(queryMysql, connMysql);
        int result = cmdMysql.ExecuteNonQuery();
        return result;
    }

    public object MakeScalar(ref MySqlConnection connMysql, string queryMysql)
    {
        MySqlCommand cmdMysql = new MySqlCommand(queryMysql, connMysql);
        object result = cmdMysql.ExecuteScalar();
        return result;
    }
}


texts:
Inspired by another question here: Sum of Prime numbers under 2 million, I decided to try and implement Eratosthenes' Sieve from scratch using the algorithm described in the article.

unsigned int CalculateSumOfPrimes(const unsigned int number) {
    if(number <= 1) return 0;
    if(number == 2) return 2;
    std::vector<unsigned int> listOfPrimes;
    CalculateListOfPrimes(listOfPrimes, number);
    unsigned int sum = 0;
    for(unsigned int i = 0; i < listOfPrimes.size(); ++i) {
        sum += listOfPrimes.at(i);
    }
    return sum;
}

void CalculateListOfPrimes(std::vector<unsigned int>& container, const unsigned int number) {
    if(container.size() != 0) {
        std::cout << "Container must be empty!" << std::endl;
        return;
    }
    unsigned int current_prime_check = 2;
    std::vector<unsigned int> listOfNonPrimes;
    while(current_prime_check < number) {
        for(unsigned int i = current_prime_check; i < number; i += current_prime_check) {
            if(i == current_prime_check) {
                container.push_back(i);
                continue;
            }
            if(std::find(listOfNonPrimes.begin(), listOfNonPrimes.end(), i) != listOfNonPrimes.end()) continue;
            listOfNonPrimes.push_back(i);
        }
        ++current_prime_check;
        while(std::find(listOfNonPrimes.begin(), listOfNonPrimes.end(), current_prime_check) != listOfNonPrimes.end()) {
            ++current_prime_check;
        }
    }

}

Currently the major bottleneck at large numbers (65536 or higher) is CalculateListOfPrimes(...) at 67% of the total 15 second run time.

Switching the usage from a std::vector to a std::list (since I'm only adding to the END of the the list, it seemed like a good idea), only saved 5%.

Looking at it, the inner while loop is going through EVERY possible number from the currently known non-prime number to the next unknown number, is there an algorithm to tell what the next number to check should be or whether or not the next number and potentially every number after it is guaranteed NOT to be in the list of primes?


texts: Usage of lens for concise update of records

texts:
I'm new to Haskell. I'm developing a game-like simulation. I try to use lenses to update the state of the world.

Current iteration of code works, but looks clumsy. I am trying to improve it, e.g. I would like to:

Get rid of direct enumeration of q1 and so on, with usage of quantityPolymorph and others in them. Problem is that partial application won't help since the function which gets applied is "in the middle" of arguments;
Get rid of incrementQuantity. I'd like something like fmap (+1), but since Quantity is not an instance of Functor, I can't do that. I can't make Quantity an instance because it has kind *. Is there a more concise way, w/o lambda?
Update world with just lenses, if possible. It looks like simple dispatching and I think it might be possible to move away from direct specification of what lens (i.e. quantityPolymorpth) should be called for which argument (f).

Important note: however the updateWorld never emits Nothing at the moment, I want to keep it returning a Maybe because later at some point it will return Nothings as well.

How can I refactor my code? Are there other things amiss with it?

The source follows.

{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE TemplateHaskell #-}

import Control.Lens
import Control.Monad
import System.Random

data Quantity = Quantity Integer deriving (Show)

instance Random Quantity where
    randomR (Quantity lo, Quantity hi) g =
        let rand = randomR (lo, hi) g
            (r, g1) = rand
        in (Quantity r, g1)
    random g =
        let rand = random g
            (r, g1) = rand
        in (Quantity r, g1)

instance Eq Quantity where
    (==) (Quantity q1) (Quantity q2) = q1 == q2

instance Ord Quantity where
    (<=) (Quantity q1) (Quantity q2) = q1 <= q2

instance Num Quantity where
    (+) (Quantity q1) (Quantity q2) = Quantity (q1 + q2)
    (*) (Quantity q1) (Quantity q2) = Quantity (q1 * q2)
    (-) (Quantity q1) (Quantity q2) = Quantity (q1 - q2)
    abs (Quantity q) = Quantity (abs q)
    signum (Quantity q) = Quantity (signum q)
    fromInteger i = Quantity i
-------------------------------

data QuantityHolder = QuantityHolder { _quantityPolymorph  :: Quantity
                                     , _quantityTeamPlayer :: Quantity
                                     , _quantityLoneWolf   :: Quantity
                                     } deriving (Show)

$(makeLenses ''QuantityHolder)
-------------------------------

data Fighter = TeamPlayer
             | LoneWolf
             | Polymorph
    deriving (Show, Eq, Ord)
-------------------------------

data World = World {
    _quantities :: QuantityHolder
} deriving (Show)

$(makeLenses ''World)

incrementQuantity (Quantity q) = Quantity (q + 1)

updateWorld :: Maybe World -> Fighter -> Maybe World
updateWorld (Just w) f =
    case f of
        Polymorph ->
            Just $ q1 w
        TeamPlayer ->
            Just $ q2 w
        LoneWolf ->
            Just $ q3 w
    where q1 = over quantities . over quantityPolymorph $ incrementQuantity
          q2 = over quantities . over quantityTeamPlayer $ incrementQuantity
          q3 = over quantities . over quantityLoneWolf $ incrementQuantity


texts: Method that reads an input file of a particular format and creates objects corresponding to the file

texts:
This is essentially a best practices question about reading a file and making sure it follows a specific format. My current implementation works, but it's a while loop with a bunch of if/else statements. I think it wouldn't be too readable for other developers.

/**
 * Request the server to add the theatre details found in the file indicated by the path.
 * The details include the theatre ID (unique across all theatres), the seating dimension, and
 * the floor area (square metres). All theatres have as many seats in a row as they do rows, and the number of
 * rows is indicated by the seating dimension.
 *

 *
The file format is, each line consists of
 * "THEATRE" "\t" theatre ID; "\t" seating dimension; "\t" floor area;
 *

 *
If there is no file associated with the path, or the file format is incorrect, then
 * the request fails.
 *
 * @param path The path indicating the file to use for the initialisation.
 * @return An empty string if the initialisation is successful, otherwise a
 * message explaining what went wrong beginning with ERROR (e.g. "ERROR incorrect format").
 */
public String initialise(String path)
{
    //IO
    File theatreFile = new File(path);
    Scanner fileScanner = null;

    try
    {
        fileScanner = new Scanner(theatreFile);
    }
    catch (FileNotFoundException e)
    {
        return ResponseMessages.FILE_NOT_FOUND_ERR_MSG.getDescription();
    }

    String currentID = null;
    int numRows;
    int floorSpace;

    /*Loop through input file tokens, check if format is correct and if so, create a theatre object
    that corresponds with the given data. */
    while(fileScanner.hasNext())
    {
        if(fileScanner.hasNext(THEATRE_NAME_MARKER))
        {
            fileScanner.next();

            if(fileScanner.hasNext(THEATRE_CODE_MARKER))
            {
                currentID = fileScanner.next();

                if (getTheatreIDs().contains(currentID))
                {
                    return ResponseMessages.DUPLICATE_CODE_ERR_MSG.getDescription();
                }

                if (fileScanner.hasNextInt())
                {
                    numRows = fileScanner.nextInt();

                    if (fileScanner.hasNextInt())
                    {
                        floorSpace = fileScanner.nextInt();
                    }
                    else
                    {
                        return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
                    }
                }
                else
                {
                    return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
                }
            }
            else
            {
                return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
            }
        }
        else
        {
            return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
        }

        Theatre newTheatre = new Theatre(currentID, numRows, floorSpace);
        theatres.add(newTheatre);
    }

    fileScanner.close();
    return ResponseMessages.FILE_FOUND_SUCCESS_MSG.getDescription();
}

Additionally, here's an example of what an input file may look like:

THEATRE T2  10  400
THEATRE T1  7   200
THEATRE T3  12  600
THEATRE 215 21  1200


texts: Rendering server side errors on the client in Node/Express

texts:
I've set up a simple Node/Express service that creates new bookmarks to a database.

In my Bookmark schema, one of the fields, URL, has validations. When you try to create a new bookmark without the correct validations, it throws an error and a message.

In other words, if you don't provide a URL to the request, then it will throw a message: "Please provide a URL."

The route for the POST request to create a new bookmark:

app.post(
    '/api/bookmarks',
    (req, res) => {
      const { url, tags } = req.body;

      const bookmark = new Bookmark({
        url,
        tags
      });

      bookmark.save()
        .then(res => {
          res.send(result)
        })
        .catch(error => {
          console.log("err:", error);
          res.status(400).send(error)
        });
    }
  );

What my Bookmark schema looks like:

const bookmarkSchema = new Schema({
  url: {
    type: String,
    required: [true, "Please provide a URL."],
    match: [urlRegex, "Your URL is invalid. Please make sure to add www."]
  },
  tags: [String]
});

When I make an API call on the front end client (e.g. via React), I am able to catch the error and subsequent message (Please provide a URL.), but as you can see, I have to call err.response.data.errors.url.message which seems very verbose and long winded.

axios.post('http://localhost:5000/api/bookmarks', { tags: ["banana", "orange"] })
  .then(result => console.log('Result:', result.data))
  .catch(err => console.log('Error:', err.response.data.errors.url.message));

It has me thinking - is there a better way to render errors here? Would it be better handle errors in the client side instead?

I'm quite new to error handling so would like to know what is considered best practice.


texts:
Here's my solution for Project Euler Problem 30. Any optimizations in time, space, or style would be greatly appreciated.

from timeit import default_timer as timer

def digit_powers(exponent):
    def power(k):
        return int(k) ** exponent
    if exponent <= 1:
        return "The exponent must be at least 2."
    else:
        total_sum = 0
        upper_bound = (exponent + 1) * (9 ** exponent)
        for number in range(10, upper_bound + 1):
            digits = [x for x in str(number)]
            if number == sum(map(power, digits)):
                total_sum += number
        return total_sum

start = timer()
ans = digit_powers(5)
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts: Exists Method Implementation for Multidimensional Array in C#

texts:
To determine whether the specified array contains specific element or not, Array.Exists can be used if the given array is one dimensional. I am attempting to implement Exists method for multidimensional array cases.
The experimental implementation
static class MDArrayHelpers
{
    public static bool Exists<T>(Array array, Predicate<T> match)
        where T : unmanaged
    {
        if (ReferenceEquals(array, null))
        {
            throw new ArgumentNullException(nameof(array));
        }

        Type elementType = array.GetType().GetElementType();
        if (!elementType.Equals(typeof(T)))
        {
            throw new System.InvalidOperationException();
        }

        foreach (var element in array)
        {
            if (match((T)element))
            {
                return true;
            }
        }
        return false;
    }
}

Test cases
Predicate<int> isOne = delegate (int number) { return number == 1; };
Predicate<int> isFour = delegate (int number) { return number == 4; };

Console.WriteLine("One dimensional case");
int[] array1 = new int[] { 1, 2, 3 };
Console.WriteLine($"Is one existed in {nameof(array1)}: {Array.Exists(array1, isOne)}");
Console.WriteLine($"Is four existed in {nameof(array1)}: {Array.Exists(array1, isFour)}");
Console.WriteLine("");

Console.WriteLine("Two dimensional case");
int[,] array2 = { { 0, 1 }, { 2, 3 } };
Console.WriteLine($"Is one existed in {nameof(array2)}: {MDArrayHelpers.Exists(array2, isOne)}");
Console.WriteLine($"Is four existed in {nameof(array2)}: {MDArrayHelpers.Exists(array2, isFour)}");
Console.WriteLine("");

Console.WriteLine("Three dimensional case");
int[,,] array3 = { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } };
Console.WriteLine($"Is one existed in {nameof(array3)}: {MDArrayHelpers.Exists(array3, isOne)}");
Console.WriteLine($"Is four existed in {nameof(array3)}: {MDArrayHelpers.Exists(array3, isFour)}");
Console.WriteLine("");

Console.WriteLine("Four dimensional case");
int[,,,] array4 = { { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } }, { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } } };
Console.WriteLine($"Is one existed in {nameof(array4)}: {MDArrayHelpers.Exists(array4, isOne)}");
Console.WriteLine($"Is four existed in {nameof(array4)}: {MDArrayHelpers.Exists(array4, isFour)}");

The output of the test code above:
One dimensional case
Is one existed in array1: True
Is four existed in array1: False

Two dimensional case
Is one existed in array2: True
Is four existed in array2: False

Three dimensional case
Is one existed in array3: True
Is four existed in array3: False

Four dimensional case
Is one existed in array4: True
Is four existed in array4: False

If there is any possible improvement, please let me know.


texts: Complexity, Usability and Readability of FluentAPIs - Sample: FluentMethodInvoker

texts:
new MethodExecuter()
    .ForAllInvocationsCheckCondition(!Context.WannaShutDown)
        .When(shouldRun).ThenInvoke(x => x.Methods(new Action[] { B.Process, A.Process }))
        .When(shouldRun).ThenInvoke(x => x.Method(B.Process).Repeat(100))
        .Invoke(x => x.Method(C.Process));

I deliberately do not say anything about what this API does. I did show this API my team mates and they did not like it. For them it is unreadable.

What do you think about the API?
What tips do you have?
What do you think about complexitiy, usability and readability of fluent APIs and how to achieve good APIs?

EDIT
Why did I build this API?

Well, I have a bunch of methods that are invoked synchronously when a condition is false. The condition applies foreach method invocation.

if (!Context.WannaShutDown) A.Process();
if (!Context.WannaShutDown) B.Process();
if (!Context.WannaShutDown) C.Process();
if (!Context.WannaShutDown) D.Process();
if (!Context.WannaShutDown) E.Process();
if (!Context.WannaShutDown) F.Process();
if (!Context.WannaShutDown)
{
   if (condition)
   {
       for (int i = 0; i <= 100 i++)
       {
           Z.Process();
       }
   }
...

I do not like such crap code. What I wanted to do is to solve "the problem" once with a class that is responsible for invocating methods. I tried to build an API that is as simple as possible, but it seems I failed.


texts:
Using various answers from Stack Overflow and  Ask Ubuntu, I've hacked together this simple C program that wipes terminal history. It works but I'm relatively new to C so I'm not sure if everything is correct.

#include <stdio.h>

int main(void) {
  // check if the program is being executed in a terminal
  if (isatty(0)) {
    // if the program is being executed in a
    // terminal just start the wiper
    system("cat /dev/null > ~/.bash_history;history -c;history -w;rm -r ~/.bash_history;exit;");
  } else {
    // if the program is being executed as a stand-alone
    // open a new terminal window and then start the wiper
    system("gnome-terminal -x sh -c 'cat /dev/null > ~/.bash_history;history -c;history -w;rm -r ~/.bash_history;exit;'");
  }
  // stop the program
  return 0;
}


texts: Log and Count the exception in a Single method

texts:
I am tring to count the number of exceptions happening and log those exceptions as well. So what I did is, I created one method addException in which I am counting all the exceptions.

addException method accepts two parameters, one is the String, and other is the boolean flag which means whether we want to terminate the program or not because of any exceptions. Meaning, if that flag is true, then I need to terminate the program whenever there are any exceptions.

So if you take a look into my below catch block, I have addException method call for counting the exceptions and below that method call I am logging the exceptions as well.

catch (ClassNotFoundException e) {
    addException(e.getCause() != null ? e.getCause().toString() : e.toString(), Read.flagTerminate);
    LOG.error("Threw a ClassNotFoundException in " + getClass().getSimpleName(), e);
} catch (SQLException e) {
    addException(e.getCause() != null ? e.getCause().toString() : e.toString(), Read.flagTerminate);
    //DAMN! I'm not....
    LOG.error("Threw a SQLException while making connection to database in " + getClass().getSimpleName(), e);
}

/**
 * A simple method that will add the count of exceptions and name of
 * exception to a map
 *
 * @param cause
 * @param flagTerminate
 */
private static void addException(String cause, boolean flagTerminate) {
    AtomicInteger count = exceptionMap.get(cause);
    if (count == null) {
        count = new AtomicInteger();
        AtomicInteger curCount = exceptionMap.putIfAbsent(cause, count);
        if (curCount != null) {
            count = curCount;
        }
    }
    count.incrementAndGet();

    if(flagTerminate) {
        System.exit(1);
    }
}

Problem Statement:-

Now what I am looking for is-

Is there any more cleaner way of doing the same thing? Meaning right now I am counting the exceptions in a method and then printing out the exceptions in the next line inside the catch block.

Is it possible to do the both of the things in the same addException method? And if the flag is true to terminate the program, then terminate the program with the proper logging as well.

What could be the best way to re write addException method do this?


texts:
I have merge two images into one. I already implemented it with some help from the internet but it takes around 2,5s. I'm testing on the simulator so let's take it as a reference.

I currently use UIGraphicsBeingImageContext. Is there any faster way to achieve it?

extension UIImage {
    func overlayWith(image: UIImage, posX: CGFloat, posY: CGFloat, topImageSize: CGSize,
                     combinedImage: @escaping (UIImage) -> Void) {
        DispatchQueue.global(qos: .userInteractive).async {
            let newWidth = self.size.width < posX + image.size.width ? posX + image.size.width : self.size.width
            let newHeight = self.size.height < posY + image.size.height ? posY + image.size.height : self.size.height
            let newSize = CGSize(width: newWidth, height: newHeight)

            UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
            self.draw(in: CGRect(origin: CGPoint.zero, size: self.size))
            image.draw(in: CGRect(origin: CGPoint(x: posX, y: posY), size: topImageSize))
            let newImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()

            DispatchQueue.main.async {
                combinedImage(newImage)
            }
        }
    }
}


texts: Requests / Facebook API - Dealing with Errors

texts:
I work in marketing and I am currently trying to aggregate data for 50 facebook pages on the same Business Page.

I have a loop that tries a series of requests to grab all data. I am not sure I am handling exceptions in the best way possible, so I was wondering if somebody had any idea on how to improve the situation.

Main problem is that, for a reason or another, the calls for page n°40 out of my 50 pages break the API Limit 8th fold. Not sure what's causing the issue, but I imagine it has to do with this part of my code.

I can post the whole function if necessary.

counter = 0

while True:

    try:

        if ('next' in s['paging']):

            next_s   =   s['paging']['next']
            s        =   requests.get(next_s).json()
            s_total.extend(s['data'])
            counter += 1

            print("Getting Page. Current progress: {}".format(counter))

        elif ('after' in s['paging']['cursors']):

            next_s       =   s['paging']['cursors']['after']
            new_page_url = next_request+next_s
            s            =   requests.get(new_page_url).json()
            s_total.extend(s['data'])
            print("Getting After. Current progress: {}".format(counter))

        elif ('32' in str(s['error']['code'])):

            print('Faced error {} in: {} '.format(str(s['error']['code']), username))
            print('Sleeping for 1 hour')
            sleep(3605)

            next_s   =   s['paging']['next']
            s        =   requests.get(next_s).json()
            s_total.extend(s['data'])
            counter += 1

            print('Continuing...')
            continue

        elif ('4' in str(s['error']['code'])):

            print('Faced error {} in: {} '.format(str(s['error']['code']), username))
            print('Sleeping for 1 hour')
            sleep(3605)

            next_s   =   s['paging']['next']
            s        =   requests.get(next_s).json()
            s_total.extend(s['data'])
            counter += 1
            print('Continuing...')
            continue

        else:
            print(s['error'])
            break

    except KeyError:

        print('Finished page : {} '.format(username))

        break


texts: An Awk program to find all primes till N

texts:
I developed Awk code to print all primes till N where N is given as command line argument. I think I took pretty much all the optimizations into account. Could someone help if it could be optimized even more. The code is as follows:

#!/usr/bin/awk -f

BEGIN{
  for (i=oddify(ARGV[1]); i>2; i=i-2){
    flag=1 #prime
    for(j=3; j<=ceil(sqrt(i)); j=j+2){
      if (i%j==0){
        flag=0 #not prime
        break
      }
    }
    if (flag==1){printf("%d\n", i) }
  }
  printf("2\n")
}

function ceil(n){
  return (n == int(n)) ? n : int(n)+1
}

function oddify(n){
  return (n%2 != 0) ? n : n-1
}

How to run: awk -f prime.awk 10000


texts: Hexadecimal to string without C++ standard library functions

texts:
For the purposes of this code review, I will use the standard library, but pretend that <cstddef> is <stddef.h>, that I didn't use std::cout, that new and delete[] are overloaded and call custom malloc functions, etc. So this is -std=c++11 -ffreestanding.

Here are my questions:

Currently my tohex function returns a buffer allocated on the heap. Is it better if I have the caller pass the buffer as a parameter instead? Is there a way to avoid heap allocation without using variable length arrays?
I have a separate function that counts the size of the digits so that I can reverse the string. What's an alternate way of doing this?
Should I prefer uint8_t or int or is unsigned okay? I don't think there should be any issues with what type I choose in the code shown.

#include <cstddef>

unsigned count(unsigned n)
{
    int digits = 0;
    while (n > 0)
    {
        ++digits;
        n /= 16;
    }
    return digits;
}

char* tohex(unsigned n)
{
    unsigned size = count(n) + 1;
    char *buffer = new char[size];
    unsigned index = size - 2;
    while (n > 0)
    {
        unsigned mod = n % 16;

        if (mod >= 10)
            buffer[index--] = (mod - 10) + 'A';
        else
            buffer[index--] = mod + '0';

        n /= 16;
    }
    buffer[size - 1] = '\0';
    return buffer;
}

#include <iostream>

int main()
{
    char *buffer = tohex(0xBEEFCAFE);
    std::cout << buffer;
    delete[] buffer;
    return 0;
}


texts: An extension method to safely retrieve or add a dictionary value

texts:
The extension method:

/// <summary>
/// Thread safe. May lock on the input dictionary.
/// </summary>
public static U GetOrAdd<T, U>(this Dictionary<T, U> dict, T key, Func<U> create) {
    U val;
    if (!dict.TryGetValue(key, out val)) {
        lock (dict) {
            if (!dict.ContainsKey(key)) {
                val = create();
                dict[key] = val;
            } else {
                val = dict[key];
            }
        }
    }
    return val;
}

Sample usage:

var idVals = new Dictionary<int, List<int>>();
List<int> vals = idVals.GetOrAdd(id, () => new List<int>());
vals.Add(3);

Explanation:

If the key exists, we quickly retrieve the value using the
TryGetValue() method
If the key doesn't exist we use the provided create delegate to make a new one
We are protected against the case of two threads simultaneously looking for a key that doesn't exist by locking on the input
dictionary and afterward re-checking to see if the key still doesn't exist

Questions:

Are there scenarios that will cause this fail?
I found this extension method to be useful, but is clear enough to be properly understood by others?
Are there easier ways to achieve the thread-safety I'm looking for?
I know it's considered dangerous and bad practice to lock on an input parameter, but can I rely on the fact that locking on a dictionary to safely add/remove elements is a common convention?


texts:
I have a table that contains information about users, which I deny loading a specific web page.

Each record contains 4 columns: referrer, ip, userAgent & email.

Each column can contain a wild card (i.e. an asterisk *), which make me block a group.

How could performance be improved with this code?

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.RAMDirectory;

import java.io.IOException;

class BlacklistLucene {

    private static final String MATCH_ALL = "*";
    private static IndexSearcher cache;

    private enum Fields {
        referrer, ip, userAgent, email
    }

    private static Document getDocument(String referrer, String ip, String userAgent, String email) {
        Document doc = new Document();
        doc.add(getStringField(referrer, Fields.referrer.name()));
        doc.add(getStringField(ip, Fields.ip.name()));
        doc.add(getStringField(userAgent, Fields.userAgent.name()));
        doc.add(getStringField(email, Fields.email.name()));
        return doc;
    }

    private static StringField getStringField(String val, String field) {
        return new StringField(field, val, Field.Store.NO);
    }

    private static BooleanQuery createQuery(String referrer, String ip, String userAgent, String email) {
        return new BooleanQuery.Builder()
                .add(createBooleanQuery(Fields.referrer.name(), referrer), BooleanClause.Occur.FILTER)
                .add(createBooleanQuery(Fields.ip.name(), ip), BooleanClause.Occur.FILTER)
                .add(createBooleanQuery(Fields.userAgent.name(), userAgent), BooleanClause.Occur.FILTER)
                .add(createBooleanQuery(Fields.email.name(), email), BooleanClause.Occur.FILTER)
                .build();
    }

    private static BooleanQuery createBooleanQuery(String key, String value) {
        return new BooleanQuery.Builder()
                .add(new TermQuery(new Term(key, value)), BooleanClause.Occur.SHOULD)
                .add(new TermQuery(new Term(key, MATCH_ALL)), BooleanClause.Occur.SHOULD)
                .build();
    }

    private static boolean isBlacklisted(String ref, String ip, String ue, String email) throws IOException {
        BooleanQuery query = createQuery(ref, ip, ue, email);
        return cache.search(query, 1).totalHits > 0;
    }

    public static void main(String[] args) throws Exception {

        RAMDirectory directory = new RAMDirectory();
        IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(new StandardAnalyzer()));
        writer.addDocument(getDocument("ref1", "127.0.0.ip1", "Mozilla UserAgent1", "email.com"));
        writer.addDocument(getDocument("ref2", "127.0.0.ip2", "Mozilla UserAgent2", "*"));
        writer.close();
        DirectoryReader reader = DirectoryReader.open(directory);
        cache = new IndexSearcher(reader);

        System.out.println(isBlacklisted("ref1", "127.0.0.ip1", "Mozilla UserAgent1", "email.com")); // true
        System.out.println(isBlacklisted("r2.com", "127.0.0.4", "Mozilla", "yahoo.com")); // false
        System.out.println(isBlacklisted("ref2", "127.0.0.ip2", "Mozilla UserAgent2", "this is ignored")); // true
        System.out.println(isBlacklisted("*", "127.0.0.ip2", "Mozilla UserAgent2", "*")); // true
    }
}


texts:
Spoiler

This code is actually BAD for performances! So don't use it! ;)

For a while now, I've been using this wrapper to avoid retyping most of it :

Public Sub PerfWrap(SubNameToRun As String, _
                    Optional ByVal DispStatusBar As Boolean = False, _
                    Optional ArgumentsToPass As String = vbNullString)
    Dim aWB As Workbook, _
        ActiveSH As Worksheet, _
        ScreenUpdateState As Boolean, _
        StatusBarState As Boolean, _
        CalcState As XlCalculation, _
        EventsState As Boolean, _
        DisplayPageBreakState As Boolean
    Set aWB = ActiveWorkbook
    Set ActiveSH = aWB.ActiveSheet
    DoEvents
    With Application
        ScreenUpdateState = .ScreenUpdating
        StatusBarState = .DisplayStatusBar
        CalcState = .Calculation
        EventsState = .EnableEvents
        DoEvents
        .ScreenUpdating = False
        .DisplayStatusBar = DispStatusBar
        .Calculation = xlCalculationManual
        .EnableEvents = False
    End With
    DisplayPageBreakState = ActiveSH.DisplayPageBreaks
    ActiveSH.DisplayPageBreaks = False

    If ArgumentsToPass <> vbNullString Then
        Application.Run SubNameToRun, ArgumentsToPass
    Else
        Application.Run SubNameToRun
    End If

    DoEvents
    ActiveSH.Activate
    ActiveSH.DisplayPageBreaks = DisplayPageBreakState
    With Application
        .ScreenUpdating = ScreenUpdateState
        .DisplayStatusBar = StatusBarState
        .StatusBar = vbNullString
        .Calculation = CalcState
        .EnableEvents = EventsState
    End With
End Sub

I use it like this :

Public Sub Launcher_CopyAndUpdate()
    Call PerfWrap("CopyAndUpdate_Templates", True)
End Sub

Or to pass arguments to the runned procedure :

Public Sub Launcher_Update()
    Call PerfWrap("Update_Templates", True, "Arg1, Arg2")
End Sub

I was wondering if :

it can be improved regarding performances
converted as a function to return the value sent by the runned function

Anyhow, any input or opinion is very welcome! :)


texts: Replacing names in text fields with aliases to help de-identify data

texts:
I have a table with over 1,000,000 records. I need to replace any names in the text fields with aliases to help de-identify the data. For this example, let's assume the table is TemporaryTest and has two fields: Id (the key field) and IndexedXML (the text field).

I have a second table, AppellationSubstitution, that has the following columns: TextEntry (a name needing replacement), Length (length of TextEntry), Replacement (the replacement name, which may be of a different length). That table has about 110,000 rows.

The first step I use is (the regex matches words in the text field -- it looks a bit odd because of some odd characters that show up in this database):

SELECT id,
       matchindex,
       matchlength,
       replacement
FROM   TemporaryTest
       CROSS APPLY
master.dbo.Regexmatches('([Xx]-)?[\w-[0-9üÿ_]]{2,}(-[\w-[0-9üÿ_]]{2,})?(''[\w-[0-9üÿ_]])?', [IndexedXML],
master.dbo.Regexoptionenumeration(0, 0, 1, 1, 0, 0, 0, 0, 0))
       INNER JOIN dbo.appellationsubstitution
       ON match = textentry
       ORDER BY Id, MatchIndex DESC;--if replace in forward order, insertion point gets moved

This produces a table with over 100,000 rows, which the following shows a few lines:

Id matchindex matchlength replacement

99309 122 5 “Demarcus”
108639 106 5 “Demarcus”
109809 84 6 “Rehbein”
110373 89 7 “Reginald”
111156 105 5 “Demarcus”
112452 129 6 “Thie”
112896 113 6 “Diberardino”
112896 92 6 “Diberardino”
113503 119 3 “Rubin”

The full procedure I'm currently trying out is:

SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;

DECLARE ReplaceCursor CURSOR LOCAL FOR
SELECT id,
       matchindex,
       matchlength,
       replacement
FROM   TemporaryTest
       CROSS APPLY
master.dbo.Regexmatches('([Xx]-)?[\w-[0-9üÿ_]]{2,}(-[\w-[0-9üÿ_]]{2,})?(''[\w-[0-9üÿ_]])?', [IndexedXML],
master.dbo.Regexoptionenumeration(0, 0, 1, 1, 0, 0, 0, 0, 0))
       INNER JOIN dbo.appellationsubstitution
       ON match = textentry
       ORDER BY Id, MatchIndex DESC;--if replace in forward order, insertion point gets moved
DECLARE @Rid int, @Rmi AS int, @Rml AS int, @Rrep AS nvarchar(255);
OPEN ReplaceCursor;
FETCH NEXT FROM ReplaceCursor INTO @Rid, @Rmi, @Rml, @Rrep;
WHILE @@FETCH_STATUS = 0
BEGIN
    UPDATE TemporaryTest
    Set IndexedXML =  STUFF([IndexedXML],@Rmi+1,@Rml,@Rrep)
        WHERE Id = @Rid;
    FETCH NEXT FROM ReplaceCursor INTO @Rid, @Rmi, @Rml, @Rrep;
END;
CLOSE ReplaceCursor;
DEALLOCATE ReplaceCursor;
COMMIT TRANSACTION

This works, but takes a very long time to run (over an hour and not yet completed), and IndexedXML is one of the smallest text fields I have in the production database.

I resorted to using a cursor as I didn't know any other way to manage sequential STUFF calls on the same cell, where subsequent STUFF calls use the result of the previous ones.

Am I taking the right course with this, or is there a faster/cleaner way of achieving this?


texts:
I need to write a TextureManager class which stores Texture objects; the problem is I'm using an std::map<Texture *, const char*> map to store Texture objects using a key.

Searching elements through a map is not ideal because of performance issues (I'm writing a C++ library, so performance is important).

I've had the idea to use an std::vector<Texture*>. In this case, I need to use an unsigned int. But after several tries, I still cannot implement it.

Here is the .h:

class CTextureManager
{
public:
    CTextureManager(SDL_Renderer *pRenderer);
    void SetRenderer(SDL_Renderer *pRenderer);

    ~CTextureManager();

    // Load File function
    CTexture *LoadFromFile(std::string name, std::string filename);

    bool UnLoad(std::string name);

    CTexture *GetTexture(std::string name);

    void ClearAll();

protected:
    std::map<std::string, CTexture *> m_mapTexture;
    SDL_Renderer *m_pRenderer;

};

and the .cpp:

CTextureManager::CTextureManager(SDL_Renderer *pRenderer)
{
    m_pRenderer = pRenderer;
}

CTextureManager::~CTextureManager()
{
    ClearAll();

    if (m_pFont != nullptr)
    {
        TTF_CloseFont(m_pFont);
    }
}

void CTextureManager::ClearAll()
{
    for (std::map<std::string, CTexture *>::iterator it = m_mapTexture.begin(); it != m_mapTexture.end(); ++it)
    {
        delete (it->second);
        (it->second) = nullptr;
    }
    m_mapTexture.clear();
}

CTexture * CTextureManager::GetTexture(std::string name)
{
    return m_mapTexture[name];
}

bool CTextureManager::UnLoad(std::string name)
{
    CTexture *pTempTexture = m_mapTexture[name];

    if (!pTempTexture)
        return false;

    delete pTempTexture;
    pTempTexture = nullptr;
    m_mapTexture.erase(name);
    return true;
}

CTexture * CTextureManager::LoadFromFile(std::string name, std::string filename)
{
    CTexture *pTexture = m_mapTexture[name];

    if (pTexture == nullptr)
    {
        pTexture = new CTexture();
        pTexture->SetRenderer(m_pRenderer);

        m_mapTexture[name] = pTexture;
    }

    if (!pTexture->LoadFromFile(filename))
        return nullptr;

    return pTexture;
}

void CTextureManager::SetRenderer(SDL_Renderer *pRenderer)
{
    m_pRenderer = pRenderer;
}


texts: Shared counter variable among different threads

texts:
I have a need to use a shared variable among different threads in c/C++.
So putting my knowledge of threads and mutexes I have written the below sample code.
Can anyone please review the code and provide me review comments so that I can improvise it in a more better way. Also I know about atomic variables but somehow I don't want to get into that and wanted to stick with threads & mutexes and locking mechanism. Below code is a working code.

#include <iostream>
#include <unistd.h>
#include <pthread.h>

using namespace std;

class Thread
{
  public:
    Thread();
    virtual ~Thread();

    int start();
    int join();
    int detach();
    pthread_t self();

    virtual void* run() = 0;

  private:
    pthread_t  m_tid;

    int        m_running;
    int        m_detached;
};

static void* runThread(void* arg)
{
    return ((Thread*)arg)->run();
}

Thread::Thread() : m_tid(0), m_running(0), m_detached(0) {}

Thread::~Thread()
{
    if (m_running == 1 && m_detached == 0) {
        pthread_detach(m_tid);
    }
    if (m_running == 1) {
        pthread_cancel(m_tid);
    }
}

int Thread::start()
{
    int result = pthread_create(&m_tid, NULL, runThread, this);
    if (result == 0) {
        m_running = 1;
    }
    return result;
}

int Thread::join()
{
    int result = -1;
    if (m_running == 1) {
        result = pthread_join(m_tid, NULL);
        if (result == 0) {
            m_detached = 0;
        }
    }
    return result;
}

int Thread::detach()
{
    int result = -1;
    cout<<"Detaching thread"<<endl;
    if (m_running == 1 && m_detached == 0) {
        result = pthread_detach(m_tid);
        if (result == 0) {
            m_detached = 1;
        }
    }
    return result;
}

pthread_t Thread::self() {
    return m_tid;
}

class Mutex
{
    friend class CondVar;
    pthread_mutex_t  m_mutex;

  public:
    // just initialize to defaults
    Mutex() { pthread_mutex_init(&m_mutex, NULL); }
    virtual ~Mutex() { pthread_mutex_destroy(&m_mutex); }

    int lock() { return  pthread_mutex_lock(&m_mutex); }
    int trylock() { return  pthread_mutex_trylock(&m_mutex); }
    int unlock() { return  pthread_mutex_unlock(&m_mutex); }
};

class shared_integer {
private:
    int i;
    Mutex mlock;

public:
    // Parameterised constructor
    shared_integer(int i = 0)
    {
        this->i = i;
    }
    // Overloading the postfix operator
    void operator++(int)
    {
       mlock.lock();
       (this->i)++;
       mlock.unlock();
    }

    void operator--(int)
    {
         (this->i)--;
    }

    // Function to display the value of i
    void display()
    {
        cout << "Value became:" <<i << endl;
    }
};
class MyThread:public Thread
{
Mutex mlock;
shared_integer &wd;
public:
MyThread(
         shared_integer & workd
        ):
         wd(workd){}
void *run() {
        for (int i = 0; i < 10; i++) {
            cout<<"thread "<<(long unsigned int)self()<<endl;
            //Currently testing with only work done
            wd++;
            wd.display();
            sleep(1);
            }
        cout<<"thread done "<<(long unsigned int)self()<<endl;
        return NULL;
    }

};
// Driver function
int main(int argc , char ** argv)
{
    shared_integer workdone(0);

    MyThread* thread1 = new MyThread(workdone);
    MyThread* thread2 = new MyThread(workdone);
    MyThread* thread3 = new MyThread(workdone);
    MyThread* thread4 = new MyThread(workdone);

    cout<<"main After creating threads"<<endl;
    thread1->start();
    thread2->start();
    thread3->start();
    thread4->start();
    cout<<"main Before joining first therad"<<endl;
    cout<<"main Before joining second therad"<<endl;
    thread1->join();
    thread2->join();
    thread3->join();
    thread4->join();

    cout<<"main done"<<endl;
return 0;

}


texts: Join via navigation properties with collection

texts:
There are some related collection objects in my table and I'm trying to get list with joining this tables. But this code is seems bad:

Entities that shortened:

User:

public partial class User
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public User()
    {
        this.UserVip = new HashSet<UserVip>();
    }
    public int Id { get; set; }
    public int UserID { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<UserVip> UserVip { get; set; }
}

UserVip

public partial class UserVip
{
    public int UserVIPID { get; set; }
    public int UserID { get; set; }
    public int VIPID { get; set; }
    public virtual User User { get; set; }
    public virtual VipType VipType { get; set; }
}

VipType

public partial class VipType
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public VipType()
    {
        this.UserVip = new HashSet<UserVip>();
    }

    public int VIPID { get; set; }
    public string Name { get; set; }
    public short BonusRatio { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<UserVip> UserVip { get; set; }
}

I'm trying to develop that: If user is in uservip table get user's uservip's viptype:

  System.Linq.Expressions.Expression<Func<UserActivity, object>>[] includeExps = new System.Linq.Expressions.Expression<Func<UserActivity, object>>[1] { x => x.User.UserVip.FirstOrDefault() != null ? x.User.UserVip.FirstOrDefault().VipType : null };
  var userActivities = includeExps.Aggregate(context.UserActivity.Where(x => x.ActivityID == activityID && x.OptionID == optionID), (current, exp) => current.Include(exp)).ToList();


texts: Removing hackery from pair of radix functions

texts:
I like the radix function and found a really neat way to compute its inverse in Python with a lambda and reduce() (so I really feel like I'm learning my cool functional programming stuff):

def unradix(source,radix):
        # such beauty
        return reduce(lambda (x,y),s: (x*radix,y+s*x), source, (1,0))

where:

>>> unradix([1,0,1,0,1,0,1],2)
(128,85)

But its dizygotic twin is unable to use the same pattern without an ugly hack:

def radix(source,radix):
        import math
        hack = 1+int(math.floor(math.log(source)/math.log(radix)))
        # ^^^^ ... _nearly_ , such beauty
        return reduce(lambda (x,y),s: (x/radix,y+[x%radix]), xrange(hack), (source,[]))

where:

>>> radix(85,2)
(0, [1, 0, 1, 0, 1, 0, 1])

How can I remove the hack from this pattern?  Or failing that, how can I rewrite this pair of functions and inverse so they use the same pattern, and only differ in "mirror-symmetries" as much as possibly?

By mirror symmetry I mean something like the way increment and decrement are mirror images, or like the juxtaposition of x*radix versus x/radix in the same code location as above.


texts: Using Enum in java to store a fixed set of mutable objects

texts:
I already posted this on Stack Overflow, but someone suggested to post it to Code Review instead.

I am creating an Android app that draws to the canvas. For this, I have defined rectangular screenareas that I want to draw to the canvas. As I am always drawing a fixed set of screenareas, I was thinking of using Enum (as Enum is designed for fixed sets).

Here is my enum:

public enum LayoutEnum {
    FULLSCREEN(
            new ScreenArea(
                new Rect(
                        0,
                        0,
                        MainActivity.getDevice().getWidth(),
                        MainActivity.getDevice().getHeight()),
                Attributes.BG_PAINT)),
    LOGO_AREA(
            new ScreenArea (
                    new Rect(
                            (int) (0.3 * FULLSCREEN.getScreenArea().getArea().width()),
                            (int) (0.3 * FULLSCREEN.getScreenArea().getArea().width()),
                            (int) (FULLSCREEN.getScreenArea().getArea().width() - 0.3 * FULLSCREEN.getScreenArea().getArea().width()),
                            (int) (0.7 * FULLSCREEN.getScreenArea().getArea().width())),
                    Attributes.BG_PAINT)
    );

    private ScreenArea screenArea;

    LayoutEnum(ScreenArea screenArea) {
        this.screenArea = screenArea;
    }

    public ScreenArea getScreenArea() {
        return screenArea;
    }
}

ScreenArea is a simple class that holds a Rect and a Paint and contains a draw method (and some getters and setters).

The question I have, is: is this a good approach? On one hand I am working with a fixed set of variables. On the other hand, these variables are mutable and I can change their attributes (e.g., using the getters and setters). For example, I can call FULLSCREEN.getScreenArea().getPaint().setColor(Color.BLUE)

When you look at Enum it says it is

  a special data type that enables for a variable to be a set of
  predefined constant

So I do have a fixed set, it is predefined, but not necessarily constant.

My original approach was to define a class called Layout which contained a HashMap of Screenarea's. In that case, I was using e.g., Layout.get("fullscreen").draw(canvas) to draw the screenarea to the canvas. In this new approach I am using e.g., FULLSCREEN.getScreenArea().draw(canvas).

One of the reasons I would like to switch is to introduce a typesafe solution. Of course, it would also be possible to switch from a HashMap to an EnumMap and store the names of my screenareas in an Enum.

Hope you can point me in the right direction: a direction that not only works (the above is already working) but is also acceptable and doesn't smell.


texts:
This code is from a flex app and is the PHP to determine if a user has read a section of text and answered a question correctly.

I write to a table that is similar to a bookmark, and then update the users points. This code works, but since I am making two calls to the database I am worried that it is too "expensive". I tried a few things like using a subquery (maybe I just don't know the syntax). I am using this for now, but I just want to do as well as I can.

public function createReadSectionAndPnts($userId, $item){
  $stmt = mysqli_prepare($this->connection,
"INSERT INTO readSection (
        user_id, chapter_id, section_letter, section_id, sub_section
        )
    VALUES (?, ?, ?, ?, ?)");
$this->throwExceptionOnError();

mysqli_bind_param($stmt, 'iisss', $userId, $item->chapter_id, $item->section_letter,
$item->section_id, $item->sub_section);
$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

$autoid = mysqli_stmt_insert_id($stmt);

mysqli_stmt_free_result($stmt);

$stmt2 = mysqli_prepare($this->connection,
"UPDATE users SET total_points = (5 + total_points)  WHERE id =?");
    $this->throwExceptionOnError();

    mysqli_bind_param($stmt2, 'i', $userId);
    $this->throwExceptionOnError();

    mysqli_stmt_execute($stmt2);
    $this->throwExceptionOnError();

    mysqli_stmt_free_result($stmt2);
    mysqli_close($this->connection);

return $autoid;
}


texts: Outputting prime numbers in given ranges

texts:
I coded an algorithm which shows prime numbers in the ranges provided by the user. The first line states the number of test cases. Example:

INPUT

2
1 10
1 5

OUTPUT

2
3
5
7

2
3
5

t - number of cases, n and m is the range
(t<=10)
m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space

And here is my problem, algorithm works fine, but website which test this, shows- too slow. I need less than 6s !

In my opinion, problem is in method addPrimeNumbers.

class PrimeNumbers{

    private static int m = 0;
    private static int n = 0;
    private static int t = 0;
    private static int i = 0;
    private static String beforeSeparate;
    private static Scanner sc = new Scanner(System.in);
    private static List<int[]> scope = new ArrayList<>();

    public static void main (String[] args) {
        t = Integer.valueOf(sc.nextLine());
        if (checkT(t)) {

            beforeSeparate = sc.nextLine();

            if (separate(beforeSeparate).length == 2) {
                m = separate(beforeSeparate)[0];
                n = separate(beforeSeparate)[1];
                i++;
            }
            if (checkM(m) && checkN(n) && t != 1 && n - m <= 100000) {
                int firstScope[] = {m,n};
                scope.add(firstScope);
                repeatReader();
            }
            else if (t == 1 && checkM(m) && checkN(n) && n - m <= 100000){
                int firstScope[] = {m,n};
                scope.add(firstScope);
            }
            for (int[] aScope : scope) {
                addPrimeNumbers(aScope[0], aScope[1]);
            }
        }
    }

    private static void repeatReader(){
        beforeSeparate = sc.nextLine();
        if (separate(beforeSeparate).length == 2){
            m = separate(beforeSeparate)[0];
            n = separate(beforeSeparate)[1];
            i++;
            int nextScope[] = {m,n};
            scope.add(nextScope);
            if (i < t){
                repeatReader();
            }
        }
    }

    private static void addPrimeNumbers(int i, int i1) {
        String result = "";

        for (int j = i; j <= i1 ; j++) {

            int counters = 0;
            for (int num = j; num >= i ; num--) {

                if (j % num == 0){
                    counters = counters +1;
                }
            }
            if (counters == 2){
                result = result + j + "\n";
            }
        }
        System.out.println(result);
    }

    private static boolean checkT(int i){
        return i > 0 && i <= 10;
    }

    private static boolean checkMinMax(int i) {
        return i >= 1 && i <= 1000000000;
    }

    private static boolean checkM(int i) {
        return checkMinMax(i) && n > 0 && i <= n;
    }

    private static boolean checkN(int i) {
        return checkMinMax(i) && m > 0 && i >= m;
    }

    private static int[] separate(String i){
        String twoValue[] = i.split(" ");

        m = Integer.parseInt(twoValue[0]);
        n = Integer.parseInt(twoValue[1]);
        return new int[]{Integer.parseInt(twoValue[0]), Integer.parseInt(twoValue[1])};
    }
}

Someone know, how to speed up this ?


texts:
Im trying to make a SFML code that takes my code i already have to make a star with a convex shape and put it into a circle of stars surrounding the point the user chooses. The User is also able to choose the amount of stars in the circle.

Here is my code for making a star

#include <iostream>
#include <SFML/Graphics.hpp>

#include <stdlib.h>

#include <time.h>
#include <math.h>
using namespace std;
using namespace sf;
int main()
{
double x;
double y;
double width;
double p = 3.14*4;
double r = width;

cout<<"Enter x"<<endl;
cin>>x;

cout<<"Enter y"<<endl;
cin>>y;

cout<<"Enter a width"<<endl;
cin >>width;

RenderWindow window(VideoMode(800,800),"My Window");
window.setFramerateLimit(60);

ConvexShape convex;
convex.setPointCount(5);

convex.setPoint(0,Vector2f(width*cos(p/5)+x,width*sin(p/5)+y));
convex.setPoint(1,Vector2f(width*cos(p/5*2)+x, width*sin(p/5*2)+y));
convex.setPoint(2,Vector2f(width*cos(p/5*3)+x, width*sin(p/5*3)+y));
convex.setPoint(3,Vector2f(width*cos(p/5*4)+x, width*sin(p/5*4)+y));
convex.setPoint(4,Vector2f(width*cos(p/5*5)+x, width*sin(p/5*5)+y));
convex.setFillColor(Color(0,0,255));

while (window.isOpen())
{
    Event event;
    while (window.pollEvent(event))
    {
        if (event.type == Event::Closed)
            window.close();
    }
    window.clear();

window.draw(convex);

    window.display();

}
return 0 ;
}


texts: If ComparisonIsTrue(thisPost, ComparisonOperator.NotEqualTo, goodCode) Then Me.Answer

texts:
This is a follow-on to a global enum for comparison operators. I wanted to pass a logical expression E.G. >= someValue as a parameter to a function, so I made an Enum and an accompanying function to analyse logical expressions.

Is my approach a good way to implement this functionality in VBA?

Public Enum ComparisonOperator
    NotEqualTo = 0
    LessThan = 1
    LessThanOrEqualTo = 2
    EqualTo = 3
    GreaterThanOrEqualTo = 4
    GreaterThan = 5
End Enum

Public Function ComparisonIsTrue(ByVal sourceValue As Variant, ByVal operator As ComparisonOperator, ByVal comparisonValue As Variant) As Boolean

    If IsNull(sourceValue) Or IsNull(comparisonValue) Then GoTo CleanFail
    If IsObject(sourceValue) Or IsObject(comparisonValue) Then GoTo CleanFail

    Dim isTrue As Boolean

    Select Case operator

        Case NotEqualTo
        isTrue = (sourceValue <> comparisonValue)

        Case LessThan
        isTrue = (sourceValue < comparisonValue)

        Case LessThanOrEqualTo
        isTrue = (sourceValue <= comparisonValue)

        Case EqualTo
        isTrue = (sourceValue = comparisonValue)

        Case GreaterThanOrEqualTo
        isTrue = (sourceValue >= comparisonValue)

        Case GreaterThan
        isTrue = (sourceValue > comparisonValue)

        Case Else
        '/ Error Handling
        Stop

    End Select

CleanExit:
    ComparisonIsTrue = isTrue
    Exit Function

CleanFail:
    isTrue = False
    GoTo CleanExit

End Function


texts:
Trying to refactor this code and can't seem to think of a way to make it cleaner. Type is  a property in my Person class.

foreach (var item in list)
{
    if (person.Type != PersonType.Employee && person.Type != PersonType.Manager && person.Type != PersonType.Contractor && person.Type != PersonType.Executive)
    {
        DoSomething();
    }
}

public enum PersonType : int {
   Employee = 0,
   Manager = 1,
   Contractor = 2,
   President = 3,
   Executive = 4
}

I should note that there are other types in the PersonType class which I don't want to show.


texts: Binary Tree Longest Consecutive Sequence

texts:
I written code to solve this problem which I found on leetcode. My solution worked for the vast majority of the test cases run against it but failed on 2 for some reason. The first test case it failed on had a extremely large input size for the tree so it's really hard to determine what is actually wrong with the algorithm I wrote:

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def lcs(root):
    if root is None:
        return 0
    left_lcs = lcs(root.left)
    right_lcs = lcs(root.right)
    add_to_left = 0
    add_to_right = 0
    if root.left is not None:
        if root.left.val - root.val == 1:
            add_to_left = 1
    if root.right is not None:
        if root.right.val - root.val  ==1:
            add_to_right =1
    if root.right is None and root.left is None:
        return 1
    return max(add_to_left + left_lcs, add_to_right + right_lcs)

Are there any glaring issues with the code that I'm just missing?


texts: Verifying the type of an AggregateException's inner exception in a unit test

texts:
I've got the following code inside an integration test.

[TestMethod]
public void Integration_GetUser_WithoutLoggingIn_ThrowsInvalidOperationException()
{
    var myApi = new Api(new Session());

    try
    {
        var irrelevant = myApi.GetUserInfoAsync().AsTask().Result;
    }
    catch (AggregateException ae)
    {
        if (ae.InnerException.GetType() == typeof(InvalidOperationException))
        {
            Assert.IsTrue(true);
        }
        else
        {
            Assert.Fail("There was no InvalidOperationException.");
        }
    }
}

Some remarks about it:

I am writing a Windows Runtime Component so the return type has to be IAsyncOperation<T>, Task<T> is not an option.
I am blocking the call using AsTask().Result, is this the most appropriate method?
Exceptions thrown in an asynchronous chain return AggregateException so I want to inspect that it throws the exception which I defined as "you are not logged in".
I'm using MSTest because NUnit can't handle WinRT types (which stinks in combination with integration tests).


texts:
In main:

for(int i = 1; i < upto; i *= 2)
    {  for(int j = 0; j < (upto - i); j += (2*i))
       {  int end2 = (2*i < (upto - j)) ? 2*i : upto - j;
          mymerge(&(array[j]), i, end2); }  }

Merge:

void mymerge(people  *arr, int end1, int end2){
  int i = 0;
  int j = end1;
  int k = 0;
  people * temp = new people[end2];

  while(i < end1 && j < end2){
    if(arr[i].lname < arr[j].lname){
        temp[k] = arr[i];
        i += 1;
    }else if(arr[i].lname > arr[j].lname){
        temp[k] = arr[j];
        j += 1;
    }else if(arr[i].fname < arr[j].fname){
        temp[k] = arr[i];
        i += 1;
    }else if(arr[i].fname > arr[j].fname){
        temp[k] = arr[j];
        j += 1;
    }else if(arr[i].dob < arr[j].dob){
        temp[k] = arr[i];
        i += 1;
    }else if(arr[i].dob >= arr[j].dob){
        temp[k] = arr[j];
        j += 1; }

   k += 1;
 }

  while( i < end1){
    temp[k] = arr[i];
    i +=1; k +=1; }

  while(j < end2){
    temp[k] = arr[j];
    j += 1; k += 1; }

  for(int c = 0; c < end2; c += 1)
    arr[c] = temp[c];

  delete [] temp;
}

Would a recursive or iterative approach improve run time? Is there a better way to use pointers? This would be for an array that is not likely to be in any partially sorted order.


texts: Fast way to count the numbers that are divisible by their own sum of digits inside a range

texts:
Inspired by this question on Stack Overflow, I wrote a function that returns the length of a list made of numbers that are divisible by their own sum of digits inside a range:

-- Returns the digits of a positive integer as a list, in reverse order.
-- This is slightly more efficient than in forward order.
digitsRev :: Int -> [Int]
digitsRev i = case i of
    0 -> []
    _ -> lastDigit : digitsRev rest
where (rest, lastDigit) = quotRem i 10

-- Returns the digits of a positive integer as a list.
digits :: Int -> [Int]
digits = reverse . digitsRev

-- Returns the sum of digits of a positive integer
sumDigits :: Int -> Int
sumDigits = sum . digits

-- Returns True if a number is divisible by the sum of it's digits and False
-- otherwise.
isDivisibleSumDigits :: Int -> Bool
isDivisibleSumDigits n = n `mod` sumDigits n == 0

-- Returns a range of positive integers in which every element is divisible by
-- the sum of it's digits. Includes the end of the range.
rangeDivisibleSumDigits :: Int -> Int -> [Int]
rangeDivisibleSumDigits range_start range_end =
    [n | n <- [range_start..range_end], isDivisibleSumDigits n == True]

-- Returns the length of the list returned by rangeDivisibleSumDigits
lengthRangeDivisibleSumDigits :: Int -> Int -> Int
lengthRangeDivisibleSumDigits range_start range_end =
    length $ rangeDivisibleSumDigits range_start range_end

Then I used this function inside a main function, like this:

main = putStrLn $ show $ lengthRangeDivisibleSumDigits 1 10000000

According to the file generated by profiling the program (compiling like this: ghc -prof -fprof-auto -rtsopts Main.hs and executing like this: ./Main +RTS -p) it took 14.36 seconds to execute main. That's slow.

Do you have ideas on a faster way to perform the task carried out by this function?

Edit

Thanks to @bisserlis 's answer below, now the code reads:

-- Returns the digits of a positive integer as a list.
digits :: Int -> [Int]
digits = map digitToInt . show

-- Returns True if a number is divisible by the sum of it's digits and False
-- otherwise
isDivisibleSumDigits :: Int -> Bool
isDivisibleSumDigits n = n `mod` (sum (digits n)) == 0

-- Returns a range of positive integers in which every element is divisible by
-- the sum of it's digits. Includes the end of the range.
rangeDivisibleSumDigits :: Int -> Int -> [Int]
rangeDivisibleSumDigits start end = filter isDivisibleSumDigits [start..end]


texts:
I have an Access database that I'm converting to SQL Server 2008. One of the queries in the database uses the LAST function. The table has a AutoNumber ID so true order is simple.

SELECT tbl_unit.unit,
       LAST(tbl_unit.date)     AS Date,
       LAST(tbl_unit.mileage)  AS Mileage
FROM   tbl_unit
GROUP  BY tbl_unit.unit

SQL 2008 doesn't have any function like that so I wrote the following:

SELECT Unit, [Date], Mileage
FROM (
    SELECT a.id, a.Unit, a.[Date], a.Mileage
    FROM tbl_Unit a
        INNER JOIN (SELECT MAX(id) MaxID, Unit FROM tbl_Unit
                    GROUP BY Unit) b ON a.id = b.maxid
) t1

I'm looking for alternates or better code.
This query returns one record for each "Unit" where the Record is the LAST record entered regardless of the date or mileage values entered. The Table has several thousand entries and this query returns over 100 rows.

The ID is both an auto incrementing number and the primary key. The following data is part of the table.

ID      Unit    DATE        Mileage
217316  171     2006-01-27  59761
216668  171     2005-12-01  57875
216194  171     2006-01-21  59346
217591  1127    2006-01-30  406692
217467  1127    2006-01-27  406339
217466  1127    2006-01-27  406127
217598  2310    2006-01-29  68372
217505  2310    2006-01-28  68187
217504  2310    2006-01-28  67987

The correct output with this set of data is:

Unit    Date        Mileage
171     2006-01-27  59761
1127    2006-01-30  406692
2310    2006-01-29  68372


texts:
I am new to C++ and this is my first program. The objective of this program is to fully complete the sequence called the Collatz conjecture.

  It concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. Otherwise, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.

I am not familiar with the language just yet and would appreciate some (constructive) feedback. The program works as intended, however, I have a feeling that some of my code is not as elegant as it could/should be.

#include <iostream>
#include <ctime>

using namespace std;

bool isValid(int num) {
  if(num <= 0) {
    return false;
  } else {
    return true;
  }
}

bool isEven(int num) {
  if (num % 2 == 0) {
    return true;
  } else {
    return false;
  }
}

void calculate(int num) {
  if (num == 1) {
    cout << endl << "Finished!" << endl;
    return;
  } else if(isEven(num)) {
    num = num / 2;
    cout << num << " ";
    calculate(num);
  } else {
    num = (num * 3) + 1;
    cout << num << " ";
    calculate(num);
  }
}

int main() {

  int input;
  cout << "Please enter an integer greater than zero." << endl;
  cin >> input;

  if(isValid(input)) {
    calculate(input);
  } else {
    cout << "Not a valid input." << endl;
    return 0;
  }

  return 0;
}


texts: Code with many "early returns (exits)" into the functional style

texts:
I have some Scala code that uses Internet to authorize a user. Therefore, it can throw Exceptions like IOException in the method.

The original code was written in Java. So, yes, it uses variables, not val. Also it "returns early" many times if some condition is not satisfied.

The following is an example. (The actual code is, of course, a little more complicated.)

def connect(): (IdInfo, PasswordInfo, ConnectionInfo) = {
  var idInfo: IdInfo = null
  var pwdInfo: PasswordInfo = null
  var connInfo: ConnectionInfo = null

  try {
    idInfo = calcIdInfo()
  } catch {
    case ex: IOException => return null
  }

  try {
    pwdInfo = calcPwdInfo(idInfo)
  } catch {
    case ex: AuthorizationException => return null
  }

  try {
    connInfo = calcConnInfo(idInfo, pwdInfo)
  } catch {
    case ex: IOException => return null
  }

  try {
    verify(idInfo, pwdInfo, connInfo)
  } catch {
    case ex: IOException => return null
    case ex: AuthorizationException => return null
  }

  (idInfo, pwdInfo, connInfo)
}

I'm trying to rewrite the code in the functional style. What I did was

Use vals instead of vars
Remove "return early"
Use None instead of null

I tried to use methods like fold, but at each stage, the types of input or the types of output are different - IdInfo, (IdInfo, PasswordInfo), (IdInfo, PasswordInfo, ConnectionInfo) are all different types - and, what each stage does is also diffrent from each other, so I couldn't use such method.

def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = {
  val idInfoOpt = try {
    Some(calcIdInfo())
  } catch {
    case ex: IOException => None
  }

  idInfoOpt map (idInfo => {
    val pwdInfoOpt = try {
      Some(calcPwdInfo(idInfo))
    } catch {
      case ex: AuthorizationException => None
    }

    pwdInfoOpt map (pwdInfo => {
      val connInfoOpt = try {
        Some(calcConnInfo(idInfo, pwdInfo))
      } catch {
        case ex: IOException => None
      }

      connInfoOpt map (connInfo => {
        try {
          verify(idInfo, pwdInfo, connInfo)
          Some(idInfo, pwdInfo, connInfo)
        } catch {
          case ex: IOException => None
          case ex: AuthorizationException => None
        }
      }) getOrElse None
    }) getOrElse None
  }) getOrElse None
}

The resultant code is more complex than the original one. There are deeper indentations, and the type of each value is not easy to determine (A lot of Options and map and getOrElse).
In the above example, the code has calc***Info() methods, but in reality the code is more complex since it has more statements between each stage, so there seems almost no reason to use the actual resultant code instead of the original one.

I think that the procedural style is better than the functional style in this case. Or not? The more complex the code is, the more chance of errors there will be. Are there better ways to get rid of vars and early returns?

For ease, here are compilable source codes (although it does nothing):
The first one: http://ideone.com/KJS1tn
The second one: http://ideone.com/gulzgs


texts: Is this a good implementation of the Factory Pattern?

texts:
Suppose I have this code:

public interface BaseType {
         public void doSomething();
    }

public class ExtendedTypeA implements BaseType {
//No Instance Variables

    @Override
    public void doSomething() {
        //really do something
    }
}

public class ExtendedTypeB implements BaseType {
//No instance variables

    @Override
    public void doSomething() {
        //really do something, but different
    }
}

public enum BaseTypesValues { EXTENDED_TYPEA, EXTENDED_TYPEB }

public BaseTypeFactoryStandard {

    public BaseType getBaseType(BaseTypesValues baseTypeValue) {
        switch(baseTypes) {
            case BaseTypesValues.EXTENDED_TYPEA:
                return new ExtendedTypeA();
            case BaseTypesValues.EXTENDED_TYPEB:
                return new ExtendedTypeB();
            default:
                throw new NoSuchTypeException();
        }
    }
}

public BaseTypeFactoryMyWay {
    public static final Map<BaseTypesValues, BaseType> factoryMap = new HashMap<//...

    static {
        factoryMap.put(BaseTypesValues.EXTENDED_TYPEA, new ExtendedTypeA());
        factoryMap.put(BaseTypesValues.EXTENDED_TYPEB, new ExtendedTypeB());
    }

    public BaseType getBaseType(BaseTypesValues baseTypeValue) {
        return factoryMap.get(baseTypeValue);
    }

}

Is the last class a good/valid implementation of the factory pattern? Take into consideration the fact that classes that implement the BaseType DO NOT have a state (no non-final instance variables); this means that the objects are lightweight.

Also, can it be implemented in this way (using a map) for the general case (in which classes have state).

Or is this a dumb way in either cases?


texts: Compute the mean, variance and standard deviation of all pairs, triplets and sets of four

texts:
My code sample for finding the mean for the case of pairs is:

import numpy as np
Data =[]
with open('testdata.txt') as my_file:
     for line in my_file:
         Data.append(line)
psize = Data.size*Data.size
p_avg =zeros(psize,float)
for i in range(0,Data.size):
    for j in range(0,Data.size):
        if i != j:
           p_avg[(Data.size*i)+j] = (Data[i]+Data[j])/2.0
        else:
           p_avg[(Data.size*i)+j] = 0.0
print p_avg

Any comments on this and hints for finding the mean and variance for triplets and sets of four efficiently would be most appreciated.


texts: Clojure core.async to handle communication with rabbitmq

texts:
I'm learning how to use rabbitmq in the course of writing a webapp in Clojure that will need to call out to Python for occasional machine learning.  On the Clojure side, the main library is Langohr, which for some reason doesn't make use of core.async.

For my ultimate use case, I expect the Clojure-side to only ever have to handle one message at a time, immediately on arrival.  (The Python side, not shown, will be doing possibly time-consuming machine learning, and will occasionally just send back some weights to the Clojure-side, which will immediately be put to use.)  So I don't expect to need any buffering or anything like that, and haven't put them in this proof-of-concept code.  I also expect there to be only one producer and only one consumer for each channel.

Toy code connecting the two below, but here are some general questions first:

It seems sensible to me as a design choice to stick incoming and outgoing messages on a core-async channel, just because that's the standard choice, but is it over-engineering to do so when I could just use Langohr functions to listen and pass callbacks?
I'm using go loops and non-blocking puts and takes for everything except for the piece that actually waits to see if an external message is waiting on the channel and sends it out for processing; that one is a blocking take in a thread on the theory that everyone says that if something might sit for a while it should be a thread rather than a go-loop (though I confess to not quite understanding why).  Is this wise?

With no further ado, some toy code that demonstrates the design.  (Leaving off the namespace declaration, but, obvs, go, chan, go-loop, and thread plus all the angle bracket/bang functions come from core.async. )

 (defn say [outqueue async-channel message]
  (go
    (>! async-channel {:queue outqueue :content message})))

(defn dispatch-messages! [mq-channel async-channel]
  (go-loop []
    (let [{:keys [queue content]} (<! async-channel)]
      (lb/publish mq-channel "" queue (json/write-str content) {:content-type "application/json"}))
    (recur)))

(defn message-receiver
  [async-channel mq-channel metadata ^bytes payload]
  (let [message (json/read-str (String. payload "UTF-8"))]
    (go
      (>! async-channel message))))

(defn listen! [async-channel mq-channel queue]
  (let [handler (partial message-receiver async-channel)]
    (lc/subscribe mq-channel queue handler {:auto-ack true})))

(defn process-messages! [async-channel processor]
  (thread
    (loop []
      (let [message (<!! async-channel)]
        (processor message))
      (recur))))

(defn setup-async-comm [mq-channel, inqueue, outqueue]
  (let [receiver-async-chan (chan)
        sender-async-chan (chan)
        sender-func (partial say outqueue sender-async-chan)
        receiver-func (partial process-messages! receiver-async-chan)]
    (dispatch-messages! mq-channel sender-async-chan)
    (lq/declare mq-channel inqueue {:exclusive false :auto-delete false})
    (lq/declare mq-channel outqueue {:exclusive false :auto-delete false})
    (listen! receiver-async-chan mq-channel inqueue)
    {:send! sender-func :receive! receiver-func}))

(defn answer [msg]
  (println "Clojure takes your Python and doubles it. "
           (mapv #(* 2 %) msg)))

(defn async-comm [mq-channel]
  (let [{:keys [send! receive!]} (setup-async-comm mq-channel "py2clj" "clj2py")]
    (send! [9, 10, 11])
    (receive! answer)))

For purposes of the toy code, the message queue channel (as opposed to the core async channel) is passed in from the main function in another namespace into the call at the bottom, which sets up and fires a test message.  Obviously, in production code, the setup will be broken out and the messages will come from user interaction etc.  But this demonstrates the basic idea of abstracting away from the messaging details and having, at bottom, a setup function that just returns functions to send and functions to receive, which then can be used by other code at will.