texts: C++ string tokenizing without streams, with certain conditions

texts:
My concern is mainly the correctness of the algorithm for tokenizing purposes. The code compiles as it is called as a member function in my program. The code does pass my small amount of unit tests for parsing inputs (61 unit tests, all pass). But, I'm slightly stressed out about this part of code, and also paranoid. I could use a pair of foreign mk.I eyeballs looking at my code. This is part of a bigger project and ideally the tokenizing should be bugfree

please take a look and give thoughts.
:'(

BACKGROUND & problem parameters
objectives of my tokenizer:

cannot use stringstreams, run out of programmemory
input cppstrings will not have newline or any such limiter at the
end(will be chucked out before inputting into
tokenize_input_refactored() ), IT will be as though the input cppstring was gotten with getline()
separate cppstrings into tokens based on single spacebar (delimiter), or the end of the string in regular way ("M4 255" is tokenized into "M4", "255")
if there's no delimiter, take the entire cppstring as token
backToBack delimiters is immediately invalid input, like " " twoSpacebars in row (or more spacebars in row)
cannot begin or end with spacebar(delimiter), immediately invalid input
too large string ( 31 or more true chars) is illegal input
empty string is illegal input
the "garbage strings" that are pushed into the vector "illegalcommand" are later on used for comparison with known words
for parsing purposes. Just to be sure that command won't be parsed as
valid. (tokens amount as well as tokens themselves are checked against expected values)

Possible solution as C++ member-function:

tokensVec is just an empty vector datamember of Gcodeparser object. It will be cleared empty after each round of tokenizing (or parsing, the same same effect).

bool GcodeParser::tokenize_input_refactored(const std::string & rawInput) {

    /*find delimiter == singleSpacebar*/
    auto res = rawInput.find(delimiter);

    /*find if there was twoOrMoreDelimiters backToBack "  " twospacebars */
    string backToBackDelim;
    backToBackDelim += delimiter;
    backToBackDelim += delimiter;
    auto res2 = rawInput.find(backToBackDelim);

    int searchInd = 0;
    int pos = 0;
    int size = rawInput.length();
    bool returnableResult = false;

    /*if the input was too large => reject as illegal*/
    if (size > maxCharAmount) {
        tokensVec.push_back("INVALID_COMMAND!");
        return false;
    }
    /*check if empty string*/
    if (size == 0) {
        tokensVec.push_back("INVALID_COMMAND!");
        return false;
    }

    /*found 2delim backtoback*/
    if (res2 != string::npos) {
        tokensVec.push_back("INVALID_COMMAND!");
        return false;
    }

    /*input ended in delimiter or started with delimiter*/
    if (rawInput[0] == delimiter || rawInput[size-1] == delimiter) {
        tokensVec.push_back("INVALID_COMMAND!");
        return false;
    }

    /*delimiter wasnt found => take complete word into vec for later parsing*/
    if (res == string::npos) {
        tokensVec.push_back(rawInput);
        return true;
    }
    else {
        while (pos != string::npos) {
            pos = rawInput.find(delimiter, searchInd);
            if (pos != string::npos) {
                tokensVec.push_back(rawInput.substr(searchInd, pos - searchInd));
                searchInd = pos + 1;
            }
        }
        /*take the last valid token*/
        tokensVec.push_back( rawInput.substr(searchInd, size - searchInd) );
        return true;
    }
}


texts: Presenting collections for code generation

texts:
I've never been too bothered by the lack of present (and thus print) support for Factor collections and other objects, but I've never needed to generate Factor programs from JSON until now.

To that end, I use these methods to turn arrays, hashtables and assocs into roundtrippable strings:

M: f present
  drop "f" ;

M: array present
  [
    [
      dup string? [
        "\"" dup surround
      ] when
      present
    ] map
  ]
  [ length ]
  bi
  [ "%s " ] replicate "" join
  vsprintf "{ " " }"  surround ;

M: assoc present
  { } assoc-clone-like present ;

M: hashtable present
  { } assoc-clone-like present "H" prepend ;

The array method was written rather haphazardly as I tried to find something that seemed robust. The way the elements are finally formatted, using replicate and vsprintf may seem sloppy but it looks better than an until, and sprintf can't be used on non-constant values.

The recursive nature allows it to be cleverly repurposed for other collection types and on arbitrarily deeply nested arrays. Moreover, string literals in arrays preserve their "quotes" so they roundtrip too, which I initially struggled with.

But, can it be improved? The goal is that any collection converts into a string and evals back into its original value (called roundtripping), which it does:

IN: scratchpad { 1 { 2 3 } "4" 5 } present ( -- x ) eval

--- Data stack:
{ 1 ~array~ "4" 5 }
IN: scratchpad H{ { 1 "a" } { 2 3 } { "4" 5 } } present ( -- x ) eval

--- Data stack:
{ 1 ~array~ "4" 5 }
H{ { 1 "a" } { 2 3 } { "4" 5 } }


texts:
This is a solution to the CodeHhef problem FCTRL2 where we are supposed to find the factorial of numbers up to 100. I have tried several techniques but I am always exceeding their time limit (1 second). Please help me optimize this code to make it execute faster.

    import java.math.BigInteger;
    import java.io.*;
    class Abc{
        public static void main(String[] args) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        BigInteger fact=new BigInteger("1");
       // BigInteger inc=new BigInteger("1");
        String str=br.readLine();
        int n=Integer.parseInt(str);

        for(int i=0;i<n;i++)
        {    String st=br.readLine();
            BigInteger number=new BigInteger(st);

            for(BigInteger bi = BigInteger.valueOf(1);bi.compareTo(number)>=0;bi = bi.add(BigInteger.ONE))
            {
                fact=fact.multiply(bi);
            }
            System.out.println(fact);
        }
    }
   }


texts: Generating business summary stats in SQL dynamically, based on an inputted date

texts:
I have the following Oracle SQL query to generate some system-stats. I am interested in making it a more efficient and readable query.

SELECT
    SUM("Req Lines") as "Requisitions Created",
    SUM("Approved Req") AS "Requisitions Approved",
    SUM("Non Approved PO") AS "PO Started",
    SUM("Approved PO") AS "PO Approved",
    SUM("w/ Receipt") AS "Receipts Completed",
    SUM("w/ Invoice") AS "Invoices Completed"
FROM(
  SELECT DISTINCT prha.Segment1 AS "Req#",

    pha.Segment1 as "PO#",
    CASE when prha.creation_date between to_date(:myDate,'DD-MON-YY') and to_date(:myDate,'DD-MON-YY') + 7  then 'Week 1'
        when prha.creation_date between to_date(:myDate,'DD-MON-YY') + 7 and to_date(:myDate,'DD-MON-YY') + 14  then 'Week 2'
        when prha.creation_date between to_date(:myDate,'DD-MON-YY') + 14 and to_date(:myDate,'DD-MON-YY') + 21 then 'Week 3'
        when prha.creation_date between to_date(:myDate,'DD-MON-YY') + 21 and to_date(:myDate,'DD-MON-YY') + 28  then 'Week 4'
      else 'After Month 1' END as "Req_Created",     1  as "Req Lines",
      prha.authorization_status as "Req Status",

    CASE when prha.authorization_status='APPROVED' then 1 else 0 END as "Approved Req",
    CASE when pha.authorization_status='APPROVED' then 1 else 0 END as "Approved PO",
    pha.authorization_status,
    CASE when (pha.authorization_status = 'APPROVED' or pha.authorization_status is null) then 0 else 1 END as "Non Approved PO",
    CASE when pda.quantity_delivered >=1 then 1 else 0 END as "w/ Receipt",
    CASE when pda.quantity_billed >=1 then 1 else 0 END as "w/ Invoice"

  FROM apps.po_requisition_lines_all prl,
    apps.po_requisition_headers_all prha,
    po.po_req_distributions_all prda,
    po.po_distributions_all pda,
    po.po_headers_all pha
  where 1=1
  and prl.requisition_header_id= prha.requisition_header_id
  and prl.requisition_line_id= prda.requisition_line_id
  and prda.distribution_id= pda.req_distribution_id(+)
  and pha.po_header_id(+)=pda.po_header_id

  AND prda.creation_date > to_date(:myDate,'DD-MON-YY')
)


texts: Transforming golden and input files in test table

texts:
I'm trying to find a way to create a test table from golden and input files.

I have the following dir structure:

pkg
|
| mypackage/
  | testdata/
    | file1.input
    | file1.golden
    | file2.input
    | file2.golden
  | mypackage_test.go
  | ...

I'm trying to find an efficient way to create a test table from a pair of input and golden files:

type test struct {
   input,
   expected string
}

func getFiles() test {
  input, _ := ioutil.ReadFile(filepath.Join("testdata", fmt.Sprintf("%s.%s", filename, "input")))
  expected, := ioutil.ReadFile(filepath.Join("testdata", fmt.Sprintf("%s.%s", filename, "golden")))
  return {string(input), string(expected)}
}

func getTable() []test {
  return []test{getFiles("file1"), getFiles("file2"), getFiles("file3")}
}

func TestInputs(t *testing.T) {
  table := getTable()
  for _, tt := range table {
    // perform the test
  }
}

I'm not really the best at writting tests, and the code above seems a bit hacky. Is there a better way to do what I'm trying?


texts:
I've been doing a lot of searching on PHP, logins, forms, cookies, sessions, etc.  And so, I've tried to gather all the info that I got from all over the place.  But, I didn't find a place with all the info, and tried to do the best secure login I could do.

This is what I have.  If this ends up being good, others can use this.  Otherwise, just ignore it.  But I'd like to have opinions.

First, every page makes sure you use HTTPS:

if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    exit();
}

Send username and pass using POST over the https should be safe enough?

Using XMLHttpRequest to check password on Check.php:

function validate() {

var un = document.form1.myusername.value;
var pw = document.form1.mypassword.value;

  httpObject = getHTTPObject();

  if (httpObject != null)
  {
    var params = "username="+un+"&password="+pw;

    httpObject.open("POST","Check.php", true);
    httpObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    httpObject.setRequestHeader("Content-length",params.length);
    httpObject.setRequestHeader("Connection","close");
    httpObject.onreadystatechange = setValid;
    httpObject.send(params);
  }

}

On Check.php, upon confirming password (which was saved on server encrypted), I set up cookie and session creating unique IDs and session secrets:

if($u==$username && $p==$password)
    {
        $valid=1;

        //Setting up session and cookie
        //if cookie stored secret does not meet session secret, session has been hijacked, the same for id
        //session is stored on server while cookie is stored on client

        session_start();
        $sessionTime = time();
        $unique_id = uniqid(sha1($_SERVER['HTTP_USER_AGENT'] . $username), true); //create a unique ID
        $sessionSecret = sha1($sessionTime . $unique_id);   // Create a unique secret based on time and ID

        $_SESSION[$unique_id]['time']    = $sessionTime;
        $_SESSION[$unique_id]['user']    = $us;
        $_SESSION[$unique_id]['secret']    = $sessionSecret;

        // if user changes cookie Secret, it wont match any secret of any other session stored in server
        setcookie("LoginCookie_s", $sessionSecret);
        setcookie("LoginCookie_i", $unique_id);

        // inform user that login was successfull
        echo $valid;
        return;
    }

Back in login: if the return value is 1, I can proceed to main page.
On the main page and every other pages I validate cookie and session:

