Better way to filter select list I'm brand new to JavaScript and jQuery and I feel like there's probably a better way to do this. It seems that the way I designed it may not be very optimal once you get a thousand entries in the list but I do like the fact that it's a live search.

Note: I tried changing the style of the <option>'s to display:none but that doesn't work in all browsers.

http://jsfiddle.net/x6cfF/3/

<input type="search" id="SearchBox" />

    <select size=2 class="scrollableinside" id="CustomerSelect">
        <option value=100>test</option>
        <option value=101>test1</option>
        <option value=102>test2</option>
        <option value=103>test3</option>
    </select>

    <select id="CustomerSelectHidden"></select>

First thing I notice is that you're actually not using jQuery all that much. The point of jQuery is really its convenience compared to the native DOM. You're foregoing that convenience in some places, and relying on jQuery in others. You can of course do it all directly using the DOM and skip jQuery, but you're not quite doing that either. My point is really just that you should decide one way or the other in order to keep the code consistent.

Also, while it's not enforced, convention dictates that function names are lowerCamelCase. If you use PascalCase it implies that a function is a constructor. I.e. your Sort function should be just sort.

However, the sort function is not necessary. Provided you always search in a "master list" of options, and those are already sorted, then the filtered options will retain that order.

The hidden select element isn't necessary either; you can clone the full option list into memory, and filter it from there without having to store it in the document.

In fact, by keeping a master list, you can "prepare" that list to make it faster to filter later.

Here's a demo of my take and here's the code:

$(function () {
    var customerSelect = $("#customer"),
        searchField    = $("#search"),
        options        = customerSelect.find("option").clone(); // clone into memory

    // generic function to clean text
    function sanitize(string) {
        return $.trim(string).replace(/\s+/g, ' ').toLowerCase();
    }

    // prepare the options by storing the
    // "searchable" name as data on the element
    options.each(function () {
        var option = $(this);
        option.data( "sanitized", sanitize(option.text()) );
    });

    // handle keyup
    searchField.on("keyup", function (event) {
        var term = sanitize( $(this).val() ),
            matches;

        // just show all options, if there's no search term
        if( !term ) {
            customerSelect.empty().append(options.clone());
            return;
        }

        // otherwise, show the options that match
        matches = options.filter(function () {
            return $(this).data("sanitized").indexOf(term) != -1;
        }).clone();
        customerSelect.empty().append(matches);
    });
});

You could do a few more things, but I'll leave that as an exercise:

If the search term contains the previous search term, you can filter the customer select directly, instead of filtering the entire "master list". I.e. if the last search was for "foo" and the next is for "foobar", you already have the results that match "foo", and only have to find a further subset that contains "foobar" rather than starting from the beginning.
If you have a very long list, or you're retrieving the search results via ajax, it's beneficial to have a delay between searches. I.e. on keyup wait, say, 100ms before filtering the list, to see if the user's still typing.


Is this password hashing acceptable for a custom MembershipProvider? I'm creating a custom MembershipProvider for an ASP.NET MVC5 application and am wanting to know if this code is acceptable for creating hashed and salted passwords.  Is there anything I can do to improve it?

EncodePassword is passed the plaintext password from the override functions.

I picked 38 hash iterations arbitrarily and I honestly don't know if it's even necessary or valuable. Should it be higher?

_machineKey is auto generated by ASP.NET for each machine/VM the software runs on. I will probably remove this to allow a distributed system and use an application key instead. Though, looking through the documentation for HMACSHA1, would it even seem like this key may be necessary?

EncodePassword() result will be stored directly in the database.

    private bool CheckPassword(string password, string dbpassword)
    {
        var salt = GetSalt(dbpassword);
        password = EncodePassword(password, salt);

        if (password == dbpassword)
        {
            return true;
        }

        return false;
    }

    private string EncodePassword(string password, string salt = "")
    {
        if (string.IsNullOrEmpty(salt))
            salt = CreateSalt();
        var hash = new HMACSHA1 { Key = HexToByte(_machineKey.ValidationKey) };
        var bytePassword = hash.ComputeHash(Encoding.Unicode.GetBytes(password + salt));

        for (int i = 0; i < 38; i++)
        {
            bytePassword = hash.ComputeHash(bytePassword);
        }
        return String.Format("{0}:{1}", bytePassword, salt);
    }

    private static string CreateSalt(int size = 64)
    {
        using (var rng = new RNGCryptoServiceProvider())
        {
            var buff = new byte[size];
            rng.GetBytes(buff);
            return Convert.ToBase64String(buff);
        }
    }

    private static string GetSalt(string password)
    {
        var passwordSplit = password.Split(':');
        if (passwordSplit.Length == 2)
        {
            return passwordSplit[1];
        }

        return String.Empty;
    }

This is a pretty good start: you've got salting done pretty well (RNGCryptoServiceProvider is one of the most common recommended was to generate a salt), and the idea of using multiple iterations is a good one.

However, doing 38 iterations of HMAC SHA1 yourself is not really going to help you much.  The point of iterations is to slow down someone who is trying to brute-force passwords by making it take longer to do so.  SHA1 is designed to be fast (it has to be in order to be used for message authentication "at scale"), so doing it multiple times doesn't slow you down all that much.

Instead, consider using an algorithm purpose-built for password hashing, like PBKDF2, bcrypt, or scrypt. They are built on the same cryptographic hash functions, but are tuned for the specific purpose of password hashing. (They also typically recommend more than 1000 iterations, significantly more than your 38.)  The easiest thing to do is to use a library like CryptSharp, SimpleCrypto.net, BCrypt.net, or many others.

UPDATE PBKDF2 is built in to the .NET Framework using the Rfc2898DeriveBytes class. Here is how to use it (based on your EncodePassword function:

private string EncodePassword(string password, string salt = "")
{
    int numIterations = 1000;

    if (string.IsNullOrEmpty(salt))
        salt = CreateSalt();

    using (var pbkdf2 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), numIterations))
    {
        var hash = pbkdf2.GetBytes(64);
        return String.Format("{0}:{1}", Convert.ToBase64String(key), salt);
    }
}

