Stop repeating myself: Similar pattern used on multiple event handlers My code listens for a number of events, and calls the Google Analytics event tracking function when they fire.

Each event uses a similar pattern. Can I achieve the same functionality without repeating myself?

/*jslint debug:true, browser:true, devel:true nomen:true */
/*global _gaq:true, jquery:true, $:true */

function trackEvent(c, a, l) {

    'use strict'; // JSLint

    //console.log(c, a, l); // Dev only

    _gaq.push(['_trackEvent', c, a, l]);

}

$(function () {

    'use strict'; // JSLint

    var alert, carousel, collapse, modal, tab, tooltip, download, external, mailto;

    // Alerts event handler

    alert = function () {

        var alertButton = $(this),
            category = 'Alerts',
            action = alertButton.next().text(),
            label;

        trackEvent(category, action, label);

    };

    $('body').on('click.alert.data-api', '[data-dismiss="alert"]', alert);

    // Carousel event handler

    carousel = function () {

        var carouselButton = $(this),
            category = 'Carousels',
            action = carouselButton.attr('data-slide'),
            label;

        trackEvent(category, action, label);
    };

    $('body').on('click.carousel.data-api', '[data-slide]', carousel);

    // Collapse event handler

    collapse = function () {

        var category = 'Collapses',
            action = $(this).text(),
            label;

        trackEvent(category, action, label);
    };

    $('body').on('click.collapse.data-api', '[data-toggle=collapse]', collapse);

    // Modal event handler

    modal = function () {

        var category = 'Modals', action, label, activeModal;

        activeModal = $(this).attr('href');
        action = $(activeModal).find('h3').text();

        trackEvent(category, action, label);
    };

    $('body').on('click.modal.data-api', '[data-toggle="modal"]', modal);

    // Tab event handler

    tab = function () {

        var category = "Tabs",
            action = $(this).text(),
            label;

        trackEvent(category, action, label);

    };

    $('body').on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', tab);

    // Tooltip event handler

    tooltip = function () {

        var category = "Tooltips",
            action = $(this).text(),
            label;

        trackEvent(category, action, label);

    };

    $('body').on('mouseenter', '[rel="tooltip"], [rel="popover"]', tooltip);

    // Download link event handler

    download = function () {

        var category = "Downloads",
            action = $(this).attr('href'),
            label;

        trackEvent(category, action, label);
    };

    $('body').on('click', 'a[href$="pdf"], a[href$="doc"], a[href$="docx"], a[href$="rtf"], a[href$="ppt"], a[href$="zip"]', download);

    // Mailto event handler

    mailto = function () {
        var category = 'Mailto',
            action = $(this).attr('href'),
            label;

        trackEvent(category, action, label);
    };

    $('body').on('click', 'a[href^="mailto"]', mailto);

    // External link event handler

    $.expr[':'].external = function (a) {
        var PATTERN_FOR_EXTERNAL_URLS = /^\w+:\/\//,
            href = $(a).attr('href');
        return href !== undefined && href.search(PATTERN_FOR_EXTERNAL_URLS) !== -1;
    };

    external = function () {

        var category = 'External links',
            action = $(this).attr('href'),
            label;

        trackEvent(category, action, label);
    };

    $('body').on('click', 'a:external', external);

});

Id suggest something like:

$('body').on('click.alert.data-api', '[data-dismiss="alert"]', function () {
  trackEvent('Alerts', $(this).next().text());
});

instead of the whole alert code, and similar things for the other items.


Merging the frequency rankings of boys' names and girls' names Problem statement:

The html pages for each year which represents the top 1000 most common Girl and Boy names in the order of their frequency are ranked and provided. And they are ranked based on the frequency of their naming. To elaborate if John is named 101 times and Johan is named 130 times they both are ranked serially as

Johan   1
John    2

To get an idea of this you can refer to this website:
https://www.ssa.gov/oact/babynames/decades/names2010s.html.

In some years, a name appears more than once in the html, but we'll just have to use one number per name. We have to make the algorithm smart about this case and choose whichever number is smaller. After retrieving the names along with their ranks we have to write that data into text file in the following format:

2006
Aaliyah 91
Aaron 57
Abagail 895
Abbey 695
Abbie 650

Implementation: I have retrieved the Girl names and Boy names along with their rankings using regular expressions. Later on I have created two dictionaries boyNames_Rank_Dict, girlNames_Rank_Dict. These dictionaries have basically names of Girls and Boys that are named in that particular year along with their ranks.

Now the challenge is to look for common girls names, boys names and their corresponding ranks. Now if there is a girl and a boy name that are same then the ranks are to be compared and the lowest rank in them has to be selected.

I have written a script for this, below is the code which is an implementation of the requirement:

from time import time
import re

def extract_names(filename):

    boyNames_rank_Dict = {}
    girlNames_rank_Dict = {}
    filestream = open(filename, "r")
    filebuffer = filestream.read()
    filematch_year = re.search(r"Popularity\s([\w.-]+)\s([\d.-]+)", filebuffer)
    year1 = filematch_year.group(2)

    filematch_rank_names = re.findall(r'td>([\d.-]+)	([\w.-]+)	([\w.-]+)', filebuffer)

    for filematch_rank_name in filematch_rank_names:
        x = int(filematch_rank_name[0])
        boyNames_rank_Dict[x] = filematch_rank_name[1]
        girlNames_rank_Dict[x] = filematch_rank_name[2]

    for boy_Rank, boy_Name in boyNames_rank_Dict.items():
        for girl_Rank, girl_Name in girlNames_rank_Dict.items():
            if boy_Name == girl_Name and boy_Rank < girl_Rank:
                 del girlNames_rank_Dict[girl_Rank]
            elif boy_Name == girl_Name and girl_Rank < boy_Rank:
                 del boyNames_rank_Dict[boy_Rank]

    names_Rank_Dict = girlNames_rank_Dict.items() + boyNames_rank_Dict.items()

    file = open("output.txt", 'w')
    file.write(year1)

    for rank, name in names_Rank_Dict:
        strx = name+' '+str(rank)
        file.write('\n')
        file.write(strx)

    file.close()

def timex():
    return round(time()*1000)

def main():
    start_time = timex()
    extract_names("/home/sreedhar/Desktop/google-python-exercises/babynames/baby1998.html")
    end_time = timex()
    print "time taken:%d seconds", (end_time-start_time)

if __name__ == "__main__":
    main()

How can I search for the rank in these Dictionaries when a matching name is found in a more efficient manner. Since when I tried to Profile the time it has taken to execute this program it took 263 milliseconds on a mere 1000 records.

  1017 function calls in 0.263 seconds

When I extrapolate this function to work on a million records the time complexity seems to be out of bounds.

Could some body kindly guide towards a more efficient implementation of this. Also make note that I'm an amateur to Python.

There is a number of things we can do to improve the solution performance-wise, but, most importantly, you don't need two dictionaries for boy and girl names and can have a single dictionary checking for the minimum value on the fly.

What if we use a collections.defaultdict with a default int value being a big number, such as sys.maxint, then we iterate over every row with ranks, boy and girl names and leave minimum ranks only.

We can also use re.finditer() instead of re.findall() to avoid having an extra list created in memory - you may notice the difference on bigger input files:

from collections import defaultdict
from time import time
import re

import sys

def extract_names(filename):
    names = defaultdict(lambda: sys.maxint)

    with open(filename, "r") as f:
        html_data = f.read()

    filematch_year = re.search(r"Popularity\s([\w.-]+)\s([\d.-]+)", html_data)
    year = filematch_year.group(2)

    filematch_rank_names = re.finditer(r'td>([\d.-]+)	([\w.-]+)	([\w.-]+)', html_data)
    for match in filematch_rank_names:
        rank, boy_name, girl_name = match.groups()
        rank = int(rank)

        names[boy_name] = min(names[boy_name], rank)
        names[girl_name] = min(names[girl_name], rank)

    with open("output.txt", 'w') as output_file:
        output_file.write(year + "\n")

        for name, rank in sorted(names.items()):
            output_file.write("{name} {rank}\n".format(name=name, rank=rank))

Note that the results are sorted by the names as required by your Google challenge:

1998
Aaliyah 222
Aaron 37
Abbey 408
Abbie 603
Abbigail 612
Abby 194
Abdul 970
Abdullah 897
Abel 378
...

Here is the simple timeit benchmark for both yours (extract_names) and mine (extract_names_new) solutions showing a dramatic improvement on my machine:

In [1]: %timeit extract_names("baby1998.html")
10 loops, best of 3: 103 ms per loop

In [2]: %timeit extract_names_new("baby1998.html")
100 loops, best of 3: 5.66 ms per loop


User generated filter and content I am writing a (multi) filter that is created when the user enters in the data through wordpress. There can be anywhere between 2 - 10 filters so I need this to be as dynamic as possible. My first approach was to write out a boolean for each possible filter being created and check if it is there or not. Inside the boolean is a click function that checks if the data === "yes" and then add a active class to the item. I rewrote it in a do while, but am not sure if this is the best approach or if they are both bad.

I am not looking for a complete answer or working example, but rather if my way makes sense. If so, why? If not, why not? And an explanation of how I could possible improve it or think of it in a different way.

Manually check

var mem = $(".member");

var filter1 = $(".filter-1");
var filter2 = $(".filter-2");
var filter3 = $(".filter-3");

var memCom1 = $(".member").data("com-1");
var memCom2 = $(".member").data("com-2");
var memCom3 = $(".member").data("com-3");

//  DO THIS FOR ALL POSSIBLE

if (memCom1.length > 0 || filter1.length > 0) {
    filter1.click(function() {
        var com1 = $(this).data("com-1");
        if(com1 === "yes") {
            $(this).addClass(active);
        }
    });
}

if (memCom2.length > 0 || filter2.length > 0) {
    filter2.click(function() {
        var com2 = $(this).data("com-2");
        if(com2 === "yes") {
            $(this).addClass(active);
        }
    });
}

if (memCom3.length > 0 || filter3.length > 0) {
    filter3.click(function() {
        var com3 = $(this).data("com-3");
        if(com3 === "yes") {
            $(this).addClass(active);
        }
    });
}

// would go up to 10

Do while

var mem = $(".member");
var active = "is-active"

do {
    var i = 1;
    if ( $(".member").data("com-"+i).length > 0 || $(".filter"+i).length > 0 ) {
        $(".filter-"+i).click(function() {
            if( $(this).data("com-"+i) === "yes" ) {
                $(this).addClass(active);
            }
        });
    }
  i++;
}

while (i <= mem.length);

The first set of code, while it's straightforward, isn't "ideal" in a sense that you are repeating code. You violate the DRY principle, so let's scratch that for your second code instead.

Now I'm not sure how data is set to the data property. I assume your filters are some kind of custom checkbox which sets com-* data attributes (since your checks are a "yes or not yes").

if (memCom3.length > 0 || filter3.length > 0)

Now as far as I understand, this condition is used only to conditionally attach the click handler. From what I see, the second condition is not required. jQuery objects are collections and jQuery methods iterate through and operate through each. If the collection is empty, the operation does nothing since it iterates through nothing. So your condition can be simplified to

$('.filter').on('click', function(){
  // What happens to each filter
});

