texts:
This is a simple hello world sample project used for instruction.  I'm just looking for general comments on the approach and design.

AdvancedHelloWorldTest.java

/**
 * AdvancedHelloWorldTest.java
 * 2014 GetGnosis.com
 */
package com.getgnosis.tutorials.tutorial01001;

import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.junit.Test;

/**
 *  Test Class for
 *  {@link com.getgnosis.tutorials.tutorial01001.AdvancedHelloWorld}
 *
 * @author mhemphill
 * @version 1.0.0 - Mar 9, 2014
 */
public class AdvancedHelloWorldTest {

    /**
     * Test method for
     * {@link com.getgnosis.tutorials.tutorial01001.AdvancedHelloWorld
     *  #AdvancedHelloWorld()}.
     */
    @Test
    public void testAdvancedHelloWorld() {
        try {
            new AdvancedHelloWorld();
        } catch (Exception e) {
            fail("Construction failed. ");
        }
    }

    /**
     * Test method for
     * {@link com.getgnosis.tutorials.tutorial01001.AdvancedHelloWorld
     *      #main(java.lang.String[])}.
     */
    @Test
    public void testMain() {
        final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outContent));
        AdvancedHelloWorld.main(null);
        assertEquals("Hello World!" + System.getProperty("line.separator"), outContent.toString());
        System.setOut(null);
    }

    /**
     * Test method for
     * {@link com.getgnosis.tutorials.tutorial01001.AdvancedHelloWorld
     *      #toString()}.
     */
    @Test
    public void testToString() {
        String helloWorldString =  new AdvancedHelloWorld().toString();
        assertEquals("AdvancedHelloWorld [message=Hello World!]",helloWorldString);
    }

}

AdvancedHelloWorld.java

/**
 * AdvancedHelloWorld.java
 * 2014 GetGnosis.com
 */
package com.getgnosis.tutorials.tutorial01001;

/**
 * This is an example program that prints the {@link String} "Hello World!" to
 * the system's output display.
 *
 * @author mhemphill
 * @version 1.0.0 - Mar 9, 2014
 */
public class AdvancedHelloWorld {

    static {
        message = "Hello World!";
    }

    /**
     * The {@link String} instance representing the message to be displayed.
     */
    private final static String message;

    /**
     * The default constructor.  Initializes the value of message via the
     * static block.
     */
    public AdvancedHelloWorld() {}

    /**
     * The application entry point.  Creates a new instance of
     * {@link AdvancedHelloWorld} and prints the value of the {@link String}
     * message to the system's output display.
     *
     * @param args - @{link String} array representing the arguments to the
     * application.  Not used in this application.
     *
     */
    public static void main(String[] args) {
        System.out.println(new AdvancedHelloWorld().getMessage());
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("AdvancedHelloWorld [");
        if (getMessage() != null)
            builder.append("message=").append(getMessage());
        builder.append("]");
        return builder.toString();
    }

    /**
     * Returns {@link String} instance representing the message to be displayed.
     *
     * @return message - {@link String} instance representing the message to
     * be displayed.
     */
    private final String getMessage() {
        return message;
    }

}


texts:
I have implemented a solution for finding all anagrams. Are there any other suggestions for improving the solution?
package main.algorithms;

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

public class AllAnagrams {
    // Sliding window
    public static void main(String args[]) {
        // s: "cbaebabacd" p: "abc"
        String str = "cbaebabacd";
        String partial = "abc";
        findAnagrams(str, partial);
    }

    public static void findAnagrams(String s, String p){
        List<Integer> list = new ArrayList<>();
        if (s == null || s.length() == 0 || p == null || p.length() == 0) return;
        int[] hash = new int[256]; //character hash
        //record each character in p to hash
        for (char c : p.toCharArray()) {
            hash[c]++;
        }
        //two points, initialize count to p's length
        int left = 0, right = 0, count = p.length();
        while (right < s.length()) {
            //move right everytime, if the character exists in p's hash, decrease the count
            //current hash value >= 1 means the character is existing in p
            if (hash[s.charAt(right++)]-- >= 1) count--;

            //when the count is down to 0, means we found the right anagram
            //then add window's left to result list
            if (count == 0) list.add(left);

            //if we find the window's size equals to p, then we have to move left (narrow the window) to find the new match window
            //++ to reset the hash because we kicked out the left
            //only increase the count if the character is in p
            //the count >= 0 indicate it was original in the hash, cuz it won't go below 0
            if (right - left == p.length() && hash[s.charAt(left++)]++ >= 0) count++;
        }
        System.out.println(list);
    }

}


texts:
I'm trying to learn Python through the excellent online book Dive Into Python 3. I have just finished chapter 2 about data types and felt like trying to write a program on my own.
The program takes an integer as input and factorizes it into prime numbers:
$ python main.py 6144
6144 -> (2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3)

$ python main.py 253789134856
253789134856 -> (2, 2, 2, 523, 60657059)

I'd like to know if I could improve it in any way. Or if I've used any bad practice and so on.
#!/usr/bin/python

import sys
import math

def prime_factorize(n):
    factors = []
    number = math.fabs(n)

    while number > 1:
        factor = get_next_prime_factor(number)
        factors.append(factor)
        number /= factor

    if n < -1: # If we'd check for < 0, -1 would give us trouble
        factors[0] = -factors[0]

    return tuple(factors)

def get_next_prime_factor(n):
    if n % 2 == 0:
        return 2

    # Not 'good' [also] checking non-prime numbers I guess?
    # But the alternative, creating a list of prime numbers,
    # wouldn't it be more demanding? Process of creating it.
    for x in range(3, int(math.ceil(math.sqrt(n)) + 1), 2):
        if n % x == 0:
            return x

    return int(n)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: %s <integer>" % sys.argv[0])
        exit()

    try:
        number = int(sys.argv[1])
    except ValueError:
        print("'%s' is not an integer!" % sys.argv[1])
    else:
        print("%d -> %s" % (number, prime_factorize(number)))

Edit:
@JeffMercado: Interesting link as I haven't encountered this before. And yes, the memoization technique should be easy to implement in my case since it is basically the same as the Fibonacci example.
In the Fibonacci example, they have a map (dictionary in Python?) outside the function, but should I do that? Global variables “are bad”? If that's the case, where does it belong? In the function prime_factorize() and I pass the map as an argument? I'm having a hard time deciding things like this, but I guess it gets easier with experience...
@WinstonEwert:

Prime factorization really only makes sense for integers. So you really use abs not fabs.

I couldn't find abs when I ran help(math), only fabs. I thought fabs was my only choice but I just found out that abs doesn't even reside in the math module. Fixed.

Tuples are for heterogeneous data. Keep this a list. It is conceptually a list of numbers, and it so it should be stored in a python list not a tuple.

You write that tuples are for heterogeneous data. I searched SO and many seems to be of this opinion. However, in the book I'm following, the author gives a few points for using a tuple:

Tuples are faster than lists. If you’re defining a constant set of values and all you’re ever going to do with it is iterate through it, use a tuple instead of a list.
It makes your code safer if you “write-protect” data that doesn’t need to be changed. Using a tuple instead of a list is like having an implied assert statement that shows this data is constant, and that special thought (and a specific function) is required to override that.

That is why a returned a tuple. Is the author's points valid or just not in this case?

Your expression, int(math.ceil(math.sqrt(n)) + 1) seems to be more complicated that it needs to be. Couldn't you get by with int(math.sqrt(n) + 1).

The upper value of range was unnecessarily complicated. Fixed.

Again, why are you trying to support something that isn't an int?

I was returning int(n) from get_next_prime_factor(n) since the number that is passed in to the function becomes a float when I divide it (in prime_factorize), so if I return just n from the function, I return a float which gets added to the list 'factors'. When I then print the factors, I get e.g. '11.0' as the last factor for the number 88.
Any other way to fix that?

I'd pass an exit code to indicate failure

Should I just exit(1) or something like that?


texts:
I've been playing around with inheritance in JavaScript and I'm wondering if there are any drawbacks to this method which tries to emulate classical inheritance from C-based languages.

Function.prototype.extends = function (parentClass) {
    function temp () { this.constructor = this; };
    temp.prototype = new parentClass();

    this.prototype = new temp();
};

var Animal = function() {
    function Animal() {};

    Animal.prototype.walk = function () {
        return this.name + ' walks';
    };

    return Animal;
}();

var Cat = function () {
    function Cat (name) {
        this.name = name;
    };

    Cat.extends(Animal);

    Cat.prototype.meow = function() {
        return this.name + ' meows';
    };

    return Cat;
}();

var Chester = new Cat('Chester');

console.log(Chester.meow()); // Chester meows
console.log(Chester.walk()); // Chester walks

This is a crude example, but can anyone point out any glaring problems?


texts: Is there currently anything wrong with my custom authentication and authorization?

texts:
I have my reasons not to use the ASP.NET membership. Though this causes me some issues. I read about a thousand articles on ASP.NET MVC custom authentication and I've found that almost all of them are just too simple to be of any use.

What I need is a good way to login a user, keep some info about him securely in a cookie (info such as id, username, email and role) and later use this info to assure that he's authorized to visit and edit certain pages. The way I have things right now is a bit convoluted and possibly insecure.

Here's the relevant code in my login method:

// Set session cookie
var cookieName = CookieHelper.MergeIntoString(user.Id, user.Username, user.IsAdmin, user.IsStaff);
// Code for the CookieHelper class is to follow below!
var timeout = model.RememberMe ? 525600 : 2880; // 365 days or 2 days
var ticket = new FormsAuthenticationTicket(cookieName, model.RememberMe, timeout);
var encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted)
{
    Expires = DateTime.Now.AddMinutes(timeout),
    HttpOnly = true
};

Response.SetCookie(cookie);

Code for the CookieHelper class:

public static class CookieHelper
{
    public static string MergeIntoString(int id, string username, bool isAdmin, bool isStaff)
    {
        return id + "/" + username + "/" + isAdmin + "/" + isStaff;
    }

    public static Dictionary<string, object> DecodeFromString(string cookieName)
    {
        var cookieDictionary = new Dictionary<string, object>();
        var cookieArray = cookieName.Split('/');

        cookieDictionary.Add("Id", cookieArray[0]);
        cookieDictionary.Add("Username", cookieArray[1]);
        cookieDictionary.Add("IsAdmin", cookieArray[2]);
        cookieDictionary.Add("IsStaff", cookieArray[3]);

        return cookieDictionary;
    }
}

Why am I using the CookieHelper class? Because I have no idea how to add more information that will be encrypted in my cookie. So I decided to put the info into the cookie name string and later split it to get my info.

And this is how I later reach into the cookie to get the user id:

var authCookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
if (authCookie == null)
    return RedirectToAction("Index", "Home");

var cookieName = FormsAuthentication.Decrypt(authCookie).Name;
var cookie = CookieHelper.DecodeFromString(cookieName);
var userId = Convert.ToInt32(cookie["Id"]);

Now I'm sure there's thousands of issues with this. Can you tell me of a better way of doing what I'm trying to do?


texts: Algorithmic complexity of this algorithm to find all ordered permutations of length X

texts:
I have written a recursive function to generate the list of all ordered permutations of length X for a list of chars.

