Simple “secret message” decoder program Since I am new to Java, I wanted to see if there were better ways of answering the same question. Are parts of my code redundant or maybe there's an easier way to get the same result?

Problem J4: Big Bang Secrets

The encoding algorithm is a Caesar cipher with a shift (\$S\$) that depends on a parameter (\$K\$) and its position in the word (\$P\$, where \$P = 1\$ for the first letter of each word): \$S = 3\$, \$P + K\$.  For example, when \$K = 3\$, ZOOM is encoded as FXAB:

\$S_1 = 3 \cdot 1 + 3 = 6\$, so Z \$\rightarrow\$ F
\$S_2 = 3 \cdot 2 + 3 = 9\$, so O \$\rightarrow\$ X
\$S_3 = 3 \cdot 3 + 3 = 12\$, so O \$\rightarrow\$ A
\$S_4 = 3 \cdot 4 + 3 = 15\$, so M \$\rightarrow\$ B

The challenge is to write a decoder. The first line of input contains \$K\$ (\$K \lt 10\$).  The second line contains the encoded message, containing up to 20 characters in uppercase.

public class Decoder {

public static void main(String[] args) {
    try {

        BufferedReader in = new BufferedReader(new InputStreamReader(
                System.in));
        int k = Integer.parseInt(in.readLine());
        String word = in.readLine();

        char[] cArray = word.toCharArray();

        for (int i = 0; i < word.length(); i++) {

            char out = (char) ((cArray[i]) - (((3 * (i + 1)) + k) % ('Z' - 'A')));

            if (out < 'A') {
                char wrap = (char) (('Z' + 1) - ('A' - out));
                System.out.print(wrap);
            } else {

                System.out.print(out);
            }
        }

    } catch (IOException e) {

        System.out.println("Error");

    }
}
}

Your program is great in that it does the job, but there are some ways to improve the implementation significantly.

As a design decision, some programs need to process data as it is being captured from the inputs. This program is not one of those, so it makes sense to make the input and processing steps very discrete.

Then, using some of the more modern Java features (the ones that have been there since Java7), you should use a try-with-resources statement to manage the input exceptions.

I would also recommend creating a container and calling method to handle the two-part inputs (the key, and the encrypted text).

Sometimes it's easier to show, than to tell. Let's start with the core decode routine. The two methods should make sense:

public static final String decode(final int key, final String encoded) {
    final int len = encoded.length();
    // prepare a space to store the decoded value
    final char[] decoded = new char[len];
    for (int i = 0; i < len; i++) {
        // use i+1 here since the algorithm has the first char at position 1, not 0.
        decoded[i] = decodeChar(encoded.charAt(i), i + 1, key);
    }
    // convert the decoded chars back to a String.
    return new String(decoded);
}

private static char decodeChar(final char encoded, final int position, final int key) {
    // modulo 26 eliminates multiple wrap-arounds.
    int rotate = (3 * position + key) % 26;
    // apply the rotation shift to the input
    int decval = (encoded - 'A') + 26 - rotate;
    // use another % 26 to keep the letters in range.
    return (char)('A' + (decval % 26));
}

Note how using the function extraction makes the code simpler?

Now, how to get the input in to that function? That would be simple:

public static void main(String[] args) {
    CypherText input = getEncoded();
    String decoded = decode(input.getKey(), input.getText());
    System.out.println("Decoded: " + decoded);
}

Note, that CypherText class is new.... but you can clearly see how the decode(...) would fit. Biw is the CypherText done?

private static final class CypherText {
    private final int key;
    private final String text;

    public CypherText(int key, String text) {
        super();
        this.key = key;
        this.text = text;
    }

    public int getKey() {
        return key;
    }

    public String getText() {
        return text;
    }

}

public static CypherText getEncoded() {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){
        int k = Integer.parseInt(reader.readLine());
        String word = reader.readLine();
        return new CypherText(k, word);
    } catch (IOException e) {
        e.printStackTrace();
        return new CypherText(0, "");
    }
}

I put this in an Ideone here


Triggerful Ruby Gem: create dynamic callbacks to methods The main purpose of Ruby is to be readable. I hope I did a good job with this gem I made. If there's any kind of suggestion of how to make this better, then please tell me.

class Trigger
  def initialize event, *callbacks
    @callbacks = callbacks
    @event = event

    if @callbacks[0].is_a? TrueClass
      @progression = true
      @callbacks.delete_at(0)
    elsif @callbacks[0].is_a? FalseClass
      @progression = false
      @callbacks.delete_at(0)
    else
      @progression = false
    end
  end

  def trigger(*args)
    case @event
    when Proc
      event_data = @event.call
    when Method
      event_data = @event.call
    else
      event_data = self.method(@event).call(*args)
    end
    @callbacks.each do |callback|
      if callback.instance_of? Trigger
        if @progression
          callback.trigger(*args, event_data)
        else
          callback.trigger(*args)
        end
      else
        case callback
        when Proc
          if @progression
            callback.call(*args, event_data)
          else
            callback.call(*args)
          end
        when Method
          if @progression
            callback.call(*args, event_data)
          else
            callback.call(*args)
          end
        else
          if @progression
            method(callback).call(*args, event_data)
          else
            method(callback).call(*args)
          end
        end
      end
    end
  end

  #triggers the callbacks without executing the original method
  def silent_trigger(*args)
    @callbacks.each do |callback|
      if callback.instance_of? Trigger
        callback.trigger(*args)
      else
        case callback
        when Proc
          callback.call
        when Method
          callback.call
        else
          method(callback).call(*args)
        end
      end
    end
  end

  # add callback(s) to instance
  def add(*callbacks)
    @callbacks.concat callbacks
  end

  def insert(index, *callbacks)
    @callbacks.insert(index, callbacks)
  end

  # remove callback(s) from instance
  def remove(*callbacks)
    callbacks.each do |callback|
      @callbacks.delete_at(@callbacks.index(callback) || @callbacks.length)
    end
  end

  def delete_at(index)
    @callbacks.delete_at(index)
  end

  def remove_all
    @callbacks = []
  end

  # fetch info from instance
  def index(callback)
    @callbacks.index(callback)
  end

  def event_name
    @event
  end

  def list
    @callbacks
  end
end

And if you want to try it out, here's a quick little console program to show you how it works:

$foobar = 0

def foo
  $foobar += 1
end

def bar
  puts $foobar
end

# create Trigger and callback, then trigger the Trigger
_foo = Trigger.new(:foo, :bar)
_foo.trigger

# create a method to determine if bar has been called before
$bar_called? = false
def bar_called
  $bar_called = true
end

# create a callback for the callback
_bar = Trigger.new(:bar, :bar_called)

# replace old callback with new one (note: you can use Methods, Procs, Symbols, Strings, or other Triggers too)
_foo.remove(:bar)
_foo.add(_bar)

# methods are not called when added to Trigger callbacks, only when triggered
puts $bar_called?
_foo.trigger
puts $bar_called?

You can find the gem here.

1) get rid of conditionals

I think your main problem here is the nested conditionals that litter your code. This increases complexity and tends to be less readable.

You can get rid of those conditionals using a method like this :

def make_callable(object)
  case object
  when Proc, Method then object
  when Trigger      then ->(*args){ object.trigger(*args) }
  else                   ->(*args){ public_send object, *args }
  end
end

so you can do things like :

@event = make_callable(event)
@callbacks = callbacks.map{ |c| make_callable c }

This way, all your callbacks will respond to call uniformly, so you won't need conditionals anymore.

2) use inheritance

As i see it, your @progression instance variable masks the need for two different behaviors, which means two different classes : a "silent" trigger, and a "verbose" one that extends the former.

class Trigger

  # factory method to instantiate the right type of callback.
  # I slightly changed the signature from the original #initialize
  # as I thought it would make more sense this way,
  # but it is possible to keep the original one with minor tweaks
  #
  def self.factory(verbose, event, *callbacks)
    verbose ? Verbose.new(event, *callbacks) : new(event, *callbacks)
  end

  def initialize(event, *callbacks)
    @event = make_callable(event)
    @callbacks = callbacks.map{ |c| make_callable c }
  end

  # SNIP : this class would also expose add_callback, remove_callback, etc.

  def trigger(*args)
    @callbacks.each{ |c| c.call(*args) }
  end

  private

  def make_callable(object)
    case object
    when Proc, Method then object
    when Trigger      then ->(*args){ object.trigger(*args) }
    else                   ->(*args){ public_send object, *args }
    end
  end
end

class Trigger::Verbose < Trigger
  def trigger(*args)
    event_data = @event.call(*args)
    super(*args, event_data)
  end
end

As you can see, this simplifies the logic a lot, and makes clear that we have two different behaviors, which is invaluable for consumers of your API.


Conditional row count across 4 tables I have the following function that works fine.  Is there a better way to do it and will this be efficient if I have 100+ rows returned from each table?

The database

Tables

wcx_articles
wcx_videos
wcx_apps
wcx_links

The corresponding _active column for each table

article_active
video_active
app_active
link_active

_active is a switch 1 or 0

This is my current function

public function findInactiveItems() {

    $query = "SELECT * FROM wcx_articles WHERE article_active = '0'
    UNION
    SELECT * FROM wcx_videos WHERE video_active = '0'
    UNION
    SELECT * FROM wcx_apps WHERE app_active = '0'
    UNION
    SELECT * FROM wcx_links WHERE link_active = '0'
    ";
        if( $this->num_rows( $query ) > 0 ) {
            $count = $this->num_rows($query);
            return $count;
        }
    }

 public function num_rows( $query ) {
    $query = $this->link->query( $query );
    if( mysqli_error( $this->link ) ) {
        $this->log_db_errors( mysqli_error( $this->link ), $query, 'Fatal' );
        return mysqli_error( $this->link );
    }
    else {
        return mysqli_num_rows( $query );
    }
    mysqli_free_result( $query );
}

SQL

If you want a count, ask for a count.  Don't ask the server to send all the data for all the rows, just to have the client count the rows.  (A few hundred rows is a trivial amount of data for a database to handle, but still, you should follow good practices.)

SELECT SUM(inactive_count) AS inactive_count
    FROM (
        SELECT COUNT(article_active) AS inactive_count
            FROM wcx_articles WHERE article_active = '0'
        UNION ALL
        SELECT COUNT(video_active)
            FROM wcx_videos WHERE video_active = '0'
        UNION ALL
        SELECT COUNT(app_active)
            FROM wcx_apps WHERE app_active = '0'
        UNION ALL
        SELECT COUNT(link_active)
            FROM wcx_links WHERE link_active = '0'
    ) AS wcs_objects;

Schema

If in fact all four of your tables are union-compatible with each other, then you should strongly consider merging them into one table with a wcx_type attribute that declares what type of object that row represents.