One more touch. Your click depends on a certain number. Now if you could just extract that number by itself, possibly using a data-* attribute on the filter.

$(".filter").on('click', function(){
  var element = $(this);
  var number = element.data('number');
  var com = element.data('com-' + number);
  var memberData = $(".member").data('com-' + number).length;
  if(!(com === 'yes' && memberData)) return;
  $(this).addClass(active);
});


Insert values into two different but similar tables I have a combobox with two items. And if one is selected I want to write data to "salary" table and if selected another, to "other" table.

The difference between two code blocks is only one word. I would like to know how I could avoid repeating same code twice.

string myConnection = "datasource=localhost; port=3306; username=root;password=root";
                if (comboBox4.SelectedItem.ToString() == "Salary")
                {
                    string insert = "insert into budget.salary (name, suma) values (@name, @price);";

                    using (var conDataBase = new MySqlConnection(myConnection))
                    using (var cmdDataBase = new MySqlCommand(insert, conDataBase))
                    {
                        cmdDataBase.Parameters.AddWithValue("@name", name);
                        cmdDataBase.Parameters.AddWithValue("@price", suma);
                        conDataBase.Open();
                        cmdDataBase.ExecuteNonQuery();

                        MessageBox.Show("Saved");
                    }
                }
                if (comboBox4.SelectedItem.ToString() == "Other")
                {
                    string insert = "insert into budget.other (name, suma) values (@name, @price);";

                    using (var conDataBase = new MySqlConnection(myConnection))
                    using (var cmdDataBase = new MySqlCommand(insert, conDataBase))
                    {
                        cmdDataBase.Parameters.AddWithValue("@name", name);
                        cmdDataBase.Parameters.AddWithValue("@price", suma);
                        conDataBase.Open();
                        cmdDataBase.ExecuteNonQuery();
                        MessageBox.Show("Saved");

                    }
                }

Declare a method:

public void InsertInto(string table) {
  string myConnection = "datasource=localhost; port=3306; username=root;password=root";
  string insert = "insert into budget." + table + " (name, suma) values (@name, @price);";

  using (var conDataBase = new MySqlConnection(myConnection))
  using (var cmdDataBase = new MySqlCommand(iterpti, conDataBase)) {
    cmdDataBase.Parameters.AddWithValue("@name", name);
    cmdDataBase.Parameters.AddWithValue("@price", suma);
    conDataBase.Open();
    cmdDataBase.ExecuteNonQuery();
    MessageBox.Show("Saved");
  }
}

And change your code to call the method:

if (comboBox4.SelectedItem.ToString() == "Salary") {
    InsertInto("salary");
}
if (comboBox4.SelectedItem.ToString() == "Other") {
    InsertInto("other");
}

Declaring a method that does what you want and then calling the method multiple times instead of repeating your code multiple times is the standard way to avoid duplicating code. This principle is known as encapsulation and is very necessary for writing clean, readable, and reusable code. You should get used to using this technique whenever possible.

More info: https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)


Filtering data on basis of attribute values I am writing code to filter data on basis of attribute values. It is possible that the user can select multiple values.

How can this be better?

Models.Products filter(ViewModel.Filter search,IEnumerable<Models.Products> product)
{
    if (search.filter!= null && search.filter.Count>0)
        {
             var f = search.First();
             var tempProducts = products
                               .Where(c => c.productattributes
                                            .Where(a => a.AttributeId == f.Id && f.Value.Contains(a.Value))
                                            .Any());
             search.filter.Remove(f);
             foreach (var fs in search)
             {
                var p = products.Where(c => c.productattributes.Where(a => a.AttributeId == fs.Id && fs.Value.Contains(a.Value)).Any());
                tempProducts = tempProducts.Union(p);
             }
             products = tempProducts;
        }
}

Filter View Model:

public class Filters
{
    public long Id { get; set; }

    public IEnumerable<string> Value { get; set; }
}

Your code appears to be incomplete but I've provided some ideas below.

Filters Class

I'm looking at your Filters class:

public class Filters
{
    public long Id { get; set; }
    public IEnumerable<string> Value { get; set; }
}

From this, I am assuming that the purpose of this is to hold the Attribute Id (key) and Search Keywords (value). So, I would propose you just use a Dictionary<long, List<string>> -- note that I changed the type of your Search Keywords to a List as I am not seeing any reason within your code example as to why it should/would need to be an IEnumberable type.

That would then change the method:

Method renamed
Parameter updated to use Dictionary instead (per above)

Here is the updated method

public IEnumerable<Product> FilterProductsByAttributeId(
    Dictionary<long, List<string>> filters,
    IEnumerable<Product> products)
{
    // your method contents here
}

Filter Method

I'm not sure why you have a complicated initializer for your tempProducts, but maybe it can be improved to something like this?

public IEnumerable<Product> FilterProductsByAttributeId(Dictionary<long, List<string>> filters, IEnumerable<Product> products)
{
    if (products == null) throw new ArgumentNullException(nameof(products));
    if (filters == null) throw new ArgumentNullException(nameof(filters));

    IEnumerable<Product> result = new List<Product>();
    foreach (var f in filters)
    {
        result = result.Union(products.Where(p => p.ProductAttributes
            .Where(a => a.AttributeId == f.Key && f.Value.Contains(a.Value)).Any()));
    }

    return result;
}

Alternatively you can use the Aggregate extension:

return
    filters
        .Aggregate(
            new List<Product>(),
            (current, next) => current.Union(..)
        );


Equivalent passwords ACPC 2014 I am preparing for ACM-TCPC (Tunisia). So I started solving problems from past ACM-ACPC versions. But I got stuck in the Problem I from 2014.

The problem consists of finding the number of non-equivalent passwords in list of passwords. Two passwords, A and B, are equivalent if len(A) == len(B)  and |A[i] -B[i]| is the same for i in [0..len(A)] (len is the length of the password and |x| is the absolute value of x).

Examples:

Input:

000
111
222

Output:

1

Input:

1111
123
214
2222

Output:

2

Input

43434
54545
45454

Output:

2

My code works fine and it solves the Judges I/O, However it takes a plentiful amount of time!

The code I wrote:

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Password {
    public static void main(String[] args){
        String[] str_tab ;
        HashMap<Integer, Integer> hm = null;
        List<String> l = null;
        try {
            int[] tab = null;
            BufferedReader br = new BufferedReader(new FileReader(new File("./password.in")));
            PrintWriter wr = new PrintWriter("./passwrd.out");
            int T = Integer.parseInt(br.readLine().toString());
            for (int i = 0; i < T; i++) {
                l = new ArrayList<String>();
                int N = Integer.parseInt(br.readLine().toString());
                for (int j = 0; j < N; j++) {
                    l.add(br.readLine().toString());
                }
                wr.println("Case "+(i+1)+": " +solve(l));
            }
            wr.close();

        }catch(Exception e){
            e.printStackTrace();
        }
}
    public static int solve(List<String> l){
        List<String> ls = new ArrayList<String>();
        ls.add(l.get(0));
        int j= 0;
        for (int i = 1; i < l.size(); i++) {
            j = 0;
            while(j<ls.size() && !isEq(l.get(i),ls.get(j))) j++;
            if(j == ls.size()) ls.add(l.get(i));
        }

        return ls.size();
    }
    public static boolean isEq(String p1, String p2){
        if(p1.length() != p2.length()) return false;
        int diff = Math.abs(p1.charAt(0) - p2.charAt(0));
        for (int i = 1; i <p1.length(); i++) {

            if(Math.abs(p1.charAt(i) - p2.charAt(i)) != diff){
                return false;
            }
        }
        return true;
    }
}

Did I get it wrong? Is there advice that could help me improve my code? (performance, organization or anything)

Lint

str_tab, hm, and tab are all unused variables.

In br.readLine().toString(), the .toString() is superfluous, as br.readLine() already returns a string.

In main(), the for (int i = 0; i < T; i++) loop would be better as for (int i = 1; i <= T; i++) so that you can avoid the (i+1).

Instead of catch (Exception e) { e.printStackTrace(); }, you could just declare main(String[] args) throws Exception.  But what kind of exception?  The code would be clearer if you narrowed it down to throws IOException.  (It's also possible to get a NumberFormatException, but for a contest problem, I wouldn't bother handling it.)

Skeleton

I would use the following outline:

public class Password {

    public static class DistinctPasswordCounter {
        public DistinctPasswordCounter(Scanner in) {
            this.in = in;
            this.n = Integer.parseInt(in.nextLine());
            …
        }

        public int count() {
            while (this.n --> 0) {
                …
            }
            return …;
        }
    }

    public static void main(String[] args)
            throws FileNotFoundException, NoSuchElementException {
        try (Scanner in = new Scanner(new File("password.in"));
             PrintWriter out = new PrintWriter("password.out")) {
            int t = Integer.parseInt(in.nextLine());
            for (int i = 1; i <= t; i++) {
                DistinctPasswordCounter counter = new DistinctPasswordCounter(in);
                out.printf("Case %d: %d\n", i, counter.count());
            }
        }
    }
}

Notable improvements:

password.out would be a more logical filename for the output.
Use try-with-resources for AutoCloseable resources.
Using Scanner instead of BufferedReader would let you not have to deal with IOException.
Passing a Scanner instead of a List<String> lets each test case work on the fly as the input streams in.
solve() doesn't really "solve".  I'd pick a more descriptive name.  Here, I've instantiated an object to represent each test case.  (I think that a good solution requires more state than I would like to pack into a single function.)  If the challenge had not required the program to be named Password, I would have just used DistinctPasswordCounter as the name of the class, and eliminated the inner class.

Strategy

Your solve() compares each password with every previously seen password, which makes it O(N2).  It's not surprising that the solution is slow, considering that N is large (up to 105).

Consider a different strategy: when you encounter a password, also note all possible variants of it.  For example, if the password 31415 appears, then also register the variants 20304, 20306, 20324, 20326, etc.

How many variants would we be talking about?  Given an original password, such as 31415, there would be…

31415 itself
the ±1 variants:
$${2 \choose 4}{0 \choose 2}{3 \choose 5}{0 \choose 2}{4 \choose 6}$$
… of which there are 25: 20304, 20306, 20324, 20326, 20504, 20506, 20524, 20526, 22304, 22306, 22324, 22326, 22504, 22506, 22524, 22526, 40304, 40306, 40324, 40326, 40504, 40506, 40524, 40526, 42304, 42306, 42324, 42326, 42504, 42506, 42524, 42526.
the ±2 variants:
$${1 \choose 5}\left(3\right){2 \choose 6}\left(3\right){3 \choose 7}$$
… of which there are 23: 13233, 13237, 13633, 13637,  53233, 53237, 53633, 53637.
the ±3 variants:
$${0 \choose 6}\left(4\right){1 \choose 7}\left(4\right){2 \choose 8}$$
… of which there are 23: 04142, 04148, 04742, 04748, 64142, 64148, 64742, 64748.
the ±4 variants:
$$\left(7\right)\left(5\right){0 \choose 8}\left(5\right){1 \choose 9}$$
… of which there are 22: 75051, 75059, 75851, 75859.
the ±5 variants:
$$\left(8\right)\left(6\right)\left(9\right)\left(6\right)\left(0\right)$$
… of which there is 1: 86960.

