texts:
A little while ago I wrote some jQuery code to make a div flip (similar to the Apple Dashboard). I know there is already code that has this idea from Jon Raasch, but this code positioned divs absolutely, which I did not need for my cause.

I just wondered if anyone could give me some advice as to how to tidy this up and make it cleaner.

(function ($) {
  $.fn.extend({
    jFlip: function (options) {
        var defaults = {
            trigF: '.flipDiv',
            trigB: '.flipDivBack'
        };
        var o = $.extend({}, defaults, options);
        return this.each(function () {
            var f = $('.front');
                b = $('.back');

            margin = f.width() / 2;
            width = f.width();
            height = f.height();
            b.hide().css({
                width: '0px',
                height: '' + height + 'px',
                marginLeft: '' + margin + 'px',
                opacity: '0'
            });

            $(o.trigF).on('click', function () {
                var $this = $(this);

                $this.parents().closest(f).animate({
                    width: '0px',
                    height: '' + height + 'px',
                    marginLeft: '' + margin + 'px',
                    opacity: '0'
                }, {
                    duration: 500
                });

                window.setTimeout(function () {
                    $this.parents().next(b).animate({
                        width: '' + width + 'px',
                        height: '' + height + 'px',
                        marginLeft: '0px',
                        opacity: '1'
                    }, {
                        duration: 500
                    });
                }, 500);
            });

            $(o.trigB).on('click', function () {
                $(this).parents().closest(b).animate({
                    width: '0px',
                    height: '' + height + 'px',
                    marginLeft: '' +margin + 'px',
                    opacity: '0',
                    display: 'none'
                }, {
                    duration: 500
                });
                var $this = $(this).parents().siblings(f);
                window.setTimeout(function () {
                    $this.stop().animate({
                        width: '' + width + 'px',
                        height: '' + height + 'px',
                        marginLeft: '0px',
                        opacity: '1'
                    }, {
                        duration: 500
                    });
                }, 500);
            });
        });
    }
  });
})(jQuery);

The div structure is this:

Front of the div

        <button class="flipDiv">Flip</button>

Back of the div

        <button class="flipDivBack">Flip Back</button>

And this is the initiation:

The only options as of yet however are trigF and trigB, which allows you to specify the name of your buttons which will flip the div.

You can see a jsFiddle of this in action here.


texts: Connect to streaming Twitter API, parse tweets, and write to CSV in real-time

texts:
I have been using Tweeepy to connect to the Twitter Streaming API to collect tweets, parse that data, and then write select fields to a CSV file.  Based on some examples that I found, I put together the following code to manage that connection.  One thing that I had to work around was how to handle the connection getting killed.  I was able to include an while-loop that properly handles exceptions and restarts the connection if needed.

I want to make sure that this code is optimized and that I'm not including things that might not be needed.

#!/usr/bin/env python

import logging
import time
import csv
import json
import tweepy
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy.streaming import StreamListener
from datetime import datetime
from dateutil import parser

# enable logging
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(levelname)s %(module)s - %(funcName)s: %(message)s',
                    datefmt="%Y-%m-%d %H:%M:%S")
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# authorize the app to access Twitter on our behalf
consumer_key = ' '
consumer_secret = ' '
access_token = ' '
access_secret = ' '
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)

# establish open connection to streaming API
class MyListener(StreamListener):

    def on_data(self, data):
        try:
            tweet = parse_tweet(data)
            content = extract_content(tweet)
            with open('tweets.csv', 'a') as f:
                writer = csv.writer(f, quotechar = '"')
                writer.writerow(content)
                #logger.info(content[3])

        except BaseException as e:
            logger.warning(e)

        return True

    def on_error(self, status):
        logger.warning(status)
        return True

# parse data
def parse_tweet(data):

    # load JSON item into a dict
    tweet = json.loads(data)

    # check if tweet is valid
    if 'user' in tweet.keys():

        # parse date
        tweet['CREATED_AT'] = parser.parse(tweet['created_at'])

        # classify tweet type based on metadata
        if 'retweeted_status' in tweet:
            tweet['TWEET_TYPE'] = 'retweet'

        elif len(tweet['entities']['user_mentions']) > 0:
            tweet['TWEET_TYPE'] = 'mention'

        else:
            tweet['TWEET_TYPE'] = 'tweet'

        return tweet

    else:
        logger.warning("Imcomplete tweet: %s", tweet)

# extract relevant data to write to CSV
def extract_content(tweet):

    content = [tweet['user']['screen_name'],
               tweet['CREATED_AT'].strftime('%Y-%m-%d %H:%M:%S'),
               tweet['TWEET_TYPE'],
               tweet['text'].encode('unicode_escape')]

    return content

def start_stream():

    while True:

        logger.warning("Twitter API Connection opened")

        try:
            twitter_stream = Stream(auth, MyListener())
            twitter_stream.filter(track=['nyc'])

        except Exception as e:
            logger.warning(e)
            continue

        finally:
            logger.warning("Twitter API Connection closed")

if __name__ == '__main__':
    start_stream()


texts: DBSCAN "region query" too slow; implement a tree?

texts:
My current DBSCAN in Python works...but its indexing is far too slow; its a linear scan:

def find(self, p):
    nearby = []
    for pt in self.data:
        # Haversine algorithm
        px, ptx, py, pty = map(math.radians, [p.x, pt.x, p.y, pt.y])
        dx = px - ptx
        dy = py - pty
        a = math.sin(dy/2)**2 + math.cos(py)*math.cos(pty)*math.sin(dx/2)**2
        c = 2*math.asin(math.sqrt(a))
        d = 6371.0*c
        if d < self.eps:
            nearby.append(pt)
    return nearby

self.eps: The defined radius in km (hence the Haversine implementation)

self.data: Python list object of my Point() objects:

class Point:
    def __init__(self, lon, lat):
        self.x = lon
        self.y = lat
        self.cluster = None
        self.neighbors = 0

