texts:
I wanted a simple thing: being able to override a base class and just add one single getter. The bad thing is the base class does override some operators and will return the wrong type. I, therefore, came across the curiously recurring template pattern which helped me to write the following.
However, I am still not very satisfied. I wrote a very similar question here which helped me to learn about CRTP.
#include <algorithm>
#include <array>
#include <iostream>

using namespace std;

template <typename C, typename T, int N>
class PointCRTP
{
   protected:
    array<T, N> elements;

   public:
    PointCRTP() = default;
    PointCRTP(array<T, N> el) : elements(el) {}

    C operator+(C& other)
    {
        C c;
        transform(elements.begin(), elements.end(), other.elements.begin(),
                  c.elements.begin(), plus<int>());
        return c;
    }

    T operator[](int k) { return elements[k]; }

    friend std::ostream& operator<<(std::ostream& os, C const& x)
    {
        os << "P(";
        for (auto k : x.elements) os << k << ", ";
        return os << "\b\b" << ')';
    }
};

template <typename T, int N>
struct Point : public PointCRTP<Point<T, N>, T, N> {
    using PointCRTP<Point<T, N>, T, N>::PointCRTP;
};

template <typename T>
struct Point2D : public PointCRTP<Point2D<T>, T, 2> {
    Point2D() = default;
    Point2D(T x, T y) : PointCRTP<Point2D<T>, T, 2>({x, y}) {}

    T getX() { return PointCRTP<Point2D<T>, T, 2>::elements[0]; }
    T getY() { return PointCRTP<Point2D<T>, T, 2>::elements[1]; }
};

int main()
{
    Point<int, 3> p({1, 2, 3});
    Point<int, 3> q({3, 4, 2});
    Point<int, 3> c = p + q;
    std::cout << c << " = " << p << " + " << q << endl;

    Point2D<int> r(1, 2);
    Point2D<int> s(3, 4);
    Point2D<int> t = r + s;
    std::cout << t << " = " << r << " + " << s << endl;
}

Is there a way to make this example simpler (shorter)?


texts: A simple encryption program using Python

texts:
I made this encryption program in Python.

I don't have much experience (or any experience at all) about encryption (since I just gave my 9th grade finals), but I had this idea about an algorithm some time back which would enable the user to encrypt words following an algorithm where the program would follow this process for each letter of the entered word; pseudocode:

Let the variable x be the position of the alphabet in the list of alphabets sorted alphabetically
Let the variable y be the position of the alphabet in the entered word
For example, if the user enters 'abcd', the program would find x and y for a, b, c and d one by one
Then, it would find the variable z = 26-x+y and z would be the position of the alphabet in the code
    in the list of alphabets
In abcd : for a - x = 1, y = 1, so, z = 26-1+1 = 26, so  coded alphabet = 26th alphabet = z
 Similarly, all of a,b,c and d will have coded alphabets as 'z'
 So, 'abcd' will be coded as 'zzzz'

Here's the Python code:

alphabets =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

# Defining all sorts of functions

def position(tofind,source):
    size = len(source)
    for i in range(0,size,1):
        if (source[i] == tofind):
            p = i + 1
            break
    return p
def encrypt(a):
    output = []
    sizea = len(a)
    for i in range(0,sizea,1):
        x = i+1
        y = position(a[i],alphabets)
        z = 26-x+y
        if (z>26):
            z = z % 26
        element = alphabets[z-1]
        output.append(element)
    return output
def converttolist(text):
    size = len(text)
    l = []
    for i in range(0,size,1):
        l.append(text[i])
    return l

# The main program

print ()
print ("NOTE : Please enter all the alphabets in lowercase...")
print ()
given = str(input("Please enter the word to be coded : "))
givenlist = converttolist(given)
outputlist = encrypt(givenlist)
print ()
print ("The code for ",given," is :-")
outputlistlength = len(outputlist)
for i in range(0,outputlistlength,1):
    print (outputlist[i],end = "")

Let me know what you think about it.


texts:
Are there any security flaws in what I plan to do?

I need to store the following in my DB:

a random string to act as a salt for encrypting a password
the encrypted password that used the salt in #1

Here's the PHP code I have to accomplish the above tasks:

<?php
    function decrypt($string, $encryption_key = '')
    {
        $initialization_vector = get_initialization_vector();

        // Convert hexadecimal data into binary representation
        $string = hex2bin($string);

        // See: http://php.net/manual/en/mcrypt.ciphers.php
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $encryption_key, $string, MCRYPT_MODE_ECB, $initialization_vector));
    }

    function encrypt($string, $encryption_key = '')
    {
        $initialization_vector = get_initialization_vector();

        // See: http://php.net/manual/en/mcrypt.ciphers.php
        $string = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $encryption_key, $string, MCRYPT_MODE_ECB, $initialization_vector);

        // Convert binary data into hexadecimal representation
        $string = bin2hex($string);

        return $string;
    }

    function get_initialization_vector()
    {
        // See: http://php.net/manual/en/mcrypt.ciphers.php
        // MCRYPT_BLOWFISH selected as it appears to be one of the "universally"
        // supported ciphers supported by the mcrypt extension
        $initialization_vector_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);

        // See: http://php.net/manual/en/function.mcrypt-create-iv.php
        // The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM
        // (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom).
        // Prior to 5.3.0, MCRYPT_RAND was the only one supported on Windows.
        $initialization_vector = mcrypt_create_iv($initialization_vector_size, MCRYPT_RAND);

        return $initialization_vector;
    }

    function get_random_string($character_set = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', $minimum_length = 8, $maximum_length = 12)
    {
        if ($minimum_length > $maximum_length)
        {
            $length = mt_rand($maximum_length, $minimum_length);
        }
        else
        {
            $length = mt_rand($minimum_length, $maximum_length);
        }

        $random_string = '';
        for ($i = 0; $i < $length; $i++)
        {
            $random_string .= $character_set[(mt_rand(0, (strlen($character_set) - 1)))];
        }

        return $random_string;
    }

    function hex2bin($hexadecimal_data)
    {
        $binary_representation = '';

        for ($i = 0; $i < strlen($hexadecimal_data); $i += 2)
        {
            $binary_representation .= chr(hexdec($hexadecimal_data{$i} . $hexadecimal_data{($i + 1)}));
        }

        return $binary_representation;
    }


texts:
The class routes URLs based on the domain.com/class/method/param/.. format. It also checks the request type (GET or POST) and calls the method name GET or POST from the identified class.

class Router {
    private $_routes,
            $_path,
            $_method,
            $_found;

    public function __construct(Array $routes, $path, $method) {
        krsort($routes);

        $this->_routes = $routes;
        $this->_path   = $path;
        $this->_method = strtoupper($method);
    }

    public function load() {
        foreach($this->_routes as $regex => $class) {
            $regex = str_replace('/', '\/', $regex);
            $regex = '^' . $regex . '\/?$';

            if(preg_match('/' . $regex . '/i', $this->_path, $params)) {
                $this->_found = true;

                $this->_classInstantiate($class, $params);

                break;
            }
        }

        if(!$this->_found) {
            throw new Exception('URL location not found: ' . $this->_path);
        }
    }

    private function _classInstantiate($class, $params) {
        if(class_exists($class)) {
            $obj = new $class($params);

            if(method_exists($obj, $this->_method)) {
                $method = $this->_method;

                $obj->$method();
            } else {
                throw new BadMethodCallException('Method not found: ' . $this->_method);
            }
        } else {
            throw new Exception('Class not found: ' . $class);
        }
    }
}

I load it up in my entry file like so:

//url to class router
$routes = (Array) $config->routes;
$path   = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];

$router = new Router($routes, $path, $method);
$router->load();

Am I utilizing dependency injection correctly?
Are there any parts of my class that I should decouple?
Is there anything I could improve in my code when it comes to OO PHP (and MVC)?


texts: Project Euler - Problem No.4 - Largest palindrome product

texts:
according to the problem:

  A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
  Find the largest palindrome made from the product of two 3-digit numbers.

Here is my code:

def largest_palindrome_product(n:int) -> int:
    '''
    Returns largest palindrome whose a product of two n digit(base 10) integer
    :param n: the number of digits in the numbers we compute the product of
    :return: largest palindrome whose a product of two n digit(base 10) integer or -1 if non were found
    '''
    # Dealing with edge cases
    if n == 1:
        return 9
    elif n < 1:
        raise ValueError("Expecting n to be >= 1")

    mul_max = -1
    upper_boundary = (10**n) - 1
    lower_boundary = 10**(n-1)

    # Searching for the largest palindrome between the upper boundary and the lower one.
    for i in range(upper_boundary, lower_boundary, -1):
        for j in range(i, lower_boundary, -1):
            str_prod = str(i*j)
            if i*j > mul_max and str_prod[::-1] == str_prod:
                mul_max = i*j

    return mul_max

Here is a small test case for this code:

from ProjectEuler.problem4 import largest_palindrome_product

if __name__ == "__main__":
    # largest prime product is of 91*99 -> returns 9009
    print(largest_palindrome_product(2))
    # Checking edge cases -> returns 9
    print(largest_palindrome_product(1))
    # largest prime product is of 993*913 -> returns 906609
    print(largest_palindrome_product(3))

Let me know your thoughts on this solution :)


texts:
After posting my first question on here, I got a lot of great feedback. I've decided to try another challenge and write it as cleanly as possible.

The rules of Odd-Even consists of the following tasks:

Given a max number a string should be returned counting up to and including that max number and adhere to the following rules in order:

Print "Even" instead of number, if the number is even, which means it is divisible by 2.
Print "Odd" instead of number, if the number is odd, which means it is not divisible by 2 and is not a prime (it should be a composite).
Print the number if it does not meet above two conditions.

I came up with the following code:

def create_oddeven_string(max_number):
    """Returns a string with numbers up to and including max_number."""

    return ",".join(create_oddeven_list(max_number))

def create_oddeven_list(max_number):
    """Returns a list with string representations of oddeven parsed numbers up to and
    including the max_number."""

    return map(parse_oddeven_number, xrange(1, max_number+1))

def parse_oddeven_number(number):
    """Returns the string "Even" when number is even, "Odd" when number is odd
    and composite, or the string representation of the number if prime."""

    if is_divisable(number, 2):
        return "Even"
    elif is_composite(number):
        return "Odd"
    else:
        return str(number)

def is_divisable(number, modulo):
    """Returns True if number % modulo == 0."""

    return number % modulo == 0

def is_composite(number):
    """Returns True if number is not a prime number (only divisable by itself and 1)."""

    if number <= 3:
        return False
    elif is_divisable(number, 2) or is_divisable(number, 3):
        return True
    else:
        i = 5
        while i*i <= number:
            if is_divisable(number, i) or is_divisable(number, (i+2)):
                return True
            i = i+6
        return False

What does not sit well with me is the parse_oddeven_number(number) function. If new situations arrive then that list is going to be a long if, elif, else structure that I'd rather not have. But I don't know what I do about simplifying that function.