For instance: ['a', 'b', 'c', 'd'] with X=2 will give [['a', 'a'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['b', 'a'], ['b', 'b'], ..., ['d', 'd']]

I'm not sure about its algorithmic complexity though (at least I know it's pretty horrible). I would say it's something around:

O(X * N^(L + X))

(where L is the number of different chars, 4 here because we have 'A', 'B', 'C', 'D', and X the length of the permutations we want to generate). Because I have 2 nested loops, which will be run X times (well, X-1 because of the special case when X = 1). Is it correct?

def generate_permutations(symbols, permutations_length):
    if permutations_length == 1:
        return [[symbol] for symbol in symbols]

    tails = generate_permutations(symbols, permutations_length-1)
    permutations = []

    for symbol in symbols:
        for tail in tails:
            permutation = [symbol] + tail

            permutations.append(permutation)

    return permutations

print(generate_permutations(['a', 'b', 'c', 'd'], 2))

By the way: I know this is not idiomatic Python and I apologize if it's ugly but it's just some prototyping I'm doing before writing this code in a different, less expressive language. And I also know that I could use itertools.permutations to do this task. By the way, I'd be interested if someone happens to know the algorithmic complexity of itertool's permutations function.


texts:
When I run my code, I get an "Excel not responding" error at this sub as I step through the code, more specifically the write portion of this code. Can anyone help optimize this? I think this is because the loop is writing so many records cell by cell (50k) records and it's causing my Excel sheet to become unresponsive.

 'writes the nRows and nCols from arr to startCell
    'if fromTop is true it starts reading from the first element of arr, otherwise it starts fromm the last element
    Public Sub writeArrToWS(arr() As Variant, startCell As Range, fromTop As Boolean, nRows As Long, nCols As Long)

        Dim i As Long, j As Long, startRow As Long, startCol As Long
        Dim thisWS As Worksheet
        Dim writeVal As Variant

        Set thisWS = startCell.Worksheet

        startRow = startCell.row
        startCol = startCell.Column

        'clear
        For i = 1 To nRows
            For j = 1 To nCols
                thisWS.Cells(startRow + i - 1, startCol + j - 1).value = ""
            Next j
        Next i

        'write
        For i = 1 To WorksheetFunction.Min(nRows, UBound(arr, 1))
            For j = 1 To nCols
                If fromTop Then writeVal = arr(i, j) Else writeVal = arr(UBound(arr, 1) - i + 1, j)
                thisWS.Cells(startRow + i - 1, startCol + j - 1).value = writeVal
            Next j
        Next i

    End Sub


texts:
I have one button on clicking I need multiple things need to be done, so I went for AJAX and PHP:

$('.go_nxt_lsn').live('click',function(e){
    e.stopPropagation();
    var user_id = $('input[name=user_id]').val();
    var course_id = $('input[name=course_id]').val();
    var taskName = "SaveActivity";
    var subTask = "watchvideo";
    var lesson_id = $(this).attr('data-lesson-id');
    var video_id = $(this).attr('data-video-id');
    var course_box = '.course_'+course_id;
    var refresh_boo = 1;

    $.ajax({
        type        : 'POST',
        url         : '<?php echo $vars['url']?>learn/pages/syllabus/saveitems.php',
        datatype    : 'html',
        data        : {subtask:subTask,lessonid:lesson_id,theSubModID:video_id,userid:user_id,prodid:course_id,taskname:taskName},
        success:function(data)
        {
            taskName = "GoToNextLesson"
            $.ajax({
                type        : 'POST',
                url         : '<?php echo $vars['url']?>learn/pages/syllabus/saveitems.php',
                datatype    : 'html',
                data        : {subtask:subTask,lessonid:lesson_id,userid:user_id,prodid:course_id,taskname:taskName},
                success:function(data)
                {
                    $.ajax({
                        type        : 'POST',
                        url         : '<?php echo $vars['url']?>learn/pages/syllabus/learn.php',
                        datatype    : 'json',
                        data        : {user_id:user_id,course_id:course_id},
                        success:function(data)
                        {
                            $.ajax({
                                type        : 'POST',
                                url         : '<?php echo $vars['url']?>mod/event_calendar/views/default/event_calendar/instantlearn.php',
                                datatype    : 'html',
                                data        : {learn_details:data,refresh_boo:refresh_boo,prodid:course_id},
                                success:function(data)
                                {
                                    $(course_box).replaceWith(data);
                                    $(".accordion").accordion({
                                        active: false,
                                        collapsible: true,
                                        heightStyle: "content"
                                   });
                                }
                            });
                        }
                    });
                }
            });
        }
    });
});

I am sending four AJAX requests one by one, so I want an alternate for this. This code works fine. But this is so lengthy. Can anybody suggest how I can minimize it?


texts:
I've tried making a payment system for an API called Payson, which is a European company similar to PayPal.

I get the right response when I press the button so it seems to work, and I wonder if you can look at my code to see if it looks OK. I didn't test the part receive but the part send i.e. the first part I've testet and it appears to work:

class PaysonHandler(webapp2.RequestHandler):

    def get(self):
        """
............Returns a simple HTML form for Payson
........"""
        logging.info('in payson')
        SellerEmail = 'niklas...@gmail.com'
        Cost = 250
        ExtraCost=0
        GuaranteeOffered=2
        OkUrl = self.request.host+"/payson_okurl" # TO DO
        Key = '319033-6152-402-b95a-37430de6b6'
        text = SellerEmail + ':' + str(Cost) + ':' + str(ExtraCost) + ':' + OkUrl + ':' + str(GuaranteeOffered) + Key
        logging.info('mdtext5: '+text)
        m = hashlib.md5()
        Generated_MD5_Hash_Value = hashlib.md5(text).hexdigest()
        BuyerEmail = 'niklas@.....se'
        AgentID = 11366
        path = os.path.join(os.path.dirname(__file__), 'templates',
                            'payson.html')
        self.response.out.write(template.render(path, {
            'SellerEmail':SellerEmail, 'Cost':Cost,  'Cost':Cost, 'AgentID':AgentID,
                  'ExtraCost':ExtraCost, 'GuaranteeOffered':GuaranteeOffered,  'OkUrl':OkUrl, 'Key':Key,  'Generated_MD5_Hash_Value':Generated_MD5_Hash_Value,  'BuyerEmail':BuyerEmail,    }))

class PaysonReceiveHandler(webapp2.RequestHandler):

    def get(self):
        """
............Receives Payson messages. Not tested
........"""
        logging.info('in payson')
        SellerEmail = 'niklas....@gmail.com'
        Cost = 10
        ExtraCost=0
        GuaranteeOffered=2
        OkUrl = self.request.host+'/payson_okurl' # TO DO
        text = SellerEmail + ':' + str(Cost) + ':' + str(ExtraCost) + ':' + OkUrl + ':' + str(GuaranteeOffered) + Key
        logging.info('mdtext5: '+text)
        m = hashlib.md5()
        Generated_MD5_Hash_Value = hashlib.md5(text).hexdigest()
        AgentID = 11366

        strYourSecretKey = "3190fb33-6152-4052-b95a-379b430de6b6";
        strOkURL = self.request.GET.get('OkURL')
        strRefNr = self.request.GET.get('RefNr')
        strPaysonRef = self.request.GET.get('Paysonref')

        strTestMD5String = strOkURL + strPaysonRef + strYourSecretKey
        strMD5Hash = hashlib.md5(strTestMD5String).hexdigest()

        logging.info('testing MD5 value')
        if strMD5Hash == self.request.GET.get('MD5'):
            logging.info('Korrekt anrop från Payson')
            logging.info('Rätt!')
            logging.info('OkUrl: ') + strOkURL
            logging.info('RefNr: ') + strRefNr
            logging.info('PaysonRef: ') + strPaysonRef
        else:
            #Felaktigt anrop från någon annan.
            logging.info("Felaktig MD5-summa!")


texts:
I need the ability to generate random MAC addresses, so I wrote up a little function that does that:
>>> random_mac()
'7C:93:B7:AF:BA:AE'
>>> random_mac()
'D8:D8:A0:D4:A5:3F'
>>> random_mac(unicast=False, universal=True)
'55:47:C6:EE:C6:2B'
>>> random_mac(unicast=True, universal=False)
'FE:A1:4B:98:76:B6'

I decided to allow the user to pick if it's unicast/multicast and universally/locally administered; even though I'll only need unicast/universal. This caused me headaches though because I'm still not great at dealing with bits. The LSB of the first octet indicates uni/multicast, and the second LSB of the octet indicates universal/local, so these bits can't be random.
After playing around with a few failed ideas (generating all random bits, then "fixing" the two bits later), I finally decided to generate a random number between 0 and 63 inclusive, left shift it twice, than add the two bits on after. It works, but it's ugly and looks suboptimal.
It's not a lot of code, but I'd like a few things reviewed:

Is there a better approach? It feels hacky generating it as two pieces then adding them together. I tried explicitly setting the bits, but the code to decide between |, and & and ~ got messier than what I have now, so I went with this way.
The number constants are bugging me too. The numbers kind of sit on a border of self-explanatory and magic, so I decided to name them to be safe. LAST_SIX_BITS_VALUE feels off though.
Is treating a boolean value as a number during bitwise operation idiomatic? Is it clear as I have it now?
Attaching the first octet to the rest is suboptimal as well. Speed isn't a huge concern, but I'm curious if there's a cleaner way that I'm missing.

from random import randint, randrange

N_MAC_OCTETS = 6
OCTET_VALUE = 256
LAST_SIX_BITS_VALUE = 63

def random_mac(unicast: bool = True, universal: bool = True) -> str:
    least_two_bits = (not unicast) + ((not universal) << 1)
    first_octet = least_two_bits + (randint(0, LAST_SIX_BITS_VALUE) << 2)
    octets = [first_octet] + [randrange(OCTET_VALUE) for _ in range(N_MAC_OCTETS - 1)]
    return ":".join(f"{octet:02X}" for octet in octets)

Examples of the bits for the first octet for different inputs:
def display(mac):
    print(mac, f"{int(mac.split(':')[0], 16):08b}")

# Unicast, Universal
>>> display(random_mac(True, True))
04:27:DE:9A:1B:D7 00000100  # Ends with 0,0

# Unicast, Local
>>> display(random_mac(True, False))
72:FB:49:43:D5:F2 01110010  # 1,0

# Multicast, Universal
>>> display(random_mac(False, True))
7D:BF:03:4E:E5:2A 01111101  # 0,1

# Multicast, Local
>>> display(random_mac(False, False))
2F:73:52:12:8C:50 00101111  # 1,1


texts: Fluid tag for displaying GitHub Gists with noscript tags in a Jekyll post

texts:
A while back I wrote a Fluid tag for Jekyll that inserts the contents of a GitHub Gist into the content of the page in  tags for RSS readers. I've noticed a couple things I'm not happy with since posting it, but I am interested in the critique it will generate here on Stack Exchange!

