texts:
I have a script that takes addresses from a CSV, and tries to find the GPS coordinates.

I am still learning Python, so comments as to general formatting (i.e. variable names, function names, etc.) are appreciated, as well as ways to tighten up the code.  (I'm using the csv module and geopy).

The CSV is a single column of addresses (following are dummy addresses) saved as a .csv file:

123 Main Street, Chicago, IL 12345
3214 Overland Drive, Los Angeles, CA 49382
29 NE 9th Street, New York, NY 29384

And my .py file:

import csv
from geopy.geocoders import Nominatim
from geopy.geocoders import GoogleV3

ADDRESS_FILE = "Addresses"

def read_csv(file):
    with open(file,'r') as f:
        reader = csv.reader(f)
        address_list = list(reader)
    return address_list

def get_lat_lon(address):
    geolocator = Nominatim()
    try:
        location = geolocator.geocode(address)
        return location.latitude, location.longitude
    except Exception:
        return 0, 0

def google_lat_lon(address):
    geolocator = GoogleV3(api_key="xxxxx")
    try:
        location = geolocator.geocode(address)
        return location.latitude, location.longitude
    except Exception:
        return 0, 0

def find_coordinates(address):
    google_found = ""
    lat, lon = get_lat_lon(address)
    lat, lon = google_lat_lon(address)
    if lat == 0 and lon == 0:
        lat, lon = google_lat_lon(address)
        google_found = "Note: used Google"
    return lat, lon, google_found

def write_file(info):
    with open(ADDRESS_FILE+" with GPS.csv","w", newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter = ",")
        for line in info:
            writer.writerow(line)

def main():
    addresses = read_csv(ADDRESS_FILE+".csv")
    address_GPS = []
    for address in addresses:
        addr = address[0].replace(u'\xa0', u' ')
        lat, lon, google_found = find_coordinates(addr)
        address_GPS.append((addr,lat,lon, google_found, '=HYPERLINK("https://www.google.com/maps/search/"&B1&","&C1,"Link")'))

    for addr in address_GPS:
        print(addr[:len(addr)-1])
    write_file(address_GPS)

if __name__ == '__main__':
    main()

Preliminary thoughts:

addr = address[0].replace(u'\xa0', u' ') - I have this because for some reason when reading the CSV, \xa0 appears in the string, throwing off the lookup. I think it's due to Encoding? I created the CSV in Excel, File-> Save as .CSV (regular .csv, not the option for Mac, or whatever else).
except Exception: - I think I should be more specific here? That's there in case there's no location found with the address.
The if lat == 0 and lon == 0 is there in case the regular geopy lookup doesn't work, I use their Google Maps option.  But say that doesn't work, and I want to use Bing or edit the address, there's probably a better way than keep on nesting that if lat == 0 and lon == 0 part.
Is it okay to have my main() like I do? Or is it better to keep the lines in main() to primarily be function calls?
Is it wise/good practice to have a return a, b, c, ..., z? Or is it best to return just one or two things per return?


texts:
Given two strings, check whether two given strings are anagram of each
  other or not. An anagram of a string is another string that contains
  same characters, only the order of characters can be different. For
  example, “act” and “tac” are anagram of each other.

  Input:

  The first line of input contains an integer T denoting the number of
  test cases. Each test case consist of two strings in 'lowercase' only,
  in a separate line.

  Output:

  Print "YES" without quotes if the two strings are anagram else print
  "NO".

  Constraints:

  1 ≤ T ≤ 30

  1 ≤ |s| ≤ 100

  Example:

  Input:

  2

  geeksforgeeks

  forgeeksgeeks

  allergy

  allergic

  Output:

  YES

  NO

My approach:

/*package whatever //do not write package name here */

import java.util.Scanner;
import java.io.IOException;
import java.util.HashMap;

class GFG {

    private static String isAnagram (String str1, String str2)
        {
            HashMap <Character, Integer>occurs = new HashMap<>();

            if (str1.length() != str2.length())
                {
                    return "NO";
                }

            for (char ch: str1.toCharArray())
                {
                    if (!(occurs.containsKey(ch)))
                        {
                            occurs.put(ch,1);
                        }
                    else
                        {
                            int count = occurs.get(ch);
                            occurs.put(ch,count + 1);
                        }
                }

            for (char ch: str2.toCharArray())
                {
                    if (!(occurs.containsKey(ch)))
                        {
                            return "NO";
                        }
                    else
                        {
                            int count = occurs.get(ch);
                            count  = count - 1;
                            if (count < 0)
                                {
                                    return "NO";
                                }
                            else
                                {
                                    occurs.put(ch,count);
                                }
                        }
                }

        return "YES";
        }

    public static void main (String[] args) throws IOException {
        Scanner sc = new Scanner (System.in);
        int numTests = sc.nextInt();

        for (int i = 0; i < numTests; i++)
            {
                String str1 = sc.next();
                String str2 = sc.next();
                System.out.println(isAnagram(str1, str2));
            }
    }
}

I have the following questions with regards to the above code:

1) How can I further improve my approach?

2) Is there a better way to solve this question?

3) Are there any grave code violations that I have committed?

4) Can space and time complexity be further improved?

Reference


texts: Dealing with a command line argument (path) with spaces

texts:
I created a key in Windows registry to have an option on every folder which allows me to simply right click, choose the right option and have a PDF made, either from JPGS, or PNGs, or TIFs.

My registry key is as follows:

  '"C:\strawberry\perl\bin\perl.exe" "C:\Users\michal\Documents\createpdf\790024.pl" "%1"'.

The code, thanks to suggestions and some major modifications by Matt Jacob works. Dealing with paths with spaces is done by:

my $folder = $ARGV[0];
$folder =~ s|\\|/|g;
$folder =~ s|/$||;

To read files I have came up with this: my @files = <"$folder/*">;

As I am a Perl newbie, I would like to see if this is correct. It works on my system.

The whole script is as follows:

#!/usr/bin/perl

use PDF::API2;
use strict;
use warnings;

my $folder = $ARGV[0];
$folder =~ s|\\|/|g;
$folder =~ s|/$||;

my $pdf_file = $folder . '.pdf';

die "Not a folder!\n" unless -d $folder;
die "There's already a pdf of that name!\n" if -f $pdf_file;

my $pdf = PDF::API2->new;

my %dispatch = (
    jpg => sub { $pdf->image_jpeg(@_) },
    png => sub { $pdf->image_png(@_) },
    tif => sub { $pdf->image_tiff(@_) },
);

my @files = <"$folder/*">;

for my $ext (sort(keys(%dispatch))) {
    my $count;

    for my $file (@files) {
        next unless $file =~ /\.$ext$/;

        my $image = $dispatch{$ext}->($file);
        my $page = $pdf->page;
        $page->mediabox(0, 0, $image->width, $image->height);
        $page->trimbox(0, 0, $image->width, $image->height);
        my $gfx = $page->gfx;
        $gfx->image($image, 0, 0);

        $count++;
    }

    last if $count;
}

if ($pdf->pages) {
    $pdf->saveas($pdf_file);
}


texts: Shortest pathway across a snakes and ladders board (Update)

texts:
Earlier I posted a fairly inefficient recursive solution to the problem of getting across a snakes and ladders board in the smallest number of moves.

I have created a much faster solution to this using Dijkstra's algorithm and I believe it is correct.

Each square on the board is linked to any square that is between 1-6 larger than it with a weight of one (equivalent of rolling a 1-6 on a dice). All snakes and ladders link squares with a weight of 1. The aim was to have the smallest total cost for the pathway between 1 and 100 (0 and 99 here as I have used list indexes).

This is the first time I have implemented Dijkstra's algorithm and the first time I have used namedtuples. I am not sure if using namedtuples was appropriate, but it made it clearer in my head.

I think I have massively over-complicated bits of code especially within the for loop under the condition if edge.start == next_item:. I seem to be using list comprehensions far too much and I know this makes the solution slower than it could be. Please could someone help me work out better ways to access the variables in my queue of named-tuples.

"""Calculate the shortest path across a snakes and ladders board using Dijkstra's shortest path"""
from collections import namedtuple

Edge = namedtuple("Edge", ("start", "end", "cost"))
Stack = namedtuple("Stack", ("start", "pathcost", "totalcost"))

class Graph:
    """Class generates graph and calculates shortest path"""
    def __init__(self, edges):
        """Generate edges in graph"""
        self.edges = [Edge(*edge) for edge in edges]

    def dijkstra_path(self, start, end):
        """Function that calculates the shortest path"""
        if start >= end or start < 0 or end > 99:
            return -1
        queue = sorted(
            (
                Stack(edge.end, edge.cost, edge.cost)
                for edge in self.edges
                if edge.start == start
            ),
            key=lambda x: x[2],
        )
        while queue:
            next_item, _, current_total = queue.pop(0)
            if next_item == end:
                return current_total
            for edge in self.edges:
                if edge.start == next_item:
                    if edge.end in [item.start for item in queue]:
                        current_cost = [
                            item.totalcost for item in queue if item.start == edge.end
                        ][0]
                        if not current_cost < edge.cost + current_total:
                            queue = [item for item in queue if item.start != edge.end]
                            queue.append(
                                Stack(edge.end, edge.cost, edge.cost + current_total)
                            )
                    else:
                        queue.append(
                            Stack(edge.end, edge.cost, edge.cost + current_total)
                        )
            queue = sorted(queue, key=lambda x: x[2])

def build_graph():
    """Chess Board"""
    list_board = [[i, i + j, 1] for i in range(100) for j in range(1, 7)]
    # Ladders
    list_board.append([1, 37, 1])
    list_board.append([19, 59, 1])
    list_board.append([28, 63, 1])
    list_board.append([55, 99, 1])
    # Snakes
    list_board.append([91, 13, 1])
    list_board.append([86, 11, 1])
    list_board.append([53, 2, 1])
    list_board.append([41, 13, 1])
    return list_board

if __name__ == "__main__":
    GRAPH = Graph(build_graph())
    FROM = 0
    TO = 100
    NUMBER_STEPS = GRAPH.dijkstra_path(FROM, TO)
    if not NUMBER_STEPS == -1:
        print(f"Can complete game in a minimum of {NUMBER_STEPS} rolls")
    else:
        print("Error. Make sure the starting point is between 0 and 99 and less than the end point",
              "which itself must be than or equal to 99")


texts:
This is related to DataDictionary Application - Model

I haven't done much on the controllers yet, as it's the first time I've written Controller-type classes and wanted some quick feedback on really simple stuff, so these presently just contain various Get methods. If this is ok for a start, I'll begin adding in all the other stuff the controllers will do.

Controller

Here's where all that structuring (hopefully) in the Model starts to come in useful. I decided to write controllers for each schema - DictionaryController, SysDataController and CompareController. I realised after writing my DictionaryController, the other two would be near identical:

//original DictionaryController
class DictionaryController {
    private Dictionary.Context context;

    public DictionaryController() {
        this.context = new Dictionary.Context();
    }

    // gets all databases
    public List<Dictionary.Database> GetDatabases() {
        this.context.Databases.Load();
        return this.context.Databases.ToList();
    }