Another thing you could do to "future-proof" your hashing is to store the number of iterations and the encryption method along with the password.  That way, if you decide to change the number of iterations used (for example, you may wish to do so if/when computing power gets to the point that a few thousand iterations isn't slow enough) you won't have to invalidate all existing passwords all at once. For example,  PHP's password_hash function (which uses bcrypt, not PBKDF2 - but the principle is the same) stores a code representing the hash function used and the number of iterations along with the salt and the password.  (For an easy look at how they do it, see this implementation.)

(A general word of advice: it is very tempting to roll your own password encryption.  Resist the urge and Just Don't Do It.)


Calling a promise recursively I'm trying to call a promise recursively. If I get a responseData with a key error I want to call the promise again and again until I don't get it.

  _getUser (url) {
    console.log('fetching url', url)
    return fetch(`$(url)/api`, {
      method: 'POST',
      headers: {},
      body: '{"key" : "body"}'
    })
    .then((response) => response.json())
    .then((responseData) => {
      console.log('Getting responseData', responseData)
      if (responseData[0].error) {
        alert(responseData[0].error.description)
        return _getUser(url)
      } else alert('User Created')
    })
    .catch((error) => {
      console.log(error)
    })
  }

Is this the best way to call a promise recursively to do what I want?

Two things you can improve:

Retry in all error cases by doing the recursive call in the catch function.
And limit the number of retries

_getUser (url, triesRemaining) {
    console.log('fetching url', url)
    return fetch(`$(url)/api`, {
      method: 'POST',
      headers: {},
      body: '{"key" : "body"}'
    })
    .then((response) => response.json())
    .then((responseData) => {
      console.log('Getting responseData', responseData)
      if (responseData[0].error) {
        alert(responseData[0].error.description)
        throw new Error();
      } else alert('User Created')
    })
    .catch((error) => {
      console.log(error)
      if(triesRemaining>0) {
        return _getUser(url,triesRemaining-1)
      } else {
        throw new Error('Could not create user. Max amount of tries reached');
      }
    })
  }


Refactoring my simple model-view-presenter architecture My application uses a simple Model-View-Presenter architecture and uses the following classes and interface:

Presenter:

public abstract class Presenter<V> {

    private V view;

    public final void setView(V view) {
        this.view = view;
    }

    protected final V getView() {
        return this.view;
    }
}

View

public abstract class View<V, P extends Presenter<V>> implements ViewAdapter<V> {

    private final P presenter;

    public View(P presenter) {
        this.presenter = presenter;
    }

    protected final P getPresenter() {
        return this.presenter;
    }

    void initialize() {
        this.getPresenter().setView(this.asView());
    }
}

ViewAdapter

interface ViewAdapter<T> {
    T asView();
}

The application is then wired up like this:

A concrete Presenter is created.
A concrete View is created, passing in the concrete Presenter as a constructor parameter.
The View is initialised. During initialisation, the View calls the asView method to pass a view instance to the presenter.

Each concrete presenter in the application is parameterised with a view interface. Each concrete view class implements a view interface and can then pass itself to the presenter during initialisation and it is in this area that I am looking for advice.

The ViewAdapter interface exists solely to allow the concrete view to pass itself to the presenter via the asView method whilst maintaining type safety. My concrete views which derive from the View class are then forced to provide an implementation of the asView method in order to provide a view instance to the presenter that is of the correct type.

Every implementation looks the same:

@Override
public FooView asView() {
    return this; // this implements the FooView interface.
}

All this basically does is force 'this' to implement FooView as I am unable to express something like this:

// Example, not valid code, won't compile!
public abstract class View<V, P extends Presenter<V>> implements V {
}

Which would allow me to remove the ViewAdapter interface and pass the view to the presenter in the abstract View class like this, removing the redundancy:

void initialize() {
    this.getPresenter().setView(this);
}

I tried it in an IDE and have some addition to the last comment. I agree that you should try

Presenter<V extends View>

plus I would add that you need to switch the signature to

public abstract class View<V, P extends Presenter>

from

public abstract class View<V, P extends Presenter<V>>

That is regarding to make it compile. Additionally, you can discard generics V since it is not used anymore in the View so the final signature would be:

public abstract class View<P extends Presenter>

Then you can get rid of ViewAdapter and the initialize method should work as you want it:

void initialize() {
    this.getPresenter().setView(this);
}


A Version 4 UUID Implementation I've been toying around with writing a decentralized, P2P application in REBOL 2, and one of the things I need to do is generate a universally unique identifier for users. I have written a function that generates a Version 4 UUID that is compliant with RFC 4122, as best as I can tell.

I have a few questions ...

Is it compliant with RFC 4122? Have I missed anything?
I am fairly new to REBOL. Is there a simpler approach I could have taken with the code? Am I using best practices in the language?
The code picks random integers and does some bitwise operations using integers too. Is it correct to do things this way? All the online examples I've come across use bytes directly and does the bitwise operations using hexidecimal numbers. REBOL doesn't support bytes directly and so that's why I've coded things this way. It appears to work correctly, but I have this nagging feeling that maybe I've overlooked something at a lower level.

Here is the REBOL 2 code

REBOL []

; IMPORTANT - random/seed now/precise must be called before running this function
; Also, it must only be seeded ONCE per application process or duplicates will occur
makeUUID: func [
    "Generates a Version 4 UUID that is compliant with RFC 4122"
    /local data
][
    ; generate 16 random integers

    ; Note: REBOL doesn't support bytes directly
    ; and so instead we pick numbers within the
    ; unsigned, 8-bit, byte range (0 - 255)

    ; Also random normally begins the range at 1,
    ; not 0, and so -1/256 allows 0 to be picked
    data: collect [loop 16 [keep -1 + random/secure 256]]

    ; set the first character in the 7th "byte" to always be 4
    data/7: data/7 and 15 or 64

    ; set the first character in the 9th "byte" to always be 8, 9, A or B
    data/9: data/9 and 63 or 128

    ; convert the integers to hexadecimal
    data: enbase/base to binary! data 16

    ; add the hyphens between each block
    data: insert skip data 8 "-"
    data: insert skip data 4 "-"
    data: insert skip data 4 "-"
    data: insert skip data 4 "-"

    head data
]

random/seed now/precise
for num 1 30 1 [print makeUUID]
halt

this isn't much shorter but instead of

; add the hyphens between each block
data: insert skip data 8 "-"
data: insert skip data 4 "-"
data: insert skip data 4 "-"
data: insert skip data 4 "-"

head data

you could write

parse data [8 skip insert "-" 3 [5 skip insert "-"] to end]
data

And you don't need a for loop

loop 30 [print makeuuid]


Trim string of words based on character count I needed a simple way to trim a string of words based on a max character count. I also needed to cut in-between words. Using WordPress, here is what I came up with, but I feel like it could be more efficient.

function count_words($content) {
    $partsArray = explode(' ', $content);
    return sizeof($partsArray);
}

function custom_length_excerpt_max_char($content, $max_chars_limit) {
    $count = 0;
    $word_limit;
    while (strlen($content) > $max_chars_limit) {
        $word_limit = count_words($content);
        $word_limit -= 1;
        $content = wp_trim_words($content, $word_limit, '');
        $count++;
        if ($count > 10) {
            break;
        }
    }
    if ($count > 0) {
        $content .= '&#8230;';
    }
    return $content;
}

I was originally using str_word_count to count the words but it was choking on HTML-encoded characters in the string.

Yes, it's extremely inefficient, because in every iteration you count the number of words twice: once in count_words, and then wp_trim_words internally has to count the words again.

Another problem is that the method won't work for content that is many words larger than the target limit length. For example with a content of 4000 chars and a limit of 100, due to the if ($count > 10) break check in the middle, the method will basically cut off the last 10 words and return a still very large content. Not sure if that was part of your plan.

I don't really know PHP. But here's a naive implementation that should be more efficient and work with long content too:

function is_letter($char) {
    return ctype_alpha($char) || in_array($char, ['-']);
}

function custom_length_excerpt_max_char($content, $max_chars_limit) {
    if (strlen($content) < $max_chars_limit) {
        return $content;
    }
    $cut_at = $max_chars_limit;
    for (; $cut_at >= 0 && is_letter($content{$cut_at}); --$cut_at);
    return substr($content, 0, $cut_at);
}

function test_custom_length_excerpt_max_char() {
    $sample = 'some sample-text some sample-text';
    for ($i = 5; $i < strlen($sample) + 10; ++$i) {
        echo custom_length_excerpt_max_char($sample, $i)."\n";
    }
}

Here's the logic behind the main function:

If the content is shorter than the limit, return it
Iterate backward from the target limit position, until you find something that's NOT a letter, and break the content there.

If you run the test function, the output is something like:

...
some
some
some sample-text
some sample-text
some sample-text
some sample-text
some sample-text
some sample-text some
some sample-text some
some sample-text some
...


"Rasterbation" function to split an image into a grid I want to create a function that splits an image into many separate blocks that when put together look like the image as a whole, often called a Rasterbator. Given the number of tiles for height and length I want and the image to Rasterbate I want the function to draw the split up image with a little padding in between.

I have created the function successfully but with a high length/height it takes a long time to create that many DOM elements sure to the nester loop, for example 100 x 100 is 10,000 divs being created and having math applied to their backgrounds.

http://jsfiddle.net/n4a7cr9z/

var img = new Image();
var width;
var height;
var length = 30;
var ylength = 20;
img.onload = function() {
width = this.width;
  height = this.height;
    for (var j = 0; j < length; j++){
    for (var i = 0; i < length; i++){
        var left = (-1 * width/length * i).toString() +"px";
        var top = (-1 * height/ylength * j).toString() +"px";
        var element = jQuery('<div/>', {
            id: i + ""+j,
            class: "splitImg",
            css: {
            "width" : Math.floor(width/length),
            "height":Math.floor(height/ylength),
          "background-position": left  + " " +  top,
          "background-image" : 'url(' + img.src + ')'
            }
            })
            element.appendTo('#wrapper');
        $("#wrapper").width(width + (length *2))
    }
    }
}
img.src = 'http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg';

I was thinking maybe creating rows or columns in batches somehow since they'll all share the same background position on either the X or Y level, like first row will all have a Y offset of 0, but I'm not sure how or if that will help.

Before you opt for a <canvas> solution you might try adapting your current code with a few go-faster tricks.

var t = Date.now();
var img = new Image();
var length = 30;
var ylength = 20;
img.onload = function() {
    var width = this.width,
        height = this.height,
        _length = -length,
        i, j;

    // create a <div/> with all basic characteristics, to be cloned over and over in the loops below.
    var $basicDiv = jQuery('<div/>', {
        class: 'splitImg',
        css: {
            'width': Math.floor(width/length),
            'height': Math.floor(height/ylength),
            'background-image': 'url(' + img.src + ')'
        }
    });
    // Finding a node in the DOM is slow. Do it once and assign the returned jQuery collection.
    // Also, #wrapper's width can be set here.
    var $wrapper = $('#wrapper').width(width + length * 2);

    for (i = 0; i > _length; i--) {
        for (j = 0; j > _length; j--) {
            $basicDiv.clone().css({'background-position': `${width/length * j}px ${height/ylength * i}px`}).appendTo($wrapper);
        }
    }
    console.log(Date.now() - t);
}
img.src = 'http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg';

Updated fiddle

Playing around with the code, I found all of the following to make a difference :

cloning a basic div created outside the nested loops,
avoiding assignments (other than loop counters) in the nested loops,
avoiding the need to multiply by -1 (twice) by counting backwards in the for(...) expressions,
using a template literal to build the background-position string. But beware, this is not yet well supported in browsers.

With the modified code, execution time on my computer halved from about 1200 - 2000 ms to 600 - 1000 ms.

You may well find a <canvas> approach to be even faster. I was surprised at what could be achieved with <canvas> when I wrote this answer.


Finding the nearest polygon Finding the nearest polygon out of a list of polygons seems to be quite a challenge on performance, due to lack of optimization.

Consider the following image:

I'll give the concept behind this. The "purple" pointer under the mouse is an entity and each blue blob is a polygon. The red ring denotes the nearest polygon, while the pink line denotes the nearest line of that polygon.

Here is the system:

Entity: performs a loop through ALL polygons.
Polygon Loop: loops through ALL vertices of the polygon in the current iteration.
Vertex Loop: if the distance between the entity and the current vertex is lower than the distance between the entity and the previous vertex, save the current vertex and the ID of the polygon the vertex belongs to.
Once all loops are finished, take the nearest polygon/vertex and get the vertex of the polygon to the left and right of the nearest vertex.
Check the left and right vertices to see which is closest to the nearest vertex. Doing so, finds the nearest line of collision to the entity.

In short, I loop through all polygons and all vertexes of each polygon to find the nearest collision line of the nearest polygon to the entity. This allows me to handle terrain, collisions, gravity, etc.

The reason for this, is that the polygons can have any shape. Since this is the case, I have to dynamically find the nearest polygon based off of the vertex of each polygon to the entity. It's costly, but gets the job done...

I know this method is inefficient, but how could I go about making this system better? Or using an entirely different and existing system that is better?

The partial code below does not include finding the nearest line. That part I am not worried about as it's very easy/fast to do.

// srce -> list(1d-array) of polygon object-IDs;
// updated -> polygon vertex array of each polygon object;
// polygon -> current iteration in the srce list(1d-array);
// with( ... ) -> current polygon of the current iteration;
// vertex -> the current vertex in the iteration of vertices of the polygon;
// srcex and srcey -> entity x,y position;
// xvertex -> x-position of the current vertex in the iteration;
// yvertex -> x-position of the current vertex in the iteration;
// nearest* vars -> store the nearest vertex/polygon data;
// size -> total vertexes in the nearest polygon;
// NOTE: Each vertex takes up 2 indexes in the list(1d-array);

// Iterate through all polygon objects;
repeat( ds_list_size( srce ) ) {
   with( ds_list_find_value( srce , polygon ) ) {
      vertex = 0;

      // Iterate through the polygon's vertices;
      repeat( ds_list_size( updated ) div 2 ) {
         xvertex = ds_list_find_value( updated , vertex );
         yvertex = ds_list_find_value( updated , vertex + 1 );
         vertex_dist = point_distance( srcex , srcey , xvertex , yvertex );

         // Here we get the current nearest point IF it's closer than the previous;
         // Here -1 means there is current NO nearest vertex;
         if ( vertex_dist < nearest_dist || nearest_dist == -1 ) {
            // If this vertex is closer than the previous, store it's data;
            nearest_dist = vertex_dist;
            nearestx = xvertex;
            nearesty = yvertex;

            // This one is confusing: nearestv stores the INDEX of the vertex in...
            // ... the array of vertices, this is a reference point for the vertex;
            nearestv = vertex;

            nearest_polygon = id;
            size = ds_list_size( id );
         }

         vertex += 2;
      }
   }

   polygon += 1;
}

If shape and number of polygons do not change (or at least not often), I would add an extra step (the new first step) to your algorithm.

Calculate the center and radius of the smallest surrounding circle for each polygon. This way you can calculate in a minimal and maximal distance of all vertices from the given position in one run without iterating through them.

If the minimum distance for a polygon is greater than the maximum of an other polygon, no vertex of that polygon can be the nearest => we can ignore this polygon.

Than proceed like you did before.

calculate distance to each polygon surrounding circle and eliminate all polygons which are too far away to be a match
Entity: performs a loop through all not eleminated polygons.
Polygon Loop: loops through ALL vertices of the polygon in the current iteration.
Vertex Loop: if the distance between the entity and the current vertex is lower than the distance between the entity and the previous vertex, save the current vertex and the ID of the polygon the vertex belongs to.
Once all loops are finished, take the nearest polygon/vertex and get the vertex of the polygon to the left and right of the nearest vertex.
Check the left and right vertices to see which is closest to the nearest vertex. Doing so, finds the nearest line of collision to the entity.


Lazy class instantiation in Python I've written some class which allows me to derive from it to make objects lazy-instantiated. Do you see notational improvements or maybe even cases where this method might not work (multiple inheritance etc.)? What else could I try?

class LazyProxy(object):
    def __init__(self, cls, *params, **kwargs):
        self.__dict__["_cls"]=cls
        self.__dict__["_params"]=params
        self.__dict__["_kwargs"]=kwargs

        self.__dict__["_obj"]=None

    def __getattr__(self, name):
        if self.__dict__["_obj"] is None:
            self.__init_obj()

        return getattr(self.__dict__["_obj"], name)

    def __setattr__(self, name, value):
        if self.__dict__["_obj"] is None:
            self.__init_obj()

        setattr(self.__dict__["_obj"], name, value)

    def __init_obj(self):
        self.__dict__["_obj"]=object.__new__(self.__dict__["_cls"], *self.__dict__["_params"], **self.__dict__["_kwargs"])
        self.__dict__["_obj"].__init__(*self.__dict__["_params"], **self.__dict__["_kwargs"])

class LazyInit(object):
    def __new__(cls, *params, **kwargs):
        return LazyProxy(cls, *params, **kwargs)

class A(LazyInit): # classes meant to be lazy loaded are derived from LazyInit
    def __init__(self, x):
        print("Init A")
        self.x=14+x

a=A(1)
print("Go")
print("15=", a.x)

Would be cool as a class decorator.

@Lazy
class MyFoo:
    ...

To me it seems like it would fit nicely as a class decorator because it's independent of what the class is representing.  It has more to do with the way the class works internally than it does with the thing that the class embodies.


Am I using Golang concurrency correctly to increase reliability? This code takes text from the standard input, maps it to a struct (if possible), and creates a JSON string from that.

I'm using a barcode scanner for the input, and I've attempted to use goroutines to ensure that if something goes wrong with the parsing or JSON-marshalling, the program will continue to receive and process input from the scanner.

Am I doing this correctly, and am I doing it in the most effective, efficient, or idiomatic way?

Because all I care about for this post is the concurrency, I've left out all code that parses the input and creates JSON.  Additionally, the only thing I do with the JSON right now is print it back out.

Thanks for taking a look at this.

package main

import (
    "fmt"
    "status2/shoporder"
)

func main() {
    var input string
    for input != "exit" {
        fmt.Scanln(&input)
        ch := make(chan string)
        quit := make(chan bool)
        go parseInput(input, ch, quit)
        go sendJson(ch, quit)
    }
}

// Take the input and generate some JSON, then return it along a channel.
func parseInput(input string, ch chan string, quit chan bool) {
    // shoporder.Parse() uses regexp to validate the input, and returns a JSON string.
    son, ok := shoporder.Parse(input)
    if !ok {
        // If the input could not be parsed into JSON, then ignore and shut down
        // both goroutines.
        quit <- true
        return
    }
    ch <- son
}

// This will eventually send the JSON using websockets, but for now I just
// print it back out.
func sendJson(ch chan string, quit chan bool) {
    select {
    case json := <-ch:
        // For now I just print the JSON.
        fmt.Println(json)
    case <-quit:
        // I make sure to quit the goroutine, because I'm worried about creating a
        // bunch that never end and just hang around.  Do I need to do this?
        return
    }
}

It seems reasonable to start a goroutine for each input, but I'm not sure you need separate goroutines for parsing and sending.  After all, one is just waiting for the other to finish.  They might as well be the same goroutine.  Then you don't need either of the channels because they were just to let these two goroutines communicate.


Calling jQuery plugin methods I have two code snippets and the following questions:

Which uses the best practice and why?
Which one is good for performance?

Code 1

jQuery( function( $ ) {

    // Responsive video
    var $area = $( "#sidebar" );
    $area.fitVids();

    // Image gallery
    var $slider = $( ".owl-carousel" );
    $slider.owlCarousel();

});

Code 2

// Global jQuery variable
var $ = jQuery;

/**
 * Responsive video
 */
var fitvidsInit = function() {
    var $area = $( "#sidebar" );
    $area.fitVids();
};

/**
 * Slides
 */
var sliderInit = function() {
    var $slider = $( ".owl-carousel" );
    $slider.owlCarousel();
};

/**
 * Execute code
 */
$( function() {
    fitvidsInit();
    sliderInit();
} )

I also have to defined the variable $ because this is in WordPress.

Any performance difference would be too small to measure.

Code 2 pollutes the global namespace with three variables: $, fitvidsInit, and sliderInit.  Therefore, Code 1 is better.  I suggest eliminating $area and $slider as well:

jQuery( function( $ ) {

    // Responsive video
    $( "#sidebar" ).fitVids();

    // Image gallery
    $( ".owl-carousel" ).owlCarousel();

});


TDD Hackerrank: Library Fines From this hackerrank:

  Problem Statement

  The Head Librarian at a library wants you to make a program that
  calculates the fine for returning the book after the return date. You
  are given the actual and the expected return dates. Calculate the fine
  as follows:

  If the book is returned on or before the expected return date, no fine
  will be charged, in other words fine is 0.
  If the book is returned in
  the same calendar month as the expected return date, Fine = 15 Hackos
  × Number of late days
  If the book is not returned in the same calendar
  month but in the same calendar year as the expected return date, Fine
  = 500 Hackos × Number of late months
  If the book is not returned in the same calendar year, the fine is fixed at 10000 Hackos. Input

  You are given the actual and the expected return dates in D M Y format in
  two separate lines. The first line contains the D M Y values for the
  actual return date and the next line contains the D M Y values for the
  expected return date.

My development philosophy was to TDD this. First write code that reads the date correctly, then start implementing the test cases from the problem statement.

I did not put anything in a separate class.

My code passed all their test cases but looks ugly as heck. Any suggestions for improvement would be appreciated!

import datetime

def testFine(dueDate, returnDate, actualFine):
    fine = getFine(dueDate, returnDate)
    if (fine != actualFine):
        print( "Test FAILED for duedate %s and returnDate %s with fine: %d but expected:%d." %( dueDate, returnDate, fine, actualFine) )

    else:
       print( "Test passed for duedate %s and returnDate %s with fine: %d." % ( dueDate, returnDate, fine) )

def tests():

    #If the book is not returned in the same calendar year, the fine is fixed at 10000 Hackos.
    testFine(datetime.date(2015,5,5), datetime.date(2016,5,6),10000)

    #If the book is returned on or before the expected return date, no fine will be charged, in other words fine is 0.
    testFine(datetime.date(2015,5,5), datetime.date(2015,5,5),0)
    testFine(datetime.date(2015,5,5), datetime.date(2015,5,3),0)
    #If the book is returned in the same calendar month as the expected return date, Fine = 15 Hackos × Number of late days

    testFine(datetime.date(2015,5,5), datetime.date(2015,5,6),15)
    testFine(datetime.date(2015,2,5), datetime.date(2015,2,10),75)

    #If the book is not returned in the same calendar month but in the same calendar year as the expected return date, Fine = 500 Hackos × Number of late months

    testFine(datetime.date(2015,2,5), datetime.date(2015,3,1),500)
    testFine(datetime.date(2015,2,5), datetime.date(2015,6,1),2000)

def getFine(dueDate, returnDate):

    if (returnDate.year > dueDate.year):
        return 10000

    if (returnDate.year == dueDate.year and returnDate.month == dueDate.month and returnDate.day > dueDate.day):
        return 15*(returnDate.day-dueDate.day)

    if (returnDate.year == dueDate.year and returnDate.month > dueDate.month):
        return 500*(returnDate.month-dueDate.month)

    return 0

def getDateFromCin():
    s = input()
    nums = [int(n) for n in s.split(" ")]
    return datetime.date(nums[2], nums[1],nums[0])

def testFunc():
    testline = input()

    print (testline + "test")
    return

def cinMain():
    returnDate = getDateFromCin()
    dueDate = getDateFromCin()
    fine = getFine(dueDate, returnDate)
    print (fine)

def main():
    tests()

cinMain()

Avoid so many temporary variables

In Python, temporary variables are used only if they benefit readability, not if they hurt it:

def getDateFromCin():
    s = input()
    nums = [int(n) for n in s.split(" ")]
    return datetime.date(nums[2], nums[1],nums[0])

Becomes:

def getDateFromCin():
    nums = [int(n) for n in input().split(" ")]
    return datetime.date(nums[2], nums[1], nums[0])

Actually, @QPaysTaxes suggested to use the splat (*) operator, and I also think it is a good idea, this shortens to function further to just:

return datetime.date(* [int(n) for n in reverse(input().split(" "))])

And:

def testFunc():
    testline = input()

    print (testline + "test")
    return

Becomes:

def testFunc():
    print (input() + "test")
    # return is not needed

And:

def cinMain():
    returnDate = getDateFromCin()
    dueDate = getDateFromCin()
    fine = getFine(dueDate, returnDate)
    print (fine)

Becomes:

def cinMain():
    returnDate = getDateFromCin()
    dueDate = getDateFromCin()
    print( getFine(dueDate, returnDate) )

Small simplifications like this are nothing interesting on their own but when you make a lot of them they start to add up making the code cleaner.

Simplify your booleans

if (returnDate.year == dueDate.year and returnDate.month == dueDate.month and returnDate.day > dueDate.day):
    return 15*(returnDate.day-dueDate.day)

If you got here, then returnDate.year == dueDate.year is surely True, as True and x == x you can simplify:

if (returnDate.month == dueDate.month and returnDate.day > dueDate.day):
        return 15*(returnDate.day-dueDate.day)

Remember to add:

if returnDate <= dueDate:
    return 0

At the start of the function to preserve correctness.

Use a testing framework

You made some work to run the automated tests, but there are already tools for that, I suggest doctest, it is very easy to use and doubles as documentation:

def book_return_fine(dueDate, returnDate):
    """
    >>> book_return_fine(datetime.date(2015,5,5), datetime.date(2016,5,6))
    10000
    """
    if (returnDate.year > dueDate.year):
        return 10000

    if (returnDate.month == dueDate.month and returnDate.day > dueDate.day):
        return 15*(returnDate.day-dueDate.day)

    if (returnDate.month > dueDate.month):
        return 500*(returnDate.month-dueDate.month)

    return 0

Just add import doctest at the start and doctest.testmod() at the end.

Naming

Naming is hard, I really do not like your names.

get is a specific OO concept and gives almost no info about what the function does.
cin is a C++ term, not everyone may remember what it stands for.
nums well, if you convert them to int they are nums but this really does not give me much info...
snake_case is the common Python naming style, not camelCase.

Spacing

Asinnaturallanguage,spacingthingsouthelpsthereaderreadfasterandeasier.

   As in natural language, spacing things out helps the reader read faster and easier.

For example:

return 15*(returnDate.day-dueDate.day)

Becomes:

return 15 * (returnDate.day - dueDate.day)


Indexed Properties in C# I was challenged to implement a mechanmism to support indexed properties in a class structure.

I wanted to avoid the need to implement an abstract property indexer class every time you want to implement a new T just because the backing store has changed. Semantically, if C# did provide indexed properties, the get/set logic would be on the class declaring the indexed property (as there would be no type).

So I implemented the following logic:

public interface IIndexedProperty<TKey, TValue>
{
    TValue this[TKey index] { get; set; }
}
public class IndexedProperty<TKey, TValue> : IIndexedProperty<TKey, TValue>
{
    private Func<TKey, TValue> Getter { get; set; }
    private Action<TKey, TValue> Setter { get; set; }
    public IndexedProperty(Func<TKey, TValue> getter, Action<TKey, TValue> setter)
    {
        this.Getter = getter;
        this.Setter = setter;
    }
    public TValue this[TKey index]
    {
        get
        {
            return Getter(index);
        }
        set
        {
            Setter(index, value);
        }
    }
}

An example implementation:

public class MyClass
{
    public IIndexedProperty<string, string> Values { get; private set; }
    private Dictionary<string, string> ValueDictionary { get; set; }
    public MyClass()
    {
        Values = new IndexedProperty<string, string>(index => ValueDictionary[index], (index, value) => ValueDictionary[index] = value);
        ValueDictionary = new Dictionary<string, string>();
    }
}

What he doesn't like about this is twofold:

It isn't reusable (you have to implement the logic in your defining class each time you use it)
It holds references to two delegates.

Can you see ways in which this can be improved?

This implementation allows for reusability of the indexer backing logic, as shown on MyClass two having two indexers using the same backing implementation. This pattern is much more reusable.

public abstract class PropertyIndexer<TKey, TValue>
{
    public abstract TValue this[TKey index] { get; set; }
}
public class MyClass
{
    private class StringDictionaryPropertyIndexer : PropertyIndexer<string, string>
    {
        private Dictionary<string, string> BackingCollection { get; set; }
        public StringDictionaryPropertyIndexer(Dictionary<string, string> backing)
        {
            this.BackingCollection = backing;
        }
        public override string this[string index]
        {
            get
            {
                string value;
                if (BackingCollection.TryGetValue(index, out value))
                    return value;
                return null;
            }
            set
            {
                BackingCollection[index] = value;
            }
        }
    }
    private Dictionary<string, string> data { get; set; }
    public PropertyIndexer<string, string> Data { get; private set; }
    private Dictionary<string, string> alternateData { get; set; }
    public PropertyIndexer<string, string> AlternateData { get; private set; }
    public MyClass()
    {
        data = new Dictionary<string, string>();
        Data = new StringDictionaryPropertyIndexer(data);
        alternateData = new Dictionary<string, string>();
        AlternateData = new StringDictionaryPropertyIndexer(alternateData);
    }
}


Generic EventArgs to go with generic EventHandler? There is as of .NET 2.0 a generic EventHandler delegate type, which can be used to define an event in terms of the EventArgs type you wish to use, without having to create a redundant delegate type to use in the event declaration.

Well, what about the EventArgs? I often find myself having to create one-offs derived from EventArgs to encapsulate extra data I wish to send. Why can't that be declared generically as well? If all I need to pass is a string, or an integer, or a Point, why do I have to create a StringEventArgs, IntEventArgs and/or PointEventArgs class respectively?

I roughed up two very basic EventArgs generic types as a proof-of-concept:

public class ReadOnlyEventArgs<T>:EventArgs
{
    public T Parameter { get; private set; }

    public ReadOnlyEventArgs(T input)
    {
        Parameter = input;
    }
}

public class EventArgs<T>:EventArgs
{
    public T Parameter { get; set; }

    public EventArgs(T input)
    {
        Parameter = input;
    }
}

The obvious difference is whether you want event handlers to be able to modify your arguments. Sometimes it's a good idea, most of the time not so good. Usage would simply look like:

public event EventHandler<EventArgs<string>> StringValidationRequested;
public event EventHandler<ReadOnlyEventArgs<int>> RecordSelectedForRetrieval;
public event EventHandler<ReadOnlyEventArgs<Point>> MouseLocationReported;

Now, obviously these are for simpler situations, but I've found most situations of event raising to be pretty simple. The only possible thing I'd add would be two more classes derived from CancelEventArgs to add that additional functionality. The fact that the Parameter can be anything including a class makes it flexible enough to pass complex data, and .NET 4's Tuples take care of the remaining situations where you might not want to define your own complex type. The only drawback I can think of is not being able to descriptively name your parameter; it's generic.

You could make it a little bit more useful if you added some supporting factory methods to create the arguments.  That way you don't have to use the constructor and its somewhat awkward syntax (having to supply the types).

public static class EventHandlerExtensions
{
    public static EventArgs<T> CreateArgs<T>(
        this EventHandler<EventArgs<T>> _,
        T argument)
    {
        return new EventArgs<T>(argument);
    }

    public static ReadOnlyEventArgs<T> CreateArgs<T>(
        this EventHandler<ReadOnlyEventArgs<T>> _,
        T argument)
    {
        return new ReadOnlyEventArgs<T>(argument);
    }
}

Then to create the instance of the arguments, you could just do this:

public event EventHandler<EventArgs<SomeArg>> SomeEvent;
public event EventHandler<ReadOnlyEventArgs<SomeArg>> SomeOtherEvent;

protected virtual void OnSomeEvent(SomeArg argument)
{
    var someEvent = SomeEvent;
    if (someEvent != null)
    {
        var args = someEvent.CreateArgs(argument);
        // instead of:
        //var args = new EventArgs<SomeArg>(argument);
        someEvent(this, args);
    }
}

protected virtual void OnSomeOtherEvent(SomeArg argument)
{
    var someOtherEvent = SomeOtherEvent;
    if (someOtherEvent != null)
    {
        var args = someOtherEvent.CreateArgs(argument);
        // instead of:
        //var args = new ReadOnlyEventArgs<SomeArg>(argument);
        someOtherEvent(this, args);
    }
}

It might be useful to have options for multiple parameters (similar to how the tuple is).  Though it might not be feasible to have all combinations of multiple (im)mutable arguments.


Grabbing city names and numbers from a CSV file I've got information that is imported from a CSV file that my site grabs every day with PHP. I'm just learning RegEx so I'm able to do what I need to do but am looking to get more efficient with my coding.

Some of example of the kinds of strings that would come in would be:

15 SE NORFOLK
5 NNE OAKLAND
1 S LOS ANGELES
1 NW SACRAMENTO
BOSTON

It's basically numbers then directional letters then city name. Sometimes there aren't numbers and letters so I'm checking to see first and then just deleting them with preg_replace if there are (I just need the city name).

Here's the expression I have that works:

$location = preg_replace('/^[\d]+[\s]+[a-zA-z]+[\s]/', '', $string);

I know with regex there are a bunch of different ways to different things so I'm curious if there's a more efficient way to do what I'm doing.

Leave out the square brackets:

^\d+\s+[A-Z]+\s+

Square brackets are used for "character classes", like

[A-Z]

which matches exactly one letter out of the range A to Z.

\d already is a class: all the numbers.


Merge Sort implemented using iterators #include <iterator>
#include <memory>
#include <algorithm>

template<typename RandomIt>
void sub_merge(RandomIt begin, RandomIt mid, RandomIt end) {
  // create copy of input array;
  const auto left_size = std::distance(begin, mid);
  const auto right_size = std::distance(mid, end);

  auto left = std::make_unique<typename std::iterator_traits<RandomIt>::value_type[]>(left_size);
  auto right = std::make_unique<typename std::iterator_traits<RandomIt>::value_type[]>(right_size);

  const auto left_begin = left.get();
  const auto left_end = left_begin + left_size;
  const auto right_begin = right.get();
  const auto right_end = right_begin + right_size;

  std::copy(begin, mid, left_begin);
  std::copy(mid, end, right_begin);

  // merge until one array is completed
  auto left_iter = left_begin;
  auto right_iter = right_begin;
  auto arr_iter = begin;

  while (left_iter < left_end && right_iter < right_end) {
    if (*left_iter < *right_iter) {
      *arr_iter = *left_iter;
      left_iter++;
    } else {
      *arr_iter = *right_iter;
      right_iter++;
    }
    arr_iter++;
  }

  // copy remaining array over
  std::copy(right_iter, right_end, arr_iter);
  std::copy(left_iter, left_end, arr_iter);
}

template<typename RandomIt>
void merge_sort(RandomIt begin, RandomIt end) {
  if (begin < end - 1) {
    const auto mid = begin + std::distance(begin, end) / 2;
    merge_sort(begin, mid);
    merge_sort(mid, end);
    sub_merge(begin, mid, end);
  }
}

My testing shows this to be correctly implemented, however I want to know if there is anywhere I could be more efficient. I also have no way to prove if my templates are used correctly. I also do not know which Iterator type is appropriate for this. STL uses RandomIterator so I went with that but I think InputIterator or possibly ForwardIterator would be suitable.

Naming

sub_merge is weird, as it doesn't match up at all with the meaning of the english word "submerge". I get its origin ("subroutine merge"), but why not simply call it merge instead?

Algorithm

This seems like a straightforward top-down implementation of mergesort. However, there are some issues:

Stability

sub_merge doesn't preserve the relative order of elements that compare equal. However, this can easily be fixed by changing the comparison operator in if(*left_iter < *right_iter) from < to <=.
Allocations + copies

Since each sub_merge call creates its own scratch space, there are \$2n\$ allocations in total. This could be replaced by creating one scratch buffer at the highest level instead.

A benefit of doing so is the reduction in the number of necessary copies. Currently, sub_merge has to copy each element into the scratch space and then back into the original range. One of those copies could be skipped using a preallocated scratch buffer and alternating between it and the original range on different recursion levels, at the cost of one fixed copy when creating the scratch buffer.

Implementation

Why not use std::vector<std::iterator_traits<RandIter>::value_type> instead of manually managing the memory via those std::unique_ptrs?

Iterator categories

You are correct that a ForwardIterator would technically work for merge sort. However, using those would mean that you'd need 1.5 extra passes over the range for each midpoint calculation (1 pass for the std::distance call, and half a pass to find the mid iterator).

This wouldn't raise the runtime complexity into a worse category, but there are more efficient sorting strategies for those cases that don't require that many passes (especially since those passes usually aren't that cheap in data structures that only have ForwardIterators or BidirectionalIterators).

That's why RandomAccessIterators are preferred for merge sort.

  However, a lot of code would need to be changed for that to work, as ForwardIterators only need to support a small subset of the operations a RandomAccessIterator has to provide (i.e. they only have operators *, ->, ++, == and !=, so no comparisons using < or iteration using -).

So, why won't InputIterators work? Because merge sort requires multiple passes over the input/output range, and InputIterators don't guarantee that they can do so.

Improved version

With some improvements, the implementation could look something like this:

#include <vector>
#include <type_traits>

template<typename Iter>
constexpr bool is_forward_iterator_v = std::is_base_of_v<std::forward_iterator_tag, typename std::iterator_traits<Iter>::iterator_category>;

template<typename ForwardIter>
ForwardIter middle_iterator(ForwardIter first, ForwardIter last) {
    static_assert(is_forward_iterator_v<ForwardIter>, "middle_iterator requires at least a ForwardIterator to work properly");

    auto dist = std::distance(first, last);
    if(dist == 0) return first;

    return std::next(first, (dist + 1) / 2);
}

template<typename InIter1, typename InIter2, typename OutIter>
OutIter merge(InIter1 left, InIter1 left_end, InIter2 right, InIter2 right_end, OutIter out) {
    while(left != left_end && right != right_end) {
        if(*left <= *right) {
            *out++ = *left++;
        } else {
            *out++ = *right++;
        }
    }

    if(left != left_end) return std::copy(left, left_end, out);
    else return std::copy(right, right_end, out);
}

template<typename Iter, typename Iter2>
void merge_sort(Iter first, Iter last, Iter2 scratch, Iter2 scratch_end) {
    const auto mid = middle_iterator(first, last);
    if(mid != last) {
        const auto scratch_mid = middle_iterator(scratch, scratch_end);

        merge_sort(scratch, scratch_mid, first, mid);
        merge_sort(scratch_mid, scratch_end, mid, last);

        merge(scratch, scratch_mid, scratch_mid, scratch_end, first);
    }
}

template<typename Iter>
void merge_sort(Iter first, Iter last) {
    auto scratch_buffer = std::vector<typename std::iterator_traits<Iter>::value_type>(first, last);

    merge_sort(first, last, scratch_buffer.begin(), scratch_buffer.end());
}

  To Do:

  Better assert iterator requirements
  Add noexcept specifications where possible
  Maybe add support for move-only types?


Calculate and use a linear equation based on sets of x and y values The following asks for 2 sets of data (with corresponding x and y values), calculates a linear equation that matches the data as closely as possible, then allows you to "play around" with the equation by substituting x values.

import Data.Char

slope :: [Float] -> [Float] -> Float
slope xs ys
    | xN /= yN = error $ "x len: " ++ show xN ++ " y len: " ++ show yN
    | otherwise = (xN * (sum $ coorProds xs ys) - xSum * ySum) /
        (xN * (sum $ squares xs) - (xSum * xSum))
    where
        (xN,yN) = (fromIntegral $ length xs, fromIntegral $ length ys)
        (xSum,ySum) = (sum xs, sum ys)

intercept :: [Float] -> [Float] -> Float
intercept xs ys
    | xN /= yN = error $ "x len: " ++ show xN ++ " y len: " ++ show yN
    | otherwise = (ySum - (b * xSum)) / xN
    where
        b = slope xs ys
        (xN,yN) = (fromIntegral $ length xs, fromIntegral $ length ys)
        (xSum,ySum) = (sum xs, sum ys)

getEquation :: [Float] -> [Float] -> ((Float -> Float),Float,Float)
getEquation xs ys = (\x -> (inter + (b * x)) , inter, b)
    where
        inter = intercept xs ys
        b = slope xs ys

coorProds :: [Float] -> [Float] -> [Float]
coorProds xs ys = map (\(x,y) -> x * y) $ zip xs ys

squares :: [Float] -> [Float]
squares = map (\x -> x * x)

cutIntoPair :: String -> (String,String)
cutIntoPair = (\(x,y)-> (x,drop 1 y)) . break (== ' ')

isFloat :: String -> Bool
isFloat = all (\c -> isDigit c || c == '.')

toFloat :: String -> Float
toFloat s
    | isFloat s = read s :: Float
    | otherwise = error $ show s ++ " is not a number"

getPairs :: IO ([Float],[Float])
getPairs = do
    i <- getLine
    let (x,y) = cutIntoPair i
    if isFloat x
        then do
            (xs,ys) <- getPairs
            return ((toFloat x : xs), (toFloat y : ys))
        else return ([],[])

useEquation :: (Float -> Float) -> IO ()
useEquation e = do
    putStr "When x = "; x <- getLine
    putStrLn $ "y = " ++ (show $ e (toFloat x)) ++ "\n"
    useEquation e

showEquation :: Float -> Float -> String
showEquation i b = "y = " ++ show i ++ " + " ++ show b ++ "x"

main = do
    putStrLn $ "Enter x and y values seperated by a space\n\t" ++
        "Then type a non-number to continue"
    (xs,ys) <- getPairs
    let (linEq,i,b) = getEquation xs ys
    putStrLn $ showEquation i b
    putStrLn "Enter x values to get their calculated y values"
    useEquation linEq

I'm looking for general feedback, and suggestions regarding the following points:

getEquation has a couple issues.

I was able to write it point-free when the function only returned the equation, but now that I'm wrapping everything in a tuple, so I can also return the calculated slope and intercept values (to show the equation later), it's not behaving as I expected. I tried writing it as a section,  like (inter + (b *), but that attempts to apply + to the function (b*), which obviously results in a "No instance" error. My solution was to just wrap it in a lambda, but that's quite ugly, in my opinion.
Is there a better way of dealing with the need to have the slope and intercept after the function is "constructed" than passing them back with the equation? The optimal solution would the ability to extract them out of the function, but I'm pretty sure that's not possible.

cutIntoPair looks ugly too. It splits a string at the first space, then returns the 2 parts. Break leaves the space in the second slot though, so to remove it, I resorted to passing the result to a lambda that leaves the first part of the tuple the same, but drops the first char of the second slot. I'd like to know if there is a cleaner way to go about this task.
The slope and intercept functions are slightly messy, but I had to cram a lot of math into the space. Tips on how to format it neater would be appreciated.

To use it, type x and y values separated by a space, pressing enter between sets. When you're done entering, type a non-number, like so:

2 4
4 8
12 24
k

I'd structure your program in a slightly different way. First, instead of passing around two arrays of float, why don't you introduce a Point data structure and work with it?
It would save you from checking that you get passed two array of the same length, which looks quite neat to me.

I think you could also consider introducing a Coefficients data structure to hold your pair of slope and intercept value. If you do that it will be much clearer what your function does.

Since you eventually want to have a function you can play with, you could create a toFunction :: Coefficients -> Float ->Float. In this way you decouple the computation of the coefficients that best fit with your data and the construction of the corresponding curve. This enables you to play not only with the curves you fit from data but also with curves you can define from their coefficients.

I think that a nicer way to compute the value could be by putting as much math as possible in some temporary variables you define in the where block. That could allow you to separate the high level computation you need to perform with all the other smaller steps required to compute some other intermediate results you need.

If you apply the changes I suggested you should come up with code similar to the following:

type Point = (Float, Float)
type Coefficients = (Float, Float)

toFunction :: Coefficients -> Float -> Float
toFunction (s, i) x = s * x + i

slope :: [Point] -> Float
slope [] = error "Empty list of points"
slope (_ : []) = error "Single point"
slope points = (n*sumCoorProds - (sumX*sumY))/ (n*sumSquares - (sumX*sumX))
  where
    n = fromIntegral $ length points
    (xs, ys) = unzip points
    sumCoorProds = sum $ map ( \(x, y) -> x * y ) points
    sumSquares   = sum $ map ( \(x) -> x * x ) xs
    sumX         = sum xs
    sumY         = sum ys

intercept :: [Point] -> Float
intercept points = (sumY - (s * sumX)) / n
      where
      (xs, ys) = unzip points
      n = fromIntegral $ length points
      s = slope points
      sumX = sum xs
      sumY = sum ys

getCoefficients :: [Point] -> Coefficients
getCoefficients points = (slope points, intercept points)


Replacing Perisan and Arabic digits I'm using this function to replace UTF-8 characters representing numbers in text with 'normal' digits.

I'm wondering if this is optimized code since this is using two str_replace()s.

public static function convertArabicNumbers($string) {
    //$engish = array(0,1,2,3,4,5,6,7,8,9);
    $persian = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
    $arabic = array('٠','١','٢','٣','٤','٥','٦','٧','٨','٩');
    $num = range(0, 9);
    return str_replace($arabic, $num, str_replace($persian, $num, $string));
}

You are right that this is not optimal (performance wise). You may want to consider two things:

static variables (those values in there are constants no need to recreate them every time).
merging the arrays.

Consider the following code:

public static function convertArabicNumbers($string) {
    //$engish = array(0,1,2,3,4,5,6,7,8,9);
    static $fromchar = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹',
                             '٠','١','٢','٣','٤','٥','٦','٧','٨','٩');
    static $num = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
    return str_replace($fromchar, $num, $string);
}

I am really uncertain about the right-to-left characters.... should they be transformed in the same way as the left-to-right ones? You're the expert on that one.

Still, you get the idea....


Turning 1D array to 2D array in TicTacToe To check a win in my TicTacToe game, I have created a 2D array that contains all the combination that a game can be won in, like so:

 private int[][] winningCombinations = new int[][] {
            {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
            {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
            {0, 4, 8}, {2, 4, 6}             //diagonal wins
        };
JButton buttons[] = new JButton[9]; // This is what I had when working with 1D array
JButton buttons[][] = new JButton[3][3]; // This is what I have now

then I have used for loop to loop through this array like this:

/*Determine who won*/
        for(int i=0; i<=7; i++){
            if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
                buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
                !buttons[winCombinations[i][0]].getText().equals("")) {
                win = true;
            }
        }

        for(int i = 0; i < 3; i++){
            if (buttons[i*3].getText().equals("X") && buttons[i*3+1].getText().equals("X") && buttons[i*3+2].getText().equals(""))
                buttons[i*3+2].setText("O");
                win = true;
            }

Everything works, but now I am planning to convert my code from 1D to 2D array, but when I convert this to 2D, it does not work. I might be wrong, but this is how I attempted to convert to 2D:

for(int i=0; i<=7; i++){
    if( buttons[winCombinations[i][0]][winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]][winCombinations[i][1]].getText()) &&
        buttons[winCombinations[i][1]][winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]][winCombinations[i][2]].getText()) &&
        !buttons[winCombinations[i][0]][winCombinations[i][0]].getText().equals("")) {
        win = true;
    }
}