When I run the DBSCAN with say 27,000 points, the find() has to iterate through each point (technically minus 1 each time, but that's moot) for at worst O(N2) (assumes no points in the 27,000 are noise (i.e. they have valid minimum points within self.eps).

I have heard maybe a tree would be better for this? Not sure which and I would prefer to not keep adding modules (if possible!).


texts: Tax Calculator using Java 8 and BigDecimal

texts:
I am learning Java8 and BigDecimal. The following exercise involved
writing a Tax Calculator that took a salary and calculated the tax
payable based on the tax band into which the salary falls. The test
passes as the code stands but if I remove the call to

setScale(0, BigDecimal.ROUND_UP)

then the rounding does not occur and the tests fail like this >

TaxCalculator.calculateTax > 712.50

java.lang.AssertionError:  Expected: is <713>
      but: was <712.50>

I don't understand that because the 2nd parameter to the divide call
specifies that rounding should be performed.

Also, Can anyone suggest
improvements to the way this class is written please? I'm just trying
to nail down best practices with respect to the Streams API. Am I using
an appropriate way to calculate a percentage in Java?

import org.junit.Before;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.TreeMap;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class TaxCalculatorTest {

    private TaxCalculator taxCalculator;

    private HashMap<BigDecimal, BigDecimal> testData = new HashMap<>(); // <salary, taxPayable>
    private TreeMap<BigDecimal, BigDecimal> taxBands = new TreeMap<>(); // uses natural ordering of keys
    // Could have used LinkedHashMap to maintain order but that relies on entries being inserted in the correct order

    @Before
    public void setup() {

        testData.put(new BigDecimal("5000"), new BigDecimal("225"));
        testData.put(new BigDecimal("11000"), new BigDecimal("413"));
        testData.put(new BigDecimal("19000"), new BigDecimal("713"));
        testData.put(new BigDecimal("27000"), new BigDecimal("905"));

        taxBands.put(new BigDecimal("10000"), new BigDecimal("4.5"));
        taxBands.put(new BigDecimal("35000"), new BigDecimal("3.35"));         // TreeMap fixes the ordering
        taxBands.put(new BigDecimal("20000"), new BigDecimal("3.75")); // This entry will be inserted before the previous one

        taxCalculator = new TaxCalculator(taxBands);
    }

    @Test
    public void calculateTax(){

        testData.forEach((salary, taxPayable) -> {

            assertThat(taxCalculator.calculateTax(salary), is(taxPayable));
        }) ;
    }
}

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.TreeMap;

class TaxCalculator {

    private static final BigDecimal NO_TAX = new BigDecimal("0");

    /*
     * scale > the number of digits to the right of the decimal point
     *
     * precision > the number of significant digits
     *
     * BigDecimal instances are immutable
     *
     */

    private BigDecimal ONE_HUNDRED = new BigDecimal("100");

    private final TreeMap<BigDecimal, BigDecimal> taxBands;

    TaxCalculator(TreeMap<BigDecimal, BigDecimal> taxBands) {
        this.taxBands = taxBands;
    }

    BigDecimal calculateTax(BigDecimal salary) {

        BigDecimal taxPayable = salary.multiply(getTaxRate(salary)).divide(ONE_HUNDRED, BigDecimal.ROUND_UP).setScale(0, BigDecimal.ROUND_UP);

        System.out.println("TaxCalculator.calculateTax > " + taxPayable);
        return taxPayable;
    }

    private BigDecimal getTaxRate(BigDecimal salary) {

        return taxBands.entrySet().stream()
                .filter((entry) -> salary.compareTo(entry.getKey()) < 0)
                .map(HashMap.Entry::getValue)
                .findFirst().orElse(NO_TAX);
    }
}


texts:
Is there a better way to insert after a node in a linked list? Currently I go through the node from the head of the list and find the node that has the value pos. If the node is not null at the end of the search then we found the position, so we do the insert.

void insert_after(List& list, int pos, int value)
{
    Node* newNode = new Node{value}, p;

    for (p = list.head; p && p->data != pos; p = p->next) {;}

    if (p)
    {
        newNode->next = p->next;
        p->next = newNode;
    }
}

I just don't know if this is the best way. Could it be improved at all?


texts:
I'm moving some octagons around and I found a serious bottleneck:

@win.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    for o in octagons:
        o.vertices = tuple(chain.from_iterable( (o.vertices[i]+dx, o.vertices[i+1]+dy) for i in range(0, 18, 2)))

The program starts lagging when about 1000 points (111 octagons) are moved at once. I must find a way to optimize it but OpenGL is the last straw I want to draw because I don't want to use an API I don't understand. Could someone suggest a way to make it faster? Any internal solution or should I use NumPy? Here's the whole code (mere 30 lines) if you want to run it on your machine:

import pyglet
from circle import octagon
from random import randrange
from itertools import chain

SIZE = 800
RADIUS = 50
COUNT = 50
WIN = SIZE, SIZE, 'Camera', True, 'tool' # x, y, caption, resizable, style

def rnd_c():
    return (randrange(256), randrange(256), randrange(256)) * 9

def rnd_pos():
    return randrange(SIZE)

win = pyglet.window.Window(*WIN, vsync=False) # vsync off to unlimit FPS
batch = pyglet.graphics.Batch()
octagons = [octagon(rnd_pos(), rnd_pos(), RADIUS, rnd_c(), batch, None) for _ in range(COUNT)]
fps = pyglet.clock.ClockDisplay()

@win.event
def on_draw():
    win.clear()
    batch.draw()
    fps.draw()

@win.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    for o in octagons:
        o.vertices = tuple(chain.from_iterable( (o.vertices[i]+dx, o.vertices[i+1]+dy) for i in range(0, 18, 2)))

def on_step(dt):
    pass
pyglet.clock.schedule(on_step)

pyglet.app.run()

Graphics are fine (I think). I can render 1000 steady octagons @ 300 FPS.


texts: Building an undirected graph from depth-first sorted node list in Python

texts:
I have an array called nodes that contains a list of Node objects. The list is sorted in depth-first order. I have a function called build_undirected_tree that assigns the parent value and creates a list of children for each Node in the list.

I'm not satisfied with the need for using the idx array to circumvent Python's lack of pass-by-reference on primitive-type arguments and I'm wondering if there's a conceptually simpler way to accomplish the same thing.

class Node(object):
    def __init__(self, child_count):
        self.child_count = child_count

'''
This is a depth-first iterator. The weird `idx` array is used because
integers cannot be pass-by-reference.
'''
def node_iterator(nodes, idx=None, parent=None):
    if idx is None:
        idx = [0]
    node = nodes[idx[0]]
    yield (node, parent)
    for i in range(node.child_count):
        idx[0] += 1
        yield from node_iterator(nodes, idx, node)

def build_undirected_tree(nodes):
    for (node, parent) in node_iterator(nodes):
        node.parent = parent
        node.children = []
        if parent is not None:
            parent.children.append(node)

nodes = [...]
# Populate nodes from a file.
build_undirected_tree(nodes)


texts:
This question is the first draft, my new revised code is here:
Anagrams for a given input 2.0

Here is my code that I wrote, which basically lists the anagrams for a given input.

I did this by reading each line in my dictionary file and comparing it to the anagram.  Only if it matched did I add it to the list, instead of adding all the words to the list and then sorting through them.

I compared the words by first checking the length of both words, and then if they matched I put put each word into a list and then sorted the list, then I compared the two lists using the equals() function. And iterated my counter.

The function of my getOutPut() was just to neaten up the printout.

What I would like are some critiques on my work and what I should/could have done differently, especially pertaining to semantic efficiency, code correctness, common practices that I may be unaware of, and code efficiency.

This is only my second project, so I want to learn from it to become a better programmer.  That's why I'm asking.

The methods are in the order they are called in:

(Note that I split the code up to make it easier to see, all the methods are inside the Anagramatic Class)

package anagramatic;

/**
 * IDE : NETBEANS
 * Additional Libraries : Guava
 * @author KyleMHB
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class Anagramatic {
static int k;

-

public static void main(String[] args) throws FileNotFoundException{
    String anagram;
    anagram=input();
    ArrayList<String> words=readFile(anagram);
    String output= getOutPut(words);
    JOptionPane.showMessageDialog(null,
            "The anagram "+anagram+" has "+k+" matches, they are:\n\n"+output);
}//PVSM

-

private static String input() {
    String input;
    input = JOptionPane.showInputDialog(null,
     "Enter the Word or words you would like to be processed");
    return input;
}//input

-

private static ArrayList readFile(String anag) throws FileNotFoundException{
    k=0;
    ArrayList<String> list;
    ArrayList<Character> a;
    ArrayList<Character> b;
    try (Scanner s = new Scanner(new File("words.txt"))){
        list = new ArrayList<>();
        while (s.hasNext()){
            String word= s.next();
            if (word.length()==anag.length()){
                a = new ArrayList<>();
                b = new ArrayList<>();
                for(int i=0;i!=word.length();i++){
                    a.add(anag.charAt(i));
                    b.add(word.charAt(i));
                }//forloop to make two lists of the words
                Collections.sort(a);
                Collections.sort(b);
                if(a.equals(b)){
                    list.add(word);
                    k++;
                }//comparing the two lists
             }//if length
          }//while
       }//try
    return list;
}//readfile

-

private static String getOutPut(ArrayList<String> words) {
    String wordz="[";
    int x=0;
    int y=0;
    for(int i=0; i!=words.size()-1;i++){
        if(x!=7){
            wordz+=words.get(i)+", ";
            x++;
        }else{wordz+="\n";x=0;}
    }//for
    wordz+=words.get(words.size()-1)+"]";
return wordz;
}//getOutPut
}//Anagramatic


texts: Run arbitrary INSERT INTO SQL Query using parameters

texts:
While DoCmd.RunSQL is all well and good for simple code, the number of times I've run into problems with unescaped apostrophes and the like was starting to nark a bit. With that in mind I crafted the below, a first attempt at a SQL wrapper for VBA which constructs and executes an arbitrary INSERT INTO query using parameters.

'Fields should be a comma-delimited string
Public Sub InsertInto(TableName As String, Fields As String, Values As Variant)
    Dim qdf As DAO.QueryDef
    Dim strParams As String
    Dim i As Long
    Dim strSQL As String

On Error GoTo Err_InsertInto
    'Assigns strParams value in format "[p1],[p2],[p3],...,[pN]"
    For i = 0 To UBound(Values)
        strParams = strParams & "[p" & i & "],"
    Next i
    strParams = Left(strParams, Len(strParams) - 1) 'Strip trailing comma

    'Construct SQL
    strSQL = "INSERT INTO " & TableName & "(" & Fields & ") " & _
             "VALUES (" & strParams & ");"
    Set qdf = CurrentDb.CreateQueryDef("", strSQL)

    'Give values to parameters
    For i = 0 To UBound(Values)
        qdf.Parameters("[p" & i & "]") = Values(i)
    Next i

    qdf.Execute

Exit_InsertInto:
    Set qdf = Nothing
    Exit Sub

Err_InsertInto:
    Select Case Err.Number
        Case 13   'Type mismatch i.e. Values is not an array
            Values = Array(Values)
            Resume
        Case Else 'Unhandled Error
            Set qdf = Nothing 'Release QueryDef object

            'Error is unhandled here, force it to 'bubble up' to calling code
            Dim iErrNum As Long, strErrDesc As String
            iErrNum = Err.Number
            strErrDesc = Err.Description
            On Error GoTo 0
            Err.Raise iErrNum, "SQLOps.InsertInto", strErrDesc
    End Select
End Sub

Likely to be called in a manner similar to (this example was used as a successful test case):

InsertInto "tblErrorLog", _
"ErrorNum,Description,User,When,Origin", _
Array(10,"Error's Description",Environ("USERNAME"),Now(),"A Ghost")

So far it seems to be working fine and does indeed alleviate the issues with unescaped apostrophes but I'm wondering whether this can be improved so I could use it as a sort of template for crafting similar functions for other SQL operations e.g. UPDATE SET / SELECT FROM.

Can this code be improved and are there any unforeseen bugs I should watch out for?


texts: Displaying total cost of prices from a table

texts:
I have this JavaScript function which gets prices from a table, adds them up, and outputs the total cost. I want to refactor this to make it as small as possible.

function getTotalPrice(do_request)
{
console.log('Get total price');
var prices_array = new Array(); // Where our prices are held

// For each .total_item_price - a <td> within my table.
$(".total_item_price").each(function(){
    var text = $(this).text();                   // Get the value
    var prices = text.substring(1, text.length); // Format it into a string
    prices_array.push(prices);                   // Push it onto our array
});

var result = eval(0);
//  Add up our array
for(i = 0; i < prices_array.length; i++)
{
    temp = eval(prices_array[i]);
    result += temp;
}
// Round up our result to 2 Decimal Places
result = Math.round(result*100)/100;
// Output/Return our result
if (do_request == null)
{
    // We want to add our shipping Price and Display the total
    // Get the Shipping Price
    //var shipping_price = $(".shipping_price").html();
    //shipping_price = shipping_price.substring(1, shipping_price.length);
    if ($(".tbl_row").length == 1) // If only 1 row exists (How do I do this?)
    {
         var size = $(".size").html();
         if((size == "A5") && ($('input[name="qty"]').val() == '1'))
         {
            console.log(' - A5 - ');
            $('.shipping_price').html('£0.67'); // Show Shipping Price (A5)
         }
         else if((size == 'A4') && ($('input[name="qty"]').val() == '1'))
         {
            console.log(' - A4 - ');
            console.log($('input[name="qty"]').val());
            $('.shipping_price').html('£0.87'); // Show Shipping Price (A4)
         }
         else
         {
            console.log('More then 1 Qty');
            $('.shipping_price').html('£0.97'); // Show Shipping Price (A4)
         }
    }
    else  // More then 1 row exists, so the price will be £0.97
    {
        console.log('false, More rows exists');
        $('.shipping_price').html('£0.97') // Show Shipping Price (A4)
    }

    var shipping_price = $(".shipping_price").html();
    shipping_price = shipping_price.substring(1, shipping_price.length);

    // Add em
    //result += eval(shipping_price);
    result += eval(shipping_price);

    // Round our result to 2 decimal places
    var result=Math.round(result*100)/100;

    // Update & Display the Result
    $('.total_order_price').html("<b>£" + result + "</b>");
}
else
{
    // Otherwise we just want the total price and return it.
    return result;
}
}


texts: Encrypting data on client side and passing it to server side

texts:
I'm passing the data to PHP server side which will use the information later as this:

    <script> function encrypt() {
        var salt = CryptoJS.lib.WordArray.random(128/8);
        var key256Bits500Iterations = CryptoJS.PBKDF2("'.$token.'", salt, { keySize: 256/32, iterations: 500 });
        var iv  = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");
        var encrypted = CryptoJS.AES.encrypt(document.loginForm.password1.value, key256Bits500Iterations, { iv: iv });
        var data_base64 = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
        var key_base64  = encrypted.key.toString(CryptoJS.enc.Base64);
        var iv_base64   = encrypted.iv.toString(CryptoJS.enc.Base64);
        var data = {encrypted: data_base64, iv: iv_base64, key: key_base64};
        document.loginForm.encrypted.value = JSON.stringify(data);
        return true;
    } </script>

My question is, since I am passing this through the form as POST, that still can be sniffed with shark-like tools and then decrypted with all information being passed through anyways.

What information should be private and how should I make them private? How could they be private if the IV, data, and the key are being send through the POST that are needed when decrypting the string?

How is the logic here flawed and how should it be used to protect data communication between client and server side computing?


texts:
Back on track with my C++ saga:

  The standard deviation of a list of numbers is a measure of how much
  the numbers deviate from the average. If the standard deviation is
  small, the numbers are clustered close to the average.  If the
  standard deviation is large, the numbers are scattered far from the
  average.  The standard deviation, \$ S \$, of a list of \$ N \$
  numbers \$ x \$ is defined as follows

  $$ S = \sqrt{\dfrac{\sum\limits_{i=1}^{N} \left( x_i - \bar{x} \right)^{2}}{N}} $$

  Where \$\bar{x} \$ is the average of the \$ N \$ numbers \$ x1, x2, .... \$ Define a function that takes a partially filled array of
  numbers as its arguments and returns the standard deviation of the
  numbers in the partially filled array.  Since a partially filled array
  requires two arguments, the function will actually have two formal
  parameters: an array parameter and a formal parameter of type int
  that gives the number of array positions used.  The numbers in the
  array will be of type double Embed your function in a suitable test
  program.

stddev.cpp:

/**
 * @file stddev.cpp
 * @brief
 * @author syb0rg
 * @date 11/6/14
 */

#include <iostream>
#include <fstream>
#include <cmath>

constexpr int NUM_ELEM = 28;

double mean(double arr[])
{
    double sum = 0;
    for (int i = 0; i < NUM_ELEM; ++i)
    {
        sum += arr[i];
    }
    return (sum / NUM_ELEM);
}

double stdDev(double arr[])
{
    double avg = mean(arr);
    double sum = 0;
    for (int i = 0; i < NUM_ELEM; ++i)
    {
        arr[i] = arr[i] - avg;
        sum += std::pow(arr[i], 2);
    }
    return std::sqrt(sum / NUM_ELEM);
}

int main()
{
    std::ifstream file("test.txt", std::ios_base::in);
    double input[NUM_ELEM] = {0.0};

    for(int i = 0; (file >> input[i]) && file.good(); ++i);
    std::cout << stdDev(input) << std::endl;
    file.close();
}


texts: How to properly detect multiple devices failure?

texts:
My software has multiple devices connected before starting. I must be sure these devices are working and are well connected. every device has different error ID code so we can see every component that is not working.

When the software will have completly test connection for every devices, we would like to show a message that will show every failing devices:

  Unable to connect on one or multiple devices [Error Code: XXXXXXX].
  Please look at the user manual at www.xxxx.com/en/UserManual and if
  you need further information, contact customer support or mail at
  xxxxx@example.com.

For the moment, i am using bitmask but i feel like it's not very "generic" and it kinda hard-coded.

We have made an ID for every class and put a base 2 number like this:

enum eErrorCode
{
    MOTORA    = 0x0000001,
    MOTORB    = 0x0000010,
    SERIAL    = 0x0000100,
    LAN       = 0x0001000,
    MAINBOARD = 0x0010000,
    GENERATOR = 0x0100000,
    MAX = 6
}

So when the Activating function fire, we can add every error:

Int32 ConnectToEveryDevice()
{
    Int32 Error = 0;
    foreach(IDevices device in this.Devices)
    {
         Error = Error | device.Connect();
    }
    return Error;
}

For example: If MotorA, Lan and Serial fail, The screen will popup the Hex [Error Code: 0x00001101] so the client can easily find the error in the user manual (online) and if we need to add devices we can do it without needing to change everything.  Does anyone have a better or cleaner alternative than this one?


texts: Project Euler #8 - Largest product in a series


texts: Builder Design Pattern To Store User Information

texts:
I am new to building with design patterns. I have been working on implementing the builder design pattern in PHP. I just want to make sure I am doing it correctly. I have been following along with this tutorial on jakowicz:
 https://www.jakowicz.com/builder-pattern-in-php/

I have made a few minor changes to the way I'm implementing the pattern but nothing too major. I just hope I am doing it correctly.

User.php

class User
{
    public $user;
    public $firstName;
    public $lastName;
    public $company;
    public $address;
    public $city;
    public $state;
    public $zip;

}

UserBuilderInterface.php

interface UserBuilderInterface
{
    public function setFirstName($firstName);
    public function setLastName($lastName);
    public function setCompany($company);
    public function setAddress($address);
    public function setCity($city);
    public function setState($state);
    public function setZip($zip);

    public function storeUser();
    public function getUser();
}

UserBuilder.php

class UserBuilder extends User implements UserBuilderInterface {

    public function __construct(){
        $this->user = new User();
    }

    public function setFirstName($firstName){
        $this->user->firstName = $firstName;
    }

    public function setLastName($lastName){
        $this->user->lastName = $lastName;
    }

    public function setCompany($company){
        $this->user->company = $company;
    }

    public function setAddress($address){
        $this->user->address = $address;
    }

    public function setCity($city){
        $this->user->city = $city;
    }

    public function setState($state){
        $this->user->state = $state;
    }

    public function setZip($zip){
        $this->user->zip = $zip;
    }

    public function getUser(){
        return $this->user;
    }

}

UserDirector.php

class UserDirector{

    public static function create(UserBuilderInterface $set, $first, $last, $company, $address, $city, $state, $zip){
        $set->setFirstName($first);
        $set->setLastName($last);
        $set->setCompany($company);
        $set->setAddress($address);
        $set->setCity($city);
        $set->setState($state);
        $set->setZip($zip);
        return $set->getUser();
    }
}

index.php

$user = UserDirector::create(new UserBuilder,'John', 'Doe', 'Foo', '1444 Foo Bar Ave', 'Fo', 'FO', '11111');

echo 'First Name:' . $user->firstName;
echo 'Last Name:' . $user->lastName;

BTW everything runs as expected. Just want to know if Im doing it right? Any feedback is greatly appreciated.

edit: My code will be used to store User information into a database. It is not for production use it is just to learn how to implement a design pattern


texts: Performance shifting for SQL Database and Linq memory grouping

texts:
I am messing around with shifting between stored procedures and business layer EF getting data rapidly then processing in memory.

This works and on a static data range of 3 months I get execution time of 2.3 seconds

Is there anything I can do to help the compiler increase CPU efficiency or even a better way to get data without worrying about locks, just get it in one quick go, it doesn't  change any way?

public static List<DashGraph> GetTimeOverviewData(DateTime start, DateTime end)
        {
            List<DashHelper> totals;
            List<DashHelper> visitors;
            List<DashHelper> visits;
            List<DashHelper> calls;

            Stopwatch sw = new Stopwatch();
            sw.Start();

            //Works like NOLOCK?
            using (new TransactionScope(
                    TransactionScopeOption.Required,
                    new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }))
            {
                using (var db = new Track_LOpEntities())
                {
                    visitors = db.JTrack_Visitors.AsNoTracking()
                        .Where(v => v.CreatedOn >= start & v.CreatedOn <= end)
                        .Select(v => new DashHelper() { DateAndTime = v.CreatedOn.Value, Source = 1 })
                        .ToList();

                    visits = db.JTrack_Visits.AsNoTracking()
                        .Where(v => v.DateTimeStart >= start & v.DateTimeStart <= end)
                        .Select(v => new DashHelper() { DateAndTime = v.DateTimeStart.Value, Source = 2 })
                        .ToList();

                    calls = db.JTrack_Calls.AsNoTracking()
                        .Where(v => v.calldate >= start & v.calldate <= end)
                        .Select(v => new DashHelper() { DateAndTime = v.calldate.Value, Source = 3 })
                        .ToList();
                }
            }

            totals = visitors.Concat(visits).Concat(calls).ToList();

            var visitorsGroup = totals.GroupBy(q => new { q.DateAndTime.Date, q.DateAndTime.Hour });

            List<DashGraph> dg = new List<DashGraph>();

            foreach (var g in visitorsGroup)
            {
                dg.Add(new DashGraph()
                {
                    Date = g.Key.Date,
                    Hour = g.Key.Hour,
                    TotalVisitors = g.Where(x => x.Source == 1).Count(),
                    TotalPageViews = g.Where(x => x.Source == 2).Count(),
                    TotalCalls = g.Where(x => x.Source == 3).Count()
                });
            }

            sw.Stop();
            var exectionTime = TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds);

            return dg;
        }