    // get database with the given primary key
    public Dictionary.Database GetDatabase(params object[] primaryKey) {
        return this.context.Databases.Find(primaryKey);
    }

    // gets all schemas
    public List<Dictionary.Schema> GetSchemas() {
        this.context.Schemas.Load();
        return this.context.Schemas.ToList();
    }

    // get all schemas belonging to the database with the given ID
    // any primary key can be passed, it will just read the first item in the array
    public List<Dictionary.Schema> GetSchemas(params object[] databasePrimaryKey) {
        var databaseID = (int)databasePrimaryKey[0];

        return (from schemas in this.Context.Schemas
                where schemas.DatabaseID == databaseID
                select schemas).ToList();
    }

    // etc
}

So, I scrapped that and instead wrote a general Controller abstract class (time to put that IContext to work!):

public abstract class Controller<TDatabase, TSchema, TTable, TColumn>
    where TDatabase : class, IEntityKey, IDatabaseKey
    where TSchema : class, IEntityKey, ISchemaKey
    where TTable : class, IEntityKey, ITableKey
    where TColumn : class, IEntityKey, IColumnKey
{
    protected IContext<TDatabase, TSchema, TTable, TColumn> Context { get; set; }

    public List<TDatabase> GetDatabases()
    {
        this.Context.Databases.Load();
        return this.Context.Databases.ToList();
    }

    public TDatabase GetDatabase(params object[] primaryKey)
    {
        return this.Context.Databases.Find(primaryKey);
    }

    public List<TSchema> GetSchemas()
    {
        this.Context.Schemas.Load();
        return this.Context.Schemas.ToList();
    }

    public List<TSchema> GetSchemas(params object[] databasePrimaryKey)
    {
        var databaseID = (int)databasePrimaryKey[0];

        return (from schemas in this.Context.Schemas
                where schemas.DatabaseID == databaseID
                select schemas).ToList();
    }

    // etc
}

And now my concrete controllers are much more simple:

public class DictionaryController
    : Controller<Dictionary.Database, Dictionary.Schema, Dictionary.Table, Dictionary.Column>
{
    public DictionaryController()
    {
        this.Context = new Dictionary.Context();
    }
}

public class CompareController
    : Controller<Compare.Database, Compare.Schema, Compare.Table, Compare.Column>
{
    public CompareController()
    {
        this.Context = new Compare.Context();
    }
}

public class SysDataController
    : Controller<SysData.Database, SysData.Schema, SysData.Table, SysData.Column>
{
    public SysDataController()
    {
        this.Context = new SysData.Context();
    }
}

Is this a good way to structure it? Or should I consider breaking it down further into DictionaryDatabaseController, DictionarySchemaController etc?


texts: Display the relative time difference between two dates

texts:
Goal: To create a function that returns the relative time difference between two given timestamps, using the DateTime class.

Current approach:

function time_elapsed($date1, $date2) {
    $dt1 = new DateTime($date1);
    $dt2 = new DateTime($date2);

    $diff = $dt1->diff($dt2);

    $ret = $diff->format('%y years, %m months, %a days, %h hours, %i minutes, %S seconds');

    $ret = str_replace(
        array('0 years,',' 0 months,',' 0 days,',' 0 hours,', ' 0 minutes,'),
        '',
        $ret
    );

    $ret = str_replace(
        array('1 years, ',' 1 months, ',' 1 days, ',' 1 hours, ',' 1 minutes'),
        array('1 year, ','1 month, ',' 1 day, ',' 1 hour, ',' 1 minute'),
        $ret
    );

    return $ret;
}

As you can see, the function works fine. I'm currently using a couple of str_replace() calls to remove the unnecessary parts from the formatted string, but I don't think that's a very good approach. I'm sure what I have written can be cleaned up and improved, using a different approach, perhaps.


texts:
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

Write a function:

class Solution { public int solution(int N); }

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..2,147,483,647].

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Solution s = new Solution();
        int x = s.solution(1041);

        System.out.println(x);
    }

}

class Solution {

    public int solution(int N)
    {
        int countZero = 0;
        Integer maxCountZeroList = 0;

        List<Integer> countZeroList = new ArrayList<Integer>();

        String nBin = Integer.toBinaryString(N);
        for (int i=1;i<nBin.length();i++) {

            if(nBin.charAt(i) == '1')
            {
                countZeroList.add(countZero);
                countZero = 0;
            }
            else
            {
                countZero++;
            }

        }

        if(countZeroList.size() > 0)
        {
            maxCountZeroList = Collections.max(countZeroList);
        }
        return maxCountZeroList;
    }
}

I am looking for more efficient way of solution of this problem


texts: Formatting a list with commas and occasional line breaks

texts:
I have an array mapped to make a typical result string separated by commas and with numbers a bit beautified with array.map(formatNumber).

Expected format is

number [quantity], number [quantity], number [quantity]

So

1234 [3], 1235 [2], 2234 [1]

My mapping function was like this:

