texts:
After receiving some feetback about my previous attempt to create reusable, easily extendable sequence generators I try once again to create such a framework.

This time there is no inheritance. Just extension methods.

The new core is the Sequence class:

public class Sequence
{
    public Sequence(int count) { Count = count; }

    public int Count { get; }

    public static Sequence Generate(int count)
    {
        return new Sequence(count);
    }

    public IEnumerable<T> Generate<T>(Func<IEnumerable<T>> generator) => generator().Take(Count);
}

By itself it doesn't do much. You need to extend it with your extensions that hook up to it and provide it with the actual generator for your sequence.

Here are some examples for the Fibonacci sequence:

static class FibonacciSequenceExtensions
{
    public static IEnumerable<T> Fibonacci<T>(this Sequence sequence, T firstTwo, T firstStep, Func<T, T, T> sum)
    {
        return sequence.Generate(() => FibonacciGenerator(firstTwo, firstStep, sum));
    }

    public static IEnumerable<int> Fibonacci(this Sequence sequence, int firstTwo, int firstStep)
    {
        return sequence.Generate(() => FibonacciGenerator(firstTwo, firstStep, (x, y) => x + y));
    }

    public static IEnumerable<TimeSpan> Fibonacci(this Sequence sequence, TimeSpan firstTwo, TimeSpan firstStep)
    {
        return sequence.Generate(() => FibonacciGenerator(firstTwo, firstStep, (x, y) => x + y));
    }

    private static IEnumerable<T> FibonacciGenerator<T>(T firstTwo, T firstStep, Func<T, T, T> sum)
    {
        var preview = firstTwo;
        var current = sum(firstTwo, firstStep);

        yield return preview;
        yield return preview;
        yield return current;

        while (true)
        {
            var newCurrent = sum(preview, current);
            yield return newCurrent;
            preview = current;
            current = newCurrent;
        }
    }
}

Then you can use it like this:

var result = Sequence.Generate(10).Fibonacci(3, 4).ToList();

What's the purpose of this? To have only a single class for all sequences. You don't have to remember where you've implemented some sequence. You can use them all via a single class.

In case someone is interested how the final version looks like I put it here under the previous quesiton because it's the inheritance edition that I decided to keep.


texts:
I took the Python class at Google code today, and this is what I made for the problem about building a word counter.

Please take a look and suggest any improvements that can be done.  Please do point out the bad practices if I have used any.

import sys

def make_dict(filename):
    """returns a word/count dictionary for the given input file"""
    myFile=open(filename,'rU')
    text=myFile.read()
    words=text.lower().split()
    wordcount_dict={}   #map each word to its count
    for word in words:
        wordcount_dict[word]=0
    for word in words:
        wordcount_dict[word]=wordcount_dict[word]+1
    myFile.close()
    return  wordcount_dict

def print_words(filename):
    """prints each word in the file followed by its count"""
    wordcount_dict=make_dict(filename)
    for word in wordcount_dict.keys():
        print word, "  " , wordcount_dict[word]

def print_top(filename):
    """prints the words with the top 20 counts"""
    wordcount_dict=make_dict(filename)
    keys = wordcount_dict.keys()
    values = sorted(wordcount_dict.values())
    for x in xrange (1,21): #for the top 20 values
        for word in keys :
            if wordcount_dict[word]==values[-x]:
                print word, "       ",wordcount_dict[word]

def main():
  if len(sys.argv) != 3:
    print 'usage: ./wordcount.py {--count | --topcount} file'
    sys.exit(1)

  option = sys.argv[1]
  filename = sys.argv[2]
  if option == '--count':
    print_words(filename)
  elif option == '--topcount':
    print_top(filename)
  else:
    print 'unknown option: ' + option
    sys.exit(1)

if __name__ == '__main__':
  main()


texts: Print out number x followed by everything in the range of 1 to (x - 1)

texts:
The original idea is to print the following numbers:

7, 1, 2, 3, 4, 5, 6

So some number x followed by everything in the range 1  to (x - 1). The key is to skip 0.

I have two versions of this. The first is a pretty straightforward for loop with modular arithmetic, skipping 0:

for (int i = 7; i <= 14; i++)
{
    int result = i % 8;

    if (result == 0)
        continue;
    else
        Console.WriteLine(result);
}

The second (and, as a disclaimer, I will almost certainly not be using this in actual production code, I wrote it more for my own learning), is based on closures:

static void Main(string[] args)
    {
        Func<int> counterFunction = RollAround(1, 8);

        for (int i = 0; i < 7; i++)
            Console.WriteLine(counterFunction());

        Console.ReadLine();
    }

    private static Func<int> RollAround(int min, int max)
    {
        int counter = max - 1;

        return () =>
        {
            int result = counter % max;

            while (result < min)
            {
                counter++;
                result = counter % max;
            }

            counter++;

            return result;
        };
    }

I'm curious if people had feedback on how these can be improved. The first one is probably "more important" in that it's intended for production code, but I'm curious about the second one as well just for my own learning (especially since I'm admittedly a bit rusty on closures).


texts: Logic/Code duplication, improve readability?

texts:
I have a function that takes a point, and given its velocity, and acceleration, calculates the time(s) for the point to collide with the line:

def ParabolaLineCollision(pos, vel, acc, line):
    """A pure function that returns all intersections."""
    pass

I have another function that wants to calculate the smallest intersection time between two entities, where an entity has a velocity/acceleration, and a list of vertices.

The algorithm of entity_intersection creates lines for each objects' list of vertices, and then calls ParabolaLineCollision on each point of each object, with each line of the other object.  My current algorithm runs slowly, and thus I would like to be able to parallelize the algorithm.

My problem is that entity_intersections is a bit hard to read, and I think that there may be some code duplication, which might possibly be eliminated.  Here's the algorithm, and

class Entity
    # ...

    @property
    def lines(self):
        """
        Get a list of lines that connect self.points.

        If self.enclosed, then the last point will connect the first point.
        """
        # type(self.enclosed) == bool

        # # I included this, as this may be where there is logic duplication with entity_intersections.
        # # It's also not very readable.

        return [(self.points[i-1], self.points[i]) for i in range((1-int(self.enclosed)), len(self.points))]

    # ...

def entity_intersections(entity, other):
    """
    Find all intersection times between two entities.

    type(entity) == type(other) == Entity
    """
    # Find relative velocity/acceleration
    a12 = entity.acceleration - other.acceleration
    a21 = other.acceleration - entity.acceleration
    v12 = entity.velocity - other.velocity
    v21 = other.velocity - entity.velocity

    entity_points, other_points = entity.points, other.points
    entity_lines, other_lines = entity.lines, other.lines

    results = []

    # Get all intersections between each object's point and the other object's line
    for point in entity_points:
        for line in other_lines:
            results.append((point, v12, a12, line))
    for point in other_points:
        for line in entity_lines:
            results.append((point, v21, a21, line))

    # Return results of ParabolaLineCollision with each list of arguments in results
    # Pseudo-code to achieve this (I haven't done the parallizing yet):
    # return min(map(ParabolaLineCollision, results))


texts: How Can I Improve/Secure My Login Script?

texts:
This is a simple login script. Thought I'm not sure when it's appropriate to use includes over just embedding the code. I'm also not sure if I should make cookies, but I guess I don't really need to right now. Also looking at my code would it be easy to create a 'Remember Me' function?

<?php
$validUser;
$validPass;
$win;
if($_POST)
{
include('admin/functions.php');
// Database Connection
AllYourBase();

if(CheckEmpty($_POST['username']))
{
    $username = $_POST['username'];
    $validUser = true;
}
else
    $validUser = false;

if(CheckEmpty($_POST['password']))
{
    $password = $_POST['password'];
    $validPass = true;
}
else
    $validPass = false;

$query = mysql_query(sprintf("SELECT * FROM Users WHERE username = '%s'",
                mysql_real_escape_string($username))) or die(exit());
$result = mysql_fetch_assoc($query);

// Split the Salt
$fs = substr($result['salt'], 0, 10);
$ls = substr($result['salt'], -10);

// Add The Salt
$pass = md5($fs.$password.$ls);
$name = $result['fname']. ' ' . $result['lname'];

// Authenticate
if($result['password'] == $pass)
{
    session_start();
    $_SESSION['name'] = $name;
    $_SESSION['auth'] = true;
    $win = true;
    // Javascript Redirect not Header()
    Redirect('index.php');
}
else
    $win = false;
}
?>

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
    <?php if($_POST && $win == false): ?>

Login Unsuccessful

    <?php endif ?>
        <input type="text" size="10" name="username" />

    <?php if($_POST && $validUser == false): ?>

Empty Username

    <?php endif ?>
        <input type="password" size="10" name="password" />

    <?php if($_POST && $validPass == false): ?>

Empty Password

    <?php endif ?>
    <input type="submit" text="Submit" />
</form>
Registration Page


texts: Beautifulsoup scrape posts that has the word python in it with no python tag

texts:
This is my first time web scraping, and here is the code I whipped up:
from bs4 import BeautifulSoup
import requests
import time

keywords = ['python']

for n in range(1000):
    res = requests.get(f"https://stackoverflow.com/questions?tab=newest&page={n}")
    time.sleep(3) # Sleep to avoid getting rate limited again
    soup = BeautifulSoup(res.text, "html.parser")
    questions = soup.select(".question-summary") # List of all question summaries in the current page
    for que in questions:
        found = False
        tagged = False
        q = que.select_one('.question-hyperlink').getText() # Store the title of the question
        for a in que.find_all('a', href=True):
            u = a['href'] # Store the link
            if u.split('/')[1] == 'questions' and u.split('/')[2] != 'tagged': # If this link is a question and not a tag
                res2 = requests.get("https://stackoverflow.com" + u) # Send request for that question
                time.sleep(3) # Extra precaution to avoid getting rate limited again
                soup2 = BeautifulSoup(res2.text, "html.parser")
                body = str(soup2.select(".s-prose")) # This is the body of the question
                if any(key in body for key in keywords):
                    found = True
            if 'tagged/python' in u:
                tagged = True

        if found and not tagged:
            print(q)

My code basically scrapes Stack Overflow posts newest first, and prints out all the posts that has the keyword "python" in its body, but no python tag. I want to know, did I implement the algorithm optimally? Can you show me where to improve?


texts: Words Counter using the revealing module pattern

texts:
Is the following a good way to use the revealing module pattern?

$(document).ready(function() {

  var wordsCounter = (function() {

    function init() {
      bindEvents();
    }

    // cache dom
    var $textArea = $('#textArea');
    var $words = $('#words'); //a span
    var $chars = $('#chars'); //a span

    function bindEvents() {
      $textArea.on('keyup', updateWordsCount);
    }

    // $textArea keyup callback function
    function updateWordsCount() {
      var text =  $textArea.val();
      var numOfChars = text.length;
      var numOfWords = countWords(text);
      $chars.html(numOfChars);
      $words.html(numOfWords);
    }

    // counts words for a given string
    function countWords(str){
      var cnt = 0;
      var flag = true;
      for(var i = 0; i < str.length; i++){
        if(str[i] !== " " && flag){
          flag = false;
          cnt++;
        }else if(str[i] === " "){
          flag = true;
        }
      }
      return cnt;
    };

    return {
      init: init
    }

  }());

  wordsCounter.init();

});

What are other good ways I can structure this code?

Also if i'm working on a larger project, should it all be in a one IIFE like this or should I divide it into more than one IIFE each one doing related things?


