Redirecting HTTP requests to HTTPS I have read a lot and spent a lot of hours trying to reach the right way to set a good htaccess in order to redirect an HTTP site to HTTPS.

There are a lot of tutorials on the Internet, even on Stack Overflow, but some of them seem to be outdated and don't meet good SEO practices.

The scenario is the following one:

My site has Cloudflare enabled
My site has a valid SSL on server-side

The current htaccess of my site:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^MYSITE\.cl$
RewriteRule ^(.*) http://www.MYSITE.cl/$1 [R=301]
RewriteRule ^/?find$ find.php [L]
RewriteRule ^/?do$   do.php   [L]
ErrorDocument 404 /404.html
Options -Indexes

and I want to change .htaccess in order to keep my good SEO rank on Google, use the HTTPS and keep the .WWW:

#OLD PART
RewriteEngine On
RewriteBase /

# Non-www to www (NEW PART)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.%{HTTP_HOST}/$1 [R=301,L]

# Non-SSL to SSL (NEW PART)
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]

#OLD PART AGAIN
RewriteRule ^/?find$ find.php [L]
RewriteRule ^/?do$   do.php   [L]
ErrorDocument 404 /404.html
Options -Indexes

Will this work like a charm? Do you have a better idea? Does my code have any redundancy? I think that I must set Cloudflare SSL parameters to FULL SSL (STRICT). Is that right?

Since your actual machines are being handled by the Cloudflare based forwarding, you can let them handle the enforced SSL and www-prefixing rules instead.

However, if you do plan on the FULL SSL feature of cloudflare, you can combine the 2 separate rules into a single one:

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

Notice that I do not rely on the $1 part of the URI, as matching (and capturing) that is just redundant.

Similarly, the next 2 rules can be combined:

RewriteRule ^/?(do|find)$ /$1.php [L]

You can chose to leave it as $1.php, but I prefer giving paths from the doc-root in my rules. It is just a personal preference.

Lastly, consider providing some gap between the Options directive and the directives provided by mod-rewrite. Again, it is another personal habit of mine; but makes it clearer to maintain large rule sets later on.


Frequency analysis based anagram checker I uploaded code solutions for some problems of the book Cracking the Coding Interview, 6th Edition to GitHub, I would like to know your rating and potential improvement of the code I wrote.

Here is the first problem of chapter 1 (anagrams):

#include <stdio.h>
#include <string.h>

/*check if one string is an anagram of another, it uses an int array
 * called alphabet to store frequencies of chars in both strings, add
 * 1 for s1 and subtract 1 for s2*/
int are_anagrams(const char *s1, const char *s2) {
    int alphabet[26] = { 0 };
    int index1, index2;
    size_t l1 = strlen(s1), l2 = strlen(s2), i;

    /*if the strings have different lengths are not anagrams */
    if (l1 != l2) return 0;

    /* count the frequencies of characters */
    for (i = 0; i < l1; ++i) {
        index1 = s1[i] - 'a';
        index2 = s2[i] - 'a';
        ++alphabet[index1];
        --alphabet[index2];
    }
    /* all the alphabet letters should be 0, otherwise the strings are not
     * anagrams */
    for (i = 0; i < 26; ++i)
        if (alphabet[i] != 0) return 0;

    return 1;
}

int main() {
    char s1[] = "aaabbbccc";
    char s2[] = "aabbaccbc";
    printf("%d\n", are_anagrams(s1, s2));
    return 0;
}

Any suggestion or advice is welcome, thanks for your time.

Avoid magic numbers, especially if they, like 26 in your code, are used repeatedly. Along the same line, keep in mind that the code only works in the "C" locale. Other locales may have alphabets of different size.
Prefer to declare variables as close to use as possible, e.g.

    for (size_t i = 0; i < l1; ++i) {
        int index1 = s1[i] - 'a';
        int index2 = s2[i] - 'a';
        ....

If the string contains non-lowercase characters, the code would do an out-of-bound access. You should ensure islower(s[i]) prior to computing indices, and ask the interviewer about what are the guarantees.
An opportunistic if (l1 != l2) return 0; is not an optimization. It still require a linear time to compute the lengths.
Along the same line, length computation is not necessary. An idiomatic C approach is to us pointers:

while ((ch = *s++) != 0)

The bullets above suggest splitting the loop into two:

while ((ch = *s1++) != 0) {
    if (islower(ch)) {
        alphabet[ch - 'a']++;
    }
}

while ((ch = *s2++) != 0) {
    if (islower(ch)) {
        alphabet[ch - 'a']--;
    }
}

Now, a DRY principle require factoring this loops into a function:

static void count_frequencies(char * s, int * alphabet, int addend) {
    while ((ch = *s++) != 0) {
        if (islower(ch)) {
            alphabet[ch - 'a'] += addend;
        }
    }
}

....
    count_frequencies(s1, alphabet, 1);
    count_frequencies(s2, alphabet, -1);

As a perk benefit, see how the /* count the frequencies of characters */ disappears.
For a very long string the integer in alphabet may overflow. Could be a nitpick, but could also be a failure, depending on the interviewer.


Best way to use an array that is returned from a function immediately in PHP I have a function that returns an array and I want to check that a certain value is not set in the array.

function testFunction() {
    return array('key' => 404)
}

if (testFunction()['key'] < 404) {
    // stay calm and carry on
}
else {
    // uh oh
}

I understand that the above will not work in php 5.3 (or anything below), however, I'd like to know what I should do in the above case. That is - what should I call the temporary array I create for the if statement? Or is there another way of dealing with this situation?

The following is what I would roughly do currently:

function testFunction() {
    return array('key' => 404)
}

$test_array = testFunction();

if ($test_array['key'] < 404) {
    // stay calm and carry on
}
else {
    // uh oh
}

Is this an acceptable thing to do?

So, .. you want to simply check whether a certain key in an array is set to a certain value.

You can't do this directly on the function call because older PHP versions don't support array dereferencing. You are right when saying you'll need an intermediate variable.

The only question remaining is what to name it. Considering that the variable will probably be situated in a really small scope, don't worry about it too much. There is a saying which says, the bigger the scope, the bigger the name. You could just name it $list.

Old replies:

  Your code does something else as what
  you describe? If you want to see
  whether a given value is present in
  the array, use in_array().

  UPDATE:

  I believe I understand what you are
  trying to accomplish now. You just
  want to see whether the key is set?

  array_key_exists()

  PHP has got a pretty good online API,
  be sure to check it for existing
  implementations when looking for a
  solution.


Comparing a list of known animals to a master list of animals This script works for what I need it to do, but I'm not all that proficient with Python yet, so I was wondering if any of the more seasoned python veterans would go about it differently.

import os
import string
import re

'''This script will take in an input list of strictly stellar IDs, and compare those IDs to a master file
with IDs AND photometric data. It will then write to a file, the lines from the master file that correspond to the known IDs
in the IDs list.'''

def pullIDs(file_input):
    '''Pulls Mon-IDs from input file.'''
    arrayID = []
    with open(file_input,'rU') as user_file:
        for line in user_file:
            arrayID.append(re.findall('Mon\-\d{6}',line))
    return arrayID

def pullLines(file_input):
    '''Creates an array component for each
    line in the input file.'''
    arrayLines = []
    with open(file_input,'rU') as info:
        for item in info:
            item.split
            arrayLines.append(item)
    return arrayLines

def getHeader(file_input):
    '''Assuming the file-header begins with a '#',
    this will pull the header line.'''
    with open(file_input,'rU') as title:
        for line in title:
            if line.startswith('#'):
                header = line
    return header

known_stars = raw_input("Enter your ID list: ")
master_list = raw_input("Enter your master list: ")
results_list = raw_input("Name your output file: ")

with open(results_list,"w+") as output:
    output.write(getHeader(master_list))
    for item in pullIDs(known_stars):
        for items in pullLines(master_list):
            if items[:10] in item:
                output.write(items)

output_fileSIZE = os.stat(results_list).st_size
if output_fileSIZE > 0:
    print "\nYour output file has been written to.\n"
else:
    print "\nThere was an error writing to your file.\n"

This essentially takes a list of known animals, say, cat and dog, and compares that list to a master list of animals and their respective information.

For example:

cat female 2 gray playful
dog male 9 black aggressive
giraffe male 12 tall hungry
elephant male 33 gray lonely
etc.

By creating two arrays for both lists, it searches for an animal that exists in both files and, once found, prints all of the more in-depth results from the 'master list' to a file.

So my file would look like this:

cat female 2 gray playful
dog male 9 black aggressive

because I only had a 'known list' of cats and dogs.

I'm just looking for tips on how to make this script better.  It also prints a header for the column information.

This is the sort of thing that Python is really good at.  Your code seems like it functions, but it will be very inefficient for large data sets. For each input value you have to check every line in the the master list -- and the way you have it set up here you're going to read the master list off disk for each input value as well, so it will be really slow.

The first step obvious fix is to load the master list into memory and keep it around for the duration of a session.  This is a fairly simple change to your existing code.  First, change your pull_lines so it returns a dictionary instead of a list:

def pullLines(file_input):
    '''returns a dictionary of the entries in <file_input> keyed by the first item in each line'''
    master_dict = {}
    with open(file_input,'rU') as info:
        for eachline in info.readlines():
            tokens = eachline.split()
            master_dict[tokens[0]] = tokens[1:]

Then, you move pull lines out of the inner loop:

lookup = pull_lines(path_to_file)
with open(results_list,"w+") as output:
    output.write(getHeader(master_list))
    for item in pullIDs(known_stars):
        if item in lookup:
            output.write(lookup[item])

This has a couple of advantages

1) not hitting the disk for every query will be much faster

2) the dictionary lookup faction is much faster than straight for loop comparison, since the dictionary uses hashed values instead of more expensive string compares.

As an aside, you should look into readlines, which the usual pythonic way of reading text files with info on lines.

For the longer term this is a great application for Python's built in database functionality (with the sqllite module). You could convert your existing text files into a sqllite database and then your lookups can be much more flexible and precise ('find spectrum and power for stars with id > X and < Y' sort of thing).  You probably also want to set this file up so you could call it from the command line, which would involve using the argparse module to grab command line arguments and out them into known_stars, master_list and output_file


Finding as many perfect numbers as possible I have tried to make a perfect number finder as efficient as possible in python. If anyone has any things I can add to make it more efficient or any problems with my code please say.