Are your …_active columns really strings?  Those columns should be of the BOOLEAN (i.e., TINYINT(1)) type.  The query should be adjusted accordingly: use …_active = 0 instead of …_active = '0'.

PHP

You reused the $query parameter to store the result of the query.  Don't be stingy like that — it's confusing.  Use a new variable to store the result.

You have a leak: mysqli_free_result( $query ); never gets called, because that statement is unreachable.

You are mixing the object-oriented and procedural styles of mysqli.  You should either use the object-oriented style consistently…

public function num_rows($query) {
    if (!($result = $this->link->query($query))) {
        $this->log_db_errors($this->link->error, $result, 'Fatal');
        return $this->link->error;
    }
    $num_rows = $result->num_rows;
    $result->free();
    return $num_rows;
}

or use the procedural style consistently…

public function num_rows($query) {
    if (!($result = mysqli_query($this->link, $query))) {
        $this->log_db_errors(mysqli_error($this->link), $result, 'Fatal');
        return mysqli_error($this->link);
    }
    $num_rows = mysqli_num_rows($result);
    mysqli_free_result($result);
    return $num_rows;
}


Converting Kinect Methods from Beta 2, to Version 1 So I have convert the getDisplayPosition from the beta version of the Kinect SDK to the full version. Here's what I have right nowThe Original

 private Point getDisplayPosition(Joint joint)
    {
        float depthX, depthY;
        nui.SkeletonEngine.SkeletonToDepthImage(joint.Position, out depthX, out depthY);
        depthX = Math.Max(0, Math.Min(depthX * 320, 320));  //convert to 320, 240 space
        depthY = Math.Max(0, Math.Min(depthY * 240, 240));  //convert to 320, 240 space
        int colorX, colorY;
        ImageViewArea iv = new ImageViewArea();
        // only ImageResolution.Resolution640x480 is supported at this point
        nui.NuiCamera.GetColorPixelCoordinatesFromDepthPixel(ImageResolution.Resolution640x480, iv, (int)depthX, (int)depthY, (short)0, out colorX, out colorY);

        // map back to skeleton.Width & skeleton.Height
        return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
    }

My Version

private Point getDisplayPosition(Joint joint)
    {
        float depthX, depthY;
        KinectSensor sensor = kinectSensorChooser1.Kinect;
        DepthImageFormat depth = DepthImageFormat.Resolution320x240Fps30;
        depthX = 320;
        depthY = 240;
        sensor.MapSkeletonPointToDepth(joint.Position, depth);
        depthX = Math.Max(0, Math.Min(depthX * 320, 320));
        depthY = Math.Max(0, Math.Min(depthY * 240, 240));
        int colorX, colorY;
        colorX = 320;
        colorY = 240;

        return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
    }

Basically I want to know if my version will do the same thing as the origin

Since I have this same question on Stack Overflow now, the answer can be found here. The updated version is:

private Point getDisplayPosition(DepthImageFrame depthFrame, Joint joint)
{
    float depthX, depthY;
    DepthImagePoint depthPoint = kineticSensor.MapSkeletonPointToDepth(joint.Position, depthImageFormat);

    depthX = depthPoint.X;
    depthY = depthPoint.Y;

    depthX = Math.Max(0, Math.Min(depthX * 320, 320));
    depthY = Math.Max(0, Math.Min(depthY * 240, 240));

    int colorX, colorY;
    ColorImagePoint colorPoint = depthFrame.MapToColorImagePoint(depthPoint.X, depthPoint.Y, sensor.ColorStream.Format);
    colorX = colorPoint.X;
    colorY = colorPoint.Y;

    return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
}


Get the difference between two dates, in the most convenient unit I use the following code in Javascript to get the difference between two Date objects. I want the result to return the difference in:

seconds if the result is less than 60 secs
minutes if the result is less than 60 mins
hours if the result is less than 24 hours
days otherwise

The code is very long and I see lots of code duplication. Isn't there a smarter/shorter way to do this (without using a library)?

function dateDiff(a, b) {
  let utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getUTCHours(), a.getUTCMinutes(), a.getUTCSeconds());
  let utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate(), b.getUTCHours(), b.getUTCMinutes(), b.getUTCSeconds());

  let result = (utc2 - utc1) / (1000 * 60 * 60 * 24);
  let floor = Math.floor(result);
  if (floor > 0) return floor + "d";

  result *= 24;
  floor = Math.floor(result);
  if (floor > 0) return floor + "h";

  result *= 60;
  floor = Math.floor(result);
  if (floor > 0) return floor + "min";

  result *= 60;
  floor = Math.floor(result);
  if (floor > 0) return floor + "sec";
}

Use getTime instead of the UTC transformation it'll return the timeStamp.

So your diff would be:

b.getTime() - a.getTime()

This will give you the milliseconds if you want the seconds you would divide it by 1000 so you would get:

var secondsDiff = (b.getTIme() - a.getTime())/1000

Then for the return

if (secondsDiff > 86400)  {
 return Math.floor(secondsDiff/86400) + ' D'
}
if (secondsDiff > 3600)  {
 return Math.floor(secondsDiff/3600) + ' h'
}
if (secondsDiff > 60)  {
 return Math.floor(secondsDiff/60) + ' min'
}
if (secondsDiff > 0) {
 return secondsDiff + ' sec'
}


Efficient dictionary printing Here's what my task is:

  Dependant on the "Logged In" user, they'll have different access rights and will see different menus.

I have tried using the .get() function.

choices = {1: "| Student Details", 2: "| Student Grades", 3: "| Finance", 4:"| Staff Details", 5:"| Staff Payments"}

print(choices.get(1))
print(choices.get(4))

GIVEN OUTPUT >>

| Student Details
| Staff Details

But it will look very inefficient with all the Access Rights. Some access rights have access to different menus e.g (Access Level 1 = Menu 1 and Menu 4). So I cannot just use a for loop to print all menus like so.

for option,num in choices.items():
    print(option,num)

I've also attempted using the itemgetter() function which is available in the operator module, but I was unable of figuring out how to:
1. Print the outcome in lines, 2. Numerate the outcome in order (1,2,3)

choices = {1: "|Student Details", 2: "| Student Grades", 3: "| Finance", 4:"| Staff Details", 5:"| Staff Payments"}

print(itemgetter(3,5)(choices))

GIVEN OUTPUT >>
('| Finance', '| Staff Payments')

REQUIRED OUTPUT >>
1 | Finance
2 | Staff Payments

Here's an example of the inefficient code I have at the moment:

if user_name == "Mike":
    print("-Managing Menu-")
    print("1 | Staff Payments. ")
    print("2 | Finance. ")
    option = int(input("Option Choice (1-2): "))
    while option not in range(1,2):
        option = int(input("Option Choice (1-2): "))
    if option == 1:
        print("Welcome to Staff Payments")
    elif option == 2:
        print("Welcome to Finance.")
    else:
        print("Error.")

I'd really appreciate any feedback and help with this task.

You say that using itemgetter is better than using choices.get, as you don't have to call get multiple times,
however this is wrong.

If we look at itemgetter it says that it uses __getitem__.
Python's function get also uses __getitem__ but allows a default value.
And so the following give the same:

print(itemgetter(3, 5)(choices))
print(tuple(map(choices.get, [3, 5])))

As you say using the above is bad, as it doesn't print things on new lines, you could use str.join.
As you want to join each one with a newline or '\n'.

print('\n'.join(map(choices.get, [3, 5])))

In both examples this won't give the same output as your inefficient code.
As there are no numbers before the choice.

To improve your inefficient code, you could alternately make an options dictionary,
and use options.get but with a supplied default value.

options = {
    1: "Welcome to Staff Payments",
    2: "Welcome to Finance"
}
print(options.get(option, "Error."))

Alternately to your current code pattern, you can make a dictionary holding users with places they are allowed to.
This would be by supplying user-names, and the allowed places in a dictionary.

# Access control list
ACL = {
    "Mike": [3, 5],
    "Joe": [1]
}

places = ACL[user_name]
options = dict(enumerate(map(choices.get, places)))
print("-Managing Menu-")
for option, num in choices.items():
    print("{} {}".format(option, num))

option = int(input("Option Choice (1-2): "))
while option not in range(1,2):
    option = int(input("Option Choice (1-2): "))

if option == 1:
    print("Welcome to Staff Payments")
elif option == 2:
    print("Welcome to Finance.")
else:
    print("Error.")

As you can see, whilst we took advantage of a new dictionary to print the allowed places,
you would still need boilerplate for all the locations.
Instead you could use str.format to display the places, just like I did for the menu.

choices = {
    1: "Student Details",
    2: "Student Grades",
    3: "Finance",
    4: "Staff Details",
    5: "Staff Payments"
}

def managing_menu(user_name):
    places = ACL[user_name]
    options = dict(enumerate(map(choices.get, places)))
    print("-Managing Menu-")
    for option, place in choices.items():
        print("{} | {}".format(option, place))

    option = int(input("Where do you wish to go: "))
    while option not in options:
        option = int(input("Where do you wish to go: "))

    location = options.get(option, None)
    if location is None:
        print("Error.")
        return

    print("Welcome to {}.".format(location))

There are some other ways that you can improve the code:

don't use raw int(input())'s instead use them with a try and except.
This will cause the program to not crash if you enter Finance, rather than 2.
You also are probably calling a function after printing "Welcome to Finance",
and so you would need to add that functionality to the options dictionary.
(It's not hard)
You should change the place you define option to become a function,
this is as you are likely to need the function in more than that one location.


Embarking on a Tic Tac Toe journey with JavaFX On my educational trek through the capabilities of JavaFX, I thought it would be a valuable challenge to create Tic Tac Toe. It took me far longer than expected to get this far, but despite likely being even further from completion, I'd like a review on the current state of things and on anything my 'blind coding' unwittingly implemented unconventionally/inefficiently/just plain weirdly.

Some names may seem strange, but that could be due to my editing the image-related code to point to URLs rather than local files for the sake of this post.

TicTacToe main class:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class TicTacToe extends Application {
    static Player player = Player.O_PLAYER;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Button[] cells = new Button[9];
        for (int i = 0; i < cells.length; i++) {
            cells[i] = new Button("",
            new ImageView(new Image("http://i.imgur.com/KAQPbPd.png")));
            registerOnAction(cells[i]);
        }

        GridPane board = new GridPane();
        for (int row = 1, col = 1, cell = 0; row <= 3; row++, col -=2) {
            board.add(cells[cell++], row, col++);
            board.add(cells[cell++], row, col++);
            board.add(cells[cell++], row, col);
        }

        Scene scene = new Scene(board);
        stage.setScene(scene);
        stage.setTitle("TicTacToe By Legato");
        stage.getIcons().add(new Image("http://i.imgur.com/gxhJkc0.png"));
        stage.show();
    }

    private static Image retrieveMarker() {
        player = player == Player.X_PLAYER ? Player.O_PLAYER : Player.X_PLAYER;
        return player.marker();
    }

    private static void registerOnAction(Button button) {
        button.setOnAction(e ->
            button.setGraphic(new ImageView(retrieveMarker()))
        );
    }
}