texts: Writing slice compare in a more compact way

texts:
I have this code snippet comparing two slice references:

  fn compare(&self, a: &[u8], b: &[u8]) -> i64 {
    let mut p1 = a.as_ptr() as *mut u8;
    let mut p2 = b.as_ptr() as *mut u8;

    let mut min_len = cmp::min(a.len(), b.len());

    let mut ret = 0;
    while min_len > 0 {
      unsafe {
        if *p1 != *p2 {
          ret = *p1 as i64 - *p2 as i64;
          break;
        } else {
          p1 = p1.offset(1);
          p2 = p2.offset(1);
        }
      }
      min_len = min_len - 1;
    }

    if ret == 0 {
      if a.len() < b.len() {ret = -1;}
      else if a.len() > b.len() {ret = 1;}
    }

    return ret;
  }

I think I wrote it down in C style. I would like to write this in Rust style.

I could replace 'ret' with std::cmp::Ordering. What else could I do?


texts:
I'm trying to pick up some Haskell skills so thought I'd write a random password generator to get to grips with using IO. It was far trickier than I expected and I employed rather more trial and error than I'd have liked.

What I've ended up with works, and while I'm happy with it generally I'd like to know if this is reasonable, idiomatic Haskell or if I've done anything peculiar.

import System.Random

-- Generate a random number in closed interval [lo, hi]
random_int :: Int -> Int -> IO Int
random_int lo hi = (randomRIO (lo,hi) :: IO Int)

-- Generate a random character from an internal alphabet
random_char :: IO Char
random_char = do
    index <- random_int 0 $ (length alphabet) - 1
    return $ alphabet !! index
    where alphabet = ['A'..'Z'] ++
                     ['a'..'z'] ++
                     ['0'..'9'] ++
                     "!\"£$%^&*()-_+={}[]:;@'~#|\\<,>.?/'"

-- Generate a random password of given length
random_password :: Int -> IO String
random_password length =
    sequence $ map (\x -> random_char) [1..length]

main :: IO ()
main = random_password 8 >>= putStrLn

The implementation of random_password feels odd and hacky, but I struggled to find another way to create an array of results from successive invocations of random_char or any way to avoid the need for sequence. Is it hacky?


texts:
This question has been asked for other languages, but I haven't seen it for C++.  Most notably here and here.

  Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.

My tests are running correctly, but I'm getting a timeout from the website codesignalDotCom.  I'm wondering what I'm doing that could be taking so much time, and what could be done to fix it.

int firstDuplicate(std::vector<int> a) {
    std::vector<int> newVector;
    std::cout << a.size() << std::endl;
    for(int i = 0; i < a.size(); i++) {
        if(std::find(newVector.begin(), newVector.end(), a.at(i)) != newVector.end()){
            return a.at(i);
        }
        newVector.push_back(a.at(i));
    }
    return -1;
}


texts: Checking if a value is within a time range

texts:
How can I improve the style to avoid so many float64()s?

func IsInTimeRange(tvalue int32,timeout int){
    t := time.Now().Unix()
    return int(math.Abs(float64(t)-float64(tvalue))) < timeout
}


texts:
i'm wondering is there any way to optimize this code?
It must be able to work with big files, for example, formatting raw 140kb .txt file (12.5k words) takes 2 seconds (measured with Stopwatch class).
Text example http://pastebin.com/2p88v8EN
Maybe i used here some bad techniques or there is some part to simplify? Maybe multithreading? I'm not familiar with this yet.
Would be grateful for help!

Code below:

class TextManipulations
{
    public string[] wordsDist;                                                  // main array, contains words in alphabetic order and output lines

    public void TextFormat(string sourcePath)                                   // creating method that will format our source text according to task
    {
        string textInput = System.IO.File.ReadAllText(sourcePath).ToLower();    // reading text from file, lowercased at start for precise search
        MatchCollection m = Regex.Matches(textInput, @"\b[\w']+\b");            // exact search of all alphanumeric "words" including words with apostrophe
        List<string> words = new List<string>();                                // creating List<T> for containing unknown amount of words

        foreach (Match match in m)                                              // assigning all matches to List<string>
        {
            words.Add(match.ToString());
        }
        words.Sort();                                                           // sorting words in alphabetic order
        wordsDist = words.Distinct().ToArray();                                 // assigning words to main array without duplicates
        System.IO.File.WriteAllLines(@"D:\output.txt", wordsDist);      // writing words into txt file to edit in setLineNumbers method
    }

    public void setLineNumbers(string sourcePath)                               // creating method for adding line numbers
    {
        string[] linesOutput = new string[wordsDist.Count()];                   // creating array that will contain line numbers
        string[] lines = System.IO.File.ReadAllLines(sourcePath);               // assigning source text by lines

        for (int j = 0; j < wordsDist.Count(); j++)                             // main cycle checking each word for presence in each line
        {
            for (int i = 0; i < lines.Count(); i++)
            {
                if (Regex.IsMatch(lines[i].ToLower(), "\\b" + wordsDist[j] + "\\b"))   // using ToLower() here, because we can't use it in line 33
                {
                    linesOutput[j] += (i + 1).ToString() + ", ";                // adding line numbers according to word
                }

            }
        }

        for (int i = 0; i < wordsDist.Count(); i++)                             // connection of two relative arrays
        {
            wordsDist[i] += "_______________________________" + linesOutput[i];
            wordsDist[i] = wordsDist[i].Remove(wordsDist[i].Length - 2);        // removing last ',' char
        }

        System.IO.File.WriteAllLines(@"D:\output.txt", wordsDist);      // writing final output result into txt file

    }

}


texts: Class simulating a connection among two pins

texts:
Following this post and the one before that, here I am asking for a review on another piece of code: the connection among two pins. As usual, be merciless in your review. Here it goes:

public class PinConnection : IObserver<Pin>
{
    #region variables
    private Pin _from;
    private Pin _to;
    private IDisposable _fromUnsubscriber;
    private IDisposable _toUnsubscriber;
    #endregion

    #region properties
    /// <summary>
    /// Get or Set the label of this PinConnection object.
    /// </summary>
    public string Label { get; set; }

    public Pin From
    {
        get
        {
            return _from;
        }
        set
        {
            _from = value;

            if (_fromUnsubscriber != null)
            {
                _fromUnsubscriber.Dispose();
            }

            if (_from != null)
            {
                _fromUnsubscriber = _from.Subscribe(this);
                _from.Notify(_from);
            }
        }
    }

    public Pin To
    {
        get
        {
            return _to;
        }
        set
        {
            _to = value;

            if (_toUnsubscriber != null)
            {
                _toUnsubscriber.Dispose();
            }

            if (_to != null)
            {
                _toUnsubscriber = _to.Subscribe(this);
                _to.Notify(_to);
            }
        }
    }
    #endregion

    #region constructors
    public PinConnection()
    {
        Code = string.Empty;
        Label = string.Empty;
    }

    public PinConnection(Pin from)
        : this()
    {
        From = from;
    }

    public PinConnection(Pin from, Pin to)
        : this(from)
    {
        To = to;
    }
    #endregion

    public void OnCompleted()
    {
        throw new NotImplementedException();
    }

    public void OnError(Exception error)
    {
        throw error;
    }

    public void OnNext(Pin value)
    {
        if (value.Equals(From) && To != null)
        {
            To.Value = value.Value;
        }
    }
}


texts: Martix of Counts of Regex Hits Over a List of Strings

texts:
I have:

A dataframe with Identifiers (TermId) and Search Terms (SearchTerm).
A list of text strings (MyText).  This likely would be a column (series) in a dataframe.

I for every string in MyText I want to get a count of hits for every regex SearchTerm, producing a table of counts.  This is a scaled down example.  I'd have 10,000 of Mytext and 100s of SearchTerms.  I am newer to Python (from R) and would like to know where can I optimize the code to make it more performant?  I'm open to what ever feedback people have to offer on all aspects of the code.
## Dependencies
import re
import pandas as pd

## Data
MyText = ['I saw xx.yy and also xx.yyy', 'FireFly* this is xx_yy there', 'I xx$YY', 'I see x.yy now .NET', 'now xx.yyxx.yyxx.yy']

MyDictionary = pd.DataFrame({
    'TermId': ['SK_{}'.format(x) for x in list(range(0, 6))],
    'SearchTerm': ['xx[.]yy', '[.]NET', 'A[+]', 'FireFly[*]', 'NetFlix[$]',  'Adobe[*]']
})

## Convert Search Term to Compiled Regex Object
MyDictionary['Regexes'] = [re.compile(s) for s in MyDictionary['SearchTerm']]

## List comprehension to double loop over the regexes &
## elements of MyText to count hits
out = {id: [len(regex.findall(s)) for s in MyText] for regex, id in zip(MyDictionary['Regexes'], MyDictionary['TermId'])}
out = pd.DataFrame(out)
out['MyText'] = MyText

## Results
print(out)
print(MyDictionary)

Which yields:
   SK_0  SK_1  SK_2  SK_3  SK_4  SK_5                        MyText
0     2     0     0     0     0     0   I saw xx.yy and also xx.yyy
1     0     0     0     1     0     0  FireFly* this is xx_yy there
2     0     0     0     0     0     0                       I xx$YY
3     0     1     0     0     0     0           I see x.yy now .NET
4     3     0     0     0     0     0           now xx.yyxx.yyxx.yy


texts: Entering address details into Google Maps geocoder

texts:
I have a Google Maps Geocoder and I am looking to refactor it. The user enters address details into a form where at the bottom there is the option to show on map.

First the map is hidden
The user clicks show_map checkbox
Map-area is shown
Map is initialized

The codeAddress() function is used if the user edits the address and wants to find it again. The showCoords() function passes the longitude and latitude through to the form for processing. I am looking for a best practice to refactor this code.

function initialize() {

    geocoder = new google.maps.Geocoder();

    codeAddress();

    map = new google.maps.Map(document.getElementById('map-canvas'));

    marker = new google.maps.Marker({
        map: map,
        position: map.getCenter(),
        draggable: true
    });

    google.maps.event.addListener(marker, 'dragend', function() {
        point = marker.getPosition();
        map.panTo(point);
        showCoords(point);
    });

    google.maps.event.addListener(map, 'dragend', function() {
        point = marker.getPosition();
        marker.setPosition(map.getCenter());
        showCoords(point);
    });

} /* END initialize */

function codeAddress(){
    var address = document.getElementById('address').value;
    geocoder.geocode({'address': address}, function(results, status){
        if(status == google.maps.GeocoderStatus.OK){
            map.setCenter(results[0].geometry.location);
            map.setZoom(15);
            marker.setPosition(map.getCenter());
            showCoords();
        }else{
            alert('Geocode was not successful for the following reason: ' + status)
        }
    });
}

function showCoords(point){
    point = marker.getPosition();
    document.getElementById("lat").value = point.lat().toFixed(5);
    document.getElementById("lng").value = point.lng().toFixed(5);
}


texts: Making a preselected drop-down selection box in HTML

texts:
I'm a PHP newbie and I have a question. Is there a better way to do this? A nice solution?

$list = isset($_GET['list']) ? htmlspecialchars($_GET['list']) : "experience";