<?php
 // Validate session and cookie
//if cookie stored secret does not meet session secret, session has been hijacked, the same for id
//session is stored on server while cookie is stored on client

//is cookie set?
if(!isset($_COOKIE["LoginCookie_s"]) || !isset($_COOKIE["LoginCookie_i"]))
{
    //this guy did not pass by login!
    header("location:Login.php");
    exit();
}

session_start();

// was session started on login?
if(!isset( $_SESSION[$_COOKIE["LoginCookie_i"]] ))
{
    //this guy did not pass by login!
    header("location:Login.php");
    exit();
}

// even if a user forged an id matching another user's id he would need to change cookie secret
// if user changes cookie id or secret, it wont match the session secret of that other user id
if( $_COOKIE["LoginCookie_s"] != $_SESSION[$_COOKIE["LoginCookie_i"]]['secret'] )
{
    //cookie and\or session has been hijacked
    header("location:Login.php");
    exit();
}

//all is fine, proceed loading the rest of the page...
 ?>

Am I missing something?


texts:
I've been working on refactoring a piece of my code that allows a user to add items to their cart. Each product can also be added with different attributes. Thus if somebody adds the same product, with matching attributes it shouldn't be added again. It should just increase the quantity by += X where X is the quantity they've chosen.

Now I feel like it can be refactored even more, but I'm not sure how to deal with that when it comes to for example making it have less queries or be faster. As it's one of the slowest processes on our application.

The add_product gets a parameter containing product_id, line_item_attributes_attributes and quantity. What I do now is check initially if the cart has that product already in the cart. If it does, it checks if the attributes are a complete match if so adds quantity, if not adds it as a new product.

  // Cart.rb
  def add_product(parameters)
    product  = Product.find(parameters[:product_id])
    quantity = parameters[:quantity].to_i
    product_attributes = parameters[:line_item_attributes_attributes].try(:to_unsafe_h) || {}
    values             = product_attributes.values
    collect_ids        = values.map { |attribute| attribute[:product_attribute] }
                               .compact
                               .flatten
                               .reject(&:empty?)
    attribute_values = collect_ids.map(&:to_i)
    attach_store_to_cart(product.store) if line_items.empty?

    current_item = line_items.where(product_id: product.id)
    if current_item
      existing_item = look_for_exact_item_match(current_item, attribute_values)
      if existing_item
        current_item = line_items.find(existing_item)
        current_item.update_attribute(:quantity, current_item.quantity += quantity)
      else
        current_item = line_items.create(product: product, quantity: quantity)
        add_attributes(current_item.id, attribute_values) if attribute_values.present?
      end
    else
      current_item = line_items.create(product: product, quantity: quantity)
      add_attributes(current_item.id, attribute_values) if attribute_values.present?
    end
    current_item
  end

  def look_for_exact_item_match(similar_items, attribute_values)
    line_item_id = nil
    similar_items.each do |item|
      if item.line_item_attributes.map(&:product_attribute_id).sort == attribute_values.sort
        line_item_id = item.id
        return line_item_id
      end
    end
    line_item_id
  end

  def add_attributes(current_item_id, attributes)
    current_time = Time.current
    columns = 'line_item_id, product_attribute_id, created_at, updated_at'
    values = attributes.map { |attribute| "(#{current_item_id},#{attribute}, TIMESTAMP '#{current_time}', TIMESTAMP'#{current_time}')" }.join(',')
    ActiveRecord::Base.connection.execute("INSERT INTO line_item_attributes (#{columns}) VALUES #{values}")
  end

  def attach_store_to_cart(store)
    update_attribute(:store, store)
  end

I feel like I might be able to improve the checking of attributes, and the collect_ids variable as it's currently doing 3 different things for the array. Which I predict is quite intensive.

I've tried to improve the process already by inserting all the attributes in one query.

I'd be interested to see how this can be improved in terms of efficiency and speed but also in an OOP way. Any feedback?


texts: A Java class for reading MaCH dosage files v2.0

texts:
Version 2 of A Java class for reading MaCH dosage files

import java.io.*;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

/**
 * Created by vu.co.kaiyin.ReadMachDosage on 15/11/14.
 */
public class Dosage {
    final String filename;
    final Pattern splitPattern;

    public Dosage(String filename) throws Exception {
        this.filename = filename;
        splitPattern = Pattern.compile("\\s+");
    }

    public double[][] readCols(int start, int end) throws IOException {
        try(
                InputStream fileStream = new FileInputStream(filename);
                InputStream gzipStream = new GZIPInputStream(fileStream);
                Reader reader = new InputStreamReader(gzipStream, "US-ASCII");
                BufferedReader bufferedReader = new BufferedReader(reader);
                ) {
            String line;
            String[] fields;
            ArrayList<double[]> dosageList = new ArrayList<>();
            boolean firstLine = true;
            int nCol;
            while ((line = bufferedReader.readLine()) != null) {
                fields = splitPattern.split(line);
                if(firstLine) {
                    nCol = fields.length - 2;
//          Data indices: x      x    1      2      3
//               Indices: 0      1    2      3      4
//               Columns: 1->241 DOSE 1.1783 0.3498 1.9834 ...
                    if(start < 1) start = 1;
                    if(end > nCol) end = nCol;
                    start++;
                    end += 2; // java end index is exclusive
                    firstLine = false;
                }
                double[] dosage = new double[end - start];
                for (int i = start; i < end; i++) {
                    dosage[i - start] = Double.parseDouble(fields[i]);
                }
                dosageList.add(dosage);
            }
            double[][] dosageMatrix = new double[dosageList.size()][];
            dosageMatrix = (double[][]) dosageList.toArray(dosageMatrix);
            return dosageMatrix;
        }
    }

    public double[][] readAll() throws Exception {
        return readCols(1, Integer.MAX_VALUE);
    }
}

Changes:

Read the file only once
Removing unused fields
Bug fixes in array elements assignment
More specific exceptions


texts: Controller method to manage SMS subscriptions

texts:
I have a huge method in my controller that is not DRY and just could use some general TLC. I'm new to ruby and I have not refactored my own code before, only contrived code you find on tutorials. Below I will show my controller, just to be clear I'm not looking for a full answer just maybe where I should start and some helpful tips.

def process_message(message, subscriber)
  if message == "tulip" || message == "stem"
    # If the user has subscribed flip the bit
    # and let them know
    subscribed = message == "tulip"
    subscriber.update(subscribed: subscribed)

    # Respond appropriately
    output = "You are now subscribed for updates."
    unless subscriber.subscribed
      output = "You have unsubscribed from notifications. Test 'TULIP' to start receieving updates again"
    end

    subscriber.add_to_group("visitor")

  elsif message == "dancers"
    subscribed = message == "dancers"
    subscriber.update(subscribed: subscribed)

    subscriber.add_to_group("dancers")

    output = "You have been subscribed to the Dancers list"

  elsif message == "staff"
    subscribed = message == "staff"
    subscriber.update(subscribed: subscribed)

    subscriber.add_to_group("staff")

    output = "You have been subscribed to the Staff list"

  elsif message == "volunteer"
    subscribed = message == "volunteer"
    subscriber.update(subscribed: subscribed)

    subscriber.add_to_group("volunteer")

    output = "You have been subscribed to the Volunteer list"

  else
    # If we don't recognize the command, text back with the list of
    # available commands
    output = "Sorry, we don't recognize that command. Available commands are: 'TULIP' or 'STEM'."
  end

  output


texts: Retry HttpClient request without handlers

texts:
I have a server and client application. In the client application, there are HttpRequestException class exceptions on requests. As it seems to me - these exceptions happen in isolated cases and not always speak about a connection problem. So I decided to do a repeat of the queries with a small amount of time:

private static async Task<T> RetryRequest<T>(Func<Task<T>> func, int retryCount = 3, int retryTimeout = 1000)
{
    var tryCount = 0;
    Exception lastException = null;
    while (tryCount < retryCount)
    {
        tryCount++;
        try
        {
            return await func.Invoke();
        }
        catch (HttpRequestException exception)
        {
            lastException = exception;
            await Task.Delay(retryTimeout);
        }
    }

    if (lastException != null)
        throw lastException;

    throw new HttpRequestException("Can't get request after retrying");
}

Usage example:

public async Task<List<NewsItemDto>> GetNewsAsync(DateTime date)
{
    return await RetryRequest(async () =>
    {
        var sd = date.ToString("dd.MM.yyyy", null);
        var query = new { date = sd };
        var queryString = query.ToQueryString();
        var response = await _client.GetAsync($"/{ModPlusPlatformRoute}/news{queryString}").ConfigureAwait(false);

        await response.HandleErrorAsync().ConfigureAwait(false);
        return await response.GetDataAsync<List<NewsItemDto>>().ConfigureAwait(false);
    });
}

HandleErrors:

public static async Task HandleErrorAsync(this HttpResponseMessage response)
{
    if ((int)response.StatusCode >= 400)
    {
        MediaTypeHeaderValue ct = response.Content.Headers.ContentType;
        if (ct != null && ct.MediaType == "text/html")
            throw new ClientException(await response.Content.ReadAsStringAsync().ConfigureAwait(false), response.StatusCode.ToString());

        ErrorModel errorModel = await response.GetDataAsync<ErrorModel>().ConfigureAwait(false);
        if (errorModel != null)
            throw new ClientException(errorModel.Error, errorModel.StatusCode.ToString());

        var webException = new WebException($"Error with code: {response.StatusCode}");
        AppMetrica.SendHttpException(webException, response.RequestMessage.ToString());
        throw webException;
    }
}

Work method I checked as best I could - everything seems fine. But I am confused by too much use of asynchrony


texts:
I need to have an unique ID for any type in C++ for a variant type. Is this code reliable for getting the ID? I don't care to have same ID for same type between multiple runs. Sorry for typos/formatting, I wrote the code on my phone and tested on Ideone.

#include <iostream>

struct Counter
{
    static size_t value;
};

size_t Counter::value = 1;

template<typename T>
struct TypeID : private Counter
{
    static size_t value()
    {
        static size_t value = Counter::value++;
        return value;
    }
};

int main()
{
    std::cout << TypeID<int>::value() << " " << TypeID<int*>::value() << " " << TypeID<Counter>::value() << " " << TypeID<int>::value();

return 0;
}

PS: I use this because std::type_index/std::type_info::hash may have the same value for different types (probably not in practice).


texts:
In my country (South Africa) mobile numbers have 10 digits and always start with a "0" (e.g. 0821231231).

But they can also have the international dialing code ("+27") replacing the "0" (e.g. +27821231231).

I have this regex:

((\+27)|(^(?!\+)(0)))\d{9}

Is there any way that this can be improved upon?


texts:
I recently started to learn Haskell in order to write some small tools for me. Currently I'm working on a program which calculates how much steam a (railcraft) boiler of a given size outputs per tick.

In the console the user inputs a string of the following format: S | L | BL-Size | BH-Size, example BH-3x3x4

I then use ParserCombinators from the Text.ParserCombinators.ReadP library to parse this string into a custom type. However I think my parser is overly complicated. Any suggestions how to simplify the following code?

module Boilers (Boiler(..), Tank(..)) where

data Boiler = Hobbyist | Locomotive | Boiler (Int, Int, Int) Tank deriving (Show)
data Tank = HighPressure | LowPressure deriving (Eq, Show)

module BoilerParser where