In the worst case, a password like 44444 or 55555 would generate 1+32+32+32+32+1 = 130 entries.  If you stick them all in a HashSet with O(1) insertion and lookup time, then the solution would be O(130 N), which is much better than O(N2) for N ≫ 130.

In practice, there will probably be much fewer than 130 variants.  For example, 31415 has just 54 variants.  Passwords that are shorter or that have a wide distribution of digits would have fewer variants.  Passwords that are equivalent to another password would generate no variants at all.  (For large N, the proportion of passwords that are equivalent to an existing password should rise dramatically due to the Birthday Paradox.)

Suggested solution

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.HashSet;
import java.util.NoSuchElementException;

public class Password {

    public static class DistinctPasswordCounter {
        private final Scanner in;
        private final HashSet<String> seenPasswords;
        private int n, distinctCount;

        public DistinctPasswordCounter(Scanner in) {
            this.in = in;
            this.n = Integer.parseInt(in.nextLine());

            // 100 is a rough estimate of the number of variants
            // per password, based on (5 * Math.pow(2, maxLength)).
            // For very large n, it could probably be tuned lower
            // due to the Birthday Paradox.
            this.seenPasswords = new HashSet<>(100 * this.n);
        }

        public int count() {
            while (this.n --> 0) {
                String password = this.in.nextLine();
                if (this.seenPasswords.add(password)) {
                    // No variant of this password has been seen before
                    this.distinctCount++;
                    int variants = this.addVariants(password);
                    // System.err.printf("%3d variants of %s\n", variants + 1, password);
                }
            }
            return this.distinctCount;
        }

        private int addVariants(String password) {
            int diff = 0, variants = 0, v;
            while (0 < (v = this.addVariants(password, ++diff, 0))) {
                variants += v;
            }
            return variants;
        }

        private int addVariants(String password, int diff, int pos) {
            if (pos >= password.length()) {
                this.seenPasswords.add(password);
                return 1;
            }
            char c1 = (char)(password.charAt(pos) - diff),
                 c2 = (char)(password.charAt(pos) + diff);
            String head = password.substring(0, pos),
                   tail = password.substring(pos + 1);
            return (c1 < '0' ? 0 : this.addVariants(head + c1 + tail, diff, pos + 1)) +
                   (c2 > '9' ? 0 : this.addVariants(head + c2 + tail, diff, pos + 1));
        }
    }

    public static void main(String[] args)
            throws FileNotFoundException, NoSuchElementException {
        try (Scanner in = new Scanner(new File("password.in"));
             PrintWriter out = new PrintWriter("password.out")) {
            int t = Integer.parseInt(in.nextLine());
            for (int i = 1; i <= t; i++) {
                DistinctPasswordCounter counter = new DistinctPasswordCounter(in);
                out.printf("Case %d: %d\n", i, counter.count());
            }
        }
    }
}


Style-Changing Handler For a Select Box Similar to my recently asked question: Style-changing handler for an HTML drop-down box How can I compress down JS and almost automate it?

I tried changing up the old questions answer a bit but never could get it working as i'm very new to JS I mainly do PHP.

So I just need the following JS compressed and automated as much as possible like last question:

function seasonChange() {

if(document.getElementById('selectseason').value == "1"){
    if(document.getElementById('selectseason1episode').value != "1 - Death Has A Shadow") {
        document.getElementById('season1episodes').style.display = 'block';
        document.getElementById('season2episodes').style.display = 'none';
        document.getElementById('season3episodes').style.display = 'none';
        document.getElementById('s1buttons').style.display = 'block';
        document.getElementById('s2buttons').style.display = 'none';
        document.getElementById('s3buttons').style.display = 'none';
    } else {
        document.getElementById('season1episode1').style.display = 'inline-block';
        document.getElementById('season1episodes').style.display = 'block';
        document.getElementById('season2episodes').style.display = 'none';
        document.getElementById('season3episodes').style.display = 'none';
        document.getElementById('s1buttons').style.display = 'block';
        document.getElementById('s2buttons').style.display = 'none';
        document.getElementById('s3buttons').style.display = 'none';
    }
}

if(document.getElementById('selectseason').value == "2"){
    if(document.getElementById('selectseason2episode').value != "1 - Peter, Peter, Caviar Eater") {
        document.getElementById('season1episodes').style.display = 'none';
        document.getElementById('season2episodes').style.display = 'block';
        document.getElementById('season3episodes').style.display = 'none';
        document.getElementById('s1buttons').style.display = 'none';
        document.getElementById('s2buttons').style.display = 'block';
        document.getElementById('s3buttons').style.display = 'none';
    } else {
        document.getElementById('season2episode1').style.display = 'inline-block';
        document.getElementById('season1episodes').style.display = 'none';
        document.getElementById('season2episodes').style.display = 'block';
        document.getElementById('season3episodes').style.display = 'none';
        document.getElementById('s1buttons').style.display = 'none';
        document.getElementById('s2buttons').style.display = 'block';
        document.getElementById('s3buttons').style.display = 'none';
    }
}

if(document.getElementById('selectseason').value == "3"){
    if(document.getElementById('selectseason3episode').value != "1 - The Thin White Line") {
        document.getElementById('season1episodes').style.display = 'none';
        document.getElementById('season2episodes').style.display = 'none';
        document.getElementById('season3episodes').style.display = 'block';
        document.getElementById('s1buttons').style.display = 'none';
        document.getElementById('s2buttons').style.display = 'none';
        document.getElementById('s3buttons').style.display = 'block';
    } else {
        document.getElementById('season3episode1').style.display = 'inline-block';
        document.getElementById('season1episodes').style.display = 'none';
        document.getElementById('season2episodes').style.display = 'none';
        document.getElementById('season3episodes').style.display = 'block';
        document.getElementById('s1buttons').style.display = 'none';
        document.getElementById('s2buttons').style.display = 'none';
        document.getElementById('s3buttons').style.display = 'block';
    }
}

}

Note: I cant reply to questions about the code but all I will say is the select season . value == 1 bit is season one e.g. I have shown 3 examples but there could be more then 3 seasons so maybe compress and automate using that $i++ variable.

Instead of testing the value of the HTML element, pass the season number in as a variable, and then you can use some of that simplifcation magic we used before:

function seasonChange() {

    var seasonNum = document.getElementById('selectseason').value;
    var first_episodes = [
        "1 - Death Has A Shadow",
        "1 - Peter, Peter, Caviar Eater",
        "1 - The Thin White Line"
    ];

    for (var i = 1; i <= first_episodes.length; i++){
        if (document.getElementById('selectseason' + seasonNum + 'episode').value == first_episodes[i - 1]) {
            document.getElementById('season' + seasonNum + 'episode1').style.display = 'inline-block';
        }
        var showOrNot = (seasonNum == i ? 'block' : 'none');
        document.getElementById('season' + i + 'episodes').style.display = showOrNot;
        document.getElementById('s' + i + 'buttons').style.display = showOrNot;
    }

}

This uses the season numbers, to test whether its the one you're switching into or not.

One suggestion I'd make though is that, instead of the first_episodes variable, I'd use a database script, in PHP or something similar, to hit the database for the different episodes/seasons.

That way you can totally move this to the automated paradise you want.


Update pass-through query from a form (an alternative to stored procedures) I've adapted a script from the book Microsoft Access Developer's Guide to SQL Server that I use to update a pass-through query via a form.

  One way to pass parameters to a pass-through query is to modify the
  QueryDef object's SQL property in code before running it,
  concatenating the parameter values you want to send.

I've chosen this method, rather than using stored procedures, because I do not have adequate privileges (create function) for creating stored procedures in the Oracle database.

I'm familiar with scripting, but I don't pretend to be an expert coder.

I figure I might as well get some input from those who know what they're doing, learn from you, and get off on the right foot. I've heard that non-experts who attempt to program in Access often end-up with these barely working, horribly designed applications that bring dread into the hearts of developers.

Obviously, I'd prefer to avoid that. Here's what I've got:

'SPT stands for SQL Pass-through (query). My pass-through query is called sptROAD_INSP

Private Sub cmdSubmit_Click()
    AssembleSptROAD_INSP Me.txtStartYear, Me.txtEndYear
End Sub

Option Compare Database
Option Explicit

Public Sub AssembleSptROAD_INSP( _
    intStartYear As Integer, _
    intEndYear As Integer)

    Dim strSQL As String
    Dim strSPTName As String

    strSPTName = "sptROAD_INSP"

    strSQL = "select " _
                    & "b.insp_id, " _
                    & "b.road_id, " _
                    & "b.insp_date, " _
                    & "b.Condition " _
            & "from " _
                    & "user1.road_insp b " _
            & "where " _
                    & "b.insp_date = ( select max(insp_date) from user1.road_insp a " _
                                      & "where a.road_id = b.road_id " _
                                          & "and extract(year from insp_date) between " _
                                          & intStartYear & " and " & intEndYear & ");"

    Call ModifyPassThrough(strQdfName:=strSPTName, strSQL:=strSQL)

    DoCmd.Close acQuery, "sptROAD_INSP"
    DoCmd.OpenQuery strSPTName
End Sub

Public Sub ModifyPassThrough( _
  ByVal strQdfName As String, _
  ByVal strSQL As String, _
  Optional varConnect As Variant, _
  Optional fRetRecords As Boolean = True)

    ' Modifies pass-through query properties
    ' Inputs:
    '   strQdfName  Name of the query
    '   strSQL      New SQL string
    '   varConnect  Optional connection string
    '   fRetRecords Optional returns records--
    '               defaults to True (Yes)

    Dim db As DAO.Database
    Dim qdf As DAO.QueryDef
    Dim strConnect As String

    Set db = CurrentDb
    Set qdf = db.QueryDefs(strQdfName)
    If IsMissing(varConnect) Then
        strConnect = qdf.Connect
    Else
        strConnect = CStr(varConnect)
    End If
    qdf.Connect = strConnect
    qdf.ReturnsRecords = fRetRecords
    qdf.SQL = strSQL
End Sub

What can I do to make this as sustainable and robust as possible?

The first thing I would suggest is to avoid as much as possible depending on the DoCmd object. The DoCmd object is essentially replicating the actual user action as if you had clicked on a button via the UI, with all the dialogs, etc. that comes with it.

For the purpose of executing a SQL, I recommend that you use the Database.Execute method, remembering to use dbFailOnError flag and very likely dbSeeChanges if your Oracle tables uses something equivalent to auto-increment for its primary key. So instead of

DoCmd.Close acQuery, "sptROAD_INSP"
DoCmd.OpenQuery strSPTName

You should want to do something like this:

CurrentDb.Execute strSPTName, dbFailOnError Or dbSeeChanges

This does essentially the same thing but without all the extraneous UI baggages that the DoCmd brings to the table. It will NOT prompt you to confirm if you want to make changes, and does NOT require you to use DoCmd.SetWarnings to suppress the unwanted UI messages associated with OpenQuery or RunSQL methods which are member of the DoCmd object.

However, Execute method is only appropriate when it's in fact a statement that is not intended to return results. If you expect results (e.g. the qdf.ReturnRecords is set to true), you would use OpenRecordset method. Therefore, you could revise your function so that it does this (untested aircode):