function formatNumberSelected(number, i) {
    return number.number + " [" + number.amount() + "]" + (i % 5 === 4 ? ',
' : ', ');
}

But to avoid comma (or comma and
) in the last iteration now is:

function formatNumberSelected(number, i, array) {
  var toReturn = number.number + " [" + number.amount() + "]";
  if ((i + 1) < array.length) {
    if (i % 5 === 4) toReturn += ',
';
    else toReturn += ', ';
  }
  return toReturn;
}

There is a better way to make this code more readable? Seems like passing array to each iteration just to find the last index is a bit too much.

If not I find better this solution not using Array.prototype.map:

function formatNumberArray(array) {
  var SEPARATOR = '';
  var toReturn = '';
  for (var index in array) {
    toReturn += SEPARATOR + array[index].number + ' [' + array[index].amount() + ']';
    if (index % 5 === 4) SEPARATOR = ',
';
    else SEPARATOR = ', ';
  }
  return toReturn;
}


texts: Inserting an entire form into MySQL database

texts:
Please review this.

public int InsertQuery(string Query)
{
    int LastInsertedID = -1;
    MySqlCommand MySqlCmd = new MySqlCommand(Query, this.sqlConn);
    try
    {
        MySqlCmd.ExecuteNonQuery();
        LastInsertedID = int.Parse(MySqlCmd.LastInsertedId.ToString());
    }
    catch (Exception excp)
    {
        Exception myExcp = new Exception("Could not execute INSERT Query.
" + Query + "
 Error:
" + excp.Message, excp);
        throw (myExcp);
    }
    return LastInsertedID;
}

public int AddChannel(NameValueCollection FormValues)
{
    string Keys = string.Join(",",FormValues.AllKeys);

    string Values = string.Join(",", FormValues.AllKeys.Select(key => String.Format("\"{0}\"", HttpContext.Current.Server.HtmlEncode(FormValues[key]))));
    return InsertQuery("INSERT INTO channels (" + Keys + ") VALUES (" + Values + ");");
}


texts:
I have a list of lines and I need to merge those who are similar (for example my machine vision script will return 3 small vertical line instead of one long vertical line).

I came up with this.
I'm not pleased with it, what do you think?

import math

class Point():
    def __init__(self, x, y):
        """
        Represent a point in a plan
            - x : x (on the width axis, 0 is at the left)
            - y : y (on the height axis, 0 is on the top)
        """
        self.x = int(x)
        self.y = int(y)

    def __str__(self):
        return '(Point : x=%s, y=%s)' %(self.x, self.y)

class Line():
    def __init__(self, a, b):
        """
        Represent a plan
            - a : viewanalyser.Point, start of the line
            - b : viewanalyser.Point, end of the line
        """
        self.a = a
        self.b = b

    def __str__(self):
        return 'Line with points : a=%s, b=%s' %(self.a, self.b)

def find_vLinesToMerge(vLines, tolerance):

    """
    Find vertical lines that can be merged (meaning they have the same x,
    there is a tolerance, for ecample if tolerance = 20 then 2 vertical lines
    spaced for less than 20 pixel on the x absciss are considered to be mergeable
        -vLines : list(Lines) : MUST BE VERTICAL LINES ONLY
        -tolerance : (int) : tolerance for detecting similar vertical lines
    """

    toMerge = []
    alreadyFlaggedForMerge = set()
    for i in range(len(vLines)):
        if i in alreadyFlaggedForMerge:
            continue
        toMergeInThisRun = set()
        for j, line in enumerate(vLines):
            if math.fabs(vLines[i].a.x - line.a.x)<tolerance:
                alreadyFlaggedForMerge.add(i)
                alreadyFlaggedForMerge.add(j)
                toMergeInThisRun.add(i)
                toMergeInThisRun.add(j)
        toMerge.append(toMergeInThisRun)

    return toMerge

vertical_lines = []
vertical_lines.append(Line(Point(1, 7), Point(1, 13)))#---------------------a / index[0]
vertical_lines.append(Line(Point(1, 14), Point(1, 27)))#--------------------a / index[1]
vertical_lines.append(Line(Point(1, 28), Point(1, 35)))#--------------------a / index[2]
vertical_lines.append(Line(Point(50, 1), Point(50, 5)))#--------------------b / index[3]
vertical_lines.append(Line(Point(80, 7), Point(80, 13)))#-------------------c / index[4]
vertical_lines.append(Line(Point(1, 36), Point(1, 55)))#--------------------a / index[5]
vertical_lines.append(Line(Point(50, 6), Point(50, 13)))#-------------------b / index[6]
vertical_lines.append(Line(Point(100, 7), Point(100, 13)))#-----------------d / index[7]
vertical_lines.append(Line(Point(100, 14), Point(100, 200)))#---------------d / index[8]
vertical_lines.append(Line(Point(100, 201), Point(100, 500)))#--------------d / index[9]
vertical_lines.append(Line(Point(80, 14), Point(80, 200)))#-----------------c / index[10]
vertical_lines.append(Line(Point(1000, 7), Point(1000, 13)))#---------------e / index[11]

print find_vLinesToMerge(vertical_lines, 20)

Output :

[set([0, 1, 2, 5]), set([3, 6]), set([10, 4]), set([8, 9, 7]), set([11])]


texts:
I'm using maps to represent a polynomial.
The key is the exponent and the value is the coefficient : Map(exp -> coef)

e.g. 2.5*x^5 + 3.0 is represented by : Map(5 -> 2.5, 0 -> 3.0)

I wrote 3 functions (in Scala) to add such polynomials. Which one is the most elegant ? Do you have another version that is preferable/better ? (Implementations in another language such as Haskell are welcome)

Here is a sample testcase :

val polynom1 = Map(0 -> 1.0, 1 -> 2.0, 2 -> 1.0)
val polynom2 = Map(0 -> 1.0, 1 -> (-2.0), 2 -> 1.0)
val expectedSum = Map(0 -> 2.0, 1 -> 0.0, 2 -> 2.0)

Here are the implementations :

def addMap1(lhs: Map[Int, Double], rhs: Map[Int, Double]) =
  ((lhs.keys ++ rhs.keys) map { k =>
    (k, lhs.getOrElse(k, 0.0) + rhs.getOrElse(k, 0.0))
  }).toMap

def addMap2(lhs: Map[Int, Double], rhs: Map[Int, Double]) = {
    def adjust(kv: (Int, Double)) = {
      val (exp, coef) = kv
      (exp, coef + lhs.getOrElse(exp, 0.0))
    }
    lhs ++ (rhs map adjust)
  }

def addMap3(lhs: Map[Int, Double], rhs: Map[Int, Double]) = {
    def addTerms(acc: Map[Int, Double], x: (Int, Double)) = {
      val (exp, coef) = x
      acc + (exp -> (coef + rhs.getOrElse(exp, 0.0)))
    }
    (lhs foldLeft rhs)(addTerms)
  }


texts: Looping through selected cells to indent text

texts:
I have written the following Google Spreadsheet script that attempts to loop through all selected cells and then update the value so that it adds an indent, by adding

=CONCAT(REPT( CHAR( 160 ), 5),"' + value[row] + '")

around the value.

Is there a better way to achieve this?

var ss = SpreadsheetApp.getActiveSpreadsheet();

function indentText() {
  var values = ss.getActiveRange().getValues();
  var newValues = new Array();

  for (i = 0; i < values.length; i++) {
    if (values[i][0] != '') {
      newValues.push(['=CONCAT(REPT( CHAR( 160 ), 5),"' + values[i][0] + '")']);
    } else {
      newValues.push(['']);
    }
  }

  ss.getActiveRange().setValues(newValues);

};

function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [{
    name : "Indent Text",
    functionName : "indentText"
  }];
  sheet.addMenu("Indent Text", entries);
};


texts: Generate similar methods programmatically

texts:
I'm repeatedly faced with writing proxy classes for various purposes, recently lazy evaluation and IPC. This usually means having a single method pattern, which just forwards the call. I'm having a hard time to do this efficiently and readable.

Let's consider an example of a (trimmed down) lazy evaluation proxy:

class Lazy(object):
    """Mockup of a Lazy-Evaluation proxy"""
    def __init__(self, call, *args, **kwargs):
        self._resolve=lambda: call(*args, **kwargs)

    def __getattr__(self, name):
        # forward getattr
        return getattr(self._resolve(), name)

    def __call__(self, *args, **kwargs):
        # forward call
        return self._resolve()(*args, **kwargs)

Basically, every method could be logically defined by a factory:

def make_lazy_method(name):
    def method(self, *args, **kwargs):
        target = self._resolve()
        return getattr(target, name)(*args, **kwargs)
    return method

Usually, I cannot rely on __getattr__, __setattr__ fetching methods for me, since there may be scoping involved (e.g. holding a lock during a method call) or I need special methods (e.g. __add__, __call__, ...).

So far, I have some approaches, which all have quite some downsides. Since they all seem convoluted somehow, my question is which one(s) are not just hacks but follow best practice.

Note that the code in question is not the resulting class, but the way of generating said class.

The obvious one is to do everything by hand.

class LazyVerbose(Lazy):
    def __add__(self, other):
        return self._resolve() + other

    def __radd__(self, other):
        return other + self._resolve()
    # roughly 280 more lines of code for other operators

This works reliably, but creates tons of duplicate code. It is difficult to write, read and maintain.
In older projects, I've modified the class' locals during creation.

import operator
class LazyLocals(Lazy):
    cls_locals = locals()
    cls_locals.update({'__%s__' % name: make_lazy_method('__%s__' % name) for name in dir(operator) if '__%s__' % name in dir(operator)})

While this worked so far, the docs explicitly advice against it and it seems to be differently defined across implementations.
Using exec to run method code created programmatically.

Portable, but kills any chance at introspection, tracebacks, maintainability or readability. Also, exec.
Using a custom metaclass.

import operator
class WrappedType(type):
    def __new__(mcs, name, bases, class_dict):
        assert 'proxy_factory' in class_dict and 'proxy_methods' in class_dict, 'class def must provide proxy_methods/_factory'
        proxy_factory = class_dict.pop('proxy_factory')
        for meth_name in class_dict.pop('proxy_methods'):
            class_dict[meth_name] = proxy_factory(meth_name)
        return type.__new__(mcs, name, bases, class_dict)

class LazyMeta(Lazy, metaclass=WrappedType):
    proxy_factory = make_lazy_method
    proxy_methods = ['__%s__' % name for name in dir(operator) if '__%s__' % name in dir(operator)]

Somewhat difficult to understand (i.e. maintain) for many people: separates definition and implementation. Setting a metaclass for py2 and py3 is also not easily portable without third party packages.

LazyMetaSix = WrappedType.__new__(
    WrappedType,
    'LazyMetaSix',
    (Lazy,),
    dict(
        proxy_factory = make_lazy_method,
        proxy_methods = ['__%s__' % name for name in dir(operator) if '__%s__' % name in dir(operator)])
    )

The above code can be tested with:

for cls in (LazyVerbose, LazyLocals, LazyMetaSix):
    lazy_obj = cls(lambda a: a*a, 4)
    print(cls.__name__, '__add__', lazy_obj + 10, lazy_obj + 12)

Python version 2.6+ and 3.3+ need to be supported.


texts: Troublesome Frog (AIO Intermediate 2013) 3.x

texts:
Recently I was trying out this problem and my code got 60% of the marks, with the remaining cases returning TLEs.

  Bazza and Shazza do not like bugs. They wish to clear out all the bugs
  on their garden fence. They come up with a brilliant idea: they buy
  some sugar frogs and release them near the fence, letting them eat up
  all the bugs.

  The plan is a great success and the bug infestation is gone. But
  strangely, they now have a sugar frog infestation. Instead of getting
  rid of the frogs, Bazza and Shazza decide to set up an obstacle course
  and watch the frogs jump along it for their enjoyment.

  The fence is a series of \$N\$ fence posts of varying heights. Bazza and
  Shazza will select three fence posts to create the obstacle course,
  where the middle post is strictly higher than the other two. The frogs
  are to jump up from the left post to the middle post, then jump down
  from the middle post to the right post. The three posts do not have to
  be next to each other as frogs can jump over other fence posts,
  regardless of the height of those other posts.

  The difficulty of an obstacle course is the height of the first jump
  plus the height of the second jump. The height of a jump is equal to
  the difference in height between it's two fence posts. Your task is to
  help Bazza and Shazza find the most difficult obstacle course for the
  frogs to jump.

  Input
  Your program should read from the file. The file will describe
  a single fence.

  The first line of input will contain one integer \$N\$: the number of
  fence posts. The next \$N\$ lines will each contain one integer \$h_i\$: the
  height of the ith fence post. You are guaranteed that there will be at
  least one valid obstacle course: that is, there will be at least one
  combination of three fence posts where the middle post is strictly
  higher than the other two.

  Output
  Your program should write to the file. Your output file should
  contain one line with one integer: the greatest difficulty of any
  possible obstacle course.

  Constraints
  To evaluate your solution, the judges will run your
  program against several different input files. All of these files will
  adhere to the following bounds:

  \$3 \leq N \leq 100,000\$ (the number of fence posts)
  \$1 \leq h_i \leq 100,000\$ (the height of each post)

  As some of the test cases will be quite large,
  you may need to think about how well your solution scales for larger
  input values. However, not all the cases will be large. In particular:

  For 30% of the marks, \$N \leq 300\$. For an additional 30% of the
  marks, \$N \leq 3,000\$. For the remaining 40% of the marks, no special > constraints apply.

Hence, I was wondering if anyone could think of a way to optimize my code (below), or perhaps provide a more elegant, efficient algorithm than the one I am currently using.

Here is my code:

infile = open('frogin.txt', 'r')
outfile = open('frogout.txt', 'w')

N = int(infile.readline())

l = []

for i in range(N):
    l.append(int(infile.readline()))

m = 0
#find maximum z-x+z-y such that the middle number z is the largest of x, y, z
for j in range(1, N - 1):
    x = min(l[0: j])
    y = min(l[j + 1:])
    z = l[j]
    if x < z and y < z:
        n = z - x + z - y
        m = n if n > m else m

outfile.write(str(m))

infile.close()
outfile.close()
exit()

If you require additional information regarding my solution or the problem, please do comment below.


texts: Coding - Find a bitwise XOR for a range of numbers in java

texts:
Find a bitwise XOR for a range for.e.g (5,8) --> 5 bitXOR 6 | 7 bitXOR 8 3 bitXOR 15 12

Expected worst time Complexity - O(log(n))

Expected worst space Complexity - O(1)

I have written the below code, could you please help me to improve it?

static List<Integer> list;
    public static void main(String[] args) {
        int bitXORProduct = solution(5,8);
        System.out.println(bitXORProduct);
    }
    public static int solution(int M, int N) {
        if (isValidatedInput(M, N)) {
            int lastXOR = M;
            int currentXOR = 0;
            try {
                for (int i = M; i < N; i++) {
                    currentXOR = computeXOR(lastXOR, i + 1);
                    lastXOR = currentXOR;
                }
            } catch (Exception e) {
                System.out.println("Error Found : -" + e);
            }
            return lastXOR;
        }
        System.out.println("Input is not in the range or valid");
        return -1;
    }
    private static boolean isValidatedInput(int M, int N) {
        if (0 <= M && 0 <= N && M <= Math.pow(10, 9) && N <= Math.pow(10, 9) && M <= N) {
            return true;
        } else
            return false;
    }
    private static Integer computeXOR(Integer m, Integer n) {
        return m ^ n;
    }


texts:
int bin_search(int* a, int key)
{
    int lo = 0;
    int hi = sizeof(a)/sizeof(int) - 1;

   while(lo <=hi)
   {
        int mid = (lo + hi)/2;

        if(key < a[mid]) { hi = mid - 1;}
        else if (key > a[mid]) { lo = mid + 1;}
        else                    return mid;
    }

    return -1;
}

....

for(i = 0; i < sz; ++i)
{
    printf("%d\n", bin_search(a, i));
}

I think that I have a problem with this, but I can't understand why:

int hi = sizeof(a)/sizeof(int) - 1;


texts:
I am currently working on a Sudoku solver that should be able to solve a 25 x 25 grid. However, I am experiencing problems optimizing it to run quick enough to actually get a result with any grid bigger than 9 x 9. I was wondering if anyone could take a look at my code and give me some ideas on how to optimize it.

public class SudokuGrid {
    private String[][] grid;

    /**
     * Constructs an empty 9x9 Sudoku Grid.
     */
    public SudokuGrid() {
        this(16);
    }

    /**
     * Constructs an empty, square Sudoku grid.
     * @param boardSize the length of each row & column
     */
    public SudokuGrid(int gridSize) {
        this.grid = new String[gridSize][gridSize];
        for (int r = 0; r < this.grid.length; r++) {
            for (int c = 0; c < this.grid.length; c++) {
                this.grid[r][c] = "-";
            }
        }
    }

    /**
     * Constructs a partially filled Sudoku grid.
     * @param str the contents of the grid (using '-' for blank)
     */
    public SudokuGrid(String str) {
        String[] contents = str.split("\\s+");
        int gridSize = (int)Math.sqrt(contents.length);

        this.grid = new String[gridSize][gridSize];
        for (int i = 0; i < contents.length; i++) {
            this.grid[i/gridSize][i%gridSize] = contents[i];
        }
    }

    /**
     * Fills the Sudoku grid with numbers using recursive backtracking.
     * @return whether the grid was successfully filled
     */

    public boolean fillGrid(){
        return fillGrid(0,0);
    }

    private boolean fillGrid(int row, int col){
        if (col >= this.grid.length) {
            col = 0;
            if (++row >= this.grid.length)
                return true;
        }
        if (!this.grid[row][col].equals("-")){
            return fillGrid(row , col + 1);
        }
        for (int i = 1; i <= this.grid.length; i++) {
            String temp = ""+i;
            if (isValidValue(row, col, temp)) {
                this.grid[row][col] = temp;
                if (fillGrid(row, col + 1)){
                    return true;
                }
            }
        }
        grid[row][col] = "-";
        return false;
    }

    private boolean isValidValue(int row, int col, String val) {
        for (int i = 0; i < this.grid.length; i++){
            if (val.equals(this.grid[i][col])){
                return false;
            }
        }

        for (int j = 0; j < this.grid.length; j++){
            if (val.equals(this.grid[row][j])){
                return false;
            }
        }

        double squareRootVal = Math.sqrt(this.grid.length);
        int rowOffset = (row / (int)squareRootVal) * (int)squareRootVal;
        int colOffset = (col / (int)squareRootVal) * (int)squareRootVal;
        for (int i = 0; i < squareRootVal; i++) {
            for (int j = 0; j < squareRootVal; j++){
                if (val.equals(this.grid[rowOffset + i][colOffset + j])){
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Constructs a String representation of the grid.
     * @return the grid in a displayable row/column format
     */
    @Override
    public String toString() {
        String output = "";
        for (int r = 0; r < this.grid.length; r++) {
            for (int c = 0; c < this.grid.length; c++) {
                output += grid[r][c] + " ";
            }
            if (r < this.grid.length-1) {
                output += "\n";
            }
        }
        return output;
    }
}


texts: Injecting an object in each function in Go

texts:
My current project uses a database represented as object. Furthermore I want to implement methods like CreateUser(), DeleteUser() etc, but my current code requires the injection of the db-object as parameter in each function.

Making the db-object global would solve the problem, but I learnt that global variables are mostly seen as a bad practice. Are there any other solutions?

package main

import (
    "fmt"
    "time"

    "github.com/jinzhu/gorm"
    _ "github.com/lib/pq"
    _ "github.com/mattn/go-sqlite3"
)

type User struct {
    ID        int
    Name      string `sql:"size:50"`
    Username  string `sql:"size:50"`
    CreatedAt time.Time
    UpdatedAt time.Time
}

func CreateUser(db gorm.DB, name, username string) {
    user := User{
        Name:     name,
        Username: username,
    }

    db.Create(&user)
}

func main() {
    db, err := gorm.Open("sqlite3", "data.sqlite3")

    if err != nil {
        fmt.Println(err)
    }

    db.DB()
    fmt.Println("Programm is running...")

    CreateUser(db, "John Doe", "johndoe")
}


texts: Python finding next word permutation with function generator

texts:
Learning how to use function generators in Python I practiced with the following code that finds the next permutation of a word and then uses this new word as input for the next one until there are no further permutations. So for example 'dbac' is followed by 'dacb' followed by 'dabc' and so on.

Basically two questions: 1) the use of two times break to stop the two for-loops is there a better way to break out of the loops, and 2) the final part try: return finally: StopIteration is this a proper construction?

def nextperm(word):

    stoploop = True
    while stoploop:
        wordlist = [*word]
        length = len(wordlist)-1
        stoploop = False
        for index_1 in range(length-1, -1, -1):
            for index_2 in range(length, index_1-1, -1):
                if wordlist[index_2] < wordlist[index_1]:
                    wordlist[index_2], wordlist[index_1] = wordlist[index_1], wordlist[index_2]
                    _first = wordlist[0:index_1+1]
                    _second = wordlist[-1:index_1:-1]
                    wordlist = _first + _second
                    word = ''.join(wordlist)
                    stoploop = True
                    yield word
                    break
            if stoploop:
                break

    try:
        return print('no further permutation possible')
    finally:
        raise StopIteration

so if you do:

for i, word in enumerate(nextperm('dcba')):
    print(f'{i:2}, {word}')

output is:

 0, dcab
 1, dbca
 2, dbac
 3, dacb
 4, dabc
 5, cdba
 6, cdab
 7, cbda
 8, cbad
 9, cadb
10, cabd
11, bdca
12, bdac
13, bcda
14, bcad
15, badc
16, bacd
17, adcb
18, adbc
19, acdb
20, acbd
21, abdc
22, abcd
no further permutation possible


texts: Feedback on generator functions and class composition in Python 3

texts:
I have written a Python script whose purpose is to read logs from CloudWatch and then post them to ElasticSearch. It is not quite finished but I've progressed far enough that I could benefit from feedback from Python experts, specifically:

Is the use of Python Generators correct and idiomatic
Is the use of Class Composition correct and idiomatic
Anything else style-wise inappropriate for Python 3.

#!/usr/bin/env python3

import json
import time
import uuid
import os
import sys

import boto3
from elasticsearch import Elasticsearch, helpers

client = boto3.client("logs")

def usage() -> None:
    print("Usage: GROUP_NAME=cloudwatch_group ES_HOST=es_host {}".format(
        os.path.basename(__file__)))
    sys.exit(1)

if "GROUP_NAME" not in os.environ:
    usage()
if "ES_HOST" not in os.environ:
    usage()

class CWLogs:
    group_name = os.environ["GROUP_NAME"]

    def events(self) -> None:
        for event in self.__generate_events():
            yield event

    def __generate_streams(self) -> None:
        kwargs = {
            "logGroupName": self.group_name,
        }

        while True:
            stream_batch = client.describe_log_streams(**kwargs)
            yield from stream_batch["logStreams"]
            try:
                kwargs["nextToken"] = stream_batch["nextToken"]
            except KeyError:
                break

    def __generate_events(self) -> None:
        stream_names = \
      [stream["logStreamName"] for stream in self.__generate_streams()]

        for stream_name in stream_names:
            kwargs = {
                "logGroupName":  self.group_name,
                "logStreamName": stream_name,
            }

            while True:
                logs_batch = client.get_log_events(**kwargs)
                yield from logs_batch["events"]
                try:
                    kwargs["nextToken"] = logs_batch["nextToken"]
                except KeyError:
                    break

class ESWriter:
    es_host = os.environ["ES_HOST"]
    elastic = Elasticsearch()

    def post(self, events: object) -> None:
        try:
            response = helpers.bulk(
                self.elastic, self.__transformer(events))
            print("\nRESPONSE:", response)
        except Exception as e:
            print("\nERROR:", e)

    @staticmethod
    def __index_name(timestamp: str) -> str:
        return "eventbridge-auth0-{}".format(
            time.strftime("%Y.%m", time.localtime(timestamp)))

    @staticmethod
    def __normalize(message: str) -> str:
        return message # TODO.

    def __transformer(self, events: object) -> None:
        for event in events:
            yield self.__transform(event)

    def __transform(self, event: dict) -> None:
        timestamp = event["timestamp"]
        index_name = self.__index_name(timestamp)
        message = self.__normalize(event["message"])

        return "\n".join([
            json.dumps({
                "index": {
                    "_id": str(uuid.uuid4()), # TODO. Check
                    "_index": index_name,
                    "_type":  "_doc"}}),
            json.dumps({
                "source": {
                    "@source": "auto-populate script",
                    "@timestamp": timestamp,
                    "@message": message}})])

if __name__ == '__main__':
    ESWriter().post(CWLogs().events())


texts:
I have a website which has reviews about games. Right now, to list the advantages (+) and disadvantages (-) of that game, there's a textarea in the admin panel with a WYSIWYG editor with only  element. So my users list their (+) with list elements :

Game is too slow

Game is very hard

I want to update it and I was wondering if it wouldn't be a better way to have input fields to add their (+) and (-) about the game and each time they want to add one, they click on a button which adds an input field. Then, when the form is submitted, I could encode the datas with JSON like :

[
    ['Game is too slow'],
    ['Game is very hard']
]

Would be like:

<input name="advantages[]" /> +

and then:

// encode
$list = json_encode($_POST['advantages']);
//decode
echo '
';
foreach($list as $item) {
    echo '
'.$item.'
';
}
echo '
';

And when I want to show the datas, I could decode them and display them as a list, which would be like the first option. My point would be to get rid of the WYSIWYG and maybe have a more flexible system.

What do you think?


texts:
I need to find all paths from a given graph. I can do that for now, however my recursive code is not efficient and my graphs are very complicated, hence I need a better algorithm.

def findLeaves(gdict):
    # takes graph and find its leaf nodes
    leaves = []
    for endNode in gdict.iterkeys():
        if not gdict[endNode]:
            leaves.append(endNode)
    return leaves

graphPaths = {}

def findPaths(gname, gdict, leave, path):
    # finds all noncycle paths
    if not gdict:
        return []
    temp = [node for node in gdict.iterkeys() if leave in gdict[node].keys() and node not in path]
    if temp:
        for node in temp:
            findPaths(gname, gdict, node, [node] + path)
    else:
        graphPaths[gname].append(path)

graph = {}
graph['graph'] = {0: {1: {}}, 1: {2: {}, 3: {}}, 2: {3: {}}, 3: {4: {}}, 4: {5: {}}, 5: {6: {}}, 6: {7: {}}, 7: {6: {}, 5: {}, 8: {}}, 8: {}}
graph['name'] = 'nameofthegraph'

# main
leaves = findLeaves(graph['graph'])
graphPaths['nameofthegraph'] = []

seenNodes = []
for leave in leaves:
    findPaths(graph['name'], graph['graph'], leave, [leave])

for path in graphPaths.values()[0]:
    print path

There is only one starting node, which makes things easier for recursive function. Every leaf needs to arrive there if a leaf is followed in reverse order.  The starting node is the one which does not have an incoming edge.

These structures are taken from pygraphviz, which simply shows the outgoing edges from any nodes. Keys are the nodes and values are outgoing edges to the nodes. However, when I have very complicated graphs as below, this code could not find all paths.

Is there any better algorithm that you can suggest? Or is there any way to optimize my algorithm for complicated graphs?


texts: Output strings from a set in lexicographical order

texts:
Puzzle Description:

  You are given 'n' strings w1, w2, ......, wn. Let Si denote the set of strings formed by considering all unique substrings of the string wi. A substring is defined as a contiguous sequence of one or more characters in the string. More information on substrings can be found here. Let 'S' = {S1 U S2 U .... Sn} .i.e 'S' is a set of strings formed by considering all the unique strings in all sets S1, S2, ..... Sn. You will be given many queries and for each query and an integer 'k'. Your task is to output the lexicographically kth smallest string from the set 'S'.

  Input:

  The first line of input contains a single integer 'n', denoting the number of strings. Each of the next 'n' lines consists of a string. The string on the ith line (\$1 <= i<= n\$) is denoted by wi and has a length mi. The next line consists of a single integer 'q', denoting the number of queries. Each of the next 'q' lines consists of a single integer 'k'.
  Note: The input strings consist only of lowercase English alphabets 'a' - 'z'.

  Output:

  Output 'q' lines, where the ith line consists of a string which is the answer to the ith query. If the input is invalid ('k' > |S|), output "INVALID" (quotes for clarity) for that case.

  Constraints:

  \$1 <= n <= 50\$
  \$1 <= mi <= 2000\$
  \$1 <= q<= 500\$
  \$1 <= k<= 1000000000\$

  Sample Input:

2
aab
aac
3
3
8
23

  Sample Output:

aab
c
INVALID

  Explanation:

  For the sample test case, we have 2 strings "aab" and "aac".

  S1 = {"a", "aa", "aab", "ab", "b"} . These are the 5 unique substrings of "aab".

  S2 = {"a", "aa", "aac",  "ac", "c" } . These are the 5 unique substrings of "aac".

  Now, S = {S1 U S2} = {"a", "aa", "aab", "aac", "ab", "ac", "b", "c"}. Totally, 8 unique strings are present in the set 'S'.

  The lexicographically 3rd smallest string in 'S' is "aab" and the lexicographically 8th smallest string in 'S' is "c". Since there are only 8 distinct substrings, the answer to the last query is "INVALID".

  Time-limit: 5 secs

import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;

public class find_str {

    private static final String INVALID = "INVALID";
    private TreeSet<String> mainset = new TreeSet<String>();
    private ArrayList<String> array = new ArrayList<String>();
    private String[] main_ary;
    private int length;
    public static void main(String args[]) {
        find_str fin = new find_str();
        Scanner scanner = new Scanner(System.in);
        int num_of_strings = scanner.nextInt();
        for (int i = num_of_strings; --i >=0;) {
            fin.process(scanner.next());
        }
        fin.initialize();
        int num_of_queries = scanner.nextInt();
        for (int i = num_of_queries; --i >=0;) {
            System.out.println(fin.query(scanner.nextInt()-1));
        }
    }

    private String query(int index) {
        if (index < length) {
            return main_ary[index];
        } else {
            return INVALID;
        }
    }

    private void process(String input) {
        int len = input.length();
        for (int i = 0; i < len; i++) {
            for (int j = i; j < len; j++) {
                mainset.add(input.substring(i, j + 1));
            }
        }
    }

    private void initialize() {
      length=mainset.size();
        main_ary=(String[]) mainset.toArray(new String[length]);
    //    array.addAll(mainset);
    }
}

This was written to solve puzzle only
First I thought of creating separate sets for each string and then later unionize all them to get final mainset and then sort them using custom comparator if necessary and later can be retrieved with index.
Later without doing all this nonsense, created tree-set which is populated with substrings on the run, thus combined process of unionizing and sorting.
For retrieving through index I had to make an ArrayList with contents of mainset.  I guess this doesn't take much time or memory than other process.


texts: Star rating: Update stars on click and don't lose the actual vote on re-hover

texts:
I'm trying to make a star based rating system.

First of all, I don't like to make it all with JS and only innerHTML the rated stars in a given div. I want to make it more like a plugin with the ability to make anything votable and you just have to pass the classes.

My biggest problem, however, is that I'm setting classes on hover and removing them on mouse leave. That's just fine until the user clicks and the classes are set. Think you can imagine what happens if the user hovers again: The classes would get removed.

But still I want the user to be able to change his vote. I managed it with two different divs where one is hidden. I absolutely don't feel comfortable with this solution:

With jQuery I'm enabling .votable on hover. On click I'm setting the actual vote to .voted and on mouse leave I'm hiding .votable and showing .voted.

$('.voted').hover(
    function() {
        $('.voted').addClass('hide');
        $('.votable').removeClass('hide');
    }
);

$('.votable').on('mouseleave',function(){
    $('.voted').removeClass('hide');
    $('.votable').addClass('hide');
});

$('.votable > i').hover(
    function() {
        $(this).prevAll().andSelf().removeClass('fa-star-o').addClass('fa-star');
        $(this).nextAll().removeClass('fa-star').addClass('fa-star-o');
    },
    function() {
        $(this).prevAll().andSelf().removeClass('fa-star').addClass('fa-star-o');
    }
);

$('.votable > i').click(function(e) {
    var vote_type = $(this).attr('data-vote-type');
    var el = $('.voted > i[data-vote-type="' + vote_type + '"]');

    $(el).prevAll().andSelf().removeClass('fa-star-o').addClass('fa-star');
    $(el).nextAll().removeClass('fa-star').addClass('fa-star-o');
});

You can see the code working at my fiddle.

What would be a better way of achieving this?


texts:
I am new to Scala and I have written a function which uses pattern matching to filter words based on some conditions.  It seems to work correctly but I am suspect that I haven't used the Scala pattern matching in the best way.  I think this because each of my cases contain an if statement.  I have not seen any examples where people use if statements in pattern matching functions so I'm thinking there might be a better way of doing this.  Or maybe this particular usage does not fit well with pattern matching.

def getImportance(token:String,stopWords:Set[String])={
    token match{
      case t if t.length()==1 => 0
      case t if t.length()>15 => 0
      case t if t.matches("\\p{Punct}+") => 0
      case t if stopWords.contains(t.toLowerCase()) => 0
      case _ => 1
    }
}


texts: C++11 version of Windows EventWaitHandle

texts:
I don't know C++ at all, but for the heck of it I tossed this together because I was talking with someone about C++ and was given the impression there is absolutely nothing quite like the windows APIs ManualReset and AutoReset EventWaitHandles, so I figured I'd see if I could create one.

I think this might work - it compiles and runs but I don't really know well enough how to make a thread to test it's multi-threading off hand in C++ and don't care to try figuring it out. Figure folks here can probably tell me if I got any of the threading primitives usage completely off or have some harrible race conditions or some such.

#include <iostream>
#include <atomic>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>

using namespace std;

class EventWaitHandle {

public:
    EventWaitHandle(bool handleWillCloseAfterOneWait, bool openAtStart)
        : autoReset(handleWillCloseAfterOneWait), handleOpen(openAtStart)
    { }

    void set() {
        {
            std::lock_guard<std::mutex> handleOpenLock(handleOpenLocker);
            handleOpen = true;
        }

        handleOpenSignal.notify_one();
    }

    void reset() {
        {
            std::lock_guard<std::mutex> handleOpenLock(handleOpenLocker);
            handleOpen = false;
        }

        handleOpenSignal.notify_one();
    }

    bool wait(int millisecondsBeforeTimeout) {
        {
            std::lock_guard<std::mutex> handleOpenLock(handleOpenLocker);

            if (handleOpen) {
                handleOpen = !autoReset;
                return true;
            }

            if (millisecondsBeforeTimeout < 1) // Handle isn't open and we are waiting no time, punt..
                return false;

        }

        auto start = std::chrono::system_clock::now();
        cout << "waiting.." << endl;
        std::unique_lock<std::mutex> lockJustForThisWaiter(handleOpenLocker);

        if(handleOpenSignal.wait_until(lockJustForThisWaiter, start + std::chrono::milliseconds(millisecondsBeforeTimeout)) == std::cv_status::timeout)
            return false;

        auto timeLeftToWaitInEventOfSpuriousness = std::chrono::milliseconds(millisecondsBeforeTimeout) - (std::chrono::system_clock::now() - start);
        int millisecondsLeftToWait = 0;
        millisecondsLeftToWait = std::chrono::duration_cast<std::chrono::milliseconds>(timeLeftToWaitInEventOfSpuriousness).count();

        return wait(millisecondsLeftToWait);
    }

private:

    bool autoReset;

    std::condition_variable handleOpenSignal;
    std::atomic<bool> handleOpen;
    std::mutex handleOpenLocker;
};

That's what I want review of, this is just example usage concept:

int main(){
    EventWaitHandle waitHandle(true, true);

    bool open;

    open = waitHandle.wait(100);
    if (open)
        cout << "open" << endl;
    else
        cout << "not open" << endl;

    waitHandle.set();

    open = waitHandle.wait(100);
    if (open)
        cout << "open" << endl;
    else
        cout << "not open" << endl;

    waitHandle.reset();

    open = waitHandle.wait(100);
    if (open)
        cout << "open" << endl;
    else
        cout << "not open" << endl;

    return 0;
}


texts:
Is there a way to speed up this code so it is \$O(n^2)\$ instead of \$O(n^3)\$? I'd appreciate if someone showed me how to do so.

public void minimalSpanning(int sVertex)
{
    source = sVertex;

    boolean[] mstv = new boolean[maxSize];

    for (int j = 0; j < gSize; j++)
    {
        mstv[j] = false;
        edges[j] = source;
        edgeWeights[j] = weights[source][j];
    }

    mstv[source] = true;
    edgeWeights[source] = 0;

    for (int i = 0; i < gSize - 1; i++)
    {
        double minWeight = Integer.MAX_VALUE;
        int startVertex = 0;
        int endVertex = 0;

        for (int j = 0; j < gSize; j++)
            if (mstv[j])
                for (int k = 0; k < gSize; k++)
                    if (!mstv[k] && weights[j][k] < minWeight)
                    {
                        endVertex = k;
                        startVertex = j;
                        minWeight = weights[j][k];
                     }
        mstv[endVertex] = true;
        edges[endVertex] = startVertex;
        edgeWeights[endVertex] = minWeight;
    } //end for
} //end minimalSpanning


texts: Scrape data from a webpage and store them in a database

texts:
I've written a script in python to parse different names ,bubbles and reviews of various restaurant names from tripadvisor and finally store them in a table named webdata in a database. There are two functions within my script: one for storing the scraped data in MySQL and the other for printing the same in the console. The scraper is doing its job just flawless. As this is my first ever try to store items in a database and print the already stored items in the console, I might not have been able to follow the rules of DRY.

I will vastly appreciate any modification I should pursue to make the script robust.

This is my attempt so far:

import mysql.connector
from bs4 import BeautifulSoup
import requests

URL = "https://www.tripadvisor.com.au/Restaurants-g255068-c8-Brisbane_Brisbane_Region_Queensland.html"

def store_info(link):
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd = "test123",
      database="mydatabase"
    )

    mycursor = mydb.cursor()
    mycursor.execute("DROP TABLE webdata") #kick out the table if it already exists
    mycursor.execute("CREATE TABLE webdata (name VARCHAR(255), bubble VARCHAR(255), review VARCHAR(255))")

    response = requests.get(link)
    soup = BeautifulSoup(response.text,"lxml")
    for items in soup.find_all(class_="shortSellDetails"):
        name = items.find(class_="property_title").get_text(strip=True)
        bubble = items.find(class_="ui_bubble_rating").get("alt")
        review = items.find(class_="reviewCount").get_text(strip=True)

        mycursor.execute("INSERT INTO webdata (name,bubble,review) VALUES (%s,%s,%s)",(name,bubble,review))
    mydb.commit()

def get_data():
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd = "test123",
      database="mydatabase"
    )
    mycursor = mydb.cursor()
    mycursor.execute("SELECT * FROM webdata")
    for item in mycursor.fetchall():
        print(item)
    mydb.close()

if __name__ == '__main__':
    store_info(URL)
    get_data() #retrieve the data from that table


texts:
I have very little experience with C, so I decided to code a simple numerical program.

An Armstrong number with \$N\$ digits is a number that is equal to the sum of its digits to the \$N^{th}\$ power, in pseudo-code:

sum { power(digit, N) for digit in number } == number

My program finds all the Armstrong numbers below the given limit.

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

int power(int a, int b) {
    int original_a = a;
    while (b --> 1) { a *= original_a;}
    return a;
}

int digits_len(int n) {
    int length = 0;
    while(n) {
        n /= 10;
        length++;
    }
    return length;
}

int sum_digits_to_the_pow(int n, int exp) {
    int sum = 0;
    while (n) {
        sum += power((n % 10), exp);
        n /= 10;
    }
    return sum;
}

bool is_armstrong(int n) {
    return n == sum_digits_to_the_pow(n, digits_len(n));
}

int main(int argc, char *argv[]) {
    assert(power(4, 3) == 64);
    assert(digits_len(4812) == 4);
    assert(sum_digits_to_the_pow(214,2) == 4+1+16);
    assert(is_armstrong(153) == true);

    for (int i=0; i < atoi(argv[1]); i++) {
        if (is_armstrong(i)) {
            printf("%d ", i);
        }
    }
}

Run my program with (it takes 22 seconds):

gcc  -std=c99 -O3 armstrong.c; time ./a.out 100000000


texts:
I ran a sonar analysis on my code and it told me the cyclomatic complexity is too high (sonar's limit is ten branches).

Here is my code:

public void myMethod(){
  try{
  // do something
  catch(SomeException e){
    throw new WrappingException("issue when doing something " + e.getMessage(), e);
  }
  catch(AnotherException e){
    throw new WrappingException("issue when doing something " + e.getMessage(), e);
  }
  // lots of other Exceptions
}

Basically, I want to catch a large set of Exceptions, (maybe always processing the same behaviour). I read the question Catching multiple types of exceptions when writing JSON but I don't use Java 7 (with which I could have all Exceptions in one catch statement) and I do not really want to catch ALL Exceptions, since I want my code to fail in a case I did not expect.

Is there any alternative that would involve fewer branches?

NOTE: What I want to achieve here is not to recover from any Exception, but to categorize the Exceptions. An upper layer is in charge of handling Exceptions, but for this purpose, Exceptions need to be properly categorized.


texts:
I have a large namespace, but I don't want enum constants to be a part of it. In cases where an enum is related with a class, I coded enums inside the class so I can reach it using the class name. However, if an enum is related with namespace functions, what is the best way to do it?

Use another namespace and put the enum inside, so from the outside it will be the same as others with different implementations?
Continue and create a class with private constructors so it will be as same as others?

Classes:

class A {
public:
   enum Type {
      Aa,
      Ab
   };

   Type GetType();
};

class B {
public:
   enum Type {
      Ba,
      Bb
   };

private:
   B();
};

B::Type DoSomething();

Namespace:

namespace B {
   enum Type {
       Ba,
      Bb
   };
}

B::Type DoSomething();

The first case seems to abuse classes, but it can be extended later to use same coding method as the others. I am in favor of namespace, but what are your opinions?


texts:
The Go programming language has that slice type, which is under the hood a pointer to an actual array. This allows treating the subarrays as actual arrays with almost no performance overhead. This code snippet is about implementing slice type for C++ arrays and vectors.

slice.h:

#ifndef SLICE_H
#define SLICE_H

#include <sstream>
#include <stdexcept>
#include <string>

template<class T>
class slice {
    private:
        T*     m_array;
        size_t m_length;

    public:
        slice(T* array, size_t length) {
            this->m_array  = array;
            this->m_length = length;
        }

        slice(T* array, size_t length, size_t skip) {
            this->m_array = array + skip;
            this->m_length = length;
        }

        T& operator[](size_t index) {
            if (index >= m_length) {
                std::ostringstream os;
                os << "Bad index: " << index << ", slice size: " << m_length;
                throw std::runtime_error(os.str());
            }

            return m_array[index];
        }

        size_t size() {
            return m_length;
        }

        T* begin() {
            return m_array;
        }

        T* end() {
            return m_array + m_length;
        }

        const T* begin() const {
            return m_array;
        }

        const T* end() const {
            return m_array + m_length;
        }
};

#endif  /* SLICE_H */

main.cpp:

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

#include "slice.h"

using std::cout;
using std::endl;
using std::vector;

int main(int argc, char** argv) {
    int int_array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    //// Should be 4, 5, 6, 7, 8.
    slice<int> pizza_slice = slice<int>(int_array, 5, 3);

    cout << "Arrays slice size: " << pizza_slice.size() << endl;

    for (int i : pizza_slice)
    {
        cout << i << endl;
    }

    vector<int> int_vector = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

    //// Should be 2, 3, 4
    pizza_slice = slice<int>(&int_vector[0], 3, 1);

    cout << "Vector slice size: " << pizza_slice.size() << endl;

    for (int i : pizza_slice)
    {
        cout << i << endl;
    }

    return 0;
}

Any critique is much appreciated.


texts: Cache-optimized matrix multiplication algorithm in C

texts:
I am trying to optimize matrix multiplication on a single processor by optimizing cache use. I am implemented a block multiplication and used some loop unrolling, but I'm at a loss on how to optimize further though it is clearly still not very optimal based on the benchmarks.

Matrices are in column major order.

Any suggestions would be appreciated!

const int blockSize = 12;

void readBlock(double outputMatrix[], double inputMatrix[], int beginX, int endX, int beginY, int endY, int n) {

        int i = 0;
        for (int x = beginX; x < endX; x++) {
                for (int y = beginY; y < endY; y++) {
                        outputMatrix[i] = inputMatrix[x*n + y];
                        i++;
                }
                for (int y = endY-beginY; y < blockSize; y++) {
                        outputMatrix[i] = 0;
                        i++;
                }

        }

        for (int x = endX - beginX; x < blockSize; x++) {
                for (int y = 0; y < blockSize; y++) {
                        outputMatrix[i] = 0;
                        i++;
                }

        }

}

int min(int a, int b) {
        if (a < b) return a;
        else return b;

}

void multiplyMatrices(double inputMatrix1[], double inputMatrix2[], double outputMatrix[], int endx, int endy) {
        for (int i = 0; i < endx; i++) {
                for (int j = 0; j < endy; j++) {
                        double cvalue = outputMatrix[i*blockSize + j];
                        for (int l = 0; l < blockSize; l+=2) {
                                double a1 = inputMatrix1[l*blockSize + j] * inputMatrix2[i*blockSize + l];;
                                double a2 = inputMatrix1[(l+1)*blockSize + j] * inputMatrix2[i*blockSize + l + 1];
                                cvalue += a1 + a2;

                        }
                        outputMatrix[i*blockSize + j] = cvalue;
                }
        }

}

void writeMatrix(double* inputMatrix, double* outputMatrix, int beginX, int endX, int beginY, int endY, int n) {
        int k,l=0;
        for (int i = beginX; i < endX; i++) {
                k = 0;
                for (int j = beginY; j < endY; j++) {
                        outputMatrix[i*n + j] = inputMatrix[l*blockSize+k];
                        k++;
                }
                l++;
        }

}

void square_dgemm(int n, double* A, double* B, double* C) {

        for (int x = 0; x < n; x += blockSize) {
                for (int y = 0; y < n; y += blockSize) {
                        double CC[blockSize*blockSize];

                        readBlock(CC, C, x, min(x + blockSize, n), y, min(y + blockSize, n), n);

                        for (int z = 0; z < n; z += blockSize) {
                                double BC[blockSize*blockSize];
                                double AC[blockSize*blockSize];
                                int zAdj = min(z + blockSize, n);
                                readBlock(AC, A, z, zAdj,y, min(y+blockSize, n), n);

                                readBlock(BC, B, x, min(x + blockSize, n), z,zAdj, n);

                                multiplyMatrices(AC, BC, CC, min(x+blockSize,n)-x,min(y+blockSize,n)-y);

                        }
                        writeMatrix(CC, C, x, min(x + blockSize, n), y, min(y + blockSize, n), n);

                }

        }
}


texts:
I wrote a snippet of code to help me memorize text out of files and was hoping to get some feedback on the code, since Python isn't my strongest language.

You can see the code on GitHub, but I've pasted it below as well.

#!/usr/bin/python
# coding=utf-8

import argparse
import codecs
import random
import sys

parser = argparse.ArgumentParser(description="""A tool to help memorize some text! When provided with a file, this program will remove random words from each line of text and ask you to provide the words that were removed.""")
parser.add_argument('--no-color', action='store_true', help='hide colorful underlining')
parser.add_argument('--a', dest='attempts', default=3, help='number of attempts to allow per word (0 for unlimited attempts, default: 3)')
parser.add_argument('filename', metavar='filename', type=str, help='the text file')

args = parser.parse_args()

try:
    with codecs.open(args.filename, 'r', 'utf-8') as f:
        current_line = ''
        for line in f:
            missing_words = [u'']
            idx = 0
            for word in line.split(' '):
                show_word = True
                if random.randrange(10) < 5:
                    show_word = False
                for char_idx in range(0,len(word)):
                    if (word[char_idx].isalpha() and show_word) or not word[char_idx].isalpha():
                        current_line += word[char_idx]
                    else:
                        missing_words[idx] += word[char_idx]
                        if not args.no_color:
                            current_line += '\033[91m'
                        current_line += '_'
                        if not args.no_color:
                            current_line += '\033[0m'
                if word[-1] != '\n':
                    current_line += ' '
                if len(missing_words[idx]):
                    missing_words.append(u'')
                    idx += 1
            missing_words.pop()
            attempts = 0
            while len(missing_words):
                print(current_line)
                try:
                    attempt = raw_input('Enter the next missing word: ')
                    if unicode(attempt,'utf-8') == missing_words[0]:
                        print("Correct! The word was '" + missing_words[0] + "'.")
                        if args.no_color:
                            current_line = current_line.replace(''.join('_' for char in missing_words[0]),missing_words[0],1)
                        else:
                            current_line = current_line.replace(''.join('\033[91m_\033[0m' for char in missing_words[0]),missing_words[0],1)
                        missing_words.pop(0)
                        attempts = 0
                    elif args.attempts > 0 and attempts == args.attempts:
                        print("Too many attempts. The word was '" + missing_words[0] + "'.")
                        if args.no_color:
                            current_line = current_line.replace(''.join('_' for char in missing_words[0]),missing_words[0],1)
                        else:
                            current_line = current_line.replace(''.join('\033[91m_\033[0m' for char in missing_words[0]),missing_words[0],1)
                        missing_words.pop(0)
                        attempts = 0
                    else:
                        print("Incorrect. Please try again.")
                        attempts += 1
                except:
                    sys.exit(0)
except IOError:
    print("File not found: '" + args.filename + "'")


texts:
The problem I am trying to solve is this.  Apples fall at various offsets relative to an apple tree at position a, and oranges fall at various given offsets relative to an orange tree at position b.  How many of each kind of fruit lie between positions s and t?

I pass 8 from the 11 test cases, I fail 3 tests due to timeout error.

I spent the last hour or so trying to refactor my code to make it faster but I am out of ideas now.
Can someone give an advice what should I do in order to make it faster?

function countApplesAndOranges(s, t, a, b, apples, oranges) {
    let house = [];
    let applesCount = 0;
    let orangesCount = 0;
    for(let i = s; i <= t; i++){
        house.push(i);
    };
    const applesPositions = apples.map(val=> val + a);
    const orangesPositions = oranges.map(val=> val + b);

    for(let j = 0; j < house.length; j++){
        for(let k = 0; k < applesPositions.length; k++){
            if(house[j] === applesPositions[k]) applesCount++;
        };
        for(let m = 0; m < orangesPositions.length; m++){
            if(house[j] === orangesPositions[m]) orangesCount++;
        };
    };
    console.log(`${applesCount}${'\n'}${orangesCount}`);

};


texts:
I've written this script to practice (not necessarily memorize, but familiarize myself with) the definitions of a lot of words.

import csv
import random

WORDS = 5    # Number of words
CHOICES = ["A", "B", "C", "D", "E"]    # Number and labelling of choices

with open("wordlist.csv") as csvfile:
    wordreader = csv.reader(csvfile)
    wordlist = [row for row in wordreader]
    words = [pair[0] for pair in wordlist]
    definitions = [pair[1] for pair in wordlist]

score = 0

count = 1
while count <= WORDS:
    print("\nQuestion", str(count))
    randomnumber = random.randint(0, len(words)-1)
    print("Word:", words[randomnumber])

    correct_answer = definitions[randomnumber]
    answers = []
    answers.append(correct_answer)
    for i in range(len(CHOICES)-1):
        randomanswer = random.randint(0, len(words)-1)
        if definitions[randomanswer] in answers:
            randomanswer -= 1
        answers.append(definitions[randomanswer])
    answers.sort()
    correct_index = answers.index(correct_answer)

    for i in range(len(CHOICES)):
        print(CHOICES[i] + ": " + answers[i])

    userinput = input("Answer: ")
    if userinput[0].upper() in CHOICES:
        userindex = CHOICES.index(userinput)
        if userindex == correct_index:
            score += 1
            print("Correct")
    else:
        print("Wrong: " + correct_answer)

    count += 1

print(str(score) + "/" + str(WORDS))

Sample output:

Python 3.4.5 (default, Jul 03 2016, 13:55:08) [GCC] on linux-027e.site, Standard
>>>
Question 1
Word: accentuate
A: Adapt
B: Forgiveness of their sins
C: Stress
D: Superintendent of a monastery
E: Unreasonable
Answer: C
Correct

Question 2
Word: ackja
A: Sami sledge
B: Singing without instruments
C: Speech problems
D: Superintendent of a monastery
E: Unreasonable
Answer: A
Correct

Question 3
Word: a cappella
A: Adapt
B: Adapt
C: Appropriate
D: Forgiveness of their sins
E: Singing without instruments
Answer: E
Correct

Question 4
Word: adequate
A: Adapt
B: Appropriate
C: Forgiveness of their sins
D: Intangible
E: Sami sledge
Answer: B
Correct

Question 5
Word: ackja
A: Adapt
B: Forgiveness of their sins
C: Sami sledge
D: Speech problems
E: Stress
Answer: C
Correct
5/5

Note that there shouldn't be duplicate questions, it's just more likely with a short wordlist like the one at the end of this post and the current implementation. Also, the same definitions shouldn't appear twice in the same question (like in Question 3) My solution to that seems to work most of the time, it's unclear to me why it doesn't work for Question 3 above.

There are a number of things that I'm wondering about:

Use of random.sample to choose words and answers, it doesn't
seem like this will make the code any shorter or concise.
I'm not quite satisfied with the code for choosing the random answers, it seems to be too complicated, as well as the code for checking the user answer. Is there an easier way to verify that the chosen letter is the one that stands for the correct definition?
How could I eliminate the chance of the same word being asked twice in one run of the script?

Here is a sample wordlist.csv, where I've translated 10 of the ca. 3500 original entries:

a cappella,Singing without instruments
absurd,Unreasonable
abbot,Superintendent of a monastery
accentuate,Stress
Aphasia,Speech problems
ackja,Sami sledge
abstrakt,Intangible
absolution,Forgiveness of their sins
adequate,Appropriate
accommodate,Adapt


texts:
Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, .. etc.

Looking for code review, optimizations, best practices.

    public class StackMinimum<T>{
       /*
        * Composition triumphs over inheritance :)
        */
       private final Stack<T> stack1 = new Stack<T>();
       private final Stack<T> stack2 = new Stack<T>();

       public void push(T item) {
           stack1.push(item);
           if (stack2.isEmpty() || ((Comparable<T>) item).compareTo(stack2.peek()) < 0) {
               stack2.push(item);
           }
        }

        public T pop() {
            T item = stack1.pop();
            if (item.equals(stack2.peek())) {
                stack2.pop();
            }
            return item;
        }

        public T peek() {
            return stack1.peek();
        }

        public int size() {
            return stack1.size();
        }

        public T getMinimum () {
            return stack2.peek();
        }

        public boolean isEmpty() {
            return stack1.isEmpty();
        }
    }

public class StackMinimumTest {

    @Test
    public void test() {
        StackMinimum<Integer> stack1 = new StackMinimum<Integer>();
        stack1.push(1);
        stack1.push(2);
        stack1.push(3);

        assertEquals(1, (int)stack1.getMinimum());

        stack1.push(-1);
        assertEquals(-1, (int)stack1.getMinimum());

        stack1.pop();
        assertEquals(1, (int)stack1.getMinimum());

        while(!stack1.isEmpty()) {
            assertEquals(1, (int)stack1.getMinimum());
            stack1.pop();
        }
    }
}


texts: Designing a text based guessing game with a branching decision tree

texts:
I am hoping to make a quick decision tree using the if statement in excel vba. The point is to have a message with a prompt show up and then it will take the person through the prompts based on the answers. Can my current approach be improved upon in any way?

Sub Decision_tree()

    a = MsgBox("Want To Play A Game?", 3)

    If a = 6 Then
    MsgBox "Let the games begin!", 1

    ElseIf a = 7 Then
    MsgBox "Okay. Press ctrl K to start over."
    End

    Else
    MsgBox "Sad. Come back later. Press ctrl K to start."
    End
    End If

    a = MsgBox("are you a boy?", vbYesNo)

    If a = 6 Then '**
       b = MsgBox("does your names start before O?", vbYesNo)
       If b < 7 Then d = MsgBox("do you live in logan?", vbYesNo)
            ElseIf b = 7 Then
                   f = MsgBox("Is your name 4 letters?", vbYesNo)
                     If d = 6 Then
                       h = MsgBox("Did you serve your mission with Josh?", vbYesNo)
                       ElseIf f = 6 Then
                        MsgBox "Your name is Ryan"
                         ElseIf f = 7 Then
                        MsgBox "your name is Trevon"
                            ElseIf d = 7 Then
                                   j = MsgBox("Did you serve a mission with Josh?")
                                   ElseIf h = 6 Then
                                   MsgBox "Your name is Cade"
                                    ElseIf h = 7 Then
                                           K = MsgBox("are you a DJ?", vbYesNo)
                                             ElseIf j = 6 Then
                                             MsgBox "your name is Houston"
                                              ElseIf j = 7 Then
                                              MsgBox "your name is Cameron"
                                                ElseIf K = 6 Then
                                                MsgBox "your name is Jack with a j"
                                                 ElseIf K = 7 Then
                                                  MsgBox "your name is burton"

    ElseIf a = 7 Then
       c = MsgBox("does your name start Before N?", vbYesNo)
        ElseIf c = 6 Then
            e = MsgBox("does your name have a K in it?", vbYesNo)
            ElseIf c = 7 Then
                   g = MsgBox("do you own a jeep?", vbYesNo)
                   ElseIf e = 6 Then
                      i = MsgBox("Are you from Idaho?", vbYesNo)
                       ElseIf g = 6 Then
                        MsgBox "your name is olivia"
                        ElseIf g = 7 Then
                        MsgBox "your name is tiffany"
                            ElseIf i = 6 Then
                            MsgBox "Your name is Kasey"
                             ElseIf i = 7 Then
                              MsgBox "Your name is Mckenna"

       End If
    End If

End Sub


texts: Counting number of messages for a mailbox over several periods

texts:
The idea is to return a number of messages received today, this week, this month.

  def index
    @mailboxes = current_user.mailboxes
    @today, @month, @week, @all_time = 0, 0, 0, 0

    @mailboxes.each do |mailbox|
      @today += mailbox.messages.today.length
      @month += mailbox.messages.week.length
      @week += mailbox.messages.month.length
      @all_time += mailbox.messages.length
    end
  end

week, month scopes are similar to the following one

  scope :today, -> { where(created_at: ((Time.zone.now - 24.hours)..Time.zone.now)) }


texts:
I may get a Map of many many items that needs to be requested to an API.

In order to improve performance, I thought about splitting that list into smaller sublists, and querying the API with this small subset.

For that, I came to this code and was wondering what was your opinion on it.

This is some banal initiator I used to test my code:

Map<String, Integer> map = new LinkedHashMap<String, Integer>();
for (int i = 0; i < 550;i ++) {
    map.put(String.valueOf(i), i);
}

Now the real code:

    int length = 100;
    List<Integer> items = new LinkedList<Integer>(map.values());
    int pages = (int) Math.ceil((double) items.size() / length);

    for (int i = 0; i < pages; i++) {
        List<Integer> sub = items.subList(i * length, ((i+1) * length > items.size() ? items.size() : (i+1) * length));
        System.out.println(sub.get(0));
        System.out.println(sub.get(sub.size() - 1));
        System.out.println("--");

        // In my case, I would call the API here, at that place, using the sublist
    }

The final output is:

0
99
--
100
199
--
200
299
--
300
399
--
400
499
--
500
549
--

This works great. What's your opinion on it?


texts: multiple if statements "forced" by database query result & external api response

texts:
Following scenario:
this is the code that resides in Ajax Controller class.
It is responsible for handling input in one of the form fields.

The logic is as follows:

If user-inputted data validate as either Tax Number or Statistical Number, it's supposed to: check for presence of such data in database, and, depending on the result, either make a call to external API (in case DB query is empty) or present the results (in case of input being found in database).

If user-inputted data doesn't validate as either Tax or Statistical Number, it is supposed to perform DB query with input treated as the customer name.

Below code works as expected.
However, it is long and I was forced to repeat some parts.
I'm looking to cut down on lines while preserving exact same logic, but I'm highly unsure as to how to make it even more compressed.

class AjaxController {

  public function customerslistAction() {
    $filterChain = new Zend_Filter();
    $filterChain->addFilter(new Zend_Filter_Digits())
                ->addFilter(new Zend_Filter_Null());

    $input = $filterChain->filter($this->getRequest()->getParam('name'));
    $collection = new Def_Model_Collection_Customer();

    /* check if $input is TaxNumber */
    if (SugApi::isTaxNumber($input)) {
      $data['tax_number'] = $input;
      $allFound = $collection->findByTaxOrStatistical($data);

      // check and return customer with this TAX_NUMBER if it is in database
      if (count(($allFound)) > 0) {
        echo Zend_Json::encode($allFound);
        return;
      }
      // call external api if it isn't in database [catch NotFound Exception]
      else {
        try {
          $sugReport = SugApi::getByTaxNumber($input);
        } catch (\SugApi\Exception\NotFoundException $e) {
          $out['results'][] = array('value' => 'Unknown tax number.');
          echo Zend_Json::encode($out);
          return;
        }
      }
    }

    /* check if $input is StatisticalNumber */
    else if (SugApi::isStatNumber($input)) {
      $data['stat_number'] = $input;
      $allFound = $collection->findByTaxOrStatistical($data);

      // check and return customer with this STATISTICAL_NUMBER if it is in database
      if (count($allFound) > 0) {
        echo Zend_Json::encode($allFound);
        return;
      }
      // call external api if it isn't in database [catch NotFound Exception]
      else {
        try {
          $sugReport = SugApi::getByStatNumber($input);
        } catch (\SugApi\Exception\NotFoundException $e) {
          $out['results'][] = array('value' => 'Unknown statistical number.');
          echo Zend_Json::encode($out);
          return;
        }
      }
    }
    // if $input is neither TAX_NUMBER nor STATISTICAL_NUMBER,
    // query database for customer with $input as customer_name
    else {
      $collection = new Def_Model_Collection_Customer();
      $data = $collection->fetchAll(array('name' => $this->getRequest()->getParam('name')));

      $out = array();
      foreach ($data as $val) {
        $out['results'][] = array(
          'id' => $val['customer_id'],
          'value' => $val['customer_name'],
          'info' => 'Tax Number: '.$val['customer_tax_number']
        );
      }
      $json = Zend_Json::encode($out);
      echo $json;
      return;
    }

    // parse successful external api response into Customer object and save it
    $customer = new Def_Model_Customer();
    $customer->setOptionsFromSugReport($sugReport);
    $customer->save();

    $out['results'][] = array(
      'id'    => $customer->customer_id,
      'value' => $customer->customer_name,
      'info'  => 'Tax Number: '.$customer->customer_tax_number
    );
    echo Zend_Json::encode($out);
  }
}


texts: Selecting names with two consecutive, same letters

texts:
I've a list of names that I'd like to iterate over and extract from it those names that have two letters that are the same right next to each other (i.e. Bill, Terry, Debby, Aaron, etc.).

The below code I have accomplishes this task, however I was wondering if there was a more efficient or line-friendly method of approaching this problem.

I started thinking about a solution involving LINQ's Where<> method, but then I wasn't sure how to use both a string variable and an int index variable inside a lambda expression.

Also, does there exist a way to accomplish this task in faster than O(n^2) time?

public static List<string> DoubleLetters(string[] array)
{
    List<string> doubleLetter = new List<string>();
    for (int i = 0; i < array.Length; i++)
    {
        for (int j = 0; j < array[i].Length - 1; j++)
        {
            if (char.ToLower(array[i][j]) == char.ToLower(array[i][j + 1]))
            {
                doubleLetter.Add(array[i]);
                break;
            }
        }
    }
    return doubleLetter;
}


texts: Beginner's exercise to ask for first names and surnames

texts:
I just started Java programming yesterday (so don't expect too much), and I've written some code. My code works the way I want it to work, but there are obviously things wrong with it.

I was wondering how it could be improved. I think I've added unnecessary things. I'm practicing using classes and other stuff.

testing.java

import java.util.Scanner;

class testing {
    private static Scanner input_sn;
    private static Scanner input_fn;
    private static Scanner input_mem;

    public static void main(String[] args){

        String First_Name;
        String Second_Name;
        int members;
        int count;

        System.out.println("Members: ");
        input_mem = new Scanner(System.in);
        members = input_mem.nextInt();

        funcs funcsObj = new funcs();

        for (count = 0; count < members; count++)
        {
            System.out.println("What is the first name? ");
            input_fn = new Scanner(System.in);
            First_Name = input_fn.nextLine();

            System.out.println("What is the second name? ");
            input_sn = new Scanner(System.in);
            Second_Name = input_sn.nextLine();

            funcsObj.names( funcsObj.setFn(First_Name), funcsObj.setSn(Second_Name));
        }
    }
}

funcs.java

public class funcs
{
    private String firstName;
    private String secondName;
    private static int members = 0;

    public String setFn(String fn)
    {
        firstName = fn;
        return fn;
    }

    public String setSn(String sn)
    {
        secondName = sn;
        return sn;
    }

    public void names(String fn, String sn)
    {
        firstName = fn;
        secondName = sn;
        members++;
        System.out.printf("%d\t%s\t%s\n", members, fn, sn);
    }
}

(I think most of the problems can be found in the funcs.java file.)


texts: Calculating Relative Strength Index for Multiple Pandas column

texts:
I want calculate RSI indicator value for multiple column in Pandas DataFrame. I am looking for a method to avoid loop, here is the code I am using:

rsi_calculations = pd.DataFrame()
for column in rsi_trans.columns:
    rsi = ta.RSI(rsi_trans[column].values, timeperiod=30)
    rsi_calculations[column] = rsi

In the above code I am calculating RSI value and appending it to pandas data frame, but its taking more time.

Is there a more efficient way to do this?

Edit:

I've imported TA-Lib as ta and used its RSI function to calculate RSI value.


texts: Spring AOP Log4j Logger example, improvement

texts:
I went through some of the stuffs on net regarding spring AOP and wrote a Spring AOP logger.

Can you guys check my code and give your valuable inputs to improve it or if it is not proper, give me an another example of how can I achieve it?

My Code is as below :

@Aspect
public class SpringAOPLogger {

    @Around("execution(* com.sample.dao.*.*(..)) || execution(* com.sample.service.*.*(..))"
            + "|| execution(* com.sample.controller.*.*(..))")
    public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        String className = joinPoint.getTarget().getClass().getSimpleName();
        final Logger logger = Logger.getLogger(joinPoint.getTarget().getClass());
        Object retVal = null;

        try {
            StringBuffer startMessageStringBuffer = new StringBuffer();

            startMessageStringBuffer.append("Entered in ").append(className).append(".");
            startMessageStringBuffer.append(joinPoint.getSignature().getName());
            startMessageStringBuffer.append("(");

            Object[] args = joinPoint.getArgs();
            for (Object arg : args) {
                startMessageStringBuffer.append(arg).append(", ");
            }
            if (args.length > 0) {
                startMessageStringBuffer.deleteCharAt(startMessageStringBuffer.length() - 1);
            }

            startMessageStringBuffer.append(")");

            //Method Entry Log
            logger.debug(startMessageStringBuffer.toString());

            StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            retVal = joinPoint.proceed();

            stopWatch.stop();

            StringBuffer endMessageStringBuffer = new StringBuffer();
            endMessageStringBuffer.append("Exit from ").append(className).append(".");
            endMessageStringBuffer.append(joinPoint.getSignature().getName());
            endMessageStringBuffer.append("(..); Execution time: ");
            endMessageStringBuffer.append(stopWatch.getTotalTimeMillis());
            endMessageStringBuffer.append(" ms;");

            //Method Exit Log
            logger.debug(endMessageStringBuffer.toString());
        } catch (Throwable ex) {
            StringBuffer errorMessageStringBuffer = new StringBuffer();
            // Create error message
            logger.error(errorMessageStringBuffer.toString(), ex);
            throw ex;
        }
        return retVal;
    }
}

and below is the spring xml configuration for the same :

    <aop:aspectj-autoproxy>
        <aop:include name="springAopLogger" />
    </aop:aspectj-autoproxy>

    <bean id="springAopLogger" class="com.sample.utility.SpringAOPLogger" />


texts: Find the longest unique string in the input list

texts:
Given a list, find the longest non-repeating (in other words I mean unique) string in the input list. Looking for code review, pointers on best practices, optimizations etc.

public final class LongestUniqueWord {

    /*
     * do not initialize this class
     */
    private LongestUniqueWord( ) {}

    /**
     * Returns the longest non-repeating(unique) word in the list.
     * If each word repeats then return null.
     *
     *
     * @param words the list of words of a news paper.
     * @return      the longest unique word.
     * @throws  IllegalArgumentException  if input size is 0.
     * @throws  NPE                       if the input is null.
     */
    public static String longestUniqueWord (List<String> words) {
        if (words.size() == 0) throw new IllegalArgumentException("The array should not be empty.");

        final Map<String, Boolean> uniqueWords = new HashMap<String, Boolean>();

        for (String word : words) {
            if (uniqueWords.containsKey(word)) {
                uniqueWords.put(word, false);
            } else {
                uniqueWords.put(word, true);
            }
        }

        int maxLength = 0;
        String longestUniqueWord = null;
        for (Entry<String, Boolean> entry : uniqueWords.entrySet()) {
            if (entry.getValue() && entry.getKey().length() > maxLength) {
                longestUniqueWord = entry.getKey();
                maxLength = longestUniqueWord.length();
            }
        }

        return longestUniqueWord;
    }

    public static void main(String[] args) {
        List<String> newsPaper = new ArrayList<String>();
        newsPaper.add("Jack");
        newsPaper.add("In");
        newsPaper.add("In");
        newsPaper.add("The");
        newsPaper.add("The");
        newsPaper.add("Box");

        System.out.println("Expected: Jack, Actual: "  + longestUniqueWord(newsPaper));

        newsPaper.add("Jack");
        System.out.println("Expected: Box, Actual: " + longestUniqueWord(newsPaper));
    }

}


texts: Stripping Quotations from a List of Lists

texts:
I have written a short function as part of my program that strips the quotation marks (") from a list of lists. An example of the input data is:
[['"foo"', '"Spam"', '123', '"Angry Badger"'],
 ['"dead"', '"Parrot"', '321', '987']]

The target result would be:
[['foo', 'Spam', '123', 'Angry Badger'],
 ['dead', 'Parrot', '321', '987']]

This code I am using to parse this is:
def quote_strip(input_file):

    for k1, v1 in enumerate(input_file):
        for k2, v2 in enumerate(v1):
            input_file[k1][k2] = v2.lstrip('"').rstrip('"')

    return input_file

This works fine, but I am pretty sure there is a way of making this a single line. I just always seem to mess up comprehensions when they have the = sign in them like this.
Any feedback would be greatly appreciated.