Any ideas how do I prettify this SQL query?

The following are a few suggestions on how I'd write the SQL.
Source Control
If you don't already have a database project, create one in Visual Studio. Then check it in to source control. Microsoft Azure DevOps Services is free & private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.
Formatting
I use the following tools for SSMS and Visual Studio, ApexSQL Refactor and Poor Man's T-Sql Formatter. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.
Copy & Paste
If you find yourself copying and pasting the same string or number over and over in your query, then you should define it as a variable. Copy and paste is a design error ~ David Parnas
Commas
I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier.
Where Clause
If you put 1=1 at the top of a WHERE condition, it enables you to freely change the rest of the conditions when debugging a query. The SQL query engine will end up ignoring the 1=1 so it should have no performance impact. Reference
Common Table Expressions (CTE)
CTE's in your SQL help with documentation. The expression name can then let other developers know why you used that expression e.g. number_of_group_auth or number_of_order_results.
Schema Names
Always reference the schema when selecting an object e.g. [dbo].[Sales].

Also check out the book Clean Code. It will change the way you think about naming conventions.

Revised SQL
Without table definitions and sample records I was unable to test this, but it should give you a good start.
WITH
number_of_group_auth -- table expression names should tell you what they're doing so you don't need to use comments
AS
(
   SELECT
        [group_count] = COUNT(*)
      , [a].[id_group]
   FROM
      [rivals].[t_rival_group_auth] AS [a]
)
,
number_of_order_results
AS
(
   SELECT
        [group_count] = COUNT(*)
      , [r].[id_group]
   FROM
      [rivals].[t_order_results] AS [rs]
      INNER JOIN [rivals].[t_rivals] AS [r] ON [r].[id] = [rs].[id_rival]
   WHERE
      1=1
      AND [rs].[c_date_order]::date = utils.getdate() ::date
      AND
         (
            [rs].[c_price] IS NOT NULL
            OR [rs].[c_failed] IS NOT NULL
         )
)
SELECT
   greatest
   (0, least
      (500,
         (
            SELECT
                [g].[c_daily_limit] * [number_of_group_auth].[group_count] - [number_of_order_results].[group_count]
            FROM
                [rivals].[t_rival_group] AS [g]
                LEFT JOIN [number_of_group_auth] AS [a] ON [a].[id_group] = [g].[id]
                LEFT JOIN [number_of_order_results] AS [r] ON [r].[id_group] = [g].[id]
            WHERE
                [g].[c_code] = [_code]
         )
      )
   );


This is Schrödinger code
It can be both correct and incorrect at the same time.
random.choice is not how we offer financial advice.
What I would suggest is to monitor previous data, the longer the better, and monitor the fluctuation in price.
See this graph (Note, a 5 year graph):

at two points on the chart you can see separate events that can be somewhat predicted by the speed at which it falls/rises in comparison to previous events.
Although this could potentially expand to be a large solution, it's about as close to accurate as you can get. (Not really, but I'm not a market analyst)
These guys are, though.
Note that the graph is 5 years; data doesn't fluctuate that much in small amounts.
Although Bitcoin can, given it's financially unstable and volatile nature.
Beyond that, your python code is nice :-)
I would suggest writing it to PEP8 however, as that is the official style guide of Python, and then you can use an online checker like pep8online.


There is almost always a better way to loop in Ruby than actually using a loop. Unfortunately, I don't know Ruby well enough to say what that better way is.

What I can say is that this line of code is a bit obtuse.

break if string.length % 2 == 0 ? i == (string.length/2) : i + j == -1 && string[i] == string[j] && i == string.length/2

While it does seem to be a very Ruby way to write something like this, it's not very readable. Ternaries stretching off the screen are not a good thing in my opinion. It's okay to use an If block there.


Advent of Code 2018 day 1 part 2: find the first aggregated number that occures twice

It also looks functional to me, and I like your use of union type State.

You can define the Zero static member of State as:

type State =
    | FinalState of int
    | IntermediateState of int * int Set
    static member Zero = IntermediateState(0, Set.empty.Add(0))

You don't have to create a separate with-definition.

In general I avoid writing the result to the console in the algorithm function it self. Instead it is more useful to return the result and let the caller handle that as needed:

let rec processListRec state lst =
    let result = lst |> Seq.fold foldState state
    match result with
    | FinalState result -> result
    | IntermediateState _ -> lst |> processListRec result

Used as:

printfn "%A" (processListRec State.Zero input)

You need some kind of stop condition or an input check if all changes are positive or negative.

For instance will [1;1;1] run forever, because no frequency will ever occur twice.

A raw recursive solution could be:

let findReoccurantFrequency input =
    if (input |> List.groupBy (fun x -> x > 0)) |> List.length < 2 then
        raise (Exception "Invalid input (only positive or negative changes)")
    else
        let rec runner lst freq freqs =
            if freqs |> List.contains freq then
                freq
            else
                let head, tail = if lst = [] then input.Head, input.Tail else lst.Head, lst.Tail
                runner tail (freq + head) (freq::freqs)
        runner input 0 []

I'm not saying that it's a better solution, just another approach for the exercise and inspiration. Especially I'm not proud of the input check.

Edit

As pointed out by JanDotNet in his comment, my input validation is poor, so it's maybe better to leave it out. Below is a revised version of my implementation using a Set instead of a List for the frequencies:

let findReoccurantFrequency input =
    let rec runner lst freq freqs =
        match freqs |> Set.contains freq with
        | true -> freq
        | false ->
            let head, tail = if lst = [] then input |> List.head, input |> List.tail else lst.Head, lst.Tail
            runner tail (freq + head) (freqs.Add(freq))
    runner input 0 Set.empty


Program for binary to decimal and vice versa

two sets of comments. IS the functionality sensible or not? Is the code good / open to improvement etc?

Firstly the functionality

Its very odd to put 101 into an int and say that its 5. The number 5 in an int is always 5, it has various string representations depending on the base used to display it. I would have much preferred seeing 2 functions:

one that accepts a string is a given base and gives that returns the valur of it as an int
one that takes an int and displays it as a string using a given base

In effect you would be recoding atoi and itoa

Now about the implementation of the features you implemented

First the code works, ++ for that. Nicely split into functions etc. ++

No Comments -- Gotta have at least some.

commonly accepted c practice is to define and initialize variables on first use. (Old compilers required all variables to be declared at start of scope, not any more)

for exmaple

   char m;
    printf("\nType b for binary to decimal conversion or d for decimal to binary conversion (max 65535)\n");
    m = getchar();

is better as

printf("\nType b for binary to decimal conversion or d for decimal to binary conversion (max 65535)\n");
char m = getchar();

You alignment is somewhat funky. Commonly accepted c styles are

while(n >= 1)
{
    ++x;
    n /= 10;
}

or

while(n >= 1){
   ++x;
   n /= 10;
}

your should '\n' on the last line of your output, its considered polite.

I would have made the conversion functions return something rather than having them do the printing. Imagine you needed to do something else with the converted value

There is no error checking. Entering 42 and asking for a 'b' conversion returns 0. THis is in fact an error, you should say so.

n,z,x are not obvious names. I see that z is a copy of n so you can restore it later, call it saven or something like that

Now for the actual logic. Given that you are doing such a strange thing I find it hard to really comment on it. But its not very clear. Taking convert, I would have converted the input to a string , base 2, then scanned the string back as decimal.


The efficiency of looping over nested dictionaries in Python

One obvious improvement:

for word_pos, word_pos_prob in word_pos_dict.items():
    marginal_prob = 0
    for pos_prob in pos_dict.values():
        marginal_prob += word_pos_prob * pos_prob

Simplifies to:

multiplier = 0
for pos_prob in pos_dict.values():
    multiplier += pos_prob
# or just 'multiplier = sum(pos_dict.values())'

for word_pos, word_pos_prob in word_pos_dict.items():
    marginal_prob = word_pos_prob * multiplier

Now the inner loop only runs once.


Counting Balanced numbers in a given array

return evensum == oddsum && evensum != 0 && oddsum != 0;

Why can't sums be zero?  With this array ... {-5, 7, 0, 5 } ... if you remove the 7, then the even elements -5 and 5 would sum to zero, and the odd elements 0 also sum to zero, giving a "balanced" array.

Move tests out of loops wherever possible.

    for (int i = 0; i < arr.length; i++) {
      if (i % 2 == 0) {
        evensum += arr[i];
      } else {
        oddsum += arr[i];
      }
    }

Here, with a 1 million element array, i % 2 == 0 is being done 1 million times.  If you summed the even and odd elements separately ...

    for (int i = 0; i < arr.length; i += 2) {
      evensum += arr[i];
    }
    for (int i = 1; i < arr.length; i += 2) {
      oddsum += arr[i];
    }

... you never have to even test i % 2 == 0, which should be a speed improvement.

The above also applies to copying elements in removeElementInArr():

    for (int i = 0, j = 0; i < arr.length && j < result.length; i++, j++) {
      if (i == index) {
        result[j] = arr[i + 1];
        i++;
      } else {
        result[j] = arr[i];
      }
    }

You know you'll be copying elements up to index, and then copying the elements after index, but you do an i == index inside the loop.  With a million elements, that is a lot of extraneous testing.

    // Copy elements before index:
    for (int i = 0; i < index; i++) {
        result[i] = arr[i];
    }

    // Copy elements after index:
    for (int i = index + 1, j = index; i < arr.length; i++, j++) {
        result[j] = arr[i];
    }

But this is still a lot of manual copying.  The JVM can do the copying for you, a lot more efficiently using System.arraycopy

    System.arraycopy(arr, 0, result, 0, index);
    System.arraycopy(arr, index + 1, result, index, result.length - index);

Now the JVM does all the bound-checking once for each call, instead of two million times when done manually on an array of one million entries.  Much faster.

If you add elements of int[], you may overflow, especially if you have a lot of elements in those arrays.  You may want to use long accumulators.

Algorithmic Improvement

While the above optimizations will speed up the code, the algorithm is still \$O(N^2)\$.  I believe you can improve this to \$O(N)\$.

The problem is you are doing a whole lot of additions, and the partial results of those additions aren't changing.  Given an array of one million entries, when you are deleting the element around index 500,000 or so, the sums of the first 200,000 even indices and the first 200,000 odd indices don't change.

Consider the array:

1, 3, 5, 7, 9, 11, 13, 15, 17, 19, ...

If you were asked to find the sum of various spans of elements, say 4rd through 8th, how would you go about doing it?  How about 2nd through 9th? Can you save any work?

If you maintained a list of cumulative sums:

1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ...

The sum of the 4rd through 8th element would be:

                 7 + 9 + 11 + 13 + 15
