Send and receive data code I need to send and receive data. Here is solution for my original problem. I want to know how safe my finished code is and how I can improve it.

int sslWrite(SSL *ssl, const std::string &data)
{
    return sslWrite(ssl, &data[0], data.size());
}

int sslWrite(SSL *ssl, const void *buf, unsigned num)
{
    const int INT_SIZE = sizeof(int);
    const int numv = INT_SIZE + num;

    std::vector<char> bufv(numv);

    memcpy(&bufv[0], &numv, INT_SIZE);
    if (num != 0) {
        memcpy(&bufv[INT_SIZE], buf, num);
    }

    int n = 0;
    while (n < num) {
        int w = SSL_write(ssl, &bufv[0], numv - n);
        if (w < 0) {
            return 0;
        }
        n += w;
    }

    return n;
}

const int BUF_INIT_SIZE = 0x10000;

std::vector<char> sslRead(SSL *ssl)
{
    const int INT_SIZE = sizeof(int);
    std::vector<char> bufv(BUF_INIT_SIZE);

    int m = SSL_read(ssl, &bufv.at(0), BUF_INIT_SIZE);

    if (m == 0) {
        return std::vector<char>();
    }

    if (m < 0) {
        throw std::runtime_error("m < 0");
    }

    const int n = *reinterpret_cast<int *>(&bufv[0]);
    bufv.resize(n);

    while (m < n) {
        int k = SSL_read(ssl, &bufv.at(m), n - m);
        if (k < 0) {
            throw std::runtime_error("k < 0");
        }
        m += k;
    }

    bufv.resize(m);

    if (m < INT_SIZE) {
        throw std::runtime_error("m < INT_SIZE");
    }

    bufv.erase(bufv.begin(), bufv.begin() + INT_SIZE);
    return bufv;
}

Portability

The code would fail if the sender and receiver platforms disagree on the size of integer.

The code would fail if the sender and receiver platforms disagree on the endianness of integer.
Partial reads

There is a chance that the very first read returns just a couple of bytes. The code still interprets it as a valid integer.
Overall

There is no need to use the same buffer for both size and payload.

m,n,k are patently bad variable names.
Recommendations

Implement a separate send_size() and read_size() routines.


Better way to group elements? this.Items is a list of products. Each product has a category (product.Attributes["category"]).

I want to render a drop down list, where all the products are grouped by category.
This works well, but how could I improve it? Could there be a way to not use a dictionary?

protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
    var groups = new Dictionary<string, List<ListItem>>();

    // sort by category
    foreach (ListItem product in this.Items)
    {
        if (!groups.ContainsKey(category))
        {
            groups.Add(category, new List<ListItem>());
        }
        groups[category].Add(product);
    }

    // render each category
    foreach (var group in groups)
    {
        // <optgroup>
        RenderOptionGroupBeginTag(group.Key, writer);

        // each option
        group.Value.ForEach(p => this.RenderListItem(p, writer));

        // </optgroup>
        RenderOptionGroupEndTag(writer);
    }
}

Since ListItemCollection implements IEnumerable, but not IEnumerable<ListItem>, you have to use Cast before you can use other LINQ methods.

After you do that, you can use GroupBy, as Steve Michael suggested and then work with the result almost exactly like with your groups:

var categoryGroups = this.Items.Cast<ListItem>()
    .GroupBy(i => i.Attributes["category"]);

foreach (var categoryGroup in categoryGroups)
{
    RenderOptionGroupBeginTag(group.Key, writer);

    foreach (var item in group)
    {
        this.RenderListItem(item, writer);
    }

    RenderOptionGroupEndTag(writer);
}

Some other changes I made to the code:

I used foreach instead of ForEach(). ForEach() looks like a LINQ method, but it behaves very differently, since it doesn't do any querying. I think that in cases like this, foreach in the most suitable option.
Changing groups (and group) to categoryGroups means that the code is clearer and so you can get rid of the loop comment.
I also removed the other comments, because I think the code is clear about what it does. If you want to emphasize that RenderOptionGroupBeginTag creates <optgroup>, maybe you should rename it? Probably to something like RenderOptgroupBeginTag.


Checking to see if an area of the screen changes I'm testing some methods for checking if an area of the screen changes, can you see any problems with how I'm doing this, and is there a better way for me to do this?

the _memoryImage2 will not change in the final app, it will be a read only array that I will check the memoryImage against.

namespace ScreenShot_BoundsTest
{
    public partial class Form1 : Form
    {
        Bitmap _memoryImage1;
        Bitmap _memoryImage2;

        Color[,] _first;
        Color[,] _second;

        private string _valueX;

        public Form1()
        {
            InitializeComponent();
        }

        private void Button1Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void GetImage()
        {
            _memoryImage2 = _memoryImage1;
            CaptureScreen();
            pictureBox2.Image = pictureBox1.Image;
            if (_memoryImage1 != null) _first = Bitmap2Imagearray(_memoryImage1);

            pictureBox1.Image = _memoryImage1;
            if (_memoryImage2 != null) _second = Bitmap2Imagearray(_memoryImage2);

            var x = CompareArrays();

            _valueX = x != true ? "false" : "true";
        }

        private bool CompareArrays()
        {
            for (var i = 0; i < _memoryImage1.Width; i++)
            {
                for (var j = 0; j < _memoryImage1.Height; j++)
                {
                    if (_first == null) continue;
                    if (_second != null)
                        if (_first[i,j] != _second[i,j])
                        {
                            return false;
                        }
                }
            }
            return _first != null && _second != null;
        }

        private void CaptureScreen()
        {
            Size s;
            using (var myGraphics = CreateGraphics())
            {
                s = new Size(100, 50);
                _memoryImage1 = new Bitmap(s.Width, s.Height, myGraphics);
            }

            var memoryGraphics = Graphics.FromImage(_memoryImage1);
            memoryGraphics.CopyFromScreen(100, 100, 10, 10, s);
        }

        private static Color[,] Bitmap2Imagearray(Bitmap b)
        {
            var imgArray = new Color[b.Width, b.Height];
            for (var y = 0; y < b.Height; y++)
            {
                for (var x = 0; x < b.Width; x++)
                {
                    imgArray[x, y] = b.GetPixel(x, y);
                }
            }
            return imgArray;
        }

        private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
        {
            GetImage();
            Thread.Sleep(100);
        }

        private void BackgroundWorker1RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            label1.Text = _valueX;
            backgroundWorker1.RunWorkerAsync();
        }
    }
}

Let's start with your algorithm. You're using Bitmap.GetPixel to convert the entire bitmap image pixel by pixel into matrix of colors. I tried this approach several years ago - it was pretty slow on .Net 2.0 and I suppose it is still slow. You should convert image into byte[] and extract color bytes out of this array, it should be hundred times faster. Look into Bitmap.Lockbits method and BitmapData class.

Remaining points are about your code readability. There are several general rules which may improve readability a lot:

If method has some result of execution then return this result instead of assigning it to some field. Also use method parameters to accept arguments instead of class fields.
If variable is not needed outside of one method's scope then do not declare a field for it, use local variable instead.
Be strongly typed. Do not cast anything to string until you really need string.

These simple rules being applied to your code mean:

Rules #1 and #3 mean that your methods should have following signature:

void GetImage() -> bool CompareCurrentImageWithPrevious()
bool CompareArrays() -> static bool CompareImageArrays(Color[,] imageArray1, Color[,] imageArray2)
void CaptureScreen() -> Bitmap CaptureScreen()

This

var x = CompareArrays();
_valueX = x != true ? "false" : "true";

Should be replaced with:

return CompareArrays();

This

for (var i = 0; i < _memoryImage1.Width; i++)
{
    for (var j = 0; j < _memoryImage1.Height; j++)
    {
        if (_first == null) continue;
        if (_second != null)
            if (_first[i,j] != _second[i,j])
            {
                return false;
            }
    }
}
return _first != null && _second != null;

Should be:

 if (_first == null || _second == null) return false;
 if (_memoryImage1.Width != _memoryImage2.Width ||
     _memoryImage1.Height != _memoryImage2.Height)
     return false;
 return _first.SequenceEquals(_second);

Do not assign result of GetImage() to class field, DoWorkEventArgs have Result property which can be used to return value computed by background worker.

private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
    e.Result = GetImage();
    Thread.Sleep(100);
}


Merge Sort Visualisation JS // variables
// arr has elements to be sorted
var arr = []
// temp is to store the intermediate results after merging
var temp = []
// seen is for marking visited i.e. sorted half as green
var seen = []
// length of array
var len = 50

// canvas initialisations
var canvas = document.getElementById("myCanvas")
canvas.width = canvas.height = 1000
var canvaswidth = canvas.width
var canvasheight = canvas.height
var ctx = canvas.getContext("2d")

// random array
for (let i = 0; i < len; i++) {
    arr.push(parseInt(Math.random() * 500))
    temp.push(parseInt(0))
    seen.push(parseInt(0))
}

// initial contents of array to be sorted
// console.log(arr)

// draw the bars
draw = (s, e) => {
    ctx.clearRect(0, 0, 1000, 1000)

    // this loop will make unvisited bars in the upper half as black
    // and visited bars in the upper half as green
    for (let i = 0; i < len; i++) {
        ctx.fillStyle = "#000000"
        ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
        if (seen[i]) {
            ctx.fillStyle = "#00ff00"
            ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
        }
    }

    // the part that was merged is made blue in the lower half
    // also its equivalent in the uper half is made white
    for (let i = s; i <= e; i++) {
        ctx.fillStyle = "#ffffff"
        ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
        ctx.fillStyle = "#0000ff"
        ctx.fillRect(15 * i, 500, 10, arr[i])
        seen[i] = 1
    }

}

// merge
merge = (s, e) => {

    let m = parseInt((s + e) / 2)
    let p1 = s
    let p2 = m + 1
    let n1 = m
    let n2 = e
    let idx = s

    while (p1 <= n1 && p2 <= n2) {
        if (arr[p1] <= arr[p2]) {
            temp[idx++] = arr[p1++]
        }
        else {
            temp[idx++] = arr[p2++]
        }
    }

    while (p1 <= n1) {
        temp[idx++] = arr[p1++]
    }

    while (p2 <= n2) {
        temp[idx++] = arr[p2++]
    }

    idx = s
    while (idx <= e) {
        arr[idx] = temp[idx++]
    }

}

// delay
function mytimeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// mergesort
const mergesort = async (s, e) => {

    if (s < e) {
        let m = parseInt((s + e) / 2)
        await mergesort(s, m)
        await mergesort(m + 1, e)
        await merge(s, e)
        // await console.log(`merged ${s} to ${e} now draw...`)
        await draw(s, e)
        await mytimeout(500)
    }

}

// calls merge sort and at last
// makes all bars become green in upper half
const performer = async () => {
    await mergesort(0, len - 1)
    // await console.log(arr)
    await draw()
}

performer()
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas id="myCanvas">
        Your browser does not support the canvas element.
    </canvas>
    <script src="testmerge.js"></script>