<select name="type" id="type">
<option value="experience">Experience</option>
<option value="magic"<?=$list == "magic" ? 'selected' : '';?>>Magic Points</option>
<option value="shielding"<?=$list == "shielding" ? 'selected' : '';?>>Shielding</option>
<option value="distance"<?=$list == "distance" ? 'selected' : '';?>>Distance</option>
<option value="melee"<?=$list == "sword" ? 'selected' : '';?>>Melee</option>
<option value="fishing"<?=$list == "fishing" ? 'selected' : '';?>>Fishing</option>
</select>


texts: Calculating chromosome coverage of a set of regions

texts:
Some background: I work mostly in Python (specifically numpy), doing Bioinformatics type work. I am interested in moving towards Haskell. Initially, I hope it will be possible to replace some of the simple exploratory scripting I've been doing with Haskell. The following is not something that would actually be particularly useful, but I thought it might be a good starting point for my first program in Haskell!

The following code takes two files:

Describes regions of a chromosome that have been
categorized as similar. Line 1 shows the start basepair of the
region, line 2 the end basepair, and so on. A shortened example: http://pastebin.com/RMd13Kv3
Shows an interaction matrix between "bins" of the chromosome. A row has chrmName startBp endBp, followed by the row of the interaction matrix. This is not necessarily in order. Example: http://pastebin.com/Q5CaVHAu

The code is attempting to work out the fraction of the whole chromosome spanned by the regions.

import System.IO
import System.Environment(getArgs)
import Data.Either
import Data.List

joinLinePairs :: [a] -> ([a], [a])
joinLinePairs x = partitionEithers $ zipWith ($) (cycle [Left, Right]) x

zipLinesPairs :: ([a], [a]) -> [(a, a)]
zipLinesPairs (a, b) = zip a b

pairDifference :: (String, String) -> Int
pairDifference (a, b) = (read b) - (read a)

domainArea :: [String] -> Int
domainArea inpLines = sum (map pairDifference $ zipLinesPairs $ joinLinePairs inpLines)

processRawMat :: [String] -> [[Int]]
processRawMat x = map (processMatRow . words) x

processMatRow :: [String] -> [Int]
processMatRow (x:y:z:_) = [read y, read z]

maxMinBin :: [[Int]] -> (Int, Int)
maxMinBin lst = (minimum vals, maximum vals)
            where vals = concat lst

coverageFrac :: (Integral a, Fractional b) => (a, a) -> a -> b
coverageFrac (mn, mx) domArea = (fromIntegral domArea) / ((fromIntegral  mx) - (fromIntegral  mn))

main :: IO ()
main = do

args <- getArgs
    rawDomains <- readFile (args !! 0)
    let coveredArea = domainArea $ lines rawDomains
    print $ coveredArea
    rawMatrix <- readFile (args !! 1)
    let rawMatLines = lines rawMatrix
    let listolists = processRawMat rawMatLines
    print $ coverageFrac (maxMinBin listolists) coveredArea

One thing I noticed is that this code is very slow when running on real data (in reality the second file can run to tens of thousands of lines, and hundreds of mb). As most of the things I would be doing involve dealing with very large text files (these would be considered small, by comparison), this worries me a bit!

I would appreciate any feedback anyone could offer me. Thanks!


texts: Sort Facebook Messenger contacts by idle time

texts:
I wrote a UserScript that auto-sorts contacts by offline time using the MutationObserver API. I tried to make it as DRY as I could think, and I also tried to make my code as straight-forward as possible, commenting thoroughly. Please let me know any improvements I can make.

// ==UserScript==
// @name         Facebook Messenger Chat Sorter
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Auto-sort contacts by offline time
// @author       Patrick Roberts
// @match        https://www.facebook.com/*
// @grant        none
// ==/UserScript==

(function() {
  'use strict';

  // mutation observer to locate chat sidebar
  var exists = new MutationObserver(function(mutations) {
    // if chat sidebar found in any mutations
    if (mutations.some(function(mutation) {
      // check if element with class is added
      if (mutation.type === 'childList') {
        // return if any added element is the chat sidebar
        return Array.from(mutation.addedNodes).some(initFbChatSidebar);
      // check if class is changed in existing element
      } else {
        // return if changed element is the chat sidebar
        return initFbChatSidebar(mutation.target);
      }
    })) {
      // then de-initialize this observer
      exists.disconnect();
      exists.takeRecords();
    }
  });

  // start locating sidebar
  exists.observe(document.body, { attributes: true, childList: true, subtree: true, attributeFilter: ['class'] });

  // returns if any element is the chat sidebar, and inits it
  function initFbChatSidebar(el) {
    if (el instanceof HTMLElement && el.classList.contains('fbChatSidebar')) {
      initChatSort(el.querySelector('ul'));

      return true;
    }

    return false;
  }

  // initializes auto-sorting
  function initChatSort(ul) {
    var li = ul.children;

    // observer to sort contacts
    var observer = new MutationObserver(sort);

    // start sorting whenever list is mutated
    observer.observe(ul, { childList: true, characterData: true, subtree: true });

    // also sort on initialization since list is already there
    sort();

    function sort() {
      // invoke native sorting algorithm
      Array.from(li).sort(function(la, lb) {
        // get offline times
        var a = getOfflineTime(la);
        var b = getOfflineTime(lb);

        // compare offline times
        return a - b;
      }).forEach(function(li) {
        // add list items to list in sorted order
        ul.appendChild(li);
      });

      // remove mutations from queue caused by sorting
      observer.takeRecords();
    }
  }

  // parse offline time from contact list item
  function getOfflineTime(li) {
    var str = li.querySelector('[class$="on"] [class$="-"]').textContent;
    var num, unit;

    num = +str.slice(0, -1);
    unit = str.slice(-1);

    // multiply time by 60 if hour
    if (unit === 'h') {
      num *= 60;
    // multiply time by 60 * 24 if day
    } else if (unit === 'd') {
      num *= 60 * 24;
    }

    return num;
  }
})();


texts:
I'd like to get some feedback on this very basic JavaScript to update which tab is showing as "active" on my simple web page. This is all in a file titled adjustactive.js and included in my footer template for all pages like so:

<script src="assets/js/adjustactive.js"></script>

Here's the full content of that .js file:

//function courtesy of comments in http://befused.com/javascript/get-filename-url
function getFileName() {
    var url = document.location.href;
    url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
    url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
    url = url.substring(url.lastIndexOf("/") + 1, url.length);
    if(url.length == 0) url = "index";
    return url;
}

function updateNav() {
    var idName = getFileName();
    document.getElementById(idName).className = "active";
}

window.onload = updateNav();


texts: Testing whether lambda expression returns true for any list element

texts:
I have the following function defined in my .emacs to test if a given executable exists within my $PATH. I implemented it with cl-reduce and the code looks really unidiomatic (to me).

(defun executable-in-path-p (executable)
  "Test if EXECUTABLE exists in path."
  (eq t (cl-reduce
         (lambda (path exists)
           (or (file-exists-p (concat (file-name-as-directory path) executable))
               exists))
         exec-path)))

Is there a more concise way to test if a list, mapped with a predicate function, has at least one element equal to t than this?

(eq t
    (cl-reduce
     (lambda (element acc)
       (or (some-check-p element)
           acc))
     some-list))

In Ruby for example I would write:

some_list.any? { |element| some_check(element) }


texts:
While I should probably be using Dependency Injection via Ninject or a similar project, I have been attempting to implement an abstract factory design that would provide me with the following easy to read and use syntax:

UniversalFactory.Factory<IFoo>.Create<FooImpl>(... parameters ...);

I'm throwing this experiment on here in order to solicit some constructive feedback both with implementation logic and design reasoning.

Here is my current implementation:

public class UniversalFactory
{
    private readonly IFactory<IFoo> FooFactoryEx;

    public UniversalFactory()
    {
        FooFactoryEx = new FooFactory();
    }

    public IFactory<T> Factory<T>()
    {
        if (typeof (T) == typeof (IFoo))
            return (IFactory<T>)FooFactoryEx;
        return null;
    }
}

public interface IFactory<in TF>
{
    T Create<T>(params object[] p) where T : TF;
}

public class FooFactory : IFactory<IFoo>
{
    public T Create<T>(params object[] p) where T : IFoo
    {
        if (typeof(T) == typeof(FooImpl))
        {
            var id = Convert.ToInt32(p[0]);
            return (T)FooImpl.Create(id);
        }
        return default(T);
    }
}

public interface IFoo
{
    // Some interface
}

public class FooImpl : IFoo
{
    public int Id { get; set; }

    private FooImpl(int id)
    {
        Id = id;
    }

    public static IFoo Create(int id)
    {
        var foo =  new FooImpl(id);
        return foo;
    }
}

This code allows a UniversalFactory to be instantiated and the following to be invoked successfully:

UniversalFactory.Factory<IFoo>().Create<FooImpl>(1);

My reasoning for this approach:

All construction is easily identifiable via the call to UniversalFactory.
Factories are invoked based on the interface implementation being constructed, hiding all details about the specific factory being used from the new object request.
The object type and its construction parameters are clearly identifiable in the request.
Object construction stays in each class, and any additional updates to other objects at construction time can take place in the factory method.

My current implementation has (at a minimum) the following flaws:

There is no compile-time safety that ensures IFoo is implemented by an IFactory. Only that FooImpl implements IFoo is ensured.
UniversalFactory.Factory has to add a check for every interface supported by a factory
Individual factories have to invoke static Create() methods within each class. It would be better if the static create could be invoked in a generic way, and Create(params object[] p) somehow mapped to Create(int a, string b, ...) as needed.

Thoughts? Feedback? Is this approach unnecessary or too complex? Hopefully this experiment is, at the least, interesting to a couple of other SO folk out there.


texts: In a list of pairs, replace snds with median of all snds with the same fst

texts:
Given is a list of pairs. I want to replace the second element of all pairs with the median of the second elements of all pairs with the same first element.

For example:

[("a",1.0),("b",3.0),("a",2.0),("a",4.0)]
->
[("a",2.0),("b",3.0),("a",2.0),("a",2.0)]

The order of the elements in the resulting list is not important. So the following result would be equally valid:

[("a",2.0),("a",2.0),("a",2.0),("b",3.0)]

My current solution looks as follows:

import Control.Arrow
import qualified Data.Map as M

median :: Fractional a => [a] -> a
median xs | null xs  = error "empty list"
          | odd  len = xs !! mid
          | even len = meanMedian
                where  len = length xs
                       mid = len `div` 2
                       meanMedian = (xs !! mid + xs !! (mid+1)) / 2

solve :: [(String, Float)] -> [(String, Float)]
solve pairs = map replaceWithMedian pairs
    where
        medianMap = map (mapSnd (:[])) >>> M.fromListWith (++) >>> M.toList
                        >>> map (mapSnd median) >>> M.fromList
        mapSnd f (x, y) = (x, f y)
        replaceWithMedian (x, y) = (x, M.findWithDefault 0 x (medianMap pairs))

main :: IO ()
main = print $ solve [("a",1.0),("b",3.0),("a",2.0),("a",4.0)]

solve feels unnecessary long to me. I'm looking for more elegant/terse solution, not character-count-wise but with a simpler algorithm.


texts: Creating custom week start and week number