If qdf.ReturnRecords Then
  Set Results = qdf.OpenRecordset(dbOpenDynaset, dbSeeChanges)
Else
  qdf.Execute dbFailOnError Or dbSeeChanges
End If

assuming that you have a variable named Results that is a `DAO.Recordset type.

Next, you are writing SQL raw. Unfortunately, a passthrough query cannot be properly parameterized. For best protection against SQL injection, you might want to consider using ADO instead of DAO, and if possible use OLEDB provider for Oracle (note that there are multiple providers, some by Oracle themselves, other by Microsoft - I can't say which is better; experimenting is needed). Note that you are not restricted to using ADO exclusively; you can use ADO in VBA code and DAO for Access form binding.

If for some reasons you cannot use ADO and must use DAO, then you should at least consider writing functions to prepare the parameters so that all strings are properly delimited, and that empty values in a textbox will result in a NULL or maybe '', depending on your needs.


Comparing two cars via their lifetime price I am currently using the Udacity Introduction to Java course. There was a topic on Algorithms and it gave an example Algorithm for comparing and purchasing two different cars in pseudo code. I decided to turn that into some Java code to see just how well I grasped the concept.

The algorithm was:

  For each car, compute. Gas cost = (miles driven / mpg) * price per
  gallon. Total cost = gas cost + car cost. If car 1 < car 2, buy car 1.
  Else, buy car 2.

//Algorithm for buying a car
//by comparing car price, MPG,
//local gas price, and the miles
//to be drive in total.
//idea from udacity Intro
//to Java course.

import java.util.Scanner;

public class buyingCars {

     public static void main (String[] args) {

            Scanner input = new Scanner(System.in);

            System.out.println("Enter the price of car one: ");
            int carOnePrice = input.nextInt();

            System.out.println("Enter the price of car two: ");
            int carTwoPrice = input.nextInt();

            System.out.println("Enter the price of gas in your area: ");
            double gasPrice = input.nextDouble();

            System.out.println ("What is the average mpg of car one? ");
            int carOneMpg = input.nextInt();

            System.out.println ("What is the average mpg of car two? " );
            int carTwoMpg = input.nextInt();

            System.out.println("Give me an amount of miles total you think you will drive in this car: ");
            int milesDriven = input.nextInt();

            double gasCostCarOne = (milesDriven / carOneMpg) * gasPrice;
            double totalCostCarOne = gasCostCarOne + carOnePrice;

            double gasCostCarTwo = (milesDriven / carTwoMpg) * gasPrice;
            double totalCostCarTwo = gasCostCarTwo + carTwoPrice;

            if (totalCostCarOne < totalCostCarTwo) {

                    System.out.println("Car One will, in total, cost less than car two. Buy it.");
            }

            else {

                    System.out.println("Car two will, in total, cost less than car one. Buy it.");
            }
      }
}

What I am wondering is if my code was clean and my form is good? Are there things I am doing in my code that I should not be, or is everything looking pretty solid?

Also, is there a simpler way of doing this? It just seems like an awful lot of code that could potentially be narrowed down. Could each car hold it's values in an array or something like that?

If there is a problem with my post, please let me know. I am still getting use to posting here.

The first thing I would try is so factor out the input-prompting routines:

 private static Scanner input = new Scanner(System.in);

 private static int askInt(String prompt) {
     System.out.println(prompt);
     return input.nextInt();
 }

 private static double askDouble(String prompt) {
     System.out.println(prompt);
     return input.nextDouble();
 }

In my opinion, there's no particular reason why the car price, fuel efficiency, or distance numbers should be integral.  Why not just do all of the work in doubles?

public class CarComparison {
     private static Scanner input = new Scanner(System.in);

     private static double ask(String prompt) {
         System.out.println(prompt);
         return input.nextDouble();
     }

     public static void main(String[] args) {
         double carOnePrice = ask("Enter the price of car one: ");
         double carTwoPrice = ask("Enter the price of car two: ");
         double gasPrice = ask("Enter the price of gas in your area: ");
         double carOneMpg = ask("What is the average mpg of car one? ");
         double carTwoMpg = ask("What is the average mpg of car two? ");
         double milesDriven = ask("Give me an amount of miles total you think you will drive in this car: ");

         double gasCostCarOne = (milesDriven / carOneMpg) * gasPrice;
         double totalCostCarOne = gasCostCarOne + carOnePrice;

         double gasCostCarTwo = (milesDriven / carTwoMpg) * gasPrice;
         double totalCostCarTwo = gasCostCarTwo + carTwoPrice;

         if (totalCostCarOne == totalCostCarTwo) {
             System.out.println("The two cars cost the same.");
         } else if (totalCostCarOne < totalCostCarTwo) {
             System.out.println("Car One will, in total, cost less than car two. Buy it.");
         } else {
             System.out.println("Car two will, in total, cost less than car one. Buy it.");
         }
      }
}

For completeness, I've added handling for the unlikely case of a tie.

A next step might be to define a totalCost() function or to define a Car object, but I think that for this problem, the benefits of further changes would be marginal, and I would just leave it at that.


Thread-Safe and Lock-Free - Queue Implementation I was trying to create a lock-free queue implementation in Java, mainly for personal learning. The queue should be a general one, allowing any number of readers and/or writers concurrently.

Would you please review it, and suggest any improvements/issues you find?

(Cross-post from StackOverflow)

import java.util.concurrent.atomic.AtomicReference;

public class LockFreeQueue<T> {
    private static class Node<E> {
        final E value;
        volatile Node<E> next;

        Node(E value) {
            this.value = value;
        }
    }

    private AtomicReference<Node<T>> head, tail;

    public LockFreeQueue() {
        // have both head and tail point to a dummy node
        Node<T> dummyNode = new Node<T>(null);
        head = new AtomicReference<Node<T>>(dummyNode);
        tail = new AtomicReference<Node<T>>(dummyNode);
    }

    /**
     * Puts an object at the end of the queue.
     */
    public void putObject(T value) {
        Node<T> newNode = new Node<T>(value);
        Node<T> prevTailNode = tail.getAndSet(newNode);
        prevTailNode.next = newNode;
    }

    /**
     * Gets an object from the beginning of the queue. The object is removed
     * from the queue. If there are no objects in the queue, returns null.
     */
    public T getObject() {
        Node<T> headNode, valueNode;

        // move head node to the next node using atomic semantics
        // as long as next node is not null
        do {
            headNode = head.get();
            valueNode = headNode.next;
            // try until the whole loop executes pseudo-atomically
            // (i.e. unaffected by modifications done by other threads)
        } while (valueNode != null && !head.compareAndSet(headNode, valueNode));

        T value = (valueNode != null ? valueNode.value : null);

        // release the value pointed to by head, keeping the head node dummy
        if (valueNode != null)
            valueNode.value = null;

        return value;
    }
}

Yes.

The combination of volatile and compare-and-swap operations is enough to make sure that the Node objects are safely published.
The compare-and-swap must be before the assignment to a volatile variable in both methods, so you're fine there. They do not need to happen atomically.

The queue exhibits odd behavior. Let's say thread 1 stops in putObject() after the CAS but before the last assignment. Next thread 2 executes putObject() in its entirety. Next thread three calls getObject(), and it cannot see either of the first two objects, even though thread 2 is completely done. There's a small chain being built up in-memory. Only after thread 1 completes putObject() are both objects visible on the queue, which is somewhat surprising, and has weaker semantics than most non-blocking data structures.

Another way of looking at the odd API is that it's nice to have a non-blocking put() but it's very strange to have a non-blocking get(). It means that the queue must be used with repeated polling and sleeping.


Drawing spirals on virtual whiteboards I have it set up so I place my mouse in the center of where I want the spiral to be, then I press enter to start the program, then define the radius initially and how much it grows each time it goes around.

I use \$\sin(\theta)\$ = opposite / hypotenuse and \$\cos(\theta)\$ = adjacent / hypotenuse to find how much my coordinates change based on the degree and the radius of my circle that itself is gradually increasing to create a spiral. There is also some printing at the end that I had just to help with debugging. As simple as I think something is going to be there are always problems.

Converting to int is because NumPy data can't be operated on.

from numpy import sin, cos, pi
import pyautogui as cc
import time
# (x-h)^2 + (y-k)^2 = r^2
# knowling radius and degree, r*sin(deg*pi/180) = rise || cos = run

input('Enter to Begin\n-->')
radius = int(input('What do you want your beginning radius to be?\n-->'))
rate = int(input('How much do you want it to increase by each cycle?\n-->'))
h, k = cc.position()
degree = 0
x = h+radius*(int(cos(degree*pi/180)*10**5)/10**5)
y = k+radius*(int(sin(degree*pi/180)*10**5)/10**5)
cc.moveTo(x, y)
cc.mouseDown()
while True:
    degree += 1
    radius += rate / 360
    x = h+radius*(int(cos(degree*pi/180)*10**5)/10**5)
    y = k+radius*(int(sin(degree*pi/180)*10**5)/10**5)
    cc.moveTo(x, y)
    print('Cords: '+str(x)+'||'+str(y))
    print('radius: '+str(radius))
    print('degree: '+str(degree))
    print()

All feedback is appreciated, but I'm really wondering how I could make this faster in Python.

The standard way to do this would be to use a tkinter canvas or pygame, but rolling with your method, you only have one huge efficiency problem, you are wasting subpixel precision on your calculations, I added a simple PRECISION constant so that you can decide at will how many degrees you advance per step, you only used 1 degree per step that is really to little, I suggest \$10\$, it looks good and goes fast.

I  also added a constant for 10**5 so that you can avoid computing it every cycle (not a big deal) but mainly so that you could explain with a name what that number does.

I also replaced the while loop with a for loop so that the program does not run indefinitely (I was quite trolled by the program taking my mouse cursor for infinite time, it was not easy to shut it down).

Also please put care in your comments, about spelling formatting etc.. and the standard format is a docstring on top of the file.

Removing the printing can also speed up your program a bit.

Enjoy your improved program:

"""
This program takes control of the mouse to draw an ellipse.

(x-h)^2 + (y-k)^2 = r^2
Knowing radius and degree,
rise = r*sin(deg*pi/180)
run  = r*cos(deg*pi/180)
"""

from numpy import sin, cos, pi
import pyautogui as cc
import time

BIG_NUM = 10**5
PRECISION = 10 # higher is less precision
ITERATIONS = 300

input('Enter to Begin\n-->')
radius = int(input('What do you want your beginning radius to be?\n-->'))
rate = int(input('How much do you want it to increase by each cycle?\n-->'))
h, k = cc.position()
degree = 0
x = h+radius*(int(cos(degree*pi/180)*BIG_NUM)/BIG_NUM)
y = k+radius*(int(sin(degree*pi/180)*BIG_NUM)/BIG_NUM)
cc.moveTo(x, y)
cc.mouseDown()

for i in range(ITERATIONS):
    degree += PRECISION
    degree %= 360
    radius += (PRECISION * rate) / 360
    x = h+radius*(int(cos(degree*pi/180)*BIG_NUM)/BIG_NUM)
    y = k+radius*(int(sin(degree*pi/180)*BIG_NUM)/BIG_NUM)
    cc.moveTo(x, y)
    #print('Cords: '+str(x)+'||'+str(y))
    #print('radius: '+str(radius))
    #print('degree: '+str(degree))
    #print()


Raising error if method not overridden by sub-class Background

I have a base (only 2 classes inherit from it, and only from it) abstract (meaning I don't want it to be used directly) class that implements some common functionality.

Some of it depends on certain methods being defined, methods whose implementation differs per the exact sub-class; so I set-up a mechanism to raise an exception in case that kind of thing happened (better explicit fail than subtle debugging, right?).

Code

class Matrix:
    """Model an abstract base interface for 2-d matrices."""

    def __init__(self):
        """Raise error as class is abstract."""
        self.__eq__ = self._flip = self._rotate = self.__error
        raise NotImplementedError("{} should not be instantiated directly".format(type(self)))

    def __error(self):
        """Raise error as certain methods need to be over-rided."""
        raise NotImplementedError("method needs to be defined by sub-class")

Question

Is that an anti-pattern, like singletons or w/e? If so, what's a better way? Should I even check for this at all (i.e., maybe similar to excessive type-checking)?

  Disclaimer: Python was my first language, and I do NOT like Java (although I have some experience from Android development); so this is not me trying to port some ruddy static pattern from another language.

With multi-inheritance and super, raising NotImplementedError is an anti-pattern.

Breaking the DRY principle

When __init__ raise a exception all subclass must repeat the initialization instead of using the default.

class BadBaseMatrix():
    """Init raise NotImplementedError"""
    def __init__(self, text_version_of_matrix):
         """text_version_of_matrix represent some argument to initialize all matrix"""
         # ...
         raise NotImplementedError

class ComplexMatrix(BadBaseMatrix):
    def __init__(self, text_version_of_matrix):
        self.text_version_of_matrix = text_version_of_matrix
        # ...

class OtherMatrix(BadBaseMatrix):
    def __init__(self, text_version_of_matrix):
        # Must redo the initialization here
        self.text_version_of_matrix = text_version_of_matrix
        # ...

instead of something like this

class BetterBaseMatrix():
    def __init__(self, text_version_of_matrix):
         """text_version_of_matrix represent some argument to initialize all matrix"""
         self.text_version_of_matrix = text_version_of_matrix

class ComplexMatrix(BetterBaseMatrix):
    # ...

class PrintMatrix(BetterBaseMatrix):
    def __init__(self, text_version_of_matrix):
        super().__init__(text_version_of_matrix)
        # in python 2, this would be super(MyMatrix, self)
        print("PrintMatrix initialized")

Breaking inheritance

class MyMatrix(BadBaseMatrix):
     def__init__(self, text_version_of_matrix):
        # I will use his implementation because it must do some important initialization there.
        super().__init__(text_version_of_matrix)

>>> matrix = MyMatrix("")
# NotImplementedError

Do you really need a abstract base class

I feel that in Python, you do not need to prevent consumers of using your class a certain way. Maybe the base class could be used as a valid container. If so, returning a correct default (possibly None) would be enough for methods.

Here a similar version as your original of a plain matrix usable as a base class. But you should define each method to be able to add it's docstring.

class PlainMatrix():
    def _do_nothing(*args, **kwargs):
        """This docstring is used for all methods ..."""
        pass  #
    rotate = flip = _do_nothing

You really need a a abstract class

Use abc.ABCMeta.

import abc

class BaseMatrix(metaclass=abc.ABCMeta):
    # In python 2,
    # __metaclass__ = abc.ABCMeta

    def __init__(self, text_version_of_matrix):
         """text_version_of_matrix represent some argument to initialize all matrix"""
         self.text_version_of_matrix = text_version_of_matrix

    @abc.abstractmethod
    def rotate(self, degree):
         """ Abstract rotate that must be implemented in subclass"""
         pass

 class SubMatrix(BaseMatrix):

    def rotate(self, degree):
        """ True implementation of rotate"""
        # ...

 class StillAbstractMatrix(BaseMatrix):
     """ StillAbstractMatrix has not implemented rotate """
     pass

 >>> sub_matrix = SubMatrix("1 2 3")
 >>> bad = StillAbstractMatrix("1 2 3")
 # Traceback (most recent call last):
 #    File "<stdin>", line 1, in <module>
 # TypeError: Can't instantiate abstract class StillAbstractMatrix with abstract methods rotate


Constantly checking existence of dictionary elements in Python: a better way? I use Python dictionaries to count words in a corpus:

words[a] = number of times I saw a in the corpus.

Every time before incrementing a counter (words[a] += 1), I need to check a condition:
does the dictionary entry words[a] actually exists?

My code:

    if a in words:
      words[a] += 1
    else:
      words[a] = 1

It there a way to improve it?

For Python >= 2.5 you can use defaultdict instead of dict:

 from collections import defaultdict
 words = defaultdict(int)
 corpus = ["your", "word", "corpus"]
 for a in corpus:
    words[a]+=1
 print words

For Python >= 2.7 you can use Counter:

from collections import Counter
corpus = ["your", "word", "corpus"]
words = Counter(corpus)
print words


Optimizing my 2D Ising model code in Julia I'm just starting to learn Julia, I work primarily in physics and am used to writing most of my code in Fortran90 and occasionally Python for Tensorflow (also Mathematica but that's less relevant). Julia has been recommended to me and I started checking it out; I like it a lot in theory as a middle ground between the speed of Fortran and the syntax of Python. To test it out I wrote a simple 2D Ising model code implementing a basic single-spin-flip Metropolis Monte Carlo algorithm. However, this code runs very slowly compared to an equivalent code in Fortran. Am I doing something wrong which is significantly affecting the performance of the code? I know almost nothing beyond what I've done here. I am using the Juno IDE in Atom on Windows 10. As an aside, I would also like to know how I can make multiple plots in the Atom plot tab, but that's secondary.

using Printf
using Plots

L       = 20             # linear size of lattice
n_sweep = 20             # number of sweeps between sampling
n_therm = 1000           # number of sweeps to thermalize
n_data  = 100            # number of data samples per temperature
temps   = 4.0:-0.3:0.1   # temperatures to sample
e1 = Array(1:n_data)     # array to hold energy measurements (fixed T)
m1 = Array(1:n_data)     # array to hold magnetization measurements (fixed T)
et = []                  # array to append average energy at each T
mt = []                  # "                      magnetizations
s  = ones(Int32,L,L)     # lattice of Ising spins (+/-1)

function measure(i)      # measure i'th sample of energy and magnetization
    en = 0
    m = 0
    for x = 1:L
        for y = 1:L
            u = 1+mod(y,L) # up
            r = 1+mod(x,L) # right
            en -= s[x,y]*(s[x,u]+s[r,y]) # energy
            m  += s[x,y]                 # magnetization
        end
    end
    energy[i] = en
    magnetization[i] = abs(m)
end

function flip(x,y,T) # apply metropolis spin flip algorithm to site (x,y) w/ temp T
    u = 1+mod(y,L)   # up
    d = 1+mod(y-2,L) # down
    r = 1+mod(x,L)   # right
    l = 1+mod(x-2,L) # left
    de = 2*s[x,y]*(s[x,u]+s[x,d]+s[l,y]+s[r,y])
    if (de < 0)
        s[x,y] = -s[x,y]
    else
        p = rand()
        if (p < exp(-de/T))
            s[x,y] = -s[x,y]
        end
    end
end

function sweep(n,T) # apply flip() to every site on the lattice
    for i = 1:n
        for x = 1:L
            for y = 1:L
                flip(x,y,T)
            end
        end
    end
end

for T in temps              # loop over temperatures
    sweep(n_therm, T)       # thermalize the lattice
    energy        = e1      # reset energy measurement array
    magnetization = m1      # same
    for i = 1:n_data        # take n_data measurements w/ n_sweep
        sweep(n_sweep, T)
        measure(i)
    end
    en_ave = sum(energy)/n_data           # compute average
    ma_ave = sum(magnetization)/n_data
    push!(et,en_ave/(L*L))                # add to the list
    push!(mt,ma_ave/(L*L))
    @printf("%8.3f  %8.3f \n", en_ave/(L*L), ma_ave/(L*L))
end

plot(temps,mt) # plot magnetization vs. temperature
#plot(temps,et)

The biggest problem with this code is the amount of things in global scope. Rewriting it to make some things const, and passing in the rest from a main function brings the time down to .7 seconds (not including the using plots which takes 3.5 seconds, compared to ~10 seconds before. Here is the updated code, I hope it helps.

using Printf
using Plots

const L       = 20             # linear size of lattice
const n_sweep = 20             # number of sweeps between sampling
const n_therm = 1000           # number of sweeps to thermalize
const n_data  = 100            # number of data samples per temperature
const temps   = 4.0:-0.3:0.1   # temperatures to sample

function measure(i, energy, magnetization, s)      # measure i'th sample of energy and magnetization
    en = 0
    m = 0
    for x = 1:L
        for y = 1:L
            u = 1+mod(y,L) # up
            r = 1+mod(x,L) # right
            en -= s[x,y]*(s[x,u]+s[r,y]) # energy
            m  += s[x,y]                 # magnetization
        end
    end
    energy[i] = en
    magnetization[i] = abs(m)
end

function flip(x, y, T, s) # apply metropolis spin flip algorithm to site (x,y) w/ temp T
    u = 1+mod(y,L)   # up
    d = 1+mod(y-2,L) # down
    r = 1+mod(x,L)   # right
    l = 1+mod(x-2,L) # left
    de = 2*s[x,y]*(s[x,u]+s[x,d]+s[l,y]+s[r,y])
    if (de < 0)
        s[x,y] = -s[x,y]
    else
        p = rand()
        if (p < exp(-de/T))
            s[x,y] = -s[x,y]
        end
    end
end

function sweep(n, T, s) # apply flip() to every site on the lattice
    for i = 1:n
        for x = 1:L
            for y = 1:L
                flip(x,y,T, s)
            end
        end
    end
end

function main()
    e1 = Array(1:n_data)     # array to hold energy measurements (fixed T)
    m1 = Array(1:n_data)     # array to hold magnetization measurements (fixed T)
    et = []                  # array to append average energy at each T
    mt = []                  # "                      magnetizations
    s  = ones(Int32,L,L)     # lattice of Ising spins (+/-1)
    for T in temps              # loop over temperatures
        sweep(n_therm, T, s)    # thermalize the lattice
        energy        = e1      # reset energy measurement array
        magnetization = m1      # same
        for i = 1:n_data        # take n_data measurements w/ n_sweep
            sweep(n_sweep, T, s)
            measure(i, energy, magnetization, s)
        end
        en_ave = sum(energy)/n_data           # compute average
        ma_ave = sum(magnetization)/n_data
        push!(et,en_ave/(L*L))                # add to the list
        push!(mt,ma_ave/(L*L))
        @printf("%8.3f  %8.3f \n", en_ave/(L*L), ma_ave/(L*L))
    end
    plot(temps,mt) # plot magnetization vs. temperature
    #plot(temps,et)
end

main()


Calculate Hamming distance between DNA sequences in Ruby I am requesting a review for my solution to this problem from exercism.io. I'm posting it here since there is not always input on solution submitted through exercism.

The problem is as stated:

  Calculate the Hamming difference between two DNA strands.

  A mutation is simply a mistake that occurs during the creation or
  copying of a nucleic acid, in particular DNA. Because nucleic acids
  are vital to cellular functions, mutations tend to cause a ripple
  effect throughout the cell. Although mutations are technically
  mistakes, a very rare mutation may equip the cell with a beneficial
  attribute. In fact, the macro effects of evolution are attributable by
  the accumulated result of beneficial microscopic mutations over many
  generations.

  The simplest and most common type of nucleic acid mutation is a point
  mutation, which replaces one base with another at a single nucleotide.

  By counting the number of differences between two homologous DNA
  strands taken from different genomes with a common ancestor, we get a
  measure of the minimum number of point mutations that could have
  occurred on the evolutionary path between the two strands.

  This is called the 'Hamming distance'.

  It is found by comparing two DNA strands and counting how many of the
  nucleotides are different from their equivalent in the other string.

GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^  ^ ^    ^^

  The Hamming distance between these two DNA strands is 7.

The tests for the problem were provided:

require 'minitest/autorun'
require_relative 'hamming'

# Common test data version: 2.0.1 f79dfd7
class HammingTest < Minitest::Test
  def test_empty_strands
    # skip
    assert_equal 0, Hamming.compute('', '')
  end

  def test_identical_strands
    # skip
    assert_equal 0, Hamming.compute('A', 'A')
  end

  def test_long_identical_strands
    # skip
    assert_equal 0, Hamming.compute('GGACTGA', 'GGACTGA')
  end

  def test_complete_distance_in_single_nucleotide_strands
    # skip
    assert_equal 1, Hamming.compute('A', 'G')
  end

  def test_complete_distance_in_small_strands
    # skip
    assert_equal 2, Hamming.compute('AG', 'CT')
  end

  def test_small_distance_in_small_strands
    # skip
    assert_equal 1, Hamming.compute('AT', 'CT')
  end

  def test_small_distance
    # skip
    assert_equal 1, Hamming.compute('GGACG', 'GGTCG')
  end

  def test_small_distance_in_long_strands
    # skip
    assert_equal 2, Hamming.compute('ACCAGGG', 'ACTATGG')
  end

  def test_non_unique_character_in_first_strand
    # skip
    assert_equal 1, Hamming.compute('AAG', 'AAA')
  end

  def test_non_unique_character_in_second_strand
    # skip
    assert_equal 1, Hamming.compute('AAA', 'AAG')
  end

  def test_same_nucleotides_in_different_positions
    # skip
    assert_equal 2, Hamming.compute('TAG', 'GAT')
  end

  def test_large_distance
    # skip
    assert_equal 4, Hamming.compute('GATACA', 'GCATAA')
  end

  def test_large_distance_in_off_by_one_strand
    # skip
    assert_equal 9, Hamming.compute('GGACGGATTCTG', 'AGGACGGATTCT')

  end

  def test_disallow_first_strand_longer
    # skip
    assert_raises(ArgumentError) { Hamming.compute('AATG', 'AAA') }

  end

  def test_disallow_second_strand_longer
    # skip
    assert_raises(ArgumentError) { Hamming.compute('ATA', 'AGTG') }

  end

And here is the solution I came up with to solve this problem:

class Hamming
  def self.compute(original, copy)
    unless original.length == copy.length
      raise(ArgumentError)
    end

    hamming = 0
    copy_char = copy.split('')
    original.each_char.with_index do |character, index|
      unless copy_char[index] == character
        hamming += 1
      end
    end
      hamming
  end
end

Please critique and/or suggest how I can improve this solution using Ruby with explanations.

1) Start using Rubocop gem.

2) Prefer guard clauses & stop execution early in a method. (Also, added 2 more conditions.):

raise ArgumentError unless original.length == copy.length
return 0 if original.empty? && copy.empty?
return 0 if original == copy

3) I would prefer Ruby's #char over #each_char in this case:

original = original.chars
copy     = copy.chars

4) I would prefer Ruby's #zip & #count over #with_index to have a better readability:

strands1.zip(strands2).count { |a, b| a != b }

At the end, it would look something like this:

class Hamming
  def self.compute(strand1, strand2)
    # Error handling and edge cases
    raise ArgumentError unless strand1.length == strand2.length
    return 0 if strand1.empty? && strand2.empty?
    return 0 if strand1 == strand2

    strands1, strands2 = strand1.chars, strand2.chars
    # Merge elements of two arrays and compare arrays of array.
    strands1.zip(strands2).count { |a, b| a != b }
  end
end


Fishy: An ASCII Programming Language I've decided to write a very simply output programming language. All the user does is write ASCII values inside ASCII fish, and the interpreter pieces the values together and outputs them.

I'm mainly looking for feedback on the interpreter, as the language itself is very easy to understand.

Here's what a Hello, World! program looks like in Fishy:

><72> ><101> ><108> ><108> ><111> ><44> ><32> ><87> ><111> ><114> ><108> ><100> ><33>

All the rules of the language are listed in the module docstring of the program.

"""

Fishy (.fishy extension)

><> Frontfish

Implementation is simple:
You enter ASCII values between the facing signs <>

Commands on separate lines will have output separated by a new line

Example:

><98> ><112> ><113> ><107>
bpqk

><97>
><108>
><101>

a
l
e

NO TRAILING WHITESPACE!
Trailing whitespace after the last fish on the line will result in a syntax error

"""

import argparse
import os
import sys
from typing import List

def run_code(code: List[str]):
    """
    Runs the passed Fishy Code
    """
    for line in code:
        # Clean up code and separate commands#
        line = line.strip("\n")
        commands = line.split(" ")

        # Check if line has multiple statements in it
        if len(commands) > 1:
            if correct_syntax(commands):
                output = "".join(chr(get_number(fish)) for fish in commands)
                print(output)
        else:
           if correct_syntax(commands):
               print(chr(get_number(commands[0])))

def correct_syntax(pond: List[str]) -> bool:
    """
    Checks the syntax of the passed list of commands on the following criteria:

    Is a fish ><..>

    Correct Example:
    ><98> ><108> ><56>

    Incorrect Example:
    ><98> >><<76>> ><[108>

    """
    for fish in pond:
        if not is_fish(fish):
            sys.exit(f"Incorrect Syntax: {fish}")
    return True

def is_fish(fish: str) -> bool:
    """
    Returns if the passed fish is the fish or not

    Fish: Starts with >< ends with >

    A fish like so ><98g> will be caught by "get_number()" function

    """
    return fish.startswith("><") and fish.endswith(">")

def get_number(fish: str) -> int:
    """
    Returns the number in the fish
    """
    # Check font fish first #
    try:
        number = int(fish[2:-1])
    except ValueError:
        sys.exit(f"Incorrect Syntax: {fish}")
    return number

def get_content(file: str) -> List[str]:
    """
    Returns all the content in the passed file path

    :param file -> str: File to read content

    :return List[str]: Content in file
    """
    with open(file, "r") as file:
        return [line for line in file]

def main() -> None:
    """
    Sets up argparser and runs main program
    """
    parser = argparse.ArgumentParser(description="Enter path to .fishy program file")
    parser.add_argument("Path", metavar="path", type=str, help="path to .fishy program file")
    args = parser.parse_args()
    file_path = args.Path

    if not os.path.isfile(file_path):
        sys.exit("The file does not exist")

    content = get_content(file_path)
    run_code(content)

if __name__ == "__main__":
    main()

Restructuring and optimization

The initial approach introduces inefficient file processing as get_content function reads all lines from the input file into a list at once and holds that list in memory throughout the entire processing. The traversal of the lines that were read is then redundantly repeated in run_code function.The more efficient way is to convert get_content into a generator function and consume one line from file at a time on demand.

The optimized get_content function:

def get_content(file: str) -> List[str]:
    """
    Yields lines from the passed file path
    :param file -> str: File to read content
    :return List[str]: Content in file
    """
    with open(file, "r") as file:
        for line in file:
            yield line.rstrip()

run_code function is renamed to parse_code

Inefficiency of validating and traversing commands

In parse_code (formerly run_code) function the commands sequence is potentially being traversed twice:
once on correct_syntax(commands) call and then - on getting numbers chr(get_number(fish)) for fish in commands.Moreover, consequent validations in this case may lead to redundant calculations.Consider the following situation: commands contains 10 items, all of them passed correct_syntax check but then, the 9th item fails on get_number check. That causes 10 redundant operations/checks.

To optimize validations we notice that is_fish and get_number are conceptually dependent on the same context - "fish" and are intended to validate the same "fish" object.Thus, those 2 validations are reasonably combined/consolidated into one validation function is_fish:

def is_fish(fish: str) -> bool:
    """
    Validates "fish" item
    Fish: Starts with >< ends with > and has number inside
    A fish like so ><98g> will fail the check

    """
    return fish.startswith("><") and fish.endswith(">") and fish[2:-1].isdigit()

get_number function is now removed. The correct_syntax function is renamed to get_fish_numbers and its responsibility now is "Collect fish numbers from valid fishes":

def get_fish_numbers(pond: List[str]) -> bool:
    """
    Collects fish numbers with checking the syntax of the passed list of commands on the following criteria:

    Is a fish ><..>

    Correct Example:
    ><98> ><108> ><56>

    Incorrect Example:
    ><98> >><<76>> ><[108>

    """
    fish_numbers = []
    for fish in pond:
        if not is_fish(fish):
            sys.exit(f"Incorrect Syntax: {fish}")
        fish_numbers.append(int(fish[2:-1]))

    return fish_numbers

And finally the optimized parse_code function:

def parse_code(code: List[str]):
    """
    Parse and output the passed Fishy Code
    """
    for line in code:
        # Clean up code and separate commands#
        commands = line.split(" ")

        # Check if line has multiple statements in it
        fish_numbers = get_fish_numbers(commands)
        if len(fish_numbers) > 1:
            output = "".join(chr(num) for num in fish_numbers)
            print(output)
        else:
            print(chr(fish_numbers[0]))


Converting height map bitmap to json This is my first F# program.

It's a command line utility that takes a parameter containing a path to an height map bitmap and prints out this height map converted to JSON format.

open System.Drawing

let convertLine (y:int) (bitmap:System.Drawing.Bitmap) =
    [ for x in 0 .. bitmap.Width - 1 -> "\"" + bitmap.GetPixel(x, y).R.ToString() + "\"" ] |> String.concat ", "

let convert (path:string) : string =
    let bitmap = new System.Drawing.Bitmap(path)
    let results = [ for y in 0 .. bitmap.Height - 1 -> convertLine y bitmap ] |> String.concat ", "

    "{\"X\": \"" + bitmap.Width.ToString() +
    "\", \"Y\": \"" + bitmap.Width.ToString() +
    "\", \"values\":[" + results + "]}"

[<EntryPoint>]
let main argv =
    let arglist = argv |> List.ofSeq

    let returnValue =
        match arglist with
            | path :: _ -> convert path
            | _ -> "Wrong number of arguments supplied"

    printfn "%s" returnValue

    match returnValue with
        | "Wrong number of arguments supplied" -> 1
        | _ -> 0

I want to make sure to write idiomatic F# and to write in a functional style.

So I would make some changes:

let returnValue =
    match arglist with
        | path :: _ -> convert path
        | _ -> "Wrong number of arguments supplied"

should probably be something like

let returnValue =
    match arglist with
        | path :: _ -> convert path
        | _ ->failwith "Wrong number of arguments supplied"

which would simplify some logic

I would also change the printing to use sprintf

"{\"X\": \"" + bitmap.Width.ToString() +
"\", \"Y\": \"" + bitmap.Width.ToString() +
"\", \"values\":[" + results + "]}"

becomes

sprintf "{\"X\": \"%i\", \"Y\": \"%i\", \"values\":[%s]}" (bitmap.Width.ToString() ) (bitmap.Width.ToString() ) results


MAXSPPROD linear algorithm I am working on the MAXSPPROD problem on interviewBit

  You are given an array A containing N integers. The special product of
  each ith integer in this array is defined as the product of the
  following:

  LeftSpecialValue: For an index i, it is defined as the index j such
  that A[j]>A[i] (i>j). If multiple A[j]’s are present in multiple
  positions, the LeftSpecialValue is the maximum value of j.

  RightSpecialValue: For an index i, it is defined as the index j such
  that A[j]>A[i] (j>i). If multiple A[j]s are present in multiple
  positions, the RightSpecialValue is the minimum value of j.

  Write a program to find the maximum special product of any integer in
  the array.

  Input: You will receive array of integers as argument to function.

  Return: Maximum special product of any integer in the array modulo
  1000000007.

  Note: If j does not exist, the LeftSpecialValue and RightSpecialValue
  are considered to be 0.

  Constraints 1 <= N <= 10^5 1 <= A[i] <= 10^9

Basically if you see the vector as a chart LeftSpecialValue and RightSpecialValue are values around local minima.

Here is the algorithm I came up with

#include <algorithm>
#include <vector>
#include <stack>
#include <iostream>

int mult_mod(int i, int j) {
    return ((i%1000000007) * (j%1000000007)) % 1000000007;
}

int next_bigger(std::vector<int>& v, std::stack<int>& stack, int i){
    while(!stack.empty()){
        int j = stack.top();
        if (v[j] <= v[i]){
            stack.pop();
        }
        else{
            stack.push(i);
            return j;
        }
    }
    stack.push(i);
    return 0;
}

void right( std::vector<int>& v, std::vector<int>& r ){
    std::stack<int> stack;

    for(int i = v.size() - 1; i >= 0; --i){
        r[i] = next_bigger(v, stack, i);
        stack.push(i);
    }
}

int maxProd( std::vector<int>&& v){
    std::vector<int> r(v.size());
    right(v, r);

    int mp = 0;
    std::stack<int> stack;
    for(int i = 0; i < v.size(); ++i){
        int j = next_bigger(v, stack, i );

        int mp_i = mult_mod(j, r[i]);
        if (mp < mp_i){
            mp = mp_i;
        }
    }
    return mp;
}

int main(){
    std::cout << maxProd({3,2,1,2,3}) << std::endl;
    std::cout << maxProd({1,2,3, 2, 1}) << std::endl;
    std::cout << maxProd({1,2,3, 4, 5}) << std::endl;
    std::cout << maxProd({0, 5, 1, 1, 1, 5}) << std::endl;
    std::cout << maxProd({5, 9, 6, 8, 6, 4, 6, 9, 5, 4, 9}) << std::endl;
        std::cout << maxProd({6, 7, 9, 5, 5, 8 }) << std::endl;
        std::cout << maxProd({1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,0,1}) << std::endl; //20

    }

This code is intended to be O(n) in time and space.
The algorithm passes all test but

  might be failing for larger test-cases

I believe it is because I am using an additional vector for RightSpecialValue, which means in worst case twice the size of the input memory.

Can it be improved to use less space?

I finally spotted the error in my submission : I was computing the maximum of left-most * right-most mod 1000000007 while I should have been computing the maximum  of left-most * right-most, then returning its value modulo 1000000007.

In other terms

int mp = 0;
std::stack<int> stack;
for(int i = 0; i < v.size(); ++i){
    int j = next_bigger(v, stack, i );

    int mp_i = mult_mod(j, r[i]);
    if (mp < mp_i){
        mp = mp_i;
    }
}
return mp;

Should be replaced by

long long int mp = 0;
std::stack<int> stack;
for (int i = 0; i < v.size(); ++i)
{
    long long int j = next_bigger(v, stack, i);
    long long int mp_i = j * r[i];
    if (mp < mp_i)
    {
        mp = mp_i;
    }
}
return mp % 1000000007;


Simple Ratelimiter Feedback I'm preparing for coding interviews and I wanted to get feedback on this question which asks you to write a simple ratelimiter that can handle 5 requests every 2 seconds for example. Since it is for a coding interview setting, I don't think it needs to be perfect.
I looked at the guava Ratelimiter for inspiration for this.
Please let me know if I have made any errors or any improvements that can be made. Any feedback is appreciated.
public class RateLimit {
    private double maxCapacity;
    private double refillRate;
    private double availableTokens;
    private long lastRefill;

    public RateLimit(double maxCapacity, long windowInSeconds) {
        this.maxCapacity = maxCapacity;
        this.lastRefill = Instant.now().toEpochMilli();
        this.refillRate = TimeUnit.SECONDS.toMicros(windowInSeconds) / maxCapacity ;
        this.availableTokens = maxCapacity;
    }

    public boolean acquire() {
        return acquire(1, true);
    }

    public boolean acquire(double requiredPermits) {
        return acquire(requiredPermits, true);
    }

    public boolean tryConsume(double requiredPermits) {
        return acquire(requiredPermits, false);
    }

    private synchronized boolean acquire(double requiredToken, boolean shouldBlock) {
        refill();

        boolean acquired = false;
        if (availableTokens >= requiredToken) {
            availableTokens -= requiredToken;
            acquired = true;
        } else if (shouldBlock) {
            double missingTokens = requiredToken - availableTokens;
            try {
                TimeUnit.MICROSECONDS.sleep((long) (refillRate * missingTokens));
                availableTokens = 0D;
                lastRefill = Instant.now().toEpochMilli();
                acquired = true;
            } catch (InterruptedException e) {
                System.out.println("Sleep interrupted");
            }
        }

        return acquired;
    }

    private void refill() {
        long now = Instant.now().toEpochMilli();
        if (now > lastRefill) {
            long elapsedTime = now - lastRefill;
            double tokensToBeAdded = Math.floor(TimeUnit.MILLISECONDS.toMicros(elapsedTime) / refillRate);
            if (tokensToBeAdded > 0) {
                availableTokens = Math.min(maxCapacity, availableTokens + tokensToBeAdded);
                lastRefill = now;
            }
        }
    }
```