</body>

</html>

Now if i change the len variable in JS to above 50 i.e. 75 or 100 the code behaves oddly..why is it so?
Are there any optimisations possible??

There is nothing wrong with your code when changing the data size to a larger number, except that the draw() method doesn't adjust the width of the columns by the ratio between the canvas size and the number of columns to be drawn.
You'll have to do some math like:
  let offset = Math.round(canvaswidth / len);
  let rectWidth = Math.round(offset * 0.9);

The rounding is because you want integer values (pixels).

ctx.fillStyle = "#000000"
ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
if (seen[i]) {
  ctx.fillStyle = "#00ff00"
  ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
}

This seems inefficient as you draw more and more columns twice through the sorting. A better solution would be something like:
ctx.fillStyle = seen[i] ? "#00ff00" : "#000000";
ctx.fillRect(offset * i, 500 - arr[i], rectWidth, arr[i]);

for (let i = s; i <= e; i++) {
    ctx.fillStyle = "#ffffff"
    ctx.fillRect(15 * i, 500 - arr[i], 10, arr[i])
    ctx.fillStyle = "#0000ff"
    ctx.fillRect(15 * i, 500, 10, arr[i])
    seen[i] = 1
}

You shouldn't "undraw" a column by drawing a white column over it. Instead you could use clearRect with the same dimensions.

let m = parseInt((s + e) / 2)

You can integer divide by two by right shifting by one:
(s + e) >> 1

You should really be careful to end each statement with a ';' (see here)

await merge(s, e)
// await console.log(`merged ${s} to ${e} now draw...`)
await draw(s, e)

You call these with await but they are not defined as async?

Your algorithm seems to works like a merge sort - as I recall it. I think I would encapsulate the parts into a class instead of having the functions in the global scope.

Besides that, I find you graphics very illustrative.


Parsing URL query and appending it at end of the other URL I am trying to grab the URL query of the URL which is in the browser's address bar, then append it at the end of the other URL and echo it to the browser.

So, if I visit my script at:

  http://script.com/script.php?a=x&b=z

and the other URL is:

  http://google.com/?c=v&d=u

then the browser will display:

  http://google.com?a=x&b=z&c=v&d=u

This code is quite slow. How can I improve this?

 function parse_me($from, &$to) {
    // $to = array();
    $from = urldecode($from);
    $from = urldecode($from);

    foreach (explode('&', $from) as $part) {
        $part = explode('=', $part);
        if ($key = array_shift($part)) {
            $to[$key] = implode('', $part);
        }
    }
    // print_r($to);
}

function add_qsrt_to_url($url) {
    $other_query_string = arrayGet($_SERVER, 'QUERY_STRING', '');

    $url_parsed = parse_url($url);
    $new_qs_parsed = array();

    if (isset($url_parsed['query'])) {
        // parse_str($url_parsed['query'], $new_qs_parsed);
        parse_me($url_parsed['query'], $new_qs_parsed);
    }
    $other_qs_parsed = array();

    // parse_str($other_query_string, $other_qs_parsed);
    parse_me($other_query_string, $other_qs_parsed);
    // print_r($other_qs_parsed);

    $final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed);
    // var_dump($final_query_string_array);
    $final_query_string = http_build_query($final_query_string_array);
    $new_url = $url_parsed['scheme'] . '://' . $url_parsed['host'];

    if (isset($url_parsed['path'])) {
        $new_url = $new_url . $url_parsed['path'];
    }

    if ($final_query_string) {
        $new_url = $new_url . '?' . $final_query_string;
    }

    return $new_url;
}

function arrayGet($array, $key, $default = NULL) {
    return isset($array[$key]) ? $array[$key] : $default;
}

I'd write it like this

function concatQueryVars($first, $second) {
    $url = strtok($first, '?');
    $first = parse_url($first, PHP_URL_QUERY);
    $second = parse_url($second, PHP_URL_QUERY);
    return !empty($url) &&
           !empty($first) &&
           !empty($second)
           ? $url . '?' . $first. '&' . $second : false;
}

echo concatQueryVars('http://example.com/?a=b', 'http://example.com/?c=d&e=f');

Result:

  http://example.com/?a=b&c=d&e=f


Optimizing a JavaScript snippet for portability and readability We have an in-house time-tracking application at the office.

We, the employees, can view an overview of our hours on a web page. This web page renders a table, with worked hours per day in table cells, which is styled as a monthly calendar. I wrote a small script which I can copy-paste in my console to get a total of hours worked too much for that month.

A relevant snippet of the HTML.

10
    &nbsp;

        08:33

11
    &nbsp;

        08:25

The JavaScript snippet.

var elementsToParse = $(".link").find("font:not(:empty)");
var totalMinutes = 0;
$.each(elementsToParse, function(index, element) {
    var text = $(element).text();
    var hours = parseInt(text.substr(1, 2));
    var minutes = parseInt(text.substr(3, 2));

    var elementTotal = ((hours * 60) + minutes) - 480;

    totalMinutes += elementTotal;
});

alert('Overtime so far: ' + totalMinutes + ' minutes');

Any thoughts on how to make the script more compact or elegant, while maybe improving readability?

I would make it less compact to improve readability.  Leave it up to your build process (minifier) to make things compact.  Your goal should be to make things understandable.

Use regular expressions

In cases like this, where you have a strict format, I love using regular expressions:

/** @const */
var TIME_FORMAT = /(\d{2}):(\d{2})/;
...
"10:30".match(TIME_FORMAT) // == ["10:30", "10", "30"]

This makes it clear that you expect a date to consist of two digits a colon, and two more digits.  As a bonus, let everyone know it's a constant with JSDoc and common coding conventions.

Define functions

Short modular code is easy to read:

/**
 * Parses a time string and returns the hours and minutes.
 */
function parseTime(text) {
    var match = String(text).match(TIME_FORMAT);

    if (match === null) {
        throw new Error('Time "' + text + '" could not be parsed.');
    }

    return {
        hours:   Number(match[1]),
        minutes: Number(match[2])
    };
}

/**
 * Gets the total minutes of overtime based on time worked and number of working hours
 * in a day.
 */
function calculateOvertime(parsedTime, workingHours) {
    var minutesWorked = parsedTime.hours * 60 + parsedTime.minutes;
    var minutesRequired = workingHours * 60;
    return minutesWorked - minutesRequired;
}

Here, the parseTime parses the time, returning an object, and calculateOvertime calculates the overtime.

Put it all together

Putting it together, your actual function does become more compact and more readable because tangental functions are extracted:

/**
 * Gets the total minutes of overtime from a tracking table.
 *
 * @param selector A CSS2.1 selector, DOM element or jQuery object pointing to the
 * tracking table.
 */
function getOvertimeFromTable(selector, dailyWorkingHours) {
    var totalMinutesOfOvertime = 0;
    var $dailyTimes = $(selector).find("font:not(:empty)");

    $dailyTimes.each(function () {
        var parsedTime = parseTime($(this).text());
        var minutesOfOvertime = calculateOvertime(parsedTime, dailyWorkingHours);

        totalMinutesOfOvertime += minutesOfOvertime;
    });
}

alert('Overtime so far: ' + getOvertimeFromTable('.links', 8) + ' minutes');

Protecting global, enabling compilation

Right now we are exposing a variety of variables and functions on the global object.  This means that anyone could call parseTime or read a similar function.  It also means a minifier can't rename the function to a shorter name.  Wrapping everything in a closure will be the final step for making sure your output code is more compact and your source needn't be:

/**
 * Alerts the number of hours of overtime you have accumulated so far in this pay cycle,
 * assuming a standard 8-hour day.
 */
(function () {
    /* Your code here */
}());


Calculating prime factors in MIPS assembly The goal of this was to be able to enter any number and print out the prime factors of that number. Are there any shorter ways of writing this code? I'm not very familiar with low-level syntax and was hoping somebody could give it a look.

.text
.align 2
.globl main

main:

# compute and display the first prime numbers up to n where n is given. Set n to be 19 but the program should work of any value of n.

li  $v0, 4
la  $a0, prompt
syscall       # call operating sys

li  $v0, 5    # read keyboard into $v0 (number n is the limit)
syscall       # call operating sys
move    $t0,$v0   # store n in $t0

li  $v0, 4    # display message to user
la  $a0, message
syscall

      # call operating sys

li  $v0, 4
la  $a0, space
syscall       # call operating sys

# Load variables into registers
lw  $t1, i  # $t1 = i
lw  $t2, k  # $t2 = k
lw  $t3, p  # $t3 = p
lw  $t5, c  # $t5 = c
lw  $t6, d  # $t6 = d

blt $t0,$t1 L2

li  $v0, 1          # print integer function call 1
move    $a0, $t1        # integer to print
syscall
        # call operating sys

li $v0, 4       # print new line
la $a0, space
syscall                 # call operating sys

    #Outer loop

L2: move $t3, $zero

    # Inner loop

L1: remu $t4, $t1, $t2
bne $t4, $zero, I

move $t3, $t5

I:  add $t2, $t2, $t5   # increment k

blt $t2, $t1 L1

bne $t3, $zero, P

li  $v0, 1          # print integer function call 1
move    $a0, $t1        # integer to print
syscall

li  $v0, 4      # print new line
la  $a0, space
syscall         # call operating sys

P:  add $t1, $t1, $t5   # increment i

move $t2, $t6

bgt  $t1, $t0, E
j L2

E:  li  $v0,    10  # system call code for exit = 10
    syscall     # call operating sys

end:    jr  $ra

.data

prompt:
.asciiz "Please enter the number you wish to find the prime numbers of :  "

message:
.asciiz "The Prime Numbers are : "

space:  .asciiz  "\n    "

#initialization of registers

i:
.word   2

p:
.word   0

k:
.word   2

c:
.word   1

d:
.word   2

Procedures

You appear to be doing everything in main while just branching into single-character procedures.  Consider renaming them to specify their purpose, while separating them from main with proper indentation and such.  I cannot tell what main should be doing by itself.  I can just see that it prompts for user input and operates the two loops with its procedures.
Since prompt is done first, consider defining it above main instead.  The end of the program should just display the result(s).

Structure

The register initializations should be placed above main for better visibility and maintainability.
The loop labels barely stand out, and this really hurts structure.  The loop procedures are all crammed together and L1 looks like just another procedure.  You could at least rename L1 and L2 to Loop1 and Loop2 respectively.
The procedures should be properly indented to help them stay isolated.

P:, for instance, hardly stands out:

P:  add $t1, $t1, $t5   # increment i

move $t2, $t6

bgt  $t1, $t0, E
j L2

All of that could should be indented together and with P: on its own line:

P:
    add $t1, $t1, $t5   # increment i

    move $t2, $t6

    bgt  $t1, $t0, E
    j L2

Comments

The side comments here seem redundant:

# Load variables into registers
lw  $t1, i  # $t1 = i
lw  $t2, k  # $t2 = k
lw  $t3, p  # $t3 = p
lw  $t5, c  # $t5 = c
lw  $t6, d  # $t6 = d