texts:
I have a page that is part of a CMS and I cannot alter any existing HTML or CSS, but I can add additional custom JavaScript and CSS. There is some text on this page I want to hide and I found a solution but it feels kludgey. I can't be sure other pages won't have similar content on them, which is why I'm being so specific in my check.

This doesn't seem like an optimal way to do this, so I'm just curious how it could be improved.

The HTML:

Welcome!

The office is closed!

And the JavaScript I'm using to hide just "The office is closed":

function removeWarning() {
  var els = document.getElementsByClassName("hero-action");
  var el = els[0]

  if (el.textContent.indexOf("office" > -1) && el.textContent.indexOf("is" > -1) && el.textContent.indexOf("closed" > -1)) {
    el.style.display = "none";
   }
}

removeWarning();

Like I said, it works it just feels dumb. I know I could make an anonymous self calling function, but I'm more interested in how to improve the if check if there is a way.

Note: I'm not just checking for the entire string because the CMS is generating the
...
 block with some weird amount of whitespace and I was struggling to match spaces, newlines, etc.


texts: Swap the names/properties in a JavaScript object

texts:
Is there a more elegant way to do this in JavaScript?

function swapKey(obj, oldKey, newKey) {
  if (obj[oldKey]) {
    obj[newKey] = obj[oldKey];
    delete obj[oldKey];
  }
  return obj;
}

(I understand that it mutates the original object and is not functional and makes the returning of obj somewhat redundant and that's okay for this particular question.)


texts: Depleting certain data from a webpage asynchronously

texts:
I've written a scraper in python using asyncio library to exhaust the name, address and phone number of all category from a webpage. Few days back, when I created a scraper to parse a webpage recursively, I got a suggestion to use asynchronous process to crawl a webpage with enormous data for the sake of optimum performance and avoiding blocking nature. However, this time I tried to follow that process so that my crawler can scrape the webpage asynchronously. It is running specklessly now. I used css selector to make the parser more readable along with acceleration of speed. This is my first time to work with this library, so I suppose there are scopes to take it to the next level whetting it's performance.

Here is what I've written:

import requests
from lxml import html
import asyncio

main_url = "https://www.someweblink/letter/{0}"

async def alphabetical_links(mainurl):

        # scraping all the links with alphbetical index from start page
        for link in [mainurl.format(chr(page)) for page in range(97,123)]:
            response = requests.get(link).text
            tree = html.fromstring(response)

            for container in tree.cssselect(".proSitemapLink a"):
                await sub_links(container.attrib['href'])
                # going for the contents of the sublinks lies within each page with alphabetical index

async def sub_links(process_links):

        response = requests.get(process_links).text
        root = html.fromstring(response)

        for container in root.cssselect(".proListing"):
            name = container.cssselect("h2 a")[0].text if container.cssselect("h2 a") else ""
            # Used text_content() to get the full address separated by "br" tag
            address = container.cssselect(".proListingLocation")[0].text_content() if container.cssselect(".proListingLocation") else ""
            phone = container.cssselect(".proListingPhone")[0].text if container.cssselect(".proListingPhone") else ""
            profilelink = container.cssselect("h2 a")[0].attrib['href'] if container.cssselect("h2 a") else ""
            await adding_weblink(name, address, phone, profilelink)
            # finally it will go to the profile page to extract website address if available

async def adding_weblink(name, address, phone, profilelink):

        response = requests.get(profilelink).text
        root = html.fromstring(response)
        weblink = root.cssselect(".proWebsiteLink")[0].attrib['href'] if root.cssselect(".proWebsiteLink") else ""
        if weblink:
            print(name, address, phone, weblink)
        else:
            print(name, address, phone)

loop = asyncio.get_event_loop()
loop.run_until_complete(alphabetical_links(main_url))
loop.close()


texts:
The old function was:

<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
    $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

    switch ($theType) {
        case "text":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "long":
        case "int":
          $theValue = ($theValue != "") ? intval($theValue) : "NULL";
          break;
        case "double":
          $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
          break;
        case "date":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "defined":
          $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
          break;
    }
    return $theValue;
}
?>

I have changed in this way:

<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
    $conn = new mysqli('localhost', 'username', 'password', 'dbname');

    $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

    $theValue = $conn->real_escape_string($theValue);
    switch ($theType) {
        case "text":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "long":
        case "int":
          $theValue = ($theValue != "") ? intval($theValue) : "NULL";
          break;
        case "double":
          $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
          break;
        case "date":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "defined":
          $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
          break;
    }
    return $theValue;
}
?>

Is what I've made correct?

Can I remove get_magic_quites_gpc() if I use PHP version 5.3.2?


texts: Simple recursive function to find missing number in a permutation

texts:
This is a short and simple Python written to help me sharpen my dulling recursion skills. It expects a sorted permutation of integers n1..n2 in list format, with a single step missing (e.g., [10,11,13]). I know it does nothing to check errors; I'm more interested in theory here.

from __future__ import division
from math import ceil

def f(lis):
    A = lis[:int(ceil(len(lis))/2)]
    B = lis[int(ceil(len(lis))/2):]
    ISA = sum(range(A[0], A[0] + len(A))) # "Ideal" Sum of A
    ISB = sum(range(B[0], B[0] + len(B))) # "Ideal" Sum of B
    if sum(A) > ISA:
        return f(A)
    elif sum(B) > ISB:
        return f(B)
    else:
        return B[0] - 1

Any thoughts on whether or not this is a decent solution? Any suggested improvements (especially in regard to time complexity)? Is there a more performant algorithm I could compare this to as a heuristic?


texts:
I'm very new both to programming and to R so please bear with me :-)
I've written the following bit of code, which works perfectly well and runs through a data file with 17446 rows in about 35 seconds. I don't really have a problem with this but am sure that this could be a lot more elegant with probably the use of the tapply function. I would love to see how you experts would rewrite this more efficiently and am sure the rewrite would teach me a lot. I've included the first few rows of the output file and hopefully the code should be fairly obvious (it must be if I managed to write it!!); it's a simple filter based on the standard deviation of a subset in one column dictating the output to another column which is set up at the start of the code. If a value in the NEE column is more than 2 stdevs of the preceeding three values then the value is taken from the mean of a subset in the NEE2 column else the value is copied from the first (if that makes sense). Please also note the "count" variable as I need to retrieve the amount of values replaced. Hope this piques someone's interest and thanks in advance for all of your time.
JonP

Dspke <- read.csv(file.choose())
nr = nrow(Dspke)
count = 0

Dspke$NEE2 <- (1:nr) #creates a new column ready for input of values

for (i in 4:nr) {

#standard deviation of the previous three values in NEE
stdev <- sd(Dspke$NEE[(i-2):i])

#if stdev>2 then NEE2 value is mean of the previous 3 values in NEE2 else copy value from NEE
if(stdev>=2) {
  Dspke$NEE2[i] <- mean(Dspke$NEE2[(i-2):i-1])
    count = count+1

    }else { Dspke$NEE2[i] <- Dspke$NEE[i]
  }

 }
  write.csv(Dspke,"Dspke.csv")

 Date_Time       NEE     NEE2
1 03/01/2012 13:00 -2.300000  1.00000
2 03/01/2012 13:30 -2.385610  2.00000
3 03/01/2012 14:00 -2.081935  3.00000
4 03/01/2012 14:30 -1.778260 -1.77826
5 03/01/2012 15:00 -2.409490 -2.40949
6 03/01/2012 15:30 -0.741030 -0.74103


texts: function to generate values of a javascript object

texts:
The following code works but I am wondering if it can be improved both readability and performance.
I am using jquery and underscore.
Any suggestions, comments or feedbacks will be appreciate.
thanks.

var getThemeName = function (theme_name, transparency) {
    if (theme_name === 'light') {
        if (transparency) {
            return translator.get('messages:theme.info.light_with_transparency', {
                percentage: transparency
            });
        }
        return translator.get('messages:theme.info.light');
    } else if (theme_name === 'dark') {
        if (transparency) {
            return translator.get('messages:theme.info.dark_with_transparency', {
                percentage: transparency
            });
        }
        return translator.get('messages:theme.info.dark');
    }
};

var THEME_ITEMS = {
    themeLight: getThemeName('light'),
    themeLightTransparency75: getThemeName('light', 75),
    themeLightTransparency50: getThemeName('light', 50),
    themeLightTransparency25: getThemeName('light', 25),
    themeDark: getThemeName('dark'),
    themeDarkTransparency75: getThemeName('dark', 75),
    themeDarkTransparency50: getThemeName('dark', 50),
    themeDarkTransparency25: getThemeName('dark', 25)
};


texts: How to remove code duplication that difference only a few lines?

texts:
I have 2 methods that do almost the same things except a few lines of code. The sample is like below.

public void Method1()
{
    DoX();

    if (value)
    {
        var input = GetA();
        DoA1();
        DoA2(input);
    }

    DoY();
}

public void Method2()
{
    DoX();

    if (value)
    {
        var input = GetB();
        DoB(input);
    }

    DoY();
}

I have two questions for this code.
1. Is it a good idea to remove code duplication is this case?
2. How to remove the duplication without make it harder to read the code


texts:
I'm have recyclerView which is needed for displayed for show list of my audio records. I added the ability to sort my audio records. Please take a look at the code that I use for sorting and tell me how it can be improved.
enum class AudioRecordSort {

    SortByDate {
        override fun sort(empties: List<AudioRecordEmpty>) {
            Collections.sort(empties, AudioRecordDateComparator())
            if (!isIncrease)
                empties.reversed()
        }
    },
    SortByName {
        override fun sort(empties: List<AudioRecordEmpty>) {
            Collections.sort(empties, AudioRecordNameComparator())
            if (!isIncrease)
                empties.reversed()
        }
    },
    SortBySize {
        override fun sort(empties: List<AudioRecordEmpty>) {
            Collections.sort(empties, AudioRecordSizeComparator())
            if (!isIncrease)
                empties.reversed()
        }
    },
    SortByTime {
        override fun sort(empties: List<AudioRecordEmpty>) {
            Collections.sort(empties, AudioRecordTimeComparator())
            if (!isIncrease)
                empties.reversed()
        }
    };

    val isIncrease: Boolean = true

    abstract fun sort(empties: List<AudioRecordEmpty>)
}

I would also like to say that I do not like that in each method I have to call
 if (! IsIncrease)
    empties.reversed ().

Could this be done in a separate place for everyone?


texts:
I have this project about using OOP in python. How to fully make use of OOP and use __init__(self)?

class Parent:
    name = "Player"
    lives = 3
    #display player running
    def run(self, name):
        self.name = name
        print "%s is running." %self.name

    #player will start to jump against enemy
    def jump(self, name):
        self.name = name
        print "%s jumps over enemy. TOINK TOINK" % self.name

    #player will start to grow
    def grow(self, name):
        self.name = name
        print "%s sarting to Grow" %self.name

For player1

#Mario
class Child1(Parent):
    name = "Mario"
    #special skill
    def blazingFire(self, name):
        self.name = name
        print "%s used his blazingFire" %self.name

For player 2