import Data.Char
import Text.ParserCombinators.ReadP
import Control.Applicative
import Boilers
import Data.Maybe

boiler :: ReadP Boiler
boiler = do
  b <- standard <++ hobbyist <++ locomotive
  maybe pfail return b

standard :: ReadP (Maybe Boiler)
standard = do
  satisfy (\c -> toUpper c == 'B')
  t <- fmap (\t -> case toUpper t of
    'H' -> Just HighPressure
    'L' -> Just LowPressure
    _   -> Nothing) get
  satisfy (== '-')
  s <- BoilerParser.size
  case t of
    Nothing -> pfail
    (Just a) -> return (Just (Boiler s a))

hobbyist :: ReadP (Maybe Boiler)
hobbyist = fmap (\c -> if toUpper c == 'H' then Just Hobbyist else Nothing) get

locomotive :: ReadP (Maybe Boiler)
locomotive = fmap (\c -> if toUpper c == 'L' then Just Locomotive else Nothing) get

size :: ReadP (Int, Int, Int)
size = do
  x <- size' 1
  satisfy (== 'x')
  y <- size' 1
  satisfy (== 'x')
  z <- size' 1
  return (x,y,z)

size':: Int -> ReadP Int
size' ds = fmap read (count ds (satisfy isDigit))


texts:
In order to implement the Observer pattern in C#, one of the ways to go (at least, the one I chose) is to make classes that implement the IObservable<T> for the observable objects and the IObserver<T> for the observers.

In a project of mine I created a base class from which every observable inherits:

public class Observable<T> : IObservable<T>
{
    private SubscriptionManager<T> _subscriptionManager;

    public Observable()
    {
        _subscriptionManager = new SubscriptionManager<T>(
            new List<IObserver<T>>());
    }

    public IDisposable Subscribe(IObserver<T> observer)
    {
        _subscriptionManager.Subscribe(observer);

        return _subscriptionManager;
    }

    public void Notify(T obj)
    {
        _subscriptionManager.Notify(obj);
    }
}

and an IDisposable class that manages the subscriptions to the observable object:

public class SubscriptionManager<T> : IDisposable
{
    private ICollection<IObserver<T>> _observers;
    private IObserver<T> _observer;

    public SubscriptionManager(ICollection<IObserver<T>> observers)
    {
        if (observers == null)
        {
            throw new ArgumentNullException("observers");
        }

        _observers = observers;
    }

    public void Subscribe(IObserver<T> observer)
    {
        _observers.Add(observer);
        _observer = observer;
    }

    public void Notify(T obj)
    {
        foreach (var observer in _observers)
        {
            observer.OnNext(obj);
        }
    }

    public void Dispose()
    {
        _observers.Remove(_observer);
    }
}

Do you see anything that can be done more efficiently, or in a better way? Do you see anything else that may be wrong?


texts:
For the input section of a script, I wrote a snippet using a while loop and an if statement to check whether there are matches for the $search. Only if there are matches does it move on to the input of $replace; if there are no matches it asks for $search again.

 while true; do
     echo "Please enter token to be replaced: "
     read -e -r search
     match="$(find . -maxdepth 1 -path "*${search}*" -printf "." | wc -c)"
     if [ "${match}" -gt 0 ]; then
         echo "${match} file(s) found"
         break
     else
         echo "no matches found!"
         echo
     fi
 done

 echo "Please enter replacement: "
 read -e -r replace

# I used the following command to check if the output was right
# echo "rename 's/$search/$replace/g' ./*"

In this snippet I used advice I got from a question I asked on Stack Overflow.

This code is going to be used as the input section of a rename script. In the last line I added an echo "rename... command to check if the output works as expected.

The script is meant to process all files matching the $search criteria in the current directory. Therefore I used find . -maxdepth 1....

The script of which this snippet is part of got reviewed here earlier.

Does this code match general standards?


texts: Create a structuringselement in the form of a line with a certain degree and length

texts:
Within Matlab there exist a function to create a structuringselement in the form of a line.
SE = strel('line',len,deg) creates a linear structuring element that is symmetric with respect to the neighborhood center, with approximate length len and angle deg. For a couple of  morphological operations I need to filter out horizontal-, vertical and other angles of lines. Within Python's CV2 a similiar function does not exist. Therefore, I wanted to recreate this function in Python

My code:

import math
import numpy as np

# bresenham function is the accepted answer of SO's post https://stackoverflow.com/questions/23930274/list-of-coordinates-between-irregular-points-in-python
def bresenham(x0, y0, x1, y1):
   points = []
   dx = abs(x1 - x0)
   dy = abs(y1 - y0)
   x, y = x0, y0
   sx = -1 if x0 > x1 else 1
   sy = -1 if y0 > y1 else 1
   if dx > dy:
      err = dx / 2.0
      while x != x1:
         points.append((x, y))
         err -= dy
         if err < 0:
            y += sy
            err += dx
         x += sx
   else:
      err = dy / 2.0
      while y != y1:
         points.append((x, y))
         err -= dx
         if err < 0:
            x += sx
            err += dy
         y += sy
   points.append((x, y))

   return points

def strel_line(length, degrees):
   if length >= 1:
      theta = degrees * np.pi / 180
      x = round((length - 1) / 2 * np.cos(theta))
      y = -round((length - 1) / 2 * np.sin(theta))
      points = bresenham(-x, -y, x, y)
      points_x = [point[0] for point in points]
      points_y = [point[1] for point in points]
      n_rows = int(2 * max([abs(point_y) for point_y in points_y]) + 1)
      n_columns = int(2 * max([abs(point_x) for point_x in points_x]) + 1)
      strel = np.zeros((n_rows, n_columns))
      rows = ([point_y + max([abs(point_y) for point_y in points_y]) for point_y in points_y])
      columns = ([point_x + max([abs(point_x) for point_x in points_x]) for point_x in points_x])
      idx = []
      for x in zip(rows, columns):
         idx.append(np.ravel_multi_index((int(x[0]), int(x[1])), (n_rows, n_columns)))
      strel.reshape(-1)[idx] = 1

   return strel

if __name__=='__main__':
   strel = strel_line(15, 105)
   print(strel)
   print(strel.shape)

Output:

[[1. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 1.]]

Do you see any ways to write my function more efficiently?


texts:
This code doesn't look too good.  Could anyone help me format it?

private void initComparisonDatatable() {
    List<BrandProfitAndLoss> brandProfitAndLossComparisonDatatable = new ArrayList<BrandProfitAndLoss>();
    BrandProfitAndLoss brandProfitAndLossCurrentYear = new BrandProfitAndLoss();
    BrandProfitAndLoss brandProfitAndLossPreviousYear = new BrandProfitAndLoss();
    // if the selected year is null and the previous year is not null
    if(brandActionForm.getBrandProfitLossList().size() <= 0 && brandActionForm.getBrandProfitLossComparisonList().size() > 0){
        for(int i = 0; i < brandActionForm.getBrandProfitLossComparisonList().size(); i++){
            brandProfitAndLossPreviousYear = brandActionForm.getBrandProfitLossComparisonList().get(i);
            brandProfitAndLossCurrentYear = new BrandProfitAndLoss(brandActionForm.getBrandProfitLossComparisonList().get(i).getDate(), brandActionForm.getDateMode(), Consts.CURRENT_YEAR);
            brandProfitAndLossComparisonDatatable.add(brandProfitAndLossCurrentYear);
            brandProfitAndLossComparisonDatatable.add(brandProfitAndLossPreviousYear);
            brandProfitAndLossComparisonDatatable.add(new BrandProfitAndLoss().getAllRateComparisonRecords(brandProfitAndLossCurrentYear
                                                     , brandProfitAndLossPreviousYear));
        }
    }
    // the selected year is not null
    else {
        for(int i = 0; i < brandActionForm.getBrandProfitLossList().size(); i++){
            brandProfitAndLossCurrentYear = brandActionForm.getBrandProfitLossList().get(i);
            brandProfitAndLossComparisonDatatable.add(brandProfitAndLossCurrentYear);
            if(brandActionForm.getBrandProfitLossComparisonList().size() > 0){
                brandProfitAndLossPreviousYear = brandActionForm.getBrandProfitLossComparisonList().get(i);
                brandProfitAndLossComparisonDatatable.add(brandProfitAndLossPreviousYear);
                brandProfitAndLossComparisonDatatable.add(new BrandProfitAndLoss().getAllRateComparisonRecords(brandProfitAndLossCurrentYear
                                                    , brandProfitAndLossPreviousYear));
            }
            else {
                brandProfitAndLossPreviousYear = new BrandProfitAndLoss(brandActionForm.getBrandProfitLossList().get(i).getDate(), brandActionForm.getDateMode(), Consts.CURRENT_YEAR);
                brandProfitAndLossComparisonDatatable.add(brandProfitAndLossPreviousYear);
                brandProfitAndLossComparisonDatatable.add(new BrandProfitAndLoss().getAllRateComparisonRecords(brandActionForm.getBrandProfitLossList().get(i)
                                                    , brandProfitAndLossPreviousYear));
            }
        }
    }
    brandActionForm.setBrandProfitLossComparisonListForDatatable(brandProfitAndLossComparisonDatatable);
}


texts:
Can you comment, review or suggest things for this? Maybe it should be broken into two methods?

friends is a list of strings of 'T' or 'F' characters representing a friendship relation.

For example for 3 people we could have

friends = ['FTF','TFT','FTF']

This means that

person 0 is friends with person 1 (since friends[0][1] == 'T'),
person 1 is friends with both person 0 and person 2 and
person 2 is friends with person 1.

The method below finds the number of friends, friends of friends and friends of friends of friends of a person for each person as well as the person with the highest such count

def mostThreeFriends(self,friends):
    best = 0
    self.nFriends = {}
    for i in range(0,len(friends)):
        count = 0
        for j in range(0,len(friends[i])):
            if i == j:
                continue
            # direct friends
            if friends[i][j] == 'T':
                count += 1
            else:
                doneCounting3 = False
                # check whether i and j have a friend k in common
                for k in range(0, len(friends)):
                    if doneCounting3:
                        break
                    if k == i or k == j:
                        continue
                    if friends[i][k] == 'T' and friends[j][k] == 'T':
                        count += 1
                        break
                    else:
                        for p in range(0, len(friends)):
                            if p == k or p == i:
                                continue
                            if friends[i][p] == 'T' and friends[p][k] == 'T' and friends[k][j] == 'T':
                                count += 1
                                doneCounting3 = True
                                break
        self.nFriends[i] = count
        best = max(best, count)

    return best


texts:
SELECT SUM(CD.[Value]) AS [Value]
    FROM [{schema}].[CompanyData] CD
        INNER JOIN #Locations T
            ON T.LocationId = CD.CompanyId
        INNER JOIN (
            SELECT CDM.CompanyId, MAX(CDM.[Date]) as MaxDate
            FROM [{schema}].[CompanyData] CDM
                INNER JOIN #Locations T
                    ON T.LocationId = CDM.CompanyId
            GROUP BY CDM.CompanyId
        ) TM
            ON CD.CompanyId = TM.CompanyId AND CD.[Date] = TM.MaxDate

I have query to select SUM from latest values for each row with different CompanyId.

Is this double join of same tables (Query and subQuery) fine or I can improve somehow it?

Thanks.


texts:
Everything is evaluated in compile-time. You will need a C++14 compiler. The compilation time is quite long, and with a bigger list input, you'll get some error messages like constexpr evaluation hit maximum step limit.