texts: Function to sort items with an array of keys

texts:
I'm working on a function to sort two elements using several properties. I want to know if the function is well structured.

function comparePropsOfAWithB(a, b, props) {
    var prop  = props[0];
    var propA = a[prop];
    var propB = b[prop];

    if (propA === propB) {
        var array = props;
        array.shift();
        return props.length ? comparePropsOfAWithB(a, b, props) : false
    } else if (propA < propB ) {
        return true
    } else {
        return false
    }
}

This function is meant to be used alongside the sort method like this:

array.sort(function(a,b) { return comparePropsOfAWithB(a,b,["a","b","c"]) })

The intent of the function is to compare two objects using several values to determine if they are different. In the example, the key "a" will be tested, and if it fails, "b" will be tested until the last element of the array is reached.


texts: Review on my multiple JQuery Slider on a page

texts:
I have successfully placed multiple jquery ui slider on a page and its transalation text too. you can check it live on:
http://outsourcingnepal.com/projects/jQuery%20slider/

I have my jquery code as :

var arrLabel1 = new Array('Not Good', 'OK', 'Average', 'Above Average', 'Excellent', 'Outstanding');
$(function() {
    $( ".slider_control" ).slider({
        value:0,
        min: 0,
        max: 5,
        step: 1,
        slide: function( event, ui ) {
            $( "#slider_" + $(this).attr('rel') ).val( ui.value );
            $( "#label_" + $(this).attr('rel') ).text( arrLabel1[ ui.value ] );
        }
    }).each(function(index){
        $( "#slider_" + (index + 1) ).val( $( this ).slider( "value" ) );
        $( "#label_" + (index + 1) ).text( arrLabel1[ $(this).slider( "value" ) ] );
    });
});

Now i would like to optimize it so that i can be independent of rel attribute.

MY HTML:

Overall:

        <input type="hidden" name="overall_review" id="slider_1" />

Cleanliness:

        <input type="hidden" name="overall_review" id="slider_2" />

Facilities:

        <input type="hidden" name="overall_review" id="slider_3" />

Location:

        <input type="hidden" name="overall_review" id="slider_4" />

Quality of Service:

        <input type="hidden" name="overall_review" id="slider_5" />

Room:

        <input type="hidden" name="overall_review" id="slider_6" />

Value of Money:

        <input type="hidden" name="overall_review" id="slider_7" />


texts:
I've just started working with Workflow (WF4) and have been playing with an idea of using it in MVC3.0 controller actions to see if it improves the maintainability of complex actions; also potentially giving the ability to make multiple DB calls in parallel to populate the output model.   Along with this I've been looking at Async controller actions but I'm not sure I've really got my head around those.  I know you can load workflow into a WorkflowApplication and call BeginRun(...) to get that to run asynchronously but I'm thinking that's the wrong approach; from looking online I've come up with the following implementation which does run as expected but I'm wondering if there's anything wrong with the code below or it will cause other issues that I've not thought about.

    [HttpPost]
    public void ConfigureAsync(ConfigureExportInputModel inputModel)
    {
        if (inputModel == null)
        {
            throw new ArgumentNullException("inputModel");
        }

        var arguments = new Dictionary<string, object> { { "ExportType", inputModel.ExportType } };
        var wf = new ErrorHandledExportWorkflow();

        AsyncManager.OutstandingOperations.Increment();
        ThreadPool.QueueUserWorkItem(o =>
                {
                    AsyncManager.Parameters["result"] = WorkflowInvoker.Invoke(wf, arguments)["MvcOutput"] as IDefineMvcOutput;
                    AsyncManager.OutstandingOperations.Decrement();
                });
    }

    public ActionResult ConfigureCompleted(IDefineMvcOutput result)
    {
        return this.ActionResultFactory.Create(this, result);
    }


texts: Optimizing "complex" iteration over Map with auxiliary maps

texts:
This will be tough to explain. I am implementing a tool to support RFC6020. But when it comes to the Choice Statement, things get weird.

For the sake of better understanding, I have to remember you a couple of things:

I have a XML and a YANG file according to the RFC.
A Choice (and it's cases) are not included on the XML, only the children of the selected case. But the .yang instead, contains a full specification of the Choice and it's cases.

Based on this there is a moment where I have only read the .yang files and send a response to something that has only knowledge of the XML structure, thus no choices.

Basically my main problem is that this (complete) path on a .yang file:

  /container/choice/case/leaf

would be simplified like this on an XPATH notation of the .xml file:

  /container/leaf

Here is the basic logic of this task:

Consider that I have:

A Map with all the elements and their complete path. (Map<String, Object> paths)
A Collection of case paths. (Collection<String> casePaths)
An auxiliary Map as an alias os those paths
(Map<String, String> choiceCaseAliases, being: "simplified path" ➔ "complete path")

I have the following ugly method:

private Map<String, String> resolveChoicePaths() {
    String path;
    for (String casePath: casePaths) {
        String choiceCase = casePath.replaceFirst(".*/([^/]+/)", "$1")+"/";
        boolean mapModified = false;
        Map<String, String> tmp = new LinkedHashMap<>();
        for (Iterator entries = choiceCaseAliases.entrySet().iterator(); entries.hasNext();) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) entries.next();
            if (entry.getKey().contains(choiceCase)) {
                path = entry.getKey().replace(choiceCase, StringUtils.EMPTY);
                tmp.put(path, entry.getValue());
                entries.remove();
                mapModified = true;
            }
        }
        if (!mapModified) {
            for (String pathKey: paths.keySet()) {
                if (pathKey.contains(choiceCase)) {
                    path = pathKey.replace(choiceCase, StringUtils.EMPTY);
                    choiceCaseAliases.put(path, pathKey);
                }
            }
        } else {
            choiceCaseAliases.putAll(tmp);
        }
    }
    return choiceCaseAliases;
}

which is call here when paths map is completely populated:

Map<String, String> resolvedChoicePaths = resolveChoicePaths();
for (Map.Entry<String, String> entry: resolvedChoicePaths.entrySet()) {
    paths.getNodes().put(entry.getKey(), paths.getNodes().get(entry.getValue()));
    paths.getNodes().remove(entry.getValue());
}

Every thing works exactly as expected, but I think there must be a cleaner way to implement the same thing this method is doing. I think that this logic might be an overkill approach (that works, yay!) to the problem which actually is kind of complex, but I don't know if that much.

OBS:

Technically, I need to put and delete things at the same iteration on  the same map, but since it's not possible AFAIK I have a temporary map for this.
That regex which is used to get a String choiceCase is bacause the parent statement of a case is always a Choice. So from a path /container/choice/case I can get the String: choice/case/ and search for it on the other elements complete path.


texts:
I made a function that converts Roman letters to integers. But I'm not happy with it, as I feel like I used too much code for a such a simple task. Any suggestion on how I can minimize it?

values = (('M',  1000),
         ('CM', 900),
         ('D',  500),
         ('CD', 400),
         ('C',  100),
         ('XC', 90),
         ('L',  50),
         ('XL', 40),
         ('X',  10),
         ('IX', 9),
         ('V',  5),
         ('IV', 4),
         ('I',  1))

def RomanToInt(year):
    result = 0
    boom = []
    for i in range(len(year)):
        for letter, value in values:
            if year[i] == letter:
                boom.append(value)
    boom.append(0)
    for i in range(len(year)):
        if boom[i] >= boom[i+1]:
            result = result + boom[i]
        else:
            result = result - boom[i]
    return result


texts: Unit testing extension method adding view location expander

texts:
Introduction

I'm writing unit tests for an extension method I wrote. Its only purpose it is to wrap startup logic which extends ViewLocationExpanders list by an instance implementating IViewLocationExpander. ViewLocationExpanders is a property of RazorViewEngineOptions, which can be configured in application startup in ConfigureServices() method. I'm using XUnit 2.4.1.

Usage

Instead of:

services.Configure<RazorViewEngineOptions>(options =>
{
    options.ViewLocationExpanders.Add(new ViewLocationExpander());
});

I can use:

services.AddViewLocationExpander(new ViewLocationExpander());

ViewLocationExpander

public class ViewLocationExpander : IViewLocationExpander
{
    public IEnumerable<string> ExpandViewLocations(
        ViewLocationExpanderContext context,
        IEnumerable<string> viewLocations)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (viewLocations == null)
        {
            throw new ArgumentNullException(nameof(viewLocations));
        }

        /*
            * Note:
            * {0} = action name
            * {1} = controller name
            * {2} = area name
            */

        var newViewLocations = new string[]
        {
            // Example: '/Views/Home/_Partials/FooBar.cshtml'
            "/Views/{1}/_Partials/{0}.cshtml",
        };

        // Add new locations *AFTER* MVC default locations.
        return viewLocations.Union(newViewLocations);
    }

    public void PopulateValues(ViewLocationExpanderContext context)
    {
        context.Values["customviewlocation"] = nameof(ViewLocationExpander);
    }
}

Extension method

public static IServiceCollection AddViewLocationExpander(
    this IServiceCollection services,
    IViewLocationExpander viewLocationExpander)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    if (viewLocationExpander == null)
    {
        throw new ArgumentNullException(nameof(viewLocationExpander));
    }

    return services.Configure<RazorViewEngineOptions>(options =>
    {
        options.ViewLocationExpanders.Add(viewLocationExpander);
    });
}

Unit tests

[Fact]
public void ExtensionMethodAddsNewViewLocationExpander()
{
    // Arrange
    var services = new ServiceCollection();
    services.AddMvc();

    // These two are required to active the RazorViewEngineOptions.
    services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
    services.AddSingleton<ILoggerFactory, LoggerFactory>();

    // Act
    var serviceProvider = services.BuildServiceProvider();
    var oldOptions = serviceProvider.GetRequiredService<IOptions<RazorViewEngineOptions>>().Value;
    services.AddViewLocationExpander(new ViewLocationExpander());
    serviceProvider = services.BuildServiceProvider();
    var newOptions = serviceProvider.GetRequiredService<IOptions<RazorViewEngineOptions>>().Value;

    // Assert
    Assert.True(newOptions.ViewLocationExpanders.Count > oldOptions.ViewLocationExpanders.Count);
}

Questions

Am I going beyond the scope of what unit testing should include? I'm afraid that my code is actually testing the basic functions of generic collections and/or aspects of ASP.NET Core.
If my concern above is true, that should I write unit tests to this at all? How should it work?


texts: Mail merge (Parsec string formatting) example

texts:
My intent is to perform "mail merge" where I can write strings like "hi <<name>>" and format them according to a HashMap.

Specifically, the string contains keys formatted as <<key>>, and the map contains the corresponding values.

I have a main concern that I'd like help with. I think it would be best to perform the parsing in multiple stages:

first find the Keys
second find the remaining Chunks
and for more complicated parsing tasks, perhaps more stages

I couldn't figure that out and instead use the more expensive lookahead function notFollowedBy and one pass. That obviously wouldn't work well if I had a slightly more complicated need.

import Data.Functor.Identity (Identity)
import Data.HashMap.Lazy as HM
import Text.Parsec
import Text.Parsec.String

-- Parsing ----------

data Merge a = Chunk a | Key a deriving (Show)

key :: Parser (Merge String)
key = Key <$> between (string "<<") (string ">>") (many1 letter)

chunk :: Parser (Merge String)
chunk = Chunk <$> many1 (notFollowedBy key >> anyChar)

prose :: ParsecT String () Identity [Merge String]
prose = many1 $ key <|> chunk

-- Formatting ----------

format :: HM.HashMap String String -> [Merge String] -> String
format _ []             = ""
format hmap (Chunk x : xs) = x ++ format hmap xs
format hmap (Key k : xs) =
  case HM.lookup k hmap of
    -- I could obviate the `error` by working within a failure monad
    Nothing -> error $ "missing key: " ++ k
    Just v -> v ++ format hmap xs

-- Testing ----------

testString = "Hi <<name>>! Do you like <<thing>>?"
testMap = HM.fromList [("name", "Adam"), ("thing", "Apples")]
main = print $ format testMap <$> parse prose "" testString


texts:
I am training a colleague who is familiar with Python but has a limited knowledge of C# and complexity. I thought the following problem could be a good start.

You are in a desert, there is a (infinite) wall in front of you and you know there is exactly one door, but you don't know if it is on the left or on the right.

I implemented the labyrinth this way:

using System;

namespace _1d_labyrinth
{
    public class Labyrinth
    {
        private int _exitPosition;
        private int _currentPosition;
        private int _nSteps;

        public int Steps
        {
            get { return _nSteps; }
        }

        public bool Solved
        {
            get { return _currentPosition == _exitPosition; }
        }

        public Labyrinth(int exitPosition)
        {
            _nSteps = 0;
            _currentPosition = 0;
            _exitPosition = exitPosition;
        }

        public bool MoveRight()
        {
            _nSteps++;
            _currentPosition++;
            return _currentPosition == _exitPosition;
        }

        public bool MoveLeft()
        {
            _nSteps++;
            _currentPosition--;
            return _currentPosition == _exitPosition;
        }
    }
}

The strategy evaluator (which just counts the total number of steps taken to solve a fixed set of labyrinths)

using System;

namespace _1d_labyrinth
{
    public static class StrategyEvaluator
    {
        public static int Run(ISolver solver, int steps)
        {
            Random rnd = new Random(1);
            int totalSteps = 0;
            for (int i = 0; i < steps; i++)
            {
                Labyrinth lb = new Labyrinth(rnd.Next() * ((rnd.Next() % 2) - 1));
                solver.Run(lb);
                if (lb.Solved)
                    totalSteps += lb.Steps;
                else
                    throw new Exception("Not solved !");
            }
            return totalSteps;
        }

    }
}

Where a solver is just a way to solve the labyrinth.

namespace _1d_labyrinth
{
    interface ISolver
    {
        void Run(Labyrinth lb);
    }
}

And this is my solution (where multiplier will be 2 or 3)

namespace _1d_labyrinth
{
    public class Solver1 : ISolver
    {
        private int _multiplier;

        public Solver1(int multiplier)
        {
            _multiplier = multiplier;
        }

        public void Run(Labyrinth lb)
        {
            bool finished = false,
                moveRight = true;

            int stepsToTake = 1,
                stepsTaken = 0;

            while (!finished)
            {
                while (stepsTaken < stepsToTake)
                {
                    if (moveRight)
                        finished = lb.MoveRight();
                    else
                        finished = lb.MoveLeft();
                    stepsTaken++;
                }
                moveRight = !moveRight;
                stepsToTake *= _multiplier;
            }
        }
    }
}

It allows to introduce interfaces and complexity. Is there anything I could add or make better in the example ?


texts: Make the smith watermann algorithm run faster

texts:
####make the BLOSUM matrix into a class for easier retrieval
class BLOSUM62():
    def __init__(self):
        with open('BLOSUM62.txt') as f1:
            entries = [(line.strip()).split() for line in f1.readlines()]
            self.scoring_matrix = {(entry[0],entry[1]):int(entry[2]) for entry in entries}

    def __getitem__(self, pair):
        return self.scoring_matrix[pair[0],pair[1]]