Player enum:

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

public enum Player {
    X_PLAYER(new ImageView(new Image("http://i.imgur.com/HY6GeUY.png"))),
    O_PLAYER(new ImageView(new Image("http://i.imgur.com/KgHHxL6.png")));

    private final ImageView view;

    Player(ImageView view) {
        this.view = view;
    }

    public Image marker() {
        return view.getImage();
    }

    @Override
    public String toString() {
        return name().charAt(0) + name().substring(2).toLowerCase();
    }
}

Follow-ups:

Completed Tic-Tac-Toe.
Tic-Tactics.

This

GridPane board = new GridPane();
for (int row = 1, col = 1, cell = 0; row <= 3; row++, col -=2) {
    board.add(cells[cell++], row, col++);
    board.add(cells[cell++], row, col++);
    board.add(cells[cell++], row, col);
}

just looks odd. The initialiszing of 3 variables , incrementing of one of then and decrementing one of them in one single for() is a little bit to much IMHO.

how about using a more obvious loop like

for (int cell = 0; cell < cells.length; cell++) {
     board.add(cells[cell], cell / 3, cell % 3);
}

ok, one has to know if he/she reads this, that this will lead to

  (0 , 0 , 0)
  (1 , 0 , 1)
  (2 , 0 , 2)
  (3 , 1 , 0)
  (4 , 1 , 1)
  (5 , 1 , 2)
  ...

but it is less code without the strange incrementing and decrementing.

The creation of the buttons should be improved. Like now you are creating a new Image for each button. Just create the Image once and reuse it like

Image image = new Image("http://i.imgur.com/KAQPbPd.png");
Button[] cells = new Button[9];
for (int i = 0; i < cells.length; i++) {
    cells[i] = new Button("", new ImageView(image);
    registerOnAction(cells[i]);
}

much better now, ins't it ?


Removing duplicates without using a temporary buffer This question is from Cracking the Coding Interview and in this question they have asked to solve without using temporary buffer.

I have used Iterator interface. Can I use it or need to re-implement it?

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

public class WithoutExtraSpace {

    public static void main(String[] args) {

        LinkedList<Integer> list = new LinkedList<Integer>();
        list.add(9);
        list.add(1);
        list.add(3);
        list.add(2);
        list.add(5);
        list.add(7);
        list.add(8);
        list.add(3);
        list.add(1);
        list.add(8);
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);

        Iterator<Integer> itr = list.iterator();
        if (itr.hasNext()) {
            Integer previous = itr.next();
            while (itr.hasNext()) {
                Integer current = itr.next();
                if (previous.equals(current)) {
                    itr.remove();
                }
                previous = current;
            }
        }
        System.out.println(list);
    }
}

public class WithoutExtraSpace {

Class names should reflect what the class does.  In this case, I would expect a name like ListUtilities or even CrackingTheCodingInterviewExercise.  It's not clear to me what WithoutExtraSpace even means.  Perhaps a reference to the lack of a temporary buffer?  Then it should have been DuplicateRemoverWithoutExtraSpace.  Or just DuplicateRemover.

    LinkedList<Integer> list = new LinkedList<Integer>();
    list.add(9);
    list.add(1);
    list.add(3);
    list.add(2);
    list.add(5);
    list.add(7);
    list.add(8);
    list.add(3);
    list.add(1);
    list.add(8);
    System.out.println(list);

I'd add some whitespace in this section:

    List<Integer> list = new LinkedList<Integer>();

    list.add(9);
    list.add(1);
    list.add(3);
    list.add(2);
    list.add(5);
    list.add(7);
    list.add(8);
    list.add(3);
    list.add(1);
    list.add(8);

    System.out.println("Unsorted:  " + list);

Now I have a declaration block, an initialization block, and the start of the coding block.

I changed the declaration of list.  Instead of being of type LinkedList, I made it of type List, which is the interface name.  This is why we have things that implement interfaces, so we don't have to care what the implementation is.  You happen to be using a LinkedList, but if you change that to an ArrayList or any other implementation, it shouldn't matter.

I added an "Unsorted:" at the beginning of the println.  When I first ran this, I didn't know what the various outputs were.  Now I do.

Avoid code in main

You put a lot of your code in the main method itself.  As a general rule, there should be very little code in main.  Process the arguments, perhaps initialize variables, and then call methods to do the heavy lifting.  This allows you to reuse those pieces that do actual work.  If all the code is in main, then you have to edit main to use it.  Further, you can't just add your class to another project; you'd have to copy the code itself.

    removeDuplicates(list);

    System.out.println("Unique:  " + list);

This is the remainder of the main method.  Now let's work on removeDuplicates.

public static <T extends Comparable<? super T>> void removeDuplicates(List<T> list) {
    Collections.sort(list);

    Iterator<T> itr = list.iterator();
    if (itr.hasNext()) {
        T previous = itr.next();

        while (itr.hasNext()) {
            T current = itr.next();

            if (previous.equals(current)) {
                itr.remove();
            } else {
                previous = current;
            }
        }
    }
}

Rather than lock us into a single implementation, let's use generics to allow us to cover a wide variety of possible types.  Why <T extends Comparable<? super T>>?  The short answer is that's what made my IDE happy.  The reason why it made the IDE happy is that Collections.sort uses it.  So we're basically saying that removeDuplicates will work with any List type that we can sort.

Everywhere in this section of code that used to say Integer now says T instead.

            if (previous.equals(current)) {
                itr.remove();
            }
            previous = current;

I changed this to

            if (previous.equals(current)) {
                itr.remove();
            } else {
                previous = current;
            }

My reasoning is that when we just removed current from the List, why should we be comparing it to other elements?  It's already gone and we shouldn't remove other elements based on something that is no longer in the List.  Note that this has no functional impact, as we know that previous and current are equal if we just removed current.  But I find it easier to follow, and it avoids an unnecessary assignment.  The new logic is that we either remove current from the list (as a duplicate) or we update previous (since there are no more duplicates of it, we need to start looking for duplicates of current).  We don't do both at once.

    System.out.println(list);

I removed the display of the sorted with duplicates list.  It seems more like debugging code than code necessary to solve the problem.  As such, it should be removed before turning in the code for review.

Your Question

  I have used Iterator interface. Can I use it or need to re-implement it?

I don't know the answer to this.  For a definitive answer, you'd have to ask the interviewer.  If you told us what the book actually says, we might be able to give you some guidance.

As a general rule, it's good to ask the interviewer questions that show you understand the problem.  Asking if it is all right to use the iterator() method of List is perfectly reasonable.

Another question that is relevant here is if you are allowed to change the existing order of the List.  Clearly it must be mutable, as you have to remove duplicates.  It's not as clear that order doesn't matter.  It might or might not.

Complexity

Collections.sort is an \$O(n \log n)\$ algorithm in terms of time.  The rest of the method is linear (\$O(n)\$) in time.  You iterate through list once.  This makes the method \$O(n \log n)\$ overall.

In terms of memory complexity, the iteration is \$O(1)\$.  It adds three variables, regardless of the size of list.  The sort is more complex.  It can use up to \$n/2\$ new object references.  That makes it \$O(n)\$ in memory complexity.  This might be a violation of the "no temporary buffer" constraint.

Testing

It looks like you tested this code in place in the main method.  It probably would have been better if you could have written this as unit tests.  As it is, each new test obliterates the old.


LeetCode: Pascal's Triangle C# https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/601/

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Please review for performance.

using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace RecurssionQuestions
{
    /// <summary>
    /// https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/601/
    /// </summary>
    [TestClass]
    public class PascalTriangleTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            IList<IList<int>> result = PascalTriangle.Generate(5);
            IList<IList<int>> expected = new List<IList<int>>();
            expected.Add(new List<int> { 1 });
            expected.Add(new List<int> { 1, 1 });
            expected.Add(new List<int> { 1, 2, 1 });
            expected.Add(new List<int> { 1, 3, 3, 1 });
            expected.Add(new List<int> { 1, 4, 6, 4, 1 });
            for (int i = 0; i < expected.Count; i++)
            {
               CollectionAssert.AreEqual(expected[i].ToList(), result[i].ToList());
            }
        }
    }

    public class PascalTriangle
    {
        public static IList<IList<int>> Generate(int numRows)
        {
            IList<IList<int>> result = new List<IList<int>>();
            if (numRows == 0)
            {
                return result;
            }
            List<int> row = new List<int>();
            row.Add(1);
            result.Add(row);
            if (numRows == 1)
            {
                return result;
            }

            for (int i = 1; i < numRows; i++)
            {
                var prevRow = result[i - 1];
                row = new List<int>();
                row.Add(1);
                for (int j = 0; j < prevRow.Count - 1; j++)
                {
                    row.Add(prevRow[j] + prevRow[j + 1]);
                }
                row.Add(1);
                result.Add(row);
            }
            return result;
        }
    }
}

Something I ran into while making my own implementation:

After 34 rows, the highest number in the row will be two 1166803110s. Adding these for row 35 exceeds the maximum value for ints, resulting in integer-overflow.

You might consider putting the line that does the addition into a checked block, so that an OverflowException is properly thrown:

for (int j = 0; j < prevRow.Count - 1; j++)
{
     checked
     {
         row.Add(prevRow[j] + prevRow[j + 1]);
     }
}

As mentioned in the comments, the values in the rows grow almost exponentially. This means that switching from int to long as datatype in the lists will only roughly double the amount of rows that can be supported before these too overflow.


What is better for the code segment, sockets or multiple processes? I am trying to fetch information out of SHOUTcast for mutiple users at the same time. Here is my current code:

<?php
    header("Access-Control-Allow-Origin:*");

    function failOut($http, $text) {
        header('HTTP/1.x ' . $http);
        die(htmlspecialchars($text));
    }

    $params = $_GET;
    $user = 'root'; // Change this to username
    $password = ''; // Put your password here. My home database doesn't have any password (is empty).

    $con = mysql_connect('localhost',$user,$password) or die('Could Not Connect..');

    $context = stream_context_create(
        array(
            'http' => array(
                //Required To fool ShoutCast or it will flood with the stream instead
                'user_agent' => "GET / HTTP/1.0\r\n"
                            ."Host:117.200.149.48\r\n"
                            ."User-Agent: Mozilla/5.0 (compatible; ShoutCastInfoClass/0.0.2; ".PHP_OS.")\r\n"
                            ."\r\n",
            ),
        )
    );

    if($params['act'] == 'st'){
        mysql_select_db('radio',$con);
        $count = mysql_query("select * from info where ID='".$params['id']."'")or die('Error In Query'.mysql_error());

        $content = null;
        $rows = mysql_num_rows($count);
        if( $rows > 0 ){
            $res = mysql_fetch_assoc($count);

            if($res['TIMESTAMP'] + 30 < time()){
                if($res['version'] == '1'){
                    $base = $res['IP'].'/admin.cgi?mode=viewxml&user=admin&pass='.$res['PASS'];
                    // Well i will change this crazy method with something non password secured pretty soon
                }else{
                    $base = $res['IP'].'/stats?sid=1';
                    // As per shoutcast v2 APIs !! :D
                }
                $content = file_get_contents($base, false, $context)or die("Unable to Load resourse");
                $dom = new DOMDocument();
                $dom->loadXML($content);
                $res['SERVERTITLE'] =  htmlspecialchars($dom->getElementsByTagName('SERVERTITLE')->item(0)->textContent);
                $res['SONGTITLE'] = htmlspecialchars( $dom->getElementsByTagName('SONGTITLE')->item(0)->textContent );
                $res['BITRATE'] = $dom->getElementsByTagName('BITRATE')->item(0)->textContent;
                $res['GENRE'] = $dom->getElementsByTagName('SERVERGENRE')->item(0)->textContent;
                $res['CONTENT'] = $dom->getElementsByTagName('CONTENT')->item(0)->textContent;

                if(strpos($res['CONTENT'],'mpeg')){
                    $res['CONTENT'] = 'MP3';
                }else if(strpos($res['CONTENT'],'aac')){
                    $res['CONTENT']= 'AAC';
                }else{
                    $res['CONTENT'] = 'OGG';
                }
                $query='update INFO SET SERVERTITLE="'.$res['SERVERTITLE'].
                '", SONGTITLE="'.$res['SONGTITLE'].
                '", BITRATE="'.$res['BITRATE'].
                '", GENRE="'.$res['GENRE'].
                '", CONTENT="'.$res['CONTENT'].
                '" , TIMESTAMP='.time().' where ID=\''.$params['id']. '\';';
                mysql_query($query,$con)or die(mysql_error());
                mysql_close($con);
            }
            unset( $res['IP'] );
            unset( $res['PASS'] );
            echo json_encode($res);
        }
    }else if($_params['act']== 's'){
        // To search for a specific keyword
        $queryString = $params['q'];
    }else if($_params['act'] == 'l'){
        // To feed list to the applet
        $cat = $params['c'];
        // Categories are various lists depending on genre languages etc...
    }
?>

I was wondering if making a phpSocket server would be better for this purpose as sockets will reduce the demand of required MySQL connections to be opened.

Or

Is my current method the best solution?

If you want to use this function you should have buffering:

function failOut($http, $text) {
    header('HTTP/1.x ' . $http);
    die(htmlspecialchars($text));
}

Otherwise it's possible that the script sends out some output (including error messages) and you can't send out any header later. (How do headers work with output buffering in PHP?) Anyway, I don't see any call to this function, so you might be able to remove it.

$con = mysql_connect('localhost',$user,$password) or die('Could Not Connect..');

As others already suggested you should use mysqli or PDO. Another note is that you might want to set the HTTP response code to 503 here to save your search engine ranking when the database is down.

$params = $_GET;
...
$count = mysql_query("select * from info where ID='".$params['id']."'")or die('Error In Query'.mysql_error());

As others already mentioned in comments it's not safe against SQL injections attacks. mysql_error() should not be the output of the script. Show only a generic error message and log the details to a server-side log file, don't help attackers. It would also be more user-friendly, most of the users doesn't care nor understand MySQL errors (or at least can't fix them). (How to log errors and warnings into a file?)

$dom->getElementsByTagName('BITRATE')->item(0)->textContent

This is in the code at least five times (with different tagname). You could create a function (whose parameter is the tagname) to remove the duplication.


Calculating mesh centers runs very slowly I have a piece of code that is used to calculate the cell centers in a rectangular mesh. The mesh size is pretty large (650 columns by 1150 rows). The code runs very slowly. I was wondering if I could employ any tricks to reduce the runtime.

In the example below, deltax is a 1D array of column spacings and deltay is a 1D array of row spacings. Maybe I need to do some sort of vectorization.

center_x = np.empty((nrow,ncol),dtype ='double')
center_y = np.empty((nrow,ncol),dtype ='double')
for i in range(nrow-1,-1,-1):
    if(i == nrow-1):
        center_y[i,:] = 0.5*deltay[nrow-1]
    else:
        center_y[i,:] = center_y[i+1,:] + 0.5*deltay[i+1] + 0.5*deltay[i]

for j in range(0,ncol):
    if(j ==0):
        center_x[:,j] = 0.5*deltax[0]
    else:
        center_x[:,j]= center_x[0,j-1] + 0.5*deltax[j-1] + 0.5*deltax[j]

There are two things I would try to change:

Is it necessary, that center_x and center_y are 2-dimensional arrays? In your code, the 2nd dimension holds redundant information and should be avoided.
The biggest problem with pure Python (but often the greatest benefit ;) ) is that it is an interpreted language and numerically heavy operations should be handled with library functions. In your case, I would try to exploit numpy's array features and calculate the center as

center_x = 0.5 * (delta_x[:ncol-1] + delta_x[1:])


PHP secure hash generator As I understand it, blowfish (actually eksblowfish, as it's used one way) is generally seen a secure hashing algorithm, even for enterprise use (correct me if I'm wrong). Because of this, I created functions to create and check secure password hashes using this algorithm, and using the (also deemed cryptographically secure) openssl_random_pseudo_bytes function to generate the salt.

<?php
/*
 * Generate a secure hash for a given password. The cost is passed
 * to the blowfish algorithm. Check the PHP manual page for crypt to
 * find more information about this setting. Returns null on failure.
 */
function generate_hash($password, $cost=11){
    /* To generate the salt, first generate enough random bytes. Because
     * base64 returns one character for each 6 bits, the we should generate
     * at least 22*6/8=16.5 bytes, so we generate 17. Then we get the first
     * 22 base64 characters
     */
    $salt=substr(base64_encode(openssl_random_pseudo_bytes(17,$secure)),0,22);
    /* If the random generation was not secure enough, do not continue
     */
    if(!$secure) return null;
    /* As blowfish takes a salt with the alphabet ./A-Za-z0-9 we have to
     * replace any '+' in the base64 string with '.'. We don't have to do
     * anything about the '=', as this only occurs when the b64 string is
     * padded, which is always after the first 22 characters.
     */
    $salt=str_replace("+",".",$salt);
    /* Next, create a string that will be passed to crypt, containing all
     * of the settings, separated by dollar signs
     */
    $param='$'.implode('$',array(
            "2y", //select the most secure version of blowfish (>=PHP 5.3.7)
            str_pad($cost,2,"0",STR_PAD_LEFT), //add the cost in two digits
            $salt //add the salt
    ));

    /* Now do the actual hashing
     */
    $hash=crypt($password,$param);
    if(strlen($hash)!=60) return null;
    return $hash;
}

/*
 * Check the password against a hash generated by the generate_hash
 * function.
 */
function validate_pw($password, $hash){
    /* Regenerating the with an available hash as the options parameter should
     * produce the same hash if the same password is passed.
     */
    return crypt($password, $hash)===$hash;
}
?>

I would have to agree with @EliasVanOotegem. Consider using password_hash() and password_verify(). All you've done is recreate something, which we know shouldn't be done.

Documentation for the former and latter.


Increasing size of video thumbnail on mouseover This is a user JavaScript for YouTube. The point is to make the thumbnail bigger on mouseover. I just want some help making it better because I don't want it to waste resources with all the extensions I have and other scrips. I also added Iframes because I have another extension that makes a preview of the video in the thumbnail. I also use Opera so make sure it works on Opera.

/*! settings begin */
//Makes the name of the video apear bellow the image if false (false/true)
var WideSideBar = true;
/*! settings end */

//Get the sidebar were the thumbnails are and the main
var videos = document.getElementById("watch7-sidebar");
var main = document.getElementById("watch7-main");
//Make the SideBar wider
if (WideSideBar) {
    main.style.width = "1117px";
    videos.style.width = "472px";
}

videos.addEventListener("mouseover", function (a) {
    if (a.target.tagName == "IMG") {
        //Make image bigger
        a.target.style.width = "292px";
        a.target.style.height = "163px";
        a.target.style.WebkitTransition = 'width 0.5s, height 0.5s';
        a.target.parentNode.parentNode.parentNode.style.width = "292px";
        a.target.parentNode.parentNode.parentNode.style.height = "163px";
        a.target.parentNode.parentNode.parentNode.style.WebkitTransition = 'width 0.5s, height 0.5s';

        //Get a higher resolution image of the thumbnail
        var video_id = a.target.parentNode.parentNode.parentNode.parentNode.parentNode.href.split('v=')[1];
        var ampersandPosition = video_id.indexOf('&');
        if (ampersandPosition != -1) {
            video_id = video_id.substring(0, ampersandPosition);
        }
        a.target.src = "http://img.youtube.com/vi/" + video_id + "/0.jpg";

    } else if (a.target.tagName == "IFRAME") {

        //Make Iframe AKA:(Thumbnail preview) bigger
        a.target.parentNode.style.WebkitTransition = 'width 0.5s, height 0.5s';
        a.target.parentNode.style.width = "292px";
        a.target.parentNode.style.height = "163px";
    }
}, false);

videos.addEventListener("mouseout", function (a) {
    if (a.target.tagName == "IMG") {

        //Make image normal size.
        a.target.style.width = "120px";
        a.target.style.height = "67px";
        a.target.parentNode.parentNode.parentNode.style.width = "120px";
        a.target.parentNode.parentNode.parentNode.style.height = "67px";
    } else if (a.target.tagName == "IFRAME") {
        //Make Iframe AKA:(Thumbnail preview) normal size
        a.target.parentNode.style.width = "120px";
        a.target.parentNode.style.height = "67px";
    }
}, false);

Why not use the :hover pseudo class and have that trigger the size change? Probably easier than having to worry about event binding.
http://jsfiddle.net/nhzNM/

<iframe class="videoPlayer" width="560" height="315" src="http://www.youtube.com/embed/90Omh7_I8vI?controls=0&rel=0" frameborder="0" allowfullscreen></iframe>
<style type="text/css">
.videoPlayer {
    width: 560px;
    height: 315px;
    -webkit-transition: height,width 1s ease;
    -moz-transition: height,width 1s ease;
    -ms-transition: height,width 1s ease;
    -o-transition: height,width 1s ease;
    transition: height,width 1s ease;
}