#Luigi
class Child2(Parent):
    name = "Luigi"
    #special Skill
    def blazingWind(self,name):
        self.name = name
        print "%s used his blazingWind" %self.name

Calling object

player = Parent()
player1 = Child1()
player2 = Child2()

#mario's turn
player1.run(mario)
player1.jump(mario)
player1.grow(mario)

Am I doing the right thing or there's a better way for this?


texts:
I've made a simple program for numerically aproximating double integral, which accepts that the bounds of the inner integral are functions:

import numpy as np
import time

def double_integral(func, limits, res=1000):
        t = time.clock()
        t1 = time.clock()
        t2 = time.clock()
        s = 0
        a, b = limits[0], limits[1]
        outer_values = np.linspace(a, b, res)
        c_is_func = callable(limits[2])
        d_is_func = callable(limits[3])
        for y in outer_values:
            if c_is_func:
                c = limits[2](y)
            else:
                c = limits[2]
            if d_is_func:
                d = limits[3](y)
            else:
                d = limits[3]
            dA = ((b - a) / res) * ((d - c) / res)
            inner_values = np.linspace(c, d, res)
            for x in inner_values:
                t2 = time.clock() - t2
                s += func(x, y) * dA
            t1 = time.clock() - t1
         t = time.clock() - t
         return s, t, t1 / res, t2 / res**2

This is, however, terribly slow. When res=1000, such that the integral is a sum of a million parts, it takes about 5 seconds to run, but the answer is only correct to about the 3rd decimal in my experience. Is there any way to speed this up?

The code i am running to check the integral is

def f(x, y):
    if (4 - y**2 - x**2) < 0:
        return 0              #This is to avoid taking the root of negarive #'s
    return np.sqrt(4 - y**2 - x**2)

def c(y):
    return np.sqrt(2 * y - y**2)

def d(y):
    return np.sqrt(4 - y**2)
# b d
# S S f(x,y) dx dy
# a c
a, b, = 0, 2
print(double_integral(f, [a, b, c, d]))

The integral is eaqual to 16/9


texts:
I am developing a service application that would implement a peer to peer messaging system. I am wondering if my following code is the best approach. It works, but I am naive and it would be nice to have validation from experts for performance and reliability.

There would be about 5 plugins and a large number of messages (over 100,000 in a day. Each message could be upto 1000 characters) may be generated by each plugin and communicated to each other based on some logic.

The following are the MEFContracts -

namespace MEFContracts{

//peer to peer message transmissions.  Any plugin or core can transmit messages to one another
public interface IPeerMessage
{
void ReceiveMessage(string message,string from,string to);
}

//Core application starts a thread on the following exported plugin function
public interface IExecuteThread
{
void ExecuteThread();
}
}

The following is the Core application export -

namespace MEFCore{
[Export(typeof(IPeerMessage))]
[ExportMetadata("MEFName", "Core")]

class MEFExports:IPeerMessage
{

public void ReceiveMessage(string message, string from, string to)
{
    log.Info("Message Received by Core :" + message + from + to);
}
}
}

The following is each plugin code.

namespace MEFPlugin{
[Export(typeof(IPeerMessage))]
[ExportMetadata("MEFName", "PlugIn")]
[Export(typeof(IExecuteThread))]

public class MEFPluginExports : IPeerMessage, IExecuteThread
{
[ImportMany]
public System.Lazy<IPeerMessage,
IDictionary<string, object>>[] _peerMessageComponents
{ get; set; }

public void ReceiveMessage(string message, string from, string to)
{
    log.Info("Message Received by Plugin:" + message + " " + from + " " + to);
}

public void ExecuteThread()
{
//The core application starts this thread which generates messages.  It then transmits these messages to the various parts based on the MEFName attribute
while(true) //I will implement later a way for the core to stop the thread when the service is stopped
{
   //generate message
   //Determine the part to communicate to, say _core

    _core.ReceiveMessage("Hello Core", "PlugIn", "Core");

}
}

And the following is the main core service

[ImportMany]
public System.Lazy<IPeerMessage,
IDictionary<string, object>>[] _peerMessageComponents
{ get; set; }
[ImportMany(typeof(IExecuteThread))]
public IEnumerable<IExecuteThread> _pluginThreads { get; set; }

public void Process()
{
    log.Info("MEFCoreService started");
    AssembleMEFComponents();

     foreach(IExecuteThread _pluginThread in _pluginThreads)
    {
        Thread _thread = new Thread(_pluginThread.ExecuteThread));
        _thread.Start();
        _thread.Join();

    }

}

public void AssembleMEFComponents()
{
    try
    {
        //Creating an instance of aggregate catalog. It aggregates other catalogs
        var aggregateCatalog = new AggregateCatalog();

        //Build the directory path where the parts will be available
       //using the directory catalog
        var directoryCatalog = new DirectoryCatalog(directoryPath, "*.dll");

        //Load parts from the current assembly
        var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

        //Add to the aggregate catalog
        aggregateCatalog.Catalogs.Add(directoryCatalog);
        aggregateCatalog.Catalogs.Add(asmCatalog);

        //Crete the composition container
        var container = new CompositionContainer(aggregateCatalog);

        // Composable parts are created here
        container.ComposeParts(this);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
}


texts: Monkeypatching __builtin__ in tests for mocking

texts:
I'm testing a little magic behaviour of my script that automatically reads from ~/.ghtoken to do automagic authentication on GitHub API requests. I want to test that this works properly by checking the headers in my mock requests to GitHub's API. I'm using HTTPretty to mock HTTP requests.

GitHub

def test_authentication(monkeypatch):
    import os.path
    import io
    import __builtin__

    auth_token = 'fhqwhgads\n'

    # Err... Just ignore how needlessly complicated this is.
    def monkeypatch_on_path_match(mod, name):
        original = getattr(mod, name)

        def patch(function):
            def patched(path, *args, **kwargs):
                if path == os.path.expanduser('~/.ghtoken'):
                    return function(path, *args, **kwargs)
                return original(path, *args, **kwargs)
            monkeypatch.setattr(mod, name, patched)
        return patch

    # Monkey-Patch exists() to say that the token exists.
    @monkeypatch_on_path_match(os.path, 'exists')
    def intercept_exists(path, *args, **kwargs):
        return True

    # Monkey-Patch open() to return specific file content.
    @monkeypatch_on_path_match(__builtin__, 'open')
    def intercept_open(path, *args, **kwargs):
        return io.BytesIO(auth_token)

    # Enable HTTPretty and register the index path.
    httpretty.enable()

    body = iter(mock_data.abbrev_search_bodies)

    def request_callback(request, uri, headers):
        headers['Content-Type'] = 'application/json; charset=utf-8'
        headers['X-RateLimit-Remaining'] = 10
        headers['Link'] = (
            '<https://api.github.com/search/repositories?'
            'q=language%3Apython&sort=stars&page=1>; rel="last"')
        return 200, headers, next(body)

    httpretty.register_uri(httpretty.GET,
                           "https://api.github.com/search/repositories",
                           body=request_callback)

    # Simply issue the request...
    ghdwn.get_github_list('java')
    assert httpretty.last_request().headers[
        'Authorization'] == 'token fhqwhgads'

    original_exists = os.path.exists

    # Now pretend that file DOES NOT exist!
    @monkeypatch_on_path_match(os.path, 'exists')
    def intercept_exists_fails(path, *args, **kwargs):
        return False

    @monkeypatch_on_path_match(__builtin__, 'open')
    def intercept_open_failure(path, *args, **kwargs):
        raise IOError('Could not find file!')

    # Issue the same request again:
    ghdwn.get_github_list('java')
    assert 'Authorization' not in httpretty.last_request().headers

    # Disable HTTPretty
    httpretty.disable()
    httpretty.reset()

My favourite part is the inexplicable monkeypatch_on_path_match decorator.

In the end, I feel like I did this because I could; not because it ends up testing whether or not my magic "authorize on the existence of a file" actually works.


texts: PDO prepared statement - binding variable number of values

texts:
Please let me know if I have over/under explained my question :)

HTML table row - the numerals from each id attribute, in this example "408" and "409", are the database tables primary ID numbers, one database table row per HTML table cell.

    Delete

jQuery - I push these ids to an array and POST it to ajax.php

$('tbody').on('click','.deleteTableRow',function(){
var IDs = [];
$(this).closest('tr').find('td').each(function(){ IDs.push(this.id); });
var deleteTableRow = IDs;
$(this).parent().parent().remove();
    jQuery.ajax({
        type: "POST",
        url: "includes/ajax.php",
        data: {deleteTableRow: deleteTableRow},
        success: function (response) {
            $('body').append(response);
        },
        error: function (response) {
            alert("Error getting php file");
        }
    });
});

PHP - ajax.php. This works wonderfully, but is there a better way to bind a variable number of values into a single prepared statement? Currently I have HTML tables containing 2 MySql rows or 3 MySql Rows, but this will need to handle around a maximum of 10 MySql rows

if(isset($_POST['deleteTableRow'])){

    // Remove empty array value generated by the table cell containing my delete button
    $deleteRowArray = array_filter($_POST['deleteTableRow']);

    // Create an array of '?,' values - one for each id
    foreach($deleteRowArray as $addBind) {
        $array[] = '?,';
    }

    // Remove the last array values comma
    end($array);
    $array[key($array)] = '?';
    reset($array);

    // Create the finished query with as many binded values as needed
    $sql = 'DELETE FROM dataformset WHERE DataFormSetId IN (' . implode($array) .') LIMIT 3';
    $q = $db->prepare($sql);

    $i = 1;
    foreach($deleteRowArray as $deleteRow) {

        // Remove the text "FieldId" and bind each ID into a single prepared statement
        $deleteRow = preg_replace("/[^0-9,.]/", "", $deleteRow);
        $q->bindValue($i, $deleteRow, PDO::PARAM_STR);
        ++$i;
    }
$q->execute();
}


texts: Does this method contain multiple implementations?

texts:
My teammate and I have a small discussion about the responsibility of a method. He thinks next method has two responsibilities and I think that only one.

 private boolean validateUsername(String username) {
    AccountValidationResult validationResult =
            mAccountValidator.validate(username, new int[]{AccountValidation.VALIDATION_REQUIRED});

    if (!validationResult.isSuccessful()) {
        mView.setUsernameModeError(validationResult.getMessage());
    } else {
        mView.setUsernameModeStandard();
    }
    return validationResult.isSuccessful();
}

I think that the responsibilities of validating the string "username" falls on the "validate" method of my mAccountValidator collaborator. Depending of the result returned by my collaborator, I change the state of the view and finally, in order to finish the process or not, I return the state of validation. This result is managed by the next method:

public void doLogin(UserCredentialModel userCredential) {

    if (!validateUsername(userCredential.getUsername())) {
        return;
    }

    if (!validatePassword(userCredential.getPassword())) {
        return;
    }

    mDoLogin.setUserCredential(userCredential);
    mDoLogin.execute();
}

What do you think about my solution? Do you think that is it enough clean or how I could improve it?

Thank a lot for your time and help.


texts:
I am trying to write simple graph lib in C++, BFS, DFS etc..
I want to create class GraphI which will represent any graph and will include necessary methods so my library could work.
Could I add/remove/improve something from my code?

#pragma once
#include <algorithm>
#include "colors.h"
struct Vertex;
template < typename T >
class GraphI {

public:
    struct Vertex {
        Vertex( const T& k, color col = color::w, int c = -1 )
            : key( k )
            , color(col)
            , cost( c ) {}