def local_alignment(v,w,scoring_matrix,gap_start, gap_extend):

    ###initialize the 3 matrices now
    M = [[0 for j in xrange(len(w)+1)] for i in xrange(len(v)+1)]
    X = [[0 for j in xrange(len(w)+1)] for i in xrange(len(v)+1)]
    Y = [[0 for j in xrange(len(w)+1)] for i in xrange(len(v)+1)]
    back_track = [[0 for j in xrange(len(w)+1)] for i in xrange(len(v)+1)]

    ###initialize the maximum scores
    max_score = -1
    max_i, max_j = 0,0

    ###populate all three matrices
    for i in xrange(1,(len(v)+1)):
        for j in xrange(1, (len(w)+1)):

            Y[i][j] = max([Y[i-1][j] - gap_extend, M[i-1][j] - gap_start])
            X[i][j] = max([X[i][j-1] - gap_extend, M[i][j-1] - gap_start])
            cur_scores = [Y[i][j], M[i-1][j-1]+scoring_matrix[v[i-1],w[j-1]], X[i][j],0]

            M[i][j] = max(cur_scores)
            back_track[i][j] = cur_scores.index(M[i][j])
            # print 'chose back_track value as'
            # print back_track[i][j]

            if M[i][j] > max_score:
                max_score = M[i][j]
                max_i, max_j = i, j

    print 'Finished making the matrix'
    # print 'M'
    # print M
    # print 'backtrack'
    # print back_track
    # Initialize the indices to start at the position of the high score.
    i, j = max_i, max_j

    # Initialize the aligned strings as the input strings up to the position of the high score.
    v_aligned, w_aligned = v[:i], w[:j]

    # Backtrack to start of the local alignment starting at the highest scoring cell.
    #while back_track[i][j] != 3 and i*j != 0 and i<=j:
    while back_track[i][j] != 3 and i*j != 0 and i>=j:
        if back_track[i][j] == 0:
            i -= 1
        elif back_track[i][j] == 1:
            i -= 1
            j -= 1
        elif back_track[i][j] == 2:
            j -= 1

    print 'finished backtracking'
    # Cut the strings at the ending point of the backtrack.
    v_aligned = v_aligned[i:]
    w_aligned = w_aligned[j:]

    return str(max_score), v_aligned, w_aligned

###now run the thing
#word1 = 'PLEASANTLY'
#word2 = 'MEANLY'

f1 = open('rosalind_laff.txt','r')
indata = f1.readlines()
f1.close()

###add '>' to last line
indata.append('>')

word1 = ''
word2 = ''
linenum = 0
chunk = []
for line in indata:
    line = line.strip()
    linenum = linenum+1
    if line=='':
        pass
    else:
        if line[0]=='>' :
            if linenum==1:
                chunk = []
            elif linenum>1 and linenum!=len(indata):
                for i in range(0,len(chunk)):
                    word1 = word1+chunk[i]
                chunk = []

            else:
                for i in range(0,len(chunk)):
                    word2 = word2+chunk[i]

        else:
            chunk.append(line)

# word1 = 'PLEASANTLY'
# word2 = 'MEANLY'

# Get the local alignment (given sigma = 11, epsilon = 1 in problem statement).
alignment = local_alignment(word1, word2, BLOSUM62(), 11, 1)

# Print and save the answer.
print '\n'.join(alignment)

f1 = open('out_localali_test.txt','w')
f1.write(str(alignment))
f1.close()

This is a working code of the smith watermann algorithm but this is too slow to run.Any suggestions to speed it up?
The main slow part is the backtrack part of it as its recursive.