.videoPlayer:hover {
    width: 650px;
    height: 365px;
}
</style>

You could use the same setup for a thumbnail positioned in front of the video embed.


Getting data from database and then outputing it to the DataGridView I am at the point where I feel that I am not doing it right. It works and does the job, but I am sure that there are more efficient and smarter ways of doing it.

I would like to see if there is a way of making it more efficient, clear, and easier to use.

This is my query getter:

    public DataTable querySQL_DT_Return(String query)
    {
        var form = Form.ActiveForm as Form1;
        DataTable RETURNME = null;
        OleDbConnection conn = new OleDbConnection(cnStr);

        try
        {
            try
            {
                conn.Open();
            }
            catch
            {
                MessageBox.Show("Can't connect to the database!");
            }

            OleDbDataAdapter Data1 = null;

            try
            {
                Data1 = new OleDbDataAdapter(query, conn);
            }
            catch
            {
                MessageBox.Show("Can't open the connection to the DB, please try again!");
                return RETURNME;
            }

            DataSet a = new DataSet();
            Data1.Fill(a);

            DataTable dt = a.Tables[0];
            //Adding data to the columns
            RETURNME = dt;
        }

        catch
        {
            //MessageBox.Show("Having issues retrieving data from Database, please try again!");
            // return RETURNME;
        }
        finally
        {
            if (conn.State.ToString() == "Open")
            {
                conn.Close();
            }
        }

        if (conn.State.ToString() == "Open")
        {

            conn.Close();
        }
        return RETURNME;
    }

When I receive the DataTable, I just loop through it getting records.

Even if you are stuck with the old/wrong technology (all the cool kids use ORMs these days), you can still dance around that and simplify the act of interfacing with it with clean code of your own. I like having a direct link to the database because I can do whatever the hell I want with it. If the author of an ORM library and I had different goals and priorities, then this library will actually hinder my productivity. Disclaimer: I have little experience with ORMs.

Anyhow, try using lots of smaller functions.
Try passing everything a method needs in - that way you can move this code into a separate class.
Use exception handling to signal that something went wrong. Do not use the MessageBox / return null combination. You might be running this code as a windows service where showing Message Boxes is not allowed. It also does not feel right. The error handling / display effort needs to be well thought out, not copy /pasted into every method.
Features are assets; code is liability, hence less code is more.
Try using descriptive variable/method/etc. names.

public DataTable RunQueryExpectOneTable(
    string queryText,
    string[] expectedColumnNames = null)
{
    return RunQueryExpectOneTable(
    connectionString: this.ConnectionString,
    queryText: queryText,
    expectedColumnNames: expectedColumnNames);
}

public static DataTable RunQueryExpectOneTable(
    string connectionString,
    string queryText,
    string[] expectedColumnNames = null)
{
    // Even the body of this using method is too long, it can be further split up into methods.
    using(var connection = new OleDbConnection(connectionString))
    {
        // Opens it and makes sure that it is open.
        this.OpenAndCheckConnection();
        var adapter = new OleDbDataAdapter(query, conn);
        DataSet ds = new DataSet();
        adapter.Fill(ds);

        // if more than one table, then throw an exception.
        if (expectedColumnNames != null)
        {
            // Also check the number and the names of the columns
        }

        return ds.Tables[0];
    }
}


Reduce the code in a WHERE clause without using dynamic SQL How can I write the following T-SQL query part in a shorter way without using dynamic SQL?

WHERE
    ( (@Max IS NULL OR @Type <> 'Products')
        OR (@Max IS NOT NULL AND @Type = 'Products'
            AND ProductCount >  @Max ) )

    AND ( (@Min IS NULL OR @Type <> 'Products')
        OR (@Min IS NOT NULL AND @Type = 'Products'
            AND ProductCount <  @Min ) )

    AND ( (@Max IS NULL OR @Type <> 'Vendors')
        OR (@Max IS NOT NULL AND @Type = 'Vendors'
            AND VendorCount >  @Max ) )

    AND ( (@Min IS NULL OR @Type <> 'Vendors' )
        OR (@Min IS NOT NULL AND @Type = 'Vendors'
            AND VendorCount <  @Min ) )

    AND ( (@Max IS NULL OR @Type <> 'Order')
        OR (@Max IS NOT NULL AND @Type = 'Order'
            AND OrderCount >  @Max ) )

    AND ( (@Min IS NULL OR @Type <> 'Order')
        OR (@Min IS NOT NULL AND @Type = 'Order'
            AND OrderCount <  @Min ) )

You will have to test this carefully, but the following query should work:

WHERE
(
  @Max IS NULL
  OR @Type = 'Products' AND ProductCount > @Max
  OR @Type = 'Vendors'  AND VendorCount  > @Max
  OR @Type = 'Order'    AND OrderCount   > @Max
)
AND
(
  @Min IS NULL
  OR @Type = 'Products' AND ProductCount < @Min
  OR @Type = 'Vendors'  AND VendorCount  < @Min
  OR @Type = 'Order'    AND OrderCount   < @Min
)


Printing out a table in console This program prints out a table in the console. Suggestions for improvements are welcome.

Example output

Name             Sex      Age
Klaus Ulbrecht   male     12
Dieter           male     14
Ursula           female   16

You can test and modify the program here.

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

class Main {
  private static List<List<String>> table;

  public static void main(String[] args) {
    initTable();
    int spacing = 3;
    printTable(spacing);
  }

  private static void initTable() {
    List<String> row1 = Arrays.asList("Name", "Klaus Ulbrecht", "Dieter", "Ursula");
    List<String> row2 = Arrays.asList("Sex", "male", "male", "female");
    List<String> row3 = Arrays.asList("Age", "12", "14", "16");
    table = Arrays.asList(row1, row2, row3);
  }

  private static void printTable(int spacing) {
    List<Integer> maxLengths = findMaxLengths();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < table.get(0).size(); i++) {
      for (int j = 0; j < table.size(); j++) {
        String currentValue = table.get(j).get(i);
        sb.append(currentValue);
        for (int k = 0; k < (maxLengths.get(j) - currentValue.length() + spacing); k++) {
          sb.append(' ');
        }
      }
      sb.append('\n');
    }

    System.out.println(sb);
  }

  private static List<Integer> findMaxLengths() {
    List<Integer> maxLengths = new ArrayList<>();
    for (List<String> row : table) {
      int maxLength = 0;
      for (String value : row) {
        if (value.length() > maxLength) {
          maxLength = value.length();
        }
      }
      maxLengths.add(maxLength);
    }
    return maxLengths;
  }
}

Hello and thank your for your code. I dont' know what kind of improvements you want but from an Object Oriented perspective I see some improvements.

The first one is to get rid of all the static methods and fields. You can easily move all your methods to an AsciiTable class with a print(OutputStream out):void method.

You can also use arrays instead of list and split the single argument to one for the columns titles and another for the content. This will clarify the initiliazation of your table.

Table table = new Table(
    new String[]{"Name", "Sex", "Age"},
    new Object[][]{
            {"Klaus Ulbrecht", "male", 12},
            {"Dieter", "male", 14},
            {"Ursula", "female", 16}
        });

As you can see I changed the order so that the cognitive load is reduced, by
looking at the declaration we alrdeay have an idea of what are the titles and the content. We read for top to bottom, so it is more easier to have a declaration that already looks like that. This avoid your brain to switch the representation.

Another improvement that you can do is apply the separation of concerns principle by moving the "printing" away of the table. This is done easily with the builder where your Table is a director that drive a Format.

With this pattern you should be able to add another representation without changing the Table.

interface Format {
    void startHeader();
    void endHeader();

    void startBody();
    void endBody();

    void startRow();
    void endRow();

    void addColumn(Object value);
}

Format console = new Ascii(System.out, "   ");
table.writeTo(console);

Now that your model (Table) is separated from the view (Format) you may discover that the model is quite simple and exists mainly to drive the view as the director in the builder pattern. But you can add new methods to filter or sort your table.

Table table = new Table(
    new String[]{"Name", "Sex", "Age"},
    new Object[][]{
            {"Klaus Ulbrecht", "male", 12},
            {"Dieter", "male", 14},
            {"Ursula", "female", 16}
    });
table.filter(1, "male"::equalsIgnoreCase)
     .sort(2, Comparator.naturalOrder())
     .writeTo(console);

Name             Sex    Age
Klaus Ulbrecht   male   12
Dieter           male   14

If you don't want to migrate to the object oriented way you can still improve the robustness of your code by dealing with empty columns or rows.

[1] Single Responsibility Priniciple is part of the S.O.L.I.D. acronym. https://en.wikipedia.org/wiki/SOLID

[2] When I speak about the builder pattern I refer to the creational pattern. Not the "fluent way of writing". https://en.wikipedia.org/wiki/Builder_pattern


std::string/std::wstring template wrapper for Win32 API I have not completed this but want to make my own template library for wrapping the Win32 API to make it compatible with std::string/std::wstring... Here's a sample of what I've worked with so far.

My questions are:

Is this a good idea?
Is it acceptable to undefine Windows API macros (e.g. #undef GetWindowText)?
Is there perhaps a better way to do this besides changing the name scheme (e.g. getWindowText or GetWindowString as opposded to GetWindowText)? I prefer not to change the names.

Note: Please don't provide answers like "why don't you just use WTL?" or "just use MFC". I prefer to deal directly with the Windows API; I just want to make it easier to work with std::basic_string.

Implementation

#ifdef _WINUSER_
#undef GetWindowTextLength
template<typename _T> int GetWindowTextLength(HWND hWnd);
template<> int GetWindowTextLength<wchar_t>(HWND hWnd) { return ::GetWindowTextLengthW(hWnd); }
template<> int GetWindowTextLength<char>(HWND hWnd) { return ::GetWindowTextLengthA(hWnd); }

#undef GetWindowText
template<typename _T> std::basic_string<_T> GetWindowText(HWND hWnd);
template<> std::basic_string<wchar_t> GetWindowText(HWND hWnd)
{
    std::size_t len = GetWindowTextLength<wchar_t>(hWnd)+1;
    std::vector<wchar_t> buffer(len);
    ::GetWindowTextW(hWnd, buffer.data(), len);
    return std::basic_string<wchar_t>(buffer.begin(), buffer.end());
}
template<> std::basic_string<char> GetWindowText(HWND hWnd)
{
    std::size_t len = GetWindowTextLength<char>(hWnd)+1;
    std::vector<char> buffer(len);
    ::GetWindowTextA(hWnd, buffer.data(), len);
    return std::basic_string<char>(buffer.begin(), buffer.end());
}
#endif//_WINUSER_

Example Usage

std::basic_string<TCHAR> text = GetWindowText(hWnd);

I have not completed this but want to make my own template library for wrapping the Win32 API to make it compatible with std::string/std::wstring...
Is this a good idea?

If you have the time to do that as an exercise, probably (there should be a lot of effort involved).
If you want to create a library for future use with an intentional name clash, probably no.

Is it acceptable to undefine Windows API macros (e.g. #undef GetWindowText)?

Not really. If you are careful about it, you can make it work, but these macros can change, their implementation can change depending on where MS wants to take their API in the future and what is behind them may change. You are better off writing your library so that there are no name clashes with MS's macro names.

Is there perhaps a better way to do this besides changing the name scheme (e.g. getWindowText or GetWindowString as opposded to GetWindowText)? I prefer not to change the names.

No. You are better off using new names. Seeing the old names in code would make me (as a client of your lib) assume they have the same semantics, parameters and behavior as the WinAPI defines (macros and all). I would assume the names belong to WinAPI and look automatically to MSDN documentation if I had questions (as in, not in your library's documentation).
Using the same name would create confusion for other people using your code, for you as a developer (consider what happens when you have an error due to a macro name accidentally included where you define your API: you'd have errors caused by name clash in macro expansion, when you don't want the macro defined. For you it would be (almost) easy to fix, as you know the problem. Consider what happens though, when a client of your code writes:
#include <yourcode.h> // undefines macros and defines your interface
#include <windows.h>  // redefines macros and causes errors

This is an error that is easy to make for client code (especially for someone not familiar with the implementation details/constraints of your library) and it is something that you cannot enforce in your library code (you actually could, if you issue #error directives in your includes but that is as brittle as the whole concept - MS changes some implementation details and you have to update your code).
Also consider that your library would have to be complete from the start - if you only implement wrappers for what you need and discover you need a new API, you'd have to define a wrapper to use it - you will be unable to simply include the WinAPI headers and using it from there (as doing so would cause macro expansion clashes).

I prefer to deal directly with the Windows API; I just want to make it easier to work with std::basic_string.

Nothing is stopping you from wrapping the calls. Just don't undefine WinAPI function access macros and replace them with functions (using undefined macro names). You'd introduce a naming/include limitation in client code that would be hard to get around to in specific cases, and would only work with ugly workarounds in client code or by requiring modifications to your library).


GameState Management efficiency So I've read numerous tutorials on handling game states in XNA, and to each tutorial I've been read, it was different from the others. Now I want to ask which way is more efficient? I've created my own ScreenManager and what not, but it wasn't satisfying to me because it was inefficient since I didn't unload any unused content.

My question is: What is an efficient way to manage your screens and its content? Is using an enum fine? Or...?

Here's my current code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Menu
{
    public class ScreenManager
    {
        // Variables
        List<GameScreen> gameScreens = new List<GameScreen>();

        // Constructors
        public ScreenManager()
        {
            gameScreens.Add(new Splashscreen());
            gameScreens.Add(new Mainscreen());
            gameScreens.Add(new Playscreen());
            gameScreens.Add(new Pausescreen());
        }

        // Public Properties
        public List<GameScreen> Screens
        {
            get { return gameScreens; }
            set { gameScreens = value; }
        }

        // Public Methods
        public void Add(GameScreen screen)
        {
            gameScreens.Add(screen);
        }

        public void LoadContent(ContentManager Content)
        {
            foreach (GameScreen screen in gameScreens)
            {
                screen.LoadContent(Content);
            }
        }

        public void Update(GameTime gameTime)
        {
            foreach (GameScreen screen in gameScreens)
            {
                screen.Update(gameTime);
            }
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            switch (ScreenState.Instance.CurrentState)
            {
                case State.Splashscreen:
                    gameScreens[0].Draw(spriteBatch);
                    break;
                case State.Menu:
                    gameScreens[1].Draw(spriteBatch);
                    break;
                case State.Play:
                    gameScreens[2].Draw(spriteBatch);
                    break;
                case State.Pause:
                    gameScreens[3].Draw(spriteBatch);
                    break;
            }
        }
    }
}

I can't be sure of this (I need to foster my XNA knowledge), but I would probably derive that class from DrawableGameComponent so that the Update and Draw methods would be overrides (not just methods that happen to be named "Update" and "Draw"), but deriving from that class might have other consequences that I'm not aware of; again, my XNA is fairly basic - it just seems natural to me for a class that has Update and a Draw methods, to derive from DrawableGameComponent: these method names are not an accident.
Update
Your Update() method is looping through each GameScreen and calling Update() on them all:

foreach (GameScreen screen in gameScreens)
{
    screen.Update(gameTime);
}

I think doing this incurs non-necessary processing: why would you bother updating the splash screen and pause screen at every single iteration? You're wasting cycles here.
Draw
Your Draw() method is more selective:

public void Draw(SpriteBatch spriteBatch)
{
    switch (ScreenState.Instance.CurrentState)
    {
        case State.Splashscreen:
            gameScreens[0].Draw(spriteBatch);
            break;
        case State.Menu:
            gameScreens[1].Draw(spriteBatch);
            break;
        case State.Play:
            gameScreens[2].Draw(spriteBatch);
            break;
        case State.Pause:
            gameScreens[3].Draw(spriteBatch);
            break;
    }
}

I like that you're using an enum here, but I don't like that you've hard-coded the gameScreens indices. Let's see.. you're storing the screens in a List, here:

List<GameScreen> gameScreens = new List<GameScreen>();

public ScreenManager()
{
    gameScreens.Add(new Splashscreen());
    gameScreens.Add(new Mainscreen());
    gameScreens.Add(new Playscreen());
    gameScreens.Add(new Pausescreen());
}

Allow me to open a nitpicking parenthesis here:

Nitpick
Instead of List<GameScreen> gameScreens = new List<GameScreen>(); and then adding the screens in the list at construction, I would have used an interface here, and initialized everything in a single statement:
private readonly IList<GameScreen> _gameScreens;

public ScreenManager()
{
    _gameScreens = new List<GameScreen>
                           {
                               new SplashScreen(),
                               new MainScreen(),
                               new PlayScreen(),
                               new PauseScreen()
                           };
}

This allows the _gameScreens private field to be readonly, which prevents the list's reference to be tampered with.

The mechanics work, but could work better if you leveraged IDictionary and turned List<GameScreen> gameScreens into a IDictionary<State, Action<SpriteBatch>>:
private readonly IDictionary<State, Action<SpriteBatch>> _gameScreenRenderer;
private readonly GameScreen _splashScreen = new SplashScreen();
private readonly GameScreen _mainScreen = new MainScreen();
private readonly GameScreen _playScreen = new PlayScreen();
private readonly GameScreen _pauseScreen = new PauseScreen();

public ScreenManager()
{
    _gameScreenRenderer = new Dictionary<State, Action<SpriteBatch>>
                            {
                                { State.SplashScreen, sb => _splashScreen.Draw(sb) },
                                { State.MainScreen, sb => _mainScreen.Draw(sb) },
                                { State.PlayScreen, sb => _playScreen.Draw(sb) },
                                { State.PauseScreen, sb => _pauseScreen.Draw(sb) }
                            };
}

An Action<SpriteBatch> is a delegate that points to any method that returns void and takes a SpriteBatch parameter; here the method is anonymous.
Each GameScreen becomes a field of the ScreenManager class, there's no need to have them in a list of any kind. Doing this turns your Draw implementation into something like this:
private void Draw(SpriteBatch spriteBatch)
{
    _gameScreenRenderer[ScreenState.Instance.CurrentState](spriteBatch);
}

Implement a similar mechanism for your Update method and you'll only be updating and rendering the screen for your CurrentState.


Shell command for the normal program termination of Skype from the command line Would the following be the right way to do it in your opinion? Can you suggest a better alternative or, if not, is there something that can be done to make the existing version better?

ps -e | grep skype | cut -d" " -f1 | xargs kill -s term

As the comments have pointed out, there exist tools to match processes by name. This is roughly equivalent (better than) what you're trying to do:

pkill skype

It's better because:

It's shorter and cleaner
It won't kill itself

By the second point I mean that ps -e | grep skype will match the grep process itself too. That won't happen when using pkill.

Code review

If we wanted to imitate pkill, I would suggest writing like this:

ps -e | awk '/[s]kype/ { print $1 }' | xargs kill

That is:

Replace two processes with one (grep + cut with awk)
Use [s]kype instead of skype is a common trick to make the awk itself not match
Drop -s term from kill, as TERM is the default signal anyway


Algorithm for shifting data I was bored and sketched out this idea in pseudocode( I will try to turn it into C++ later) for taking a set of numeric data and manipulating it. I ran through it manually and it seems to put the data in a range [0, something]

count =
data[count] = { d_0, d_1, … , d_(count -1) }
sigma = $Σ_{a∈ℕ} data_a$
avg = sum / count

newData[count] = {}

for x in data
  append (x · avg)/count to newData

What I am curious about, is if this "doodle" has any potential uses, or if it can be extended somehow?

Your computer will get bored, too, dividing (over?) by count over and again. Use
avg_count = sum / count / count - or
scale = something / sum


Flask app to return close prices & average I've been working on a little challenge in order to learn more.. I've written the following code, which works. I'm just concerned that there are several areas where my lack of in depth Python knowledge has forced me to 'go the long way around'. I'm really keep to learn more and learn in the correct way, so looking for areas I can improve the code & also shorten it where possible.
The idea is, we use a free API to obtain some JSON data containing a list of dates and stock price information. The JSON gives a 'refreshed date' which is the latest date the data has been obtained, I'm then calculating a list of N dates PRIOR to this date, and returning the stock close price for each of those past days, and then returning the average of those prices.
The code works, and I'm quite happy of that.. but I don't want to stop here. I want to make sure I'm learning the right way.
Since the stock market is closed on Sat/Sun, we need to avoid weekends when calculating the list of dates, so N=3 on a Monday, would be 3 'stock market' days prior to Monday, thus - Mon, Fri, Thu.
For anyone who is interested in looking at the format of data being read in there's a demo API key: https://www.alphavantage.co/query?apikey=demo&function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT
CODE:
from datetime import date, timedelta, datetime
import json
from requests import Request, Session
from flask import Flask, make_response

app = Flask(__name__)

# To be passed in with ENV-Vars
SYMBOL='MSFT'
NDAYS = 3

api_key = 'apikey="XXXXXXXX"&'
function = 'function=TIME_SERIES_DAILY_ADJUSTED&'
symbol = f'symbol={SYMBOL}'
url = f'https://www.alphavantage.co/query?{api_key}{function}{symbol}'

session = Session()
output = session.get(url)
data = json.loads(output.text)

refreshed = datetime.strptime(str(data['Meta Data']['3. Last Refreshed']), '%Y-%m-%d').date()
dates = []
output = {}
def prev_days(rdate):
    rdate -= timedelta(days=NDAYS)
    while rdate.weekday() > 4:
        rdate -= timedelta(days=1)
    return rdate

past_date = prev_days(refreshed)

delta = refreshed - past_date
for i in range(delta.days + 1):
    dates.append(refreshed - timedelta(days=i))

for date in dates:
    close = data['Time Series (Daily)'][str(date)]['4. close']
    output.update({str(date): float(close)})

avg = sum(list(output.values())) / len(list(output.values()))

def resp():
    return f'{SYMBOL} data={list(output.values())}, average={avg}'

@app.route('/')
def main():
    response = make_response(resp(), 200)
    response.mimetype = "text/plain"
    return response

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

Relays
Your current design:

fetches data from alphavantage once, on startup
offers it to anyone who hits any of your interfaces on port 5000 (which, by the way, is already used by a large number of services other than the default Flask development webserver)

This seems unusual. Perhaps it's just to try out a random use of Flask for learning purposes, which is fine, but:
If you really want to preserve this API as an effective relay, it should probably be authenticated. You can add that here, or in a frontend (nginx, etc). Also, just bind to 80 once you hit production. A frontend can do HTTPS termination effectively translating from 443 to 80.
If all you want is code to conveniently get alphavantage data, don't make your own HTTP API; just make a requests wrapper library.
Globals

To be passed in with ENV-Vars

should apply to api_key, as that's a secret that should not be hard-coded.
Also, it's an odd choice to hard-code symbol. With very little introduced complexity, you can make your code parametric on symbol (and perhaps also function).
Otherwise: session, output, data, etc. probably shouldn't be globals. Consider making an LRU cache for data, and taking advantage of Flask's before_first_request, and moving the great majority of your global code into functions.
For session in particular, there's currently no advantage to having that - you might as well just requests.get since you only do it once.
Request formation
Don't pre-format key-value query parameter pairs. Instead,
session.get(
    'https://www.alphavantage.co/query',
    params={
        'apikey': API_KEY,
        'function': 'TIME_SERIES_DAILY_ADJUSTED',
        'symbol': 'MSFT',
    },
)

Response parsing
json.loads(output.text)

is unnecessary. Just use output.json. Also, between get() and .json, call output.raise_for_status. This will increase the quality of error information when something goes wrong.
Sum over an iterable
sum(list(output.values()))

should not use list. sum can operate on any iterable.


Attaching both mouseenter and mouseleave event handlers using jQuery I'm a newbie to javascript, and day after day, I try to write better code with jQuery.

For example, I wrote this code earlier:

$$foo= $(".foo");

$$foo.mouseenter(function() {
    $(this).find('h1').addClass("hover");
});

$$foo.mouseleave(function() {
    $("h1").removeClass("hover");
});

What I want to happen with this code is when the mouse enters .foo the h1 gets a new background color or any style applying on class, hover.

Another example:

$$foo= $(".foo");

$$foo.mouseenter(function() {
    $(this).find('h1').addClass("hover");
    $(this).find('input').focus();
});

$$foo.mouseleave(function() {
    $("h1").removeClass("hover");
    $(".foo input").val('');
});

What I want to happen here is when the mouse enters .foo the input gets focus, and when mouse out the input's values are removed.

Both cases are working perfect, but I want to know if there is a better way to do this (mouse enter and mouse out)?

First of all you can use jQuery hover and passing 2 functions (mouseenter, mouseleave)
and u can shorten it also with jQuery end

$('.foo').hover(
    function () {
        $(this).find('h1').addClass("hover").end().find('input').focus();
    },
    function () {
        $(this).find('h1').removeClass("hover").end().find('input').val('');
    }
);


Random string generator that 'guesses' user inputted word This takes a user inputted string, then tries to randomly 'guess' it. The problem is that whenever the input's length is 6 digits or more, it takes an incredibly long time to process it. Is there a more efficient way of doing this?

import random as rand
import string

def main(word):
    len_word = len(word)
    ntries = 0
    while True:
        letters = []
        for i in range(len_word):
            letters.append(rand.choice(string.ascii_lowercase))

        ntries += 1
        b = ''.join(letters)

        if b==word:
            print('Mission accomplished. It took ' + str(ntries) + ' tries.')
            break

if __name__ == '__main__':
    main(input('input a word: '))

Note: I have tried making the program guess the letters one by one, and then check if said letter was right, but it seemed to make the problem even worse.

Docstrings

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition.

def guess_word():
    """Do calculations and return correct guessed word."""

Style

check pep0008 https://www.python.org/dev/peps/pep-0008/ the official Python style guide and here are some comments:

import string

def main(word):

Surround top-level function and class definitions with two blank lines.

ntries = 0
if b==word:

Use descriptive variable names, improves readability and general
understanding of the code.
Always surround these binary operators with a single space on either
side: assignment (=), augmented assignment (+=, -= etc.), comparisons
(==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and,
or, not). Except when = is used to set a function parameter.

The code

len_word

len_word = len(word)
ntries = 0
while True:
    letters = []
    for i in range(len_word):

the variable len_word is unnecessary, can be expressed:

while True:
    letters = []
    for i in range(len(word)):

Random brute forcing:

a sample size of 6 out of 26 alphabets has 230230 possible combinations (where order is unimportant and each combination has n! re-orderings where n = combination length (letters in the word) what is very obvious is that with such algorithms, it is very likely that zombie dinosaurs start showing up before the code guesses the correct word (10 years to be able to guess a 10 letter word for 500,000 secret words/passwords examined per second). So if what you are trying to build is a password cracker, the algorithms that are better than brute forcing are beyond the scope of this review.

What your mini-program does is trying n digit random choices and comparing them to the secret word which number of trials is variable

input a word: red
Mission accomplished. It took 8428 tries.

input a word: red
Mission accomplished. It took 16894 tries.

and since it's a random choice(not entirely random because it's based on a so-called 'pseudo-random' algorithm, you might generate the same number of trials for a random.seed(n)) this is not the case however, it tries different possibilities, so with some bad luck, that with some word lengths might keep running until aliens start making documentaries about us.

Assuming we can check each character separately:

(** This is not the case of password crackers in the real world which must guess the exact word).

# Note: I have tried making the program guess the letters one by one, and then
# check if said letter was right, but it seemed to make the problem even worse.

and since you asked about separate letter comparison:

import string

def guess_word():
    """Match characters with user input and return number of iterations, correct guess."""
    possible = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation + ' '
    secret_word = input('Enter word: ')
    yield len(possible) * len(secret_word)
    for index in range(len(secret_word)):
        for char in possible:
            if secret_word[index] == char:
                yield char

if __name__ == '__main__':
    word = list(guess_word())
    print(f"Total: {word[0]} iterations.\nWord: {''.join(word[1:])}")


Parse HTTP header using Python and tcpflow I wrote a program that reads a pcap file and parses the HTTP traffic in the pcap to generate a dictionary that contains HTTP headers for each request and response in this pcap.

My code does the following:

Uses tcpflow to reassemble the tcp segments
Read the files generated by tcpflow and check if it related to HTTP
If the file contains HTTP traffic, my code will read the file and generate a corresponding dictionary that contains the HTTP header fields.

I test my code with multiple test cases, but honestly I don't have a good experience in Python, so could anyone check it for me please?

import os
from os import listdir
from os.path import isfile, join
from StringIO import StringIO
import mimetools
def getFields(headers):
    fields={}
    i=1
    for header in headers:
        if len(header)==0:
           continue

        # if this line is complement for the previous line
        if header.find(" ")==0 or
           header.find("\t")==0:
           continue

        if len(header.split(":"))>=2:
           key = header.split(":")[0].strip()

           # if the key has multiple values such as cookie
           if fields.has_key(key):
              fields[key]=fields[key]+" "+header[header.find(":")+1:].strip()
           else:
              fields[key]=header[header.find(":")+1:].strip()

              while headers[i].find(" ")==0 or
                    headers[i].find("\t")==0 :
                    fields[key]=fields[key]+" "+headers[i].strip()
                    i=i+1
              # end of the while loop
          # end of the else

        else:
             # else for [if len(header.split(":"))>=2: ]
             print "ERROR: RFC VIOLATION"

      # end of the for loop
    return fields

def main():
    # you have to write it in the terminal "cd /home/user/Desktop/empty-dir"
    os.system("tcpflow -r /home/user/Desktop/12.pcap -v")

    for f in listdir("/home/user/Desktop/empty-dir"):
        if f.find("80")==19 or f.find("80")==41:
           with open("/home/user/Desktop/empty-dir"+f) as fh:
                fields={}
                content=fh.read()  #to test you could replace it with content="any    custom http header"
                if content.find("\r\n\r\n")==-1:
                   print "ERROR: RFC VIOLATION"
                   return
                headerSection=content.split("\r\n\r\n")[0]
                headerLines=headerSection.split("\r\n")
                firstLine=headerLines[0]
                firstLineFields=firstLine.split(" ")
                if len(headerLines)>1:
                   fields=getFields(headerLines[1:])
                if len(firstLineFields)>=3:
                   if firstLine.find("HTTP")==0:
                      fields["Version"]=firstLineFields[0]
                      fields["Status-code"]=firstLineFields[1]
                      fields["Status-desc"]=" ".join(firstLineFields[2:])
                   else:
                      fields["Method"]=firstLineFields[0]
                      fields["URL"]=firstLineFields[1]
                      fields["Version"]=firstLineFields[2]
                else:
                  print "ERROR: RFC VIOLATION"
                  continue
                print fields
                print "__________________"

    return 0

if __name__ == '__main__':
 main()

New Lines and indentations help the interpreter know where the code terminates and blocks end, you have to be super careful with them

Like in your if condition, you can't have a newline in between the conditions.

if header.find(" ")==0 or
    header.find("\t")==0:
    continue

This code will error out because you can't have a new line in your condition statement.

Python is New Line Terminated.  It should read like this

if header.find(" ")==0 or header.find("\t")==0
    continue

Same with this piece of code

while headers[i].find(" ")==0 or
    headers[i].find("\t")==0 :
    fields[key]=fields[key]+" "+headers[i].strip()
    i=i+1

It should read:

while headers[i].find(" ")==0 or headers[i].find("\t")==0 :
    fields[key]=fields[key]+" "+headers[i].strip()
    i=i+1


Make a list's elements consecutive by an integer n Write a method makeConsecutiveByN that could be added to the
  ArrayIntList class that takes an integer n as a parameter, removes any
  list element that does not differ from the previous element by exactly
  n. For example, both 8 and 2 differ from 5 by exactly 3. Your method
  should return true if the list was changed and false if not. For
  example, suppose elementData stores the following element values: [1,
  3, -6, 1]. We need to compare every set of pairs. If we remove an
  element we need to compare the next element in the list to the last
  non-removed element. If n were 2 and we made a call on the previous
  list we would compare 1 and 3, keep 3 and then compare 3 and -6. We
  would discard -6 and so then compare 3 and the last 1. Our call would
  return true. You may not use any other arrays, lists, or other data
  structures to help you solve this problem, though you can create as
  many simple variables as you like.

I'm looking for better/other ways to write this code. I noticed that I wasn't able to iterate from the right-to-left because this problem depends on the direction of traversal. With that in mind, are there other ways I can think about solving this problem? Also looking for general feedback to cleaning up my code for the future. It is also worth noting that this is code that would be added to a custom ArrayIntList class.

public boolean makeConsecutiveByN(int n) {
    boolean isChanged = false;
    for (int i = 0; i + 1 < size; i++) {
        if (Math.abs(elementData[i] - elementData[i + 1]) != n) {
            remove(i + 1);
            i--;
            isChanged = true;
        }

    }
    return isChanged;
}

remove() is most likely linear. If so, the entire method has a quadratic time complexity. However there is a linear algorithm, which does not rely on remove():

    int kept = 0;
    int unknown = 1;
    while (unknown < size) {
        if (Math.abs(data[kept] - data[unknown]) == n) {
            data[++kept] = data[unknown];
        }
        unknown++;
    }
    erase(kept + 1, size);  // or whatever method you have to delete the tail of the array
    return unknown - kept > 1;

A perk benefit of this approach is that you don't need to reassign isChanged every time an element is removed.


C code to parse out certain characters in a string I have the following code

int eval(char* string) {

char* token;

outputString[0] = NULL;

token = strtok(string, " ");

while(token != NULL){

   if(strstr((char *) token, "@") != NULL) {
      strcat(outputString, "@");
      token = calc(token);
   }
   strcat(outputString, token);
   strcat(outputString, " ");
   token = strtok(NULL, " ");
}

 printf("%s\n", outputString);

}

It is called on a string that looks like this

The water has @TREE and @SKY in it.

This code works completely fine. However I want to make it more efficient.

The code is supposed to do the following --

Cut the string up by spaces, however, if an @ is found, it should be sent away to be evaluated by calc();. If none are found, we continue splitting the string by spaces until one is actually found. While we are running through, we concatenate it onto outputString and continue forward.

outputString doesn't have enough room to accomodate the results. It can hold just one byte. It is just unlucky coincidence that the code does not segfault. In any case, undefined behaviour.

If the intention is just to print the result out, you don't need outputString at all. Just printf the tokens as you compute them.
strcat must scan the entire outputString to figure out where it ends. The overall time complexity of the repeated strcats becomes roughly quadratic. I recommend to maintain a pointer to the end of outputString, and strcpy the token.


Updating progress bar animation The general idea is is a progress bar that updates the totals and percentage continually.

This just gets a bit choppy when I trigger a few of these independently on the same page. I'm doing a bit of math at every step, and wonder if there is a better way to accomplish this.

$bar.animate({width:percent+"%"}, {
    duration : o.time,
    easing   : 'swing',
    complete : function() {
        $amount.text('$'+amount.toFixed(2));
        $diff.text('$'+(o.max - amount).toFixed(2));
        $percent.text(Math.floor(percent));
    },
    step : function(now, fx) {
        var actual_amount = (now / 100) * o.max;
        $percent.text(Math.floor(now));
        $amount.text('$'+actual_amount.toFixed(2));
        $diff.text('$'+(o.max - actual_amount).toFixed(2));
        if (o.warning.warning !== 0) {
            if (now > o.warning.alert) {
                $bar.css("background-color", o.alert_color);
            }
            else if (now > o.warning.warning) {
                $bar.css("background-color", o.warning_color);
            }
            else {
                $bar.css("background-color", beginning_color);
            }
        }
    },
});

Whenever the above code gets rerun you're re-instantiating those functions. So the first thing I would recommend is to define the callbacks outside of the immediate scope of whatever's re-running it so they only get instantiated once.

// In a galaxy not so far away…
var animationComplete = function() {
    $amount.text('$'+amount.toFixed(2));
    $diff.text('$'+(o.max - amount).toFixed(2));
    $percent.text(Math.floor(percent));
}, animationStep = function(now, fx) {
    …
};

// meanwhile, back at the farm…
$bar.animate({width:percent+"%"}, {
    duration : o.time,
    easing   : 'swing',
    complete : animationComplete,
    step : animationStep // Got rid of a trailing comma here…
});

Without more context it's hard to say what else you can get away with. You could truncate all your values toFixed(2) early, which would simplify the math for very fractional numbers, but probably not enough for anyone to notice. If, at an earlier point you multiply all your numbers by 100, then you could deal entirely with integers, but there could be some output formatting constraints that make that hard.

All that said, it's likely your animation jitters have nothing to do with the performance of the above JavaScript. You might see some small gains by using CSS transitions and animations instead, which theoretically allow the browser to take better advantage of graphics hardware. (You can still trigger the actual css value changes with JavaScript.)


Classic merge sort (part 2) (Initial discussion from Classic merge sort, since it is new code, I start a new thread)

Post my code below, my major question is, I have to create another array result to hold sub-parts merge sort result. Is there a way I can just use original number to save additional space in result?

Any other comments on code bugs, performance (in terms of algorithm time complexity), code style, etc. are appreciated.

Code written in Python 2.7.

def merge_sort(numbers, start, end):
    if start == end:
        return
    pivot_index = start + (end-start)//2
    merge_sort(numbers, start, pivot_index)
    merge_sort(numbers, pivot_index+1, end)
    i = start
    j = pivot_index+1
    result = []
    while i <= pivot_index and j <= end:
        if numbers[i] <= numbers[j]:
            result.append(numbers[i])
            i+=1
        else:
            result.append(numbers[j])
            j+=1
    if i <= pivot_index:
        result.extend(numbers[i:pivot_index+1])
    if j <= end:
        result.extend(numbers[j:end+1])
    k=0
    for i in range(start, end+1):
        numbers[i] = result[k]
        k+=1

if __name__ == "__main__":
    numbers = [1,4,2,5,6,8,3,4,0]
    merge_sort(numbers, 0, len(numbers)-1)
    print numbers

You can make your merge sort run 35% faster by allocating the auxiliary memory only once and reusing it throughout the algorithm:

def coderodde_merge(source,
                    target,
                    source_offset,
                    target_offset,
                    left_run_length,
                    right_run_length):
    left_run_index = source_offset
    right_run_index = source_offset + left_run_length

    left_run_index_bound = right_run_index
    right_run_index_bound = right_run_index + right_run_length

    while left_run_index != left_run_index_bound and right_run_index != right_run_index_bound:
        if source[right_run_index] < source[left_run_index]:
            target[target_offset] = source[right_run_index]
            right_run_index += 1
        else:
            target[target_offset] = source[left_run_index]
            left_run_index += 1
        target_offset += 1

    while left_run_index != left_run_index_bound:
        target[target_offset] = source[left_run_index]
        target_offset += 1
        left_run_index += 1

    while right_run_index != right_run_index_bound:
        target[target_offset] = source[right_run_index]
        target_offset += 1
        right_run_index += 1

def coderodde_mergesort_impl(source,
                             target,
                             source_offset,
                             target_offset,
                             range_length):
    if range_length < 2:
        return

    left_run_length = range_length // 2
    right_run_length = range_length - left_run_length

    coderodde_mergesort_impl(target,
                             source,
                             target_offset,
                             source_offset,
                             left_run_length)

    coderodde_mergesort_impl(target,
                             source,
                             target_offset + left_run_length,
                             source_offset + left_run_length,
                             right_run_length)

    coderodde_merge(source,
                    target,
                    source_offset,
                    target_offset,
                    left_run_length,
                    right_run_length)

def coderodde_mergesort(array, start, end):
    range_length = end - start

    if range_length < 2:
        return

    aux = [array[index] for index in range(start, end)]
    coderodde_mergesort_impl(aux, array, 0, start, range_length)

def coderodde_mergesort_all(array):
    coderodde_mergesort(array, 0, len(array))

When running this demonstration, I get the following results:

OP mergesort in 17628 milliseconds.
coderodde mergesort in 11411 milliseconds.
Algorithms agree: True

Also, as an additional nitpick, by PEP 8 you should separate binary operators by a space before and after, i.e., not i+=1, but i += 1.

Check you range

If I do something as crazy as

ar = [1, 2, 3]
merge_sort(ar, 0, -1)

you will get a stack overflow.


Iterator producing unique random numbers in a specified range I needed an iterator that produced random numbers, never repeating them, in a specified range of 0..max-1 (index for a collection). When the numbers are exhausted it should not have a next anymore.

The simplest way might be to shuffle an ArrayList and make an iterator. But in typical usage, I will want only 4-5 unique random numbers, from a total in the region of 100. So shuffle seemed too CPU-heavy. And here is the class I came up with. It is written in Java 8 (the requirement of version 8 is acceptable in my case).

import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class NonRepeatingRandom implements Iterator<Integer> {

    private List<Integer> unused;
    private Random random;

    public NonRepeatingRandom(int max) {
        unused = IntStream.range(0, max).boxed().collect(Collectors.toList());
        random = new Random();
    }

    @Override
    public boolean hasNext() {
        return ( unused.size() > 0 );
    }

    @Override
    public Integer next() {
        int size = unused.size();
        if ( size==0 ) {
            throw new java.util.NoSuchElementException();
        }
        int idx = random.nextInt(size);
        int result = unused.get(idx);
        unused.remove(idx);
        return result;
    }

}

I would appreciate comments on this code.

Looks pretty reasonable. Just a few minor issues:

    public NonRepeatingRandom(int max) {

That's fine for general-purpose use, but you should consider adding a constructor which takes (int, Random) for testing purposes.

    @Override
    public boolean hasNext() {
        return ( unused.size() > 0 );
    }

I generally recommend favouring isEmpty() over size() == 0. For many collections isEmpty() just calls size(), but for some it is much more efficient, so it's a good habit to always use isEmpty().

        int idx = random.nextInt(size);
        int result = unused.get(idx);
        unused.remove(idx);

This is the biggest problem, although for your typical use case it might be relatively minor because it doesn't sound like this iterator is going to be a bottleneck.

Removing a random element from a list takes \$O(n)\$ time. But since you don't care about the order of the elements in the list, you could copy the last element to position idx and then delete the last element in \$O(1)\$ time.