def is_prime(num):
    if num <= 1: return False
    elif num <= 3: return True
    elif num % 2 == 0 or num % 3 == 0: return False
    i = 5
    while i * i <= num:
        if num % i == 0 or num % (i + 2) == 0:
            return False
        i += 6
    return True

def is_mersenne_prime(prime, mersenne_prime):
    s = 4
    for i in range(prime - 2):
        s = (s*s - 2) % mersenne_prime
    if s == 0: return True
    else: return False

def calculate_perfects():
    print(6)
    prime = 3
    while True:
        if is_mersenne_prime(prime, 2**prime-1):
            print(2**(2*prime-1)-2**(prime-1))
        while True:
            prime += 2
            if is_prime(prime):
                break

calculate_perfects()

The biggest improvement to this code is to use a prime generator that uses an efficient sieve. I will use the one here in my answer, as it is really fast.

from itertools import count
                                     # ideone.com/aVndFM
def prime_sieve():                   # postponed sieve, by Will Ness
    yield 2; yield 3; yield 5; yield 7;  # original code David Eppstein,
    sieve = {}                           #   Alex Martelli, ActiveState Recipe 2002
    ps = prime_sieve()               # a separate base Primes Supply:
    p = next(ps) and next(ps)            # (3) a Prime to add to dict
    q = p*p                              # (9) its sQuare
    for c in count(9,2):                 # the Candidate
        if c in sieve:               # c's a multiple of some base prime
            s = sieve.pop(c)         #     i.e. a composite ; or
        elif c < q:
             yield c                 # a prime
             continue
        else:   # (c==q):            # or the next base prime's square:
            s=count(q+2*p,2*p)       #    (9+6, by 6 : 15,21,27,33,...)
            p=next(ps)               #    (5)
            q=p*p                    #    (25)
        for m in s:                  # the next multiple
            if m not in sieve:       # no duplicates
                break
        sieve[m] = s                 # original test entry: ideone.com/WFv4f

This function gives two advantages: first, it is much more efficient, but it also makes the rest of the logic easier. Instead of going through odd numbers, testing if they are prime, and if they are using them, the logic becomes simply

def calculate_perfects():
    yield 6
    primes = prime_sieve()
    for prime in primes:
        if is_mersenne_prime(prime):
            yield 2**(2*prime-1)-2**(prime-1)

This is not a lot faster because almost all of the time is spent in is_mersenne_prime, but it is cleaner and about 1% faster.

If we want actually faster performance, however, we need to look at is_mersenne_prime. Profiling reveals that 25% of the time is spent in the for i in range(prime-2) line. This is unfortunate, as there is very little to do to speed this up. However, the other 75% is in s = (s*s - 2) % mersenne_prime. While this initially appears to be a dead end, it isn't quite. It is probably obvious that the expensive operation here is the mod call, and thanks to some number theorists much smarter than me, it turns out that k % 2^n-1 is the same as k & 2^n + k>>n mod n. Since this only uses bitwise opps, it is much faster. below is an implementation.

def mod_mersenne(n, prime, mersenne_prime):
    while n > mersenne_prime:
        n = (n & mersenne_prime) + (n >> prime)
    if n == mersenne_prime:
        return 0
    return n

if we call this in is_mersenne_prime, it is over 3x as fast as before. Here is the updated is_mersenne_prime code

def is_mersenne_prime(prime):
    mersenne_prime = 2**prime - 1
    s = 4
    for _ in range(prime - 2):
        s = mod_mersenne((s*s - 2), prime, mersenne_prime)
    return s == 0

On my computer this takes 5.2 instead of 16.4 seconds to generate the first 16 perfect numbers.

The next improvement we can get comes from using multiple processes. Each time is_mersenne_prime is run, it is run with information that doesn't depend on any other run. As such, we can test several numbers at a time. Here is the code that does this.

from itertools import count, compress
from multiprocessing import Pool

def calculate_perfects():
    yield 6
    primes = prime_sieve()

    pool = Pool(processes=8)
    while True:
        next_primes = [next(primes) for _ in range(8)]
        is_mersenne = pool.map(is_mersenne_prime, next_primes)
        for prime in compress(next_primes, is_mersenne):
            yield 2**(2*prime-1)-2**(prime-1)

This code is a little uglier, two lines longer, but can calculate the first 20 mersenne primes in 2.3 seconds (1.5 on pypy3)

More speedups can be found by not running the test if 2**prime-1 has an easily findable small factor. Such factors must take the form 2*k*prime+1, and factor in (1, 7) mod(8).factor will be in (1,7) at specific points depending on whether prime=4n+1 or 4n-1. The following code checks for these factors, and is a good first check before Lucas-Lehrer

def has_small_factor(prime, limit):
    """ Does 2**prime-1 have a factor less than 2*prime*limit? """
    step = 2 * prime
    if prime % 4 == 1:
        wheel = cycle((0,0,1,1))
    else:
        wheel = cycle((1,0,0,1))
    for factor in compress(range(1 + step, step*int(limit), step), wheel):
        if factor%15 in (3, 5, 9):
            continue
        if pow(2, prime, factor)-1 in (0, factor):
            return True
    return False