        int getCost() const { return cost; }
        const T& getKey() const { return key; }
        T& getKey() { return key; }
        void setColor( color c ) { color = c; }
        color getColor() { return color; }

        int cost;
        color color;
        T key;
        bool operator<( const Vertex& v1 ) const {
            return key < v1.key;
        }
    };
    using Graph = std::map<Vertex, std::list<Vertex> >;
    GraphI() = default;
    virtual ~GraphI() = default;

    virtual void add_vertex( const T& vertex ) {
        // if exists then add else do nothing
        _graph[ vertex ] = {};
        ++_size;
    }
    virtual void add_edge( const T& from,
                   const T& to,
                  int cost = -1 ) {
        // if vertices do NOT exist return
        auto it = _graph.find( from );
        if ( it == _graph.end() ) return;

        auto it2 = _graph.find( to );
        if ( it2 == _graph.end() ) return;

        auto& neighbours = it->second;
        auto it_exists = std::find_if( neighbours.begin(),
                        neighbours.end(),
                        [&to]( const Vertex& vertex ) { return vertex.getKey() == to; } );
        // if edge already exists
        if ( it_exists != neighbours.end() ) return;
        neighbours.emplace_back( Vertex(to, color::w, cost) );
    }
    virtual void remove_vertex( const T& vertex ) {
        _graph.erase( vertex );
        --_size;
        // remove all edges going TO vertex
        for ( auto& v : _graph ) {
            auto it = std::find_if( v.second.begin(),
                        v.second.end(),
                        [&vertex]( const auto& v )
                        { return vertex == v.getKey(); } );
            // if vertex does NOT exist
            if ( it == v.second.end() ) return;
            v.second.erase( it );
        }

    }
    virtual void remove_edge( const T& from, const T& to ) {
        auto it = _graph.find( from );
        if ( it == _graph.end() ) return;

        auto &edges = it->second;
        auto it2 = std::find_if( edges.begin(), edges.end(),
                    [&]( const auto& vertex ) { return vertex.key == to; } );

        if ( it2 == edges.end() ) return;
        edges.erase( it2 );
    }

    const Graph& graph() const { return _graph; }
    unsigned size() const { return _size; }
private:
    Graph _graph;
    unsigned _size;
};


texts: Reverse an integer, find the absolute difference, then reverse again

texts:
For one of my university assignments, we were asked to take an unsigned int, reverse its digits, find the absolute difference between the original and reversed, then reverse that, and you receive the "Magic Number".

$$ R(\ \lvert R(A) - A\rvert\ )$$

where \$A\$ is a positive integer and \$R(n)\$ means reverse.

We were also asked to take multiple inputs at once and keep track of the largest absolute difference between all inputs.

#include <stdio.h>

// Reverse an unsigned integer
unsigned int reverseInteger(unsigned int input) {

    unsigned int output = 0;

    while (input != 0) { // Terminate when input is 0
        output = output * 10 + input % 10; // Can't use =* here, order of operations!
        input /= 10;
    }

    return output;
}

// Find the absolute differnece between a reversed number, then reverse the absolute difference
unsigned int generateMagicNumber(unsigned int input) {

    /* Find Absolute Difference */
    if (input < reverseInteger(input)) {
        input = reverseInteger(input); // If the result will be negative, reverse the number before finding the difference
        input -= reverseInteger(input);
    }
    else {
        input -= reverseInteger(input);
    }

    largestAbsoluteDifference(input);

    return reverseInteger(input); // Reverse absolute difference to find the magic number

}

// Find the largest of all values passed to this function
unsigned int largestAbsoluteDifference(unsigned int input) {

    static unsigned int keep = 0; // Must be static!

    return (input > keep) ? (keep = input) : keep; // If the input is greater than the current, store the input. Else, keep the current.

}

int main() {

    int inputs;
    printf("Enter number of inputs: ");
    scanf("%d", &inputs);
    printf("Enter space separated: ");

    for (int i = 0; i < inputs; i++) {
        unsigned int num;
        scanf("%u", &num);

        if (i == 0) { printf("\nOutput: "); } // Append label only on first iteration

        printf("%u ", generateMagicNumber(num)); // Generate and print the magic number
    }

    printf("\nLargest Absolute Difference: %u\n", largestAbsoluteDifference(0)); // Must pass 0 into largestAbsoluteDifference

}

Example Input / Output

Enter number of inputs: 5
Enter space separated: 23 512 454 94 100

Output: 9 792 0 54 99
Largest Absolute Difference: 297

Notes / Concerns

The way I wrote the largestAbsoluteDifference seems slimy me to (having to pass 0 to get the result).
I've got in the habit of calling functions inside a printf instead of storing the value in a variable and then printing the variable (see lines 56, 59). Is this okay?
In generateMagicNumber I had to make sure finding the difference wouldn't result in a negative number (which you can't store in an unsigned int). Is my method the best way to find the absolute value like that?


texts: Find diagonal positions for bishop movement

texts:
In a chess board, I need to find the diagonals a bishop can move on, and more specifically, the coordinates of those squares. So, given a grid of any size and a position in that grid (expressed in coordinates within the grid), I have to compute the coordinates of the diagonals of that initial position.

I'm using zero-based indexing, and the (row, column) notation for coordinates.

For example, on a 8x8 grid, with starting position of (0, 0), the returned list should be [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7)].

On a 8x8 grid, with starting position of (3, 4), the returned list should be [(3, 4), (2, 3), (1, 2), (0, 1), (4, 5), (5, 6), (6, 7), (4, 3), (5, 2), (6, 1), (7, 0), (2, 5), (1, 6), (0, 7)]

This is my working program in Python 3:

def diagonals(coord, size):
    limit = size - 1
    coords = [coord]
    row = coord[0]
    col = coord[1]

    while row > 0 and col > 0:
        row -= 1
        col -= 1
        coords.append((row, col))

    row = coord[0]
    col = coord[1]

    while row < limit and col < limit:
        row += 1
        col += 1
        coords.append((row, col))

    row = coord[0]
    col = coord[1]

    while row < limit and col > 0:
        row += 1
        col -= 1
        coords.append((row, col))

    row = coord[0]
    col = coord[1]

    while row > 0 and col < limit:
        row -= 1
        col += 1
        coords.append((row, col))

    return coords

coord = (3, 4)
size = 8
print(diagonals(coord, size))

Depending on the diagonal (4 cases), row and column are added or subtracted by one until the last square is reached, and everything is kept in a list, which in the end is returned.

It works, but it left me wondering if there's a simpler, different, better way of doing this, probably using linear algebra or something? And what about idiomatically, how can this be more pythonic?


texts: Takes function and throws exception if passed function doesn't throw an exception

texts:
The code below is part of a toy test assertion library I've written.

I'm looking for feedback specifically on lines 4 - 9.  I'd like to extract them from the throws function.  I can think of two options.

Create a function with a name like maybeReportExceptionError().  This seems not great because a) it feels like the function has two responsibilities and b) the maybe in the name seems hard to understand for someone not familiar with the inner workings of the function.
Replace the if/else if with a polymorphism.  I'm not sure how to go about this.

Any thoughts greatly appreciated!

function throws(testFunction, expectedMessage) {
  var thrownMessage = getFunctionExceptionMessage(testFunction);

  if (thrownMessage === undefined) {
    throw new Error("Expected an exception");
  } else if (thrownMessage !== expectedMessage) {
    throw new Error("Threw - " + thrownMessage + " - not - " + expectedMessage);
  }
};

function getFunctionExceptionMessage(fn) {
  try {
    fn();
  } catch (exception) {
    return exception.message;
  }
};

// USAGE:

// Throws "Error: Expected an exception"
throws(function() {

}, "Expected message");

// Throws "Error: Threw - Thrown message - not - Expected message"
throws(function() {
  throw new Error("Thrown message");
}, "Expected message");


texts:
I've written a program and it needs a review by skilled programmers.

The programs goal is to change 0-s to X and X-s to 0. The rule is X or O can move only to an empty place and x or o can only "jump" over one X or O. Program looks like:

------------------
|x|x|x|x| |o|o|o|o|
------------------

User input

move from? (0-8)

3

move to? (0-8)

4

Output

 -----------------
|x|x|x| |x|o|o|o|o|
------------------

package tornasz;
import java.util.Scanner;

public class Tornasz {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char[] table = {'x', 'x', 'x', 'x', ' ', 'o', 'o', 'o', 'o'};
        int [] move = new int[2];
        int result;
        int counter = 0;

        do
        {
            drawPlayfield(table, counter);
            move = getValidMove(sc,table,move);
            makeMove(table,move);
            result = checkWin(table);
            counter ++;
        }
        while (result == 0);
        drawPlayfield(table,counter);
        displayWinner(result);
    }

    public static void drawPlayfield(char [] table, int counter){
        System.out.println("Lépésszám: "+counter);
        System.out.println("------------------");
        System.out.println("|"+table[0]+"|"+table[1]+"|"+table[2]+
                "|"+table[3]+"|"+table[4]+"|"+table[5]+"|"+table[6]+"|"+table[7]
        +"|"+table[8]+"|");
        System.out.println("------------------");
        counter++;
    }
    public static int [] getValidMove(Scanner sc, char [] table, int [] move)
    {
        System.out.println("Melyik mezővel lépsz? (0-8)");
        int start = sc.nextInt();
        if (start == -1)
        {
            System.exit(0);
        }
        System.out.println("Melyik mezőre lépsz? (0-8)");
        int destination = sc.nextInt();
        if (destination == -1)
        {
            System.exit(0);
        }
        while (start < 0 || start > 8 || destination < 0 || destination > 8)
        {
            System.out.println("Érvénytelen lépés!");
            System.out.println("Melyik mezővel lépsz? (0-8)");
            start = sc.nextInt();
            if (start == -1)
            {
                System.exit(0);
            }
            System.out.println("Melyik mezőre lépsz? (0-8)");
            destination = sc.nextInt();
            if (destination == -1)
            {
                System.exit(0);
            }
        }
        while (table[destination] != ' ')
        {
            System.out.println("Érvénytelen lépés!");
            System.out.println("Melyik mezővel lépsz? (0-8)");
            start = sc.nextInt();
            System.out.println("Melyik mezőre lépsz? (0-8)");
            destination = sc.nextInt();
        }

        int [] movement = new int[2];
        movement[0] = start;
        movement[1] = destination;
        return movement;
    }
    public static void makeMove(char [] table, int [] move)
    {
        table[move[1]] = table[move[0]];
        table[move[0]] = ' ';
    }
    public static int checkWin(char [] table)
    {
        if (table[0] == 'o' && table[1] == 'o' && table[2] == 'o' &&
                table[3] == 'o' && table[4] == ' ' && table[5] == 'x' &&
                table[6] == 'x' && table[7] == 'x' && table[8] == 'x')
        {
        return 1;
        }
        return 0;
    }
    public static void displayWinner(int result)
    {
        if (result == 1)
        {
            System.out.println("Gratulálok, vége a játéknak!");
        }
    }

}