(Obviously, some of the internals regarding methods required to make Liquid tags work (such as the parameters to initialize and having a render method) aren't negotiable, but you get the idea.)

require 'digest/md5'
require 'net/https'
require 'uri'

module Jekyll
  class GistTag < Liquid::Tag
    def initialize(tag_name, text, token)
      super
      @text         = text
      @cache        = true
      @cache_folder = File.expand_path "../_gist_cache", File.dirname(__FILE__)
    end

    def render(context)
      return "" unless @text =~ /([\d]*) (.*)/

      gist, file = $1.strip, $2.strip
      script_url = "https://gist.github.com/#{gist}.js?file=#{file}"

      code       = get_cached_gist(gist, file) || get_gist_from_web(gist, file)
      code       = code.gsub "<", "&lt;"
      string     = ""
      string    += "
#{code}
"
      return string
    end

    def get_gist_url_for(gist, file)
      "https://gist.github.com/raw/#{gist}/#{file}"
    end

    def cache_gist(gist, file, data)
      file = get_cache_file_for gist, file
      File.open(file, "w+") do |f|
        f.write(data)
      end
    end

    def get_cached_gist(gist, file)
      return nil if @cache == false
      file = get_cache_file_for gist, file
      return nil unless File.exist?(file)
      return File.new(file).read
    end

    def get_cache_file_for(gist, file)
      bad_chars = /[^a-zA-Z0-9\-_\.]/
      gist      = gist.gsub bad_chars, ''
      file      = file.gsub bad_chars, ''
      md5       = Digest::MD5.hexdigest "#{gist}-#{file}"
      File.join @cache_folder, "#{gist}-#{file}-#{md5}.cache"
    end

    def get_gist_from_web(gist, file)
      gist_url          = get_gist_url_for(gist, file)
      raw_uri           = URI.parse(gist_url)
      https             = Net::HTTP.new(raw_uri.host, raw_uri.port)
      https.use_ssl     = true
      https.verify_mode = OpenSSL::SSL::VERIFY_NONE
      request           = Net::HTTP::Get.new(raw_uri.request_uri)
      data              = https.request(request)
      data              = data.body
      cache_gist(gist, file, data) unless @cache == false
      data
    end
  end

  class GistTagNoCache < GistTag
    def initialize(tag_name, text, token)
      super
      @cache = false
    end
  end
end

Liquid::Template.register_tag('gist', Jekyll::GistTag)
Liquid::Template.register_tag('gistnocache', Jekyll::GistTagNoCache)


texts: Using matlabpool: Is my embedding correct?

texts:
A general question: For using matlabpool, I write the line

matlabpool open local 12;

as the first line in my code and the line:

matlabpool close;

as the last. Is this correct?


texts: Write a function named isSuper that returns 1 if its array argument is a isSuper array, otherwise it returns 0

texts:
An Super array is defined to be an array in which each element is greater than sum of all elements before that.

For example:

{2, 3, 6, 13} is a Super array. (2 < 3, 2+3 < 6, 2 + 3 + 6 < 13)
{2, 3, 5, 11} is a NOT a Super array. 2 + 3 < 5 is false.

I wrote following code to find the array is Super Array or not .

public class SuperArray {
    public static void main(String args[]) {
         System.out.println("The result is: " + isSupper(new int[] {2, 3, 6, 13}));
         System.out.println("The result is: " + isSupper(new int[] {2, 3, 5, 11}));
    }
    public static int isSupper(int[] a){
        int result = 0;
        int sum = 0;
        int nextValue = 0;
        for(int i = 0; i < a.length; i++) {
            nextValue = a[i];
            if(nextValue > sum) {
                result = 1;
            } else {
                result = 0;
                break;
            }
            System.out.println("sum is: " + sum);
            System.out.println("next Value is: " + nextValue);
            sum += a[i];
        }
        return result;
    }
}

Is this a good way to find Super array? First a assign sum = 0 and check that sum to first number of an array and so on.


texts: PHP session_set_saver_handler with session timeout

texts:
I have developed a class that utilises the session_set_saver_handler function so I can store sessions within my DB. The class works just as I would like.

However, my only concern is the way I have approached the session timeout.

Current the _read() function code looks like:

/**
     * Read session function
     * @access public
     * @return the 'data' record providinf the PDO statement executed correctly. Otherwise, return false.
     */
    public function _read($id)
    {

        $timeout = time() - $this->accessTime;
        $locked  = false;

        $this->database->query('SELECT updatedTime, data FROM sessions WHERE session = :id AND locked = :locked');
        $this->database->bind(':id', $id);
        $this->database->bind(':locked', $locked);

        if($this->database->execute())
        {
            if($this->database->rowCount() > 0)
            {
                $row = $this->database->singleResult();

                if($row['updatedTime'] < $timeout)
                {

                    //Set the location of the user.
                    $url = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

                    if($url != $this->redirectUrl)
                    {
                        header('Location: ' . $this->redirectUrl);
                        return;
                    }

                    return '';
                }

                return $row['data'];
            }
        }

        return '';
    }

When I originally create the script I hard coded the redirect URL. The problem was logout.php (the file the user is redirected to) contains the session class. Meaning I have a constant loop. So I approached it by implementing the following:

if($row['updatedTime'] < $timeout)
                {

                    //Set the location of the user.
                    $url = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

                    if($url != $this->redirectUrl)
                    {
                        header('Location: ' . $this->redirectUrl);
                        return;
                    }

                    return '';
                }

This seems to me more of a 'hack' than intelligent code.

Did I approach this correct (probably not)? If not, what would be a more intelligent work around?


texts: Reading a CSV file containing a dataset of 8×8 images

texts:
I am trying to implement a machine learning algorithm (k-nn for example).  But before I attempt to do that I was hoping for some feedback on my current Main class, which essentially builds 8×8-pixel matrices into an array to be manipulated later. (See the data description and sample dataset.)

import java.util.*;
import java.io.*;

public class Main {

    static class Data {

        int[] dataSet;
        int classCode;

        public Data(int[] dataSet, int label) {
            this.dataSet = dataSet;
            this.classCode = label;
        }

        @Override
        public String toString() {
            return "Class Code: " + classCode + " DataSet:" + Arrays.toString(dataSet) + "\n";
        }

    }

    ArrayList<Data> dataSetList;
    int[][] dataArray = new int[2810][65];

    private void readFile(String csvFile) {
        int instances = 0;
        dataSetList = new ArrayList<>();
        try {
            Scanner scan = new Scanner(new BufferedReader(new FileReader(csvFile)));
            while (scan.hasNext()) {
                String line = scan.next();
                String[] extractedDataFromFile = line.split(",");
                for (int i = 0; i < extractedDataFromFile.length; i++) {
                    dataArray[instances][i] = Integer.parseInt(extractedDataFromFile[i]);
                }
                dataSetList.add(new Data(dataArray[instances], dataArray[instances][extractedDataFromFile.length - 1]));
                instances++;
            }
            System.out.println(dataSetList.toString());
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.readFile("dataset1.csv");
    }

}

This is my first time experimenting with machine learning and any feedback on my current approach as well as an algorithm to look at beyond this would be hugely appreciated.


texts:
I have this code and at the end of it, FastMM shows that there were memory leaks with all the objects of TSinc:

unit sinc_int;

interface

uses
  Classes,
  log_listener_list_int,
  tick_listener_list_int;

type
  ISinc = interface;

  ISincList = interface;

  ISinc = interface ['{53814230-6308-4259-99FF-6054F2C91F9C}']
  function Execute: Boolean;
  function SincList: ISincList;
  function Log: string;
  procedure AddLog(const Texto: string);
  function LogListenerList: ILogListenerList;
  function TickListenerList: ITickListenerList;
  function SincIntervaloMili: Integer;
  function EstaSincronizando: Boolean;
  procedure Start;
  procedure Stop;
  end;

  ISincList = interface ['{F3355798-4584-4DCE-8EBA-3692B14FA132}']
  function Add(const Item: ISinc): Integer;
  function Count: Integer;
  function Get(const Index: Integer): ISinc;
  procedure Put(const Index: Integer; Item: ISinc);
  procedure Remove(const Item: ISinc);
  procedure Clear;
  procedure Start;
  procedure Stop;
  end;

implementation

end.

unit sinc_class;

interface

uses
  sinc_int, log_listener_list_int, tick_listener_list_int, sinc_thread_class;

type
  TSinc = class (TInterfacedObject, ISinc)
  protected
    FLog: string;
    FSincList: ISincList;
    FLogListenerList: ILogListenerList;
    FTickListenerList: ITickListenerList;
    FSincIntervaloMili: Integer;
    FEstaSincronizando: Boolean;
    FThread: TSincThread;
  public
    constructor Create; virtual;
    destructor Destroy; override;
    function Execute: Boolean; virtual; abstract;
    function SincList: ISincList;
    function Log: string; virtual;
    procedure AddLog(const Texto: string);
    function LogListenerList: ILogListenerList;
    function TickListenerList: ITickListenerList;
    function SincIntervaloMili: Integer;
    function EstaSincronizando: Boolean;
    procedure Start;
    procedure Stop;
  end;

implementation

uses
  sinc_list_class,
  log_listener_list_class,
  tick_listener_list_class;

{ TSinc }

procedure TSinc.AddLog(const Texto: string);
begin
  FLogListenerList.AddLog(Texto);
  FLog:=FLog+Texto;
end;

constructor TSinc.Create;
begin
  FSincList:=TSincList.Create;
  FLogListenerList:=TLogListenerList.Create;
  FTickListenerList:=TTickListenerList.Create;
  FEstaSincronizando:=False;
  FThread:=TSincThread.Create(Self);
end;

destructor TSinc.Destroy;
begin
  FSincList.Clear;
  FSincList:=nil;
  FLogListenerList.Clear;
  FLogListenerList:=nil;
  FTickListenerList.Clear;
  FTickListenerList:=nil;
  FThread.Free;
  inherited;
end;

function TSinc.EstaSincronizando: Boolean;
begin
  Result:=FEstaSincronizando;
end;

function TSinc.Log: string;
begin
  Result:=FLog;
end;

function TSinc.LogListenerList: ILogListenerList;
begin
  Result:=FLogListenerList;
end;

function TSinc.SincIntervaloMili: Integer;
begin
  Result:=FSincIntervaloMili;
end;

function TSinc.SincList: ISincList;
begin
  Result:=FSincList;
end;

procedure TSinc.Start;
begin
  FEstaSincronizando:=True;
  FSincList.Start;
  FThread.Resume;
end;

procedure TSinc.Stop;
begin
  FThread.Suspend;
  FSincList.Stop;
  FEstaSincronizando:=False;
end;

function TSinc.TickListenerList: ITickListenerList;
begin
  Result:=FTickListenerList;
end;

end.

And when I do this:

procedure TForm2.btnSinc1Click(Sender: TObject);
begin
  SincTest:=TSincTest.New;
  SincTest:=nil;
end;

It shows that there were memory leaks with the TSincTest class, its lists and even the thread.


texts: Minimum amount of spaces inserted in a given string, such that it gets composed only of elements from a given list

texts:
The Challenge

  Given a big string and a list of smaller strings, find the minimum amount of spaces that must be inserted between characters of the string in such way that it becomes composed only of elements from the list of smaller strings. (and which are the respective elements used). [Python 3]

For instance, if you had as a string: 'foobarpy' and as a list: ['foo', 'bar', 'py', 'foob', 'arpy'], the optimal solution would be: foob arpy, requiring you to insert only a single space in the string.

Basically:

-The "big string" must be "transformed" into a combination of elements from the list, only by inserting spaces in between characters of it (with the least amount of spaces as possible)

-Elements can't be repeated

-Not all the elements must be used

# Sample input
big_string = '3141592653589793238462643383279'
small_strings = ['3', '314', '49', '9001', '15926535897', '14', '9323', '8462643383279', '4', '793', '3141592653589793238462643383278', '314159265358979','3238462643383279']

My Solution

As I see it, instead of trying to "slice" the given string, it's easier to try to combine the elements from the list and look for the match with the least elements.
My full code: https://repl.it/@LucasWerner/String-Least-Spacing

Get rid of elements in the list that don't appear in the string.

# Required modules
import itertools
import numpy as np

small_strings = [x for x in small_strings if x in big_string]

Combine elements in groups of sizes from 1 to the length of the list (just gathering  to whole thing together) and check whether the combination has the same length as the given string... that would select fewer possibilites to further analyze. Store the possibilites as a list of tuples.

possibilites = list()
for k in range(1, len(small_strings)): #k is the size of the combination
  c = list(itertools.combinations(small_strings, k))
  combinations =  [x for x in c if sum(len(i) for i in x) == big_string_len]
  possibilites.extend(combinations)

Permutate the tuples inside the list to see if they match the big_string. If so, store the permutated tuple in a list of matches.

matches = list()
for tup in possibilites:
  p = list(itertools.permutations(tup))
  permutations = [x for x in p if ''.join(x) == big_string]
  matches.extend(permutations)

Bind the matches with their lengths in a dictionary

sizes = dict()
for tup in matches:
  sizes[tup] = len(tup)

Finding the optimal solution (minimal length and where it occurres)

min_key = min(sizes, key=sizes.get)
min_val = sizes[min_key]

Giving the optimal solution

print('Best solution is', ' '.join(min_key), 'with', min_val - 1, 'space(s)')

Which in this case would print:

  Best solution is 314159265358979 3238462643383279 with 1 space(s)

It's my first month learning Python and I was really hoping to get some feedback and tips from far more experient programmers about what I could change/learn/improve in the code to make it better/more efficient.


texts: Lowering speed on my hybride encryption function for large files

texts:
I have an assignment to encrypt files (+- 1 gb) and speed is an important factor. I am also kinda forced to the C# language since nobody in my group knows C++. The time now recorded for 100 mb is 12 seconds could somebody give me advice if it is possible to improve the speed my encryption function below.

private void buttonSearch_Click(object sender, RoutedEventArgs e)
{
    if (fileSelected && fileDestination)
    {
        String key = AESEncrypt.GenerateKey();
        progressBar.Visibility = Visibility.Visible;
        try
        {
            // AES Encrypt the file
            AESEncrypt.EncryptFile(textBoxSelectFile.Text, textBoxDestinationFile.Text, key,login.PrivateKey, progressBar);

            SecurityDB.Login loginB = (SecurityDB.Login)loginDataGrid.SelectedItem;
            byte[] Storekey = RSAEncrypt.EncryptKey(loginB.PublicKey, key);
            AESEncrypt.CreateKey(Storekey, this.textBoxDestinationFile.Text+"\\");

            // Writing PublicKey in destination Folder
            using (StreamWriter writer = new StreamWriter(this.textBoxDestinationFile.Text + "\\publicKey.txt"))
            {
                writer.WriteLine(loginB.PublicKey);
            }

        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message);
        }
    }
    else
    {
        System.Windows.MessageBox.Show("Select Folders");
    }
}

public static async void EncryptFile(string inputFile, string outputFile, string sKey, String privateKey, ProgressBar progress)
{
    String fileName = inputFile;
    fileName = "\\" + fileName.Split('\\').Last();
    var progres = new Progress<int>(value => progress.Value = value);
    UnicodeEncoding UE = new UnicodeEncoding();

    await Task.Run(async () =>
        {
            byte[] key = UE.GetBytes(sKey);

            FileStream fsCrypt = new FileStream(outputFile + fileName, FileMode.Create);

            RijndaelManaged RMCrypto = new RijndaelManaged();

            CryptoStream cs = new CryptoStream(fsCrypt,
                        RMCrypto.CreateEncryptor(key, key),
                        CryptoStreamMode.Write);

            FileStream fsIn = new FileStream(inputFile, FileMode.Open);

            int data;
            byte[] buffer = new byte[0x1000];
            double i = 0;

            while ((data = await fsIn.ReadAsync(buffer, 0, buffer.Length)) > 0)
            {
                cs.Write(buffer, 0, buffer.Length);
                i += buffer.Length;
                number = (int)(i / fsIn.Length * 100);
                ((IProgress<int>)progres).Report(number);
            }
            fsIn.Close();
            cs.Close();
            fsCrypt.Close();

            byte[] hash = Hashing.HashFile(outputFile + fileName, privateKey);
            File.WriteAllBytes(outputFile + "\\Hashing.txt", hash);
        });
}


texts: Executing remote command using expect from C++

texts:
I wrote some code to execute remote commands over ssh, using expect, from c++. The code works but is a bit of a mess of c / c++ since there doesn't seem to be an idiomatic way to achieve much of what I wanted in pure c++. I appreciate that there are nominally some security concerns with the way I'm using passwords, but these aren't a concern for my use cases.

remote_commmand.h

#pragma once

#include <stdexcept>

struct RemoteException : public std::runtime_error {
    using std::runtime_error::runtime_error;
};

void remote_command(const std::string &host, const std::string &user, const std::string &password, const std::string &cmd);

remote_command.cpp

#include "remote_command.h"
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <fstream>
#include <vector>

using std::string;

namespace {

const char* expect_template =
"set timeout 60\n"
"spawn ssh %s@%s %s\n"
"expect {\n"
"   \"*yes/no*\"\n"
"   {\n"
"       send \"yes\\r\"\n"
"       exp_continue\n"
"   }\n"
"   \"*?assword:*\"\n"
"   {\n"
"       send -- \"%s\\r\"\n"
"       send -- \"\\r\"\n"
"       expect eof\n"
"   }\n"
"}\n";

class TempFile {

public:
    explicit TempFile(const char* contents){
        file_name = std::tmpnam(nullptr);
        std::ofstream f(file_name.c_str(), std::ios::out);
        if(!f.write(contents, std::strlen(contents))){
            throw std::runtime_error("ofstream");
        }
    }

    ~TempFile(){
        std::remove(file_name.c_str());
    }

    TempFile(TempFile &other) = delete;
    TempFile& operator=(TempFile &other) = delete;

    std::string file_name;
};

}

void remote_command(const string &host, const string &user, const string &password, const string &cmd){
    std::vector<char> formatted_cmd;
    const std::size_t formatted_size = std::strlen(expect_template) + host.size() + user.size() + password.size() + cmd.size();
    formatted_cmd.resize(formatted_size);

    const std::size_t res = std::snprintf(&formatted_cmd[0], formatted_size, expect_template, user.c_str(), host.c_str(), cmd.c_str(), password.c_str());

    if (res <= 0 || res >= formatted_size ){
        throw RemoteException("infsufficient size for snprintf");
    }

    TempFile tempfile(&formatted_cmd[0]);

    int r = execl("/usr/bin/expect", "-f", tempfile.file_name.c_str(), (char *)0);
    if (r == -1){
        throw RemoteException(string("execl") + std::strerror(errno) );
    }
}

example usage

remote_command("my-host", "user", "pw", "/path/to/my/script.sh");


texts: Dictionary synonym lookup via networking

texts:
I have a small TCP service running on port 4444 which, given a word, will look up synonyms in a dictionary. Below is my Scala code for connecting to the socket, sending the lookup command and parsing the response. If the word exists, then the last line of the response from the service will contain a string with 200 as the status code, otherwise it will return 404.

How can I make this code easier to read and more idiomatic?

private def lookupWord(word: String): Option[String] = {
        val socket = new Socket(InetAddress.getByName("localhost"), 4444)
        val out = new PrintStream(socket.getOutputStream)
        val reader = new BufferedReader(new InputStreamReader(socket.getInputStream, "utf8"))
        out.println("LOOKUP "  + word)
        out.flush()

        var curr = reader.readLine()
        var response = ""
        while(!curr.contains("200") && !curr.contains("404")) {
          response += curr + "\n"
          curr = reader.readLine()
        }
        socket.close()
        curr match {
          case code if code.contains("200") => {
            Some(response)
          }
          case _ => None
        }
      }


texts: Bitcoin wallet address and private key generator

texts:
I wanted to learn how to create a Bitcoin wallet in code. I used as reference this guide which has code examples in JavaScript.

I wrote my implementation in Python. Here is the resulting code:

#!/usr/bin/env python

'''
Creates BitCoin Wallet complaint credentials:
- Public Key
- Private Key
- Private Key (Wallet Import Format)
'''

import hashlib
import base58
import ecdsa

from ecdsa.keys import SigningKey
from utilitybelt import dev_random_entropy
from binascii import hexlify, unhexlify

def random_secret_exponent(curve_order):
    while True:
        random_hex = hexlify(dev_random_entropy(32))
        random_int = int(random_hex, 16)
        if random_int >= 1 and random_int < curve_order:
            return random_int

def generate_private_key():
    curve = ecdsa.curves.SECP256k1
    se = random_secret_exponent(curve.order)
    from_secret_exponent = ecdsa.keys.SigningKey.from_secret_exponent
    return hexlify(from_secret_exponent(se, curve, hashlib.sha256).to_string())

def generate_public_key(private_key_hex):
    hash160 = ripe_hash(private_key_hex)
    public_key_and_version_hex = b"04" + hash160
    checksum = double_hash(public_key_and_version_hex)[:4]
    return base58.b58encode(public_key_and_version_hex + checksum)

def ripe_hash(key):
    ret = hashlib.new('ripemd160')
    ret.update(hashlib.sha256(key).digest())
    return ret.digest()

def double_hash(key):
    return hashlib.sha256(hashlib.sha256(key).digest()).digest()

def generate_private_key_wif(private_key_hex):
    private_key_and_version = b"80" + private_key_hex
    checksum = double_hash(private_key_and_version)[:8]
    hashed = private_key_and_version + checksum
    return base58.b58encode(private_key_and_version + checksum)

def main():
    private_key_hex = generate_private_key()
    public_key_hex = generate_public_key(private_key_hex)
    private_key_wif_hex = generate_private_key_wif(private_key_hex)
    print("Private Key: " + private_key_hex)
    print("Public Key: " + public_key_hex)
    print("Private Key (WIF Format): " + private_key_wif_hex)

if __name__ == '__main__':
    main()

How to run:

Private Key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Public Key: 2Uc973e5adf5867512dd7a21638810bd53422
Private Key (WIF Format): xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

I have my concerns about the correctness of the generated keys, as well as for the private key in WIF format. In theory it should be a short string.


texts:
I tend to be rather prolific in my sharing of things I find online. I'm interested in tracking my own habits to make them more effective. Therefore, I submit the above to be critiqued by the lot of you. Have at it.

import argparse
from backports.lzma import LZMAFile
import csv
import datetime
import time
import tweepy

parser = argparse.ArgumentParser(description='Links report on twitter -- some basic metrics as to how many links I shared today')
parser.add_argument('API_KEY', action='store', metavar='API_KEY', help='Twitter API key')
parser.add_argument('API_SECRET', action='store', metavar='API_SECRET', help='Twitter API secret')
parser.add_argument('ACCESS_TOKEN', action='store', metavar='ACCESS_TOKEN', help='Twitter access token')
parser.add_argument('ACCESS_SECRET', action='store', metavar='ACCESS_SECRET', help='Twitter access secret')
parsed = parser.parse_args()

auth = tweepy.OAuthHandler(parsed.API_KEY, parsed.API_SECRET)
auth.set_access_token(parsed.ACCESS_TOKEN, parsed.ACCESS_SECRET)
api = tweepy.API(auth)

tweets = []

today = datetime.datetime.today() - datetime.timedelta(hours=24)
today.replace(hour=0, minute=0, second=0, microsecond=0)
today = today.timetuple()

def links_today(link):
    date_of_link = time.localtime(long(link[0]))
    return today < date_of_link

with LZMAFile('/home/ec2-user/public_html/links.csv.xz') as fin:
    reader = csv.reader(fin.readlines()[1:])
    tweets = filter(links_today, reader)

status = 'In the last 24 hours, I sent {0} links to {1} unique recipients.'.format(len(tweets[1]), len(set(tweets[2])))

if len(tweets) != 0:
    api.update_status(status=status)


texts: Printing 1,000,000 numbers in 1 sec. in Python

texts:
Here's a fairly simple task from CSES Problem Set - Permutations 1070 that reads:

A permutation of integers 1,2, …, n is called beautiful if there are no adjacent elements whose difference is 1.
Given n, construct a beautiful permutation if such a permutation exist

The constraints are pretty tight:

Time limit: 1.00 s
Memory limit: 512 MB
1 ≤ n ≤ 10^6

Here's the code:
n = int(input())
if n == 2 or n == 3:
    print("NO SOLUTION")
elif n == 1:
    print(1)
elif n == 4:
    print("3 1 4 2")
else:
    for i in range(1, n + 1, 2):
        print(str(i) + " ", end=" ")
    for i in range(2, n + 1, 2):
        print(str(i) + " ", end=" ")

It passes all tests except for n = 1000000. For that test it takes 15 sec. on my machine. The code is in Python 3.8
The question is, what can can be improved in terms of printing the numbers?


texts: Array of immutable objects initialized at compile-time

texts:
I have a class that contains defines 'magic' numbers at compile time such as basic array sizes, fixed ip address, etc. so that I have one place to edit if changes are required.

In this nested class I need to define tuples of maximum and minimum values that correspond to each of 4 bands of an IR camera.  I'd like to use the data like this (for readability):

int x = lutBounds[3].min;

Is my code below considered 'good practice'?  If not, why, and what would be better.  I'm completely self-taught in Java but try to use 'best practices' when I can recognize them.

/**
 * LUTBounds holds a band datum for the upper and lower bounds of interest.
 * @author programmer
 *
 */
 static class LUTBounds {
    final int   min;
    final int   max;

    LUTBounds(final int min, final int max) {
        this.min = min;
        this.max = max;

    }

}

// usage: int x = lutBounds[3].min;
final static LUTBounds[]    lutBounds   = { new LUTBounds(14_123, 30_123),
        new LUTBounds(14_922, 40_123), new LUTBounds(14_815, 41_123),
        new LUTBounds(14_300, 40_123) };


texts:
So I was trying to do this exercise from Tour of Go. I managed to get it working. I am not at all sure that it is correctly concurrent or idiomatic (I started learning Go, like, 4 hours ago).

I would really appreciate feedback about my solution. Here's the relevant meat of the code. Full code available below.

type urlToFetch struct {
  Url   string
  Depth int
}

// Group stuff together, so that it's easier to pass around.
type fetchContext struct {
  Queue   chan urlToFetch
  History map[string]int
  Quit    chan int
  Fetcher Fetcher
}

func Crawl(url string, depth int, fetcher Fetcher) {
  context := fetchContext{
    Queue:   make(chan urlToFetch, 500),
    History: make(map[string]int),
    Quit:    make(chan int, 50),
    Fetcher: fetcher,
  }

  go fetchOne(&context)
  context.Queue <- urlToFetch{url, depth}

  <-context.Quit
}

func fetchOne(ctx *fetchContext) {
  timeout := time.After(2000 * time.Millisecond)

  select {
  case utf := <-ctx.Queue:
    if utf.Depth > 0 {
      body, urls, err := ctx.Fetcher.Fetch(utf.Url)
      ctx.History[utf.Url] = 1

      if err != nil {
        fmt.Println(err)
        return
      }
      fmt.Printf("found: %s %q\n", utf.Url, body)

      for _, u := range urls {
        go fetchOne(ctx)
        if _, ok := ctx.History[u]; !ok {
          ctx.Queue <- urlToFetch{u, utf.Depth - 1}
        } else {
        }
      }
    }
  case <-timeout:
    ctx.Quit <- 1
  }
}

The full source is at: http://pastie.org/8443147


texts:
I wrote this pretty simple program (it's an exercise from a book). It counts the words in a simple string. The book is a very old one (I think it's from 2003) and uses char arrays. Because of this, I don't know if this solution is a proper one or not.

Can you tell me whether it is okay or not?

#include <iostream>

int main()
{
    int count_words(std::string);

    std::string input_text;
    std::cout<< "Enter a text: ";
    std::getline(std::cin,input_text);

    std::cout << "Number of words: " << count_words(input_text) << std::endl;
    return 0;
}
int count_words(std::string input_text)
{
    int number_of_words = 1;
    for(int i = 0; i < input_text.length();i++)
        if(input_text[i] == ' ')
            number_of_words++;
    return number_of_words;
}


texts:
I don't know what this problem is named, so I can't Google for a solution about it. Here's the image:

There are three pitchers with capacities of 10, 7 and 3 quarts.

We need to move the water from a pitcher (or jar) to another pitcher so it will result in 5, 5 and 0.

I have to print all the steps needed to make the pitchers contains 5, 5 and 0 quarts of water.

Here's my working code. Please review it and tell me how to make it better, faster, shorter, more readable.

class Jar
  attr_accessor :max, :current, :target

  def initialize max, current, target
    @max = max
    @current = current
    @target = target
    raise 'max should not be 0' if max == 0
  end

  def full?
    return @current == @max
  end

  def empty?
    return @current == 0
  end

  def overflow
    return 0 if @current < @max
    over = @current - @max;
    @current = max
    return over
  end

  def move_to o
    o.current += @current
    @current = o.overflow
  end

end

class Quartz
  MAX_STEPS = 12

  def initialize max, init, target
    raise 'max.length must equal init.length' if max.length != init.length
    raise 'max.length must equal target.length' if max.length != target.length
    @ite = (0..(max.length-1))
    @memoize = {}
    @targets = []
    @steps = []
    @all_solutions = []
    @jars = @ite.collect { |x| Jar.new(max[x],init[x],target[x]) }
    @targets = current(:target)
  end

  def recurse step=1
    orig = current
    @steps << orig
    if orig == @targets
      p @steps
      return @steps.length
    end
    return false if step>=MAX_STEPS

    @memoize[orig] = step

    @jars.each do |x|
      next if x.empty?
      @jars.each do |y|
        next if x == y
        next if y.full?
        x.move_to y
        done = @memoize[current]
        if done
          restore orig
          next
        end
        ok = recurse(step+1)
        #return ok if ok # return only first solution
        @steps.pop
        restore orig
      end
    end

    return false
  end

  def current attr=:current
    @jars.collect{ |x| x.send attr }
  end

  alias_method :to_array, :current

  def restore a
    @ite.each { |i| @jars[i].current = a[i] }
  end

end

q = Quartz.new [10,7,3], [10,0,0], [5,5,0]
p q.recurse

This is the program's output:

[[10, 0, 0], [3, 7, 0], [3, 4, 3], [6, 4, 0], [6, 1, 3],
 [9, 1, 0], [9, 0, 1], [2, 7, 1], [2, 5, 3], [5, 5, 0]]


texts:
I've created my first jQuery plugin, so please try to understand :)

My plugin code looks like so:

(function($) {
$.fn.ajaxSelect = function(options) {
    var $this = this;
    //options
    var settings = $.extend({}, defaults, options);
    //disable select
    if ($.ui.selectmenu && settings.selectmenu && settings.disableOnLoad) {
        $this.selectmenu('disable');
    }
    //ajax call
    $.ajax({
        type: settings.type,
        contentType: settings.contentType,
        url: settings.url,
        dataType: settings.dataType,
        data: settings.data
    }).done(function(data) {
        var n = data.d || data;
        var list = "";
        $.each(n, function(i) {
            list += '<option value=' + n[i].Id + '>' + n[i].Nazwa + '</option>';
        });
        $this.filter("select").each(function() {
            $(this).empty();
            $(this).append(list);
            if ($.ui.selectmenu && settings.selectmenu) {
                $this.selectmenu();
            }
        });
        settings.success.call(this);
    }).fail(function() {
        settings.error.call(this);
    });

    return this;
};

var defaults = {
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: '/echo/json/',
    dataType: 'json',
    data: null,
    async: true,
    selectmenu: true,
    disableOnLoad: true,
    success: function() {},
    error: function() {}
};
})(jQuery);

Demo of usage is available at http://jsfiddle.net/Misiu/ncWEw/

What I was trying to accomplish:

Select multiple elements at one time
Filter only selects from selected items (in case selector would select other elemnts)
Makes only ONE request to server
First build option string and then append it instead of adding items in loop
Specify 2 callbacks: one for error and second for success

I think that it would be better to use more of deferred objects, but I don't have idea how.
Any improvements and hints are welcome :)


