Create URL using data obtained from filters Unfortunately there is no URL where you can see the code working. I hope you all can figure out what the code does simply by looking at it.

GitHub

var FilteredNav = {
      wrapper: $(".dept-filters")
      , init: function() {
        FilteredNav.changeUrl();
        FilteredNav.createUrl();
      }
      , createUrl: function() {
        var url = null
          , urlItems = null;

        $.each(FilteredNav.wrapper, function() {
          // clean it all up before creating the url
          urlItems = [];

          var self = $(this)
            , checkedInput = self.find('input[type="checkbox"]:checked')
            , submitButton = self.find('.refinar-btn');

          // select only the relevant items
          $.each(checkedInput, function(i, item) {
            urlItems.push($(item).attr("rel"));
          });

          if (checkedInput.length) {
            // create the url
            url = document.location.protocol
            + "//"
            + document.location.host
            + "/"
            + self.attr("data-dept")
            + "/?"
            + urlItems.join("&");

            // add new url as href of 'refine' button
            submitButton.removeClass("hide").attr("href", url);
          } else {
            submitButton.addClass("hide");
          }
        });
      }
      , changeUrl: function() {
        FilteredNav.wrapper.find('input[type="checkbox"]').bind("change", FilteredNav.createUrl);
      }
    };

    // uncomment this line when testing on the console
    // FilteredNav.init();

    // comment this line when testing on the console
    $(document).ready(function() {
      FilteredNav.init();
    });

Your code looks pretty good! Here are a few comments:

Prefer to use .data('dept') over .attr('data-dept').
Prefer to use .on('change', ...) over .bind('change', ...).
rel is an invalid attribute on input elements. You can use data-rel instead.
It's a inefficient to create URLs for every FilteredNav.wrapper whenever any checkbox is changed, since it should only affect one of them. Consider having changeUrl only affect the enclosing .dept-filters. (This is as simple as just removing the .each() and setting self = $(this).closest(FilteredNav.wrapper);.) Then in init, use $.each(FilteredNav.wrapper, changeUrl);.
This might look like:

var FilteredNav = {
  wrapper: $(".dept-filters")
  , init: function() {
    FilteredNav.changeUrl();
    $.each(FilteredNav.wrapper, FilteredNav.createUrl);
  }
  , createUrl: function() {
    var urlItems = [];

    var self = $(this).closest(FilteredNav.wrapper)
    , checkedInput = self.find('input[type="checkbox"]:checked')
    , submitButton = self.find('.refinar-btn');

    // select only the relevant items
    $.each(checkedInput, function(i, item) {
      urlItems.push($(item).data("rel"));
    });

    if (checkedInput.length) {
      // create the url
      var url = document.location.protocol
      + "//"
      + document.location.host
      + "/"
      + self.data("dept")
      + "/?"
      + urlItems.join("&");

      // add new url as href of 'refine' button
      submitButton.removeClass("hide").attr("href", url);
    } else {
      submitButton.addClass("hide");
    }

    // Just to demonstrate
    submitButton.siblings('output').text(submitButton.attr('href'));
  }
  , changeUrl: function() {
    FilteredNav.wrapper.find('input[type="checkbox"]').on("change", FilteredNav.createUrl);
  }
};

// uncomment this line when testing on the console
// FilteredNav.init();

// comment this line when testing on the console
$(document).ready(function() {
  FilteredNav.init();

  // don't leave my Stack Snippet! :)
  $('a').on('click', function() { return false; });
});
a {
  text-decoration: none;
  color: inherit;
}

.refinar-btn {
  border: 1px solid black;
  display: inline-block;
  padding: 1ex;
}

.refinar-btn.hide {
  background: #eee;
  color: #777;
}

        <input type="checkbox" data-rel="filter1" />
        Filter 1

        <input type="checkbox" data-rel="filter2" />
        Filter 2

        <input type="checkbox" data-rel="filter3" />
        Filter 3

    Refine
    <output></output>

        <input type="checkbox" data-rel="filterA" />
        Filter A

        <input type="checkbox" data-rel="filterB" />
        Filter B

        <input type="checkbox" data-rel="filterC" />
        Filter C

    Refine
    <output></output>

You can take this even further and only generate the URL when the submit button is actually clicked. You would then have to add or remove the .hide class in a different way. One solution is to have a very simple change handler for the checkboxes that just sets .hide if any are checked. Alternatively, you could move it entirely out of the script and use CSS similar to the following, which would be pretty dependent on your structure. For example, it wouldn't work in my snippet above.

.refinar-btn {
    /* hide styles, e.g.: */
    opacity: 0.5;
    box-shadow: 0;
}

input[type="checkbox"]:checked ~ .refinar-btn {
    /* show styles, e.g.: */
    opacity: 1;
    box-shadow: ...;
}


Shuffle a deck of cards and draw 2 I recently came across a coding challenge on some sort of technological basket weaving forum, where you had to pick 2 cards from a shuffled deck. I believe the challenge can be interpreted 2 ways:

Generate random deck, pick first 2
Generate sequential (or any) deck, pick 2 random cards

I went for option one. I believe I have used a good shuffling algorithm and accounted for modulo bias.
My main priorities:

correctness
code easy to handle and read

cards.c
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define SWAP_INT(a,b) {int tmp=a; a=b; b=tmp;}

const char const* suits[4] = {"Diamonds","Clubs","Hearts","Spades"};
const char const* ranks[13] = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};

// from min inclusive to max inclusive
int rand_ranged_inclusive(int min, int max)
{
    if (min > max)
        SWAP_INT(min, max);

    if (min == max)
        return min;

    int range = max-min+1;
    int biased_interval = RAND_MAX%(range-1);
    int x;

    // prevent modulo bias by choosing a number outside biased interval
    do {
        x = rand();
    } while (x < biased_interval);

    return x%range + min;
}

// Fisher-Yates (Durstenfield)
int shuffle(int arr[], int len)
{
    for (int i = 0; i < len; ++i) {
        int j = rand_ranged_inclusive(i, len-1);
        SWAP_INT(arr[i], arr[j]);
    }
}

void print_card(int c)
{
    if (c < 0 || c > 52)
        printf("Joker\n");

    const char const* suit = suits[c/13];
    const char const* rank = ranks[c%13];

    printf("%s of %s\n", rank, suit);
}

int main(int argc, char const *argv[])
{
    srand(time(NULL));

    int cards[52] = {0};

    for (int i = 0; i < 52; ++i)
        cards[i] = i;

    shuffle(cards, 52);

    print_card(cards[0]);
    print_card(cards[1]);

    return 0;
}

I feel like it can be optimized some more, especially picking random numbers, but reading from dev/urandom seems overall slower, when the modulo bias is so small and easily overcome.

rand_ranged_inclusive(a, b) is a surprisingly long function name, for how little information it communicates to the reader. I have frequently seen versions of this function named randint(a, b) or randint0(b) — but where the possible outputs are between 0 inclusive and b exclusive!
Using "half-open ranges" like this has huge advantages in C, because C uses half-open ranges for everything else. To pick a random element from an array, you want randint0(NELEM(a)). To pick a random character from a string, you want randint0(strlen(s)). And so on.
if (min > max)
    SWAP_INT(min, max);

Here and throughout, I strongly recommend curly-bracing all your control flow, including if and for bodies which are currently only one line long. These braces may one day save you from a goto fail bug.
Also, I think it's un-idiomatic that you are going out of your way to produce well-defined behavior for rand_ranged_inclusive(6, 1). I claim that that kind of input clearly indicates a bug in the caller, and you should be using assert(min <= max) here. (Or, if you switch to half-open ranges, assert(min < max).)
Your choice to handle rand_ranged_inclusive(6, 1) becomes even weirder when you consider that you do not handle seemingly valid parameters such as rand_ranged_inclusive(-10, INT_MAX). (The caller who tries that gets integer overflow and undefined behavior.)
int range = max-min+1;
int biased_interval = RAND_MAX%(range-1);

The use of RAND_MAX % ... instead of (RAND_MAX+1) % ... is an immediate red flag for me, after our discussion of half-open ranges. (RAND_MAX is an endpoint-which-is-included, similar to INT_MAX.) All these +1 and -1 would go away if you switched to half-open ranges. I bet they're hiding some off-by-one errors. Let's trace through a sample input.
Suppose min=1, max=6, RAND_MAX=10. (This is legitimately the first input I traced.) Then range=6, biased_interval=0... so the do-while loop runs only once before dropping out... but you end up choosing 1-4 twice as often as 5-6.
Did you test this code at all?  How did you test it?
I think the algorithm you want here is more like
int range = max - min + 1;
int discard_top_k = ((RAND_MAX % range) + 1) % range;
int real_max = RAND_MAX - discard_top_k;
do {
    x = rand();
} while (x > real_max);

int j = rand_ranged_inclusive(i, len-1);

Your Fisher-Yates shuffle looks correct; but notice again that you're having to add a -1 to fix up the lack of half-open ranges in your random-number code.

if (c < 0 || c > 52)
    printf("Joker\n");

Is this situation possible? If it's supposed to be impossible, you should assert(0 <= c && c < 52) (hey look! half-open ranges!)
Also notice the off-by-one error in your code because of (say it with me) the lack of half-open ranges.

char const *argv[]

I agree with Linus on this one. Prefer
const char **argv


Better way to code download speed calcuation I'm writing a program that downloads stuff from the internet. While the program is working fine, I want to get one critical part reviewed. I use System.Diagnostics.StopWatch object to measure the time taken for the ns (NetworkStream) object to read the bytes in buffer. I then divide the number of elapsed seconds in stopwatch by number of bytes received to calculate the speed of my download in KBPS.

However, this method is giving me some extraordinarily large speeds (in excess of 8000KBPS), whereas I know that my internet bandwidth is not that fast. Is there anything wrong with this method? If not, then what is the correct way of getting the download speed? Here is my code:

while(true) //(bytesToRead>0)
{

    sw.Start();
    int n = ns.Read(buffer, 0, buffer.Length);
    sw.Stop();
    Speed = (float)n / sw.Elapsed.TotalSeconds;

    if (n==0)
        break;

    fs.Write(buffer,0,n);

    BytesRead+=n; //TODO: Persist the bytesRead object somewhere, so that it can be taken back for resumes
    bytesToRead -= n;
    OnProgress(this,new System.EventArgs());
    if (Status == DownloadStatusEnum.Paused) break;
}

Your summary complaint is that you're measuring short term xfer rate from system buffers to user space, rather than long term xfer rate from distant server to local network interface.

After a few roundtrips, TCP opens the congestion window and can have many KiB of data in flight. I don't know what your buffer.length is, but you make it sound like it is short enough that you're not blocking on read. That is, ns.Read() finds quite a lot of data buffered at the OS level, and returns a buffer's worth of it at once, so that your timing represents local CPU / memory bandwidth rather than network bandwidth.