What the Backtrack part does-
backtracking
looks in a matrix
starting from i,j which are now the indices of the greatest score calculated
itearting as i-1, j-1
until they find bbackstarck[i][j]==3
we check the value of backtrack[i][j[ recursively


texts: Exporting information on a collection of books to Excel

texts:
I have the following code that loops through a collection of objects and dumps different properties out to Excel.  The whole j++ on every other line doesn't seem very elegant.  Is there a more elegant way to have this functionality where I loop through objects in a collection and dump out properties?

int rowIndex = 2;
foreach (BookInfo book in books)
{
    int j = 1;
    excelExport.SetCell(j, rowIndex, book.BookId);
    j++;
    excelExport.SetCell(j, rowIndex, book.Book);
    j++;
    excelExport.SetCell(j, rowIndex, book.System);
    j++;
    excelExport.SetCell(j, rowIndex, book.Age);
    j++;
    excelExport.SetCell(j, rowIndex, book.StartDate);
    j++;
    excelExport.SetCell(j, rowIndex, book.Pages);
    rowIndex++;
}

I am constantly adding new columns at the beginning and middle, so I want to avoid hard coding column names.


texts:
I'd like to know how to improve this code because I think that the main_func is too big and I can not split it into other functions or classes.
Also, I want to know if I can or should use classes to make it cleaner.
import random
import string

def starting():
    print('HANGMAN')
    print('Set game mode:')
    print('0. To exit')
    print('1. Easy')
    print('2. Medium')
    print('3. Hard')
    difficult = int(input('Your choice: '))
    if difficult == 1:
        difficult_easy()
    elif difficult == 2:
        difficult_medium()
    elif difficult == 3:
        difficult_hard()

    else:
        exit('Exiting...')

def main_func(word_lst, guesses_given):

    secret_word = random.choice(word_lst)
    output = []
    guessed_letters = []
    alphabet = string.ascii_letters
    length = len(secret_word)
    print(f'Your word has {len(secret_word)} characters ')

    for i in range(len(secret_word)):
        output.append('_')

    while '_' in output:

        letter = input('Enter a letter: ')

        if letter not in alphabet:
            print('You should enter only one letter!\n ')
        elif len(letter) != 1:
            print('You can only display 1 letter at a time\n')
        else:
            if letter not in guessed_letters:
                guessed_letters.append(letter)

                if letter in secret_word:
                    for n in range(length):
                        if secret_word[n] == letter:
                            output[n] = letter.upper()
                    print(*output, sep=' ')
                    if '_' not in output:
                        print('You won!')

                if letter not in secret_word:
                    guesses_given -= 1
                    print(f"This letter is not in the secret word. REMAINING TRIES: {guesses_given}\n")
                    if guesses_given == 0:
                        print(f"You lost. The secret word was '{secret_word.upper()}'")
                        break

            else:
                print('You have already guessed this letter!\n\n')

    print('GAMEOVER')
    play_again()

def play_again():
    again = input('Play again? (y/n)\n')
    if again.lower() == 'yes' or again.lower() == 'y':
        starting()
    else:
        exit('Exiting...')

def difficult_easy():
    main_func(['hall', 'exam', 'road', 'gate', 'debt', 'poet', 'sir', 'girl', 'food'], 14)

def difficult_medium():
    main_func(['customer', 'baseball', 'language', 'stranger', 'quantity',
               'judgment', 'republic', 'proposal', 'magazine'], 12)

def difficult_hard():
    main_func(['assumption', 'impression', 'restaurant', 'indication', 'excitement',
               'depression', 'government', 'inspection', 'protection', 'investment'], 10)

if __name__ == '__main__':
    starting()

For me, it looks garbage, but I did my best to make it simple and short at the same time. I want to use classes to make it more simple, but I still hadn't figured out... The last thing I want to ask is about the if __name__ == '__main__':, am I using it correctly?
I posted it on Stack Overflow but people said that the site is only for specific problems in your code, so they told me to go here.


texts: IService or defining IProductService, ICustomerService

texts:
As per tutorial here, I have the following classes:
(In reference to this tutorial's section)
namespace Supermarket.API.Domain.Services
{
    public interface ICategoryService
    {
         Task<IEnumerable<Category>> ListAsync();
    }
}

IProductService.cs
namespace Supermarket.API.Domain.Services
{
    public interface IProductService
    {
         Task<IEnumerable<Product>> ListAsync();
    }
}

ICustomerService.cs
namespace Supermarket.API.Domain.Services
{
    public interface ICustomerService
    {
         Task<IEnumerable<Customer>> ListAsync();
    }
}

I have about 10 Domains that I want to have the same interface as above (i.e. the service ability to GET items for e.g. Customer / Product / OrderItem / Order)
In view of the DRY principle, I am thinking of changing to the below:
public interface IService<T>
{
    /// <summary>
    /// Gets a collection of entities
    /// </summary>
    /// <returns></returns>
    Task<IEnumerable<T>> ListAsync();
}

Whereby at implementation time, it looks like the below:
public class CustomerService : IService<Customer>
{
    public async Task<IEnumerable<Customer>> ListAsync()
    {
        var entities =  await // Imeplementation of DAL to follow

        return entities;
    }
}

None of the tutorials that I have read so far does anything similar to keep the interface DRY. Is this a good idea? Thanks.


texts:
public function setErrorReporting() {
    if($this->debugMode == 0) {
        error_reporting(0);
    } elseif($this->debugMode == 1) {
        error_reporting("E_ALL");
    } elseif($this->debugMode == 2) {
        error_reporting("E_ALL");
        // Also log errors
    }

I want to change the error reporting based on a value from a config file. (eithor 0, 1 or 2)
But if I ever wanted to increase the options then it won't scale like this.

Is there a better way of handling this?


texts:
I have an HTML file that contains a submit form, which asks the users the fill in their personal info:

then it will post and store into the DB by method of PHP SQL:

 // Check input errors before inserting in database
if (empty($CName_err) && empty($Address_err) && empty($amount_err) && empty($Phone_err)) {
    // Prepare an insert statement
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO database (CName, Address, Phone, Amount ,Ticket, Purpose) VALUES (?, ?, ?, ? ,?, ?)";

    $q = $pdo->prepare($sql);
    $q->execute(array($CName, $Address, $Phone, $amount ,$Ticket ,$Purpose));
    Database::disconnect();

Hence, any risks of an SQL injection attack in this case?

What should I do to improve my coding?


texts:
I've recently just finished my implementation of a DBSCAN in C++ for a machine learning framework. I've tried to follow the pseudocode implementation on Wikipedia as best I could. I also found some example implementations on Github to help as well. So far, this is what my code looks like. I was wondering if my implementation looks similar to the pseudocode and if their was anything I could add in terms of correctness or even speed.

std::vector<uint32_t> DBSCAN::regionQuery(uint32_t p)
{
   Metrics metrics;
   MetricCoordinates _mc;
   uint32_t coordinates_size = coordinates[0]->lat_pts.size();
   if (cluster_weights.dist_metric == "haversine"){
      for (uint32_t i = 0; i < coordinates_size; i++){
         _mc.lat_1 = coordinates[0]->lat_pts[i];
         _mc.lat_2 = coordinates[0]->lat_pts[p];
         _mc.long_1 = coordinates[0]->long_pts[i];
         _mc.long_2 = coordinates[0]->long_pts[p];
         if (metrics.haversineDistanceMetric(_mc) <= cluster_weights.eps){
            rq_pts.push_back(i);
         }
      }
   } else if (cluster_weights.dist_metric == "euclidean"){
      for (uint32_t i = 0; i < coordinates_size; i++){
         _mc.lat_1 = coordinates[0]->lat_pts[i];
         _mc.lat_2 = coordinates[0]->lat_pts[p];
         _mc.long_1 = coordinates[0]->long_pts[i];
         _mc.long_2 = coordinates[0]->long_pts[p];
         if (metrics.euclideanDistanceMetric(_mc) <= cluster_weights.eps){
            rq_pts.push_back(i);
         }
      }
   }
   // all points within the eps neighborhood
   return rq_pts;
}

void DBSCAN::expandCluster(uint32_t p, std::vector<uint32_t>* ec_neighbor_pts, int32_t* n_clusters)
{
   cluster_pts.push_back(std::vector<int32_t>());
   cluster_pts[*n_clusters].push_back(p);
   uint32_t ec_neighbors_size = ec_neighbor_pts->size();
   assert(ec_neighbors_size != 0);
   for (uint32_t i = 0; i < ec_neighbors_size; i++){
      if (!visited_pts[ec_neighbor_pts->at(i)]){
         // mark point p as visited
         visited_pts[ec_neighbor_pts->at(i)] = true;
         std::vector<uint32_t> ec_neighbor_pts_ = regionQuery(ec_neighbor_pts->at(i));
         if (ec_neighbor_pts_.size() >= cluster_weights.min_pts){
            ec_neighbor_pts->insert(ec_neighbor_pts->end(), ec_neighbor_pts_.begin(), ec_neighbor_pts_.end());
         }
         // mark point p as clustered
         clustered_pts[ec_neighbor_pts->at(i)] = true;
         // add any other points that haven't been clustered
         if (clustered_pts[ec_neighbor_pts->at(i)]){
            cluster_pts[*n_clusters].push_back(ec_neighbor_pts->at(i));
         }
      }
   }
}

void DBSCAN::performClusterSearch()
{
   uint32_t coordinates_size = coordinates[0]->lat_pts.size();
   for (uint32_t i = 0; i < coordinates_size; i++){
      if (visited_pts[i]) {
         continue;
      } else {
         // mark point p as visited
         visited_pts[i] = true;
         std::vector<uint32_t> rq_neighbor_pts = regionQuery(i);
         if (rq_neighbor_pts.size() < cluster_weights.min_pts){
            noise_pts_.push_back(rq_neighbor_pts[i]);
         } else {
            n_clusters_++;
            // mark point p as clustered
            clustered_pts[i] = true;
            expandCluster(i, &rq_neighbor_pts, &n_clusters_);
         }
      }
   }
}


texts: Print all permutations of a given string in Java

texts:
I want to print all permutations of a given string in Java. To do this I create one auxiliary array boolean used[] to check if I have used some character or not.

private static void permute(String s) {
        int n = s.length();
        boolean[] used = new boolean[n];
        char[] in = s.toCharArray();
        StringBuffer output = new StringBuffer();
        doPermute(in, output, used, n, 0);
    }

//helper method
private static void doPermute(char[] in, StringBuffer output,
            boolean[] used, int n, int level) {
        // TODO Auto-generated method stub
        if(n == level){
            System.out.println(output.toString());
            return;
        }
        for (int i = 0; i < in.length; i++) {
            if(used[i])
                continue;
            output.append(in[i]);
            used[i] = true;
            doPermute(in, output, used, n, level+1);
            used[i] = false;
            output.setLength(output.length()-1);
        }
    }

//main() method
public static void main(String[] args) {
        String s = "dog";
        permute(s);
    }

My main question: is there more elegant/better solution? Can I avoid using this auxiliary array (I tried to but it didn't work)?


texts:
I want to randomly permute a finite list in the most effective and efficient way in C#. My attempt is as follows.

/*===================================*
 * Compile it to produce Shuffle.exe *
 * ==================================*/
using System;
using System.Collections.Generic;
using System.IO;

namespace Shuffle
{
    class Program
    {
        static void Main(string[] args)
        {
            int Columns = int.Parse(args[0]);
            int Rows = int.Parse(args[1]);
            int Seed = int.Parse(args[2]);
            string OutputFilename = args[3];

            List<string> OrderedList = new List<string>();
            for (int x = 0; x < Columns; x++)
                for (int y = 0; y < Rows; y++)
                    OrderedList.Add(string.Format("{{{0},{1}}}", x, y));

            Random rnd = new Random(Seed);
            List<string> ShuffledList = new List<string>();

            for (int i = 0; i < Columns * Rows; i++)
            {
                int x = rnd.Next(OrderedList.Count);
                ShuffledList.Add(OrderedList[x]);
                OrderedList.RemoveAt(x);
            }

            using (StreamWriter sw = new StreamWriter(OutputFilename))
            {
                foreach (string s in ShuffledList)
                    sw.WriteLine(s);
            }

        }
    }
}

This program will be used in my production. Could you review whether or not my code is already the most efficient and effective in C#?


texts: Getting the value of a custom attribute from an enum

texts:
Suppose we have an enum called "Planet" and it has a custom attribute of class "PlanetAttr",
these methods will give you the attribute value for a given Planet value:

private static PlanetAttr GetAttr(Planet p)
{
    return (PlanetAttr)Attribute.GetCustomAttribute(ForValue(p), typeof(PlanetAttr));
}

private static MemberInfo ForValue(Planet p)
{
    return typeof(Planet).GetField(Enum.GetName(typeof(Planet), p));
}

But is this a good way to retrieve the value of a custom attribute from an enum?  I am uncomfortable with the number of method calls involved.  Is there a more efficient way, e.g. can it be done without looking up the enum constant's name?

This code is from a StackOverflow question.

using System;
using System.Reflection;

class PlanetAttr: Attribute
{
    internal PlanetAttr(double mass, double radius)
    {
        this.Mass = mass;
        this.Radius = radius;
    }
    public double Mass { get; private set; }
    public double Radius { get; private set; }
}

public static class Planets
{
    public static double GetSurfaceGravity(this Planet p)
    {
        PlanetAttr attr = GetAttr(p);
        return G * attr.Mass / (attr.Radius * attr.Radius);
    }

    public static double GetSurfaceWeight(this Planet p, double otherMass)
    {
        return otherMass * p.GetSurfaceGravity();
    }

    public const double G = 6.67300E-11;

    private static PlanetAttr GetAttr(Planet p)
    {
        return (PlanetAttr)Attribute.GetCustomAttribute(ForValue(p), typeof(PlanetAttr));
    }

    private static MemberInfo ForValue(Planet p)
    {
        return typeof(Planet).GetField(Enum.GetName(typeof(Planet), p));
    }

}

public enum Planet
{
    [PlanetAttr(3.303e+23, 2.4397e6)]  MERCURY,
    [PlanetAttr(4.869e+24, 6.0518e6)]  VENUS,
    [PlanetAttr(5.976e+24, 6.37814e6)] EARTH,
    [PlanetAttr(6.421e+23, 3.3972e6)]  MARS,
    [PlanetAttr(1.9e+27,   7.1492e7)]  JUPITER,
    [PlanetAttr(5.688e+26, 6.0268e7)]  SATURN,
    [PlanetAttr(8.686e+25, 2.5559e7)]  URANUS,
    [PlanetAttr(1.024e+26, 2.4746e7)]  NEPTUNE,
    [PlanetAttr(1.27e+22,  1.137e6)]   PLUTO
}


texts:
I am building a library that uses animations in a canvas.

I need to apply effects to some objects in the canvas and I came up with an effect stack that contains each effect to be executed on a object. Each object has it's own effect stack, because each effect has some random values to them.

As each effect needs to be executed on a set of frames, I need those to get back in the effect stack to be continued in the next frame.

Here is what I want:

Note that each effect in the stack is consumed once. If the effect is not completed, it is reinserted on the stack.

I came up with a couple of solutions:

I pop() the effect, consume it and unshift() it in the stack. Reading only the top of the stack n times (n -> nb of effects).
The opposite is also possible: shift() -> consume() -> push()

The problem with these 2, is the shift() and the unshift() as it copies all the values in memory to another location. I'd prefer to use pop() or push() only.
I use 2 stacks. One for the current effects to be consumed and the other for the effects that are consumed. And each frame, I copy the values from #2 to #1, then reset the #2.

But now, I have to create 2 stacks for each object and add a function to process those, which complicates all the code that needs access to these effects.

A basic implementation for the second solution is:

var EffectStack = function() {
    this.stack = [];
    this.queued = [];
}

EffectStack.prototype.length = function() {
    return this.stack.length;
};

EffectStack.prototype.push = function( fx ) {
    this.stack.push( fx );
};

EffectStack.prototype.pop = function( fx ) {
    return this.stack.pop( fx );
};

EffectStack.prototype.update = function() {
    this.stack = this.queued.slice(0);
    this.queued = [];
};

EffectStack.prototype.continue = function( fx ) {
    this.queued.push( fx );
};

And for the animated object:

/**
 * Applies each effect and updates the Effect Stack by queuing
 * the effects that weren't complete.
 */
AnimObject.fn.consumeEffects = function() {
    var fx
    while( this.eStack.length() > 0 ) {
        // fx = {
        //     func: function(){ ...core of the effect... },
        //     data: { ... }
        // }
        fx = this.eStack.pop();
        fx.func( this, fx );
    }

    this.eStack.update();
}

Effect Example

/**
 * This is an Effect (fx).
 */
changeOpacity: function( value, step ){
    return {

        // Basic information.
        data: {
            step: step ? step : Math.random()*0.06 + 0.04,
            targetValue: value ? value : Math.random()*0.7 + 0.2
        },

        // The core of the effect.
        func: function( particle, fx ){
            if(!FX.opacity_FUNC( animObj, fx.data )) {
                // **IMPORTANT**
                // Add to stack if the effect isn't over.
                animObj.eStack.continue({
                    data: fx.data,
                    func: fx.func
                });
            }
        }
    }
}

/**
 * -- THIS IS A SUB_EFFECT. IT CONTAINS THE CORE LOGIC --
 * -- SUB_EFFECTS CAN BE MIXED TOGETHER. --
 * Changes the opacity of a AnimObject that is floating.
 *
 * @param animObj   : Affected AnimObject.
 * @param data      : Transformation data.
 */
opacity_FUNC: function( animObj, data ) {

    // Distance to targetValue.
    var _delta = (animObj.opacity - data.targetValue);

    // If the <animObj> still validates the conditions,
    // continue the effect till it's done.
    if ((animObj.isFloating || animObj.isMoving) && Math.abs(_delta) > 0.1)
    {
        animObj.opacity += data.step * (_delta > 0 ? -1 : 1);
        return false;
    }

    // Effect is over.
    else
    {
        animObj.opacity = data.targetValue;
        return true;
    }
},

Here is a little jsfiddle of what my sandbox looks like.

But, I still need to copy the values. Any better ideas?


texts:
This is the code I use to dynamically build error messages.
Utility.h
#ifndef THORSANVIL_SOCKET_UTILITY_H
#define THORSANVIL_SOCKET_UTILITY_H

#include <string>
#include <vector>
#include <sstream>

namespace ThorsAnvil
{
    namespace Socket
    {

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
print(std::ostream&, std::tuple<Tp...> const&)
{ }

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
print(std::ostream& s, std::tuple<Tp...> const& t)
{
    s << std::get<I>(t);
    print<I + 1, Tp...>(s, t);
}

template<typename... Args>
std::string buildStringFromParts(Args const&... args)
{
    std::stringstream msg;
    print(msg, std::make_tuple(args...));
    return msg.str();
}

template<typename... Args>
std::string buildErrorMessage(Args const&... args)
{
    return buildStringFromParts(args...);
}

    }
}

#endif

The code works for all types that can be streamed. Including io manipulators.
std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);

buildStringFromParts("Date: ", std::put_time(&tm, "%c %Z"), "\r\n");

This generates the string:
Date: Sun Jun  5 01:55:19 2016 PDT


texts: Do I need to close my FileOutputStreams?

texts:
I have inlined temporary FileOutputStream that I am not able to explicitly close.

Is that a problem?

File raw = new File(uri.getPath());
Bitmap myBitmap = BitmapFactory.decodeFile(uri.getPath());

File compressedPicture = MEUtils.createTemporaryFile(getPackageName());
// see here
myBitmap.compress(Bitmap.CompressFormat.JPEG,
                  mObjectiveDefinitionForTakingPictureResult.getQuality(),
                  new FileOutputStream(compressedPicture));

JpegImageMetadata jpegMetadata = (JpegImageMetadata) Sanselan.getMetadata(raw);
TiffImageMetadata exif = jpegMetadata.getExif();
TiffOutputSet outputSet = exif.getOutputSet();
outputSet.setGPSInDegrees(app.locationListener.getLongitude(),
                          app.locationListener.getLatitude());

File compressedPictureWithMetadata = MEUtils.createTemporaryFile(getPackageName());
// see here
OutputStream compressedPictureWithMetadataOutputStream = new BufferedOutputStream(new FileOutputStream(compressedPictureWithMetadata));
new ExifRewriter().updateExifMetadataLossless(compressedPicture,
                                              compressedPictureWithMetadataOutputStream,
                                              outputSet);

EDIT

It seems that BufferedOutputStream can conveniently wrap a FileOutputStream, directly by inline it in the constructor: http://developer.android.com/reference/java/io/BufferedOutputStream.html


texts:
class ReportFormat(object):
    PDF = 0
    TEXT = 1

class Report(object):
    """Strategy context."""

    def __init__(self, format_):
        self.title = 'Monthly report'
        self.text = ['Things are going', 'really, really well.']
        self.format_ = format_

class Handler(object):

    def __init__(self):
        self.nextHandler = None

    def handle(self, request):
        self.nextHandler.handle(request)

class PDFHandler(Handler):

    def handle(self, request):
        if request.format_ == ReportFormat.PDF:
            self.output_report(request.title, request.text)
        else:
            super(PDFHandler, self).handle(request)

    def output_report(self, title, text):
        print ''
        print '  '
        print '    <title>%s</title>' % title
        print '  '
        print '  '
        for line in text:
            print '
%s
' % line
        print '  '
        print ''

class TextHandler(Handler):

    def handle(self, request):
        if request.format_ == ReportFormat.TEXT:
            self.output_report(request.title, request.text)
        else:
            super(TextHandler, self).handle(request)

    def output_report(self, title, text):
        print 5*'*' + title + 5*'*'
        for line in text:
            print line

class ErrorHandler(Handler):

    def handle(self, request):
        print "Invalid request"

if __name__ == '__main__':
    report = Report(ReportFormat.TEXT)
    pdf_handler = PDFHandler()
    text_handler = TextHandler()

    pdf_handler.nextHandler = text_handler
    text_handler.nextHandler = ErrorHandler()

    pdf_handler.handle(report)

O/P:

*****Monthly report*****
Things are going
really, really well.


texts: Testing distance between characters in a string

texts:
Here is another challenge from Coderbyte. I found this one challenging, although not quite as much as the previous two I've posted. Based on the feedback I received on my earlier posts, I structured this solution as a function. It is probably better than my previous solutions but still could be improved.

In particular, I am wondering if there is a way to condense my while loops, perhaps by determining the a and b indices at the same time or maybe by building a helper function? It seems like there is redundancy there. Resetting the index variable strikes me as particular clumsy or inelegant, but it had to happen somehow. I'm also not to happy with splitting the string and then joining the modified array to deal with the spaces. Any feedback on these issues or other suggestions to improve the code would be greatly appreciated.

Here's the challenge, slightly modified:

  Take a str parameter and return true if there are any occurrences of
  characters "a" and "b" separated by exactly 3 places  (i.e. "lane
  borrowed" would result in true because there is exactly three
  characters between a and b). Otherwise return the string false.

(While I was posting this, I realized I had not accounted for spaces. My interpretation of the instructions is that spaces do not count as characters. I have updated my code accordingly.)

var str = prompt("Please enter a string: ").split("");

function test(str){
var index = 0;
var arrayA = [];
var arrayB = [];

while (index >= 0){ //removes spaces
  index = str.indexOf(" ");
  if (index >= 0) {
  str.splice(index, 1);
  }
}
str=str.join("");
index = 0;

while(str.indexOf("a",index) != -1){ //Identifies indices of "a"
  arrayA.push(str.indexOf("a",index));
  index = str.indexOf("a", index)+1;
}

index=0;

while(str.indexOf("b",index) != -1){//Identifies indicies of "b"
  arrayB.push(str.indexOf("b",index));
  index = str.indexOf("b", index)+1;
  }

for(var i=0; i<arrayA.length; i++){//determines if any a's and b's are 3 characters apart
  for(var j=0; j<arrayB.length; j++){
    if (Math.abs(arrayA[i]-arrayB[j]) === 3){
      return true;
    }
  }
}
return false;
}

console.log(test(str));

Here's a revised version:

function ABCheck(str) {
  str = str.split("");
  for (var i = 0; i<str.length; i++){
    if (str[i] === " "){
      str.splice(i,1);
      console.log(str);
    }
  }
  for (var i = 0; i< str.length; i++){
    if (str[i] === "a" && (str[i-3] === "b" || str[i+3] === "b")){
      return true;
    }
  }
  return false;
}


texts: Find the greatest gcd among the pairs of two equal sized arrays and prints the sum of that pair

texts:
You are given two arrays AA and BB containing elements each. Choose a pair of elements x,y such that:

x belongs to array AA. y belongs to array BB. gcd(x,y) is the maximum for all pairs x,y.

If there is more than one such pair x,y having maximum gcd, then choose the one with maximum sum. Print the sum of elements of this maximum-sum pair.

NOTE: returns gcd(x,y) the largest integer that divides both x and y.

Constraints:

$$1≤N≤5\cdot 10^5$$
$$1≤A_i≤10^6$$
$$1≤B_i≤10^6$$

Input format:

The first line of the input contains n denoting the total number of elements of arrays AA and BB. Next line contains n space separated positive integers denoting the elements of array AA. Next line contains n space separated positive integers denoting the elements of array BB.

Output format:

From all the pairs having maximum gcd , print the sum of one that has the maximum sum.

public class Solution2 {

static int gcdcalc(int x, int y){
   if(y == 0)
   {
       return x;
   }
   return gcdcalc(y, x%y);
}

static int maximumGcdAndSum(int[] A, int[] B) {
    int gcd,sum,maxgcd=0,maxsum=0;
    for(int A_i = 0; A_i < A.length; A_i++)
    {
        for(int B_i = 0; B_i < B.length; B_i++)
        {
            sum = A[A_i] + B[B_i];
            gcd = gcdcalc(A[A_i], B[B_i]);
            if(maxgcd < gcd)
            {
                maxgcd = gcd;
                maxsum = sum;
            }
            if(maxgcd == gcd)
            {
                if(maxsum < sum)
                    maxsum = sum;
            }
        }
    }
    return maxsum;
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int[] A = new int[n];
    for(int A_i = 0; A_i < n; A_i++){
        A[A_i] = in.nextInt();
    }
    int[] B = new int[n];
    for(int B_i = 0; B_i < n; B_i++){
        B[B_i] = in.nextInt();
    }
    int res = maximumGcdAndSum(A, B);
    System.out.println(res);
 }
}


texts: Suggestions for a Dungeons and Dragons-like game

texts:
This game is similar to a Dungeons and Dragons game. How could I improve the efficiency of the program?  For example, where can I add functions, records etc?  This is for a school Controlled Assessment so any help would really be appreciated.

import random
play1 = True

str1 = int(input("Enter a value for strength"))
print("you have chosen",str1,)

skl1=int(input("Please enter a value of skill, and then press enter"))
print("you have chosen: ",skl1,)

str2 =int(input("Enter a value for strength"))
print("you have chosen: ",str2,)

skl2=int(input("Please enter a value of skill, and then press enter"))
print("you have chosen: ",skl2,)

strdif=str1-str2
    if strdif<0:
    strdif=str2-str1
    strdif=strdif//5

skldif=skl1-skl2
    if skldif<0:
    skldif=skl2-skl1
    skldif=skldif//5

while play1 == True:

   num1=random.randint(1,6)
   num2=random.randint(1,6)

   if num1>num2:
        str1+=strdif
        skl1+=skldif
        str2-=strdif
        skl2-=skldif

    if num2>num1:
        str2+=strdif
        skl2+=skldif
        str1-=strdif
        skl1-=skldif

    if skl1<0:
        skl1=0
    if skl2<0:
        skl2=0

    if str1<=0:
        play1 = False
        print("Character 2 Won the game")
   elif str2<=0:
        play1 = False
        print("Character 1 Won the game")

   if str1 > str2:
       print("Character 1 won the encounter, now has",str1,"strength and",skl1,"skill")
       print("Character 2 lost the encounter, now has",str2,"strength and",skl2,"skill")
   else:
       print("Character 2 won the encounter, now has",str2,"strength and",skl2,"skill")
       print("Character 1 lost the encounter, now has",str1,"strength and",skl1,"skill")


texts: Publishing angular-cli component library to npm or like

texts:
I've found a lot of blog posts that seem to suggest publishing a library TypeScript (as source) and all to npm or to a private repository. It feels like we should be doing some transpiling first and then publishing only something that is ready to consume.

Can you critique my approach for publishing a angular-cli+angular(4) components library to npm or like?

Context

Multiple angular front-end SPA's that may have common components i.e. a navigation bar. These common components could be published as a library including the navigation bar to npm or a privately scoped npm repository for use by the various front-end apps.

The common components could be developed in a project using angular-cli, angular(4).

Approach

Create tsconfig.aot.json which inherits from tsconfig.json so that we can aot transpile the project back to es5

Ensure that metadata and index files are included/emitted
Ensure the src/.npmignore files are in place to include/exclude files already excluded by the .gitignore

When the tests pass with ng test, ng e2e, ng lint, and ng build as described in the .travis.yml

npm version patch (or major etc.)
git push + git push --tags

When the tag passes on CI

ngc -p tsconfig.aot.json which will create the distribution
npm publish

Code

The code can be found on GitHub

Referenced files

tsconfig.aot.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "",
    "module": "es2015",
    "baseUrl": "",
    "types": [],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "files": [
    "src/app/app.module.ts",
    "src/main-aot.ts",
    "index.ts"
  ],
  "angularCompilerOptions": {
    "genDir": "./dist/aot",
    "skipMetadataEmit" : false
  }
}

tsconfig.aot.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": true,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "./node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

src/.npmignore

*.ts
!*.d.ts
.npmignore

.travis.yml

language: node_js
dist: trusty
node_js:
  - 6.1
sudo: required
addons:
apt:
  sources:
    - google-chrome
  packages:
    - google-chrome-stable
    - google-chrome-beta
before_install:
  - export CHROME_BIN=chromium-browser
  - export DISPLAY=:99.0
  - sh -e /etc/init.d/xvfb start
install:
  - npm install
  - npm install codecov
script:
  - npm run ng test -- --single-run=true --browsers Chrome --code-coverage
  - ./node_modules/codecov/bin/codecov
  - npm run ng e2e
  - npm run ng lint
  - npm run ng build
  - npm run package


texts: AI agent fails when aligned with its target

texts:
I'm making an AI agent (blue entity) that pursues a target (green entity) while avoiding an obstacle (red entity).

The code works as it should most of the times, but will fail if all the entities are aligned in either the X or Y axis or any direction diagonally. I suspect this is due to dividing by zero.

I fixed the problem by simply checking if the axes were zero and then applying a slight offset.

if (vectorTargetX === 0) vectorTargetX += 0.1;
if (vectorTargetY === 0) vectorTargetY += 0.1;

However, this feels like a cheap fix and it seems like there might be some underlying problems in my code. Are there any better ways to go about this, maybe even more efficient?

You can see the how the AI agent fails by clicking the buttons in the example below.

const ctx = document.getElementById('canvas').getContext('2d');

let targetX = 150;
let targetY = 100;

let obstacleX = 200;
let obstacleY = 100;

let agentX = 300;
let agentY = 101;

function loop() {
  requestAnimationFrame(loop);

  // Calculate difference vectors
  let vectorTargetX = targetX - agentX;
  let vectorTargetY = targetY - agentY;

  let vectorObstacleX = obstacleX - agentX;
  let vectorObstacleY = obstacleY - agentY;

  // Calculate length between vectors
  const lengthTarget = Math.sqrt(vectorTargetX * vectorTargetX + vectorTargetY * vectorTargetY);
  const lengthObstacle = Math.sqrt(vectorObstacleX * vectorObstacleX + vectorObstacleY * vectorObstacleY);

  // Normalize vectors
  vectorTargetX = vectorTargetX / lengthTarget;
  vectorTargetY = vectorTargetY / lengthTarget;

  vectorObstacleX = vectorObstacleX / lengthObstacle;
  vectorObstacleY = vectorObstacleY / lengthObstacle;

  // Check if agent is within collision distance
  if (lengthObstacle < 60) {
    // Append displacement vector
    vectorTargetX -= vectorObstacleX * 0.7;
    vectorTargetY -= vectorObstacleY * 0.7;

    const displacedLength = Math.sqrt(vectorTargetX * vectorTargetX + vectorTargetY * vectorTargetY);

    // Move agent towards target while adding avoidance force
    agentX += vectorTargetX / displacedLength;
    agentY += vectorTargetY / displacedLength;
  } else {
    // Move agent towards target
    agentX += vectorTargetX;
    agentY += vectorTargetY;
  }

  if (lengthTarget < 12) {
    unaligned();
  }

  ctx.clearRect(0, 0, 500, 500);

  ctx.beginPath();
  ctx.fillStyle = '#00ff00';
  ctx.arc(targetX, targetY, 6, 0, Math.PI * 2, false);
  ctx.fill();

  ctx.beginPath();
  ctx.fillStyle = '#ff0000';
  ctx.arc(obstacleX, obstacleY, 6, 0, Math.PI * 2, false);
  ctx.fill();

  ctx.beginPath();
  ctx.fillStyle = '#0000ff';
  ctx.arc(agentX, agentY, 6, 0, Math.PI * 2, false);
  ctx.fill();

  ctx.font = '18px sans-serif';
  ctx.fillStyle = "#000000";
  ctx.fillText("X: " + agentX.toFixed(2), 10, 20);
  ctx.fillText("Y: " + agentY.toFixed(2), 10, 40);
}

function aligned() {
  agentX = 300;
  agentY = 100;
}

function unaligned() {
  agentX = 300;
  agentY = 101;
}

loop();
<canvas id="canvas"></canvas><br>
<button onclick="aligned()">Spawn agent aligned</button>
<button onclick="unaligned()">Spawn agent unaligned</button>


texts:
Is there any way to simplify it further?

import java.util.*;

class Triangle {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();

        if(a==b && b==c)
            System.out.println("Equilateral");

        else if(a >= (b+c) || c >= (b+a) || b >= (a+c) )
            System.out.println("Not a triangle");

        else if ((a==b && b!=c ) || (a!=b && c==a) || (c==b && c!=a))
            System.out.println("Isosceles");

        else if(a!=b && b!=c && c!=a)
            System.out.println("Scalene");
    }
}


texts:
I'm teaching myself Java and I had some basic questions on how well I am writing my code for readability. I feel like sometimes I'm just writing code that works, and I'm not that proud of myself when I have finished. I'm not asking you to rewrite my code; I'm just asking for some pointers on how optimize my code for readability.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Hangman implements ActionListener{
    JFrame frame;
    JTextField userInput;
    JLabel textContents;
    String word = "horse";
        int correctGuesses;
    int incorrectGuesses;
    String guessesLeft;
    boolean lose = false;
    StringBuilder wordsGuessedCorrectly;
    JLabel letters;

    Hangman() {
        incorrectGuesses = 0;
        correctGuesses = 0;
        guessesLeft = "You have " + (6 - incorrectGuesses) +" chances left to guess a " + word.length() + " letter word";
        wordsGuessedCorrectly = new StringBuilder();

        frame = new JFrame("A Hangman Game");
        frame.setSize(300,125);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(3, 1));

        userInput = new JTextField();
        userInput.addActionListener(this);
        frame.add(userInput);

        textContents = new JLabel();
        textContents.setText(guessesLeft);
        textContents.setHorizontalAlignment(JLabel.CENTER);
        textContents.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        frame.add(textContents);

        letters = new JLabel("The letters you guess correctly go down here!");
        letters.setHorizontalAlignment(JLabel.CENTER);
        letters.setBorder(BorderFactory.createLineBorder(Color.RED));
        frame.add(letters);

        frame.setVisible(true);

    }

    String seperateLetter(String a, int x, int y) {
        return a.substring(x, y);
    }

    void testLetter(String a) {
        if (word.contains(a) && wordsGuessedCorrectly.toString().contains(a) == false && correctGuesses != (word.length() - 1)) {
            correctGuesses++;
            wordsGuessedCorrectly.append(a);
            letters.setText(wordsGuessedCorrectly.toString());
            textContents.setText("Correct Guess!");
        }
        else if (word.contains(a) && wordsGuessedCorrectly.toString().contains(a)) {
            textContents.setText("You've already guessed this letter!");
        }
        else if (word.contains(a) && wordsGuessedCorrectly.toString().contains(a) == false && correctGuesses == (word.length() - 1)) {
            lose = true;
            textContents.setText("You Win!");
            wordsGuessedCorrectly.append(a);
            letters.setText(wordsGuessedCorrectly.toString());
        }
        else if (word.contains(a) == false && incorrectGuesses == 5){
            textContents.setText("You lose!");
            lose = true;
        }
        else {
            incorrectGuesses++;
            textContents.setText("Incorrect Guess! You have " + (6 - incorrectGuesses)  + " left.");
        }
    }

    public void actionPerformed(ActionEvent ae) {
        if (lose == false) {
            testLetter(seperateLetter(userInput.getText(), 0 , 1));
            userInput.setText("");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Hangman();
            }
        });
    }
}


