Non-curses pager in C I have written a pager in C that is supposed to be used in systems where curses is not installed (or broken). It can also be used as a system-wide pager, it works with man pages (only on BSD, though). I want to spot any portability or output problems, as there may be some due to the dependence on buffered input:

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

/*
 * A very SIMPLE pager that does not require curses. If your curses library
 * is broken, this is practically the only portable one you can easily get.
 * Written by Daniel Roskams, in the public domain
 */

int
main(
    int argc,
    char *argv[])
{
    FILE *fp;
    int ch;

    if (argc < 2) {
        fp = stdin;
    } else if ((fp = fopen(argv[1], "r")) == NULL) {
        perror(argv[1]);
        return EXIT_FAILURE;
    }

    while ((ch = fgetc(fp)) != EOF) {
        if (ch == '\n') {
            getchar();
        } else {
            putchar(ch);
        }
    }

    if (ferror(fp)) {
        perror(argv[1]);
        return EXIT_FAILURE;
    }

    fclose(fp);
    return EXIT_SUCCESS;
}

I don't think there are any code problems themselves, since it compiles with the -Weverything flag with clang.

Bug
You're code has a bug-ish. When using this, if instead of hitting enter when asked to enter a character you enter some other letter and then you press enter, then next newline will be skipped and you will have two lines merged into one:

Fooa
BarHello, World!
Spama
Eggs

where the text file was:

Foo
Bar
Hello, World!
Spam
Eggs

To be honest, I'm not quite sure which line this is occurring on, but I think it has something to do with the getchar() call; when I pressed a, the next line was printed out.
Bug #2
Using the same file as above but this time passing it through STDIN like so:
./a.out < Foo

I got this as a result:

 Fooarello, World!pamggs

I didn't touch the keyboard at all; it just flew through the file. I don't think this is intended.
However, this time, I think I know why. It's this line:
getchar();

When the end of a line is reached, then this is called. However, since the file you are reading is from stdin and getchar() also reads from stdin, then this call is going to remove the next character from the file.
See the input again, but with the characters removed by getchar:

FoobarHello, World!spameggs

The bolded characters are the characters that appeared after each newline.


Rapidly requesting a file from a server Here is a Python script I wrote earlier for rapidly requesting a file from a server and timing each transaction. Can I improve this script?

from time import time
from urllib import urlopen

# vars
url = raw_input("Please enter the URL you want to test: ")

for i in range(0,100):
    start_time = time()
    pic = urlopen(url)

    if pic.getcode() == 200:
        delta_time = time() - start_time
        print "%d" % (delta_time * 100)
    else:
        print "error"
print "%d requests made. File size: %d B" % (i, len(pic.read()))

I'm new to Python, though, so I'm not sure if this is the best way to go about it.

Here are some comments on your code:

raw_input is a very inflexible way to get data into a program: it is only suitable for interactive use. For more general use, you should get your data into the program in some other way, for example via command-line arguments.
urllib.urlopen was removed in Python 3, so your program will be more forward-compatible if you use urllib2.urlopen instead. (You'll need to change the way your error handling works, because urllib2.urlopen deals with an error by raising an exception instead of returning a response object with a getcode method.)
The comment # vars does not seem to contain any information. Improve it or remove it.
The range function starts at 0 by default, so range(0,100) can be written more simply as range(100).
100 seems rather arbitrary. Why not take this as a command-line parameter too?
The variable pic seems poorly named. Is it short for picture? The urlopen function returns a file-like object from which the resource at the URL can be read. The examples in the Python documentation accordingly use f or r  as variable names.
I assume that this code is only going to be used for testing your own site. If it were going to be used to time the fetching of resources from public sites, it would be polite (a) to respect the robots exclusion standard and (b) to not fetch resources as fast as possible, but to sleep for a while between each request.
If an attempt to fetch the resource fails, you probably want to exit the loop rather than fail again many times.
You say in your post that the code is supposed to time "the entire transaction", but it does not do this. It only times how long it takes to call urlopen. This generally completes quickly, because it just reads the headers, not the entire resource. You do read the resource once (at the very end), but outside the timing code.
You multiply the time taken by 100 and then print it as an integer. This seems unnecessarily misleading: if you want two decimal places, then why not use "%.2f"?
Finally, there's a built-in Python library timeit for measuring the execution time of a piece of code, which compensates for things like the time taken to call time.

So I might write something more like this:

from sys import argv
from timeit import Timer
from urllib2 import urlopen

if __name__ == '__main__':
    url = argv[1]
    n = int(argv[2])
    length = 0

    def download():
        global length, url
        f = urlopen(url)
        length += len(f.read())
        f.close()

    t = Timer(download).timeit(number = n)
    print('{0:.2f} seconds/download ({1} downloads, average length = {2} bytes)'
          .format(t / n, n, length / n))


"Multi-key" dictionary I was making a relatively large-scale project in Python as a learning experiment, and in the process I found that it would be useful to have a map (or, in Python, I guess they're called dictionaries) where a value could have multiple keys.  I couldn't find much support for this out there, so this is the implementation I ended up going with:

def range_dict(*args):
    return_val = {}
    for k,v in args:
        for i in k:
            return_val[i] = v
    return return_val

COINS = range_dict((range(1,15), None),
                     (range(15,30), "1d6x1000 cp"),
                     (range(30,53), "1d8x100 sp"),
                     (range(53,96), "2d8x10 gp"),
                     (range(96,101), "1d4x10 pp"))

I was told that this wasn't really a good way to achieve what I wanted to do, but I don't really understand why.  It works perfectly in my application.  What's wrong with this?  Is there a better, more Pythonic way to do this?

1. Comments on your code

No docstrings! What does your code do and how am I supposed to use it?
No test cases. This ought to be a good opportunity to use doctests.
Given that your purpose here is to implement RPG lookup tables, your design seems a bit hard to use. The printed RPG table probably says something like this:

1-8     giant spider
9-12    skeleton
13-18   brass dragon
...

but you have to input it like this (adding one to the limit of each range):

range_dict((range(1, 9), "giant spider"),
           (range(9, 13), "skeleton"),
           (range(13, 18), "brass dragon"),
           ...)

which would be easy to get wrong.
The design also seems fragile, because it doesn't ensure that the ranges are contiguous. If you made a data entry mistake:

d = range_dict((range(1, 8), "giant spider"),
               (range(9, 13), "skeleton"),
               (range(13, 18), "brass dragon"),
               ...)

then the missing key would later result in an error:

>>> d[8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 8

2. An alternative approach

Here's how I'd implement this lookup table:

from bisect import bisect_left
from collections.abc import Mapping

class LookupTable(Mapping):
    """A lookup table with contiguous ranges of small positive integers as
    keys. Initialize a table by passing pairs (max, value) as
    arguments. The first range starts at 1, and second and subsequent
    ranges start at the end of the previous range.

    >>> t = LookupTable((10, '1-10'), (35, '11-35'), (100, '36-100'))
    >>> t[10], t[11], t[100]
    ('1-10', '11-35', '36-100')
    >>> t[0]
    Traceback (most recent call last):
      ...
    KeyError: 0
    >>> next(iter(t.items()))
    (1, '1-10')

    """
    def __init__(self, *table):
        self.table = sorted(table)
        self.max = self.table[-1][0]

    def __getitem__(self, key):
        key = int(key)
        if not 1 <= key <= self.max:
            raise KeyError(key)
        return self.table[bisect_left(self.table, (key,))][1]

    def __iter__(self):
        return iter(range(1, self.max + 1))

    def __len__(self):
        return self.max

Notes on this implementation:

The constructor takes the maximum for each range (not the maximum plus one), making data entry less error-prone.
The minimum of each range is taken from the end of the previous range, thus ensuring that there are no gaps between ranges.
The collections.abc.Mapping abstract base class provides much of the functionality of a read-only dictionary. The idea is that you supply the __getitem__, __iter__ and __len__ methods, and the Mapping class supplies implementations of __contains__, keys, items, values, get, __eq__, and __ne__ methods for you. (Which you can override if you need to, but that's not necessary here.)
I've used bisect.bisect_left to efficiently look up keys in the sorted table.


An implementation for the double factorial I have written this piece of code that implements the double factorial in Python both iteratively and recursively; the code works without problems, but I'm interested in improving my overall programming style. Here's the code:

def semif_r(n):                 #recursive implementation
    if n == 0 or n == 1:
        z = 1
    else:
        z= n * semif_r(n-2)
    return z

def semif_i(n):             #iterative implementation
    N = 1
    if n == 0 or n == 1:
        return 1
    elif n%2 == 1:
        for i in range(0,n/2):
            N =  (2*i + 1)*N
            VAL = N
        return n*VAL

    elif n%2 == 0:
        for i in range(0,n/2):
            N =  (2*i+2)*N
            VAL = N
    return VAL

I hope that some experienced programmers can give me some feedback about improving my code!

The recursive solution

The z local variable, you can just return directly.

The else could be dropped, as the if before it returns from the function.

Adding some doctests would be useful.

def semif_r(n):
    """
    >>> semif_r(5)
    15
    >>> semif_r(6)
    48
    >>> semif_r(25)
    7905853580625
    """
    if n == 0 or n == 1:
        return 1
    return n * semif_r(n - 2)

The iterative solution

No need to declare N up front. You could declare and initialize when you need it.

VAL is unnecessary, whenever its value is referenced, it's equal to N, so you could use N instead of VAL everywhere.

The start value of a range is 0 by default, so you don't need to specify that explicitly.

In n / 2, you're counting on that integer division will occur with truncation. In Python 3 there is a separate operator // for this.
It's good to make your code ready for Python 3, by using //, and adding this import:

from __future__ import division

The logic in the two range loops are almost the same. It would be good to extract that logic to a helper function.

As with the recursive implementation, doctests would be nice.

Note that in this code:

elif n%2 == 1:
    # ...

elif n%2 == 0:
    # ...

There, the 2nd elif could be replaced with a simple else,
since if n % 2 != 1, then it must be inevitably 0.

Putting it all together:

def semif_i(n):
    """
    >>> semif_i(5)
    15
    >>> semif_i(6)
    48
    >>> semif_i(25)
    7905853580625
    """
    if n == 0 or n == 1:
        return 1

    def multiply(coef):
        val = 1
        for i in range(n // 2):
            val *= (2 * i + coef)
        return val

    if n % 2 == 1:
        return n * multiply(1)

    return multiply(2)

Coding style

Please follow PEP8, the coding style guide (see the writing style in my sample implementations).


"Speed date" interview questions I'm learning Ruby and I would like to know if I have used the good syntax.
My script works, but can I simplify it and make it more elegant.

puts "Hello, what is youre name?"
name = gets.chomp

puts "Are you a boy? (yes/no)"
genre = gets.chomp

if genre == ("yes")
    puts "Do you like soccer #{name}? (yes/no)"
    foot = gets.chomp

        if foot == ("yes")
            puts "And beer? (yes/no)"
            biere = gets.chomp

                if biere == ("yes")
                    puts "Nice buddy!"
                else
                    puts "Too bad #{name}! But you like soccer!"
                end
        else
            puts "You're complicated #{name}!!!"
        end
else
    puts "Do you like romantics movies?"
    film = gets.chomp
end

I suggest defining an ask for free-form answers and a choose function for multiple-choice questions.  The choose function can perform validation.

You can use case-when instead of if-else.

def ask(msg)
  puts msg
  gets.chomp
end

def choose(msg, choices)
  loop do
    down_choices = choices.map(&:downcase)
    puts "#{msg} (#{choices.join('/')})"
    result = gets.chomp.downcase
    return result if down_choices.include?(result)
    puts "That answer is invalid"
  end
end

name = ask "Hello, what's you're name, dude?"
case choose "Are you a boy?", ["yes", "no"]
when "yes" # boy
  case choose "Do you like soccer #{name}?", ["yes", "no"]
  when "yes" # likes soccer
    case choose "And beer?", ["yes", "no"]
    when "yes" # likes beer
      puts "Nice buddy!"
    else # doesn't likes beer
      puts "Too bad #{name}! But you like soccer!"
    end
  else # doesn't like soccer
    puts "You're complicated #{name}!!!"
  end
else # girl
  ask "Do you like romantics movies?"
end

Note that nothing is done with the answer to the question, "Do you like romantics movies?".


Reverse the word order in string, without reversing the words I was tasked with using C++ to turn this

"Hello Jarryd, do you like socks?"

into:

"socks? like you do Jarryd, Hello";

Edit: The condition was to reverse this in place.

Here's what I came up with, knocked up in Visual Studio using the TestExplorer to run it. Criticism is much appreciated!

.h

namespace SentenceFlipNamespace
{
    class SentenceFlip
    {
    public:
        SentenceFlip();
        ~SentenceFlip();

        int FlipSentenceInPlace(char* in_Sentence);
        void SentenceFlip::Move(int in_StartIndex, char in_String[]);

    };
}

.cpp

namespace SentenceFlipNamespace
{
    SentenceFlip::SentenceFlip()
    {
    }

    SentenceFlip::~SentenceFlip()
    {
    }

    int SentenceFlip::FlipSentenceInPlace(char in_Sentence[])
    {
        int index = 0;
        int length = strlen(in_Sentence);

        while (index < length)
        {
            int dist = 0;
            int wordSize = 0;

            //Get the characters to the first word
            for (int i = length - 1; i > 0; i--)
            {
                if (in_Sentence[i] == ' ' && i != length - 1)
                {
                    dist = i - index;
                    wordSize = length - i - 1; //exclude the space
                    break;
                }
            }

            //Push everything forwards
            for (int i = 0; i <= dist; i++)
                Move(index, in_Sentence);

            //This leaves a space at the end, push it forward
            if (index + wordSize >= length)
                return 0;

            for (size_t i = 0; i < length - wordSize - index - 1; i++)
                Move(index + wordSize, in_Sentence);

            index += wordSize + 1; //include the space
        }

        return -1;
    }

    void SentenceFlip::Move(int in_StartIndex, char in_String[])
    {
        char temp = in_String[in_StartIndex];
        int length = strlen(in_String);
        for (int j = length - 1; j >= in_StartIndex; j--)
        {
            char temp2 = in_String[j];
            in_String[j] = temp;
            temp = temp2;
        }
    }
}

Test Method, since I don't invoke it in main.

namespace CodeChallengesTests
{
    TEST_CLASS(TextFlip)
    {
    public:
        TEST_METHOD(SentenceFlipInPlace)
        {
            SentenceFlipNamespace::SentenceFlip *testFlip = new SentenceFlipNamespace::SentenceFlip();
            char input[] = "Hello Jarryd, do you like socks?";
            char expectedResult[] = "socks? like you do Jarryd, Hello";
            testFlip->FlipSentenceInPlace(input);

            Assert::AreEqual(expectedResult, input, "Results do not match");
        }
    };

}

Your algorithm is supremely inefficient. Moving a word to the front moves all the other characters to the back, resulting in a quadratic algorithm. In addition to that, you repeatedly recalculate the length of the null terminated string.

As an aside, the standard library provides std::rotate() for moving part of a sequence from the end to the beginning, no need to write your own.

There is an alternative in-place algorithm which swaps every character at most twice, and traverses three times. Thus it is trivially proven linear:

Reverse every word in isolation. Remember the end if needed.
Reverse everything.

The standard library features std::reverse() for implementing this.


Pack several file documents into the single archive file in c# public byte[] PackToZip(IEnumerable<byte[]> files)
    {
        using (var archiveStream = new MemoryStream())
        {
            using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create))
            {
                foreach (var file in files)
                {
                    var entryName = string.Format("entry name");
                    using (var entryStream = archive.CreateEntry(entryName).Open())
                    {
                        entryStream.Write(file, 0, file.Length);
                    }
                }
            }

            return archiveStream.ToArray();
        }
    }

Is it safe, robust and efficient?

Every file within the ZIP archive has the same path, so it would be awkward when extracting them.  You should either take another parameter enumerating the entry names, or generate them automatically using a counter.

There's a limit to the scalability of this code, since the input and output all have to fit within memory.  That problem can be avoided by accepting Streams instead of byte[]s for the input.  You should also accept a Stream to which the output should be written.  You could still do everything in memory by using MemoryStreams everywhere, but you would also have the flexibility to read from and write to files or the network.


Grouping dates by weeks using reduce() I am trying to implement a function groupWeeks(dates) using reduce that allows me to group an array of objects { date: '2019-03-11', count: 8 } by weeks.

The following code works fine. Is there a way to refactor it? It seems to me that my solution is unnecessarily complex. Please ignore Date.prototype.getWeekNumber and getWeekStart(date).

const dates = [
  { date: '2019-02-24', count: 10 },
  { date: '2019-02-25', count: 11 },
  { date: '2019-02-26', count: 12 },
  { date: '2019-03-09', count: 8 },
  { date: '2019-03-10', count: 7 },
  { date: '2019-03-11', count: 6 },
  { date: '2019-04-14', count: 3 },
  { date: '2019-04-15', count: 2 },
  { date: '2019-04-16', count: 4 },
  { date: '2019-04-22', count: 5 }
];

/**
 * Returns the week number for this date.  dowOffset is the day of week the week
 * "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
 * the week returned is the ISO 8601 week number.
 * @param int dowOffset
 * @return int
 */
Date.prototype.getWeek = function(dowOffset) {
  /*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.epoch-calendar.com */

  dowOffset = typeof dowOffset == 'int' ? dowOffset : 0; //default dowOffset to zero
  var newYear = new Date(this.getFullYear(), 0, 1);
  var day = newYear.getDay() - dowOffset; //the day of week the year begins on
  day = day >= 0 ? day : day + 7;
  var daynum =
    Math.floor(
      (this.getTime() -
        newYear.getTime() -
        (this.getTimezoneOffset() - newYear.getTimezoneOffset()) * 60000) /
        86400000
    ) + 1;
  var weeknum;
  //if the year starts before the middle of a week
  if (day < 4) {
    weeknum = Math.floor((daynum + day - 1) / 7) + 1;
    if (weeknum > 52) {
      nYear = new Date(this.getFullYear() + 1, 0, 1);
      nday = nYear.getDay() - dowOffset;
      nday = nday >= 0 ? nday : nday + 7;
      /*if the next year starts before the middle of
           the week, it is week #1 of that year*/
      weeknum = nday < 4 ? 1 : 53;
    }
  } else {
    weeknum = Math.floor((daynum + day - 1) / 7);
  }
  return weeknum;
};

function getWeekStart(date) {
  var offset = new Date(date).getDay();
  return new Date(new Date(date) - offset * 24 * 60 * 60 * 1000)
    .toISOString()
    .slice(0, 10);
}

function groupWeeks(dates) {
  const groupsByWeekNumber = dates.reduce(function(acc, item) {
    const today = new Date(item.date);
    const weekNumber = today.getWeek();

    // check if the week number exists
    if (typeof acc[weekNumber] === 'undefined') {
      acc[weekNumber] = [];
    }

    acc[weekNumber].push(item);

    return acc;
  }, []);

  return groupsByWeekNumber.map(function(group) {
    return {
      weekStart: getWeekStart(group[0].date),
      count: group.reduce(function(acc, item) {
        return acc + item.count;
      }, 0)
    };
  });
}

console.log(groupWeeks(dates));

You said to ignore getWeekStart(), but I'm afraid I can't do that.  It appears that the intention of getWeekStart() is to take a date string (in YYYY-MM-DD form) and find the Sunday that starts the week (in YYYY-MM-DD form).  However, depending on the time zone in which the code is executed, it may actually find the Monday, or possibly a Saturday instead.

The problem is that

new Date("YYYY-MM-DD") interprets the date as a UTC timestamp:

  Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

date.getDay() returns the day of the week for the specified date according to local time, where 0 represents Sunday.
date.toISOString() works in UTC:

  The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

For the code to be reliably correct, you must work consistently in UTC — in other words, call date.getUTCDay() instead.

Furthermore, I'd rename getWeekStart() to weekStart().  The "get" prefix implies that you are fetching something that already exists.  However, you are actually computing something, so the prefix is superfluous, perhaps even misleading.


Password storage slim/trim it down? I have created a personal password storage program that takes the user's username, password, and for what account it is for, and stores it in a text file and can also read from them (assuming you type the right name in). What I'm looking to do, is either trim it down (take out none needed code) or finding more effective ways to go about this.

import java.io.*;
import java.util.*;

public class testing_file
{
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);

        System.out.println("Access or create?");
        String select = input.nextLine();

        switch(select)
        {
            case "Create":

                String name, user, password;
                FileOutputStream fop = null;
                File file;
                System.out.println("What account is this for?");
                name = input.nextLine();
                System.out.println("Enter the Username");
                user = input.nextLine();

                try
                {
                    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("c:/"+name+".dnx")));
                    file = new File("c:/"+name+".dnx");
                    fop = new FileOutputStream(file);

                    if (!file.exists())
                    {
                        file.createNewFile();
                    }

                    System.out.println("You may now input your password");
                    password = input.nextLine();

                    pw.write("Account: " + name);
                    pw.println();
                    pw.write("Username: " + user);
                    pw.println();
                    pw.write("Password: " + password);
                    pw.flush();
                    pw.close();
                    System.out.println("Operation Complete");

                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    try
                    {
                        if (fop != null)
                        {
                            fop.close();
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
                break;

            case "Access":
                String string="";
                System.out.println("Enter the account you wish to view");
                name = input.nextLine();
                String file1 = "c:/"+name+".dnx";

                //reading
                try{
                    InputStream ips=new FileInputStream("C:/"+name+".dnx");
                    InputStreamReader ipsr=new InputStreamReader(ips);
                    BufferedReader br=new BufferedReader(ipsr);
                    String line;
                    while ((line=br.readLine())!=null)
                    {
                        System.out.println(line);
                        string+=line+"\n";
                    }
                    br.close();
                }
                catch (Exception e){
                    System.out.println(e.toString());
                }
                break;

            default:
                System.out.println("Invalid method, terminating program");
                break;
        }
    }
}

Couple of Points.

Most Important: If your looking for secure password storage do not write your own library. Password storage is a very complex at best pratice. So I you care about the contents of the plain text password file being accessed don't do this.

If this is a learning exercise or not that critical go ahead, just keep that in mind.

Now for the actual review.

First thing that grabs me is if you are using Java 7 then you should
look at using try with resources. Try with resources has two
advantages for your code. First it always closes the streams (Under
normal jvm operation) secondly it is a little less verbose to write.

Basic syntax would be :

        try (PrintWriter pw = new PrintWriter(new BufferedWriter(
                new FileWriter("c:/" + name + ".dnx")));)
        {
        //Rest of code here.
        catch (IOException e)
        {
            e.printStackTrace();
        }

This eliminates the need for a lot of the closing resources.

Second problem you open a File reference that is never used. Remove all occurences of fop and file.
Consider moving the two "cases" to seperate methods. They are seperate things and don't need to share blocks.
I'm not convinced as your printing the stack trace anyway if there is any need to catch the exceptions. Let the method just throw them (Note this is only because this is a self contained program I'm suggesting this.

EDIT:

This is a first stab at refactoring. I've followed my advise above then further more there are three places where your writing a key and value into a stream followed by a blank line. I've moved that to a seperate method. I've also added in your pattern for user input to a method. Hopefully you find this shorter and not too hard to read.

There are a few other points that came up when I was doing this but their not so important.

Class Name: Your class doesn't follow java naming conventions.
All in Main: If the objective is to practice with java please note that this isn't very object orientated. The standard java idiom would be to create a class (possibly an instance of itself) and set the values you want on this for example no need to pass scanner and pw arround as I have done in my refactor.
Naming no huge deal but you should consider more meaningful names for variables "string" I'm looking at you.

import java.io.*;
import java.util.*;

public class testing_file {
    public static void main(String args[]) throws IOException {

        Scanner input = new Scanner(System.in);
        String select = prompt(input, "Access or create?");

        switch (select) {
            case "Create":
                createPasswordEntry(input);
                break;

            case "Access":
                readPasswordFile(input);
                break;

            default:
                System.out.println("Invalid method, terminating program");
                break;
        }
    }

    private static String prompt(Scanner input, String question) {
        System.out.println(question);
        return input.nextLine();
    }

    private static void readPasswordFile(Scanner input) throws IOException {
        String name = prompt(input, "Enter the account you wish to view");

        //reading
        try (
                InputStream ips = new FileInputStream("C:/" + name + ".dnx");
                InputStreamReader ipsr = new InputStreamReader(ips);
                BufferedReader br = new BufferedReader(ipsr);
        ) {
            String line, string = "";
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                string += line + "\n";
            }
        }
    }

    private static void createPasswordEntry(Scanner input) throws IOException {
        String name, user, password;
        name = prompt(input, "What account is this for?");
        user = prompt(input, "Enter the Username");

        try (
                PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("c:/" + name + ".dnx")));
        ) {
            password = prompt(input, "You may now input your password");
            writeKeyValue(pw, "Account", name);
            writeKeyValue(pw, "Username: ", user);
            writeKeyValue(pw, "Password", password);
            pw.flush();
            pw.close();
            System.out.println("Operation Complete");
        }
    }

    private static void writeKeyValue(PrintWriter pw, String key, String name) {
        pw.write(key + ": " + name);
        pw.println();
    }
}