texts:
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.MutableDateTime;
import org.joda.time.ReadWritableDateTime;
import org.joda.time.Weeks;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class WorkDateUtils {

    private static Context mContext;
    public WorkDateUtils(Context context) {
        mContext = context;
    }

    /**
     *  Get the date of the first work date of the first week of the year.
     *  Set it to 01/01 and count forward.
     *  setting DayOfWeek(FIRST_DAY_OF_WEEK) can get us into last year, and I want
     *  that to be -1 with the first whole week of the current year as 0.
     */
    public static DateTime getFirstWorkDateOfYear(int year, int first_day) {
        ReadWritableDateTime readWritableDateTime = new MutableDateTime(year, 1, 1, 0, 0, 0, 0);
        while (readWritableDateTime.getDayOfWeek() != first_day) {
            readWritableDateTime.addDays(1);
        }
        return readWritableDateTime.toDateTime();
    }
    /**
     * Get the date of the beginning of the week containing the current day.
     *
     */
    public static DateTime getStartOfWorkWeek(DateTime dateTime, int first_day) {
        ReadWritableDateTime readWritableDateTime = dateTime.toMutableDateTime();
        readWritableDateTime.setMillisOfDay(0);
        while (readWritableDateTime.getDayOfWeek() != first_day) {
            readWritableDateTime.addDays(-1);
        }

        // Make sure we have the right week.
        while (readWritableDateTime.isAfter(dateTime)) {
            readWritableDateTime.addWeeks(-1);
        }

        return readWritableDateTime.toDateTime();
    }

    public static Week workWeekNumber(DateTime workDate) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        final Integer FIRST_DAY_OF_WEEK = preferences.getInt("workweek_start", DateTimeConstants.SUNDAY);

        Week workWeek = new Week();
        int week;

        DateTime firstWorkDate = getFirstWorkDateOfYear(workDate.getYear(), FIRST_DAY_OF_WEEK);

        DateTime firstOfWeek = getStartOfWorkWeek(workDate, FIRST_DAY_OF_WEEK);

        workWeek.setWeekStart(firstOfWeek.withTime(0, 0, 0, 0).toString());
        workWeek.setWeekEnd(firstOfWeek.plusDays(6).withTime(23, 59, 59, 999).toString());

        week = Weeks.weeksBetween(firstWorkDate, firstOfWeek).getWeeks();
        workWeek.setWeekNum(week);

        return workWeek;
    }
}

I've run this through tests for entire years and not seen any issues, but this will get called heavily, and hoping to optimize it as much as I can.

the Weeks class is just a holder to pass everything around.


texts: Variable duplicate as static and non-static

texts:
So I have implemented an application that acts as a chatbot for telegram in C#. I use a library that allows to set a filter of updates that the application whishes to receive. I assume the filter makes it more performant. This filter is passed in the StartReceiving method. My bot consists of multiple modules and each of these may require different types of updates. So I have in each module a field public IImmutableSet<UpdateType> UpdateTypeFilter. When calling the StartReceiving function at the start of the application I union the sets of all modules to see what kind of updates I need to receive and then pass that.

//need to convert back to mutable set
ISet updateTypes = Module1.UpdateTypeFilter.ToHashSet();
//NOTE: UpdateTypeFilter is static
updateTypes.Union(Module2.UpdateTypeFilter);
telegramClient.StartReceiving(updateTypes);

This requires a static field since at this point the modules have not yet been created as the bot is not part of a chat yet. The modules are created when the bot is added to a chat:

void OnAddedToChat(Chat chat) {
  IList<Module> modules = new List() {
    new Module1(),
    new Module2()
  };
  //chats is of type Dictionary<long, IList<Module>>
  chats.Add(chat.Id, modules);
}

Then when actually receiving updates I filter for each module according to which update type they wish to receive.

void OnMessageReceived(Message message) {
  IList<Module> modules = chats.GetValueOrDefault(message.Chat.Id);
  if(modules == null) {
    //The bot has just been added to the chat.
    OnAddedToChat(message.Chat);
    return;
  }
  foreach(Module module in modules) {
    //Note UpdateTypeFilter cannot be static
    if(module.UpdateTypeFilter.Contains(message.Type)
      module.ProcessMessage(message);
  }
}

As already commented in the code once the UpdateTypeFilter has to be static and once not. How can I solve this nicely? So far I just have two variables where one is called 'UpdateTypeFilterStatic' but that is not nice. I could move the filtering to the modules themselves. Then I can use the static variable both times but then it would be duplicate code in each module since I cannot generalize it into the interface. And duplicate code is not nice either.

Any ideas how to make it nicer are welcome :)


texts: Two index computations differing in execution time

texts:
Code

I have the following piece of code

        #define equidIND(divid, recip) (size_t)((divid) * (recip) + 0.5)
        ...
        // Get index for average velocity
        //idx_velo_avg    = (size_t)(velo_avg * funmaps_velo->map_velo_step_recip + 0.5);
        idx_velo_avg = equidIND(velo_avg, funmaps_velo->map_velo_step_recip);
        // Get effective velocity
        velo_eff = sqrt(velo_pos_k * velo_pos_k + accel * delta_s);
        // Get index for effective velocity (HOTSPOT)
        idx_velo_eff = equidIND(velo_eff, funmaps_velo->map_velo_step_recip);

Explanation

It contains three lines with operations

First line - idx_velo_avg = ...  Getting index by value using rounding/NNinterpolation:

Mapping value to index by division turned into a multiplication with the reciprocal:
velo_avg * funmaps_velo->map_velo_step_recip
Adding 0.5 to the resulting double
Truncating using a cast (size_t). The values are always > 0 btw.

The second line computes then the effective velocity, using a call to sqrt.
The third line does exactly the same as the first, but with a different base value (first line velo_avg - third line velo_eff)

Profiling

Very Sleepy and AMD CodeXL give similar profiling results

The snapshot is taken from AMD CodeXL.

Question(s)

What I wonder is:

Is this way of computing an index a good, fast and secure one?
Why does the third line apparently more than 4 times slower than the first. At least this is how I interpret the percentage values in CodeXL and Very Sleepy kind of confirms this interpretation. Has it to do with the intermediate call to sqrt?

ASM

As additional information, the assembly view shows the following (link to image)


texts:
The main view in my (toy!) Todo app is, of course, to display the list of tasks.  These are grouped by some criterion, and the tasks structure below is actually a list of pairs (header, list of tasks).

{% for tasks in tasks %}

{{ tasks.0 }}:

    {% for t in tasks.1 %}

            = 1 %}prio-medium{% endif %}
                {% if t.priority >= 2 %}prio-high{% endif %}
                ">
                {{ t.description }}

            {% if t.due_date %}
                due,
                <span class="
                    {% if t.days_to_due_date < 15 %}date-soon{% endif %}
                    {% if t.days_to_due_date < 3 %}date-very-soon{% endif %}
                    {% if t.days_to_due_date < 0 %}date-overdue{% endif %}
                    ">
                    {{ t.relative_due_date }}

            {% endif %}
            -
            {% if not t.done %}
                Done!
            {% else %}
                Not done!
            {% endif %}
            -
            Edit

    {% endfor %}

{% empty %}

Cool! Nothing to do...

{% endfor %}

In particular, I'm wondering if deciding which CSS class to assign is considered to be the view function's role, or if it's correct to put it in the template.

Similarly, I'm also wondering about the presence of several URLs in the template. Would they be better in the tasks structure itself?  Or should they be provided through some methods in the Task class? After all, relative_due_date is already a function that's only used for display (it returns a string like 'Yesterday', 'Tomorrow' or 'In 3 days'). And shouldn't I use reverse()?


texts: Searching faster for a file on the drive using Python

texts:
I am trying to write a code that should look on the laptop for a file, open it, if found, and read the context of that file (it should be .txt or .doc). So far, I wrote this code which is working:
def search(drive, target):
    file_path = ''
    if drive == "D":
        for root, dirs, files in os.walk(r"D:\\"):
            for name in files:
                if name == target:
                    file_path = os.path.abspath(os.path.join(root, name))
    elif drive == "C":
        for root, dirs, files in os.walk(r"C:\\"):
            for name in files:
                if name == target:
                    file_path = os.path.abspath(os.path.join(root, name))
    return file_path

def path():
    file_name = input("Enter the name of the desired file: ")
    path = os.path.abspath(file_name)
    file_path = search(path[0], file_name)
    return file_path