Now I only need to set the movement rules. I think it will be an another method with boolean.


texts:
I'm a little unhappy with the look of this "flexible" way of dealing with errors from an API in Ruby:

class ApiError < StandardError
  def initialize(response)
    message = response.is_a?(String) ? response
            : !(response.respond_to? 'body') ? 'Error'
            : response.body.is_a?(Hash) ? response.body['message']
            : response.body.to_s
    super(message)
  end
end

The idea is you can pass to ApiError.new either a string, or an object with an accessor called body in which case we'll take the body if it's a string or its message property if it's a hash. We'll use a generic error message if the argument is anything else.

What would be the idiomatic alternative, if any? I'm happy to take suggestions for completely different approaches (multiple constructors, static factories, etc.) but am still interested in a single-initialize-method approach. I know I can do if...elsif...elsif...else...end. Is that better?


texts:
I'm absolutely new to Clojure (started learning it yesterday). After I went through some tutorials and checked out the basics I implemented the following Binary search algorithm:

(defn log-search
    [elements, elem-to-find]
        (loop [left 0
            right (- (count elements) 1)]
          (when (<= left right)
          (def m (int (Math/floor (/ (+ left right) 2))))
          (def actual (nth elements m))
              (cond
                  (= actual elem-to-find) m
                  (< actual elem-to-find) (recur (+ m 1) right)
                  (> actual elem-to-find) (recur left (- m 1))))))

The followings are intentional in the implementation:

returning nil on empty sequence
I return nil if the element is not present
I do not care if (+ left right) overflows on very big sequence (I'm focusing only on the language features)

My questions:

Is there any Clojure (or funcional programming) antipattern in the
code?
What would be a more functional (or Clojure) approach?

Any other suggestions are more than welcomed.

Thank you.


texts:
I am concerned about a few things about my heap implementation. This is in Kotlin.

For starters-

When and when not to use expressions?
The use of also to swap numbers

Other suggestions about the algorithm and the code are welcome.

class BinaryHeap : Iterable<Int> {

    private val array = mutableListOf(0)
    var heapSize = 0

    override fun iterator(): Iterator<Int> = array.iterator()

    private fun parent(i: Int) = i.shr(1)

    private fun left(i: Int) = i.shl(1)

    private fun right(i: Int) = i.shl(1).plus(1)

    private fun maxHeapify(i: Int) {

        var largest: Int
        val left = left(i)
        val right = right(i)

        largest = if (left <= heapSize && array[i] > array[left]) i
        else if (left <= heapSize) left
        else i

        if (right <= heapSize && array[largest] < array[right])
            largest = right

        if (largest != i) {
            swap(largest, i)
            maxHeapify(largest)
        }

    }

    val max = if (heapSize != 0) array[1] else -1

    fun extractMax(): Int {
        return if (heapSize < 1)
            -1
        else {
            val max = array[1]
            array[1] = array[heapSize]
            heapSize--
            maxHeapify(1)
            max
        }
    }

    private fun swap(i: Int, j: Int) {
        array[i] = array[j].also { array[j] = array[i] }
    }

    fun insert(i: Int) {
        if (array.size > heapSize + 1)
            array[++heapSize] = i
        else {
            array.add(i)
            heapSize++
        }
        var badNode = heapSize
        var parentBadNode = parent(badNode)
        while (parentBadNode != 0 && array[parentBadNode] < array[badNode]) {
            swap(parentBadNode, badNode)
            badNode = parentBadNode.also { parentBadNode = parent(parentBadNode) }
        }
    }

    fun insert(i: Iterable<Int>) {
        i.forEach {
            insert(it)
        }
    }

    override fun toString(): String {
        return array.joinToString { "$it " }
    }
}
```


texts:
I have this tiny function that expects an int and returns an int with the bytes swapped:
public class Main {

    public static void main(String[] args) {
        int cafeBabe = 0xcafebabe;
        System.out.println(Integer.toHexString(cafeBabe));
        System.out.println(Integer.toHexString(byteSwap(cafeBabe)));
        System.out.println(Integer.toHexString(byteSwap(byteSwap(cafeBabe))));
    }

    public static int byteSwap(int a) {
        return ((a & 0xff000000) >>> 24) |
               ((a & 0x00ff0000) >>> 8)  |
               ((a & 0x0000ff00) << 8)   |
               ((a & 0x000000ff) << 24);
    }
}

Basically, we are switching between endianess. Now, is there a better/more efficient way of accomplishing the task?


texts:
The problem statement can be found here. In short, here's what the problem is about:

  You're given a set of numbers and you need to find whether the the numbers are ordinary or psycho. For a number to be psycho, its number of prime factors that occur even times should be greater than the number of prime factors that occur odd number of times. Else, it's ordinary.

My solution for this is as follows:

First, I initialize the Sieve of Eratosthenes. This is the fastest method I know to get a list of prime numbers.
Next, I loop over all the test cases and loop over all it's factors that are prime to increment the even and odd counter, to finally compare them and find the answer. For this I have to loop from 0 to half of the number.

This algorithm of mine is \$O(n)\$ for one input. Since the input size is of the order of \$10^7\$ and the number of inputs of the order of \$10^6\$ my algorithm takes time of the order of \$10^{13}\$. I need help with reducing this time.

#include <cstdio>
using namespace std;

bool primes[5000000];

void erastho()
{
   for (int i = 0; i < 5000000; i++)
   {
      primes[i] = 1;
   }
   primes[0] = 0;
   primes[1] = 0;
   for (int i = 2; i < 3164; i = i + 1)
   {
      if (primes[i])
      {
         int p = i*2;
         while(p < 5000000)
         {
            primes[p] = 0;
            p = p + i;
         }
      }
      else continue;
   }
}

int main()
{
   erastho();
   int t;
   scanf("%d", &t);
   while(t--)
   {
      int n;
      scanf("%d", &n);
      int hal = n/2;
      int v, ev = 0, od = 0;
      for (int i = 2; i <= hal; i++)
      {
         if((primes[i]) && (n%i == 0))
         {
            while (n%i == 0)
            {
               n = n/i;
               v++;
            }
            if (v % 2 == 0) ev++;
            else od++;
            v = 0;
         }
      }
      if (ev > od)
      {
         printf("%s \n","Psycho Number");
      }
      else
      {
         printf("%s \n", "Ordinary Number");
      }
   }
}


texts: What is wrong with my Genetic Algorithm?

texts:
I am trying to understand how genetic algorithms work. As with everything, I learn by attempting to write something on my own;however, my knowledge is very limited and I am not sure if I am doing this right.

The purpose of this algorithm is to see how long it will take half of a herd to be infected by a disease if half of that population are already infected. It is just an example I came up with in my head so I am not sure if this would even be a viable example.

Some feedback on how I can improve my knowledge would be nice.

Here is the code:

import random

def disease():
    herd = []
    generations = 0
    pos = 0
    for x in range(100):
        herd.append(random.choice('01'))
    print herd
    same = all(x == herd[0] for x in herd)
    while same == False:
        same = all(x == herd[0] for x in herd)
        for animal in herd:
            try:
                if pos != 0:
                    after = herd[pos+1]
                    before = herd[pos-1]
                    if after == before and after == '1' and before == '1' and animal == '0':
                        print "infection at", pos
                        herd[pos] = '1'
            #print herd
                pos += 1
            except IndexError:
                pass
        pos = 0
        generations += 1
        random.shuffle(herd)
        #print herd
    print "Took",generations,"generations to infect all members of herd."
if __name__ == "__main__":
    disease()

I am looking for comments based on the logic of this algorithm. What can be improved, and what has to be improved to make this a true genetic algorithm if it isn't one already.


texts: Is it possible to refactor these two similar methods that handle T and List?

texts:
Is there a way to unify or refactor two methods that do basically the same but the difference being of handling a type of object or a collection of the same type of object?
The following is an implementation of two methods that have very similar behavior. They handle a cache for an API, so when someone asks for a value or a set of values, it verifies that the entry is in cache already. If not, they call the method that will return from an external API: a value or a set of values. Finally the methods, update the cache and return the value/values.
public async Task<T> GetValue<T>(string cacheKey, Func<Task<T>> getItem, MemoryCacheEntryOptions memoryCacheEntryOptions = null)
{
    if (_memoryCache.TryGetValue(cacheKey, out T cacheEntry))
    {
        return cacheEntry;
    }
    else
    {
        cacheEntry = await getItem();

        return SetValue(cacheKey, cacheEntry, memoryCacheEntryOptions);
    }
}

public async Task<IList<T>> GetValues<T>(string cacheKey, Func<Task<IList<T>>> getItems, MemoryCacheEntryOptions memoryCacheEntryOptions = null)
{
    if (_memoryCache.TryGetValue(cacheKey, out IList<T> cacheEntries))
    {
        return cacheEntries;
    }
    else
    {
        cacheEntries = await getItems();

        return SetValues(cacheKey, cacheEntries, memoryCacheEntryOptions);
    }
}


texts:
I have written a code to count the number of files in a folder and if there are any folder inside folder it will count the files in that folder too.

import java.io.File
class GetFileCount {
  def getFilesCount(dir: String):Int = {
    val file = new File(dir)
    require(file.exists() && file.isDirectory)
    def inDirectoryFiles(inDir:List[File]):Int={
      if(inDir.filter(_.isDirectory).nonEmpty)
        inDir.filter(_.isFile).length + inDirectoryFiles(inDir.flatMap(_.listFiles.toList))
      else
        inDir.filter(_.isFile).length
    }
    file.listFiles.filter(_.isFile).toList.length + inDirectoryFiles(file.listFiles.filter(_.isDirectory).toList)
  }
}

I feel like it could be done more nicely.


texts:
A valid Sudoku board has the following properties

The board must be square (n-by-n). Let m = sqrt(n)
All rows must contain the numbers 1-n
All columns must contain the numbers 1-n
All nine m-by-m blocks must contain all numbers 1-n

The following MATLAB code verifies a Sudoku board of arbitrary sizes (where n is a square number):

function correct_board = sudoku_checker(board)

correct_board = true;
[rows, cols] = size(board);
correct_size = (rows == cols) && mod(sqrt(rows),1) == 0;
if correct_size == false
    disp('The board is not square')
    correct_board = false
else
    disp('The board is square')
    for ii = 1:rows
        if ~(isequal(unique(board(:,ii)), (1:rows)') && isequal(unique(board(ii,:)), (1:rows)))
            disp(['Numbers ' num2str(1) '-' num2str(rows) ' are not present in all rows or columns'])
            correct_board = false;
            return
        end
    end
    disp(['Numbers ' num2str(1), '-' num2str(rows) ' are present in all rows and columns'])

    cell_blocks = mat2cell(board, repmat(sqrt(rows),sqrt(rows),1),repmat(sqrt(rows),sqrt(rows),1));
    blocks_ok = all(arrayfun(@(x) isequal(unique(cell_blocks{x}),(1:rows)'), 1:rows));
    if blocks_ok == true
        disp(['All blocks are OK'])
    else
        disp(['All blocks are not OK'])
        correct_board = false;
        return;
    end
    disp('Board is OK')
end
end

A valid board will give the following output:

sudoku_checker(board)
The board is square
Numbers 1-9 are present in all rows and columns
All blocks are OK
Board is OK

An incorrect board will give an output like this (dependent on which condition that fails):

sudoku_checker(board)
The board is square
Numbers 1-4 are present in all rows and columns
All blocks are not OK

I'm wondering if there are ways to improve this code. I'm looking for improvements in performance and algorithm, as well as improvement in coding style etc.

Can I simplify any expressions? Remove some boolean operators?


texts: Given two sorted arrays, add the elements of the second array into the first

texts:
In Cracking the Coding Interview by Gayle Laakmann McDowell, there's a question that asks you to write code for the following:

  Given two sorted arrays, A and B. Write a method merging the elements
  of B into A in sorted order. Assume A has a large enough buffer at the
  end to hold all of B's elements.

Though the problem isn't very hard, I've been striving to increase the readability of my code in general. As such, I wrote two versions of my solution, and am looking for input on which version is most readable.

Version 1:

// Given two sorted arrays, adds the elements of the second array into
// the first, while maintaining ordering property.
// XXX: Assumes first array has enough buffer space to hold all elements
public static <Type extends Comparable<Type>> Type[]
mergeIntoFirstArray(Type[] first_array, Type[] second_array) {

    int first_idx         = numElementsInArray(first_array) - 1;
    int second_idx        = second_array.length - 1;
    int merge_idx        = numElementsInArray(first_array) + second_array.length - 1;    //

    // merge largest values first, until either array is exhausted
    while (first_idx >= 0 && second_idx >= 0) {
        Type first_value    =  first_array[first_idx];
        Type second_value    =  second_array[second_idx];

        // add the largest value
        if (first_value.compareTo(second_value) > 0){
            first_array[merge_idx] = first_value ;
            first_idx--;
        } else {
            first_array[merge_idx] = second_value ;
            second_idx--;
        }
        merge_idx-- ;
    }

    // if second_array still has values, merge them in
    while (second_idx >=0) {
        first_array[merge_idx] = second_array[second_idx] ;
        merge_idx-- ;
        second_idx--;
    }

    return first_array ;
}

Version 2:

public static <Type extends Comparable<Type>> Type[]
mergeIntoFirstArrayV2(Type[] first_array, Type[] second_array) {
    int f    = numElementsInArray(first_array)-1;
    int s    = second_array.length - 1;

    // merge in largest values first
    for (int merge_idx = f + s + 1 ; merge_idx >= 0 ; merge_idx--) {
        Type fvalue    =  f >= 0 ? first_array[f]  : null;
        Type svalue    =  s >= 0 ? second_array[s] : null;

        // first value exists, and is greater than second value
        if (fvalue != null &&
            (svalue == null || fvalue.compareTo(svalue) > 0)) {
            first_array[merge_idx] = svalue ;
            s_idx--;
        }
        else {
            first_array[merge_idx] = svalue ;
            s_idx--;
        }
    }

    return first_array ;
}

Any meaningful input on improving the readability of either method would also be appreciated. For one, I think my variable names might be unclear or too long in some cases. For version 2, I suspect that though the code is more concise, it is harder to understand at a glance.


texts: Perl script to rename files in a directory tree

texts:
I'm taking a scripting language course with no prior scripting language or Linux experience, though I've taken classes in VB, Java, and C++. Our first assignment is to write a script that will traverse the directory tree of the location the script is run from and rename the files according to some predetermined rules. In this case, directories are to have spaces, \", and any .hxx or .cxx extensions removed. Files get the same treatment except their extensions are changed to .h or .cpp respectively. Also, the script isn't supposed to actually change the file names, just produce a file with the commands to do so, mine are bash commands in the form of mv 'old file name' 'old_file_name'.

#!/usr/bin/perl -w

use Cwd;
use File::Find;
use strict;

my $file = "output.txt";
my $dir = getcwd;

# Creates file to print output to, Die with error message if we can't open it
open my $fh, '>>', $file
    or die "$file: $!\n";

# traverse the directory tree
find(\&process_files, $dir);

# creates a file of bash rename scripts
sub process_files
{
    my $s1 = $_;
    if (-f)
    {
        $s1 =~ s/\s/_/g;
        $s1 =~ s/\"//g;
        $s1 =~ s/\.cxx/\.cpp/g;
        $s1 =~ s/\.hxx/\.h/g;
        print $fh "mv '" , $_ , "' " ,  $s1 , "\n";
        print "mv '" , $_ , "' " ,  $s1 , "\n";
    }
    if (-d)
    {
        $s1 =~ s/\s/_/g;
        $s1 =~ s/\"//g;
        $s1 =~ s/\.(cxx|hxx)//g;
        print $fh "mv '" , $_ , "' " ,  $s1 , "\n";
        print "mv '" , $_ , "' " ,  $s1 , "\n";
    }
}
close $fh;


texts: Compact ways to filter even numbers in Java int array

texts:
I am writing some examples of Java programs on GitHub rsp/ppj for people to learn and I want them to be as simple and compact as possible, to work on Java 1.7.x (a.k.a. Java 7) and to not use any non-standard libraries that need installation.

This question is about my WhereEven example:

a function of an int[] array that returns an int[] array with only even numbers

(The method can internally use any other data types if it makes sense.)

Here is how my example looks like right now:

static int[] even(int[] t) {
    int i, j;
    for (i=j=0; i < t.length; i++)
        if (t[i] % 2 == 0) j++;
    int[] r = new int[j];
    for (i=j=0; i < t.length; i++)
        if (t[i] % 2 == 0) r[j++] = t[i];
    return r;
}

I am not satisfied with that code because it is much more complex than the same in JavaScript - even using the old ES5 syntax (few years older than Java 7) it is:

function even(t) {
    return t.filter(function(x){ return x % 2 == 0; });
}

It is even better in Scheme, which is amazing considering the fact that this is a language that's 40 years old:

(define (even t)
    (filter even? t))

But I can't get to the solution that is even remotely as simple and readable in Java. Of course I can add comments and more meaningful variable names, but the point is that in Scheme and JS the code is simple and the meaning is obvious as it is. What I am looking for is a way to write a better code, not to write the same code but with better names.

What in your opinion is "the best" way to improve the above code to be most useful for an educational example like this? Maybe the shortest way in terms of lines/characters, the most readable way, the most idiomatic way, the way using best practices, the most crazy way? I am looking forward to every suggestion of my code improvement that would help people learn something about Java and maybe I'll put few different approaches in my tutorial.

The only requirement is taking an int[] array, returning a new int[] array (but internally the method can use any other data types if it makes sense), working on Java 1.7.x (a.k.a. Java 7) and not using any non-standard classes.


texts:
My special case: home project, automatic downloader for podcasts.

Overall algorithm is:

Download a list of available podcasts
hash the podcasts
load metadata + hash of downloaded podcasts from sqlite db
Algorithm this questions is about -  throw out all already downloaded.
Download new podcasts
save metadata to sqlite db

Algorithm discussion

I'm hoping for comments on using std::rotate, performance, and the implementation.

For downloaded data, I currently use a vector. For data from DB, I also use a vector.

I merge both together and sort them according to the hashes (obviously).

And algorithm doubleEraser on the merged vector.

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <string>

template <typename ForwardItr>
ForwardItr doubleEraser(ForwardItr first, ForwardItr last)
{
 auto itr = first;
 typename std::iterator_traits<ForwardItr>::value_type firstMatch = *first;
 bool hasFirstMatch(false);

 while(itr != last)
 {
  auto next = std::next(itr);
  if(next != last && *itr == *next)
  {
    if(!hasFirstMatch)
    {
     hasFirstMatch = true;
     firstMatch = *itr;
    }
    else
    {
     if(*itr == firstMatch) // again at first match
     {
       return itr;
     }
    }

    std::rotate(itr, std::next(itr, 2), last); // throw matched elements to the end of container
   }
   else
    ++itr;
  }
 return last;
}

template <typename T>
void print(T& c)
{
 for(auto & element : c)
  std::cout << element << " ";

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

template <class T>
void process(std::vector<T>& t)
{
  std::string formating(" \t");
   std::cout << "input: " << formating;
 print(t);
 std::sort(t.begin(), t.end());
 std::cout << "sorted:" << formating;
 print(t);
 auto itr_begin = doubleEraser(t.begin(), t.end());
 std::cout << "dEraser:" << formating;
 print(t);
 t.erase(itr_begin, t.end());
 std::cout << "output:" << formating;
 print(t);
}

int main()
{
 std::vector<int> vec {1,2,3,4,5,6,7,8,9,3,5,6,7,2};
 std::vector<char> vec2 {'A', 'C', 'D', 'D', 'G', 'A' };
 std::vector<std::string> vec3 {"Hello", "World", "that", "be", "that", "Hello"};

 process(vec);
 process(vec2);
 process(vec3);
}


texts: Encoding text to keypresses on old phone keyboard (0-9*#)

texts:
I am going through "Haskell Programming from first principles" for the first time and I would like to get some pointers on what can be improved in my code, which is the following:

module DaPhone ( stringToKeyTaps
           , fingerTaps
           , mostPopularLetter
           , mostPopularWord
           , coolestLtr
           , coolestWord
           , daPhoneTaps
           , daPhoneTaps
           , testKeyBoard
           , testConvo) where

import Data.Char
import Data.List
import Data.Maybe

type KeyLabel = Char
type Digit = Char

data Key = Key KeyLabel [Digit] deriving (Eq, Show)
label (Key l _) = l
digits (Key _ ds) = ds

isDigitOf :: Digit -> Key -> Bool
c `isDigitOf` key = c `elem` (digits key)

type KeyboardLayout = [Key]

getKeyFor :: KeyboardLayout -> Digit -> Key
getKeyFor kmap c = fromJust $ find (c `isDigitOf`) kmap

type Taps = Int
type KeyTaps = [(KeyLabel, Taps)]

stringToKeyTaps :: KeyboardLayout -> String -> KeyTaps
stringToKeyTaps _ [] = []
stringToKeyTaps kmap (c:cs)i
    | c `elem` ['A'..'Z'] =
    charToKeyTap kmap '^' : stringToKeyTaps kmap ((toLower c):cs)
    | c `elem` charSet = charToKeyTap kmap c : stringToKeyTaps kmap cs
    | otherwise = stringToKeyTaps kmap cs
    where charSet = foldr ((++) . (digits)) [] kmap

charToKeyTap kmap c =
        (label $ theKey, (fromJust $ elemIndex c $ digits $ theKey) + 1)
                        where theKey = getKeyFor kmap c

fingerTaps :: KeyTaps -> Taps
fingerTaps = foldr ((+) . snd) 0

mostPopularLetter :: String -> Char
mostPopularLetter = mostPopularElement

mostPopularWord :: String -> String
mostPopularWord = mostPopularElement . words

coolestLtr :: [String] -> Char
coolestLtr = mostPopularLetter . filter (/=' ') . concat

coolestWord :: [String] -> String
coolestWord = mostPopularWord . intercalate " "

mostPopularElement :: (Ord a, Eq a) => [a] -> a
mostPopularElement = head . head .
        sortBy (\x y -> (length y) `compare` (length x)) . group . sort

-- provided variables
testKeyBoard :: KeyboardLayout
testKeyBoard = [ Key '1' "1"
               , Key '2' "abc2"
               , Key '3' "def3"
               , Key '4' "ghi4"
               , Key '5' "jkl5"
               , Key '6' "mno6"
               , Key '7' "pqrs7"
               , Key '8' "tuv8"
               , Key '9' "wxyz9"
               , Key '0' " 0"
               , Key '*' "^"
               , Key '#' ".,"
               ]

testConvo :: [String]
testConvo = [ "Wanna play 20 questions"
            , "Ya"
            , "U 1st haha"
            , "Lol ok. Have u ever tasted alcohol lol"
            , "Lol ya"
            , "Lol ur cool haha. Ur turn"
            ]

--partially applied converter for provided exercise
daPhoneTaps = stringToKeyTaps testKeyBoard

I would love to get a code review by someone better acquainted to functional programming and Haskell.


texts:
I have written this code representing a class hierarchy of character classes, and a world class to print their properties.

Is anything unclear about this code?  Am I utilizing good practices?

class Human{
    protected String name;
    protected int health;
    protected int armorLevel;
    protected int magicLevel;
    protected int experience;
    protected int level;
        Human(){
        name = "Andrew The Magic";
        health = 100;
        armorLevel = 1;
        magicLevel = 1;
        experience=0;
        level =1;
        }

    Human(String name){
        this(); //calling main constructor
        this.name = name;
    }

void fight() {}
void levelUp() {}
void showAbility() { System.out.println("Name: "+name+" HP: "+health+" ARMOR: "+armorLevel+" MAGIC: "+magicLevel+" EXP: "+experience+" LVL: "+level); }
void yell(){    System.out.println("IM A CHARACTER ;-(");   }
}

//--------------------------------------------------------------
class Warrior extends Human{

    Warrior(){
        super();
    }

    Warrior(String name){
        super(name);
    }

    void fight(){
        System.out.println("I attack with sword");
        experience +=10;
        if (experience >= 20 ){ levelUp();  }
        }

    void levelUp(){
        System.out.println("LEVEL UP!");
        health +=100;
        armorLevel +=25;
        level++;
    }

    void yell(){
        System.out.println("IM A GLORIOUS WARRIOR "+name);
    }
}
//--------------------------------------------------------------

public class World{

    static void greeting(Human p){
        p.yell();
    }

        public static void main(String[] args){
          Warrior w = new Warrior("Noname the Warrior");
            w.showAbility();
            w.fight();
            w.showAbility();
            w.fight();
            w.showAbility();

            greeting(w);
   }
}


texts:
Since this problem involves small numbers (particularly with a small loop count of 100), it's possible to ease the modulo operation setup by simply working with 16-bit and 8-bit registers:

$$\dfrac{\text{[AX] (16-bit register)}}{\text{[other 8-bit register]}} = \text{[AH] (remainder)}$$

My main concern is with the layout.  Every "basic" high-level implementation I've seen has a check and print together for each case.  I've found it easier to do the same thing here, but I'm not sure if that would also be too readable in assembly.

I'm also aware that it's good to minimize register-moving.  Unfortunately, I still do that with every case since I'm incrementing with one register (CX) and using another (AX) for the dividend.  I can stick to AX for both, but that may involve keeping a copy of the current counter value, which may just make the code a bit more complicated.  I suppose it's not much of a problem here anyway.

Macros used:

nwln -  prints a newline
PutStr - prints a defined string
PutInt - prints a 16-bit integer value

It's not necessary to address the macros; they do work properly.

%include "macros.s"

.DATA

fizz_lbl:       DB    "Fizz", 0
buzz_lbl:       DB    "Buzz", 0
fizzbuzz_lbl:   DB    "FizzBuzz", 0

.CODE
.STARTUP

xor   CX, CX ; counter

main_loop:
   inc   CX
   cmp   CX, 100

   jg    done

   fizzbuzz_check:
      mov   AX, CX ; dividend = counter
      mov   BH, 15 ; divisor
      div   BH     ; (counter / 15)

      cmp   AH, 0            ; counter divisible by 15?
      je    print_fizzbuzz   ; if so, proceed with printing

      jmp   fizz_check       ; if not, try checking for fizz

      print_fizzbuzz:
          PutStr   fizzbuzz_lbl
          nwln
          jmp      main_loop

   fizz_check:
      mov   AX, CX ; dividend = counter
      mov   BH, 3  ; divisor
      div   BH     ; (counter / 3)

      cmp   AH, 0        ; counter divisible by 3?
      je    print_fizz   ; if so, proceed with printing

      jmp   buzz_check   ; if not, try checking for buzz

      print_fizz:
          PutStr   fizz_lbl
          nwln
          jmp      main_loop

   buzz_check:
      mov   AX, CX ; dividend = counter
      mov   BH, 5  ; divisor
      div   BH     ; (counter / 5)

      cmp   AH, 0        ; counter divisible by 5?
      je    print_buzz   ; if so, proceed with printing

      jmp   print_other  ; if not, then can only display number

      print_buzz:
          PutStr   buzz_lbl
          nwln
          jmp      main_loop

   print_other:
      PutInt   CX
      nwln
      jmp   main_loop

done:
   .EXIT


texts:
Just to quickly explain what this is and what it does: it's a config handler that loads a file that has configuration data in INI format, key=value that sort of format. I then just store it all inside a double string dictionary and take items from the dictionary when I need them.

Questions:

Is my dispose pattern okay? Do I even need to dispose in the first place? I'm still learning about disposing and memory management.
Should I be locking on the dictionary?
Am I okay to use LINQ? I recently got told that LINQ slows down your code. Is there any better way to do this? Is the speed much different?

namespace Pitaya.Root.Core.Config
{
    internal class ConfigHandler : IDisposable
    {
        private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

        private Dictionary<string, string> _configItems;

        internal ConfigHandler()
        {
            _configItems = new Dictionary<string, string>();
            LoadConfig("/resources/config/config.ini");
        }

        internal void LoadConfig(string configFile)
        {
            try
            {
                if (!File.Exists(configFile) || FileUtilities.IsFileLocked(new FileInfo(configFile)))
                {
                    Logger.Error("Either your config file couldn't be found, or its open somewhere else.");

                    Console.ReadKey(true);
                    Environment.Exit(0);
                }

                _configItems = File.ReadLines(configFile).Where(IsConfigurationLine).Select(line => line.Split('=')).ToDictionary(line => line[0], line => line[1]);
            }
            catch (Exception exception)
            {
                Logger.Fatal("Error while loading config: " + exception.Message);
                Logger.Fatal(exception.StackTrace);

                Console.ReadKey(true);
                Environment.Exit(0);
            }
        }

        private static bool IsConfigurationLine(string line)
        {
            return !line.StartsWith("#") && line.Contains("=");
        }

        internal string GetConfigValueByKey(string key)
        {
            if (!_configItems.TryGetValue(key, out var value))
            {
                Logger.Warn("Missing configuration key `" + key + "`");
            }

            return value;
        }

        public void Dispose()
        {
            Dispose(true);
        }

        private void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            _configItems.Clear();
            _configItems = null;
        }
    }
}


texts:
For this graph and its vertex cover I try to compare the LP solution with the optimal and the rounded solution.

from scipy.optimize import linprog
obj = [1, 1, 1, 1, 1, 1, 1, 1]
lhs_ineq = [[ -1,  -1, 0, 0, 0, 0, 0, 0],[ -1,  0, 0, -1, 0, 0, 0, 0],[ 0,  -1, -1, 0, 0, 0, 0, 0],[ 0,  -1, 0, 0, -1, 0, 0, 0],[ 0,  0, -1, -1, 0, 0, 0, 0],[ 0,  0, 0, -1, 0, 0, 0, -1],[ 0,  0, 0, -1, 0, 0, -1, 0],[ 0,  0, 0, 0, -1, -1, 0, 0],[ 0,  0, 0, 0, 0, -1, -1, 0],[ 0,  0, 0, 0, 0, -1, 0, -1]]
rhs_ineq = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
bnd = [(0, float("inf")),(0, float("inf")),(0, float("inf")),(0, float("inf")),(0, float("inf")),(0, float("inf")),(0, float("inf")),(0, float("inf"))]
opt = linprog(c=obj, A_ub=lhs_ineq, b_ub=rhs_ineq, bounds=bnd, method="revised simplex")
print(opt)

What comes out is the following, which looks like the optimal solution even though it was done with LP.
     con: array([], dtype=float64)
     fun: 3.0
 message: 'Optimization terminated successfully.'
     nit: 11
   slack: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
  status: 0
 success: True
       x: array([0., 1., 0., 1., 0., 1., 0., 0.])

The array in the output [0,1,0,1,0,1,0,0] represents a vertex cover with the nodes 2,4,6 which is also the optimal solution (the digit is 0 for a node not in the solution and 1 otherwise).


texts:
I've been thinking my posts aren't that great, and so I've been wanting to improve them.
One sure fire way to do this is to look at all of my downvoted posts.
Not knowing if Stack Exchange allows you to do this already, I decided I should learn SQL, and wrote a SEDE query.
The query, downvoted posts by user, takes a single parameter which is the user id.
And returns a list of downvoted posts, with a link to the post, its score, and the amount of downvotes.

I've never written a line of SQL before, and so I'm unsure if my query is any good.
I think using GROUP BY is a bit weird to get a sum of all the downvotes, is there a better way to do this?
And having looked at various other SEDE queries, I don't know if my style is any good either.

declare @user_id int = ##UserId:int##

SELECT
    p.Id as [Post Link],
    p.Score,
    sum(case when p.Id = v.PostId then 1 else 0 end) as [Downvotes]
FROM
    Posts p
inner join
    Votes v on p.Id = v.PostId
WHERE
    p.OwnerUserId = @user_id
and v.VoteTypeId=3
GROUP BY
    p.Id, p.Score
ORDER BY 'Downvotes' DESC, Score DESC


texts: Printing letters in order like a pyramid

texts:
There is this hackerrank question, where we need a rhombus of letters. As to my opinion it can be viewed as some fractal, or similar logic.

Well I solved the question, but I am obviously disappointed with the code I come up with. Actually when I started writing I knew how I would end-up and I was ready to ask a question here.

I am reluctant to share this code of mine but it is necessary, if I am to improve.

size = int(raw_input())
alphabet = "abcdefghijklmnopqrstuvwxyz"
def draw(size):
    shape = "" # The answer
    tmp_size = size # defining a temporary size variable to help with the solution
    tmp_size -= 1
    while tmp_size+1:
        hyphen_count = (size-tmp_size) *2 - 2 # Needed hyphen count for the left-right of new_line
        hypens = hyphen_count*"-" # Hyphens to be added

        # The new line, the strange ranges I used was to get the correct letters in place. Probably needs simplifying.
        new_line = "-".join([alphabet[abs(num)] for num in range(1-size,tmp_size-size+1) + range(size-tmp_size-1, size)])

        # Draw one line if it is the first line
        if tmp_size == size - 1:
            shape = shape + new_line
        # Draw to both top and bottom if it is not the first line.
        else:
            shape = hypens + new_line + hypens + "\n" + shape + "\n" + hypens + new_line + hypens
        tmp_size -= 1
    return shape
print draw(size)

I added many comments for easier evaluation of this badly-written code. So what I ask is:

Dear users with algorithm experience, please help me find a better method if not the code itself. (Maybe a recursion ?)
Dear programmers, please help me implement better python.
Dear users that know everything, please teach me everything.


texts: Pasting Values To/From a Calculation Model

texts:
I have a Database worksheet (SoapUI - CollisionsSingle) that have around 1500 records and 38 columns of data per record. I have a VBA script that copies the records into a algorithm worksheet (COL_STpremcalc) and then copies the results back to the database worksheet. However it takes around 1-2 minutes to perform 1 record, and all but breaks my laptop to the point I can't do anything while it runs.

Sub SingleRating()
Dim i As Long
Dim iteration As Variant
Dim seleciton As Variant
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = Worksheets("SoapUI - CollisionsSingle")
Set ws2 = Worksheets("COL_STpremcalc")

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayStatusBar = False

iteration = 0
iteration = InputBox("Please Select Row Iteration", "", "1")
seleciton = iteration + 3

    For i = 4 To seleciton

        ws2.Range("B3").Value = ws1.Range("D" & i).Value

        ws2.Range("B4").Value = ws1.Range("E" & i).Value

        ws2.Range("B5").Value = ws1.Range("F" & i).Value

        ws2.Range("B6").Value = ws1.Range("G" & i).Value

        ws2.Range("E3").Value = ws1.Range("H" & i).Value

        ws2.Range("E4").Value = ws1.Range("I" & i).Value

        ws2.Range("E5").Value = ws1.Range("J" & i).Value

        ws2.Range("E6").Value = ws1.Range("K" & i).Value

        ws2.Range("G3").Value = ws1.Range("L" & i).Value

        ws2.Range("G4").Value = ws1.Range("M" & i).Value

        ws2.Range("G5").Value = ws1.Range("N" & i).Value

        ws2.Range("J3").Value = ws1.Range("O" & i).Value

        ws2.Range("J6").Value = ws1.Range("P" & i).Value

        ws2.Range("C9:E9").Value = ws1.Range("Q" & i, "S" & i).Value

        ws2.Range("C10:E10").Value = ws1.Range("T" & i, "V" & i).Value

        ws2.Range("C11:E11").Value = ws1.Range("W" & i, "Y" & i).Value

        ws2.Range("C12:E12").Value = ws1.Range("Z" & i, "AB" & i).Value

        ws2.Range("C13:E13").Value = ws1.Range("AC" & i, "AE" & i).Value

        ws2.Range("C14:E14").Value = ws1.Range("AF" & i, "AH" & i).Value

        ws2.Range("C15:E15").Value = ws1.Range("AI" & i, "AK" & i).Value

        ws2.Range("C16:E16").Value = ws1.Range("AL" & i, "AN" & i).Value

        '''''''''''''''''''''''''''''''''''''''''''''''''

        ws1.Range("AO" & i).Value = ws2.Range("M4").Value

        Application.StatusBar = "Current iteration: " & (i - 1) & "/" & iteration
    Next i

Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayStatusBar = True

End Sub

The reason I don't just do the calculation in the database worksheet is that there is about 100+ calculations that happen before the final results and the calculations are complex.

The calculation happens almost instantly, it is the copying of the data back and forth that I believe is slowing the whole thing down.

Is there a way to make this more efficient to the point it would only take around 20-30 minutes?


texts: Tree structure with support for inorder and preorder traversal

texts:
I am learning Tree Data Structures and came up with this code for implementing basic Tree Node using class and performing various Tree based operations like Traversals and others. The code works perfectly but the structure is bothering me a lot, such as this line of code here:

print(tree.size(tree))

How can I improve the code structure?

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

    def __str__(self):
        return self.data

    def inorder(self, node):
        if node is not None:
            self.inorder(node.left)
            print(node.data)
            self.inorder(node.right)

    def preorder(self, node):
        if node is not None:
            print(node.data)
            self.preorder(node.left)
            self.preorder(node.right)

    def size(self, node):
        if node is None:
            return 0
        return self.size(node.left) + 1 + self.size(node.right)

tree = Node(1)
tree.left = Node(2)
tree.right = Node(3)
tree.left.left = Node(4)
tree.left.right = Node(5)

print(tree.size(tree))


texts: Improving handling of data structure used in parallel

texts:
I have a class extending the Dictionary class. This class is used for storing some information (modeled in CustomClass) and accessing it through an integer ID.

To extend this class I have added a TryAdd method, specific to my workflow, which implement different behaviours for the cases of trying to add a new or a already existing CustomClass object.

public class CustomDictionary : Dictionary<int, CustomClass>
    {
        private void TryAdd(int ID, CustomClass customObject)
        {
            if (this.ContainsKey(ID))
            {
                //some operations
            }
            else
            {
                //some others operations
                this.Add(customObject);
            }
        }
    }

There will be only one instance object for this class. I want to add locks to provide thread safety and syncronisation for the object of type CustomDictionary.
TryAdd and data accessing operation will frequently occur in parallel for this structure.

Have in mind that at the moment I can't use framework 4.0 so I can't use ConcurrentCollections.

To ensure thread safety I put this.Add(customObject); within a lock(this) but I have read that this is very bad.

Then I read about locking using a private object.

public class CustomDictionary : Dictionary<int, CustomClass>
    {
        private object lockObject = new Object();

        private void TryAdd(int ID, CustomClass customObject)
        {
            if (this.ContainsKey(ID))
            {
                //some operations
            }
            else
            {
                //some others operations
                lock(lockObject)
                {
                    this.Add(customObject);
                }
            }
        }
    }

Is this the good way of doing it? Should I also lock the CustomDictionary object when I read data from that object?

Any improvements for the implementation of this class would be helpfull.


texts:
I'm becoming acquainted with ruby by taking some of my legacy shell scripts and rewriting them as .rb.

The pattern that is emerging is that I have a number of different dumb tasks, that do what they are told, and a coordinator that is responsible for ordering the tasks, and providing to the tasks the data that will be needed.

For instance, at the end of one of my jobs, I will need to convert some data to a human readable format, perform a two phase upload of that data to a remote server, and then send a notification to subscribers announcing the successful delivery of the data.

class PublishReportProcess
  def initialize(convertor, uploader, email)
    @convertor = convertor
    @uploader = uploader
    @email = email
  end

  def run(task = {})
    convert_context = {}
    convert_context[:type] = 'geo'
    convert_context[:output] = "#{task[:workspace]}/#{task[:report_id]}.json"

    @convertor.convert(convert_context)

    upload_context = {}
    upload_context[:local] = convert_context[:output]
    upload_context[:staging] = "#{task['reports']['workspace']['uri']}/#{task['report_id']}"
    upload_context[:remote] = "#{task['reports']['repository']['uri']}/#{task['report_id']}"

    @uploader.upload(upload_context)

    email_context = {}
    email_context[:message] = <<MESSAGE
There is a new report available at #{task['reports']['repository']['uri']}/#{task['report_id']}.

Share and enjoy
MESSAGE

    @email.email(email_context)
  end
end

The implementation of the tasks, if it matters, tend to be using the arguments of the map passed to them to create a command line string that can be passed to Open3.popen2e.


texts:
I'm learning Django and making my (technically second) project.

The project features several apps, including player_interface and manager_interface.

Here's the player_interface/models.py:

from django.db import models
from django.contrib.auth.models import User

class PlayerProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.PROTECT,
                                limit_choices_to={'is_staff': False})
    balance = models.PositiveIntegerField(default=0)

    def __str__(self):
        return f'PlayerProfile user_id={self.user_id} balance={self.balance}'

In the manager_interface app, I want to create users together with corresponding player profiles. So I made a form (in manager_interface/forms.py):

from django import forms
from django.contrib.auth.models import User
from django.db import transaction

from player_interface.models import PlayerProfile

PlayerProfileUserFormset = forms.inlineformset_factory(
    User, PlayerProfile, fields=('balance',),
    extra=1, max_num=1, can_delete=False)

class PlayerUserForm(forms.ModelForm):
    def __init__(self, data=None, instance=None, **kwargs):
        super().__init__(data=data, instance=instance, **kwargs)
        self.formset = PlayerProfileUserFormset(data=data,
                                                instance=self.instance)

    def is_valid(self):
        return super().is_valid and self.formset.is_valid()

    @transaction.atomic
    def save(self):
        super().save()
        self.formset.save()
        return self.instance

    class Meta:
        model = User
        fields = ('username', 'password')

And this is how I use this form in manager_interface/views.py:

<...>

class CUPlayerMixin:
    template_name = 'manager_interface/players_form.html'
    form_class = PlayerUserForm
    success_url = reverse_lazy('players_list')

class CreatePlayerView(CUPlayerMixin, edit_views.CreateView):
    pass

class UpdatePlayerView(CUPlayerMixin, edit_views.UpdateView):
    queryset = User.objects.filter(is_staff=False)
    slug_field = 'username'
    slug_url_kwarg = slug_field

And the relevant template bit is:

{% block content %}
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <div>{{ form.formset.as_p }}</div>
        <button type="submit">Submit</button>
    </form>
{% endblock %}

The code above works.

My question is: is this a good, Django way to handle a form for both a model and its association?

In this case, I edit both the User model with the associated PlayerProfile. That's why I decided to use the formset: it would automatically populate the subform for the player profile and then save it with the self.formset.save() part, keeping track of the association and all.

Thank you very much!


texts:
I have a route I've rewrote to use promises.

router.post(
  '/forgot-password',
  (req, res) => {
    //generate random password
    let passwordString = Math.random().toString(36).slice(-10);

    User
      .findOne({'username': req.body.email})
      .then(foundUser => {
        foundUser.setPassword(
          passwordString,
          () => {
            foundUser.save(
              () => {
                emailService.sendForgotPassword(foundUser, passwordString);
                req.flash('success', 'Please check your email.');
                res.redirect('/login');
              });
          });
      })
      .catch(err => {
        if(err && err.message) req.flash('error', 'Cannot find a user by that email.');
        res.redirect('back');
      });
  });

I think my then route could be better than what it is now. How do I optimize the promise chain a little better?