Bash script to find included files in C code I've got the following shell script (let say get_includes.sh):

#!/usr/bin/env bash
includes=($(grep ^#include file.c | grep -o '"[^"]\+"' | tr -d '"'))
echo "0: ${includes[0]}"
echo "1: ${includes[1]}"

which aims at finding relative include files in source code file.

So for given file like this (file.c):

#include "foo.h"
#include "bar.h"

#include <stdio.h>

int main(void) {
    printf("Hello World\n");
    return 0;
}

It'll return the following results which are correct:

$ ./get_includes.sh
0: foo.h
1: bar.h

The code works as expected, however shellcheck complains about the following issues:

$ shellcheck get_includes.sh

    In get_includes.sh line 2:
    includes=($(grep ^#include file.c | grep -o '"[^"]\+"' | tr -d '"'))
              ^-- SC2207: Prefer mapfile or read -a to split command output (or quote to avoid splitting).

    For more information:
      https://www.shellcheck.net/wiki/SC2207 -- Prefer mapfile or read -a to spli...
      https://www.shellcheck.net/wiki/SC2236 -- Use -n instead of ! -z.

So:

I can't quote command substitution, as I expect the command to expand to an array.
I don't want to ignore the warning, I'd like to correct it.

I'm using Bash 4.

So, how I can correct the above line to satisfy shellcheck? If possible, I'd like to keep it in one-liner.

I've tried the following approaches which failed:

$ (grep ^#include file.c | grep -o '"[^"]\+"' | read -a myarr; echo $myarr)
(nothing is printed)
$ (grep ^#include file.c | grep -o '"[^"]\+"' | mapfile myarr; echo $myarr)
(nothing is printed)

... so what's going on?

$ (grep ^#include file.c | grep -o '"[^"]\+"' | read -a myarr; echo $myarr)
(nothing is printed)
$ (grep ^#include file.c | grep -o '"[^"]\+"' | mapfile myarr; echo $myarr)
(nothing is printed)

Why doesn't this work? Because "each command in a pipeline is executed in its own subshell". As the page explains, you could enable the lastpipe option to have the last element of the pipeline run in the current process. (The page doesn't mention that this will only work when you use it in a script, where job control is not active (as mentioned here). It won't work in an interactive shell.)

Keep pipelines as short as possible

It's good to use the fewest possible processes in pipelines.
Multiple grep in a pipeline are points to look at with suspicion.
You can make the first grep work a little harder,
using a stricter pattern, and then you can achieve the same result with 2 processes instead of 3:

grep '^#include .*"' file.c | cut -d'"' -f2


SQLite search disregarding spaces and Pinyin tones I have a column where, pretty much, each entry has numbers (specifically #1-4) and spaces (' '). I wanted to make a query that could avoid having to know these numbers and spaces.

$results = $db->query( "SELECT CHS, PIN, DEF FROM MAIN WHERE CHS LIKE '%".$q."%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(PIN, '1',''),'2',''),'3',''), '4',''),' ','') LIKE '%".$q."%' OR PIN LIKE '%".$q."%'");

The part that I'm worried (read:ashamed) about is:

REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(PIN, '1',''),'2',''),'3',''), '4',''),' ','')

Is this a super bad way to code?

Very interesting question!

I can't see which other way could be used in SQL by itself.

But an alternative method might be to prepare a regexp pattern, then use it with REGEXP, like this:

function tones_pattern($str) {
  for ($i = 0, $n = strlen($str); $i < $n; $i++) {
    @$pattern .= $str[$i] . '([1-4] )?';
  }
  return @$pattern;
}

$results = $db->query("
SELECT CHS, PIN, DEF
FROM MAIN
WHERE CHS LIKE '%" . $q . "%'
OR PIN REGEXP '" . tones_pattern($q) . "'
OR PIN LIKE '%" . $q . "%'
");

So you get rid of what ashames you :)
But I didn't test it, and it might have performance issues. Let me know!

Note: I wrote the $pattern above according what I understand from the example you gave in your comment, i.e. each tone digit is always followed by a space. So two points:

If the above rule is true, then your own solution could already be a bit simplified into
REPLACE(REPLACE(REPLACE(REPLACE(PIN, '1 ',''),'2 ',''),'3 ',''), '4 ','')
At the opposite if the space is not always present, my $pattern must be turned from '([1-4] )?' to [1-4]? ?


C++ binary search tree, not using recursion I made binary search tree using classes. I would like to know if I could do something better or maybe there is something wrong with my code. I decided not to use recursion. I would be very thankful for any suggestions.

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class Bst
{
private:
    struct BstNode
    {
        int data;
        BstNode* left;
        BstNode* right;
    };
public:
    Bst()
    {
        root = nullptr;
    }
    BstNode* insert(int data)
    {
        BstNode* newNode = new BstNode();
        newNode->data = data;
        newNode->left = nullptr;
        newNode->right = nullptr;
        return newNode;
    }
    bool add(int number)
    {
        if (root == nullptr)
        {
            root = insert(number);
        }
        else
        {
            BstNode* tmp_root = root;
            while (tmp_root != nullptr)
            {
                if (number <= tmp_root->data)
                {
                    if (tmp_root->left == nullptr)
                    {
                        tmp_root->left = insert(number);
                        return true;
                    }
                    else
                    {
                        tmp_root = tmp_root->left;
                    }
                }
                else
                {
                    if (tmp_root->right == nullptr)
                    {
                        tmp_root->right = insert(number);
                        return true;
                    }
                    else
                    {
                        tmp_root = tmp_root->right;
                    }

                }
            }
        }
        return false;
    }
    bool search(int number)
    {
        BstNode* tmp_root = root;
        while (tmp_root != nullptr)
        {
            if (number == tmp_root->data) return true;
            if (number < tmp_root->data)
            {
                tmp_root = tmp_root->left;
                continue;
            }
            if (number > tmp_root->data)
            {
                tmp_root = tmp_root->right;
            }
        }
        return false;
    }

private:
    BstNode* root;
};

int main()
{
    Bst tree;
    tree.add(10);
    tree.add(15);
    tree.add(2);
    tree.add(4);
    tree.add(7);
    for (int i = 1; i <= 20; i++)
    {
        string exist = tree.search(i) ? "YES" : "NO";
        cout << i << ": " << exist << endl;
    }
    system("pause");
    return 0;
}

You Break the Rule of Three/Five

{
    Bst  tree1;
    tree1.add(5);
    tree1.add(6);

    Bst  tree2(tree1);  // You just made a copy.
                        // Even though there is no copy constructor!

    tree2.add(8);       // both trees have 8 in them!!!!
}

Both trees are a mirror of each other. Adding nodes to one also adds nodes to the other. Also if you add the appropriate clean up code this will cause a break.

This is all caused because the compiler generates a couple of methods automatically. These methods work perfectly most of the time. But if your class contains an "Owned" RAW pointer then it does not work like you would expect.

So the simplest solution is to disable these auto-generated methods. You can then fix them later when you understand what is going on (look up rule of three).

    // Add this to your class.
    Bst(Bst const&)            = delete;
    Bst(Bst&&)                 = delete;
    Bst& operator=(Bst const&) = delete;
    Bst& operator=(Bst&&)      = delete;

Your class Leaks

For every call to new there must be a corresponding call to delete

    BstNode* newNode = new BstNode();

I don't see any calls to delete in your code. I don't see a destructor in your code to handle the clean up. So Add a destructor that deletes the tree from the root down.

Interface

The insert function:

BstNode* insert(int data)

looks out of place for a public function. This looks like an internal function that is called when you know where to insert the data value. Best to just make this private.

Simlify your Code

    BstNode* newNode = new BstNode();
    newNode->data = data;
    newNode->left = nullptr;
    newNode->right = nullptr;
    return newNode;

This can be replaced with a single line:

    return new BstNode{data, nullptr, nullptr};

Finding the node to insert a value:

    // Personally I would write this using recursion.
    // Its a balanced tree the chance of blowing the stack are small.
    BstNode*& find(BstNode*& node, int value)
    {
        if (node == nullptr) {
            return node;
        }
        return (node->value <= value)
                  ? find(node->left,  value)
                  : find(node->right, value);
    }

    // But if you must implement it using a loop then
    // its not much harder to write (you just need to handle
    // pointers to pointers). But it does make slightly harder
    // to read (Which is why I prefer the recursion route).
    BstNode*& find(BstNode*& node, int value)
    {
        BstNode** loop = &node;
        while(*loop != nullptr) {
            loop = (*loop)->value <= value
                  ? &((*loop)->left)
                  : &((*loop)->right);
        }
        return *loop;
    }

    void add(int value)
    {
        BstNode*&  nodeToModifiy = find(root, value);
        nodeToModifiy = insert(value);
    }


Prime pair set finder (Project Euler problem 60) I made a code that can find the prime sets:

  The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.

  Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.

First I made a set of 2 primes that satisfies two conditions.The first condition was the digit sum cannot be 3. The other condition was the concentrating test. After finding these all 2 prime sets, I tried to add the third prime to the set and again I checked these 2 conditions are satisfied. After that, I tried to add the fourth prime and so on.

The problem is, it gives answer in 41 min so what should I do?

import itertools
import time

start = time.perf_counter()
def prime(N):
    if N == 0 or N == 1 or N == 5:
        return False
    for i in range(2, int(N ** 0.5) + 1):
        if N % i == 0:
            return False
    return True

def dig_sum(j, n):  # j is the number, n is the element in the list as tuple
    d = 0
    if j == 0:
        for k in n:
            d += sum(int(digit) for digit in str(k))
        if d%3 == 0:
            return False
        return True
    else:
        s = sum(int(digit) for digit in str(j))
        for k in n:
            w = s + sum(int(digit) for digit in str(k))
            if w % 3 == 0:
                return False
        return True

def con_test(j, n):  # j is the number, n is the element in the list as tuple
    if j == 0:
        w = int(str(n[0]) + str(n[1]))
        w1 = int(str(n[1]) + str(n[0]))
        if prime(w) == False or prime(w1) == False:
            return False
        return True
    else:
        for i in n:
            w = int(str(j) + str(i))
            w1 = int(str(i) + str(j))
            if prime(w) == False or prime(w1) == False:
                return False
        return True

def st(n):            #to get rid of the repeated elements
    H = [tuple(sorted(i)) for i in n]
    G = set(H)
    return G

Primes = [i for i in range(3,8000) if prime(i) == True]   #Prime range

Com_two = list(itertools.combinations(Primes,2))

G2 = [i for i in Com_two if dig_sum(0,i) == True and con_test(0,i) == True]

G2r = st(G2)

G3 = [(i,*j) for i in Primes for j in G2r if dig_sum(i,j) == True and con_test(i,j) == True ]

G3r = st(G3)

G4 = [(i,*j) for i in Primes for j in G3r if dig_sum(i,j) == True and con_test(i,j) == True ]

G4r = st(G4)

G5 = [(i,*j) for i in Primes for j in G4r if dig_sum(i,j) == True and con_test(i,j) == True ]

F = [(sum(j),j) for j in G5]

end = time.perf_counter()
Time = end-start
print(Time)
print(F)

This is not so much of a code review question as it is an algorithm review question.

You are calling dig_sum() way too much.  You want pairs of primes, which summed together are not a multiple of 3: p1 + p2 != 3n.   If p1 % 3 == 1 and p2 % 3 == 2, then these primes must not be paired together.  This implies you can partition Primes into two sets: P1 and P2.

P1 = [ p for p in Primes if p % 3 != 2]
P2 = [ p for p in Primes if p % 3 != 1]

Note that 3 is actually part of both sets.

You can then solve the problem using primes from one set, then the other, and choose the lowest sum.

This gives 2 speed ups:

Half of the pairs are never considered, being from opposite sets.
dig_sum() need never be called, since the pairs will never equal 3.

Your prime(N) function can be sped up.   You are testing for prime by testing for divisibility by all values from 2 to sqrt(N).  You only need to test for divisibility by prime numbers in that range ... and you have a list of Primes.  Of course building the list of prime numbers using the prime(N) function, while using that list of prime numbers in that function is a bit of an conundrum... but not impossible.  Watch out for special cases.

You could also test if the number is prime by asking if N in Primes:.  Making Primes as set() would speed that up, but may also have a disadvantage; consider the pros and cons.

Glad to see you are making progress!

Your next improvement will come from further reducing the set of primes you are trying to pair with.  for i in P1 is better than for i in Primes because half the primes weren’t even tested.  We will further reduce the primes into smaller sets:

If you collect primes from P1 which pair with 3, and then you search the entire P1 space again looking for another prime which pairs with both numbers, you are retesting primes you’ve already rejected.

Instead: collect all primes from P1 which pair with 3.  Call that set P1{3}.  Then, for each number i in that set, you could look for other numbers j in this smaller set which form a conforming pair.

Better: compute all sets P1{i}.  Then you can do set intersections: P1{3} & P1{i}.  All numbers j in that intersection form conforming triples (3,i,j).

All numbers k in the intersect P1{3} & P1{i} & P1{j} will form conforming quadruples (3,i,j,k).

And so on.


Simplify double AJAX request for jQueryUI's autocomplete widget I'm using jQueryUI's Autocomplete widget for a product search. The data is in a database, so as the souce I passed it an AJAX request. My problem is, that I need some data about the currently focused option, so in the autocomplete's focus method, I'm calling another AJAX request to the same PHP file, to get some other data.

Here's the jQuery code I'm currently using:

$('.termeknev.ujtermek').autocomplete({
    autoFocus: true,
    minLength: 1,
    source: function (request, response) {
        $.ajax({
            url: "/backend/termekek-query.php",
            type: "POST",
            data: {
                "term": request.term
            },
            success: function (data) {
                response($.map(JSON.parse(data), function (items) {
                    return {
                        value: items.nev,
                        label: items.nev
                    }
                }));
            },
            error: function (error) {}
        });
    },
    focus: function (event, ui) {
        var $elem = event.target,
            $egysegar;
        $.ajax({
            url: "/backend/termekek-query.php",
            type: "POST",
            data: {
                "term": ui.item.value
            },
            success: function (data) {
                $egysegar = data.egysegar;
                $($elem).parent().parent('.ujtermek_wrapper').find('td.egysegar').text($egysegar);
            }
        });

    }
});

And here's the pretty simple PHP file it sends the request to:

<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    if(isset($_POST["term"]) && !empty($_POST["term"])) {
        require_once "../includes/constants.php";
        require '../includes/class.db.php';
        $searchTerm = trim($_POST["term"]);

        $db = new db(CONNECTION_STRING, DATABASE_USERNAME, DATABASE_PASSWORD);

        $bind = array(
            ":term" => "%$searchTerm%"
        );

        $results = $db->select(TERMEKEK_TABLE, "nev LIKE :term", $bind, "nev, egysegar");

        echo json_encode($results);
    }
}
?>

Note that I'm also using a PDO wrapper class, but that's irrelevant right now.

Anyway, is there any way to make this cleaner?

Regarding to readability, the code structure is actually great and it's easy to read the code.

The only thing, regarding to readability, is that you have mixed quotes everywhere.

But still, your code has things you can change:

Javascript:

You are using the autocomplete plugin with a request to the server.

You can skip that whole trouble and simply use the source option.
This will save you a lot of time.

If you don't like it (for whatever reason it is), you should do something on the error event on your $.post call.
Displaying an error message is better than doing nothing.
Ultimately, you can implement a caching system, but this is arguable.

If you still don't want to use the source option, you should remove the var $egysegar.
That var is completely useless.
This line:

$($elem).parent().parent('.ujtermek_wrapper').find('td.egysegar').text($egysegar);

Can be safely replaced by this one:

$($elem).parent().parent('.ujtermek_wrapper').find('td.egysegar').text(data.egysegar);

Of even shorter:

$($elem).parents('.ujtermek_wrapper').find('td.egysegar').text(data.egysegar);

PHP:

On your php file, you have this line:

if(isset($_POST["term"]) && !empty($_POST["term"])) {

According to the php documentation for the function empty():

  Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
  The following things are considered to be empty:
  - "" (an empty string)
  - 0 (0 as an integer)
  - 0.0 (0 as a float)
  - "0" (0 as a string)
  - NULL
  - FALSE
  - array() (an empty array)
  - $var; (a variable declared, but without a value)

This is a terrible idea!
If the search term is "0", it won't provide any results.
Replace your code with this:

if(isset($_POST["term"]) && $_POST["term"] !== "") {

This will solve the issue by verifying if the term isn't an empty string by using a strict comparison.

Right below, you have this:

require_once "../includes/constants.php";
require '../includes/class.db.php';

You mixed the quotes and you used 2 different instructions to include files.
I assume you can safely use require here, unless you include it on the file class.bd.php.
This will reduce the overhead of checking if the file was included before or not.
More yet (as a sidenote): you can use include instead! (assuming the file will always exist).

On the next line, you have this block:

$searchTerm = trim($_POST["term"]);

$db = new db(CONNECTION_STRING, DATABASE_USERNAME, DATABASE_PASSWORD);

$bind = array(
    ":term" => "%$searchTerm%"
);

$results = $db->select(TERMEKEK_TABLE, "nev LIKE :term", $bind, "nev, egysegar");

echo json_encode($results);

The code itself is fine, but why you store trim($_POST["term"]) in a variable to use it inside a string?
This makes readability a bit hard and it is a terrible idea on this code.
Remove that variable and concatenate it with the "%" string.
This is the result:

$bind = array(
    ":term" => "%".trim($_POST["term"])."%"
);

This is the right way to do it.

Edit (2014/12/01):

Since you are using the LIKE clause, you should escape the % character or it will return funky results.
You should escape it.
A great suggestion can be found here: How to escape literal percent sign when NO_BACKSLASH_ESCAPES option is enabled?
Using that brilliant idea, your code would be like this:

$bind = array(
    ":term" => "%".str_replace('%','|%',trim($_POST["term"]))."%"
);

$results = $db->select(TERMEKEK_TABLE, "nev LIKE :term escape '|' ", $bind, "nev, egysegar");

Or similar.

Outside the scope of the review, you can replace the whole block with only 2 lines:

$db = new db(CONNECTION_STRING, DATABASE_USERNAME, DATABASE_PASSWORD);

echo json_encode( $db->select(TERMEKEK_TABLE, "nev LIKE :term escape '|' ", array( ":term" => "%".str_replace('%','|%',trim($_POST["term"]))."%" ) , "nev, egysegar") );


Splitting a long string based on its graphical presentation I got a long string, let's call it Story.
I fetch this story from a database so I don't know how long it is.

I want to display this story in a view, but what if the story is too long so it doesn't fit in one view?

I don't want to adjust the font size because it may be a very long story and making the font size smaller is not a good solution.

Therefore I want to split the Story into more than one view.
By passing the story and getting a separated story as an array of String every item in the array can fit in one view.

This is the code, it hopefully gives you a hint what I'm trying to achieve exactly:

extension String {

    /// - returns: The height that will fit Self
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
        return ceil(boundingBox.height)
    }

    #warning("it's so slow that i can't handle it in main thread , ( 21 second for 15 items in array )")
    /// complition contains the separated string as array of string
    func splitToFitSize(_ size : CGSize = UIScreen.main.bounds.size ,font : UIFont = UIFont.systemFont(ofSize: 17) , complition : @escaping (([String]) -> Void) )  {
        DispatchQueue.global(qos: .background).async {

            // contents contains all the words as Array of String
            var contents = self.components(separatedBy: .whitespaces)

            var values : [String] = []
            for content in contents {
                // if one word can't fit the size -> remove it , which it's not good, but i don't know what to do with it
                guard content.isContentFit(size: size , font : font) else {contents.removeFirst(); continue;}
                if values.count > 0 {
                    for (i , value) in values.enumerated() {
                        var newValue = value
                        newValue += " \(content)"
                        if newValue.isContentFit(size: size, font: font) {
                            values[i] = newValue
                            contents.removeFirst()
                            break;
                        }else if i == values.count - 1 {
                            values.append(content)
                            contents.removeFirst()
                            break;
                        }
                    }
                }else {
                    values.append(content)
                    contents.removeFirst()
                }
            }
            complition(values)
        }
    }

    /// - returns: if Self can fit the passing size
    private func isContentFit(size : CGSize, font : UIFont) -> Bool{
        return self.height(withConstrainedWidth: size.width, font: font) < size.height
    }
}

This code is working, but it takes very long.
If I want to split a story to 15 views it takes 20 seconds or even longer.

How can I optimize this so it runs faster?

General remarks

Here are some general remarks that could make your code look a little cleaner :

Avoid using ; at the end of an instruction unless you have to put multiple instructions in the same line.
Document the functions properly: The description of the complition parameter of splitToFitSize isn't well formatted.
The correct spelling of complition is completion.
This is subjective and probably nitpicky: Put a space only where needed, one after the closing curly brace of a scope: } else, and none before a punctuation sign:  (size: size, font: font).

Catching the culprits

Sources of slow code:

" \(content)": String interpolation is slow as previously stated here.
self.components(separatedBy: .whitespaces): This has both a time and space complexity of O(n). Better iterate over the story with a String.Index.
DispatchQueue.global(qos: .background) : This is the lowest priority you could give to code and it wastes time by switching from the main thread to a background one, and back.
contents.removeFirst(): This is called in multiple places and repeatedly. Each call is O(n) since all the elements of the contents array shifted (Have a look here). This means that this algotithm shifts the elements of the contents array n + (n-1) + (n-2) + ... + 1 times. Knowing that :
$$n + (n-1) + (n-2) + ... + 1 = \frac{n(n+1)}{2}$$

it makes this algorithm O(n2), with n being the number of elements in contents. To circumvent this use an index that traverses the array.

Alternative implementation

Here is an alternative solution to split a string into a given size using a certain font :

extension String {

    static let blanks: [Character] = [" ", "\n", "\t"]

    func splitToFit (size: CGSize, using font: UIFont) -> [String] {
        var output: [String] = []
        var (fitted, remaining) = fit(self, in: size, using: font)
        var lastCount = fitted.count
        output.append(fitted)

        while remaining != "" {
            (fitted, remaining) = fit(remaining,
                                      in: size,
                                      using: font,
                                      lastCount: lastCount)
            lastCount = fitted.count
            output.append(fitted)
        }

        //Trim white spaces if needed
        //return output.map { $0.trimmingCharacters(in: .whitespacesAndNewlines)}
        return output
    }

    private func fit(
        _ str: String,
        in size: CGSize,
        using font: UIFont,
        lastCount: Int = 0) -> (String, String) {

        if !str.isTruncated(in: size, using: font) {
            return (str, "")
        }

        var low = 0
        var high = str.count - 1
        let lastValidIndex = high
        var substr = ""
        let step = lastCount/10  //Could be adjusted

        if lastCount != 0 {
            high = min(lastCount, lastValidIndex)
            while !str[0..<high].isTruncated(in: size, using: font) {
                low = high
                high = min(high + step, lastValidIndex)
            }
        }

        while low < high - 1 {
            let mid = low + (high - low)/2
            //Or more efficiently
            //let mid = Int((UInt(low) + UInt(high)) >> 1)
            //Have a look here https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html

            substr = str[0..<mid]

            let substrTruncated = substr.isTruncated(in: size, using: font)

            if substrTruncated {
                high = mid
            } else  {
                low = mid
            }
        }

        substr = str[0..<low]

        while !String.blanks.contains(substr.last!) {
            substr.removeLast()
            low -= 1
        }

        let remains = str[low..<str.count]
        return (substr, remains)
    }
}

It calls these other extensions :

extension String {
    func isTruncated(in size: CGSize, using font: UIFont) -> Bool {
        let textSize = (self as NSString)
            .boundingRect(with: CGSize(width: size.width,
                                       height: .greatestFiniteMagnitude),
                          options: .usesLineFragmentOrigin,
                          attributes: [.font: font],
                          context: nil).size

        return ceil(textSize.height) > size.height
    }

    subscript (range: Range<Int>) -> String {
        let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
        let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
        let range = startIndex..<endIndex

        return String(self[range])
    }
}

This code is inspired by this library but twice as fast . Further improvements are possible.

It was tested using the following code:

class ViewController: UIViewController, UIScrollViewDelegate {

    var scrollView: UIScrollView! {
        didSet{
            scrollView.delegate = self
        }
    }

    private let font = UIFont.systemFont(ofSize: 17)

    override func viewDidLoad() {
        super.viewDidLoad()

        let width = view.frame.width
        let height = view.frame.height
        let labelSize = CGSize(width: width - 40.0, height: height - 60.0)
        //Split the story here
        //let start = Date()
        let strings = story.splitToFit(size: labelSize, using: font)
        //let end = Date()
        //print("time =", end.timeIntervalSince(start))

        let scrollViewFrame = CGRect(x: 0,
                                     y: 0,
                                     width: width,
                                     height: height)

        scrollView = UIScrollView(frame: scrollViewFrame)
        scrollView.contentSize = CGSize(width: width * CGFloat(strings.count), height: height)
        scrollView.isPagingEnabled = true

        let colors: [UIColor] = [.red, .green, .blue]

        for i in 0 ..< strings.count {
            let label = UILabel()
            label.numberOfLines = 0
            label.frame = CGRect(origin: CGPoint(x: width * CGFloat(i) + 20.0,
                                                 y: 40.0),
                                 size: labelSize)
            label.backgroundColor = colors[i % 3]
            label.font = font
            label.text = strings[i]
            label.translatesAutoresizingMaskIntoConstraints = false
            scrollView.addSubview(label)
        }

        view.addSubview(scrollView)
    }
}

with story being a 10-paragraph string, 1104 total words, 7402 total characters, generated on this website, it takes 54ms on my local machine to split the story.

If the story is too long, and to avoid blocking the main thread I would recommend adding subviews asynchronously to the UIScrollView as the fitted strings are calculated one by one.


Select a list from a 2D list, take the last item from its nearest non empty left neighbour and put it at its head I've just got into Haskell a few days ago and I love it. I'm looking for some pointers and best practices on how to organise and write Haskell code specifically when it comes to managing errors, which I have done using Maybe.

The following is an implementation of "select a list from a 2D list, take the last item from its nearest non empty left neighbour and put it at its head" which is going to be a sub-routine of a puzzle solver.

How can I improve the succinctness of my function? I notice that the more complex the logic of my code gets, it starts to be somewhat unreadable.

module Seq where

import Data.Maybe

{-
 - Given a 2D list, select a list via 1-based index
 - Transfer the last item  of its immediate non blank
 - left neighbour to its head.
 - @param [[Int]]   input 2D list
 - @param Int       index of target list
 - @return          the input 2D list after operation -}
pull  :: Maybe [[Int]] -> Int -> Maybe [[Int]]

-- CASE : null input
pull Nothing _                = Nothing
-- CASE : nothing left to pull
pull (Just _) 1               = Nothing
pull (Just ([]:xss)) 2        = Nothing
-- CASE : index out of bounds
pull (Just [xs]) n            = Nothing

-- CASE : currently nothing to pull
pull (Just ([]:xs:xss)) n
  | p' == Nothing = Nothing
  | otherwise     = Just ([] : p'')
  where
    p' = pull (Just (xs:xss)) (n-1)
    p''= fromJust p'

-- CASE : base case; immediate pull
pull (Just (xs:xs2:xss)) 2   = Just ((init xs) : ((last xs):xs2) : xss)

-- CASE : intermediary blank; split results
pull (Just (xs:[]:xss)) n
  | p' == Nothing = Nothing
  | otherwise     = Just ((head p'') : [] : (tail p''))
  where
    p' = pull (Just (xs:xss)) (n-1)
    p''= fromJust p'

-- CASE : typical recursion to destination
pull (Just (xs:xs2:xss)) n
  | p' == Nothing = Nothing
  | otherwise     = Just (xs : p'')
  where
    p' = pull (Just (xs2:xss)) (n-1)
    p''= fromJust p'

The following are test cases for the function:

-- pull (Just [[1,2],[],[3],[]]) 4 == Just [[1,2],[],[],[3]]
-- pull (Just [[1,2],[],[3],[]]) 3 == Just [[1],[],[2,3],[]]
-- pull (Just [[1,2],[],[3],[]]) 2 == Just [[1],[2],[3],[]]
-- pull (Just [[],[],[1,2,3],[]) 2 == Nothing

First of all, there is no need for pull's first parameter to be Maybe [[Int]]. More on that later. Also, it will get easier if we switch the parameters. Also more on that later.

So let's start with that modification:

pull  :: Int -> [[Int]] -> Maybe [[Int]]
pull 1 _      = Nothing
pull 2 ([]:_) = Nothing
pull _ [_]    = Nothing

As you can see, I don't use names for things I'm not interested in. This makes it possible to focus on the interesting parts, e.g. the 1 and 2 matches, and the single-element match in the last line.

Now, your other definitions get a lot easier if you don't use guards, but pattern matching instead. If we rewrote the next pattern with your style, we end up with:

pull n ([]:xs:xss) =
  | p' == Nothing = Nothing
  | otherwise     = Just ([] : p'')
  where
    p' = pull (n-1) (xs:xss)
    p''= fromJust p'

Which is slightly easier due to the missing Justs in pull (n-1) …. However, with a case … of …, it's a lot more succinct:

pull n ([]:xss) = case pull (n-1) xss of
  Nothing -> Nothing
  Just p  -> Just ([] : p)

This "if there is Nothing return nothing, otherwise change the Just value" slightly pattern is so common, that there is even a function for that, fmap, which you can think of as

fmap :: (a -> b) -> Maybe a -> Maybe b
fmap _ Nothing  = Nothing
fmap f (Just v) = Just (f v)

So we can shorten that whole case to

pull n ([]:xss) = fmap ([]:) (pull (n-1) xss) -- *

We continue for the following cases:

pull 2 (xs:ys:xss) = Just ((init xs) : ((last xs):ys) : xss)
pull n (xs:[]:xss) = case pull (n-1) (xs:xss) of
  Nothing -> Nothing
  Just p  -> Just ((head p) : [] : (tail p))

pull n (xs:xss) = fmap (xs:) (pull (n-1) xss) -- *

Note that in both cases marked with -- *, you pattern matched on xs2:xss and used xs2:xss. That's not necessary.

So all patterns are:

pull  :: Int -> [[Int]] -> Maybe [[Int]]
pull 1 _           = Nothing
pull 2 ([]:_)      = Nothing
pull _ [_]         = Nothing
pull n ([]:xss)    = fmap ([]:) (pull (n-1) xss)
pull 2 (xs:ys:xss) = Just ((init xs) : ((last xs):ys) : xss)
pull n (xs:[]:xss) = case pull (n-1) (xs:xss) of
  Nothing -> Nothing
  Just p  -> Just ((head p) : [] : (tail p))
pull n (xs:xss) = fmap (xs:) (pull (n-1) xss)

Now that you can see all cases, it should be obvious that your missing at least one, namely the one for the empty list pull 0 []. Also note that using last and init isn't very efficient, since you need to traverse the list twice. You could write a function like

splitLast :: [a] -> ([a], a)

which returns both the init and the last element. But that's left as an exercise.

TL;DR

use case … of … (or pattern matching) instead of guards if you want to use the matched value either way (or use pattern guards).
make sure that you handle all cases
use Maybe on outputs; if your function cannot do something sensible with Maybe inputs, don't use it, that's what >>= is for.


Deleting temporary rows and columns from 21-sheet workbook I've created a VBA code to delete extra rows and columns that were needed for initial calculations but are required to be removed before converting/importing a csv into a database. The code loops through 21 sheets and runs for about 4 minutes. Is this a decent run time or can it be shortened?

Public Sub Test()

Dim xWs As Worksheet
Set xWs = ActiveSheet
Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim CalcMode As Long
Dim ViewMode As Long

'SETTING DEPENDENT VALUES TO ABSOLUTE VALUES============================='

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    xWs.DisplayPageBreaks = False
    xWs.UsedRange.Value = xWs.UsedRange.Value
Next

'DELETING ROWS BASED ON COLUMN B VALUES=================================='

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    xWs.DisplayPageBreaks = False
    Firstrow = xWs.UsedRange.Cells(1).Row
    Lastrow = xWs.UsedRange.Rows(xWs.UsedRange.Rows.count).Row
    For Lrow = Lastrow To Firstrow Step -1
        With xWs.Cells(Lrow, "B")
            If Not IsError(.Value) Then
                If .Value = "0" Then .EntireRow.Delete
            End If
        End With
    Next Lrow
Next

'DELETING DUPLICATE IP ADDRESSES=========================================='

With Sheets("IP-Unassigned")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Firstrow = .UsedRange.Cells(1).Row
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.count).Row
    For Lrow = Lastrow To Firstrow Step -1
        With .Cells(Lrow, "H")
            If Not IsError(.Value) Then
                If .Value = "1" Then .EntireRow.Delete
            End If
        End With
    Next Lrow
End With

'DELETING EXTRA COLUMNS========================================================'

With Sheets("IP-FSW")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-2070")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-MNTR")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-BBS")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-DET")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-TTR")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-CCTV")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(8).EntireColumn.Delete
    Columns(7).EntireColumn.Delete
End With

With Sheets("IP-Unassigned")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Columns(16).EntireColumn.Delete
    Columns(15).EntireColumn.Delete
    Columns(14).EntireColumn.Delete
    Columns(13).EntireColumn.Delete
    Columns(12).EntireColumn.Delete
    Columns(11).EntireColumn.Delete
    Columns(10).EntireColumn.Delete
    Columns(9).EntireColumn.Delete
    Columns(8).EntireColumn.Delete
End With

'=========================================================================='

End Sub

Portland Runner gave some good hints in the comments. Your selection and view changes do not add any value to what you want to achieve. I was able to remove all of them without issues. When doing macro-based Excel manipulation, you should always consider:

Setting Application.ScreenUpdating to False
Setting Application.Calculation to xlManual
Setting Application.EnableEvents to False
Resetting all of these values when you have completed the work

Of course, there will be exceptions, but these should be rare.

Always remember Option Explicit in VBA

Looking at absolute values:

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    xWs.DisplayPageBreaks = False
    xWs.UsedRange.Value = xWs.UsedRange.Value
Next

This can simply be:

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.UsedRange.Value = xWs.UsedRange.Value
Next

Cleaner, easier to see what it does, and easier to maintain.

Looking at Column B conditionals:

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    xWs.DisplayPageBreaks = False
    Firstrow = xWs.UsedRange.Cells(1).Row
    Lastrow = xWs.UsedRange.Rows(xWs.UsedRange.Rows.count).Row
    For Lrow = Lastrow To Firstrow Step -1
        With xWs.Cells(Lrow, "B")
            If Not IsError(.Value) Then
                If .Value = "0" Then .EntireRow.Delete
            End If
        End With
    Next Lrow
Next

Can become:

For Each xWs In Application.ActiveWorkbook.Worksheets
    Firstrow = xWs.UsedRange.Cells(1).Row
    Lastrow = xWs.UsedRange.Rows(xWs.UsedRange.Rows.count).Row
    For Lrow = Lastrow To Firstrow Step -1
        With xWs.Cells(Lrow, "B")
            If Not IsError(.Value) Then
                If .Value = "0" Then .EntireRow.Delete
            End If
        End With
    Next Lrow
Next

But I see repetition here. You can save your self a small loop. Admittedly, in the example you gave not a big issue but still a good practice to have.

Combining the loops - take note of the order in which I have done this. Do the most work first, and then do the simple clean-up. You could do it the other way (unless the xlError gets converted to a value on the way through?) but considering how much work is done in each step and how each step impacts on the amount of future work is a good habit.

For Each xWs In Application.ActiveWorkbook.Worksheets
    Firstrow = xWs.UsedRange.Cells(1).Row
    Lastrow = xWs.UsedRange.Rows(xWs.UsedRange.Rows.count).Row ' this is yet another different way I have seen to get the last row!
    For Lrow = Lastrow To Firstrow Step -1 ' Good that you know to go backwards.
        With xWs.Cells(Lrow, "B")
            If Not IsError(.Value) Then
                If .Value = "0" Then .EntireRow.Delete
            End If
        End With
    Next Lrow
    xWs.UsedRange.Value = xWs.UsedRange.Value ' Good that you know the simple way to convert formulas to values.
Next

Deleting extra columns - I see a lot of repetition here, and room for a subroutine.

Private Sub Delete78(xWs as Worksheet) 'Sheet could also include a Chart sheet
    xWS.Columns(8).EntireColumn.Delete
    xWS.Columns(7).EntireColumn.Delete
End Sub

Interestingly, you could also do Col7.Del, and then Col7.Del again to achieve the same effect! But at least the way you have written it shows the intent to remove the two columns.

You main part of the code then becomes:

Delete78 Sheets("IP-FSW")
Delete78 Sheets("IP-2070")
Delete78 Sheets("IP-MNTR")
Delete78 Sheets("IP-BBS")
Delete78 Sheets("IP-DET")
Delete78 Sheets("IP-TTR")
Delete78 Sheets("IP-CCTV")

Still some repetition - and this could be fixed as well. But that can be another day. Or perhaps now. Because your last code block seems different but is really the same. So let us try a new subroutine.

Private Sub DeleteColumnBlock(xWs as Worksheet, LastColumn as Long, FirstColumn as Long) ' Get the user to enter the values in a logical order. I chose this way.
    Dim ColIterator as Long
    ' Do some input validation. If they have entered bad values, fix it.
    For ColIterator = LastColumn to FirstColumn Step -1
        xWs.Columns(ColIterator).EntireColumn.Delete
    Next ColIterator
End Sub

Because we are dealing with a contiguous block, you could also do the slightly more obscure - same effect, but slightly harder to see at a glance what you intend to do. Add some good comments if you intend to do this!

For ColIterator = FirstColumn to LastColumn
    xWs.Columns(FirstColumn).EntireColumn.Delete ' continually remove a column until the right number have been removed.
Next ColIterator

Your main part of that entire block then becomes:

DeleteColumnBlock Sheets("IP-FSW"), 8, 7
DeleteColumnBlock Sheets("IP-2070"), 8, 7
DeleteColumnBlock Sheets("IP-MNTR"), 8, 7
DeleteColumnBlock Sheets("IP-BBS"), 8, 7
DeleteColumnBlock Sheets("IP-DET"), 8, 7
DeleteColumnBlock Sheets("IP-TTR"), 8, 7
DeleteColumnBlock Sheets("IP-CCTV"), 8, 7
DeleteColumnBlock Sheets("IP-Unassigned"), 16, 8

Summary

Turn off the parts of Excel that you don't need when doing grunt
work.
Try to run through a loop only once, don't repeat your loops
unless it is really really necessary.
DRY (don't repeat yourself) - repetition is a sign that you can
modularise some code making it easier to maintain.
Use explicit addressing, avoid Active and Select unless there is
no other way (e.g. copying sheets to a new workbook is a subroutine,
not a function so ActiveWorkbook is the only way to immediately
reference that new workbook).
-- If you do Activate or Select, make sure your following code is    actually using those elements.
-- And then consider if you can already reference it explicitly and do    so!

Addendum

In my examples above, I provided a very mechanistic way of deleting columns (based on the OP code). Two more ways to do this without using a loop are to set a range:

e.g. xWS.Range(xWS.Cells(1,7), xWS.Cells(1,8).EntireColumn.Delete
Setting a union of the columns, and then deleting


Proper Case Conversion (Performance) I wrote a simple function that converts an array of words into proper case (using bitwise operations) and returns the array. I performed a simple test using std::chrono to check how fast it was able to perform the conversion. Using a vector of 1000 words the function was able to do it in an average of 27 microseconds.

My question is, if there is a faster way of doing this or if there is anything that I have missed that may be detrimental to the performance of the function. In addition, if there is any syntactical issues or changes that you would recommend that would be greatly appreciated.

#include <vector>
#include <string>

std::vector<std::string> ToProperCase(std::vector<std::string>& array)
{
    if (array.empty())
        return array;

    // Loop through each word
    for (std::string& value : array)
    {
        // Loop through each character in the word
        for (unsigned int i = 0; i < value.size(); ++i)
        {
            // Capitalise first character
            value[0] &= (~(1 << 5));

            // Convert character to lower case
            if (i > 0)
                value[i] |= (1 << 5);
        }
    }

    return array;
}

std::vector<std::string> ToProperCase(std::vector<std::string>& array)
{
    // ...
    return array;
}

There are many styles when it comes to capitalization. ToProperCase should have a better name to indicate what the function does, which is to capitalize the first letter of each word.

array is a non-local reference being returned by value. Is this intended?

    if (array.empty())
        return array;

    // Loop through each word
    for (std::string& value : array)

While compilers will optimize it, the early return is unnecessary. The range-based for will check to see if array is empty. If it is, the function will return array.

Don't say in comments what can be clearly stated in code. Rather than using variable names like array and value, omit the comment and use words and word respectively. Reserve comments to concisely state intent and keep them crisp.

        // Loop through each character in the word
        for (unsigned int i = 0; i < value.size(); ++i)
        {
            // Capitalise first character
            value[0] &= (~(1 << 5));

            // Convert character to lower case
            if (i > 0)
                value[i] |= (1 << 5);
        }
    }

What is the proper case of a digit? Punctuation? Control characters? Should you be mutating non-alpha characters?

You do more work than necessary here. For every character in the word, you bitwise-and the first character then bitwise-or the current character. You can unswitch the body of the innermost loop by handling the first character before every subsequent character.

    for (auto& word : words)
    {
        if (word.empty()) continue;

        word[0] = std::toupper(static_cast<unsigned char>(word[0]));

        for (auto i = 1u; i < word.size(); ++i)
        {
            word[i] = std::tolower(static_cast<unsigned char>(word[i]));
        }
    }


Learning C: K&R 1-22: 'fold'. Is this solution very unwieldy? This exercise gave me some trouble, but I think I have a solution here that fulfils the spec. However it's very long compared to what I'm looking at on the solutions page at clc-wiki.net.

In the course of solving the problem I loop over my buffered line three or four times. This seems like quite a lot, and the various edge cases I have to account for means my prog is over 100 lines long (including spacing).

If anyone is kind enough to have patience to read it, I'd really appreciate your thoughts. Could it be shorter? Are there any glaring redundancies?

#include <stdio.h>

#define FOLD 20

int getline( char s[], int max );
int does_line_have_blanks( char line[], int len );
int locate_last_space ( char line[], int len );
int find_split( char line[], int len, int offset);
int mark_split_and_clean_trailing_spaces( char line[], int len, int spacecount );
int print_with_split( char s[], int split_pos );

int main()
{
  int len, i, split_pos, offset;
  char line[FOLD+1];

  len = split_pos = 0;
  for ( i = 0; i < FOLD+1; ++i )
    line[i] = 0;
  offset = 0; /*keeps track of characters that overflow the split so next buffer may be shortened accordingly*/

  while ( ( len = getline(line, (FOLD+1) - offset) ) > 0 ) {

    split_pos = find_split ( line, len, offset );

    offset = print_with_split( line, split_pos );

    /* clean out buffer*/
    for ( i = 0; i < FOLD+1; ++i )
      line[i] = '\0';
  }
  return 0;
}

int getline ( char s[], int max ) /* doesn't add newlines as K&R's does */
{
  int i, c;

  for (i = 0 ; i < max-1 && (c = getchar()) != EOF && c != '\n'; i++ )
    s[i] = c;
  s[i] = '\0';

  return i;
}

int find_split( char line[], int len, int offset ) {

    int i, split_pos, blanks;

    i = split_pos = 0;

    /*make sure there are blanks - if not the line will be printed as-is*/
    blanks = does_line_have_blanks( line, len );

    if ( len < FOLD-offset || blanks != 1 ) {
      split_pos = len; /* hit a newline or EOF - split at end of input */
    } else {
      split_pos = locate_last_space( line, len );
    }
    return split_pos;
}

int does_line_have_blanks( char line[], int len ) {

  int i, blanks;

  i = blanks = 0;

  for ( i = 0; i < len; ++i )  { /*len is at null char in line*/
    if (line[i] == ' ' )
      blanks= 1;
  }
  return blanks;
}

int locate_last_space ( char line[], int len ) {

  int i, inspace, spacecount, split_pos;

  inspace = spacecount = split_pos = 0;

  for ( i = 0; i < len; ++i ) {
    if ( line[i] == ' ' ) {
      inspace = 1;
      ++spacecount;
    } else {
      inspace = 0;
      if ( spacecount > 0 ) { /*if we leave inspace state, split on the preceding char */
        spacecount = 0;
        split_pos = i -1;
      }
    }
  }

  if ( inspace == 1 ) { /* and if we left in a space... */
    split_pos = mark_split_and_clean_trailing_spaces( line, len, spacecount );
  }

  return split_pos;
}

int mark_split_and_clean_trailing_spaces( char line[], int len, int spacecount ) {

  int split_pos, i;

  split_pos = i = 0;

  split_pos = len - spacecount; /*... split where it started */
  for ( i = split_pos + 1; i < len; ++i ) { /*nullify trailing spaces as per instructions*/
    line[i] = '\0';
  }

  return split_pos;
}

int print_with_split( char line[], int split_pos ) {

   int i, offset;

   offset = 0;

   for ( i = 0; i < split_pos; ++i ) {
      putchar(line[i]);
    }
    putchar('\n');
    for ( i = (split_pos + 1 ); line[i] != '\0'; ++i) /*miss out the space we split on*/ {
      ++offset; /* extra chars on next line, so buffer will be smaller */
      putchar(line[i]);
    }

    return offset;
}

EDIT Added a return type for main()

Instead of reading an entire line, then finding where to break the line, I think I'd read one word, and depending on the length of the line up to that point and the length of the word, decide whether or not to write a new-line before writing that word.

That way, the main loop would come out something like this:

while (getword(buffer, max_len)!=EOF) {
    if (current_length + strlen(buffer) > max_len) {
       print("\n");
       current_length = 0;
    }
    print(buffer);
    current_length += strlen(buffer);
}


House number parsing I have 2 functions used for parsing a house number and I think these can both be improved.

Any suggestions?

input:

45a - 47b

  or

45a bis 47b

output:

45,a,47,b

public static string[] HausnummerAufteilen(string hausNummer)
    {
        string[] result = new string[4];
        string[] resultVon = new string[2];
        string[] resultBis = new string[2];

        resultVon[0]  = string.Empty;
        resultVon[1]  = string.Empty;
        resultBis[0]  = string.Empty;
        resultBis[1]  = string.Empty;

        int pos1, pos2;
        pos2 = 0;
        pos1 = hausNummer.IndexOf("bis");
        if (pos1 != -1)
        {
            pos2 = pos1 + 3;
        }
        else
        {
            pos1 = hausNummer.IndexOf("-");
            if (pos1 != -1)
                pos2 = pos1 + 1;
        }

        if (pos1 > 0)
        {
            resultVon = HausnummerBuchst(hausNummer.Substring(0, pos1).Trim());
            resultBis = HausnummerBuchst(hausNummer.Substring(pos2, hausNummer.Length - pos2).Trim());
        }
        else
            resultVon = HausnummerBuchst(hausNummer);

        List<string> list = new List<string>();
        list.AddRange(resultVon);
        list.AddRange(resultBis);
        result = list.ToArray();

        return result;
    }

    public static string[] HausnummerBuchst(string hauseNummer)
    {
        string[] result = new string[2];

        result[0] = string.Empty;
        result[1] = string.Empty;

        int iPos;
        int testInt;
        bool bFound = false;

        for (iPos = 0; iPos < hauseNummer.Length; iPos++)
        {

            if (!int.TryParse(hauseNummer[iPos].ToString() ,out testInt))
            {
                bFound = true;
                break;
            }
        }

        if (bFound)
        {
            result[0] = hauseNummer.Substring(0, iPos).Trim();
            result[1] = hauseNummer.Substring(iPos, hauseNummer.Length - iPos).Trim();
        }
        else
            result[0] = hauseNummer;

        return result;

    }

Anytime I encounter a method that's only doing read-only parsing of strings and I see it's using String.IndexOf() and positions, it leaps out at me like a gigantic code smell.

Sometimes upon examination it turns out to be a legitimate and wise usage. However very often the programmer is manually splitting strings and looping through parts of the string. In other words they are doing exactly what String.Split() and foreach loops would offer them, but doing it the longer and less readable way.

This is one of those cases.

This may be just my personal taste in code. In any case, I can show you how I would tackle this problem using foreach and Split(), which I believe would be a great improvement to your methods. Except for this difference I think we might have taken comparable approaches.

Variable names

A lot of your variables are named with very little descriptiveness. You may understand that variables are named so that someone maintaining or reading the code (like me) can understand what's going on, but you could do much better in this department.

result: You use this word many times in your variable names. The problem is this name is completely useless to me. I can see it is the result of something (variously a function, a loop or some other process) but beyond that you might as well just call the variable foo or bar. hauseNummerVon and hauseNummerBin are far more understandable than resultVon and resultBin - I now know exactly what it is; it's the from house number and the to house number.

For either result[] array, I am left with nothing and I would have to read all of the code before I understood what they contained. This is a little backwards - I should know what the variable contains, then be able to read the code - with descriptive variable names giving me a greater understanding of what's going on.

bFound: Don't shorten your variable names like this. I'm left wondering: What is a b? What does it mean if it's found? Maybe this would be more recognisable to a German reader, but even so, expanding b to a word to say exactly what's found would do wonders for readability.
pos1, pos2: SeparatorPosition and SeparatorEnd would have been more descriptive. Better yet these variables are entirely unnecessary if you just use String.Split().

My approach

As I mentioned above, as oppose to editing your methods, I've written from scratch how I'd tackle this problem.

ParseHouseNumberRange

This is the entry method. You feed this method a string such as "20a bis 21c". It splits it up on the "bis" or the "-" (defined in the separators array) in order to produce smaller chunks of the original string.

Each of these chunks is passed to  then passes each of the results (in this case, "20a " and " 21c", spaces included) over to the non-public method ParseHouseNumber below. ParseHouseNumber will split these chunks up further and this method combines all the results into a single array which is returned.

Given "20a bis 21c" or similar, it returns an array: 20, a, 21, c.

public string[] ParseHouseNumberRange(string houseNumberRange)
{
    string[] separators = new string[] {"bis", "-"};
    string[] houseNumbers = houseNumberRange.Split(separators,
        StringSplitOptions.RemoveEmptyEntries);

    List<string> parsedList = new List<string>();

    foreach (string houseNumber in houseNumbers)
    {
        parsedList.AddRange(ParseHouseNumber(houseNumber));
    }

    return parsedList.ToArray();
}

ParseHouseNumber

This method takes a segment of an address from the method above, such as "20a ". After trimming out any spaces, it walks through the string character by character, plucking out digits and letters and sorting them into their own individual sections e.g. "1c4ad3" would be split into the sections 1, c, 4, ad, 3. Any non-digit non-letter characters are ignored.

Once all sections have been sorted out from the string provided to it, it returns those sections in the form of an array.

public string[] ParseHouseNumber(string houseNumber)
{
    bool firstRun = true;
    bool alphabeticMode = false; // set on first run

    houseNumber = houseNumber.Trim();

    List<string> sections = new List<string>();
    string currentSection = "";

    foreach (char c in houseNumber)
    {
        bool isLetter = Char.IsLetter(c);
        bool isDigit = Char.IsDigit(c);

        if (!(isDigit || isLetter)) continue;

        // If we've switched character type, then a section's finished.
        if (firstRun)
        {
            alphabeticMode = isLetter;
            firstRun = false;
        }
        else if ((isLetter && !alphabeticMode)
            || (isDigit && alphabeticMode))
        {
            sections.Add(currentSection);
            currentSection = "";
            alphabeticMode = !alphabeticMode;
        }

        currentSection += c;
    }

    if (currentSection != "") sections.Add(currentSection);

    return sections.ToArray();
}


Non-recursive tree traversal I want you to give me some feedback on how I could make it better or simpler.

public class NonRecursiveTraversal {

    private TreeNode root;

    private static class TreeNode {
        TreeNode left;
        TreeNode right;
        int item;

        TreeNode (TreeNode left, TreeNode right, int item) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    public void createBinaryTree (Integer[] arr) {
        if (arr == null)  {
            throw new NullPointerException("The input array is null.");
        }

        root = new TreeNode(null, null, arr[0]);

        final Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        final int half = arr.length / 2;

        for (int i = 0; i < half; i++) {
            if (arr[i] != null) {
                final TreeNode current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (arr[left] != null) {
                    current.left = new TreeNode(null, null, arr[left]);
                    queue.add(current.left);
                }
                if (right < arr.length && arr[right] != null) {
                    current.right = new TreeNode(null, null, arr[right]);
                    queue.add(current.right);
                }
            }
        }
    }

    public void preOrder() {
        if (root == null) return;

        final Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.add(root);

        while (!stack.empty()) {
            TreeNode node = stack.pop();
            System.out.print(node.item + " ");
            // LIFO
            if (node.right != null) stack.push(node.right);
            if (node.left != null) stack.push(node.left);
        }
    }

    public void reverseOrder() {
        if (root == null) return;

        final Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.add(root);

        while (!stack.empty()) {
            TreeNode node = stack.pop();
            System.out.print(node.item + " ");
            // LIFO
            if (node.left != null) stack.push(node.left);
            if (node.right != null) stack.push(node.right);
        }
    }

    public void inOrder() {
        if (root == null) return;

        final Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode node = root;

        while (!stack.isEmpty() || node != null) {
            if (node != null) {
                stack.add(node);
                node = node.left;
            } else {
               node = stack.pop();
               System.out.print(node.item + " ");
               node = node.right;
            }
        }
    }

    public void postOrder  () {
        if (root == null) return;

        final Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode node = root;

        while (!stack.isEmpty() || node != null) {
            while (node != null) {
                if (node.right != null) stack.add(node.right);
                stack.add(node);
                node = node.left;
            }

            node = stack.pop();

            // (node.right) != null means this node is parent of that tiny subtree
            // stack.pop != null ensures it was not the root.
            if (node.right != null && !stack.isEmpty() && node.right == stack.peek()) {
                TreeNode nodeRight = stack.pop();
                stack.push(node);
                node = nodeRight;
            } else {
                System.out.print(node.item + " ");
                node = null;
            }
        }
    }
}

Also, please correct my complexities: time and space both being \$O(n)\$.

I would not throw NullPointerException; it indicate that you are trying to use a variable which is null. Throw IllegalArgumentException instead; it indicated that arguments provided are not in a legal state.

And I personally don't like nesting too much loops and conditions. Try to separate them into smaller methods. When you put a block of code into a method, you are documenting it with the method name. Same applies for long conditions.

For example,

node.right != null && !stack.isEmpty() && node.right == stack.peek()

takes a while to "decipher". When you put it into the method isParentOfSubtree(...), it is obvious.

Also consider using some logger instead of System.out.