Testability
Whilst not a prerequisite for a review, @Marc is correct that unit tests would be helpful here and you would usually want to include them in your exercise submission.  You want to demonstrate both that you know the code works as importantly that you've considered how easy it is to test.  Time in particular can be challenging to unit test if classes have not been constructed with it as a consideration.  You may wish to take a look at this Stack overflow question for some suggestions about how you could improve your time testability.
Naming
One of the things that struck me as a little odd was that your blocking methods are called acquire and your non-blocking method is called tryConsume.  I'm not sure I understand the disconnect, is there a reason it couldn't be called tryAcquire?  Have you been asked to provide both blocking and non-blocking versions of the limiter as part of the exercise?
final
Fields that don't change after they've been initialized (such as refillRate) should be marked as final to indicate that you're not planning on changing them.
Starvation and Flooding
Lets take your example of 5 requests every 2 seconds.  If I call acquire(500), nothing happens for 200 seconds, then 500 messages get sent (probably within a single second).  Is this the expected behaviour?  During the wait time while the number of required allocations are being waited on, no other threads are able to acquire and send either.  It's possible that this is expected/desired behaviour, however it seems like a potential flaw, particularly since a greedy blocking call could mean that the non-blocking request is never successful, so something I'd expect them to ask about if you get to interview.  Things to consider are do you need to allow a single call to reserve X permits, or would it be better to have them acquire single permits at a time as they send each message?  If you need to support multiple permits, should there be a limit on the maximum number of permits that can be requested in one go (such as the size of the window or maxCapacity).