At this point the slowest thing about our code is that we have to multiply large numbers together. The good news is that gmpy2 has a library that makes this faster. Importing it and modifying the code to be mersenne_prime = 2**mpz(prime) -1, yields a 3x speedup (although it doesn't work well with pypy). At this point my laptop can find the first 24 perfect numbers in 33 seconds.


PHP script to generate hreflang tags I'm currently working on a website which provides content to users based on their region. As a result the website has subdirectories for the appropriate regions. For example, a pricing page would look something like this:

http://mydomain.com/ie/pricing
http://mydomain.com/gb/pricing
http://mydomain.com/fr/pricing

In order to target the appropriate search engines and signify to Google that there are different versions of the page, I've implemented hreflang tags. A good example of a site that uses these would be view-source:https://www.tripadvisor.ie/. If you view the source you will see a long list of hreflang tags to denote multiple regional versions of the page.

So, for my site, I decided to write a PHP script that would output the relevant hreflang tags on the correct page:

<?php $url = $_SERVER['REQUEST_URI']; ?>
<?php if(strpos($url, "pricing") == true): ?>
<link rel="alternate" href="http://www.mydomain.com/ie/pricing/" hreflang="en-ie" />
<link rel="alternate" href="http://www.mydomain.com/gb/pricing/" hreflang="en-gb" />
<link rel="alternate" href="http://www.mydomain.com/fr/pricing/" hreflang="en-fr" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="en" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="x-default" />
<?php endif; ?>

However, the problem I'm facing is that if the URL contains pricing ANYWHERE it will output the above which is not correct if the URL was something like: http://www.mydomain.com/pricing-types.

To counteract this I added another if statement which checks to ensure that the word types is not present in the URL:

<?php $url = $_SERVER['REQUEST_URI']; ?>
<?php if(strpos($url,"pricing") == true && strpos($url, "types") == false): ?>
<link rel="alternate" href="http://www.mydomain.com/ie/pricing/" hreflang="en-ie" />
<link rel="alternate" href="http://www.mydomain.com/gb/pricing/" hreflang="en-gb" />
<link rel="alternate" href="http://www.mydomain.com/fr/pricing/" hreflang="en-fr" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="en" />
<link rel="alternate" href="http://www.mydomain.com/pricing/" hreflang="x-default" />
<?php endif; ?>

Would anyone have any recommendations of how I could improve my script to read the URLs and match them to the appropriate hreflang tags but being more explicit in the URLs I read?

I would think that you would want to decouple the logic you use to determine what localization to display from the logic you are using to actually render the hreflang links in HTML.

With your current approach, you are going to get into a serious mess as you try to localize additional pages in your application.

You would need to hard-code similar links to what you have shown across every page. You would also need to maintain separate hard-coded versions for each page to show the slight variations in these links based on which page the user is currently on.  For example, if user is on fr page, they should not see alternate hreflang link for fr.

You also probably need to be thinking about generating an appropriate canonical URL tag as part of this same logic.

Also, over time, you may find the need to send hreflang hints in HTTP headers instead of in HTML <head> element.  By decoupling your logic for determining which localizations settings are applicable for a page (more of a routing concern), from how you convey that information to the browser/spider (a display concern), you can make you logic more re-usable across your application.

If you do not already have a central class or library of classes that handle localization logic for your application, you should strongly consider this.

I think what you should be striving for is a usage pattern like the following in your display context.

HTML link example:

<head>
    <!-- other header elements -->
    <?php $localization->displayAltLangLinks(); ?>
</head>

Header example:

<?php
// PHP application bootstrapping here

// send headers
$localization->setAltLangHeaders();

// page output follows

Here I have shown a theoretical Localization class/object where you could encapsulate your logic related to: current localization being requested, localization to be served, outputting localization info to browser, etc.

I think you need a better strategy for determining what language is being requested.  Relying on $_SERVER['REQUEST_URI'] will likely make your app fragile to user input.  For example,  what if I used URI of /PRICING/ in browser?  Your current code breaks.  What if I put /es/pricing/?  Your code would be triggered even though no localization would be served, when perhaps a 404 should be returned, or even a 301 to default page.

You really need to think about handling the logic around URI rewriting/redirecting at the web server and/or application bootstrap level.  A common pattern in providing the type of URI's you are looking to use it to put in a rewrite at the web server level to redirect something like:

/fr/pricing/

to

/* for individual PHP scripts */
/pricing.php?lang=fr

/* for front-controller application with central routing */
/index.php?lang=fr

This allows you to pass the language requested as a parameter to your script.  Also, if the language segment of the URI doesn't match the languages your application supports perhaps the request falls through your rewrite rules and generates a 404 or 301 redirect depending on how you want to handle these requests.

By handling localization settings early in the response processing cycle you could also do things like look at the user's browser Accept-language request headers, any user preferences settings (cookies, session settings, use preferences stored in database, etc.), to determine when localization should be rendered and performing appropriate redirects for those users.

So to summarize:

Handle localization settings and routing for the page much earlier in response process than at display time.
Dynamically generate these link  tags(and probably canonical tag) in response to what localizations are available for the route as well and what current requested localization is.


Process N lists simultaneously by doing permutations I'm trying to see if someone can come up with a better solution for this algorithm.

I have an input of three lists/queues and I have to group/sort the elements of xpn, tu, and efx — depending on the presence (or not) of UniqueKey. For instance, if UniqueKey exists, I have to try to form a list/tuple of xpn, tu, and efx (if they exists for that UniqueKey)...and so on.

This is the "main" class:

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public final class Request {
  private Map<String, List<Tuple3<Node, Node, Node>>> result;

  private Queue<Node> xpn;

  private Queue<Node> tu;

  private Queue<Node> efx;

  public Map<String, List<Tuple3<Node, Node, Node>>> transform() {
    final int max = estimateSize();
    result = new LinkedHashMap<>(max / 3);
    for (int i = 0; i < max; i++) {
      pollFrom(xpn).ifPresent(it -> process(it, Category.XPN));
      pollFrom(tu).ifPresent(it -> process(it, Category.TU));
      pollFrom(efx).ifPresent(it -> process(it, Category.EFX));
    }
    return Collections.unmodifiableMap(result);
  }

  private int estimateSize() {
    final int[] sizes = { sizeOf(xpn), sizeOf(tu), sizeOf(efx) };
    int max = sizes[0];
    for (int i = 1; i < sizes.length; i++) {
      if (sizes[i] > max) { max = sizes[i]; }
    }
    return max;
  }

  private Optional<Node> pollFrom(final Queue<Node> collection) {
    return (null != collection) ? Optional.ofNullable(collection.poll()) : Optional.empty();
  }

  private void process(final Node thiz, final Category category) {
    if (result.containsKey(thiz.getUniqueKey())) {
      final List<Tuple3<Node, Node, Node>> values = result.get(thiz.getUniqueKey());
      final Optional<Tuple3<Node, Node, Node>> optional = values.stream()
        .filter(tuple3 -> emptyBucket.apply(tuple3, category))
        .findFirst();
      if (optional.isPresent()) {
        final Tuple3<Node, Node, Node> tuple3 = optional.get();
        if (Category.XPN == category) {
          tuple3.update1(thiz);
        } else if (Category.TU == category) {
          tuple3.update2(thiz);
        } else {
          tuple3.update3(thiz);
        }
      } else {
        result.get(thiz.getUniqueKey()).add(tupleFrom(thiz, category));
      }
    } else {
      final List<Tuple3<Node, Node, Node>> list = new LinkedList<>();
      list.add(tupleFrom(thiz, category));
      result.put((null != thiz.getUniqueKey()) ? thiz.getUniqueKey() : IdGen.uuid(), list);
    }
  }

  private BiFunction<Tuple3<Node, Node, Node>, Category, Boolean> emptyBucket = (tuple, category) -> {
    if (Category.XPN == category) {
      return null == tuple._1();
    } else if (Category.TU == category) {
      return null == tuple._2();
    } else { // EFX
      return null == tuple._3();
    }
  };

  private Tuple3<Node, Node, Node> tupleFrom(final Node thiz, final Category category) {
    final Tuple3<Node, Node, Node> empty = new Tuple3<>(null, null, null);
    switch (category) {
      case XPN:
        return empty.update1(thiz);
      case TU:
        return empty.update2(thiz);
      case EFX:
        return empty.update3(thiz);
    }
    return empty;
  }

  private int sizeOf(final Collection<Node> collection) {
    return (null != collection) ? collection.size() : 0;
  }

  private enum Category {
    XPN, // 1st element in tuple
    TU,  // 2nd element in tuple
    EFX  // 3rd element in tuple
  }
}

The content of Node and Tuple3 are irrelevant, but I can post it if that may help. I'm just trying to see if there is a better way of doing this. The reason you don't see a constructor is because that class is being constructed/deserialized via Jackson. I would really like to avoid having result at class level.

PS: Don't mind about the method/variable names.

Not sure why you're making it so hard on yourself. Why not just go through each of the 3 queues individually?

For the first queue, just go through it and make a new Node for each element. Add it to your result list.

For the other 2 queues, check if the index is already in the result list. If it is, add it to that node, otherwise create a new node.

EDIT it seems my point wasn't clear, so let me show you the difference:

public Map<String, List<Tuple3<Node, Node, Node>>> transform2() {
    Map<String, List<Tuple3<Node, Node, Node>>> result = new LinkedHashMap<>(estimateSize() / 3);

    for (Node node : xpn) {
        if (!result.containsKey(node.getUniqueKey())) {
            result.put(node.getUniqueKey(), new LinkedList<>());
        }
        result.get(node.getUniqueKey()).add(new Tuple3<Node, Node, Node>(node, null, null));
    }

    for (Node node : tu) {
        if (!result.containsKey(node.getUniqueKey())) {
            result.put(node.getUniqueKey(), new LinkedList<>());
        }
        List<Tuple3<Node, Node, Node>> tuples = result.get(node.getUniqueKey());
        boolean needNew = true;
        for (Tuple3<Node, Node, Node> tuple : tuples) {
            if (tuple._2() == null) {
                tuple.update2(node);
                needNew = false;
                break;
            }
        }
        if (needNew) {
            tuples.add(new Tuple3<>(null, node, null));
        }
    }

    for (Node node : efx) {
        if (!result.containsKey(node.getUniqueKey())) {
            result.put(node.getUniqueKey(), new LinkedList<>());
        }
        List<Tuple3<Node, Node, Node>> tuples = result.get(node.getUniqueKey());
        boolean needNew = true;
        for (Tuple3<Node, Node, Node> tuple : tuples) {
            if (tuple._3() == null) {
                tuple.update3(node);
                needNew = false;
                break;
            }
        }
        if (needNew) {
            tuples.add(new Tuple3<>(null, null, node));
        }
    }
    return result;
}

I personally find this a lot easier to understand than all your indirections and switches.

If you really don't want to have one big method you can also split it up like this:

public Map<String, List<Tuple3<Node, Node, Node>>> transform() {
    Map<String, List<Tuple3<Node, Node, Node>>> result = new LinkedHashMap<>(estimateSize() / 3);

    for (Node node : xpn) {
        Tuple3<Node, Node, Node> tuple = getTupleToModify(result, node.getUniqueKey(), (n -> null == n._1()));
        tuple.update1(node);
    }

    for (Node node : tu) {
        Tuple3<Node, Node, Node> tuple = getTupleToModify(result, node.getUniqueKey(), (n -> null == n._2()));
        tuple.update2(node);
    }

    for (Node node : efx) {
        Tuple3<Node, Node, Node> tuple = getTupleToModify(result, node.getUniqueKey(), (n -> null == n._3()));
        tuple.update3(node);
    }
    return result;
}

private Tuple3<Node, Node, Node> getTupleToModify(
        Map<String, List<Tuple3<Node, Node, Node>>> currentTuples,
        String key, Function<Tuple3<Node, Node, Node>,
        Boolean> filter) {

    if (!currentTuples.containsKey(key)) {
        currentTuples.put(key, new LinkedList<>());
    }

    List<Tuple3<Node, Node, Node>> list = currentTuples.get(key);
    for (Tuple3<Node, Node, Node> tuple : list) {
        if (filter.apply(tuple)) {
            return tuple;
        }
    }
    Tuple3<Node, Node, Node> result = new Tuple3<>(null, null, null);
    list.add(result);
    return result;
}


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

So on click:

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

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

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

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

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

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

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

Let's go through it one section at a time.

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

You don't have to explicitly append 'px' to your numeric values. jQuery is smart enough to
correctly format your CSS styles.
Since this is a jQuery plugin, you return this; at the end of the function. This is good, as
it preserves chaining.
If the .center function is only used for the loading divs, consider removing it and instead
styling the divs with plain CSS.

#loader {
    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -50px; /* half of the height */
    margin-left: -100px; /* half of the width */
}
...

$( ".buttonFinish" ).on('click', function(event) {
    $('body').fadeOut('slow');
    $('#loader').center();
    $('#loading').center();
    $('#loader').show();
    $('#loading').show();

As mentioned by @Flambino, this particular code (as presented in the question) will fade out the entire body of the HTML document, which includes everything, even the loader elements. Perhaps the code that you're actually using is slightly different (is the selector .body or #body instead?).
It's best practice to enclose JavaScript that uses external dependencies inside an IIFE.
By doing so, you can use the "safe" name of an external dependency while still being able to
alias is to a more convenient identifier locally. In addition, you can freely create variables inside the scope
of the IIFE without polluting the global namespace. Your example code is fairly short, but you likely have much
more code on the page, and it is a good habit to have regardless. Here's one way to do it:

(function($) {
    $( ".buttonFinish" ).on('click', function(event) {
        ...
    });
})(jQuery);

You can select both elements at the same time, just like in CSS: $('#loader, #loading').
You can chain the .show() and .center() together: $('...').show().center().

    //Use the above function as:
    var request = $.ajax({
        url:'{{ URL::route('saveCart') }}',
        type:'POST'
        });

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

Since you're not using the request variable for anything other than .done(),
you can skip declaring it and simply chain .done() after $.ajax():

$.ajax({
    ...
}).done(function(msg) {
    ...
});

As an overall note, the indentation of the code (as it is in the question) seems haphazard,
making the control flow more difficult to see than it could be. Making matching
braces have the same indentation (and, in general, maintaining a consistent style)
will help make the code more readable and understandable.


Fastest and minimal random access data structure in Java I have written up a data structure in Java that supports the following features:

get(i)
set(i, e)
add(e)
remove(e)
contains(e)
size

Elements must remain in order and iteration needs to be as fast as possible. The code does not require thread safety.

I am looking for ways to improve the speed further. It is critical to reduce times to as small as possible because this code will be invoked hundreds of thousands of times per second. I believe it's possible to optimize my stream() method!

This is my current solution which seems to work:

import java.util.Iterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public final class Indexer<E> implements Iterable<E> {

    private final int minIndex;
    private final Object[] arr;

    private int size = 0;
    private int highest;

    public Indexer(int minIndex, int capacity) {
        this.minIndex = highest = minIndex;
        arr = new Object[capacity];
    }

    public Indexer(int capacity) {
        this(0, capacity);
    }

    @SuppressWarnings("unchecked")
    public E get(int index) {
        return (E) arr[index];
    }

    @SuppressWarnings("unchecked")
    public E set(int index, E element) {
        Object last = arr[index];
        arr[index] = element;
        if (last == null && element != null) {
            size++;
            if (highest < index)
                highest = index;
        } else if (last != null && element == null) {
            size--;
            if (highest == index)
                highest--;
        }
        return (E) last;
    }

    public int add(E element) {
        int index = nextIndex();
        set(index, element);
        return index;
    }

    public void remove(E element) {
        for (int i = minIndex; i <= highest; i++) {
            if (element == arr[i]) {
                set(i, null);
                return;
            }
        }
    }

    public boolean contains(E element) {
        for (E e : this) {
            if (element == e)
                return true;
        }
        return false;
    }

    public int size() {
        return size;
    }

    public int nextIndex() {
        for (int i = minIndex; i < arr.length; i++) {
            if (null == arr[i])
                return i;
        }
        throw new IllegalStateException("Out of indices!");
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            private int pointer = minIndex;

            @Override
            public boolean hasNext() {
                return size > 0 && pointer <= highest;
            }

            @Override
            @SuppressWarnings("unchecked")
            public E next() {
                return (E) arr[pointer++];
            }

        };
    }

    public Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }

}

