Optimization of sieve of Erathosthenes #include <iostream>
    #include <conio.h>
    #include <windows.h>
    #include <math.h>
    using namespace std;
    #define RUNS 1000
    char z[100000];
    int i,j,k,c;

    void main(void)
      {
      DWORD starttime,endtime;
      float totaltime;

      starttime = GetTickCount();//get start time
      for(k=0;k<RUNS;k++)
      {
          c=0;

      //for (i=0;i<10000;i++) z[i]=0; //clear array
      memset(z,0,100000);
        z[0]=1; // 0 is not a prime
        z[1]=1;  // 1 is not a prime
            //now remove all evens from 4 up
            for(i=4;i<100000;i=i+2) z[i]=1; //remove evens
            //now loop through remaing up to square root of max number
            for(i=3;i<316;i=i+2)
            {
            if(z[i]==0) for(j=2*i;j<100000;j=j+i) z[j]=1;
            }
      }

      endtime=GetTickCount();//get finish time
      //calc time
      for(i=0;i<100000;i++)
      {
      if(z[i]==0) {cout<<i<<" ";c++;}
      }
      cout<<"primes found="<<c<<endl;
      totaltime=((float)endtime-(float)starttime)/(1000.0*RUNS);//calculate total time in secs
      cout<<"Totaltime="<<totaltime<<" sec\n";

      printf("Press any key to end");

      getch();
      }