= (1 + 3 + 5) + (7 + 9 + 11 + 13 + 15) - (1 + 3 + 5)
= (1 + 3 + 5  +  7 + 9 + 11 + 13 + 15) - (1 + 3 + 5)
=                    64                -      9
=               cumulative[8]          -  cumulative[3]

We've preprocessed the input into a cumulative sum array, which is done once \$O(N)\$, and then any subrange sum can be computed in \$O(1)\$ by a simple subtraction.

You've got some issues to work out, such as how and where to store cumulative sums of only the even/odd indices, how to compute the sum of all even indices after an element at index x is removed, etc. But given this is a programming challenge, the implementation is left to student.


Given an unordered list of numbers, find all pairs that add up to x

What is the time complexity of this solution? They will definitely ask that.

The description doesn't specify the ordering of the pairs. It would be good to ask to clarify. If the pairs can be unordered, and the numbers are unique, a more efficient algorithm exists. (Hint: would it help to use a hash set? What will be the time complexity then? If the numbers may contain duplicates, then a hash map of counts could be used, as @mleyfman pointed out.)

This looks suspicious:

int[] sorted = numbers;
Arrays.sort(sorted);

The variable sorted is redundant. You simply gave numbers another name. Which is fine, as long as you keep in mind that the sort operation destroys the original ordering of the input.

Speaking of input... You implemented the solution in a main method, using hardcoded values. It would be better to write a proper function that takes the array and target as parameters, and (ideally) return something. That way the solution becomes unit-testable.

In this if-else chain the last else if can be a simple else:

if (sum > x)
    // ...
else if (sum == x){
    // ...
}
else if (sum < x)
    // ...

And it's recommended to use braces with even single-line statements.

With a better name for x (like target), you wouldn't need the comment here:

    int x = 6; //target sum


Recursive vs. non-recursive implementations of Fibonacci sequence

Before we got any further, a word of warning. The complexity is only valid in a particular computational model.

The complexity of these algorithms is \$O(\log n)\$ only if the addition takes constant time. For large \$n\$ it is not the case.

Fibonacci numbers grow exponentially with n. It means that the number of bits grows linearly. Now we are in the Turing machine realm. The last addition itself takes \$O(n)\$, which is way more than \$\log n\$.

The overall complexity should be \$O(n\log{n})\$ in both cases. Why the two exhibit different performance?

The likely reason is that there is a subtle difference between them. fib_1 maintains just one matrix, F. fib_2 maintains two of them, F, M, and must do roughly twice as many reallocations as fib_1 does. The matrices contain huge numbers, and I expect that the memory management time dominates. Yet another factor the computational model shall now consider.


Couple of things I've done to your code:

Early exits
Redundant code removal
Readability improvement

Keep in mind that I have not tested this, but it should work. And also, the code will only work on PHP 5.4 and greater.

Cleaned up version:

<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['icon'])) {
    echo 'Image upload failed.';

    return;
}

$file = [
    'name' => stripslashes($_FILES['icon']['name']),
    'path' => $_FILES['icon']['tmp_name'],
    'ext'  => strtolower(pathinfo($_FILES['icon']['name'], PATHINFO_EXTENSION)),
    'size' => filesize($_FILES['icon']['tmp_name'])
];

$supportedExts = [
    'jpg',
    'jpeg',
    'png',
    'gif'
];

if (!in_array($file['ext'], $supportedExts)) {
    echo 'Extension not supported.';

    return;
}

if ($file['size'] > 400 * 1024) {
    echo 'You have exceeded the image size limit.';

    return;
}

list($image['x'], $image['y']) = getimagesize($file['path']);

switch ($file['ext']) {
    case 'jpg':
    case 'jpeg':
        $imgResrc1 = imagecreatefromjpeg($file['path']);
        break;
    case 'png':
        $imgResrc1 = imagecreatefrompng($file['path']);
        break;
    default:
        $imgResrc1 = imagecreatefromgif($file['path']);
}

$imageSizes = array(
    [
        'x' => 300,
        'y' => $image['y'] / $image['x'] * 300
    ],
    [
        'x' => 500,
        'y' => $image['y'] / $image['x'] * 500
    ]
);

foreach ($imageSizes as $size) {
    $imgResrc2 = imagecreatetruecolor($size['x'], $size['y']);

    imagecopyresampled($imgResrc2, $imgResrc1, 0, 0, 0, 0, $size['x'], $size['y'], $image['x'], $image['y']);

    // Shouldn't the extension be .jpg / .jpeg since you're using imagejpeg()?
    $filePath = 'usericons/' . $size['x'] . '-'. $_SESSION['username'] . '.png';

    imagejpeg($imgResrc2, $filePath, 100);

    imagedestroy($imgResrc2);
}

imagedestroy($imgResrc1);

hasIcon($_SESSION['username']);

echo '<script>window.location = \'/Users/\';</script>';

// TODO: Print success message


Javascript/Typescript anagram String search

This is quite a nice idea for a learning project.

I created a jsfiddle to test your code. Initially I was not able to run your program, as there were a few minor bugs, most relevant:

When you use element.addEventListener, the this context of your App instance is not captured, even though you are using an arrow function. This leads to this.searchIndex being undefined when the keyup event handler is executed. I fixed this, by introducing a local variable before the handler:

const index = this.resultIndex;
element.addEventListener('keyup', (e) => {
  let target = <HTMLInputElement>e.target;
  console.log(target.value, e);
  console.log(index.getSearchResults(target.value))
})

You can also bind the this context to your handler explicitly, if you prefer.

element.addEventListener('keyup', ((e) => {
  let target = <HTMLInputElement>e.target;
  console.log(target.value, e);
  console.log(this.resultIndex.getSearchResults(target.value))
}).bind(this))

I wasn't able to transpile the arrow function with direct return of the double-negated str and changed it to

(str) => { return !!str; }

even though

str => str

does the same (with respect to the filter function.)

Coding Style

I have some remarks regarding your coding style.

You use semicolons inconsistently. I would prefer to always use semicolons at the end of a statement.
const vs. let: You should use const, whenever you don't intend to reassign the given variable, which is almost always the case - except string concatenations and declaration before assignment.
implicit return types (e.g. in RandomWordGenerator::getWordList()) are not very helpful. If you make the return type explicit, i.e. getWordList() : string[], the compiler will enforce all code paths to return a value, which helps to reduce programming errors.
implicit parameter types: the SearchIndex::getSearchResults(str) method does not specify the parameter type explicitly, but rather implicitly by naming the parameter str. Use getSearchResults(searchTerm : string) instead and two things are resolved at the same time: First your parameter type is specified, and second, your parameter name is way more relevant in the context of the usage of this method. This is a problem that occurs more often in your code, also with variables. sortedStrArr could be defined as sortedCharacters : string[] and sortedStr could be sorted : string. You could also make the member variable types explicit. indexMap should be index : {[key : string] : string[]}
using private methods for methods that don't need to be accessible from the outside. In your code all of SearchIndex's methods, except getSearchResults could be private.
unused code: You call document.getElementById('content'); without ever using the returned element. The member variable indexMapCharArray is reset to an empty array, but never used.

I am not a big fan of the method chaining in RandomWordGenerator either. The chaining as you implement it does not prevent the user of your code to call createAnagrams before calling createWords.

SOLID Principles

A scenario for extending your application could be to replace the random word generation with e.g. an English dictionary. I assume that in the real world use case one would also only want to find the anagrams already present in the dictionary.

Currently this is not possible without touching the SearchIndex class, which is unfavorable coupling. Also I'm not very satisfied with the fact, that SearchIndex does need to call the getWordList() method of RandomWordGenerator.

I would recommend the following signature of SearchIndex's constructor:

constructor(private wordList : string[])

This way you don't depend on the way the word list is generated to provide it to the SearchIndex anymore.

If you want to allow the user to provide multiple sources of word lists, you could have an interface for this:

interface IWordListSource {
    getWordList() : string[];
}

and make RandomWordGenerator, DictionaryWordSource or other implementations implement that interface. It would be okay to inject that interface into the SearchIndex, like constructor(private wordListSource : IWordListSource) instead of directly providing the word list, if you prefer.

Your App class is coupled to a specific document structure, i.e. the existence of an input element with the class search-field is required. I would recommend to inject this element into the App instance either when calling start() or when constructing the instance.

One should also think about, whether logging to the browser's console is the best way of outputting information to the user of your program.


Is this appropriate way to pass data from presentation to application layer?

Overall, your code is very good, there is not much to review..

In your ViewModel, you might want to use DataAnnotations to do client (using jquery unobstrusive script)/server validation ex :

public class ProductCreateViewModel : ICreateProductCommand
{
    [Required]
    public string Name { get; set; }

    [Required]
    public int Price { get; set; }
}

public ActionResult ProductCreateAction(ProductCreateViewModel vm)
{
    if(ModelState.IsValid) //Server validation of the data annotations.
    {
        _productService.CreateProduct(vm);
        return Json(new { Ok = true });
    }
}