Wow, this is pretty nice code. I've only got a few little nitpicks.

NB: I have not benchmarked the code before and after making these changes. If you'd like, I can, but as of right now, these are untested changes.

NB2: Most of these are just conforming to convention, since after a bit of research I've discovered that the JIT makes things scary fast after a few thousand iterations by putting in every optimization I'd never think of.

In remove(E) and contains(E), you compare equality with == instead of equals. This is a bad idea, because sometimes people want to specify their way of comparing objects. If they don't, this will default to Object's implementation, which is just ==. The exception, of course, is when you're dealing with either primitives or null, but you don't have to worry about that, since you can't use primitive types as E, and their class equivalents all define equals appropriately.
It's standard for remove to return the element it just removed, so you'll want to change the internals of the for a little bit:

if (element.equals(arr[i])) {
    set(i, null);
    return element;
}

and change the method signature to match.
I'd recommend adding a remove(int) as well, which does basically the same thing as remove(E) but doesn't have to loop through. It would look something like this:

public E remove(int index) {
    E ret = get(index);
    set(index, null);
    return ret;
}

Continuing with the trend of "I think your methods are bad and here's how I think you should do them instead", I think your lack of indexOf is bad and here's how I think you could implement it:

public int indexOf(E element) {
    for (int i = minIndex; i < size; i++) {
        if (element.equals(arr[i]))
            return i;
    }
    return -1;
}

In set(int, E) I'd recommend renaming last to original, or it might be confused with the last element of the array.
In iterator()'s anonymous class's next(), you should add a check to make sure that you're not overstepping the array's bounds, even if all you end up doing is throwing a different error. corsiKa suggested using an IllegalStateException, which makes a good bit of sense. The most important thing is that, from the name of the exception alone, you can figure out roughly what went wrong, though not necessarily the details.

That's about it! Well-written code all. If you give me some test cases, I can benchmark the version with my tips and the version without.


First attempt at writing Rock Paper Scissors game I made this Rock Paper Scissors game and I would like for this to be critiqued.

import System.IO
import System.Random
import Control.Monad
import Control.Arrow

data Throw = Rock | Paper | Scissors
           deriving (Show, Read, Enum, Bounded)

instance Random Throw where
  random g = first toEnum $ randomR (a, b) g
    where a = fromEnum (minBound :: Throw)
          b = fromEnum (maxBound :: Throw)

  randomR (a, b) g = first toEnum $ randomR (a', b') g
    where a' = fromEnum a
          b' = fromEnum b

beats :: Throw -> Throw -> Bool
Rock     `beats` Scissors = True
Paper    `beats` Rock     = True
Scissors `beats` Paper    = True
_        `beats` _        = False

play :: Throw -> Throw -> String
play p1 p2
  | p1 `beats` p2 = "You win!"
  | p2 `beats` p1 = "You lose."
  | otherwise     = "Tie."

main :: IO ()
main = do
  putStr "Enter your move [Rock, Paper, or Scissors]: "
  hFlush stdout
  p1 <- getLine >>= readIO
  p2 <- liftM (fst . random) getStdGen
  putStrLn $ show p1 ++ " vs. " ++ show p2
  putStrLn $ play p1 p2

The style is pretty good, I can just see two minor improvements you could do: Firstly, you can define random in terms of your own randomR in order to save a few keystrokes:

instance Random Throw where
  random = randomR (minBound, maxBound)
  randomR (a, b) g = ...

At this point Haskell's typing even derives the type of minBound for you, so you can lose the explicit annotations.

Second, you should probably use randomIO instead of liftM (fst . random) getStdGen. That is not only shorter, but also updates the generator state, which means that you won't get the same result if you call it twice in the program.


Pythons Around the Rose Based off my Java Petals Around the Rose, I thought it would be good practice to write something again in a different language.

Because the language is Python, I named it "Pythons Around the Rose", and everywhere in my code, the word "rose" would be replaced with "python".

Also, "Potentate" is replaced with "Pytentate".

Code:

import random

def display_help():
    example = get_dice_result()
    print("The name of the game is Pythons Around the Rose.",
          "The name is important. I will roll five dice,",
          "and I will tell you how many pythons there are.",
          "\nFor example:", sep = "\n")
    print_dice(example)
    print("Will result in ", get_answer(example), ".", sep = "")
    print("\nIf you answer correctly 8 times in a row, you",
          "will be declared a \"Pytentate of the Rose\".", sep = "\n")

def play():
    streak = 0
    while True:
        dice = get_dice_result()
        if play_once(dice):
            streak += 1
        else:
            streak = 0
        if streak == 8:
            print('You are now declared a "Pytentate of the Rose"!')
            break;
    print("Thank you for playing!")

def get_dice_result():
    result = [get_dice_roll(), get_dice_roll(),
              get_dice_roll(), get_dice_roll(), get_dice_roll()]
    return result

def get_dice_roll():
    return random.randrange(6) + 1

def play_once(results):
    print("How many pythons here?")
    print_dice(results)
    guess = get_guess()
    answer = get_answer(results)
    if guess == answer:
        print("Correct!")
        return True
    print("Incorrect. The answer is ", answer, ".", sep = "")
    return False

def get_guess():
    guess = 0
    valid = False
    while not valid:
        try:
            guess = int(input("> "))
            valid = True
        except:
            print("\nOops! That is not a number. Try again: ")
    return guess

def get_answer(dice):
    answer = 0
    for i in dice:
        if i == 3:
            answer += 2
        elif i == 5:
            answer += 4
    return answer;

def print_dice(dice):
    rows = ["|", "|", "|"]
    for i in dice:
        if i == 1:
            rows[0] += "       |"
            rows[1] += "   .   |"
            rows[2] += "       |"
        elif i == 2:
            rows[0] += " .     |"
            rows[1] += "       |"
            rows[2] += "     . |"
        elif i == 3:
            rows[0] += " .     |"
            rows[1] += "   .   |"
            rows[2] += "     . |"
        elif i == 4:
            rows[0] += " .   . |"
            rows[1] += "       |"
            rows[2] += " .   . |"
        elif i == 5:
            rows[0] += " .   . |"
            rows[1] += "   .   |"
            rows[2] += " .   . |"
        elif i == 6:
            rows[0] += " .   . |"
            rows[1] += " .   . |"
            rows[2] += " .   . |"
    print(rows[0], rows[1], rows[2], sep = "\n")

def main():
    display_help()
    play()

if __name__ == '__main__':
    main()

I wrote it to be based of standard conventions as close as possible. Because I'm a Java person, I might have added a ; somewhere in my code, or perhaps accidentally forgot to follow conventions somewhere.

In general your code looks nice, but it does show that you've got a another programming language background, and thus you do it the standard imperative way instead of utilizing some of the more pythonic way. In this review I'm deliberately going a little over the top, but in return you get to see some of the more special pythonic constructions.

Using __doc__ to get the docstring for display_help – In Python you can and should describe your code using docstrings, typically text with triple quotes, i.e. """ ... """. These can be used to describe the module, functions, classes (and methods). They typically come on the line after the definition of the item you want to document.

A neat thing is that this docstring can be accessed using a special variable, __doc__, or for a function as display_help.__doc__. And then it can be used for print outs, or similar.
Work a little more on naming methods – It is not very common in Python to have get_xxxx methods, rather name them according to specific function, like roll_multiple_dice() or roll_die(). Aim for simplicity and clarity. Using get_answer() implies that you want me to insert the answer of something, whilst number_of_pythons() indicates that this is going to be calculated.
List comprehensions are your friend – Instead of repeating code to build the list, use return [roll_die() for _ in range(number_of_dice)] which implements three nice features:

A list comprehension, which builds a list based on the inner generator, i.e. [ ... ]
The use of for within the generator, x for x in range(y), which compresses a for loop into the expression. This one would return the numbers from 0 to y-1
The use of _ when we don't really care about the number, but just want the code in front of the for loop to be executed

Generator expressions – The for loop of last item, can also be used outside of list comprehension, i.e sum(x for x in range(y)), which would sum all the numbers from 0 through y-1.

One major difference between a list comprehension and generator, is that the list comprehension actually builds the entire list, whilst the generators works in the background and gives you another element when you want it.

In the sum example this means that if you had y=1000000 you wouldn't allocate memory for more than 1 int, whilst if you used list comprehension you would allocate the entire list of 1 million elements, and then sum it.
The Python ternary, i.e. a  = b if c else d – This could take some time to get used to, but actually it reads out quite nicely: Set the value of a to b if the condition c is true, or d if not true.

Disclaimer: In my refactored code this is where it got a little ugly, as I combined multiple of this construction. But still, they kind of make sense. I used them in both number_of_pythons() and print_dice().
Avoid one-time intermediate variable – It's quite common to skip the intermediate variable, especially if you use them only once, and rather use the expression directly. I.e. in roll_die() just return the random number, and in roll_multiple_dice() return the list directly.
In some cases, you can sum using Booleans – Doing the if True: a += 1 is kind of an anti-pattern, and can in some cases be replaced by a += True, or in your case: streak += play_once(...).

Bug found by 200_success: Here the simplification went too far, as I by simply summing, removed the resetting of the streak counter.

Avoid flag variables, if possible – Your use of valid in get_guess() is better written using while True and a break like in your input validations. And skipping the intermediate variable, you could return straight out of the loop.
Try to avoid the chained if commands, doing the same stuff – In both get_answer() and print_dice() you have if chains where the block kind of does the same. This is usually an indication that you could find a better way of handling it.

In get_answer() I opted for a double ternary, doing answer += 2 if i == 3 else 4 if i == 5 else 0.
In print_dice() I used the fact that a six sided die has only 5 distinct patterns, and then I used yet another double ternary to select from the different options.

Disclaimer: Even though this code is a lot shorter than yours, that doesn't mean it is nicer as such. But it does show an alternate way, and there are multiple ways to print die results. See here or here.