I'm trying to find any optimization for my sieve of Eratosthenes code for counting first 100000 prime numbers.
The program first mark all even numbers, than square root of max number.
The program already does take fraction of the seconds to count these prime numbers, but I`m looking for any optimization to make it even quicker.

if (z[i] == 0)
    for (j = 2 * i; j < 100000; j = j + i)
        z[j] = 1;

can be changed to

if (z[i] == 0)
    for (j = i * i; j < 100000; j = j + 2 * i)
        z[j] = 1;

as

k * i (with k < i) is already set to 1 by sieve k.
when j is odd, j + i is even and so already set by even sieve.

For readability, you may split into function and do some renaming, to have something like:

const int N = 100000;
const int SQRT_N = 316;

void shieve(char (&isNotPrime)[N])
{
    memset(isNotPrime, 0, N);
    isNotPrime[0] = 1; // 0 is not a prime
    isNotPrime[1] = 1; // 1 is not a prime
    // now remove all evens from 4 up
    for (int i = 4; i < N; i = i + 2) {
        isNotPrime[i] = 1; // remove evens
    }
    // now loop through remaing up to square root of max number
    for (int i = 3; i < SQRT_N; i = i + 2) {
        if (!isNotPrime[i]) {
            for(int j = i * i; j < N; j = j + 2 * i) {
                isNotPrime[j] = 1;
            }
        }
    }
}


Extracting ids out of arguments of different types I'm building a Ruby API client. My brief is to extract ids out of various inputs and fetch the relevant data. It's working just fine at the moment but I think it's a little clumsy.

My specs (which pass):

shared_examples 'it requests ids' do |resource|
  it 'sends the ids to Foo::Client' do
    Foo.stub(:parse)
    Foo::Client.should_receive(resource).once.with(expected)
    Foo.send(resource, *args)
  end
end

describe Foo do
  describe 'resources have numeric ids only'
    [:accounts, :contacts].each do |resource|
      it_behaves_like 'it requests ids', resource do
        let(:args) { [1, 2] }
        let(:expected) { [1, 2] }
      end

      it_behaves_like 'it requests ids', resource do
        let(:args) { [3, 'jesse-pinkman', 5, {'links' => {resource.to_s => [98, 99]}}] }
        let(:expected) { [98, 99, 3, 5] }
      end
    end
  end

  describe 'resources have numeric and string ids'
    [:clients, :services].each do |resource|
      it_behaves_like 'it requests ids', resource do
        let(:args) { [2,'saul-goodman', 6] }
        let(:expected) { [2, 6, 'saul-goodman'] }
      end

      it_behaves_like 'it requests ids', resource do
        let(:args) { [3, 'saul-goodman', 5, {'links' => {resource.to_s => [202, 234]}}] }
        let(:expected) { [202, 234, 3, 5, 'saul-goodman'] }
      end
    end
  end
end

And my code:

module Foo
  class << self
    [:accounts, :contacts, :clients, :services].each do |resource|
      define_method(resource) do |*args|
        ids = []
        unless args.empty?
          ids += hash_ids(args, resource)
          ids += numeric_ids(args)
          ids += text_ids(args) unless numeric_ids_only?(resource)
        end
        parse(client.send(resource, ids))
      end
    end

    private

    def hash_ids(args, resource)
      args.collect { |arg| arg['links'][resource.to_s] if arg.is_a? Hash }.compact!.flatten!.to_a
    end

    def numeric_ids(ids)
      ids.select { |id| !id.is_a?(Hash) && id.to_i > 0 }
    end

    def text_ids(ids)
      ids.select { |id| id.is_a? String }
    end

    def numeric_ids_only?(resource)
      [:accounts, :contacts].include?(resource)
    end

    def client
      Foo::Client
    end

    def parse(json)
      Foo::Adapter::JSON.parse(json)
    end
  end
end

My particular concern is the ugly concatenating of the ids array and passing all those args around. Any tips?

You should expect
Starting a couple of years back, rspec is moving to a new expectation syntax, you should consider porting to it:

shared_examples 'it requests ids' do |resource|
  it 'sends the ids to Foo::Client' do
    allow(Foo).to receive(:parse)

    expect(Foo::Client).to receive(resource).once.with(expected)

    Foo.send(resource, *args)
  end
end

Be more transparent
Your code hides pretty well the fact that clients and services is different from accounts and contacts - both in your code and in your tests.
It makes your code quite obfuscated (in the name of DRYness?) - you should make it clear that you have two different behaviors - and spell them out:

shared_examples 'resources have numeric ids only' do |resource|
  it_behaves_like 'it requests ids', resource do
    let(:args) { [1, 2] }
    let(:expected) { [1, 2] }
  end

  it_behaves_like 'it requests ids', resource do
    let(:args) { [3, 'jesse-pinkman', 5, {'links' => {resource.to_s => [98, 99]}}] }
    let(:expected) { [98, 99, 3, 5] }
  end
end

shared_examples 'resources have numeric and string ids' do |resource|
  it_behaves_like 'it requests ids', resource do
    let(:args) { [2,'saul-goodman', 6] }
    let(:expected) { [2, 6, 'saul-goodman'] }
  end

  it_behaves_like 'it requests ids', resource do
    let(:args) { [3, 'saul-goodman', 5, {'links' => {resource.to_s => [202, 234]}}] }
    let(:expected) { [202, 234, 3, 5, 'saul-goodman'] }
  end
end

it_behaves_like 'resources have numeric ids only', :accounts
it_behaves_like 'resources have numeric ids only', :contacts
it_behaves_like 'resources have numeric and string ids', :clients
it_behaves_like 'resources have numeric and string ids', :services

And in your code, I would rather use simple method delegation than meta-coding:

class << self
  def accounts(*args)
    parse(client.accounts(hash_ids(args, :accounts) + numeric_ids(args))
  end

  def contacts(*args)
    parse(client.accounts(hash_ids(args, :contacts) + numeric_ids(args))
  end

  def clients(*args)
    parse(client.accounts(hash_ids(args, :clients) + numeric_ids(args) + text_ids(args))
  end

  def services(*args)
    parse(client.accounts(hash_ids(args, :services) + numeric_ids(args) + text_ids(args))
  end
end

It might be less DRY, but it is a lot clearer what your class actually does.


WPF Mvvm async function ViewModel I worried about this code in a ViewModel. ViewModel should not contain any code except binding's. But without async update the ui would freeze. How do I improve it? I'm restricted to using .net 3.5 or below.

public ShippingDocumentsRegisterViewModel()
{
    this.Columns = model.InitializeColumns();
    Action<object> Documents = new Action<object>(GetDocumentsAsync);
    IAsyncResult result = Documents.BeginInvoke(new AsyncCallback(GetDocumentsAsync),null, null);
}

public void GetDocumentsAsync(object param)
{
    this.ShippingDocuments = model.GetDocuments();
}

Model:

class ShippingDocumentsModel
    {
        public ObservableCollection<ShippingDocument> GetDocuments()
        {
            var documents = new ObservableCollection<ShippingDocument>();
            for (int i = 0; i < 100; i++)
            {
                System.Threading.Thread.Sleep(50);
                documents.Add(new ShippingDocument { Name = i.ToString() });
            }
            return documents;
        }

        public ObservableCollection<ShippingDocumentColumDescriptor> InitializeColumns()
        {
            return new ObservableCollection<ShippingDocumentColumDescriptor>
            {
                new ShippingDocumentColumDescriptor { HeaderText = "Статус", DisplayMember = "Status" },
                new ShippingDocumentColumDescriptor { HeaderText = "Підпис", DisplayMember = "Signature" }
            };
        }
    }

ViewModel:

public class ShippingDocumentsRegisterViewModel : ViewModelBase
    {
        ShippingDocumentsModel model = new ShippingDocumentsModel();

        public ShippingDocumentsRegisterViewModel()
        {
            this.Columns = model.InitializeColumns();
            Action<object> Documents = new Action<object>(GetDocumentsAsync);
            IAsyncResult result = Documents.BeginInvoke(new AsyncCallback(GetDocumentsAsync),null, null);
        }

        public void GetDocumentsAsync(object param)
        {
            this.ShippingDocuments = model.GetDocuments();
        }

        private ObservableCollection<ShippingDocument> shippingDocuments;

        public ObservableCollection<ShippingDocument> ShippingDocuments
        {
            get
            {
                return shippingDocuments;
            }

            private set
            {
                shippingDocuments = value;
                RaisePropertyChanged("ShippingDocuments");
            }
        }

        public ObservableCollection<ShippingDocumentColumDescriptor> Columns { get; private set; }

        private ICommand _addColumnCommand;

        public ICommand AddColumnCommand
        {
            get
            {
                if (_addColumnCommand == null)
                {
                    _addColumnCommand = new RelayCommand<string>(
                        s =>
                        {
                            this.Columns.Add(new ShippingDocumentColumDescriptor { HeaderText = s, DisplayMember = s });
                        });
                }
                return _addColumnCommand;
            }
        }

        private ICommand _removeColumnCommand;

        public ICommand RemoveColumnCommand
        {
            get
            {
                if (_removeColumnCommand == null)
                {
                    _removeColumnCommand = new RelayCommand<string>(
                        s =>
                        {
                            this.Columns.Remove(this.Columns.FirstOrDefault(d => d.DisplayMember == s));
                        });
                }
                return _removeColumnCommand;
            }
        }
    }

Edit:

I think maybe this solution would be better?

BackgroundWorker BW = new BackgroundWorker();
            BW.DoWork += (o, e) =>
            {
                this.ShippingDocuments = model.GetDocuments();
            };
            BW.RunWorkerAsync();

General

Your model should not return an ObservableCollection because that collection should be used only if its change notification ability is needed (e.g. with data binding). The method GetDocuments should return an Array or an IEnumerable.
The method InitializeColumns also seems to be GUI related. Consider moving it to the view model.

Background Processing

If you have to load documents in the background, I would suggest using BackgroundWorker (for .Net Framework 3.5 and below). But you should use it more like:

Pass the model to the RunWorkerAsyncmethod and use the Argument property to access it.
Do not access view model properties from within the DoWork delegate because that is the code that will be executed in the background. Assign the calculated result to the Result property instead.
Use the RunWorkCompleted method to process the calculated result on the GUI thread.

e.g:

var bw = new BackgroundWorker();
bw.DoWork += (o, e) => e.Result = (e.Argument as Model).GetDocuments();
bw.RunWorkerCompleted += (s, e) => ShippingDocuments = new ObservableCollection((ShippingDocument[])e.Result);
bw.RunWorkerAsync(model);


Building a list of dates between two dates My solution to this feels 'icky' and I've got calendar math falling out of my ears after working on similar problems for a week so I can't think straight about this.

Is there a better way to code this?

import datetime
from dateutil.relativedelta import relativedelta

def date_count(start, end, day_of_month=1):
    """
    Return a list of datetime.date objects that lie in-between start and end.

    The first element of the returned list will always be start and the last
    element in the returned list will always be:
        datetime.date(end.year, end.month, day_of_month)

    If start.day is equal to day_of_month the second element will be:
        start + 1 month

    If start.day is after day_of_month then the second element will be:
        the day_of_month in the next month

    If start.day is before day_of_month then the second element will be:
        datetime.date(start.year, start.month, day_of_month)

    >>> start = datetime.date(2012, 1, 15)
    >>> end = datetime.date(2012, 4, 1)
    >>> date_count(start, end, day_of_month=1) #doctest: +NORMALIZE_WHITESPACE
    [datetime.date(2012, 1, 15), datetime.date(2012, 2, 1),
    datetime.date(2012, 3, 1), datetime.date(2012, 4, 1)]

    Notice that it's not a full month between the first two elements in the
    list.

    If you have a start day before day_of_month:
    >>> start = datetime.date(2012, 1, 10)
    >>> end = datetime.date(2012, 4, 1)
    >>> date_count(start, end, day_of_month=15) #doctest: +NORMALIZE_WHITESPACE
    [datetime.date(2012, 1, 10), datetime.date(2012, 1, 15),
    datetime.date(2012, 2, 15), datetime.date(2012, 3, 15),
    datetime.date(2012, 4, 15)]

    Notice that it's not a full month between the first two elements in the
    list and that the last day is rounded to
    datetime.date(end.year, end.month, day_of_month)
    """
    last_element = datetime.date(end.year, end.month, day_of_month)

    if start.day == day_of_month:
        second_element = start + relativedelta(start, months=+1)
    elif start.day > day_of_month:
        _ = datetime.date(start.year, start.month, day_of_month)
        second_element = _ + relativedelta(_, months=+1)
    else:
        second_element = datetime.date(start.year, start.month, day_of_month)

    dates = [start, second_element]

    if last_element <= second_element:
        return dates

    while dates[-1] < last_element:
        next_date = dates[-1] + relativedelta(dates[-1], months=+1)
        next_date = datetime.date(next_date.year, next_date.month, day_of_month)
        dates.append(next_date)
    dates.pop()

    dates.append(last_element)

    return dates

How about...

def date_count(start, end, day_of_month=1):
    dates = [start]
    next_date = start.replace(day=day_of_month)
    if day_of_month > start.day:
        dates.append(next_date)
    while next_date < end.replace(day=day_of_month):
        next_date += relativedelta(next_date, months=+1)
        dates.append(next_date)
    return dates

And by the way it seems like a nice opportunity to use yield, if you wanted to.

def date_count2(start, end, day_of_month=1):
    yield start
    next_date = start.replace(day=day_of_month)
    if day_of_month > start.day:
        yield next_date
    while next_date < end.replace(day=day_of_month):
        next_date += relativedelta(next_date, months=+1)
        yield next_date

Another possibility - discard the first value if it is earlier than the start date:

def date_count(start, end, day_of_month=1):
    dates = [start.replace(day=day_of_month)]
    while dates[-1] < end.replace(day=day_of_month):
        dates.append(dates[-1] + relativedelta(dates[-1], months=+1))
    if dates[0] > start:
        return [start] + dates
    else:
        return [start] + dates[1:]

Or use a list comprehension to iterate over the number of months between start and end.

def date_count(start, end, day_of_month=1):
    round_start = start.replace(day=day_of_month)
    gap = end.year * 12 + end.month - start.year * 12 - start.month + 1
    return [start] + [round_start + relativedelta(round_start, months=i)
                      for i in range(day_of_month <= start.day, gap)]

Finally, I don't know dateutil but it seems you can use rrule:

from dateutil import rrule
def date_count(start, end, day_of_month=1):
    yield start
    for date in rrule(MONTHLY,
                      dtstart=start.replace(day=day_of_month),
                      until=end.replace(day=day_of_month)):
        if date > start:
            yield date


Return the number of unique ways you can climb the staircase There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.

For example, if N is 4, then there are 5 unique ways:

1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2

What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.

public class DailyCodingProblem12 {
    public static void main(String args[]) {
        int[] X = { 1, 2 };
        int N = 4;
        int result = solution(N, X);
        System.out.println(result);

        int[] X1 = { 1, 2, 3 };
        N = 4;
        result = solution(N, X1);
        System.out.println(result);

        int[] X2 = { 1, 2, 3 };
        N = 3;
        result = solution(N, X2);
        System.out.println(result);
    }

    static int solution(int N, int[] X) {
        int[] memory = new int[N + 1];
        memory[0] = 1;
        memory[1] = 1;
        return noOfWays(N, X, memory);
    }

    static int noOfWays(int N, int[] X, int[] memory) {
        if (memory[N] != 0) {
            return memory[N];
        }
        int noOfWays = 0;
        for (int i = 0; i < X.length && (N - X[i] >= 0); i++) {
            memory[N - X[i]] = noOfWays(N - X[i], X, memory);
            noOfWays += memory[N - X[i]];
        }
        return noOfWays;

    }

}

How do I improve my solution? There is a way to save more space?

Dynamic programming approach

My main advice is to prefer bottom-up iteration to top-down memoization. These are the two main approaches to dynamic programming as described on Wikipedia. Now, while there is nothing absolutely wrong with top-down approaches, bottom-up is, at least for this problem

cleaner to code
does not take up space on the stack
runs faster if method calls are slower than iteration

Finally, your code may re-compute the same values multiple times. This is not true of all top-down approaches, but is easy to avoid using bottom-up dynamic programming.

Bugs

incorrect if X is not sorted
incorrect if X does not contain 1 due to unnecessary memory[1] = 1

Minor style points

use more descriptive class and variable names
instead of N - X[i] >= 0 use N >= X[i]
prefer enhanced for loops

static int solution(int totalStairs, int[] stepSizeOptions) {
    int[] numberWays = new int[totalStairs+1];
    numberWays[0] = 1;

    for (int numStairs = 1; numStairs <= totalStairs; numStairs++) {
        for (int stepSize : stepSizeOptions) {
            if (numStairs >= stepSize) {
                numberWays[numStairs] += numberWays[numStairs - stepSize];
            }
        }
    }

    return numberWays[totalStairs];
}


Printing a list as "a, b, c." using Python Is there a better way to do this? Assuming very long lists, is this slow and wasteful?

flavors = ['chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee']

for flavor in flavors:
    print(flavor, end = ', ' if (flavors.index(flavor) != len(flavors) -1) else '.')

Output:

chocolate, vanilla, caramel, strawberry, coffee.

TL;DR:

Despite this being the currently accepted & highest voted answer, these methods from this answer and variations (1, 2) of it:

print(", ".join(flavours) + ".")         # Peilonrayz
print(", ".join(flavours), end=".\n")    # Maarten Fabré
print(f'{", ".join(flavors)}.')          # Andy

are all faster than the solution originally proposed in this answer:

print(*flavours, sep=', ', end='.\n')

Original Answer, Plus Explanation & Timing Analysis:

Consider also:

flavours = ['chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee']
print(*flavours, sep=', ', end='.\n')

This does not perform any unnecessary string concatenation, nor does it require a loop variable to test for the final index.

How does this work?

The print function takes a variable number of arguments, and so would be defined something like:

def print(*args, sep=' ', end='\n', file=sys.stdout, flush=False):
    # ...

except it is a built-in function.

The *args parameter consumes all of the unnamed arguments into one list for processing by the function, allowing the function to take a variable number of arguments.

In the statement,

print(*flavours, sep=', ', end='.\n')

The "splat operator" (*) takes the iterable flavours and expands it into a list of arguments for the function, allowing the caller to pass a variable number of arguments to a function, taken from the contents of a container (list, tuple, etc).

The Python interpreter could match the *flavours splat operator with the *args variable argument list of the print function, and simply pass the flavours list into the args.

But does it?  I got worried.  Perhaps, because a list is given, and the variable argument list (in CPython) is passed as a tuple, the list actually must be copied.  How much time does it take.

After creating a class Null output stream, to speed up the printing, I began passing variable sized lists to the various answers, and profiling the results.  While my solution is one of the least amounts of code, it turns out that @Peilonrayz's solution of ", ".join(flavours) seems to be the fastest.

Using tuples or lists doesn't seem to affect the performance much, so any thought that splatting a tuple instead of a list, to be collected into a *args variable argument tuple may be optimized to a no-op, seems to have been squashed.

Since print will automatically convert objects to strings for printing, the above will work for all object types in a list.  The ", ".join(flavours) will only work for strings; it would have to be modified to convert non-strings to strings to be truly equivalent:

print(", ".join(map(str, flavours)) + ".")


Alphabetically-sorted word lookup The goal of this code is to save a list of 250000 words with a number that indicates its frequency. The 250000 are sorted alphabetically but the frequency is unsorted. The idea is that a user must insert capitalized words, spaces or numbers after each word to lookup in the saved 250000-word list.

The max number of inputs are 1000 word+space+frequency pair per line.

The frequency domain is \$1 <= frequency <= 1000000\$. Every input must result in an output containing a list of the most relevant words \$>=\$ word-frequency entered and also ordered alphabetically in descending order.

How can I finish this code in a more efficient way?

public static void Main()
{
   {
      var dic = new Dictionary<string, int>();

      int counter = 0;

      StreamReader sr = new StreamReader("C:\\dicti.txt");

      while (true)
      {
          string line = sr.ReadLine();   // To read lines
          string[] ln;
          if (line == null) break;            // There is no more lines
          try
          {
              ln = line.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
              string a = ln[0];
              int b = Convert.ToInt32(ln[1]);

              dic.Add(a, b);
          }
          catch (IndexOutOfRangeException) { break; }
      }

      string[] ln2;
      string am, word;
      int bm;

      do
      {
                //counter++;
                do
                {
                    word = Console.ReadLine();

                    ln2 = word.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);

                    am = ln2[0];

                    bm = Convert.ToInt32(ln2[1]);

                } while (!(am.Length >= 2 && bm >= 1 && bm <= 1000000));

                if (true)
                {
                    var aj = (dic.Where(x => x.Value >= bm)
                        .Where(x => x.Key.StartsWith(am))
                        .OrderByDescending(d => d.Value).Take(2));

                    foreach (var p in aj)
                    {
                        Console.WriteLine("{0} ", p.Key);
                    }
                }
            } while (counter < 1001);
   }
}

Dictionary<Y> is only efficient if you access the entries through the key. You are enumerating the dictionary with linq. This is very slow. Try to access it like this:

int count;
if (dic.TryGetValue(am, out count)) {
    // found
} else {
    // not found
}

You cannot search for keys that start with a text. If you want to do this then look for a more appropriate data structure. A binary tree inserts and looks up fast and sorting happens automatically. However, keep in mind that simple binary trees (not AVL trees) perform badly if items are added in a presorted order. A binary tree would also allow you to search for beginning of words.

EDIT:

I have thought things over. It would be possible to work with two collections at the same time. It is a bit complicated to handle, but should be faster.

Let me explain. We are using binary trees, because, unless dictionaries, they are ordered by the key. Let us store the information with the words as key and the frequencies as value in the first binary tree. In the second binary tree, we use the frequency as key. Because several words can have the same frequency, we use a list of words as value. With this approach, we have our information ordered by words and by frequencies at the same time.

Now let us update the frequency of a word, which is already contained in our collections. As an example, let us add 50 to the frequency of the word “TEDDY”:

We look up the word in collection 1. We see that the frequency of the word is 100.
We look up the words with frequency 100 in collection 2. We find two corresponding words, “TEDDY” and “HOUSE”.
We ignore “HOUSE” and remove “TEDDY” from collection 2.
We re-insert “TEDDY” in collection 2 with a frequency of 100 + 50 = 150. Because the frequency is used as key, it will probably be inserted at a different place in the tree structure.
We update the frequency in collection 1 to 150. Since the key does not change, we can just replace the value “in place”.

After these operations, both collections are still ordered by words and by frequencies respectively. Moreover, both look up operations, the remove and the insert operation were fast.


SICP exercise 1.3 - sum of squares of two largest of three numbers From SICP

Exercise 1.3: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

Square is:

(define (square x) (* x x))

I know the code could be written using language features like lambda or let, but first to remain true to the exercise, I wouldn't use features that are not discussed yet.

I took advantage of the fact that we only have three numbers that's why I am able to reduce my code into two if statements. All of the tests I've done produced correct output.

Please review my code.

(define (sum-of-squares a b c)
    (if (> a b)
        (+ (square a)
            (square (if (> b c)
                b
                c)))
        (+ (square b)
            (square (if (> a c)
                a
                c)))))

Here's an implementation with let. If possible I would like this reviewed as well.

(define (sum-of-squares a b c)
    (let ((bc (if (> b c) b c))
    (ac (if (> a c) a c)))
    (if (> a b)
        (+ (square a) (square bc))
        (+ (square b) (square ac)))))

Now, I find this second implementation not shorter than the first, but I think it's easier to read because it can be difficult to read expressions with more expressions nested inside as with the first implementation. On the other hand I realized it's worthless to do this because the variables aren't used more than once. For expressions more complicated than expressions contained in this procedure, would it be a good idea to put them inside let even if they are only used once?

How can I improve these codes and make them faster?

First of all, the name sum-of-squares is misleading.  Longer names-separated-with-hyphens are quite acceptable in Scheme, so why not tell the whole truth?  I suggest sum-of-squares-except-min or sum-of-squares-of-greatest-two.

The first solution is a bit of a brute-force approach.  It works, but it is not obvious at a glance how it works unless you trace all paths of the decision tree.

The second solution, if the indentation and naming were improved, would be a bit clearer.

(define (sum-of-squares-except-min a b c)
    (let ((max-of-bc (if (> b c) b c))
          (max-of-ac (if (> a c) a c)))
         (if (> a b)
             (+ (square a) (square max-of-bc))
             (+ (square b) (square max-of-ac)))))

Personally, I would adapt the second approach and go "all the way" with it.  Then, all the possibilities would be laid out logically, one per line.

(define (sum-of-squares-except-min a b c)
    (let ((least (min a b c)))
         (cond ((= least a) (+ (square b) (square c)))
               ((= least b) (+ (square a) (square c)))
               (else        (+ (square a) (square b))))))

min should be built in, but you can implement it as a helper function yourself if you need to.

Alternatively, sum all the squares, then subtract the square of the least.

Which approach is fastest?  It's hard to say, without benchmarking, whether it's better to define fewer intermediate variables, do less branching, or do less arithmetic.  I wouldn't worry about performance for such a simple problem.


Validate several validation groups I have 2 validation groups, VG1 and VG2.  I have a button BtnInsert that saves data into Datasource. Its Validation Group is VG2. Now, I want to validate both VG1 and VG2 when a user clicks the BtnInsert.

protected void BtnInsert_click(object sender,EventArgs e)
{
    // validate VG1
    Page.Validate("VG1");
    // Page.Validate("VG2") is not required as BtnInsert is of that group
    if(Page.IsValid)
    {
       // call insert function
    }
}

Is this code right, and by clicking BtnInsert, both groups are validated?

AFAIK, you won't get client-side validation of VG2, but otherwise I can't see that it shouldn't work. (There is probably a client-side event and a method you could call to duplicate the behavior for the client)


A Simple C++ Client That Sends Data Over TLS Using OpenSSL I am learning C++ and socket programming and OpenSSL. As such, I decided to make a simple client that opens a TLS connection and writes some data as practice. It also serves as a base for more complex applications.

I'm very new to C++, so I don't know if I'm using good naming conventions or other basic practices. The program is using OpenSSL 1.1.0.

#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

//Not sure what headers are needed or not
//This code (theoretically) writes "Hello World, 123" to a socket over a secure TLS connection
//compiled with g++ -Wall -o client.out client.cpp -L/usr/lib -lssl -lcrypto
//Based off of: https://www.cs.utah.edu/~swalton/listings/articles/ssl_client.c
//The OpenConnection method was heavily based on the answer to this post: https://stackoverflow.com/questions/52727565/client-in-c-use-gethostbyname-or-getaddrinfo

const int ERROR_STATUS = -1;

SSL_CTX *InitSSL_CTX(void)
{
    const SSL_METHOD *method = TLS_client_method(); /* Create new client-method instance */
    SSL_CTX *ctx = SSL_CTX_new(method);

    if (ctx == nullptr)
    {
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }
    return ctx;
}

int OpenConnection(const char *hostname, const char *port)
{
    struct hostent *host;
    if ((host = gethostbyname(hostname)) == nullptr)
    {
        perror(hostname);
        exit(EXIT_FAILURE);
    }

    struct addrinfo hints = {0}, *addrs;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    const int status = getaddrinfo(hostname, port, &hints, &addrs);
    if (status != 0)
    {
        fprintf(stderr, "%s: %s\n", hostname, gai_strerror(status));
        exit(EXIT_FAILURE);
    }

    int sfd, err;
    for (struct addrinfo *addr = addrs; addr != nullptr; addr = addr->ai_next)
    {
        sfd = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol);
        if (sfd == ERROR_STATUS)
        {
            err = errno;
            continue;
        }

        if (connect(sfd, addr->ai_addr, addr->ai_addrlen) == 0)
        {
            break;
        }

        err = errno;
        sfd = ERROR_STATUS;
        close(sfd);
    }

    freeaddrinfo(addrs);

    if (sfd == ERROR_STATUS)
    {
        fprintf(stderr, "%s: %s\n", hostname, strerror(err));
        exit(EXIT_FAILURE);
    }
    return sfd;
}

void DisplayCerts(SSL *ssl)
{
    X509 *cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */
    if (cert != nullptr)
    {
        printf("Server certificates:\n");
        char *line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
        printf("Subject: %s\n", line);
        delete line;
        line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
        printf("Issuer: %s\n", line);
        delete line;
        X509_free(cert);
    }
    else
    {
        printf("Info: No client certificates configured.\n");
    }
}

int main(int argc, char const *argv[])
{
    SSL_CTX *ctx = InitSSL_CTX();
    SSL *ssl = SSL_new(ctx);
    if (ssl == nullptr)
    {
        fprintf(stderr, "SSL_new() failed\n");
        exit(EXIT_FAILURE);
    }

    //Host is hardcoded to localhost for testing purposes
    const int sfd = OpenConnection("127.0.0.1", argv[1]);
    SSL_set_fd(ssl, sfd);

    const int status = SSL_connect(ssl);
    if (status != 1)
    {
        SSL_get_error(ssl, status);
        ERR_print_errors_fp(stderr); //High probability this doesn't do anything
        fprintf(stderr, "SSL_connect failed with SSL_get_error code %d\n", status);
        exit(EXIT_FAILURE);
    }

    printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
    const char *chars = "Hello World, 123!";
    SSL_write(ssl, chars, strlen(chars));
    SSL_free(ssl);
    close(sfd);
    SSL_CTX_free(ctx);
    return 0;
}

Here's the same code in a Gist!

C++ review
You still need a C review!
Idioms/Patterns
RAII idiom
In C++ we have this concept that an object should clean up its own resources. So when an object is created it will create and hold onto resources and when it is destroyed it will clean up those resources.
When learning about the idiom people mostly talk about memory and smart pointers. This is how we stop memory leaks in C++ that happen in C when things don't got as planned.
You should also note that an objects destructor is called when the control leaves the scope in which the object is created. However that scope is left. So even if you throw an exception that causes the stack to unwind as it unwinds the stack the destructors for all automatic objects are being called.
You need to apply this to your code.
 // this is an anti pattern in C++
 Stuff*   data = crate_data();

 ... do stuff with data
 ... do stuff with data

 destroy_data();

If you see this in your code you should be using RAII.
 class StuffHolder
 {
     Stuff*   data;

     public:
         StuffHolder()
             : data(crate_data())
         {}
         ~StuffHolder()
         {
              destroy_data(data);
         }
 };

 // Then in your code
 StuffHolder   dataHolder;

 ... do stuff with data
 ... do stuff with data

That's the pattern you should be using.
Exceptions
Exceptions make code easier to understand. Use them.
In your code you have places that you call exit(). Which is fine as it makes the rest of the code easy to read as you are not writing code to pass error message back through many layers of code so it keeps the code nice and simple.
There is a disadvantage in that you have exit locations scattered through your code. Have you been consistent with the error messages that are generated? You have to search and check every exit location.
A lot of code (especially bigger apps or libraries) don't want want to exit. They are part of a bigger framework so in C code you need to add error logic explicitly to the code to force the stack to unwind to the point where the user can take an action based on the error, or in a server you have a single place that is doing the error logging (so that it is consistent; otherwise each library will end up generating logs in a different way).
Exceptions provide the best of both worlds. You have a single place to catch and log exceptions. You don't have to write explicit error handling code (this is what exceptions do they unwind the code).
When you use exceptions with RAII all your resource are also correctly handled and released so you have no issues with releasing resources.
I can see several different ways of generating error messages in the code:
    ERR_print_errors_fp(stderr);
    exit(EXIT_FAILURE);

    perror(hostname);
    exit(EXIT_FAILURE);

    fprintf(stderr, "%s: %s\n", hostname, gai_strerror(status));
    exit(EXIT_FAILURE);

    SSL_get_error(ssl, status);
    ERR_print_errors_fp(stderr); //High probability this doesn't do anything
    fprintf(stderr, "SSL_connect failed with SSL_get_error code %d\n", status);
    exit(EXIT_FAILURE);

When you start having automated tools run over your logs this will be a real pain. Have a single point generate the error message so it is consistent for all places in the code. Then you can write tools that can easily analyze your error logs.
Code Review.
Would like to point out you don't use a single C++ header file.
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

Like the comment (It provides useful information).
//Not sure what headers are needed or not
//This code (theoretically) writes "Hello World, 123" to a socket over a secure TLS connection
//compiled with g++ -Wall -o client.out client.cpp -L/usr/lib -lssl -lcrypto
//Based off of: https://www.cs.utah.edu/~swalton/listings/articles/ssl_client.c
//The OpenConnection method was heavily based on the answer to this post: https://stackoverflow.com/questions/52727565/client-in-c-use-gethostbyname-or-getaddrinfo

Returning pointers
Returning pointers in C++ is very uncommon.
SSL_CTX *InitSSL_CTX(void)

You usually return an object (or reference). If you have a resource it is contained within an object that you return. That way the resource is correctly handled and released. If you are returning a pointer to an object that is owned locally by the function/method then you would normally return a reference. This guarantees that the object exists (can never be nullptr) but it also an indication that you are not releasing ownership of the pointer.
Terrible comment.
    // Bad comment
    const SSL_METHOD *method = TLS_client_method(); /* Create new client-method

    // Another terrible comment
    X509 *cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */

Comments like this are useless. In fact they are worse than useless they are dangerous. The comment tells me no more than the function name so it is not providing any real information. Also in the future as this code is maintained and made better the next developer could change the function call but leave the comment. Then a third developer sees there is a discrepancy between code and comment. Now what does he do? Does he fix the comment? Does he fix the code?
The point is comments de-generate over time and become less useful unless you are very active in maintaining them. So write code that is self documenting. Add comments that is explain WHAT (you are trying to do) or WHY (you are trying to do it) don't write comments that explain HOW (you are doing it). The code explains how (there are exceptions to this rule but you will have people tell you when there is an exception and the code needs to be commented).
One variable declaration per line:
    struct addrinfo hints = {0}, *addrs;

One variable declaration per line. Also in C++ you don't need the struct. In C++ we normally (unlike C) put the * next to the type. Types are exceedingly important in C++ (much more than in C) so we like to know the exact type. To me the above line is hard to parse.
    addrinfo   hints = {0};
    addrinfo*  addrs;

That looks so much neater and I can see the exact type of each variable.
Dead Code
Remove dead code.
This function is not used anywhere. Delete it from your code.
void DisplayCerts(SSL *ssl)

Main is special
Don't need a return in main().
    return 0;

You can do it; but people use no return value to indicate that the app will never generate an error code. So if I see a return 0; at the end then I start looking through main to see if there are any return 1; in the code.
Now I will admit that I would also add return 0; because you have used exit() in your code. But If I had written the code I would not have an exit() and consequently probably not had an return 0;.
int main(int argc, char* argv[])
{
    try {
       std::vector<std::string>   args(argv, argv + argc);
       exampleClient(args);
    }
    catch(std::exception const& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
        throw;
    }
    catch(...)
    {
        std::cerr << "Unknown Error: Red Alert\n";
        throw;
    }
}

Issues
Not sure if this is an error but it looks like one.
SSL_CTX *ctx = InitSSL_CTX();
SSL *ssl = SSL_new(ctx);
const int sfd = OpenConnection("127.0.0.1", argv[1]);

...

SSL_free(ssl);
close(sfd);
SSL_CTX_free(ctx);

You are creating the resources in a different order to closing them. Seems very code smelly. I would expect resource to be released in the reverse order of creation to make sure there are no interdependencies.
Being Selfish
I have already written a wrapper for C++ clients to use sockets.
https://lokiastari.com/blog/2016/05/26/c-plus-plus-wrapper-for-socket/index.html
The source is here:
https://github.com/Loki-Astari/Examples/tree/master/Version2
Look at client.cpp to see how to use it look at Socket.h for the interface. Would be nice to have a SSL Implementation. It may be as simple as providing an implementation of Protocol.h ie SSLProtocol. Just saying. I would review that.


GIS feature labeling and removal of None or Empty fields A working label expression for ArcGIS 10.3. I was using dictionary key:values but sometimes the keys would have the same value so my items were 'disappearing' out of the dictionary. Now I use this simple counter to group my values from a list (0,1) (2,3) (4,5). I think the if functions might be able to be combined, as well as perhaps setting the list[i*2] and list[(i*2)+1] to variables instead of repeating them 3 times.

def FindLabel ( [Elevation] , [Out_Elev] , [Out_Loc] , [In1_Elev] , [In1_Loc] , [In2_Elev] , [In2_Loc] , [In3_Elev] , [In3_Loc]  ):
  list = [Out_Elev],[Out_Loc],[In1_Elev],[In1_Loc],[In2_Elev],[In2_Loc],[In3_Elev],[In3_Loc]
  x = [Elevation] + " Top"
  for i in range(len(list)/2):
    if list[i*2] is not None:
      if list[i*2].strip() != "":
       if list[(i*2)+1] is not None:
         if list[(i*2)+1].strip() !="":
           x = x  + "\n" + "(" + str(list[i*2]) + ": " + str(list[(i*2)+1]) + ")"
  return x

You can consolidate the body of this quite a bit.  First, I'd make list[i*2] and list[i*2+1] into variables, probably

first_element = list[i*2]
second_element = list[i*2+1]

Then you can clean up the if statements as well

if first_element and first_element.strip() and second_element and second_element.strip():

However, that makes it clear that what you're doing is the same for both.  I'd write a little helper function

def validate_element(element):
    return element and element.strip()

if validate_element(first_element) and validate_element(second_element):

You should also use a format string and string.join instead of concatenation

lines = ["{} Top".format([Elevation]]

for i in range(len(list)/2):
    first_element = list[i*2]
    second_element = list[i*2+1]
    if validate_element(first_element) and validate_element(second_element):
        lines.append("({}:{})".format(first_element, second_element))

return '\n'.join(lines)

You could probably turn this into a list comprehension if you wanted to, but that probably isn't worth the effort and ugliness that would ensue.

Your names in general are pretty bad - list is especially horrific because you're now masking a builtin function - you can no longer use the list constructor.  Try to use descriptive names to actually describe what the values represent.


Converting a bytearray into an integer I am working on a program to decode MMS PDU files.  They are binary files and I am reading them byte by byte and decoding each header value as I come to it.

One header value is the Date, and it's represented as follows (in hex):

85 04 57 E2 A2 49

0x85 is the "Date" header, 0x04 is the data length (4 bytes) and the 4 following bytes represent the date (timestamp).

I have code to read those 4 bytes and return it to me as a bytearray:

bytearray(b'W\xe2\xa2I')

Apparently \x57 is a W and \x49 is an I.

In order to parse this as a date, I need to convert it to an int.  These bytes represent the timestamp 1474470473 (or 0x57E2A249).

I have code to convert this byte array into an int, but there has got be a better way to do it than the way I came up with.

timestamp = int(''.join(map(hex, byte_range)).replace('0x', ''), 16)
value = datetime.fromtimestamp(timestamp)

That is, I am converting every byte to a string (like "0x57"), joining them together, removing the "0x"s, then reading that string as a base 16 value.  This works, but it seems a little too convoluted.

I then realized that I could replace the join/map with binascii.hexlify, so now my code is:

timestamp = int(binascii.hexlify(byte_range), 16)
value = datetime.fromtimestamp(timestamp)

Like I said, this code works, but I just feel there's a better way to do this than to convert the bytearray into a string and then parse that string back as a base-16 int.

To decode binary data, use struct.unpack().

>>> import struct
>>> byte_range = bytearray(b'\x85W\xe2\xa2I')
>>> date_header, timestamp = struct.unpack('>BL', byte_range)
>>> date_header
133
>>> timestamp
1474470473


Create Word Document in C++ I am new to COM programming in C++ and while this code works welcome suggestions to improve readability/reliability. This creates a blank word document and adds the text Hello, World.

// The Microsoft Office Object type library (mso.dll)
    #import "libid:2DF8D04C-5BFA-101B-BDE5-00AA0044DE52" raw_interfaces_only, named_guids,\
        rename("DocumentProperties", "_DocumentProperties"), \
        rename("SearchPath", "_SearchPath"), \
        rename("RGB", "_RGB")

     //  The Microsoft Office Word Object type library (msword.olb)
    #import "libid:00020905-0000-0000-C000-000000000046" raw_interfaces_only,\
        rename("ExitWindows", "_ExitWindows"), \
        rename("ReplaceText", "_ReplaceText"), \
        rename("FindText", "_FindText"), \
        rename("RGB", "_RGB")
    #include <Windows.h>

    int main()
    {
        HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
        Word::_ApplicationPtr pWordApp;
        Word::DocumentsPtr pWordDocs;
        Word::_DocumentPtr pWordDoc;
        Word::RangePtr pRange;
        hr = pWordApp.CreateInstance(__uuidof(Word::Application));
        pWordApp->put_Visible(VARIANT_TRUE);
        pWordApp->get_Documents(&pWordDocs);

        pWordDoc.CreateInstance(__uuidof(Word::Document));
        pRange.CreateInstance(__uuidof(Word::Range));
        VARIANT vTemplate;
        VariantInit(&vTemplate);
        vTemplate.vt = VT_BSTR;
        vTemplate.bstrVal = SysAllocString(L"");

        VARIANT vNewTemplate;
        VariantInit(&vNewTemplate);
        vNewTemplate.vt = VT_BOOL;
        vNewTemplate.boolVal = false;

        VARIANT vDocType;
        VariantInit(&vDocType);
        vDocType.vt = VT_I4;
        vDocType.iVal = Word::WdNewDocumentType::wdNewBlankDocument;

        VARIANT vVisible;
        VariantInit(&vVisible);
        vVisible.vt = VT_BOOL;
        vVisible.boolVal = true;

        VARIANT vStart;
        VariantInit(&vStart);
        vStart.vt = VT_I4;
        vStart.iVal = 0;

        VARIANT vEnd;
        VariantInit(&vEnd);
        vEnd.vt = VT_I4;
        vEnd.iVal = 0;

        pWordDocs->Add(&vTemplate, &vNewTemplate, &vDocType, &vVisible, &pWordDoc);
        pWordDoc->Range(&vStart, &vEnd, &pRange);

        BSTR str = SysAllocString(L"Hello, World!");
        pRange->put_Text(str);
        SysFreeString(str);
    }

First off, I think it's worth thinking carefully about whether C++ is the best tool for this task.  It certainly can be done, but you may find better documentation/more support for COM/interop from C# or VBA.  Particularly for such a simple task.

HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

You need to check the result of CoInitializeEx and every other API call you make.  Think of each API call as a polite request.  Windows may (and frequently does) decline requests.  In your program, these errors will be really hard to diagnose because you will simply not see your desired result.  A better idea is to use a function/macro to check the result is correct.  In this case, it should look something like:

assert(S_OK == CoInitializeEx(NULL, COINIT_APARTMENTTHREADED));

You may want to get fancier with the macro.  This way you will know where (and where not) to spend time debugging.

Quoting MSDN:

  To close the COM library gracefully on a thread, each successful call to CoInitialize or CoInitializeEx, including any call that returns S_FALSE, must be balanced by a corresponding call to CoUninitialize.

You forgot to call CoUninitialize.  Your program (well, actually your thread) is supposed to tell Windows when it will start using COM and when it is done.

This is a great place to use RAII:

struct COMThread {
    COMThread() {
        assert(S_OK == CoInitializeEx(NULL, COINIT_APARTMENTTHREADED));
    }

    ~ COMThread() {
        CoUninitialize(); // returns void, no need to check return value
    }
};

In general you should read MSDN for every function you call and probably write a few comments summarizing your findings (and maybe even a URL... sometimes the docs are hard to re-find IMO).

vTemplate.bstrVal = SysAllocString(L"")

Did you forget to deallocate this BSTR?  This could be another RAII wrapper.

VARIANT vTemplate;
VariantInit(&vTemplate);
vTemplate.vt = VT_BSTR;

Once again, there is a free function VariantClear which could be RAII.  A wrapper around variant is not a bad idea -- most of your code creates/clears variants.

I could not find docs for the specific Word functions you are calling, but I suspect there is a way to achieve this without using so many variants (based on some experience using other parts of the COM API).  I know this is not as helpful as it could be.

Despite a few things to clean up, I think you're off to a good start.  You have the general procedure down which is the most important thing.


Radix Sort speed improvement I was trying to optimize the Radix Sort code, because I never found a code that was simple and easy to understand yet wasn't any slower. I have seen codes on web and in some books that implement arbitrary radices such as 10 and others and also do modulo operation rather than bit-shifting. Those codes however have always been slower that their comparison based counterparts in the same language.

Since Radix Sort runs in \$O(n)\$ time, I built up my version of Radix Sort which is coded below in C. I choose C language because of speed, however please correct me if I'm going wrong. The code also works for negative numbers too.

I have optimized the code as far as I could go, and maybe I might have missed some more optimization techniques.

Any ideas with which I can increase the execution speed ?

Motivation for optimization:
http://codercorner.com/RadixSortRevisited.htm
http://stereopsis.com/radix.html
I was unable to implement all the optimizations in the articles, as it was beyond my skills and understanding mostly and somewhat lack of sufficient time. Other techniques not included in them or out of the box would definitely help a lot.

This is the pointer optimized version, "long" on my system is 32 bits.

long* Radix_Sort(long *A, size_t N, long *Temp)
{
    long Z1[256] ;
    long Z2[256] ;
    long Z3[256] ;
    long Z4[256] ;
    long T = 0 ;
    while(T != 256)
    {
        *(Z1+T) = 0 ;
        *(Z2+T) = 0 ;
        *(Z3+T) = 0 ;
        *(Z4+T) = 0 ;
        ++T;
    }
    size_t Jump, Jump2, Jump3, Jump4;

    // Sort-circuit set-up
    Jump = *A & 255 ;
    Z1[Jump] = 1;
    Jump2 = (*A >> 8) & 255 ;
    Z2[Jump2] = 1;
    Jump3 = (*A >> 16) & 255 ;
    Z3[Jump3] = 1;
    Jump4 = (*A >> 24) & 255 ;
    Z4[Jump4] = 1;

    // Histograms creation
    long *swp = A + N;
    long *i = A + 1;
    for( ; i != swp ; ++i)
    {
        ++Z1[*i & 255];
        ++Z2[(*i >> 8) & 255];
        ++Z3[(*i >> 16) & 255];
        ++Z4[(*i >> 24) & 255];
    }

    // 1st LSB byte sort
    if( Z1[Jump] == N );
    else
    {
        swp = Z1+256 ;
        for( i = Z1+1 ; i != swp ; ++i )
        {
            *i = *(i-1) + *i;
        }
        swp = A-1;
        for( i = A+N-1 ; i != swp ; --i )
        {
            *(--Z1[*i & 255] + Temp) = *i;
        }
        swp = A;
        A = Temp;
        Temp = swp;
    }

    // 2nd LSB byte sort
    if( Z2[Jump2] == N );
    else
    {
        swp = Z2+256 ;
        for( i = Z2+1 ; i != swp ; ++i )
        {
            *i = *(i-1) + *i;
        }
        swp = A-1;
        for( i = A+N-1 ; i != swp ; --i )
        {
            *(--Z2[(*i >> 8) & 255] + Temp) = *i;
        }
        swp = A;
        A = Temp;
        Temp = swp;
    }

    // 3rd LSB byte sort
    if( Z3[Jump3] == N );
    else
    {
        swp = Z3 + 256 ;
        for( i = Z3+1 ; i != swp ; ++i )
        {
            *i = *(i-1) + *i;
        }
        swp = A-1;
        for( i = A+N-1 ; i != swp ; --i )
        {
            *(--Z3[(*i >> 16) & 255] + Temp) = *i;
        }
        swp = A;
        A = Temp;
        Temp = swp;
    }

    // 4th LSB byte sort and negative numbers sort
    if( Z4[Jump4] == N );
    else
    {
        swp = Z4 + 256 ;
        for( i = Z4+129 ; i != swp ; ++i )
        {
            *i = *(i-1) + *i;
        }
        *Z4 = *Z4 + *(Z4+255) ;
        swp = Z4 + 128 ;
        for( i = Z4+1 ; i != swp ; ++i )
        {
            *i = *(i-1) + *i;
        }
        swp = A - 1;
        for( i = A+N-1 ; i != swp ; --i )
        {
            *(--Z4[(*i >> 24) & 255] + Temp) = *i;
        }
        return Temp;
    }
    return A;
}

I never found a code that was simple and easy to understand yet wasn't any slower

Note the order. Start readable.
Start with What shall this be good for?: (doc)comment your code.

No slower than what? A "well known implementation" for reference and as a base-line would be useful.

Things I liked:

"non-obvious" code blocks are commented
(short-circuit set-up, negative numbers sort)
trying to keep the number of passes low
handling of negative numbers via histogram instead of value manipulation

Dislikes (beyond missing doc comments):

not declaring the size parameter const N
this would at least hint that the memory pointed to by A and Temp may be modified
naming
while I like i for index without further significance, I prefer p for a pointer
What is the significance of Z in Z1…4?
case:
assuming capital case OK for arrays: why N, T, Jump1…4?
naked literals (beyond 0±1)
repetition
starting with types: have a value type, a histogram type
with "the rearrangement blocks", I'd prefer benchmark/machine code comparisons between
zeroing memory with open code - use memset(destination, 0, count)
"empty then" instead of inverting the condition
*(p+e) instead of p[e] (let alone *(e+p)) - without revisiting the standard, I would have denied this was well defined.)
updating a counter using increment/decrement
I think of those operations as next/previous and use += 1(-= 1) for numerical adjustment
not using an explicit variable (histogram handling, mostly)
re. speed: not special-casing "small" arrays

Things I don't want to presume warranted:

bit operations preferred to ldiv_t ldiv()
bit operations using compile time constants over using parameters (would allow factoring out)
"walking memory backwards" as fast as "forwards"


Swift iOS - Call back functions I'm working on an iOS app which handles API request based on authentication. Authentication is done through OAuth and every API request is sent along with access_token. In certain cases, the access_token might be expired causing the API request to fail. I would need to call the refresh_token method to refresh the access_token followed by the API request. I have used NotificationCenter to handle callbacks. Are there better ways to handle this using closures or something else?

class DeviceInfo {

    func generateRefreshToken(callbackNotifier : String) -> Void {

        Alamofire.request(DeviceAPIRequest.GEN_REFRESH_TOKEN(refreshToken)).responseJSON {

            (request, response, results, error) -> Void in
            if (error == nil) {

                let jsonResponse = JSON(results!)
                self.accessToken = jsonResponse["access_token"].stringValue
                self.refreshToken = jsonResponse["refresh_token"].stringValue
                let refreshStatus = NSDictionary(object: "success", forKey: "status")

                NSNotificationCenter.defaultCenter().postNotificationName(callbackNotifier, object: self, userInfo: refreshStatus)

            } else {
                let refreshStatus = NSDictionary(object: "failed", forKey: "status")
                NSNotificationCenter.defaultCenter().postNotificationName(callbackNotifier, object: self, userInfo: refreshStatus)
            }
        }
    }

}

and

class UserAPI {

    func getUsers() -> Void {

        let tokenType:String = deviceInfo.tokenType
        let accessToken:String = deviceInfo.accessToken

        Alamofire.request(UserAPIRequest.GET_USER_PARTITION(tokenType, accessToken)).responseJSON() {

            (request, response, results, error) in

            if (error == nil) {

                // sucessfull in getting users...

            } else {

                // possible chances are access_token is expired.
                if response?.statusCode == 403 {
                    self.deviceInfo.generateRefreshToken("getUsers")
                } else {
                    DDLogError("Error while processing getUsers() : \(error)")
                }
            }
        }
    }
}

Very regularly when dealing with asynchronous stuff (among other things) in iOS development, we have to make a decision between three tools.

Closures (blocks, callbacks, etc)
NSNotificationCenter
The delegate pattern.

Which one is right for you depends on the scenario.  It won't always be the same one.  As a general rule, we can use the number of objects we want to respond to the result as a guideline for which pattern to use.

Closures (blocks, callbacks, etc.) are good for when we want zero objects tied to waiting on the result.  We just pass the closure and forget about it.  0 objects.
NSNotificationCenter is a good approach when we want any number of unknown objects to be able to respond to the result.  The thing working on producing the result knows nothing about these objects, it just creates a notification when it's complete.  0-many objects.
The delegate pattern is good when we want exactly one object to respond to the result.  Using the delegate pattern, the delegate and the worker object know quite a bit about each other.  The worker object will define a protocol of set methods that its delegate must implement or can optionally implement, and the worker object can call any of these.  1 object.

It looks here like we most likely want the delegate pattern for our scenario, given that our generateRefreshToken method takes a custom notification string.  But I will cover all three options lightly (and perhaps after picking one you for sure want to use, you can improve your code and post another question where we cover that topic in detail).

For all of these scenarios, we need to consider the same information--what do we need to pass to our completion handling code?

Some indication of success vs failure.
If failure, details on the failure.
If success, the results.

Closures (blocks, callbacks, etc)
This is basically the approach that joekim's answer takes.  Our method, generateRefreshToken just needs to take a single argument, a completion block.  That completion block should be defined as a closure that accepts arguments that convey the information we outlined above, and return void.  joekim's answer outlines a very good approach to this, but how you implement it specifically is up to you.  Frequently these sorts of closures will simply take an NSData or NSDictionary object to represent the data (or perhaps just a regular Swift Dictionary) and an NSError optional to indicate success or failure (and hold failure details).

NSNotificationCenter
This is effectively the pattern you're currently using.  But remember, I described NSNotificationCenter as being for when you want zero to many objects responding to completion.  As such, when we use NSNotificationCenter, we probably should be accepting a string parameter to tell us the name of the notification.  Instead, the file that declares this class should probably also expose two String constants that the object will use for its notification.  One of these notifications is the "success" notification, and the other is the "error" notification.  The "userInfo" passed with the "success" notification is simply the necessary data we want to collect, and the "userInfo" passed with the "failure" notification simply contains the error.
The reason that I recommend this approach (two notifications) is simply because NSNotificationCenter allows observers a lot of control and flexibility.
If I want to use a single method to observe both methods and just check to see what's in user info, I can.
If I want to use two methods and separate my error handling logic from my success handling logic, I can.
If I want to ignore failure (or success), I can.  If I want to have one object handle success and another handle failure, I can.

The Delegate Pattern
This is the pattern I actually think is most appropriate for your scenario.  For this pattern, we must start by declaring a protocol that defines the methods we'll be calling on our delegate.  Something like this might work:
@objc protocol GenerateTokenDelegate {
    func tokenGeneratorDidSucceed(tokenGenerator: DeviceInfo)
    func tokenGeneratorDidFail(tokenGenerator: DeviceInfo)
}

Of course, this approach means we must declare our protocol as @objc, and our class DeviceInfo, must also be an Objective-C class (make it inherit from NSObject), and we must do this so we can hold a weak reference to our delegate.  If we hold a strong reference to our delegate (which will typically already have a strong reference to us), we risk creating a retain cycle.  The delegated object should hold a weak reference to its delegate.
So now we need to add a weak reference to our delegate to our class:
class DeviceInfo:NSObject{
    weak var delegate: GenerateTokenDelegate?
    // the rest of our class definition
}

Now, when we instantiate our class, we set its delegate property equal to the object we want it to call back to (which conforms to GenerateTokenDelegate protocol), and when we've completed our asynchronous code, we call back to it as such:
self.delegate?.tokenGeneratorDidFail(self)

And obviously, we can set our protocol up to define our methods in any such way and take any set of arguments (though we'll always want to pass self as the first argument, typically).
We can also declare optional methods.  Suppose we maybe don't want to force the delegate to handle errors.  We can let the "didFail" method be an optional part of the protocol.
optional func tokenGeneratorDidFail(tokenGenerator: DeviceInfo)

And now we'd call it as such:
self.delegate?.tokenGeneratorDidFail?(self)

Notice both sets of question marks.  The delegate may or may not be nil, and even if it's not nil, it may or may not implement the method we're trying to call.


Find common preamble of a list of strings Think of a set of text lines starting with a common string, e.g. indented code.

my $preamble = reduce {
    my $len = min(length $a, length $b);
    --$len while substr($a, 0, $len) ne substr($b, 0, $len);
    return substr($a, 0, $len);
} @lines;

Note that after the first invocation chances are high that $a already has the final result.

I'm wondering if there is a better approach in comparing the two strings in the reduce block. The while loop does not seem to be the best approach. It's also less readable since it does not convey the intent of the code (find common preamble of $a and $b).

Update:
After feedback from amon here is an alternative:

my $preamble = reduce {
    my $len = min(length $a, length $b);
    my ($current_prefix, $string) = (substr($a, 0, $len), substr($b, 0, $len));

    while($current_prefix ne $string) {
        chop $current_prefix;
        chop $string;
    }

    return $current_prefix;
} @lines;

I think this is an improvement in both performance and readability.

First of all, I think it is very good that you used reduce, as it clearly shows how the algorithm works. At least, to a reader who understands functional idioms.

One problem in your code is that you keep using $a and $b. These two names do not convey any meaning. We could do instead:

my $prefix = reduce {
  my ($current_prefix, $string) = ($a, $b);
  ...

Then, I would shorten the $current_prefix until it is at the beginning of the other $string:

until (0 == index $string, $current_prefix) {
  chop $current_prefix;
}

I did not use the statement modifier form of until or while – I don't believe that they make code much easier to read the way a postfix if or for can do. Note that the empty string occurs at the beginning of any string, so the termination condition of that loop is safe.

If you do not like index or chop, you could equivalently use the less efficient

until ($string =~ /\A\Q$current_prefix/) {
  $current_prefix =~ s/.\z//s;
}

Either way, the concept of shortening the prefix by removing one character at a time until it fits should be easier to read than all the substringing you used.

Cutting the prefix to the length of the string would just be an optimization:

$current_prefix = substr $current_prefix, 0, length $string;

Put together, we would get the following code:

my $prefix = reduce {
  my ($current_prefix, $string) = ($a, $b);

  # the prefix cannot be longer than the string
  $current_prefix = substr $current_prefix, 0, length $string;

  # remove characters from the prefix until it occurs at the beginning.
  # "" is always a prefix, so the loop properly terminates.
  until (0 == index $string, $current_prefix) {
    chop $current_prefix;
  }

  return $current_prefix;
} @strings;

The code might be easier to understand for people who don't know reduce if you express it in the imperative form:

my ($prefix, @strings) = @original_strings;
for my $string (@strings) {
  # the prefix cannot be longer than the string
  $prefix = substr $prefix, 0, length $string;

  # remove characters from the prefix until it occurs at the beginning.
  # "" is always a prefix, so the loop properly terminates.
  until (0 == index $string, $prefix) {
    chop $prefix;
  }
}
# now $prefix is the prefix of all @original_strings

Oh look, it's shorter too!


Circular primes below 10^1025 The problem

Project Euler: 35 is stated in the following way

  Circular primes

  Problem 35

  The number, 197, is called a circular prime because all rotations of
  the digits: 197, 971, and 719, are themselves prime.

  There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31,
  37, 71, 73, 79, and 97.

  How many circular primes are there below one million?

My attempt

I solved this question some time ago, and have now come back to it because I saw it pop up a few times here on CR. I wanted to over-engineer the problem and instead of finding the circular primes under a million I wanted to find them under some crazy big number.

It is not terribly quick, but uses that all circular primes above a million are repunit primes with a prime number of digits.

I included two different ways of checking whether a number (or in this case a list of numbers) is a circular prime. I use the following

def is_circular_2(p):
    for i in range(len(p)):
        if not isprime(int(''.join(map(str, p[i:]+p[:i])))):
            return False
    return True

However after some quick googling, the following seem to be the "preferred" way

def lst_2_int(lst):
    return int(''.join(map(str, lst)))

def is_circular(p):
    return all(isprime(lst_2_int(p[i:]+p[:i])) for i in range(len(p)))

However after some light speedtests using timeit, this version is a tad slower. As many other answers do I cycle through the products of the odd integers [1, 3, 7, 9] since no prime can end in an even integer, or 5.

I do not bother saving the primes or non primes already found. Is it "worth" it? isprime from the primefac libary already seems quite fast. To find the really big circular primes I iterate over the repunit primes. Eg primes only consisting of 1`s. No need to check if it is circular. I also used the small increase that a repunit number is prime if and only if it contains a prime number of digits.

