texts:
This post goes over how I updated my 2048 merge function code from spaghetti code to being somewhat more readable.

Spaghetti Old Code

I incorporated a few techniques from pretty much all of your suggestions! I realized there were a lot of logical mistakes and redundancy in my code, like why append 0's over and over again when it's not necessary at all, because in the end I back-track, account for missing numbers, and then append 0(s) in their place.

Improvements in new code vs. old code:

Use of list comprehensions
Use of Python's built-in truthiness
Minimal branches (fewer if(s), else(s), etc.)
Infusing new and useful methods like extend into my code
Improving the code style by enhancing readability
Removing redundandcy and flawed logic

def merge(nums):
    '''
    Takes a list as input
    returns merged pairs with
    non zero values shifted to the left.
    fancy interactive doc test below, no output means no problems.
    >>> merge([2, 0, 2, 4])
    [4, 4, 0, 0]
    >>> merge([0, 0, 2, 2])
    [4, 0, 0, 0]
    >>> merge([2, 2, 0, 0])
    [4, 0, 0, 0]
    >>> merge([2, 2, 2, 2, 2])
    [4, 4, 2, 0, 0]
    >>> merge([8, 16, 16, 8])
    [8, 32, 8, 0]
    '''
    slide = [num for num in nums if num]
    pairs = []
    for idx, num in enumerate(slide):
        if idx == len(slide)-1:
            pairs.append(num)
            break
        elif num == slide[idx+1]:
            pairs.append(num*2)
            slide[idx+1] = None
        else:
            pairs.append(num)  # Even if not pair you must append
    slide = [pair for pair in pairs if pair]
    slide.extend([0] * (len(nums) - len(slide)))
    return slide

if __name__ == '__main__':
    import doctest
    doctest.testmod()

Sidenote: Pylint yells at me for using i instead of idx.


texts:
This is a question from GeeksForGeeks

Given an array of integers, find a combination of four elements in the
array whose sum is equal to a given value X.
Input: First line consists of T test cases. First line of every test
case consists of an integer N, denoting the number of elements in an
array. Second line consists of N spaced array elements. Third line of
every test case X.
Output: Single line output, print 1 if combination is found else 0.
Constraints: 1<=T<=100
1<=N<=100
Example: Input: 1 6 1 5 1 0 6 0 7
Output: 1

Here is the code
#include <iostream>
#include <cassert>
#include <vector>

int main() {
    int t, n, val, x, sum = 0;
    bool found = false;
    std::cin >> t;
    assert(t >= 1 && t <= 100);

    while (t--)
    {
        std::cin >> n;
        assert(n >=1 && n <= 100);
        std::vector<int> vec(n);
        for (int i = 0; i < n; i++)
        {
            std::cin >> val;
            vec[i] = val;
        }

        std::cin >> x;

        for (int i = 0; i < n - 3; i++)
        {
            for (int j = i + 1; j < n - 2; j++)
            {
                for (int k = j + 1; k < n - 1; k++)
                {
                    for (int l = k + 1; l < n; l++)
                    {
                        sum = vec[i] + vec[j] + vec[k] + vec[l];
                        if (sum == x)
                        {
                            found = true;
                            break;
                        }
                    }
                }
            }
        }

        if (found == true)
        {
            std::cout << 1 << std::endl;
        }
        else
        {
            std::cout << 0 << std::endl;
        }
    }
    return 0;
}

How to optimise this code?


texts: Building and getting a form of objects that have multiple properties

texts:
I'm building a form dynamically in a web app where I'm using product_id to keep track which product I'm reading and then product_<id>_property to grab the value of it. Then in my view I end up with this:

for product_id in request.POST.getlist('product_id'):
    ProductPlacement.objects.create(
        product = Product.objects.get(id=product_id),
        board = board,
        x = request.POST.get('product_{0}_x'.format(product_id)),
        y = request.POST.get('product_{0}_y'.format(product_id)),
        width = request.POST.get('product_{0}_width'.format(product_id)),
        height = request.POST.get('product_{0}_height'.format(product_id)),
        rotation = request.POST.get('product_{0}_rotation'.format(product_id)),
        z = 0
    )

It's not very pretty, is there a nicer more readable way of doing it?


texts:
I am trying to write a program to find a zip file's password. I know the password consists of only lower-case letters and it's length does not exceed 6 characters. I wanted to check the passwords of length 1 first, then length 2 and so on.

So I used breadth first search, but then I realized that BFS consumes so much memory, and std::queue makes things even worse. So I had to switch to depth first search. BUT... depth first search does not check the shortest passwords first. So that's a problem. How can I improve the memory management in my bfs function, Or change my dfs function so that it would check the shortest passwords first (I'm not sure if the latter is even possible)

Also my estimation is that the bfs function would be using about 2 Gigabytes of memory. How can I fix this?

#include <iostream>
#include <queue>

std::string key = "banana";

void checkPassword(std::string s) {
  if (s == key) { //example checker function
    std::cout << "Password is : " << s << std::endl;
  }
}

void bfs(std::string s = "") {
  std::queue <std::string> q;
  q.push(s);
  while(q.size()) {
    std::string u = q.front();
    checkPassword(u);
    q.pop();
    if (u.size() < 6) {
      for (int i = 'a'; i <= 'z'; i++) {
        u += i;
        q.push(u);
        u.pop_back();
      }
    }
  }
}

void dfs(std::string s = "") {
  checkPassword(s);
  if (s.size() < 6) {
    for (int i = 'a'; i <= 'z'; i++) {
      s.push_back(i);
      dfs(s);
      s.pop_back();
    }
  }
}

int main() {
  dfs();
  std::cout << "Finished Time : " << clock() / (double) CLOCKS_PER_SEC;
}


texts:
I am trying to implement algorithms related to trees in Scala. I have dabbled with the following implementations of a tree. Are there any pros and cons of preferring the non-Option related implementation over the one that uses Option?

Implementation with Option:

  sealed trait Node {
    val label: Int
  }
  case class LeafNode(override val label: Int) extends Node
  case class BranchNode(override val label: Int, left: Option[Node], right: Option[Node]) extends Node

  def inorderTraversal(aTree: Option[Node]): List[Int] = {
    def helper(aTree: Option[Node], acc: List[Int]): List[Int] = aTree match {
      case None => acc
      case Some(LeafNode(label)) => helper(None, label :: acc)
      case Some(BranchNode(label, left, right)) => helper(left, acc) ++ helper(None, label :: acc) ++ helper(right, acc)
    }
    helper(aTree, List.empty[Int])
  }

Implementation without Option:

  sealed trait Tree {
    def value: Int
    def left: Tree
    def right: Tree
    def isEmpty: Boolean
    def inorder(acc: List[Int]): List[Int] = {
      if (isEmpty) acc else {
        left.inorder(acc) ++ List(value) ++ right.inorder(acc)
      }
    }
  }

  case object Leaf extends Tree {
    override def value = throw new IllegalArgumentException
    override def left = throw new IllegalArgumentException
    override def right = throw new IllegalArgumentException
    override def isEmpty = true
  }

  case class Branch(override val value: Int, left: Tree=Leaf, right: Tree=Leaf) extends Tree {
    override def isEmpty = false
  }

The Option related implementation leads to a lot of pattern matching code, sometimes multiple case statements. Whereas with the non-Option method I can get by using the isEmpty check. I am biased towards the non-Option method because the code appears simpler to follow.

Which one is better and why?


texts:
You give this function a pointer and how many bytes you want to extract as a decimal and it returns it.

long long
byte_extract
(void * source, size_t bytes)
{
    long long num = 0, m = 1;
    size_t i;

    for(i = 0; i != bytes; i++)
    {
        num += (((unsigned char*)source)[i]*m);
        m<<=0x8;
    }
    return num;
}