Use constants, not magic number – Instead of hiding a 5 and an 8 in the code, use constants at top of file like REQUIRED_STREAK_RUN = 8 and NUMBER_OF_DICE = 5. This allows you to change them easily (and you can still make the document reflect the change using str.format()
Use str.format() for string formatting - This is a very useful construct, which is well worth some time to look into. You could either use it without names (see end of play_once()), or you could name your variables like in display_help().

PS! If using Python 2, I recommend using from __future__ import print_function to get the full extent of this beauty there as well.
Feature: You can't quit your program without becoming a Pythentate – I think it's nice to give users a way out. I've implemented a lazy version with terminating if entering a negative answer. This could be done a lot nicer, but it should be an option to quit at any time.

Refactored code

Here is the code using most (if not all) of the advice from above:

"""Pythons Around the Rose

The name of the game is Pythons Around the Rose.
The name is important. I will roll {number_of_dice} dice,
and I will tell you how many pythons there are.

For example:

| .   . |       | .   . | .     | .   . |
|   .   |   .   |       |   .   |   .   |
| .   . |       | .   . |     . | .   . |

Will result in 10 pythons. If you answer
correctly a given {streak_run} number of times you
will be declared a "Pythentate of the Rose".
"""
import random
import sys

REQUIRED_STREAK_RUN = 8
NUMBER_OF_DICE = 5

def display_help():
    """Use the docstring of the module."""
    print(__doc__.format(number_of_dice = NUMBER_OF_DICE,
                         streak_run = REQUIRED_STREAK_RUN))

def play():
    """Play until declared a Pytentate..."""
    streak = 0
    while True:

        # My bug: streak += play_once(roll_multiple_dice(NUMBER_OF_DICE)):
        if play_once(roll_multiple_dice(NUMBER_OF_DICE)):
            streak += 1
        else:
            streak = 0

        if streak == REQUIRED_STREAK_RUN:
            print('You are now declared a "Pytentate of the Rose"!')
            break

    print("Thank you for playing!")

def roll_multiple_dice(number_of_dice):
    """Return a list of die rolls."""
    return [roll_die() for _ in range(number_of_dice)]

def roll_die():
    """Return a single die roll."""
    return random.randrange(6) + 1

def play_once(results):
    """Play a single round, and return True if correct guess."""
    print("How many pythons here?")
    print_dice(results)

    guess = get_guess_of_pythons()

    # Simple bail out option... :-)
    if guess < 0:
        sys.exit(0)

    answer = number_of_pythons(results)
    if guess == answer:
        print("Correct!")
        return True

    print("Incorrect. The answer is {}".format(answer))
    return False

def get_guess_of_pythons():
    """Get input of pythons from user."""
    while True:
        try:
            return int(input("> "))
        except:
            print("\nOops! That is not a number. Try again: ")

def number_of_pythons(dice):
    """Return correct number of pythons."""
    return sum(2 if i == 3 else
               4 if i == 5 else
               0 for i in dice)

EYES = ["       |",
        "   .   |",
        " .     |",
        "     . |",
        " .   . |"]

def print_dice(dice):
    """Return a three-line string of all the dice."""
    rows = ["|", "|", "|"]
    for i in dice:
        rows[0] += EYES[0] if i == 1 else \
                   EYES[2] if i < 4 else \
                   EYES[4]

        rows[1] += EYES[4] if i == 6 else \
                   EYES[1] if i % 2 == 1 else \
                   EYES[0]

        rows[2] += EYES[0] if i == 1 else \
                   EYES[3] if i < 4 else \
                   EYES[4]

    print('\n'.join(rows))

def main():
    display_help()
    play()

if __name__ == '__main__':
    main()

Conclusion

I hope you are not intimidated by the length of this answer, or the content, because your code does look nice and it does do the work. But there are things to work with to make it more Pythonic, and I hope you've gotten a gist of even more of the beauty of Python here.


Most efficient way to get columns where one is minimum I have a table with 3 columns in the format below:

WebcastChannelId, WebcastEventId, SortSequence

1 , 2 , 1
1 , 5 , 2
1 , 3 , 3
2 , 7 , 2
2 , 8 , 1

I would like to get the values for the webcastChannelId  and WebcastEventId with the minimum sort sequence.

In the above example this would be:

WebcastChannelId, WebcastEventId, SortSequence

1 , 2 , 1
2 , 8 , 1

I have the following, which gets what I require, but I don't know if there is a more efficient way to do this?

SELECT wcwel.WebcastChannelId, wcwel.WebcastEventId
FROM [dbo].[WebcastChannelWebcastEventLink] wcwel with (nolock)
inner join [dbo].[WebcastChannelWebcastEventLink] wcwel1 with (nolock) on wcwel1.WebcastChannelId = wcwel.WebcastChannelId
group by
wcwel.WebcastChannelId,
wcwel.WebcastEventId,
wcwel.SortSequence
having
wcwel.SortSequence = MIN(wcwel1.SortSequence)

Formatting
You use a mixture of lowercase and UPPERCASE keywords, you should stick to one or the other. It makes it much easier to read the query if you do. I am going to stick with UPPERCASE as it is the convention.
An alternate approach
Might I suggest storing the minimum SortSequence value in a variable and then using that to filter out records you don't need.
Here is what I came up with.
DECLARE @Minimum_Sort_Seq INT =
(
    SELECT MIN(SortSequence)
    FROM WebcastChannelWebcastEventLink
)

SELECT wcwel.WebcastChannelId,wcwel.WebcastEventId
FROM WebcastChannelWebcastEventLink wcwel
WHERE wcwel.SortSequence = @Minimum_Sort_Seq

This query returned the same results in my testing. You can run this to check yourself:
CREATE TABLE #WebcastChannelWebcastEventLink
(
    WebcastChannelId INT,
    WebcastEventId INT,
    SortSequence INT
)

INSERT INTO #WebcastChannelWebcastEventLink
SELECT 1,2,1 UNION ALL
SELECT 1,5,2 UNION ALL
SELECT 1,3,3 UNION ALL
SELECT 2,7,2 UNION ALL
SELECT 2,8,1

SELECT wcwel.WebcastChannelId, wcwel.WebcastEventId
FROM #WebcastChannelWebcastEventLink wcwel WITH (NOLOCK)
INNER JOIN #WebcastChannelWebcastEventLink wcwel1 WITH (NOLOCK)
    ON wcwel1.WebcastChannelId = wcwel.WebcastChannelId
GROUP BY
wcwel.WebcastChannelId,
wcwel.WebcastEventId,
wcwel.SortSequence
HAVING
wcwel.SortSequence = MIN(wcwel1.SortSequence)

DECLARE @Minimum_Sort_Seq INT =
(
    SELECT MIN(SortSequence)
    FROM WebcastChannelWebcastEventLink
)

SELECT wcwel.WebcastChannelId,wcwel.WebcastEventId
FROM WebcastChannelWebcastEventLink wcwel
WHERE wcwel.SortSequence = @Minimum_Sort_Seq

DROP TABLE #WebcastChannelWebcastEventLink


Change level button's image There are 12 buttons, and each of them has 3 options for selecting pictures, depending on the data. It works but I think need a shorter and more intelligent decision.

import SpriteKit

class SelectEasyLevelViewController: UIViewController{

@IBOutlet weak var level_1: UIButton!
@IBOutlet weak var level_2: UIButton!
@IBOutlet weak var level_3: UIButton!
@IBOutlet weak var level_4: UIButton!
@IBOutlet weak var level_5: UIButton!
@IBOutlet weak var level_6: UIButton!
@IBOutlet weak var level_7: UIButton!
@IBOutlet weak var level_8: UIButton!
@IBOutlet weak var level_9: UIButton!
@IBOutlet weak var level_10: UIButton!
@IBOutlet weak var level_11: UIButton!
@IBOutlet weak var level_12: UIButton!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    //This thing help me to open data
    if  UserDefaults.standard.array(forKey: "levelPassed") != nil {
        Model.sharedInstance.levelPassed = UserDefaults.standard.array(forKey: "levelPassed") as! [Int]
    }

let image = UIImage(named: "levelbutton01")
let image2 = UIImage(named: "levelbutton02")
let image3 = UIImage(named: "levelbutton03")

    switch Model.sharedInstance.levelPassed[0] {
    case 1:
        level1.setBackgroundImage(image, for: .normal)
    case 2:
        level1.setBackgroundImage(image2, for: .normal)
    case 3:
        level1.setBackgroundImage(image3, for: .normal)
    default:
        break

    }

    ..........................................
    Here codes for button 2, 4, 5, 6, 7, 8, 9, 10, 12
    .........................................

    switch Model.sharedInstance.levelPassed[11] {
    case 1:
        level_12.setBackgroundImage(image, for: .normal)
    case 2:
        level_12.setBackgroundImage(image2, for: .normal)
    case 3:
        level_12.setBackgroundImage(image3, for: .normal)
    default:
        break

    }
}

Or maybe another way.

DRY - Don't Repeat Yourself:

1) change this block into an method:

switch Model.sharedInstance.levelPassed[0] {
    case 1:
        level1.setBackgroundImage(image, for: .normal)
    case 2:
        level1.setBackgroundImage(image2, for: .normal)
    case 3:
        level1.setBackgroundImage(image3, for: .normal)
    default:
        break
}

into this (assuming you can access thee image1 to image 3:

func applyImage(button: UIButton, level: Int){
    switch Model.sharedInstance.levelPassed[0] {
        case 1:
            level1.setBackgroundImage(image, for: .normal)
        case 2:
            level1.setBackgroundImage(image2, for: .normal)
        case 3:
            level1.setBackgroundImage(image3, for: .normal)
        default:
            break
    }
}

so you can call it this way:

applyImage(level_1,1)
applyImage(level_2,2)
applyImage(level_12,12)

2) avoid the switch:

arrays are zero based, so you decrease the level by 1

let images = [image1,image2,image3]

func applyImage(button: UIButton, level: Int, images: [UIImage]){
    button.setBackgroundImage(images[level-1], for: .normmal)
}
applyImage(level_1 , 1, images)
applyImage(level_2 , 2, images)
applyImage(level_12,12, images)

3) use IBOutletCollection and .tag property

because the order of an IBOutletCollection is not guaranteed you should use the tag property to ensure it shows the right information:

@IBOutlet var buttons: [UIButton]!

let images = [image1,image2,image3]

for button in buttons {
    button.setBackgroundImage(images[level-1], for: .normmal)
}