The simplest remedy is to record initial starting time and don't touch it, report cumulative bytes read over cumulative elapsed time.

If your residential ISP does traffic shaping, and you want the display to reflect the fact that the first 30 seconds goes at 3 Mbps but longer downloads go at 1 Mbps, then keep a circular buffer of the last dozen or so timestamps, and use that to report on recent progress. Old measurements will age out, so after a while they will no longer affect the display.


Calculate g.c.d and l.c.m. in C I wrote a simple program to perform g.c.d and l.c.m., trying to follow the Linux kernel coding style. I know C for about one year, but I'm still a beginner.

Example:

user@compuer:~/projects/tmp$ ./tmp 21 45
G.C.D: 3
l.c.m: 315

Code:

#include <stdlib.h>
#include <stdio.h>

/*
 * It returns the greatest common divisor between two numbers. The numbers
 * must not be negative (undefined behaviour).
 */
int gcd(int a, int b);

/*
 * It returns the least common multiple. The numbers must not be negative
 * (undefined behaviour).
 */
int lcm(int a, int b);

int main(int argc, char *argv[])
{
        int retval = -1, a, b;

        if (argc != 3) {
                fprintf(stderr, "Error: missing or too many arguments\n");
                goto err_exit;
        }

        a = strtol(argv[1], NULL, 0);
        b = strtol(argv[2], NULL, 0);

        if (a < 0 || b < 0) {
                fprintf(stderr, "Error: numbers must be postive\n");
                goto err_exit;
        }

        if (!a || !b)
                printf("Warning: one or both numbers are 0.\n");

        printf("G.C.D: %d\nl.c.m: %d\n", gcd(a, b), lcm(a, b));

        retval = 0;

        err_exit:
                return retval;
}

int gcd(int a, int b)
{
        int retval = b, r = a;

        if (!a)
                goto exit;

        // Euclidean alrgorithm.
        do {
                a = b;
                b = r;

                r = a % b;
        } while (r);

        retval = b;

        exit:
                return retval;
}

int lcm(int a, int b)
{
        int retval = 0;

        if (a && b)
                retval = a / gcd(a, b) * b;

        return retval;
}

Makefile:

.PHONY = clean all

PROGNAME = tmp

SHELL = /bin/sh

CC ?= gcc

CFLAGS = -Wall -Wextra

all : main.o
    $(CC) -o $(PROGNAME) $^

clean :
    $(RM) *.o $(PROGNAME)

I don't see the point in using goto here. There's no resource clean up or any other strong reason to resort to it.  It just makes the control flow more complicated.
How to fix it? In the main function, you can just return the value immediately in case of an error. In the gcd function, you can run the while loop with a condition a != 0. It'll make the code easier to folloow and eliminate a corner case a = 0.
The error message fprintf(stderr, "Error: missing or too many arguments\n"); seems too generic to me. It would be more helpful if it were more detailed (too many and missing arguments are clearly different cases).
An LCM of two int's may not fit into int. I'd recommend to document that your program has undefined behavior if the LCM is too large or use a wider integer type.


Checking two arrays for matches Is there a better way to do this?

    var duplicate = false;
    for (var i = 0; i < acceptedFiles.length; i++) {
        for (var j = 0; j < attachments.attachments.length; j++) {
            if (attachments.attachments[j].name === acceptedFiles[i].name) {
                duplicate = true;
            }
        }
    }

Presumably, once a duplicate is found you don't need to continue looping:

if (attachments.attachments[j].name === acceptedFiles[i].name) {
    duplicate = true;
}

With JavaScript, the best thing would be to wrap up your for loops in a function:

function containsDuplicate(acceptedFiles, attachments) {
    for (var i = 0; i < acceptedFiles.length; i++) {
        for (var j = 0; j < attachments.attachments.length; j++) {
            if (attachments.attachments[j].name === acceptedFiles[i].name) {
                return true;
            }
        }
    }
    return false;
}

As this is a problem that applies to multiple languages, look at the break keyword.


Generating filters to remove query variables from a URL This function takes a URL structure which is most often a query string (but sometimes not) and generates filters to remove query variables from the URL.

If you're looking at an archive like

  http://example.com/?genre=rock&band=deep-purple

you'll get the following output:

[ROCK X] [DEEP PURPLE X]

so you can remove those "filters".

I have a lot (too much maybe) of nested structure-- if anyone has any general optimization or refactoring pointers for me I'd really appreciate it!

<?php
function event_filters() {
    $output = '';
    $filterclear = get_bloginfo('wpurl').'/events';
    $filterclass = 'filter-clear cp block fl search-tag tdn pr con ic-right ic-x c2h btn bg1 c2';
    $queryString = $_SERVER['QUERY_STRING'];
    $home = get_bloginfo('wpurl');

    parse_str($queryString, $params);
    $filter_count = count($params);

    // IF IS SINGLE DAY VIEW
    if(tribe_is_day()) {
        $day_title = ucwords(strftime( '%e de %B ', strtotime( get_query_var('eventDate') )));
        $output .= ''.$day_title.'';
    }

    foreach ($params as $key => $term) {
        $tags = explode(' ',$term);
        $tag_count = count($tags);

        $term = get_term_by('slug', $term, $key);
        $term_name = $term->name;

        if($filter_count == 1 && $tag_count <= 1) {
            // IF IS ONE KEY AND ONE TERM
            $output .= ''.$term_name.'';
        } else {
            if($tag_count > 1) {
                foreach($tags as $tag) {
                    // IF THERE IS MORE THAN ONE TERM PER KEY, LOOP THROUGH EACH TERM
                    $the_tag = get_term_by('slug', $tag, $key);
                    $tag_name = $the_tag->name;

                    $filterclear = str_replace($tag, '', $queryString);
                    $filterclear = str_replace(array('=+', '++', '+&'), array('=', '+', '&'), $filterclear);

                    if(substr($filterclear, -1) == '+'){
                        $filterclear = substr($filterclear,0,-1);
                    }

                    $output .= ''.$tag_name.'';
                }
            } else {
                // OR ELSE THERES JUST ONE TERM PRESENT
                $filterclear = remove_query_arg($term,$queryString);
                $output .= sprintf("%s", $filterclear, $term_name);
            } // END TAG_COUNT
        } // END FILTER_COUNT
    } // END FOR EACH

    return $output;
}
?>

Breaking Up Is Hard To Do

My first suggestion would be to break up your one function into many. No need to do all of that in just one function. The best way to do this would be to go about it logically. That is to say, break up your function by their purpose. For instance you could create a get_params() function like the following.

function getParams($queryString) {
    parse_str($queryString, $params);
    return $params;
}

This is a poor example because it doesn't take much from your code, but it does show how your functions should be specialized. Break them up so that they do only one thing and do it well. Even if you don't find yourself reusing that function it will help you in the long run. Don't believe me? Try it and then run your program again. Where is that error coming from now? I am almost positive it will have narrowed the amount of code you need to look at and will probably tell you in which function to look through. Here's a couple more small functions for you. Not to say there aren't more, these are just some maybe not so obvious ones to get you started.

function getOutput($class, $title, $href) {
    return '' . $title . '';
}

function getTermBy($key, $term) {
    return get_term_by('slug', $term, $key);
}

That last function might not be all that great, but if this were a class you could make it so that you'd only have to pass the $term to it, which would be better and cleaner. I tend to tell everyone to ignore OOP until they are ready for it, just as I am telling you. Work on the suggestions in this answer and once this all becomes second nature I think you'd be ready for it. For the time being, just breaking up your code will make it easier to transition into classes should you ever decide to convert this over to one.

What's This Now!

It may be common knowledge what some of these functions do ('get_bloginfo()`), but I haven't a clue. I'm assuming this is wordpress or something. Never got into it myself so I'm not sure. Never the less, you should be commenting your code to let people know what you're doing. You don't have to go into great detail, just enough to say what you expect the outcome to be. I do see that you have some comments, but they seem to be more structural rather than functional.

norunonfunctionsasitishardtoread

Look up, now look down, now back up at me. Sadly these run-on functions are hard to read.

$day_title = ucwords(strftime( '%e de %B ', strtotime( get_query_var('eventDate') )));

But with the power of good code separation your code could look as good as mine!

$eventDate = get_query_var('eventDate');
$eventDateTime = strtotime($eventDate);
$formattedTime = strftime('%e de %B', $eventDateTime);
$day_title = ucwords($formattedTime);
//OR
$day_title = get_query_var('eventDate');
$day_title = strtotime($day_title);
$day_title = strftime('%e de %B', $day_title);
$day_title = ucwords($day_title);

I've always wanted to do that :) Anyways, now that I've had my fun... It won't hurt anything to separate code like this, it will just increase the number of lines in your program. It will still run the same and the slight increase in filesize will be neglible and wont make it run any slower, or if it does, it will be so miniscule as to be unnoticeable.

Consistency

You seem to be struggling with how you want your code to look. This is very common in a new programmer who is still unsure as to what style they want to adopt. You should pick one and stick with it though. Right now you have oneword, camelCase, and under_score variables/functions with no consistency. The only other reason I could think of for code to look like this is if it were all copy-pasted in without fully understanding it, which should never be the case, nor do I think it is. This is not to say you need to pick just one. You can mix and match. Some people use camelcase for variables and underscore for functions, or vice-versa. Its entirely up to you, there is no right or wrong, just preference. But once you pick one you like you should stick with it.

If you ever join a team this will become a big factor, though your preferences will mater little and you'll have to conform your style to the project lead's. They do this for consistency and being consistent with your own code will get you in the hang of this.

Final Thoughts

I've not found your issue, but implementing these suggestions might help you find it. I had a little fun with the answer, so my apologies, but it should still be helpful and understandable.


Counting all pairs that differ by k Given an array of numbers and another number k, how can I find the number of 2 elements such as their difference is equal to k?

def pairs(n,k)
  n.combination(2).select{|x|(x[0]-x[1] == k) || (x[1]-x[0] == k)}.count
end

I ran a test where n was an array of 8000 different 10 digit numbers.

However, this took about 30 seconds to solve, and ideally it would solve in under a second.

It looks like there is a problem with my algorithm, but I can't figure out how to make it more efficient.

The logical solution here is to sort the data in order, then scan it looking ahead for the partner that has the right difference to the target. Slicing, and combinations, etc. are not going to be the most efficient algorithm.

A sort with \$O(n \log n)\$ scaling, and a simple 'look ahead' to find a potential pairing, will be much, much faster.

If your data has duplicates, then you will need to look for multiple matches for the correct difference.

Consider doing a binary search for the target value, which will still leave you at an overall performance of \$O(n \log n)\$ algorithm


Filtering a data structure using regex predicates Assume we have a data-structure like this:

(def data
     (atom [{:id 1 :first-name "John1" :last-name "Dow1" :age 14}
            {:id 2 :first-name "John2" :last-name "Dow2" :age 54}
            {:id 3 :first-name "John3" :last-name "Dow3" :age 34}
            {:id 4 :first-name "John4" :last-name "Dow4" :age 12}
            {:id 5 :first-name "John5" :last-name "Dow5" :age 24}]))

I want to filter it by specific keys using regex in predicates, so I ended up with this function which works fine, but I guess code is ugly and duplicated. How can I get rid of code duplication?

(defn my-filter [str-input]
  (let [firstname (filter #(re-find (->> (str str-input)
                                         (upper-case)
                                         (re-pattern))
                                    (upper-case (:first-name %)))
                     @data)
        lastname (filter #(re-find (->> (str str-input)
                                        (upper-case)
                                        (re-pattern))
                                   (upper-case (:last-name %)))
                    @data)
        age (filter #(re-find (->> (str str-input)
                                   (upper-case)
                                   (re-pattern))
                              (upper-case (:age %)))
               @data)]
    (if-not (empty? firstname)
      firstname
      (if-not (empty? lastname)
        lastname
        (if-not (empty? age)
          age)))))