#include <iostream>
#include <limits>
#include <initializer_list>

template<typename T>
class List
{
  template<typename T2>
  friend std::ostream &operator<<(std::ostream &, const List<T2> &);
public:
  constexpr List();
  constexpr List(std::initializer_list<T>);
  constexpr T head() const;
  constexpr List<T> tail() const;
  constexpr List<T> add(T) const;
  constexpr List<T> merge(List<T>) const;
  constexpr List<T> reverse() const;
  template<typename Filter>
  constexpr List<T> filter(Filter) const;
  constexpr List<T> sort() const;
  constexpr T sum() const;
private:
  int length;
  T array[std::numeric_limits<int>::max() >> 2];
};

template<typename T>
constexpr List<T>::List()
: length {0}
, array {0}
{
}

template<typename T>
constexpr List<T>::List(std::initializer_list<T> l)
: length {static_cast<int>(l.size())}
, array {0}
{
  for (auto it = l.begin(); it != l.end(); ++it)
  {
    array[it - l.begin()] = *it;
  }
}

template<typename T>
constexpr T List<T>::head() const
{
  return array[0];
}

template<typename T>
constexpr List<T> List<T>::tail() const
{
  List<T> l;
  l.length = length - 1;
  for (int i = 0; i < l.length; ++i)
  {
    l.array[i] = array[i + 1];
  }
  return l;
}

template<typename T>
constexpr List<T> List<T>::add(T t) const
{
  List<T> l {*this};
  l.array[l.length++] = t;
  return l;
}

template<typename T>
constexpr List<T> List<T>::merge(List<T> l) const
{
  for (int i = l.length - 1; i >= 0; --i)
  {
    l.array[i + length] = l.array[i];
  }
  for (int i = 0; i < length; ++i)
  {
    l.array[i] = array[i];
  }
  l.length += length;
  return l;
}

template<typename T>
constexpr List<T> List<T>::reverse() const
{
  List<T> l;
  l.length = length;
  for (int i = 0; i < l.length; ++i)
  {
    l.array[i] = array[length - i - 1];
  }
  return l;
}

template<typename T>
template<typename Filter>
constexpr List<T> List<T>::filter(Filter f) const
{
  List<T> l;
  for (int i {0}; i < length; ++i)
  {
    if (f(array[i]))
    {
      l = l.add(array[i]);
    }
  }
  return l;
}

template<typename T>
struct LT
{
  T pivot;
  constexpr bool operator()(T t) const
  {
    return t < pivot;
  }
};

template<typename T>
struct GE
{
  T pivot;
  constexpr bool operator()(T t) const
  {
    return t >= pivot;
  }
};

template<typename T>
constexpr List<T> List<T>::sort() const
{
  if (length == 0)
  {
    return *this;
  }
  return tail().filter(LT<T> {head()}).sort().add(head())
  .merge(tail().filter(GE<T> {head()}).sort());
}

template<typename T>
constexpr T List<T>::sum() const
{
  if (length == 0)
  {
    return T {};
  }
  return head() + tail().sum();
}

template<typename T>
std::ostream &operator<<(std::ostream &os, const List<T> &l)
{
  os << '{';
  for (int i {0}; i < l.length - 1; ++i)
  {
    os << l.array[i] << ", ";
  }
  return os << l.array[l.length - 1] << '}';
}

inline constexpr List<int> range(int a, int b, int c = 1)
{
  List<int> l;
  while (a < b)
  {
    l = l.add(a);
    a += c;
  }
  return l;
}

int main()
{
  constexpr std::size_t n = range(0, 300).reverse().sort().sum();
  std::cout << n << std::endl;
}


texts: Parsing a string using a regex and doing a mathematical calculation if there is a match

texts:
This is my first time writing anything in C#/.NET. I have written a simple function that takes a string, splits it, compares each split value with a regex and if it matches it'll take the second part of the string, which is a double and rounds it and than replaces the old value in the string with the new rounded value. However I feel like this code could be much cleaner but since I have no experience I'm not sure how. I would appreciate any tips so I can improve my skills

public static void Main()
{
        String pattern = "FL2 (77) Flashing,77,a=1.875,A=90.0,b=3.625,B=95.0,c=1.375,C=175.0,d=2.5,hem=0.5,16GA-AL,";
        string[] fParams = pattern.Split(',');
        Regex regex = new Regex("([a-zA-Z]=.*?)");

        for (int i = 0; i < fParams.Length; i++)
        {
            if (regex.IsMatch(fParams[i]))
            {
                Console.WriteLine("true " + fParams[i]);
                if (fParams[i].Any(char.IsUpper))
                {
                    Console.WriteLine("upper case", fParams[i]);
                    string[] param = fParams[i].Split('=');
                    // Note in actual program I do more complex calculations
                    Double value = Math.Round(Convert.ToDouble(param[1]));
                    pattern = pattern.Replace(fParams[i], param[0]+"="+Convert.ToString(value));
                }
                else
                {
                    Console.WriteLine("lower case", fParams[i]);
                    string[] param = fParams[i].Split('=');
                    // Note in actual program I do more complex calculations
                    Double value = Math.Round(Convert.ToDouble(param[1]) * 2) / 2;
                    pattern = pattern.Replace(fParams[i], param[0] + "=" + Convert.ToString(value));
                }

            }
        }

        //return pattern;
}

Here is the link to the fiddle


texts: C# function to execute queries in a SQL Server database

texts:
public static DataSet execute_query(string query)
{
    DataSet ds = new DataSet();
    SqlConnection con = new SqlConnection();
    con.ConnectionString = DataAccessLayer.Properties.Settings.Default.cn;
    try
    {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(query, con);
        da.Fill(ds);
    }
    catch (Exception ex)
    {
        ds = null;
    }
    finally
    {
        if (con.State == ConnectionState.Open) con.Close();
    }

    return ds;
}


texts: scrollTo and hide element code improvements

texts:
In this post, I asked how to scroll to an element and hide another via jQuery.

In my main javascript file I've made a script, but I'm not sure if it's correct. Can you tell me if this is a good way to do it, or if I can do it another better way?

$(function() {
    //Some default variables?
    var headerLoaded = true,
            contentLoaded = false,
            header = "#fitScreen";
    exploreBtn = "#exploreBtn",
            content = "#content";

    //This starts up a fullscreen video
    var videobackground = new $.backgroundVideo($(header), {
        "path": "assets/video/",
        "filename": "oceans",
        "types": ["mp4", "ogg", "webm"]
    });

    //When i click on the button the actually load the content
    $(exploreBtn).on('click', function() {
        event.preventDefault();
        init();
    });

    var init = function() {
        if (!contentLoaded && headerLoaded) {
            console.log("Loading content....");
            $(content).fadeIn(500, function() {
                $('html body').animate({
                    scrollTop: $(content).offset().top
                }, 1000, function() {
                    $(header).fadeOut(100, function() {
                        headerLoaded = false;
                        $('#content').css('top', 0);
                        $('html, body').css('overflow-y', 'scroll');
                        $(window).scrollTop(0);
                        $('nav').navi();
                    });
                    contentLoaded = true;
                    console.log("Done");
                });
            });
        } else {
            alert('Content already loaded..');
            $(this).stop();
        }
    };
});


texts: Detecting a cycle in a linked list using Java

texts:
I'm solving HackerRank "Linked Lists: Detect a Cycle" challenge.

  A linked list is said to contain a cycle if any node is visited more
  than once while traversing the list.

  Complete the function provided in the editor below. It has one
  parameter: a pointer to a Node object named head that points to the head
  of a linked list. Your function must return a boolean denoting whether
  or not there is a cycle in the list. If there is a cycle, return true;
  otherwise, return false.

  Note: If the list is empty, head will be null.

/*
Detect a cycle in a linked list. Note that the head pointer may be 'null' if the list is empty.

A Node is defined as:
    class Node {
        int data;
        Node next;
    }
*/

boolean hasCycle(Node head) {
    HashSet<Node> seen = new HashSet<Node>();

    Node current = head;
    while (current != null && current.next != null) {
        if (seen.contains(current)) {
            return true;
        }

        seen.add(current);
        current = current.next;
    }

    return false;
}

As a beginner Java developer, what can be improved here?


texts: One program using three functions to compare two double-precision numbers

texts:
I am currently learning C++ though Bjarne Stroustrup book Programming Principles and Practices using C++.