PS: all code is untested pseudo code - but it should show you the idea how to improve your code


Is this the right way to read every line? I am never to sure when it comes to ifstream and reading lines. I am often confused with the good(), bad(), eof() and so on.

Could anyone tell me if I am doing it right?

int parseLine(std::ifstream & _file)
{

  while( std::getline( _file, line, '\n' ).good() && !_file.eof() )
  {
     // some treatment
  }

  return 0;
}

Too complicated. Just say:

for (std::string line; std::getline(_file, line); )
{
    // process "line"
}

The function std::getline, like most iostreams operations, returns a reference to the stream object itself, which can be evaluated in a boolean context to tell you whether it is still good, i.e. whether the extraction operation succeeded.

Also, the function shouldn't be called "parseLine", but "parseAllLines" or "parseStream".


Javascript function to get cellId from map point I wrote this, and I would like to know if this code is clean.

It lets me know if a point is in the middle of an isometric cell.

const getMapPointFromCellId = cellId => {

    var {x, y} = getCoordinatesFromCellId(cellId)

    x = x * constants.cellWidth
    if (y % 2) x += constants.offsetWidth

    y = y * constants.offsetHeight

    return {x, y}
}
const getCellIdFromMapPoint = (x, y) => {
   var cellId = 0
   while(cellId < constants.numberCells){

       const cellCoordinates = getMapPointFromCellId(cellId)

       const offsetX = cellCoordinates.x + constants.offsetWidth
       const offsetY = cellCoordinates.y + constants.offsetHeight

       const endX = cellCoordinates.x + constants.cellWidth
       const endY = cellCoordinates.y + constants.cellHeight

       if (cellCoordinates.x < x && x < cellCoordinates.x + constants.cellWidth)
          if (cellCoordinates.y < y && y < cellCoordinates.y + constants.cellHeight){

            if (x < offsetX && y < offsetY)
                if ((offsetY - y) / (cellCoordinates.x - x) > (offsetY - cellCoordinates.y) / (cellCoordinates.x - offsetX)) return cellId
            if (x > offsetX && y < offsetY)
                if ((offsetY - y) / (endX - x) <= (offsetY - cellCoordinates.y) / (endX - offsetX)) return cellId
            if (x < offsetX && y > offsetY)
                if ((offsetY - y) / (cellCoordinates.x - x) <= (offsetY - endY) / (cellCoordinates.x - offsetX)) return cellId
            if (x > offsetX && y > offsetY)
                if((offsetY - y) / (endX - x) >= (offsetY - (constants.cellHeight - constants.offsetHeight)) / (endX - offsetX)) return cellId

        }

       cellId++
   }

  return -1
}

I always like to document my functions using high-level doc-blocks, e.g.

/**
 * Return the ID of the cell whose center is at the given point or -1 if ...
 *
 * @param {number} x - The x coordinate of the given point.
 * @param {number} y - The y coordinate of the given point.
 * @return {number} cell ID or -1 if no cell found at given point.
 */
const getCellIdFromMapPoint = (x, y) => { ... }

Also, I use inline comments to help the reader and my future self to understand complex statements such as

// Do C if A and B or C:
if (x < offsetX && y < offsetY)
   if ((offsetY - y) / (cellCoordinates.x - x) > (offsetY - cellCoordinates.y) / (cellCoordinates.x - offsetX)) return cellId

Better yet, take those complex statements as a hint to better refactor your code.

I advise to use available language constructs where appropriate. If you replace a simple for-loop with a while-loop for no apparent reason, a fellow developer will have a harder time to read and understand your code.

Also, I really recommend to use curly brackets with if-statements. The lack of those might be more pleasing to the eye by hiding the deep nesting, but makes reading and understanding as well as modifying your code much harder.

I suggest to combine if-clauses with identical statements. Instead of writing e.g.

if (A)
  if (B)
   return cellId;
if (C)
  if (D)
   return cellId

write e.g.

if ((A && B) || (C && D)) {
  return cellId;
}

Better yet, write helper functions to reduce the complex conditions, e.g.

if (isSomeCondition(A, B) || isSomeOtherCondition(C, D)) {
  return cellId;
}

Give those functions clear, self-documenting names to help the reader along. In your case, those could be e.g. isWithinRect(x, y, rect) or similar.

Your algorithm's runtime complexity is probably linear in the number of available cells. If you find that your application is running slow because of that, you can employ techniques such as spatial partitioning to improve runtime performance.


C++ My implementation of a simple sum type (variant) Here is a simple variant type I have made. For simplicity, it only can handle two different values. I am planning on using this to create a variadic variant template, using inheritance and recursion.

The requirements for my variant type:

It must have performance similar to std::variant
It must not dynamically allocate memory
There must be no undefined behavior
It should check as much as possible at compile-time, and throw an exception if access is attempted to the wrong type
It must support nontrivial types

Here is the source:

#include <iostream>
#include <cstddef>
#include <typeindex>
#include <optional>
#include <algorithm>
#include <stdexcept>
#include <functional>

/** A variant (sum type) that can contain one of two different types at any one time**/
template<typename T1, typename T2>
class Either {

    using Bigest = std::conditional_t<sizeof(T1) <= sizeof(T2), T1, T2>;
    alignas(sizeof(Bigest)) std::byte storage[sizeof(Bigest)];
    std::optional<std::type_index> conatinedType;
    std::function<void(std::byte*)> destructor;

public:
    Either() : conatinedType(std::nullopt) {}

    template<typename T>
    Either(const T& value) : conatinedType(typeid(T)) {
        static_assert(std::is_same<T1,T>::value || std::is_same<T2,T>::value, "Either cannot contain type T");
        const auto src = reinterpret_cast<const std::byte*>(&value);
        for(size_t i = 0; i < sizeof(T); i++) {
            storage[i] = src[i];
        }
        destructor = [](std::byte* data){ (*reinterpret_cast<T*>(data)).~T(); };
    }

    class BadVariantAccess : public std::exception {};

    template<typename T>
    const T& getAs() const {
        static_assert(std::is_same<T1,T>::value || std::is_same<T2,T>::value, "Either cannot contain type T");
        if(conatinedType == typeid(T)) {
            const auto ptr = reinterpret_cast<const T*>(&storage);
            return *ptr;
        }
        else throw BadVariantAccess();
    };
};

And a test:

struct MyInt {
    int val;
    MyInt(const int& val) : val(val) {
        std::cout << "making int!" << std::endl;
    }
    ~MyInt() {
        std::cout << "destructing int!" << std::endl;
    }
};

struct MyDouble {
    double val;
    MyDouble(const double& val) : val(val) {
        std::cout << "making double!" << std::endl;
    }
    ~MyDouble() {
        std::cout << "destructing double!" << std::endl;
    }
};

int main()
{
    Either<MyInt, MyDouble> e = MyDouble(5.0987);

    try{
        std::cout << e.getAs<MyDouble>().val << std::endl;
    }
    catch(...) {
        std::cerr << "Bad Variant Access" << std::endl;
    }

    return 0;
}

Construction and destruction of non-trivial types

Unfortunately, your class does not really support non-trivial types, because your class copies the representation of the supplied values and instead of invoking the proper copy constructor.  In other words, you create no object in the Either class, so the behavior of reinterpret_casting the storage and calling the destructor is undefined.

Interestingly, you store the destructor function object but never actually call it, so the class ends up working for trivial types, which do not require invocations to the corresponding constructor or destructor.  However, making your code work by letting two errors cancel out each other is not really a good idea.

The copy and move semantics of your class is also broken.  We'll try to fix this problem later.

Use of runtime type information (typeid)

The usage of typeid is a bit overkill here and not optimal, because it forces the user to pass exactly the same type as one of the stored types, disallowing conversions.  In fact, simply storing an index seems to suffice.

std::variant uses overload resolution to deduce the type, which is hard to implement.  You may consider supporting in_place construction.  (On the other hand, std::variant is typically implemented with unions because of constexpr requirements.)

The storage

using Bigest = std::conditional_t<sizeof(T1) <= sizeof(T2), T1, T2>;
alignas(sizeof(Bigest)) std::byte storage[sizeof(Bigest)];
std::optional<std::type_index> conatinedType;
std::function<void(std::byte*)> destructor;

Consider using std::aligned_storage.  As I said above, we can simply store an index.

using storage_type = std::aligned_storage_t<std::max( sizeof(T1),  sizeof(T2)),
                                            std::max(alignof(T1), alignof(T2))>;
storage_type storage;
std::size_t index;

For valueless variants, we can provide a special index:

static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max();

The constructors

The default constructor of std::variant default-constructs the first alternative type.  You can go into the valueless state instead:

Either() noexcept
    : index{npos}
{
}

Here's how you'd support in place constructors:

template <std::size_t I, typename... Args>
explicit Either(std::in_place_t<I>, Args&&... args)
{
    construct<I>(std::forward<Args>(args)...);
}

template <std::size_t I, typename U, typename... Args>
explicit Either(std::in_place_t<I>, std::initializer_list<U> ilist, Args&&... args)
{
    construct<I>(ilist, std::forward<Args>(args)...);
}

where the private member function template construct is defined like

template <std::size_t I>
struct alternative_type {
    static_assert(I < 2);
    using type = std::conditional_t<I == 0, T1, T2>;
};
template <std::size_t I>
using alternative_type_t = typename alternative_type<I>::type;

// not exception safe
template <std::size_t I, typename... Args>
void construct(Args&&... args)
{
    index = I;
    ::new (static_cast<void*>(&storage))
        alternative_type_t<I>(std::forward<Args>(args));
}

Special member functions

As I said before, you need to implement the copy/move/destruction operations.  Here's the copy constructor for example: (SFINAE and explicit issues are omitted for simplicity.)

Either(const Either& other)
{
    if (other.index == 0) {
        construct<T1>(other.get<0>());
    } else if (other.index == 1) {
        construct<T2>(other.get<1>());
    } else {
        index = npos;
    }
}


Summing two time periods using JodaTime I'm building a Java method to sum arithmetically two time periods, using the JodaTime library. My code works fine, but I think that it's possible optimize to reduce the time execution.

import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

public class Test {

    public static void main(String[] args)
    {
        String time1 = "08:00";
        String time2 = "08:00";

        System.out.println(Operation_Sum(time1,time2));
    }