Simple calculator with classes in C++ I came to C++ from Java. This is my attempt at making a calculator on about 2 days worth of knowledge. I don't really know what is redundant or unnecessary. Nor do I know of the better ways to achieve this effect.

First class (it does the math):

#pragma once
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class a {
public:
double add(double a, double b) {
    return a + b;
}
double sub(double a, double b) {
    return a - b;
}
double mult(double a, double b) {
    return a * b;
}
double div(double a, double b) {
    return a / b;
}
};

Second class (it makes the strings):

#pragma once
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class text {
public:
string add(double a, double b, double ans) {
    return to_string(a) + " + " + to_string(b) + " = " + to_string(ans);
}
string sub(double a, double b, double ans) {
    return to_string(a) + " - " + to_string(b) + " = " + to_string(ans);
}
string div(double a, double b, double ans) {
    return to_string(a) + " / " + to_string(b) + " = " + to_string(ans);
}
string mult(double a, double b, double ans) {
    return to_string(a) + " * " + to_string(b) + " = " + to_string(ans);
}
string first() {
    return "First Number: ";
}
string second() {
    return "Second Number: ";
}
string op() {
    return "Operator: ";
}
string wrong() {
    return "Invalid Operator!";
}
};

Main method:

#include "a.h"
#include "text.h"
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
text ask;
a mather;
string temp;
char op;
double a, b, ans;