Going through the drills, I am trying to purposefully write efficient and readable code (good coding practices. However, I think I may be overdoing it with my use of functions for tasks within my program.

//Function to check if the entered numbers are similar in value
double similarValues(double valueBigger, double valueSmaller)
{
    if ((valueBigger - valueSmaller) < 0.01) {
        return 1;   //Return 1 if the values are similar
    }
    else {
        return 0;
    }
}

//Function checks which value is larger
double valueLarger(double value01, double value02)
{
    if (value01 > value02) {
        return value01;
    }
    else if (value01 < value02) {
        return value02;
    }
    else {
        return 0;       //Return 0 if the values are equal!
    }
}

//Function checks which value is smaller
double valueSmaller(double value01, double value02)
{
    if (value01 > value02) {
        return value02;
    }
    else if (value01 < value02) {
        return value01;
    }
    else {
        return 0;       //Return 0 if the values are equal!
    }
}

int main()
{

    // Reads two integers on each loop and prints them//
    double value02;
    double value01;

    while (cin >> value01 >> value02) {

        // Checks if the functions valueSmaller & valueLarger have not retuned 0
        if (valueSmaller(value01, value02) != 0 || valueLarger(value01, value02) != 0) {
            cout << "The smaller value is: " << valueSmaller(value01, value02) << " , the larger value is: " << valueLarger(value01, value02) << "\n";

            //Checks if the values are at least similar, returns 1 if true
            if (similarValues(valueLarger(value01, value02), valueSmaller(value01, value02)) == 1) {
                cout<<"The numbers are almost equal. \n";
            }
        }
        // If functions valueSmaller & valueLarger have returned 0 then do the below instuction
        else if (value01 == value02) {
            cout << "Both of these numbers are equal!" << "\n";
        }
        // If the values entered cannot be processed then output an error message
        else {
            cout << "Not a value I know! Incorrect input" << "\n";
        }

    }
}

Please critically (I do not mind if it is harsh) state what programming practices I am not following or following correctly. Also, whether my coding is on par with what you would deem as following great coding conventions.

Am I overdoing the functions?
Am I using return values differently then they should be used?
Is my code readable?
Are my comments accurate and to the point or are they vague?


texts: Using includes() vs. hash function to check if an unordered_set is a subset of another unordered_set

texts:
I did two methods to determine if an unordered_set is a subset of another unordered_set, using hashing, and the built-in includes().

I want to see if using a hash function will improve the run time, but I've noticed that there is no really big different in their time, so I start wondering, if what I did is the right idea of hashing!

Could you please look at my code to see if I did the hashing correctly?

#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <iomanip>
#include <algorithm>
#include <functional>

struct Sstruct {
    int Iv;
    float Fv1;
    float Fv2;
};

bool operator==(Sstruct a, Sstruct b) { return a.Iv == b.Iv; }

struct MyHash {
    size_t operator()(const Sstruct& x) const { return std::hash<int>()(x.Iv); }
};

bool IsIn(const std::unordered_set<int>& S1, const std::unordered_map <int, std::unordered_set<int>>::const_iterator& iter)
{
    for (std::unordered_set<int>::const_iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2)

        if (S1.find(*iter2) == S1.end())
        {
            return false;
        }

    return true;

}

int main()
{

    std::unordered_set<Sstruct, MyHash> S1{ { 1, 0.9, 0.1 }, { 2, 0.8, 0.2 }, { 3, 0.9, 0.01 }, { 4, 0.7, 0.5 }, { 7, 0.7, 0.2 }, { 8, 0.1, 0.5 } };

    std::unordered_map <int, std::unordered_set<int>> S2;

    S2[0].insert({ { 1 }, { 2 }, { 3} }); //  S2 is a subset of S1
    S2[1].insert({ { 3}, { 4 }, { 5} }); // S2 is a subset of S1
    S2[3].insert({ { 2 }, { 4 } }); // S2 is  a subset of S1
    S2[4].insert({ { 3 }, { 4 }}); // S2 is  a subset of S1
    S2[5].insert({ { 3 },  { 5 } }); // S2 is a subset of S1
    S2[6].insert({ { 1 }, { 2 }, { 8 } }); //  S2 is a subset of S1
    S2[7].insert({ { 3 }, { 4 }, { 6 } }); // S2 is not a subset of S1
    S2[8].insert({ { 2 }, {7 } }); // S2 is  a subset of S1
    S2[9].insert({ { 7 }, { 8 } }); // S2 is  a subset of S1
    S2[10].insert({ { 5 }, { 6 } }); // S2 is not a subset of S1

    std::unordered_set<int > SetOne;

    for (std::unordered_set<Sstruct, MyHash> ::iterator iter = S1.begin(); iter != S1.end(); ++iter)
        SetOne.insert(iter->Iv);

    float time1, time2;

    time1 = (float)clock() / CLOCKS_PER_SEC;

    // method 1: using hashing
    /*for (std::unordered_map <int, std::unordered_set<int>>::const_iterator SetTwo = S2.begin(); SetTwo != S2.end(); ++SetTwo)
        {
        if ((IsIn(SetOne, SetTwo)) == true)
            std::cout << "S2 is a subset of S1";

        else
            std::cout << "S2 is not a subset of S1";

        std::cout << "\n";
    }*/

    // method 2 using STL includes()
    std::unordered_map <int, std::unordered_set<int>>::const_iterator SetTwo = S2.begin();
    while (SetTwo != S2.end())
    {
        if (std::includes(SetOne.begin(), SetOne.end(), SetTwo->second.begin(), SetTwo->second.end()))

            std::cout << "S2 is a subset of S1";

        else
            std::cout << "S2 is not a subset of S1";
        ++SetTwo;
        std::cout << "\n";
    }

    time2 = (float)clock() / CLOCKS_PER_SEC;

    std::cout << "\n  Finishing Time " << time2 - time1 << " secs";
    std::cout << "\n\n";

    std::cin.get();
}


texts: Finding overlaps between two lists of axis-aligned rectangles

texts:
I am trying to find an efficient solution for finding overlapping of n rectangles where rectangles are stored in two separate lists. We are looking for all rectangles in listA that overlap with rectangles in listB (and vice versa). Comparing one element from the first list to second list could take immensely large amount of time. I am looking for an efficient solution.

I have two lists of axis-aligned rectangles:

rect = Rectangle(10, 112, 56, 15)
rect2 = Rectangle(0, 0, 1, 15)
rect3 = Rectangle (10, 12, 56, 15)

listA = [rect, rect2]
listB= [rect3]

which is created from the class:

import numpy as np
import itertools as it

class  Rectangle(object):
    def __init__(self, left, right, bottom, top):
        self. left = left
        self.bottom = bottom
        self.right = right
        self.top = top

    def overlap(r1, r2):
        hoverlaps = True
        voverlaps = True
        if r1.left > r2.right or r1.right < r2.left:
            hoverlaps = False
        if r1.top < r2.bottom or r1.bottom > r2.top:
            voverlaps = False
        return hoverlaps and voverlaps

I need to compare rectangle in listA to listB the code  goes like this which is highly inefficient - comparing one by one

for a in it.combinations(listB) :
    for b in it.combinations(listA):
        if a.overlap(b):

Any better efficient method  to deal with the problem?


texts: Find the largest odd number (follow-up code)

texts:
Ask user to input 10 integers and then print the largest odd number that was entered. If no odd number was entered, print a message to that effect.

This is a follow-up code on feedback from Find the largest odd number

This time I've taken care of a bug related to the number of integers entered and tried to handle invalid input if any. Please let me know if the code still can be tidied up in any way. I'm a beginner programmer.

print "You'll be asked to enter 10 integers."
print 'The program will look for odd numbers, if any.'
print 'Then, it will print the largest odd number.'
print 'Press Enter to start.'
raw_input('-> ')

numbers_entered = []

while True:
    try:
        number = int(raw_input('Enter an integer: '))
        numbers_entered.append(number)
    except ValueError:
        print 'That was not an integer.'

    if len(numbers_entered) == 10:
        break

odd_numbers = [item for item in numbers_entered if item % 2 == 1]

if odd_numbers:
    print 'The largest odd number entered was {}.'.format(max(odd_numbers))
else:
    print 'No odd number was entered.'


texts:
I have written a simple (read: incomplete) tuple implementation that, AFAICT, does not violate the standard layout requirements. It's largely based on Nish's implementation, but I use a recursive hierarchy of nested members, rather than recursive inheritance. Unfortunately this approach necessitates recursion for element access.  But for my purposes I am willing to sacrifice compilation time for a predictable memory layout... my tuple stores elements in the "correct" order.

Aside from lengthy compilation times, are there any obvious flaws to this approach?

#include <cstddef>
#include <type_traits>

template <class... Ts>
struct tuple;

template <class T, class... Ts>
struct tuple<T, Ts...>
{
    T first;
    tuple<Ts...> rest;
};

template <class T>
struct tuple<T>
{
    T first;
};

namespace detail {

    template < ::std::size_t i, class T>
    struct tuple_element;

    template < ::std::size_t i, class T, class... Ts>
    struct tuple_element<i, tuple<T, Ts...> >
        : tuple_element<i - 1, tuple<Ts...> >
    {};

    template <class T, class... Ts>
    struct tuple_element<0, tuple<T, Ts...> >
    {
        using type = T;
    };

    template < ::std::size_t i>
    struct tuple_accessor
    {
        template <class... Ts>
        static inline typename tuple_element<i, tuple<Ts...> >::type & get (tuple<Ts...> & t)
        {
            return tuple_accessor<i - 1>::get(t.rest);
        }

        template <class... Ts>
        static inline const typename tuple_element<i, tuple<Ts...> >::type & get (const tuple<Ts...> & t)
        {
            return tuple_accessor<i - 1>::get(t.rest);
        }
    };

    template <>
    struct tuple_accessor<0>
    {
        template <class... Ts>
        static inline typename tuple_element<0, tuple<Ts...> >::type & get (tuple<Ts...> & t)
        {
            return t.first;
        }

        template <class... Ts>
        static inline const typename tuple_element<0, tuple<Ts...> >::type & get (const tuple<Ts...> & t)
        {
            return t.first;
        }
    };

    template <class T, class... Ts>
    struct tuple_builder
    {
        static inline void make (tuple<typename ::std::decay<T>::type, typename ::std::decay<Ts>::type...> & t, T && x, Ts &&... xs)
        {
            t.first = x;
            tuple_builder<Ts...>::make(t.rest, ::std::forward<Ts>(xs)...);
        }
    };

    template <class T>
    struct tuple_builder<T>
    {
        static inline void make (tuple<typename ::std::decay<T>::type> & t, T && x)
        {
            t.first = x;
        }
    };

} // namespace detail

template <class... Ts>
inline tuple<typename ::std::decay<Ts>::type...> make_tuple (Ts &&... x)
{
    tuple<typename ::std::decay<Ts>::type...> t;
    detail::tuple_builder<Ts...>::make(t, ::std::forward<Ts>(x)...);
    return t;
}

template < ::std::size_t i, class... Ts>
inline typename detail::tuple_element<i, tuple<Ts...> >::type & get (tuple<Ts...> & t)
{
    return detail::tuple_accessor<i>::get(t);
}

template < ::std::size_t i, class... Ts>
inline const typename detail::tuple_element<i, tuple<Ts...> >::type & get (const tuple<Ts...> & t)
{
    return detail::tuple_accessor<i>::get(t);
}

static_assert(::std::is_standard_layout<tuple<bool, int, float, char, double, tuple<int, char> > >(), "Compiler is stupid");

For more context, see this


texts: Accounting for floating point error when rounding

texts:
I have to implement some business logic that will round a number (typically a double) upwards. Given that this number comes from a third-party and I don't know how they come to calculate it I'm anticipating errors in it. My proposed routine to mitigate rounding errors (like Math.ceil(1.000000000000002) = 2) is as follows:
export const roundupDiscount = (discount: number) => {
    // We have to give advantage to the customer for the discount value when rounding,
    // that is to say, we will sacrifice the penny when we can't be exact. This means
    // we have to always round the discount upwards (so we can't Math.round because
    // half the time we'll round in the wrong direction.)
    // To account for numbers like, say, 1.000000000000002 (i.e. (1 / 5 / 7) * 5 * 7))
    // then we subtract off a "small" number (scaled with the magnitude of discount)
    // which will nudge below the number we will round up to

    if (!discount) return 0 // discount shouldn't be negative

    const magnitude = Math.floor(Math.log(discount) / Math.log(10))
    const epsilon = Math.pow(10, magnitude - 14)
    return Math.ceil(discount - epsilon)
}

Given that a double has between 15-17 significant digits in it, I'm choosing epsilon, arbitrarily, such that I have a couple of trailing digits to play with.
Can anybody spot any cases where this is going to get things wrong? simplify this thing, or, given this is node.js point me towards an npm module that does this kind of thing for me?
Note: I have to get this past code-review at work so I'd much prefer if there was a good library out there that I can use instead and not even bother submitting this!


texts:
I just finished building a simple random Tic Tac Toe generator. The program will display 3 rows of a random numbers 0-1 and will print a message when 3 of the same numbers align. The program works perfectly, to my knowledge.

I am posting this code here in hopes that I can gain some advice/tips in regards to optimization and/or simplification.

import random

row1 = [round(random.uniform(0, 1)), round(random.uniform(0, 1)), round(random.uniform(0, 1))]
row2 = [round(random.uniform(0, 1)), round(random.uniform(0, 1)), round(random.uniform(0, 1))]
row3 = [round(random.uniform(0, 1)), round(random.uniform(0, 1)), round(random.uniform(0, 1))]

print(row1)
print(row2)
print(row3)

# If statements for all 3 rows
if (row1[0] == row1[1]) and [row1[1] == row1[2]] and (row1[2] == row1[0]):
    print("All " + str(row1[0]) + "'s in top row!")
if (row2[0] == row2[1]) and [row2[1] == row2[2]] and (row2[2] == row2[0]):
    print("All " + str(row2[0]) + "'s in middle row!")
if (row3[0] == row3[1]) and [row3[1] == row3[2]] and (row3[2] == row3[0]):
    print("All " + str(row3[0]) + "'s in bottom row!")

# If statements for all 3 columns
if (row1[0] == row2[0]) and [row2[0] == row3[0]] and (row3[0] == row1[0]):
    print("All " + str(row1[0]) + "'s in left column!")
if (row1[1] == row2[1]) and [row2[1] == row3[1]] and (row3[1] == row1[1]):
    print("All " + str(row1[1]) + "'s in middle column!")
if (row1[2] == row2[2]) and [row2[2] == row3[2]] and (row3[2] == row1[2]):
    print("All " + str(row1[2]) + "'s in right column!")

# If statements for diagonals
if (row1[0] == row2[1]) and (row2[1] == row3[2]) and (row3[2] == row1[0]):
    print("All " + str(row1[0]) + "'s in diagonal!")
if (row1[2] == row2[1]) and (row2[1] == row3[0]) and (row3[0] == row1[2]):
    print("All " + str(row1[2]) + "'s in diagonal!")


texts:
After taking some great advice on this question, I'm hoping for some more feedback on my quadratic expression calculator.

This is my code as stands:

public class Quadratic_Equations {

    private final static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            System.out.println("Please enter a, b and c or enter \"exit\" at any time to exit");
            double a = promptUserUntilValidInput("Please enter a:");
            double b = promptUserUntilValidInput("Please enter b:");
            double c = promptUserUntilValidInput("Please enter c:");
            System.out.println(formatOutput(calculateQuadraticFormula(a, b, c)));
            System.out.println();
        }
    }

    private static String formatOutput(Set<Double> resultsFromEquation) {
        if (resultsFromEquation == null)
            return "These numbers do not compute - they produce an illegal result.";
        else {
            return resultsFromEquation.toString();
        }
    }

    private static double promptUserUntilValidInput(String prompt){
        if (prompt.equals("exit")) {
            sc.close();
            System.exit(0);
        }
        boolean valid = false;
        Double value = new Double(0.0);
        while(!valid){
            System.out.println(prompt);
            value = tryParse(sc.nextLine());
            if (value != null)
                valid = true;
        }
        return value;
    }

    private static Double tryParse(String text){
        try{
            return Double.parseDouble(text);
        }
        catch (NumberFormatException e){
            return null;
        }
    }

    public static Set<Double> calculateQuadraticFormula(double a, double b, double c) {
        Set<Double> results = new HashSet<Double>();
        double temp = (b * b) - (4 * a * c);
        if (temp < 0)
            return null;
        if( temp == 0 ) {
            results.add(-b / 2 * a);}
        else if( temp > 0) {
            results.add( (-b + Math.sqrt(temp) ) / (2 * a) );
            results.add( (-b - Math.sqrt(temp) ) / (2 * a) );
        }
        return results;
    }
}