    private static String Operation_Sum(String time1, String time2)
    {
        String output;
        long start = System.currentTimeMillis();

        if (time1.equals("00:00") && time2.equals("00:00"))
        {
            output = "00:00";
        }
        else if (time1.equals("00:00"))
        {
            output = time2;
        }
        else if (time2.equals("00:00"))
        {
            output = time1;
        }
        else
        {
            boolean sign_time1 = false;
            boolean sign_time2 = false;
            String[] time1_out, time2_out;

            boolean negative = false;
            String output_split[];

            if (time1.contains("-"))
            {
                time1_out = time1.split(":");
                time1_out[0] = time1_out[0].replace("-", "");
                time1_out[1] = time1_out[1].replace("-", "");
                time1 = time1_out[0] + ':' + time1_out[1];
                sign_time1 = true;
            }

            if (time2.contains("-"))
            {
                time2_out = time2.split(":");
                time2_out[0] = time2_out[0].replace("-", "");
                time2_out[1] = time2_out[1].replace("-", "");
                time2 = time2_out[0] + ':' + time2_out[1];
                sign_time2 = true;
            }

            PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
            builder.minimumPrintedDigits(2);
            builder.printZeroAlways();
            builder.appendHours();
            builder.appendLiteral(":");
            builder.appendMinutes();
            PeriodFormatter pf = builder.toFormatter();

            Period period1 = pf.parsePeriod(time1);
            Period period2 = pf.parsePeriod(time2);
            Period normalized;
            Period total = null;

            if (sign_time1 && sign_time2)
            {
                total = period1.plus(period2);
                negative = true;
            }

            if (sign_time1 && !sign_time2)
            {
                total = period2.minus(period1);
            }

            if (!sign_time1 && sign_time2)
            {
                total = period1.minus(period2);
            }

            if (!sign_time1 && !sign_time2)
            {
                total = period1.plus(period2);
                negative = false;
            }

            normalized = total.normalizedStandard(PeriodType.time());
            output_split = pf.print(normalized).split(":");

            if (output_split[1].contains("-"))
            {
                output = output_split[0] + ":" + output_split[1].replace("-", "");
            }
            else
            {
                output = (negative ? "-" : "") + output_split[0] + ":" + output_split[1];
            }
        }

        long end = System.currentTimeMillis();

        System.out.println("exec time sum1: " +(end - start) + " ms");
        return output;
    }
}

You're really overcomplicating it. The great thing about Joda Time is that it can do all the hard work for you. This simplified method will give the exact same output as your original Operation_Sum:

static String sumTimes(String time1, String time2) {
    PeriodFormatter formatter = new PeriodFormatterBuilder()
            .minimumPrintedDigits(2)
            .printZeroAlways()
            .appendHours()
            .appendLiteral(":")
            .appendMinutes()
            .toFormatter();

    Period period1 = formatter.parsePeriod(time1);
    Period period2 = formatter.parsePeriod(time2);
    return formatter.print(period1.plus(period2));
}

Test cases I used on both your method and this new one:

@Test
public void testSum8Plus8() {
    String time1 = "08:00";
    String time2 = "08:00";
    assertEquals("16:00", JodaDemo.sumTimes(time1, time2));
}

@Test
public void testSum8Plus18() {
    String time1 = "08:00";
    String time2 = "18:00";
    assertEquals("26:00", JodaDemo.sumTimes(time1, time2));
}

@Test
public void testSum8Minus18() {
    String time1 = "08:00";
    String time2 = "-18:00";
    assertEquals("-10:00", JodaDemo.sumTimes(time1, time2));
}

In addition to the simplification, some other improvements:

Variables should be named camelCase (don't start with capital letter, don't use underscore)
Typical *Builder classes support a fluent interface, so instead of builder.someMethod(); builder.anotherMethod();, you can just chain the calls as builder.someMethod().anotherMethod();
Unit tests are good to let you make changes and confirm that everything is still working. It's also easier for code reviewers, so they can easily test refactored version of the code. Try to include more tests to cover all corner cases.

There were glaring logical mistakes in your original implementation. For example in this code:

if (time1.contains("-"))
{
    time1_out = time1.split(":");
    time1_out[0] = time1_out[0].replace("-", "");
    time1_out[1] = time1_out[1].replace("-", "");
    time1 = time1_out[0] + ':' + time1_out[1];
    sign_time1 = true;
}

This is (pretty much) equivalent to the simpler and better:

if (time1.contains("-")) {
    time1 = time1.replaceAll("-", "");
    sign_time1 = true;
}

That is, here, and in many other places in your code, you were doing a lot of operations that can be easily simplified to fewer operations.


Array to Grid using a table I have been doing some personal projects for fun and most of them have visual representation of boards (ej: sudoku solvers, chess PGN viewer, etc) and I always end up doing something like this:

var wid=10;
var hei=6;
var len=(wid*hei);
var map="005000200000000008000600000006000700000040000000500030400000".split("");

var str="

";

for(var i=0;i<len;i++){
    if(i&&!(i%wid)){
        str+="

";
    }
    str+=""+((map[i]!=0)?map[i]:"&nbsp;")+"	";
}

str+="

";

document.body.innerHTML+=str;

with CSS styles like:

*{margin:0;padding:0;}
#board{margin:15px auto;text-align:center;}
#board,#board td{border:1px solid #000;}
#board td{width:45px;height:47px;font-size:20px;}

I want to know if there is a better, more readable way to achieve this?, maybe using arr.join()?

Despite already having accepted an answer, I'd like to point out a different way to approach this.

Since you are building the board with JavaScript I'm assuming that you want to modify the content of the board dynamically. (If not then the question would be why you are using JavaScript and not a server-side generation).

In that case it could make sense to separate generation and filling the board. That way you could simply exchange each method without affecting the other.

For generation you could continue to use your solution just with empty or default values, or use DOM generation:

var rowCount = 6;
var colCount = 10;
var board = document.createElement('table');
for (var r = 0; r < rowCount; r++) {
  var row = board.insertRow();
  for (var c = 0; c < colCount; c++) {
    row.insertCell();
  }
}

Or simply use static HTML.

And then you write a function that sets the value of a cell which will work no matter how you created the board. Something like:

function setBoardValue(board, x, y, value) {
   board.rows(y).cells(x).innerHTML = value;
}

And then you can loop over your "map" in anyway you like and call it:

var map="005000200000000008000600000006000700000040000000500030400000".split("");

for (var i=0;i<len;i++){
  setBoardValue(board, i % colCount, Math.floor(i / rowCount), map[i] != 0 ? map[i] : "&nbsp;");
}

In the end this solution if technically slower that your solution, but usually not in an amount that would be noticeable by the user and you have an advantage with the separation of the concerns.


Table join in DAO and delegating ResultSet reading I'm wondering if (and how) this idea could come to bite me in the future.

I was thinking that I should take away the responsability from any given DAO to know how to load a different object from a joined resultset, besides from not needing to know the names used in the database itself.

(Here is a very simplified - working - )

Example

Let's say I have Cards and Clients. Not really important but, each client will only be able to use one card at a time.

The join example is in CardDAO -> getCardList() method.

Tables

Card Table Data

+---------+----------------+
| card_id | card_client_id |
+---------+----------------+
|       1 | 1              | // Card 1 used by client 1
|       2 | NULL           | // Card 2 available
+---------+----------------+

Client Table Data

+-----------+-------------+
| client_id | client_name |
+-----------+-------------+
|         1 | Client X    |
|         2 | Client Y   |
+-----------+-------------+

Codes

Simplified and reduced (Exceptions, Connections, closes(), etc). Also, Card and Client classes are just POJOs, like so:

public class Client {
    private int id;
    private String name;
    // Getters & setters
}

public class Card {
    private int id;
    private Client client;
    // Getters & setters
}

ClientDAO

public class ClientDAO{
    public static final String table = "tb_client";
    // Column names as defined in the table
    public static final String id = "client_id";
    public static final String name = "client_name";

    // Other methods

    public static Client loadClient(ResultSet rs){
        Client client = new Client();
        client.setId(rs.getInt(ClientDAO.id));
        client.setName(rs.getString(ClientDAO.name));
        return client;
    }
}

CardDAO

public class CardDAO{
    public static final String table = "tb_card";
    // Column names as defined in the table
    public static final String id = "card_id";
    public static final String client = "card_client_id";

    // Other methods

    public List<Card> getCardList(){
        List<Card> cards = new ArrayList<Card>();
        // Sql could be just concat too
        String sql = String.format("SELECT ca.*, cl.* FROM %s AS ca INNER JOIN %s AS cl ON ca.%s = cl.%s WHERE ca.%s is not null",
                CardDAO.table,
                ClientDAO.table,
                CardDAO.id,
                ClientDAO.id,
                CardDAO.client);

        PreparedStatement pstn = this.con.prepareStatement(sql);
        ResultSet rs = pstn.executeQuery();
        while (rs.next()) {
            cards.add(CardDAO.loadCard(rs));
        }
        return cards;
    }

    public static Card loadCard(ResultSet rs){
        Card card = new Card();
        card.setId(rs.getInt(CardDAO.id)); // Don't know the column name, it doesn't matter here
        // CardDAO doesn't need to know how to load Client, just 'SELECT' everything and delegate a loader
        card.setClient( ClientDAO.loadClient(rs) );
        return card;
    }
}

On a side note, this would be the generated query:

SELECT ca.*, cl.* FROM tb_card AS ca INNER JOIN tb_client AS cl ON ca.card_id = cl.client_id WHERE ca.card_client_id is not null

Some things I already thought:

Increased complexity when writing queries;
Need to always load all the columns from a given table to make it possible for the loadXClass method to be called (can't select specific fields, only everything);
What if there are more levels to it? Example: the client has an address that is linked to an Address table, so I'd have to include it in the query and join every time so the code doesn't fail, even when not using it.

What are your thoughts?

I was thinking that I should take away the responsability from any given DAO to know how to load a different object from a joined resultset

Well, I would have made a view which does the selection and the dao would then do the mapping, or rather the disassembly and re-assembly of the resultSet (get all Cards, extract Clients, set the Client to the corresponding Card). So at least it's only one select.

Or you could introduce a new type in a layer 'above' both dao's, which does the mapping.

To your thoughts:

  Increased complexity when writing queries

Yeaaah, that's why people tend to use existing ormappers ;) - you might want to introduce some static methods in your base dao, e.g. all() and join(String table, String condition), so the writing is more fluent and it's better to read... you might want to check the Criterion API/impl of hibernate, it's quite nice to write and read, but that's quite the work, if you really want to implement your own ormapper with a certain amount of sql features.

And: Most important: It's your job to make a class or a method readable. In test cases, I even write a static tomorrow() method, which creates a new Date and adds a day. Of course, you have to write a lot in java, but that must not be the excuse, to make your code not readable.

  Need to always load all the columns from a given table to make it possible for the loadXClass method to be called (can't select specific fields, only everything);

I really think the 'only select data you need' paradigma is quite out dated. The management of the 'choose what columns' thingy, the 'be careful because its not null in the backend but someone might not have loaded that column' and the inconvenient increase of execution plans on your backend - which has to be managed, too - is in my opinion much more expensive compared to just select all (= upgrade the switch or add another cpu to the backend server)

  What if there are more levels to it? Example: the client has an address that is linked to an Address table, so I'd have to include it in the query and join every time so the code doesn't fail, even when not using it.

... I think a view with a dao responsible for that case is the way to go ;-)

To be honest, in ormappers, I do not like the represent the complete erd in java objects approach. Maybe I just didn't get it, but sometimes it gets quite horrible. I mean, you have a Customer, the Customer has a List of Addresses, a List of Orders, a List of PhoneNumbers, a List of Items in the Shopping Card, a List of open bills and and and. And everything is present in the type of hell. And it gets worse, because all those dependencies have other dependencies, too. I found, that an app, at least above a certain size and complexity, is much more maintainable, if "those" problems are taken care of with a certain degree of isolation, even though that means, there is some redundancy, maybe a ClientAddress type and a ClientOrders type, instead of a "one size fits all" approach.

Hope that helps,...


Looking for matching names among two text files I'm trying to enhance the execution speed of my below code. I am using only vanilla JavaScript. I would be willing to bring in additional libraries and plugins as long as they will enhance the overall speed of the code.

The goal is to have the absolute fastest execution time of the below code.

Currently, it executes from start to finish in approx. 320 - 350 ms. I want to make any modifications necessary to make it perform faster than that, particularly with exponentially larger datasets.

Setup

I have two .txt files, names and data.
names contains a list of last names, one name per line:

Nader
Sanford
Kovacek
Lynch
etc...

data contains a much longer list, of first names, last names, a comma and a value:

Kailee Huel,2
Arianna Runolfsson,4
Marshall Kuhn,3
Cristina Huel,4
Garnett Medhurst,3
etc...

Task

Iterate through data.txt using the last names in names.txt. If any of the last names from names.txt have a match in data.txt, increment a counter with the value on that line (after the comma). Some last names are repeated in both names.txt and data.txt. Output the final value of the counter.

<script type="text/javascript">

  var names,
  data;

    // doc rdy
    document.onreadystatechange = function(){
      console.time('execution length');
      if( document.readyState == "complete" ){
        init();
      }
    }

    // setup
    function init(){
      var base      = "data/sample2/",
          namesFile = base+"names.txt",
          dataFile  = base+"data.txt";

      loadFile(namesFile, function(e){
        names = e;
        loadFile(dataFile, function(ev){
          processData(ev);
        });
      });
    }

    function processData(e){
      var counter = 0;
      var namesProcessed = {};

      // for each last name,
      for( var i=0; i<names.length; i++ ){
        // if "data object" contains "this name" AND "this name" does not exist in rmvdNames, add its val to counter
        if( e.hasOwnProperty(names[i]) && ! namesProcessed.hasOwnProperty(names[i]) ){
          counter += e[names[i]];
          namesProcessed[names[i]] = true;
        }
      }
      console.log(counter);
      console.timeEnd('execution length');
    }

    // ajax loading
    function loadFile( filename, callback ){
      var client = new XMLHttpRequest();
      var result;
      client.open('GET', filename);
      client.onreadystatechange = function() {
        if( client.readyState==4 && client.status==200 ){
          result = client.responseText.split("\n");
          // custom handling for the data set..
          if( result[0].search(',') !== -1 ){
            result = arrCSVtoObj(result);
          }

          callback(result);
        }
      }
      client.send();
    }

    // converts an array of CSV to a key:value object
    function arrCSVtoObj(csvArr) {
      var obj = {};

      // for each line in the array,
      for( var i=0; i<csvArr.length; i++ ){
        // split into key:value on comma
        var split = csvArr[i].split(",");
        var key =  getLastName(split[0]);
        var val = parseInt(split[1]);

        // assign the new property to the object
        if( ! obj.hasOwnProperty(key) ){
          if( val > 0 ){
            obj[key] = val;
          }
        }else{
          obj[key] += val;
        }
      }
      return obj;
    }

    function getLastName(e){
      var nameArr = e.split(" ");
      return nameArr[1];
    }

  </script>

I know the biggest time sink in this script are the loops (there are several: looping through object properties, looping through data to parse it, etc). How can I speed these actions up? What measures can I take to improve the above code and optimize absolute speed with large datasets?

The first thing that really jumped out at me is your loadFile method is using synchronous http requests (looks accidental as you're using a callback anyway, see msdn for why this should be avoided etc).

Instead of client.open('GET', filename); you probably want client.open('GET', filename, true);

Making async requests will allow the first notable improvement I would make is to make init loading async. I'm going to use the native promises -- feel free to adapt

// setup
function init() {
  var base = "data/sample2/",
    namesFile = base + "names.txt",
    dataFile = base + "data.txt";

  Promise.all([loadFile(namesFile), loadFile(dataFile)])
  .then(function(values) {
    var names = values[0];
    processData(values[1]);
  });
}

// ajax loading
function loadFile(filename) {
  return new Promise(function(resolve, error) {
    var client = new XMLHttpRequest();
    client.open('GET', filename, true);
    client.onreadystatechange = function() {
      if (client.readyState == 4 && client.status == 200) {
        var result = client.responseText.split("\n");
        // custom handling for the data set..
        if (result[0].search(',') !== -1) {
          result = arrCSVtoObj(result);
        }
        resolve(result);
      }
    };
    client.send();
  });
}


How to manage different views I answered a question in stackoverflow but I gave a solution that looks a little dirty to me, I'd like your opinion because I think there is a much smarter way to do it.

A guest user should be able to choose between two different view modalities.

My approach was to implement an action and store the choice in the session.
I paste some relevant code here as well:

  # application_controller.rb
  def set_view_type # TODO: here is the part I don't like
    session[:view_type] = params[:view_type]
    redirect_to :back
  end

  # x_controller.rb
  def index
    case session[:view_type].to_sym
    when :box render 'index_box'
    else      render 'index_list'
    end
  end

Then I use two link_to (instead of radiobutton as in stackoverflow) to choose the view, and those should be visible anytime in the layout, this is why I use application_controller for that.

PS: I don't know if it's correct to ask for a question that it's still open in SO, feel free to answer straight there by me, I just think here I'm posting my solution that I would like to be revised.

For the part you do not like, you can set a before_filter in ApplicationController. Therefore a redirect will not be necessary. Selection form can resubmit to the current page with "view_type" parameter.

#application_controller.rb
before_filter :check_view_type, :only => [:index]

def check_view_type
   session[:view_type] = params[:view_type] if params[:view_type].present?
end

For this specific example I would prefer layout and partial views. It is well described in Rails guides.

#x/index.html.erb
render :partial => 'item', :layout => current_layout, :collection => @items

#application_controller.rb
helper_method :current_layout

def supported_layouts
    [nil]
end

def current_layout
 supported_layouts.include? session[:view_type] ? session[:view_type] : supported_layouts.first
end

#x_controller.rb
def supported_layouts
    %w[box list]
end

def index
  # only index logic
end


Shared Pointer based Object Pool Implementation with fixed object count I'm implementing a object pool with shared_ptr to access with multiple thread.
Any suggestions to improve my implementation

template <typename T>
class Section : public std::enable_shared_from_this<Section<T>>
{
public:

template <typename... E>
Section(std::size_t size, E... args)
    : std::enable_shared_from_this<Section<T>>()
    , m_mem(size,T(args...))
{
    for(auto& itr: m_mem)
    {
        destroy(&itr);
        m_objs.push(&itr);
    }
}
virtual ~Section() = default;

void isEmpty() const
{
    std::unique_lock<std::mutex> lk(m_lock);
    return m_objs.empty();
}
template <typename... E>
std::shared_ptr<T> create(E... args)
{
    T* obj = getObject();
    if(obj != nullptr)
    {
        new (obj) T(args...);
    }
    return std::shared_ptr<T>(obj,[this](T* ptr)->void
    {
        destroy(ptr);
        std::unique_lock<std::mutex> lk(m_lock);
        m_objs.push(ptr);
    });
}

private:
std::list<T> m_mem;
std::queue<T*> m_objs;
mutable std::mutex m_lock;

T* getObject()
{
    std::unique_lock<std::mutex> lk(m_lock);
    if (!m_objs.empty())
    {
        T* obj = m_objs.front();
        m_objs.pop();
        return obj;
    }
    return nullptr;
}

void destroy(T* obj)
{
    obj->~T();
}
};

Small nitpicks

The constructor and create could profit from perfect forwarding args (so references of all kinds can be used.

template<typename... E>
Section(size_t size, E&&... args) :
    std::enable_shared_from_this<Section<T>>(),
    m_mem(size, T(std::forward<E>(args)...))
    { /* ... */ }

Do you have any specific reason to prefer std::list<T> over std::vector<T> for m_mem? std::vector<T> would use less memory (no pointers from each element to the next), and the memory used would be contiguous (so iterating over it is very likely faster due to cache effects).

Correctness

Every std::shared_ptr<T> returned by Section<T>::create() might be dangling. This can happen if the Section<T> gets destroyed while there are still std::shared_ptr<T> pointing to contained objects.

This is a result of the std::shared_ptr<T> not owning the pointer.

If you can guarantee that there won't be any std::shared_ptr<T> pointing into the Section<T> when the Section<T> is destroyed, this problem easily disappears.

If this can't be guaranteed, there are two options:

Introducing your own smart pointer type that checks the Section<T> for validity every time it's dereferenced, as the standard smart pointers (std::unique_ptr, std::shared_ptr and std::weak_ptr) are not designed for this task.
(Ab-)using the returned std::shared_ptr<T> to keep the section alive. This can be done in the lamda init capture of the custom deleter.

return std::shared_ptr<T>(obj, [section = shared_from_this()](T *ptr) -> void
{
    section->destroy(ptr);
    std::unique_lock<std::mutex> lk(section->m_lock);
    section->m_objs.push(ptr);
});

Note: This might keep the section alive far longer than intended! (Some might also say that this is an ugly hack...)