texts: Game of Life search program for Herschel-generating baits

texts:
Golly is a cross-platform, Python and Perl extendable (like in this case, Python), free Conway's Game of Life simulator written in C++ (or Python) that runs in arbitrary speed and large, marvelous patterns.

Herschel is a pattern named after William Herschel (the heptomino resembles Saturn's planetary symbol ♄, and somewhere in the naming process Saturn got confused with Uranus, which was discovered by Herschel). Herschels frequently appear in the evolution of chaotic patterns.

The following script is a Golly script that searches for positions where one in a list of still lifes can create a Herschel (or another pattern specified in the "herschels" list) when reacting with the pattern already in the board.

import golly as g
from sys import exit

herschels = []

testrect = g.getselrect();
if testrect == []:
    g.exit("Select the area where the still life is placeable!")

if g.empty():
    g.exit("There is no pattern to add bait!")

stillLifes = []

def addStillLife():
    while True:
        stillLife = g.getstring("What still life to test for? (RLE)", "2o$2o!", "HRF v0.1")
        stillLifes.append(g.parse(stillLife))
        addAnother = g.getstring("Add another still life? (y|n)", "n", "HRF v0.1")
        if addAnother.lower() == "n":
            break
        elif addAnother.lower() != "y":
            g.exit("Invalid letter!")

def removeFirstLine(str):
    result = str.rsplit('\n')
    result.pop(0)
    return ''.join(result)

def addResultDesired():
    while True:
        herschelDesired = g.getstring("What result to find? (RLE)", "3o$obo$obo!", "HRF v0.1")
        herschels.append(g.parse(herschelDesired))
        addAnother = g.getstring("Add another result desired? (y|n)", "n", "HRF v0.1")
        if addAnother.lower() == "n":
            break
        elif addAnother.lower() != "y":
            g.exit("Invalid letter!")

addStillLife()
addResultDesired()
debug = g.getstring("Debug mode? (y|n)", "n", "HRF v0.1")
if debug.lower() == "y":
    g.autoupdate(True)
elif debug.lower() != "n":
    g.exit("Invalid letter!")

def testReaction(xpos, ypos, sli):
    orig = g.getcells(g.getrect())
    g.putcells(stillLifes[sli], xpos, ypos)
    this = g.getcells(g.getrect())
    i = 0
    oldgeneration = g.getgen()
    while i < 301:
        g.step()
        for y in herschels:
            if g.getcells(g.getrect()) == y:
                break
        i += 1
    if i == 301:
        g.show("No result found at x:" + str(xpos) + ", y:" + str(ypos) + ", still life " + str(sli))
    g.clear(0)
    g.clear(1)
    if i == 301:
        this = g.putcells(orig)
    else:A
        g.show("Found reaction!")
        g.putcells(this)
    g.setgen(oldgeneration)

n = 0
while n < testrect[2]:
    m = 0
    while m < testrect[3]:
        o = 0
        while o < len(stillLifes):
            testReaction(n + testrect[0], m + testrect[1], o)
            o += 1
        m += 1
    n += 1


texts:
I have a problem similar to the question, namely reading in text which describes a date - in various formats. I want to use the parseTimeM function from Date.Time module in time package.

My current solution can probably be improved style wise but it should remain easy to read and easy to extend. Suggestion?

readDate3 :: Text ->   UTCTime
readDate3 datestring  =

    case shortMonth of
        Just t -> t
        Nothing -> case longMonth of
            Just t2 -> t2
            Nothing -> case monthPoint of
                Just t3 -> t3
                Nothing -> case germanNumeralShort of
                  Just t3 -> t3
                  Nothing -> case germanNumeral of
                    Just t3 -> t3
                    Nothing -> case isoformat of
                      Just t4 -> t4
                      Nothing -> errorT   ["readDate3", datestring, "is not parsed"]

    where
        shortMonth = parseTimeM True defaultTimeLocale
            "%b %-d, %Y" (t2s datestring) :: Maybe UTCTime
        longMonth = parseTimeM True defaultTimeLocale
            "%B %-d, %Y" (t2s datestring) :: Maybe UTCTime
        monthPoint = parseTimeM True defaultTimeLocale
            "%b. %-d, %Y" (t2s datestring) :: Maybe UTCTime
        germanNumeral = parseTimeM True defaultTimeLocale
            "%-d.%-m.%Y" (t2s datestring) :: Maybe UTCTime
        germanNumeralShort = parseTimeM True defaultTimeLocale
            "%-d.%-m.%y" (t2s datestring) :: Maybe UTCTime
        isoformat = parseTimeM True defaultTimeLocale
            "%Y-%m-%d" (t2s datestring) :: Maybe UTCTime