Looking for any sort of general comments on my code. Not sure if my code can be improved speedwise, but comments there are appreciated as well.

The code

from primefac import isprime, primes
from itertools import product  # cartesian product

'''
Circular primes
Project Euler: Problem 35

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?
'''

def lst_2_int(lst):
    return int(''.join(map(str, lst)))

def is_circular(p):
    return all(isprime(lst_2_int(p[i:]+p[:i])) for i in range(len(p)))

def is_circular_2(p):
    for i in range(len(p)):
        if not isprime(lst_2_int(p[i:]+p[:i])):
            return False
    return True

def repunit(k):
    return (10**k-1)//9

def find_circular_primes_under(digits):

    if type(digits) != int or digits <= 0:
        raise ValueError(
            "Error: power needs to be a positive integer, 10^input")

    circular_lst = []
    # Circular primes under 10
    total = 0
    for k in xrange(10):
        if isprime(k):
            circular_lst.append(k)

    # Circular primes under 10^6
    for k in xrange(2, min(digits+1, 7)):
        for combo in product([1, 3, 7, 9], repeat=k):
            if is_circular_2(list(combo)):
                circular_lst.append(lst_2_int(combo))

    # All circular primes over 10^6 are repunit primes (1...1 where ... =
    # index)
    if digits > 6:
        prime_lst = primes(digits+1)
        # All repunit primes have a prime number of digits
        for prim in prime_lst[3::]:
            if isprime(repunit(prim)):
                circular_lst.append('1 ... 1 ['+str(prim)+']')
    return circular_lst