Matrices ... 1D or 2D format

In computing it is common to have matrix-like problems. Graphics, mathematics, and Tic-Tac-Toe.

It is often easier to have the matrix data stored as a 1D array, or 'flattened'.

Whether you have it as a 1D or a 2D array does not really matter for the functional aspect, but it can often have a really big impact on the readability.

A matrix of M x N dimension would be stored, for example, as :

int[][] matrix = new int[M][N];

To 'visit' all members of that matrix you need to:

for (int r = 0; r < M; r++) {
    for (int c = 0; c < N; c++) {
        // do someting with matrix[r][c];
    }
}

As a flattened matrix, it would be:

int[] matrix = new int[M * N];

To visit the members, it is:

for (int i = 0; i < matrix.length; i++) {
    // do something with matrix[i];
}

When you have complicated indexing, the flattene system can be more efficient.

Additionally, the flattened matrix has interesting memory properties that often leads to better performance on High-Performing Computational clusters.

Converting from one format to the other is relatively simple.

final int width = 3;
matrix1D[row * width + col] = matrix2D[row][col];
matrix2D[i / width][i % width] = matrix1D[i];

Review

In your case, your matrix is small, and you should chose whichever format makes the code most readable.

If you choose a 2D implementation, you should make sure your winning combinations array is expressed as a 2D format....