First up, notice that you're creating 3 leted names by using exactly the same expression but replacing one key lookup function. This is a prime candidate for deduplication by making a local function.

(defn my-filter [str-input]
  (let [seek (fn [k](filter #(re-find (->> (str str-input)
                                         (upper-case)
                                         (re-pattern))
                                    (upper-case (k %)))
                     @data))
         firstname (seek :first-name)
        lastname (seek :last-name)
        age (seek :age)]
    (if-not (empty? firstname)
      firstname
      (if-not (empty? lastname)
        lastname
        (if-not (empty? age)
          age)))))

Next we can notice that the remainder is just doing the same "return this if it's not empty" logic with each of the three keys in sequence. some returns the first non-falsy result of a function on a sequence so by adding a seq to the seek function we can turn empty filter sequences into nils we can combine the two and get the logic we want. I used letfn this time because we're only leting fns, might as well.

(defn my-filter [str-input]
  (letfn[(seek [k]
               (seq (filter #(re-find (->> (str str-input)
                                         (upper-case)
                                         (re-pattern))
                                    (upper-case (k %)))
                     @data)))]
    (some seek [:first-name :last-name :age])))


array_diff in JavaScript In PHP exists a function array_diff (http://php.net/manual/de/function.array-diff.php) which returns the difference of two arrays.
I have tried the implement my own version in JavaScript.

Any feedback is welcome. :)

function getArrayDiff(a, b) {
  var ret = [],
      merged = [];

  merged = a.concat(b);

  for (var i = 0; i < merged.length; i++) {
    // When the element is contained ONLY
    //   one time then the search from
    //   left returns the same value as
    //   the search from the right.
    if (merged.indexOf(merged[i]) ==
        merged.lastIndexOf(merged[i])) {
      // ... in that case the element
      // is pushed to the result array.
      ret.push(merged[i]);
    }
  }

  return ret;
}

// -- Test ----------
a = [2, 4, 8, 16, 32];
b = [2, 4, 32, 64, 128, 256];

console.log(getArrayDiff(b, a));

Live Demo on CodePen:
http://codepen.io/mizech/pen/GpVMEd

You can use Array#filter to get elements from array which are not present in other array.

var a = [2, 4, 8, 16, 32],
    b = [2, 4, 32, 64, 128, 256];

// Define custom method on Array prototype
// Pass the array as parameter
Array.prototype.diff = function (arr) {

    // Merge the arrays
    var mergedArr = this.concat(arr);

    // Get the elements which are unique in the array
    // Return the diff array
    return mergedArr.filter(function (e) {
        // Check if the element is appearing only once
        return mergedArr.indexOf(e) === mergedArr.lastIndexOf(e);
    });
};

// How to call?
var diff = a.diff(b);

console.log(diff);
document.write('<pre>' + JSON.stringify(diff, 0, 4) + '</pre>');

Shorter version:

var diff = array1.concat(array2).filter(function (e, i, array) {
    // Check if the element is appearing only once
    return array.indexOf(e) === array.lastIndexOf(e);
});


Quick sort algorithm in Rust I have written this Rust code to implement the quick sort algorithm. Could you review it and tell me if it is idiomatic or not? Especially about my use of the slices?

fn quick_sort<T: Ord>(array: &mut [T]) {
    let n = array.len();
    if n > 0 {
        let mut i_pivot = 0;
        for i in 1..n {
            if &array[i] < &array[n - 1] {
                array.swap(i, i_pivot);
                i_pivot += 1;
            }
        }
        array.swap(i_pivot, n - 1);
        quick_sort(&mut array[0..i_pivot]);
        quick_sort(&mut array[i_pivot + 1..n]);
    }
}