texts: Making the font as big as possible without overflowing each div

texts:
I made a function that makes font sizes in
s as big as possible without overflowing. It takes a long time to run. How do I optimize this?

$(document).ready(() => {
  $('.text-fit').each((index, element) => {
    let currentElement = $(element);
    let fontSize = 999;
    currentElement.wrapInner("

");
    while (currentElement.find('.wrapper').innerHeight() > currentElement.innerHeight()) {
      fontSize -= 1;
      currentElement.css('font-size', fontSize + 'px');
    }
  });
});


texts: An attempt at a Haskell Servant API - repetition of Left/Right case matching

texts:
I'm attempting to learn more about Haskell by completing a "hobby" project - a simple API to save/retrieve content for pages - used with Hakyll to generate static sites.

I have got something working for the tasks of retrieving all of the content for a site, and for adding a new page to a site. Hooray!

However, the code suffers from extraordinary verbosity.  I suspect I could improve things by bringing in some kind of monad transformer to deal with the IO (Either String ()), but I am not familiar enough with monad transformers to even be able to work out where to start.

siteServer :: Server SiteAPI
siteServer = site :<|> addPage
    where
          site :: Int -> Handler Site
          site i = do
              s <- liftIO $ loadSite i
              case s of
                  Left err -> throwError err404 { errBody = "Site not found!" `BS.append` (BS.pack err) }
                  Right s' -> return s'

          addPage :: Int -> Page -> Handler ()
          addPage i p = do
              s <- liftIO $ savePage i p
              case s of
                Left err -> throwError err404 { errBody = "Site not found!" `BS.append` (BS.pack err) }
                Right _ -> return ()

          savePage :: Int -> Page -> IO (Either String ())
          savePage i p = do
              s <- loadSite i
              case s of
                Left err -> return $ Left err
                Right s' -> savePage' s' p

              where savePage' :: Site -> Page -> IO (Either String ())
                    savePage' (Site name pages) p = saveSite (Site name (p:pages))

                    saveSite :: Site -> IO (Either String ())
                    saveSite s = catch writeSiteToFile returnError
                              where --returnError :: IOException -> IO (Either String ())
                                    returnError e = return $ Left ("Failed to write to file: " ++ show i ++ ". " ++ show (e :: IOException))
                                    --writeSiteToFile :: IOException -> IO (Either String ())
                                    writeSiteToFile = Right <$> BS.writeFile (getSiteFilename i) (encode s)


texts: Find two numbers that sum closest to a given number

texts:
I'm working on the problem of finding 2 numbers that their sum is closest to a specific number. Input numbers are not sorted.

My major idea is to sort the numbers and find from two ends. I'm wondering if there are any better ideas in terms of algorithm time complexity. Any advice of code bug and code style is appreciated.

import sys
def find_closese_sum(numbers, target):
    start = 0
    end = len(numbers) - 1
    result = sys.maxint
    result_tuple = None
    while start < end:
        if numbers[start] + numbers[end] == target:
            print 0, (numbers[start], numbers[end])
            return
        elif numbers[start] + numbers[end] > target:
            if abs(numbers[start] + numbers[end] - target) < result:
                result = abs(numbers[start] + numbers[end] - target)
                result_tuple = (numbers[start], numbers[end])
            end -= 1
        else:
            if abs(numbers[start] + numbers[end] - target) < result:
                result = abs(numbers[start] + numbers[end] - target)
                result_tuple = (numbers[start], numbers[end])
            start += 1

    return result, result_tuple

if __name__ == "__main__":
    numbers = [2,1,4,7,8,10]
    target = 16
    numbers = sorted(numbers)
    print find_closese_sum(numbers, target)


texts: Conditional execution based on input string's prefix

texts:
I have this method that basically takes a string and does different things
depending on what the string starts with. Is there a cleaner way to write this method?

public String analyze(BotMessage message)
{

    String lcmsg = message.message().toLowerCase();
    //Not a command
    if(!lcmsg.startsWith("!")) return "-1";

    //Message from whatever
     if(lcmsg.startsWith("!ping")) return "pong!";
     if(lcmsg.startsWith("!tournament")) return tournament(message);

     //message from skype
     if(message.skype())
     {
         if(lcmsg.startsWith("!settournament")) return settournament(message);
         if(lcmsg.startsWith("!promote")) return promote(message);
         if(lcmsg.startsWith("!checkin")) return checkin(message);
         if(lcmsg.startsWith("!checkout")) return checkout(message);
         if(lcmsg.startsWith("!checkedin")) return checkedin(message);
         if(lcmsg.startsWith("!updatetournament")) return updatetournament();

     }

    return "-1";
}


texts: Consume rest endpoint removing payload's unwanted properties and falsy values

texts:
Let's suppose that there's a third part web service and I want to make a GET
request to it and use the response to feed my project's service.

Next code will allow me to create a dict object only with non-falsy keys' values:

import requests
from abc import ABC, abstractmethod

class AbstractPayload(dict, ABC):
    def __new__(cls, *args, **kwargs):
        """Validate: values are not empty and that each key in kwargs exists
        in cls.fields iterable, then it creates and returns the final dict
        instance using the field and the value as key-value pairs."""
        return {
            field: v for field, v in kwargs.items() if v and field in cls.fields
        }

    @property
    @abstractmethod
    def fields(cls):
        """Valid fields' iterable. Override this as you need."""
        pass

class UpdatePayload(AbstractPayload):
    fields = ('location', 'capacity', 'maxlatency', 'tags')

# Usage example:
response = requests.get('/thirdpart/device/189')
if response.ok:
    requests.patch('/mydevices/33', json=UpdatePayload(**response.json()))

Summary:

Avoiding unwanted fields being added to the endpoint patch payload.
Having a unique block of code (__new__ method) where the properties are
gonna be evaluated to discard falsy values.
Making it easily adaptable to all the api resources (just inheriting from
a class and defining a fields iterable)

Questions:

What do you think about this approach?
Do you have any suggestions to improve it?
Or even better, Do you have another cleaner approach?


texts:
I am making a permutation generator in c. Any ideas how I can make it faster?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
    char s[] = "abcdefghijklmnopqrstuvwxyz";
    int n = 8, c[n], i, l = strlen(s);
    char w[n];

    for(i = 0; i < n; i++){
        c[i] = 0;
        w[i] = '\0';
    }
    w[n] = '\0';
    while(c[0] < l){
        for(i = 0; i < n; i++){
            w[i] = *(s + c[i]);
        }
        printf("%s\n", w);
        c[n - 1] += 1;
        for(i = n - 1; i >= 0; i--){
            if(c[i] > l - 1 && i != 0){
                c[i] = 0;
                c[i - 1] += 1;
            }
        }
    }
}