cout << ask.op();
cin.get(op);
cout << ask.first();
cin >> a;
cout << ask.second();
cin >> b;

switch (op) {
case '+':
    ans = mather.add(a, b);
    temp = ask.add(a, b, ans);
    break;
case '-':
    ans = mather.sub(a, b);
    temp = ask.sub(a, b, ans);
    break;
case '/':
    ans = mather.div(a, b);
    temp = ask.div(a, b, ans);
    break;
case '*':
    ans = mather.mult(a, b);
    temp = ask.mult(a, b, ans);
    break;
default:
    cout << "Invalid Operator!";
}

cout << temp;
cin.get();
cin.get(); //I don't know how to avoid using this twice
return 0;
}

Welcome to C++.

A few notes:

When working outside of a toy project, avoid using namespace std. For why, see here.
In addition, when working outside of a toy project, I encourage you to define your classes within the scope of a namespace. Only you can fight namespace pollution.
Your a header does not make use of the iostream, string, or stringstream headers. They need not be included in that header.
Your text header does not make use of the iostream or stringstream headers. They need not be included in that header.
Header includes are transitive. Because your main function includes your text header which in turn includes the string header, the main.cpp need not also include string.
Your main implementation file does not make use of the sstream headers. They need not be included in that file.
Your a class methods made no use of the class instance. That said, these methods could be declared as static.
Your text class methods made no use of the class instance. That said, these methods could also be declared as static.
When you write to the terminal, you probably want a next line character. You can do this either by appending a \n to the output or by calling to std::endl in the iostream header. For more on the distinction, please see this post.
return 0; is actually unnecessary to indicate successful execution of the main function as of C99. reference

Also, please do not return a constexpr char *. Assuming you haven't specified otherwise, your compiler is very likely compiling to the C++ 11 specification. In which case, your string methods will be subject to return value optimization outside of debug mode and no temporary variables or heap allocations will be made.