The problem is that this piece of code is very slow, as it has to look on each directory on the drive (the only trick I used to save some time was to take the abspath and to look on what drive it is saved, thus it doesn't look on each existing drive).
I am thinking of using multiprocessing, but I do not know how to use it. Can anybody help? Thank you very much for your time!


texts: MySQL query to find country and state of active users

texts:
Is there any reason NOT to wrap a long query over multiple line via new lines vs using concatenation?

For example, consider this:

$this->query("SELECT u.*, COALESCE(c2.name,u.state) AS real_state, c.name AS real_country, bc.alpha3 AS country_iso, bs.code AS state_iso
                    FROM " . MAIN_DB . ".users AS u
                    INNER JOIN " . MAIN_DB . ".countries AS c ON u.country=c.id
                    LEFT JOIN " . MAIN_DB . ".countries AS c2 ON u.state=c2.id
                    LEFT JOIN " . BLESTA_DB . ".countries AS bc ON c.country_iso_code=bc.alpha2
                    LEFT JOIN " . BLESTA_DB . ".states AS bs ON bc.alpha2=bs.country_alpha2 AND COALESCE(c2.name,u.state)=bs.name
                    WHERE u.active=1 AND u.mail_activated=1 AND u.blesta_id=0");

VS

$this->query("SELECT u.*, COALESCE(c2.name,u.state) AS real_state, c.name AS real_country, bc.alpha3 AS country_iso, bs.code AS state_iso " .
                    "FROM " . MAIN_DB . ".users AS u " .
                    "INNER JOIN " . MAIN_DB . ".countries AS c ON u.country=c.id " .
                    "LEFT JOIN " . MAIN_DB . ".countries AS c2 ON u.state=c2.id " .
                    "LEFT JOIN " . BLESTA_DB . ".countries AS bc ON c.country_iso_code=bc.alpha2 " .
                    "LEFT JOIN " . BLESTA_DB . ".states AS bs ON bc.alpha2=bs.country_alpha2 AND COALESCE(c2.name,u.state)=bs.name " .
                    "WHERE u.active=1 AND u.mail_activated=1 AND u.blesta_id=0");

Are there any possible problems with the first code or is either fine?


texts:
I've two similar functions and I want to use one generic function with two params, dialog and buttons.  How do I do it?

My functions:

LanguageLogosView.showConfirmRemoveDialog = function () {
    var def = $.Deferred();
    var buttons = {
        buttons: {
            "Remove": function () {
                def.resolve(true);
                $(this).dialog("close");
            },
            Cancel: function () {
                def.resolve(false);
                $(this).dialog("close");
            }
        }
    };
    $('#dialog-confirm-remove').dialog($.extend(LanguageLogosView.dialogConfirmDefaultSettings, buttons));
    return def;
}

LanguageLogosView.showConfirmEmptyRowsDialog = function () {
    var def = $.Deferred();
    var buttons = {
        buttons: {
            "Save": function () {
                def.resolve(true);
                $(this).dialog("close");
            },
            Cancel: function () {
                def.resolve(false);
                $(this).dialog("close");
            }
        }
    };
    $("#dialog-confirm-save-with-empty-rows").dialog($.extend(LanguageLogosView.dialogConfirmDefaultSettings, buttons));
    return def;
}


texts: Project Euler Problem 52: Permuted multiples

texts:
This is my solution to Project Euler
Problem 52 - Permuted Multiples. In the problem I'm searching for the smallest value of x such that x, 2x, 3x, 4x, 5x, and 6x use the same digits.

x = 125874
while True:
    x += 1
    if sorted(set(str(x))) == sorted(set(str(x * 2))) == \
        sorted(set(str(x * 3))) == sorted(set(str(x * 4))) == \
            sorted(set(str(x * 5))) == sorted(set(str(x * 6))):
        print x
        break

Is this bad Python? Is there a better way to write this instead of using a while True loop? I've tried adding the if condition to the while loop, but keep getting an infinite loop.


texts:
I have an extension that adds values to a class and I was wondering if there was a faster way to do this.

Does a for loop execute faster or would a LINQ query do better?

public static List<T> DataTableToList<T>(this DataTable dt) where T : class, new()
{
    List<T> dataTableList = new List<T>();
    var rowsCount = dt.Rows.Count;
    var columnCount = dt.Columns.Count;

    for (int i = 0; i < rowsCount; i++)
    {
        T obj = new T();
        int j = -1;
        Type type = obj.GetType();
        PropertyInfo[] properties = type.GetProperties();

        foreach (PropertyInfo property in properties)
        {
            if (j == -1)
            {
                property.SetValue(obj, Guid.NewGuid());
            }
            else if (j < columnCount)
            {
                if (dt.Rows[i][j] == null) continue;
                property.SetValue(obj, dt.Rows[i][j].ToString());
            }
            j++;
        }
        dataTableList.Add(obj);
    }
    return dataTableList;
}


texts: Reading many kinds of numbers from a byte buffer

texts:
I've been trying to find a way to collapse all these methods into one.

Current I have these methods

default byte readByte(long address) {
    return read(address, 1).get();
}

default int readShort(long address) {
    return read(address, 2).getShort();
}

default int readInt(long address) {
    return read(address, 4).getInt();
}

default long readLong(long address) {
    return read(address, 8).getLong();
}

default float readFloat(long address) {
    return read(address, 4).getFloat();
}

default double readDouble(long address) {
    return read(address, 8).getDouble();
}

They are used to read a certain amount of bytes of a memory address (ex 8 bytes for long, 4 for int, 2 for short, etc).

I find using the multiple methods is not very pleasing to look at.

In theory I'd like a solution similar to something like this:

default <T> T read(long address) {
  if (T instanceof Long) {

      return read(address, 8).getLong();
  } else if (T instanceof Integer) {

      return read(address, 4).getInt();
  } else if (T instanceof Short) {

      return read(address, 2).getShort();
  } else if (T instanceof Byte) {

      return read(address, 1).get();
  } else if (T instanceof Double) {

      return read(address, 8).getDouble();
  } else if (T instanceof Float) {

      return read(address, 4).getFloat();
  } else if (T instanceof Boolean) {

      return read(address, 1).get() == 1;
  }

  throw new RuntimeException("Unknown generic type!");
}

But I don't think that is possible due to the limitation of Java generics.

Can you think of a better/less redundant solution?


texts: Dynamic programming based range minimum query

texts:
I am implementing a DP-based range minimum query data structure and algorithm in Python 2.7. Any advice on algorithm time complexity improvements, code bugs or code style issues are appreciated.

More information about range minimum query.

from collections import defaultdict
import random
def build_rmq(numbers):
    rmq_map = defaultdict(int) # key: tuple of (start, end) index, value: min value
    j = 0
    while 2 ** j - 1 < len(numbers):
        j += 1
    j -= 1
    # print j
    for step in range(0,j+1):
        for i in range(0, len(numbers)):
            if step == 0:
                rmq_map[(i,step)] = numbers[i]
                continue
            if i + 2 ** (step-1) < len(numbers):
                rmq_map[(i,step)] = min(rmq_map[(i, step-1)], rmq_map[(i + 2 ** (step-1), step-1)])
            else:
                rmq_map[(i,step)] = rmq_map[(i, step-1)]

    return rmq_map

def rmq_query(start, end, rmq_map):
    j = 0
    while start + 2 ** j - 1 <= end:
        j += 1
    j -= 1
    x = rmq_map[(start, j)]
    y = rmq_map[(end + 1 - 2 ** j, j)]
    return min(x,y)

if __name__ == "__main__":
    numbers = [0,5,2,5,4,3,1,6,3]
    rmq_map = build_rmq(numbers)
    #print rmq_map
    start = random.randint(0, len(numbers)-1)
    end = random.randint(0, len(numbers)-1)
    if start > end:
        start, end = end, start
    print start, end, numbers[start:end+1]
    print rmq_query(start, end, rmq_map)


texts: MySQL query to select number of fields occurring more times than x

texts:
I want to find out the 'rank' of a word in any given language. A word with a rank of 1 means it's the most commonly used word in the language.
There are two MySQL tables.
document:

id: 1
language: "english"

word:

id: 2
body: "the"
document_id: 1

There are about 1 million rows in the word table. Here is a query that works, but it takes 7-10 seconds. Is there a better way to write this query?
select count(*) + 1
    from (
        select word.body, count(*) as count
        from word
        join document on word.document_id = document.id
        where document.language = 'english'
        group by word.body
    ) t
    where count > (select count
    from (
        select word.body, count(*) as count
        from word
        join document on word.document_id = document.id
        where document.language = 'english'
        group by word.body
    ) t
    where body = 'the')


texts:
I made simple Kruskal/Prim algorithm with a graph constructed by nested Python dictionary.

Kruskal

parent = {}
rank = {}

def find(v):
    if parent[v] != v:
        parent[v] = find(parent[v])

    return parent[v]

def union(v, u):
    root1 = find(v)
    root2 = find(u)

    if rank[root1] > rank[root2]:
        parent[root2] = root1
    else:
        parent[root1] = root2
        if rank[root1] == rank[root2]:
            rank[root2] += 1

def kruskal(graph):
    for v in graph.keys():
        parent[v] = v
        rank[v] = 0

    edges = []
    mst = []

    for outer_key in graph.keys():
        for inner_key, inner_weight in graph[outer_key].items():
            edges.append((inner_weight, outer_key, inner_key))

    edges.sort()

    for edge in edges:
        weight, v, u = edge

        if find(v) != find(u):
            union(v, u)
            mst.append(edge)

    return mst

if __name__ == '__main__':
    arg_graph = {
        'A': {'B': 10, 'D': 5},
        'B': {'A': 10, 'C': 2, 'D': 7, 'E': 12},
        'C': {'B': 2, 'E': 11, 'F': 14},
        'D': {'A': 5, 'B': 7, 'E': 6, 'G': 9},
        'E': {'B': 12, 'C': 11, 'D': 6, 'F': 15},
        'F': {'C': 14, 'E': 15, 'G': 3},
        'G': {'D': 9, 'F': 3}
    }

    print(kruskal(arg_graph))

Prim

import queue

def prim(graph):
    que = queue.PriorityQueue()
    mst = []
    visited = set()

    starting_vertex = list(graph.keys())[0]
    visited.add(starting_vertex)

    for next_to, weight in graph[starting_vertex].items():
        que.put((weight, starting_vertex, next_to))

    while que.empty() is False:
        edge = que.get()
        weight, frm, to = edge

        if to in visited:
            continue

        visited.add(to)
        mst.append(edge)

        for next_to, weight in graph[to].items():
            if next_to not in visited:
                que.put((weight, to, next_to))

    return mst

if __name__ == '__main__':
    arg_graph = {
        'A': {'B': 10, 'D': 5},
        'B': {'A': 10, 'C': 2, 'D': 7, 'E': 12},
        'C': {'B': 2, 'E': 11, 'F': 14},
        'D': {'A': 5, 'B': 7, 'E': 6, 'G': 9},
        'E': {'B': 12, 'C': 11, 'D': 6, 'F': 15},
        'F': {'C': 14, 'E': 15, 'G': 3},
        'G': {'D': 9, 'F': 3}
    }

    print(prim(arg_graph))

With this algorithm, minimun spanning tree is made like this:

"""
        10         2                                   2
  [A]--------[B]-------[C]            [A]        [B]-------[C]
   |    7   / |   11  / |              |    7   /
 5 | +-----+ 12  +---+  | 14         5 | +-----+
   |/         | /       |              |/
  [D]--------[E]-------[F]    ===>    [D]--------[E]       [F]
   |     6         15   |              |     6              |
   +----+           +---+              +----+           +---+
      9 |           | 3                   9 |           | 3
        +----[G]----+                       +----[G]----+

                                       (Minimum Spanning Tree)
"""

People says time complexity of Kruskal's Algorithm is \$O(ElogE)\$ and Prim's Algorithm is \$O(ElogV)\$. (E = number of edges, V = nubmer of vertices)

Then, does my code also have same complexity?

My Kruskal's Algorithm seems have \$O(V^2)\$ because of nested for-loop, and I can't figure out how complex my Prim's Algorithm is.


texts: 1-line conditional statement needs to be trimmed down

texts:
I have this conditional statement with use of regex:

do_stuff if (@string.match(/<(?:ingr?)>/i) &&
            @string.match(/<(?:prod:alchemy?)>/i)) ||
            @string.match(/<(?:key?)>/i)

It's a 1-line conditional statement, but due to it's length, it taking 3 lines instead. I'm wondering if there's a way to trim this down, so that I can fit it into 1 line. Preferably to be something like

do_stuff if (regex here)


texts: Calling a Function to Calculate Multiple Coefficients

texts:
I'm working through a practice problem and am wondering
if there's a more efficient way of writing my code  and/or if the syntax for my pointers looks correct.

The practice problem:

Given the absolute temperatures Tc of a cold reservoir and Th of a hot reservoir (in degrees Kelvin), the coefficients of performance (cp) of the refrigeration cycle and heat pump are given by:

Refrig: cp = Tc / (Th - Tc)
Heat: cp = Th / (Th - Tc)

Write a program that will call a function to prompt the user for the values of  Tc and Th .  It then calls a function that calculates the two coefficients of performance.  Finally, it calls a function to print the results.

Here is what I have:

#include <stdio.h>

void temperature(float *, float *);
void performance(float,float,float *, float *);
void PrintResults(float,float,float,float);

int main()
{
    float Tc, //cold reservoir; user input
        Th, //hot reservoir; user input
        Rcp, //refrigeration cycle coefficient of performance
        Hcp; // Heat pump coefficient of performance

    temperature(&Tc,&Th); //Prompts user for cold & hot reservoir temperatures
    performance(Tc,Th,&Rcp,&Hcp); //Calculates the coefficients of performance
    PrintResults(Tc,Th,Rcp,Hcp); //Prints the coefficients of performance
    return 0;
}
void temperature(float *ptrTc, float *ptrTh)
{
    printf("Enter the absolute temperature for a cold reservoir (in Kelvin): ");
    scanf("%f",&*ptrTc);
    printf("Enter the absolute temperature for a hot reservoir (in Kelvin): ");
    scanf("%f",&*ptrTh);
}
void performance(float Tc, float Th, float *ptrRcp, float *ptrHcp)
{
    *ptrRcp = Tc/(Th-Tc);
    *ptrHcp = Th/(Th-Tc);
}
void PrintResults(float Tc, float Th, float Rcp, float Hcp)
{
    printf("\nGiven the absolute temperatures of %.2f K for the cold reservoir",Tc);
    printf(" and %.2f K for the hot reservoir,",Th);
    printf(" the coefficient of performance for the refrigeration cycle is %.2f K",Rcp);
    printf(" and the coefficient of performance for the heat pump is %.2f K\n",Hcp);
}


texts:
I m making a script to store date information in the smallest size in bits

(I don't mind of the actually memory use in the program / runtime)

#!/usr/bin/env python
import random
import datetime

MAGIC = "DAT"

def extract(data, size):
    return (((data >> size) << size) ^ data)

def compress_date(year, month, day, hour, minute):
    assert year <= 31
    assert month <= 12
    assert day <= 31
    assert hour <= 24
    assert minute <= 60

    data = 0
    data = (data << 5) + year
    data = (data << 4) + month
    data = (data << 5) + day
    data = (data << 5) + hour
    data = (data << 6) + minute
    return (data)

def decompress_date(data):
    minute = extract(data, 6)
    data >>= 6

    hour = extract(data, 5)
    data >>= 5

    day = extract(data, 5)
    data >>= 5

    month = extract(data, 4)
    data >>= 4

    year = extract(data, 5)
    data >>= 5
    return (year, month, day, hour, minute)

date = serialgen.compress_date(10, 11, 30, 24, 60)
print date
print hex(date)
print decompress_date(date)

output:

11269692
0xabf63c
(10, 11, 30, 24, 60)

Can I do something to clear up the ugly parts:

data = 0
data = (data << 5) + year
data = (data << 4) + month
data = (data << 5) + day
data = (data << 5) + hour
data = (data << 6) + minute

minute = extract(data, 6)
data >>= 6

hour = extract(data, 5)
data >>= 5

day = extract(data, 5)
data >>= 5

month = extract(data, 4)
data >>= 4

year = extract(data, 5)
data >>= 5

Do you have any suggestions to improve this code?


texts: Are there side-effects to having a generic Ninject factory?

texts:
Consider this class:

using Ninject;
using Ninject.Syntax;
using Ninject.Parameters;

namespace MyApp.Dependencies.Factories
{
    public abstract class FactoryBase<T> where T : class
    {
        private IResolutionRoot _resolutionRoot;
        protected FactoryBase(IResolutionRoot resolutionRoot)
        {
            _resolutionRoot = resolutionRoot;
        }

        protected T Create(params IParameter[] parameters)
        {
            return _resolutionRoot.Get<T>(parameters);
        }
    }
}

What this class really abstracts away, is the _resolutionRoot.Get<T> part, allowing for concrete factory classes to look something like this:

//using Ninject; // not needed
using Ninject.Syntax;
using Ninject.Parameters;

public interface IUnicornFactory
{
    Unicorn Create(string name, int hornLength, Color color);
}

public class UnicornFactory : FactoryBase<Unicorn>, IUnicornFactory
{
    public UnicornFactory(IResolutionRoot resolutionRoot)
        : base(resolutionRoot)
    { }

    public Unicorn Create(string name, int hornLength, Color color)
    {
        return Create(new ConstructorArgument("name", name),
                      new ConstructorArgument("hornLength", hornLength),
                      new ConstructorArgument("color", color));
    }
}

Is this overkill, or something that I'll thank myself for later, when I have dozens of factory classes? I find the base factory merely allows for synctactic sugar in the concrete factory implementations - are there any side-effects to this?


texts: Checking for memory leaks in data structures

texts:
I'm looking for a code review for my JavaScript code that checks if there is any memory leaks in data structures. Please include constructive criticism, as well as details on what I can do to make this code more efficient.

// memoryleak.js
// (C) 2014 Kyle Maune
// checks for memory leaks in data structs

MemoryLeak = {

  uniq_id: (new Date()).getTime(),
  checked: 1,
  is_seen: [],

  checkLeaks: function(obj) {
    var self = MemoryLeak

    if(!obj || (typeof obj == 'function') || self.checked > 20000)
      return;

    if ((self._isArray(obj) || self._isObject(obj))) {
      if (self._isArray(obj)) {
        self._logTooBig(obj, obj.length)
        for (var i = 0; i < obj.length; i++) {
          self._checkIfNeeded(obj[i])
        }
      }
      else if (self._isObject(obj)) {
        self._logTooBig(obj, self._keys(obj).length)

        for (var key in obj) {
          self._checkIfNeeded(obj[key])
        }
      }
    }
  };

  _checkIfNeeded: function(obj) {
    if (!obj)
      return;

    var self = MemoryLeak;
    self.checked++

    if ((self._isArray(obj) || self._isObject(obj))) {
      if(obj.__leaks_checked == self.uniq_id)
        return;
      obj.__leaks_checked = self.uniq_id

      setTimeout(self._partial(self.checkLeaks, obj), 5);
    }
  };

  _logTooBig: function(obj, limit) {
    if (limit > 200) {
      console.log('Object too big, memory leak? [size: ' + limit + ']')
      console.log(obj)
      console.log('-------')
    }
  };

  _keys: function(obj) {
    var rval = [], prop
    for (prop in obj)
      rval.push(prop)
    return rval;
  };

  _isArray: function(obj) {
    try {
      return obj instanceof Array
    }
    catch(e) {
      return false;
    }
  };

  _isObject: function(obj) {
    return (typeof obj == 'object')
  };

  _partial: function(fn) {
    var args = Array.prototype.slice.call(arguments)
    args.shift()
    return function() {
      var new_args = Array.prototype.slice.call(arguments)
      args = args.concat(new_args)
      return fn.apply(window, args)
    }
  }
}


texts: Clean up repeated file.writes, if/elses when adding keys to a dict

texts:
I'm getting familiar with python and I'm still learning it's tricks and idioms.

Is there an better way to implement print_html() without the multiple calls to html_file.write()?  I only separated the HTML for clarity instead of putting the entire string inside write().

In get_car(), is there a way to avoid using if/else to make the dict key ' ' if listing.find() returns nothing?

Is there anything that is flat out wrong and should be avoided/improved?

#!/usr/bin/python

import requests
import bs4
import os

### Declarations

home         = os.environ['HOME']
filename     = home + '/results.html'
results_file = open(filename, 'w')

req = requests.get([url_removed])

soup     = bs4.BeautifulSoup(req.content)
listings = soup.find_all('div', class_='listing listing-findcar listing-dealer     ')
listings.reverse()

### Functions

def print_header(message, html_file):
    html_file.write(message)

def print_html(car, html_file):
    price    = '
' + car['price'].strip() + '
'
    image    = ''
    year     = '
' + car['year'].strip() + ' ' + car['trim'].strip() + '
'
    color    = '
' + car['color'].strip() + '
'
    miles    = '
' + car['miles'].strip() + '
'
    dealer   = '
' + car['dealer'].strip() + '
'
    phone    = '
' + car['phone'].strip() + '
'
    distance = '
' + car['distance'].strip() + '
'
    link     = '
[text_removed]
'

    html_file.write(price)
    html_file.write(image)
    html_file.write('
')
    html_file.write(year)
    html_file.write(color)
    html_file.write(miles)
    html_file.write(dealer)
    html_file.write(phone)
    html_file.write(distance)
    html_file.write(link)
    html_file.write('
')

def get_car(listing):
    car = dict()

    # Year
    if listing.find('span', class_='atcui-truncate ymm'):
        car['year'] = listing.find('span', class_='atcui-truncate ymm').get_text()
    else:
        car['year'] = ''

    # Trim
    if listing.find('span', class_='trim'):
        car['trim'] = listing.find('span', class_='trim').get_text()
    else:
        car['trim'] = ''

    # Price
    if listing.find('h4', class_='primary-price'):
        car['price'] = listing.find('h4', class_='primary-price').get_text()
    else:
        car['price'] = ''

    # Mileage
    if listing.find('span', class_='mileage'):
        car['miles'] = listing.find('span', class_='mileage').get_text()
    else:
        car['miles'] = ''

    # Color
    if listing.find('span', class_='color'):
        car['color'] = listing.find('span', class_='color').get_text()
    else:
        car['color'] = ''

    # Distance
    if listing.find('span', class_='distance-cont'):
        car['distance'] = listing.find('span', class_='distance-cont').get_text()
    else:
        car['distance'] = ''

    # Dealer
    if listing.find('span', class_='owner-title atcui-block atcui-bold'):
        car['dealer'] = listing.find('span', class_='owner-title atcui-block atcui-bold').get_text()
    else:
        car['dealer'] = ''

    # Dealer phone
    if listing.find('span', class_='owner-phone'):
        car['phone'] = listing.find('span', class_='owner-phone').get_text()
    else:
        car['phone'] = ''

    # Image
    if listing.find('img', class_='atcui-vehicle-image   '):
        car['image'] = listing.find('img', class_='atcui-vehicle-image').get('src')
    else:
        car['image'] = ''

    # Link
    if listing.find('a', class_='vehicle-title atcui-trigger '):
        car['link'] = listing.find('a', class_='vehicle-title atcui-trigger ').get('href')
    else:
        car['link'] = ''

    return car

### Main

print_header('
' + str(len(listings)) + ' CARS FOUND
', results_file)

for listing in listings:
    listing_dict = get_car(listing)
    print_html(listing_dict, results_file)


texts: Rails: Setting a transient attribute on a set of objects from one model based on information from a junction model

texts:
I have a user model, a task model, and a junction model user_task that saves the data joining the two:

class Task < ActiveRecord::Base
  attr_accessor :completed_on
  has_many :user_tasks

class UserTask < ActiveRecord::Base
  attr_accessible :task_id, :user_id, :completed_on
  belongs_to :user
  belongs_to :task

class User < ActiveRecord::Base
  has_many :user_tasks, :dependent => :destroy
  has_many :tasks, :through => :user_tasks

In order to query the tasks and show if they're complete or not when a user is logged in, I have a transient attribute, (I think that's the correct terminology) an attr_accessor on the task model :completed_on. Right now I'm looping through the tasks as follows in order to get this attribute filled out.

This just thrown in a controller as a quick hack to provide what I need.

  @tasks.each do |task|
    if current_user.tasks.include? task
      task.completed_on = current_user.user_tasks.find_by_task_id(task.id).completed_on
    end
  end

I need something that, given an array of tasks and a user_id, loops through the tasks and fills that variable with the completed_on date if the user has finished that task. The goal for this is that when responding to JSON, I have overriden as_json on the task model to merge the completed_on attribute into the JSON hash:

h.merge({:completed_on => completed_on})

Possible ideas to get this done more properly:

Create a function on the tasks model that takes a user ID, joins the
user_tasks table to the tasks table, with a where clause to specify
the user. This idea is actually half baked and I'm not sure where to
go from here.
Pretty much put the code above into the user model and    change
current_user to self. I'm not sure what to name it though,
completed_tasks doesn't fit since not all of them would be completed.
fill_completed_on may work.
Utilize a decorator somehow? Is it worth    it just for this single
attribute? If so, how would I structure it?
Something like Task.where(conditions) then Task.where(conditions).completed_by(user) then setting the completed_on on the latter and merging the two results.

It feels like I'm doing this the a bad way, and could be leveraging ActiveRelation/scopes somehow.

I also think there is a better way to do include completed_on in when needed and not have to override the task model's as_json to get it to appear.


texts: Building a UI to fetch list of features and edit them

texts:
I am building a UI which fetches a list of features based on an ID and then the user can edit the list of features and save it. The script also build the UI based on the data structure currently hard coded in.

Was hoping you guys review it and let me know how I can improve it

    "use strict";

var activeFeatures = [
      //hardcoded structure
      {
        feature: 'feautreName',
        variants: {
          'featureVariant': 'percentage'
        }
      }
    ],
    //container there the ui will be build
    list = document.querySelector('#features');

// builds the vairants per variant
function injectVariants(variants) {
  var variantHtml = '';

  Object.keys(variants).forEach(function (variant) {
    var percentage = variants[variant] || 0;
    variantHtml += '
' + variant + '<input type="text" id="' + variant + '" class="percentage-active" value="' + percentage + '">
'
  })

  return variantHtml;
}

// builds the list of features
function buildFeaturesList(featureList) {
  let featureList = featureList || activeFeatures
  list.innerHTML = '';

  featureList.forEach(item => {
    list.innerHTML += '
 ' + item.feature + '
' + injectVariants(item.variants) + '

';
  })

}

// gets document based on Id and click checked if feature is checked
function getDoumentWithFeautres() {
  var r = new XMLHttpRequest(),
      documentId = document.getElementById("documentFeatures").value;

  if (documentId !== '') {
    r.open('GET', '/id/' + documentId, true);
    r.onreadystatechange = function () {
      if (r.readyState != 4 || r.status != 200) return;
      let currentFeatures = JSON.parse(r.responseText).features || [];

      buildFeaturesList(currentFeatures);

      currentFeatures.forEach(item => {
          document.getElementById(item.feature).querySelector('.checkbox').setAttribute('checked', true);
      });
    };
    r.send();
  }
}

// each feautre has a checkbox for user to select a feature
// this is for toggles
const toggleCheckBox = (target) => {
  if (target.getAttribute('checked') === "true") {
    target.setAttribute('checked', false);
  } else {
    target.setAttribute('checked', true);
  }
}

//build the payload before posting
function getActiveFeatures() {
  var listOfFeaturesElements = [].slice.call(document.querySelectorAll(".checkbox"));
  var payload = {};

  Payload.id = document.getElementById("documentFeatures").value;
  payload.features = [];

  listOfFeaturesElements.forEach(function (element) {
    var featureObject;

    if (element.getAttribute("checked") === 'true') {

      featureObject = (activeFeatures.filter(function (obj) {
          return obj.feature === element.getAttribute('data-feature')
      }));

      Object.keys(featureObject[0].variants).map(function (item) {
          featureObject[0].variants[item] = document.getElementById(item).value
      });

      payload.features.push(featureObject[0]);
    }
  });

  return payload;
}

// post updated features on save
function updateDocument(target) {
  var payload = getActiveFeatures(),
      r = new XMLHttpRequest();

  r.open("POST", "/journeys", true);
  r.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  r.onreadystatechange = function () {
      if (r.readyState != 4 || r.status != 200) return;
  };
  r.send(JSON.stringify(payload));
}

document.body.addEventListener('click', function (e) {
  switch (e.target.classList[0]) {
    case 'search':
      getDoumentWithFeautres()
      break;
    case 'checkbox':
      if (journey) toggleCheckBox();
      break;
    case 'save':
      if (journey) updateDocument(e.target);
      break;
    default: break;
  }
});

buildFeaturesList();


texts: Dynamically call a function in a given module

texts:
I use the following code that is working as expected and I want to get some feedback from the community how I can Improve it...

  The code does the following:

Get Some request with specific action to run which is describe in JSON file
e.g. URL is like aaa/bbb/invokeFn
Find this invokeFn in the config.json and call to function with the same name in the module
the files are located in folder under the project.

Please refer to my JavaScript and I need help with the followings

  Does it make sense to divide it for two functions or maybe more?
  How you put the variables better? Between those two function.
  Any other feedback how can I improve the code in JS will be very helpfull

 run: function (req, res, urlPath) {

                var pluginPath = constants.INT;
                var extPluginPath = constants.EXT;

                var isFnCalled = false;
                globby([objPath,extobjPath ])
                    .then(function (extensions) {
                        extensions.forEach(function (file) {
                            if (!isFnCalled) {

                                var filePath = file.split('/');
                                var fileName = filePath[filePath.length - 1];
                                var reqFile = "../" + filePath[2] + "/" + fileName;

                                isFnCalled = runFunction( req,res,reqFile,isFnCalled, urlPath);
                            }
                        });
                    }).catch(function (err) {
                        console.log('error: ', err);
                    }
                )
            }
        };

        var runFunction = function (req, res,reqFile, isFnCalled, urlPath) {
            var rAction = urlPath[2];
            //require JSON
            var config = require(reqFile + 'on');
            //require Module
            var obj = require(reqFile);
            for (var provider in config.providers[0]) {
                if ((config.providers[0][provider].path === rAction && !isFnCalled)
                    && (req.method === config.providers[0][provider].method.toUpperCase())) {
                    var fnName = config.providers[0][provider].function;
                    if (typeof obj[config.providers[0][provider].function] === "function") {
                        try {
                            isFnCalled = true;
                            //invoke function
                            console.log("Function " + fnName + " is called");
                            obj[fnName](req, res, urlPath);
                        }
                        catch (err) {
                            res.status(500).send("Error returned from obj " + err);
                        }
                        if (!res.headerSent) {
                            res.end("function " + fnName + " finish successfully ", 200);
                        }
                    }
                }
            }
            return isFnCalled;
        };


texts:
I'm toying with Regexes to parse IP Addresses.  I've got it to test for anything over 255:

public static boolean isIpAddress(String address)
{
    String regex = "^((25[0-5])|(((1[0-9]|2[0-4])|[1-9])?[0-9]))(\\.((25[0-5])|(((1[0-9]|2[0-4])|[1-9])?[0-9]))){3}$";
    try{
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(address);

        return m.find();
    }catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return false;
}

Is there a more efficient way to write that regex?

I understand that I could probably run something like this:

String[] addressChunks = address.split(".");
String regex = "^((25[0-5])|(((1[0-9]|2[0-4])|[1-9])?[0-9]))$";
Pattern p = Pattern.compile(regex);
for(String s: addressChunks)
{
    Matcher m = p.matcher(s);
    if(!m.find(s))
    {
      return false;
    }
}
return true;

But I'd rather keep it to one line of regex and compare it all instead of doing a split.


texts: Find the most frequent number in an array

texts:
I implemented a solution for: Finding the most frequent number from an array. How are my variable names? Or how could I improve this?

 private static Integer findMostFrequentNumber(int[] givenArray) {
    int mostFrequentNumber = 0;
    if (givenArray != null) {
        Map<Integer, Integer> numberOccuranceMap = new HashMap<>();
        int mostFrequentOccurance = 0;

        for (Integer number : givenArray) {
            if (!numberOccuranceMap.containsKey(number)) {
                numberOccuranceMap.put(number, 1);
            } else {
                numberOccuranceMap.put(number, numberOccuranceMap.get(number) + 1);
            }
            if (numberOccuranceMap.get(number) > mostFrequentOccurance) {
                mostFrequentNumber = number;
                mostFrequentOccurance = numberOccuranceMap.get(number);
            }
        }
    }
    return mostFrequentNumber;
}


texts:
I have the following python script like:

query_parser.py

#!/usr/bin/env python

def count_resources_per_category(resource_names):
    APPS_MAP = {
        'billing': ["paypal", "checkout", "cart", "order-service"],
        'browse': ["content", "localization", "pricing", "search",],
        'some_category': ["random-1", "random-2"],
    }
    results_map = {}
    for key, _ in APPS_MAP.items():
        results_map[key] = 0
    results_map['other'] = 0
    # now we have:
    #   results_map = {
    #     'checkout': 0,
    #     'browse': 0,
    #     'MCM': 0,
    #     'other': 0
    #   }
    for resource_name in resource_names:
        FOUND_IT = False
        for key, app_names in APPS_MAP.items():
            if FOUND_IT:
                break
            for app_name in app_names:
                if app_name in resource_name:
                    results_map[key] += 1
                    FOUND_IT = True
                    break
        if not FOUND_IT:
            results_map['other'] += 1

    return results_map

def determine_if_resource_count_issue(results_map):
    RESULT_FOUND = False
    for key, count in results_map.items():
        if count:
            if RESULT_FOUND:
                print("The script isn't gonna work as planned")
                return True
            RESULT_FOUND = True
    print("All good :)")
    return False

#--------------------------------------------------------------------

""" TESTS """

# test_count_resources_per_category():
test_input = [
    'some-prefix-pricing', # browse
    'some-prefix2-cart', # billing
    'content', # browse
    'some-random-thing-not-found' # other
]
expectation = {
    'browse': 2,
    'billing': 1,
    'some_category': 0,
    'other': 1
}
result = count_resources_per_category(test_input)
assert result == expectation

#--------------------------------------------------------------------

# test_determine_resource_count_issue_passes():
test_input = {
    'browse': 234234234,
    'billing': 0,
    'some_category': 0,
    'other': 0
}
assert False == determine_if_resource_count_issue(test_input)

#--------------------------------------------------------------------

# test_determine_resource_count_issue_fails():
test_input = {
    'browse': 2,
    'billing': 1,
    'some_category': 0,
    'other': 1
}
assert True == determine_if_resource_count_issue(test_input)

#--------------------------------------------------------------------

It has some tests at the bottom explaining how it works, but the goal is to ensure each result from running a query is only for 1 category at a time.

I was wondering what the clean, pythonish way to handle these nested loops would be without the FOUND_IT and RESULT_FOUND flags. Any improvements welcome.


texts: Using bind instead of promises or stacked callbacks

texts:
I've seen tutorials about node promises and such but not using bind. I feel like I can do lots of things this way and keep everything clean:

Updater.prototype.generateLocFieldForDocs = function(docs) {
  console.log('list obtained')
  async.eachLimit(docs, 10, this.generateLocFieldForDoc.bind(this), this.generateLocFieldForDocsDone.bind(this))
}

Updater.prototype.generateLocFieldForDoc = function(doc, done) {
  this.collection.update({_id: doc._id},
  {$set: {
    loc: {...}
  }}, function(err, result) {
    this.errorHandler(err)
    done()
  }.bind(this))
}

Updater.prototype.generateLocFieldForDocsDone = function(err) {
  this.errorHandler(err)
  this.generateLocFieldNextSection()
}

What do you think about using classes and bind like this in node.js?

What bind does is that it's sets the this in the function body to the this passed to bind therefore keeping the context you want.


texts:
I'm new to Python. For learning purposes, I want to create desktop application by using QtWebKit and Flask. You can find the source code here

Main idea is:

create a form including a QWebview widget
create a Flask app
run Flask app on QWebview

It works correctly but I want to know:

How can I improve my code?
is this good way to create desktop apps?

My code is:

main.py

from core.Core import *

app = Flask(__name__)

from routes import *

if __name__ == '__main__':
    main(app)

core module: core/Core.py

import sys
from flask import Flask , render_template
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from threading import Thread

class FlaskThread(QThread):

    def __init__(self,app):
        QThread.__init__(self)
        self.app = app

    def __del__(self):
        self.wait()

    def run(self):
        self.app.run()

def main(app):
    th = FlaskThread(app)
    th.start()
    #qt init
    qtapp = QApplication(sys.argv)
    qtapp.aboutToQuit.connect(lambda : th.terminate())
    webview = QWebView()
    webview.load(QUrl('http://localhost:5000'))
    webview.show()
    sys.exit(qtapp.exec_())

and then routes.py

from main import *

@app.route('/')
def index():
    #return 'hi'
    return render_template('index.html')


texts: Is there a better way for this ui component?

texts:
I need to create a component for displaying a list of avatar users....If the users present in the array is more then 3 I have to display a number to indicate the remaining amount of users.
Example:
[{id:1, name: 'Paul', surname: 'Rudd'}, {id:2, name: 'Rose', surname: 'Pink'}, {id:3, name: 'Richard', surname: 'Gere'}, {id:4, name: 'Anna', surname: 'Ross'}, {id:5, name: 'Raphael', surname: 'Bublè'},{id:6, name: 'Gene', surname: 'Hoffman'},{id:7, name: 'Anthony', surname: 'Florence'}]

I have to see 3 avatar images with the first letter of name and surname:
PR, RP, RG 4+
This is my component:
    @Component({
      selector: 'mgg-users-detail',
      templateUrl: './users-detail.component.html',
      styleUrls: ['./users-detail.component.scss'],
    })

    export interface users {
      id: number;
      name: string;
      surname: string;
    }
    export class UsersDetailComponent implements OnInit {
      @Input()
      collaborators: users[]

      constructor() {}

      ngOnInit(): void {}

    }

and this is the html:
    <div *ngIf="users && users.length > 1">
        <div *ngFor="let user of users; index as i">
          <img
            *ngIf="i <= 2"
            [src]="'https://dummyimage.com/50x50/6ECFDB/fff&text=' + collaborator.name[0] + collaborator.surname[0]"
          ></img>
        </div>
        <img
          *ngIf="users.length > 3"
          [src]="'https://dummyimage.com/50x50/6ECFDB/fff&text=' + (users.length - 3)"
        >
        </img>
    </div>

Can I improve the code in other way?


texts:
It's not fair that 1% of the users hold 75% of the lolcode questions. #OccupyMatsMug
  ~ user2296177

I agree. Without further ado, here's the LOLCODE version of 99 bottles of beer on the wall:

OBTW
    PRINT TEH LOLCODE VERSHUN OV N BOTTLEZ OV BER ON TEH WALL.
TLDR

HAI 1.3

  HOW IZ I COUNTDOWN YR NUMAH
    I HAS A NAUW ITZ A NUMBR
    I HAS A LEZZ ITZ A NUMBR
    IM IN YR LOOPZ NERFIN YR COWNTR TIL BOTH SAEM COWNTR AN DIFF OF 1 AN NUMAH
      NAUW R SUM OF NUMAH AN COWNTR
      LEZZ R DIFF OF NAUW AN 1
      VISIBLE SMOOSH NAUW AN " LITTERS OV KITTEHS ON TEH NETZ" MKAY
      VISIBLE SMOOSH NAUW AN " LITTERS OV KITTEHS" MKAY
      VISIBLE "WAN FALLS DOWN AN BREAKZ PAH"
      VISIBLE SMOOSH LEZZ AN " LITTERS OV KITTEHS ON TEH NETZ" MKAY
      VISIBLE ""
    IM OUTTA YR LOOPZ

    VISIBLE "1 LITTER OV KITTEHS ON TEH NETZ"
    VISIBLE "1 LITTER OV KITTEHS"
    VISIBLE "WAN FALLS DOWN AN BREAKZ PAH"
    VISIBLE "NO MOAR LITTERs OV KITTEHS ON TEH NETZ"
  IF U SAY SO

  I IZ COUNTDOWN YR 99 MKAY

KTHXBYE

Disclaimer: No actual kittens were harmed while writing this program.

The number of iterations is held in the variable NUMAH. I know NUMBR is a more fitting name, but that's already claimed as a type.

The above is compiled using the latest lci using the 1.3 specification (thanks to Pimgd for the link). Since the 1.3 specification doesn't contain every feature of the language, see the 1.2 specification as well.

I don't think LOLCODE has templates or the likes, so getting all the output on screen is a bit tedious.

Output:

99 LITTERS OV KITTEHS ON TEH NETZ
99 LITTERS OV KITTEHS
WAN FALLS DOWN AN BREAKZ PAH
98 LITTERS OV KITTEHS ON TEH NETZ

etc.

1 LITTER OV KITTEHS ON TEH NETZ
1 LITTER OV KITTEHS
WAN FALLS DOWN AN BREAKZ PAH
NO MOAR LITTERs OV KITTEHS ON TEH NETZ

Is this idiomatic LOLCODE?


texts: Pascal triangle produced for a particular integer K

texts:
Please be brutal and let me know what you think of the code below, if written at an interview.

Problem:

  Given an index k, return the kth row of the Pascal's triangle.

  For example, given k = 3, return [1,3,3,1].

  Time it took:
  25 minutes (perfectly working solution)

  Space Complexity:
  O(K)

  Time Complexity:
  O(N2)?

public ArrayList<Integer> getRow(int rowIndex) {
    List<ArrayList<Integer>> allList = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> toAdd = new ArrayList<Integer>();
    if(rowIndex==0){
        toAdd.add(1);
        return toAdd;
    }

    if(rowIndex>=1){
        toAdd = new ArrayList<Integer>();
        toAdd.add(1);
        toAdd.add(1);
        allList.add(toAdd);
        if(rowIndex==1){
            return toAdd;
        }
    }
    for(int i=1; i<rowIndex; i++){
        ArrayList<Integer> temp = new ArrayList<Integer>();
        temp.add(1);
        for(int j=1; j<allList.get(i-1).size(); j++){
            temp.add(allList.get(i-1).get(j-1) + allList.get(i-1).get(j));
        }
        temp.add(1);
        allList.add(temp);
    }
    return allList.get(rowIndex-1);
}


texts:
I was wondering if this implementation of selection sort could be improved. Are there any things that I have done wrong?

template<typename Element>
void selection_sort(Element arr[], size_t size) {
    auto index_toSort = 0u;
    while (index_toSort < size) {
        auto index_smallest = index_toSort;
        for (auto index = index_toSort; index < size; ++index) {
            if (arr[index] < arr[index_smallest]) {
                index_smallest = index;
            }
        }
        std::swap(arr[index_toSort], arr[index_smallest]);
        ++index_toSort;
    }
}


texts:
I have some working code, but it seems a bit clunky.

I need to get data from a service. The service will hold the data in local storage if possible (to make it speedier), but if it's not been accessed before, it will need an http GET to a web server. The example contains only one GET, but there could be many in the future.

Service code

var module = angular.module('myapp.service', ["ngStorage"]);

module.service('jsonlistservice', function ($http, $q, $timeout, $localStorage) {

    var getStuff = function(){

      if ($localStorage.stuff != undefined && $localStorage.stuff != "") {

        return $q(function (resolve, reject) {
          var x = {};
          x.data = $localStorage.stuff;
          resolve(x);
        });

        }else{
            return $http.get('data/sample.json').success(function(response){
              $localStorage.stuff = response;
            });
        }
    };

    return{
        getStuff: getStuff,
    };
});

From a controller this would be accessed like so:

'use strict';
angular.module('myApp.view1', ['ngRoute', 'myapp.service'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])

.controller('View1Ctrl', ['$scope', 'jsonlistservice', function($scope, myappservice) {

    var myDataPromise = myappservice.getStuff();
        myDataPromise.then(function(result){
            $scope.test = result.data[950].Id;
            console.log("returned");
        });

}]);

What is the correct pattern for this sort of thing please?


texts: Preprocessing text input to a machine-learning algorithm

texts:
I have written the following function to preprocess some text data as input to machine learning algorithm. It lowercase, tokenises, removes stop words and lemmatizes, returning a string of space-separated tokens. However, this code runs extremely slowly. What can I do to optimise it?

import os
import re
import csv
import time
import nltk
import string
import pickle
import numpy as np
import pandas as pd
import pyparsing as pp
import matplotlib.pyplot as plt
from sklearn import preprocessing
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import sent_tokenize, word_tokenize
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer

def preprocessText(text, lemmatizer, lemma, ps):
        '''
        Lowercase, tokenises, removes stop words and lemmatize's using word net. Returns a string of space seperated tokens.
        '''
        words = text.lower()
        words = re.sub("[^a-zA-Z]", " ", words)
        words = word_tokenize(words)
        stemmed_words = []
        stops = set(stopwords.words("english"))
        meaningful_words = [w for w in words if not w in stops]
        text = ""
        if lemmatizer == True:
            pos_translate = {'J':'a', 'V':'v', 'N':'n', 'R':'r'}
            meaningful_words = [lemma.lemmatize(w,pos=pos_translate[pos[0]] if pos[0] in pos_translate else 'n') for w,pos in nltk.pos_tag(meaningful_words)]
            for each in meaningful_words:
                if len(each) > 1:
                    text = text +" " + each
            return text
        else:
            words_again = []
            for each in meaningful_words:
                words_again.append(ps.stem(each))
            text = ""
            for each in words_again:
                if len(each) > 1:
                    text = text +" " +each
            return(text)


texts: Improving function that compares two strings

texts:
I'm learning C and have made this very simple function to compare two strings. I would like to know how it can be improved:

int match(char* string1, char* string2)
{
    size_t i = 0;

    while (string1[i] != '\0' || string2[i] != '\0') {
        if (string1[i] != string2[i]) {
            return 0;
        }
        ++i;
    }

    return 1;
}

I figured it will only do 2 comparisons per iteration, and 3 in the last iteration. Also, I believe it won't go beyond the end of any array because it will return before iterating beyond the null terminator.


texts:
I'm looking for OOP tips or advice.

    ;(function ( $, window, document, undefined ) {

  if ( typeof Object.create !== 'function' ) {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
  }

  if (!Function.prototype.bind) { // check if native implementation available
    Function.prototype.bind = function(){
      var fn = this, args = Array.prototype.slice.call(arguments),
          object = args.shift();
      return function(){
        return fn.apply(object,
          args.concat(Array.prototype.slice.call(arguments)));
      };
    };
  }

  $.component = function( name, object ) {
    $.fn[name] = function( options ) {
      return this.each(function() {
        if ( !$.data( this, name ) ) {
          $.data( this, name, Object.create(object).init(
            $.extend(true, {}, $.fn[name].opts, options), this )
          );
        }
      });
    };
  };

})( jQuery, window , document );

(function ( $, window, document, undefined ) {

  var dropdown = {
    opts: {},
    init: function( options, el ) {
      this.$el = $(el).on('click.dropdown',
        (function(evt){
          this.toggle(evt);
        }).bind(this)
      );
      this.opts = $.extend(true, this.opts, options);
      this.isShowing = false;
      return this;
    },
    show: function (evt) {
      if(evt) evt.preventDefault(); evt.stopPropagation();
      $(this.opts.header).addClass('show-mobile-nav');
      this.isShowing = true;
      this.bindClose();
    },
    hide: function (evt) {
      if(evt) evt.preventDefault();
      $(this.opts.header).removeClass('show-mobile-nav');
      this.isShowing = false;
      return this;
    },
    bindClose: function () {
      $('html').on('click.dropdown',
        (function(evt){
          var $targ = $(event.target || window.event.srcElement),
          targetIsNotDropdown = !$targ.is(this.opts.menu),
          targetsNotAChildOfDropdown = $(this.opts.menu).has( $targ ).length == 0;
          if( targetIsNotDropdown && targetsNotAChildOfDropdown) {
            $('html').off('.dropdown');
            this.hide();
          }
        }).bind(this)
      );
      return this;
    },
    toggle: function (evt) {
      if(evt) evt.preventDefault();
      if ( !this.isShowing ) {
        this.show(evt);
      } else {
        this.hide(evt);
      }
    }
  };

  $.component('dropdown',dropdown);

})( jQuery, window , document );