Before I go on, there are a few things I should point out.

I'm aware this could be better if the quadratic stuff was in a class of its own - however, for the purposes of this simple exercise I'm happy skipping that.

My main issues are:

static Scanner. Some people on previous question suggested making this a private variable, but then it needs to get passed to everything. Is this worth it?
Does it look okay to close the scanner (and exit the program) where I do?
Do other methods look single-responsibility-ish enough?


texts:
I am studying for interviews for various companies. I wrote a solution to this problem, but if an experience programmer looks at it I am sure there are certain areas the code can be made in to a more beautiful code.

  Given a triangle, find the minimum path sum from top to bottom. Each
  step you may move to adjacent numbers on the row below.

  For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

  The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

My DP solution:

public class Solution {
public static int minimumTotal(List<List<Integer>> triangle) {
        if(triangle==null){
            return -1;
        }
        int [][] dp=new int[triangle.size()][triangle.size()];
        for(int i=0;i<triangle.size();i++){
            Arrays.fill(dp[i],0);

        }
        getMin(triangle,0,0,dp);
        return dp[0][0];
    }

    public static int getMin(List<List<Integer>> tri, int level, int index, int [][]dp){
        if((level+1)==tri.size()){
            dp[level][index]=tri.get(level).get(index);
            return dp[level][index];
        }else{
            int left=-1;
            int right=-1;
            if(dp[level+1][index]!=0){
                left=dp[level+1][index];
            }else{
                left=getMin(tri, level+1, index,dp);
            }
            if(dp[level+1][index+1]!=0){
                right=dp[level+1][index+1];
            }else{
                right=getMin(tri, level+1, index+1,dp);
            }
            dp[level][index]=tri.get(level).get(index)+Math.min(left,right);

            return dp[level][index];
        }
    }
}


texts: Sessions class With assoc-array - practicing

texts:
I try to dealing with sessions.. including arrays before moving to "database".

Sessions class.file

<?php
session_start();
class Sessions {

public static function ready($name){
  return isset($_SESSION[$name]) ? true : false;
}
    public static function get($name){
      if(isset($_SESSION[$name])){
        return $_SESSION[$name];
      }else {
        return false;
      }
      }

public static function set($name, $val = []){
  return $_SESSION[$name] = $val;

}

    public static function des($name){
      if(self::ready($name)){
       unset($_SESSION[$name]);
      }

    }

}

index.php file

<?php

include_once "Sessions.php";

const BR = '
';

$er = [];
$data = array([
    'id'=> '1',
    'username'=> 'user1',
    'password'=>'123456'
  ],
  [
    'id'=> '2',
    'username'=> 'user2',
    'password'=>'654321'
  ]
);

//submit
if(isset($_POST['submit'])){
  // Error Msgs
$er[] = "Not found in array";
// Forms Inputs
$username = $_POST['username'];
$password = $_POST['password'];

//fetch users in array
foreach ($data as $key => $value) {
  if(in_array($username, $value)){
    if( $username == $value['username'] && $password == $value['password'] ){
      $uid = $value['id'];
      $unm = $value['username'];
      //Sessions class
      Sessions::set('id', $uid);
      Sessions::set('username', $unm );
      // Error Msgs
     unset($er[0]);
    }
}
  }
}