texts:
I was recently going through some code that I wrote a while ago as an effort to improve my code.

There was one foreach statement that I was especially proud of the rewrite as I believe it is much more readable than it was before, and I believe it will last longer now.

This code in particular is simply a table body that has a check box (Basically a status check) and a plaintext "task" that was assigned to users stored in a database.

Here is the old code:

<?
    $taskuid = $tasks['uid'];
    $type    = "task";
    foreach($taskData as $key => $value) {
        echo "
";
        echo "  " . (($value['status'] == 1) ? "" : //Status complete
            "") . "  	"; //Status incomplete
        echo "$value[task]	";
        echo "
";
    }
?>

Here is the new code:

<?
    foreach($taskData as $key => $value) {
        echo "
";
        echo "  ";
        echo "      ";
        echo "          ";
        echo "      ";
        echo "  $value[task]	";
        echo "
";
    }
?>

While writing this, I realized the code actually has the same amount of lines, but there is (what I consider to be) a significant difference in the amount of symbols used (The old code being 752 characters and the new one being 564 characters That's nearly 200 characters!)

My question is this, what would you have done differently while rewriting this code? I'm very interested in the different ways code can be written, I know there are a lot of ways this simple task could be done.


texts: Compare / Join two object collections LINQ

texts:
I have two csv files that I need to compare and merge together. There is a 'big' list with many records and columns of data and a 'small' list of the desired records and some additional data. The ultimate goal is to output the records on the small list joined with the data in the big list.

The below code seems to make the correct selects, but I am unsure if I should be looking at using JOIN instead?

I like the cleanness of this solution in how it handles the CSV files in such few lines of code - let ... some.Split(',') - and haven't come up with as clean of a way in using JOIN.

string[] small = System.IO.File.ReadAllLines(@"I:\\" + Environment.UserName + "\\smallfile.csv");

string[] big = System.IO.File.ReadAllLines(@"J:\\DROPFOLDERS\\bigfile.csv");

IEnumerable<MBSGroup> queryMBSObjects =
from smallLine in small
let splitSmallLine = smallLine.Split(',')
from bigLine in big
let splitBigLine = bigLine.Split(',')
where ((splitSmallLine[0] == splitBigLine[0] && splitSmallLine[2] == splitBigLine[1] && splitSmallLine[0] != "" && splitSmallLine[2] != "" && splitBigLine[1] != "") ||
       (splitSmallLine[0] == splitBigLine[0] && splitSmallLine[2] == splitBigLine[5] && splitSmallLine[0] != "" && splitSmallLine[2] != "" && splitBigLine[5] != ""))
select new MBSGroup()
{
    write data to merge object
};
List<MBSGroup> MBSlists = queryMBSObjects.ToList();


texts: Python - Iterating over contents of BeautifulSoup element very slow

texts:
I have a large HTML document where everything is inside a main div, structured like this:

    \\block 1

content1acontent1b

content1c

    \\block 2

content2acontent2b

content2c

    ...

As you can see the contents of the header divs are related to the paragraphs, so my Python code separates these tag blocks into lists of a list so I can take out their contents later:

main_div = soup.find("div", class_="main")
headers = main_div.find_all("div", class_="header")

all_blocks = []
current_block = []

for tag in main_div.contents:
    if tag in headers:
        all_blocks.append(current_block)
        current_block = [tag]
    else:
        current_block.append(tag)

all_blocks.append(current_block)  # append final block
all_blocks = all_blocks[1:]  # take off first empty list

Problem is this seems to take forever on a ~12MB HTML file I'm feeding it (less than 1% done after 1h, while parsing the file with bs4 only took 25s).
Is there something really inefficient in my code or is this going to be slow anyway?


texts: Can this code, to convert string to integer, be made more compact?

texts:
Problem:
String to integer(leetcode)

Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:

Only the space character ' ' is considered as a whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31-1]. If the numerical value is out of the range of representable values, (2^31-1) or -2^31 is returned.