if __name__ == '__main__':

    circular_primes = find_circular_primes_under(400)
    for prim in circular_primes:
        print prim
    print "Found a total of", len(circular_primes), 'circular primes.'

It's hard to review this kind of code unless there's a clear idea of what your self-imposed constraints are. What I mean by this is that the code makes use of an assumption (all permutable primes over \$10^6\$ are repunits) that it does not check. But if it is legitimate to make use of assumptions that the program itself does not check, then it would be much faster to avoid all those calls to isprime and write:

# https://oeis.org/A004023
A004023 = 19, 23, 317, 1031, 49081, 86453, 109297, 270343
circular_lst.extend((10**p - 1) // 9 for p in A004023 if p <= digits)


Quickselect algorithm in Swift I recently answered a question
 on Stack Overflow about finding the k-largest element in an array, and
present my implementation of the Quickselect algorithm in Swift for review.

This is essentially the iterative version described in
Wikipedia: Quickselect, only that the
paritioning does not move the pivot element to the front of the second partition.
That saves some swap operations but requires an additional check when updating the lower bound.

The language is Swift 3, compiled with Xcode 8.1.

extension Array where Element: Comparable {

    public func kSmallest(_ k: Int) -> Element {
        precondition(1 <= k && k <= count, "k must be in the range 1...count")

        var a = self // A mutable copy.
        var low = startIndex
        var high = endIndex

        while high - low > 1 {

            // Choose random pivot element:
            let pivotElement = a[low + Int(arc4random_uniform(UInt32(high - low)))]

            // Partition elements such that:
            //   a[i] <  pivotElement    for low <= i < pivotIndex,
            //   a[i] >= pivotElement    for pivotIndex <= i < high.
            var pivotIndex = low
            while a[pivotIndex] < pivotElement {
                pivotIndex += 1
            }
            for i in pivotIndex+1 ..< high {
                if a[i] < pivotElement {
                    swap(&a[pivotIndex], &a[i])
                    pivotIndex += 1
                }
            }

            if k <= pivotIndex {
                // k-smallest element is in the first partition:
                high = pivotIndex
            } else if k == pivotIndex + 1 {
                // Pivot element is the k-smallest:
                return pivotElement
            } else {
                // k-smallest element is in the second partition
                low = pivotIndex
                if a[low] == pivotElement {
                    low += 1
                }
            }
        }

        // Only single candidate left:
        return a[low]
    }

    public func kLargest(_ k: Int) -> Element {
        return kSmallest(count + 1 - k)
    }
}

Examples:

let a = [ 9, 7, 6, 3, 4, 2, 5, 1, 8 ]
for k in 1 ... a.count {
    print(a.kSmallest(k))
}
// 1 2 3 4 5 6 7 8 9

let b = [ "b", "a", "c", "h" ]
print(b.kLargest(2))
// "c"

Feedback on all aspects of the code is welcome, such as (but not limited to):

Possible improvements (speed, clarity, swiftyness, ...).
Naming. In particular: what would be a better name for kSmallest(_ k: Int)
in consideration of the
Swift API Design Guidelines?
The check if a[low] == pivotElement looks artificial, but without that
an infinite loop can occur, e.g. for an array with all elements equal.
Is there a better solution?

Remark: To make this code compile with Swift 4 (or later), just replace the line

swap(&a[pivotIndex], &a[i])

with

a.swapAt(pivotIndex, i)

There are a lot of loops in here. I would probably turn at least one of them into a recursive function; actually, refactoring high low and pivotIndex into let constants with recursion should be faster due to optimizations. (I'm not that good of an FP programmer to mock something up for you quickly).

Otherwise, one suggestion I'd make (just my preference), you have two major loops smooshed next to each other, perhaps another empty line could help readability:

            // Partition elements such that:
            //   a[i] <  pivotElement    for low <= i < pivotIndex,
            //   a[i] >= pivotElement    for pivotIndex <= i < high.
            var pivotIndex = low

            while a[pivotIndex] < pivotElement {
                pivotIndex += 1
            }

            for i in pivotIndex+1 ..< high {
                if a[i] < pivotElement {
                    swap(&a[pivotIndex], &a[i])
                    pivotIndex += 1
                }
            }

I would definitely try refactoring some of this to FP, then running it through some measureBlock()s in Xcode to see if it's faster.

Hope this helps!


Insert and attach tag to the post in same time I created a form with title, body and tag input and there are 3 tables: posts, tags and post_tag.

Now I use this function to add new tags and attach them to the post

postcontroller.php

 public function store(Request $request)
    {
        $input = $request->all(); //get inputs value

        $tag = $input['tag'];
        $tagdone = Tag::create(['name'=>$tag]);
        $tagid = $tagdone->id; //insert tag to tags table

        $posts = Posts::create($input); //insert posts table
        $postid = $posts->id;

        Posts::find($postid)->tags()->attach($tagid); //attach tag to the post
    }

There are actually 3 actions at the same time. But I think there are better ways than this one, so I'd like some feedback on what I've written.

Use the following:

 public function store(Request $request)
    {
        $input = $request->all(); //get inputs value

        $tag = $input['tag'];
        $tagdone = Tag::create(['name'=>$tag]);
        $tagid = $tagdone->id; //insert tag to tags table

        $posts = Posts::create($input); //insert posts table

        $posts->tags()->attach($tagid); //attach tag to the post
    }

This will reduce your database queries by one SELECT by removing Posts::find($postid).

Apart from the above, is there any reason for using three database tables? Just from the code provided it doesn't seem to be necessary and I would only use one table with all three inputs. Or at least reduce to two database tables as follows:

 public function store(Request $request)
    {
        $input = $request->all(); //get inputs value

        $tag = $input['tag'];
        $tagdone = Tag::create(['name'=>$tag]); //insert tag to tags table

        $input['tagid'] = $tagdone->id;

        $posts = Posts::create($input); //insert posts table, including tagid
    }


Am I missing any security loopholes in this php script that reads and outputs directory/file from $_GET variable Due to a weird server setup on one of my client's websites, I needed to setup a script to load referenced pdf files through a case-insensitive lookup.  We originally looked into mod_speling, but it was causing issues with other mod_rewrite declarations. I'm not entirely sure why, but I didn't have much control over those other declarations, since they had other people working on their site as well.

So anyway, they have a bunch of references to their PDF files all over the internet with a bunch of different capitalization. Realizing that getting all of these to switch over to the proper file name was gonna be nearly impossible, I opted to write a script to do the translation for me.

The script forces http://www.somedomain.com/somedirectory/subdirectory/anypdffile.pdf to load through my pdffiles.php file.

The script seems to work perfectly. I'm not too worried about server performance, as I don't think it's gonna be used all that often. I just wanted to get a second pair of eyes to make sure I didn't leave any major security loopholes in here since I'm reading a directory/file from a $_GET variable.

First I added this to the .htaccess file to redirect all pdf files to a php script

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} \.pdf$ [NC]
RewriteRule (.*) pdffiles.php?p=$1

Then put the following code in the pdffiles.php file:

<?php

// shorthand for our docroot
$root = $_SERVER['DOCUMENT_ROOT'];

// get our filepath (correct format is "somedir/otherdir/xyz.pdf")
$path= $_GET['p'];

// Rule 1 - Don't allow empty path
if (!empty($path)) {
    // get the directory for our file
    $dir = dirname($root.'/'.$path);

    // get the filename
    $file = basename($path);

    // get our extension
    $ext = pathinfo($file, PATHINFO_EXTENSION);

    // Rule 2 - Don't allow direct access to the script
    if (!strstr($_SERVER['REQUEST_URI'], 'pdffiles.php')) {

        // Rule 3 - Ensure PDF extension
        if (strtolower($ext) == "pdf") {

            // Rule 3 - Make sure document root + path is a real path
            if (($dir = realpath($dir))) {

                // Loop through directory contents
                if ($fh = opendir($dir)) {
                    while (false !== ($tfile = readdir($fh))) {

                        // ignore the default directories
                        if ($tfile != "." && $tfile != "..") {

                            // convert both to all lower case and try to match
                            if (strtolower($tfile) == strtolower($file)) {

                                // if they match then go ahead and output file
                                header("Content-type: application/pdf");
                                readfile($dir.'/'.$tfile);
                                exit;

                            }
                        }

                    }
                }

            }
        }

    }
}

// we failed one of our checkpoints, redirect to 404
header("HTTP/1.1 301 Moved Permanently");
header("Location: /notfound.html");
?>

As Jason stated checking for ".." is a good idea. If there are only a limited number of path where the pdfs are located on the server, I would even prefer matching against this set.

Nevertheless, you might also want to invert your ifs to get rid of the nesting and use guard conditions.

<?php
    // !!!! comment intention, not what your code is doing

    // Don't allow direct access to the script
    if (strstr($_SERVER['REQUEST_URI'], 'pdffiles.php')) notFound();

    // expected format is "somedir/otherdir/xyz.pdf"
    $path= $_GET['p'];
    if (empty($path)) notFound();

    $root = $_SERVER['DOCUMENT_ROOT'];
    $dir = realpath(dirname($root.'/'.$path));
    if ($dir===FALSE) notFound();
    $file = basename($path);
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    if (strtolower($ext) != "pdf") notFound();

    if ($fh = opendir($dir)) {
        while (false !== ($tfile = readdir($fh))) {
           if ($tfile == "." || $tfile == "..") continue;
           if (strtolower($tfile) != strtolower($file)) continue;

           header("Content-type: application/pdf");
           readfile($dir.'/'.$tfile);
           exit;
        }
    }

    function notFound() {
         // we failed one of our checkpoints, redirect to 404
         header("HTTP/1.1 301 Moved Permanently");
         header("Location: /notfound.html");
         exit();
    }
// ? > !!!! omit this. It's not necessary and you will have no empty line in you php files.

Maybe you want to also have a look at the DirectoryIterator


Converting List to a DataTable and/or DataSet Extension Methods Can someone help me improve this code?  I and trying to have a couple extension methods to convert strongly-typed lists to a DataSet and DataTable respectively.

But... being so green to C#, I am not sure this is the most efficient way to do this.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;

namespace o7th.Class.Library.Data
{
/// <summary>
/// List to DataTable Converter
/// </summary>
public static class ListConverter
{

    /// <summary>
    /// Convert our List to a DataTable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    /// <returns>DataTable</returns>
    public static DataTable ToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        object[] values = new object[props.Count];
        using (DataTable table = new DataTable())
        {
            long _pCt = props.Count;
            for (int i = 0; i < _pCt; ++i)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
            }
            foreach (T item in data)
            {
                long _vCt = values.Length;
                for (int i = 0; i < _vCt; ++i)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }
    }

    /// <summary>
    /// Convert our List to a DataSet
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <returns>DataSet</returns>
    public static DataSet ToDataSet<T>(this IList<T> list)
    {
        Type elementType = typeof(T);
        using (DataSet ds = new DataSet())
        {
            using (DataTable t = new DataTable())
            {
                ds.Tables.Add(t);
                //add a column to table for each public property on T
                PropertyInfo[] _props = elementType.GetProperties();
                foreach (PropertyInfo propInfo in _props)
                {
                    Type _pi = propInfo.PropertyType;
                    Type ColType = Nullable.GetUnderlyingType(_pi) ?? _pi;
                    t.Columns.Add(propInfo.Name, ColType);
                }
                //go through each property on T and add each value to the table
                foreach (T item in list)
                {
                    DataRow row = t.NewRow();
                    foreach (PropertyInfo propInfo in _props)
                    {
                        row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
                    }
                    t.Rows.Add(row);
                }
            }
            return ds;
        }
    }

}
}

There are a few things I notice right off the bat.

Your variable names while not bad, could be better.  For instance props -> properties.  Stuff like this makes the code easier to read.
You have the properties, why not use a foreach loop to fill the datatable (you did it in ToDataSet)
the _ prefex should be used for class variables, not local variables.
try using var when declaring obvious variable types var row = t.NewRow()
There is no error checking when you are filling the values in the data table.  What happens if it is not a class (int, double, long)?  You could force the generic to be a class by adding where T : class.
Why don't you use the ToDataTable method to create the table in the ToDataSet method?  This will eliminate duplicate code, and have 1 point of failure/modification as required.  As an aside, I would use the code from ToDataSet to create your DataTable, as it is written better.
While I applaud your use of it, I'm not sure the using syntax is appropriate here.  I would move that to where these methods are being called using (var dt = list.ToDataTable())  Having it here will more than likely cause unexpected things to happen in your code.
I would make these extend IEnumerable<T> as that will make them way more useful by not limiting them to IList<T>.

I do like your use of white space and indentation, so good job on that.  The extra indentation will be removed when the using statements are removed.  I also like the name of your methods, very clear and concise to their intent.