?>
<?php
//Sessions class
$susername = Sessions::ready('username');
$sid = Sessions::ready('id');
if( $susername AND $sid) { ?>
<?$sid?>
<?$susername?>
<?=BR.Sessions::get('username').BR?>
<?=BR.Sessions::get('id').BR?>

Out

<? if( isset( $er[0] ) ) { echo $er[0];}else { unset( $er[0] ); } ?>

<form  method="post">
  <input type="text" name="username" value="">
  <input type="password" name="password" value="">
  <input type="submit" name="submit" value="submit">
</form>

logout.php file

<?php
include_once "Sessions.php";
Sessions::des('username');
Sessions::des('id');
header("Location:session.php");
?>

Is it good for beginner..! is there something wrong..! is there better way for that messy code ?


texts: Text box intuitive user-interaction using focus listeners

texts:
This code aims to replace labels used to explain a text box's container. This is done by adding a default string when the text box is considered empty to explain the purpose of the text box. However, when the text box is not considered empty, the text box will behave normally.

This is what I have written to solve my issue, I am posting it here for feedback and tips regarding anything to do with my code.

private void jTextFieldFocusGained(FocusEvent evt) {
    if(jTextField.getText().equals(TEXT_DEFAULT))
    {
        jTextField.setForeground(FOCUSED_COLOR);
        jTextField.setText(TEXT_FOCUSED);
    }
}
private void jTextFieldFocusLost(FocusEvent evt) {
    if(jTextField.getText().equals(TEXT_FOCUSED))
    {
        jTextField.setText(TEXT_DEFAULT);
        jTextField.setForeground(COLOR_DEFAULT);
    }
}
private final String TEXT_FOCUSED = "";
private final String TEXT_DEFAULT = "Type text here...";
private final Color COLOR_FOCUSED = Color.BLACK;
private final Color COLOR_DEFAULT = Color.LIGHT_GRAY;


texts: Search through multiple lists, but have functions that do that in parts

texts:
I have an Entity Framework table of Addresses. I'm building a Repository that would allow me to search for an Address by either parts of the Address or the whole address.

Here's what I've got so far:

public class AddressRepository : Repository<Address>
{
    public List<Address> GetByAddress(string street, string city, string state, string zip)
    {
        return DbSet
            .Where(address => address.Street.Contains(street))
            .Where(address => address.City.Contains(city))
            .Where(address => address.State.Contains(state))
            .Where(address => address.Zip.Contains(zip))
            .ToList();
    }

    public List<Address> GetByStreet(string street)
    {
        return DbSet.Where(address => address.Street.Contains(street)).ToList();
    }

    public List<Address> GetByCity(string city)
    {
        return DbSet.Where(address => address.Street.Contains(city)).ToList();
    }

    public List<Address> GetByState(string state)
    {
        return DbSet.Where(address => address.Street.Contains(state)).ToList();
    }

    public List<Address> GetByZip(string zip)
    {
        return DbSet.Where(address => address.Street.Contains(zip)).ToList();
    }
}

Here is my Repository base class:

public class Repository<T> where T : class
{
    private readonly ApplicationDbContext _applicationDbContext = new ApplicationDbContext();

    protected DbSet<T> DbSet { get; }

    protected Repository()
    {
        DbSet = _applicationDbContext.Set<T>();
    }

    public virtual List<T> GetAll()
    {
        return DbSet.ToList();
    }

    public virtual T Get(int id)
    {
        return DbSet.Find(id);
    }

    public virtual void Add(T entity)
    {
        DbSet.Add(entity);
    }

    public virtual void SaveChanges()
    {
        _applicationDbContext.SaveChanges();
    }
}

Now, I'm thinking that in my GetByAddress function I should be calling my GetByStreet/City/State/Zip functions instead of repeating their code.

I haven't quite figured out how to do that, so any help or suggestions regarding that would be great.

As a side question: In my Repository class I have a GetAll function that returns the whole DbSet as a list, should I be calling GetAll().Where(...) instead of calling DbSet.Where(...)?


texts: Display resources for each factory in the Rocket Valley Tycoon

texts:
I'm new here. I'm trying to teach myself programming by learning Python. I have assigned myself the following task.

There's a game I'm playing (Rocket Valley Tycoon) where the goal is to basically place an Extractor to gather resources, then use Factories to transform the resource into a good, which then usually gets processed again by another Factory into a processed good.

The point of the program I'm trying to write is to be able to see the resources needed for any Factory. So, for example, Copper plates need 10 carbon and 20 copper ore, and at the same time, the carbon needs 2 coal and 4 water, so I would like the final output to be something like:

Copper plates need 20 copper ore, 20 coal, and 40 water. I have a working prototype, that works with just this, but if I know it can be simplified somehow. (Especially in the print_total function)

Also, this only works with a Factory that has just one "child" Factory and not with n "child" Factories. This is the first tech tree:

Can someone please point me in the right direction?

class Factory:

    def __init__(self, name, ing1, amount1, ing2=None, amount2=None):
        self.name = name
        self.ing1 = ing1
        self.amount1 = amount1
        self.ing2 = ing2
        self.amount2 = amount2
        self.total_amount1_1 = None
        self.total_amount1_2 = None
        self.total_amount2_1 = None
        self.total_amount2_2 = None
        self.total_ing1_ing1 = None
        self.total_ing1_ing2 = None
        self.total_ing2_ing1 = None
        self.total_ing2_ing2 = None

    def print_ing(self):
        print(self.name + ' needs: ')
        print(self.amount1, self.ing1.name, self.amount2, self.ing2.name)

    def print_total(self):
        if isinstance(self.ing1, Factory):
            print('Ing1 is Factory')
            self.total_ing1_ing1 = self.ing1.ing1
            self.total_ing1_ing2 = self.ing1.ing2
            self.total_amount1_1 = self.amount1 * self.ing1.amount1
            self.total_amount1_2 = self.amount1 * self.ing1.amount2
        elif isinstance(self.ing2, Factory):
            print('Ing2 is Factory')
            self.total_ing2_ing1 = self.ing2.ing1
            self.total_ing2_ing2 = self.ing2.ing2
            self.total_amount2_1 = self.amount2 * self.ing2.amount1
            self.total_amount2_2 = self.amount2 * self.ing2.amount2
        print(self.name + ' needs: ')
        print(self.amount1, self.ing1.name, self.total_amount2_1,
              self.total_ing2_ing1.name, self.total_amount2_2,\
              self.total_ing2_ing2.name)

class Extractor:
    def __init__(self, name):
        self.name = name

coal = Extractor('Coal')
water = Extractor('Water')
copper_ore = Extractor('Copper Ore')
carbon = Factory('Carbon', coal, 2, water, 4)
copper_plates = Factory('Copper Plates', copper_ore, 20, carbon, 10)


texts: Recording a customer's shopping cart as an order 2.0

texts:
Some days ago, I put up a question here for review about the best way to handle JDBC transactions in the context of an e-commerce Java web application.

After a kind suggestion from user @gardenhead, I decided to use the try-with-resources construct to automatically close my resources, namely the statement and the connection objects.

I also found this SO answer, which told me how to properly use try-with-resources for this kind of operation.

This is my improved code:

public long insertOrder(Customer customer, Hashtable<String, CartItem> shoppingCart)
{
    try (Connection connection = MySqlConnection.getConnection()) {
         try (Statement statement = connection.createStatement()) {
            connection.setAutoCommit(false);
            long orderId = System.currentTimeMillis();
            OrderPeer.insertOrder(statement, orderId, customer);
            OrderDetailsPeer.insertOrderDetails(statement, orderId, customer);
            connection.commit();
            return orderId;
        } catch (SQLException e) {
            connection.rollback();
            System.err.println("Could not insert order: " + e.getMessage());
            return 0L;
        }
    } catch (SQLException e) {
        return 0L;
    }
}

The rollback is triggered when either there is a problem with the transaction itself, or when there is a problem with the automatic closing of the statement. The later due to the fact that it would be indicative of a database access error that left the transaction in an unknown state.

If there is anything else that could be improved, please let me know.


texts: Selecting employees in certain departments using LINQ

texts:
I am trying to select the DepartmentName from Employee Table based on where condition. Is any way to simplify the code?

List<Department> lstdepartment=(from i in _context.Department
                                select i).ToList();

    List<Employee>lstEmployee=(from e in _context.Employee
                            where e.EmployeeId=EmployeeId
                            select new EmployeeInfo
                            {
                                EmployeeId = e.EmployeeId,
                                FirstName = e.FirstName,
                                LastName = e.LastName,
                                MiddleName = e.MiddleName,
                                //Need code simplifiaction
                                DepartmentName=lstdepartment.Where(w=>w.DepartmentId==e.DepartmentId)
                                .Select(x=>x.DepartmentName).SingleOrDefault();
                            }).ToList();


texts:
K and R Exercise 5-10

  Write the program expr, which evaluates a reverse Polish expression
  from the command line, where each operator or operand is a separate
  argument.

  For example,

expr 2 3 4 + *

  evaluates

2 * (3+4)

#include <stdio.h>
#include "expression_parser.h"

int parse_polish(int size, char *expression[])
{
    char *entry;
    int temp1, temp2;

    if (expression[1] && ((isdigit(*expression[1]) &&
        isdigit(*expression[2])))) {
        stack_init(&size, expression);
        expression++;
        for ( ; *expression; expression++) {
            if (isdigit(*(entry = *expression)))
                push(atoi(entry));
            else {
                switch (*entry) {
                    case '+':
                        push(pop() + pop());
                        break;
                    case '-':
                        temp1 = pop();
                        temp2 = pop();
                        push(temp1 - temp2);
                        break;
                    case '*':
                        push(pop() * pop());
                        break;
                    case '/':
                        temp1 = pop();
                        temp2 = pop();
                        if (!(temp2))
                            return -1;
                        else
                            push(temp1 / temp2);
                        break;
                    default:
                        return -1;
                }
            }
        }
        return pop();
    } else
          return -1;
}

Repository


texts:
I (ruby beginner) have a performance issue with the following ruby code. The idea is to aggregate a CSV into a smaller, better-to-handle file and calculating the average of some values. Basically the same code in groovy runs about 30 times faster. And I can't believe that Ruby is that slow! ;-)

Some background:
The file consists of lines like this (it is an output file of a JMeter performance test):

timeStamp|elapsed|label|responseCode|responseMessage|threadName|dataType|success|failureMessage|bytes|Latency
2013-05-17_16:30:11.261|4779|Session_Cookie|200|OK|Thread-Gruppe 1-1|text|true||21647|4739

All values of e.g. a certain minute are selected by looking at the first 16 characters of the timestamp:

2013-05-17_16:30:11.261 => 2013-05-17_16:30

I wanted to collect values in buckets/slices which are represented by the shortened timestamp and the label (third column). The value of the second column ("elapsed") is summed up.

require 'csv'
require_relative 'slice'

# Parameters: <precision> <input file> [<output file>]
precision = ARGV[0].to_i
input_file = ARGV[1]
output_file = ARGV[2]

time_slices = Hash.new

CSV.foreach(input_file, {:col_sep => '|', :headers => :first_line}) do |row|
  current_time_slice = row['timeStamp'][0, precision]

  if time_slices[current_time_slice] == nil
    time_slices[current_time_slice] = Hash.new
  end

  if time_slices[current_time_slice][row['label']]
    time_slices[current_time_slice][row['label']].put_line(row)
  else
    new_slice = Slice.new(current_time_slice, row['label'])
    new_slice.put_line(row)
    time_slices[current_time_slice][row['label']] = new_slice
  end
end

out = File.new(output_file, 'a')
out.puts 'time|label|elapsed_average'
time_slices.values.each do |time_slice|
  time_slice.values.each do |slice|
    out.puts slice.aggregated_row
  end
end

The slice class looks like this:

class Slice
  attr_accessor :slice_timestamp, :slice_label, :lines, :sum, :count

  def initialize(slice_timestamp, slice_label)
    @slice_timestamp = slice_timestamp
    @slice_label = slice_label
    @count = 0
    @sum = 0
  end

  def put_line(line)
    @sum = @sum + line[1].to_i
    @count = @count + 1
  end

  def average
    @sum / @count
  end

  def aggregated_row
    @slice_timestamp + '|' + @slice_label + '|' + average.to_s
  end
end

I think that I chose a quite straightforward and non-optimized approach, but still - the same approach is much faster in Groovy. What can be the reason for that?


texts:
Implementation of a hash function in java, haven't got round to dealing with collisions yet.
I tried to use good code, refactored, descriptive variable names, nice syntax.

My code must be efficient and extensible.

Would be interested to know how you guys would improve.
Three classes:

TestHash - main method is here, hash is initialised and data
inserted and read
HashTable -object were the hash table is held
HashEntry - each entry in the array is a 'HashEntry' object

HashTable

import java.io.*;

public class HashTable {
    // number of indexes in hash table
    private final static int TABLE_SIZE = 100;
    // initialise array of HashEntry (table)
    HashEntry[] table;

    // constructor, create array, assign all values to null
    HashTable() {
        // create array of HashEntry, predefined size
        table = new HashEntry[TABLE_SIZE];
        // assign all values to null
        for (int i = 0; i < TABLE_SIZE; i++) {
            table[i] = null;
        }
    }

    // from key, find the correct index, load the HashEntry object and return the value
    public String getValue(String key) {
        int index = this.getKeyIndex(key);
        HashEntry chosen_entry = table[index];
        String chosen_entry_value = chosen_entry.getValue(key);
        return chosen_entry_value;
    }

    // creates a new HashEntry object, inserts that into the table array at the correct index
    // determined by getKeyIndex(key)
    public void insert(String key, String value) {
        int index = this.getKeyIndex(key);
        HashEntry keyValuePair;
        keyValuePair = new HashEntry(key, value);
        table[index] = keyValuePair;
        return;
    }

    // ** PRIVATE FUNCTIONS ** //
    // get index from key
    private Integer getKeyIndex(String key) {
        int hash = 7;
        for (int i = 0; i < key.length(); i++) {
            hash = (hash*31 + key.charAt(i))%100;
        }
        return hash;
    }
}

HashEntry

public class HashEntry {
    private String key;
    private String value;

    HashEntry(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return this.key;
    }

    public String getValue(String key) {
        // use string key to move down linked list in case of collision
        // haven't implemented this yet
        return this.value;
    }
}

TestHash

public class TestHash {
    public static void main(String[] args)
    {
        HashTable tableHash = new HashTable();
        tableHash.insert("david", "england");
        tableHash.insert("joe", "united states");
        tableHash.insert("maria", "china");
        System.out.println(tableHash.getValue("joe"));
    }
}


texts:
I wrote a Python script to scan my music library, randomly select 50 songs, and play them in VLC media player. It works great, just a little slow (takes several seconds to launch).

I know that walking through my entire music library (thousands of songs) is a brute force (slow) way to do it. What would be a faster approach?

I would also appreciate any suggestions on syntax or Pythonic improvements.

from subprocess import Popen
import os, sys
import random

# http://ubuntuforums.org/showthread.php?t=2136340
# http://stackoverflow.com/questions/19859840/excluding-directories-in-os-walk
def scanfolder(rootpath, exclude_dirs, file_ext):
    musiclist = []
    for path, dirs, files in os.walk(rootpath):
        dirs[:] = [d for d in dirs if d not in exclude_dirs]
        for f in files:
            if f.endswith(file_ext):
                mp3 = os.path.join(path, f)
                musiclist.append(mp3)
    return musiclist

# input variables
vlcpath = r'C:\Program Files (x86)\VideoLAN\VLC\vlc.exe'
musicpath = r'G:\Music Collection'
excludedirectories = ['_baby music','Buble, Michael','ballroom dancing']
filetype = r'.mp3'
len_playlist = 50

# run script
print 'party on... filling glasses!'
mp3_list = scanfolder(musicpath, excludedirectories, filetype)
playlist = random.sample( mp3_list, min(len_playlist, len(mp3_list)) )
Popen([vlcpath] + playlist)
print 'done: added %i items from library containing %i \'%s\' files' % (len(playlist), len(mp3_list), filetype)


texts: Filtering potentially malicious user-defined CSS property values using ScssPhp

texts:
I have a script that allows stylesheet customization on a per-property basis. For example, I expose the "background-image" property for people to enter their own SCSS values to be entered in the mixin.

I want to know if I'm opening up an avenue for exploitation by doing this.

Some things to note are that I'm using ScssPhp, and my code looks like this:

using Leafo\ScssPhp\Compiler;

$scss = new Compiler();
$scss->setFormatter('Leafo\ScssPhp\Formatter\Expanded');
$scss->setImportPaths([ __DIR__.'/Application/Extra/bourbon/', __DIR__.'/Application/View/default/' ]);
$scss->setVariables([
    'background-color' => '#ffffff',
    'background-image' => 'linear-gradient(top, rgba(30,87,153,1) 0%, rgba(125,185,232,1) 100%)'
]);
die($scss->compile('@import "style.scss";'));

And for the SCSS (a snippet):

@import "bourbon";

$background-color: #332517 !default;
$background-image: null !default;

body {
    /* ... other style properties ... */
    background-color: $background-color;

    @if $background-image != null {
        @include background-image($background-image);
    }
}

This is just strictly for testing purposes right now. The parser treats these strictly as variables and it looks as if the mixin ignores junk like concatenating a behavior property onto the end of the background-image variable string. Mostly this will just be editing colors and backgrounds of elements I define variables for. So all input is done into variables, and then hopefully into mixins provided by Bourbon.

Relevant library references (parseValue method)

Background Image

So if it ignores junk and only accepts valid input into the background-image mixin, then is that sufficient to make sure users can not input malicious CSS?


texts:
I need to generate a huge array from a few words, and not random, I must get the same array always for the same words.

I wrote this code which will generate 3050 from 51 letters, but I'm sure there is a better way to do it.

The idea is to convert the letters to ASCII numbers and put them into an array, then manipulate this array to get a new big array.

this.otpOne = 'OrangePie'
this.otpTwo = 'ClearBlueSky'
this.otpThree = 'RedApplePie'
this.otpFour = 'MakeItEasy'
this.otpFive = 'blueBerry'

gen();

function gen() {
    let otpString = this.otpOne + this.otpTwo + this.otpThree + this.otpFour + this.otpFive;
    let otpStringArray = otpString.split('').map(char => char.charCodeAt(0));
    let otpStringSorted = otpStringArray.sort();
    let median = this.median(otpStringSorted);
    Array.prototype.swap = function () {
        let len = this.length;
        let d = [];
        for (let y = 0; y < len; y++) {
            if (y + 1 < len) {
                let tempOne = this[y];
                let tempTwo = this[y + 1];
                d.push(tempTwo, tempOne);
                tempOne = '';
                tempTwo = '';
            }
        }
        return d;
    };

    let left = [], right = [], odd = [], even = [];
    odd.push(otpStringSorted.filter(num => Math.abs(num) % 2 === 1));
    even.push(otpStringSorted.filter(num => Math.abs(num) % 2 === 0));
    right.push(otpStringSorted.filter(num => Math.abs(num) > median));
    left.push(otpStringSorted.filter(num => Math.abs(num) < median));
    let chunksOne = this.makeChunks(otpStringSorted, 2);
    let chunksTwo = this.makeChunks(otpStringSorted, 3);
    let chunksThree = this.makeChunks(otpStringSorted, 4);
    let chunksFour = this.makeChunks(odd.concat(right).flat(), 2);
    let chunksFive = this.makeChunks(even.concat(left).flat(), 2);
    let otpStringSortedRev = Array.from(otpStringSorted).reverse();
    let stringsArraysV1 = [
        ...odd.flat(),
        ...left.flat(),
        ...even.flat(),
        ...right.flat(),
        ...chunksOne.flat(),
        ...chunksTwo.flat(),
        ...chunksThree.flat(),
        ...chunksFour.flat(),
        ...chunksFive.flat(),
        ...otpStringSortedRev.flat()];
    let stringsArraysV2 = [
        ...even.flat(),
        ...right.flat(),
        ...odd.flat(),
        ...even.flat(),
        ...chunksFive.flat(),
        ...chunksFour.flat(),
        ...chunksThree.flat(),
        ...chunksTwo.flat(),
        ...chunksOne.flat(),
        ...otpStringSortedRev.flat()];
    let stringsArraysV3 = stringsArraysV1.filter(num => Math.abs(num) % 2 === 1 ? num / 2 : num)
    let stringsArraysV4 = stringsArraysV2.filter(num => Math.abs(num) % 2 === 1 ? num / 2 : num)
    this.stringsArrays = [
        ...stringsArraysV1,
        ...stringsArraysV2,
        ...stringsArraysV3,
        ...stringsArraysV4,
        ...otpStringSorted.swap(),
        ...stringsArraysV1.swap(),
        ...stringsArraysV2.swap(),
        ...stringsArraysV3.swap(),
        ...stringsArraysV4.swap(),
    ];

    $('.key').text(this.stringsArrays)
    $('.len').text('len: ' + otpString.length + ' to ' + this.stringsArrays.length)

}

function makeChunks(array, size) {
    let add = (a, b) => a + b,
        newArray = [],
        i = 0;
    while (i < array.length) {
        newArray.push(array.slice(i, i += size).reduce(add) % (33 - 126));
    }
    let finalArray = newArray.map(num => num < 34 ? ((92 - num) + num) : num);

    return finalArray;
}

function median(values) {
    values.sort(function (a, b) {
        return a - b;
    });
    let half = Math.floor(values.length / 2);

    if (values.length % 2)
        return values[half];
    else
        return (values[half - 1] + values[half]) / 2.0;
}
```


texts: File archiver, archive files into a zip file

texts:
I've created a simple little file archiver that will run through a given directory and extract your files into an archive folder. It's pretty cool if I do so say myself, I would like some critique on what I've done, and some ideas on how I could better this program, better syntax, easier ways to do this, etc..

using System;
using System.IO;
using System.IO.Compression;

namespace ArchiveCreator
{
    class Program
    {
        //When program is run successfully
        //this will be the output
        public string Success(string input)
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(input);
            return input;
        }

        //When program encounters an error
        //this will be the output
        public string Warn(string input)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(input);
            return input;
        }

        //When program has information to show
        //this will be the output
        public string Say(string input)
        {
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine(input);
            return input;
        }

        //Main method
        static void Main(string[] args)
        {
            //These variables are used to create a
            //random string that will be used as the
            //zip files name
            var chars = "abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var stringChars = new char[8];
            var random = new Random();

            //Info is used as provide the type of
            //information that will be displayed
            //by the program
            Program info = new Program();

            //Create the zip file name
            for (int i = 0; i < stringChars.Length; i++)
            {
                stringChars[i] = chars[random.Next(chars.Length)];
            }
            string finalString = new String(stringChars);

            info.Say("Starting file extraction..");

            string userName = Environment.UserName;
            string startDir = $"c:/users/{userName}/test_folder";
            string zipDir = $"c:/users/{userName}/archive/{finalString}.zip";
            string dirName = $"c:/users/{userName}/archive";

            //Check if the directory exists
            if (Directory.Exists(dirName))
            {
                info.Say("Directory already exists, resuming");
            }
            else
            {
                //Create it if it doesn't
                Directory.CreateDirectory(dirName);
            }

            try
            {
                ZipFile.CreateFromDirectory(startDir, zipDir);
            }
            catch (Exception e)
            {
                info.Warn($"Error: {e}");
            }
            info.Success($"Extracted files successfully to: {zipDir}");
            info.Say("Press enter to exit..");
            Console.ReadLine();
        }
    }
}


texts: Sorting dictionary according to letter patterns

texts:
I've written a JavaScript dictionary sorting algorithm, which takes a .txt file (the dictionary), and loads it via node's file system. The purpose of this algorithm is to sort every word into its corresponding array based on its letter pattern. For example, the word little would have the letter pattern of ABCCDE, and hello would have the letter pattern of ABCCD. The purpose of this sorting algorithm is to use it to decode substitution ciphers; however, this is the only working code I've written so far for it. This code works, and I have a sorted dictionary file here.

However, I want to know how I might be able to improve this algorithm to make it as fast and efficient as possible. Even though its only run once, I want to get into the habit of writing efficient code.

To break down exactly what's going on in the algorithm I've added a few comments, but to elaborate it loads each word from the dictionary and stores it in an array, in which I then iterate through the array and each letter of the word. The clpl variable starts at 'A', and it checks if it exists in a temp object. If it does, it adds that letter to the letter pattern, if it does not, it creates a new property on the object and assigns it the current letter as a value. It adds the assigned letter to lp, which is initialized as an empty string.

The line clpl = String.fromCharCode(clpl.charCodeAt(0) + 1);gets the next letter. After it has iterated through each letter in the word, it checks if the current letter pattern exists in the sortedDictionary object, if it does it pushes it to an array containing all words with its letter pattern. If it does not, it creates a new array for that letter pattern and pushes the current word to that array. After it has gone through every word, it writes the sortedDictionary object to an external JSON file.

//load file system
var fs = require("fs");
//load jsonfile
var jsonfile = require("jsonfile");

//create var for dictionary file
var dictFile = "american-english", sortedDictFile = "sortedDictionary.json";

//empty object to hold sorted dictionary according to letter patterns
//empty dictionary array to hold words
var sortedDictionary = {}, dictionary = [];

//declare variables for use
var temp, clpl, lp, word;

console.time("Dictionary Sort");

fs.readFile(dictFile, "utf8", function(error, data){
    if(error) throw error;
    //push all words into an array
    dictionary = data.toString().split("\n");

    for(var i = 0; i < dictionary.length; i++){
        //set word to current word in dictionary
        word = dictionary[i];
        //set temp to empty object, clpl to A, and lp to an empty string
        //this is used to get the current letter pattern
        temp = {}, clpl = 'A', lp = '';

        for(var j = 0; j < word.length; j++){
            if(word[j] in temp){
              lp += temp[word[j]];
            } else {
              temp[word[j]] = clpl;
              lp += clpl;
              clpl = String.fromCharCode(clpl.charCodeAt(0) + 1);
            }
        }

        //if letter pattern of word exists in sorted dictionary
        if(lp in sortedDictionary){
            //add word to the array of words with same letter pattern
            sortedDictionary[lp].push(word);
        } else {
            //if letter pattern is new, create new array to store words
            sortedDictionary[lp] = [];
            //add word to the array of words with same letter pattern
            sortedDictionary[lp].push(word);
        }
    }

    //write the sortedDictionary object to the sortedDictionary.json file
    jsonfile.writeFile(sortedDictFile, sortedDictionary, {spaces: 2}, function(error){
        if(error) throw error;
    });

    //time to sort and write to json file - Dictionary Sort: 687ms (137602 lines)
    console.timeEnd("Dictionary Sort");
});


texts:
I am quite new to F# and just wrote my first program. It checks if the query exists in the brand list and returns the matching brand.

Query is the string you are searching for in the brand list. So someone could be looking for "Miso Power Washer X1000" the idea is that my function analyses the query to see if there is a matching brand. Later the remainder ("Power Washer X1000") could be parsed as well. In this way I am able to "parse" the query of the user and give it context. This meta data will be used to give better search results when the database is queried.

I used stringInArray in order to split the logic into a separate function. Of course I could do something like Array.filter(fun (elem: string) -> query.IndexOf(elem) > -1)) brands But I felt it was less readable.

Sometimes when learning a new language you get things to work. However someone more experienced say: you can use this or that which is more common, faster etc. I am looking for this kind of feedback before creating a bunch of code which turns out to be rubbish through the eyes of an experienced F# programmer.

Is this the correct way to use F# function structure?

Code

module Program =

    [<EntryPoint>]
    let main argv =
        let query = "Miso Power Washer X1000"

        let brands = [|
            "Hayo"
            "Miso"
            "The Master"
            "Vector"
        |]

        let stringInArray = fun (elem: string) ->
            query.IndexOf(elem) > -1

        let getBrands (query: string): string[] =
            Array.filter(stringInArray) brands

        let result = getBrands query
        printfn "%A" result

        0

Output

[|"Miso"|]