Test if string is numeric I want to implement the following function:

// Return true if and only if 's' is numeric including
// leading positive/negative sign, decimal point.
bool isnumeric( const char * s );

It is somewhat similar to strtol() but I don't need to return the number.

My approach is to count various things unless I can bail out:

bool isnumeric( char const * str ) {
  if( !str ) { return false; }
  int signs = 0;
  int decimals = 0;
  int digits = 0;
  int digitsAfterDecimal = 0;

  for( char const * p = str; *p; ++p ) {

    if( (*p == '+') || (*p == '-') ) {
      if( (decimals > 0) || (digits > 0) ) { return false; }
      signs += 1;
      if( signs == 2 ) { return false; }
    }
    else if( *p == '.' ) {
      decimals += 1;
      if( decimals == 2 ) { return false; }
    }
    else if( ! isdigit( *p ) ) {
      return false;
    }
    else {
      digits += 1;
      if( decimals > 0 ) {
        digitsAfterDecimal += 1;
      }
    }
  }
  return (decimals > 0) ? ((digits > 0) && (digitsAfterDecimal > 0))
                        : (digits > 0) ;
}

I also have the following tests:

void test_isnumeric() {
  assert( isnumeric( "42" ) );
  assert( isnumeric( "42.0" ) );
  assert( isnumeric( "42.56" ) );
  assert( isnumeric( "+42" ) );
  assert( isnumeric( ".42" ) );
  assert( isnumeric( "+.42" ) );

  assert( ! isnumeric( "42." ) );
  assert( ! isnumeric( "++42" ) );
  assert( ! isnumeric( "+." ) );
  assert( ! isnumeric( "4+" ) );
}

int main( void ) {
  test_isnumeric();
}

To make it easy to clone and modify, the full code is available here.

Please comment on design, structuring, test coverage etc. Mentioning failing tests are most welcome.

State variables are bad. Keep the state explicit, along the lines of:

if (*p == '+' || *p == '-') p++;
if (!isdigit(*p)) return False;
while (isdigit(*p)) p++;
if (*p == 0) return True;
if (*p != '.') return False;
p++;
while (isdigit(*p)) p++;
return *p == 0;

Update: few fixes thanks to Edward


Finding minimum array integer I'm trying to solve one simple task and on first look it's working.
Any advice on how I can optimize this code will be appreciated.
A quick description of the task would be:
You have a file from which you read the integers.

The first line has two values:

The array width
The number of test cases

The second line has actual array values.
After that, you have \$N\$ rows all containing the array range which should be checked.

\$N =\$ the number of test cases.
Here's a link to my code

<?php
$handle = fopen("php://stdin", "r");
$getFirstRow = fgets($handle);
$firstrow = explode(" ", $getFirstRow);
$firstrow1 = intval($firstrow[0]);
$firstrow2 = intval($firstrow[1]);

$getString = fgets($handle);
for ($z=0;$z<$firstrow2;$z++)
{
$getRange = fgets($handle);
$getRagearr = explode(" ", $getRange);
$i=intval($getRagearr[0]);
$j=intval($getRagearr[1]);
$arrResult = array();
$lane = explode(" ", $getString);
for ($p=$i;$p<=$j;$p++)
{
array_push($arrResult, $lane[$p]);
}
$result = min($arrResult);
echo $result.PHP_EOL;
}

You should indent your code properly to make it more readable.

Posting PHP on JSFiddle is apocalyptic insanity a bad idea. JSFiddle is for JavaScript.
Use IDEOne for PHP Instead.

Your use of whitespace could be improved.

 for ($z=0;$z<$firstrow2;$z++)

into: for ($z = 0; $z < $firstrow2; $z++)

Your variable naming is shortened, sometimes confusing, and flat out bad practice in places.
Transform them from lowercase to camelCase.

You don't even use $firstrow1, remove it.

$getRagearr sounds like a pirate themed narcotic. Perhaps $getRangeArray would be much clearer.

$j=intval($getRagearr[1]): what's wrong with good ole' fashioned int()?'

This is the result of all my suggestions:

$handle = fopen("php://stdin", "r");
$getFirstRow = fgets($handle);
$firstRowArray = explode(" ", $getFirstRow);
$numOfTestCases = int($firstRow[1]);

$getString = fgets($handle);
for ($i = 0; $i < $numOfTestCases; $i++) {
    $getRange = fgets($handle);
    $getRangeArray = explode(" ", $getRange);
    $arrayWidth = int($getRangeArray[0]);
    $arrayLength = int($getRangeArray[1]);
    $arrayResult = array();
    $lane = explode(" ", $getString);
    for ($currentPos = $arrayWidth; $currentPos <= $arrayLength; $currentPos++) {
        array_push($arrayResult, $lane[$currentPos]);
    }
    $result = min($arrayResult);
    echo $result.PHP_EOL;
}

Other than that, your code looks well-structured.


Print all lines of a text file containing the same duplicated word I'm implementing my very first Go application and I would like to receive an hint on how to make a certain check faster.

I have a huge txt file in which each line is structured like the following:

key text
key text
   .
   .
key text

Where key is ALWAYS 6 HEX digits long and text is ALWAYS 16 HEX digits long.

  I need to find and print all the lines which have the same text value.
  For instance, suppose we have 2 lines like the following

  000000 1234567890123456
  111111 1234567890123456

  They should be both printed.

Here's my code:

r, _ := os.Open("store.txt")
    scanner := bufio.NewScanner(r)
    for scanner.Scan() {
        line := scanner.Text()
        text := line[7:]
        if !contains(duplicates, text) {
            duplicates = append(duplicates, text)
        } else {
                t, _:= os.Open("store.txt")
                dupScan := bufio.NewScanner(t)
                    //currLine := dupScan.Text()
                for dupScan.Scan() {
                    currLine   := dupScan.Text()
                    currCipher := currLine[7:23]
                    if( currCipher == text ){
                    fmt.Println(currLine)
                    }
                }
                t.Close()
            }
    }
fmt.Println("Done Check")
//Close File
r.Close()

func contains(s []string, e string) bool {
    for _, a := range s {
        if a == e {
            return true
        }
    }
    return false
}

It works just fine but, since I have million lines, it's really slow. I'm only capable of doing it with a single thread and not using goroutines.

Have you any suggestion on how I should change this code to speed up the check?

You have a bug

I don't think your program works as intended. If a line exists \$N > 1\$ times, it will be printed \$N (N - 1)\$ times. Because:

The first time it's seen, it will be added to duplicates and not printed. So far so good.
The 2nd, 3rd, ... Nth time it's seen, all \$N\$ occurrences will be printed.

When \$N = 2\$, the program will appear to work fine.
But when \$N > 2\$ there will be excess output of duplicates, which is probably not the way you intended.

Performance

There are several inefficient operations.

The worst is re-reading the file for every duplicate. If the million lines contain pairs of 500000 values, the file will be read 500001 times.

Another inefficient operation is storing the unique values in a slice, instead of a map. The contains implementation based on a slice has  \$O(n)\$ time complexity, which would be \$O(1)\$ using a map.

To improve performance you could use a map of counts. Read the entire file once to build this map. Unique values will have a count of 1, duplicates will have > 1. Read the file again, checking the count in the map, if it's > 1 then print the line.

Resource management and error handling

In Go, it's recommended to use defer to close resources soon after you opened them, so you don't forget later. So instead of this:

fh, err := os.Open(path)

// large block of code

fh.Close()

It's recommended to write like this:

fh, err := os.Open(path)
if err != nil {
    panic("could not open file: " + path)
}
defer fh.Close()

// rest of the code

Closely related is error handling. You ignored the error value returned by os.Open, which is not wise. The rest of the program will make little sense if opening the file fails. Always remember and consider to handle errors.

Coding style

It's good to run go fmt on your program before asking for a review.
It automatically reformats it following the standard of Go.

Suggested implementation

Putting the above tips together:

func main() {
    path := "/tmp/store.txt"
    counts := readCounts(path)
    check(path, counts)
}

func check(path string, counts map[string]int) {
    fh, _ := os.Open(path)
    defer fh.Close()

    scanner := bufio.NewScanner(fh)
    for scanner.Scan() {
        line := scanner.Text()
        text := line[7:]
        if counts[text] > 1 {
            fmt.Println(line)
        }
    }
}

func readCounts(path string) map[string]int {
    fh, err := os.Open(path)
    if err != nil {
        panic("could not open file: " + path)
    }
    defer fh.Close()

    scanner := bufio.NewScanner(fh)
    counts := make(map[string]int)

    for scanner.Scan() {
        line := scanner.Text()
        text := line[7:]
        counts[text] += 1
    }

    return counts
}


Remove specified number of characters from a string From an exercise in Kochan's Programming in C, following a chapter on C's null-terminated strings:

  Write a function called removeString to remove a specified number of
  characters from a character string. The function should take three
  arguments: the source string, the starting index number in the source
  string, and the number of characters to remove. So, if the character
  array text contains the string "the wrong son", the call

  removeString (text, 4, 6);

  has the effect of removing the characters “wrong “ (the
  word “wrong” plus the space that follows) from the array text. The
  resulting string inside text is then "the son".

I found the exercise interesting to implement. I know I could have used strlen to get the length of the string, but I like the idea of handling everything in a single pass (I imagine strlen has to traverse the characters looking for a null-byte).

Any comments/criticisms are welcome. Here's my solution:

void removeString (char text[], int index, int rm_length)
{
    int i;

    for ( i = 0; i < index; ++i )
        if ( text[i] == '\0' )
            return;

    for ( ; i < index + rm_length; ++i )
        if ( text[i] == '\0' ) {
            text[index] = '\0';
            return;
        }

    do {
        text[i - rm_length] = text[i];
    } while ( text[i++] != '\0' );
}

And a test drive

int main (void)
{
    char string1[] = "the wrong son";
    char string2[] = "the wrong son";
    char string3[] = "the wrong son";

    printf ("string1: %s\n", string1);
    printf ("string2: %s\n", string2);
    printf ("string3: %s\n\n", string3);

    printf ("removeString (string1, 13, 6)\n");
    removeString (string1, 13, 6);
    printf ("string1: %s\n\n", string1);

    printf ("removeString (string2, 11, 6)\n");
    removeString (string2, 11, 6);
    printf ("string2: %s\n\n", string2);

    printf ("removeString (string3, 4, 6)\n");
    removeString (string3, 4, 6);
    printf ("string3: %s\n\n", string3);

    return 0;
}

Output:

string1: the wrong son
string2: the wrong son
string3: the wrong son

removeString (string1, 13, 6)
string1: the wrong son

removeString (string2, 11, 6)
string2: the wrong s

removeString (string3, 4, 6)
string3: the son

One quick stylistic comment.

Braces

for ( ; i < index + rm_length; ++i )
    if ( text[i] == '\0' ) {
        text[index] = '\0';
        return;
    }

Constructs like this are begging to have a subtle hidden bug in them. Always use braces if you have more than a single statement inside a for/if statement.

for (; i < index + rm_length; ++i) {
    if ( text[i] == '\0' ) {
        text[index] = '\0';
        return;
    }
}