To answer your second question, I believe it is better to use two separated actions to separate the use cases of when you will use Create vs. Update. Plus one day you might have different roles for adding and updating (it's a little hardcore but it could happen), you would want your actions to be marked with different authentication attributes (If you use MVC membership)


Code review:

As a rule, it's almost never a good idea to create your own thread directly - better to  let an ExecutorService do the thread management for you.

if (isPrime(i) == true)

should be written

if (isPrime(i))

similarly

if ( count > 0 )
{
    //number is prime
    return true;
}
else
{
    //number is not prime
    return false;
}

should be

return count > 0 ;

You should also write some tests, since this condition looks backwards.

But for this specific case, kasperd has the right idea - you don't care how many different factors that the number has, just whether or not it is prime; early exit is the right answer here.

It would improve the code to separate the calculation from the reporting.

interface PrimeListener {
    void onPrime(long prime);
}

class TrivialPrimeListener implements PrimeListener {
    private final PrintStream out;

    TrivialPrimeListener (PrintStream out) {
        this.out = out;
    }

    TrivialPrimeListener () {
        this(System.out);
    }

    void onPrime(long prime) {
        // Even better would be to make this flexible about where it
        // sends t
        out.println(prime + " is prime");
    }
}

Then your loop would look like:

for ( long primeCandidate = start ; primeCandidate <= last ; primeCandidate++)
{
    if (isPrime(primeCandidate))
    {
        this.listener.onPrime(primeCandidate);
    }

}

And your initialization code would look something like

    this.startNum = start;
    this.endNum = end;
    this.listener = new TrivialPrimeListener();


You use a variable named dictionary. This is not helpful, as it's just the variable's type. Use meaningful variable names, how about handsigns or shapes or commands.

There are really three things being associated: the move names, the user input, and whatever internal representation you use. You currently have the user input being equivalent to the internal representation; that's okay. Initially I was against the idea of using a dictionary, but doing so allows you to use any user input.

Whatever variable name and type you use, the data structure does not need to be reinitialized in each loop. Set it once and leave it (though this may not affect your speed)

userChoice  = int(raw_input("Select One [1:Rock, 2:Paper, 3:Scissors, 0:Exit] : ")) I don't like this, because it duplicates the contents of your dictionary structure. You should just have one copy of the mapping, and refer to it here.

if (userChoice in (1,2,3)): same thing with this. You should just check if it's one of the keys.

           print "Computer Choice is   : ", sysChoice,  dictionary[sysChoice]
           print "Your Choice is       : ", userChoice, dictionary[userChoice]

This is duplicated code. Factor it out into a new function.

user and sys are poor variable names. It took a while before I realized that they meant the length of the user's and computer's current winning streaks. The variable name should reflect its purpose.

Why do you have else and except blocks that do literally nothing?


Initial attempt at node.js automatic redirection

if (err) {
        if (name == nope)
            rv = "INTERNET!";
        else {
            rv = readFile(nope, response);
            return;
        }
    }
    else rv = dat;

Omitting {} can easily go sideways especially if you mix it like in the example above. I suggest to always use them.

Even if it's just

else { rv = dat; }

they greatly helps to see where the if/else ends.

var nope = "./redirect.html";

Since you doesn't seem to change it anwhere, I'd make it a constant too.


Java Cryptography AES/GCM/NoPadding without IV

First of all, thank you for using my Bouncy Castle additions:

  Maarten Bodewes  initial implementation of HKDF and NIST SP 800-108 MAC based KDF functions.

Design review:

You are trying to emulate Java's Cipher class. However, I don't think this is such a good idea if your encrypt methods and is so much different. The Cipher class in Java is reusable for the same key (and, unfortunately, same IV) and this one is clearly not. I would not try this hard. Better make this class more specific to the use case and avoid generic wrapper classes.

In itself, you may wonder if combining the key derivation and cipher is a good idea. You're removing the update functionality, for instance. This is less of a problem if this is for a specific use case.

Code review:

public class AesGcmSymmetricCipher {

Better made final.

The name doesn't fully capture what the class is about. Symmetric is already captured by Aes. The key derivation part is missing on the other hand.

public static final int KEY_BYTES = 32; // AES-256

I generally use 256 / Byte.SIZE so it is clear where the 32 comes from, that way you don't need the comment.

public byte[] encrypt(byte[] key, byte[] clearData) throws InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

clearData is generally called plaintext or simply message within the crypto community.

Other users will probably wonder what happened with the IV or nonce and where to insert it.

Arrays.clear(iv);
Arrays.clear(key);

Beware that Oracle made a huge mistakes by making the actual keys in software impossible to destroy. You can do this and fool yourself. It's great that you thought of this though - you're not in the wrong here.

return "AES-256/GCM/NoPadding using HKDF";

Nice but it doesn't capture all the little details - how is the IV calculated, for instance - so it doesn't seem to be of much use. You cannot specify it to anybody and they will know how to implement it.

Otherwise the class and design seems spot on to me, so well done.


Unique elements of a list and corresponding indices in Haskell

Various Comments

First, Stack Exchange sent the body of my response into the void when I logged in to post it, so I'm going to be a bit more brief and a bit less organized than I originally wanted because I'm lazy.

This is not really reviewing your code, so it would've been better served as a comment, but I didn't think to comment my approach before I wrote out all the code. Might as well share it in case it's helpful.

To be honest, I don't quite understand your second solution, but on a second read it looks like it might still be n^2 (same asymptotic complexity as your first solution), so that would explain why it's slower. I assumed at first it was just something to do with mutability and vectors (which I don't really understand myself), but on second read I'm no longer so sure about this.

If you don't mind me being frank in answering your first question: I don't really think it's nice. I had a pretty rough time reading it, to the point where I instead just wrote a more Haskell-inclined solution that has better asymptotic performance than your first one.

Proposed Solution

Are you okay with an n log n solution? If memory serves, with the right choice of set/map, the log's base is so large that it is effectively linear.

Here is one such solution

import Data.List (foldl', sortOn)
import Data.Map (Map)
import qualified Data.Map as Map

-- | Gives the unique elements of 'elems' in order.
orderedNub :: Ord a => [a] -> [a]
orderedNub elems = sortOn (firstIndexMap Map.!) (Map.keys firstIndexMap)
  where
    -- Insert such that if the value is already in 'firstIndexMap', it is not
    -- updated.
    addElem m (elem, index) = Map.insertWith (flip const) elem index m
    -- Left fold in order to get the first occurance of each element.
    firstIndexMap = foldl' addElem Map.empty $ zip elems [0..]

-- | Gives the unique elements of 'elems' and the indices of 'elems' in
-- the unique list of elements.
unique :: Ord a => [a] -> ([a], [Int])
unique elems = (uniques, indices)
  where
    uniques = orderedNub elems
    uniqueInds = zip uniques [0..]
    indexMap = foldr (uncurry Map.insert) Map.empty uniqueInds
    -- We can use unsafe indexing since we know that 'indexMap' has
    -- the right values.
    indices = [indexMap Map.! x | x <- elems]

Some Notes About the Solution

I changed the code so it is correct now, assuming you want to preserve order. Some of these comments may be a bit out of date as a result.
orderedNub' is a kind of clunky definition, but it should have better asymptotic performance than nub. I’m pretty sure you can avoid the overhead of an actual sort (one clunky way would be to use a vector like you’re using).
uncurry Map.insert is a cute pointfree thing, if that's not your dig just sub it with a lambda or helper function.
I can't think of a good way to avoid using Map.!, even though it's partial. If I used Map.lookup, then there'd have to be a fromJust or a Maybe overhead, even though the map is, by construction, going to have the right keys. Guess this is a shortcoming of the type system.


I haven't been a C guy for years, but a few observations:

You have int oddArray[oddIndex], evenArray[evenIndex]; declared, but the only time you use it is to add the entered number, and even that will fail because you have basically declared them as size[0], so oddArray[1] will throw an exception.

I think [even|odd]Index and [even|odd]Total can be combined into one variable.

I'm not sure what the standard is for C, but I really don't like the multiple declarations on one line.  There should be a single declaration per line.  Its less confusing that way.

You could also put some error handling around the input.  What happens if somebody enters "A"?  Your program would crash.  I also think your instruction should be a little more clear.  What does "please enter some numbers." really mean?

Minor thing, you forgot to indent the line after the if's at the bottom.

I would also move the reporting to a different function and reduce duplication.

Your code could turn out like this:

#include <stdio.h>

void DisplayResults(char numberType[], int total, int sum);

int main(void)
{
    int oddCount= 0;
    int evenCount= 0;
    int evenSum = 0;
    int oddSum = 0;
    int userInput;

    printf("Please enter a number followed by <enter>.  Enter \"0\" to exit: \n");

    while (((scanf("%d", &userInput)) == 1) && (userInput != 0))
    {

        switch (userInput%2)
        {
            case 0:
                evenCount++;
                evenSum += userInput;
                break;

            default:
                oddCount++;
                oddSum += userInput;
                break;
        };
    }

    DisplayResults("Even", evenCount, evenSum);
    DisplayResults("Odd", oddCount, oddSum);
    return 0;
}

void DisplayResults(char numberType[], int count, int sum)
{
    if (total > 0)
    {
        printf("%s total: %d, %s average: %d\n", numberType, count, numberType, sum/count);
    }
    else
    {
        printf("There are no %s numbers!\n", numberType);
    }
}

Please excuse me if I have the syntax wrong, I haven't used C in about 20 years.


Logger module in child processes from os.fork()

Thomas, your solutions looks good. I have few remarks regarding the code style.

The following code looks a bit strange to me:

for num in range(number + 1):
    # prime numbers are greater than 1
    if num > 1:
        for i in range(2,num):
        ...

You can easily replace it with:

for num in range(2, number + 1):
    for i in range(2, num):
    ...

Do not use string concatenations, they are making your code less readable. Better use the .format() method of the string:

'child:' + str(os.getpid()) + ':' + str(num)

# Better:
'child:{pid}:{num}'.format(pid=os.getpid(), num=num)

In order to not put the meta information to every logging request, you can use logging formatters. Please check that doc for more details: https://docs.python.org/2/howto/logging-cookbook.html#using-logging-in-multiple-modules.
To simplify logging creation and make a code a bit more readable, you can create a function get_logger:

def get_logger(pid):
    file_name = 'logs/child_primes_{}.log'.format(pid)
    file_handler = logging.FileHandler(file_name)
    name = 'child:{}'.format(pid)
    logger = logging.getLogger(name)
    logger.addHandler(file_handler)
    # TODO: Add a formater here
    return logger


Scrape a jobs board and keep persistent record

Code Quality and Other Improvements

I would use a cursor and a connection as context managers to avoid having to explicitly close them and let Python safely close them if an error happens:

with sqlite3.connect('jobs.db') as connection:
    with connection.cursor() as cursor:

making the query defined as a multi-line string could benefit readability:

cursor.executemany("""
    INSERT INTO
        jobs
    VALUES (?, ?, ?, ?, ?)""", new_result)

watch for PEP8 code style violations - for instance, organize imports in a proper way

Performance

We can definitely do better performance-wise:

switch from lxml to html.parser (requires lxml to be installed):

BeautifulSoup(page, "lxml")

since you need only span elements, let BeautifulSoup parse only them:

from bs4 import BeautifulSoup, SoupStrainer

parse_only = SoupStrainer('span')
BeautifulSoup(page, "lxml", parse_only=parse_only)


Your problem is here:

for i in itertools.product(words, repeat = N):

This brute-force approach is why it's taking so long. Let \$k\$ be the
number of \$N\$-letter words. For two or three letters, the time is
proportional to \$k^2\$ or \$k^3\$. Bad enough, but for four letters, it's
\$k^4\$, which is horrendous. \$k\$ is probably significantly larger for
four letters as well, depending on your word list.

So, we need to drastically prune the number of combinations to try.
There are many ways this might be done. One idea would be to prune
things a row at a time. Suppose the first row is "ACHE". Look at all
words beginning with "A". None begin with "AA" or "AQ". So the next row
can eliminate all words beginning with "A" or "Q". Similarly, second-row
second letter can't be "B" or "C" or several other things, because no
words begin with "CB" or "CC", etc. This approach should cut way down on
the combinations.


Entity Framework - Table structure, navigating many descendants, etc

I also work on an e-commerce platform that has tons of data in it.  What I've found is that if you have more than a very basic query, write the query yourself.  EF speeds up saving records and very basic selects, but as soon as you start doing something a bit complicated, EF will spit out thousands of lines of SQL for something you could have done yourself in 100.  You are better off just trying to create the SQL for it and use Dapper or just create an object that you can map directly back to from the query.  Use context.Database.SqlQuery(sql, parameters).ToList() and you'll be able to get exactly what you need.  Though, naturally, it is going to be way more work on your part since you have to do all the joins manually and type that out, but if you need it to perform, then I would really recommend just typing it out.  I've had calls go from 60 seconds down to < 4 by just doing it myself instead of relying on EF.


Your binary tree setup does not appear to be well balanced.... and no, the counter is unnecessary. I think you have perhaps over-thought the process...

If the data is pre-sorted, you can simply bifurcate your data in a recursive process.

Your method is very close to what I would do, so copy/paste:

private TreeNode dpPreOrderRecursive (int[] arr, /*Counter counter,*/ int min, int max) {

    int mid = (min + max) >> 1;
    TreeNode treeNode = new TreeNode(null, arr[mid], null);
    treeNode.left = mid > min ? dpPreOrderRecursive(arr, min, mid - 1) : null;
    treeNode.right = mid + 1 < max ? dpPreOrderRecursive(arr, mid + 1, max) : null;
}

Then, you can get your tree with:

TreeNode root = dpPreOrderRecursive(arr, 0, arr.length);

(none of the Integer.MIN/MAX).


Collect the iterator into the new vector

You don't need to loop over a range to populate a vector with elements. The collect method has enough information to construct a Vec<u64> on the spot. This also makes the result variable unnecessary.

    pub fn new(length: u64) -> QuickFind {
        QuickFind {
            items: (0..length).collect(),
        }
    }

C-GETTER

The convention for getter names is without the prefix get_, unless get makes up the entire method name. get_items(&self) becomes items(&self).

Reconsider usize as the index type.

There appear to be multiple conversions from u64 to usize in the code. Indeed, usize is the common integral type for referring to a relative (non-negative) position of a value in memory. With that done, the only integer cast is in new, so as to turn the range (0..length) into a range of values rather than a range of indices.

The final code:

Playground

#[derive(Debug)]
pub struct QuickFind {
    items: Vec<u64>,
}

impl QuickFind {
    pub fn new(length: usize) -> QuickFind {
        QuickFind {
            items: (0..length as u64).collect(),
        }
    }

    pub fn union(&mut self, left_index: usize, right_index: usize) {
        let left_group_id = self.items[left_index];

        self.items[right_index] = left_group_id;
    }

    pub fn items(&self) -> &[u64] {
        &self.items
    }

    pub fn is_connected(&self, left_index: usize, right_index: usize) -> bool {
        self.items[left_index] == self.items[right_index]
    }
}


Review: Finished router class for custom mini framework

Your constructor is doing too much. Just because the only thing you are going to do with your router is initialize it, that doesn't mean you can't have more methods. And as Sven pointed out, it probably shouldn't have access to the global state. Inject whatever you need.

You have two public properties, one uses underscores the other camelCase. I would suggest picking a particular naming scheme and sticking to it. Consistency is important.

Your code seriously violates the arrow anti-pattern. You might consider refactoring to remove some of the indentation and if/else statements. For instance, reversing the first if/else and returning early will allow you to then drop the else, thus removing one level of indentation from your entire method.

if( ! $url ) {
    $controller = new $this->start_page;
    $controller->index();
    return;
}

//etc...

I've never been one for magic numbers and these vague array keys bug me. It shouldn't be necessary to provide comments to understand what each array key does. I would consider padding an array to ensure the size then creating a list. At the same time you can run each component through a loop to clean it. I'm wanting to say you can use array_map() or array_walk() instead of the loop, but I don't feel like trying to figure that out right now. I'm not quite sure what your REGEX is doing so I don't know if there is a better way, but check out filter_var(), that may do what you need.

$components = explode( '/', $url, 3 );
foreach( $components as $key => $component ) {
    $components[ $key ] = preg_replace( '/[^a-z-]/', '', $component );
}
$components = array_pad( $components, 3, FALSE );

list( $class, $method, $params ) = $components;

By the way, where did $class originally come from? The first time I see it is when you check to see if it exists in the $staticRoutes property. If that is a global you should know that globals are evil and you should be ashamed.


TrieContainer[26] contains a magic number. Since we can calculate with char I'd write TrieContainer['Z' - 'A' + 1] to make it clear.

I'd use System.out.printf("\n%b", isWordPresent(start, "abcd")) rather than string concatenation System.out.println("\n"+isWordPresent(start, "abcd")).

I'd let if follow by a space to distinguish it from method invocations (as you do it with for). I'd also surround else with spaces.

You're inconsistent in surrounding operators with spaces or not. Do the former.

I'd rename isFound to isWordFound.

Since the variables character are just local to for I'd call them just ch.

character-97 can be replaced with ch - 'a' then.

Array indices can be char, too. So:

for (int i = 0; i < start.series.length; i++) {
    ...
    ... (char)(97+i));

... can be changed to:

for (char ch = 0; ch < start.series.length; ch++) {
    ...
    ... (ch + 'a'));

I think start isn't an ideal name. With this if(start.isEnd) looks somehow irritating.

Having just static methods in Trie and public variables in TrieContainer doesn't look well-designed.


The first thing I had to do when seeing your code was looking up “LRU”. Apparently it stands for “Least Recently Used”, something to do with caching.

In your constructor, you initialize the map. This could also be done at the point of declaration:

private final Map<K, Entry<K, V>> map = new HashMap<K, Entry<K, V>>();

You also keep the eldest entry around – it would be more idiomatic to call it the oldest entry.

In your Entry class, I would swap the arguments to (key, value, left, right). Just because one variable points to the left sublist, this does not mean that it has to be the leftmost parameter in the constructor. For each node, the key and value are the more important information, and should come first. Actually, you never use left and right in the Entry constructor.

(…time goes by, now I understand you are implementing a circular buffer as a doubly linked list…)

It would be beneficial to add some helper methods in the Entry class, as this would be better encapsulation.

/**
 * An Entry in a (circular) doubly linked list.
 */
private static class Entry<K, V> {
  K key;
  V value;
  Entry<K, V> left, right;

  Entry(K key, V value) {
    this.key   = key;
    this.value = value;
  }

  /**
   * Connect "this" and "left" so that "left" is on the left side.
   *
   * @param left The new left side, may be null
   * @return This entry
   */
  Entry<K, V> addLeft(Entry<K, V> left) {
    this.left = left;
    if (left != null) left.right = this;
    return this;
  }

  /**
   * Connect "this" and "right" so that "right" is on the right side.
   *
   * @param right The new right side, may be null
   * @return This entry
   */
  Entry<K, V> addRight(Entry<K, V> right) {
    this.right = right;
    if (right != null) right.left = this;
    return this;
  }

  /**
   * Insert this entry between the specified nodes, keeping track of backlinks.
   *
   * @param left  The new left side, may be null
   * @param right The new right side, may be null
   * @return This entry
   */
  Entry<K, V> insertBetween(Entry<K, V> left, Entry<K, V> right) {
    return this.addLeft(left).addRight(right);
  }

  /**
   * Remove this entry out of the linked list, so that the left
   * and right entries now connect to each other directly.
   */
  void remove() {
    if (this.left  != null) {
      this.left .addRight(this.right);
    }
    else if (this.right != null) {
      this.right.addLeft (this.left );
    }
    this.left = this.right = null;
  }
}

Doing so would also increase testability of your design, and it makes it easier to reason about your code.

This now simplifies your other methods, e.g. addFirst becomes

private void addFirst(Entry<K, V> entry) {
    remove(entry);
    if (oldest == null) {
        oldest = entry.addLeft(entry); // implies addRight(entry)
    } else {
        entry.insertBetween(oldest.left, oldest);
    }
}

and remove simplifies to:

private void remove(Entry<K, V> entry) {
    assert entry != null;

    if (entry == oldest) oldest = entry.right;
    entry.remove();
}

The remaining methods are Ok, because they build upon these operations.

In general, the lack of comments made it very hard for me to understand your code.

For example, I was wondering why you weren't using a LinkedList as a Queue. Then I realized that removing an element would be O(n) instead of O(1). It makes sense to keep track of design decisions in comments, and to specify complexity guarantees in the documentation.
Then, such comments like “Allowing null. Since, this is behavior of linkedhashmap.” do not convey useful information. What variable may be null? What is linkedhashmap? What does all of that have to do with insertion?

The algorithmic side was excellent, but your code was rather hard to understand.


It's not terrible as it is, but you're right to wonder if there's a better way.  As you noticed already, it would be nice to keep the associations between the abbreviation and the corresponding directory in one place.

Fortunately, there's a very slick way to to that.  First, create a text file file that contains just the file associations:

e.txt

db      D:\Alex\Dropbox
bin     D:\Alex\Scripts\Bin

e.cmd

@echo off
FOR /F "tokens=1,2" %%i in (e.txt) do if "%~1" EQU "%%i" ( explorer "%%j" & EXIT /B )
ECHO Invalid target %target%.

This uses a relatively obscure feature of the FOR command that allows us to parse a file.  You can read more about that by executing HELP FOR from the command line.

Naturally, in the real version, you'd want to specify the full path to the e.txt file.

Allowing spaces in directory names

If you might have spaces in the directory names, you can do so with little additional effort.  For example, we can use = for the delimiter in the text file so that each line now looks like this:

sp=D:\Alex\Scripts\Advanced Scripting

Now just modify the script so that we specify the delimiter.  To do that change the part of the line that says "tokens=1,2" to read "tokens=1,2 delims==" and that's it.


Linq IEnumerable extensions for void functions

This is generally considered to be a bad idea. IEnumerable has deferred execution, which means that in your example, someList can be forced to enumerate any desired number of times.

As a consequence, it depends on the implementation behind the IEnumerable whether any changes applied by action will still be visible after your methods have run. There are two possibilities:

someList is a materialized list (for example, List<SomeObject>). After running ForEachAction, a new enumeration of someList will produce the same, modified, objects.
someList is an enumerable that produces new objects on each execution. After running ForEachAction, a new enumeration of someList will produce new objects. The changed objects are out of scope and will soon be garbage collected.

An example of the second option is an IQueryable against a SQL backend. When it is executed it will emit a SQL query that returns new objects from the database (caching as applied by many ORMs aside).

In that case it totally depends on what happens in action whether any effect of it is persistent. If action only modifies objects in someList its effect will be lost. If it uses objects in someList to change some external state (e.g. increment some sum value) its effect will persist.

As a conclusion, I wouldn't do this. If you want to apply void methods to any IEnumerable, first materialize it to a list and then apply existing methods. Instead of...

someList.ForEachAction(x => x.Update());

...you'd have...

var concreteList = someList.ToList();
concreteList.ForEach(x => x.Update());

Now continue working with concreteList so you'll be sure that the effect of x.Update() will remain visible in your code.


Functionaly Finding Prime Factors with Multiplicity

First of all, we can make your prime_factors_mult easier to read if we use where:

prime_factors_mult :: Int -> [(Int, Int)]
prime_factors_mult n = reverse . fst . foldl go ([], n) $ candidates
  where
    candidates = [2 .. floor . sqrt . fromIntegral $ n]
    go acc@(factors, val) x
      | val `mod` x == 0 = let (k, v) = reduce val x in ((x, k) : factors, val `div` v)
      | otherwise        = acc

By the way, Haskell programs use camelCase, so primFactorsMult would be appropriate. However, does this function really capture your intend? Let us write it as imperative variant for a second:

# pseudo-python
def prime_factors_mult(n):
    result = []

    for i in range(2, sqrt(n)):
        count = 0
        while n % i == 0:
            n = n / i
            count = count + 1

        if count > 0:
            result = result.append({i, count})

    return result

This is a lot easier to read. We should strive to have an algorithm in Haskell that's just as easy to read, right? By the way, both the pseudo-code as well as your original code contained an error: what happens on 2*7? \$\sqrt{14} < 7\$, therefore we never check the second prime. We should check that too:

# pseudo-python
def prime_factors_mult(n):
    result = []

    for i in range(2, sqrt(n)):
        count = 0
        while n % i == 0:
            n = n / i
            count = count + 1

        if count > 0:
            result = result.append({i, count})

    # n is prime at this point:
    if n > 1:
        result = result.append({n, 1})

    return result

Allright. Now let's try to get a variant of Haskell that's just as readable. We do that by explicit recursion and then later figure out how we can get rid of that:

isDivisibleBy n k = n `rem` k == 0

primeFactorsMult :: Int -> [(Int, Int)]
primeFactorsMult = go 2
  where
    go _ 1 = []
    go k n
       | n `isDivisibleBy ` k = (k, m)   : go (k + 1) (n `div` d)
       | n < k * k            = [(n, 1)]
       | otherwise            = go (k + 1) n
      where
        (m, d) = reduce n k

Allright, that seems to work. However, do we actually need the isDivisibleBy check? No. reduce does that for us. So let's get rid of that:

primeFactorsMult :: Int -> [(Int, Int)]
primeFactorsMult = filter ((0 /=) . snd) . go 2
  where
    go _ 1 = []
    go k n
       | n <= k    = [(n, 1)]
       | otherwise = (k, m)   : go (k + 1) (n `div` d)
      where
        (m, n') = reduce n k

Great. Now we're getting somewhere. We have now two paths we can choose to continue. Either we take our new approach, which is essentially mapAccumL, or we inline reduce. Let us follow both.

Mapping with a state

In the code above, we essentially mapped over the list of factors [2..n] with a state: the current value of n, or rather n `div` d. It turns out that there is already a function for that kind of operation, namely mapAccumL. We can incorporate into our function:

primeFactorsMult :: Int -> [(Int, Int)]
primeFactorsMult n = filter ((0 /=) . snd) . snd . mapAccumL go n $ 2 : [3,5..n]
  where
    go n k = (n `div` d, (k, m))
      where
        (m, n') = reduce n k

As you can see, we got rid of the recursive calls in go and the base case, since that's now handled by mapAccumL. We also swapped the arguments, since mapAccumL gives the state first. Also, since primes are odd (except for 2), we've optimized the list slightly.

Unfortunately, we still need to get rid of those with 0 multiplicity. However, what if we didn't return a pair?

Return factors, one by one

This time, we inline the functionality of reduce:

primeFactors :: Int -> [Int]
primeFactors n = go 2
  where
    go _ 1 = []
    go k n = case n `quotRem` k of
               (q, 0) -> k : go k q
               _      ->     go (k + 1) n

This will now return a list like [2,2,2,2,2,2,2,2,2,5,5,5,7,7,9,9,10]. By the way, this quotRem shows a possible optimization of reduce:

reduce :: Int -> Int -> (Int, Int)
reduce val x =
    if m == 0 then
        let (k, v) = reduce d x in (1 + k, v * x)
    else
        (0, 1)
 where
    (d, m) = val `divMod` x

But when all your numbers are positive, you want to use quotRem since it's usually faster. Note that many modern processors do mod and div at the same time, so using the appropriate function when you ened both results can be a boon.

Back to our prime factors. Now we have the factors. But how can we get the multiplicity? We use group:

primeFactorsMult :: Int -> [(Int, Int)]
primeFactorsMult = map (\xs -> (head xs, length xs)) . group . primeFactors

Since group returns only non-empty lists, we can safely apply head.

Remarks on style

I strongly suggest you to move large lambdas into their own bindings. That made the first variant of prime_factors_mult more readable and is the usual style, for example in GHC's code.

Also, if you use both the results of div and mod use divMod, or—if you use positive numbers only or don't want the specific behaviour behind divMod—quotRem.

Don't be afraid to give something in your code a name. That makes it easier to grasp and to change later. Also, you might notice that a function is reusable.

And, by the way, primes are a "hard" topic, as in: it's not easy to get proper bounds of the numbers you have to check, since you would need to know whether n is already a prime, or whether n / 2 is a prime, or n / 3 and so on.

Exercises

In go you can use (k + 2) if you handle 2 separately. How can you do that?
In most go functions we can stop much, much sooner if n is a prime if we know the original n. Why? (Hint: what is the largest prime factor that can be in a number? And what is the second largest prime factor?)


Counting permutations without repetitions for a number or a string

One of the best ways to make a program faster is not to compute things that you don't have to. In this question you are asked to compute the number of permutations. But your implementation goes and constructs all the permutations themselves, only to throw them all away again. It would be better to count them directly, via some kind of a mathematical formula.

Let's take a simpler example to show how this might work. Supposing that you knew that the string you are given has no repeated characters, for example ABC. Then the permutations are:

ABC ACB BAC BCA CAB CBA

but we can count them by observing that there are 3 choices for the first letter, 2 for the second, and one for the third, hence the total number of permutations is \$3 × 2 × 1 = 6\$. We call this "3 factorial" and write \$3! = 6\$.

In the actual question, the string might have repetitions. So let's look at a simple example. Suppose we are given the string AABC, with a repeated letter. Let's distinguish the two copies of A (for the moment) by writing one of them as a and generate all \$4! = 4 × 3 × 2 × 1 = 24\$ permutations:

AaBC AaCB ABaC ABCa ACaB ACBa BAaC BACa BCAa CAaB CABa CBAa
aABC aACB aBAC aBCA aCAB aCBA BaAC BaCA BCaA CaAB CaBA CBaA

You'll see that these permutation come in twos: one with A before a (I've put these in the top row) and the other with a before A (in the bottom row). Two is of course the number of permutations of two items: \$2! = 2\$. So if we go back to the situation where A and a are indistinguishable, there are \${4! \over 2!} = {24 \over 2} = 12\$ permutations.

One more example. Suppose the string is AAAB, with one letter repeated three times. Let's distinguish the three copies as before, and generate all \$4 × 3 × 2 × 1 = 24\$ permutations:

AaαB AaBα ABaα BAaα
AαaB AαBa ABαa BAαa
aAαB aABα aBAα BaAα
aαAB aαBA aBαA BaαA
αAaB αABa αBAa BαAa
αaAB αaBA αBaA BαaA

You'll see that these permutations come in columns of six: in each column there's one with A before a before α, one with A before α before a, and so on, for each of the \$3! = 6\$ permutations of Aaα. So if we go back to the situation where all the As are indistinguishable, there are \${4! \over 3!} = {24 \over 6} = 4\$ permutations.

In the general case where you have a string of \$n\$ letters where \$n_1\$ of them are identical, and another \$n_2\$ of them are also identical, and so on, then the number of permutations is the multinomial formula $$ {n! \over n_1!\,n_2!\ldots n_k!}. $$

So that's easy to program, using collections.Counter to count the number of occurrences of each character in the string, and math.factorial to compute the factorials:

from collections import Counter
from math import factorial

def permutation_count(s):
    """Return the number of different permutations of s."""
    s = str(s)
    c = 1
    for i in Counter(s).values():
        c *= factorial(i)
    return factorial(len(s)) // c

And since it doesn't have to construct all the permutations, it can count large numbers of permutations in a fraction of a second:

>>> permutation_count('AAAABBBCCDDEEFFGHIJKLMNOPQRSTUVWXYZ')
4484873249299542070167817420800000000

A quick timing comparison. First, your code from the post:

>>> from timeit import timeit
>>> timeit(lambda:perms('AAABBCDEF'), number=1)
201.83495365083218

Second, the revised code using a set:

>>> timeit(lambda:len(set(permutations('AAABBCDEF'))), number=1)
0.09620095230638981

Third, counting them directly:

>>> timeit(lambda:permutation_count('AAABBCDEF'), number=1)
5.3646042943000793e-05

That's about 54 microseconds, about 3.7 million times faster than the code in the post.


recv() is a system call, which has relatively high overhead.  You should avoid calling recv() just to read one byte at a time.  Instead, read a reasonable sized buffer (something like the size of an IP packet).  Your wrapper object should maintain a buffer of bytes that have been returned by a previous call to recv() but that have not yet been returned to the caller (bytes after a newline character).

In implementing such a buffered interface, you would be forced to use the return value of recv() correctly.  recv() returns the number of bytes read, or -1 if an error occurred.  The error code is stored in the errno global variable, not the return value of recv().


Function to find sum of digits in the number a^b where a, b are positive integers

The problem calls for computing the sum of digits in 21000.  You did 210000.  Overachiever!

There are a few things you could do to improve readability.

char *arr looks a lot like a string.  One might initially think that you are storing the number as a string (i.e., ASCII '0'… '9').  You could dispel that impression by changing it to unsigned char *arr.  To be even clearer, I would use a typedef unsigned char digit; so that you can declare digit *arr.  Then it is clear that you are using binary-coded decimal.

As long as you are doing binary-coded decimal, there is no advantage to putting the most-significant digit first.  With the least-significant digit first, the code is simpler, and there is the nice property that the number is sum(arr[i] * 10**i for i in range(len(arr))).

For further readability, I would define a struct to represent the big decimal:

typedef unsigned char digit;

typedef struct {
    int capacity;
    int dcount;
    digit *digits;  /* Unsigned binary-coded decimal. The number is
                       sum(arr[i] * 10**i for i in range(dcount)) */
} bigdecimal;

There are a lot of variables in your sumdigit() — not quite a mess, but enough to start being concerned.  The function name sumdigit is also a bad code smell.  I would also decompose the operations for readability.  (Defining the bigdecimal type makes that practical.)

void mult(unsigned int a, bigdecimal *b) {
    int carry = 0;

    for (int i = 0; i < b->dcount; ++i) {
        int sum = a * b->digits[i] + carry;
        carry = sum / 10;
        b->digits[i] = sum % 10;
    }

    while (carry > 0) {
        int sum = b->digits[b->dcount] + carry;
        carry = sum / 10;
        b->digits[b->dcount] = sum % 10;
        b->dcount++;
    }
}

bigdecimal *exponentiate(unsigned int base, unsigned int power) {
    bigdecimal *result = malloc(sizeof(bigdecimal));
    result->capacity = 1 + (int) (power * log10(base));
    result->digits = calloc(result->capacity, sizeof(digit));

    /* base**0 == 1 */
    result->digits[0] = 1;
    result->dcount = 1;

    for (int p = 0; p < power; p++) {
        mult(base, result);
    }

    return result;
}

unsigned int sumdigit(bigdecimal *b) {
    unsigned int sum = 0;
    for (int i = b->dcount - 1; i >= 0; --i) {
        sum += b->digits[i];
    }
    return sum;
}

void free_bigdecimal(bigdecimal *b) {
    free(b->digits);
    free(b);
}

int main(void) {
    bigdecimal *n = exponentiate(2, 1000);
    printf("%u\n", sumdigit(n));
    free_bigdecimal(n);
    return 0;
}

I've used C99 variable scoping in the for-loops because it's nicer.


You really don't need two queries to do this. You can just use your second query, and if it doesn't return any results, report that. Eg:

$stmt = $conn->prepare("SELECT pw FROM Users WHERE email = ? LIMIT 1");
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();

if(mysqli_num_rows($result) == 0){
    echo "Email has not been registered yet";
}

$pwHashed = $result->fetch_assoc();
if(password_verify($pw, $pwHashed["pw"])){
    echo "Password correct";
}else{
    echo "Password incorrect";
}

Other than this, your code looks good. You use prepared statements, so it's secure, and your style is consistent and easy to read. I would probably write pw as password as it's more readable, but otherwise everything looks good.


MySQL limit across multiple tables in multiple queries

Yes, there is: create a stored procedure and UNION the result sets then sort the records and return them to PHP.


Being inspired by recent xkcd comic I will review this particular piece of code:

res := strings.Split(r.URL.Path, "/")
path, err := strconv.Atoi(res[1])

As far as I understand it converts path string "/123" to int 123.

I see several issues here:

this code creates unnecessary (and possibly large) slice,
assumes that res[1] is always there,
parses negative numbers,
and allows input /123/whatever/goes/here/.

Split

Use strings.SplitN when you know how many parts of the slice you need. On /a/b/c/d/ input strings.Split will create slice with six items, but you need only res[1].

..

url.URL documentation states, that relative paths may omit leading slash. So on .. or . input access to res[1] will trigger panic with "runtime error: index out of range" message.

Malicious HTTP request may contain lots of crap similar ../.. so is crucial to validate this.

I suggest you to check that the path begins with a slash or test the length of res.

stronv.ParseUint

strconv.Atoi allows negative numbers. You can use strconv.ParseUint instead.

Path from HTTP request is same thing as any other form of user input. Proper handling of it is full of gotchas.

I suggest you to check that path begins with a slash and use strings.TrimSuffix to remove one possible trailing slash:

// Check that r.URL.Path begins with "/",
if (r.URL.Path[0] == "/") {
    // skip leading slash and trim one(!) possible trailing shash.
    num := strings.TrimSuffix(r.URL.Path[1:], "/")
    // Try to parse non negative number,
    tmp, err := strconv.ParseUint(num, 10, 32)
    if err != nil {
        // and return 404 if there is no one.
    }
    // Convert uint to int.
    index := int(tmp)

    // function body continues...
}


It doesn't feel right, because you have a lot of repetitive code.

Notice how each property selector's where statement contains

        where objectiveIds.Contains(winner.ObjectiveID)
        where winner.Active
        where winner.UserID == up.UserID

That means you can refactor this where condition to a join in the containing query.

Also, you specify an order by clause, when you are only using the values to get the Count().  This does nothing but take up space and time.

I think this query might be more along the line of what you are trying to achieve:

        var rankingDtos =
                    from user in MetaData.UserProfile
                    let userWinners = from winner in MetaData.Winner
                                      let objectives = from objective in MetaData.Objective
                                                       where winner.ObjectiveID == objective.ObjectiveID
                                                       select objective
                                      where winner.UserID == user.UserID && winner.Active
                                      orderby winner.CreatedOn descending
                                      select new
                                                 {
                                                     Winner = winner,
                                                     Objectives = objectives
                                                 }
                    select new RankingDTO
                               {
                                   UserId = user.UserID,
                                   FirstName = user.FirstName,
                                   LastName = user.LastName,
                                   LastWinnerDate = userWinners.First().Winner.CreatedOn,
                                   WinnerCount = userWinners.Count(x => objectiveIds.Contains(x.Winner.ObjectiveID)),
                                   Video1 = userWinners.Count(x => x.Objectives.Any(o => o.ObjectiveNm == Constants.Promotions.SecVideo1)),
                                   Quiz1 = userWinners.Count(x => x.Objectives.Any(o => o.ObjectiveNm == Constants.Promotions.SecQuiz1))
                               };


Finding the longest Collatz sequence cycle

Formatting
USE PROPER INDENTATION - Please!
If you're using Eclipse, press Ctrl + Shift + F.
If you're using Netbeans or IntelliJ, press Alt + Shift + F.
If you're not using any IDE, start doing so!

Braces
Once your code is properly formatted it can be seen that you're not using braces here:
if (j < 50000000)
    arr[(int) (j - 1)] = count;

It is especially important to use braces when you're code's not formatted properly, as it is easy to accidentally add an extra statement inside the if, which would cause unexpected results.
if (j < 50000000) {
    arr[(int) (j - 1)] = count;
}

Close Scanner
Scanners should be closed when they have been used. sc.close(); at the end of your program will take care of that.

Unnecessary outer while
Your outermost while "loop" is only executed once because there is a break; at the end of it. This could be an if instead and the break; at the end removed.

Use the length of the array
if (j < 50000000) {

and
if (n < 50000000) {

Should instead be:
if (j < arr.length) {

and
if (n < arr.length) {

respectively.

Slight simplification
if (n % 2 == 0) {
    n = n / 2;
    count++;
}
else {
    n = (3 * n) + 1;
    count++;
}

Can be written as:
n = (n % 2 == 0 ? n / 2 : (3 * n) + 1);
count++;

Or at least, if you don't like the conditional operator (... ? ... : ...), use the if-else for n but do count++ before or after the if/else.

Variables
Your naming leaves some things to be desired. x and y for example should be named startTime and endTime, the current names makes it sound like it is related to coordinates, which it is not.
The only variable with any meaning is max and count. It is hard to tell what kind of max max is though, naming it maxCycles would make that clearer.
As for your other variables, long i, j, n, pos, I certainly cannot tell what they're used for without looking at your code for a while. These variable names tell me absolutely nothing!
To get a better overlook of the variables, it is better to declare the variables as close to their usage as possible. y (endTime) is declared at the top, but not used until the end of the method.

Extract Method
Your main method is doing way too many things right now.
Extract parts of your code to different methods:
For example, your entire while (n != 1) loop can be extracted to a determineCycles method.

Speed Improvement
Currently you're saving the result of one calculation into your array, and while that's a good start you are missing out on some values you can use.
Let's take the example of 3. The sequence is: 3, 10, 5, 16, 8, 4, 2, 1
The only result you are storing from this operation is 3 --> 7. But you have also found out that 10 has the value 7 - 1, 5 has the value 7 - 2, 16 has the value 7 - 3 and so on... Your algorithm would increase significantly in speed if you were also storing these intermediate values.


Determine number of even, odd, and zero digits of a given integer

Do not see the point in: get_line()

get_line(line);

// Vs

std::getline(std::cin, line);

Get Integer is well done. Most people forget to test if there is anything else remaining on the line.

A simple enhancement is:

        char remaining;
        if(converter >> remaining)

        // easier to rewrite as:
        if (!converter.str().empty())

Also there is already a boost function that does something similar:

long value = boost::lexical_cast<long>(line); // Will throw if anything left on line.

Over complicating this:

    num = (num - (num % 10))/10;

You can simplify it too:

    num /= 10;  // Integer division truncates.

I think this is a logical error:

    if(res == 0){
        zero++;
    }
    else if(res % 2 == 0){ // zero is an even number
                           // do you really want that else?

Your one major error is:

int oez[3] = {odd,even,zero};
return oez;

You are returning a pointer to an array that has gone out of scope. Personally I would return a std::vector<int>. Don't worry on a simple returning like this the copy back of the array will be optimized out (look up RVO and NVRO).

std::vector<int> oez = {odd,even,zero};
return oez;


Here are some examples of how most apps do:

Apache renders everything in the folder. If you want to hide access to a subfolder, you do that with an htaccess in this subfolder.
Define each route yourself. This'd mean having a whitelist in your case. (In some array or something.)
Keep the routes in the database. This allows you to handle permissions easily.

I haven't often seen the blacklist way. Why? Because of a simple security principle: blacklists may accidentally treat bad input as safe.


Composition or Private Inheritance for Implementing Builder?

Herb Sutter in his book 'Exceptional C++', Item 24 (Uses and Abuses of Inheritance), discusses the issue, and cites the following reasons for using private inheritance (instead of containment):

Override a virtual function
Access to a protected member
Construct the used object before, or destroy it after, another base sub-object
Share a common virtual base class or override the construction of a virtual base class
We benefit substantially from the empty base class optimization
We need "controlled polymorphism" - LSP IS-A, but in certain code only

If one of these situations applies, then you must use private inheritance.  Otherwise, containment is preferred.

The last of these reasons is cited as a possible reason for protected inheritance.

He also comments:

  That's as complete a list as I can make of the reasons to use non-public inheritance.  (In fact, just one additional point would make this a complete list of all reasons to use any kind of inheritance: We need public inheritance to express IS-A. [...])

The item occupies 8 pages.


You don't need to store the whole file contents, compute hash instead. Also converting each image to JPEG is not necessary, use image.RawFormat, it would be a bit faster.
using (SHA256 sha = SHA256.Create())
using (var ms = new MemoryStream((int)new FileInfo(file).Length))
{
    image.Save(ms, image.RawFormat);
    ms.Position = 0;
    data = Convert.ToBase64String(sha.ComputeHash(ms));
}

2nd option
if (!uniqueData.Contains(data))
{
    uniqueData.Add(data);
    // ...
}

Can be simplified to
if (uniqueData.Add(data))
{
    // ...
}

Also twice getting the directoriry files can be once
string[] files = Directory.GetFiles(imageFolderPath);
int fileCount = files.Length;

foreach (var file in files)
{
    // ...
}

And finally this one
if (!Directory.Exists(yearDirectory))
{
    Directory.CreateDirectory(yearDirectory);
}

Directory.CreateDirectory creates directory if it not exists, otherwise it does nothing. You can remove Exists check.
Directory.CreateDirectory(yearDirectory);


I would say your design is fine. In general I advise injecting IHandleViewModel<T> implementations directly into consumers, because this makes it easier to verify the object graph directly and makes it clearer what the consumer actually depends on. You should do this, unless you regularly inject multiple IHandleViewModel<T>s into the same consumer, while you are pretty sure that these consumers are NOT violating the Single Responsibility Principle.

But if you decide to inject the ViewModelProcessor mediator, I advice to add a single unit/integration test to the system that verifies whether there is an IHandleViewModel<T> implementation for each view model in the system. This prevents you from getting an exception at runtime because an implementation is missing.

The IViewModel marker interface gets useful when writing such unit test, because this interface allows you to find all view models easily as follows:

// Arrange
var viewModelHandlerTypes =
    from assembly in AppDomain.CurrentDomain.GetAssemblies()
    from type in assembly.GetTypes()
    where typeof(IViewModel).IsAssignableFrom(type)
    where !type.IsAbstract && !type.IsGenericTypeDefinition
    select typeof(IHandleViewModel<>).MakeGenericType(type);

// Act
viewModelHandlerTypes.ToList().ForEach(container.GetInstance);

About Async Programming

A last suggestion I would like to make is to get rid of the complete async programming model. Asynchronous methods tend to spread through your application like a virus and make both programming and debugging your application much harder. Yes, this asynchronous programming has become WAY easier than it used to be, but it is STILL harder than synchronous programming and it will probably stay harder untill the .NET runtime has been rewritten from the ground up (if that's even possible).

I know this is against popular opinion, but there is hardly ever a reason to polute your entire code base with this asynchronous programming model. Main reason for Microsoft to push this programming model really hard is because it is more efficient when running in the cloud. This makes sense, because in Azure, you pay per CPU cycle and per the number of machines you need. But on the other hand, asynchronous programming costs way more developer cycles, and because developers are quite expensive, it is quite unlikely that your savings on the Azure bills will actually compensate the extra developer costs. But obviously, you will have to do the math yourself.

Don't get me wrong, of course we want -and need- responsive UIs so we might need a few async/await calls inside your Window, Page or View Model classes in our presentation layer built with WPF, Silverlight, Win Forms or some other client technology. You can still do this, even though your whole code base below is synchronous, with synchonous calls to the database, web services and the file system. When doing that, you will still be able to make your UI responsive, but the only difference is that you'll have a background thread sleeping most of the time, instead of using I/O completion ports. But I've never ever worked on an application where having this single extra background thread was a problem. Even for Windows Phone applications this is a non-issue.

But since you're building an MVC application, don't bother in making your controller code asynchronous, the user's browser will wait anyway, even if you make your controller asynchronous.

Asynchronous programming may be the new shiny thing in the .NET world, and with some training and experience, we can become quite effective as developers in applying it, but even than it is more painful than synchronous progamming (which is hard enough by itself), and instead of spending money on training developers learning how to do async, I rather spend this money in training them to learn the SOLID design principles, Test Driven Development, Functional Programming or writing clean code. There are so many other skills that are probably more important and more effective in reducing the total cost of ownership, that I rather have my money on that first.


This is the textbook example of an inner join. The most canonical way to have your id columns being used for the matching, set them as an index first (here using inplace operations to save on extra variable names; depending on your use, you might prefer new copies instead):

dat1.set_index('id', inplace=True)
dat2.set_index('id', inplace=True)

Then, the whole operation becomes this simple join on index:

>>> overall_data = dat1.join(dat2, how='inner')
>>> overall_data

    dat1  dat2
id
2     56    19
3     57    19
4     45    20

If you do not want to modify the original DataFrames, you can use utility function merge instead, which performs the same operation, but needs the common column name specified explicitely:

>>>  pd.merge(dat1, dat2, how='inner', on='id')

   id  dat1  dat2
0   2    56    19
1   3    57    19
2   4    45    20


Rather than prompting for input, almost all shell scripts (including this) would be improved by accepting the static input (action and key) as arguments and then reading standard input to EOF to produce the output. For this you'll want a main method which just orchestrates argument parsing and passing the resulting values to the function or method which does the actual substitution. This makes it very easy to combine the script with other commands in a common way. argparse is very well suited for this.
Encrypting vs decrypting is simply a matter of shifting the characters left vs right. You can use this information to halve the code.
The brute force method should be implemented by running a single function 26 times.
In general, the code should be split into functions until there is no obvious duplication anywhere. This should massively simplify everything except the input handling, meaning that the interesting part of the script should end up being maybe three lines.
You should handle input one line at a time, so that even huge input results in small memory use.


Wrapper around a Python API for creating user interfaces

One thing you could do is ensure that events only reach those who are interested in that particular type of event. Right now you seem to be sending out a generic events that you then check to see what type they are.

I wrote a similar answer some time ago to another question on Stack Overflow. You can read it here:
► https://stackoverflow.com/questions/7249388/7294148#7294148


Algorithm to identify a shift and its type based on on and off times

First Things first:

Method Signature:

public string IdentifyShift(DateTime inTime, DateTime OutTime)

C# conventions state, that public methods should be PascalCased (check), and local variables, as well as private fields, should be camelCased (partly). Furthermore your calculations are not depending on anything, but the method itself, they don't access class fields. You can, could and should make it static.

public static string IdentifyShift(DateTime inTime, DateTime outTime)

TimeSpan, one Day:

DateTime from= Convert.ToDateTime("05/01/2014 12:00:00");
DateTime to=Convert.ToDateTime("05/02/2014 12:00:00");

TimeSpan aDay = (to - from).Duration();

Have you read up on the Constructors of TimeSpan? There is one, where you can do the following:

TimeSpan aDay = new TimeSpan(1,0,0,0);

Returning Strings:

Returning strings is.. well It can be horrendous. In your case it's not a good idea: you have 3 Predefined States: DayShift, NightShift, InvalidShift. These can be extracted to an enum structure. This would change your Method signature to the Following:

public static Shift IdentifyShift(DateTime inTime, DateTime outTime)

Given the case you introduce an enum like this:

enum Shift
{
   DayShift, NightShift, InvalidShift
}

Conditions in itself:

  Day shift - From 7AM to 7PM
  Night shift - From 7PM to 7AM (on the next day)
  The employee should report before 8AM for a day shift, otherwise the shift will not be taken into account.
  The employee should report before 8PM for a night shift, otherwise the shift will not be taken into account.
  If an employee leaves before the regular off time of a shift, that shift will not be taken into account.

This gives following conditions, assuming inTime is before outTime (and they are not more than one Day apart):

DayShift: if(7AM <= inTime(hour) < 8AM AND 7PM < outTime(hour))
NightShift: if(7PM <= inTime(hour) < 8PM AND 7AM < outTime(hour))
InvalidShift: all else

Keep in mind, that as soon as the clock shows 08:00:00 / 20:00:00 respectively, that marks the shift as invalid.

Extracting Magic Numbers

You can further clarify the intentions of your Code, if you extract the magic numbers (7AM, 7PM, and so on) to named constants:

const int DAY_SHIFT_START = 7;
const int DAY_SHIFT_DEADLINE = 8;
const int NIGHT_SHIFT_START = 19;
const int NIGHT_SHIFT_DEADLINE = 20;

You can thus simplify your code to the following:

public static Shift IdentifyShift(DateTime inTime, DateTime outTime)
{
    if (inTime >= outTime)
    {
        throw new ArgumentException("inTime is not before outTime");
    }
    if ((outTime - inTime).Duration() > new TimeSpan(1, 0, 0, 0))
    {
        throw new ArgumentException("outTime is more than 24 hours after inTime");
    }

    int inHour = inTime.Hour;
    int outHour = outTime.Hour;
    if (inHour >= DAY_SHIFT_START &&
        inHour < DAY_SHIFT_DEADLINE && outHour > NIGHT_SHIFT_START)
    {
        return Shift.DayShift;
    }
    else if (inHour >= NIGHT_SHIFT_START &&
        inHour < NIGHT_SHIFT_DEADLINE && outHour > DAY_SHIFT_START)
    {
        return Shift.NightShift;
    }
    else
    {
        return Shift.InvalidShift;
    }
}


Is this good approach to use debug functions for implementing features?

Since this is a code review site, let me point out that the following is an abomination:

return (0 == ($v % 2)) ? false: true;

The constants are redundant. Much simpler:

return (0 != ($v % 2));

(The parentheses are also redundant but that’s unrelated.)


I see a number of issues with your code, but let me answer your questions first:

1. Will the Pushbuttons and lineEdits get destroyed once 'container' is destroyed?

Yes, the pushbuttons and lineedits get destroyed when container gets destroyed

2. Do I need to destroy m_contact separately?

I do not see where m_contact is created. In the above code you just declare a pointer to a MainContact object. Nothing is created/allocated, so nothing needs to be destroyed.

Recommended reading is the detailed description of the QObject documentation:

  QObjects organize themselves in object trees. When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor.

I have the impression that you do not have a clear idea what you need to do with all the pointers/objects etc. If my further comments sound like spoonfeeding, then I'm sorry for this. But I think a step-by-step discussion of your code will help you (my comments always after the code):

class MainDialog: public QWidget {

here you declare your class as a subclass of QWidget. this means your class will be a QWidget and therefore a QObject too.

        Q_OBJECT
    public: MainDialog(QWidget *parent=0);
    private:
        QPushButton *m_newClick;
          QPushButton *m_editClick;
         MainContact *m_contact;

you declare three pointers. No object will be created by this. This is just your handle to have access to the objects later.

    }

MainDialog::MainDialog(QWidget *parent):QWidget(parent) {

with QWidget(parent) you initialize the QWidget component of your class MainDialog

    QWidget *container= new QWidget();

here you create a local pointer to a QWidget and create a new QWidget object without specifying a parent of this new object. Local means that this variable is only valid within the scope of this function. To be exact: the scope is between the curly brackets {}. The variable will be destroyed when the program flow leaves the scope.

    QPushButton *m_newClick =new QPushButton("New", container);
    QPushButton *m_editClick= new QPushButton("Edit", container);

here you create two new local pointers to QPushButton objects which (!!!) hiding the pointers that you have created as private members of your class. Not all compilers will warn you about this. Your code should be just this: m_newClick =new QPushButton("New", container);

    QLineEdit *m_text=new QLineEdit(container);

as above m_text is a local pointer and will point to a newly created QLineEdit object.

    QVBoxLayout *vlayout=new QVBoxLayout();
    QHBoxLayout *hlayout=new QHBoxLayout();
    hlayout->addWidget(m_newClick);
    hlayout->addWidget(m_editClick);
    vlayout->addLayout(hlayout);

This bit is correct. You are using local pointers to the layouts which is absolutely fine; you don't need them later on. One important point here: the ownership is transferred to the layout. That means, the container object is no longer parent of the pushbuttons.

You could avoid the use of local varables by writing it like this: hlayout->addWidget(new QPushButton("New")); but then you have no handle to connect with.

    connect(m_viewClick,SIGNAL(clicked()),this,SLOT(viewClick()) );

the variable m_viewClick is not defined. This is probably just a typo here on CR. But the slot viewClick() is also not defined in the class above.

    connect(m_newClick,SIGNAL(clicked()),this,SLOT(newClick()) );

same here: newClick() is not defined.

    setWindowTitle("Welcome");

    setLayout(vlayout);

here you set the layout that contains your previously constructed objects to this MainDialog object. MainDialog becomes the new owner of vlayout and with it all the pushbuttons and lineedits.

Perhaps you also need to call show().

}

here we are at the end of the scope of MainDialog constructor function. At this point the following variables will be destroyed: container m_newClick m_editClick m_text vlayout hlayout. These are just the pointers. Since the ownership of all the objects has been transferred, no object will be destroyed. This results in a "leak" of the container and m_text object.

Summary of the problems:

the container object is useless
the three private variables m_newClick m_editClick and m_contact are not used.
the local variables m_newClick and m_editClick hide private member variables. This is a perfect example why prefixes on member variables are bad.
don't connect non-existing functions.

The following is an example with the above suggestions implemented:

class MainDialog : public QWidget
{
    Q_OBJECT
public: MainDialog(QWidget *parent=0);
public slots:
    void newClick();
    void editClick();
    void endEdit();
}

MainDialog::MainDialog(QWidget *parent)
    :   QWidget(parent)
{
    QVBoxLayout * vlayout = new QVBoxLayout;
    QHBoxLayout * hlayout = new QHBoxLayout;
    QPushButton * newButton = new QPushButton("New");
    QPushButton * editButton = new QPushButton("Edit");
    QLineEdit * lineEdit = new QLineEdit();
    hlayout->addWidget(newButton);
    hlayout->addWidget(editButton);
    vlayout->addWidget(lineEdit);
    vlayout->addLayout(hlayout);

    connect(editButton, SIGNAL(clicked()), this, SLOT(editClick()) );
    connect(newButton, SIGNAL(clicked()), this, SLOT(newClick()) );
    connect(lineEdit, SIGNAL(editingFinished(), this, SLOT(endEdit()) );

    setWindowTitle("Welcome");
    setLayout(vlayout);
    show();
}


Your code looks promising but has some code smells.

When you have a big method you should consider splitting the method
up into methods/classes.
When you have a lot of code duplication you
should consider extracting common logic into methods/classes.
Your code is hard to test, consider extracting related logic into classes.

Example of a refactoring that could help you clean this code:

public class String_Hash_Generator  {

    public static void main(String args[]) throws NoSuchAlgorithmException {
        Scanner inputScanner = new Scanner(System.in);
        System.out.print("String: ");
        String input = inputScanner.next();

        CryptographyGenerator generator = new CryptographyGenerator();

        System.out.println("\nMD2: " + generator.generateMD2(input)
                + "\nMD5: " + generator.generateMD5(input)
                + "\nSHA-1: " + generator.generateSHA1(input)
                + "\nSHA-256: " + generator.generateSHA256(input)
                + "\nSHA-384: " + generator.generateSHA384(input)
                + "\nSHA-512: " + generator.generateSHA512(input));
    }
}

public class CryptographyGenerator {

    public String generateMD2(String input) throws NoSuchAlgorithmException {
        return generateString(input, "MD2", 32);
    }

    public String generateMD5(String input) throws NoSuchAlgorithmException {
        return generateString(input, "MD5", 32);
    }

    public String generateSHA1(String input) throws NoSuchAlgorithmException {
        return generateString(input, "SHA-1", 40);
    }

    public String generateSHA256(String input) throws NoSuchAlgorithmException {
        return generateString(input, "SHA-256", 64);
    }

    public String generateSHA512(String input) throws NoSuchAlgorithmException {
        return generateString(input, "SHA-512", 128);
    }

    public String generateSHA384(String input) throws NoSuchAlgorithmException {
        return generateString(input, "SHA-384", 96);
    }

    private static String generateString(String input, String algorithm, int minLength) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        byte[] bytes = messageDigest.digest(input.getBytes());
        BigInteger integer = new BigInteger(1, bytes);
        String result = integer.toString(16);
        while (result.length() < minLength) {
            result = "0" + result;
        }
        return result;
    }
}


Linq to entities query for donor registrations

First thing to do, is to layout the query so that you can actually read it. Optimizing something you can't read is not really possible.

var monthlySummary =
    (from county in context.Counties.AsEnumerable()
     let query = context.DonorStatusActions
                        .Where(x => x.Donor.CountyId == county.CountyId
                                 && x.ActionTakenOn >= prev
                                 && x.ActionTakenOn < next)
     let data = query
         .GroupBy(x => x.Donor, x => x, (key, grp) => new
             {
                 Item1 = key,
                 Item2 = grp.OrderByDescending(y => y.ActionTakenOn)
                            .FirstOrDefault()
             })
         .Where(x => x.Item2.IsDonor
                 && ((model.WebSignUp != "2"
                     && x.Item2.Donor.WebSignUp == (model.WebSignUp == "1" ? true : false))
                 || model.WebSignUp == "2"))
     let registrations = data.Select(x => x.Item2)
     let previous = registrations.Count(x =>
         x.ActionTakenOn >= prev && x.ActionTakenOn < curr)
     let current = registrations.Count(x =>
         x.ActionTakenOn >= curr && x.ActionTakenOn < next)
     select Tuple.Create(county.Name, previous, current)
    ).ToList();

Yikes!

Ok let's remove the fluff.

from county in context.Counties.AsEnumerable()

Counties is already an Enumerable - it's an IQueryable<County>, and by soft-casting it like this, you've told LINQ "don't bother translating that to T-SQL, give me all counties and let LINQ-to-Objects deal with it instead" (see this answer).

If you ran a SQL profiler when your code runs, I bet you're not going to see the T-SQL you'd expect.

Just do this instead:

from county in context.Counties

This part needs a cleanup:

 .Where(x => x.Item2.IsDonor
         && ((model.WebSignUp != "2"
             && x.Item2.Donor.WebSignUp == (model.WebSignUp == "1" ? true : false))
         || model.WebSignUp == "2"))

I'm scratching my head over this one:

x.Item2.Donor.WebSignUp == (model.WebSignUp == "1" ? true : false)

Why not just do this instead?

x.Item2.Donor.WebSignUp == (model.WebSignUp == "1")

I have to say that Donor.WebSignUp being a bool while model.WebSignUp is a string, is pretty confusing.

These magic "1" and "2" values are annoying. They have a special meaning, but nobody knows what it is. Looks like a misused string that should be an int, or even better, an enum.

Regardless, the condition is redundant and could be simplified to this:

 .Where(x => x.Item2.IsDonor && (
     model.WebSignUp == "2" || x.Item2.Donor.WebSignUp == (model.WebSignUp == "1")))

Be sure to profile the generated T-SQL and show execution plan to have SQL Server tell you if any index could speed things up; I suspect you might need one on Donors.WebSignUp, too.


"Longest Palindromic Substring" challenge solution is inefficient

Why is it slow?

The input string S can be up to 1000 characters.

Your DP solution considers all \$\mathcal{O}(|S|^2)\$ substrings of S and you're checking for each of these substrings, if it is a palindrome, in linear time in terms of the length of this substring.

Faster solutions

You can do it easily in \$\mathcal{O}(|S|^2)\$ using a polynomial hashing technique.

There are of course more sophisticated and linear solutions based on the famous Manacher algorithm.


Implementing a custom iterator by inheriting from an existing iterator class and overriding operator*

Use of public inheritance in this case strikes me as problematic.

Public inheritance means that a pointer/reference to an object of the derived class can be converted implicitly to a pointer/reference to the base class. Worse, it also means that an object of the derived class can be implicitly converted ("sliced") to an instance of the base class.

If that happens, you quickly run into a problematic situation: since operator * isn't defined as virtual in the base class, invoking it via a pointer/reference to base will invoke the base version of the operator. Your operator overload isn't really overriding the base class'--it's just hiding it.

This isn't saving a whole lot of work either--you're using an unordered associative container, which only provides forward iterators, so all your inheritance is saving is implementing operator++.

I suppose to be fair, I should add that people rarely pass iterators by reference, so it's not particularly likely that you'll trigger the problems outlined above. On the other hand, history teaches us that idiots can be surprising crafty in figuring out ways to shoot themselves in the feet.


Composing CPU instructions by merging four short hex strings

Assembly opcodes are not constructed with string manipulations. They are very carefully designed with bit positioning, so a simple add operation between two integers might not be the best way to describe it.

So your mergeHex method that god-knows-what does with strings should become a method that might do some bit shifting, masks, ...

I sampled the behavior of your mergeHex with two calls (which is not enough to know what it does for all your possible scenarios), but anyway I reached the following conclusion:

The output is a 16bits (word) hex string.
The first 8 bits are given by hexShared[0] | ((hexshared[1] & 0xF0) >> 4)
The last 8 bits are given by  ((hexshared[1] & 0x0F) << 4) | values[2]

Turning this into an algorithm becomes now trivial, let me suggest an implementation with some simplifications:

private static string ToWord(string[] hexTokens){
    var values = hexTokens
        .Select(t => HexToInt(t))
        .ToArray();

    var result = values[0] << 8 | values[1] << 4 | values[2];
    return result.ToString("X1");
}