fn main() {
    // Fixed-size array (type signature is superfluous)
    let mut xs = [
        8, 13, 20, 13, 4, 21, 24, 13, 18, 23, 14, 6, 10, 2, 4, 6, 16, 6, 17, 9, 8, 20, 14, 19, 7,
        9, 18, 0, 18, 1, 8, 10,
    ];

    quick_sort(&mut xs);

    println!("{:?}", xs);
}
```

Code review:
1. Your code has a bug here for i in 1..n,
the correct version starts from zero: for i in 0..n,
Change your main to the following code and then cargo run:

fn main() {
    let mut xs = vec![
        8, 13, 20, 13, 4, 21, 24, 13, 18, 23, 14, 6, 10, 2, 4, 6, 16, 6, 17, 9, 8, 20, 14, 19, 7,
        9, 18, 0, 18, 1, 8, 10,
    ];
    let mut v = xs.clone();
    v.sort();
    quick_sort(&mut xs);
    assert_eq!(v, xs);
}

You will see this error:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `[0, 1, 2, 4, 4, 6, 6, 6, 7, 8, 8, 8, 9, 9, 10, 10, 13, 13, 13, 14, 14, 16, 17, 18, 18, 18, 19, 20, 20, 21, 23, 24]`,
 right: `[0, 1, 2, 4, 6, 6, 7, 6, 8, 4, 8, 9, 9, 10, 10, 8, 13, 13, 14, 14, 16, 17, 18, 18, 18, 19, 20, 20, 13, 23, 24, 21]`', src/main.rs:25:5

Rename i_pivot to j, since it is just an index and your pivot is a[n - 1].
Change if n > 0 to if n > 1 since the slice length should be at least two.
You don't need Ord here, PartialOrd is enough (try it here):

fn quick_sort<T: PartialOrd>(a: &mut [T]) {
    let n = a.len();
    if n > 1 {
        let mut j = 0;
        for i in 0..n {
            if &a[i] < &a[n - 1] {
                a.swap(i, j);
                j += 1;
            }
        }
        a.swap(j, n - 1); // pivot
        quick_sort(&mut a[0..j]);
        quick_sort(&mut a[j + 1..n]);
    }
}

fn main() {
    let mut xs = vec![
        8, 13, 20, 13, 4, 21, 24, 13, 18, 23, 14, 6, 10, 2, 4, 6, 16, 6, 17, 9, 8, 20, 14, 19, 7,
        9, 18, 0, 18, 1, 8, 10,
    ];
    let mut v = xs.clone();
    v.sort();
    quick_sort(&mut xs);
    assert_eq!(v, xs);
}


What about percentage usage? I'm thinking about the usage of percent, example, in margins.

We can use overlay to separate our layout by DPI sizes, but why can't we use percentage?

Something like that:

Display display = getWindowManager().getDefaultDisplay();

float width = display.getWidth();
float height = display.getHeight();

//20% of left margin
float imageMarginLeft = ( width * 20 ) / 100;

And then set this margin to the image, or whatever element.

Is this bad?

You can simplify math whenever possible. No reason to multiply by 20 then divide by 100. Just multiply by .20. If you needed a result that was twenty percent in addition to 100 percent of what you already had you could multiply by 1.2. It saves a process making your code just a tad more efficient!


Simple/Naive Implementation of Identity and Maybe Monad in Elixir This is my first crack at a identity monad and a maybe monad in Elixir:

defmodule Monad do
  @doc "v is value to be wrapped as monadic value"
  def return(v), do: fn -> v end
  @doc "m is monad function, mv is monadic value"
  def bind(m, mv), do: m.(mv.())
end

#Simple identity monad
id = fn s -> s end
h = Monad.return(:ok)
r = Monad.bind(id, h)

#Maybe monad
maybe = fn s -> if is_nil(s), do: :error, else: s end
r = Monad.bind(maybe, h)

I'd like to see if there is a way to make the monad into a protocol since the return and bind seem to be common to all monads.

I think you're sort of missing the point with this code - the difference between different kinds of monads (Maybe vs. List vs. Identity, etc.) is in the different implementations of return and bind. I think a good starting place might be reading through a library that implements monads in elixir, like monad. Looking into that you can see that for example Maybe is implemented like this (simplifying):

def return(x), do: {:just, x}

def bind({:just, x}, f), do: f.(x)
def bind(:nothing, _), do: :nothing

def fail(_), do: :nothing

While  for example Error (the second-simplest I think) is implemented like this:

def return(x), do: {:ok, x}

def bind(e = {:error, _}, _), do: e
def bind({:ok, x}, f), do: f.(x)

def fail(msg), do: {:error, msg}

The difference between the two being that in one case you only get information that there is no result (:nothing) while in the other you either get a result or some information on the error (represented by {:error, _}). Also note that both have additional helper functions to for example extract the result (presumably at the end of the computation).


Print the first, last, and in-between integers of a range Given our spec from Code Golf:

  Given two integers, output the two integers, and then the range between them.
  The order of the range must be the same as the input.

  Examples:

 Input        Output
 0,  5   ->   [0, 5, 1, 2, 3, 4]
-3,  8   ->   [-3, 8, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
 4,  4   ->   [4, 4]
 4,  5   ->   [4, 5]
 8,  2   ->   [8, 2, 7, 6, 5, 4, 3]
-2, -7   ->   [-2, -7, -3, -4, -5, -6]

Using our test driven approach :)

import org.junit.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.*;

public class CodeGolfTest {

@Test
public void firstLastAndEverythingBetweenExampleOTo5() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(0, 5);
    assertThat(integers).isNotNull().hasSize(6).containsExactly(0,5,1,2,3,4);

}

@Test
public void firstLastAndEverythingBetweenExampleMinus3To8() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(-3, 8);
    assertThat(integers).isNotNull().hasSize(12).containsExactly(-3,8,-2,-1,0,1,2,3,4,5,6,7);

}

@Test
public void firstLastAndEverythingBetweenExample4To4() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(4, 4);
    assertThat(integers).isNotNull().hasSize(2).containsExactly(4,4);

}

@Test
public void firstLastAndEverythingBetweenExample4To5() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(4, 5);
    assertThat(integers).isNotNull().hasSize(2).containsExactly(4,5);

}

@Test
public void firstLastAndEverythingBetweenExample8To2() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(8, 2);
    assertThat(integers).isNotNull().hasSize(7).containsExactly(8,2,7,6,5,4,3);

}

@Test
public void firstLastAndEverythingBetweenExampleMinus2ToMinus7() {

    final List<Integer> integers = CodeGolf.firstLastAndEverythingBetween(-2, -7);
    assertThat(integers).isNotNull().hasSize(6).containsExactly(-2,-7,-3,-4,-5,-6);

}
}

Can we optimize further this code?

The implementation:

import java.util.ArrayList;
import java.util.List;

public final class CodeGolf {

    private CodeGolf() {
    }

    public static List<Integer> firstLastAndEverythingBetween(final int a, final int b) {

        if (a == b) {
            return addAB(a, b);
        }

        final List<Integer> result = addAB(a, b);
        int initial = getInitial(a, b);

        for (int n = 1; n < Math.abs(b - a); n++) {
            result.add(initial);
            if (b > a) {
                initial++;
            } else {
                initial--;
            }
        }

        return result;
    }

    private static int getInitial(int a, int b) {
        return (b > a) ? (a + 1) : (a - 1);
    }

    private static List<Integer> addAB(int a, int b) {
        final List<Integer> result = new ArrayList<>();
        result.add(a);
        result.add(b);
        return result;
    }
}

As you ask for optimization:

You re-evaluate Math.abs() in each iteration of the loop, which is a constant value. Consider for(int n = 1, upperBound = Math.abs(b - a); n < upperBound; n++) instead.
The same goes for if (b > a) which is also constant. Maybe calculate an offset beforehand int offset = (b > a) ? 1 : -1; and then just add the offset in the loop.
... and if you already calculate such an offset, you may also use it to replace getInitial() with initial = a + offset;


U.S. State Capitals Quiz (Python) I have a program that gives the player a random U.S. state, asks for its capital, and keeps score. This keeps going until the player decides to stop playing. At the end, it prints out both the amount of correct answers and amount of incorrect answers.
I took some of the advice into account that I got on my other posts and put the dictionary within the main function (I had it in its own function before), but was wondering if there was a more efficient way to do the while loop that is the basis of the game, as well as if me converting the dict to a list is an okay way to solve this problem.
MIN = 0
MAX = 49

import random

def main():

    stateDict = {'Alabama': 'Montgomery',
              'Alaska': 'Juneau',
              'Arizona': 'Phoenix',
              'Arkansas': 'Little Rock',
              'California': 'Sacramento',
              'Colorado': 'Denver',
              'Connecticut': 'Hartford',
              'Delaware': 'Dover',
              'Florida': 'Tallahassee',
              'Georgia': 'Atlanta',
              'Hawaii': 'Honolulu',
              'Idaho': 'Boise',
              'Illinois': 'Springfield',
              'Indiana': 'Indianapolis',
              'Iowa': 'Des Moines',
              'Kansas': 'Topeka',
              'Kentucky': 'Frankfort',
              'Louisiana': 'Baton Rouge',
              'Maine': 'Augusta',
              'Maryland': 'Annapolis',
              'Massachusetts': 'Boston',
              'Michigan': 'Lansing',
              'Minnesota': 'Saint Paul',
              'Mississippi': 'Jackson',
              'Missouri': 'Jefferson City',
              'Montana': 'Helena',
              'Nebraska': 'Lincoln',
              'Nevada': 'Carson City',
              'New Hampshire': 'Concord',
              'New Jersey': 'Trenton',
              'New Mexico': 'Santa Fe',
              'New York': 'Albany',
              'North Carolina': 'Raleigh',
              'North Dakota': 'Bismarck',
              'Ohio': 'Columbus',
              'Oklahoma': 'Oklahoma City',
              'Oregon': 'Salem',
              'Pennsylvania': 'Harrisburg',
              'Rhode Island': 'Providence',
              'South Carolina': 'Columbia',
              'South Dakota': 'Pierre',
              'Tennessee': 'Nashville',
              'Texas': 'Austin',
              'Utah': 'Salt Lake City',
              'Vermont': 'Montpelier',
              'Virginia': 'Richmond',
              'Washington': 'Olympia',
              'West Virginia': 'Charleston',
              'Wisconsin': 'Madison',
              'Wyoming': 'Cheyenne'}

    statesList = list(stateDict)

    correct = 0
    incorrect = 0

    again = 'y'

    while (again == 'y'):
        num = random.randint(MIN,MAX)
        state = statesList[num]
        print('\n' + state)
        ans = input("\nEnter the capital of this state: ")
        if (ans == stateDict[state]):
            correct += 1
            print("Correct")
            again = input("Type y to play again, anything else to stop: ")
        else:
            incorrect += 1
            print("Incorrect")
            again = input("Type y to play again, anything else to stop: ")

    print("\nYou have",correct,"correct answers")
    print("\nYou have",incorrect,"incorrect answers")

main()

You are on the right track in several respects -- for example, putting all
behavior/actions inside of functions. That said, constants are fine at the top
level, and one advantage of putting them there is allowing the reader to
focus on the algorithm without the visual heaviness of a big data structure.
Don't force your user to worry about capitalization: lowercase the data and
then use Python's built-in string methods to capitalize geographic names for
presentation to the user.
Opinions vary on this, but I recommend using natural language as the primary
(not sole) guide when picking variables: in most contexts, for example,
capitals is a better name than stateDict; states better than
statesList. Sometimes a data-type suffix can disambiguate names, but
don't make that your first impulse.
The random library includes a choice() function, so you do not
need MIN, MAX.
I recommend less chatty messages to users in interactive programs. Once
the user understands the basics (computer prints state, user types capital),
they do not require verbose instructions. Ruthless text cutting is
a virtue in these situations.
Nest the main() call under the conditional shown below. This mechanism will
make your scripts amenable to importing, easier debugging, and
automated testing should you ever need it.
Whenever you find yourself creating multiple closely related variables
(correct and incorrect), consider whether you can unify them under a data
structure. Sometimes taking that approach will suggest further refactoring to
simplify code (for example, by reducing if-else branching). In the illustration
below, I started just by focusing on unifying the correct/incorrect tallies,
but that inspired other simplifications in the reporting of overall results.
import random

# Your dict, but lowercase.
capitals = {
    'alabama': 'montgomery',
    'alaska': 'juneau',
    ...
}

def main():
    # Setup.
    states = tuple(capitals)
    tally = {True: 0, False: 0}
    results = {True: 'Correct', False: 'Incorrect'}
    result = ''

    # Quiz loop.
    print('State capitals quiz:')
    while True:

        # Get user reply.
        state = random.choice(states)
        ans = input(f'{result}{state.title()}? ').lower()
        if ans in ('', 'q', 'quit'):
            break

        # Tally result.
        res = ans == capitals[state]
        tally[res] += 1
        result = results[res] + '. '

    # Print overall results.
    fmt = 'Results:\n- {}: {}\n- {}: {}'
    args = (results[True], tally[True], results[False], tally[False])
    print(fmt.format(*args))

if __name__ == '__main__':
    main()

Finally, people who take quizzes generally want to see the right answers.
You could print the correct result immediately in response to a wrong reply. Or
you could keep track of all states with bad replies and print correct answers
at the end.


Better way to validate user input in cakephp I'm trying to find a way to make my code easeier to read, so i found that major part of the code is validation trough if, ifelse:

    if (!$this -> is_valid_username($username)) {
        $this -> Session -> setFlash('Enter valid client username, Error 1.', 'default', array(), 'errorlogaddclient');
        $this -> redirect('/dashboard/settings');
        exit ;
    }
    if (!$this -> is_valid_password($password) || !$this -> is_valid_defpass($password)) {
        $this -> Session -> setFlash('Enter valid password, Error 2.', 'default', array(), 'errorlogaddclient');
        $this -> redirect('/dashboard/settings');
        exit ;
    }
    if ($this -> is_already_client($user)) {
        $this -> Session -> setFlash("User is already someone's client, Error 3", 'default', array(), 'errorlogaddclient');
        $this -> redirect('/dashboard/settings');
        exit ;
    }//ect

so what is proper/better way to do this

I would split up the code into objects, with good object oriented patterns. This should result in objects that have very distinct responsibilities.

The pattern I think you should primarily look into is the "Proxy" pattern (See "Design Patterns" book by "Gang of four".) It can be used to extract the code that ensures security, for example. It makes the security code independent from the domain logic / data access / user interface.

It may mean refactoring a lot of code, but once done, you can then write thorough unit-tests for the security proxy in isolation, giving you a rock solid foundation.

Write tests, then write the testable code, (i.e. isolated) then refactor to the point where it's neat and tidy.


Print input one word per line I'm doing K&R C Exercises.  I could use a code review to see how I can improve my logic. The excercise is:

  Write a program that prints its input one word per line with getchar.

My basic idea is we need to know whether or not we're in a word. We use the IN status.  Every time we hit a blank space, tab, or newline, the status is changed to OUT.

Please offer only suggestions based on what i'm learning in the book up to this point, "symbolic constants,  if else, and loops only." Also thoughts on my comments would be welcome.

// Exercise1.11.cpp : Defines the entry point for the console application.
/*
 Write a program that prints its input one word per line.
*/

#include "stdafx.h"

#define IN 1
#define OUT 0

int _tmain(int argc, _TCHAR* argv[])
{
    int status = OUT;
    int c;

    while ((c = getchar()) != EOF){

        // Check to see if char is not a new line, blank or space.
        if ((c != '\n' && c !=' ' && c != '\t') ){

            if (status == OUT){
                putchar('\n');
                status = IN;
            }

            putchar(c);
        }
        else {
            // char is a new line, blank or tab, so don't process them.
            status = OUT;
        }
    }

    return 0;
}

Overall it looks like you are in the right track, though I think you have overcomplicated things a bit with that custom state flag and constants. C99 gives you the bool type, which could be used instead. Failing that, I would have settled with an integer. The defines seem overkill for such a tiny program.

You can omit the return 0 at the end of main, it is implicit (C99 standard).

_tmain and _TCHAR are Microsoft extensions, added by Visual Studio when you create a project with it. Be advised that this is a compiler extension and is therefore non-portable. The standard C entry point function is called just main and it should take no arguments, unless you need to process the command line.

Prefer exposing your #include dependencies instead of relying on the auto-generated stdafx.h that Visual Studio adds for you. Your program needs at least <stdio.h>.

This is how I would have written it, using a simple bool to keep track of the state, and, as @Loki suggested, using isspace() to test the character (always avoid reinventing the wheel, unless you really mean to):

#include <stdio.h>   // getchar() & friends
#include <ctype.h>   // isspace()
#include <stdbool.h> // bool, true, false

int main(void)
{
    int c;
    bool needNewLine = false;

    while ((c = getchar()) != EOF) {

        if (isspace(c)) {
            needNewLine = true;
            continue;
        }

        if (needNewLine) {
            putchar('\n');
            needNewLine = false;
        }

        putchar(c);
    }
}


Asynchronous website monitor I have a class which is responsible for checking whether a website is up or down. I've made it to run asynchronously, but I would like critique if this is a good/bad way or if there is another better way to do it.

class UrlChecker {
    private readonly IValidationCondition _condition;
    private readonly Dictionary<string, UrlStatus> _status = new Dictionary<string, UrlStatus>();
    private readonly object _lock = new object();

    public UrlChecker(IValidationCondition condition) {
        _condition = condition;
    }

    public void CheckRange(IEnumerable<string> urls, Action<Dictionary<string, UrlStatus>> callback) {
        var options = new ParallelOptions {MaxDegreeOfParallelism = 5};
        Parallel.ForEach(urls, options, Check);

        callback(_status);
    }

    private void Check(string url) {
        Console.WriteLine("Checking " + url);

        var req = (HttpWebRequest) WebRequest.Create(url);
        req.Timeout = 10 * 10000; // 10 seconds

        HttpWebResponse resp;

        try {
            resp = (HttpWebResponse)req.GetResponse();
        }
        catch(WebException ex) {
            // We got an exception, consider it as down
            lock (_lock)
                _status.Add(url, UrlStatus.Down);
            return;
        }

        if(resp.StatusCode != HttpStatusCode.OK) {
            lock (_lock)
                _status.Add(url, UrlStatus.Down);
            return;
        }

        using(var reader = new StreamReader(resp.GetResponseStream())) {
            // Check for empty response
            var html = reader.ReadToEnd();
            if(string.IsNullOrEmpty(html)) {
                lock(_lock) {
                    _status.Add(url, UrlStatus.Down);
                }
            }

            // Validate against condition
            if(!_condition.IsValid(html)) {
                lock(_lock) {
                    _status.Add(url, UrlStatus.Down);
                }
                return;
            }
        }

        // We reached the end without problems, it's a valid url
        lock(_lock) {
            _status.Add(url, UrlStatus.OK);
        }
    }
}

It's called like so:

checker.CheckRange(urls, status => {
    if(status.Any(x => x.Value == UrlStatus.Down))
        EmailFailing(message);
});

The second parameter is obviously a callback that's invoked when all checks are done.

Am I locking correctly?

Is this an acceptable way of doing it? Checking with Fiddler proves that it's working correctly, but is there a better way?

I don't see how this runs asynchronously. callback(_status); will still only be called after all processing is finished, parallel or not. In this case this makes the callback rather redundant, as it does the same as a simple return value.

If you want to make it asynchronous you'll need to store the callback as a member variable, but return immediately in CheckRange. Start the actual processing on a separate thread by e.g. using a BackgroundWorker. Once this execution completes, you can call the stored callback with the result.


How to make my code shorter. This Code formats Credit card number. Vanilla JS How to make my script shorter and better? This code allows only digits, auto-format card number like this XXXX XXXX XXXX XXXX. if user hits delete or backspace to delete space in between digits, nothing happens caret just moves 1 space forward or backward, it depends on which key user pressed (delete or backspace). If user hits backspace after digit and the previous second symbol is space then backspace deletes the digit and moves 2 spaces back like this (XXXX X|XXX XXXX XXXX -> XXXX| XXXX XXXX XXX ). Delete key dose the same but vice versa like this (XXX|X XXXX XXXX XXXX -> XXXX |XXXX XXXX XXX ). It also allows ctrl+c,ctrl+v,ctrl+a,ctrl+x.

let input = document.querySelector('input');

input.addEventListener('keyup', function (e) {
    let cursor = input.selectionStart;
    let inpVal = input.value;
    let cardCode = inpVal.replace(/\s/g, '').substring(0, 16);
    cardCode = cardCode != '' ? cardCode.match(/.{1,4}/g).join(' ') : '';
    input.value = cardCode;
    let key = e.keyCode || e.which;
    // let ctrl = e.ctrlKey || key === 17 || e.metaKey;
    if ((key >= 48 && key <= 57) || (key >= 96 && key <= 105)) {
        if (cursor < parseInt(inpVal.length)) {
            input.selectionEnd = cursor;
        }
    } else if (key == 8) {
        if (input.value[cursor - 1] == ' ') {
            input.selectionEnd = cursor - 1;
        } else {
            input.selectionEnd = cursor;
        }
    } else if (key == 46) {
        if (input.value[cursor + 1] == ' ') {
            input.selectionEnd = cursor + 2;
        } else {
            input.selectionEnd = cursor;
        }
    }
});
input.addEventListener('keydown', function (e) {
    let inpVal = input.value;
    let cursor = input.selectionStart;
    let key = e.keyCode || e.which;
    let ctrl = e.ctrlKey || key === 17 || e.metaKey;
    if (
        key == 9 ||
        // Ctrl+A
        (key == 65 && ctrl === true) ||
        // Ctrl+C
        (key == 67 && ctrl === true) ||
        // Ctrl+X
        (key == 88 && ctrl === true) ||
        // Ctrl+V
        (key == 86 && ctrl === true) ||
        // home, end, влево, вправо
        (key >= 35 && key <= 40) ||
        (key >= 48 && key <= 57) ||
        (key >= 96 && key <= 105)
    ) {
        return;
    } else if (key == 8) {
        if (input.value[cursor - 1] == ' ' && cursor < parseInt(inpVal.length)) {
            e.preventDefault();
            input.selectionEnd = cursor - 1;
        }
    } else if (key == 46) {
        if (input.value[cursor] == ' ' && cursor < parseInt(inpVal.length)) {
            e.preventDefault();
            input.selectionStart = cursor + 1;
        }
    } else {
        e.preventDefault();
    }
});
<form method="GET" action="#" class="card">
                <label style="font-size: 20px; display: block; padding: 10px" for="cardnum">Credit Card number</label>
                <input style="font-size: 20px; padding: 10px" autocomplete="off" id="cardnum" name="cardnum" type="text" maxlength="19" title="Please enter a card number in XXXX XXXX XXXX XXXX format" pattern="^\d{4}\s\d{4}\s\d{4}\s\d{4}$" inputmode="numeric" required />
            </form>

I've mainly got three points:

The whole thing should be wrapped in a function with the reference to the input element passed in. Currently it is hard coded to (only) apply to the first input on the page, which doesn't seem like a practical scenerio.

Instead of using the deprecated/non-standard keyCode and which, you should be using key. And if you do use keyCode you should define all code numbers as constants.

Unless I'm missing some side-effect, the use of parseInt on inpVal.length is pointless.


Is there a better way to output a javascript array from ASP.net? I often run into the problem of producing a javascript array on an ASP.net page from an IEnumerable and I was wondering if there was an easier or clearer way to do it than

<% bool firstItem = true;
   foreach(var item in items){
      if(firstItem)
      {
         firstItem = false;
      }
      else
      {%>
        ,
      <%}%>
     '<%:item%>'
  %>

The whole thing is made much more verbose because of IE's inability to handle a hanging comma in an array or object.

With a bit of help from System.Linq this becomes quite easy.

var array = [ <%=
    string.Join(",", items.Select(v => "'" + v.ToString() + "'").ToArray())
%> ];


Calculate average of array of objects per key value using reduce I want to find average of an array of objects based on their key values using the new functional programming style. I found my way around array reduce and solved my problem, but not sure if this is the best way to do it.

Please take a look at my code and see if this is the way to use reduce for my purpose.

Let's say I have an array of objects as follows:

private data = [
    {tv: 1, radio:5,fridge:4},
    {tv: 2, radio:2,fridge:null},
    {tv: 3, radio:6,fridge:5}
];

I want to create another array containing the averages of each of the items in my data array. What I have, and is working, is below:

function summary(){
    var keys= Object.keys(data[0]);
    var sums = {};
    var averages = Object.keys(this.data.reduce((previous, element) => {
        keys.forEach(el => {
            if(element[el] !== null){
                if (previous.hasOwnProperty(el)) {
                    previous[el].value += element[el];
                    previous[el].count += 1;
                } else {
                    previous[el] = {
                        value: element[el],
                        count: 1
                    };
                }
            }
        });
        return previous;
    }, sums)).map(name => {
        return {
            name: name,
            average: sums[name].value / sums[name].count
        };
    });
    console.log(averages);
}

Running the code will give me my expected results:

average = [
    { "name": "tv", "average": 2 },
    { "name": "radio", "average": 4.333333333333333 },
    { "name": "fridge", "average": 4.5 }
]

But is this the best way to solve my problem using new reduce functions?

Here is possibly an even more functional programming style solution, which makes use of a temporary ES6 Map object. This has the advantage over a plain object: you can turn it into an array of pairs, and chain on that to get the final result:

var data = [
    {tv: 1, radio:5, fridge:4},
    {tv: 2, radio:2, fridge:null},
    {tv: 3, radio:6, fridge:5}
];

var avg = Array.from(data.reduce(
        (acc, obj) => Object.keys(obj).reduce(
            (acc, key) => typeof obj[key] == "number"
                ? acc.set(key, (acc.get(key) || []).concat(obj[key]))
                : acc,
        acc),
    new Map()),
        ([name, values]) =>
            ({ name, average: values.reduce( (a,b) => a+b ) / values.length })
    );

console.log(avg);

Instead of immediately summing up the values, this code first collects the different values into an array per property, in a Map, then it calculates the averages from those arrays, turning it into the desired target structure.

Alternative output structure

Personally I find it more logical to produce output that has the same structure as the input objects, so I provide this very similar alternative. Only the final map is replaced by a reduce:

var data = [
    {tv: 1, radio:5, fridge:4},
    {tv: 2, radio:2, fridge:null},
    {tv: 3, radio:6, fridge:5}
];

var avg = Array.from(data.reduce(
        (acc, obj) => Object.keys(obj).reduce(
            (acc, key) => typeof obj[key] == "number"
                ? acc.set(key, (acc.get(key) || []).concat(obj[key]))
                : acc,
        acc),
    new Map())).reduce(
        (acc, [name, values]) =>
            Object.assign(acc, { [name]: values.reduce( (a,b) => a+b ) / values.length }),
        {}
    );

console.log(avg);

Performance improvement

As you asked in comments about performance, I tried to improve on it, without giving up on functional programming.

I took my first code version (which will be more performant than the second), and changed the first half of the algorithm: the numbers are now summed up immediately, keeping a count next to it. For this I introduced an immediately invoked (arrow) function:

var data = [
    {tv: 1, radio:5, fridge:4},
    {tv: 2, radio:2, fridge:null},
    {tv: 3, radio:6, fridge:5}
];

var avg = Array.from(data.reduce(
        (acc, obj) => Object.keys(obj).reduce(
            (acc, key) => typeof obj[key] == "number"
                ? acc.set(key, ( // immediately invoked function:
                        ([sum, count]) => [sum+obj[key], count+1]
                    )(acc.get(key) || [0, 0])) // pass previous value
                : acc,
        acc),
    new Map()),
        ([name, [sum, count]]) => ({ name, average: sum/count })
    );

console.log(avg);

This stays within the functional programming rules, but I expect better performance than the first two versions I posted.


Core Data model of video and entities I have a Core Data model with two entities: Video and Playlist.

A Video can be a member of many Playlists
A Playlist can have many Videos, including the same Video multiple times
A Playlist's Videos are ordered

  Video <<----->> Playlist

That being said, I've decided that I need a third entity: Playlist Item.

A Playlist Item has an index
A Playlist Item can only have a relationship with one Video entity and one Playlist entity

And so, this causes the original specification to be revised...

A Video can have many Playlist Items
A Playlist can have many Playlist Items, but each Playlist Item has a unique index
A Playlist's Playlist Items are ordered using the index attribute

Video <---->> Playlist Item <<----> Playlist

So, the addition of the Playlist Item entity allows me to have many-to-many relationships between Video and Playlist and still maintain ordered lists. Adding this third entity however adds complexity to the overall design.

I am wondering if it is wise to hide that complexity managing the Playlist Item objects in the Video and Playlist implementations.

Video

@interface Video : NSManagedObject

@property (strong, nonatomic) NSSet *playlists; // Custom accessor; Transient attribute; data persisted in Playlist Item
// No declared NSSet for playlistItems

@end

Playlist

@interface Playlist: NSManagedObject

@property (nonatomic, strong) NSArray *videos; // Custom accessor...
// No declared playlistItems here either!

@end

It seems by doing this I will gain code that is better at revealing intentions.

The code smell I'm getting is that NSManagedObjects subclasses are model classes and should therefore not have any controller type glue. Furthermore it makes my Video and Playlist classes completely dependent upon the Playlist Items class. But, all of that said writing the accessor is trivial, which is why I'm considering this approach:

- (NSArray *)videos
{
    [self willAccessValueForKey:@"videos"];
    NSArray *v = [self primitiveVideos];
    [self didAccessValueForKey:@"videos"];

    if (v) {
        return v;
    }

    NSSet *pi = [self playlistItems];

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES];
    NSArray *orderedPlaylistItems = [pi sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

    NSUInteger count = [orderedPlaylistItems count];
    NSMutableArray *videos = [NSMutableArray arrayWithCapacity:count];
    for (int index = 0; index < count; index++) {
        [videos addObject:[[orderedPlaylistItems objectAtIndex:index] video]];
    }

    v = videos;
    [self setPrimitiveVideos:v];

    return v;
}

(This code is pretty rough, but you get the point, a few lines and voila! an array of video objects from the set of playlist items)

Maybe there is a design pattern or best practice that would help guide my decision?

Perhaps I'm missing something, but it seems that the Video objects don't really need to know about what playlists they belong to, do they?

A playlist is a collection of videos.  You don't need a playlist index object.  You just need an array on each playlist that keeps track of what videos are on its playlist and in what order.  A simple array does all this for you.

It seems to me that the only reason a video would need to know what playlists it belonged to is if you wanted to provide some functionality for a video to quickly find all playlists it belonged to.  And when I say this, I mean a request where it's important for this information to be returned near instantly.

Even without the video knowing any information about the playlists, your code could still iterate through every playlist asking it whether or not it contained a given video and get the answer to what all playlists the video belongs to.  This might be a little time consuming, but I think it's a rare request.

But it seems what's most likely is that a user will either want to play an individual video, or play a playlist.  The request to play all playlists that contain this particular video seems an odd one to me.


Interface to the Force.com REST API I'm implementing an interface to the Force.com REST API, with very specific ideas about which parts of the API I need. My problem is with testability of consumers of this API abstraction.

The first thing I came up with was a Gateway, one method per action:

interface SalesforceApiGateway {
    fun getLastUpdated(type: ObjectType, backTill: Duration = Duration.ofDays(1)): LastUpdated
    fun getDetails(type: ObjectType, uuid: String, fields: List<String> = emptyList()): Details

    data class LastUpdated(val error: Throwable? = null, val response: LastUpdatedResponse? = null)
    data class Details(val error: Throwable? = null, val response: DetailsResponse? = null)
}

Consumers would get an instance of this interface @Injected, so tests could easily implement the interface and pass that to the unit under test.

But adding more object types and keeping responses meaningful and statically typed became increasingly difficult. Which is why I switched to the following:

interface SalesforceApiClient: HttpClient, BackendAuthenticator<SalesforceCredentials> {}

sealed class SalesforceRequest<T>(val apiClient: SalesforceApiClient) {
    fun getLastUpdated(backTill: Duration = Duration.ofDays(1)): List<String> {
        val req: HttpGet = buildHttpRequest()
        val resp = apiClient.execute(req)
        return ObjectMapper().readValue(resp.entity.content,
            object: TypeReference<List<String>>() {})
    }

    fun getDetails(uuid: String): T {
        val req: HttpGet = buildDetailRequest(uuid)
        val resp = apiClient.execute(req)
        return ObjectMapper().readValue(resp.entity.content, getValueClass())
    }

    abstract fun getObjectType(): String
    abstract fun getFields(): List<String>
    abstract fun getValueClass(): Class<T>

    class UserRequest(api: SalesforceApiClient): SalesforceRequest<User>(api) {
        override fun getObjectType() = "USER"
        override fun getFields() = User::class.members.map { it.name }
        override fun getValueClass(): Class<User> = User::class.java
    }
}

Voila, typed responses and a set of requests you can reason about at compile time. API consumers are happy now.

But how do I test around this beast? Of course, I can mock SalesforceApiClient, which is just the sum of HttpClient and BackendAuthenticator. But I feel dirty leaking knowledge about the structure of Force.com REST responses into unit tests for users of UserRequest. This kind of feeling tells me there's something wrong my class design. How can I do better?

I haven't found a way to properly test/mock SalesforceRequest when exercising it's consumers.

What it did do was make me realize

Naming the class Request and then providing multiple "request"-like methods on it was a mistake. Each SalesforceRequest subtype was a full blown API provider.
Following from 1, I took the generics approach to make the SalesforceApiGateway type-safe (which was the initial driver for the request classes).

I ended up with the following interface:

interface SalesforceObject {
    val Id: String
    val CreatedById: String
    val LastModifiedDate: Instant
}

interface SalesforceApiGateway {
    val API_VERSION: String
    val MAX_RECENT_DAYS: Duration

    fun <T: SalesforceObject> getLastUpdated(type: KClass<T>, backTill: Duration = Duration.ofDays(1)): LastUpdated

    fun <T: SalesforceObject> getLastUpdated(type: KClass<T>, backTill: Instant): LastUpdated
            = getLastUpdated(type, Duration.between(backTill, Instant.now(Clock.systemUTC())))

    fun <T: SalesforceObject> getDetails(type: KClass<T>, uuid: String, fields: List<String> = type.members.map { it.name }): Details<T>

    data class LastUpdatedResponse(val ids: List<String> = emptyList(),
                                   val latestDateCovered: String = ISO_DATES.format(ZonedDateTime.now(Clock.systemUTC())))
    data class LastUpdated(val error: Throwable? = null, val response: LastUpdatedResponse? = null)

    data class DetailsResponse<T>(val wrapped: T)
    data class Details<T>(val error: Throwable? = null, val response: DetailsResponse<T>? = null)
    companion object {
        val ISO_DATES = DateTimeFormatter.ISO_OFFSET_DATE_TIME
    }
}

The upside is that I can now use Kotlin's awesome defaulted parameters to allow my gateway consumers to not care about fields they want to select, but advanced, future uses can still override that choice. It also allows me to express that I want gateway implementations to be in charge of properly de-serializing responses to the correct requested type. Plus, I still get to keep my interface, so testing is trivial by implementing a dummy.

There's several things that were suggested in the process:

Use the Result class to model success/failure instead of custom "result" classes. I wasn't able to wrap my head around their model of creating a result from an existing basic type (like my List<String>). Maybe next time.
Using Retrofit (thanks orangy for mentioning that!) to generate the code for the gateway. However, Jake Wharton confirmed Retrofit won't allow me to template my method, resulting n methods per SalesforceObject. I tried it and just copy and pasting my methods made my skin crawl.


Array Duplicate Item Filtering by Element Value I'm learning to code PHP and gave myself a challenge: Filter array data by matching a specific element value for duplication. I went through it logically on paper then wrote code and it worked on the first try :) But I bet it is the most inefficient way, so to learn I would like to compare it against what others would do. Below is my code. The array is just a few elements with keys like name and id. My result is a list of only items with unique ids from an array with many duplicate ids but different names.

Also, part of the challenge was testing XML, JSON, and Arrays so I made the original data XML and used SimpleXML but made a copy of that data as a PHP array and worked with that to do filtering (XPath challenge next).

Thanks for looking and any suggested improvements that I can learn from.

//$items is a SimpleXML array of items with name and id elements with many duplicate ids but different names.

//first iteration of id collection
$ids = array();
$countedIds = array();
//convert simplexml array $items to normal array (copy)
$itemsArray = json_decode(json_encode($items), TRUE);
foreach ($itemsArray as $idItem)
{
    //collection all ids
    $ids[] = $idItem['id'];
}
//count number of each id and store in separate array
$countedIds = array_count_values($ids);
#print_r($countedIds);

//start cleaning out duplicates
foreach($itemsArray as $key => &$item)
{
    //clear any whitespace (thanks internets)
    #$thisid = trim($item->id); //if using simplexml
    $thisid = trim($item['id']);
    //check if this id is duplicated (multiple copies) in array
    if($countedIds[$thisid] >1)
    {
        echo $thisid . "item has duplicates (" . $countedIds[$thisid] . ")
";
        //add found dupes to separate array
        $dupes[] = $thisid;
        //remove this item from $itemsArray and original $items simplexml array
        unset($itemsArray[$key]);
        unset($items[$key]);
        echo "removed element index " . $key . $item . "

";
        //remove this id from $ids array
        unset($ids[$key]);
        //clear out the counted ids
        unset($countedIds);
        //make a fresh array for counting ids
        $countedIds = array();
        //get updated id count
        $countedIds = array_count_values($ids);

        //test simplexml unset?
        #unset($sxe->$this->channel->item);
    }
}
//review results
print_r($countedIds);
print_r($ids);
print_r($dupes);
print_r($itemsArray);
print_r($items);

If the sole purpose was to have a resultant array of objects that did not have a duplicated id then I would be tempted with the below:

// Indexes keyed by item id
$indexes = array();

// Cast to array of objects
$items = current((array)$items);

foreach ($items as $index => $item) {
    $id = ((array)$item)['id'];

    if (isset($indexes[$id])) {
        // Unset this item
        unset($items[$index]);
        // Unset the original instance
        unset($items[$indexes[$id]]);
    } else {
        $indexes[$id] = $index;
    }
}

// List names of items that doesn't have an id that is duplicated
foreach ($items as $item) {
    // Still have original SimpleXml object to work with
    echo $item->name . "\n";
}


Math game with 'hard' and easy questions In my competition, I was to create a game that asked at least 5 easy questions, and up to ten hard questions, summing fifteen questions. Please review my code, especially how I formatted it with the class. ALL criticism is appreciated.

#SkillsUSA Computer Programming Problem Number One - Math Challenge

import random
import time

class Math_game(object):

    def __init__(self):

        print("Welcome to the Official Math Game of SkillsUSA!\nYou will have at least five relatively simple questions,\nand up to ten difficult ones.\nGood luck!")
        time.sleep(5)
        x = 3
        while x != 0:
            print("Starting in ",x,"...")
            time.sleep(1)
            x -= 1

        #Above we can see a cheesy intro with the time countdown.

        self.tried = 0
        self.correct = 0
        self.easyQuestionsAsked = 0
        self.numCorrect = -1

        #The __init__ method is simply the initiating object. When an object of the class is made, this method/function is automatically called.
        #By automatically declaring all of these objects, we can start keeping track of the number of questions attempted, correct, etc.

    def prob(self, maximum, operators):

        self.maximum = maximum
        self.operators = operators
        self.num_a, self.num_b = [random.randint(1,self.maximum),random.randint(1,self.maximum)]

        #In the above line, we are able to declare two variable values in one, efficient line.

        operators = ['+','-','*']

        self.operator = operators[random.randint(0,int(self.operators))]

        #The operators parameter of the "prob" method is used to access the list of operators, If only two operators are available to use, a random number
        #chooses between + or -. Otherwise, it will choose between + or - or *.

        if self.maximum < 50:

            if self.num_a <= self.num_b:
                self.num_a = random.randint(1,self.maximum)

        #If it is an easy problem and we are not allowed to use negatives, and the first number is smaller than the second, just default to 25.

        if self.operator== '+':
            self.answer = self.num_a + self.num_b
        elif self.operator == '-':
            self.answer = self.num_a - self.num_b
        else:
            self.num_a, self.num_b = random.randint(-12,12), random.randint(-12,12)
            # If we are using the multiplication operator, set the numbers to max out at 12, or be as low as -12.
            self.answer = self.num_a * self.num_b

        #Above, we use the parameter, userself.answer, and see if the self.answer is correct. Below, we the returned value is whether the user correctly self.answered the question.

        return self.num_a, self.operator, self.num_b

    def isCorrect(self, userInput):

        self.userInput = userInput
        #Simply returning whether the user answer was correct or not.
        return self.userInput == self.answer

game = Math_game()
#Make an object of the  Math_game class.
while game.tried <= 15:
    if game.easyQuestionsAsked <= 5:
        game.prob(25,1)
        game.easyQuestionsAsked += 1
        #While we have not asked 15 questions yet, and while there have been less than 5 easy questions asked, ask another easy question.
    else:
        game.prob(50,2)
    userAnswer = int(input("Problem:  {0} {1} {2}  :  ".format(game.num_a, game.operator, game.num_b)))
    #If we do not HAVE to ask an easy question, feel free to ask a hard one.

    if game.isCorrect(userAnswer):
        game.numCorrect += 1
        print("Right!")
    else:
        print("Wrong!")
    game.tried += 1
    #Accumalting questions asked.

if game.numCorrect > 11:
    print("Great job! ({0}/15)".format(game.numCorrect))
else:
    print("Try again for a better score! ({0}/15)".format(game.numCorrect))
print("This window will automatically close in ten seconds.")

time.sleep(10)
quit()

A few notes touching upon encapsulation and responsibilities:

    def __init__(self):

        print("Welcome to the Official Math Game of SkillsUSA!\nYou will have at least five relatively simple questions,\nand up to ten difficult ones.\nGood luck!")
        time.sleep(5)
        x = 3
        while x != 0:
            print("Starting in ",x,"...")
            time.sleep(1)
            x -= 1

the initialization method of a class should be responsible to get the object into a workable state. It's supposed to initialize any required fields and then stop there.

This one here doesn't. Whenever some code creates a "new instance" of Math_game you'll get this welcome message, your thread will be locked up for 8 seconds, all this is stuff you don't want to have in your initializer. Only after that you get to the actually interesting stuff, namely initializing your fields.

Additionally this method is missing a docstring (that seems to be rather unconventional on __init__ methods, thanks to Gareth Rees) and instead has some non-parsable comments, which are suited to explain the code to python beginners (like I am one :D). You might prefer to add the docstring on class-level as suggested by Gareth.

That being said, your "cheesy intro" should be a separate method, taking a few parameters.

Next thing is: whenever a module gets imported in python, code in there is executed. This includes your current code. You definitely shouldn't do that.

The simple and idiomatic fix for that is:

if __name__ == '__main__':

For more information on this construct, read up at stackoverflow

Overall your class could use more "API documentation". As of now if I wanted to use this from somewhere else, as a minigame or something, I'd have to jump through some hoops (with the problematic __init__ only being the first). This includes the less convenient name prob. This method takes two arguments and if I didn't have the source code, I'd have no clue what they were.

The first step to fixing this is getting a proper docstring in there. The next thing is to extract some responsibilities to clarify your design.

You should not return the solution when generating the problem. Instead you should store it somewhere in the class instead, so it can be checked properly with isCorrect.

While we're there: Your naming is sometimes a little off. You're violating the official conventions in a few places isCorrect being one of them. Methods, as well as variables and fields are supposed to be named in snake_case, Classes are supposed to be named in CapWords (without underscores)...

There's also tools that check the PEP-8 conventions for you, one of them being the IDE pycharm. Make use of these tools to simplify your life when coding ;)


Calculating nth power of x I have written this code which precisely calculates the nth power of x by a recursive method.

I compared my program with Java's pow(double, double) function, and most of the time I get comparable results, although sometimes pow is slow and the other times this program is slow.

Can anyone suggest any improvements or the way Java implements this function?

public double power(long x, int n) {

    double pow = 1L;
    if(n==0)
        return 1;
    if (n == 1)
        return x;
    if(n%2==0){
        pow = power(x, n / 2);
        return pow * pow;
    }
    else{
        pow = power(x,n/2);
        return pow * pow * x;
    }
}

The Java implementation of pow is implemented for double, rather than long, and probably uses logarithms. This makes direct comparison difficult - pow should have a more or less constant factor time, but double precision arithmetic can be expensive.

Otherwise, it seems reasonably straightforward.

If you're looking for speed, did you try using bit shifts rather than divides? It's possible that the compiler optimizes a divide by 2 to a bit shift, put possibly not. Though, the bit shift is probably somewhat less readable than the divide - and it is possible to be too clever.


Form for choosing settings for a game I've created a form to choose the settings. These settings are automatically saved in a file from the game client in this form:

["Setting"] = {
    ["track"] = "Water Shield",
    ["duration"] = {
        ["minimum"] = {
            ["enabled"] = 1,
            ["value"] = 50,
        },
        ["maximum"] = {
        },
    },
    ["stack"] = {
        ["minimum"] = {
        },
        ["maximum"] = {
            ["enabled"] = 1,
            ["value"] = 2,
        },
    },
}

I had previously asked a similar question on how to save the data, but now to load the data I created this function:

function loadSettings()
    local options = { 'duration', 'stack' }
    for i=1, #options do
        local option = options[i]

        if not db[option] then
            db[option] = { minimum = {}, maximum = {} }
        end

            local enabled
            local value

            enabled = db[option].minimum.enabled
            if (enabled) then _G["min"..option].cbutton:SetChecked(1) else _G["min"..option].cbutton:SetChecked(0) end
            value = db[option].minimum.value
            if (value) then _G["min"..option].ebox:SetText(value) else _G["min"..option].ebox:SetText("\00") end

            enabled = db[option].maximum.enabled
            if (enabled) then _G["max"..option].cbutton:SetChecked(1) else _G["max"..option].cbutton:SetChecked(0) end
            value = db[option].maximum.value
            if (value) then _G["max"..option].ebox:SetText(value) else _G["max"..option].ebox:SetText("\00") end

    end
end

Where

db = The "Setting" table
SetChecked(enable) = True to check the button; false to uncheck (boolean)
SetText("text") = Text to be placed in the edit box (string)

Could you help me to make the code less repetitive and more clean and elegant?

On a cursory glance, you can change the statement:

if (enabled) then _G["min"..option].cbutton:SetChecked(1) else _G["min"..option].cbutton:SetChecked(0) end

to

_G["min"..option].cbutton:SetChecked( enabled and 1 or 0 )


Swift permutations of the digits of an Integer I want to return all of the permutations of an integer in Swift.

var outputArray = [[Int]]()
func perms ( _ input: [Int], _ output: [Int]) {
    if input.count == 0 {
        outputArray.append( [ Int( output.map{  String($0) }.joined() )! ] )
    }
    else {
        for i in 0..<input.count {
            let current = [input[i]]
            let before = Array( input [0..<i] )
            let after = Array( input [(i + 1) ..< input.count] )
            perms(before + after, current + output)
        }
    }
}

func permsOfInteger(_ input: Int) -> [[Int]] {
    var inp = input
    var inpArray = [Int]()
    while inp > 0 {
        inpArray.append(inp % 10)
        inp = inp / 10
    }
    perms(inpArray, [])
    return (outputArray)
}

( permsOfInteger(5432) )

I don't want to switch the algorithm (I'm aware of Heap's algorithm) but rather improve my implementation here. Any advice?

My main point of criticism is that the code uses a global variable to share data between the main function and the auxiliary function. That is problematic for various reasons:

The variable must be reset before the function can be called again.
The variable can be modified from outside of your function, causing
wrong results.
The function is not thread-safe.

Example:

print(permsOfInteger(12)) // [[12], [21]]
print(permsOfInteger(12)) // [[12], [21], [12], [21]]

So

var outputArray = [[Int]]()

should be a local variable of func permsOfInteger(). You can then pass it as an “inout argument” to the helper function func perms(), or make that helper function a nested function of the main function:

func permsOfInteger(_ input: Int) -> [[Int]] {

    var outputArray = [[Int]]()

    func perms (_ input: [Int], _ output: [Int]) {
        // ... adds something to `outputArray` ...
    }

    // ...
    perms(inpArray, [])
    return (outputArray)
}

Why is the return type a nested array where each “integer permutation” is wrapped into a single-element array? Returning a simple array of integers seems more natural to me, and would be more efficient:

func permsOfInteger(_ input: Int) -> [Int] {
    // ...
}

print(permsOfInteger(12)) // [12, 21]

As @janos already said, combining the digits to an integer should be done in “pure maths” instead of using string operations. This can be done with reduce(), for example:

let digits = [1, 2, 3]
let number = digits.reduce(0, { $0 * 10 + $1 })
print(number) // 123

An [UInt8] array would be sufficient to store the decimal digits and save some memory. Here is a possible implementation as a computed property and custom initializer of the Int type:

extension Int {
    var decimalDigits: [UInt8] {
        precondition(self >= 0, "Value must not be negative")
        var digits = [UInt8]()
        var n = self
        while n > 0 {
            digits.append(UInt8(n % 10))
            n /= 10
        }
        return digits
    }

    init(decimalDigits: [UInt8]) {
        self = decimalDigits.reduce(0, { $0 * 10 + Int($1) })
    }
}

The slicing

let before = Array(input[0..<i])
let after = Array(input[(i + 1) ..< input.count])

can be slightly shorted with partial ranges:

let before = Array(input[..<i])
let after = Array(input[(i + 1)...])

An alternative would be to remove the current element from the input array:

var remaining = input
let current = [remaining.remove(at: i)]
perms(remaining, current + output)

Instead of if input.count == 0 you can test if input.isEmpty – it does not make a difference for arrays, but can be more efficient for arbitrary collections, where determining the count requires a traversal of the entire collection.

For the same reason you might want to replace

for i in 0..<input.count { ... }

by

for i in input.indices { ... }

since collection indices are not always zero based.

Finally, I would suggest some more descriptive variable names and argument names. Putting it all together, the function could look like this:

func permutations(of number: Int) -> [Int] {

    var permutations = [Int]()

    func addPermutations(of digits: [UInt8], withSuffix suffix: [UInt8]) {
        if digits.isEmpty {
            permutations.append( Int(decimalDigits: suffix) )
        } else {
            for i in digits.indices {
                var remainingDigits = digits
                let currentDigit = [remainingDigits.remove(at: i)]
                addPermutations(of: remainingDigits, withSuffix: currentDigit + suffix)
            }
        }
    }

    addPermutations(of: number.decimalDigits, withSuffix: [])
    return (permutations)
}

print(permutations(of: 123))
// [123, 213, 132, 312, 231, 321]


concatenation of HTML from return functions My controller is looking something like this.

Each of the methods called generate some HTML. The concatenated HTML variable gives the final render of the page

Is there a better way to generate my HTML to render coming from different functions:

 $html = $renderer->render($clear_form);
 $html .= $this->render_preview();
 $config = \Drupal::config('amu_import_ldap.settings');
 if (null != $config) {
   $submits = $config->get('import_submits');
   $html .= $this->render_ldap_imports($submits);
 }
 $build = [
  '#markup' => Markup::create("
            {$html}
        "),
];
return $build;

Use a template engine like Twig, Plates or Blade.

You should have base layouts, partials and templates.


First stage of a complex calculator implementation in C++ The following code shows the primary data structure of my calculator.

Header file contents :- theCalc.hpp

#ifndef THECALC_H_
#define THECALC_H_

#include "iostream"
#include "utility"
#include "string"
#include "cstring"
#include "cmath"

using namespace std;

class theCalc
{

protected :
    pair <float, float> inputNumberPair;
    pair <float, float> outputNumberPair;
    float flFirstNumber;
    float flSecondNumber;

public :
    void getTheInputs (string firstNumber, string secondNumber);
};

#endif

Implementation file content :- theCode.cpp

#include "theCalc.h"

void theCalc::getTheInputs(string firstNumber, string secondNumber)
{
    flFirstNumber = stof (firstNumber);
    if (!secondNumber.empty())
    {
    flSecondNumber = stof (secondNumber);
    }
    inputNumberPair = make_pair(flFirstNumber, flSecondNumber);

    cout << inputNumberPair.first << endl;
    if (!secondNumber.empty())
        {
    cout << inputNumberPair.second << endl;
        }
}

Someone to go through the code and please suggest me whether I am doing good in OOP and data structure implementation. Please suggest me is my methodologies good as a robust algorithm or I am making things complicated unnecessarily.

I am now in the learning process and need my code to be reviewed as I am a beginner.

Please take a look at the shared github the following link for the overall code.

https://github.com/arviCV/bHive2

Never write using namespace ... in a header. You're forcing users of your library to do something they almost certainly don't want to do.

Don't pass strings by value. Pass them by const reference (to avoid making copies) or pass them as std::(C++17) (or boost::) string_view. This also doesn't force the caller to use an actual std::string, a string_view being easily constructed even from a char buffer.

Don't mix responsibilities, separate user input from the rest of the code. Using std::cout in your class quickly becomes wrong when you change the user interface to a graphical one, or if the code ends up in a server application that only responds to network requests.


Enhancing PHP realpath($path); PHP realpath($path); is insufficient for some cases since it returns false on paths that dont exist on a file system.

I need a function that extends realpath($path); to return even path that does not exist yet. Such function would be used for keeping a user within his filesystem directory and/or restricting modifications to some directories and files.

function DesiredRealPath($path_string) {
    $desired_path = explode("/", str_replace("\\", "/", $path_string)); // convert back slashes to front slashes and create array of desired directories
    $real_path = explode("/", str_replace("\\", "/", realpath("."))); // convert back slashes to front slashes and create array of actual directories
    if(mb_substr($path_string, 0, 1) == "/" || mb_substr($path_string, 0, 1) == "\\") { // if path string begins with a slash, slice all actual directories except for root
        $real_path = array_slice($real_path, 0, 1); // "/" points to root directory
    }
    foreach ($desired_path as $desired_element) {
        switch ($desired_element) {
            case "":
                break;
            case ".":
                break;
            case "..": // remove last element of actual directories if array has at least 2 directories left
                if(count($real_path) >= 2) {
                    array_pop($real_path);
                }
                break;
            default: // push desired directory into actual directories
                array_push($real_path, $desired_element);
                break;
        }
    }
    return implode("/", $real_path); // put array of actual directories into a string
}

So far I have tested on both Windows and Linux, this function has determined precise directory even non-existant ones.

My question is, whether this function has any flaws or security vulnerabilities?

Because you’re allowing path traversal, your function doesn’t restrict even system paths. To exemplify the danger of your function, check examples below, where realpath('.') points to /web/users/alice:

DesiredRealPath('files/photos'); # It returns `/web/users/alice/files/photos` and this is OK
DesiredRealPath('/etc/passwd'); # It returns `/etc/passwd` and it’s very BAD
DesiredRealPath('../bob/photos'); # It returns `/web/users/bob/photos` and this is also BAD

To protect against Path Traversal Attack, you should ignore “dot” directories. For example, consider this function:

function basepath($rel_path)
{
    $base = str_replace('\\', '/', realpath('.'));
    $parts = explode('/', str_replace('\\', '/', $rel_path));

    foreach ($parts as $part) {
        if ($part && $part != '.' && $part != '..') {
            $base .= "/{$part}";
        }
    }
    return $base;
}

Testing the same paths as in the example above, no one escapes the /web/users/alice directory:

basepath('files/photos'); # /web/users/alice/files/photos
basepath('/etc/passwd'); # /web/users/alice/etc/passwd
basepath('../bob/photos'); # /web/users/alice/bob/photos

For better security, make sure to configure the open_basedir directive correctly.

By the way, if you have a script for which you want prevent path traversal, add the following at the top of your script:

ini_set('open_basedir', __DIR__);


jQuery toggle script I have been working on a toggle script, but I find myself repeating my code.  Is there a way of combining it all?

jQuery(document).ready(function($) {
    var topContainer = $("#alles");
    var topButton = $(".abutton");
    topButton.click(function() {
        topContainer.slideToggle(1200, 'easeInOutQuart');
        $(".hideable").slideToggle(1200, 'easeInOutQuart');
    });

    var topContainer2 = $("#voorbeelden");
    var topButton2 = $(".bbutton");
    topButton2.click(function() {
        topContainer2.slideToggle(1200, 'easeInOutQuart');
        $(".hideable").slideToggle(1200, 'easeInOutQuart');
    });

    var topContainer3 = $("#contact");
    var topButton3 = $(".cbutton");
    topButton3.click(function() {
        topContainer3.slideToggle(1200, 'easeInOutQuart');
         $(".hideable").slideToggle(1200, 'easeInOutQuart');
    });
});
.container {
    display:block;
    width:500px;
    margin:0 auto;
}

.hideable {
 width: 500px;
 margin: 0 auto;
}

#alles {
    float:left;
    width:500px;
    height:500px;
    background:#ff4000;
}

#voorbeelden {
    float:left;
    width:500px;
    height:100px;
    border-top:1px solid #ddd;
    background:#cc6600;
}

#contact {
    float:left;
    width:500px;
    height:100px;
    border-top:1px solid #ddd;
    background:#bb3300;
}

.toggleable {
    display:none;
}

stuff

more stuff

a

     stuff

b

                    stuff

c

                    stuff

You can either write a method that is bound to the global scope and takes two arguments, the onClick element and the slideToggle element, and does just what you want (without writing redundant code).

function bindToggleTwo(cElem, tElem) {
   $(cElem).click(function() {
      $(tElem).slideToggle(1200, 'easeInOutQuart');
      $(".hideable").slideToggle(1200, 'easeInOutQuart');
   });
}

jQuery(document).ready(function($) {
    bindToggleTwo("#alles", ".abutton");
    bindToggleTwo("#voorbeelden", ".bbutton");
    bindToggleTwo("#contact", ".cbutton");
});

Alternatively, you could write a jQuery function that is called on a jQuery object to do the very same. Basically this is a function that expects to be scoped such that this is  a jQuery object. Anyway, both of these methods work, and will simplify your code. :)

jQuery.fn.bindToggleTwo = function(tElem) {
  $(this[0]).click(function() {
     $(tElem).slideToggle(1200, 'easeInOutQuart');
     $(".hideable").slideToggle(1200, 'easeInOutQuart');
  });
}

jQuery(document).ready(function($) {
    $("#alles").bindToggleTwo(".abutton");
    $("#voorbeelden").bindToggleTwo(".bbutton");
    $("#contact").bindToggleTwo(".cbutton");
});