My solution:
I have implemented this code below. I have noted down the requirements and implemented the code. It was hard to keep track of all the details. Before acceptance, I got WA 4 times(and it seems like the code I've written is not compact).
class Solution:
    def myAtoi(self, s: str) -> int:
            l = len(s)
            if l==0:
                print(1)
                return 0
            if l==1:
                if s==" " or s=="+" or s=="-":
                    return 0
                elif(s.isnumeric()):
                    return int(s)
                else:
                    return 0
            res = ""
            i = 0
            while(i<l and s[i]==" "):
                i+=1
                if i==l:
                    return 0
            ispos = False
            if(s[i]=="+"):
                ispos = True
                i+=1
            isnegative = False
            if(s[i]=='-' and not ispos):
                isnegative = True
                i+=1
            if(i<len(s) and not s[i].isnumeric() and s[i]!='+' and s[i]!='-'):
                return 0
            while(i<l):
                if s[i].isnumeric():
                    res += s[i]
                else:
                    break
                i+=1
            if len(res)>0:
                x = int(res)
            else:
                return 0
            if isnegative:
                if x>=(1<<31):
                    return -(1<<31)
                x *= -1
            if x>=((1<<31) - 1):
                return (1<<31)-1
            return x

Can anyone write a compact code for this problem?

I also like to know if there is an approach to solve this kind of implementation problems so that I can write compact code. Can anyone share any better method to analyze this type of implementation problem? (or, any suggestion to be better in solving this kind of problems where we need to keep track of many things)


texts:
Implementation:

IEnumerable<BigInteger> Fibs()
{
    BigInteger a = 0;
    BigInteger b = 1;
    while(true)
    {
        b = a + (a = b);
        yield return a;
    }
}

Usage:

void Main()
{
    // take first 100 fib numbers
    var fibs = Fibs().Take(100);
}

How can I improve this?


texts: Locating child of a nearby ancestor with jQuery

texts:
I have the following markup, and I'm wondering how best to locate the nearest previous dpicker input element and give it focus with jQuery when a.dpicon is clicked.

  <input autocomplete="off" class="dpicker" type="text" name="mdpdate" id="mdpdate">

I've used this, and it works, but it seems pretty cumbersome:

$(".dpicon").click(function(){
  $(this).parent().parent().prev().children(".dpicker").focus();
});

Also, there will be times that the 'dpicon' element will be before the input in markup, not after it. Is there a way to catch both instances?


texts: Java implementation of the longest monotone increasing subsequence

texts:
Problem: Given a set of n distinct numbers, find the length of the longest monotone increasing subsequence.
For example, let's take this array [1,2,9,4,7,3,11,8,14,6]
The longest monotone increasing subsequence of this array is [1,2,4,7,11,14]. So the desired result is, the length of the array which is 6.

Algorithm (taken from R.G. Dromey's How to Solve it by computer):

Establish the data set a[1...n] of n elements.
Set two loops, one to find out out each terminating point and the inner loop to find it's increasing subsequence.
start the first loop at index 2 so that it will initially have a sequence.
in the inner loop,
if current element is less than maximum of previous sequence, then,
identify the subsequence and if the length of subsequence is larger than the length of previous longest subsequence then update the length, position of maximum and maximum value.

else, update the length, position of maximum and maximum value so far.

import java.util.*;

public class Monotone {

  public static int maxMonotonicSequenceLength(int[] elements) {
    int maxValue = 0;
    int positionOfMax = 0;
    int length = 2;

    for (int i = 2; i < elements.length; ++i) {
      if (elements[i] < maxValue) {
        int count = 1;
        int previousMaxElement = 0;

        for (int j = 1; j <= i-1; ++j) {
          if ((elements[j] < elements[i]) &&
              previousMaxElement < elements[j]) {

            previousMaxElement = elements[j];
            count = count + 1;
            if (length < count) {
              length = count;
              positionOfMax = j;
              maxValue = elements[j];
            }
          }
        }
      } else {
        positionOfMax = i;
        maxValue = elements[i];
        length = length + 1;
      }
    }
    return length + 1;
  }

  public static void main(String args[]) {
    int[] list = new int[10];

    list[0] = 1;
    list[1] = 2;
    list[2] = 9;
    list[3] = 4;
    list[4] = 7;
    list[5] = 3;
    list[6] = 11;
    list[7] = 8;
    list[8] = 14;
    list[9] = 6;

    System.out.println("lenght of subsequence: " + maxMonotonicSequenceLength(list));
  }
}


texts: Generic PHP function for making a struct out of multiple resultsets from a stored procedure call

texts:
The stored procedures must return their first resultset in the form:

(
    [index] int,
    [id] varchar(50)
)

where

[index] is 0,1,2,3,... and
[id] is the name of the struct.

As long as the first resultset returns the names of the resultsets in the same order they are returned by the stored procedure the php struct will store each struct in the struct by it's name.

Example ResultSet 0:

0,'resultsets'
1,'codes'
2,'listings'
3,'users'

Example Function Call:

$struct = genericMultiResults('exec dbo.genericProcedure');

Example Results:

$struct['resultsets'][0]; // 'resultsets'
$struct['resultsets'][1]; // 'codes'
foreach($struct['codes'] as $code) {  // loop over the records of the codes resultset
    ...
}
foreach($struct['listings'] as $listing) { /* loop over the records of the listings resultset */
    ...
}

Implementation:

function genericMultiResultSet($sql) {
    global $conn;

    // resultset holder
    $resultSets = array();
    // resultsets key name, can be changed by record 0 of resultset 0
    $resultSetsKey = 'resultsets';
    // current resultset name, only used by resultsets 1 and above, not by 0, defaults to name of 0
    $resultSetKey  = 'resultsets';

    // execute multi-resultset procedure or sql statement
    $results = sqlsrv_query($conn,$sql);
    // assume we have the first resultset, loop over resultsets
    do {
        // loop over rows in resultset
        while($row = sqlsrv_fetch_array($results,SQLSRV_FETCH_ASSOC)) {
            // if the structure is $row['index'], $row['id'] then assume it is a resultsets key
            if(isset($row['index']) && isset($row['id']) && count($row) == 2) {
                // if resultsets key not created yet, create it
                if(count($resultSets) == 0) {
                    $resultSets[$row['id']] = array();
                    // assume first record in resultset describes itself (the resultset, not the row)
                    $resultSetsKey = $row['id'];
                }
                // add entry to resultsets key
                $resultSets[$resultSetsKey][$row['index']] = $row['id'];
            // otherwise, not a resultsets key
            } else {
                // if no array for current $resultset create it
                if(!isset($resultSets[$resultSetKey])) {
                    $resultSets[$resultSetKey] = array();
                }
                // add row to it's resultset within $resultSets
                array_push($resultSets[$resultSetKey],$row);
            }
        }
        // get next key for next resultset
        if(isset($resultSets[$resultSetsKey][count($resultSets)])) {
            $resultSetKey = $resultSets[$resultSetsKey][count($resultSets)];
        }
    // get next resultset
    } while(!is_null(sqlsrv_next_result($results)));

    sqlsrv_free_stmt($results);
    return $resultSets;
}

So my implementation works perfectly, does exactly what I want, lets me edit the procedures (add remove resultsets at will) and I only have to modify my php that uses the function, I never have to touch the function.

So my question:  Is there a more elegant implementation to get the same result, ie, reference the resultsets by name set in first resultset, rather than referencing them by the order they are returned?


texts:
I need to round numbers in a Word document, as I couldn't find a built-in way, here is my approach, it rounds all numbers in selection.

As I use VBA mainly in Excel I'm not sure whether I've done it the best way possible:

Sub RoundNumbers()
    Dim OrigRng As Range
    Dim WorkRng As Range
    Dim FindPattern As String
    Dim FoundVal As String

    Set OrigRng = Selection.Range
    Set WorkRng = Selection.Range
    FindPattern = "([0-9]){1,}.[0-9]{1,}"

    Do
        With WorkRng
            .SetRange OrigRng.Start, OrigRng.End ' using "set WorkRng = OrigRng" would cause them to point to the same object (OrigRng is also changed when WorkRng is changed)
            If .Find.Execute(findtext:=FindPattern, Forward:=True, _
                    MatchWildcards:=True) Then
                .Expand wdWord ' I couldn't find a reliable way for greedy matching with Word regex, so I expand found range to word
                .Text = round(CDbl(.Text) + 0.000001) ' VBA's round() perform bankers' rounding, adding a small number is a quick fix which works for my data
            End If
        End With
    Loop While WorkRng.Find.Found
End Sub

Input example:

Lorem ipsum dolor sit amet, consectetur adipiscing elit 15.12. Duis vestibulum gravida elit 3.1415, ac pretium neque suscipit ut. Pellentesque eu ipsum quam.

| 94.3 | 1.5  | 39   | 6.5  |
| 62.4 | 56.6 | 96.4 | 46.4 |
| 92   | 1.2  | 62.1 | 77.6 |
| 55.4 | 83.3 | 44.3 | 49.5 |
| 13.9 | 8.5  | 95.2 | 14.4 |
| 62.5 | 37.4 | 24   | 23.4 |
| 71.9 | 81.6 | 10.3 | 21.6 |

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse nec elementum massa. Donec sit amet volutpat ligula.


texts:
I know randomness in programming can be a deep topic, and searching the topic seems to result in Fisher-Yates being the best method, but I'm curious what people would say about this method.

Basically, since I have the cards as objects, I just add a property of a random number then sort the entire array based on those random numbers.

const suits = [
  {
    digit: 'H',
    word: 'hearts'
  },
  {
    digit: 'C',
    word: 'clubs'
  },
  {
    digit: 'D',
    word: 'diamonds'
  },
  {
    digit: 'S',
    word: 'spades'
  }
]
const cardsWithoutSuits = [
  {
    numeric: 1,
    word: 'ace',
    digit: 'A'
  },
  {
    numeric: 2,
    word: 'two',
  },
  {
    numeric: 3,
    word: 'three',
  },
  {
    numeric: 4,
    word: 'four',
  },
  {
    numeric: 5,
    word: 'five',
  },
  {
    numeric: 6,
    word: 'six',
  },
  {
    numeric: 7,
    word: 'seven',
  },
  {
    numeric: 8,
    word: 'eight',
  },
  {
    numeric: 9,
    word: 'nine',
  },
  {
    numeric: 10,
    word: 'ten',
  },
  {
    numeric: 11,
    word: 'jack',
    digit: 'J'
  },
  {
    numeric: 12,
    word: 'queen',
    digit: 'Q'
  },
  {
    numeric: 13,
    word: 'king',
    digit: 'K'
  }
]

function createDeck(decks = 1){
  let deck = [];
  for (let i = 0; i < decks; i++) {
    suits.forEach( x => {
      cardsWithoutSuits.forEach( y => {
        deck.push({
          numeric: y.numeric,
          word: y.word,
          suit: x.word,
          phrase: `${y.word} of ${x.word}`,
          abbr: `${y.hasOwnProperty('digit') ? y.digit : y.numeric}${x.digit}`
        })
      })
    })
  }
  return deck;
}

function shuffle(array){
  array.forEach( x =>{
    x.ran = Math.random();
  })
  array.sort( (a, b) =>{
    return a.ran - b.ran;
  })

  return array;
}

let deck = shuffle(createDeck(2));
console.log(deck);


texts: Simple python script to shorten URLs in specified text files

texts:
A recent question inspired me to write a script for this task:

Shorten URLs in specified text files using googleapis.com
Handle multiple URLs, whether on the same line or multiple lines

The original question tried to do this in Bash, but it gets quite tricky when it comes to handling multiple URLs, so I decided to rewrite in Python:

#!/usr/bin/env python

import sys
import os
import re
import urllib2
import json

re_url_pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')

def shorten_url(url):
    print("Shortening url {} ...".format(url))
    post_url = 'https://www.googleapis.com/urlshortener/v1/url?fields=id'
    postdata = {'longUrl': url}
    headers = {'Content-Type': 'application/json'}
    req = urllib2.Request(post_url, json.dumps(postdata), headers)
    return json.loads(urllib2.urlopen(req).read())['id']

def shorten_urls_in_text(text):
    found_urls = False
    for url in set(re_url_pattern.findall(text)):
        short_url = shorten_url(url)
        text = text.replace(url, short_url)
        found_urls = True

    return found_urls, text

def shorten_urls_in_file(path):
    text = read_file(path)
    found_urls, text = shorten_urls_in_text(text)

    if found_urls:
        write_file(path, text)

def shorten_urls_in_files(*paths):
    for path in paths:
        if os.path.isfile(path):
            print('Shortening urls in file {} ...'.format(path))
            shorten_urls_in_file(path)
        else:
            print('No such file: {}'.format(path))

def read_file(path):
    with open(path) as fh:
        return fh.read()

def write_file(path, text):
    with open(path, 'w') as fh:
        fh.write(text)

if __name__ == '__main__':
    shorten_urls_in_files(*sys.argv[1:])

And some unit tests:

#!/usr/bin/env python

import unittest
from test.test_support import run_unittest

from shorten_urls import shorten_url
from shorten_urls import shorten_urls_in_text

sample_url1 = 'http://news.ycombinator.com'
sample_url1_shortened = 'http://goo.gl/ovZB'

class UrlShortenerTestCase(unittest.TestCase):
    def test_shorten_url(self):
        self.assertEqual(sample_url1_shortened, shorten_url(sample_url1))

    def test_replace_nothing(self):
        orig = 'hello'
        found_urls, text = shorten_urls_in_text(orig)
        self.assertFalse(found_urls)
        self.assertEqual(orig, text)

    def assert_correct_replacement(self, fmt):
        orig = fmt.format(url=sample_url1)
        expected = fmt.format(url=sample_url1_shortened)
        found_urls, text = shorten_urls_in_text(orig)
        self.assertTrue(found_urls)
        self.assertEqual(expected, text)

    def test_replace_one(self):
        fmt = '''hello world {url}'''
        self.assert_correct_replacement(fmt)

    def test_replace_many(self):
        fmt = '''hello world {url}\nnewline {url} again\n{url} last'''
        self.assert_correct_replacement(fmt)

    def test_replace_many_on_same_line(self):
        fmt = '''hello world {url} same line {url} again'''
        self.assert_correct_replacement(fmt)

def test_main():
    run_unittest(UrlShortenerTestCase)

if __name__ == '__main__':
    test_main()

It's not great that it needs to read the entire file in memory, but for handling relatively small files I thought it should be good enough.

I would like a review in terms of Python coding practices, style, and possible over-engineering.

I'm also wondering if urllib2 is considered more widely available than requests. I would prefer requests as it has simpler syntax, but I used urllib2 to make it more widely usable (if that's even true).


texts:
This is an online problem.  The challenge is to print the kth prime number, for each k given in the input (1 ≤ k ≤ 15000).  The first line of input indicates the number of inputs on the subsequent N lines.

Example input:

4
1
2
3
4

Example output:

2
3
5
7

(the 1st 2nd 3rd and 4th prime numbers).

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 100000000

void prime(int n)
{
    int i,j,temp,count=0;

    for(i=2;i<=MAX;i++)
    {
        temp=0;
        for(j=2;j<=sqrt(i);j++)
        {
            if(i%j==0)
            {
                temp=1;
                break;
            }
        }
        if(temp==0)
        {
            count++;
        }
        if(count==n)
        {
            printf("%d\n",i);
            break;
        }
    }
}

int main()
{
   int n,i;

   scanf("%d",&n);
   int arr[n];

   for(i=0;i<n;i++)
   {
       scanf("%d",&arr[i]);
   }
   for(i=0;i<n;i++)
   {
       prime(arr[i]);
   }

   return 0;
}

This code is working fine on codeblocks but is exceeding time limits on an online judge. I've tried manipulating this code in two more ways

using pointer and malloc in the main function
running the loop from j=1 to j=i/2 instead of upto sqrt(i)

(latter is more efficient due to fewer iterations of loop). Any suggestions?


texts:
Function queries data from an Aurora database. Aurora database is the MySQL engine therefore, I'm querying it with a MySQL NPM module. If there is something better, I'm all ears.

The calling function has a try-catch block to manage exceptions. This function just connects to Aurora, submits a query, and displays the results to the console.

const mysql = require('mysql');

function aurora_query_decorator(host, user, password, port, database) {
    const esb_db_connectionstring = {
        "host" : host,
        "user" : user,
        "password" : password,
        "port" : port,
        "database" : database,
        "connectTimeout" : 5000
    };
    console.log('Connection String: ', esb_db_connectionstring);

    console.log("Attempting to connect to Aurora...");
    const esb_db = mysql.createConnection(esb_db_connectionstring);

    esb_db.connect( (error) => {
        if (error) throw error;

        const esb_db_query_sql = "select * from things";
        console.log('Query: ', esb_db_query_sql);

        console.log("Attempting to query Aurora...");
        esb_db_query = esb_db.query(esb_db_query_sql);

        esb_db_query.on('error', error => { throw error } );

        esb_db_query.on('fields', data => { console.log(data) } );

        esb_db_query.on('end', () => { esb_db.end() } );
    });

    return;
}

Looking for general feedback. All constructive feedback welcome.

Ultimately, I'll be querying Aurora from Lambda functions. Does it make sense to try to pool connections?


texts: PopupMenu implementation that hacks inflating a @MenuRes

texts:
Summary

Usage will ask for a Context and a @MenuRes and then use the PopupHack.class to inflate the menu resource and retrieve the Menu and MenuItems.

Reasoning

To allow the creation of a List<Object> by supplying a menu resource xml. For use within a larger project/library.

PopupHack.class

static class PopupHack extends PopupMenu {
    PopupHack(Context context, int menuRes) {
        //noinspection ConstantConditions or (new View(context)?)
        super(context, null);
        inflate(menuRes);
    }

    int size(){
        return getMenu().size();
    }

    CharSequence title(int index) {
        return getMenu().getItem(index).getTitle();
    }

    Drawable icon(int index) {
        return getMenu().getItem(index).getIcon();
    }
}

Usage

 public static void usage(@NonNull Context context, @MenuRes int menuRes){
    final PopupHack hack = new PopupHack(context, menuRes);
    for (int i = 0; i < hack.size(); i++) {
        final CharSequence title = hack.title(i);
        final Drawable icon = hack.icon(i);
        Log.i("Usage", String.format("Title: %s Icon: %s", title, icon));
    }
}

The code is completely operational.


texts: Simple cube that moves around the container with keys

texts:
I made a basic cube that can move around of container and jump too. It's basic but I want to know if I can use better methods, better formatting, or shorten the code.

This my HTML:

and this is my Javascript code with a little jQuery:

var velocity = 2;
var acceleration = 0.002;
var gravity = 2;
var key_left = false;
var key_right = false;
var key_up = false;
window.addEventListener('keydown', handleKeyDown)
window.addEventListener('keyup', handleKeyUp)

function handleKeyDown(event) {
if (event.keyCode == 65) {
    key_left = true;
} else if (event.keyCode == 68) {
    key_right = true;
} else if (event.keyCode == 87) {
    key_up = true;
}
};

function handleKeyUp(event) {
if (event.keyCode == 65) {
    key_left = false;
    velocity = 2;
    acceleration = 0.002;
} else if (event.keyCode == 68) {
    key_right = false;
    velocity = 2;
    acceleration = 0.002;
} else if (event.keyCode == 87) {
    key_up = false;
}
};

setInterval(function () {
var move = parseFloat($(".box").css("marginRight"));
var moveLimt = (parseFloat($(".cube").css("width")) - 100)

if (key_left === true && move < moveLimt) {
    $(".box").css("marginRight", function () {
        move += (velocity += acceleration);
        return move.toString() + "px";
    });
} else if (key_right === true && move > 0) {
    $(".box").css("marginRight", function () {
        move -= (velocity += acceleration);
        return move.toString() + "px";
    });
}

var jump = parseFloat($(".cube").css("height"));

if (key_up === true) {
    $(".cube").css("height", function () {
        jump += (gravity);
        if (jump < 402) {
            return jump.toString() + "px";
        }
    });
} else if (key_up === false) {
    $(".cube").css("height", function () {
        jump -= (gravity);
        if (jump > 98) {
            return jump.toString() + "px";
        }
    });
}
});


texts:
This is a continued discussion (from here => Group duplicate files) with new code and new thoughts/questions (see special question part for details for new questions), and I decide to make a new post.

Here is my source code which group duplicate files together, written in Python 2.7. Any advice on smarter ideas to group duplicate files together more efficient, it will be great. Any general advice on code bugs and code style are also appreciated.

Problem statement:

I am given a list of files e.g. ["1.txt", "2.txt", "3.txt", "4.txt", "5.txt", "6.txt"]. I want to group all files which have the exact same content. Suppose in this example, file "1.txt", "2.txt", "3.txt" are the same, file "4.txt", "5.txt", "6.txt" have common header, but "4.txt", "6.txt" are exactly the same whole content. Then, the output should be two groups "1.txt", "2.txt", "3.txt" and "4.txt", "6.txt".

My major idea:

To avoid reading full content for each file, I generate a hash code for a file header (in my example, I define the file header to be the first 10 bytes of a file)
If more than 1 (>=2) files have the same header, I will read the full content and see if they are the exact same whole content -- I still generate hashing for whole content since if multiple files are the same hashing for header, there are many different potential duplication sub-groups, using hashing is easy to group true equal content file together.

Special question

I find below implementation still needs to read whole file content for any potential duplicate files. Wondering if any better ideas for improvement in terms of performance perspective?

Source code in Python 2.7

from collections import defaultdict

def read_whole_file(filename):
    with open(filename) as f:
        return hash(f.read())
def read_file_header(filename, header_length):
    with open(filename) as f:
        return hash(f.read(header_length))
def group_duplicate_files(filenames):
    header_buf = defaultdict(list)
    whole_buf = defaultdict(list)
    for f in filenames:
        header_buf[read_file_header(f,10)].append(f)
    for files in header_buf.values():
        if len(files) == 1:
            continue
        for f in files:
            whole_buf[read_whole_file(f)].append(f)
    return whole_buf.values()
if __name__ == "__main__":
    files = ["1.txt", "2.txt", "3.txt", "4.txt", "5.txt", "6.txt"]
    print group_duplicate_files(files)


texts: UPDATED: Ambient time context to help unit testing

texts:
The following test demonstrates the functionality of Time class which is supposed to be used instead of DateTime.Now. You could just read the static Time.Now property to get current UTC time. In case of unit testing though you could wrap the  code under test in a using statement in the form of using(new Time(2019, 12, 31, 23, 59)) { ... } and get this date and time consistently being returned till time context disposing.

[TestClass]
public class Time_Should
{
    [TestMethod]
    public void Adjust()
    {
        Assert.IsTrue(Time.Now > new DateTime(2020, 1, 1));
        using (new Time(2010, 1, 1))
        {
            Assert.AreEqual(new DateTime(2010, 1, 1), Time.Now);
            using (new Time(2011, 1, 1))
                Assert.AreEqual(new DateTime(2011, 1, 1), Time.Now);

            Assert.AreEqual(new DateTime(2010, 1, 1), Time.Now);
        }
        Assert.IsTrue(Time.Now > new DateTime(2020, 1, 1));
    }
}

UPDATE: For those who never tested ambient properties:

Imagine that you have a business object depending on the current time:

class Job
{
     public decimal  DailyRate { get; set; } = 100;
     public DateTime Started { get; set; } = DateTime.Now;
     public decimal Earned => (DateTime.Now - Started).TotalDays * DailyRate;
}

It is untestable. Using the class above would help with that:

class Job
{
       public decimal  DailyRate { get; set; } = 100;
       public DateTime Started { get; set; } = Time.Now;
       public decimal Earned => (Time.Now - Started).TotalDays * DailyRate;
}

Now you could test:

var job = new Job { Started = new DateTime(2020, 1, 1) };
using(new Time(2020, 1, 2))
      Assert.AreEqual(100m, job.Earned);

The library code:

public class Time : IDisposable
{
    static AsyncLocal<Time> Context { get; } = new AsyncLocal<Time>();

    public Time(int year, int month=1, int day=1, int hour=0, int minute=0, int second=0)
        : this(new DateTime(year, month, day, hour, minute, second))
    {
    }

    public Time(DateTimeOffset constant)
    {
        Constant = constant;
        Parent = Context.Value;
        Context.Value = this;
    }

    Time Parent { get; }
    DateTimeOffset Constant { get; }

    public void Dispose() =>
        Context.Value = Parent;

    public static DateTimeOffset Now =>
        Context.Value?.Constant ?? DateTimeOffset.UtcNow;
}