texts:
I want to generate some random data and store it in a container. I split the container into disjoint intervals using iterators and pass them to a thread function (I hope its body isn't important here).

There are several design-related questions here:

Is it a good practice to solve such task in this manner?
If it is, do I optimally pass and receive parameters in thread_func?

#include <iostream>
#include <thread>
#include <random>
#include <utility>

template <typename Iterator, typename Distributions>
void thread_func(Iterator b, Iterator e, Distributions& ds)
{
    // *b++ = something, while b != e
}

int main()
{
    auto nthreads = std::thread::hardware_concurrency() ?: 1;
    std::cout << nthreads << " concurrent threads possible" << std::endl;

    const int nevents = 1'000'000;
    std::vector<std::pair<int, int>> events(nevents);

    int nparts = nevents / nthreads;

    std::vector<std::poisson_distribution<>> distributions;
    for (int i = 0; i < 10; i++)
        distributions.emplace_back(5);

    std::vector<std::thread> threads;
    for (int i = 0; i < nthreads - 1; i++) {
        auto left  = begin(events) + nparts * i;
        auto right = begin(events) + nparts * (i+1);

        auto f = [l=std::move(left), r=std::move(right), &d=distributions] { thread_func(l, r, d); };

        threads.emplace_back(f);
    }
    auto f = [l=begin(events)+nparts*(nthreads-1), r=end(events), &d=distributions] { thread_func(l, r, d); };
    threads.emplace_back(f);

    for (auto&& t : threads)
        t.join();
}


texts: Somewhat esoteric if statement in a paginated feed

texts:
I am working on the home page of a website that will have a paginated feed (much like a blog's home page).

One of the requirements is that when a user navigates to a non-existent page, he or she will be redirected to the last available page. For example, when the user navigates to a non-existent page such as page number 500, they will be redirected to the highest (last available) page number which might be something sensible like 10.

The code to fulfill this requirement easy enough looks like this:

private const int PageSize = 5;
public ActionResult Index(int pageNumber = 1)
{
    IEnumerable<Post> posts = repository.All();
    PagedList<Post> page = posts.Paginate(pageNumber, PageSize);

    if (page.Count == 0 && pageNumber != 1)
    {
        return RedirectToAction("Index", new { pageNumber = page.TotalPageCount });
    }

    return View(page);
}

My problem with this code is the following expression:

page.Count == 0 && pageNumber != 1

Personally I find this code hard to reason about (and I am the person who wrote it!).  How can I make the meaning of this expression clearer? Is there an alternative, more readable way  of implementing this logic perhaps?

The condition begins by evaluating whether the requested page has any posts - if the contents of the page are empty, the page effectively does not exist. The condition then checks whether the user is attempting to access the home page (the first page) or not. This check is important because if the database is empty, the user still needs to be able to access the first page - so that the view can display a nice error message.


texts:
I just wrote this small inch <-> cm conversion program. It works just fine, although I know that I've done some things in a rather stupid manner and that it could be improved.

def conversion():
    try: amount = int(raw_input("Please enter the value: "))
    except ValueError:
        print "Please specify a valid amount."
        return conversion()
    answer = raw_input("Please choose between converting FROM kilograms/pounds: ")
    if answer == "kilograms":
        return amount * 2.2
    elif answer == "pounds":
        return amount / 1.45
    else:
        print "Please choose between kilograms and pounds."
        restart = raw_input("Try again? ")
        if restart == "yes":
            return conversion()
        elif restart == "y":
            return conversion()
        else:
            print "Okay, bye."
            return

print conversion()


texts: Ruby class to encapsulate Retrying (for instance, with email)

texts:
One of my clients sends quite a few emails a day ... I would think over 500. They are mostly reports to clients or employees. The volume has become sufficient that intermittent issues with gmail (like the occasional and annoying "please try again later" error, or "too many logins" error) are causing missed reports and headaches. We also have some issues with the MapQuest API and this might help.

So I'm writing this class to encapsulate the process of the immediate retry (as opposed to the "give it back to Resque to try again later" process.)

Dependencies:

Uses my gem Valuable which makes modeling easier.

Feedback welcome.

class Retryer < Valuable
  has_value :attempts, :default => 3
  has_value :logger, default: lambda { Rails.logger }

  has_value :tries, :default => 0

  has_collection :reraise, :default => [NotImplementedError]

  def fire
    raise "You must provide a block of code to try" unless block_given?

    begin
      self.tries += 1
      yield
    rescue Timeout::Error => err
      logger && logger.warn("    - Timeout!")
      sleep(0.5)
      retry if self.tries < self.attempts
    rescue => err
      if reraise.include? err.class
        logger && logger.warn("    - try #{self.tries} of #{attempts} failed and will be reraised: #{err}")
        raise err
      else
        logger && logger.warn("    - try #{self.tries} of #{attempts} failed with #{err}")
        retry if self.tries < self.attempts
      end
    end
  end
end

One thing I'd like to add is the option to run another proc/block if all attempts raise. For instance, notify Rollbar. I imagine it working somewhat like js promises. But I would only do it if I could figure out a readable interface...


texts: Non-recursive approach to the Rod-Cutting

texts:
I've given the Rod-Cutting Problem a go with a non-recursive approach that use a cache instead, with a bottom up approach. For anyone who hasn't heard about the Rod-Cutting problem, it's defined as follows:

  Serling Enterprises buys long steel rods and cuts them into shorter
  rods, which it then sells. Each cut is free. The management of Serling
  Enterprises wants to know the best way to cut up the rods. We assume
  that we know, for i = 1, 2, ..., the price pi in dollars that Serling
  Enterprises charges for a rod of length i inches. Rod lengths are
  always an integral number of inches. Given a rod of length n inches
  and a table of prices pi for i = 1, 2, ..., n determine the maximum
  revenue obtainable by cutting up the rod and selling the pieces. Note
  that if the price pn for a rod of length n is large enough, an optimal
  solution may require no cutting at all.

public static int[] prices = new int[]{1,5,8,9,10,17,17,20};

public static void main(String[] args) {

    // Best Price Check #1
    for (int i = 1; i < 9; i++) {
        System.out.println(i + " => " + bestPrice(i));
    }

}

public static int bestPrice(int n) {

    // This works like a cache
    int[] maxPrices = new int[n+1];

    // The trick here is to work from the bottom up
    for (int i = 1; i <= n; i++) {

        int max_price = prices[i-1]; // Without cuts

        // Try all cuts length with combo from existing cache
        for (int j = 1; j <  i; j++) {
            max_price = Math.max(max_price, maxPrices[i-j] + prices[j-1]);
        }
        maxPrices[i] = max_price;
    }

    return maxPrices[n];

}


texts: Parsing a text file of nested structures using a state machine

texts:
My goal is to have something really simple with as small an amount of code as possible.  The real code is used to parse a text file of nested structures. This code is highly simplified but is the general way that the state machine would work.

Is there a replacement for the global?

# python doesn't support enums but can do this way
class state:
    OUT = 0
    DNARRAY = 1            # under "DN array" heading
    CSTA_REQUEST = 2       # aPDU-rose : invoke :
    CSTA_RESPONSE = 3      # aPDU-rose : retResult :
    END_OF_FILE   = 4

currentstate = state.OUT

def do_out():
    print "doing OUT - transitioning to DNARRAY"
    global currentstate
    currentstate = state.DNARRAY

def do_dnarray():
    print "doing dn array - transitioning to csta request"
    global currentstate
    currentstate = state.CSTA_REQUEST

def do_csta_request():
    print "doing csta request - transitioning to csta response"
    global currentstate
    currentstate = state.CSTA_RESPONSE

def do_csta_response():
    print "doing csta response - transitioning to END_OF_FILE"
    global currentstate
    currentstate = state.END_OF_FILE

statemap = {state.OUT : do_out,
           state.DNARRAY : do_dnarray,
           state.CSTA_REQUEST : do_csta_request,
           state.CSTA_RESPONSE : do_csta_response,
}

def decisions():
    while(currentstate != state.END_OF_FILE):
        statemap[currentstate]()

    print "done!"

decisions()


texts:
This query currently takes approximately 250 seconds to run and I'd like to reduce it by as much as I can. I have tried using left joins instead of subqueries and it increases run time.

SELECT `items`.`id`,

ifnull((SELECT sum(`history`.`quantity`) FROM `history` where `history`.`itemID` = `items`.`id` and `history`.`date` > date_sub(now(), interval 7 DAY) group by `itemID`), '0') as `sold7`,
ifnull((SELECT round(`supply`) FROM `supply` WHERE `itemID` = `items`.`id` AND `date` > date_sub(now(), interval 7 DAY) group by `itemID`), '0') as `listed7`,

ifnull((SELECT sum(`history`.`quantity`) FROM `history` where `history`.`itemID` = `items`.`id` and `history`.`date` > date_sub(now(), interval 30 DAY) group by `itemID`), '0') as `sold30`,
ifnull((SELECT round(`supply`) FROM `supply` WHERE `itemID` = `items`.`id` AND `date` > date_sub(now(), interval 30 DAY) group by `itemID`), '0') as `listed30`,

ifnull((SELECT sum(`history`.`quantity`) FROM `history` where `history`.`itemID` = `items`.`id` and `history`.`date` > date_sub(now(), interval 60 DAY) group by `itemID`), '0') as `sold60`,
ifnull((SELECT round(`supply`) FROM `supply` WHERE `itemID` = `items`.`id` AND `date` > date_sub(now(), interval 60 DAY) group by `itemID`), '0') as `listed60`,

ifnull((SELECT sum(`history`.`quantity`) FROM `history` where `history`.`itemID` = `items`.`id` and `history`.`date` > date_sub(now(), interval 90 DAY) group by `itemID`), '0') as `sold90`,
ifnull((SELECT round(`supply`) FROM `supply` WHERE `itemID` = `items`.`id` AND `date` > date_sub(now(), interval 90 DAY) group by `itemID`), '0') as `listed90`,

ifnull((SELECT sum(`history`.`quantity`) FROM `history` where `history`.`itemID` = `items`.`id` and `history`.`date` > date_sub(now(), interval 180 DAY) group by `itemID`), '0') as `sold180`,
ifnull((SELECT round(`supply`) FROM `supply` WHERE `itemID` = `items`.`id` AND `date` > date_sub(now(), interval 180 DAY) group by `itemID`), '0') as `listed180`

FROM `items`

group by `items`.`id`


texts:
I made a brute force password cracker with Python, but it's extremely slow. How can I make it faster?

import itertools
import string
import time

def guess_password(real):
    chars = string.ascii_uppercase + string.digits
    password_length = 23
    start = time.perf_counter()
    for guess in itertools.product(chars, repeat=password_length):
        guess = ''.join(guess)
        t = list(guess)
        t[5] = '-'
        t[11] = '-'
        t[17] = '-'
        tg = ''.join(t)
        if tg == real:
            return 'Scan complete. Code: \'{}\'. Time elapsed: {}'.format(tg, (time.perf_counter() - start))

print(guess_password('E45E7-BYXJM-7STEY-K5H7L'))

As I said, it's extremely slow. It takes at least 9 days to find a single password.


texts: Next node of a node in Binary search tree

texts:
To find the node next to a given node we need to consider two cases.
case 1: if the node has a right subtree then return the min node in its right subtree.
case 2: if the node doesn't have a right subtree then return the ancestor of the node whose left subtree contains the node.

class NodeWithParent {
    int data;
    NodeWithParent left;
    NodeWithParent right;
    NodeWithParent parent;

    NodeWithParent(int x) {
        data = x;
    }
}

public class nextNodeOfANodeInBST {

    public static NodeWithParent getMin(NodeWithParent root) {
        while (root.left != null) {
            root = root.left;
        }
        ;
        return root;
    }

    public static NodeWithParent nextNode(NodeWithParent curNode) {
        if (curNode == null) {
            return null;
        }
        if (curNode.right != null) {
            return getMin(curNode.right);
        } else if (curNode.data > curNode.parent.data) // its the right child
        {
            // find an ancestor for which the curNode is in the left subtree
            while (curNode.parent != null && curNode.data > curNode.parent.data) {
                curNode = curNode.parent;
            }
            if (curNode.parent != null && curNode.parent.data < curNode.data)
                return curNode;
            else
                return curNode.parent;

        } else
            return curNode.parent;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        NodeWithParent root = new NodeWithParent(15);
        root.parent = null;
        root.left = new NodeWithParent(10);
        root.left.parent = root;
        root.right = new NodeWithParent(20);
        root.right.parent = root;
        root.left.left = new NodeWithParent(8);
        root.left.left.parent = root.left;
        root.right.right = new NodeWithParent(25);
        root.right.right.parent = root.right;
        root.right.left = new NodeWithParent(17);
        root.right.left.parent = root.right;
        root.left.right = new NodeWithParent(12);
        root.left.right.parent = root.left;
        root.left.left.left = new NodeWithParent(6);
        root.left.left.left.parent = root.left.left;
        root.left.right.left = new NodeWithParent(11);
        root.left.right.left.parent = root.left.right;
        root.right.left.left = new NodeWithParent(16);
        root.right.left.left.parent = root.right.left;
        root.right.right.right = new NodeWithParent(27);
        root.right.right.right.parent = root.right.right;
        NodeWithParent nextNode = nextNode(root.right.left);
        if (nextNode != null)
            System.out.println(nextNode.data);
        else
            System.out.println("No next node for " + root.right.left.data);
    }
}


texts: Python program to calculate what pawns are safe

texts:
In chess there are eight rows numbered from 1 to 8 and 8 columns a-h. Pawns which are on the lowest row are always in danger to be captured. The objective of the program is to calculate which pawns are saved.

Given the coordinates of seven pawns return the number of pawns which are safe.

For example:

safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6
safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1
safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e3"}) == 2

The code:

def safe_pawns(pawns: set) -> int:
    row_numbers = []
    list_of_pawns = list(pawns)
    letters_string = "abcdefgh"
    safe_pawns_list = []

    #check if there are neighbors which protect you
    for pawn in list_of_pawns:
        if pawn[0] == "a":
            if letters_string[1] + str(int(pawn[1])-1) in list_of_pawns:
                safe_pawns_list.append(pawn)
        elif pawn[0] == "h":
            if letters_string[6] + str(int(pawn[1])-1) in list_of_pawns:
                safe_pawns_list.append(pawn)
        else:
            if ((letters_string[letters_string.index(pawn[0]) + 1] + str(int(pawn[1]) - 1))
            in list_of_pawns):
                 safe_pawns_list.append(pawn)
            elif (letters_string[letters_string.index(pawn[0]) - 1] + str(int(pawn[1]) - 1)
            in list_of_pawns):
                safe_pawns_list.append(pawn)

    #delete the pawns which belong to the lowest row number
    for pawn in list_of_pawns:
        row_numbers.append(pawn[1])

    lowest_row_indexes = []

    for i, row_number in enumerate(row_numbers):
        if row_number == min(row_numbers):
            lowest_row_indexes.append(i)

    for i, lowest_row_index in enumerate(lowest_row_indexes):
        del list_of_pawns[lowest_row_index - i]
        del row_numbers[lowest_row_index - i]

    return len(safe_pawns_list)

How could this be improved?


texts:
I want to easily measure method's execution time. Of course instead of doing something like this:

var timer = Stopwatch.StartNew();
DoSomething();
timer.Stop();
Console.WriteLine(timer.ElapsedMilliseconds)

I want to make it more elegant. What I've managed is something like this:

static class MethodMeasurer
{
    public static T Invoke<T>(Func<T> action, out Stopwatch stopwatch)
    {
        var timer = Stopwatch.StartNew();
        var res = action.Invoke();
        timer.Stop();
        stopwatch = timer;
        return res;
    }

    public static void Invoke(Action action, out Stopwatch stopwatch)
    {
        var timer = Stopwatch.StartNew();
        action.Invoke();
        timer.Stop();
        stopwatch = timer;
    }
}

And here is the usage:

class Program
{
    static void Main(string[] args)
    {
        MethodMeasurer.Invoke(DoSomething1, out var s1);
        Console.WriteLine("s1 executed time: " + s1.ElapsedMilliseconds);

        var doSomething2Measured = MethodMeasurer.Invoke(DoSomething2, out var s2);
        Console.WriteLine("s2 executed time: " + s2.ElapsedMilliseconds);
        Console.WriteLine("s2 returned: " + doSomething2Measured);

        var doSomething3Measured = MethodMeasurer.Invoke(() => DoSomething3(5), out var s3);
        Console.WriteLine("s3 executed time: " + s3.ElapsedMilliseconds);
        Console.WriteLine("s3 returned: " + doSomething3Measured);
    }

    static void DoSomething1()
    {
        Thread.Sleep(100);
    }

    static int DoSomething2()
    {
        Thread.Sleep(300);
        return 1;
    }

    static int DoSomething3(int i)
    {
        Thread.Sleep(300);
        return i;
    }
}

So what do you think about that? Would you suggest I use a different solution, or is mine okay?


texts:
Please review and tell me what improvements can be made:

package trees;

import java.util.LinkedList;
import java.util.Queue;

public class PrintBSTLevelByLevel {

     public static class Node {

        int data;
        Node left;
        Node right;

        Node(int val){

            this.data = val;
            Node left = null;
            Node right = null;

        }
    }

      public void LevelOrderQueue(Node root){

          Queue q = new LinkedList();
          int levelNodes = 0;

          if(root == null) return;
          q.add(root);

          while(!q.isEmpty()){

              levelNodes = q.size();

              while (levelNodes > 0){

                  Node n = (Node)q.remove();
                  System.out.println(""+n.data);
                  if(n.left!= null)
                      q.add(n.left);
                  if(n.right!=null)
                      q.add(n.right);
                  levelNodes--;

              }
              System.out.println("");

          }

          //return null;
      }

    public static void main(String[] args) {

        Node root = new Node(5);

        root.left = new Node(10);
        root.right = new Node(15);
        root.left.left = new Node(20);
        root.left.right = new Node(25);
        root.right.left = new Node(30);
        root.right.right = new Node(35);

        PrintBSTLevelByLevel l = new PrintBSTLevelByLevel();

        System.out.println(" Output by Better Approach : ");
        l.LevelOrderQueue(root);

    }

}


texts:
I often make changes on my code-base and manually using sed, awk or perl -pi -e is not always as efficient as having a simple alias: git pie.

Furthermore, because I am working on Cygwin, I cannot do real in-place replacement without a temporary file that I have to manually suppress afterwards.

Last but not least, sed, awk and perl -pi -e touch all the files that make them new from the point of view of make. I rather want to touch only the file with real changes so I wrote this Git alias:

[alias]

    # Replace
    pie = "!f() {                                            \
        git ls-files -z | xargs -0 perl -e '                 \
            my $eval = shift @ARGV;                          \
            foreach my $file (@ARGV) {                       \
                next unless -f $file;                        \
                open my $fd, \"<\", $file;                   \
                my $content = do { local $/; <$fd>};         \
                close $fd;                                   \
                my $new = do { $_ = $content; eval $eval; }; \
                if ($content ne $new) {                      \
                    open my $fd, \">\", $file;               \
                    print $fd $_;                            \
                    close $fd;                               \
                }                                            \
            }                                                \
        ' \"$1\"; }; f"

I am sure some simplifications can be made on this piece of code, so I ask for your opinion.

The usage is:

$ git pie s/foo/bar/g

I decided to slurp the whole file in memory in order to do multiline regexes which is very convenient sometime despite the performance.

There is perhaps a missing feature: the ability to exclude or include some file extensions only or simply allow this call:

$ git ls-files | grep -P '[.][ch]$' | xargs git pie s/foo/bar/

I still didn't figure out how I want to do it. One possible way is:

$ git pie 's/foo/bar/ if $file =~ /\.(ch)$/'


texts:
I've just solve one problem that notifies users if their password is going to expire in 14 days.  The script is working fine. I just want to improve my code and desire some suggestions.

#!/usr/bin/env python
# Author :- Rahul Patil<linuxian.com>
#

import sys
import os

#-----------------------------------------------------------------
# Provide Ldap DN Details to Perform Ldap Search using anonymouse
#-----------------------------------------------------------------
Domain = 'linuxian.com'
EmailDomain = 'abc.om' # if your mail domain is different this will becom user@abc.com
ConnectDC = 'ldap://localhost:389'
# if 14 days remains to expire password then it will send email to that user
# until user update the new password
PwdWarnDays = 14
pwdMaxAge = 45 # default password expire in 45 days as per ldap ppolicy

Subject = "Ldap Password Expiry Details"

MsgBody = """
Dear %s,
    Your Password Will be Expire in %s, we request you to please
change your password, your last password change date is %s

Best Regards,
Linux Admin
"""

def GetUserDetails():
        """ This Function Will save all details in file
        it will use ldap search query for the same."""
        # Create bind dn eg. dc=example,dc=com
        BindDN = ','.join([ 'dc=' + d for d in Domain.split('.') ])
        #
        import ldap
        l = ldap.initialize(ConnectDC)
        # Perform Ldap Search
        return  l.search_s(
                BindDN,
                ldap.SCOPE_SUBTREE,
                '(uid=*)',['uid','pwdChangedTime']
            )

def CheckExpiry():
        """
        This Function will Check each user ExpiryWarning
        if it more thans WarningDays then it will send Emails
        to that particuler user
        """
         import datetime
         for k,v in Users:
                    uid = ''.join(v['uid'])
                    if 'pwdChangedTime' not in v:
                            pass
                            #print "User " + uid + "  not Updated Password"
                    try:
                          l = ''.join(v['pwdChangedTime'])
                    except:
                            pass

                    if 'pwdChangedTime' in v:
                        # To extrace year month day
                        d1 = datetime.date.today()
                        d2 = datetime.date(int(l[0:4]),int(l[4:6]),int(l[6:8]))
                        DaysOfPasswordChange = (d1 - d2).days
                        d2 = d2.strftime('%d, %b %Y')

                        ExpireIn = pwdMaxAge - DaysOfPasswordChange

                        # if password not changed before 14 days
                        if ExpireIn <= PwdWarnDays:
                            SendMail = "echo '" + MsgBody % (uid,ExpireIn,d2) + "' \
                                      mail -s " + '"' + Subject + '"' + ' ' + \
                                      uid + '@' + EmailDomain
                            #os.system(SendMail)
                            print SendMail

if __name__ == '__main__':
        Users = GetUserDetails()
        CheckExpiry()


texts: this code returns environment varibles or passed enverionment variable with values

texts:
#!/usr/bin/env python

import os, sys

variable =  sys.argv

def enVar(variable):
        """
        This function returns all the environment variable set on the machine or in active project.
        if environment variable name is passed to the enVar function it returns its values.
        """
        nVar = len(sys.argv)-1
        if len(variable) == 1: # if user entered no environment variable name
                for index, each in enumerate(sorted(os.environ.iteritems())):
                        print index, each
        else: # if user entered one or more than one environment variable name
                for x in range(nVar):
                        x+=1
                        if os.environ.get(variable[x].upper()): # convertes to upper if user mistakenly enters lowecase
                                print "%s : %s" %  (variable[x].upper(), os.environ.get(variable[x].upper()))
                    else: print 'Make sure the Environment variable "%s" exists or spelled correctly.' % variable[x]

enVar(variable)

i run the above file as show.py is their a better way to do it ?


texts: Binary Search Implementation for Integer Array

texts:
Purpose

Implement a binary search algorithm that takes a sorted int array and some int target value and returns the index of the
target value, if it exists.

Discussion

The way I thought about implementing a binary search algorithm was the following

Given an array of sorted int values, pick the first, last, and middle indices (round down if there is an even number of indices).
If the target value equals any of the values at the first/ last / middle index, return that index.
Else, check to see if the target value is less / greater than the middle index value.

If it's less than the middle index value, than we can assume that the target value, if it exists,
is between the first index and the middle index (since the array should be sorted). Thus, we can call our search
function on this sub-array, specifying a start index of the first index + 1 (since we already checked this)
and an end index of the middle index - 1 (again, since we already checked this).
If it's greater than the middle index value, we can assume that the target value is between the middle index and the last index.
Thus, we can call the search function on this sub-array, specifying a start index of the middle index + 1 and an
end index of the last index - 1.

We continue this process of analyzing the sub-arrays until our sub-array is empty, in which case a NoSuchElementException
is thrown.

Things that I'm unsure about

Does it make sense to have the public search method immediately call the private searchSubArray method?
The reason I did this is to obfuscate the idea of a leftIndex / rightIndex from the API user.
Does the NoSuchElementException make sense? Would returning -1 make more sense?
Any particular thoughts on my use of early returns?

Implementation

import java.util.NoSuchElementException;

public class BinarySearcher {
    /**
     * Executes a binary search for some target value given an input array of sorted values
     * @param values a sorted array
     * @param target a value to search for
     * @return the index of the target value, if it exists. If the target value does not exist, a NoSuchElementException is thrown.
     */
    public static int search(int[] values, int target) {
        return searchSubArray(values, 0, values.length - 1, target);
    }

    private static int searchSubArray(int[] values, int leftIndex, int rightIndex, int target) {
        if (values.length == 0 || leftIndex < 0 || rightIndex < 0) {
            throw new NoSuchElementException(String.format("Unable to find target: {} in values", target));
        }

        if (target == values[leftIndex]) {
            return leftIndex;
        }

        if (target == values[rightIndex]) {
            return rightIndex;
        }

        int middleIndex = Double.valueOf(Math.floor((rightIndex - leftIndex) / 2)).intValue();

        int middleValue = values[middleIndex];

        if (target < middleValue) {
            return searchSubArray(values, leftIndex + 1, middleIndex - 1, target);
        }

        else if (target > middleValue) {
            return searchSubArray(values, middleIndex + 1, rightIndex - 1, target);
        }

        else {
            return middleIndex;
        }
    }
}


texts: Reconstruct a string, given a list of subsequence triplets

texts:
I wrote a solution to this CodeWars challenge:

  There is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string.

  A triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. "whi" is a triplet for the string "whatisup".

  As a simplification, you may assume that no letter occurs more than once in the secret string.

  You can assume nothing about the triplets given to you other than that they are valid triplets and that they contain sufficient information to deduce the original string. In particular, this means that the secret string will never contain letters that do not occur in one of the triplets given to you.

So, for example, given triplets [['t','u','p'], ['w','h','i'], ['t','s','u'], ['a','t','s'], ['h','a','p'], ['t','i','s'], ['w','h','s']], my code would reconstruct the secret string whatisup.  My code builds a dictionary, with each character from string as a key, and possible characters that precede the key as the value.  Then, it loops through the dictionary, building the secret string a character at a time.

def recoverSecret(triplets):
    secret = ''
    secret_dict = {}
    # any better way to build a dictionary based on relationship of triplets?
    for x in triplets:
        for y in x:
            secret_dict.setdefault(y, set()).update(x[x.index(y) - 1]) if x.index(y) != 0 else secret_dict.setdefault(y, set())

    def removeChar(c) -> dict:
        '''find first char in secret'''
        #any better way to remove element from set that is value of dictionary when value in set?
        {v.remove(c) for k, v in secret_dict.items() if c in v}

    def findChar() -> str:
        '''find first char in secret when there is no char in front of it'''
        #any better way to find character when value is dictionary is empty?
        return next(k for k, v in secret_dict.items() if not v)

    while secret_dict:
        first_char = findChar()
        #any better way to rebuild dictionary when key == k?
        secret_dict = {k: v for k, v in secret_dict.items() if k != first_char}
        removeChar(first_char)
        secret = secret + first_char
    return secret


texts: Adding SecureString support to Lib2GitSharp

texts:
A library that I use doesn't support SecureString in its credentials for connecting to GitHub, so I'm submitting a pull request to add it. I know it's not ideal to pull the actual string out, but the idea here is to minimize the amount of time the string is in memory. Also, allowing client code to utilize the fact that WPF uses a SecureString for passwords without having to do this conversion themselves.

Am I handling the SecureString "correctly" here? I know very little about unmanaged memory.
Is it a poor decision to store the Username in one as well? I'm second guessing that decision now. NetworkCredential uses a plain string for this and the secure version only for the password.

Some notes:

I would use a constructor, but it's the style of the project to use an object initializer.
It's also in the style of the project to place the properties at the bottom like you'll see below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibGit2Sharp.Core;
using System.Security;
using System.Runtime.InteropServices;

namespace LibGit2Sharp
{
    /// <summary>
    /// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access.
    /// </summary>
    public sealed class SecureUsernamePasswordCredentials : Credentials
    {
        /// <summary>
        /// Callback to acquire a credential object.
        /// </summary>
        /// <param name="cred">The newly created credential object.</param>
        /// <returns>0 for success, &lt; 0 to indicate an error, &gt; 0 to indicate no credential was acquired.</returns>
        protected internal override int GitCredentialHandler(out IntPtr cred)
        {
            if (Username == null || Password == null)
            {
                throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password.");
            }

            IntPtr passwordPtr = IntPtr.Zero;
            IntPtr userNamePtr = IntPtr.Zero;

            try
            {
                passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password);
                userNamePtr = Marshal.SecureStringToGlobalAllocUnicode(Username);

                return NativeMethods.git_cred_userpass_plaintext_new(out cred, Marshal.PtrToStringUni(userNamePtr), Marshal.PtrToStringUni(passwordPtr));
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
                Marshal.ZeroFreeGlobalAllocUnicode(userNamePtr);
            }

        }

        /// <summary>
        /// Username for username/password authentication (as in HTTP basic auth).
        /// </summary>
        public SecureString Username { get; set; }

        /// <summary>
        /// Password for username/password authentication (as in HTTP basic auth).
        /// </summary>
        public SecureString Password { get; set; }
    }
}


texts:
I made this simple game code. Can you please give me some advice on how I can improve it?

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include <time.h>
#include <windows.h>

void main ()
{
    printf("\t\tWelcome to our gessing game\n\n\n");
    printf("the computer choose a random number between 1-99, try to gess the random number...");

    srand(time(NULL));

    int gess,i=0,found=0,  r = rand()%100;

    while (i<10 && found==0)
    {
        printf("\n My gess is:\t");
        scanf("%d",&gess);
        if (gess==r)
        {
            found=1;
            i++;
        }
        else if(gess>r)
        {
            printf("\n Too big\n");
            i++;
        }
        else if(gess<r)
        {
            printf("\n Too small\n");
            i++;
        }
    }
    if (found==1&&gess==1)
        printf("\n Very good the number is %d this is your %dst gess",gess,i);
    else if(found==1&&gess==2)
        printf("\n very good the number is %d this is your %dnd gess",gess,i);
    else if(found==1&&gess==3)
        printf("\n very good the number is %d this is your %drd gess",gess,i);
    else if(found==1&&gess!=1&&gess!=2&&gess!=3)
        printf("\n very good the number is %d this is your %dth gess",gess,i);
    else
        printf("\n Never mind try again");
    getch();
}


texts:
I was asked to perform the following tasks at one of the technical interviews. I did the BST implementation in python. I think the solution passed all of the solution. I broke down the tasks in the following bulletin:

#  1) initilize the binary Search tree
#  2) Implement the "put" and "contains" methods with helper function
#  3) Test the "inOrderTraversal" method.
#  4) Add additional relevant tests

import unittest

class BST(object):
    def __init__(self):
        self.root = Node()

    def put(self, value):
        self._put(value, self.root)

    def _put(self, value, node):
        if node.value is None:
            node.value = value
        else:
            if value < node.value:
                if node.left is None:
                    node.left = Node()
                self._put(value, node.left)
            else:
                if node.right is None:
                    node.right = Node()
                self._put(value, node.right)

    def contains(self, value):
        return self._contains(value, self.root)

    def _contains(self, value, node):
        if node is None or node.value is None:
            return False
        else:
            if value == node.value:
                return True
            elif value < node.value:
                return self._contains(value, node.left)
            else:
                return self._contains(value, node.right)

    def in_order_traversal(self):
        acc = list()
        self._in_order_traversal(self.root, acc)
        return acc

    def _in_order_traversal(self, node, acc):
        if node is None or node.value is None:
            return
        self._in_order_traversal(node.left, acc)
        acc.append(node.value)
        self._in_order_traversal(node.right, acc)

class Node(object):
    def __init__(self, value=None, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

class TestBST(unittest.TestCase):
    def setUp(self):
        self.search_tree = BST()

    def test_bst(self):
        self.search_tree.put(3)
        self.search_tree.put(1)
        self.search_tree.put(2)
        self.search_tree.put(5)
        self.assertFalse(self.search_tree.contains(0))
        self.assertTrue(self.search_tree.contains(1))
        self.assertTrue(self.search_tree.contains(2))
        self.assertTrue(self.search_tree.contains(3))
        self.assertFalse(self.search_tree.contains(4))
        self.assertTrue(self.search_tree.contains(5))
        self.assertFalse(self.search_tree.contains(6))

        self.assertEqual(self.search_tree.in_order_traversal(), [1,2,3,5])

    def test_empty(self):
        self.assertEqual(self.search_tree.in_order_traversal(), [])

    def test_negative(self):
        self.search_tree.put(-1)
        self.search_tree.put(11)
        self.search_tree.put(-10)
        self.search_tree.put(50)
        self.assertTrue(self.search_tree.contains(-1))
        self.assertTrue(self.search_tree.contains(11))
        self.assertTrue(self.search_tree.contains(-10))
        self.assertTrue(self.search_tree.contains(50))

        self.assertEqual(self.search_tree.in_order_traversal(), [-10,-1,11,50])

    def test_dupes(self):
        self.search_tree.put(1)
        self.search_tree.put(2)
        self.search_tree.put(1)
        self.search_tree.put(2)
        self.assertTrue(self.search_tree.contains(1))
        self.assertTrue(self.search_tree.contains(2))

        self.assertEqual(self.search_tree.in_order_traversal(), [1,1,2,2])

    def test_none(self):
        self.search_tree.put(None)
        self.assertFalse(self.search_tree.contains(None))

        self.assertEqual(self.search_tree.in_order_traversal(), [])

if __name__ == '__main__':
    unittest.main()


texts:
Challenge
Swap the numbers surrounding the words in sentences.
Specifications

The first argument is a path to a file.
The file contains multiple lines.
Each line is a test case represented by a sentence.
Each sentence begins and ends with a number.
Print out the sentence obtained by swapping the numbers surrounding each word.

Constraints

The suffix and the prefix of each word may be equal.
Sentences are from 1 to 17 words long.
The number of test cases is 40.
All characters are ASCII.
The numbers are single digit positive intgers 0-9.

Sample Input

4Always0 5look8 4on9 7the2 4bright8 9side7 3of8 5life5
5Nobody5 7expects3 5the4 6Spanish4 9inquisition0

Sample Output

0Always4 8look5 9on4 2the7 8bright4 7side9 8of3 5life5
5Nobody5 3expects7 4the5 4Spanish6 0inquisition9

Source
My solution
#include <stdio.h>
#include <ctype.h>

#define LINE_BUFFER 256

int fileExists(char *filename) {
    FILE *file = fopen(filename, "r");
    if (file != NULL) {
        fclose(file);
    }
    return file != NULL;
}

void swapNumbers(char line[LINE_BUFFER]) {
    int temp = 0;
    int position = 0;
    int swapped = 0;

    for (int i = 0; i < LINE_BUFFER; i++) {
        if (isdigit(line[i])) {
            if (!swapped) {
                position = i;
                temp = line[i];
                swapped = 1;
            } else {
                line[position] = line[i];
                line[i] = temp;
                swapped = 0;
            }
        }
    }
}

int main(int argc, char *args[]) {
    if (argc < 2) {
        puts("File path not provided.");
        return 1;
    }

    if (argc > 2) {
        puts("Excessive arguments, only the first will be considered.");
    }

    if (!fileExists(args[1])) {
        puts("Could not access file / file not found.");
        return 1;
    }

    FILE *file = fopen(args[1], "r");
    char line[LINE_BUFFER];

    while (fgets(line, LINE_BUFFER, file)) {
        swapNumbers(line);
        printf("%s", line);
    }

    fclose(file);
}


texts:
I'm building an iOS app for test-taking and I want to be sure of my model before proceeding.

I found this post very helpful and tried to implement a simplified version for Core Data.

Here are some of my assumptions:

Each User can take multiple tests
Each User has one set of answers per Test taken
Each Test has one User
Each Question has many answers

Here is my Core Data model:

Overall, what do you think of my database schema? Is it sufficient to handle a simple test-taking app?

Also, are Test_Questions and User_Answers necessary?

I could, in theory, have a relationship directly between Test andQuestion? Test -->> Question. I would like to know which is better.

Here are my model headers for Test_Questions and User_Answers:

Test_Questions.h

@class Question, Test;

@interface Test_Questions : NSManagedObject

@property (nonatomic, retain) Test *test;
@property (nonatomic, retain) NSSet *questions;
@end

@interface Test_Questions (CoreDataGeneratedAccessors)

- (void)addQuestionsObject:(Question *)value;
- (void)removeQuestionsObject:(Question *)value;
- (void)addQuestions:(NSSet *)values;
- (void)removeQuestions:(NSSet *)values;

@end

User_Answers.h

@class Answer, User;

@interface User_Answers : NSManagedObject

@property (nonatomic, retain) User *user;
@property (nonatomic, retain) NSSet *userAnswersSet;
@end

@interface User_Answers (CoreDataGeneratedAccessors)

- (void)addUserAnswersSetObject:(Answer *)value;
- (void)removeUserAnswersSetObject:(Answer *)value;
- (void)addUserAnswersSet:(NSSet *)values;
- (void)removeUserAnswersSet:(NSSet *)values;

@end


texts:
Please review my custom ArrayList class I constructed from scratch and add any suggestions or constructive criticisms. The point of this template class is give the user a lightweight ArrayList with optimal control over how it operates.

It is automatically created on the heap with an optional seed value which determines how much space to give it upon being recreated after filling up. It comes with a refine function which cuts off the garbage values at any time and it can also be reseeded. Seed default is 10 new array spots for each recreation.

#ifndef MEMORYLIST_H
#define MEMORYLIST_H

//Class is designed to be a basic array list off the stack
template <class Heap> class MemoryList {
private:
    Heap *array;    //ArrayList on Heap
    int length;     //Max Length of ArrayList
    int counter;    //Current Position on ArrayList
    int seed;       //amount to add by when limit is breached

    //Increase list if needed
    inline void spaceCheck() {
        if (counter == length) {
            int i;

            Heap *temp = new Heap[length];

            for (i = 0; i < length; ++i) {
                temp[i] = array[i];
            }

            delete [] array;

            length += seed;
            array = new Heap[length];

            for (i = 0; i < length - 10; ++i) {
                array[i] = temp[i];
            }

            delete[] temp;
        }
    }

    inline void shiftRight(int place) {
        for (int i = length - 1; i >= place + 1; --i) {
            array[i] = array[i - 1];
        }
    }

public:
    MemoryList(int seed = 10) {
        this->seed = seed;
        length = seed;
        counter = 0;
        array = new Heap[length];
    }

    //just shows what value is stored in what position
    Heap showValue(int position) {
        return array[position];
    }

    //tack a value to the end
    void newValue(Heap variable){
        spaceCheck();

        array[counter] = variable;
        ++counter;
    }

    //tack a value anywhere you want and array will self adjust
    void insertValue(int position, Heap variable) {
        spaceCheck();
        shiftRight(position);

        array[position] = variable;
        ++counter;
    }

    //delete any value you'd like and array will self adjust
    void deleteValue(int position) {
        for (int i = position; i < length - 1; ++i) {
            array[i] = array[i + 1];
        }

        --counter;
    }

    //Overwrite any value you'd like, no need to adjust anything
    void overWrite(int position, Heap variable) {
        array[position] = variable;
    }

    //swap any two array points
    void swap (int position1, int position2) {
        Heap temp;
        temp = array[position1];
        array[position1] = array[position2];
        array[position2] = temp;
    }

    //reseed amount of space you'd like to allocate when you're running out
    //of room
    void reSeed(int seed) {
        this->seed = seed;
    }

    //is item in array?
    bool search(Heap item) {
        //this might make it faster ::shrug::
        for (int i = 0, j = counter; i < counter; ++i, --j) {
            if (array[i] == item || array[j] == item) return true;
        }
        return false;
    }

    //Creates perfect ArrayList stored on heap without garbage
    void refine() {
        int i;

        length = counter;
        Heap *temp = new Heap[length];

        for (i = 0; i < length; ++i) {
            temp[i] = array[i];
        }

        delete [] array;
        array = new Heap[length];

        for (i = 0; i < length; ++i) {
            array[i] = temp[i];
        }

        delete[] temp;
    }

    void finished(){
        delete[] array;
    }
};

#endif // MEMORYLIST_H


texts: Pulls href tags using BeautifulSoup with Python

texts:
As if this isn't extremely obvious, I am a new coder.

My code works, but is quite far from ideal. I'm also not sure if there are unnecessary bits, since I've been trying to get this to work for a few days on and off, so I've started and stopped multiple times.

The goal is to have cleaner code, with a #comment on each line (unless extremely basic) so as to improve my annotation habits. Please let me know what you would do to improve it overall.

import urllib.request as ur
from bs4 import BeautifulSoup

url = str(input('Enter URL- ')) #convert input to string
html = ur.urlopen(url).read() #read html
soup = BeautifulSoup(html, "html.parser") #retrieve all of the anchor tags
Count_ = int(input('Enter count: ')) #convert input to integer
pos_1 = int(input('Enter position: ')) #convert input to integer
tags = soup('a')
final = '' #url of name list before break
curpos = ''
print('Retrieving: ', url) #prints starting point/url
count = int(Count_) + 1
while count > 1 : #starting a definite loop that goes until count is smaller than 1
    pos = 0
    for tag in tags :
        if pos == int(pos_1) - 1 : #conditional statement regarding position
            curpos = tag.get('href', None)
            break
        pos = pos + 1 #increases value of pos for each tag
    final = curpos #
    url = str(curpos) #
    html = ur.urlopen(url).read()
    soup = BeautifulSoup(html, "html.parser")
    tags = soup('a')
    count = count - 1 #for every iteration in the loop, subtract 1 from the value of count
    print('Retrieving: ', final)


texts: Simple C++ Dynamicly allocated Matrix with only one memory allocation

texts:
I was bothered with existing matrix allocation methods that take variable rows and columns, so I made a small class that only needs one memory allocation.

template <typename T>
class Matrix{
    T* data;
    size_t rows, columns;

public:
    Matrix(const size_t rows, const size_t columns) : rows(rows), columns(columns) {
        // One single allocation to store data
        data = new T[rows+columns + 1];
    }

    T* operator[](const size_t r) {
        return data+(r*columns);
    }
};

// Example

int main() {

    Matrix<int> mat(5,3);

    mat[2][1] = 1;

    //...

}


texts: Selecting and inserting MySQL records using PDO

texts:
This PHP class connects to and queries the database MuSKL. I am a novice, and I ask you to comment on the approach and style of code.

<?php

class MysqlAccess {

    private $dsn = 'mysql:dbname=bid;host=127.0.0.1';
    private $user = 'bid_root';
    private $password = 'e1e2e3e4e5er';
    private static $_db;
    private $_PDO;
    public $fetchQueryResult;

    private function __construct() {
        try {

            $this->_PDO = new PDO($this->dsn, $this->user, $this->password);

            $this->_PDO->exec('SET NAMES utf8');
        } catch (PDOException $e) {

            echo $e->getMessage();
        }
    }

    protected function __clone() {}

    static public function getInstance() {
        if (is_null(self::$_db)) {
            self::$_db = new self();
        }
        return self::$_db;
    }

    public function querySelect($tableName, array $arrayColum) {

        if (!is_array($arrayColum) or ! is_string($tableName)) {
            die('Неверный формат данных в запросе SELECT в запросе SQL');
        }

        $colums;

        foreach ($arrayColum as $value) {
            if (!is_string($value)) {
                die('Неверный формат данных в запросе SQL');
            }
            $colums .= SequrityData::SequrityReturnData($value) . ', ';
        }

        $colums = substr($colums, 0, -2);

        // запрос к базе данных
        $results = $this->_PDO->query('SELECT ' . $colums . ' FROM ' . SequrityData::SequrityReturnData($tableName));

        $this->fetchQueryResult($results);
    }

    public function queryInsert($tableName, array $arrayColums) {

        if (!is_array($arrayColums) or ! is_string($tableName)) {
            die('Неверный формат данных в запросе SELECT в запросе SQL');
        }

        $colums;

        foreach ($arrayColums as $key => $value) {

            if (!is_string($value) or ! is_string($key)) {

                die('Неверный формат данных в запросе SQL');
            }
            $colums .= SequrityData::SequrityReturnData($key) . ', ';
            $values .= '\'' . SequrityData::SequrityReturnData($value) . '\', ';
        }
        $colums = substr($colums, 0, -2);
        $values = substr($values, 0, -2);

        $tableName = SequrityData::SequrityReturnData($tableName);
        $insert = "INSERT INTO $tableName ($colums) VALUES ($values)";
        $this->_PDO->query($insert);
    }

    function __set($name, $value) {

        if (!is_string($name) && !is_string($value)) { // проверка на строку
            die('Неверный формат в сеттере');
        }

        $this->$name = $value;
    }

    private function fetchQueryResult($results) {

        $arrResult = $results->fetchAll(PDO::FETCH_ASSOC);

        foreach ($arrResult as $key => $value) {

            $this->$key = $value;
        }
    }
}


texts: Extract and divide algorithm implementation in Elixir

texts:
I just started learning Elixir and stumbled upon this challenge over on Programming Puzzles & Code Golf. It is a well-suited task for beginners, so I chose to give it a go (to be clear, give it a go means solve it normally, not golfing it). To keep this question self-contained, here is the task – citing the linked post:

  For a given positive integer \$n\$:

  Repeat the following until \$n < 10\$ (until \$n\$ contains one digit).
  Extract the last digit.
  If the extracted digit is even (including 0) multiply the rest of the integer by \$2\$ and add \$1\$ ( \$2n+1\$ ). Then go back to step 1 else move to step 4.
  Divide the rest of the integer with the extracted digit (integer / digit) and add the remainder (integer % digit), that is your new \$n\$.

For example, \$61407\$ gives \$5\$ when ran through this mechanism. I've come up with the following code:

defmodule ExtractAndDivide do
  def extract_and_divide(x) do
    if x < 10 do x
    else
      head = div x, 10
      tail = rem x, 10
      case rem tail, 2 do
        0 -> head * 2 + 1 |> extract_and_divide
        1 -> div(head, tail) + rem(head, tail) |> extract_and_divide
      end
    end
  end
end

I'm seeking general advice, but mainly focusing on the following:

Naming and Syntax better practices (usage of parenthesises, variable names etc.)
Usage of |> (pipe) in this context. Would you ever see it used the way I did it in production code? Should I switch to "normal" notation instead?
Less verbose or more elegant way to avoid the seemingly unaesthetic if x < 10 do x ... else ... end structure, perhaps using case would be better here?
Is recursion the way to go? Should I stick to it or are there better, equivalent methods?


texts:
I've written a stable implementation of insertion sort, that sorts an array in ascending order.

Please let me know of any improvements/optimisations that can be made.

import java.util.List;

public class InsertionSort {
    public static void start(List<Integer> arrayToSort){
        for(int i = arrayToSort.size() - 1; i > 0; i--){    // i is the leftmost index of sorted elements
            // j is the index at which the new element inserted in the sorted part of the array
            for(int j = arrayToSort.size() - 1; j >= i; j--){
                if(arrayToSort.get(i - 1) > arrayToSort.get(j)){
                    insert(i - 1, j + 1, arrayToSort);
                    break;
                }
            }
        }
    }

    private static void insert(int source, int destination, List<Integer> arrayToSort){
        arrayToSort.add(destination, arrayToSort.get(source));
        arrayToSort.remove(source);
    }
}


texts: Thread Safe Objects in CSharp - ConcurrentDictionary

texts:
I'm using ConcurrentDictionary to hold the records.. I'm reading files from the local system in parallel, to speed up the process.

Sample 1:

static ConcurrentDictionary<Int64, Byte[]> concurrentDictionary = new ConcurrentDictionary<Int64, Byte[]>();

private void ReadFilesFromDirectory()
{
  string[] docNames = Directory.GetFiles(CompleteLettersDirectory);
  Parallel.ForEach(docNames, new ParallelOptions { MaxDegreeOfParallelism = 8 }, file =>
    {
      try
      {
          int64 letterId = Convert.ToInt64(file.Split('_')[1]);
          Byte[] CompleteLetterContent;
          CompleteLetterContent = ConvertToPdfWithAspose(System.IO.File.ReadAllBytes(file), letterId);
          concurrentDictionary.GetOrAdd(letterId, CompleteLetterContent);
      }
      catch (Exception ex)
      {
          //Logger.WriteFile(letterId.ToString() + Environment.NewLine, ex);
      }
    }
}

Sample 2: In this sample I want to keep multiple values in dictionary as such I created a letter class which has multiple properties. As Letter class is not threadsafe, will it create any issues ?

static ConcurrentDictionary<Int64, Letter> concurrentDictionary = new ConcurrentDictionary<Int64, Letter>();

private void ReadFilesFromDirectory()
{
  string[] docNames = Directory.GetFiles(CompleteLettersDirectory);
  Parallel.ForEach(docNames, new ParallelOptions { MaxDegreeOfParallelism = 8 }, file =>
    {
      try
      {
          int64 letterId = Convert.ToInt64(file.Split('_')[1]);
          Byte[] LetterContent;
          Byte[] CompleteLetter;

          Letter letter = new Letter();
          letter.LetterId = letterId;

      if(file.Contains("CL"))
      {
    letter.CompleteLetter = ConvertToPdfWithAspose(System.IO.File.ReadAllBytes(file), letterId);
      }
      else
      {
    letter.LetterContent = ConvertToHTML(System.IO.File.ReadAllBytes(file), letterId);
      }
    concurrentDictionary.GetOrAdd(letterId, letter);
          }
      catch (Exception ex)
  {
          //Logger.WriteFile(letterId.ToString() + Environment.NewLine, ex);
      }
    }
}

public class Letter
  {
      public Int64 LetterId { get; set; }
      public Byte[] LetterContent { get; set; }
      public Byte[] CompleteLetter { get; set; }
  }

Can anyone advise if code samples are threadsafe.
Also, should string docNames which holds documents from the directory and is passed to Parallel.ForEach be also threadsafe or not? Or any other recommendation.


texts: Reading data with different but similar semantics

texts:
I am writing code that reads data from a DB, where boolean values are stored as 0/1 nullable integers.

I decided to write a simple function to encapsulate the logic which converts the integer values to boolean. Thing is, I sometimes need to regard the db null value as boolean false, and sometimes just as null.

So I've come up with the following two extension methods:

// Read the specified column value from row as nullable boolean,
// treating integer 0 as false, and any other non-null value as true.
public static bool? ReadAsBoolNullable(this DataRow row, string columnName)
{
    if (row.IsNull(columnName))
    {
        return null;
    }
    else
    {
        return row[columnName] != 0;
    }
}

// Read the specified column value from row as boolean,
// treating null and integer 0 as false, and any other value as true.
public static bool ReadAsBool(this DataRow row, string columnName)
{
    bool? data = row.ReadAsBoolNullable(columnName);
    return data.HasValue ? data.Value : false;
}

My main concern about this code is that I potentially have hundreds of millions of records, each having up to 10 boolean (not nullable) columns. So the second function will be executed a lot and will have to call the first one a lot. Could this damage performance significantly, given that the function itself doesn't do much?


texts: Check if an Array of Arrays contains a value in node js

texts:
In C#, I could check if any of the nested List collection has a value. Example of such structure Check a List[]> contains a value using Linq

List<int> a= new List<int>(){ 2, 2, 3, 4, 5};
List<int> b= new List<int>() { 2, 2, 2, 6 };
List<List<int>[]> c = new List<List<int>[]>();
c.Add(new[]{a,b});

  // checking if the value is in any of the collections. for example, this will result to 2
  var result = c.SelectMany(x => x).SelectMany(x => x).Any(p => p == 2);

but since I'm exploring the LINQ capabilities in node js , I decided to extend this to an Array of Arrays

var data= [[2, 2, 3, 4, 5],[2, 2, 2, 6], [9], [13, 1,1,90]];
var LINQ = require('node-linq').LINQ;
var resultI=new LINQ(data).Any(function(row)
{
 return  checkElement(row);
});
 console.log(resultI);

function checkElement(array)
    {
     for(var i = 0 ; i< array.length; i++)
        {
           if(array[i]== 19){
             return true;
         }
     }
 }

Note: I installed the LINQ module  using
 npm install https://github.com/wearefractal/node-linq/tarball/master
Can this be improved? please any suggestions will be quite appreciated.


texts:
I'm trying to use sockets to create a simple client and server architecture and I'm wondering if there is any other way to create non-blocking, 'async' sockets instead using fcntl(), select() or Boost Library? How can I implement this in a C++ style? I'm using threads to accept new connections and receive data, but in this case it doesn't work well enough (receive hangs, waiting for data, vector isn't a good container for thread based operations etc.).

My code:

const char * SERVER_HOST = "127.0.0.1";
const unsigned short MAX_CONNECTIONS = 10;
const int MAX_DATA_BUFFER = 4096;
const unsigned int SERVER_PORT = 8989;

std::vector<int> clients;

int acceptClient(int serverFd, sockaddr* saddr, socklen_t *sin_size)
{
    while(true)
    {
        int newSocketFd = accept(serverFd, saddr, sin_size);

        if (newSocketFd != -1)
        {
            clients.push_back(newSocketFd);
            std::cout << "New client!" << std::endl;
        }
    }
}

int recive()
{
    while(true)
    {
        for(auto x : clients)
        {
            char buffer[4096];
            int nbytes = recv(x, buffer, sizeof(buffer), 0);
            std::cout << "Socket descriptor: " << x << std::endl;
            if (nbytes != -1)
            {
                buffer[nbytes] = '\0';
                string str(buffer);
                std::cout << "Recived from: " << x << " " << str << std::endl;
            }

            if (nbytes == 0)
            {
                std::cout << "Connection refused..." << std::endl;
                std::remove_if(clients.begin(), clients.end(), [x](int fd)->bool{fd = x;});
            }
        }
    }
}

int main()
{
    int serverFd;
    struct sockaddr_in serverSockAddr = {};
    serverSockAddr.sin_addr.s_addr = INADDR_ANY;
    serverSockAddr.sin_port = htons(SERVER_PORT);
    serverSockAddr.sin_family = AF_INET;
    memset(&serverSockAddr.sin_zero, '\0', 8);

    if ((serverFd= socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    std::cout << "Socket created..." << std::endl;

    if (bind(serverFd, reinterpret_cast<sockaddr * >(&serverSockAddr), sizeof(sockaddr)) == -1)
    {
        perror("bind");
        exit(EXIT_FAILURE);
    }
    std::cout << "Bind complete..." << std::endl;

    int yes = 1;
    if (setsockopt(serverFd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
    {
        perror("setsockpt");
        exit(EXIT_FAILURE);
    }
    std::cout << "Socket cleared if stuck..." << std::endl;

    if (listen(serverFd, MAX_CONNECTIONS) == -1)
    {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    std::cout << "Socket listen..." << std::endl;

    int clientFd;
    socklen_t sin_size = sizeof(struct sockaddr_in);
    sockaddr_in clientSockAddr = {};

    std::thread t1 (acceptClient, serverFd, reinterpret_cast<struct sockaddr*>(&clientSockAddr), &sin_size);
    std::thread t2 (recive);

    char buf[1024];
    std::cin>>buf;

    return 0;


texts:
Failing to get a solution to my problem from other people, I got tired of waiting and wrote this (rather rushed) Text class to deal with the text problems I've been having in Pygame. I wanted the text to update itself, so that it would be unnecessary to keep track of its original position. After playing a lot with it, I found this solution:

class Text(object):

    def __init__(self, value, size, color,
                 left_orientation=False,
                 font=None,
                 x=0, y=0,
                 top=None, bottom=None, left=None, right=None,
                 centerx=None, centery=None):

        self._size = size
        self._color = color
        self._value = value
        self._font = pygame.font.Font(font, self._size)
        self.width, self.height = self._font.size(self._value)
        self.left_orientation = left_orientation

        self.image = self._create_surface()
        self.rect = self.image.get_rect()
        if x: self.rect.x = x
        if y: self.rect.y = y
        if top: self.rect.top = top
        if bottom: self.rect.bottom = bottom
        if left: self.rect.left = left
        if right: self.rect.right = right
        if centerx: self.rect.centerx = centerx
        if centery: self.rect.centery = centery

    def _create_surface(self):
        return self._font.render(self._value, True, self._color)

    def set_value(self, new_value):
        if new_value != self._value:
            self._value = new_value
            self.image = self._create_surface()

            new_rect = self.image.get_rect(x = self.rect.x, y = self.rect.y)
            if self.left_orientation:
                width_diff = new_rect.width - self.rect.width
                new_rect.x = self.rect.x - width_diff
            self.rect = new_rect

    def set_position(self, x_or_x_and_y, y=None):
        if y != None:
            self.rect.x = x_or_x_and_y
            self.rect.y = y
        else:
            self.rect.x = x_or_x_and_y[0]
            self.rect.y = x_or_x_and_y[1]

So, if a text is supposed to increase to the left, all that I have to do is initialize a Text object with the left_orientation parameter set to True and, whatever the rect is, it will update itself to remain at it's original position.

Is this a good solution? If not, what would be a better one?


texts:
I have code that converts each sheet of a spreadsheet into a .txt file. It works well, however, given the big number of exports (about 90 .txt files), I'd like to seek advice on how to speed it up.

Sub xlsxTotxt()

Dim i As Integer
Dim directory As String
Dim fname As String
Dim xWs As Worksheet
Dim xTextFile As String
Dim rdate As String

directory = ThisWorkbook.Sheets("Macro").Range("D576").Value
rdate = ThisWorkbook.Sheets("Macro").Range("E47").Value
i = 0
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While ThisWorkbook.Sheets("Macro").Range("D577").Offset(i).Value <> ""
fname = Sheets("Macro").Range("D577").Offset(i).Value
Workbooks.Open (directory & fname)
For Each xWs In Workbooks(fname).Worksheets
xWs.Copy
xTextFile = directory & rdate & " - " & xWs.name & ".txt"
Application.ActiveWorkbook.SaveAs filename:=xTextFile, FileFormat:=xlText
Application.ActiveWorkbook.Saved = True
Application.ActiveWorkbook.Close
Next
Workbooks(fname).Close
i = i + 1
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub


texts:
So, i recently wrote code that can count the number of monotonic items (increasing, decreasing and constant). For an input such as x = [1,2,3,3,2,0] The provided example was:

1. Increasing: [1,2], [2,3], [1,2,3]
2. Constant: [3,3]
3. Decreasing: [3,2], [2,0], [3,2,0]

So, i broke the problem into two steps, firstly just getting all biggest monotonic sequences, and then finding all sub-lists within those sequences.
During the process it seemed to me that things started getting rather long and i was surprised by how "big" the whole thing seemed by the end of it. I was wondering if there are any tricks i missed or steps i could have done better. Also looking for tips on code readability as well. Code starts below:

x = [1,2,3,3,2,0]
prev = x[0]
curr = x[1] #keep track of two items together during iteration, previous and current
result = {"increasing": [],
          "equal": [],
          "decreasing": [],
          }

def two_item_relation(prev, curr): #compare two items in list, results in what is effectively a 3 way flag
    if prev < curr:
        return "increasing"
    elif prev == curr:
        return "equal"
    else:
        return "decreasing"

prev_state = two_item_relation(prev, curr) #keep track of previous state
result[prev_state].append([prev]) #handle first item of list

x_shifted = iter(x)
next(x_shifted) #x_shifted is now similar to x[1:]

for curr in x_shifted:
    curr_state = two_item_relation(prev, curr)
    if prev_state == curr_state: #compare if current and previous states were same.
        result[curr_state][-1].append(curr)
    else: #states were different. aka a change in trend
        result[curr_state].append([])
        result[curr_state][-1].extend([prev, curr])
    prev = curr
    prev_state = curr_state

def all_subcombinations(lst): #given a list, get all "sublists" using sliding windows
    if len(lst) < 3:
        return [lst]
    else:
        result = []
    for i in range(2, len(lst) + 1):
        for j in range(len(lst) - i + 1):
            result.extend([lst[j:j + i]])
    return result

print(" all Outputs ")
result_all_combinations = {}

for k, v in result.items():
    result_all_combinations[k] = []
    for item in v:
        result_all_combinations[k].extend(all_subcombinations(item))

print(result_all_combinations)
#Output:
{'increasing': [[1, 2], [2, 3], [1, 2, 3]],
 'equal': [[3, 3]],
 'decreasing': [[3, 2], [2, 0], [3, 2, 0]]}


texts:
How can this be optimized?

$text = "reverseesrever"; // Reverse and esrever
$b = false;

for($i = 0; $i < strlen($text); $i++) {
    if($text[$i] !== $text[strlen($text) - 1 - $i]) {
        $b = true;
        break;
    }
}

echo ($b) ? "YES" : "NO"; // result: NO.


texts:
The input is an unsorted array of integers. The output should be an array of integers sorted based on the modulus of 3 (or any other number).

It begins with all integers conforming to Integer % 3 == 0 then 1 and then 2.

public class sortByMod {
public static void main(String args[]) throws Exception {

    int a[] = {1,90,2100, 12, 24, 80, 90, 5};
    LinkedList<List<Integer>> a1=sortMod(a);
    for(int i=0; i <a1.size();i++)
            System.out.print(a1.get(i)+" ");
}

public static LinkedList sortMod(int a[]){
    HashMap<Integer, TreeSet<Integer>> map = new HashMap<Integer, TreeSet<Integer>>();
    for(Integer i =0; i<a.length;i++){
        Integer modKey = a[i]%3;
        if(!map.containsKey(modKey)){
            map.put(modKey, new TreeSet<Integer>());
        }
        TreeSet<Integer> temp = map.get(modKey);
        temp.add(a[i]);
        map.put(modKey,temp);
    }
    LinkedList<List<Integer>> result= new LinkedList<List<Integer>>();
    TreeSet<Integer> temp;
    for(int i=0;i<=2;i++) {

        if(map.containsKey(i)){
           temp = map.get(i);
        }
        else return null;

        List<Integer> list = new ArrayList<Integer>(temp);
        result.add(list);

    }
    return result;
}
}


texts: Strategy design pattern with various duck type classes

texts:
I've recently picked up the Head First Design Patterns book in an effort to become a more efficient and better Python programmer. Unfortunately, the code examples in this book are in Java.

I'm not the first one that wishes there was a Python version of this book, but I thought that writing the Python code would be a great exercise.

I've tried to implement the Strategy design pattern from Chapter 1 of Head First Design Patterns below in Python. Now, I know that Python is not Java in a general sense, but not in the nitty-gritty sense. So, I'm sure there are more Pythonic things that I can do to this code.

Off the top of my head we could probably implement the Duck class set_fly_behavior() and set_quack_behavior() using the Python property built-in.

Any other suggestions?

#!/usr/bin/env python

################################################################################
# Abstract Duck class and concrete Duck type classes.
################################################################################
class Duck(object):
    def __init__(self):
        pass

    def set_fly_behavior(self, fb):
        self.fly_behavior = fb

    def set_quack_behavior(self, qb):
        self.quack_behavior = qb

    def perform_fly(self):
        self.fly_behavior.fly()

    def perform_quack(self):
        self.quack_behavior.quack()

    def swim(self):
        print "All ducks float, even decoys!"

class MallardDuck(Duck):
    def __init__(self):
        Duck.__init__(self)
        fly_instance = Fly()
        self.set_fly_behavior(fly_instance)
        quack_instance = Quack()
        self.set_quack_behavior(quack_instance)
        print "I'm a real Mallard Duck"

class ModelDuck(Duck):
    def __init__(self):
        Duck.__init__(self)
        fly_no_way_instance = FlyNoWay()
        self.set_fly_behavior(fly_no_way_instance)
        squeak_instance = SqueakQuack()
        self.set_quack_behavior(squeak_instance)
        print "I'm a Model Duck"

class DecoyDuck(Duck):
    def __init__(self):
        Duck.__init__(self)
        fly_no_way_instance = FlyNoWay()
        self.set_fly_behavior(fly_no_way_instance)
        mute_instance = MuteQuack()
        self.set_quack_behavior(mute_instance)
        print "I'm a Decoy Duck"

################################################################################
# Fly behavior interface and behavior implementation classes.
################################################################################
class FlyBehavior():
    def __init__(self):
        pass

class Fly(FlyBehavior):
    def fly(self):
        print "I'm flying!!"

class FlyNoWay(FlyBehavior):
    def fly(self):
        print "I can't fly"

class FlyRocketPowered(FlyBehavior):
    def fly(self):
        print "I'm flying with a rocket!"

################################################################################
# Quack behavior interface and behavior implementation classes.
################################################################################
class QuackBehavior():
    def __init__(self):
        pass

class Quack(QuackBehavior):
    def quack(self):
        print "Quack"

class MuteQuack(QuackBehavior):
    def quack(self):
        print "<< Silence >>"

class SqueakQuack(QuackBehavior):
    def quack(self):
        print "Squeak"

################################################################################
# Test Code.
################################################################################
if __name__ == "__main__":

    print '#'*80
    print "Mallard Duck"
    print '#'*80
    mallard = MallardDuck()
    mallard.perform_quack()
    mallard.perform_fly()

    print '#'*80
    print "Model Duck"
    print '#'*80
    model = ModelDuck()
    model.perform_fly()
    fly_rocket_powered_instance = FlyRocketPowered()
    model.set_fly_behavior(fly_rocket_powered_instance)
    model.perform_fly()

    print '#'*80
    print "Decoy Duck"
    print '#'*80
    decoy = DecoyDuck()
    decoy.perform_fly()
    decoy.perform_quack()


texts:
Writing a MMORPG server in nodejs, I have to handle packets. These packets have a structure of

<length> <id> <data>

So what I did was use a node package called packet

And first get the packet id:

client.on('data', function(data) {
  parser.extract("l16 => length, l16 => id", function (packet) {
    if (packet.id === 300) {

    }
    if (packet.id === 301) {

    }
    if (packet.id === 302) {

    }
    if (packet.id === 303) {

    }
  });

  // parse the packet id to handle it accordingly
  parser.parse(data);
});

There are packet Id's upto 1000+ which would make my if statements very long. But each packet id contains different data and different ways to handle it.

For example packet 300 which is the handshake packet. It sends the client version to the server and the servers checks it and returns if it is correct or not, if not then client will error wrong version.

  if (packet.id === 300) {
    console.log('[recieved] packet:handshake');

    parser.extract("handshake", function (packet) {
      if (packet.gameClientVer === config.gameClientVer) {
        // do stuff
      } else {
        // do stuff
      }
    });

    // parse structure for packet 300
    parser.parse(data);
  }
});

the handshake packet is defined as:

serializer.packet("handshake", "l16 => length, l16 => id, l16 => gameClientVer, l16 => gameUpdateVer, l16 => gameDateVer");

My question is, how can I improve this?


texts: Insert Selected item in listbox using Ado.net and stor proc

texts:
I create this class method to Enter Selected Items Form CheckboxList to associated resource I use ADO.net & store Proc to insert data can someone help me to improve it and make to so clean instead of my Hacks BTW I use Microsoft Enterprise Lib

public  static void Insert(List<int> listSkills, int rID)
        {
            var connection = ConfigurationManager.ConnectionStrings["SiteSqlServer"];
            Database objDB = new SqlDatabase(connection.ConnectionString);
            //int val = 0;
            using (DbCommand cmd = objDB.GetStoredProcCommand("Insert_Skills_Resources"))
            {
                foreach (var s in listSkills)
                {
                    try
                    {
                        objDB.AddInParameter(cmd, "@SkillID", DbType.Int32, s);
                        objDB.AddInParameter(cmd, "@ResourceID", DbType.Int32, rID);

                        objDB.ExecuteNonQuery(cmd);
                        cmd.Parameters.Clear();

                    }
                    catch (Exception ex)
                    {

                        throw ex;

                    }
                }

            }


texts:
Is the algorithm correct? It seems to work.

print("Multiple sequence longest common subsequence implementation in Python.\nFor example a naive algorithm would perfom c*128^128 elementary operations on a problem set of 128 sequences of length 128 elements.")
print(" That is: ", 128**128, "operations.")

from collections import defaultdict
import sys

def ptable(m, n, table):
   for i in range(m):
       line = ""
       for j in range(n):
           line += str(table[i, j]) + " "
       print(line)

def lcs(x, y):
    table = defaultdict(int)
    n = len(x)
    m = len(y)

    for i in range(n):
        for j in range(m):
            if x[i] == y[j]:
                table[i, j] = table[i-1, j-1]+1
            else:
                table[i, j] = max(table[i-1, j], table[i, j-1])

    return table

def mlcs(strings):
    strings = list(set(strings))
    tables = dict()
    for i in range(1, len(strings)):
        x = strings[i]
        for y in strings[:i]:
            lcsxy = lcs(x, y)
            tables[x,y] = lcsxy

    def rec(indexes):
        for v in indexes.values():
            if v < 0:
                return ""
        same = True
        for i in range(len(strings)-1):
            x = strings[i]
            y = strings[i+1]
            same &= x[indexes[x]] == y[indexes[y]]
        if same:
            x = strings[0]
            c = x[indexes[x]]
            for x in strings:
                indexes[x] -= 1
            return rec(indexes) + c
        else:
            v = -1
            ind = None
            for x in strings:
                indcopy = indexes.copy()
                indcopy[x] -= 1
                icv = valueat(indcopy)
                if icv > v:
                    ind = indcopy
                    v = icv
            indexes = ind
            return rec(indexes)

    def valueat(indexes):
        m = 12777216
        for i in range(1, len(strings)):
            x = strings[i]
            for y in strings[:i]:
                lcsxy = tables[x,y]
                p = lcsxy[indexes[x],indexes[y]]
                m = min(m, p)
        return m

    indexes = dict()
    for x in strings:
        indexes[x] = len(x) - 1
    return rec(indexes)

def check(string, seq):
    i = 0
    j = 0
    while i < len(string) and j < len(seq):
        if string[i] == seq[j]:
            j += 1
        i += 1
    return len(seq) - j

def checkall(strings, seq):
    for x in strings:
        a = check(x, seq)
        if not a == 0:
            print(x, seq, a)
            return False
    return True

strings = []
sigma = ["a", "b", "c", "d"]
#sigma = ["a", "b"]
import random
for i in range(5):
    string = ""
    for j in range(128):
        string += random.choice(sigma)
    strings += [string]

#strings = ["abbab", "ababa", "abbba"]
#strings = ["abab", "baba", "abaa"]
#strings = ["bacda", "abcde", "decac"]
#strings = ["babbabbb", "bbbaabaa", "abbbabab", "abbababa"]
#strings = ["human", "chimpanzee", "woman"]
#strings = ["ababa", "babab", "bbbab"]
#strings = ["ababaaba", "abbabbaa", "aaaaabba"]
#strings = ["aabbbaba", "aaaabbba", "aabbbaab"]
print("Strings:", strings)
l = mlcs(strings)
print("Lcs:", l, checkall(strings, l))`


texts: Memorise array and print number of occurrences

texts:
I have written a slow solution to the Memorise Me problem on hackerearth

  The first line of input will contain N, an integer, which is the
  total number of numbers shown to your team.

  The second line of input contains N space separated integers.

  The third line of input contains an integer Q, denoting the total
  number of integers.

  The Next Q lines will contain an integer denoting an integer,
  Bi, for which you have to print the number of occurrences of that number (Bi) in those N numbers on a new line.

  If the number Bi isn’t present then print NOT PRESENT
  on a new line.

  Constraints

  $$1 \le N \le 10^5$$

  $$0 \le B_i \le 1000$$

  $$1 \le Q \le 10^{55}$$

    #include <stdio.h>
    int check(int z,int c[1001][2],int q,int arr[])
    {
        int i =0;
        while(c[i][0]!=-1)
        {
        if (z==c[i][0])
        {
            return c[i][1];
            break;
        }
    else
    {
        c[i][0]=z;
        c[i][1]=count(z,arr,q);
        return c[i][1];
    }
    i++;
    }

    }
     int count(int z,int arr[],int q)
     {
         int occurence=0;
         for(int k=0;k<q;k++)
         {
             if(z==arr[k])
             {
                 occurence++;
             }
         }
     return occurence;

     }
    int main()
    {
        int c[1001][2];

            for(int i=0;i<=1001;i++)
            {
                c[i][0]=-1;
                c[i][1]=0;
            }
            c[0][0]=9999;
        int n;
        scanf("%d",&n);
        int arr[100000];
        int i;
        for(i=0;i<n;i++){
            scanf("%d",&arr[i]);
            }
        int q;
        scanf("%d",&q);
        int j;
        int B[100000];
        int occurence1=0;

        for(j=0;j<q;j++)
        {
            scanf("%d",&B[j]);
            occurence1=check(B[j],c,q,arr);

            if(occurence1==0)
            {
                printf("NOT PRESENT\n");
            }
            else
            {
                printf("%d\n",occurence1);
            }
            }
        }

Code taking 0.9 seconds for a set of input where \$n=10^5\$ else it's taking 0.1 seconds.  Can you suggest a shorter way to reduce time complexity!  And suggest improvements in the code itself.


texts: Scraper for parsing, downloading, and setting images beside each link in an Excel file

texts:
I've written a script in VBA which is able to parse image links from a website, download and store them in a local folder and finally set those images beside each link in an Excel file.
As the script is a bit big, I tried to make it clean so that it can serve the purpose errorlessly. However, it can do successfully what I mentioned above. There are always rooms for improvement, though.
Here is the full code:
Sub SavingImagesfinal()

Dim http As New XMLHTTP60, htmldoc As New HTMLDocument
Dim htmlas As Object, htmla As Object, html As Object, item As Object
Dim stream As Object, tempArr As Variant, fileSource As String
Dim pic As String, myPicture As Picture, rng As Range
Dim cl As Range, AspectRatio As Double

With http
    .Open "GET", "https://www.yify-torrent.org/search/1080p/", False
    .send
    htmldoc.body.innerHTML = .responseText
End With

Set htmlas = htmldoc.getElementsByClassName("movie")

    For Each htmla In htmlas
        Set html = htmla.getElementsByTagName("img")
        For Each item In html
            x = x + 1
            Cells(x, 1) = "https" & Split(item.src, "about")(1)

            fileSource = Replace(item.src, "about", "https")
            tempArr = Split(item.src, "/")
            tempArr = tempArr(UBound(tempArr))
        Next item

        With http
            .Open "GET", fileSource, False
            .send
        End With

        Set stream = CreateObject("ADODB.Stream")
        With stream
            .Open
            .Type = 1
            .write http.responseBody
            .SaveToFile ("D:\Test\Images\" & tempArr & ".jpg")
            .Close
        End With
    Next htmla

    Set rng = Range("B1:B18")

    For Each cl In rng
        pic = cl.Offset(0, -1)

        Set myPicture = ActiveSheet.Pictures.Insert(pic)

        AspectRatio = myPicture.Width / myPicture.Height
        With myPicture
            .ShapeRange.LockAspectRatio = msoFalse
            .Width = cl.Width
            .Height = cl.Height
            .Top = Rows(cl.Row).Top
            .Left = Columns(cl.Column).Left
        End With
    Next cl
End Sub


texts: Parsing numbers from equations into strings

texts:
This is my first code in C++.  Since I'm new to the language, I'm just looking for pointers on what can be made better.  I tried to cut out unnecessary stuff, but there are some comments in there.  I know Java, so if you're trying to explain anything in Java, I can understand it.

Feel free to mention anything, whether it be code style (which I'm completely unsure what the conventions are in C++), performance, etc.

The goal of the program is to take an equation, such as 5x^2+48204x=7, and parse the 5 and 48204 into strings.

using namespace std;

void printHelp();

class Equation {
public:
    string equation1;
    string equation2;

    int matrix [3][2];

    Equation(string one, string two) {
        one.erase(remove_if(one.begin(), one.end(), isspace), one.end());
        two.erase(remove_if(two.begin(), two.end(), isspace), two.end());
        equation1 = one;
        equation2 = two;

        cout << equation1 << endl;

        init();
    }

    void init() {
        size_t firstx = equation1.find_first_of("x");
        size_t secondx = equation1.find_first_of("x", firstx + 1);
        if (secondx == string::npos) {
            cout << "Secondx == 0" << endl;
        }

        //cout << firstx << endl;
        //cout << secondx << endl;

        int startloc = firstx - 1;

        while (true) {
            //cout << "starting with startloc = " << startloc << endl;
            if (startloc == -1) {
                break;
            }
            char c = equation1.at(startloc);
            if (c == ' ' || c == '=' || c == '+' || c == '-' || c == '*' || c == '/') {
                //cout << "Found something" << endl;
                break;
            }
            startloc--;
        }

        string s;
        unsigned int i = startloc + 1;
        //cout << i << endl;
        //cout << firstx << endl;
        while (i < firstx) {
            //cout << "Character at " << i << endl;
            //cout << equation1[i] << endl;
            stringstream ss;
            string temp;
            ss << equation1[i];
            ss >> temp;
            s.append(temp);
            i++;
        }
        cout << s << endl;

        startloc = secondx - 1;

        while (true) {
            //cout << "starting with startloc = " << startloc << endl;
            if (startloc == 0) {
                cout << "Problem" << endl;
            }
            char c = equation1.at(startloc);
            if (c == ' ' || c == '=' || c == '+' || c == '-' || c == '*' || c == '/') {
                //cout << "Found something" << endl;
                break;
            }
            startloc--;
        }

        s = "";
        i = startloc + 1;
        while (i < secondx) {
            stringstream ss;
            string temp;
            ss << equation1[i];
            ss >> s;
            s.append(temp);
            i++;
        }

        cout << s << endl;
    }

};

int main(int argc, char *argv[])
{
    Equation equation(argv[1], "blank");
    //printHelp();
    string s;
    cin >> s;
    return 0;
}

void printHelp()
{
    cout << "Welcome!" << endl;
    cout << "Stuff about commands" << endl;
}


texts:
I'm very new to Haskell as was hoping to get some feedback on my code AND I have some specific questions. I've posted code below or you can see it here.

I'd welcome ideas on how better to calculate the Maclaurin series. Ideas on how better to do the math itself are welcome but I had in mind what Haskell ideas am I missing out on.

My specific questions are:

Are (almost) all the calculations for Factorial going to be done every time for each value of my Maclaurin series? Or is there some sort of caching going on? One can appreciate that calculating 100! from scratch seems crazy if you've just done 99!
Notice the signature at end: maclaurin :: ( Floating b) => Int-> b -> b I tried using maclaurin :: ( Integral a, Floating b) => a-> b -> b , thinking that would be best. Didn't work. I stumbled on this scheme by removing signature and typing :t maclaurin in WinGHci. I'm surprised it worked! I thought we had to declare each parameter?

--import Data.List(genericTake)

 -- MacClaurin series for Sin(x) is f(0) + f'(0)(x)/1! + f''(0)(x)^2 / 2!  +
  ... + f^n (0) x^n / n!
  -- or in the case of Sin(x):  0 + 1x + 0 + -1x^3 / 3! + 0 + 1 x^5 / 5! + 0
  + -1x^7/7! ...
   -- See Wikipedia https://en.wikipedia.org/wiki/Taylor_series

-- return list of alterating 0 and 1
    -- not needed for maclaurin or macResult
ymod2 :: Integral a =>  [a]
ymod2  = map (\y->(y `mod` 2)) [0..]

factorial :: (Integral a) => a -> a
factorial 0 = 1
factorial n = n * factorial (n - 1)

powersMac :: (Integral a) => a -> a
powersMac n
    | n == 0 = 0
    | n == 1 = 1
    | ( (n `mod` 2) == 0 ) = 0
    | otherwise =  ( (-1) * powersMac (n-2) )

-- return list of 0, 1, 0, -1, 0, 1, 0, -1 ...
powersMacList :: (Integral a) => [a]
powersMacList  = map (\y->(powersMac y)) [0..]

-- return list of x^0, x^1, x^2, ... x^n
powersOfx :: (Enum b, Floating b) =>  b -> [b]
powersOfx  x = map (\y->(x^^y)) [0..]

-- return list of 0, 1, 0, -1, 0, ... to n
firstLst :: Integral a =>  [a]
firstLst   = zipWith (*) (ymod2 ) (powersMacList)

-- return list of 0x, 1x, 0x^2, -1x^3, ... to n
secondLst :: (Enum b, Floating b) =>  b -> [b]
secondLst  x = zipWith (*) (map fromIntegral(powersMacList )) (powersOfx  x)

-- return list of 0, 1x, 0 , -1x^3 / 3! , 0 , 1 x^5 / 5! , 0 ... to n
thirdLst :: ( Enum b, Floating b) =>  b -> [b]
thirdLst  x = zipWith (/) (secondLst  x) (map fromIntegral ( (map(\y->(factorial y) ) [0..])) )

-- sum the list to get result
macResult :: (  Enum b, Floating b) =>  Int -> b -> b
macResult  n x = sum (take n (thirdLst  x))

maclaurin :: (  Floating b) => Int-> b -> b
maclaurin  n x = sum ( take n (zipWith (*) (map(\y->(x^^y))[0..])(zipWith (/) (map fromIntegral (powersMacList )) (map fromIntegral (map(\y->(factorial y) )[0..]) )) ))