int[][][] winningcombinations = {
  { {0, 0}, {0, 1}, {0, 2} }, // Top
  { {1, 0}, {1, 1}, {1, 2} }, // Middle
  { {2, 0}, {2, 1}, {2, 2} }, // Bottom
  { {0, 0}, {1, 0}, {2, 0} }, // left
  .......
}

Magic Numbers

Java arrays have a length property. Use it. You have the code:

for(int i=0; i<=7; i++){ .... }

This should be:

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

Code Style

In Java recommended code style puts spaces around operators and reserved words.

for(int i=0; i<=7; i++){ .... }

should be (ignoring the 7)

for (int i = 0; i <= 7; i++) { .... }


Service Layer, using Entity Framework 6.2 I would like you to review a part of my warehouse application, a Service Layer to be exact. The architecture of the program is:

DB --> .Data (EF's DbContext/Entities) --> .ServiceLayer (Business) --> WCF services

I have Repo/UoW patterns implemented in Data (EF's DbConext has it built in). Basically nothing more. Raw DbSets and Entities. The whole magic is being done in Business layer obviously.

In Business layer I have implemented a bunch of Services, like PurchaseOrderService or ReceivingService. The thing is those services can be used by WCF Service directly AND by Business themselves. For example GetItemStatus can be used by WCF Service with the same name "GetItmeStatus" OR it can be used by GetItemQuantity service (because if the Item is Blocked, the Qty is 0). Let me post the code:

public class ItemService
{
    IContextFactory ContextFactory { get; set; }

    public ItemService(IContextFactory contextFactory)
    {
        ContextFactory = contextFactory;
    }

    public ItemStatus GetItemStatus(int itemId, WarehouseContext warehouseContext = null)
    {
        ItemStatus returnedItemStatus = ItemStatus.New;

        //DBContext should be disposed only if it was created here, locally
        bool shouldBeDisposed = (warehouseContext == null);
        if (shouldBeDisposed) warehouseContext = ContextFactory.CreateWarehouseContext();

        try
        {
            returnedItemStatus = warehouseContext.Items.Where(p => p.ItemId == itemId).Status;
        }
        finally
        {
            if (shouldBeDisposed) warehouseContext?.Dispose();
        }

        return returnedItemStatus;
    }

    public int GetItemQuantity(int itemId, WarehouseContext warehouseContext = null)
    {
        int returnedQuantity = 0;

        //DBContext should be disposed only if it was created here, locally
        bool shouldBeDisposed = (warehouseContext == null);
        if (shouldBeDisposed) warehouseContext = ContextFactory.CreateWarehouseContext();

        try
        {
            if (GetItemStatus(itemId, warehouseContext) != ItemStatus.Blocked)
            {
                returnedQuantity = warehouseContext.Items.Where(p => p.ItemId == itemId).Quantity;
            }
        }
        finally
        {
            if (shouldBeDisposed) warehouseContext?.Dispose();
        }

        return returnedQuantity;
    }
}

Of course, this example shows two methods from the same service. It's possible that one service will create another service and calls its function.

I would like you, to review the way I handle optional Context parameter, try finally block instead of pretty using block. This way, I don't have to create DbContext during every trip to the database. I can create a DbContext per Context. When I must get ItemStatus (ItemStatus only) from the WCF (or any other client) layer.. I can do it! and the DbContext will be created and disposed.

How do you like it? Thanks!

How do you like it?

I don't like it ;-)

Because...

This is a repository and should be named ItemRepository
Unless you can prove (with proper profiler results) that reusing the context has a better performance I wouldn't care about it. Because of this opmization your API gets more complicated and confusing. See Performance Considerations (Entity Framework) Actually you might win more performance by disabling change-tracking than by reusing the context.
The ContextFactory property is public and it has a setter. Why? It's already set via the constructor. Make it either a private field or remove the constructor because a constructor informs me that this value is mandatory. For this class however it's both. Mandatory for creation but it can be set to null after creating the ItemService. This is very confusing.
You don't need any of the helper variables returnedItemStatus or returnedQuantity. Just return the value where you get it.
ItemStatus.New is another confusing thing. If I try to GetItemStatus and it does not exist then I expect it to either throw or return a status that tells me the item actually does not exist. How can it be New if it wasn't found? The same applies to the other method. If the item does not exist I expect either an exception or a -1 for the quantity that informs me that the item does not exist. Saying 0 for something that isn't even there is just wrong. It makes me think it could be or was there but is sold out. So, does a 0 mean you don't offer it at all or it's currently not in stock? 0 is not a very useful result in this case. You should better differentiate both cases.
Here I'm done reviewing your code because you cannot return a single Status from this query .Where(p => p.ItemId == itemId).Status which makes me think this is not your real service...
One last thought... instead of querying each item property at a time with queries like these... why don't you simply get the item or an info-object about it. I would save you a lot of database trips.


LeetCode 49: Group Anagrams I'm exceeding the time limit for a 10,000 word test case provided on LeetCode:

  Given an array of strings, group anagrams together.

  For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
  Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

  Note: All inputs will be in lower-case.

Any suggestions on how I could speed this up a little bit?

public HashMap<String, List<Integer>> createMap(String[] strs)
{
  HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();

    for(String s: strs)
    {
     char[] charArray = s.toCharArray();
     Arrays.sort(charArray);
     String sortedString = new String(charArray);

     if(map.containsKey(sortedString))
     {
        List<Integer> pos = map.get(sortedString);
        pos.add(Arrays.asList(strs).indexOf(s));
        map.put(sortedString, pos);
     }

    else
    {
        List<Integer> pos = new ArrayList<Integer>();
        pos.add(Arrays.asList(strs).indexOf(s));
        map.put(sortedString, pos);
    }
  }

  return map;
}

public List<List<String>> groupAnagrams(String[] strs) {

  HashMap hm = createMap(strs);

  List<List<String>> anagrams = new ArrayList<List<String>>();

  for(Object k: hm.keySet())
  {
    String key = k.toString();
    ArrayList pos = (ArrayList)hm.get(key);

    List<String> a = new ArrayList<String>();
    for(Object p : pos)
    {
      int idx = Integer.parseInt(p.toString());
      a.add(strs[idx]);
    }
    anagrams.add(a);
  }
  return anagrams;
}

Why so slow

It's important to consider the time complexity of all the operations in your program.

Take a closer looks at this part I extracted from your code:

for(String s: strs)
{
 // ...

    pos.add(Arrays.asList(strs).indexOf(s));

For each s, converting a String[] to a List<String>, in order to use the indexOf method to find the index of s? That doesn't sound so good. How about making that a counting loop?

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

    pos.add(i);

But why use indexes at all? Why not make this method return a Map<String, List<String>> instead?

for (String s : strs) {
    // ...

    pos.add(s);

If you do that, then the implementation of the other method becomes simply:

public List<List<String>> groupAnagrams(String[] strs) {
    return new ArrayList<>(createMap(strs).values());
}

Good practices

The code violates many good practices and common conventions:

Never use raw types, for example use HashMap<String, List<String>> instead of just HashMap without type parameters
Prefer to declare variables with interface types, for example Map<String, List<String>> instead of HashMap<String, List<String>>
Use the diamond operator <> when possible, for example new HashMap<> instead of new HashMap<String, List<String>>
Use consistent indentation, and please place braces they way I did in my examples above


Feedback on a Small Trivia Game in C# I wanted to get some feedback concerning the program. It's console based and in C#. If I should try to add constraints like making sure only the 4 questions shown are able to be typed in and nothing else or uses a number system to retrieve and set answers and if to add a randomization. If I am to add randomization how am I to do so with string and methods? Was thinking of loading it from an external file where questions and answers would be read, randomized and printed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Trivia_Game
{
class Questions
{
    public void Question1()
    {
        List<string> Q1 = new List<string>();
        Q1.Add("Paris");
        Q1.Add("Spain");
        Q1.Add("England");
        Q1.Add("Portugal");

        string Answer1="";

        string TrueAnswer = "Paris";

            for (int i = 0; i < Q1.Count; i++)
            {

                Console.Write(Q1[i] + ", ");

            }

            Console.WriteLine();

        while (Answer1 != TrueAnswer)
        {
            Console.WriteLine("What is the Capital of France?");
            Answer1 = Console.ReadLine();
            Console.WriteLine();

            if (Answer1 != TrueAnswer)
            {
                Console.WriteLine("Wrong answer");
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("Correct");
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Questions questions = new Questions();

        questions.Question1();

        Console.ReadKey();
    }
}
}

You can create a Question class which include the question, the answers, and the right answer.

Then you create a list of questions hard coded / from file / from server ( what ever you want)

Convert the code in Question 1 to be more generic and work with the Question class.


Elegant way of making a List of an attribute from a list of objects containing that attribute If this is my class:

class Something
{
    UUID id;
    // Other members
}

Given a List<Something> things and I want to get a List<UUID> ids, this is what I usually do:

List<UUID> ids = new ArrayList<UUID>
for(Something thing : things)
{
     ids.add(thing.getId());
}
return ids;

Is there a more elegant way of doing this in Java 6?

[I googled for this pattern, however, didn't find much as I think I lacked the right keywords]

When I have encountered this type of problem, it typically involves creating some ugly code in your method to do that iteration. In essense, there is no way to do things any differently, you have to iterate, and collect the UUID's (but, you could wait for Java8 and do lambdas ..).

But, there is no reason why you have to do it outside of the Something class. A trick you can do which keeps like-code together, is to put a static method on Something, which does:

public static final List<UUID> getUUIDs(Iterable<Something> somethings) {
    List<UUID> ids = new ArrayList<UUID>();
    for(Something thing : somethings) {
        ids.add(thing.getId());
    }
    return ids;
}

Now that code is stashed away somewhere useful, and when you need it you can:

for (UUID uuid : Something.getUUIDs(things) {
    ... do something ....
}


Writing the "Camel Game" with Python I'm currently on Ch 4 Lab 4 in Programming Arcade Games with Python and Pygame.

Any feedback on how I could improve the code would be awesome. I'm using Python IDLE 3.4.3.

import random

print("Welcome to Camel!")
print("""You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down! Survive your desert trek and out run the natives.""")
print()

#variables
milesTraveled = 0
thirst = 0
camelFatigue = 0
nativesTraveled = -20
canteen = 3
done = False

#start main loop
while not done:
    nativesBehind = milesTraveled - nativesTraveled
    fullSpeed = random.randrange(10, 21)
    moderateSpeed = random.randrange(5, 13)
    print("""
    A. Drink from your canteen.
    B. Ahead at moderate speed.
    C. Ahead full speed.
    D. Stop for the night.
    E. Status check
    Q. Quit.""")
    print()
    userInput = input("Your choice? ")
    if userInput.lower() == "q":
            done = True

#status
    elif userInput.lower() == "e":
        print("Miles traveled: ",milesTraveled)
        print("Drinks in canteen: ",canteen)
        print("Your camel has ",camelFatigue,"amount of fatigue.")
        print("The natives are ",nativesBehind,"miles behind you.")
#stop for night
    elif userInput.lower() == "d":
        camelFatigue *= 0
        print("Your camel feels refreshed and happy his fatigue is now ",camelFatigue)
        nativesTraveled += random.randrange(7, 15)
#move full speed
    elif userInput.lower() == "c":
        print("You traveled ",fullSpeed,"miles!")
        milesTraveled += fullSpeed
        thirst += 1
        camelFatigue += random.randrange(1, 4)
        nativesTraveled += random.randrange(7, 15)
        oasis = random.randrange(1, 21)

#move moderate speed
    elif userInput.lower() == "b":
        print("You traveled ",moderateSpeed,"miles!")
        milesTraveled += moderateSpeed
        thirst += 1
        camelFatigue += 1
        nativesTraveled += random.randrange(7, 15)
        oasis = random.randrange(1, 21)

        #drink canteen
    elif userInput.lower() == "a":
        if canteen == 0:
            print("You're out of water.")
        else:
            canteen -= 1
            thirst *= 0
            print("You have ",canteen,"drinks left and you are no longer thirsty.")

#not done check
    if oasis == 20:
        camelFatigue *= 0
        thirst *= 0
        canteen = 3
        print("You found an oasis! After taking a drink you filled your canteen and the camel is refreshed.")
    if nativesBehind <= 15:
        print("The natives are drawing near!")
    if milesTraveled >= 200 and not done:
        print("You made it across the desert, you win!")
        done = True
    if nativesTraveled >= milesTraveled:
        print("The natives caught and beheaded you.")
        print("You're dead!")
        done = True
    if thirst > 4 and thirst <= 6 and not done:
        print("You are thirsty")
    if thirst > 6:
        print("You died of dehydration!")
        done = True
    if camelFatigue > 5 and camelFatigue <= 8 and not done:
        print("Your camel is getting tired.")
    if camelFatigue > 8:
        print("Your camel is dead.")
        done = True

Bad instructions

Perhaps the lab is instructing you specifically to write code in a certain way just for learning purposes, but there is some questionable advice in the instructions that I would recommend disregarding.

Printing the game instructions using multiple print statements is poor practice.  Combining the instructions into one long triple-quoted string is more readable and efficient.

Introducing a done flag variable is a bad idea in general.  If your goal is to direct the execution of code in a loop, use statements like continue, break, return, or raise.  Setting a variable just to have it tested later is needlessly indirect.  In fact, I would say that for this exercise, a done flag fails to capture enough state information for a realistic game.  (More on that below.)

Logic

The input is case-insensitive.  To avoid code repetition, you should immediately normalize the input to lowercase (or uppercase, as the instructions suggest):

user_choice = input("Your choice? ").upper()

There are five menu options, plus the "Quit" option.  Of those five, two are "instantaneous", and three involve the passage of time.  Of the three options that involve passage of time, two cause you to cover some distance.  The code should therefore be structured such that similar code is placed together.  Also, you should avoid generating and discarding random numbers that you aren't going to use (for example, fullSpeed = random.randrange(10, 21) when the user hasn't even decided to make a move).

# Quit
if user_choice == "Q":
    break

# Status check
elif user_choice == "E":
    print(…)

# Drink from canteen
elif user_choice == "A":
    if canteen == 0:
        print("You're out of water.")
    else:
        canteen -= 1
        thirst = 0
        print(…)

# Stop for the night
elif user_choice == "D":
    natives_traveled += random.randrange(7, 15)
    camel_fatigue = 0
    print(…)

# Moderate speed
elif user_choice == "B":
    natives_traveled += random.randrange(7, 15)
    miles_traveled += random.randrange(5, 13)
    camel_fatigue += 1
    thirst += 1

# Full speed
elif user_choice == "C":
    natives_traveled += random.randrange(7, 15)
    miles_traveled += random.randrange(10, 21)
    camel_fatigue += random.randrange(1, 4)
    thirst += 1

It's odd how you write variable *= 0 when you could just set variable = 0.

By my interpretation, it should not be possible to stumble across an oasis while resting for the night.  It would be even more realistic (and easier to code) if the probability of finding an oasis were proportional to the distance covered, but I don't get to make the rules.

When evaluating the situation at the end of the loop, I would place the position checks first, then the health checks, then any applicable warnings.  You don't really care about the natives drawing near or finding an oasis if you've already crossed the finish line.  You can also simplify the thirst and fatigue checks if you test for death first.  (By the way, in Python, you can also write double-ended inequalities like 5 < camelFatigue <= 8.)

# Position checks
if miles_traveled >= 200:
    print("You made it across the desert!")
    break
elif natives_traveled >= miles_traveled:
    print("The natives caught and beheaded you.\nYou're dead!")
    break

# Health checks
# 1 in 20 chance of finding an oasis
if user_choice != "D" and random.randrange(20) == 0:
    camel_fatigue, thirst, canteen = 0, 0, 3
    print("You have found…")
elif thirst > 6:
    print("You died of dehydration!")
    break
elif camel_fatigue > 8:
    print("Your camel is dead.")
    break

# Warnings
if natives_traveled >= miles_traveled - 15:
    print("The natives are drawing near!")
if thirst > 4:
    print("You are thirsty")
if camel_fatigue > 5:
    print("Your camel is getting tired.")


Business Letter in HTML Here's my first effort at reformation: a business letter I wrote for a friend.  I would appreciate a review.  (Yes, I know this is a trivial example and it would be much more beneficial to have something reviewed that is more complicated.  But I want to nip bad practices in the bud now, before they become embedded in me.)

<!DOCTYPE HTML>

            Lopes de Almeido, Evanildo

            Bl&auml;siring 161

            4057 Basel

            01 Dezember, 2012

            Betreff:  Vertretung waehrend Reise

                Sehr geehrte Frau Graf,

                Ich fliege nach Brasilien am 29. Dezember 2012 f&uuml;r 6 Wochen.
                Meine Nichte kann mich vertreten.  Sie arbeitet sehr gesissenhaft.
                Sie heisst Yasmin.  Ihre Nummer ist xxx.

            Freundliche Gr&uuml;sse

            Evanildo Lopes do Almeida

            Hauswart Binningerstrasse 19/23

CSS

Since this is a single document, not a webpage of a website, it's fine to use internal CSS in the style element instead of linking to an external stylesheet. However, if you plan to write more letters in the future, you should create a stylesheet that includes all the shared styles that are typical for a letter and link to it from each letter (<link rel="stylesheet" href="letter.css" />).

You could name your classes more meaningful, but this is only a good practice, not a requirement.

You could omit the class on body.

Encoding/Charset

You should add the encoding to the document. If you want to use UTF-8 (recommended), add <meta charset="utf-8" /> as the first child of the head element.

title element

You are missing the title element, which is required. Add it as child of head: <title>Vertretung während Reise – 1. Dezember 2012</title>

Return address

The use of
 is correct here. However, the date is not part of the address, and therefor it shouldn't be separated by br. Put the date in its own element instead. HTML5 offers the time element.

Because this is your address (and not the recipient address), you should enclose it in the address element.

You could enclose the return address and the date in the header element. It might also be possible to enclose the return address in a footer element and the time in a header (probably together with the h1), but this could be overkill ;)

Subject line / Betreff

Instead of using a meaningless div for the subject, you should use h1 here, as it is the heading of the whole document.

Salution / Anrede

It's arguably if the salution is a paragraph on its own, or if it is part of the first paragraph. I think when followed by a comma, it should be part of the following paragraph. But this is not undisputed (I have no detailed knowledge about the semantics of a letter).

Greets

The use of the br element to separate the greeting from your anme is correct here. But don't use several br elements just because you want to add more spacing. Use only one and apply a class to it, so that you can give it a higher vertical margin (CSS).

Also, include this in a p instead of a div.

Example

So your letter could look like:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Vertretung während Reise – 1. Dezember 2012</title>
    <link rel="stylesheet" href="letter.css" />

      <address class="return-address">
        Lopes de Almeido, Evanildo

        Bläsiring 161

        4057 Basel

      </address>

      <time datetime="2012-12-01">01 Dezember, 2012</time>

      Betreff:  Vertretung waehrend Reise

          Sehr geehrte Frau Graf,

          Ich fliege nach Brasilien am 29. Dezember 2012 für 6 Wochen.
          Meine Nichte kann mich vertreten.  Sie arbeitet sehr gesissenhaft.
          Sie heisst Yasmin.  Ihre Nummer ist xxx.

          …

        Freundliche Grüsse

        Evanildo Lopes do Almeida

        Hauswart Binningerstrasse 19/23


Basic Java CLI terminal calculator I have asked a question on how to make a CLI calculator accept infinite numbers until you specify that you want the answer. Now I have figured out how to do it, but I do really want to know how can I improve my code.

package ribchinski;

import java.util.Scanner;

public class Calculator {
    public static double answer;
    public static Scanner in = new Scanner(System.in);
    public static boolean done = false;

    public static void main(String[] args) {

        System.out.println("Enter your expression:");
        System.out.println("Num: ");
        double firstNum = in.nextDouble();
        in.nextLine();

        while (!done) {
            System.out.println("Operator: ");
            String operand = in.nextLine();

            if (operand.equals("=")) {
                break;
            }
            System.out.println("Num: ");
            double secondNum = in.nextDouble();
            in.nextLine();

            calculate(firstNum, operand, secondNum);
            firstNum = answer;
        }
        System.out.println("Answer: " + answer);
    }

    public static void calculate(double num1, String equ, Double num2) {

        switch (equ) {

        case ("+"):
            answer = (num1 + num2);
            break;

        case ("-"):
            answer = (num1 - num2);
            break;

        case ("*"):
            answer = (num1 * num2);
            break;

        case ("/"):
            answer = (num1 / num2);
            break;
        }
    }
}

Any comments on this would be helpful!

Nice solution.  This code is pretty legible, which is great if you have to debug anything.  There are a few simple ways you can make your program more user-friendly and resistant to user error.

Input:

For the user, it can be tedious to type in their values on every line, always being asked for

Num:
Operator:
Num:
Operator:
   ...

Can you use in.nextDouble() and in.next(".") to read in all of your numbers and operators at once, from a line like 10+9-7 or 10+9-7=?  in.next(String pattern) matches a regular expression, and . is the pattern for any single character.

Error Handling:

What happens if the user types in a bad operator?  If someone tries to ask for 11+10_9, the operation is ignored in this case.  Instead of getting the result of 11+10-9 = 12, they could get a result of 21 without realizing there was a mistake.  A good way to protect against that is to use a default: statement in your switch block.  A way to handle these errors and let the program or the user know there was a mistake is by writing

default: throw new IllegalArgumentException(equ + " is not a valid operator");

Object Oriented Programming:

Generally, static variables should be reserved for variables that are shared between multiple instances of a class, and any other variables should be made local or non-static.  The static variables you've defined here work properly, but reorganizing the methods and changing the variables into local ones will make it easier to add functionality to this calculator later.

public static double answer;

Rather than saving the answer in a static or object-level variable, you can return it from your functions.  This lets you keep more careful track of what makes changes to it.  Imagine if you had a lot of different functions like calculate that incrementally update the answer every time they execute.  If you started seeing the wrong answer due to a bug in the code, it could be difficult to trace it to the broken function.

To handle answer the object-oriented way, rename main() to whatever you like, change both of your functions from void to double type, and return the partial answer and the end answer from each of them, handling them locally.  You can make a new main() that calls your renamed function and handle the printing of the answer in main() instead of the function that does the work.

public static boolean done = false;

done is never actually changed or used.  while(true) is functionally equivalent to the loop that you wrote.  This is a fairly common pattern, and there are a few ways to go about organizing it.  Yours is handy because the variable done communicates that this loop will continue until something is 'done'.  The best place to explain to the reader how a while() loop is supposed to terminate is right there in the condition.

One more descriptive (but also less clean) way to write that condition would be

String operand;
while((String operand = in.nextLine()) != '='){

This assigns the operator to operand and performs the comparison without the need for a break statement.  You can use a do-while loop to handle the first number and print "Operator: " to the console before reading operand, if you like.

public static Scanner in = new Scanner(System.in);

This is often tolerated as a static variable, since we're very unlikely to change the fact that we're reading from System.in in the middle of our calculations.  On the other hand, in doesn't need to be static, and since it's a resource that should be closed when we're done with it, the best practice is to make it a local variable or manage it carefully as needed.  The object-oriented approach is to use a loosely-coupled function like readExpression() for your input, and then let all of the calculation happen in a different function.

You might also want to be consistent with your arguments in

public static void calculate(double num1, String equ, Double num2){

double is a primitive type, while Double is a class.  That distinction won't cause a logical error here, but consistency always helps when a program grows larger and more complex.

Order of Operations:

Your program handles each step of the calculation correctly, but it doesn't understand Order of Operations.  That's a more complex concept that you'll have to look at a whole expression for instead of being able to handle each operation piece by piece.

The fully object-oriented solution is to treat the expression and the individual operations as their own objects and apply logic to those objects piece by piece.  You could, for instance, create a list of numbers and operations, and scan through that list, applying the highest-priority (multiplication and division in this case) operations first.

The fully functional solution is to scan the expression and use recursion to decide which numbers need to into calculate() first, returning the results of each calculate() step up until the base function returns the final answer.

There are many ways to do it, and you can think about how you'd like to implement it in your calculator


Check duplicate items in Mongodb I need to query MongoDB and check if an item exists or not:

class MongoDBPipeline(object):

    def __init__(self):
        connection = pymongo.MongoClient(
            settings['MONGODB_SERVER'],
            settings['MONGODB_PORT']
        )
        db = connection[settings['MONGODB_DB']]
        self.collection = db[settings['MONGODB_COLLECTION']]

    def process_item(self, item, spider):
        dup_check = self.collection.find({'image':item['image']}).count()
        if dup_check == 0 :
            self.collection.insert(dict(item))
            log.msg("Image added to MongoDB database!",
                     level=log.DEBUG, spider=spider)
            print "image Added!"
        else:
           print "Image Exist"
        return item

For now it works, but I want to know if I am doing it the right way or if there is a better solution.

Method

The fastest way to check if an item into a MongoDB is unique (and if it isn't, not insert it) is to create a unique index on the related columns and catch the error upon insertion time.

Watch more here.

MongoDB - Features

Maybe this would be OT, but I would like to let you know all this:

MongoDB is inconsistent by default. The documentation claims "strong consistency," but the default implementation considers an operation "complete" as soon as it is queued in the send buffer of a client, even before it has been seen by any node. There is a big discrepancy between the discussion in Mongo blogs and the default implementation in the code. You have to take extra measures to ensure that an update has propagated to all replicas.

I'll list you the advantages and the disadvantages, just to let you make an idea, I don't like so much MongoDB.

Advantages

Lightning fast.
You can perform rich queries, can create on the fly indexes with a single command.
Lightning fast.
Replication is very easy.

Disadvantages

Indexes take up a lot of RAM. They are B-tree indexes and if you have many, you can run out of system resources really fast.
Very unreliable. No single server durability. If something crashes while it's updating 'table-contents' - you lose all you data. Repair takes a lot of time, but usually ends up in 50-90% data loss if you aren't lucky. So only way to be fully secure is to have 2 replicas in different datacentres.

Obviously, there could be some alternative to MongoDB.