The top comment describes this block clearly enough, whether or not the reader already knows that lw means load word.  The side comments don't add anything else here.
This comment is also redundant:

syscall       # call operating sys

Unless there are some special circumstances to note, such comments do not add anything important.  Readers familiar with MIPS commands will already know what this means.  You may just mention this at the top of the program if you'd like for anyone to know what this means.  Putting it with every call just clutters your code.

This, on the other hand, doesn't state the obvious:

add $t2, $t2, $t5   # increment k

Without the comment, all I can tell is that this is equivalent to $t2 += $t5, and not that it increments k.  These are situations where commenting on separate commands is helpful.

Overall, this is just very hard to follow.  If there are bugs in here, it would be difficult to isolate them.  This, in turn, hurts maintainability.  Comments alone can't help with this, either.  The overall structure must be sound, otherwise fixing problems is just a matter of picking apart separate lines, one-by-one.


Encapsulate results in div tags I would like to turn the following:

this is a $test

into

this is a
$test

currently I have

var regexp = new RegExp('$([^\\s]*)','g'),
    html = '
this is a $test
',
    matched = html.match(regexp)[0]

if (matched){
   html = html.replace(match, '
' + match + '
')
}

which works, but is there a more concise way of doing this?

Sure, use String.replace. As an added bonus, it doesn't fail when there is no match:

'
this is a $test
'.replace(/(\$\w+)/g, '
$1
')


Quick Sort c program I recently learned quick sort through https://www.geeksforgeeks.org/quick-sort/ but found it hard to follow. So, from what I understand wrote the following program.

#include <stdio.h>
void quick_sort(int[],int,int);
int main(){
    int arr[100];
    int n;
    printf("Enter the elements :");
    scanf("%d",&n);
    for(int i = 0 ; i < n ; i++){
        printf("%d:",i+1);
        scanf("%d",&arr[i]);
    }
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    for(int i = 0; i < n; i++){
        printf("%d ",arr[i]);
    }
    printf("\n");

    quick_sort(arr,0,n - 1);

    for(int i = 0; i < n; i++){
        printf("%d ",arr[i]);
    }
    printf("\n");
}

void quick_sort(int arr[],int pivot_, int right_){
    //Base condtion.
    if(pivot_ == right_ )//pivot = left = right == no more check
        return;
    int i ;
    int pivot, left ,right;
    pivot = pivot_;//first element...
    right = right_;//last element...
    left = pivot + 1; // second element.
    int middle;
    while( left <= right ){
        if(arr[left] >= arr[pivot]){
            if(arr[right] <= arr[pivot]){
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
                right --;
                left ++;
            }else{
                right --; // left > pivot but right !< pivot
            }
        }else{
            left ++;// left is not > pivot.
        }
    }
    i = pivot + 1;
    while(arr[i] < arr[pivot]) i++;
    i--; // last smaller value than pivot encountered.
    middle = i; // swappppppp..
    int temp = arr[pivot];
    arr[pivot] = arr[i];
    arr[i] = temp;
    // now left of i is less than pivot and right of is greater than pivot.

    quick_sort(arr,0,middle);
    quick_sort(arr,middle + 1,right_);
}

This is the kind of function that benefits from unit tests.  I wrote a few simple tests in C++ with GoogleTest:

extern "C" {
    void quick_sort(int arr[],int pivot_, int right_);
}

#include <gtest/gtest.h>

#include <algorithm>
#include <iterator>
#include <numeric>

TEST(quick_sort, empty)
{
    int a[1] = {};
    quick_sort(a, 0, 0-1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, one_element)
{
    int a[] = { 0 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, two_same)
{
    int a[] = { 0, 0 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, two_asc)
{
    int a[] = { 0, 1 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, two_desc)
{
    int a[] = { 1, 0 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, three_123)
{
    int a[] = { 1, 2, 3 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, three_231)
{
    int a[] = { 2, 3, 1 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, three_312)
{
    int a[] = { 3, 1, 2 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, four)
{
    int a[] = { 3, 1, 2, 0 };
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

TEST(quick_sort, large)
{
    int a[100];
    std::iota(std::rbegin(a), std::rend(a), -50);
    quick_sort(a, 0, sizeof a / sizeof a[0] - 1);
    EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
}

The first thing this highlighted was the unusual calling convention - right_ is an inclusive bound, but without any guidance, most C coders would expect an exclusive bound.

(In passing, I'll also point out that pivot_ isn't very meaningful to most callers - I think that left would be a better choice of name there.)

The second thing we see (diagnosed by running under Valgrind) is undefined behaviour when we run off the end of the array here:

    while(arr[i] < arr[pivot]) i++;

That needs to be fixed before this code is ready.


Exceeded time limit to solve super pow I tried to solve the Super Pow - LeetCode

  Super Pow

  Medium

  Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.

  Example 1:

Input: a = 2, b = [3]
Output: 8

  Example 2:

Input: a = 2, b = [1,0]
Output: 1024

My solution

import unittest
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s")

class Solution(object):
    def superPow(self, a, b):
        """
        :type a: int
        :type b: List[int]
        :rtype: int
        """
        digit = int("".join(map(str, b)))
        product = a ** digit
        res = product % 1337
        return res

class MyCase(unittest.TestCase):
    def setUp(self):
        self.solution = Solution()

    def test_1(self):
        a = 2
        b = [1, 0]
        answer = 1024
        check = self.solution.superPow(a, b)
        self.assertEqual(answer, check)

unittest.main()

The solution exceeded the time limit.

How could I improve my solution?

Python's built-in pow already has this functionality.

class Solution(object):
    def superPow(self, a, b):
        """
        :type a: int
        :type b: List[int]
        :rtype: int
        """
        digit = int("".join(map(str, b)))
        return pow(a, digit, 1337)

The bottleneck then might be parsing the list of digits into the integer. To remedy that, you can try to use the fact that

\$
\begin{align}
a^{123} ~\text{mod}~ 1337 &= (a^{100}\cdot a^{20}\cdot a^3)~\text{mod}~ 1337& \\
              &= (a^{100}~\text{mod}~ 1337 \cdot a^{20}~\text{mod}~ 1337\cdot a^3  ~\text{mod}~ 1337) ~\text{mod}~ 1337& \\
\end{align}\$

class Solution(object):
    def superPow(self, a, b):
        """
        :type a: int
        :type b: List[int]
        :rtype: int
        """
        ret = 1
        for i, digit in enumerate(reversed(b)):
            ret = (ret * pow(a, digit * 10**i, 1337)) % 1337
        return ret

And here are some timings for inputs of increasing length (from 1 to 10 digits, because your function would take way too long otherwise), with a = 2 and where super_pow_op is your function, super_pow_built_in is my first function and super_pow_expanded is my second function.

And here for 3 to 1000 digits, but only with my two functions:


Kotlin fake properties and their usage I had an idea recently of simplifying some of the code I already have in my Android app that uses Kotlin. I somewhat new to Kotlin, so any opinion would be very appreciated.
Before giving you what idea I had, I will give a base example of what code I have right now:
Lets say that in my app I have a functionality for user to log in and save his credentials for automatic future logging in. Here it is in code.
object MyRepository {
 // Plenty of irrelevant code here...
 fun getUserInfo(): User? {
  // Here we fetch the local data storage and check if any credentials are saved
  return userInfoDao.getUserInformation()
 }

 fun setUserInfo(user: User) {
  // Here we save user credentials to local data storage for future uses
  userInfoDao.saveUserInformation(user)
 }
}

This lead me to think that something like this could be done in a simpler manner, and here is the example:
object MyRepository {
 var userInfo: User?
   get() = userInfoDao.getUserInformation()
   set(value) = userInfoDao.saveUserInformation(value)
 }
}

This of course is much simpler version of what was written above. However, what I am curious is how good of a practice this is in terms of Kotlin standards and general code readability?

Generally speaking, I would not expect a database call to be made simply by referring to a property, such as with val user = MyRepository.userInfo. If a database call is being made, it's better to have a function for it.
I'd even argue that it would even be better to name the function fetchUserInformation than getUserInformation to be clear that this is not just a simple getter.


strstr implementation Please review my strstr implementation. This is an interview question that does not allow the use of strlen(). Is there a better way than using a boolean below?

#include <iostream>
#include <cstring>
char* my_strstr(char * s1, const char *s2)
{
  if ( s1 == NULL || s2 == NULL )
    return NULL;

  size_t s2Size = 0;

  const char *end = s2;
  while (*end++)
    ++s2Size;

  bool match;
  while ( *s1 )
  {
    match = true;
    for ( int i = 0; i < s2Size ; ++i )
    {
      if ( s1[i] != s2[i] )
      {
        match = false;
        break;
      }
    }
    if ( match )
      return s1;

    ++s1;
  }
  return NULL;
}

const char* my_strstr(const char * s1, const char *s2)
{
  return my_strstr(const_cast<char*>(s1),s2);
}

int main()
{
  const char str[]= "This is a strstr test";
  const char search[]= "strstr";

  const char *result = my_strstr(str,search);

  if ( result )
    printf("original: %s\n item: %s\n found: %s\n", str, search, result );
}

By counting the length of s2, you missed the point of this exercise.  Technically, you didn't call strlen(), but you emulated it, which is arguably even worse.  The point was to test your proficiency with pointers, and you failed this interview question.  (Why not count the length?  Because it's possible to do it without incurring the cost of that O(n) operation.  The only time you need to walk along the entire length of s2 is when a match is imminent.)

The strstr(3) documentation probably calls the arguments s1 and s2.  However, I'll borrow a rare piece of wisdom from the PHP documentation and call the arguments haystack and needle.

Don't use variables to control the execution flow.  Prefer to use more active means such as continue, break, and return.  If you have detected a match, what are you waiting for?  Celebrate your success with an immediate return!

Your imports are wrong.  The only library function you call is printf(), so you should #include <cstdio>.

Here's a solution.

#include <cstdio>

char* my_strstr(char *haystack, const char *needle) {
    if (haystack == NULL || needle == NULL) {
        return NULL;
    }

    for ( ; *haystack; haystack++) {
        // Is the needle at this point in the haystack?
        const char *h, *n;
        for (h = haystack, n = needle; *h && *n && (*h == *n); ++h, ++n) {
            // Match is progressing
        }
        if (*n == '\0') {
            // Found match!
            return haystack;
        }
        // Didn't match here.  Try again further along haystack.
    }
    return NULL;
}

const char* my_strstr(const char *haystack, const char *needle) {
    return my_strstr(const_cast<char *>(haystack), needle);
}

int main() {
    const char *str = "This is a strstr test";
    const char *search = "strstr";

    const char *result = my_strstr(str, search);

    if (result)
        printf("original: %s\n item: %s\n found: %s\n", str, search, result);
    return 0;
}


Memory leak using UserControls I seem to have a memory leak on this method but can't figure it out. This method is called every 10sec by a timer which acts like a refresh.

    //Variables

    List<UserControls.userControlAlert> theDataPages = new List<UserControls.userControlAlert>();

    private OleDbConnection mycon;
    private OleDbCommand oleDbCmd;
    private OleDbDataReader dataReader;

    //This method looks for the Alerts in the Data Base and displays the info in a User Control
    private void ShowData()
    {
        try
        {

            mycon.Open();

            string queriesLabels = "SELECT *FROM MP where State = @stateAccepted OR State = @stateRejected";

            oleDbCmd = new OleDbCommand(queriesLabels, mycon);
            oleDbCmd.Parameters.Add("@stateAccepted", OleDbType.VarChar, 10).Value = "Accepted";
            oleDbCmd.Parameters.Add("@stateRejected", OleDbType.VarChar, 10).Value = "Rejected";

            dataReader = oleDbCmd.ExecuteReader();
                while (dataReader.Read())
                {

                    TabPage page = new TabPage("MP "
                                 + (DTL.TabPages.Count + 1).ToString());
                    UserControls.userControlAlert aForm = new UserControls.userControlAlert();
                    aForm.Parent = page;
                    aForm.showReaderRow(dataReader);
                    DTL.TabPages.Add(page);
                    theDataPages.Add(aForm);
                }
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            dataReader.Close();
            mycon.Close();
        }
    }

Timer (10sec):

 private void timer1_Tick(object sender, EventArgs e)
    {
        if (DTL.TabCount > 0)
        {
            theDataPages.Clear();
            DTL.TabPages.Clear();
            ShowData();
        }
        else
        {
            theDataPages.Clear();
            ShowData();
        }
    }

If I leave the application open, every 10sec I see an increment on the memory in that process, after some time windows closes the application.

Your code should make use of using statements instead of the finally statement of the try/catch.

It will allow you to get rid of those ugly private variables in exchange for fun scope specific variables in the using statements. And no matter what the connections are all closed.  I think that you are leaving open the OldDbCommand which might be holding onto the OleDbConnection or at the very least just holding the whole command in memory, but when it runs again it creates an entirely new command.

private OleDbConnection mycon;
private OleDbCommand oleDbCmd;
private OleDbDataReader dataReader;

//This method looks for the Alerts in the Data Base and displays the info in a User Control
private void ShowData()
{
    try
    {

        mycon.Open();

        string queriesLabels = "SELECT *FROM MP where State = @stateAccepted OR State = @stateRejected";

        oleDbCmd = new OleDbCommand(queriesLabels, mycon);
        oleDbCmd.Parameters.Add("@stateAccepted", OleDbType.VarChar, 10).Value = "Accepted";
        oleDbCmd.Parameters.Add("@stateRejected", OleDbType.VarChar, 10).Value = "Rejected";

        dataReader = oleDbCmd.ExecuteReader();
            while (dataReader.Read())
            {

                tabPage page = new tabPage("MP "
                             + (DTL.TabPages.Count + 1).ToString());
                UserControls.userControlAlert aForm = new UserControls.userControlAlert();
                aForm.Parent = page;
                aForm.showReaderRow(dataReader);
                DTL.TabPages.Add(page);
                theDataPages.Add(aForm);
            }
    }
    catch (Exception error)
    {
        MessageBox.Show(error.ToString());
    }
    finally
    {
        dataReader.Close();
        mycon.Close();
    }
}

Here is what I would do:

private void ShowData()
{
    try
    {
        using (OleDbConnection mycon = new OleDbConnection("connectionString")
        {
            mycon.Open();
            string queriesLabels = "SELECT *FROM MP where State = @stateAccepted OR State = @stateRejected";

            using (OleDbCommand oleDbCmd = new OleDbCommand(queriesLabels, mycon))
            using (oleDbDataReader dataReader = oleDbCmd.ExecuteReader())
            {
                oleDbCmd.Parameters.Add("@stateAccepted", OleDbType.VarChar, 10).Value = "Accepted";
                oleDbCmd.Parameters.Add("@stateRejected", OleDbType.VarChar, 10).Value = "Rejected";

                while (dataReader.Read())
                {
                    tabPage page = new tabPage("MP "
                                + (DTL.TabPages.Count + 1).ToString());
                    UserControls.userControlAlert aForm = new UserControls.userControlAlert();
                    aForm.Parent = page;
                    aForm.showReaderRow(dataReader);
                    DTL.TabPages.Add(page);
                    theDataPages.Add(aForm);
                }
            }
        }
    }
    catch (Exception error)
    {
        MessageBox.Show(error.ToString());
    }
}

Your OleDbCommand makes use of the IDisposable interface, so use it and make sure that it doesn't leak.


Find Watson's integer Problem Statement:

Watson gives Sherlock an array \$A_1\$, \$A_2\$ ... \$A_N\$.
He asks him to find an integer \$M\$ between \$P\$ and \$Q\$ (both inclusive), such that, \$\min \{|A_i-M|, 1 \le i \le N\}\$ is maximised. If there are multiple solutions, print the smallest one.

Input Format:

The first line contains \$N\$. The next line contains space separated N integers, and denote the array \$A\$. The third line contains two space separated integers denoting \$P\$ and \$Q\$.

Constraints:

\$1 \le N \le 10^2\$
\$1 \le A_i \le 10^9\$
\$1 \le P \le Q \le 10^9\$

My code:

#include <bits/stdc++.h>
int main()
{   int size,print,dist=INT_MIN,answer,start,end,diff;
    std::vector <int> arr;
    std::cin>>size;
    for(int i=0;i<size;i++)
    {   int templ
        std::cin>>temp;
        arr.push_back(temp);
    }
    std::sort(arr.begin(),arr.end());
    std::cin>>start>>end;
    for(int i=start;i<=end;i++)
    {
        dist=INT_MAX;
        for(int j=0;j<size;j++)
        {
            diff=fabs(i-arr[j]);
            if(diff>dist)
                break;
            dist=std::min(dist,diff);

        }
        if(dist>answer)
        {
            answer=dist;
            print=i;
        }
    }
    std::cout<<print;
    return 0;
}

My code is producing the output that I'm expecting, however it is failing with the hackerrank judge telling me that the time limit has been exceeded.

According to me its running time is O(n(p-q)).
Then it should clear all the test cases in less than 2s (assuming computer can compute 10^9 problems in a second, I remember reading somewhere that that's how most online judges work). At most my program will work on 10^11 problems (n*p-q= 10^2 *10^11).

Do my timing predictions make sense?

How can I improve my code, particularly the performance so that it is able to pass this judge?

General Advise
Online coding challenges may not be timed as far as how long it takes to write them. Take the time to write better code rather than rushing through it. Don't make assumptions about the size of data or the run time that is allowed, on line research may be incorrect about this, because times won't be posted.

Big O Calculation
Does the Big O Calculation include the call to sort() if not, then that can be part of the timing problem.

Use Functions
The program is too complex and needs to be broken into functions. One function gets the array of numbers of input. Another function should do the calculation. The main() function should just control the program.

Declare Variables as Needed
There is a list of variables at the very beginning, this is more C like than C++. If the program is broken into functions this large list of variables at the top is not needed.

Meaningful Variable Names
The variable size is a good name, although the type might be size_t rather than int. The other variable names might be more meaningful if the were declared where they were needed.

Missing Includes
The code is missing some necessary include files:

#include <vector>
#include <iostream>
#include <algorithm>

std::sort()
The call to sort is missing the third argument, which should be the comparison to use in the sort.


SQL LIKE search in Angular filter objects I made this AngularJS 1.x filter, to search using a the same SQL LIKE syntax. Right now only the percentage symbol (%) is supported, the underscore symbol (_) is not.

Under the hood I'm simply building a RegExp from a format string passed as a parameter (ie. the search string), then I'm looping over all the object properties inside an input array (first parameter).

I'm looking for some feedback about performance, and in particular about any possible "edge cases" in which it would perform bad or could possibly break.

Here's the code (ES6/ES2015 syntax):

"use strict";

export default function likeFilter() {
  return (input, format) => {
    if (!(input instanceof Array && "string" === typeof format && format.length)) {
      return input;
    }

    const like = format.indexOf("%") >= 0;
    const startLike = like && format.charAt(0) === "%";
    const endLike = like && format.charAt(format.length - 1) === "%";
    const split = [];

    split.splice(0, 0, ...format.split("%"));

    if (startLike) {
      split.shift();
    }

    if (endLike) {
      split.pop();
    }

    let regexp = split.join(".*");

    if (!startLike) {
      regexp = "^" + regexp;
    }

    if (!endLike) {
      regexp += "$";
    }

    regexp = new RegExp(regexp, "mi");

    return input.filter(el => {
      for (let key in el) {
        if (el.hasOwnProperty(key)) {
          if (regexp.test(el[key])) {
            return true;
          }
        }
      }

      return false;
    });
  }
};

Example usage:

JS code (angular filters module):

"use strict";
import likeFilter from "./like";
filtersModule.filter("like", likeFilter);

HTML code (angular template):

<input type="text" ng-model="data.searchstring" />

I think you inverted startLike with endLike.

const like = format.indexOf("%") >= 0;
const startLike = like && format.charAt(0) === "%";
const endLike = like && format.charAt(format.length - 1) === "%";

When I read startLike I could misunderstand with startWith, that is the popular term used in APIs.

So it's complicated to read the code, as you work with an inverted logic.

I will use startWith(== endLike) and endWith (== startLike), instead.

Another point about naming is:

const split = [];

I think it is meaningless and a very bad choice for an array name.

Consider the case in a future time if you need to use Array.split():

split.split(...);

Not so good in readability.

Consider the code:

const split = [];

split.splice(0, 0, ...format.split("%"));

Not sure why you want to do all this work to just assign an array.

You could just use:

const split = format.split("%");


Keeping track of voting There is HTML that triggers the code below I want to disallow executing the script more than once per 24 hours. I wanted this script to store the last visit time in a table against the user ID in a database, then do a time calculation and back them out until the 24 hour expiry time.

<?php
//Input correct values into this section
$dbhost = '888888';
$dbuser = '888888';
$dbpass = '888888';
$dbname = '888888';
$dbtable = 'redeem';
$dbtable2 = 'playersthatvoted';
//------------------------------------
$input = 'diamond 12';
$player = $_POST['Player'];
$time = time();
if(!isset($_COOKIE['24Hourvote'])){
   //---- This is the connection
   $conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ('Error: ' . mysql_error());
   mysql_select_db($dbname);
   $query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";
   $query2 = "INSERT INTO `".$dbname."`.`".$dbtable2."` (`player`, `time`) VALUES ('".$player."', '".$time."')";
   mysql_query($query1);
   mysql_query($query2);
   $query= 'SELECT `player` FROM `playersthatvoted` ASC LIMIT 0, 10 ';
   $result = mysql_query($query);
   mysql_close($conn);
   echo 'Done! Type /redeem in-game to get your diamonds.';
   $ip=@$REMOTE_ADDR;
   setcookie ("24Hourvote",$ip,time()+86400,'/',true,…
} else {
   echo 'You have already voted today! Come back later...'; }
?>

Note: this is intended to be a Community wiki since it was taken from a deleted answer by yannis; The suggestion to do this was here

mysql_* functions
Stop using them, immediately! They are essentially deprecated, as they refer to MySQL before version 4.1. They are not removed as to not brake backward compatibility, but there's no point in using them.
The drop in replacement is myslqi_* functions, which are based around a newer MySQL driver that works better with MySQL 5.x. You can easily replace most references to myslq_* functions by just adding the extra i.
But a far better solution is PDO, an object oriented database agnostic interface. Since you are starting out in object oriented PHP you'll definitely appreciate the object orient part, and as for the database agnostic part, it means that you can easily switch databases (with minor modifications).
Verbatim copy from another one of my reviews.
Long if, small else
Instead of:
if( condition ) {
    // blah
    // blah
    // blah
    // blah
    // blah
    // blah
    // blah
    // blah
    // blah
} else {
    // blah
}

consider refactoring as:
if( !condition ) {
    // blah
    exit();
}

// blah
// blah
// blah

It's a bit more readable.
Player, you've been played
You get $player from a post variable:
$player = $_POST['Player'];

and then you go and feed it to the database:
$query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";

and, sooner or later, you're dead. Read everything you can about SQL injection on Wikipedia and the manual. Tips:

User input is unsafe, and it includes everything that comes from the environment ($_POST, $_GET, $_SESSION, $_COOKIE, $_SERVER, etc).
Always validate and sanitize user input. Not only when you feed it to a database, always.

For this instance, your best bet would be to go with PDO and prepared statements, that's how the cool kids do it anyway. Additionally, use the Filter extension.
Error suppression operator
$ip=@$REMOTE_ADDR;

First of all, where does $REMOTE_ADDR come from and why do you suppress errors? What exactly are you doing there and what can go wrong.
In any case, forget all about the error suppression operator, it's evil and it must die.


Controlling permissions in a MVP application In a Windows forms payroll application employing MVP pattern (for a small scale client) I'm planing user permission handling as follows (permission based) as basically its implementation should be less complicated and straightforward.

NOTE: System could be simultaneously used by few users (maximum 3) and the database is at the server side.

This is my UserModel. Each user has a list of permissions given for them.

class User
{
    string UserID { get; set; }
    string Name { get; set; }
    string NIC {get;set;}
    string Designation { get; set; }
    string PassWord { get; set; }
    List <string> PermissionList = new List<string>();
    bool status { get; set; }
    DateTime EnteredDate { get; set; }
}

When user login to the system it will keep the current user in memory.

For example in BankAccountDetailEntering view, I can control the permission to access a command button as follows.

 public partial class BankAccountDetailEntering : Form
    {
        bool AccountEditable {get; set;}

        public BankAccountDetailEntering ()
        {
            InitializeComponent();
        }

        private void BankAccountDetailEntering_Load(object sender, EventArgs e)
        {
            cmdEditAccount.enabled = false;

            OnLoadForm (sender, e); // Event fires...

            If (AccountEditable )
            {
                cmdEditAccount.enabled=true;
            }
         }
    }

In this purpose all relevant presenters (like BankAccountDetailPresenter) should aware of UserModel as well in addition to the corresponding business Model it is presenting to the View.

class BankAccountDetailPresenter
{
    BankAccountDetailEntering _View;
    BankAccount _Model;
    User _UserModel;
    DataService _DataService;

    BankAccountDetailPresenter( BankAccountDetailEntering view, BankAccount model, User userModel, DataService dataService )
    {
        _View=view;
        _Model = model;
        _UserModel = userModel;
        _DataService = dataService;
        WireUpEvents();
    }

    private void WireUpEvents()
    {
        _View.OnLoadForm += new EventHandler(_View_OnLoadForm);
    }

    private void _View_OnLoadForm(Object sender, EventArgs e)
    {

        foreach(string s in _UserModel.PermissionList)
        {
            If( s =="CanEditAccount")
            {
                _View.AccountEditable =true;
                return;
            }
        }
    }

    public Show()
    {
        _View.ShowDialog();
    }
}

So I'm handling the user permissions in the presenter iterating through the list. Should this be performed in the Presenter or View? Any other more promising ways to do this?  I'd appreciate it if you could review the code and provide your feedback.

Full disclosure: I haven't done much with windows forms applications, so I may be breaking some otherwise well known winforms programming patterns.

Permissions are better handled by a service, so that you can more easily unit test that layer, plus the permissions logic becomes portable between presenters to promote DRYness of your code (Don't Repeat Yourself).

public class UserPermissionsService
{
    private User _user = null;

    public UserPermissionsService(User user)
    {
        _user = user;
    }

    public bool CanEditAccount { get { return _user.PermissionList.Contains("CanEditAccount"); } }
}

Then to use it:

public partial class BankAccountDetailEntering : Form
{
    UserPermissionsService PermissionsService { get; set; }

    public BankAccountDetailEntering()
    {
        InitializeComponent();
    }

    private void BankAccountDetailEntering_Load(object sender, EventArgs e)
    {
        cmdEditAccount.enabled = PermissionsService.CanEditAccount;
    }
}

The BankAccountDetailEntering form would need to instantiate the user permissions service with the proper user object before the BankAccountDetailEntering_Load method gets called.


Recursive function refactoring help: occurrences of char in string starting at ith char Just getting into functional programming and F# with the most appropriately titled Functional Programming Using F#. I wrote the following function definition for problem 2.4 but I'm thinking there's most likely a more elegant and/or idiomatic solution:

let rec occurrencesFromIth =
    let bool2int x = if x then 1 else 0
    function
    | str:string, i, _ when i >= str.Length -> 0
    | str, i, ch ->
        isIthChar (str,i,ch ) |> bool2int |> (+) (occurrencesFromIth (str,i+1,ch ))

isIthChar is defined as:

let isIthChar ( str:string, i, ch ) = str.[i] = ch

The actual problem description is:

  Declare the F# function occFromIth:

  string * int * char -> int where
  occFromIth(str,i,ch) = the number of occurrences of character ch in positions j in the string str with j >= i.

  Hint: the value should be 0 for i >= size str.

A simple recursive function would be:

let rec occFromIth s i ch =
  if i >= String.length s then 0
  else (if s.[i] = ch then 1 else 0) + occFromIth s (i + 1) ch


Exercise for playing wordgames with user input I'm trying to getting integer keyboard input to call the corresponding method.
invalid input works, keyboard input 3 works, input 2 exits, input 1 calls the wrong method.
I've not yet worked on the subtring and points problem method yet.
Regards, and I appreciate your feedback.
import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;

public class WordGames {

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

    getSelection();
    File file = new File("DICTIONARY.txt");
        if (file.isFile() == true) {
        }
        else {
            System.out.println("File doesn't exist.  Exiting.");
            System.exit(0);
        }

    subStringProblem();
    pointsProblem();

    }

    static String getSelection() {
        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("Welcome to the Word Games program menu.");
        System.out.println("Select from one of the following options.");
        System.out.println("1. Substring problem.");
        System.out.println("2. Points problem.");
        System.out.println("3. Exit.");
        System.out.println("Enter your selections: ");

        if ( ! keyboardInput.hasNextInt()) {

           System.out.println("Invalid option.  Try again.");
           getSelection();

        } else if (keyboardInput.hasNextInt(1)){
            subStringProblem();
            getSelection();

        } else if (keyboardInput.hasNextInt(2)){
            pointsProblem();
            getSelection();

        } else if (keyboardInput.hasNextInt(3)){
        }    System.out.println("Good Bye!");
             System.exit(0);
        return null;
    }

    static String subStringProblem() {
        System.out.println("Substring problem.");
        System.out.println("Enter a Substring:");
    return null;
    }
    static String pointsProblem() {
        System.out.println("Points problem.");

    return null;
    }
}

1. Proper indentation
Please have a look at a style guide. One important topic of style guides is how to "correctly" indent your code:
import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;

public class WordGames {

    public static void main(String[] args) throws FileNotFoundException {
        getSelection();
        File file = new File("DICTIONARY.txt");
        if (file.isFile() == true) {
        }
        else {
            System.out.println("File doesn't exist.  Exiting.");
            System.exit(0);
        }

        subStringProblem();
        pointsProblem();
    }

    static String getSelection() {
        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("Welcome to the Word Games program menu.");
        System.out.println("Select from one of the following options.");
        System.out.println("1. Substring problem.");
        System.out.println("2. Points problem.");
        System.out.println("3. Exit.");
        System.out.println("Enter your selections: ");

        if (!keyboardInput.hasNextInt()) {

           System.out.println("Invalid option.  Try again.");
           getSelection();

        } else if (keyboardInput.hasNextInt(1)) {
            subStringProblem();
            getSelection();

        } else if (keyboardInput.hasNextInt(2)) {
            pointsProblem();
            getSelection();

        } else if (keyboardInput.hasNextInt(3)) {
            System.out.println("Good Bye!");
            System.exit(0);
        }
        return null;
    }

    static String subStringProblem() {
        System.out.println("Substring problem.");
        System.out.println("Enter a Substring:");
        return null;
    }

    static String pointsProblem() {
        System.out.println("Points problem.");
        return null;
    }
}

2. Empty if
if (file.isFile() == true) {
}
else {
    System.out.println("File doesn't exist.  Exiting.");
    System.exit(0);
}

This is not necessary. Just use
if (file.isFile()) {
}
else {
    System.out.println("File doesn't exist.  Exiting.");
    System.exit(0);
}

Without an == the if will automatically check if the value is true.
Even better:
if(!file.isFile()) {
    System.out.println("File doesn't exist.  Exiting.");
    System.exit(0);
}

Empty if-statements should be avoided.
3.Input validation
In getSelection(), your program doesn't crash when the user enters a letter instead of a number. That is good. But your program does crash, when the user enters a number not equal to 1, 2 or 3. This problem can be avoided like this:
int sel = 0;
try{
    sel = keyboardInput.nextInt();
} catch (InputMismatchException e){
    keyboardInput.next();
    System.out.println("Invalid option. Try again.");
    getSelection();
}

if (sel == 1) {
    subStringProblem();
    getSelection();
}
else if (sel == 2) {
    pointsProblem();
    getSelection();
}
else if (sel == 3) {
    System.out.println("Good Bye!");
    System.exit(0);
}
else {
    System.out.println("Invalid option. Try again.");
    getSelection();
}

If you are not familiar with try-catch yet, I suggest reading the documentation.
4.Unnecessary returns
If you don't want to return something in your methods, you can use void as return type instead of String.
For example:
static String subStringProblem() {
    System.out.println("Substring problem.");
    System.out.println("Enter a Substring:");
    return null;
}

should be replaced with
static void subStringProblem() {
    System.out.println("Substring problem.");
    System.out.println("Enter a Substring:");
}

5. Access modifiers
It is considered good practice to always add Access modifiers to your methods. Instead of
static void getSelection() {

it should be
private static void getSelection() {

6. throws
The throws-keyword in the main-method is not necessary.
Code
import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.util.InputMismatchException;

public class WordGames {

    public static void main(String[] args) {
        getSelection();
        File file = new File("DICTIONARY.txt");
        if(!file.isFile()) {
            System.out.println("File doesn't exist. Exiting.");
            System.exit(0);
        }
        subStringProblem();
        pointsProblem();
    }

    private static void getSelection() {
        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("Welcome to the Word Games program menu.");
        System.out.println("Select from one of the following options.");
        System.out.println("1. Substring problem.");
        System.out.println("2. Points problem.");
        System.out.println("3. Exit.");
        System.out.println("Enter your selections: ");

        int sel = 0;
        try{
            sel = keyboardInput.nextInt();
        } catch (InputMismatchException e){
            keyboardInput.next();
            System.out.println("Invalid option. Try again.");
            getSelection();
        }

        if (sel == 1) {
            subStringProblem();
            getSelection();
        }
        else if (sel == 2) {
            pointsProblem();
            getSelection();
        }
        else if (sel == 3) {
            System.out.println("Good Bye!");
            System.exit(0);
        }
        else {
            System.out.println("Invalid option. Try again.");
            getSelection();
        }
    }

    private static void subStringProblem() {
        System.out.println("Substring problem.");
        System.out.println("Enter a Substring:");
    }

    private static void pointsProblem() {
        System.out.println("Points problem.");
    }
}


Read numbers until a prime is entered then print non-primes I'm a beginner at C#. I just want to know what is the C# way to do this by its convention and a better algorithm as well.

using System;
using System.Collections.Generic;

public class Program
{
    static public void Main()
    {
        bool prime = false;
        List<int> non_primes = new List<int>();

        while (prime == false)
        {
            int number = 0;

            Console.Write("#: ");
            number = Convert.ToInt32(Console.ReadLine());

            prime = true;
            for (int i = 2; i <= number / 2; i++)
            {
                if (number % i == 0)
                    prime = false;

                if (prime == false)
                    non_primes.Add(number);
            }
        }

        if (non_primes.Count != 0)
            Console.WriteLine("none-primes: {0}", string.Join(" ", non_primes.ToArray()));
        else
            Console.WriteLine("none-primes: zero");

        Console.WriteLine("press any key to continue");
        Console.ReadKey();
    }
}

I am no C# programmer, so I can't tell you much about the "C# way" to code. But I'll try to help you with your algorithm.

First things first, if I'm not mistaken your for-loop may fill the list of non-primes multiple times for a given number if it has more than one divisor. I'd suggest using the break; statement to exit the loop after you found the first, i.e.

for (int i = 2; i <= number / 2; i++)
        {
            if (number % i == 0){
                prime = false;
            }
            if (prime == false){
                nones.Add(number);
                break;
            }
        }

This will also save time by skipping unnecessary iterations. You should also increment by two instead of one, because all even numbers - and their multiples - will be divisible by two.

Since all numbers are either primes or multiples of primes you could further reduce compute time by skipping over numbers that are not prime. For example, fill an array with prime numbers below 100, then first try to divide the input by numbers in the array.
If it can't be divided by any of them, go back to the for-loop you already wrote and start from the highest prime you used.


Merge all files in a directory with a specific extension I come from Python, with a bit a FORTRAN and Matlab some years ago.
I'm trying to learn C. My first attempt at a program is one to merge all the files in a directory with a specified extension

/*
MERGE: Merges text files. Gives the ability to all files in a
directory with specified extension.
*/
#include <stdio.h>
#include <dirent.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>

/* Function prototypes */
int append_to_file(const char *filename, const char *outfilename); // Appends the contents of filename to outfilename
int scandir(char dirname[], char const *ext, char outfile[]); // Scans a directory for files of a specific extension and merges them
bool has_extension(char const *name, char const *ext);
void usage(); // Prints out usage information (help) to the console
void path_combine(char *dest, const char *path1, const char *path2); // Combines a directory name and filename to a single filepath

int main(int argc, char *argv[])
{
    int nfiles; // Number of files merged

    if (argc == 4)
    {
        nfiles = scandir(argv[1], argv[2], argv[3]);
        printf("Merged %d files\n", nfiles);

        return 0;
    }
    else
    {
        printf("Wrong input, quitting");
        return 1;
    }

}

int append_to_file(const char *filename, const char *outfilename)
{
    FILE *infile, *outfile;
    char ch;
    infile = fopen(filename, "r");
    outfile = fopen(outfilename, "a");

    if (infile == NULL)
    {
        printf("Input file is empty, skipping...\n");
        return 1;
    }

    while ((ch = fgetc(infile)) != EOF)
        fputc(ch, outfile);

    printf("Appended file\n");

    fclose(infile);
    fclose(outfile);

    return 0;

}

int scandir(char dirname[], char const *ext, char outfile[])
/* Scans a directory and merges all files of given extension */
{
    DIR *d = NULL;
    struct dirent *dir = NULL;
    char filepath[strlen(dirname) + 255];
    int i = 0;

    d = opendir(dirname);

    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            if (has_extension(dir->d_name, ext))
            {

                path_combine(filepath, dirname, dir->d_name);
                printf("%s\n", filepath);
                append_to_file(filepath, outfile);
                i++;
            }

        }
        closedir(d);
    }
    return i;
}

bool has_extension(char const *name, char const *ext)
{
    size_t len = strlen(name);
    return len > 4 && strcmp(name+len-4, ext) == 0;
}

void path_combine(char *dest, const char *path1, const char *path2)
{
    const char *last_char = path1;
    int append_sep = 0;
    char sep[] = "/";

#ifdef WIN32
    sep[0] = '\\';
#endif

    /* Find the last character in the first path*/
    while(*last_char != '\0')
        last_char++;

    /* If the last character is not a seperator, we must add it*/
    if (strcmp(last_char, sep) !=0)
    {
        append_sep = 1;
    }

    strcpy(dest, path1);
    if (append_sep)
        strcat(dest, sep);
    strcat(dest, path2);

}

void usage()
{
    printf("\t=================\n");
    printf("\t      MERGE\n");
    printf("\t=================\n");
    printf("Merge two or more text files\n");
    printf("Usage:\n");
    printf("\tCall merge with a directory name and desired extension:\n");
    printf("\tmerge DIRNAME .csv OUTPUTFILE\n\n");

};

I realise there are many things I haven't done here (such as any real error handling), but bear in mind this is a first attempt as part of the learning process.
Rather than being told to 'go look up xx' where xx is a whole area of learning, I'm more interested in specifics if possible.

Are there any obvious code smells?
Is there anything that could obviously be implemented better?
Particularly usage of pointers, which I am still getting to grips with.

scandir

It is not a good name for 2 reasons. First, it exists in a global namespace, and second, it doesn't tell what the function does. Your scandir not only scans the directory, but does an actual merge as well. I would recommend to scan the directory with a standard library's scandir and then merge files (from the list it returns) in a merge function.

A perk benefit of using a stock scandir is an ability to control the merge order. Right now it is unpredictable.

Yet another benefit of separating responsibilities is that if outfile is in the same directory with source files and it has an target extension, the results could be very strange.
has_extension presumes that the extension is always 3 characters. It is not necessarily so. It should calculate an actual length of the ext argument.
append_to_file produces a misleading diagnostics. The fopen may fail for many reasons, but file being empty is not one of them. Display the error message with perror or strerror.
path_combine

Contrary to a popular belief, windows understands a forward slash as a path separator (backslash is an artifact of cmd.exe). There's no need to special case windows.

It is also not necessary to test for last character for being a separator. Just add the separator anyway, it is harmless.

That said, I don't think that you need it at all: just chdir() to the source directory first.


Text replacement with Räubersprache ("Røversprog") I've been toying with Haskell again and implementing a simple text replacement program that replaces all consonants c in a text by coc, i.e., inserting an 'o' in between:
> robber_simple "abcdef"
"abobcocdodefof"

This is rather simple to implement:
robber_simple :: [Char] -> [Char]
robber_simple [] = []
robber_simple (x:xs)
  | x `elem` monophthongs = x:(robber_simple xs)
  | otherwise            = x:'o':x:(robber_simple xs)
  where -- vowels represented by one character, or monograph
        monophthongs :: [Char]
        monophthongs = "aeiouy"

However, in many languages, such as German, we have multigraphs which can act as vowels or consonants, such as "uh" ("uhr") or "sch" ("schokolade").
So I implemented a more complicated program which does a basic lookahead to figure out, whether the, say 's', we currently read is actually part of a "sch".  I'm not happy with it, though :)
import Data.List

robber :: [Char] -> [Char]
robber xs = robber' xs [] where
  robber' :: [Char] -> [Char] -> [Char]
  -- Read first character into backlog
  robber' (x:xs) [] = robber' xs [x]
  -- Nonempty prefix, new input can either form a multigraph prefix or end one.
  robber' (x:xs) (p:ps)
    -- Current character with existing prefix forms a prefix of a multigraph
    | token `elem` (prefixes multigraph_consonant) = robber' xs token
    | token `elem` (prefixes multigraph_vowel)     = robber' xs token
    -- The current token makes it clear that we aren't reading a multigraph
    | otherwise                                    = (robber' [] (p:ps))    ++ (robber' (x:xs) [])
    where token = (p:ps) ++ [x]
  -- No input, consume characters in backlog.
  robber' [] pref
    -- Either this forms a multigraph...
    | pref `elem` multigraph_consonant                   = pref ++ 'o':pref
    | pref `elem` multigraph_vowel                       = pref
    -- ... or not.
    | otherwise                                          = robber_simple pref

-- consonant phoneme made up of multiple characters
multigraph_consonant :: [[Char]]
multigraph_consonant = ["sch", "ch", "sc"]

-- same for vowels
multigraph_vowel :: [[Char]]
multigraph_vowel = ["ei", "uh"]

prefixes :: [[a]] -> [[a]]
prefixes xs = concat $ map prefix xs

prefix :: [a] -> [[a]]
prefix = inits

The parsing/tokenizing strategy I use, is to read characters and store them into the backlog until a character (or end of input) comes that determines that the current backlog can be treated as one unit.  That is, it either is a complete monograph (e.g., "sch") or definitely not a prefix of a monograph ("c").
In that case, I replace the backlog x with either x++'o':x or leave it, depending on whether it is a consonant or a vowel.
Finally, I carry on parsing the rest of the string.
Any suggestions welcome!

I probably would reach directly for Parsec or another parsing library writing this from scratch, but I think even with a more direct recursive solution you've drastically overcomplicated this!
Separate your problem into constituent pieces which you find easier to handle on their own terms. In this case, I would start by writing a function phoneme :: [Multigraph] -> String -> (Phoneme, String) to consume only a single n-graph off of a given word.
import Data.List (isPrefixOf, stripPrefix)

type Phoneme = String
type Multigraph = Phoneme

phoneme :: [Multigraph] -> String -> Maybe (Phoneme, String)
phoneme multigraphs word@(letter:rest) = -- The use of @ is an example of an 'as-pattern'
    case filter (`isPrefixOf` word) multigraphs of
      (multigraph:_) -> Just (multigraph, fromJust $ stripPrefix multigraph word)
      []             -> Just ([letter], rest)
phoneme _multigraphs [] = Nothing        -- Prefixing an arg with _ says to the compiler
                                         -- that you meant not to use it in the definition
                                         -- i.e. you won't get a warning when compiling
                                         -- with -Wall (specifically --Wunused-matches)

This version achieves multigraph detection by testing the passed multigraphs against the remaining portion of the string, \$O(m)\$ in the number of multigraphs. Your original version tests every multigraph against every prefix of the string, making it \$O(mn)\$.
Now the next obvious step is to use this function in breaking an entire string into its constituent phonemes.
import Data.List (unfoldr)

phonemes :: [Multigraph] -> String -> [Phoneme]
phonemes multigraphs = unfoldr (phoneme multigraphs)

Sometimes you either know about a common Haskell concept or you don't. In this case, if you're unfamiliar, unfoldr :: (b -> Maybe (a, b)) -> b -> [a] repeatedly applies a function that returns a desired output and some state to itself, collecting the output into a list and terminating once the function reaches the “end” and has returned Nothing.
Now before anything else we have to be able to robber an individual phoneme.
robberPhoneme :: [Multigraph] -> [Multigraph] -> Phoneme -> String
robberPhoneme _mconsonants mvowels p
  | p `elem` mvowels = p
  | p `elem` vowels  = p
  | otherwise        = p ++ "o" ++ p
  where vowels = map pure "aeiouy"

You could obviously leave out the consonants argument, but I think it's helpful to remind callers not to just pass all of the multigraphs they have on hand, vowels being treated differently from consonants.
And now we're ready to tie it together.
robber :: [Multigraph] -> [Multigraph] -> String -> String
robber mconsonants mvowels = concatMap (robberPhoneme mconsonants mvowels)
                           . phonemes (mconsonants ++ mvowels)

And there you go! Much less bookkeeping, parsed strictly left to right, and by relying entirely on standard functions for all of the recursion anyone reading my code (including me, later) can quickly understand how control flows through the program without having to mentally grapple with primitive recursion.
This doesn't sit wholly perfectly with me (I'd probably create a datatype to represent all the different kinds of phonemes in a language and pass that around instead, I didn't feel good just throwing the monophthongs in there but it was expedient, couple other nits) but it's enough of a solution that I'd ship it.


Finding the largest word in the given String If there are two or more words that are the same length, return the first word from the string with that length. I am a beginner. Could anyone highlight good and bad parts of the following program.Also, had it been last word from the string with that length, would it give different result in Chrome and Firefox because of it being unstable in Chrome ?

function LongestWord(sen) {

var arr2=[];
var arr =sen.split(" ");
var arr1=arr;
arr.sort(function (a,b){

if(a.length<b.length){
    return -1;
}
else if(a.length===b.length){
    return 0;
}
else return 1;
});

var len =arr[arr.length-1].length;
for(var i =0 ; i<arr1.length;i++)
  {
     if(arr1[i].length===len)
    {
    arr2.push(arr[i]);
    break;
     }

    }
  return(arr2.pop());

}

Before I give you my answer, a bit of critique regarding your code:

Naming convention in JS use camelCase.
What is sen? By itself, it doesn't tell me what it is. Name your variables meaningfully, one that tells you what it does the first time you read it.
Be consistent with whitespace. Usually, there should be spaces before and after operators (ie. a = b, foo = [] etc.)
Indention. Always have proper indention.
By sorting, you already fail the criteria of "first longest word prevails" because of sort instability.

You can simply use reduce. Carry around the longest word through the array, replacing it when you find something longer.

function findLongestWord(sentence) {
  return sentence.split(' ').reduce(function(longestWord, word){
    return word.length > longestWord.length ? word : longestWord;
  });
}

var str = "The quick brown fox jumps over the lazy dog";

document.write(findLongestWord(str));


Jquery Max character with character count for input and textarea I have got this working ok, I just think that it can be improved and reduce the amount of code. If anybody could help that would be brilliant.

// Max Length Input
$('input[maxlength]').each(function() {
    var maxCharLength = $(this).attr("maxlength");

    if(maxCharLength < 0 || maxCharLength > 5000){
    } else {
        var charLength = $(this).val().length;
        $(this).after(" " + charLength + " of " + maxCharLength + " characters used");
        $(this).keyup(function() {
            var charLength = $(this).val().length;
            $(this).next("span").html(charLength + ' of ' + maxCharLength + ' characters used');

            if(charLength == maxCharLength ) {
                $(this).next("span").html(' Maximum of ' + maxCharLength + ' characters used.');
                $(this).next("span").addClass("red");
            } else { $(this).next("span").removeClass("red"); }
        });
    }
});

// Max Length textarea
$('textarea[maxlength]').each(function() {
    var maxCharLength = $(this).attr("maxlength");

    if(maxCharLength < 0 || maxCharLength > 5000){
    } else {
        var charLength = $(this).val().length;
        $(this).after(" " + charLength + " of " + maxCharLength + " characters used");

            $('textarea[maxlength]').keyup(function(){

                var limit = parseInt($(this).attr('maxlength'));
                var text = $(this).val();
                var chars = text.length;

                $(this).next("span").html(chars + ' of ' + limit + ' characters used');

                if(chars > limit){
                    var new_text = text.substr(0, limit);
                    $(this).val(new_text);

                    $(this).next("span").html(' Maximum of ' + limit + ' characters used.');
                    $(this).next("span").addClass("red");
                } else { $(this).find("span").removeClass("red"); }
            });
    }
});

There are a few things I would suggest:
1. Replace you numbers with constants and revert the condition to get rid of 'else':

var minTextLength = 0;
var maxTextLength = 5000;
if (maxCharLength >= minTextLength || maxCharLength <= maxTextLength){
      //Your code...
    }

2. Move the block of code:

$(this).next("span").html('<strong> Maximum of ' + maxCharLength + ' characters used.</strong>');
            $(this).next("span").addClass("red");
        } else { $(this).next("span").removeClass("red"); }

To a separate function.

And there are a couple of things that confuse me:
1. In 'Max Length textarea' you have:

$('textarea[maxlength]').keyup()

Is it correct? Becasue it means that you'll add a lot of handlers to all your textarea[maxlength].

2
. In your 'Max Length Input' you have:

if(charLength == maxCharLength )

Maybe it could be replaced with:

if(charLength > maxCharLength )

Depending on the answers to these questions, maybe it'll be possible to move the keyup  handler to a separate function. And maybe even the whole code from both 'Max Length textarea' and 'Max Length Input'.


Optimizing gradient function in C++ I'm computing the gradient of an image manually (without using built in functions) and I want to make it faster but keeping the same performance.
I'm very open to any suggestions.. currently learning c++ optimzation and STL lib in recent c++.

Here is my code, my main concern is gradiantAndDirection function that I need to optimize. The TimerAvrg struct is how I compute the running time of that function:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
#include <chrono>

struct   TimerAvrg
{
    std::vector<double> times;
    size_t curr=0,n;
    std::chrono::high_resolution_clock::time_point begin,end;
    TimerAvrg(int _n=30)
    {
        n=_n;
        times.reserve(n);
    }

    inline void start()
    {
        begin= std::chrono::high_resolution_clock::now();
    }

    inline void stop()
    {
        end= std::chrono::high_resolution_clock::now();
        double duration=double(std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count())*1e-6;
        if ( times.size()<n)
            times.push_back(duration);
        else{
            times[curr]=duration;
            curr++;
            if (curr>=times.size()) curr=0;}
    }

    double getAvrg()
    {
        double sum=0;
        for(auto t:times)
            sum+=t;
        return sum/double(times.size());
    }
};

//Those variables will be in a class with gradiantAndDirection
uchar *dirImg;
int gradThresh = 20;

void gradiantAndDirection(cv::Mat& GxGy, const cv::Mat &grey)
{
    cv::Mat smoothImage;
    GaussianBlur(grey, smoothImage, cv::Size(5, 5), 1.0);
    uchar *smoothImg = smoothImage.data;

    GxGy.create( grey.size(),CV_16SC1);
    short* gradImg = (short*)GxGy.data;

    dirImg = new unsigned char[grey.cols*grey.rows];

    //Initialization of row = 0, row = height-1, column=0, column=width-1
    for (int j = 0; j<grey.cols; j++)
        gradImg[j] = gradImg[(grey.rows - 1)*grey.cols + j] = gradThresh - 1;

    for (int i = 1; i<grey.rows - 1; i++)
        gradImg[i*grey.cols] = gradImg[(i + 1)*grey.cols - 1] = gradThresh - 1;

    for (int i = 1; i<grey.rows - 1; i++) {
        for (int j = 1; j<grey.cols - 1; j++) {
            int com1 = smoothImg[(i + 1)*grey.cols + j + 1] - smoothImg[(i - 1)*grey.cols + j - 1];
            int com2 = smoothImg[(i - 1)*grey.cols + j + 1] - smoothImg[(i + 1)*grey.cols + j - 1];
            int gx;
            int gy;
            gx = abs(com1 + com2 +  (smoothImg[i*grey.cols + j + 1] - smoothImg[i*grey.cols + j - 1]));
            gy = abs(com1 - com2 +  (smoothImg[(i + 1)*grey.cols + j] - smoothImg[(i - 1)*grey.cols + j]));
            int sum;
            if(0)
                sum = gx + gy;
            else
                sum = (int)sqrt((double)gx*gx + gy*gy);

            int index = i*grey.cols + j;
            gradImg[index] = sum;
            if (sum >= gradThresh) {
                if (gx >= gy) dirImg[index] = 1;//1 vertical
                else      dirImg[index] = 2;//2 Horizontal
            }
        }
    }
}

int main( int argc, char** argv )
{
    cv::Mat image;
    image = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);

    float sum=0;
    cv::Mat GxGy;
    for(int alpha = 0; alpha <20 ; alpha++)
    {
        TimerAvrg Fps;
        Fps.start();
        gradiantAndDirection(GxGy, image);
        Fps.stop();
        sum = sum + Fps.getAvrg()*1000;
    }

    std::cout << "\rTime detection=" << sum/19 << " milliseconds" << std::endl;
    cv::resize(GxGy,GxGy,cv::Size(image.cols/2,image.rows/2));
    cv::Mat result8UC1;
    cv::convertScaleAbs(GxGy, result8UC1);
    cv::imshow( "Display window",result8UC1);
    cv::waitKey(0);

    return 0;
}

I compile my code under Ubuntu 16.04 gcc 8.1.0

g++ -std=c++1z -fomit-frame-pointer -O3 -ffast-math -mmmx -msse -msse2 -msse3 -DNDEBUG -Wall improve_code.cpp -o improve_code -fopenmp `pkg-config --cflags --libs opencv`

Include what you use

We use std::abs and std::vector but the code lacks the necessary includes:

#include <cmath>
#include <vector>

Perform a single task well

Why do we perform the Gaussian blur?  What if the input is already sufficiently blurred, or if it needs a bigger kernel?

If we make the caller responsible for this preparation step, we give it more control, and we can focus on a single responsibility in this function.

Fix the memory leak

This allocation is never released:

dirImg = new unsigned char[grey.cols*grey.rows];

In fact, this entire (global) array seems only to be assigned to, and never used, so we could remove it entirely.

Simplified indexing

It might be easier to use index throughout, and add rows or columns directly with ±grey.cols and ±1:

      const int index = i*grey.cols + j;
      int com1 = smoothImg[index + grey.cols + 1] - smoothImg[index - grey.cols - 1];
      int com2 = smoothImg[index - grey.cols + 1] - smoothImg[index + grey.cols - 1];
      int gx = std::abs(com1 + com2
                        + smoothImg[index + 1] - smoothImg[index + 1]);
      int gy = std::abs(com1 - com2
                        + smoothImg[index + grey.cols] - smoothImg[index - grey.cols]);

Use the standard library

There's no need to (badly) re-write std::hypot() for the computation of sum (also, drop the if (0) - that's always false).

      const int sum = std::hypot(gx, gy);

Saturate, don't overflow

The std::hypot() value could conceivably be larger than the range of int, or of gradImg[] (depending on the relative sizes of the target's integer types) - in such cases, we should std::clamp the value to the possible range, rather than suffering Undefined Behaviour.

Spelling

Prefer standard spelling: gradient, not gradiant.


Detecting two keys pressed in quick succession My computer has been having this issue where when I press a key, two key presses get registered. The goal of this program is to detect the time delta between the two keys so that I can set an effective debounce threshold. I also thought that it would be a good idea to try out Rust, so here it is:

use std::{mem, ptr, env, process, io};
use std::io::Read;
use std::io::Write;
use std::fs::File;
use std::collections::HashMap;

const EV_SYN: u16 = 0x00;
const EV_KEY: u16 = 0x01;

#[repr(C)]
struct LinuxTimeval {
    tv_sec: isize,
    tv_usec: isize,
}

impl LinuxTimeval {
    fn to_microseconds(&self) -> u64 {
        self.tv_sec as u64 * 1000000u64 + self.tv_usec as u64
    }
}

#[repr(C)]
struct LinuxInputEvent {
    time: LinuxTimeval,
    type_: u16,
    code: u16,
    value: i32,
}

fn read_struct_from_file<T: Sized>(file: &mut File) -> T {
    let mut buf = vec![0u8; mem::size_of::<T>()];
    match file.read(&mut buf) {
        Ok(sz) => assert!(sz == buf.len()),
        Err(err) => panic!("Unable to read from device: {}", err),
    }
    let ptr = &buf as &[u8] as *const [u8] as *const T;
    unsafe { ptr::read(ptr) }
}

fn read_events_from_file(file: &mut File) -> Vec<LinuxInputEvent> {
    let mut vec = Vec::new();
    loop {
        let event: LinuxInputEvent = read_struct_from_file(file);
        if event.type_ == EV_SYN {
            if vec.len() > 0 {
                break;
            } else {
                continue;
            }
        } else {
            vec.push(event);
        }
    }
    vec
}

fn process_key_event(event: &LinuxInputEvent,
                     last_occurence_per_key: &mut HashMap<u16, u64>,
                     threshold: u64) {
    let key = event.code;
    let micros = event.time.to_microseconds();
    match last_occurence_per_key.get(&key) {
        None => (),
        Some(last_micros) => {
            let delta = micros - last_micros;
            if delta < threshold {
                println!("Key code {:3}: event delta: {} us",
                         key, delta);
            }
        }
    }
    last_occurence_per_key.insert(key, micros);
}

fn print_usage_and_exit(program_name: &str) {
    writeln!(&mut io::stderr(), "Usage: {} <microseconds-delta>",
             program_name).unwrap();
    process::exit(1);
}

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() != 2 { print_usage_and_exit(&args[0]); }
    let threshold: u64 = args[1].parse().unwrap_or(0);
    if threshold == 0 { print_usage_and_exit(&args[0]); }
    let mut file;
    match File::open("/dev/input/by-path/platform-i8042-serio-0-event-kbd") {
        Ok(f) => { file = f },
        Err(err) => panic!("Unable to open file: {}", err),
    }
    let mut last_occurence_per_key = HashMap::new();
    loop {
        match read_events_from_file(&mut file)
                .iter().find(|&event| event.type_ == EV_KEY && event.value == 1) {
            None => continue,
            Some(event) => process_key_event(event,
                                             &mut last_occurence_per_key,
                                             threshold),
        }
    }
}

Please let me know if any improvements can be made.

Highlights

Using the libc crate for C data types
No heap allocation of read struct
No (new) panics — better error handling
Event iterator instead of vectors
New types and traits to collect related functionality

Beware - I still haven't gotten this to actually read any events on my machine, but it does compile. That should be good enough, right? ^_^

libc crate

The libc crate should always be used when interoperating with C code. This crate is guaranteed to have the correct sizes for platform-specific types.

Additionally, it already has a definition for timeval, so that was nice.

Less heap allocation

I used mem::uninitialized to create an on-stack version of the struct with no values. I then got a reference to that area as bytes and read directly to that.

Note that I marked that function as unsafe - depending on what T resolves to, it could produce very bad results.

Error handling

Everywhere that had a panic! or assert! was changed into a Result. This allows the caller to decide how to deal with the error. The most awkward place left is in the call to read_c_struct, as it just stops the iterator on failure. Instead, it could return the Result directly and allow its caller to see the failure.

Embrace the Iterator

Rust loves iterators. This seemed like a perfect case for it - you have a stream of events and you want to do something based on them. I reworked your method into an Iterator implementation. This allows the caller to decide how much memory to allocate; in the final code, I believe it's very small. It also allows using the filter method and other iterator adaptors.

New types and traits

Iterators need a type to exist, and I also felt that your hashmap and threshold needed to live together. I also moved the read-specific methods into a new trait that is then implemented for all types that implement Read.

Complete code

There's a few comments scattered about for smaller things, but here it is:

extern crate libc;

use std::{mem, env, process, io, slice};
use std::io::{Read, Write};
use std::fs::File;
use std::collections::HashMap;

// Some helper methods for reading things
trait ReadExtensions : Read {
    /// Completely fill the supplied buffer
    fn read_complete(&mut self, buf: &mut [u8]) -> io::Result<()> {
        let mut total_read = 0;
        while total_read < buf.len() {
            match self.read(&mut buf[total_read..]) {
                // Unable to read anything
                Ok(0) => return Err(io::Error::new(io::ErrorKind::Other, "Unable to read")),
                // Read some amount
                Ok(n) => total_read += n,
                // Might have been interrupted by something
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {},
                Err(e) => return Err(From::from(e))
            }
        }
        Ok(())
    }

    /// Directly read a C struct.
    ///
    /// Unsafe because only the concrete type of `T` can determine if
    /// the result is safe. Should only be used to read structs
    /// composed of primitive types without any pointers.
    unsafe fn read_c_struct<T>(&mut self) -> io::Result<T> {
        // avoid allocating on the heap
        let mut val = mem::uninitialized();
        let ptr = &mut val as *mut T as *mut u8;
        let mut buf = slice::from_raw_parts_mut(ptr, mem::size_of::<T>());

        try!(self.read_complete(buf));
        Ok(val)
    }
}

impl<R> ReadExtensions for R where R: io::Read {}

const EV_KEY: u16 = 0x01;

fn to_microseconds(tv: libc::timeval) -> u64 {
    // u64 suffix unneeded, adding _ for readability
    tv.tv_sec as u64 * 1_000_000 + tv.tv_usec as u64
}

// Using libc
#[derive(Copy,Clone)]
#[repr(C)]
struct LinuxInputEvent {
    time: libc::timeval,
    type_: libc::uint16_t,
    code: libc::uint16_t,
    value: libc::int32_t,
}

/// An iterator of Linux events
struct InputSource {
    file: File,
}

impl InputSource {
    fn new(path: &str) -> io::Result<InputSource> {
        let f = try!(File::open(path));
        Ok(InputSource { file: f })
    }
}

impl Iterator for InputSource {
    type Item = LinuxInputEvent;

    fn next(&mut self) -> Option<LinuxInputEvent> {
        unsafe { self.file.read_c_struct() }.ok()
    }
}

/// Tracks when multiple presses of the same key occurs and calls the
/// callback when duplicate events are triggered within a threshold.
struct KeyEventSink {
    last_occurences: HashMap<u16, u64>,
    threshold: u64,
}

impl KeyEventSink {
    fn new(threshold: u64) -> KeyEventSink {
        KeyEventSink {
            last_occurences: HashMap::new(),
            threshold: threshold,
        }
    }

    // Take a closure so we don't have to worry about user interface here
    fn process_event<F>(&mut self, event: LinuxInputEvent, f: F)
        where F: FnOnce(u16, u64)
    {
        let key = event.code;
        let micros = to_microseconds(event.time);

        // if-let for one useful match arm
        if let Some(last_micros) = self.last_occurences.get(&key) {
            let delta = micros - last_micros;
            if delta < self.threshold {
                f(key, delta)
            }
        }
        self.last_occurences.insert(key, micros);
    }
}

fn print_usage_and_exit(program_name: &str) {
    writeln!(&mut io::stderr(), "Usage: {} <microseconds-delta>", program_name).unwrap();
    process::exit(1);
}

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() != 2 { print_usage_and_exit(&args[0]); }
    let threshold: u64 = args[1].parse().unwrap_or(0);
    if threshold == 0 { print_usage_and_exit(&args[0]); }

    // just use value of match
    let input = match InputSource::new("/dev/input/event2") {
        Ok(f) => f,
        Err(err) => panic!("Unable to open file: {}", err),
    };

    let mut sink = KeyEventSink::new(threshold);

    let key_events = input.filter(|&event| event.type_ == EV_KEY && event.value == 1);
    for key_event in key_events {
        sink.process_event(key_event, |key, delta| {
            println!("Key code {:3}: event delta: {} μs", key, delta);
        })
    }
}

Followups

  is there any particular reason you added the Copy and Clone traits to LinuxInputEvent?

Basically, LinuxInputEvent is a simple type comprised of Copyable values, and it's also fairly small in the grand scheme of things. Making it Copy simply improves the ergonomics of using it. If you implement Copy, you need to implement Clone.

  Seeing as the function is used at most once, FnOnce would also be better than Fn

Absolutely correct - I updated to use this.

I also updated the read_complete method a bit based on feedback from this Stack Overflow question.